Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/agent-orchestration.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ The core applies these to every way an agent can start another one: `spawn_agent
| Plugin launch options | `launchOptions` from an orchestrator reach only plugins that declared `launch.delegable: true`; everything a plugin contributes still passes the core-owned flag and configuration checks (no permission, sandbox, hook or bypass flags, no OpenCode/Kimi configuration that sets approvals). |
| YOLO | Enforced in the main process: only for a CLI the person acknowledged YOLO for in the launcher, never for a subagent, never from an orchestrator's control connection; a plugin with `sessions:launch` needs the same acknowledgement. |
| Isolation | Every subagent and every agent a plugin starts runs inside agent isolation (below) when it is on; where there is no layer, a subagent runs in normal (it asks) and its card says why. |
| Provider keys | A subagent and every card a plugin starts (a plain terminal card included) inherit only an allowlist of the person's environment (path, home, locale, terminal, temporary and XDG base folders, proxy and certificate variables, the CLIs' home folders): no provider API key (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …), token (`GH_TOKEN`, `CLAUDE_CODE_OAUTH_TOKEN`, …), cloud credential, admin key, CanvasTTY credential (`CANVASTTY_GITHUB_TOKEN`) or OpenCode inline config, also not through the configuration CanvasTTY adds for the launch. A key it needs comes from a launch contribution's `secretEnv`, or the person lists the variable in `CANVASTTY_AGENT_PASS_ENV`. Orchestrators cannot start plain terminal cards. See [installing-and-security.md](installing-and-security.md#agent-protection-layers). |
| No settings | The `canvastty_agents` tools and an orchestrator's control connection cannot change settings, base protection, profiles, plugin trust or isolation. |

## Agent isolation
Expand Down
2 changes: 2 additions & 0 deletions docs/installing-and-security.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ Agents work in their own mode; CanvasTTY's layers sit outside it as a quiet safe

Isolation keeps approval configuration read-only, including OpenCode's project and custom config files and its `agent`/`agents` directories. CLI state and caches remain writable. A moved CLI home is refused if its real path overlaps host credentials or private CanvasTTY data; a selected account folder below `account-homes` remains available. Credential exclusions use the host environment captured before launch contributions, even if the launch changes `HOME`.

**Provider keys in the environment.** A plain terminal card you start keeps your whole environment, except CanvasTTY's own credentials (`CANVASTTY_GITHUB_TOKEN`, any `CANVASTTY_*TOKEN`/`*KEY`/`*SECRET`/`*PASSWORD`), which only the app uses. An agent card never inherits those nor organization-level admin credentials (`OPENAI_ADMIN_KEY`, `ANTHROPIC_ADMIN_KEY`, any `*_ADMIN_*KEY` or `*_ADMIN_*TOKEN`), whoever starts it. An agent you start yourself otherwise keeps your environment, ordinary provider keys such as `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` included, in every profile, so a CLI signed in by API key keeps working (an exported `ANTHROPIC_API_KEY` still takes precedence over Claude Code's subscription sign-in). Subagents and every card a plugin starts (a plain terminal card included, since the plugin drives it) inherit only what a process needs: `PATH`, `HOME`, user, shell, locale and terminal variables, temporary folders, the XDG base folders and desktop type (`XDG_CONFIG_HOME`, `XDG_RUNTIME_DIR`, `XDG_CURRENT_DESKTOP`, …; other `XDG_` and `LC_` variables are not inherited, so a session cookie such as `XDG_SESSION_COOKIE` is not), the Windows system folders, proxy variables (`HTTP(S)_PROXY`, `ALL_PROXY`, `NO_PROXY`), certificate settings (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`), `EDITOR`/`VISUAL`/`PAGER` and the CLIs' own home folders (`CODEX_HOME`, `CLAUDE_CONFIG_DIR`, …). No provider key, token, cloud credential, `SSH_AUTH_SOCK` or OpenCode inline config (`OPENCODE_CONFIG_CONTENT`, which can hold keys) reaches them, also not through the configuration CanvasTTY adds for the launch; a key they need comes explicitly, through a launch contribution's `secretEnv`. To pass a variable anyway, list it in `CANVASTTY_AGENT_PASS_ENV` (comma-separated, e.g. `CANVASTTY_AGENT_PASS_ENV=OPENAI_ADMIN_KEY`) in the environment CanvasTTY starts with. This is about inherited variables only: without the isolation layer an agent runs as you and can still read a key from your shell profile file, and a plain terminal card runs your login shell, which reads that file.

OpenCode Auto inspects only regular local config files of at most 1 MiB. An existing source that cannot be inspected adds no Auto allowances. A launch contributor's uninspectable config is refused; only absent optional directory candidates are skipped. JSONC comments and trailing commas are parsed without changing quoted strings.

**Git audit.** When an isolated agent session ends, is closed or is restored after a quit, CanvasTTY checks the repositories under its folder whose git folder changed. If git would now run something outside isolation (a `core.hooksPath`, a filter or diff driver, `fsmonitor`, a hook file, `info/attributes`), a notice lists exactly what changed; **Neutralize** removes those keys and disables those files, **Keep as is** leaves them. It does not undo other file changes inside the project.
Expand Down
2 changes: 2 additions & 0 deletions docs/installing-and-security.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ gh variable set SPARKLE_PUBLIC_ED_KEY --repo howdeploy/CanvasTTY \

**Аудит git.** Когда изолированная сессия агента заканчивается, закрывается или восстанавливается после выхода, CanvasTTY проверяет репозитории в её папке, у которых изменилась папка git. Если git теперь запустит что-то вне изоляции (`core.hooksPath`, фильтр или diff-драйвер, `fsmonitor`, файл хука, `info/attributes`), появляется уведомление со списком изменений; **Обезвредить** удаляет эти ключи и отключает файлы, **Оставить как есть** ничего не трогает. Другие изменения файлов в проекте аудит не откатывает.

**Ключи провайдеров в окружении.** Обычный терминал, запущенный вами, получает всё ваше окружение, кроме собственных учётных данных CanvasTTY (`CANVASTTY_GITHUB_TOKEN`, любые `CANVASTTY_*TOKEN`/`*KEY`/`*SECRET`/`*PASSWORD`), которые нужны только приложению. Карточка агента никогда не наследует ни их, ни админ-ключи и админ-токены организации (`OPENAI_ADMIN_KEY`, `ANTHROPIC_ADMIN_KEY`, любые `*_ADMIN_*KEY` и `*_ADMIN_*TOKEN`). В остальном агент, запущенный вами, получает ваше окружение, включая обычные ключи вроде `OPENAI_API_KEY` и `ANTHROPIC_API_KEY`, в любом режиме, так что CLI со входом по API-ключу работает как раньше. Субагенты и любые карточки, запущенные плагинами (включая обычный терминал, ведь им управляет плагин), наследуют только то, что нужно процессу: `PATH`, `HOME`, переменные пользователя, оболочки, локали и терминала, временные папки, базовые XDG-папки и тип рабочего стола (`XDG_CONFIG_HOME`, `XDG_RUNTIME_DIR`, `XDG_CURRENT_DESKTOP`, …; прочие переменные `XDG_` и `LC_` не наследуются, а значит, и cookie сеанса вроде `XDG_SESSION_COOKIE`), системные папки Windows, прокси (`HTTP(S)_PROXY`, `ALL_PROXY`, `NO_PROXY`), настройки сертификатов (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`), `EDITOR`/`VISUAL`/`PAGER` и домашние папки CLI (`CODEX_HOME`, `CLAUDE_CONFIG_DIR`, …). Ни ключей провайдеров, ни токенов, ни облачных учётных данных, ни `SSH_AUTH_SOCK`, ни встроенной конфигурации OpenCode (`OPENCODE_CONFIG_CONTENT`, в ней бывают ключи) они не получают, в том числе через конфигурацию, которую CanvasTTY добавляет к запуску; нужный ключ передаётся явно, через `secretEnv` вклада в запуск. Чтобы всё же передать переменную, перечислите её в `CANVASTTY_AGENT_PASS_ENV` (через запятую) в окружении, с которым запускается CanvasTTY. Речь только о наследуемых переменных: без слоя изоляции агент работает от вашего имени и может прочитать ключ из файла профиля оболочки, а обычный терминал запускает вашу login-оболочку, которая этот файл читает.

### Linux: если bubblewrap не запускается

Ubuntu 24.04 и новее (и другие дистрибутивы с `kernel.apparmor_restrict_unprivileged_userns=1`) разрешают создавать непривилегированные пространства имён пользователя только программам с профилем AppArmor, а bubblewrap без них не работает. CanvasTTY проверяет это один раз (после неудачи — снова через минуту) и при включённой изоляции, если `bwrap` установлен, но не запускается, ведёт себя как на компьютере без слоя изоляции: субагенты и агенты от плагинов работают вручную, а карточка объясняет почему. Чтобы разрешить, дайте bubblewrap собственный профиль (рекомендуется, касается только `bwrap`):
Expand Down
2 changes: 2 additions & 0 deletions docs/installing-and-security.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ gh variable set SPARKLE_PUBLIC_ED_KEY --repo howdeploy/CanvasTTY \

**Git 审计。** 隔离的智能体会话结束、被关闭或在退出后恢复时,CanvasTTY 会检查其文件夹下 git 目录发生变化的仓库。如果 git 现在会在隔离外运行某些东西(`core.hooksPath`、filter 或 diff 驱动、`fsmonitor`、hook 文件、`info/attributes`),会出现一条列出具体变化的通知;**Neutralize** 删除这些键并停用这些文件,**Keep as is** 保持不变。它不会撤销项目内的其他文件改动。

**环境中的服务商密钥。** 你自己启动的普通终端卡片保留你的全部环境,但不包括 CanvasTTY 自己的凭据(`CANVASTTY_GITHUB_TOKEN`,以及任何 `CANVASTTY_*TOKEN`/`*KEY`/`*SECRET`/`*PASSWORD`),它们只供应用本身使用。智能体卡片永远不会继承这些凭据,也不会继承组织级管理员凭据(`OPENAI_ADMIN_KEY`、`ANTHROPIC_ADMIN_KEY`,以及任何 `*_ADMIN_*KEY` 或 `*_ADMIN_*TOKEN`)。除此之外,你自己启动的智能体在任何模式下都保留你的环境,包括 `OPENAI_API_KEY`、`ANTHROPIC_API_KEY` 等普通密钥,因此用 API 密钥登录的 CLI 照常工作。子智能体以及插件启动的任何卡片(包括普通终端卡片,因为由插件操控)只继承进程所需的变量:`PATH`、`HOME`、用户、shell、语言区域和终端变量、临时目录、XDG 基础目录和桌面类型(`XDG_CONFIG_HOME`、`XDG_RUNTIME_DIR`、`XDG_CURRENT_DESKTOP` 等;其他 `XDG_` 和 `LC_` 变量不会继承,因此 `XDG_SESSION_COOKIE` 这类会话 cookie 也不会)、Windows 系统目录、代理变量(`HTTP(S)_PROXY`、`ALL_PROXY`、`NO_PROXY`)、证书设置(`SSL_CERT_FILE`、`SSL_CERT_DIR`、`NODE_EXTRA_CA_CERTS`、`REQUESTS_CA_BUNDLE`、`CURL_CA_BUNDLE`)、`EDITOR`/`VISUAL`/`PAGER` 以及各 CLI 自己的主目录(`CODEX_HOME`、`CLAUDE_CONFIG_DIR` 等)。它们拿不到任何服务商密钥、令牌、云凭据、`SSH_AUTH_SOCK` 或 OpenCode 内联配置(`OPENCODE_CONFIG_CONTENT`,其中可能含有密钥),通过 CanvasTTY 为启动添加的配置也不会;需要的密钥通过启动贡献的 `secretEnv` 显式传入。如仍要传递某个变量,请在 CanvasTTY 启动时的环境中把它列入 `CANVASTTY_AGENT_PASS_ENV`(逗号分隔)。这里只涉及继承的变量:没有隔离层时,智能体以你的身份运行,仍可从 shell 配置文件中读取密钥;普通终端卡片运行你的登录 shell,也会读取该文件。

### Linux:bubblewrap 无法启动时

Ubuntu 24.04 及更新版本(以及其他设置了 `kernel.apparmor_restrict_unprivileged_userns=1` 的发行版)只允许带 AppArmor 配置文件的程序创建非特权用户命名空间,而 bubblewrap 需要它。CanvasTTY 会检查一次(失败后一分钟再查),启用隔离时,如果 `bwrap` 已安装却无法启动,就按没有隔离层的电脑处理:子智能体和插件启动的智能体以手动模式运行,卡片会说明原因。要允许它,可以为 bubblewrap 单独添加配置文件(推荐,只影响 `bwrap`):
Expand Down
17 changes: 13 additions & 4 deletions src/main/services/TerminalManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ import { LaunchRefusal } from "./launchRefusal.ts";
import { configuredMode } from "./configuredMode.ts";
import { envKey, RESERVED_ENV, type LaunchPipeline, type PreparedLaunch } from "./LaunchPipeline.ts";
import type { EnvironmentRegistry } from "./EnvironmentRegistry.ts";
import { agentEnvironment, shellEnvironment } from "./ambientProviderKeys.ts";
import {
persistedTerminalSession,
normalizeNestedCodex,
Expand Down Expand Up @@ -2061,19 +2062,27 @@ export class TerminalManager {
): PlannedSpawn | { failure: LaunchFailure } {
const providerCli = provider === "terminal" ? undefined : this.providerClis.get(provider);
if (providerCli?.state === "unavailable") return { failure: providerCli };
// The person's environment: a plain shell the person starts keeps all of it but CanvasTTY's own credentials; their
// own agent cards also lose admin keys; a delegated card (a subagent, or any card a plugin started, plain shell
// included, since its owner drives it) gets only an allowlist (ambientProviderKeys.ts). Every launch builder below
// reads this, never process.env; what a launch sets explicitly is added on top.
const delegated = this.isDelegated(id, role);
const baseEnvironment = provider === "terminal" && !delegated
? shellEnvironment(terminalEnvironment())
: agentEnvironment(terminalEnvironment(), { delegated });
// What decides whether Claude's lifecycle hooks may go over HTTP (ClaudeHttpHooks.ts): where and how it runs.
const claudeHttp = provider === "claude" && providerCli?.state === "available" ? {
executable: providerCli.executable,
profile,
environmentWrapped,
env: { ...terminalEnvironment(), ...providerCli.environment, ...(contribution?.env ?? {}) },
env: { ...baseEnvironment, ...providerCli.environment, ...(contribution?.env ?? {}) },
args: contribution?.args ?? [],
cwd
} : undefined;
const shellCli = provider === "terminal" && !environmentWrapped ? this.providerClis.get("codex") : undefined;
const agentRuntime = provider === "terminal"
? shellCli?.state === "available" ? this.agentRuntime?.prepareShellLaunch?.({ terminalSessionId: id, cli: shellCli, environment: terminalEnvironment() }) ?? null : null
: this.agentRuntime?.prepareLaunch({ terminalSessionId: id, provider, cwd,
? shellCli?.state === "available" ? this.agentRuntime?.prepareShellLaunch?.({ terminalSessionId: id, cli: shellCli, environment: baseEnvironment }) ?? null : null
: this.agentRuntime?.prepareLaunch({ terminalSessionId: id, provider, cwd, environment: baseEnvironment,
...(captureResult ? { captureResult: true } : {}),
...(claudeHttp ? { claudeHttp } : {}),
...(answerCaptureGrantExpiresAt === undefined ? {} : { answerCaptureGrantExpiresAt }) }) ?? null;
Expand Down Expand Up @@ -2106,12 +2115,12 @@ export class TerminalManager {
terminalSessionId: id,
provider,
cwd,
environment: baseEnvironment,
...(bridged ? {
includeOrchestration: true,
orchestrationTools: [...(role === "orchestrator" ? ORCHESTRATION_TOOL_NAMES : []), ...pluginTools]
} : {})
}) ?? null;
const baseEnvironment = terminalEnvironment();
const browserEnvironment = agentBrowser?.environment ?? {};
const runtimeEnvironment = agentRuntime?.environment ?? {};
const orchestrationEnvironment = agentOrchestration?.environment ?? {};
Expand Down
11 changes: 8 additions & 3 deletions src/main/services/agent-browser/AgentBrowserBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface PrepareAgentBrowserLaunchInput {
includeOrchestration?: boolean;
/** The canvastty_agents tools this session may use (default: the core tools). */
orchestrationTools?: readonly string[];
/** The card's own (already filtered) environment, which the launch builds from instead of the app's. */
environment?: Readonly<Record<string, string | undefined>>;
}

export interface PreparedAgentBrowserPtyLaunch {
Expand Down Expand Up @@ -66,12 +68,14 @@ export class AgentBrowserBridge implements AgentBrowserLaunchCoordinator {
// Browser access off: no canvastty_browser and no browser capability, but a session that gets canvastty_agents
// (orchestrators, plugin tools) still gets it; that server has its own capability and gateway.
if (!this.gateway.isEnabled) return input.includeOrchestration ? this.prepareOrchestrationOnly(input) : null;
const capability = this.gateway.registerAgent(input);
const { environment, ...agent } = input;
const capability = this.gateway.registerAgent(agent);
let providerLaunch;
try {
providerLaunch = this.providers.prepare(input.provider, capability.connectionId, {
...(input.includeOrchestration ? { orchestration: true } : {}),
...(input.orchestrationTools ? { orchestrationTools: input.orchestrationTools } : {})
...(input.orchestrationTools ? { orchestrationTools: input.orchestrationTools } : {}),
...(environment ? { environment } : {})
});
} catch (error) {
this.gateway.revokeTerminalSession(input.terminalSessionId);
Expand All @@ -93,7 +97,8 @@ export class AgentBrowserBridge implements AgentBrowserLaunchCoordinator {
const providerLaunch = this.providers.prepare(input.provider, connectionId, {
orchestration: true,
browser: false,
...(input.orchestrationTools ? { orchestrationTools: input.orchestrationTools } : {})
...(input.orchestrationTools ? { orchestrationTools: input.orchestrationTools } : {}),
...(input.environment ? { environment: input.environment } : {})
});
return this.launchWith(providerLaunch, "", connectionId, () => undefined, {});
}
Expand Down
Loading
Loading