diff --git a/docs/canvastty-plugin.schema.json b/docs/canvastty-plugin.schema.json index 14103b92c..2ae9abe90 100644 --- a/docs/canvastty-plugin.schema.json +++ b/docs/canvastty-plugin.schema.json @@ -37,7 +37,7 @@ "type": "array", "maxItems": 12, "uniqueItems": true, - "items": { "enum": ["storage", "secrets", "sessions:read", "limits:read", "launcher:open", "external:open", "browser:open", "media:library", "playlists:read", "playlists:write", "hermes:hud", "desktop:embed", "network", "launch:contribute", "environment:provide", "decision:provide", "tools:agents", "sessions:events", "sessions:read-screen", "sessions:launch", "sessions:control", "cards:decorate", "browser:engine"] } + "items": { "enum": ["storage", "secrets", "sessions:read", "limits:read", "launcher:open", "external:open", "browser:open", "media:library", "playlists:read", "playlists:write", "hermes:hud", "desktop:embed", "network", "launch:contribute", "environment:provide", "decision:provide", "tools:agents", "sessions:events", "sessions:read-screen", "sessions:launch", "sessions:control", "sessions:control-any", "cards:decorate", "browser:engine"] } }, "contributions": { "type": "array", @@ -83,7 +83,7 @@ "type": "array", "maxItems": 12, "uniqueItems": true, - "items": { "enum": ["storage", "secrets", "sessions:read", "limits:read", "launcher:open", "external:open", "browser:open", "media:library", "playlists:read", "playlists:write", "hermes:hud", "desktop:embed", "network", "launch:contribute", "environment:provide", "decision:provide", "tools:agents", "sessions:events", "sessions:read-screen", "sessions:launch", "sessions:control", "cards:decorate", "browser:engine"] } + "items": { "enum": ["storage", "secrets", "sessions:read", "limits:read", "launcher:open", "external:open", "browser:open", "media:library", "playlists:read", "playlists:write", "hermes:hud", "desktop:embed", "network", "launch:contribute", "environment:provide", "decision:provide", "tools:agents", "sessions:events", "sessions:read-screen", "sessions:launch", "sessions:control", "sessions:control-any", "cards:decorate", "browser:engine"] } }, "files": { "type": "array", "minItems": 1, "maxItems": 500, "items": { "$ref": "#/$defs/moduleAsset" } } } diff --git a/docs/plugin-api.d.ts b/docs/plugin-api.d.ts index e37a8946b..321aef423 100644 --- a/docs/plugin-api.d.ts +++ b/docs/plugin-api.d.ts @@ -100,7 +100,7 @@ export interface CanvasTTYPluginContext { id: string; name: string; version: string; - permissions: Array<"storage" | "secrets" | "sessions:read" | "limits:read" | "launcher:open" | "external:open" | "browser:open" | "media:library" | "playlists:read" | "playlists:write" | "hermes:hud" | "desktop:embed" | "network" | "launch:contribute" | "environment:provide" | "decision:provide" | "tools:agents" | "sessions:events" | "sessions:read-screen" | "sessions:launch" | "sessions:control" | "cards:decorate" | "browser:engine">; + permissions: Array<"storage" | "secrets" | "sessions:read" | "limits:read" | "launcher:open" | "external:open" | "browser:open" | "media:library" | "playlists:read" | "playlists:write" | "hermes:hud" | "desktop:embed" | "network" | "launch:contribute" | "environment:provide" | "decision:provide" | "tools:agents" | "sessions:events" | "sessions:read-screen" | "sessions:launch" | "sessions:control" | "sessions:control-any" | "cards:decorate" | "browser:engine">; modules: string[]; }; contribution: { @@ -523,7 +523,7 @@ export interface CanvasTTYServiceHostApi { launchOptions?: Record>; environment?: { pluginId: string; kind: string; options?: Record }; }): { sessionId: string }; - /** Needs `sessions:control`; only cards this plugin created. Enter is added unless `submit: false`. */ + /** Needs `sessions:control`; only cards this plugin created, or with `sessions:control-any` a Codex, Claude or Kimi card the person opened (not plain terminals, other providers, subagents or other plugins' cards). Enter is added unless `submit: false`. */ /** Waits until a launch its plugins prepare has started; `sent` is false (and the text dropped) when it did not start. */ "sessions.send"(params: { sessionId: string; text: string; submit?: boolean }): { sessionId: string; @@ -535,8 +535,12 @@ export interface CanvasTTYServiceHostApi { reason?: string; }; }; + /** Needs `sessions:control` (and `sessions:control-any` for Codex, Claude and Kimi cards the person opened). Esc only for an idle card the person has not typed into since its last turn, with a dismissible menu's hint in its last lines. */ + "sessions.dismiss"(params: { sessionId: string }): { sessionId: string; dismissed: boolean; reason?: string }; /** Needs `sessions:control`; only cards this plugin created. Closes the card, keeps its environment data. */ "sessions.stop"(params: { sessionId: string }): { sessionId: string; stopped: true }; + /** Needs `limits:read`. The same account-free snapshot `host.limits.get` gives surfaces. */ + "limits.get"(params?: Record): { state: "ready"; snapshot: unknown }; /** Needs `cards:decorate`. `null` removes this plugin's badge from the card. */ "cards.setBadge"(params: { sessionId: string; badge: { text: string; tone?: CanvasTTYCardTone; tooltip?: string } | null }): null; } diff --git a/docs/plugins.md b/docs/plugins.md index 866367510..a79cfeaff 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -156,9 +156,10 @@ A service may call back this host API (the base that later extension points add | `event` `{ event, data }` | notification | none | Delivered to this plugin's live surfaces through `host.service.onEvent` | | `redaction.register` `{ values }` | request | none | Up to 32 strings (4096 characters each, 8 or more to count) that CanvasTTY masks in every text one agent reads from another; kept in memory only | | `secrets.get` `{ key }` | request | `secrets` permission | The plugin's own secret (the same store as `host.secrets`), or `null`. The value is then masked like `redaction.register` values. For keys a service needs itself (an API key for a model it calls); never send one back to a surface | +| `limits.get` | request | `limits:read` | `{ state: "ready", snapshot }` (or `{ state: "loading", snapshot: null }` before the first one): the same account-free `LimitsSnapshot` web surfaces get (per provider windows with `usedPercent` and `resetsAt`) | | `sessions.subscribe` / `sessions.list` / `sessions.unsubscribe` | request | `sessions:events` | Card events and the open cards (see [Session events](#session-events-and-plugin-owned-cards-sessions)) | | `sessions.create` | request | `sessions:launch` | Starts a card the plugin owns | -| `sessions.send` / `sessions.stop` | request | `sessions:control` | Only for cards the plugin started | +| `sessions.send` / `sessions.dismiss` / `sessions.stop` | request | `sessions:control` | Only for cards the plugin started; `sessions:control-any` adds send and dismiss for Codex, Claude and Kimi cards the person opened (not subagents) | | `cards.setBadge` `{ sessionId, badge }` | request | `cards:decorate` | A short plain-text badge on any card (see [Card badges and actions](#card-badges-and-actions-cardsdecorate)) | The host binds every call to the service's own plugin; a service cannot name another plugin or read another plugin's secrets, and reaches sessions only through the `sessions:*` permissions below. The example [`service-echo`](../examples/plugins/service-echo) saves a token from its page with `host.secrets.set` and its service reads it with `secrets.get`, answering only whether one is set. @@ -355,14 +356,15 @@ interface PluginSessionEvent { } ``` -Events carry metadata only. With `sessions:read-screen` (the consent text says this is private data), `status` and `exited` events add the last 4000 characters of the card's output as plain text, masked by the redaction registry. `sessions.list` returns the same summaries on demand. +Events carry metadata only. With `sessions:read-screen` (the consent text says this is private data), `status` and `exited` events add the last 4000 characters of the card's output as plain text, masked by the redaction registry. `sessions.list` returns the same summaries on demand, and `sessions.screen` `{ sessionId }` returns `{ sessionId, screen }` with that text for one card, for an agent that ends a turn without a status change (Codex at a usage limit stays `working`). Control follows the agent-control gateway's model: the service is one controller and owns only what it created. Ownership is saved with the card's session record, so a restored card still belongs to the plugin that started it. | Request | Gate | Effect | |:--|:--|:--| | `sessions.create` `{ provider, cwd, profile?, title?, launchOptions?, environment? }` | `sessions:launch` | Starts an `agent` card through the normal launch pipeline (launch options and environments included; a refusal shows on the card). The card is visible and never takes focus. At most 16 per plugin. Answer `{ sessionId }` | -| `sessions.send` `{ sessionId, text, submit? }` | `sessions:control` | Types the text (Enter unless `submit: false`) into a card this plugin started. A card whose launch its plugins still prepare gets it once that launch started; `sent` is false when the launch did not start (the text is dropped) | +| `sessions.send` `{ sessionId, text, submit? }` | `sessions:control` | Types the text (Enter unless `submit: false`) into a card this plugin started, or with `sessions:control-any` into a Codex, Claude or Kimi card the person opened. Delivery is the same staged path: in Codex, Claude and Kimi cards it waits for an empty composer, and it refuses while the card needs approval. Other providers have no composer check, so `sessions:control-any` does not reach them: the person's draft would be submitted with the text. A card whose launch its plugins still prepare gets it once that launch started; `sent` is false when the launch did not start (the text is dropped) | +| `sessions.dismiss` `{ sessionId }` | `sessions:control` | Presses Esc in a card it may send to, only when the card is idle, the person has not typed into it since its last turn, and a dismissible menu's hint is in its last lines (such as Claude's usage-limit options; Claude, Codex and Kimi cards only); `dismissed` is false otherwise and nothing is written | | `sessions.stop` `{ sessionId }` | `sessions:control` | Closes a card this plugin started; its environment data is kept | A foreign or unknown id gets the same error, so a plugin cannot probe other cards. There is no delete and no screen-reading control call. @@ -423,12 +425,13 @@ host.onStorageChange(listener) notifies every live contribution of the same plug | `decision:provide` | A service's `decide` and `canvastty.decide` | Sees agents' commands and file writes (with their input) before they run and can block them or ask the person; allowing needs a second confirmation | | `tools:agents` | A service's `tools` and `canvastty.tools.call` | Offers tools to agents of the listed roles; receives their arguments and the calling card's summary | | `sessions:events` | `sessions.subscribe`, `sessions.list` | Card metadata: provider, role, parent, title, status, folders, environment ref; no screen text | -| `sessions:read-screen` | `screen` in status and exit events | The end of every card's output (masked): private data | +| `sessions:read-screen` | `screen` in status and exit events, `sessions.screen` | The end of every card's output (masked): private data | | `sessions:launch` | `sessions.create` | Starts visible agent cards through the normal launch | -| `sessions:control` | `sessions.send`, `sessions.stop` | Types into and closes only the cards the plugin started | +| `sessions:control` | `sessions.send`, `sessions.dismiss`, `sessions.stop` | Types into and closes only the cards the plugin started | +| `sessions:control-any` | `sessions.send`, `sessions.dismiss` (with `sessions:control`) | Also types into Codex, Claude and Kimi cards the person opened; never plain terminals, other providers, other plugins' cards, subagents or `sessions.stop`. Those agents run commands with the person's permissions, so the consent treats it as running any command | | `cards:decorate` | `cards.setBadge`, a service's `cardActions`, `canvastty.cards.invoke` | Plain-text badges on cards and actions in their menu | | `browser:engine` | A service's `browserEngine` and `canvastty.browserEngine.*` | Receives the URLs of agents' background tabs and serves them from its own engine; no cookies, profile or credentials | -| `limits:read` | `limits.get` | The same sanitized `LimitsSnapshot` used by HOME | +| `limits:read` | `limits.get` (surfaces and services) | The same sanitized `LimitsSnapshot` used by HOME | | `launcher:open` | `launcher.open` | Opens the built-in provider Focus Card or terminal action; it does not bypass user launch choices | | `external:open` | `external.open` | Opens only an explicit HTTP(S) URL through the OS | | `browser:open` | `browser.open` | Opens only an explicit HTTP(S) URL in CanvasTTY's embedded Browser card and its shared browser session, including localhost | diff --git a/docs/plugins.ru.md b/docs/plugins.ru.md index 9b46a0b3f..09a48d2d8 100644 --- a/docs/plugins.ru.md +++ b/docs/plugins.ru.md @@ -137,9 +137,10 @@ Script запускается отдельным процессом из кат | `event` `{ event, data }` | уведомление | нет | Доставляется открытым поверхностям плагина через `host.service.onEvent` | | `redaction.register` `{ values }` | запрос | нет | До 32 строк (до 4096 символов, учитываются от 8), которые CanvasTTY маскирует во всём тексте, который один агент читает у другого; хранятся только в памяти | | `secrets.get` `{ key }` | запрос | разрешение `secrets` | Собственный секрет плагина (то же хранилище, что `host.secrets`) или `null`. Значение затем маскируется, как значения `redaction.register`. Для ключей, которые нужны самому сервису (API-ключ модели, которую он вызывает); никогда не отправляйте его обратно на страницу | +| `limits.get` | запрос | `limits:read` | `{ state: "ready", snapshot }` (или `{ state: "loading", snapshot: null }` до первого снимка): тот же `LimitsSnapshot` без данных аккаунта, что получают веб-поверхности (окна провайдеров с `usedPercent` и `resetsAt`) | | `sessions.subscribe` / `sessions.list` / `sessions.unsubscribe` | запрос | `sessions:events` | События окон и список открытых окон (см. «События сессий») | | `sessions.create` | запрос | `sessions:launch` | Запускает окно, которым владеет плагин | -| `sessions.send` / `sessions.stop` | запрос | `sessions:control` | Только для окон, запущенных этим плагином | +| `sessions.send` / `sessions.dismiss` / `sessions.stop` | запрос | `sessions:control` | Только для окон, запущенных этим плагином; `sessions:control-any` добавляет send и dismiss для окон Codex, Claude и Kimi, открытых человеком (не субагентов) | | `cards.setBadge` `{ sessionId, badge }` | запрос | `cards:decorate` | Короткая текстовая метка на любом окне (см. «Метки и действия на окнах») | Хост привязывает каждый вызов к плагину самого сервиса: сервис не может назвать другой плагин или прочитать секреты другого плагина, а к сессиям обращается только через разрешения `sessions:*` ниже. Пример [`service-echo`](../examples/plugins/service-echo) сохраняет токен со своей страницы через `host.secrets.set`, а его сервис читает его через `secrets.get` и отвечает только, задан ли он. @@ -333,14 +334,15 @@ interface PluginSessionEvent { } ``` -События содержат только метаданные. С `sessions:read-screen` (в тексте согласия сказано, что это личные данные) события `status` и `exited` добавляют последние 4000 символов вывода окна обычным текстом, замаскированным реестром секретов. `sessions.list` возвращает те же сводки по запросу. +События содержат только метаданные. С `sessions:read-screen` (в тексте согласия сказано, что это личные данные) события `status` и `exited` добавляют последние 4000 символов вывода окна обычным текстом, замаскированным реестром секретов. `sessions.list` возвращает те же сводки по запросу, а `sessions.screen` `{ sessionId }` возвращает `{ sessionId, screen }` с этим текстом для одного окна — для агента, который заканчивает ход без смены статуса (Codex на лимите остаётся `working`). Управление устроено как в шлюзе agent-control: сервис — один контроллер и владеет только тем, что создал. Владение сохраняется в записи сессии окна, поэтому восстановленное окно по-прежнему принадлежит плагину, который его запустил. | Запрос | Условие | Действие | |:--|:--|:--| | `sessions.create` `{ provider, cwd, profile?, title?, launchOptions?, environment? }` | `sessions:launch` | Запускает окно `agent` через обычный конвейер запуска (включая опции запуска и среды; отказ показывается на окне). Окно видимо и никогда не забирает фокус. Не больше 16 на плагин. Ответ `{ sessionId }` | -| `sessions.send` `{ sessionId, text, submit? }` | `sessions:control` | Вводит текст (с Enter, если не `submit: false`) в окно, запущенное этим плагином. Окно, чей запуск ещё готовят плагины, получает его, когда запуск начался; `sent` равен false, если запуск не состоялся (текст отбрасывается) | +| `sessions.send` `{ sessionId, text, submit? }` | `sessions:control` | Вводит текст (с Enter, если не `submit: false`) в окно, запущенное этим плагином, а с `sessions:control-any` — в окно Codex, Claude или Kimi, открытое человеком. Доставка та же: в окнах Codex, Claude и Kimi ждёт пустое поле ввода и отказывает, пока окно ждёт подтверждения. У других провайдеров поле ввода не проверяется, поэтому `sessions:control-any` до них не достаёт: черновик человека отправился бы вместе с текстом. Окно, чей запуск ещё готовят плагины, получает его, когда запуск начался; `sent` равен false, если запуск не состоялся (текст отбрасывается) | +| `sessions.dismiss` `{ sessionId }` | `sessions:control` | Нажимает Esc в окне, куда плагину можно писать, только если окно простаивает, человек ничего не вводил в него после прошлого хода, а подсказка закрываемого меню стоит в последних строках (например, меню лимита Claude; только окна Claude, Codex и Kimi); иначе `dismissed` равен false и ничего не вводится | | `sessions.stop` `{ sessionId }` | `sessions:control` | Закрывает окно, запущенное этим плагином; данные его среды сохраняются | Чужой или неизвестный id получает одну и ту же ошибку, поэтому плагин не может прощупывать другие окна. Удаления и чтения экрана через управление нет. @@ -401,12 +403,13 @@ host.onStorageChange(listener) сообщает всем открытым пов | `decision:provide` | `decide` сервиса и `canvastty.decide` | Видит команды и записи файлов агентов (с их вводом) до выполнения и может запрещать их или спрашивать человека; для разрешения нужно второе подтверждение | | `tools:agents` | `tools` сервиса и `canvastty.tools.call` | Предлагает инструменты агентам указанных ролей; получает их аргументы и сводку вызывающего окна | | `sessions:events` | `sessions.subscribe`, `sessions.list` | Метаданные окон: провайдер, роль, родитель, заголовок, статус, папки, ref среды; без текста экрана | -| `sessions:read-screen` | `screen` в событиях status и exited | Конец вывода каждого окна (замаскированный): личные данные | +| `sessions:read-screen` | `screen` в событиях status и exited, `sessions.screen` | Конец вывода каждого окна (замаскированный): личные данные | | `sessions:launch` | `sessions.create` | Запускает видимые окна агентов через обычный запуск | | `sessions:control` | `sessions.send`, `sessions.stop` | Вводит текст и закрывает только окна, запущенные плагином | +| `sessions:control-any` | `sessions.send`, `sessions.dismiss` (вместе с `sessions:control`) | Вводит текст и в окна Codex, Claude и Kimi, открытые человеком; никогда в обычные терминалы, окна других провайдеров, других плагинов и субагентов, и без `sessions.stop`. Эти агенты выполняют команды с правами человека, поэтому согласие приравнивает это разрешение к запуску любых команд | | `cards:decorate` | `cards.setBadge`, `cardActions` сервиса, `canvastty.cards.invoke` | Текстовые метки на окнах и действия в их меню | | `browser:engine` | `browserEngine` сервиса и `canvastty.browserEngine.*` | Получает URL фоновых вкладок агентов и открывает их в своём движке; без cookies, профиля и учётных данных | -| `limits:read` | `limits.get` | Тот же очищенный `LimitsSnapshot`, который использует HOME | +| `limits:read` | `limits.get` (поверхности и сервисы) | Тот же очищенный `LimitsSnapshot`, который использует HOME | | `launcher:open` | `launcher.open` | Открывает штатную Focus Card или запуск терминала; не обходит пользовательский выбор | | `external:open` | `external.open` | Передаёт ОС только явную HTTP(S)-ссылку | | `browser:open` | `browser.open` | Открывает только явную HTTP(S)-ссылку во встроенной карточке Browser и её общей browser-сессии, включая localhost | diff --git a/docs/plugins.zh-CN.md b/docs/plugins.zh-CN.md index 21651e19b..f818f145f 100644 --- a/docs/plugins.zh-CN.md +++ b/docs/plugins.zh-CN.md @@ -135,9 +135,10 @@ Hook-only 插件使用空的 `contributions` 与非空的 `hooks`。安装只复 | `event` `{ event, data }` | 通知 | 无 | 通过 `host.service.onEvent` 发送给该插件的活动界面 | | `redaction.register` `{ values }` | 请求 | 无 | 最多 32 个字符串(每个最多 4096 字符,8 字符以上才生效),CanvasTTY 会在一个 agent 读取另一个 agent 的所有文本中遮蔽它们;只保存在内存中 | | `secrets.get` `{ key }` | 请求 | `secrets` 权限 | 插件自己的机密(与 `host.secrets` 同一存储),或 `null`。之后该值会像 `redaction.register` 的值一样被遮蔽。用于服务自身需要的密钥(例如它调用的模型的 API 密钥);绝不要把它发回界面 | +| `limits.get` | 请求 | `limits:read` | `{ state: "ready", snapshot }`(首个快照之前为 `{ state: "loading", snapshot: null }`):与网页界面相同、不含账户信息的 `LimitsSnapshot`(各提供方窗口的 `usedPercent` 与 `resetsAt`) | | `sessions.subscribe` / `sessions.list` / `sessions.unsubscribe` | 请求 | `sessions:events` | 卡片事件和当前打开的卡片(见“会话事件”) | | `sessions.create` | 请求 | `sessions:launch` | 启动一张归插件所有的卡片 | -| `sessions.send` / `sessions.stop` | 请求 | `sessions:control` | 仅限该插件启动的卡片 | +| `sessions.send` / `sessions.dismiss` / `sessions.stop` | 请求 | `sessions:control` | 仅限该插件启动的卡片;`sessions:control-any` 还允许向用户打开的 Codex、Claude 与 Kimi 卡片 send 与 dismiss(不含子智能体) | | `cards.setBadge` `{ sessionId, badge }` | 请求 | `cards:decorate` | 在任意卡片上显示简短的纯文本标记(见“卡片标记与动作”) | 宿主把每次调用绑定到服务自身的插件:服务无法指定其他插件或读取其他插件的机密,只能通过下面的 `sessions:*` 权限访问会话。示例 [`service-echo`](../examples/plugins/service-echo) 在其页面用 `host.secrets.set` 保存令牌,其服务用 `secrets.get` 读取,只回答是否已设置。 @@ -331,14 +332,15 @@ interface PluginSessionEvent { } ``` -事件只包含元数据。具有 `sessions:read-screen`(同意文本说明这是私人数据)时,`status` 和 `exited` 事件会附带卡片输出的最后 4000 个字符,为纯文本并经过密钥遮蔽。`sessions.list` 按需返回同样的摘要。 +事件只包含元数据。具有 `sessions:read-screen`(同意文本说明这是私人数据)时,`status` 和 `exited` 事件会附带卡片输出的最后 4000 个字符,为纯文本并经过密钥遮蔽。`sessions.list` 按需返回同样的摘要;`sessions.screen` `{ sessionId }` 为单张卡片返回 `{ sessionId, screen }`,适用于结束一轮却不改变状态的智能体(Codex 达到用量上限后仍为 `working`)。 控制方式与 agent-control 网关相同:服务是一个控制者,只拥有它创建的卡片。所有权随卡片的会话记录保存,因此恢复后的卡片仍属于启动它的插件。 | 请求 | 条件 | 效果 | |:--|:--|:--| | `sessions.create` `{ provider, cwd, profile?, title?, launchOptions?, environment? }` | `sessions:launch` | 通过常规启动流程启动一张 `agent` 卡片(包括启动选项和环境;拒绝原因显示在卡片上)。卡片可见且从不抢占焦点。每个插件最多 16 张。回答 `{ sessionId }` | -| `sessions.send` `{ sessionId, text, submit? }` | `sessions:control` | 向本插件启动的卡片输入文本(除非 `submit: false`,否则带回车)。启动仍由插件准备中的卡片在启动开始后收到文本;启动未成功时 `sent` 为 false(文本被丢弃) | +| `sessions.send` `{ sessionId, text, submit? }` | `sessions:control` | 向本插件启动的卡片输入文本(除非 `submit: false`,否则带回车),具有 `sessions:control-any` 时也可向用户打开的 Codex、Claude 或 Kimi 卡片输入。在 Codex、Claude 与 Kimi 卡片中会等待输入框为空,卡片等待批准时拒绝。其他提供方没有输入框检查,因此 `sessions:control-any` 不覆盖它们:否则用户的草稿会随文本一起提交。启动仍由插件准备中的卡片在启动开始后收到文本;启动未成功时 `sent` 为 false(文本被丢弃) | +| `sessions.dismiss` `{ sessionId }` | `sessions:control` | 在可输入的卡片中按 Esc:仅当卡片空闲、上一轮之后用户未输入,且最后几行显示可关闭菜单的提示(例如 Claude 的用量限制菜单;仅限 Claude、Codex 和 Kimi 卡片);否则 `dismissed` 为 false,不写入任何内容 | | `sessions.stop` `{ sessionId }` | `sessions:control` | 关闭本插件启动的卡片;保留其环境数据 | 他人的或未知的 id 得到相同的错误,因此插件无法探测其他卡片。没有删除操作,也没有读取屏幕的控制调用。 @@ -399,9 +401,10 @@ host.onStorageChange(listener) 会把 host.storage.set 的写入通知给同一 | `decision:provide` | 服务的 `decide` 和 `canvastty.decide` | 在 agent 的命令和文件写入运行之前看到它们(含输入),可以拒绝或询问用户;允许需要第二次确认 | | `tools:agents` | 服务的 `tools` 和 `canvastty.tools.call` | 向所列角色的 agent 提供工具;接收其参数和调用方卡片的摘要 | | `sessions:events` | `sessions.subscribe`、`sessions.list` | 卡片元数据:服务商、角色、父级、标题、状态、文件夹、环境 ref;不含屏幕文本 | -| `sessions:read-screen` | status 和 exited 事件中的 `screen` | 每张卡片输出的末尾(已遮蔽):私人数据 | +| `sessions:read-screen` | status 和 exited 事件中的 `screen`、`sessions.screen` | 每张卡片输出的末尾(已遮蔽):私人数据 | | `sessions:launch` | `sessions.create` | 通过常规启动流程启动可见的 agent 卡片 | -| `sessions:control` | `sessions.send`、`sessions.stop` | 只能向本插件启动的卡片输入文本并关闭它们 | +| `sessions:control` | `sessions.send`、`sessions.dismiss`、`sessions.stop` | 只能向本插件启动的卡片输入文本并关闭它们 | +| `sessions:control-any` | `sessions.send`、`sessions.dismiss`(需同时具有 `sessions:control`) | 也可向用户打开的 Codex、Claude 与 Kimi 卡片输入文本;不包括普通终端、其他提供方、其他插件的卡片和子智能体,也不能 `sessions.stop`。这些智能体以用户的权限执行命令,因此同意文本将其视为可运行任意命令 | | `cards:decorate` | `cards.setBadge`、服务的 `cardActions`、`canvastty.cards.invoke` | 卡片上的纯文本标记及其菜单中的动作 | | `browser:engine` | 服务的 `browserEngine` 和 `canvastty.browserEngine.*` | 接收 agent 后台标签页的 URL 并用自己的引擎打开;没有 cookie、配置文件或凭据 | | `limits:read` | `limits.get` | 与 HOME 使用的同一个脱敏 `LimitsSnapshot` | diff --git a/src/main/index.ts b/src/main/index.ts index 03fabc250..609dbe374 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -414,6 +414,11 @@ async function initializeServices(ipc: IpcRegistrar): Promise { return pluginSecretsService.get(pluginId, key); }, sessions: (pluginId, serviceId, method, params, permissions) => pluginSessions?.handle(pluginId, serviceId, method, params, permissions), + limits: async () => { + // A service may ask while startup still runs; it gets the same answer a surface gets before its first snapshot. + if (!limitsService) return { state: "loading", snapshot: null }; + return { state: "ready", snapshot: withoutAccountScope(await limitsService.get()) }; + }, setBadge: (pluginId, params) => { if (!pluginCards) throw new Error("Cards are not ready yet."); return pluginCards.setBadge(pluginId, params); diff --git a/src/main/services/PluginManager.ts b/src/main/services/PluginManager.ts index a6ccaa39c..0da621eab 100644 --- a/src/main/services/PluginManager.ts +++ b/src/main/services/PluginManager.ts @@ -151,6 +151,7 @@ const PLUGIN_PERMISSIONS = new Set([ "sessions:read-screen", "sessions:launch", "sessions:control", + "sessions:control-any", "cards:decorate", "browser:engine" ]); diff --git a/src/main/services/PluginServiceSupervisor.ts b/src/main/services/PluginServiceSupervisor.ts index baf8939f0..f0ebff72f 100644 --- a/src/main/services/PluginServiceSupervisor.ts +++ b/src/main/services/PluginServiceSupervisor.ts @@ -41,6 +41,8 @@ export interface PluginServiceHost { * does not know. `permissions` are the plugin's active manifest permissions; it checks them per method. */ sessions?(pluginId: string, serviceId: string, method: string, params: unknown, permissions: readonly PluginPermission[]): unknown; + /** `limits.get`, already checked for `limits:read`: the same account-free snapshot web surfaces get. */ + limits?(pluginId: string): Promise; /** `cards.setBadge` (EP-7), already checked for `cards:decorate`. */ setBadge?(pluginId: string, params: unknown): unknown; /** The service process ended (stopped, crashed or removed): its subscriptions end with it. */ @@ -628,6 +630,10 @@ export class PluginServiceSupervisor { this.options.host.registerSecrets?.(spec.pluginId, values.values as string[]); return null; } + if (method === "limits.get" && this.options.host.limits) { + if (!spec.permissions.includes("limits:read")) throw new Error("Plugin does not have the limits:read permission."); + return this.options.host.limits(spec.pluginId); + } if (method === "cards.setBadge" && this.options.host.setBadge) { if (!spec.permissions.includes("cards:decorate")) throw new Error("Plugin does not have the cards:decorate permission."); return this.options.host.setBadge(spec.pluginId, params); diff --git a/src/main/services/PluginSessions.ts b/src/main/services/PluginSessions.ts index e6a3acbd7..5fc220d80 100644 --- a/src/main/services/PluginSessions.ts +++ b/src/main/services/PluginSessions.ts @@ -61,6 +61,7 @@ interface TerminalPort { setPluginOwner(id: string, pluginId: string): void; readBuffer(id: string): TerminalBufferSnapshot; deliverPrompt(id: string, text: string, submit?: boolean, signal?: AbortSignal): Promise; + dismissIdleMenu(id: string): Promise<{ dismissed: boolean; reason?: string }>; dispose(id: string, options?: { keepEnvironmentData?: boolean }): void; redactSecrets(text: string): string; redactSecretsTail(text: string, maxChars: number): string; @@ -82,13 +83,17 @@ interface Subscriber { const MAX_OWNED_PER_PLUGIN = 16; const MAX_SEND_CHARS = 16_000; const MAX_SCREEN_CHARS = 4_000; +/** `deliverPrompt` waits for these providers' empty composer; see `TerminalManager.deliverPrompt`. */ +const COMPOSER_CHECKED_PROVIDERS = new Set(["codex", "claude", "kimi"]); /** * Session events and plugin-owned session control (EP-4). A service subscribes to card events (metadata only; * the redacted end of the output only with `sessions:read-screen`). It can start cards through the normal launch * pipeline (launch options and environments included), and send text to and stop only the cards it started: * the same ownership rule as the agent-control gateway. Ownership lives on the card's saved record, so a restored - * card stays under the plugin that started it. + * card stays under the plugin that started it. With `sessions:control-any` a service may also send text to the + * Codex, Claude and Kimi cards the person opened (never a plain terminal, another plugin's card, a subagent or + * another provider, and never stop them). */ export class PluginSessions { private readonly deps: PluginSessionsDependencies; @@ -118,12 +123,22 @@ export class PluginSessions { case "sessions.list": need("sessions:events"); return { sessions: this.summaries(pluginId, values.ownedOnly === true) }; + case "sessions.screen": { + // The same redacted tail events carry, on demand: an agent that never ends its turn sends no status event. + need("sessions:read-screen"); + const sessionId = typeof values.sessionId === "string" ? values.sessionId : ""; + if (!this.summary(sessionId)) throw new Error("No such session."); + return { sessionId, screen: this.screen(sessionId) }; + } case "sessions.create": need("sessions:launch"); return this.create(pluginId, values); case "sessions.send": need("sessions:control"); - return this.send(pluginId, values); + return this.send(pluginId, values, permissions.includes("sessions:control-any")); + case "sessions.dismiss": + need("sessions:control"); + return this.dismiss(pluginId, values, permissions.includes("sessions:control-any")); case "sessions.stop": need("sessions:control"); return this.stop(pluginId, values); @@ -248,8 +263,8 @@ export class PluginSessions { } /** `sent` confirms a PTY write, not provider submission/acceptance. */ - private send(pluginId: string, values: Record): Promise<{ sessionId: string; sent: boolean; delivery?: PromptDeliveryReceipt }> { - const sessionId = this.requireOwned(pluginId, values.sessionId); + private send(pluginId: string, values: Record, anyAgent: boolean): Promise<{ sessionId: string; sent: boolean; delivery?: PromptDeliveryReceipt }> { + const sessionId = anyAgent && this.isPersonAgentCard(values.sessionId) ? values.sessionId : this.requireOwned(pluginId, values.sessionId); if (typeof values.text !== "string" || values.text.length === 0 || values.text.length > MAX_SEND_CHARS) { throw new Error(`text must be 1 to ${MAX_SEND_CHARS} characters.`); } @@ -258,6 +273,12 @@ export class PluginSessions { .then((delivery) => ({ sessionId, sent: delivery.delivered, ...(delivery.receipt ? { delivery: delivery.receipt } : {}) })); } + /** Esc for an idle card's menu (such as Claude's usage-limit options); the host checks the menu is on screen. */ + private dismiss(pluginId: string, values: Record, anyAgent: boolean): Promise<{ sessionId: string; dismissed: boolean; reason?: string }> { + const sessionId = anyAgent && this.isPersonAgentCard(values.sessionId) ? values.sessionId : this.requireOwned(pluginId, values.sessionId); + return this.deps.terminals.dismissIdleMenu(sessionId).then((result) => ({ sessionId, ...result })); + } + private stop(pluginId: string, values: Record): { sessionId: string; stopped: true } { const sessionId = this.requireOwned(pluginId, values.sessionId); // Closes the card; environment data is kept, as when a person closes it and chooses Keep. @@ -269,6 +290,17 @@ export class PluginSessions { return this.deps.terminals.pluginContext(sessionId)?.owner ?? null; } + /** + * An agent card the person opened; plain terminals, other plugins' cards and subagents (an orchestrator's chain, + * which no plugin owns either) stay reachable only by their owner (a plugin's own cards go through `requireOwned`). + * Only providers whose empty composer delivery verifies: elsewhere the person's draft would be submitted with the text. + */ + private isPersonAgentCard(sessionId: unknown): sessionId is string { + const context = typeof sessionId === "string" ? this.deps.terminals.pluginContext(sessionId) : null; + return Boolean(context && context.owner === null && COMPOSER_CHECKED_PROVIDERS.has(context.metadata.provider) + && context.metadata.role !== "subagent"); + } + /** A foreign or unknown id gets the same answer, so a plugin cannot probe other cards. */ private requireOwned(pluginId: string, sessionId: unknown): string { if (typeof sessionId !== "string" || this.owner(sessionId) !== pluginId) { diff --git a/src/main/services/TerminalManager.ts b/src/main/services/TerminalManager.ts index 03d2417e8..02bc329ce 100644 --- a/src/main/services/TerminalManager.ts +++ b/src/main/services/TerminalManager.ts @@ -66,7 +66,7 @@ import { launchEffortProblem, launchModelProblem, type ReasoningEffort } from ". import { SecretRedactionRegistry } from "./safety/SecretRedaction.ts"; import type { DecisionSession } from "./DecisionHooks.ts"; import { tryPtyOperation } from "./ptySafety.ts"; -import { SessionScreen } from "./materials/sessionScreen.ts"; +import { SessionScreen, terminalScreenText } from "./materials/sessionScreen.ts"; import { TerminalReplayState } from "./terminalReplayState.ts"; import { codexPromptInput, codexTerminalComposerReady } from "./codexInput.ts"; import { claudeTerminalComposerReady, promptComposer, promptPasteObserved, type PromptDeliveryReceipt } from "./promptDelivery.ts"; @@ -227,6 +227,8 @@ export const PTY_EXIT_WAIT_MS = 2_000; export const PTY_KILL_WAIT_MS = 1_000; /** Longer than every plugin step of a launch together (prepare, resume, launch options, wrap). */ export const LAUNCH_INPUT_WAIT_MS = 60_000; +/** A menu's "Esc to cancel" hint sits in its last lines; output above them is not a menu. */ +const DISMISS_HINT_LINES = 8; /** `delivered` acknowledges a PTY write, not the CLI accepting or submitting it. */ export type InputDelivery = ({ delivered: true } | { delivered: false; reason: string }) & { receipt?: PromptDeliveryReceipt }; @@ -1002,6 +1004,46 @@ export class TerminalManager { return this.deliverInput(id, data, options.waitMs ?? LAUNCH_INPUT_WAIT_MS, signal, provider === "codex", prompt); } + /** + * Presses Esc in an idle agent card that shows a dismissible menu (such as Claude's usage-limit options), the guard + * agent-control `dismiss` uses: never while a turn runs, an approval waits, input is queued, or the composer is ready. + * Nor after the person typed since the last clean turn: their draft is not a menu. The hint must be in the last + * lines of the screen, where menus put it, not in the agent's earlier output. + */ + async dismissIdleMenu(id: string): Promise<{ dismissed: boolean; reason?: string }> { + const session = this.sessions.get(id); + if (!session || session.metadata.exitCode !== null || !session.process) return { dismissed: false, reason: "The session does not accept input." }; + const busy = (): boolean => session.metadata.status === "working" || session.metadata.status === "needs_approval"; + if (busy() || session.inputQueue) return { dismissed: false, reason: "The agent is busy; nothing was written." }; + const typed = (): boolean => (session.manualInputRevision ?? 0) !== (session.cleanInputRevision ?? 0); + if (typed()) return { dismissed: false, reason: "The person typed into the card; nothing was written." }; + const provider = session.metadata.provider; + // Without a composer check an "Esc to interrupt" footer of a running process would read as a menu. + if (provider !== "claude" && provider !== "kimi" && provider !== "codex") { + return { dismissed: false, reason: `Menus are not recognized in ${provider} cards; nothing was written.` }; + } + const screen = new SessionScreen({ geometry: (target) => this.geometry(target), readBuffer: (target) => this.readBuffer(target) }, id); + try { + const state = await screen.inspect((terminal) => ({ + ready: provider === "claude" ? claudeTerminalComposerReady(terminal, this.claudeUnstyledComposerAllowed(id)) + : provider === "kimi" ? kimiComposerReady(terminal) + : codexTerminalComposerReady(terminal, this.codexUnstyledComposerAllowed(id)), + text: terminalScreenText(terminal) + })); + const footer = state?.text.split("\n").filter((line) => line.trim()).slice(-DISMISS_HINT_LINES).join("\n") ?? ""; + if (!state || state.ready || !/\besc(?:ape)?\s+to\s+(?:cancel|exit|go back)|Press[^\n]*(?:esc|escape)/iu.test(footer)) { + return { dismissed: false, reason: "No dismissible idle menu is visible." }; + } + } finally { + screen.dispose(); + } + // A prompt delivery may have started during the inspection: Esc between its paste and submit would break it. + if (this.sessions.get(id) !== session || busy() || session.inputQueue || typed()) { + return { dismissed: false, reason: "The card changed; nothing was written." }; + } + return this.inputChecked(id, "\x1b", "automation") ? { dismissed: true } : { dismissed: false, reason: "The terminal no longer accepts input." }; + } + lastPromptDelivery(id: string): PromptDeliveryReceipt | undefined { const receipt = this.sessions.get(id)?.promptDelivery; return receipt ? { ...receipt } : undefined; diff --git a/src/renderer/src/features/plugins/PluginSettingsSection.tsx b/src/renderer/src/features/plugins/PluginSettingsSection.tsx index df1a80f31..8c04c0d6b 100644 --- a/src/renderer/src/features/plugins/PluginSettingsSection.tsx +++ b/src/renderer/src/features/plugins/PluginSettingsSection.tsx @@ -1082,6 +1082,7 @@ function permissionKey(permission: PluginPermission): TranslationKey { "sessions:read-screen": "permissionSessionsReadScreen", "sessions:launch": "permissionSessionsLaunch", "sessions:control": "permissionSessionsControl", + "sessions:control-any": "permissionSessionsControlAny", "cards:decorate": "permissionCardsDecorate", "browser:engine": "permissionBrowserEngine", network: "permissionNetwork" diff --git a/src/renderer/src/lib/i18n.ts b/src/renderer/src/lib/i18n.ts index fb3b47fbd..0c3efa20f 100644 --- a/src/renderer/src/lib/i18n.ts +++ b/src/renderer/src/lib/i18n.ts @@ -421,6 +421,7 @@ const ru = { permissionSessionsReadScreen: "Читает конец вывода окон агентов (секреты скрыты) — это ваши личные данные", permissionSessionsLaunch: "Запускает окна агентов (видимые, без фокуса) через обычный запуск", permissionSessionsControl: "Пишет в запущенные им окна и закрывает их (только свои окна)", + permissionSessionsControlAny: "Даёт задания агентам Codex, Claude и Kimi в ваших окнах, а они выполняют команды с вашими правами. Это всё равно что дать плагину запускать любые команды на этом компьютере (закрывать окна не может)", permissionCardsDecorate: "Показывает короткие метки на окнах и добавляет свои действия в меню окна", permissionBrowserEngine: "Открывает фоновые вкладки агентов в своём браузерном движке: получает их адреса, без cookies и профиля", environmentKeepTitle: "Сохранить данные среды?", @@ -1494,6 +1495,7 @@ const en: Record = { permissionSessionsReadScreen: "Reads the end of agent cards' output (secrets masked) — this is your private data", permissionSessionsLaunch: "Starts agent cards (visible, never focused) through the normal launch", permissionSessionsControl: "Types into and closes the cards it started (only its own cards)", + permissionSessionsControlAny: "Gives tasks to Codex, Claude and Kimi agents in your cards, which run commands with your permissions. Treat it as letting the plugin run any command on this computer (it cannot close cards)", permissionCardsDecorate: "Shows short labels on cards and adds its own actions to a card's menu", permissionBrowserEngine: "Opens agents' background tabs in its own browser engine: receives their addresses, no cookies or profile", environmentKeepTitle: "Keep environment data?", diff --git a/src/shared/contracts.ts b/src/shared/contracts.ts index 6827fde93..56c7013f5 100644 --- a/src/shared/contracts.ts +++ b/src/shared/contracts.ts @@ -835,6 +835,7 @@ export type PluginPermission = | "sessions:read-screen" | "sessions:launch" | "sessions:control" + | "sessions:control-any" | "cards:decorate" | "browser:engine"; diff --git a/tests/plugin-services.test.mjs b/tests/plugin-services.test.mjs index 263b5e12e..73203c460 100644 --- a/tests/plugin-services.test.mjs +++ b/tests/plugin-services.test.mjs @@ -317,6 +317,28 @@ test("the host API is minimal: unknown methods and storage without permission ar assert.match(replies[1], /storage permission/); }); +test("limits.get gives a service the account-free limits snapshot only with limits:read", async (t) => { + const root = await mkdtemp(join(tmpdir(), "canvastty-service-limits-")); + const calls = []; + const snapshot = { state: "ready", snapshot: { fetchedAt: 1, providers: [] } }; + const { instance } = supervisor({ host: { + storageGet: async () => null, storageSet: async () => {}, emit: () => {}, + limits: async (pluginId) => { calls.push(pluginId); return snapshot; } + } }); + t.after(async () => { await instance.dispose(); await rm(root, { recursive: true, force: true }); }); + await instance.sync([ + await specFor(join(root, "a"), "com.example.a", "probe", PROBE, []), + await specFor(join(root, "b"), "com.example.b", "probe", PROBE, ["limits:read"]) + ]); + await instance.request("com.example.a", "probe", "host", { method: "limits.get", params: {} }); + await instance.request("com.example.b", "probe", "host", { method: "limits.get", params: {} }); + const reply = (pluginId) => instance.report(pluginId).log.find((entry) => entry.message.startsWith("host-reply"))?.message; + await waitFor(() => reply("com.example.a") && reply("com.example.b")); + assert.match(reply("com.example.a"), /limits:read permission/); + assert.deepEqual(JSON.parse(reply("com.example.b").slice("host-reply ".length)).result, snapshot); + assert.deepEqual(calls, ["com.example.b"]); +}); + test("message sizes are bounded in both directions", async (t) => { const root = await mkdtemp(join(tmpdir(), "canvastty-service-sizes-")); const { instance } = supervisor({ maxFrameBytes: 4_096 }); diff --git a/tests/plugin-tools-events-cards.test.mjs b/tests/plugin-tools-events-cards.test.mjs index aa95bca69..10c134706 100644 --- a/tests/plugin-tools-events-cards.test.mjs +++ b/tests/plugin-tools-events-cards.test.mjs @@ -301,6 +301,10 @@ test("session events carry card metadata, never screen text without sessions:rea terminals.applyProviderSignal?.(card.id, { kind: "lifecycle", state: "working" }); calls[0].exit(3); await flush(); + const asked = sessions.handle("p2", "svc", "sessions.screen", { sessionId: card.id }, ["sessions:read-screen"]); + assert.equal(asked.sessionId, card.id); + assert.match(asked.screen, /^compiling with \S+\n$/u); + assert.ok(!asked.screen.includes(SECRET), "on-demand screen text is redacted"); terminals.dispose(card.id); await flush(); const forPlugin = (pluginId) => notices.filter((notice) => notice.pluginId === pluginId).map((notice) => notice.params); @@ -316,6 +320,9 @@ test("session events carry card metadata, never screen text without sessions:rea assert.match(screened.screen, /^compiling with \S+\n$/u); assert.ok(!screened.screen.includes(SECRET), "screen text is redacted"); assert.ok(!screened.screen.includes("\u001b"), "screen text is plain"); + // The same tail on demand, only with the permission and for a card that exists. + assert.throws(() => sessions.handle("p1", "svc", "sessions.screen", { sessionId: card.id }, ["sessions:events"]), /sessions:read-screen/u); + assert.throws(() => sessions.handle("p2", "svc", "sessions.screen", { sessionId: "missing" }, ["sessions:read-screen"]), /No such session/u); // A stopped service subscribes again when it starts. sessions.serviceStopped("p1", "svc"); terminals.create({ provider: "terminal", cwd, profile: "normal", position: at }); @@ -372,6 +379,92 @@ test("plugins control only the sessions they created (create, send, stop), like assert.equal(sessions.handle("p1", "svc", "sessions.delete", {}, launch), undefined, "unknown methods fall through"); }); +test("sessions:control-any types into any agent card but never a plain terminal", async (t) => { + const { calls, terminals, sessions } = world(); + t.after(() => terminals.disposeAll()); + const agent = terminals.create({ provider: "claude", cwd, profile: "normal", position: at, title: "Person's agent" }); + const shell = terminals.create({ provider: "terminal", cwd, profile: "normal", position: at }); + const foreign = terminals.create({ provider: "codex", cwd, profile: "normal", position: at, title: "Another plugin's agent" }); + terminals.setPluginOwner(foreign.id, "p2"); + const orchestrator = terminals.create({ provider: "claude", cwd, profile: "normal", position: at, role: "orchestrator" }); + const subagent = terminals.create({ provider: "claude", cwd, profile: "normal", position: at, role: "subagent", parentSessionId: orchestrator.id }); + // No composer check for this provider: the person's draft there would be submitted with the plugin's text. + const unguarded = terminals.create({ provider: "qwen", cwd, profile: "normal", position: at, title: "Person's qwen" }); + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "idle" }); + await flush(); + const control = ["sessions:control"]; + const any = ["sessions:control", "sessions:control-any"]; + // Without the permission a person's card stays out of reach. + assert.throws(() => sessions.handle("p1", "svc", "sessions.send", { sessionId: agent.id, text: "continue" }, control), /No session this plugin started/u); + // control-any needs control itself, and never reaches plain terminals, other plugins' cards, an orchestrator's + // subagents, cards without a composer check, unknown ids or stop. + assert.throws(() => sessions.handle("p1", "svc", "sessions.send", { sessionId: agent.id, text: "x" }, ["sessions:control-any"]), /sessions:control/u); + terminals.inputChecked(unguarded.id, "half-typed"); + for (const id of [shell.id, foreign.id, subagent.id, unguarded.id, "missing"]) { + assert.throws(() => sessions.handle("p1", "svc", "sessions.send", { sessionId: id, text: "rm -rf ." }, any), /No session this plugin started/u); + assert.throws(() => sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: id }, any), /No session this plugin started/u); + } + assert.throws(() => sessions.handle("p1", "svc", "sessions.stop", { sessionId: agent.id }, any), /No session this plugin started/u); + calls[0].print("\x1b[2J\x1b[H❯ "); + const pending = sessions.handle("p1", "svc", "sessions.send", { sessionId: agent.id, text: "continue" }, any); + await waitFor(() => calls[0].writes.length > 0); + assert.deepEqual(calls[0].writes, ["\x1b[200~continue\x1b[201~"]); + calls[0].print("\x1b[2J\x1b[H❯ continue"); + await waitFor(() => calls[0].writes.length > 1); + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "working", event: "UserPromptSubmit" }); + assert.equal((await pending).sent, true); + assert.deepEqual(calls[1].writes, [], "the plain terminal got nothing"); + assert.deepEqual(calls[2].writes, [], "another plugin's card got nothing"); + assert.deepEqual(calls[4].writes, [], "the subagent got nothing"); + assert.deepEqual(calls[5].writes, ["half-typed"], "the person's qwen draft got nothing added"); +}); + +test("sessions.dismiss presses Esc only for an idle agent menu, like agent-control dismiss", async (t) => { + const { calls, terminals, sessions } = world(); + t.after(() => terminals.disposeAll()); + const agent = terminals.create({ provider: "claude", cwd, profile: "normal", position: at }); + const any = ["sessions:control", "sessions:control-any"]; + assert.throws(() => sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: agent.id }, ["sessions:control"]), /No session this plugin started/u); + // An empty composer is not a menu: nothing is written. + calls[0].print("\x1b[2J\x1b[H❯ "); + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "idle" }); + assert.equal((await sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: agent.id }, any)).dismissed, false); + // Claude's usage-limit options while a turn still runs: nothing is written either. + const menu = "\x1b[2J\x1b[HYou've hit your limit · resets 3am\r\n What do you want to do?\r\n ❯ 1. Upgrade your plan\r\n 2. Stop and wait for limit to reset\r\n Enter to confirm · Esc to cancel"; + calls[0].print(menu); + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "working" }); + assert.equal((await sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: agent.id }, any)).dismissed, false); + assert.deepEqual(calls[0].writes, []); + // The person typed during that turn: their draft is not a menu, so idle alone does not allow Esc. + terminals.inputChecked(agent.id, "draft"); + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "idle" }); + assert.match((await sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: agent.id }, any)).reason, /typed/u); + // A clean turn later, the menu is dismissed. + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "working" }); + terminals.applyProviderSignal(agent.id, { kind: "lifecycle", state: "idle" }); + assert.deepEqual(await sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: agent.id }, any), { sessionId: agent.id, dismissed: true }); + assert.deepEqual(calls[0].writes, ["draft", "\x1b"]); + // An Esc hint far above the last lines is earlier output, not a menu. + calls[0].print(`\x1b[2J\x1b[HPress Esc to cancel the build\r\n${Array.from({ length: 10 }, (_, line) => `output ${line}`).join("\r\n")}`); + assert.equal((await sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: agent.id }, any)).dismissed, false); + assert.deepEqual(calls[0].writes, ["draft", "\x1b"]); + // A prompt delivery that starts while the screen is inspected keeps its paste and submit together: no Esc between. + calls[0].print(menu); + const delivery = new AbortController(); + const dismissing = terminals.dismissIdleMenu(agent.id); + const prompt = terminals.deliverPrompt(agent.id, "continue", true, delivery.signal); + assert.match((await dismissing).reason, /changed/u); + delivery.abort(); + await prompt; + assert.ok(!calls[0].writes.slice(2).includes("\x1b"), "no Esc was written during the delivery"); + // A process in the plugin's own terminal has no composer check: its "Press Esc to interrupt" is not a menu. + const shell = terminals.create({ provider: "terminal", cwd, profile: "normal", position: at }); + terminals.setPluginOwner(shell.id, "p1"); + calls[1].print("\x1b[2J\x1b[Hbuilding\r\nPress Esc to interrupt"); + assert.match((await sessions.handle("p1", "svc", "sessions.dismiss", { sessionId: shell.id }, any)).reason, /not recognized/u); + assert.deepEqual(calls[1].writes, []); +}); + test("a plugin keeps control of the cards it started after a restore; the owner is saved on the record", async (t) => { const directory = await mkdtemp(join(tmpdir(), "canvastty-owner-")); t.after(() => rm(directory, { recursive: true, force: true }));