Files
apes-sidebar/src/tools.ts
T
Atlas Zeng 6c891514b5 feat(injection): 统一面板宿主注入重构——含块层+几何写路径+chunk缓存+锚点弱化+桌面/移动适配 (#232)
* feat(injection): 统一面板宿主——固定含块层 + 挂载自检降级 + body 锚点守卫

- Sidebar 渲染根包 [data-dsh-panel-host](fixed inset-0 pointer-events:none)
- 面板/开关簇由 fixed 改 absolute(层内视口坐标等价),免疫套壳中间层 transform 劫持
- 挂载后一次性几何自检:页面级 transform 时降级 absolute + rAF 视口同步
- MutationObserver(body childList)守卫锚点被宿主清空时重挂

* perf(injection): 几何写路径统一为 writeGeometry + 面板 layout 隔离

- 拖拽帧与打开态共用单一推挤写入器(--dsh-sidebar-width/height)
- .panel/.bottomPanel contain: layout style——内部重排不外泄
- 拖拽期(body[data-dsh-sidebar-dragging])才挂 will-change: transform

* perf(chunks): HMR 激活保留未变 chunk 的已解析 exports + ETag HEAD 重验证

- 新增 revalidateChunksOnReactivate():激活时 HEAD 每个已加载 chunk 对比 ETag,
  未变保留内存缓存(跳过重注入/重执行),变更或不可达则 fail-open 重取
- 测试夹具与孤儿缓存条目不跨激活存活
- index.tsx 激活路径由 resetChunks() 改为 revalidateChunksOnReactivate()

* fix(layout): 推挤锚点改 data 属性 + #root calc 宽度防桌面壳溢出

- nth-child(2) → #root [data-dsh-frame] > [data-pane="conversation"](实证同元素)
- #root 宽度 calc(100% - var) 与 margin 同步过渡:web 视觉不变(实测 1140+300=1440 无溢出),
  Desktop 壳(#208)width:100% 的加性溢出根因消除

* feat(desktop): 桌面信号自动探测 + win32 顶栏 overlay 自动避让 + 键盘/safe-area 适配

- 新增 desktop-env.ts:解析 dsh-desktop-mode/platform URL 信号与 preload 标记
- win32 advanced 壳自动启用 titleBarCompat(32px overlay),手动 pref 仍可覆盖
- visualViewport 键盘 inset:底部面板/窄屏抽屉键盘弹起时上移
- 面板与开关簇 safe-area-inset 适配(env() 桌面端为 0)
- 单测 7 例(含 URLSearchParams 前导 ? 剥除修复)

* docs+e2e: 注入方案实施记录(路线B关闭、偏差记录、基线数据)+ 契约同步 + e2e 新断言

- 设计文档:路线 B 标记关闭、§8.1 改单 PR 步骤(含 commit 对照)、拖拽基线数据、实施偏差记录
- AGENTS.md §8:data-dsh-panel-host 含块层、推挤锚点契约(禁 nth-child)、桌面信号
- mount.e2e:data-dsh-panel-host 断言 + win32 advanced 桌面信号场景

* fix(cr): 响应 #232 CR 三条 findings

- P1 降级同步:按未修正几何判定(跟踪自身补偿量),祖先 transform 消失才退出循环——
  修正后矩形不再被误判为无需修正(自清除缺陷)
- P1 chunk 重验证成为 loadChunk 屏障:重验证挂起期间不提供缓存,杜绝 HMR 竞态陈旧 exports;
  测试夹具加载不再被误记为生产加载
- P2 键盘 inset:innerHeight - (vv.height + vv.offsetTop),并监听 scroll(offsetTop 变化)
- 新增屏障单测 1 例;设计文档偏差记录更新

* fix(chunks): 屏障 HEAD 加超时兜底 + resetChunks 清 revalidation

- revalidateChunksOnReactivate 的 HEAD 与 recordEtag 均带
  AbortSignal.timeout(5s):路由挂起时 fail-open(drop + 重取),
  屏障不再可能无限期阻塞所有懒加载 chunk(CR #232 P1 修复的健壮性缺口)
- resetChunks 同步清 revalidation:重验证挂起期间重置后,
  loadChunk 不再等待已丢弃状态的孤儿任务(finally 身份判断 no-op)
- 单测 +2:HEAD 挂起超时 fail-open(fake AbortSignal.timeout 触发中止)、
  resetChunks 清屏障后 loadChunk 立即放行

* fix(deps): align @deepseek-ai/* peers with DSH 0.1.0-rc.8

- peer/devDependencies: 13 个 @deepseek-ai/* 从 ^0.1.0-rc.7 升至
  ^0.1.0-rc.8;删除随 rc.8 消失的 dsh-client-web-react / dsh-client-schema-form
  (无 rc.8 发布、rc.8 依赖树与壳 bundle 零引用、插件 src 零引用);
  cordis peer/devDep 同步升 ^4.0.0-rc.8
- 版本 0.13.1 -> 0.14.0(package.json / dsh.plugin.json /
  SIDEBAR_SERVICE_VERSION 三处同步)
- CHUNK_EXTERNALS / CLIENT_EXTERNALS / CLIENT_REQUIRE_ALLOWED 三处镜像
  同步删除两个死包(primitives/slots 仍是 rc.8 壳静态模块表种子,保留)
- CI 挂载冒烟钉版 @deepseek-ai/dsh@0.1.0-rc.7 -> rc.8
- pnpm clean --lockfile 全量重解析:lockfile 内 @deepseek-ai/* rc.7 残留
  清零(传递链同升 rc.8,杜绝 #206 式混用树);pnpm-workspace.yaml
  minimumReleaseAgeExclude 按 #207 模式整体换为 rc.8 列表
- 文档同步:README 安装说明、AGENTS.md CI 钉版、外部插件指南与设计文档
  cordis 示例、issue 模板版本示例

* feat(prefs): editorExplorer 默认独立(关)——文件各自新开 tab

- SIDEBAR_PREFS_DEFAULTS 与 host PrefsSchema 的 editorExplorer 默认
  true -> false:新会话树点击/打开文件按 path 新开 tab,无路径窗口即
  纯资源管理器;合并模式保留为可选手动开启(持久化过的用户设置不受影响)
- 测试同步:prefs.spec 默认断言翻转、plugin-shape.spec 与 smoke.spec
  默认对象翻转;editor-host 合并模式用例显式开启 editorExplorer(split
  用例本已显式);side-card-section-rows 的 select 行用例固定选中 Merged
- e2e 重写:mount.e2e 文件打开流程从 in-place 断言改为独立模式
  (新开 hello.txt tab、Files home tab 保留),文件头注释同步
- 契约文档同步:AGENTS.md §3.4 editor 行默认描述翻转 + CI 冒烟描述、
  README/README_EN v0.13.0 特性描述 + v0.14.0 changelog

* fix(client): rc.8 模块系统经 ctx.modules 注入 + chunk 副本全局共享

rc.8 不再暴露 window.__DSH_MODULES__ 页面全局(改由 ctx.modules 服务
提供),chunk 外部依赖解析全面失效(terminal/editor/mermaid 全部
"client module system unavailable")。修复:

- src/client/index.tsx: inject 增加 'modules'(Cordis 服务访问守卫,
  此前直接读 ctx.modules 抛 "cannot get property modules without
  inject");apply() 激活时 setChunkModuleSystem(ctx.modules)
- package.json dsh.client.inject 增加 @deepseek-ai/dsh-client-modules
- chunk-loader: 注入写插件自有页面全局 __dshSidebarModuleSystem__——
  懒加载 chunk bundle 各自内联一份 loader(rc.7 靠官方全局回退工作,
  rc.8 全局消失后副本注入变量恒空);moduleSystem() 按
  注入变量 → 插件全局 → rc.7 全局回退解析
- context-types: Context 镜像补 modules 服务声明(client half)
- e2e: assertNoCrash 失败时输出错误条文本;独立模式断言修正
  (Files 数量按存在性、mermaid 流程先切回 Files、md 预览 locator 去掉
  重复的 [data-dsh-better-sidebar] 嵌套)

验证:typecheck / 639 测试全绿;本地 rc.8 CLI + Chromium 挂载冒烟 3/3
通过(drag-layout、mount 深扫含 editor/mermaid chunk、桌面信号)

* feat(settings): 终端 shell/shellArgs 可在设置页配置(bash 管理)

- SidebarPrefs 新增 terminalShell / terminalShellArgs(默认空 = 保持
  yaml config.shell → $SHELL / 登录 shell / powershell.exe 的既有解析)
- 终端卡齿轮二级页面新增两行 text 配置(与字体行同列)
- host 侧生效链路:UI 终端 WS 打开与 agent terminal_create 均读取
  设置文档覆盖(ptyManager.open / AgentPtyRegistry.create 增加可选
  shell 覆盖参数;shellOverridesOf 解析设置文档);设置页写入即时
  影响之后打开的终端(既有 pty 保持原 shell)
- locales zh/en 文案;parsePrefs 校验新字段;测试同步

* feat(settings): 侧边卡片设置页加 DSH-better-sidebar 版本徽标

- 设置页 intro 下新增身份徽标:名称 + v{service.version}(服务实例
  版本,与 package.json 由 tests/service.spec.ts 保持同步)
- token 驱动样式(--dsw-alias-*),名称/版本 pill 布局

* fix(drag): 快速拖动提交最后位置 + HMR 后中心列重定位兜底

快速释放(浏览器合并/丢失 pointermove 突发,超快速 flick 甚至可能
完全无 move)时的回退问题:
- pointerup 优先采用最后一次已知拖动值(rAF pending),而非 up 位置
  (事件合并时可能等于按下位置)
- pointercancel / lostpointercapture 中断时同样提交最后已知位置;
  无 move 时用中断事件自身的坐标计算(clamp 后提交)——只有真正
  未产生位移的拖动才回滚
- commitDrag 统一 flush + 同值提交 + 立即重测中心列(消除提交后
  React 用旧 centerRect 覆盖底栏 right 的中间帧)

HMR 重激活后底栏空白(输入框被推挤上移、强制刷新恢复):
- 根因:新组件实例重跑 locate 时壳的 centerCol 尚未就绪,而壳重建
  复用 #root 子节点(childList 观察器不触发)→ centerRect 卡 {0,0}
  → 底栏 visibility:hidden 永久空白
- 修复:额外观察 <html> 的 style 属性(layout push 写回 --dsh-sidebar-*
  时重定位重测);底栏打开时 effect 重跑 locate/measure 兜底
- 底栏未测量时由「不渲染」改为 visibility:hidden(渲染链不被几何
  门控,jsdom 测试不回归)

e2e 新增:极快拖动(单 move 立即 up)提交拖动位置、稳定后不回退

* feat(plugins): 添加插件目录支持搜索/分组/独立滚动(多插件场景)

- PluginListBody 顶部加实时搜索框(按名称/id/描述过滤,空结果提示)
- PluginEntry 增加可选 category 分组字段(i18n 友好),目录条目按组
  渲染(未分类条目保持平铺);数量徽标跟随过滤结果
- 条目列表 max-height + overflow-y 独立滚动,插件多时弹窗不再无限
  增长;渲染数量由搜索天然收敛
- locales zh/en(搜索占位、无匹配);测试文件固定英文环境
  (vitest 4.1.11+ jsdom 跟随系统 locale,本机 zh-CN 导致英文文案
  断言漂移)

* chore(deps): 适配 pnpm 11.8 supply-chain 校验(exclude 通配)

pnpm 11.8.0 起对 lockfile 既有条目强制 minimumReleaseAge 校验,
且精确 exclude(@scope/pkg@version)对带 peer 依赖后缀的解析条目
匹配失效(44 条误报违规,CI 全红)。@deepseek-ai/* scope 为官方
可信 scope,minimumReleaseAgeExclude 改为 '@deepseek-ai/*' 通配
(保留 rc.1 历史与 stable 条目);通配经实测通过全部 504 条校验。

* docs: v0.14.0 changelog 补全(自 v0.13.1 全部更改 + 特别声明 rc.8 适配)

新增条目:终端 shell/shellArgs 设置页配置、设置页版本徽标、
添加插件目录搜索/分组/滚动、rc.8 模块系统迁移、拖拽健壮性修复;
版本说明块醒目声明本版适配 DSH 0.1.0-rc.8(rc.7 及更早无法解析依赖)
2026-08-20 02:09:36 +08:00

480 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Eight model-facing tools for the agent-owned sidebar terminals (tmux
* semantics: spawn-and-detach, send-keys, read, wait-for, resize, signal,
* close, list). Each tool binds to the calling agent's session through
* `exec.agent.session.id`, so the model never passes a sessionId — the
* agent identity is the scope.
*
* Conventions (per plugin-development-guide.md §3):
* C1 — parameters schema-validated before `execute` runs.
* C4 — `execute` returns one canonical JSON value; `render` is a separate
* pure text projection.
* C6 — `exec.signal.throwIfAborted()` before any spawn.
* C10 — no UI/transport vocabulary in the canonical value.
*/
import { defineTool } from '@deepseek-ai/dsh-tools'
import type { ToolRunContext } from '@deepseek-ai/dsh-tools'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { Context } from './context-types.ts'
import {
AgentPtyRegistry,
ALLOWED_SIGNALS,
type AgentTerminalSignal,
type AgentTerminalSnapshot,
} from './agent-pty.ts'
/** Maximum UTF-8 bytes of one `terminal_read` result text. */
const READ_BYTE_LIMIT = 256 * 1024
/**
* Bound a string to a byte limit, marking truncation. Truncation never
* splits a multi-byte UTF-8 sequence: when the byte cap lands inside one,
* the walk-back retreats to the sequence's leading byte so the retained
* prefix decodes cleanly (a split would decode to U+FFFD).
* @internal exported for the unit tests, like {@link snapshotOf}.
*/
export function boundBytes(text: string, maxBytes: number): { text: string; truncated: boolean } {
const buf = Buffer.from(text, 'utf8')
if (buf.byteLength <= maxBytes) return { text, truncated: false }
// The byte at `end` is a continuation byte (10xxxxxx) exactly when the
// character that started before `end` spills past the cap. Stop at the
// first non-continuation byte — the retained prefix is then intact.
let end = maxBytes
while (end > 0 && ((buf[end] ?? 0) & 0xc0) === 0x80) end -= 1
return { text: buf.subarray(0, end).toString('utf8'), truncated: true }
}
/** Pure text projection helper (the canonical value is already structured). */
function textRender<T>(fn: (value: T) => string): (_args: unknown, value: unknown) => ContentBlock[] {
return (_args, value) => [{ type: 'text', text: fn(value as T) }]
}
/** Extract the calling agent or throw the canonical "no agent" error. */
function requireAgent(agent: Agent | undefined): Agent {
if (agent === undefined) {
throw new Error('sidebar terminal tools require an initiating agent')
}
return agent
}
/** Resolve the calling agent's session id (the registry scope + ownership key). */
function sessionIdOf(exec: ToolRunContext): string {
return requireAgent(exec.agent).session.id
}
/**
* Register the eight terminal tools against the host tool registry. The
* `resolveCwd` callback threads the live session cwd (authoritative from the
* session store, falling back to the process cwd) so a freshly-created
* terminal lands in the right directory without the model passing it.
* Every uuid-keyed tool first asserts the terminal belongs to the calling
* session (`registry.assertOwned`), so one agent can never reach another
* session's terminals.
* @param ctx - host plugin context (carries the tools service).
* @param registry - the agent-owned terminal registry.
* @param resolveCwd - live cwd resolver for one session id.
* @returns a disposer that unregisters all eight tools (the caller gates
* registration on the side-card setting and calls this to turn them off).
*/
export function registerTools(
ctx: Context,
registry: AgentPtyRegistry,
resolveCwd: (sessionId: string) => string,
readShellOverrides: () => { shell?: string; shellArgs?: string[] },
): () => void {
const disposers: Array<() => void> = []
const register = (tool: ReturnType<typeof defineTool>): void => {
disposers.push(ctx.tools.register(tool))
}
register(defineTool({
name: 'terminal_create',
description:
'Open a persistent terminal in the sidebar and run a command in it. '
+ 'Spawns an interactive shell, writes the command + Enter to its stdin, and returns a uuid handle. '
+ 'The terminal stays alive after the command exits — send more input with terminal_send (set submit=true to run a command), '
+ 'read output with terminal_read, send Ctrl+C with terminal_signal(signal="SIGINT"), '
+ 'and close it with terminal_close when done. '
+ 'Use this for interactive shells, REPLs, long-running dev servers, '
+ 'or any work that needs persistent terminal state across tool calls. '
+ 'The terminal appears as a new tab in the right sidebar (titled with the `title` you provide) so the user can watch and interact with it.',
parameters: {
title: {
type: 'string',
required: true,
description: 'Short human-readable label for the terminal tab (e.g. "dev server", "python repl").',
},
command: {
type: 'string',
required: true,
description: 'Shell command to run in the freshly spawned shell. The host appends an Enter key automatically — do NOT include a trailing newline. Pass "" to open a bare shell with no command.',
},
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
uuid: { type: 'string', required: true, description: 'Opaque handle for the new terminal. Pass to terminal_send / terminal_read / terminal_resize / terminal_signal / terminal_close.' },
title: { type: 'string', required: true, description: 'The title you provided (echoed for confirmation).' },
},
},
render: textRender((v: { uuid: string; title: string }) =>
`Opened terminal "${v.title}" (uuid: ${v.uuid}). The sidebar tab appears automatically; use terminal_read to see output and terminal_send (with submit=true) to run more commands.`,
),
},
execute: (args: { title: string; command: string }, exec) => {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
const cwd = resolveCwd(sessionId)
const { shell, shellArgs } = readShellOverrides()
const uuid = registry.create(sessionId, args.title, args.command, cwd, 80, 24, shell, shellArgs)
return Promise.resolve({ uuid, title: args.title })
},
}))
register(defineTool({
name: 'terminal_list',
description:
'List every terminal the current agent has opened in this session. Returns each terminal\'s uuid, title, '
+ 'the command it was started with, and whether the top-level process has exited (with exit code/signal if so). '
+ 'Use this to recover state after a long sequence of tool calls or to find a terminal you forgot to close.',
parameters: {},
output: {
schema: {
type: 'array',
items: {
type: 'object',
additionalProperties: false,
properties: {
uuid: { type: 'string', required: true },
title: { type: 'string', required: true },
command: { type: 'string', required: true },
exited: { type: 'boolean', required: true },
exitCode: { oneOf: [{ type: 'integer' }, { type: 'null' }] },
exitSignal: { oneOf: [{ type: 'string' }, { type: 'null' }] },
},
},
},
render: (_args, value) => {
const list = value as AgentTerminalSnapshot[]
if (list.length === 0) return [{ type: 'text', text: 'No agent terminals open in this session.' }]
const lines = list.map((t) => {
const status = t.exited
? `exited (code ${t.exitCode ?? '?'}, signal ${t.exitSignal ?? 'none'})`
: 'running'
return ` ${t.uuid} "${t.title}" [${status}] $ ${t.command}`
})
return [{ type: 'text', text: `Agent terminals in this session:\n${lines.join('\n')}` }]
},
},
execute: (_args, exec) => {
const sessionId = sessionIdOf(exec)
return Promise.resolve(registry.list(sessionId))
},
}))
register(defineTool({
name: 'terminal_send',
description:
'Send raw text (keystrokes) to a terminal opened with terminal_create — tmux send-keys semantics. '
+ 'The text is written verbatim to the pty stdin. '
+ 'To submit a command, set submit=true (appends an Enter key); do NOT put "\\n" or "\\r" in the text yourself. '
+ 'To send Ctrl+C (interrupt the running command), use the terminal_signal tool with signal="SIGINT" — do NOT try to send the control character "\\u0003" as text. '
+ 'Use terminal_signal with signal="SIGTSTP" for Ctrl+Z (suspend) as well. '
+ 'This tool does NOT wait for the command to finish or for output to settle — pair with terminal_read to observe the result. '
+ 'Throws if the terminal has exited.',
parameters: {
uuid: {
type: 'string',
required: true,
description: 'Terminal uuid from terminal_create or terminal_list.',
},
text: {
type: 'string',
required: true,
description: 'UTF-8 text to write to the terminal stdin (verbatim, no shell escaping). Do not include trailing newlines — use the submit flag instead.',
},
submit: {
type: 'boolean',
description: 'Append an Enter key (carriage return) after the text to submit a command. Default: false. Set to true when sending a command to run; leave false for partial input or control sequences.',
},
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
uuid: { type: 'string', required: true },
bytes: { type: 'integer', required: true, description: 'Number of UTF-8 bytes written (including the Enter key if submit was true).' },
},
},
render: textRender((v: { uuid: string; bytes: number }) =>
`Sent ${v.bytes} byte(s) to terminal ${v.uuid}.`,
),
},
execute: (args: { uuid: string; text: string; submit?: boolean }, exec) => {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
registry.assertOwned(args.uuid, sessionId)
const payload = args.submit === true ? `${args.text}\r` : args.text
registry.send(args.uuid, payload)
return Promise.resolve({ uuid: args.uuid, bytes: Buffer.byteLength(payload, 'utf8') })
},
}))
register(defineTool({
name: 'terminal_read',
description:
'Read a bounded page of retained output from an agent terminal without sending input. '
+ 'The host keeps up to ~1 MiB of scrollback; this tool returns up to 500 lines per call. '
+ 'Use `offset` to paginate forward ( 0-based from the start of the retained transcript ) or backward ( negative reads from the end, e.g. -50 reads the last 50 lines ). '
+ 'Returns `totalLines` so you know how much scrollback remains. '
+ 'Output is bounded to 256 KiB per call; longer pages are truncated with the `truncated` flag.',
parameters: {
uuid: {
type: 'string',
required: true,
description: 'Terminal uuid from terminal_create or terminal_list.',
},
offset: {
type: 'number',
description: '0-based line offset from the start of the retained transcript (default 0). Negative reads from the end (e.g. -50 = last 50 lines).',
},
count: {
type: 'number',
description: 'Maximum lines to return (default 500, hard cap 500).',
},
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
text: { type: 'string', required: true, description: 'The slice of transcript for the requested page.' },
totalLines: { type: 'integer', required: true, description: 'Total lines in the retained transcript.' },
lineBegin: { type: 'integer', required: true, description: '0-based index of the first line in `text` (inclusive).' },
lineEnd: { type: 'integer', required: true, description: '0-based index of the last line in `text` (exclusive).' },
truncated: { type: 'boolean', required: true, description: 'Whether `text` was truncated to fit the 256 KiB read cap.' },
},
},
render: (_args, value) => {
const v = value as { text: string; totalLines: number; lineBegin: number; lineEnd: number; truncated: boolean }
const head = `[lines ${v.lineBegin}..${v.lineEnd} of ${v.totalLines}${v.truncated ? '; truncated to 256KiB' : ''}]`
return [{ type: 'text', text: `${head}\n${v.text}` }]
},
},
execute: (args: { uuid: string; offset?: number; count?: number }, exec) => {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
registry.assertOwned(args.uuid, sessionId)
const result = registry.read(args.uuid, args.offset, args.count)
const bounded = boundBytes(result.text, READ_BYTE_LIMIT)
return Promise.resolve({
text: bounded.text,
totalLines: result.totalLines,
lineBegin: result.lineBegin,
lineEnd: result.lineEnd,
truncated: bounded.truncated,
})
},
}))
register(defineTool({
name: 'terminal_wait_for',
description:
'Block until a substring appears in a terminal\'s retained transcript, or until the timeout elapses, or until the terminal exits — whichever happens first. '
+ 'Use this to synchronize on command completion cues ( e.g. a shell prompt, "done", "Listening on", "Build successful" ) '
+ 'without busy-polling terminal_read. '
+ 'The wait scans the FULL retained transcript (up to ~1 MiB) on every poll, so a needle that scrolled past the most recent chunk is still a match. '
+ 'Returns `found` with the line/column of the first occurrence, `timeout` if the needle did not appear in time, or `exited` if the terminal process died before the needle appeared. '
+ 'Default timeout is 10 seconds; raise it for long-running commands ( dev servers, test suites ). '
+ 'The wait is cooperative: a tool-call cancel ( or agent turn end ) aborts it immediately.',
parameters: {
uuid: {
type: 'string',
required: true,
description: 'Terminal uuid from terminal_create or terminal_list.',
},
needle: {
type: 'string',
required: true,
description: 'Substring to wait for (case-sensitive, verbatim). Must be non-empty.',
},
timeout_ms: {
type: 'number',
description: 'Maximum wait in milliseconds (default 10000, i.e. 10s). Clamped to a minimum of 100ms.',
},
},
output: {
schema: {
oneOf: [
{
type: 'object',
additionalProperties: false,
properties: {
kind: { type: 'string', required: true, const: 'found' },
needle: { type: 'string', required: true },
line: { type: 'integer', required: true, description: '0-based line index in the retained transcript where the needle first appeared.' },
column: { type: 'integer', required: true, description: '0-based column index within that line where the match starts.' },
elapsedMs: { type: 'integer', required: true, description: 'Wall-clock milliseconds from wait start to match.' },
},
},
{
type: 'object',
additionalProperties: false,
properties: {
kind: { type: 'string', required: true, const: 'timeout' },
needle: { type: 'string', required: true },
timeoutMs: { type: 'integer', required: true, description: 'The configured timeout that elapsed.' },
totalLines: { type: 'integer', required: true, description: 'Total lines retained when the timeout fired. Call terminal_read to inspect the tail.' },
},
},
{
type: 'object',
additionalProperties: false,
properties: {
kind: { type: 'string', required: true, const: 'exited' },
needle: { type: 'string', required: true },
exitCode: { oneOf: [{ type: 'integer' }, { type: 'null' }], description: 'Exit code, if known.' },
exitSignal: { oneOf: [{ type: 'string' }, { type: 'null' }], description: 'Exit signal name, if killed by a signal.' },
},
},
],
},
render: (_args, value) => {
const v = value as { kind: 'found' | 'timeout' | 'exited'; needle: string; elapsedMs?: number; timeoutMs?: number; line?: number; column?: number; exitCode?: number | null; exitSignal?: string | null }
if (v.kind === 'found') {
return [{ type: 'text', text: `Found "${v.needle}" at line ${v.line}, column ${v.column} (after ${v.elapsedMs}ms).` }]
}
if (v.kind === 'timeout') {
return [{ type: 'text', text: `Timed out after ${v.timeoutMs}ms waiting for "${v.needle}". Call terminal_read to inspect the transcript.` }]
}
const exitInfo = v.exitCode !== undefined && v.exitCode !== null ? ` (exit code ${v.exitCode})` : ''
return [{ type: 'text', text: `Terminal exited before "${v.needle}" appeared${exitInfo}.` }]
},
},
async execute(args: { uuid: string; needle: string; timeout_ms?: number }, exec) {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
registry.assertOwned(args.uuid, sessionId)
// The registry validates the needle (empty → bad-request) and returns
// the camelCase result the schema above declares directly — no
// field-by-field projection.
const timeoutMs = args.timeout_ms ?? 10_000
return await registry.waitFor(args.uuid, args.needle, timeoutMs, exec.signal)
},
}))
register(defineTool({
name: 'terminal_resize',
description:
'Resize an agent terminal\'s pty ( cols × rows ). The host clamps both to a 2..1024 sane range. '
+ 'Most shells redraw their prompt and any full-screen TUI on the next output frame. '
+ 'No-op if the terminal has exited. Returns the dimensions actually applied.',
parameters: {
uuid: { type: 'string', required: true, description: 'Terminal uuid from terminal_create or terminal_list.' },
cols: { type: 'integer', required: true, description: 'New column count ( clamped to 2..1024 ).' },
rows: { type: 'integer', required: true, description: 'New row count ( clamped to 2..1024 ).' },
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
uuid: { type: 'string', required: true },
cols: { type: 'integer', required: true },
rows: { type: 'integer', required: true },
},
},
render: textRender((v: { uuid: string; cols: number; rows: number }) =>
`Resized terminal ${v.uuid} to ${v.cols}×${v.rows}.`,
),
},
execute: (args: { uuid: string; cols: number; rows: number }, exec) => {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
registry.assertOwned(args.uuid, sessionId)
const dims = registry.resize(args.uuid, args.cols, args.rows)
return Promise.resolve({ uuid: args.uuid, ...dims })
},
}))
register(defineTool({
name: 'terminal_signal',
description:
'Send a POSIX signal to an agent terminal\'s foreground process — this is how you send Ctrl+C, Ctrl+Z, etc. '
+ 'Use signal="SIGINT" for Ctrl+C (interrupt the running command), signal="SIGTERM" to request termination, '
+ 'signal="SIGKILL" to force-kill the pty, signal="SIGHUP" to hang up (many shells exit), signal="SIGTSTP" for Ctrl+Z (suspend). '
+ 'Do NOT try to send control characters (like "\\u0003") through terminal_send — use this tool instead. '
+ 'On Windows, only SIGKILL and SIGTERM are effective — others are accepted but may no-op. '
+ 'No-op if the terminal has already exited. Use terminal_close to dispose of the terminal entirely.',
parameters: {
uuid: { type: 'string', required: true, description: 'Terminal uuid from terminal_create or terminal_list.' },
signal: {
type: 'string',
required: true,
enum: ALLOWED_SIGNALS as readonly string[],
description: 'Signal to deliver: SIGINT (Ctrl+C) | SIGTERM | SIGKILL | SIGHUP | SIGTSTP (Ctrl+Z).',
},
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
uuid: { type: 'string', required: true },
signal: { type: 'string', required: true },
},
},
render: textRender((v: { uuid: string; signal: AgentTerminalSignal }) =>
`Sent ${v.signal} to terminal ${v.uuid}.`,
),
},
execute: (args: { uuid: string; signal: AgentTerminalSignal }, exec) => {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
registry.assertOwned(args.uuid, sessionId)
registry.signal(args.uuid, args.signal)
return Promise.resolve({ uuid: args.uuid, signal: args.signal })
},
}))
register(defineTool({
name: 'terminal_close',
description:
'Close an agent terminal and release its process. The uuid becomes invalid for all subsequent tool calls. '
+ 'Idempotent: closing an already-closed uuid is a no-op. '
+ 'The corresponding sidebar tab is removed automatically when the host pushes the updated terminal list. '
+ 'Always close terminals you no longer need — the host keeps the pty alive until you do.',
parameters: {
uuid: { type: 'string', required: true, description: 'Terminal uuid from terminal_create or terminal_list.' },
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
uuid: { type: 'string', required: true },
closed: { type: 'boolean', required: true, description: 'Whether a live terminal was actually dropped (false if the uuid was already gone).' },
},
},
render: textRender((v: { uuid: string; closed: boolean }) =>
v.closed ? `Closed terminal ${v.uuid}.` : `Terminal ${v.uuid} was already closed.`,
),
},
execute: (args: { uuid: string }, exec) => {
exec.signal.throwIfAborted()
const sessionId = sessionIdOf(exec)
registry.assertOwned(args.uuid, sessionId)
const closed = registry.close(args.uuid)
return Promise.resolve({ uuid: args.uuid, closed })
},
}))
return () => {
for (const dispose of disposers) dispose()
}
}