diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index 81912accfe..6f42792274 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -15,5 +15,5 @@ en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: c4b12ca80865e670 - zh: 396426fad0105eaa + en: c6def9831c503e1f + zh: c4c2ac5cca9f0e07 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 6d9aea0408..f359842afd 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, during execution. macOS releases that run’s remaining keys when the program ends or the user pauses it. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Each Agent owns an input connection, and the helper tracks holds by that connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS and Windows both implement this lifecycle. Custom helpers must support the matching connection-scoped query and release operations. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index ceed375ff3..e41400e492 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。每个 Agent 使用独立的输入连接,helper 按连接记录持有输入。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 和 Windows 都实现了这套生命周期。自定义 helper 必须支持按连接查询和释放持有输入。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 1ef6862c46..6d7d84b795 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -277,6 +277,14 @@ jobs: } else { pnpm install --frozen-lockfile } + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Build and test the Windows CUA helper + shell: pwsh + run: | + dotnet build packages/experimental/cua-windows/native/cua-windows.slnx --configuration Release -p:RestoreLockedMode=true + dotnet run --project packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj --configuration Release --no-build - name: Run Windows-specific native tests shell: pwsh run: >- @@ -284,6 +292,7 @@ jobs: --no-file-parallelism --testTimeout 90000 packages/shell/tool-pwsh/tests/loader.spec.ts + packages/experimental/cua-windows/tests/loader-composition.spec.ts packages/workflow/workflow-ptc/tests/workflow-ptc.spec.ts packages/experimental/tool-ralph/tests/integration.spec.ts packages/subprocess/subprocess-local/tests/process-exit.spec.ts diff --git a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts index c1b88715c3..69c451d5a8 100644 --- a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts +++ b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts @@ -91,6 +91,22 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { expect(second.content).toHaveLength(1) expect(JSON.parse(textOf(second.content[0]))).toEqual({ visits: 2, sameWindow: true, pid: state.pid }) + const held = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'await app.sendKeyEvent("shift", "down"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("w", "down"); inspect("Input sequence finished.")', + description: 'Hold mixed input across MCP programs', + } }) as CallResult + expect(held.isError).toBeUndefined() + await expect(`${JSON.stringify(held, null, 2)}\n`).toMatchFileSnapshot('./expected/held-inputs.json') + const up = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'await app.sendKeyEvent("w", "up"); await win.toggleMouse("left", "up"); await app.sendKeyEvent("shift", "up")', description: 'Release the held input', + } }) as CallResult + expect(up.isError).toBeUndefined() + expect(up.content.some(block => block.type === 'text' && block.text.includes(''))).toBe(false) + const afterRelease = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'inspect("After release")', description: 'Continue without held input', + } }) as CallResult + expect(afterRelease.content).toEqual([{ type: 'text', text: 'After release\n' }]) + const reset = await probe.request('tools/call', { name: 'cua_reset', arguments: {} }) as CallResult expect(reset.isError).toBeUndefined() expect(textOf(reset.content[0])).toContain('Program environment cleared') diff --git a/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json b/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json new file mode 100644 index 0000000000..03817767b3 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json @@ -0,0 +1,12 @@ +{ + "content": [ + { + "type": "text", + "text": "Input sequence finished.\n" + }, + { + "type": "text", + "text": "\nCUA inputs are still held:\n- Key \"shift\", appHandle \"fixture-app\" (application input).\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n" + } + ] +} diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index a6f105de6e..069c1460c4 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -39,7 +39,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -53,6 +53,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/apps/web/tests/cua-run-code.e2e.ts b/apps/web/tests/cua-run-code.e2e.ts index 272f418272..2a49c519e9 100644 --- a/apps/web/tests/cua-run-code.e2e.ts +++ b/apps/web/tests/cua-run-code.e2e.ts @@ -60,7 +60,7 @@ it.skipIf(mode === 'record')('shows standard CUA programs and their recorded sou const results = events.filter(event => event.type === 'tool/result') expect(results).toHaveLength(2) expect(results.every(event => !event.data.message.isError)).toBe(true) - expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(8) + expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(12) const calls = page.locator('[data-tool="cua_run_code"]') const description = 'Select and capture the fixture window' const turnControl = page.locator('[data-turn-process="1"]') @@ -78,7 +78,7 @@ it.skipIf(mode === 'record')('shows standard CUA programs and their recorded sou const source = calls.first().locator('pre.shiki') await source.waitFor() expect(await source.textContent()).toContain('var app = await cua.getApp("test.fixture")') - expect(await page.locator('[data-subcalls] [data-tool="cua"]').count()).toBe(8) + expect(await page.locator('[data-subcalls] [data-tool="cua"]').count()).toBe(12) expect(events.filter(event => event.type === 'tool/ptc-dispatch' && event.data.content.some(block => block.type === 'image'))).toHaveLength(1) expect(events.filter(event => event.type === 'tool/result' && event.data.message.content.some(block => block.type === 'image'))).toHaveLength(1) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 635dbc7d32..743fa41757 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -982,7 +982,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:36`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:35`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 547f7953e2..1df664ee5d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -984,7 +984,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:36`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:35`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 5a44907ae7..56e555a4c2 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -15,11 +15,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`mcp-client`](../packages/mcp/mcp-client), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua-macos`](../packages/experimental/cua-macos), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`cua-macos`](../packages/experimental/cua-macos), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | @@ -86,11 +86,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:47`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `timeline/priority` | `emit` | [`packages/experimental/timeline/src/storage.ts:56`](../packages/experimental/timeline/src/storage.ts) | [`timeline`](../packages/experimental/timeline) (`emit`) | [`timeline`](../packages/experimental/timeline) | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`timeline`](../packages/experimental/timeline) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua-macos`](../packages/experimental/cua-macos), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua`](../packages/experimental/cua), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | +| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`cua`](../packages/experimental/cua), `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | | `webserver/authorize` | `bail` | [`packages/host/webserver/src/index.ts:60`](../packages/host/webserver/src/index.ts) | `remote-connection` (`bail`), `webserver` (`bail`) | `connection` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index c5023b5a19..e588a55e62 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -17,11 +17,11 @@ | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`mcp-client`](../packages/mcp/mcp-client), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua-macos`](../packages/experimental/cua-macos), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`cua-macos`](../packages/experimental/cua-macos), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | @@ -88,11 +88,11 @@ | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:47`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `timeline/priority` | `emit` | [`packages/experimental/timeline/src/storage.ts:56`](../packages/experimental/timeline/src/storage.ts) | [`timeline`](../packages/experimental/timeline) (`emit`) | [`timeline`](../packages/experimental/timeline) | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`timeline`](../packages/experimental/timeline) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua-macos`](../packages/experimental/cua-macos), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua`](../packages/experimental/cua), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | +| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`cua`](../packages/experimental/cua), `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | | `webserver/authorize` | `bail` | [`packages/host/webserver/src/index.ts:60`](../packages/host/webserver/src/index.ts) | `remote-connection` (`bail`), `webserver` (`bail`) | `connection` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 7c1fcb7cb9..2fcd2866d7 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1173,6 +1173,7 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_agent pkg_cua --> pkg_attachment pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node @@ -1977,7 +1978,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`deepseek-chat-import`](../packages/experimental/deepseek-chat-import) | `experimental` | [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`tool-web`](../packages/web/tool-web) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index f600f9b63e..093c715d55 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1175,6 +1175,7 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_agent pkg_cua --> pkg_attachment pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node @@ -1979,7 +1980,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`deepseek-chat-import`](../packages/experimental/deepseek-chat-import) | `experimental` | [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`tool-web`](../packages/web/tool-web) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 6e8a366336..585e52c377 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 1387c4505dde2faf zh: 48570fa1c13d6910 /session-persistence-event-catalog/persistence-type-fingerprints: - en: 0e8a5cac08282eb3 - zh: 050d23cee1ce8d42 + en: 5bb7a5d2e525b76b + zh: 62aeb34aea1d5094 /session-persistence-event-catalog/event-envelope: en: ad543efedf4f0719 zh: efbd331937078535 @@ -450,8 +450,14 @@ en: 361b41088e68982e zh: 361b41088e68982e /session-persistence-event-catalog/resolved-persistence-types/cua-activity: - en: 9696ddd60bb757ee - zh: 9696ddd60bb757ee + en: 2866f653d9cdc446 + zh: 2866f653d9cdc446 +/session-persistence-event-catalog/resolved-persistence-types/cua-held-inputs: + en: 32bea85c24c54dc6 + zh: 32bea85c24c54dc6 +/session-persistence-event-catalog/resolved-persistence-types/cua-inputs-released: + en: 41141c29ec14954f + zh: 41141c29ec14954f /session-persistence-event-catalog/resolved-persistence-types/danger-full-access: en: f7c17b7b2874f5f4 zh: f7c17b7b2874f5f4 @@ -1044,11 +1050,11 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: a3b95fd203c1f49a - zh: 6ba49f77a2f43d2c + en: 97d292b5102d99f4 + zh: 2c18baa2a597508c /session-persistence-event-catalog/resolved-persistence-types/developermessage: - en: 234609a0e5496290 - zh: 29ebde00af4030ff + en: dc0e772287dd49b9 + zh: 57e1927844b891c1 /session-persistence-event-catalog/resolved-persistence-types/epochheader: en: 5b2edbecb9e5dad5 zh: bce84092937602fb @@ -1158,11 +1164,11 @@ en: 6dbe099c62f7c226 zh: 6fd788f63c038c91 /session-persistence-event-catalog/resolved-persistence-types/llmretrystartedeventdata: - en: 1b00decc27a33303 - zh: 9756cfd1e0a9b8fd + en: 0163c039e0d076d3 + zh: 09ce845f1aa2247f /session-persistence-event-catalog/resolved-persistence-types/message: - en: 187ae8e83f1e098c - zh: b8d2a6da204ab374 + en: 85464dd8bfd3de11 + zh: fcaa569c62f40d1e /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackdelete: en: c582953270d4ca44 zh: 966ccfe2e7660a2a @@ -1173,14 +1179,14 @@ en: f58575a1fc96df42 zh: 9f0c6ed9033e5c9d /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackrating: - en: b1fe7f73ef131d37 - zh: a7f21077264c3672 + en: c6b485863570b464 + zh: a43270a1d8793a94 /session-persistence-event-catalog/resolved-persistence-types/messagesource: - en: 728c7e3a866becb4 - zh: 8485fead5c4f8a68 + en: ef9c082111abc052 + zh: 8716c7f96df49470 /session-persistence-event-catalog/resolved-persistence-types/message~2: - en: 5d9460cc6936bef1 - zh: df2f345f231826fe + en: bf5191eae029675e + zh: 9fe288da158d31e0 /session-persistence-event-catalog/resolved-persistence-types/modelmessagesource: en: 65a618e2ec94bbc4 zh: 622197f4b127068b @@ -1239,11 +1245,11 @@ en: 9a54c4478ad3b620 zh: 02c4c1fd7e252770 /session-persistence-event-catalog/resolved-persistence-types/sessiontitleeventdata: - en: 8d2d7edebcec76a1 - zh: 9a7aa822a2fcd13a + en: f12651cc6a8cbf55 + zh: a06e22fd119383b2 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: 41eb5d6bd15268fc - zh: 14e90961ce528f74 + en: e2e5cda8c14a355c + zh: c7ced08de148ba4e /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 7a7245bb23c38655 zh: 6d96a94c367fbe64 @@ -1359,14 +1365,14 @@ en: 3df95e0ae2ab468a zh: d146e8ebb3ff53b1 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: 64239a49fc1b7a03 - zh: 94244191ec54f293 + en: 889856c5db3aa2e4 + zh: 4a4c8508360e30f8 /session-persistence-event-catalog/resolved-persistence-types/usermessage: - en: f100fd2d226790f8 - zh: f6c765322689dec4 + en: a979c583756bc3f6 + zh: f6fcd77a09ab92b5 /session-persistence-event-catalog/resolved-persistence-types/usermessage~2: - en: fe1eb648b1f6fb24 - zh: be0cc7169d049641 + en: 1b4d5020cf81d7b6 + zh: 0ffdcd05b937ce4c /session-persistence-event-catalog/resolved-persistence-types/workflowagentoutcome: en: 711564ea7898e156 zh: 36b88b84a6dc3c7e @@ -1572,11 +1578,11 @@ en: 4cb1c48095df98dc zh: 5a03e44761af559e /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: 1caa8c0bc2304254 - zh: 40f7856c9b499578 + en: 724ab704fc5316d0 + zh: 04d9c7c611e45521 /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: 636edf9e560ec6e5 - zh: 2dce475574d31c29 + en: a152f57536c9f587 + zh: 8393d63e3035e0b3 /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1593,11 +1599,11 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: 730b56bd3eb40edb - zh: de4a92f09d55e6a4 + en: cc21643deee5d5c5 + zh: f4280ec6fa02442a /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: - en: 939d08138402b791 - zh: 30b7b41f19940633 + en: 65a0655a8d52b6f7 + zh: d2b1be08f3943905 /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: en: f287a358fce87bb4 zh: b332f4b99b5d9db6 @@ -1635,8 +1641,14 @@ en: ec733000e7c8bc23 zh: 091389d028d9c789 /session-persistence-event-catalog/resolved-persistence-types/kind-cua-activity-form-notice: - en: b2d834240d76ef1a - zh: 5cd10724fc6deccf + en: 978a6d9d74878842 + zh: 2641a019f4d023ed +/session-persistence-event-catalog/resolved-persistence-types/kind-cua-held-inputs-form-notice: + en: f4925e26d98a7ce7 + zh: 059d7b9474f7c9de +/session-persistence-event-catalog/resolved-persistence-types/kind-cua-inputs-released-form-notice: + en: 3dbe03c5f2048836 + zh: 723cd5f33af39a76 /session-persistence-event-catalog/resolved-persistence-types/kind-disposed: en: 9b4155c7c2c46023 zh: 1cd75eecdc41e8ad @@ -2025,11 +2037,11 @@ en: 95c48ecc35b7c82c zh: 248ac36607f3306c /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: - en: 5d3e430ae83c1a12 - zh: fdee1f50c818af41 + en: 13301052501c3194 + zh: 9e3467f2d8279016 /session-persistence-event-catalog/resolved-persistence-types/type-agent-inbox-spliced: - en: 4656c3737756b03a - zh: 58f296636d0b825a + en: b66888e730bfb97d + zh: 1c87e97178d256fd /session-persistence-event-catalog/resolved-persistence-types/type-approval-asked: en: 9c77f18b0dad22f0 zh: 8894cf2878fe90db @@ -2073,11 +2085,11 @@ en: ba73fb10b7e2ffc9 zh: 8d5c97e63e5f16da /session-persistence-event-catalog/resolved-persistence-types/type-deliverables-presented: - en: ce049f7665b8fe76 - zh: bae7694af8cddcfa + en: cdf9f3a3acf0614b + zh: 54669ccc33433fc6 /session-persistence-event-catalog/resolved-persistence-types/type-developer-message: - en: af5cb180a32d88d0 - zh: d62b6654961472bd + en: 216566add5f0f4da + zh: f65526f890ac89c9 /session-persistence-event-catalog/resolved-persistence-types/type-disabled: en: 04db8a26a3befdd4 zh: 8b24a37ac00bac8a @@ -2151,11 +2163,11 @@ en: acf7e21e4d21ebff zh: fb83a853634d204a /session-persistence-event-catalog/resolved-persistence-types/type-session-title: - en: 92b2794ad91ebd87 - zh: d61cca93425872da + en: de1ae46c18f25ed8 + zh: b1b9fa41b883e1b4 /session-persistence-event-catalog/resolved-persistence-types/type-session-title-llm-request: - en: a33aea2b63a5b224 - zh: 3424933865736257 + en: 41d9c840b794f149 + zh: 345cc6ffb44daf3a /session-persistence-event-catalog/resolved-persistence-types/type-step-end: en: 7fc233c4a569dae2 zh: bc2b3fed4a397c00 @@ -2235,11 +2247,11 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 21f98490fc3e1482 - zh: c0e10a7cedc0f416 + en: 3838c5ec40f3b4d8 + zh: 0611ca5037165df6 /session-persistence-event-catalog/resolved-persistence-types/type-user-message: - en: 6f360fadf7420228 - zh: a2c42bbcd25ae836 + en: 43cdaf56d65bbbde + zh: 62a8153ebd2678f8 /session-persistence-event-catalog/resolved-persistence-types/type-web-deepseek-search-llm-request: en: 99c8837344178a47 zh: bf746f5678346596 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 8f8a7dcd3b..2b3b3baa6a 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -23,7 +23,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7) | +| `event:agent/inbox/spliced` | event | `41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -36,7 +36,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8` | [`{ type: "developer/message" }`](#persistence-type-sha256-54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8) | +| `event:developer/message` | event | `8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710` | [`{ type: "developer/message" }`](#persistence-type-sha256-8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -58,7 +58,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f) | +| `event:session/title-llm-request` | event | `64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41) | @@ -81,7 +81,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d` | [`{ type: "user/message" }`](#persistence-type-sha256-94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d) | +| `event:user/message` | event | `b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8` | [`{ type: "user/message" }`](#persistence-type-sha256-b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace-root/change` | event | `025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc` | [`{ type: "workspace-root/change" }`](#persistence-type-sha256-025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc) | @@ -1731,6 +1731,22 @@ SHA-256: `566ff6353402bf04c27f6073f9a13fcf0d7bfa438aa1c7ad9ece63fe108edfba` `"cua-activity"` + + +### `"cua-held-inputs"` + +SHA-256: `9d42da116fccdc399c2877bb46488c6690e3968c02de6ff2a55e83adc67cc496` + +`"cua-held-inputs"` + + + +### `"cua-inputs-released"` + +SHA-256: `a6816f39283ae26f0cd16cfce35724eb676a1f1b57afbc91094a36b2d2a40b2d` + +`"cua-inputs-released"` + ### `"danger-full-access"` @@ -3477,7 +3493,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web | `body` | required | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | required | `string` | - + @@ -3485,7 +3501,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web ### `DeveloperMessage` -SHA-256: `e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f` +SHA-256: `14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502` Sources: [`packages/llm/llm/src/message.ts:182`](../packages/llm/llm/src/message.ts) @@ -3494,7 +3510,7 @@ Sources: [`packages/llm/llm/src/message.ts:182`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"developer"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7) | Source compatibility: `source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -4193,7 +4209,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr | `step` | required | `number` | | `turn` | required | `number` | - + @@ -4201,15 +4217,15 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr ### `Message` -SHA-256: `cf751a091c7c75efbd3ca13b26fa0bfa485e0f20b9c175437d3aa33afc2890a1` +SHA-256: `dff922ce762afdc70de374c9fafe7b9a2733f58549e317af799954decb2704be` Sources: [`packages/llm/llm/src/message.ts:221`](../packages/llm/llm/src/message.ts) One of: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f) -- [`UserMessage`](#persistence-type-sha256-daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614) +- [`DeveloperMessage`](#persistence-type-sha256-14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502) +- [`UserMessage`](#persistence-type-sha256-b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea) - [`SystemMessage`](#persistence-type-sha256-04c12e59a9ed4d7a59b642223a9bdd3b4303c1d27873c72c5e487760892bbb08) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4286,7 +4302,7 @@ One of: - `"negative"` - `"positive"` - + @@ -4294,7 +4310,7 @@ One of: ### `MessageSource` -SHA-256: `7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d` +SHA-256: `c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7` Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message.ts) @@ -4312,6 +4328,8 @@ Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message | `compact-checkpoint` | not declared | `compactionId`: `string` | [`CompactionCheckpointSource`](#persistence-type-sha256-31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648) | | `cordis-host-runner` | not declared | none | [`{ kind: "cordis-host-runner" }`](#persistence-type-sha256-02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79) | | `cua-activity` | `"notice"` | `summary`: `string` | [`{ kind: "cua-activity", form: "notice" }`](#persistence-type-sha256-7f7cc4903d822e9a54ff3214cb5d0163b124955ecf677f8937c5585aa55f09c3) | +| `cua-held-inputs` | `"notice"` | `summary`: `string` | [`{ kind: "cua-held-inputs", form: "notice" }`](#persistence-type-sha256-8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21) | +| `cua-inputs-released` | `"notice"` | `summary`: `string` | [`{ kind: "cua-inputs-released", form: "notice" }`](#persistence-type-sha256-ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b) | | `dsh-session-title-llm` | `"catalog"` | none | [`{ kind: "dsh-session-title-llm", form: "catalog" }`](#persistence-type-sha256-80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc) | | `dsh-session-title-llm` | `"instructions"` | none | [`{ kind: "dsh-session-title-llm", form: "instructions" }`](#persistence-type-sha256-224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc) | | `dsh-session-title-llm` | `"notice"` | `summary`: `string` | [`{ kind: "dsh-session-title-llm", form: "notice" }`](#persistence-type-sha256-8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6) | @@ -4423,13 +4441,13 @@ Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | not declared | none | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `69b87f3f1cbd2e33e2c2d6563a35c4e6a57e521c0f00ca8df508b42835e8da4d` +SHA-256: `5bcaeed5facdbccc89dbc5cb0dee03b710b2f4189b72bae3d805b39f419034d1` -Array of [`Message`](#persistence-type-sha256-cf751a091c7c75efbd3ca13b26fa0bfa485e0f20b9c175437d3aa33afc2890a1). +Array of [`Message`](#persistence-type-sha256-dff922ce762afdc70de374c9fafe7b9a2733f58549e317af799954decb2704be). @@ -4797,7 +4815,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ | `source` | required | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | required | `string` | - + @@ -4805,7 +4823,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ ### `SessionTitleLlmRequestEventData` -SHA-256: `6d3098e367bc9ebf4ea907cfe826690cc4892d796672a3904b33d064158da409` +SHA-256: `86a9b7da960c2a983fe66f1ba8dd92e41b53bff4d8758043bea19378d3a62608` Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4813,7 +4831,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/sess |---|---|---| | `maxTokens` | required | `number` | | `messageSeqs` | required | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | required | [`Message[]`](#persistence-type-sha256-69b87f3f1cbd2e33e2c2d6563a35c4e6a57e521c0f00ca8df508b42835e8da4d) | +| `messages` | required | [`Message[]`](#persistence-type-sha256-5bcaeed5facdbccc89dbc5cb0dee03b710b2f4189b72bae3d805b39f419034d1) | | `reasoningEffort` | optional | `string` | | `route` | required | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | required | `string` | @@ -5520,7 +5538,7 @@ Sources: [`packages/core/session/src/types.ts:248`](../packages/core/session/src | `interrupted` | not declared | none | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | not declared | none | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5528,7 +5546,7 @@ Sources: [`packages/core/session/src/types.ts:248`](../packages/core/session/src ### `UserMessage` -SHA-256: `daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614` +SHA-256: `b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea` Sources: [`packages/llm/llm/src/message.ts:187`](../packages/llm/llm/src/message.ts) @@ -5537,19 +5555,19 @@ Sources: [`packages/llm/llm/src/message.ts:187`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"user"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7) | Source compatibility: `source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. Attribution-only additions: `action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `758b3558f0398bdd1f5837e7d237c2cf1ebb3967a5e2776f487287d81cc5b923` +SHA-256: `26d2d4da493daea93cf37ebb47514f30f290276aa9940bbca96e04a82c049793` -Array of [`UserMessage`](#persistence-type-sha256-daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614). +Array of [`UserMessage`](#persistence-type-sha256-b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea). @@ -6556,18 +6574,18 @@ Sources: [`packages/core/session/src/types.ts:405`](../packages/core/session/src | `reason` | required | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | optional | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `041960dcab4a409b4d50f524abbec606e518dc198f84d6a84922155096326592` +SHA-256: `7dd505cd3b36da219ed87f3d7b03061ed8d23b26bc3900603a81d27454b67f69` Sources: [`packages/core/session/src/types.ts:327`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `headerSeq` | optional | `number` | -| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f) | +| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502) | | `step` | required | `number` | | `turn` | required | `number` | @@ -6651,17 +6669,17 @@ Sources: [`packages/core/session/src/types.ts:442`](../packages/core/session/src |---|---|---| | `inherited` | optional | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `2ea337d0a09fdd6a96c853397f72438c7256bba373b98400c4af8d142b47aaf0` +SHA-256: `72258a6fae4af8fdb2934cb16af46b7d5c8b7f25f84785164532f237b9b69270` Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | Property | Presence | Type | |---|---|---| -| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-758b3558f0398bdd1f5837e7d237c2cf1ebb3967a5e2776f487287d81cc5b923) | +| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-26d2d4da493daea93cf37ebb47514f30f290276aa9940bbca96e04a82c049793) | | `outcome` | optional | `"canceled"` | | `removedCount` | optional | `number` | | `start` | required | `number` | @@ -6832,6 +6850,30 @@ Sources: [`packages/experimental/cua-macos/src/recent-activity.ts:11`](../packag | `kind` | required | `"cua-activity"` | | `summary` | required | `string` | + + +### `{ kind: "cua-held-inputs", form: "notice" }` + +SHA-256: `8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"notice"` | +| `kind` | required | `"cua-held-inputs"` | +| `summary` | required | `string` | + + + +### `{ kind: "cua-inputs-released", form: "notice" }` + +SHA-256: `ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"notice"` | +| `kind` | required | `"cua-inputs-released"` | +| `summary` | required | `string` | + ### `{ kind: "disposed" }` @@ -8360,17 +8402,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | required | `number` | | `type` | required | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7` +SHA-256: `41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-2ea337d0a09fdd6a96c853397f72438c7256bba373b98400c4af8d142b47aaf0) | +| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-72258a6fae4af8fdb2934cb16af46b7d5c8b7f25f84785164532f237b9b69270) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8611,17 +8653,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | required | `number` | | `type` | required | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8` +SHA-256: `8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-041960dcab4a409b4d50f524abbec606e518dc198f84d6a84922155096326592) | +| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-7dd505cd3b36da219ed87f3d7b03061ed8d23b26bc3900603a81d27454b67f69) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -9021,17 +9063,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | required | `number` | | `type` | required | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f` +SHA-256: `64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829` | Property | Presence | Type | |---|---|---| -| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-6d3098e367bc9ebf4ea907cfe826690cc4892d796672a3904b33d064158da409) | +| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-86a9b7da960c2a983fe66f1ba8dd92e41b53bff4d8758043bea19378d3a62608) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -9470,17 +9512,17 @@ Sources: [`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) | `type` | required | `"usage"` | | `usage` | required | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d` +SHA-256: `b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8` | Property | Presence | Type | |---|---|---| -| `data` | required | [`UserMessage`](#persistence-type-sha256-daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614) | +| `data` | required | [`UserMessage`](#persistence-type-sha256-b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 010d589730..ec3ecd47f0 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -25,7 +25,7 @@ | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7) | +| `event:agent/inbox/spliced` | event | `41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -38,7 +38,7 @@ | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8` | [`{ type: "developer/message" }`](#persistence-type-sha256-54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8) | +| `event:developer/message` | event | `8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710` | [`{ type: "developer/message" }`](#persistence-type-sha256-8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -60,7 +60,7 @@ | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f) | +| `event:session/title-llm-request` | event | `64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41) | @@ -83,7 +83,7 @@ | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d` | [`{ type: "user/message" }`](#persistence-type-sha256-94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d) | +| `event:user/message` | event | `b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8` | [`{ type: "user/message" }`](#persistence-type-sha256-b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace-root/change` | event | `025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc` | [`{ type: "workspace-root/change" }`](#persistence-type-sha256-025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc) | @@ -1733,6 +1733,22 @@ SHA-256: `566ff6353402bf04c27f6073f9a13fcf0d7bfa438aa1c7ad9ece63fe108edfba` `"cua-activity"` + + +### `"cua-held-inputs"` + +SHA-256: `9d42da116fccdc399c2877bb46488c6690e3968c02de6ff2a55e83adc67cc496` + +`"cua-held-inputs"` + + + +### `"cua-inputs-released"` + +SHA-256: `a6816f39283ae26f0cd16cfce35724eb676a1f1b57afbc91094a36b2d2a40b2d` + +`"cua-inputs-released"` + ### `"danger-full-access"` @@ -3479,7 +3495,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` | `body` | 必需 | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | 必需 | `string` | - + @@ -3487,7 +3503,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` ### `DeveloperMessage` -SHA-256: `e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f` +SHA-256: `14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502` 来源:[`packages/llm/llm/src/message.ts:182`](../packages/llm/llm/src/message.ts) @@ -3496,7 +3512,7 @@ SHA-256: `e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"developer"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -4195,7 +4211,7 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` | `step` | 必需 | `number` | | `turn` | 必需 | `number` | - + @@ -4203,15 +4219,15 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` ### `Message` -SHA-256: `cf751a091c7c75efbd3ca13b26fa0bfa485e0f20b9c175437d3aa33afc2890a1` +SHA-256: `dff922ce762afdc70de374c9fafe7b9a2733f58549e317af799954decb2704be` 来源:[`packages/llm/llm/src/message.ts:221`](../packages/llm/llm/src/message.ts) 以下类型之一: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f) -- [`UserMessage`](#persistence-type-sha256-daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614) +- [`DeveloperMessage`](#persistence-type-sha256-14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502) +- [`UserMessage`](#persistence-type-sha256-b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea) - [`SystemMessage`](#persistence-type-sha256-04c12e59a9ed4d7a59b642223a9bdd3b4303c1d27873c72c5e487760892bbb08) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4288,7 +4304,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` - `"negative"` - `"positive"` - + @@ -4296,7 +4312,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` ### `MessageSource` -SHA-256: `7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d` +SHA-256: `c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7` 来源:[`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message.ts) @@ -4314,6 +4330,8 @@ SHA-256: `7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d` | `compact-checkpoint` | 未声明 | `compactionId`: `string` | [`CompactionCheckpointSource`](#persistence-type-sha256-31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648) | | `cordis-host-runner` | 未声明 | 无 | [`{ kind: "cordis-host-runner" }`](#persistence-type-sha256-02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79) | | `cua-activity` | `"notice"` | `summary`: `string` | [`{ kind: "cua-activity", form: "notice" }`](#persistence-type-sha256-7f7cc4903d822e9a54ff3214cb5d0163b124955ecf677f8937c5585aa55f09c3) | +| `cua-held-inputs` | `"notice"` | `summary`: `string` | [`{ kind: "cua-held-inputs", form: "notice" }`](#persistence-type-sha256-8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21) | +| `cua-inputs-released` | `"notice"` | `summary`: `string` | [`{ kind: "cua-inputs-released", form: "notice" }`](#persistence-type-sha256-ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b) | | `dsh-session-title-llm` | `"catalog"` | 无 | [`{ kind: "dsh-session-title-llm", form: "catalog" }`](#persistence-type-sha256-80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc) | | `dsh-session-title-llm` | `"instructions"` | 无 | [`{ kind: "dsh-session-title-llm", form: "instructions" }`](#persistence-type-sha256-224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc) | | `dsh-session-title-llm` | `"notice"` | `summary`: `string` | [`{ kind: "dsh-session-title-llm", form: "notice" }`](#persistence-type-sha256-8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6) | @@ -4425,13 +4443,13 @@ SHA-256: `7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d` | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | 未声明 | 无 | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `69b87f3f1cbd2e33e2c2d6563a35c4e6a57e521c0f00ca8df508b42835e8da4d` +SHA-256: `5bcaeed5facdbccc89dbc5cb0dee03b710b2f4189b72bae3d805b39f419034d1` -[`Message`](#persistence-type-sha256-cf751a091c7c75efbd3ca13b26fa0bfa485e0f20b9c175437d3aa33afc2890a1) 的数组。 +[`Message`](#persistence-type-sha256-dff922ce762afdc70de374c9fafe7b9a2733f58549e317af799954decb2704be) 的数组。 @@ -4799,7 +4817,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` | `source` | 必需 | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | 必需 | `string` | - + @@ -4807,7 +4825,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` ### `SessionTitleLlmRequestEventData` -SHA-256: `6d3098e367bc9ebf4ea907cfe826690cc4892d796672a3904b33d064158da409` +SHA-256: `86a9b7da960c2a983fe66f1ba8dd92e41b53bff4d8758043bea19378d3a62608` 来源:[`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4815,7 +4833,7 @@ SHA-256: `6d3098e367bc9ebf4ea907cfe826690cc4892d796672a3904b33d064158da409` |---|---|---| | `maxTokens` | 必需 | `number` | | `messageSeqs` | 必需 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-69b87f3f1cbd2e33e2c2d6563a35c4e6a57e521c0f00ca8df508b42835e8da4d) | +| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-5bcaeed5facdbccc89dbc5cb0dee03b710b2f4189b72bae3d805b39f419034d1) | | `reasoningEffort` | 可选 | `string` | | `route` | 必需 | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | 必需 | `string` | @@ -5522,7 +5540,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` | `interrupted` | 未声明 | 无 | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | 未声明 | 无 | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5530,7 +5548,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` ### `UserMessage` -SHA-256: `daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614` +SHA-256: `b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea` 来源:[`packages/llm/llm/src/message.ts:187`](../packages/llm/llm/src/message.ts) @@ -5539,19 +5557,19 @@ SHA-256: `daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"user"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. 仅表示归属的新增 kind:`action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `758b3558f0398bdd1f5837e7d237c2cf1ebb3967a5e2776f487287d81cc5b923` +SHA-256: `26d2d4da493daea93cf37ebb47514f30f290276aa9940bbca96e04a82c049793` -[`UserMessage`](#persistence-type-sha256-daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614) 的数组。 +[`UserMessage`](#persistence-type-sha256-b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea) 的数组。 @@ -6558,18 +6576,18 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` | `reason` | 必需 | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | 可选 | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `041960dcab4a409b4d50f524abbec606e518dc198f84d6a84922155096326592` +SHA-256: `7dd505cd3b36da219ed87f3d7b03061ed8d23b26bc3900603a81d27454b67f69` 来源:[`packages/core/session/src/types.ts:327`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `headerSeq` | 可选 | `number` | -| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f) | +| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502) | | `step` | 必需 | `number` | | `turn` | 必需 | `number` | @@ -6653,17 +6671,17 @@ SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` |---|---|---| | `inherited` | 可选 | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `2ea337d0a09fdd6a96c853397f72438c7256bba373b98400c4af8d142b47aaf0` +SHA-256: `72258a6fae4af8fdb2934cb16af46b7d5c8b7f25f84785164532f237b9b69270` 来源:[`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| -| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-758b3558f0398bdd1f5837e7d237c2cf1ebb3967a5e2776f487287d81cc5b923) | +| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-26d2d4da493daea93cf37ebb47514f30f290276aa9940bbca96e04a82c049793) | | `outcome` | 可选 | `"canceled"` | | `removedCount` | 可选 | `number` | | `start` | 必需 | `number` | @@ -6834,6 +6852,30 @@ SHA-256: `7f7cc4903d822e9a54ff3214cb5d0163b124955ecf677f8937c5585aa55f09c3` | `kind` | 必需 | `"cua-activity"` | | `summary` | 必需 | `string` | + + +### `{ kind: "cua-held-inputs", form: "notice" }` + +SHA-256: `8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"notice"` | +| `kind` | 必需 | `"cua-held-inputs"` | +| `summary` | 必需 | `string` | + + + +### `{ kind: "cua-inputs-released", form: "notice" }` + +SHA-256: `ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"notice"` | +| `kind` | 必需 | `"cua-inputs-released"` | +| `summary` | 必需 | `string` | + ### `{ kind: "disposed" }` @@ -8362,17 +8404,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | 必需 | `number` | | `type` | 必需 | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7` +SHA-256: `41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-2ea337d0a09fdd6a96c853397f72438c7256bba373b98400c4af8d142b47aaf0) | +| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-72258a6fae4af8fdb2934cb16af46b7d5c8b7f25f84785164532f237b9b69270) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8613,17 +8655,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | 必需 | `number` | | `type` | 必需 | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8` +SHA-256: `8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-041960dcab4a409b4d50f524abbec606e518dc198f84d6a84922155096326592) | +| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-7dd505cd3b36da219ed87f3d7b03061ed8d23b26bc3900603a81d27454b67f69) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -9023,17 +9065,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | 必需 | `number` | | `type` | 必需 | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f` +SHA-256: `64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-6d3098e367bc9ebf4ea907cfe826690cc4892d796672a3904b33d064158da409) | +| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-86a9b7da960c2a983fe66f1ba8dd92e41b53bff4d8758043bea19378d3a62608) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -9472,17 +9514,17 @@ SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` | `type` | 必需 | `"usage"` | | `usage` | 必需 | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d` +SHA-256: `b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614) | +| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml b/docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml new file mode 100644 index 0000000000..53b2626688 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-19-cua-input-notices.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/persistence-changes/2026-11-19-cua-input-notices.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-11-19-cua-input-notices: + en: 05ad48d04065f2d6 + zh: 7d35d69bb75dbd82 +/2026-11-19-cua-input-notices/summary: + en: 99c8df735ac604f9 + zh: b7d7f1b6d2e53645 +/2026-11-19-cua-input-notices/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-11-19-cua-input-notices/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-11-19-cua-input-notices/compatibility: + en: d9081b4686482328 + zh: 33254ef8c6e5c6a9 +/2026-11-19-cua-input-notices/verification: + en: e25c20c14355cfc6 + zh: 67b8b1adf15f80b6 +/2026-11-19-cua-input-notices/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.md b/docs/persistence-changes/2026-11-19-cua-input-notices.md new file mode 100644 index 0000000000..d65afe1035 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-11-19-cua-input-notices + +English | [中文](2026-11-19-cua-input-notices.zh.md) + +## Summary + +Adds cua-held-inputs and cua-inputs-released producer attribution using the existing notice form and text content. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-19-cua-input-notices +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-11-18-cua-activity-context" + after: "41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049" + decision: same-version + - root: "event:developer/message" + previous: "2026-11-18-cua-activity-context" + after: "8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-11-18-cua-activity-context" + after: "64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829" + decision: same-version + - root: "event:user/message" + previous: "2026-11-18-cua-activity-context" + after: "b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8" + decision: same-version +``` + + +## Compatibility + +This remains Session format V4. New readers retain every previous source kind and event field. Released V4 readers accept nonempty unknown producer kinds in user/developer messages, preserve their metadata and text, and already understand notice summaries. The same source objects occur in queued inbox messages and recorded title-request messages. These two kinds describe input state; restoring or deriving a Session does not replay native input or recreate holds. No event discriminator, header, message role or existing source meaning changes. + + +## Verification + +pnpm run test packages/session/session-format-v3-to-v4/tests/attribution.spec.ts packages/session/session-format-v3-to-v4/tests/message-sources.spec.ts: 12 tests passed. Seven focused headless/TypeScript SDK CUA snapshots, the shipped cua-mcp profile expectation, Web CUA replay and Python SDK replay passed. CUA behavior tests cover persisted held notices, confirmed release notices after pause, and removal of delayed stale notices. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json b/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json new file mode 100644 index 0000000000..0a5d2a84e0 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json @@ -0,0 +1,276 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8"} + ], + "types": [], + "nodes": { + "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, + "04c12e59a9ed4d7a": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"3d1339bcc98cb537","optional":false}],"indices":[]}, + "05205074b24d8340": {"kind":"literal","value":"action-cards"}, + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, + "0a92c5bdfa06c2e2": {"kind":"object","properties":[{"name":"displayName","type":"4cd48f3e5108bd6e","optional":true},{"name":"providerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subjectId","type":"4cd48f3e5108bd6e","optional":false},{"name":"tenantId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "0ed8d1108fe7a5e1": {"kind":"object","properties":[{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "0eeb17e1df89b1eb": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "0f46153645c29784": {"kind":"object","properties":[{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "0fe52387f6505270": {"kind":"literal","value":"plan-mode"}, + "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, + "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, + "14e81f18050da9ee": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"c519fc9b5b12fa24","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "16d0507cb94b4cfc": {"kind":"literal","value":"relay"}, + "1922cd79a70806c1": {"kind":"literal","value":"skill-invocation"}, + "1938c8c20f1cba7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1e0b0b66b6f0c53f": {"kind":"literal","value":"aborted"}, + "1e709346005826eb": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1ebc6f9ff3aa9e3a": {"kind":"literal","value":"completed"}, + "1f0133217eeeffd8": {"kind":"literal","value":"tool-call"}, + "1f1385dbc3e875c0": {"kind":"literal","value":"repeat-tool-reminder"}, + "1fdad624334d3548": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "2152caf1a71e588e": {"kind":"object","properties":[{"name":"kind","type":"2e4debca12f2c449","optional":false},{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "2235d957bf4b7c6c": {"kind":"object","properties":[{"name":"kind","type":"7b1ce60193fa8b69","optional":false}],"indices":[]}, + "224aa11d4d5f88c4": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "23af3759678a30de": {"kind":"literal","value":"dsh-session-title-llm"}, + "24b10f7cdae64928": {"kind":"literal","value":"runtime-context"}, + "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "26d2d4da493daea9": {"kind":"array","element":"b72ba9c86f4510fc"}, + "2765e9119edf5816": {"kind":"literal","value":"model"}, + "277b61f9c6f81704": {"kind":"literal","value":"file"}, + "28936c614bd4e7e2": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "290f32bfd81ff85a": {"kind":"object","properties":[{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "297fbd8067d7815a": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, + "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, + "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, + "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, + "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, + "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "335e242de1fcc17b": {"kind":"union","types":["bcf0caf62d964b2f","e438a9d4fb883b3e"]}, + "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, + "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "3bd652ebfa8726b3": {"kind":"union","types":["0657d3ca5ac4e7bf","938f7c7357bc403e"]}, + "3bdb8dc6989655b0": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "3c2535ca0a2062f1": {"kind":"literal","value":"reasoning"}, + "3d1339bcc98cb537": {"kind":"object","properties":[{"name":"complete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"09655b34d7f3cf1e","optional":false},{"name":"reset","type":"dacf3d5f3e4ff619","optional":true},{"name":"sections","type":"8decd4949d9ee4ad","optional":true}],"indices":[]}, + "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, + "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, + "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "41b562e6d6c59ac2": {"kind":"object","properties":[{"name":"data","type":"72258a6fae4af8fd","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, + "43e311235aa537df": {"kind":"object","properties":[{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"83d6916021eede8f","optional":false}],"indices":[]}, + "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "4902846b72aabae5": {"kind":"literal","value":"retired"}, + "4991dfc415c9efeb": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "49dab019d00e8c26": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "4a561c111a78d452": {"kind":"literal","value":"refusal"}, + "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4b259f7f8f0a44ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"isError","type":"aa93010d0e521ad7","optional":true},{"name":"role","type":"a13d8f379222ece8","optional":false},{"name":"source","type":"d9c462b9f62fdd3e","optional":false},{"name":"toolCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, + "4d60dddaa65d3da8": {"kind":"object","properties":[{"name":"actor","type":"0a92c5bdfa06c2e2","optional":false},{"name":"kind","type":"6ba7edb6447b6a3e","optional":false},{"name":"shareId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4e44c9118152f682": {"kind":"literal","value":"text"}, + "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, + "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, + "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, + "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "566ff6353402bf04": {"kind":"literal","value":"cua-activity"}, + "58015da1c1950a66": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "587bb11da730e06a": {"kind":"literal","value":"session/title-llm-request"}, + "589d0d91239681f8": {"kind":"literal","value":"developer"}, + "58f94390b982f8a5": {"kind":"literal","value":"image/png"}, + "5b7abd24d8a133e7": {"kind":"union","types":["792eb6cb1f6bed83","a408aa610f991ff3"]}, + "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5bcaeed5facdbccc": {"kind":"array","element":"dff922ce762afdc7"}, + "5cdbf342b7748d15": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "5d03ba38734809bc": {"kind":"array","element":"0657d3ca5ac4e7bf"}, + "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, + "63ba8895cc09e469": {"kind":"literal","value":"retry"}, + "64b6ec45d21f5aed": {"kind":"object","properties":[{"name":"data","type":"86a9b7da960c2a98","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, + "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, + "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "68141cbe3994a5ff": {"kind":"literal","value":"max-tokens"}, + "68f44f59e91c4139": {"kind":"literal","value":"user"}, + "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, + "6ba7edb6447b6a3e": {"kind":"literal","value":"share-viewer"}, + "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, + "6f22a9d02b9a1f11": {"kind":"object","properties":[{"name":"baseline","type":"dacf3d5f3e4ff619","optional":true},{"name":"baselineIdentity","type":"4cd48f3e5108bd6e","optional":true},{"name":"changes","type":"2ab12a0e345658f9","optional":false},{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"fbd2c74b346a1595","optional":false}],"indices":[]}, + "6f44f32be9bcd9a8": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, + "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, + "72258a6fae4af8fd": {"kind":"object","properties":[{"name":"inserted","type":"26d2d4da493daea9","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, + "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, + "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, + "792eb6cb1f6bed83": {"kind":"object","properties":[{"name":"contentIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"noticeIndex","type":"5d03ba38734809bc","optional":true},{"name":"order","type":"0657d3ca5ac4e7bf","optional":false},{"name":"state","type":"c8e6f48878cc2a2f","optional":false}],"indices":[]}, + "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, + "7dd505cd3b36da21": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"14e81f18050da9ee","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, + "7f7cc4903d822e9a": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"566ff6353402bf04","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, + "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, + "814d9434e1ddf907": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"3c2535ca0a2062f1","optional":false}],"indices":[]}, + "82470020b5bfcb1a": {"kind":"literal","value":"agent-message"}, + "824a4aad44a54e24": {"kind":"union","types":["4d60dddaa65d3da8","deebfc7c62177ea8"]}, + "825ca23416b1ea9d": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "829a2fb3be6efd4b": {"kind":"literal","value":"agent/inbox/spliced"}, + "83079c8a3f733ac3": {"kind":"object","properties":[{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8338ee303e2bd448": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, + "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "848639f8787f035b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"866f7b2dbdc5b421","optional":true},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "85d6d96ff8842974": {"kind":"literal","value":"answered"}, + "85f9b505b7bdff1f": {"kind":"literal","value":"tool-addition"}, + "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "866f7b2dbdc5b421": {"kind":"union","types":["1e0b0b66b6f0c53f","1ebc6f9ff3aa9e3a","4a561c111a78d452","68141cbe3994a5ff","a2be0f0cb59f0d4a"]}, + "86a9b7da960c2a98": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"5bcaeed5facdbccc","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "87b1a33564b9a4d6": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8a2e3e7a523e622b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9d42da116fccdc39","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8af841fc9b265ade": {"kind":"literal","value":"system"}, + "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8decd4949d9ee4ad": {"kind":"array","element":"5b7abd24d8a133e7"}, + "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8ecc75abd481f9ea": {"kind":"object","properties":[{"name":"data","type":"7dd505cd3b36da21","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "8f1062573ea91841": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"63ba8895cc09e469","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, + "904bf499d98be4a3": {"kind":"union","types":["7382c4fc95fe8c5d","b765ee31033cea46","f6cb462f808309e3"]}, + "938f7c7357bc403e": {"kind":"primitive","type":"null"}, + "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, + "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, + "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "96f4a9c81fc0f940": {"kind":"union","types":["3e2ece4967cfebe9","62ecb62dc0fe1b5e"]}, + "99135d8a39379779": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "99e7e7d7fed55ae6": {"kind":"literal","value":"tool-jobs"}, + "99f0e98184709ad1": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "9ac52f0f84fec2eb": {"kind":"literal","value":"model-selection"}, + "9d42da116fccdc39": {"kind":"literal","value":"cua-held-inputs"}, + "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "a13d8f379222ece8": {"kind":"literal","value":"tool"}, + "a15a19ef63cf5d1b": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "a16e567c8cd2c55c": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "a2066bd52f61218b": {"kind":"object","properties":[{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "a2be0f0cb59f0d4a": {"kind":"literal","value":"error"}, + "a3c6f1ea38e9a61d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a408aa610f991ff3": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"noticeIndex","type":"5d03ba38734809bc","optional":true},{"name":"state","type":"4902846b72aabae5","optional":false}],"indices":[]}, + "a4afec59b75aad5d": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a6816f39283ae26f": {"kind":"literal","value":"cua-inputs-released"}, + "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, + "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, + "aa2bf9e82b9fdeb9": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, + "aae343bc3d663c83": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "aba175fb20ffc711": {"kind":"array","element":"83079c8a3f733ac3"}, + "ada310bf0bdb8fed": {"kind":"object","properties":[{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "ade057f4fdc387ae": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "aec150797b655c5f": {"kind":"literal","value":"catalog"}, + "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b2a5c8c008a31e3d": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "b3681c026a0b98e9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "b4ec0af39fd52ed9": {"kind":"object","properties":[{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b52f215a6cd69105": {"kind":"array","element":"8064c03c87c357fd"}, + "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b72ba9c86f4510fc": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"c519fc9b5b12fa24","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "b765ee31033cea46": {"kind":"literal","value":"set"}, + "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, + "b8ed92a5ca59733f": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "b9bcecf9562bc661": {"kind":"object","properties":[{"name":"data","type":"b72ba9c86f4510fc","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, + "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "baccc97ec34be6c4": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "bb94f3217aa56c88": {"kind":"literal","value":"hooks-codex"}, + "bbc5696e3f13c758": {"kind":"opaque","reason":"unknown"}, + "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, + "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, + "c519fc9b5b12fa24": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","3d1339bcc98cb537","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f7cc4903d822e9a","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8a2e3e7a523e622b","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","ce6e647c9e653b5d","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, + "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, + "c748fb42c80a1200": {"kind":"array","element":"86e1e384495ee09a"}, + "c77ac037cb8af460": {"kind":"literal","value":"timeline-priority"}, + "c8e6f48878cc2a2f": {"kind":"literal","value":"active"}, + "cb1c8959e1726f82": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ce6e647c9e653b5d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a6816f39283ae26f","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "d215701afb7aafbf": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"c77ac037cb8af460","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, + "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, + "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true}, + "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, + "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, + "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "de25352d2dc41963": {"kind":"literal","value":"user/message"}, + "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, + "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "deebfc7c62177ea8": {"kind":"object","properties":[{"name":"kind","type":"95a3ffccbf3c8afc","optional":false}],"indices":[]}, + "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, + "dff922ce762afdc7": {"kind":"union","types":["04c12e59a9ed4d7a","14e81f18050da9ee","4b259f7f8f0a44ad","b72ba9c86f4510fc","fa87537f4a9c1e25"]}, + "e438a9d4fb883b3e": {"kind":"literal","value":"append"}, + "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, + "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, + "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f19bee84bf3d2090": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f230c0b583e23b25": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "f29d63336e8266d8": {"kind":"object","properties":[{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "f2da0f27c1e6add5": {"kind":"object","properties":[{"name":"attachment","type":"f19bee84bf3d2090","optional":false},{"name":"type","type":"277b61f9c6f81704","optional":false}],"indices":[]}, + "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, + "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f68c335306535a00": {"kind":"literal","value":"user-approval"}, + "f6afe41e3926f422": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "f6cb462f808309e3": {"kind":"literal","value":"replace"}, + "f7283223aacdc39b": {"kind":"object","properties":[{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f88f1b7b6bb733f6": {"kind":"literal","value":1}, + "f97f47b0eb87905e": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fa87537f4a9c1e25": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"95c0e88fcf0bafb2","optional":false},{"name":"source","type":"719c51f67074f970","optional":false}],"indices":[]}, + "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, + "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, + "fcf427290c6213c2": {"kind":"primitive","type":"never"}, + "fcf81d3c58c13593": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fe1a7acdeed4d0f5": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"} + } +} diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md b/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md new file mode 100644 index 0000000000..4e837f64e5 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-11-19-cua-input-notices + +[English](2026-11-19-cua-input-notices.md) | 中文 + +## 概述 + +新增 cua-held-inputs 和 cua-inputs-released 来源标识,使用现有 notice 形式和文本内容。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-19-cua-input-notices +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-11-18-cua-activity-context" + after: "41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049" + decision: same-version + - root: "event:developer/message" + previous: "2026-11-18-cua-activity-context" + after: "8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-11-18-cua-activity-context" + after: "64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829" + decision: same-version + - root: "event:user/message" + previous: "2026-11-18-cua-activity-context" + after: "b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8" + decision: same-version +``` + + +## 兼容性 + +保持 Session 格式 V4。新读取器保留此前所有来源种类和事件字段。已发布的 V4 读取器允许用户或开发者消息使用非空的未知来源种类,保留其元数据和文本,并已支持 notice 摘要。收件箱排队消息和已记录的标题请求消息使用相同的来源对象。这两个种类描述输入状态;恢复或派生 Session 不会重放原生输入,也不会重新建立持有状态。事件判别字段、文件头、消息角色和既有来源含义均不改变。 + + +## 验证 + +pnpm run test packages/session/session-format-v3-to-v4/tests/attribution.spec.ts packages/session/session-format-v3-to-v4/tests/message-sources.spec.ts:12 项测试通过。7 个定向 headless/TypeScript SDK CUA 快照、发行配置 cua-mcp 的预期输出、Web CUA 回放及 Python SDK 回放通过。CUA 行为测试覆盖持有提醒入日志、暂停后确认的释放提醒,以及迟到旧提醒的移除。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/historical-formats/README.i18n.yaml b/docs/persistence-changes/historical-formats/README.i18n.yaml index 62e4dd7e29..2c739fcd2f 100644 --- a/docs/persistence-changes/historical-formats/README.i18n.yaml +++ b/docs/persistence-changes/historical-formats/README.i18n.yaml @@ -15,8 +15,8 @@ en: 14c57f30e676f6e3 zh: b1a0ccf26fab3727 /session-persistence-formats/format-references: - en: 85f24f5efbf8208d - zh: 83b01364996757a0 + en: 69446a7513fe20ca + zh: 9fa6ba2b6b057bf5 /session-persistence-formats/scope-and-evidence: en: 44ba17a168ec63ac zh: c80a44bdbf17a174 diff --git a/docs/persistence-changes/historical-formats/README.md b/docs/persistence-changes/historical-formats/README.md index df84eb9190..881a3e00b1 100644 --- a/docs/persistence-changes/historical-formats/README.md +++ b/docs/persistence-changes/historical-formats/README.md @@ -32,7 +32,7 @@ The index is generated from validated snapshots and the current writer constant. | 1 | PR #3349 | [V1](v1.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 67 / 648 | +| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 67 / 652 | diff --git a/docs/persistence-changes/historical-formats/README.zh.md b/docs/persistence-changes/historical-formats/README.zh.md index 1cfb6b1699..f335b828db 100644 --- a/docs/persistence-changes/historical-formats/README.zh.md +++ b/docs/persistence-changes/historical-formats/README.zh.md @@ -32,7 +32,7 @@ description: "查找从 V0 到工作区写入器版本的每个 Session 格式 | 1 | PR #3349 | [V1](v1.zh.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.zh.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.zh.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 67 / 648 | +| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 67 / 652 | diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 7e229b7fe1..e87800d467 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -5,7 +5,7 @@ {"key":"JsonlHeaderLine","kind":"header","digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f"}, {"key":"SessionEventEnvelope","kind":"envelope","digest":"5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc"}, {"key":"event:agent-preset/selected","kind":"event","event":"agent-preset/selected","surface":false,"digest":"a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b"}, - {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7"}, + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049"}, {"key":"event:approval/asked","kind":"event","event":"approval/asked","surface":false,"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1"}, {"key":"event:approval/decided","kind":"event","event":"approval/decided","surface":false,"digest":"bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3"}, {"key":"event:approval/policy","kind":"event","event":"approval/policy","surface":false,"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78"}, @@ -18,7 +18,7 @@ {"key":"event:compaction/start","kind":"event","event":"compaction/start","surface":false,"digest":"db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965"}, {"key":"event:compaction/summary","kind":"event","event":"compaction/summary","surface":false,"digest":"e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602"}, {"key":"event:deliverables/presented","kind":"event","event":"deliverables/presented","surface":false,"digest":"13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176"}, - {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710"}, {"key":"event:feedback/message-delete","kind":"event","event":"feedback/message-delete","surface":false,"digest":"3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796"}, {"key":"event:feedback/message-put","kind":"event","event":"feedback/message-put","surface":false,"digest":"b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf"}, {"key":"event:feedback/record","kind":"event","event":"feedback/record","surface":false,"digest":"b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8"}, @@ -40,7 +40,7 @@ {"key":"event:session-log-deepseek/delivery-accepted","kind":"event","event":"session-log-deepseek/delivery-accepted","surface":false,"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9"}, {"key":"event:session/end-seed","kind":"event","event":"session/end-seed","surface":false,"digest":"5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e"}, {"key":"event:session/title","kind":"event","event":"session/title","surface":false,"digest":"1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5"}, - {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829"}, {"key":"event:step/end","kind":"event","event":"step/end","surface":false,"digest":"e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05"}, {"key":"event:step/start","kind":"event","event":"step/start","surface":false,"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986"}, {"key":"event:subagent/catalog","kind":"event","event":"subagent/catalog","surface":false,"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41"}, @@ -63,7 +63,7 @@ {"key":"event:tool/result","kind":"event","event":"tool/result","surface":true,"digest":"7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397"}, {"key":"event:turn/end","kind":"event","event":"turn/end","surface":false,"digest":"0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce"}, {"key":"event:turn/start","kind":"event","event":"turn/start","surface":false,"digest":"aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8"}, - {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8"}, {"key":"event:web/deepseek-search-llm-request","kind":"event","event":"web/deepseek-search-llm-request","surface":false,"digest":"0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52"}, {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3"}, {"key":"event:workspace-root/change","kind":"event","event":"workspace-root/change","surface":false,"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc"}, @@ -77,7 +77,6 @@ {"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc","names":[],"sources":[]}, {"digest":"02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79","names":[],"sources":["packages/extensions/cordis-host-runner/src/index.ts:16"]}, {"digest":"0341d4c3dfcd53253cdc1e789d9130d3cd848b6f8b0706bf92f313a68b39ff23","names":[],"sources":[]}, - {"digest":"041960dcab4a409b4d50f524abbec606e518dc198f84d6a84922155096326592","names":[],"sources":["packages/core/session/src/types.ts:327"]}, {"digest":"04c12e59a9ed4d7a59b642223a9bdd3b4303c1d27873c72c5e487760892bbb08","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:176"]}, {"digest":"05205074b24d8340cfd7995f6cb64779c7f1241490954700115601e264178877","names":[],"sources":[]}, {"digest":"058fc9a6b4fbd5d43437c3a64170002070dfc98e18d87de294b564ae446ca8ae","names":["packages/subagent/subagent/src/catalog.ts#SubagentCatalogEvent"],"sources":["packages/subagent/subagent/src/catalog.ts:32"]}, @@ -120,6 +119,7 @@ {"digest":"13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176","names":[],"sources":[]}, {"digest":"14230f9b8b5797bb7e8c621fa636531cfbde2ffba1ef5f1fd058216ff21952a0","names":[],"sources":[]}, {"digest":"142c37d302aa22a0a57915b5255939d3ca91c1811ca13fddcf84cf76ea00758a","names":[],"sources":[]}, + {"digest":"14e81f18050da9ee77f4bbe28812bb08fcb3e9031dde06720459ffafb7305502","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:182"]}, {"digest":"15196447222782e773eb943c92b18316ce96b9af0f0cfddb6e57ba8274ecc5ff","names":[],"sources":[]}, {"digest":"1528539c63db8b23506f0209a99ce77d8ad138adfbfcee3d4769b7382d93756c","names":[],"sources":["packages/deliverables/tool-present/src/types.ts:15"]}, {"digest":"15495614ccfa9cbdeefb0ec2abd76406435f4c6ff3dae42acae8e09ef42025c9","names":[],"sources":[]}, @@ -173,6 +173,7 @@ {"digest":"260523b412c19ad8c2bb00093b07f64245ff8ba6b2f76c5b545303772ac9704c","names":[],"sources":[]}, {"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78","names":[],"sources":[]}, {"digest":"26c879bdd130e8b8683a6ce588414fad2244783d6573ca399fa0de184a2b0bb1","names":[],"sources":[]}, + {"digest":"26d2d4da493daea93cf37ebb47514f30f290276aa9940bbca96e04a82c049793","names":[],"sources":[]}, {"digest":"2765e9119edf5816ac1ab4c95c5ee32c90403f3742962eff11544f7752d59d2e","names":[],"sources":[]}, {"digest":"277b61f9c6f8170425fa6ffe06cfa14376757a896a4749cb82a687d7364c4fc9","names":[],"sources":[]}, {"digest":"287211846beea1eccb5f9acee00d20388a38fcb2e95858fa2332d6f58529379a","names":[],"sources":["packages/llm/llm/src/types.ts:165"]}, @@ -189,7 +190,6 @@ {"digest":"2da725e554cd89301d829ed9dc45a572c3cd1b93b5e91d0d71f007976d8a0863","names":[],"sources":[]}, {"digest":"2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f","names":["packages/schedule/schedule/src/types.ts#ScheduleChange"],"sources":["packages/schedule/schedule/src/types.ts:232"]}, {"digest":"2e4debca12f2c449f96dc6574f3fbf2fb346193443114a241d01a236362ec48c","names":[],"sources":[]}, - {"digest":"2ea337d0a09fdd6a96c853397f72438c7256bba373b98400c4af8d142b47aaf0","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e","names":["packages/team/agent-team/src/types.ts#TeamMessageSnapshot"],"sources":["packages/team/agent-team/src/types.ts:112"]}, {"digest":"2f1e6a7ebace43d727ae138ddcd352eb3813960009e5805b8c5ac84300c97716","names":["packages/attachment/attachment/src/types.ts#ImageMediaType"],"sources":["packages/attachment/attachment/src/types.ts:8"]}, {"digest":"2f3f201c8846e19c20bb75c02280e3d4eb3c57509e4715f0c0a4d1d4f91a7a06","names":[],"sources":[]}, @@ -235,7 +235,7 @@ {"digest":"3fdf9582c3b5597df104d32d97dab6c6ee3a93794f3034ec6ada6272404ea27f","names":["packages/schedule/schedule/src/types.ts#LegacyAfterScheduleRecord"],"sources":["packages/schedule/schedule/src/types.ts:161"]}, {"digest":"4018a00144474b6c60dc1aa6e5c1f03611c66bd739833779a7d20a511df6d082","names":["packages/team/agent-team/src/types.ts#TeamTaskSnapshot"],"sources":["packages/team/agent-team/src/types.ts:64"]}, {"digest":"408927267422a7b2beb6df354ff7c1406d929a5646554f48adf85eb8372f811c","names":[],"sources":[]}, - {"digest":"41586248fbed6edc749e789f57533377519bb1f5941f8a53149a31e4a3a984d7","names":[],"sources":[]}, + {"digest":"41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049","names":[],"sources":[]}, {"digest":"4208123b50df5006b181481ab45fcf1cde807b88d3fd4d340090bc2e202fac41","names":[],"sources":[]}, {"digest":"42e0916e0dda5f6d1e7bb05d8514717147c036a79c9f36085683469516c1fd3f","names":[],"sources":[]}, {"digest":"4312134fc6f9cad507c31390bd3d147535492dd77621ec517c5e85f853d53a03","names":[],"sources":[]}, @@ -280,7 +280,6 @@ {"digest":"5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777","names":[],"sources":["packages/core/session/src/types.ts:390"]}, {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:289"]}, {"digest":"53cf1704ae0709c7678bcf070c83c619fc48ca1b5c173b74cfa8702f22a8e492","names":[],"sources":[]}, - {"digest":"54588f397f0f084fbde634df6be453defaf348a21fdbec869031951f2d9974d8","names":[],"sources":[]}, {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:370"]}, {"digest":"557e148d30b79ee48645850832b30c717d7c3b64641deb5d6133b8b4e91ee0b8","names":[],"sources":[]}, {"digest":"5654685d7557ec747e74887237065e626a5bdfa426ca43f7fbb0b6fee9b0916c","names":[],"sources":[]}, @@ -301,6 +300,7 @@ {"digest":"5b7abd24d8a133e7d43f7d8a5824e841233f57ddd2288d9923d3443ffa245e16","names":["packages/llm/llm/src/message.ts#SystemPromptSectionState"],"sources":["packages/llm/llm/src/message.ts:34"]}, {"digest":"5bb69b88517f6214f2af4d1a6d2b771e271ad3ad695cc9c2c272069ae698c9bc","names":[],"sources":[]}, {"digest":"5bc66269cfaf614c0ecda8ecb469f23101a7609793fc2b693ac23c4aecdb575e","names":[],"sources":[]}, + {"digest":"5bcaeed5facdbccc89dbc5cb0dee03b710b2f4189b72bae3d805b39f419034d1","names":[],"sources":[]}, {"digest":"5bd310104cfe448e530beb11422d2f791e2e32e8e95fdc528a15f9ca693dae75","names":[],"sources":[]}, {"digest":"5c45bf4c544a7211dcd8ba6ba7e5f1bc39b49e7a9df9d5cbdc8e87c22771b37b","names":[],"sources":[]}, {"digest":"5cb63db9fe57dc09c3a1c2b84c3edf73ff5b62960155d8436a2377a5c43ce32c","names":[],"sources":[]}, @@ -325,6 +325,7 @@ {"digest":"62ecb62dc0fe1b5e70217f8a80c39256a40ee3a1917be14e5ca899d20c35f7fd","names":[],"sources":[]}, {"digest":"63ba8895cc09e4693cf0819fdcd18c084bef195febda5b6a23af279b3852be36","names":[],"sources":[]}, {"digest":"6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f","names":["packages/subagent/subagent/src/descriptor.ts#ContinuableSubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:72"]}, + {"digest":"64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829","names":[],"sources":[]}, {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]}, {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:36"]}, {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]}, @@ -334,7 +335,6 @@ {"digest":"688e853dc149f0d30b31765c12ec7e3be74169bdf1a4c6463a10b945d50cc1b8","names":[],"sources":[]}, {"digest":"68f44f59e91c41395076cb77265981a601680ec8a381bbbeb6ab754ffdc94573","names":[],"sources":[]}, {"digest":"693f4952fb5565da96c06bace8924b098ac2fbc915fde0ff8019701183abc057","names":[],"sources":["packages/llm/llm/src/types.ts:168"]}, - {"digest":"69b87f3f1cbd2e33e2c2d6563a35c4e6a57e521c0f00ca8df508b42835e8da4d","names":[],"sources":[]}, {"digest":"69d238a6e9b08d67f601b1825962963d8d3523cb69ebf6208c697dc5d058c199","names":[],"sources":[]}, {"digest":"6ab45ac76839722df912f3ba50f1c6b41f2d614bde11f1aabfae04117ccdc80d","names":[],"sources":[]}, {"digest":"6b23ed9ce1b397e602788dbe033693bf97642a69e23fcab1cc45bf6f13b6d619","names":[],"sources":[]}, @@ -346,7 +346,6 @@ {"digest":"6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4","names":[],"sources":[]}, {"digest":"6cda0d6d3b4336d83998fe580628426df81c2afbab5d768b8813b56d569120e8","names":[],"sources":[]}, {"digest":"6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65","names":[],"sources":[]}, - {"digest":"6d3098e367bc9ebf4ea907cfe826690cc4892d796672a3904b33d064158da409","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406","names":[],"sources":["packages/preset/agent-preset-registry/src/session.ts:30"]}, {"digest":"6ea608bdc8a7a63d3d23b84c49721325094db88d136482e43a820945295eee3e","names":[],"sources":[]}, {"digest":"6ebcc2dbec9f2dabca9f668ae6d39e877899b180740570f453409db339221df3","names":[],"sources":[]}, @@ -360,12 +359,12 @@ {"digest":"7180844e1066230c5e891f1b9ccd942423b0fe48aac6ded7eef2a285b288a732","names":[],"sources":[]}, {"digest":"719c51f67074f97034a6c94297fe1f4b5d3c8d392c57586dab732aa5398c7a91","names":["packages/llm/llm/src/message.ts#ModelMessageSource"],"sources":["packages/llm/llm/src/message.ts:23"]}, {"digest":"71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:27"]}, + {"digest":"72258a6fae4af8fdb2934cb16af46b7d5c8b7f25f84785164532f237b9b69270","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"72ec79127a9c0d0241b1106a74cc2b24c81ce467170f1c3c93f7b71a9496d227","names":[],"sources":[]}, {"digest":"7382c4fc95fe8c5db65ca4d9da572b115d0dbb818b7f32c22ab040318ffbb4bc","names":[],"sources":[]}, {"digest":"750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5","names":["packages/jobs/jobs/src/types.ts#JobSettleCause"],"sources":["packages/jobs/jobs/src/types.ts:253"]}, {"digest":"7554565be416b0342053ee6a46256c9dab07c487349b4a5f10bab1edc151c619","names":[],"sources":[]}, {"digest":"756b5e23a5cb2c7f486f366a828f7461c88902af21125bd6810881f4ccbff6cc","names":[],"sources":[]}, - {"digest":"758b3558f0398bdd1f5837e7d237c2cf1ebb3967a5e2776f487287d81cc5b923","names":[],"sources":[]}, {"digest":"7624ca28c61ca0eaa4f015140f3cea6e0c16cce2f2960fab5f531203d253903e","names":[],"sources":[]}, {"digest":"763c8a20af487263a0080548274f7437ef4a86e0ba8769127d1ced10a72c664d","names":[],"sources":[]}, {"digest":"76632533f67879dcb346fcae640540dbc89b2472b0bce88c59f7e48fc5c0e668","names":[],"sources":[]}, @@ -381,6 +380,7 @@ {"digest":"7d226b9fd95b4ba213d4237c22e930a91c3c769c95ca7f92977b9d625ba13438","names":["packages/goal/goal/src/domain.ts#GoalChangeMeta"],"sources":["packages/goal/goal/src/domain.ts:44"]}, {"digest":"7d54a5a5e629e2e7783bfac72683bcc5e969e9f43426b9289826aaf294ff6344","names":["packages/feedback/command-feedback/src/types.ts#FeedbackRecord"],"sources":["packages/feedback/command-feedback/src/types.ts:27"]}, {"digest":"7d65acf0a3a43a8f445ce5d3320b42eca492739fc931b2a7516bfb8368dc2c68","names":["packages/llm/llm/src/types.ts#ContentBlockType"],"sources":["packages/llm/llm/src/types.ts:155"]}, + {"digest":"7dd505cd3b36da219ed87f3d7b03061ed8d23b26bc3900603a81d27454b67f69","names":[],"sources":["packages/core/session/src/types.ts:327"]}, {"digest":"7df62978a2b7de8540e714152297743e0a622209a46a5ac9513fc0fad73ca23b","names":[],"sources":[]}, {"digest":"7eaef7a763ba5b949b8464bc8add8980a3a5ab566014b69787aeba71e5dfe07b","names":[],"sources":[]}, {"digest":"7f13860ee89a2d35ce09f958e85a04566cd59cb1de1d73a9619a9b631961dc71","names":[],"sources":[]}, @@ -388,7 +388,6 @@ {"digest":"7f7fd5a6b0064f597534b29ff62ef26e786dffccf5e14f654a7d4fcea2c35f04","names":[],"sources":[]}, {"digest":"7f9365bae9fcb73e1e34061a1acfe0422c1a5fd351848cace9bebbe806f28462","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:36"]}, {"digest":"7f959241c24128b4983b559984811861dc59774b85905c8fa57c6cb0148a3dbc","names":["packages/goal/goal/src/domain.ts#GoalMessageSource"],"sources":["packages/goal/goal/src/domain.ts:47"]}, - {"digest":"7ff387c25ac82a62e5ebb6e1f89ebc0b2330246667eb195c858b7f831fd4d59d","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:161"]}, {"digest":"8064c03c87c357fd1575cb9395ce86e6dcbe2d275bf7717864a02cddf01827d5","names":["packages/llm/llm/src/types.ts#ContentBlock"],"sources":["packages/llm/llm/src/types.ts:157"]}, {"digest":"80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc","names":[],"sources":[]}, {"digest":"8067b0d232c350f189738e60ee3c9939d46ca3b32b45db5525237b077893f649","names":[],"sources":[]}, @@ -412,6 +411,7 @@ {"digest":"85fe96bf15d5c7559eec3bae4d6cf1a76fda9f5be05a29c2830cff560cab0c0d","names":[],"sources":[]}, {"digest":"8620189c8e33582708ece48fd2d20dc4d57912486a17bdbb9aea4c44f7018062","names":[],"sources":[]}, {"digest":"866f7b2dbdc5b421eab3e629312d1c839b75c259633b4b43b50d23bac44d92a0","names":[],"sources":[]}, + {"digest":"86a9b7da960c2a983fe66f1ba8dd92e41b53bff4d8758043bea19378d3a62608","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"86d1d0e9cfebb240421187e3dc37fb71cc38a1501885cf32f8f9adef7b0a2bde","names":["packages/subagent/subagent/src/descriptor.ts#SubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:89"]}, {"digest":"86e1e384495ee09ac2d60c9db3610f1f1fddac2d248f6f1d6000e78054680219","names":["packages/llm/llm/src/message.ts#ContextSnapshotSection"],"sources":["packages/llm/llm/src/message.ts:95"]}, {"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]}, @@ -419,6 +419,7 @@ {"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]}, {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:500"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, + {"digest":"8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, {"digest":"8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad","names":[],"sources":["packages/interaction/permission-presets/src/index.ts:61"]}, {"digest":"8ad45ad053b4d89f8865c17cc9ff3b8748e86045f3f0fb816269a34af2619141","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:31"]}, @@ -432,6 +433,7 @@ {"digest":"8e611bf46821e5003a1605a73560a6f56388295149d449dfe2142d5ec335f29c","names":["packages/llm/llm/src/types.ts#ToolAdditionBlock"],"sources":["packages/llm/llm/src/types.ts:122"]}, {"digest":"8e8155594e07812356b67d732196dda894b0f9c91a5969d51612cf490b0a016d","names":[],"sources":[]}, {"digest":"8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af","names":["packages/schedule/schedule/src/types.ts#OneShotScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:213"]}, + {"digest":"8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710","names":[],"sources":[]}, {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:394"]}, {"digest":"8f324cea3916c0517261e88167def8efb3a9994c1135e23d40ed9fd48f8c7bd4","names":[],"sources":[]}, {"digest":"8f6d609794bf5afc01d7ccf3e03811d32f4b8047f58a2c9a98db0154c2ad7cb9","names":[],"sources":[]}, @@ -446,7 +448,6 @@ {"digest":"93cbbc5a7fd0b1aa1ff1b9a6bb5ec52b073f48e5a5200365c45c0cd54059e1b9","names":[],"sources":["packages/interaction/user-approval/src/types.ts:55"]}, {"digest":"93d38436347f67c9022aacbc4472e283d722bcab8eb73fc376aaf7b6a6b9fb35","names":[],"sources":[]}, {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, - {"digest":"94e41fc6c2fc24fb9dd979f52c2842d385a89ea92ad9ae52315b6420f523f00d","names":[],"sources":[]}, {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:498"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, @@ -461,12 +462,12 @@ {"digest":"99f0e98184709ad10f27bfdeaafb4457d9d2b413f402331764798cdb7d3cbe4d","names":[],"sources":[]}, {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:65"]}, {"digest":"9a410ddf56792b2b7cd4a224a2e54dc4dee30a8e8e6b1c2b9a1d19992b217adc","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:20"]}, - {"digest":"9a8fdf1cc2efb1e06832a5191db0636146cd6f073cc4acc61d6ff8fa813def9f","names":[],"sources":[]}, {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:256"]}, {"digest":"9ac52f0f84fec2eb9f71c2937e497d759db5ca0da4836d93a679d113684141f2","names":[],"sources":[]}, {"digest":"9acbe713f3f641921dd3333b240aa72e176d795327c24e8d9db9b68b16771b49","names":[],"sources":[]}, {"digest":"9b4fd974c124c83743efe030ba4e1250e087505f3f74588716a521fb8d453267","names":[],"sources":[]}, {"digest":"9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:62"]}, + {"digest":"9d42da116fccdc399c2877bb46488c6690e3968c02de6ff2a55e83adc67cc496","names":[],"sources":[]}, {"digest":"9d80129e13edfb6feb03ed327e6085c6ef60b97ad074244b2f5fd4667424a6a4","names":[],"sources":[]}, {"digest":"9e07693fd7cd9babe0688c22c986e4d519ae1c0e40eeea13b2dc583bed2abc86","names":[],"sources":[]}, {"digest":"9e2c06d8653585b33d72d5c1a80da79c8a24a88c284409bca15cc0f0ead5ebfb","names":[],"sources":[]}, @@ -491,6 +492,7 @@ {"digest":"a43327a1739c3fa477f32981071fef7d8ba6ae5f32a84fd70f547b2eee59e93e","names":[],"sources":[]}, {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:392"]}, {"digest":"a6567ccb2e530606b775371eb4fa31468d72084339968e8b0440a516a23b39dc","names":[],"sources":[]}, + {"digest":"a6816f39283ae26f0cd16cfce35724eb676a1f1b57afbc91094a36b2d2a40b2d","names":[],"sources":[]}, {"digest":"a6b41f5bede8094d7bf635be5d69b1bd7a25e006ca9cf9415bceb9322f1a7feb","names":["packages/experimental/hook-protocol/src/types.ts#HookDialect"],"sources":["packages/experimental/hook-protocol/src/types.ts:48"]}, {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, {"digest":"a720757f704a2512e9d2f20da4a093e582472176236a75ab8b8eb7aaff17d85a","names":[],"sources":[]}, @@ -549,6 +551,7 @@ {"digest":"b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0","names":[],"sources":["packages/core/session/src/types.ts:217"]}, {"digest":"b6f94c17dd9bbd7cd57015198b7c7c88407f0e3b89faab176ca3c11c3d864d3e","names":[],"sources":[]}, {"digest":"b70f3e81fe11b7a5f2504fb47a4502fb8d9c8f0731fdfe8ddcaf9b41f5a6e196","names":[],"sources":[]}, + {"digest":"b72ba9c86f4510fc61b7ef4c47005f5f43786cb09915d3ca1e4134fc4503a6ea","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:187"]}, {"digest":"b765ee31033cea463863faf3fc6a0a1b85c47c6a2f13fe1ce833abe56105114b","names":[],"sources":[]}, {"digest":"b79641a9d25e756636dc0c706fdf3c4583ccb7d4920e009e6e86c0759cf4de4c","names":[],"sources":[]}, {"digest":"b79ada42962cad0190a9d465805260567621fa3a4abd757eb31e6016b52d5ab5","names":[],"sources":[]}, @@ -560,6 +563,7 @@ {"digest":"b9305f0ea75ccd6a6061c27fde19f2ab85534f9f3c1a717b573b077ebae0f611","names":[],"sources":[]}, {"digest":"b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26","names":[],"sources":[]}, {"digest":"b993441f8ce7d27b80e619e113e232ae8e62d3d5a8340f6bfe12d8c4c018e62f","names":[],"sources":[]}, + {"digest":"b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8","names":[],"sources":[]}, {"digest":"ba2a1a8f194b1bb21f270713398f6643e206e8ff5f7f26f6d36a88e3f0f0ab10","names":[],"sources":[]}, {"digest":"ba4c40b4381e0dcdfab8fc9fc75b5c9b3e8f09ef56deeb1bec8e703b0ef8cd6d","names":[],"sources":[]}, {"digest":"ba77b58995e36f14bb13886b0493d0a1a63d5db10b1a6cd9f6ac65a72cf832ec","names":[],"sources":[]}, @@ -583,6 +587,7 @@ {"digest":"c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3","names":[],"sources":[]}, {"digest":"c43b119ce579b3e9983a0d3adc4ba402ebb9ba773d89738a2dab01ecf5813943","names":[],"sources":[]}, {"digest":"c460ea99c4124f01e9893c8febbcbd783cadb2d5b11f073ddcd8a9d7e5bf545d","names":[],"sources":["packages/core/session/src/types.ts:345"]}, + {"digest":"c519fc9b5b12fa24780e5d87a511f0b973e06633b8939150449986cffb76ddd7","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:161"]}, {"digest":"c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49","names":[],"sources":[]}, {"digest":"c55827fba7018198772c50e37cb7d3f60a3d8bb6e94b07de72dee0d9f8968005","names":[],"sources":["packages/interaction/user-questions/src/types.ts:134"]}, {"digest":"c5687b1313206a6ff334066047b6a0681611467dc4df8c5a8e71d0b6df39311f","names":[],"sources":[]}, @@ -601,8 +606,8 @@ {"digest":"cda2345a9be9d139df49ccbd16dcba716f3440178bf20ff8b801fda1f5eb77dc","names":[],"sources":[]}, {"digest":"cdca80b8dad24d4e7b1d5a288a8475ba8d8d46be385bd2da85f122ee836f1670","names":[],"sources":[]}, {"digest":"cdee10e87dbed8440d8b6935888624884878efc7af95402e94171b29f173dced","names":[],"sources":["packages/llm/llm-retry/src/types.ts:17"]}, + {"digest":"ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b","names":[],"sources":[]}, {"digest":"cef171adf021a1867d244618a3dbbaafc22beb17c7f3df3ee203393271c8c6f6","names":["packages/core/tool-executor-ptc/src/types.ts#PtcDispatchEventData"],"sources":["packages/core/tool-executor-ptc/src/types.ts:21"]}, - {"digest":"cf751a091c7c75efbd3ca13b26fa0bfa485e0f20b9c175437d3aa33afc2890a1","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:221"]}, {"digest":"cffcdc19881ab61ec0a9ce18743996f7ac44ac8889f34dfac36ae745574aa22f","names":["packages/goal/goal/src/domain.ts#GoalClearChangeMeta"],"sources":["packages/goal/goal/src/domain.ts:35"]}, {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d215701afb7aafbfd63205a6bbb8803aed60810bd613e2dbbc43071c38b6c568","names":[],"sources":["packages/experimental/timeline/src/reminders.ts:14"]}, @@ -620,7 +625,6 @@ {"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:28"]}, {"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]}, {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:62","packages/session/working-directory/src/index.ts:67"]}, - {"digest":"daac534c628bd121b5e9245c31af42588b87f53c3e54f0aa67453151e6245614","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:187"]}, {"digest":"dacf3d5f3e4ff619c1320e64a48dec5e7ecd7870bece65fbd449a0e63adfa521","names":[],"sources":[]}, {"digest":"db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c","names":[],"sources":[]}, {"digest":"db6c5246911d47a7969f6b4cb47c7d0dbbde75c402710b22ace3672fa97bebe0","names":[],"sources":[]}, @@ -639,6 +643,7 @@ {"digest":"df5d9709b7db2a72510dc52052a23f0c38f39730af1504bab8bccabc14fae528","names":[],"sources":[]}, {"digest":"df843efd87c78cf8de98f8e0d0216956cd568d0d0e56a22c853663e274aa1a18","names":[],"sources":[]}, {"digest":"dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd","names":["packages/team/agent-team/src/types.ts#TeamMemberPhase"],"sources":["packages/team/agent-team/src/types.ts:47"]}, + {"digest":"dff922ce762afdc70de374c9fafe7b9a2733f58549e317af799954decb2704be","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:221"]}, {"digest":"e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05","names":[],"sources":[]}, {"digest":"e2ad8f5bcd813f268ffef1b10a12d7ddd2b8ced8b9b6d0275b3f6b7ed094a187","names":[],"sources":[]}, {"digest":"e2d0367e5716bc188435e51718ebff8ce873190625fa93b1c5331102d98758fa","names":[],"sources":[]}, @@ -657,7 +662,6 @@ {"digest":"e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344","names":["packages/schedule/schedule/src/types.ts#EveryScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:220"]}, {"digest":"e6411b09c1d982f789bf741ca74e2bea69df56029847f86a6148e722039ee732","names":[],"sources":[]}, {"digest":"e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:20"]}, - {"digest":"e7302d45b4726043f078badfb5354ad61340da10a381e937e67256ffc495f20f","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:182"]}, {"digest":"e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4","names":[],"sources":[]}, {"digest":"e7ce49f12953583fad217bf80fb9f1463acff2c3e9471a823782661675fb124c","names":[],"sources":[]}, {"digest":"e7e154d47d5fbc5366330fb4dade1f108c6dfe4335044d21ded14b7bf1dce084","names":[],"sources":[]}, @@ -727,7 +731,6 @@ "025f11632cd02aae": {"kind":"object","properties":[{"name":"data","type":"da60ed58a8fa23d7","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"5f22f22ce033e6ce","optional":false}],"indices":[]}, "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, "0341d4c3dfcd5325": {"kind":"literal","value":"product-interaction"}, - "041960dcab4a409b": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"e7302d45b4726043","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "04c12e59a9ed4d7a": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"3d1339bcc98cb537","optional":false}],"indices":[]}, "05205074b24d8340": {"kind":"literal","value":"action-cards"}, "058fc9a6b4fbd5d4": {"kind":"union","types":["0e10d7c096b47e61","5d542ac7bdf13310","8faed5b52ab2d2df","a0f25b5aeeebf2bf","a43327a1739c3fa4","b6896938660a1dfe","cbbe8377ee744964","e2ad8f5bcd813f26"]}, @@ -770,6 +773,7 @@ "13d3d180f977bf78": {"kind":"object","properties":[{"name":"data","type":"1528539c63db8b23","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1a2718b00937b236","optional":false}],"indices":[]}, "14230f9b8b5797bb": {"kind":"literal","value":"chunk"}, "142c37d302aa22a0": {"kind":"literal","value":"always"}, + "14e81f18050da9ee": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"c519fc9b5b12fa24","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "15196447222782e7": {"kind":"object","properties":[{"name":"data","type":"5b6fb1f226ff5640","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"8cdd3fdd295cee53","optional":false}],"indices":[]}, "1528539c63db8b23": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"files","type":"1d9cb3caa96100b1","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "15495614ccfa9cbd": {"kind":"literal","value":"codex"}, @@ -823,6 +827,7 @@ "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, "26718e15e7e395bc": {"kind":"object","properties":[{"name":"data","type":"11f70b595aa76897","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"36d6a9a871d949ea","optional":false}],"indices":[]}, "26c879bdd130e8b8": {"kind":"literal","value":"dispatch"}, + "26d2d4da493daea9": {"kind":"array","element":"b72ba9c86f4510fc"}, "2765e9119edf5816": {"kind":"literal","value":"model"}, "277b61f9c6f81704": {"kind":"literal","value":"file"}, "287211846beea1ec": {"kind":"object","properties":[{"name":"kind","type":"6c1cccb433ddc153","optional":false}],"indices":[]}, @@ -839,7 +844,6 @@ "2da725e554cd8930": {"kind":"literal","value":"fork"}, "2e3523541e942ef6": {"kind":"union","types":["18dc21f12bbac8ad","8e8e91646a5cae3f","e6063d0451dc0202","eea687d437880bd5"]}, "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, - "2ea337d0a09fdd6a": {"kind":"object","properties":[{"name":"inserted","type":"758b3558f0398bdd","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "2eafefdc6f79a492": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"targetId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, @@ -885,7 +889,7 @@ "3fdf9582c3b5597d": {"kind":"object","properties":[{"name":"afterSeconds","type":"0657d3ca5ac4e7bf","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"5b232a9b9bfcc0fc","optional":false},{"name":"prompt","type":"4cd48f3e5108bd6e","optional":false},{"name":"scheduledAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"title","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, "4018a00144474b6c": {"kind":"object","properties":[{"name":"blockedBy","type":"93c33d9687613293","optional":false},{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"ownerId","type":"4cd48f3e5108bd6e","optional":true},{"name":"ownerName","type":"4cd48f3e5108bd6e","optional":true},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"status","type":"b2d2a01e51341a3b","optional":false},{"name":"subject","type":"4cd48f3e5108bd6e","optional":false},{"name":"writeScopes","type":"93c33d9687613293","optional":false}],"indices":[]}, "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, - "41586248fbed6edc": {"kind":"object","properties":[{"name":"data","type":"2ea337d0a09fdd6a","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, + "41b562e6d6c59ac2": {"kind":"object","properties":[{"name":"data","type":"72258a6fae4af8fd","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "4208123b50df5006": {"kind":"object","properties":[{"name":"data","type":"ad0c38a0adb82a94","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"3e0eff5946255ff0","optional":false}],"indices":[]}, "42e0916e0dda5f6d": {"kind":"object","properties":[{"name":"data","type":"7f9365bae9fcb73e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"fe792a6cd4304945","optional":false}],"indices":[]}, "4312134fc6f9cad5": {"kind":"literal","value":"turn/end"}, @@ -930,7 +934,6 @@ "5302e76315127761": {"kind":"object","properties":[{"name":"error","type":"a81059ca06999da1","optional":true},{"name":"message","type":"4b259f7f8f0a44ad","optional":false},{"name":"meta","type":"c592ce75aab73fca","optional":true},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "530da6c0267813bb": {"kind":"union","types":["34d1ab5c5df37818","4f507598cf476214","e7ce49f12953583f","f789af5ab844827e"]}, "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, - "54588f397f0f084f": {"kind":"object","properties":[{"name":"data","type":"041960dcab4a409b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "54f9276a1617d7c1": {"kind":"object","properties":[{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"stream","type":"84bbfdce7d2eab5b","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "557e148d30b79ee4": {"kind":"literal","value":"agent-preset/selected"}, "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, @@ -951,6 +954,7 @@ "5b7abd24d8a133e7": {"kind":"union","types":["792eb6cb1f6bed83","a408aa610f991ff3"]}, "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5bcaeed5facdbccc": {"kind":"array","element":"dff922ce762afdc7"}, "5bd310104cfe448e": {"kind":"literal","value":"resource-cost"}, "5c45bf4c544a7211": {"kind":"object","properties":[{"name":"data","type":"8a9c990773f798ea","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"ae63d9d1080ed894","optional":false}],"indices":[]}, "5cb63db9fe57dc09": {"kind":"literal","value":"teardown"}, @@ -975,6 +979,7 @@ "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, "63ba8895cc09e469": {"kind":"literal","value":"retry"}, "6487b10ba7542f3c": {"kind":"object","properties":[{"name":"agentModel","type":"4cd48f3e5108bd6e","optional":true},{"name":"agentProvider","type":"4cd48f3e5108bd6e","optional":true},{"name":"agentReasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"mode","type":"e5d3828df1ec3e2a","optional":false},{"name":"persona","type":"4cd48f3e5108bd6e","optional":true},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"toolFilter","type":"3cfc3a56502da1f8","optional":true},{"name":"version","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "64b6ec45d21f5aed": {"kind":"object","properties":[{"name":"data","type":"86a9b7da960c2a98","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "6598cd6da253948d": {"kind":"object","properties":[{"name":"context","type":"50cf02d875f8a1f1","optional":false},{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"error","type":"4cd48f3e5108bd6e","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"phase","type":"dfce5db4aa42b7eb","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, "66ba70f6f068da44": {"kind":"object","properties":[{"name":"deferLoading","type":"dacf3d5f3e4ff619","optional":true},{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parameters","type":"0aa62ab51b36c0e6","optional":false}],"indices":[]}, @@ -984,7 +989,6 @@ "688e853dc149f0d3": {"kind":"literal","value":"reasoning-chunks"}, "68f44f59e91c4139": {"kind":"literal","value":"user"}, "693f4952fb5565da": {"kind":"object","properties":[{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"kind","type":"a2be0f0cb59f0d4a","optional":false}],"indices":[]}, - "69b87f3f1cbd2e33": {"kind":"array","element":"cf751a091c7c75ef"}, "69d238a6e9b08d67": {"kind":"literal","value":"interrupted"}, "6ab45ac76839722d": {"kind":"literal","value":"assistant/message"}, "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, @@ -996,7 +1000,6 @@ "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "6cda0d6d3b4336d8": {"kind":"literal","value":"feedback/message-put"}, "6cf082d0fb6034de": {"kind":"literal","value":"producer"}, - "6d3098e367bc9ebf": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"69b87f3f1cbd2e33","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "6e52dd55a1d48954": {"kind":"object","properties":[{"name":"agentPreset","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, @@ -1010,12 +1013,12 @@ "7180844e1066230c": {"kind":"literal","value":"service-stability"}, "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, "71bb3254ec8f1e49": {"kind":"object","properties":[{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"texts","type":"93c33d9687613293","optional":false},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"688e853dc149f0d3","optional":false}],"indices":[]}, + "72258a6fae4af8fd": {"kind":"object","properties":[{"name":"inserted","type":"26d2d4da493daea9","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "72ec79127a9c0d02": {"kind":"array","element":"c592ce75aab73fca"}, "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, "750a2b129d67704d": {"kind":"union","types":["5cb63db9fe57dc09","6cf082d0fb6034de","bab6865794007548"]}, "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, - "758b3558f0398bdd": {"kind":"array","element":"daac534c628bd121"}, "7624ca28c61ca0ea": {"kind":"literal","value":"create"}, "763c8a20af487263": {"kind":"object","properties":[{"name":"data","type":"7d226b9fd95b4ba2","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"237c004c73b6b288","optional":false}],"indices":[]}, "76632533f67879dc": {"kind":"literal","value":"delegation"}, @@ -1031,6 +1034,7 @@ "7d226b9fd95b4ba2": {"kind":"union","types":["1df34a6c086866ff","cffcdc19881ab61e"]}, "7d54a5a5e629e2e7": {"kind":"object","properties":[{"name":"category","type":"3305a4bb6b6c29b4","optional":true},{"name":"text","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, "7d65acf0a3a43a8f": {"kind":"union","types":["1f0133217eeeffd8","277b61f9c6f81704","3c2535ca0a2062f1","4e44c9118152f682","83d6916021eede8f","85f9b505b7bdff1f","fb8b6a2e53cb9cf4"]}, + "7dd505cd3b36da21": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"14e81f18050da9ee","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, @@ -1038,7 +1042,6 @@ "7f7fd5a6b0064f59": {"kind":"object","properties":[{"name":"data","type":"5dd766ccd1702a11","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"10e386801903f9d4","optional":false}],"indices":[]}, "7f9365bae9fcb73e": {"kind":"object","properties":[{"name":"runId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"8465ece5e9d9007c","optional":false}],"indices":[]}, "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "7ff387c25ac82a62": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","3d1339bcc98cb537","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f7cc4903d822e9a","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, @@ -1062,6 +1065,7 @@ "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "866f7b2dbdc5b421": {"kind":"union","types":["1e0b0b66b6f0c53f","1ebc6f9ff3aa9e3a","4a561c111a78d452","68141cbe3994a5ff","a2be0f0cb59f0d4a"]}, + "86a9b7da960c2a98": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"5bcaeed5facdbccc","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "86d1d0e9cfebb240": {"kind":"union","types":["5f758f3de5f00c18","6487b10ba7542f3c"]}, "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "871bfd6f7bb91061": {"kind":"literal","value":"provisioning"}, @@ -1069,6 +1073,7 @@ "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "88a610b831be6d92": {"kind":"object","properties":[{"name":"argumentsDelta","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"type","type":"9b4fd974c124c837","optional":false}],"indices":[]}, "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8a2e3e7a523e622b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9d42da116fccdc39","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8a6e1ec9e8db346b": {"kind":"object","properties":[{"name":"data","type":"119abe2b9c0b2f46","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"b9305f0ea75ccd6a","optional":false}],"indices":[]}, "8a9c990773f798ea": {"kind":"object","properties":[{"name":"preset","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8ad45ad053b4d89f": {"kind":"object","properties":[{"name":"decision","type":"4cd48f3e5108bd6e","optional":false},{"name":"durationMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"exitCode","type":"0657d3ca5ac4e7bf","optional":true},{"name":"handlerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"point","type":"4cd48f3e5108bd6e","optional":false},{"name":"stderrSummary","type":"4cd48f3e5108bd6e","optional":true},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, @@ -1082,6 +1087,7 @@ "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, "8e8155594e078123": {"kind":"literal","value":"workspace/changes"}, "8e8e91646a5cae3f": {"kind":"object","properties":[{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"operation","type":"26c879bdd130e8b8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, + "8ecc75abd481f9ea": {"kind":"object","properties":[{"name":"data","type":"7dd505cd3b36da21","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "8f1062573ea91841": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"63ba8895cc09e469","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, "8f6d609794bf5afc": {"kind":"tuple","elements":[{"type":"4e88776858652856","optional":false,"rest":false}]}, @@ -1096,7 +1102,6 @@ "93cbbc5a7fd0b1aa": {"kind":"object","properties":[{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"outcome","type":"930c1cd289def119","optional":false}],"indices":[]}, "93d38436347f67c9": {"kind":"literal","value":0}, "94c56aeb1564ad73": {"kind":"literal","value":"in_progress"}, - "94e41fc6c2fc24fb": {"kind":"object","properties":[{"name":"data","type":"daac534c628bd121","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "95080295115fbd83": {"kind":"object","properties":[{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"5abab3a27fd27366","optional":false}],"indices":[]}, "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, @@ -1111,12 +1116,12 @@ "99f0e98184709ad1": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, "9a2a9029f8d7ede0": {"kind":"object","properties":[{"name":"content","type":"8f6d609794bf5afc","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false}],"indices":[]}, "9a410ddf56792b2b": {"kind":"object","properties":[{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"phase","type":"4cd48f3e5108bd6e","optional":true},{"name":"runId","type":"4cd48f3e5108bd6e","optional":false},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "9a8fdf1cc2efb1e0": {"kind":"object","properties":[{"name":"data","type":"6d3098e367bc9ebf","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "9a930283b91d493d": {"kind":"object","properties":[{"name":"adapterDefaults","type":"326a9bfda27dda58","optional":true},{"name":"config","type":"67d5f73ceae82f52","optional":false},{"name":"system","type":"fcf427290c6213c2","optional":true},{"name":"tools","type":"a0baff42eb900561","optional":true}],"indices":[]}, "9ac52f0f84fec2eb": {"kind":"literal","value":"model-selection"}, "9acbe713f3f64192": {"kind":"literal","value":"image/offload"}, "9b4fd974c124c837": {"kind":"literal","value":"tool-call-delta"}, "9c001ecb5e1d3c38": {"kind":"object","properties":[{"name":"max_tokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messages","type":"b993441f8ce7d27b","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"thinking","type":"37ff65426bcf130f","optional":true},{"name":"tools","type":"4aed17ec726b5397","optional":false}],"indices":[]}, + "9d42da116fccdc39": {"kind":"literal","value":"cua-held-inputs"}, "9d80129e13edfb6f": {"kind":"literal","value":"other"}, "9e07693fd7cd9bab": {"kind":"literal","value":"ask"}, "9e2c06d8653585b3": {"kind":"array","element":"1cde1bedde79c5e8"}, @@ -1141,6 +1146,7 @@ "a43327a1739c3fa4": {"kind":"object","properties":[{"name":"childCreatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":true},{"name":"mode","type":"fc351843b8ecbd05","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"137ac60e26bcb192","optional":false}],"indices":[]}, "a4afec59b75aad5d": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "a6567ccb2e530606": {"kind":"object","properties":[{"name":"data","type":"0d47a8f3d847243c","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"0a8a062bc9c3c0d9","optional":false}],"indices":[]}, + "a6816f39283ae26f": {"kind":"literal","value":"cua-inputs-released"}, "a6b41f5bede8094d": {"kind":"union","types":["15495614ccfa9cbd","aff60ef947c18b01"]}, "a6da9ad5d42ae83a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"runId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, @@ -1199,6 +1205,7 @@ "b6ef9c6210be8350": {"kind":"object","properties":[{"name":"kind","type":"1ebc6f9ff3aa9e3a","optional":false}],"indices":[]}, "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b72ba9c86f4510fc": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"c519fc9b5b12fa24","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "b765ee31033cea46": {"kind":"literal","value":"set"}, "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, "b79ada42962cad01": {"kind":"object","properties":[{"name":"data","type":"86d1d0e9cfebb240","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"5ebce1317eacd2c1","optional":false}],"indices":[]}, @@ -1210,6 +1217,7 @@ "b9305f0ea75ccd6a": {"kind":"literal","value":"hook/invoked"}, "b978cff734e62143": {"kind":"object","properties":[{"name":"data","type":"79ddc907312f97cf","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"af0750d32d97d47b","optional":false}],"indices":[]}, "b993441f8ce7d27b": {"kind":"tuple","elements":[{"type":"9a2a9029f8d7ede0","optional":false,"rest":false}]}, + "b9bcecf9562bc661": {"kind":"object","properties":[{"name":"data","type":"b72ba9c86f4510fc","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "ba77b58995e36f14": {"kind":"array","element":"07e1a58c58b593f5"}, @@ -1233,6 +1241,7 @@ "c2f49004d9ae38a9": {"kind":"union","types":["1ebc6f9ff3aa9e3a","b57a2889408de36e","ef226a90ddac6cd8"]}, "c43b119ce579b3e9": {"kind":"literal","value":"paused"}, "c460ea99c4124f01": {"kind":"object","properties":[{"name":"message","type":"04c12e59a9ed4d7a","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "c519fc9b5b12fa24": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","3d1339bcc98cb537","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f7cc4903d822e9a","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8a2e3e7a523e622b","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","ce6e647c9e653b5d","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, @@ -1251,8 +1260,8 @@ "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cdca80b8dad24d4e": {"kind":"literal","value":"tool-workflow/run-start"}, "cdee10e87dbed844": {"kind":"object","properties":[{"name":"delayMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"maxRetries","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mode","type":"3bc287e765d58dc3","optional":false},{"name":"policyKey","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"retry","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ce6e647c9e653b5d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a6816f39283ae26f","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cef171adf021a186": {"kind":"object","properties":[{"name":"arguments","type":"bbc5696e3f13c758","optional":false},{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"error","type":"a81059ca06999da1","optional":true},{"name":"isError","type":"aa93010d0e521ad7","optional":false},{"name":"meta","type":"c592ce75aab73fca","optional":true},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parentCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "cf751a091c7c75ef": {"kind":"union","types":["04c12e59a9ed4d7a","4b259f7f8f0a44ad","daac534c628bd121","e7302d45b4726043","fa87537f4a9c1e25"]}, "cffcdc19881ab61e": {"kind":"object","properties":[{"name":"cleared","type":"0b6d718c693fdf7f","optional":false},{"name":"clearedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"kind","type":"237c004c73b6b288","optional":false},{"name":"operation","type":"e7e154d47d5fbc53","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "d0fbb0ca1bbba059": {"kind":"literal","value":"delete"}, "d215701afb7aafbf": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"c77ac037cb8af460","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, @@ -1270,7 +1279,6 @@ "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, "da60ed58a8fa23d7": {"kind":"object","properties":[{"name":"cwd","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "daac534c628bd121": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"7ff387c25ac82a62","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "dacf3d5f3e4ff619": {"kind":"literal","value":true}, "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, @@ -1289,6 +1297,7 @@ "df5d9709b7db2a72": {"kind":"literal","value":"positive"}, "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, "dfce5db4aa42b7eb": {"kind":"union","types":["871bfd6f7bb91061","b57a2889408de36e","c8e6f48878cc2a2f"]}, + "dff922ce762afdc7": {"kind":"union","types":["04c12e59a9ed4d7a","14e81f18050da9ee","4b259f7f8f0a44ad","b72ba9c86f4510fc","fa87537f4a9c1e25"]}, "e0a787e6ec76c7c9": {"kind":"object","properties":[{"name":"data","type":"ef11a3b7fa2033ae","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"c219efbdfd53b836","optional":false}],"indices":[]}, "e2ad8f5bcd813f26": {"kind":"object","properties":[{"name":"childCreatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"mode","type":"e5d3828df1ec3e2a","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "e2d0367e5716bc18": {"kind":"literal","value":"compaction/start"}, @@ -1307,7 +1316,6 @@ "e6063d0451dc0202": {"kind":"object","properties":[{"name":"acceptedAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"operation","type":"26c879bdd130e8b8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "e6411b09c1d982f7": {"kind":"literal","value":"parent"}, "e72269f931559e90": {"kind":"object","properties":[{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"texts","type":"93c33d9687613293","optional":false},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"f9cfc89e8fe085b4","optional":false}],"indices":[]}, - "e7302d45b4726043": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"7ff387c25ac82a62","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "e75916628f3f10c2": {"kind":"object","properties":[{"name":"data","type":"8ad45ad053b4d89f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"a3a259a1aa5401af","optional":false}],"indices":[]}, "e7ce49f12953583f": {"kind":"literal","value":"initial"}, "e7e154d47d5fbc53": {"kind":"literal","value":"clear"}, diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index ccba1e55d8..0d3db58b7f 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -154,15 +154,23 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. * Release one Agent's retained program environment with the dedicated runtime's owner release. The program * process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` * call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native - * connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's + * connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent's * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. - * @returns Completion after the process has exited and its output has drained. - * @throws When the process cleanup fails. + * @returns Completion after the process has exited, its output has drained, and held-input cleanup has settled. + * @throws When environment or input cleanup fails, reporting both causes if both fail. */ release(agent: Agent): Promise +/** + * Release the Agent's tracked input while retaining its program variables and application grants. + * Providers without held-input state support retain their existing cancellation behavior. + * @param agent - Owner of the input to release. + * @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed. + */ +releaseInputs(agent: Agent): Promise + /** * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. * A host that forwards screenshots outside a model request reads the same request version with it, so the diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 2bed7a57e3..8170748e7e 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -154,15 +154,23 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. * Release one Agent's retained program environment with the dedicated runtime's owner release. The program * process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` * call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native - * connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's + * connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent's * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. - * @returns Completion after the process has exited and its output has drained. - * @throws When the process cleanup fails. + * @returns Completion after the process has exited, its output has drained, and held-input cleanup has settled. + * @throws When environment or input cleanup fails, reporting both causes if both fail. */ release(agent: Agent): Promise +/** + * Release the Agent's tracked input while retaining its program variables and application grants. + * Providers without held-input state support retain their existing cancellation behavior. + * @param agent - Owner of the input to release. + * @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed. + */ +releaseInputs(agent: Agent): Promise + /** * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. * A host that forwards screenshots outside a model request reads the same request version with it, so the diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml new file mode 100644 index 0000000000..2bbea41110 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +/: + en: 9256c8b808ebc45d + zh: ca6524b78cd7f365 +/cua-reports-held-input-after-programs: + en: 37252a5d19c7fe09 + zh: f1b33b7da3935155 +/cua-reports-held-input-after-programs/change: + en: 80ab79f78e26ff43 + zh: e6ba8ac29eaabf50 +/cua-reports-held-input-after-programs/migration: + en: c26899347e7a24c9 + zh: ae78a24c58d6f80f diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md new file mode 100644 index 0000000000..e04619385b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: Explicit CUA input on macOS and Windows persists across programs and turns, with system reminders after successful programs. +--- +# CUA reports held input after programs + +English | [中文](guide.zh.md) + +## Change + +On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, environment reset and disposal request release in reverse dispatch order. On disconnect the helper attempts a final release. Windows silently discards the disconnected owner’s records if that attempt fails or times out. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, cleanup sends an up for each input the helper still holds. If you also hold the same key or button, that up may interrupt your press. A focus change sends the up to the desktop without reactivating the original window. + +## Migration + +1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. +2. Upgrade the platform package and helper together. A custom `helperPath` must accept `getHeldInputs({})` and `releaseHeldInputs({})` on the same connection that dispatched the input. +3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. When a program fails or is cancelled during execution, it waits for cleanup. If the program succeeds but a post-execute policy rejects the output, the tool returns the policy error and CUA finishes cleanup independently. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md new file mode 100644 index 0000000000..96527ce8c3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: macOS 和 Windows 的 CUA 显式输入跨程序和回合保持,成功结束的程序通过 system reminder 报告持有状态。 +--- +# CUA 在程序结束后报告持有输入 + +[English](guide.md) | 中文 + +## 变更 + +macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、环境重置和销毁时会请求按派发顺序的反序释放。断连时,helper 会最后尝试释放。若失败或超时,Windows helper 会静默丢弃该连接的持有记录。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 清理时会为 helper 仍持有的输入发送 up。如果你也按住同一个键或按钮,这次 up 可能打断你的按压。焦点变化后,up 发往当前桌面,原窗口不会被重新激活。 + +## 迁移 + +1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 +2. 同步升级平台包和 helper。自定义 `helperPath` 必须在派发输入的同一条连接上接受 `getHeldInputs({})` 和 `releaseHeldInputs({})`。 +3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序执行中失败或取消时,会等待自身的清理。如果程序执行成功,但后置策略拒绝结果,工具返回策略错误,CUA 单独等待原生释放确认。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 84db53e338..71fc1dcb96 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,14 +15,14 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-cua-macos/use-this-package: - en: c529fedb203d7449 - zh: 3c3536b007fe626a + en: f6818a200b1abff1 + zh: 39d8eb55397546b5 /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 6097d7d03bc8dfad - zh: 0978077447118d64 + en: 4764629c9d31b705 + zh: 107fa3b77bce0734 /deepseek-ai-dsh-cua-macos/understand-the-implementation: - en: d441fbe64f97ddd9 - zh: 821af0f6ac8bb225 + en: 812aa05e9fc15883 + zh: bacb60868d67bd1d /deepseek-ai-dsh-cua-macos/further-exploration: en: ff9fac614001a98f zh: 329678941154aaea @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work: - en: c2351f259e56b220 - zh: 9acccae181af616e + en: e02532b63468b1e6 + zh: 6653e74e3e702da9 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 14b779be60..33b5c2478d 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -88,7 +88,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-m `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. For `pressKey`, `click`, and `drag`, use `command`, `shift`, `option`/`alt`, `control`/`ctrl`, or `fn`. Only `pressKey` accepts `cmd` as a modifier alias for `command`. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code` or `cua_run_code`. The first down holds the key across subsequent tool calls. For an ordinary key already held by this execution, each additional down sends one key-down marked as a repeat to the original process. Choose the interval between calls. A control can filter synthetic repeats, so check its response. One up releases the key. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. +For a long press, call `app.sendKeyEvent('w', 'down')`. Explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -128,7 +128,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Ordinary `mouseMove(target)` defaults to AX hover. Without both `AXShowAlternateUI` and `AXShowDefaultUI` on an enabled target or ancestor, it returns `HOVER_UNAVAILABLE` without prompting. Only when the task requires physical movement should the main task call `win.mouseMove(target, { useSystemInput: true })`. On approval the Host rechecks the window and point and dispatches this move. Pass `useSystemInput: true` on every physical move. Later explicit moves reuse the decision until the session closes or DSH restarts. Omitting the option or passing `false` uses AX. Refusal sends no input. -`win.toggleMouse(button, direction)` sends a window event at the current cursor by default. A press must hit the selected foreground window or it returns `FOREGROUND_REQUIRED`. A release can reach that window after the cursor leaves or focus changes. For a control that reads system button state, pass `{ useSystemInput: true }` on both press and release. This shares the drag approval. Moving the mouse while the button is held can drag items. The end of the turn or connection releases an outstanding system button. +`win.toggleMouse(button, direction)` sends a window event at the current cursor by default. Down must hit the selected foreground window. For system button state, pass `{ useSystemInput: true }` on down; this shares the drag approval. Up always uses the saved route, even after focus changes or window closure. System-button cleanup still releases at the current pointer if the original process exits. PID-directed release verifies the saved process identity and skips an exited or reused PID. By default, drag posts mouse events to the target window. For controls that need system button state, use `win.drag(from, to, { useSystemInput: true })`. This shares the session permission for system-pointer moves. The start and path must hit the foreground window. Cancellation or loss of the target releases the button at the last posted point. @@ -155,6 +155,8 @@ Element clicks use opaque element IDs from the current snapshot. Left clicks sup ## Understand the implementation +The shared helper's `HeldInputs` records connection, process generation, application/window and actual input route before dispatch. One lock orders posts, state queries and releases. Program middleware queries native state after successful execution and defers a logged reminder to the outer tool result. Failure and cancellation close input admission and await `releaseHeldInputs` using an independent bounded request. Native connection shutdown cancels and joins in-flight work before fallback release. A killed host relies on that disconnect path; host callbacks cannot be guaranteed. +
Dispatch and resource ownership @@ -236,7 +238,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -248,7 +250,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. @@ -271,11 +275,11 @@ External monitoring covers session-stream input; PID-directed background input a The native operation deadline (`timeoutMs`), per-AX-call timeout (`axTimeoutMs`), and response size limit (`maxResponseBytes`) still apply to larger tree reads. -The queue orders individual native requests. Holding an app object does not reserve its application across a Session; [continuous interaction](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md) grants no cross-call ownership. Capture RPCs that never return occupy the single capture slot; creating new app objects does not reset that system connection. +The queue orders individual native requests. Holding an app object does not reserve its application across a Session; [continuous interaction](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md) does not reserve an application across calls. Capture RPCs that never return occupy the single capture slot; creating new app objects does not reset that system connection. -- Window-directed button presses require an explicit release even if the program ends. Send up to the same window in a `finally` block. +- The native acknowledgement confirms event dispatch, not application processing. If turn cleanup is refused, times out, or loses its connection, CUA reports the uncertainty and blocks all CUA operations in that task. Inspect the desktop manually before starting a new task. - macOS 14 is the minimum supported version; settings navigation, drag acceptance, and permission refresh require qualification on each supported release. If macOS requires quitting and reopening the helper after a Screen Recording change, its preflight check can remain denied until that restart. The guide can be dismissed without terminating other connections. - The guide closes when its selected settings window leaves the visible-window list, including when a Space switch or minimization removes it. Request permission again after returning to reopen the guide. - This provider supports macOS. For Windows, see the [Windows provider](../cua-windows/README.md#setup). Browser tabs, AX diffs, unassociated system panels and accessory-only apps are unsupported. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 3767eedfc9..989a0197c0 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -88,7 +88,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。`pressKey`、`click` 和 `drag` 都接受修饰键 `command`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`。只有 `pressKey` 的修饰键参数还接受 `command` 的别名 `cmd`。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时,在 `run_code` 或 `cua_run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久。控件可能过滤模拟的重复事件,可通过控件的实际变化确认效果。松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 +长按时调用 `app.sendKeyEvent('w', 'down')`。显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -128,7 +128,7 @@ inspect(await window.getScreenshot()) 普通 `mouseMove(target)` 默认通过辅助功能悬停。如果目标或其祖先没有同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`,则返回 `HOVER_UNAVAILABLE`,不会弹窗。只有任务确实需要移动用户的鼠标时,主任务才调用 `win.mouseMove(target, { useSystemInput: true })`。用户允许后,Host 重新检查窗口和目标位置,再执行本次移动。每次移动系统指针都要显式传 `useSystemInput: true`。省略参数或传 `false` 时使用辅助功能悬停。拒绝时不派发输入。会话记住此次选择,直到关闭会话或重启 DSH。 -默认情况下,`win.toggleMouse(button, direction)` 在当前指针位置向所选窗口发送事件。按下要求指针命中前台应用的所选窗口,否则返回 `FOREGROUND_REQUIRED`。松开允许指针移出窗口或应用失去焦点。只有控件需要读取系统鼠标键状态时,才在按下和松开时都传 `{ useSystemInput: true }`。系统模式与拖动共用会话审批,按住期间用户移动鼠标也可能触发拖动。任务回合结束或连接关闭时会松开剩余的系统按键。 +`win.toggleMouse(button, direction)` 默认向窗口发送当前鼠标位置的事件。按下时必须命中选定的前台窗口。需要系统按钮状态时,在 `down` 上传入 `{ useSystemInput: true }`,沿用拖动审批。`up` 始终使用保存的输入方式和窗口,即使焦点改变或窗口关闭也如此。原进程退出后,系统按钮清理仍在当前鼠标位置释放;定向释放会检查保存的进程身份,跳过已退出或复用的 PID。 默认拖动向目标窗口发送鼠标事件。需要系统鼠标按键状态的控件可使用 `win.drag(from, to, { useSystemInput: true })`。该操作与系统指针移动共用会话授权,起点和拖动路径必须位于可接收输入的前台窗口内。取消或失去目标窗口时,helper 在最后投递的位置释放鼠标键。 @@ -155,6 +155,8 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ## 理解实现 +共享 helper 的 `HeldInputs` 在派发前记录连接、进程代次、应用或窗口和实际输入方式。同一把锁维护派发、状态查询和释放。程序中间件在成功执行后查询原生状态,并把已记录的提醒附加到外层工具结果。失败和取消会关闭输入准入,通过独立且有超时限制的请求等待 `releaseHeldInputs`。原生连接关闭会先取消并等待在途操作,再做兜底释放。宿主被强杀时依赖断连清理,无法保证宿主回调执行。 +
操作分派与资源归属 @@ -236,7 +238,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -248,7 +250,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. @@ -271,11 +275,11 @@ Pass useSystemInput: true only when the task requires system keyboard or mouse i 读取较大的树仍受原生操作超时(`timeoutMs`)、单次 AX 调用超时(`axTimeoutMs`)和响应大小限制(`maxResponseBytes`)约束。 -队列只排序单次原生请求。持有 app 对象不会为 Session 保留应用,[连续交互](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)不分配跨调用所有权。一直不返回的系统截图 RPC 会占用唯一捕获槽位,重新创建 app 对象不会重置该系统连接。 +队列只排序单次原生请求。持有 app 对象不会为 Session 保留应用,[连续交互](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)不在调用之间独占应用。一直不返回的系统截图 RPC 会占用唯一捕获槽位,重新创建 app 对象不会重置该系统连接。 -- 默认窗口模式下,程序结束时不会自动补发松开事件。调用方应在 `finally` 中向原窗口发送 `up`。 +- 原生确认表示事件已派发,不表示应用已处理。回合清理被拒绝、超时或断连时,CUA 会报告不确定结果,并禁止该任务的全部 CUA 操作。请手动检查桌面状态后再创建新任务。 - 最低支持 macOS 14;设置导航、拖放接收和权限刷新需要在各支持版本验收。若 macOS 要求在修改屏幕录制权限后退出并重新打开 helper,权限检查在重启前可能仍返回未授权。可以关闭引导框,不必终止其他连接。 - 所选设置窗口离开可见窗口列表时,引导框会关闭,包括切换桌面空间或最小化导致窗口不再可见的情况。返回后再次申请权限可重新打开引导。 - 本提供方适用于 macOS。Windows 的配置见 [Windows 提供方](../cua-windows/README.zh.md#setup)。不支持浏览器标签、AX 差分、无法确认应用归属的系统面板和仅后台辅助类型的应用。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 9fe20454b2..cf416c0a78 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: da316afc1edbe50e zh: a150c1dacc689f4b /dsh-cua-native-helper/observation-and-input: - en: 4821c4e278a5c0bf - zh: 53105c1d7e175a89 + en: d52f2d056703e787 + zh: 70993f7d024d831d /dsh-cua-native-helper/verification: en: 40bb7339f914bb9a zh: 272a3aae64f55d87 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 7191139c72..420b9a7fb8 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -104,7 +104,7 @@ Input target discovery uses the same range recovery as observation. All recovery Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt. -Window-directed `toggleMouse` posts one press or release to the selected process at the current pointer. A press must hit the foreground window; a release may be outside. Explicit `useSystemInput` posts through the HID event tap. The connection that pressed the button can move it with system `mouseMove` on that window or release it through the same window handle. The Host requests release at turn end; disconnect also releases the button. +Window-directed `toggleMouse` posts one press or release to the selected process at the current pointer. A press must hit the foreground window; a release may be outside. Explicit `useSystemInput` posts through the HID event tap. The connection that pressed the button can move it with system `mouseMove` on that window or release it through the same window handle. Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and default drag validate window ownership and bounds, then post to the target PID and window. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. An explicit `useSystemInput: true` drag posts through the HID event tap, checks the foreground window at the start and each movement, and supplies one gesture event number and per-segment deltas. Cancellation releases at the last posted point. @@ -114,7 +114,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host associates directional key events with one `run_code` or `cua_run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. A repeated down from the owner posts one key-down with `keyboardEventAutorepeat` set and reuses the existing record. The event is posted to the recipient PID. An AppKit view can receive the initial down and final up while filtering the marked repeat. Repeats, explicit up and cleanup verify the original process identity. A conflicting down or up reports the key and whether another session or another run holds it. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. +`HeldInputs` records the requesting connection, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection’s holds, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. `releaseHeldInputs` returns the records whose up events were dispatched, for confirmed cleanup notices. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 3fe04ab12f..6c3ba13175 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -104,7 +104,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 -窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemInput` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。Host 在回合结束时请求清理,连接关闭也会松开按键。 +窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemInput` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。 点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和默认拖动核实窗口归属和边界后,向目标进程和窗口投递事件。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。显式传入 `useSystemInput: true` 的拖动通过 HID 投递,起点及每段移动都要命中目标前台窗口。手势共用事件号,每段携带位移。取消时在最后投递的位置松开鼠标键。 @@ -114,7 +114,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为每次 `run_code` 或 `cua_run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,向接收进程发送一次带 `keyboardEventAutorepeat` 标志的按下事件。AppKit 视图可能只收到首次按下和最终松开,过滤中间的重复事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 +`HeldInputs` 在派发前记录请求所属的连接、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告当前连接的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 4882209c14..47a66d7552 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -81,15 +81,17 @@ actor AXWorker { private let maxClickHoldMs: Int private let sessionState: @Sendable () -> Bool? private var access: AXAccess? - private let heldKeys: HeldKeys + private let connectionID: UUID + private let heldInputs: HeldInputs private var keyboard: KeyboardInput? private var pointer: WindowPointerInput? private var hovers: [String: AXHover] = [:] private var closed = false - init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, heldKeys: HeldKeys = HeldKeys(), + init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, heldInputs: HeldInputs = HeldInputs(), connectionID: UUID = UUID(), sessionState: @escaping @Sendable () -> Bool? = NativePlatform.sessionLocked) { - self.heldKeys = heldKeys + self.heldInputs = heldInputs + self.connectionID = connectionID self.cancellation = cancellation self.axTimeout = axTimeout self.textEventInterval = textEventInterval @@ -119,8 +121,8 @@ actor AXWorker { if let keyboard, let pointer { return (keyboard, pointer) } let poster = PIDEventPoster() let latch = cancellation - let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, held: heldKeys, checkCancellation: { try latch.check() }) - let mouse = WindowPointerInput(poster: poster, checkCancellation: { try latch.check() }) + let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, held: heldInputs, connection: connectionID, checkCancellation: { try latch.check() }) + let mouse = WindowPointerInput(poster: poster, held: heldInputs, checkCancellation: { try latch.check() }) keyboard = key; pointer = mouse return (key, mouse) } @@ -210,17 +212,13 @@ actor AXWorker { trace: ScreenshotTrace? = nil) async throws -> DriverOutcome { try cancellation.check() guard !closed else { throw NativeFailure(code: "NATIVE_CLOSED", message: "Helper is closing") } - if method == "releaseHeldKeys" { - try keyboard?.releaseHeldKeys(run: params.string("runId")) - return .result(Self.actionResult) - } if method == "getActionSchema" { return .result(try ActionSchema.parameter(action: params.string("action"))) } var recovery = AXChildRecoveryBudget(maxElements: NativeProtocol.elementRange.upperBound, timeout: axTimeout) if method == "sendKeyEvent", try params.string("direction") == "up" { let handle = try params.string("appHandle") - let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, run: params.string("runId"), useSystemInput: params.optionalBoolean("useSystemInput") ?? false) { + let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, useSystemInput: params.optionalBoolean("useSystemInput") ?? false) { try NativePlatform.requireUnlocked(observeSession()) try NativePlatform.requireAccessibility() return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog, budget: &recovery) @@ -363,7 +361,7 @@ actor AXWorker { maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange))) case "sendKeyEvent": let system = try params.optionalBoolean("useSystemInput") ?? false - try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId"), useSystemInput: system) { + try inputs().0.keyDown(params.string("key"), app: handle, useSystemInput: system) { if system { return identity } return try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) } @@ -389,22 +387,16 @@ actor AXWorker { suffix: params.optionalString("suffix"), mode: params.optionalString("selectionType") ?? "text") case "toggleMouse": let id = try params.windowID() - let isDown = try params.string("direction") == "down" - let window: WindowInfo - if isDown { - guard NativePlatform.frontPID() == identity.pid else { - throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "Activate the selected application before pressing a mouse button") - } - window = try ax().coordinateWindow(identity, id, budget: &recovery).window - } else { - window = try NativePlatform.ownedWindow(identity.pid, id) + guard NativePlatform.frontPID() == identity.pid else { + throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "Activate the selected application before pressing a mouse button") } + let window = try ax().coordinateWindow(identity, id, budget: &recovery).window let route = WindowRoute(owner: identity, windowID: id, bounds: window.bounds) if try params.optionalBoolean("useSystemInput") == true { return .systemButtonDown(route, try WindowPointerInput.button(params.string("mouseButton"))) } - try await inputs().1.toggleMouse(in: route, - button: params.string("mouseButton"), isDown: isDown) + try await inputs().1.mouseDown(owner: .init(connection: connectionID, app: handle), + in: route, button: params.string("mouseButton")) case "click", "mouseMove": let useSystemInput = try params.optionalBoolean("useSystemInput") ?? false let holdMs = params.contains("holdMs") ? try params.integer("holdMs", in: 0...maxClickHoldMs) : nil @@ -558,8 +550,6 @@ actor AXWorker { .object(["dispatched": .bool(true), "hoverRoute": .string(route), "systemPointerMoved": .bool(pointerMoved)]) } func shutdown() { - do { try keyboard?.releaseHeldKeys() } - catch { fputs("Could not release held keys on disconnect: \(error)\n", stderr) } closed = true; snapshots.removeAll(); observedWindowBounds.removeAll(); targets.removeAll(); hovers.removeAll() access = nil; keyboard = nil; pointer = nil } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift new file mode 100644 index 0000000000..861dfb7f48 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -0,0 +1,250 @@ +// One ledger orders key and pointer posts across the shared helper's workers and connections. +import CoreGraphics +import Foundation + +/// The lock covers registration, dispatch, explicit release, and reverse-order cleanup. +final class HeldInputs: @unchecked Sendable { + struct Owner: Equatable { + let connection: UUID + let app: String + } + enum Mode: Equatable { + case keyboard(CGKeyCode, CGEventFlags, String, system: Bool) + case windowPointer(CGMouseButton, UInt32) + case systemPointer(CGMouseButton, UInt32) + } + private struct Press { + let owner: Owner + let recipient: ProcessIdentity + let mode: Mode + let up: CGEvent + let post: (CGEvent) -> Void + let prepareRelease: ((CGEvent) throws -> Void)? + } + private let lock = NSLock() + private var pressed: [Press] = [] + + private let systemFlags: () -> CGEventFlags + + init(systemFlags: @escaping () -> CGEventFlags = { CGEventSource.flagsState(.combinedSessionState) }) { + self.systemFlags = systemFlags + } + + func snapshot(pid: Int32, system: Bool = false) -> [CGKeyCode: CGEventFlags] { + lock.withLock { + Dictionary(uniqueKeysWithValues: pressed.compactMap { + guard case .keyboard(let code, let flag, _, let viaSystem) = $0.mode, viaSystem == system, + system || $0.recipient.pid == pid else { return nil } + return (code, flag) + }) + } + } + + private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { + let source = holder.connection != caller.connection ? "another session" : "a different application handle" + return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it before using it.") + } + + /// Repeats retain the original recipient and do not change the cleanup order. + func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, system: Bool = false) throws -> Bool { + try lock.withLock { + guard let key = pressed.first(where: { $0.owner == owner && $0.mode.keyCode == code }) else { return false } + guard key.mode.isSystem == system else { throw RequestParameters.invalid("Match useSystemInput to the held key") } + guard case .keyboard(_, let flag, _, _) = key.mode, flag.isEmpty, down.type == .keyDown else { + throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") + } + try NativePlatform.verify(key.recipient) + down.flags = flags(for: key.recipient, system: system) + down.setIntegerValueField(.keyboardEventAutorepeat, value: 1) + key.post(down) + return true + } + } + + func keyDown(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, + down: CGEvent, up: CGEvent, system: Bool = false, post: @escaping (CGEvent) -> Void) throws { + try lock.withLock { + if let key = pressed.first(where: { $0.mode.keyCode == code && (($0.mode.isSystem && system) || $0.recipient.pid == recipient.pid) }) { + throw conflict(name, holder: key.owner, caller: owner) + } + pressed.append(Press(owner: owner, recipient: recipient, mode: .keyboard(code, flag, name, system: system), up: up, + post: post, prepareRelease: nil)) + down.flags = flags(for: recipient, system: system) + post(down) + } + } + + private func flags(for recipient: ProcessIdentity, system: Bool, releasing: CGEventFlags = []) -> CGEventFlags { + pressed.reduce(into: system ? systemFlags().subtracting(releasing) : CGEventFlags()) { + if case .keyboard(_, let flag, _, let viaSystem) = $1.mode, system == viaSystem, + system || $1.recipient == recipient { $0.formUnion(flag) } + } + } + + /// System releases must reach the desktop even after the original process or window disappears. + private func release(at index: Int) throws -> Bool { + let press = pressed[index] + if case .systemPointer = press.mode { + if let point = CGEvent(source: nil)?.location { press.up.location = point } + } else if !press.mode.isSystem { + do { try NativePlatform.verify(press.recipient) } + catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { + pressed.remove(at: index) + return false + } + } + try press.prepareRelease?(press.up) + pressed.remove(at: index) + if case .keyboard(_, let flag, _, let system) = press.mode { + press.up.flags = flags(for: press.recipient, system: system, releasing: flag) + } + press.post(press.up) + return true + } + + func keyUp(owner: Owner, name: String, code: CGKeyCode, system: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + let dispatched = try lock.withLock { () throws -> Bool? in + guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.keyCode == code }) else { return nil } + guard pressed[index].mode.isSystem == system else { throw RequestParameters.invalid("Match useSystemInput to the held key") } + return try release(at: index) + } + if let dispatched { return dispatched } + let recipient = try recipientIfUnheld() + throw lock.withLock { + if let key = pressed.first(where: { $0.mode.keyCode == code && $0.recipient == recipient }) { + return conflict(name, holder: key.owner, caller: owner) + } + return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' before 'up'.") + } + } + + func pointerDown(owner: Owner, route: WindowRoute, button: CGMouseButton, system: Bool, + down: CGEvent, up: CGEvent, post: @escaping (CGEvent) -> Void, + prepareRelease: ((CGEvent) throws -> Void)? = nil) throws { + try lock.withLock { + try checkPointerAvailable(route: route, button: button, system: system) + pressed.append(Press(owner: owner, recipient: route.owner, + mode: system ? .systemPointer(button, route.windowID) : .windowPointer(button, route.windowID), up: up, post: post, prepareRelease: prepareRelease)) + post(down) + } + } + + /// A balanced action cannot release another operation's held mouse button. + func requirePointerAvailable(route: WindowRoute, button: CGMouseButton, system: Bool) throws { + try lock.withLock { try checkPointerAvailable(route: route, button: button, system: system) } + } + + private func checkPointerAvailable(route: WindowRoute, button: CGMouseButton, system: Bool) throws { + if pressed.contains(where: { press in + switch press.mode { + case .keyboard: return false + case .systemPointer: return true + case .windowPointer(let held, _): return system || (held == button && press.recipient == route.owner) + } + }) { throw Self.pointerBusy } + } + + /// The requested routing option is irrelevant to an up: use the route saved by its down. + func pointerUp(owner: Owner, window: UInt32, button: CGMouseButton) throws -> Bool { + try lock.withLock { + guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.pointer == button && $0.mode.window == window }) else { + throw RequestParameters.invalid("Release the mouse button through the same connection, application and window that pressed it") + } + return try release(at: index) + } + } + + /// Create and post movement under the same lock as ownership and the saved release point. + func moveSystem(owner: Owner, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { + try lock.withLock { + let press = pressed.first { if case .systemPointer = $0.mode { return true }; return false } + let event: CGEvent + if let press { + guard press.owner == owner, press.recipient == route.owner, press.mode.window == route.windowID, + let button = press.mode.pointer else { throw Self.pointerBusy } + event = try SystemPointerInput.event(WindowPointerInput.dragged(button), source: nil, at: screen, + button: button, group: press.up.getIntegerValueField(.mouseEventNumber)) + let previous = CGEvent(source: nil)?.location ?? press.up.location + event.setIntegerValueField(.mouseEventDeltaX, value: Int64(screen.x.rounded() - previous.x.rounded())) + event.setIntegerValueField(.mouseEventDeltaY, value: Int64(screen.y.rounded() - previous.y.rounded())) + } else { + event = try SystemPointerInput.event(.mouseMoved, source: nil, at: screen, button: .left, group: 0) + } + try checkCancellation() + SystemPointerInput.post(event) + press?.up.location = screen + } + } + + private func record(_ press: Press) -> JSONValue { + var record: [String: JSONValue] = ["appHandle": .string(press.owner.app)] + switch press.mode { + case .keyboard(_, _, let name, let system): + record["kind"] = .string("key") + record["key"] = .string(name) + record["mode"] = .string(system ? "system" : "application") + case .windowPointer(let button, let window), .systemPointer(let button, let window): + record["kind"] = .string("mouse") + record["button"] = .string(button == .left ? "left" : button == .right ? "right" : "middle") + record["windowId"] = .string(String(window)) + if case .systemPointer = press.mode { record["mode"] = .string("system") } + else { record["mode"] = .string("window") } + } + return .object(record) + } + + /// Only the caller's registered input is disclosed; physical user input is never inferred. + func held(connection: UUID) throws -> JSONValue { + try lock.withLock { + for index in pressed.indices.reversed() { + let press = pressed[index] + guard press.owner.connection == connection else { continue } + if press.mode.isSystem { continue } + do { try NativePlatform.verify(press.recipient) } + catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { + pressed.remove(at: index) + } + } + return .array(pressed.filter { $0.owner.connection == connection }.map { press in + record(press) + }) + } + } + + @discardableResult + func release(connection: UUID) throws -> [JSONValue] { + try lock.withLock { + var failures: [String] = [] + var released: [JSONValue] = [] + for index in pressed.indices.reversed() { + let press = pressed[index] + guard press.owner.connection == connection else { continue } + do { if try release(at: index) { released.append(record(press)) } } + catch { failures.append(String(describing: error)) } + } + if !failures.isEmpty { throw NativeFailure(code: "INPUT_CLEANUP_FAILED", message: failures.joined(separator: "; ")) } + return released + } + } + + private static var pointerBusy: NativeFailure { + NativeFailure(code: "INPUT_BUSY", message: "A mouse button is held; release it before dispatching a conflicting gesture") + } +} + +private extension HeldInputs.Mode { + var isSystem: Bool { + switch self { + case .keyboard(_, _, _, let system): return system + case .systemPointer: return true + case .windowPointer: return false + } + } + var keyCode: CGKeyCode? { if case .keyboard(let code, _, _, _) = self { return code }; return nil } + var pointer: CGMouseButton? { + switch self { case .keyboard: return nil; case .windowPointer(let button, _), .systemPointer(let button, _): return button } + } + var window: UInt32? { + switch self { case .keyboard: return nil; case .windowPointer(_, let window), .systemPointer(_, let window): return window } + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift deleted file mode 100644 index 2f143df86f..0000000000 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift +++ /dev/null @@ -1,122 +0,0 @@ -// All connections to the shared helper deliver to the same desktop processes. -import CoreGraphics -import Foundation - -/// The lock covers both the held-key records and their corresponding PID-targeted event posts. -/// Shutdown may release a connection's keys outside the ordinary request scheduler. -final class HeldKeys: @unchecked Sendable { - struct Owner: Equatable { - let connection: UUID - let run: String - let app: String - } - - private struct Press { - let owner: Owner - let recipient: ProcessIdentity - let code: CGKeyCode - let flag: CGEventFlags - let up: CGEvent - let system: Bool - } - - private let lock = NSLock() - private var pressed: [Press] = [] - private let systemFlags: () -> CGEventFlags - - init(systemFlags: @escaping () -> CGEventFlags = { CGEventSource.flagsState(.combinedSessionState) }) { - self.systemFlags = systemFlags - } - - func snapshot(pid: Int32, system: Bool = false) -> [CGKeyCode: CGEventFlags] { - lock.withLock { Dictionary(uniqueKeysWithValues: pressed.filter { $0.system == system && (system || $0.recipient.pid == pid) }.map { ($0.code, $0.flag) }) } - } - - private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { - let source: String - if holder.connection != caller.connection { source = "another session" } - else if holder.run != caller.run { source = "another run_code execution" } - else { source = "a different application handle in this run_code" } - return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it or for its run_code to end.") - } - - /// Repeats use the saved recipient even when the selected application's focused panel has changed. - func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, system: Bool = false, post: (CGEvent, Int32, Bool) -> Void) throws -> Bool { - try lock.withLock { - guard let key = pressed.first(where: { $0.owner == owner && $0.code == code }) else { return false } - guard key.system == system else { throw RequestParameters.invalid("Match useSystemInput to the held key") } - guard key.flag.isEmpty, down.type == .keyDown else { - throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") - } - try NativePlatform.verify(key.recipient) - down.flags = flags(for: key.recipient, system: key.system) - down.setIntegerValueField(.keyboardEventAutorepeat, value: 1) - post(down, key.recipient.pid, key.system) - return true - } - } - - func down(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, - down: CGEvent, up: CGEvent, system: Bool = false, post: (CGEvent, Int32, Bool) -> Void) throws { - try lock.withLock { - if let key = pressed.first(where: { $0.code == code && (($0.system && system) || $0.recipient.pid == recipient.pid) }) { - throw conflict(name, holder: key.owner, caller: owner) - } - pressed.append(Press(owner: owner, recipient: recipient, code: code, flag: flag, up: up, system: system)) - down.flags = flags(for: recipient, system: system) - post(down, recipient.pid, system) - } - } - - private func flags(for recipient: ProcessIdentity, system: Bool, releasing: CGEventFlags = []) -> CGEventFlags { - pressed.reduce(into: system ? systemFlags().subtracting(releasing) : CGEventFlags()) { if $1.system == system && (system || $1.recipient == recipient) { $0.formUnion($1.flag) } } - } - - /// An up always targets the process selected at down. Never post to a recycled PID. - private func release(at index: Int, post: (CGEvent, Int32, Bool) -> Void) throws -> Bool { - let key = pressed[index] - do { if !key.system { try NativePlatform.verify(key.recipient) } } - catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { - pressed.remove(at: index) - return false - } - pressed.remove(at: index) - key.up.flags = flags(for: key.recipient, system: key.system, releasing: key.flag) - post(key.up, key.recipient.pid, key.system) - return true - } - - func up(owner: Owner, name: String, code: CGKeyCode, system: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity, - post: (CGEvent, Int32, Bool) -> Void) throws -> Bool { - let dispatched = try lock.withLock { () throws -> Bool? in - guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.code == code }) else { return nil } - guard pressed[index].system == system else { throw RequestParameters.invalid("Match useSystemInput to the held key") } - return try release(at: index, post: post) - } - if let dispatched { return dispatched } - let recipient = try recipientIfUnheld() - throw lock.withLock { - if let key = pressed.first(where: { $0.code == code && $0.recipient == recipient }) { - return conflict(name, holder: key.owner, caller: owner) - } - return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' in this run_code before 'up'.") - } - } - - func release(connection: UUID, run: String?, post: (CGEvent, Int32, Bool) -> Void) throws { - try lock.withLock { - defer { - // A closed connection cannot retry an unverifiable recipient. - if run == nil { pressed.removeAll { $0.owner.connection == connection } } - } - var firstError: Error? - for index in pressed.indices.reversed() { - let owner = pressed[index].owner - guard owner.connection == connection, run == nil || owner.run == run else { continue } - do { _ = try release(at: index, post: post) } - catch { firstError = firstError ?? error } - } - if let firstError { throw firstError } - } - } -} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index f421f655bf..8be9975889 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -9,14 +9,15 @@ final class KeyboardInput { let flag: CGEventFlags } - private let connection = UUID() - private let held: HeldKeys + private let connection: UUID + private let held: HeldInputs private let postProcess: (CGEvent, Int32) -> Void private let system: SystemKeyboardInput private let textEventInterval: Double private let checkCancellation: @Sendable () throws -> Void - init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldKeys = HeldKeys(), system: SystemKeyboardInput = SystemKeyboardInput(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldInputs = HeldInputs(), connection: UUID = UUID(), system: SystemKeyboardInput = SystemKeyboardInput(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { + self.connection = connection self.held = held self.postProcess = post self.system = system @@ -29,30 +30,28 @@ final class KeyboardInput { else { postProcess(event, pid) } } - func keyDown(_ name: String, app: String, run: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws { - let owner = HeldKeys.Owner(connection: connection, run: run, app: app) + func keyDown(_ name: String, app: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws { + let owner = HeldInputs.Owner(connection: connection, app: app) let code = try Self.keyCode(name) let source = try Self.source(system: useSystemInput) let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) try checkCancellation() if useSystemInput { try system.validateTarget(recipient().pid) } - if try held.repeatIfHeld(owner: owner, name: name, code: code, down: down, system: useSystemInput, post: post) { return } + if try held.repeatIfHeld(owner: owner, name: name, code: code, down: down, system: useSystemInput) { return } if useSystemInput { try system.requireReleased([code]) } let target = try recipient() let up = try Self.keyEvent(source: source, code: code, down: false, flags: []) try checkCancellation() try NativePlatform.verify(target) - try held.down(owner: owner, recipient: target, name: name, code: code, flag: Self.namedModifier(name)?.flag ?? [], - down: down, up: up, system: useSystemInput, post: post) + try held.keyDown(owner: owner, recipient: target, name: name, code: code, flag: Self.namedModifier(name)?.flag ?? [], + down: down, up: up, system: useSystemInput, post: { [postProcess, system] event in + if useSystemInput { system.post(event) } else { postProcess(event, target.pid) } + }) } - func keyUp(_ name: String, app: String, run: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { - try held.up(owner: .init(connection: connection, run: run, app: app), name: name, code: Self.keyCode(name), system: useSystemInput, - recipientIfUnheld: recipientIfUnheld, post: post) - } - - func releaseHeldKeys(run: String? = nil) throws { - try held.release(connection: connection, run: run, post: post) + func keyUp(_ name: String, app: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + try held.keyUp(owner: .init(connection: connection, app: app), name: name, code: Self.keyCode(name), system: useSystemInput, + recipientIfUnheld: recipientIfUnheld) } /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. @@ -65,7 +64,7 @@ final class KeyboardInput { chord.append(Key(keyCode: code, flag: Self.namedModifier(name)?.flag ?? [])) let alreadyHeld = held.snapshot(pid: pid, system: useSystemInput) guard alreadyHeld[code] == nil else { - throw RequestParameters.invalid("Key '\(name)' is already held for this target. Use pressKey after the run_code that holds it releases it.") + throw RequestParameters.invalid("Key '\(name)' is already held for this target. Use pressKey after the holder releases it.") } var selected = Set(alreadyHeld.keys) var flags = alreadyHeld.values.reduce(useSystemInput ? system.currentFlags() : CGEventFlags()) { $0.union($1) } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 7a34767220..bfab6c7adb 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -12,6 +12,7 @@ enum NativeProtocol { "getActionSchema": ["action"], "getApp": ["selector"], "getCapabilities": [], + "getHeldInputs": [], "getState": ["appHandle", "details", "includeMenus", "maxDepth", "maxElements", "windowId"], "invoke": ["appHandle", "elementId", "snapshotId", "windowId"], "launchApp": ["appHandle"], @@ -24,13 +25,12 @@ enum NativeProtocol { "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], "permissionStatus": [], "pressKey": ["appHandle", "key", "modifiers", "useSystemInput", "windowId"], - "releaseHeldKeys": ["runId"], - "releaseSystemButton": [], + "releaseHeldInputs": [], "requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"], "screenshot": ["appHandle", "windowId"], "scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"], "selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"], - "sendKeyEvent": ["appHandle", "direction", "key", "runId", "useSystemInput", "windowId"], + "sendKeyEvent": ["appHandle", "direction", "key", "useSystemInput", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], "takeWindowActivity": ["appHandle", "observations"], diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 8facd85eae..82103f609e 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -49,7 +49,7 @@ import Darwin self.onFatal = onFatal worker = AXWorker(cancellation: cancellation, axTimeout: configuration.axTimeoutSeconds, textEventInterval: configuration.textEventIntervalSeconds, maxClickHoldMs: configuration.maxClickHoldMs, - heldKeys: scheduler.heldKeys) + heldInputs: scheduler.heldInputs, connectionID: connectionID) input = JSONLInput(limit: configuration.maxRequestBytes, cancellation: cancellation, channel: channel) self.writer = writer } @@ -189,9 +189,11 @@ import Darwin private func execute(_ request: NativeRequest, trace: ScreenshotTrace?) async throws -> JSONValue { let params = try RequestParameters(request) try cancellation.check() - if request.method == "releaseSystemButton" { - scheduler.systemPointer.release(connection: connectionID) - return AXWorker.actionResult + if request.method == "getHeldInputs" { + return try scheduler.heldInputs.held(connection: connectionID) + } + if request.method == "releaseHeldInputs" { + return .array(try scheduler.heldInputs.release(connection: connectionID)) } if request.method == "screenshot" { try capture.requireAvailable() } // A dispatched action can invalidate the snapshot that identifies its window. @@ -215,12 +217,12 @@ import Darwin let requiresCatalog = ["getApp", "launchApp", "listApps", "findApps", "typeText", "pressKey", "sendKeyEvent", "click"].contains(request.method) let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil) let result: JSONValue - if request.method == "toggleMouse", try params.optionalBoolean("useSystemInput") == true, - try params.string("direction") == "up" { - try scheduler.systemPointer.up(connection: connectionID, app: params.string("appHandle"), window: params.windowID(), - button: WindowPointerInput.button(params.string("mouseButton"))) - result = AXWorker.actionResult - } else if request.method == "permissionStatus" { + if request.method == "toggleMouse", try params.string("direction") == "up" { + let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, + app: params.string("appHandle")), window: params.windowID(), button: WindowPointerInput.button(params.string("mouseButton"))) + return .object(["dispatched": .bool(dispatched)]) + } + if request.method == "permissionStatus" { result = permissions.status() } else if request.method == "applicationIcons" { var icons: [String: JSONValue] = [:] @@ -265,10 +267,11 @@ import Darwin case .foreground(let plan): result = try await performForeground(plan, requestID: request.id) case .mouseMove(let route, let point): let latch = cancellation - try scheduler.systemPointer.move(connection: connectionID, in: route, at: point, checkCancellation: { try latch.check() }) + let owner = HeldInputs.Owner(connection: connectionID, app: try params.string("appHandle")) + try scheduler.systemPointer.move(owner: owner, in: route, at: point, checkCancellation: { try latch.check() }) result = AXWorker.mouseMoveResult(route: "system-pointer", pointerMoved: true) case .systemButtonDown(let route, let button): - try scheduler.systemPointer.down(connection: connectionID, app: params.string("appHandle"), in: route, button: button, + try scheduler.systemPointer.down(owner: .init(connection: connectionID, app: params.string("appHandle")), in: route, button: button, checkCancellation: { try cancellation.check() }) result = AXWorker.actionResult case .paste(let plan): @@ -311,7 +314,6 @@ import Darwin stopping = true permissions.closeGuide(owner: connectionID) cancellation.cancel() - scheduler.systemPointer.release(connection: connectionID) deadline?.cancel() deadline = nil cancelRequest(NativeFailure(code: "NATIVE_CANCELLED", message: "Native client disconnected")) @@ -326,6 +328,8 @@ import Darwin await pending?.value deadline?.cancel() deadline = nil + do { try scheduler.heldInputs.release(connection: connectionID) } + catch { fputs("Could not confirm input release on disconnect: \(error)\n", stderr) } await worker.shutdown() onClose() } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift index d2e0c051d5..856ae4dcc0 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift @@ -7,8 +7,8 @@ import Dispatch let id: UUID let continuation: CheckedContinuation } - let heldKeys = HeldKeys() - let systemPointer = SystemPointerInput() + let heldInputs = HeldInputs() + lazy var systemPointer = SystemPointerInput(held: heldInputs) private var owner: UUID? private var waiting: [Waiting] = [] diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift index c6645acf84..598f6752c5 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift @@ -1,18 +1,12 @@ -// The shared desktop has one system pointer. Its held button belongs to the connection and window that pressed it. +// System pointer validation; HeldInputs owns every persistent button press. import CoreGraphics import Dispatch import Foundation @MainActor final class SystemPointerInput { - private struct Press { - let connection: UUID - let app: String - let route: WindowRoute - let button: CGMouseButton - let group: Int64 - let release: CGEvent - } - private var press: Press? + private let held: HeldInputs + + init(held: HeldInputs) { self.held = held } nonisolated static func event(_ type: CGEventType, source: CGEventSource?, at screen: CGPoint, button: CGMouseButton, group: Int64, flags: CGEventFlags? = nil, clickState: Int64 = 1) throws -> CGEvent { @@ -30,8 +24,7 @@ import Foundation event.post(tap: .cghidEventTap) } - func down(connection: UUID, app: String, in route: WindowRoute, button: CGMouseButton, checkCancellation: () throws -> Void) throws { - guard press == nil else { throw Self.busy } + func down(owner: HeldInputs.Owner, in route: WindowRoute, button: CGMouseButton, checkCancellation: () throws -> Void) throws { try WindowPointerInput.validateWindow(route) guard let point = CGEvent(source: nil)?.location else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not read the current pointer position") @@ -42,49 +35,15 @@ import Foundation let down = try Self.event(WindowPointerInput.down(button), source: nil, at: point, button: button, group: group) let up = try Self.event(WindowPointerInput.up(button), source: nil, at: point, button: button, group: group) try checkCancellation() - press = Press(connection: connection, app: app, route: route, button: button, group: group, release: up) - Self.post(down) + try held.pointerDown(owner: owner, route: route, button: button, system: true, down: down, up: up, post: Self.post) } - func move(connection: UUID, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { + func move(owner: HeldInputs.Owner, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { try WindowPointerInput.validate(point, in: route) try WindowPointerInput.validateWindow(route) let screen = WindowPointerInput.screenPoint(point, in: route) try WindowPointerInput.checkSystemHit(route, at: screen) - let event: CGEvent - if let press { - guard press.connection == connection, press.route.owner == route.owner, press.route.windowID == route.windowID else { throw Self.busy } - let button = press.button - event = try Self.event(WindowPointerInput.dragged(button), source: nil, at: screen, button: button, group: press.group) - let previous = CGEvent(source: nil)?.location ?? press.release.location - event.setIntegerValueField(.mouseEventDeltaX, value: Int64(screen.x.rounded() - previous.x.rounded())) - event.setIntegerValueField(.mouseEventDeltaY, value: Int64(screen.y.rounded() - previous.y.rounded())) - } else { - event = try Self.event(.mouseMoved, source: nil, at: screen, button: .left, group: 0) - } + try held.moveSystem(owner: owner, route: route, screen: screen, checkCancellation: checkCancellation) try checkCancellation() - Self.post(event) - press?.release.location = screen - try checkCancellation() - } - - func up(connection: UUID, app: String, window: UInt32, button: CGMouseButton) throws { - guard let press, press.connection == connection, press.app == app, press.route.windowID == window, press.button == button else { - throw RequestParameters.invalid("Release the system button through the same window and connection that pressed it") - } - release(connection: connection) - } - - /// Releasing at the current pointer also works after focus changes or the original window closes. - func release(connection: UUID) { - guard let press, press.connection == connection else { return } - if let point = CGEvent(source: nil)?.location { press.release.location = point } - press.release.flags = CGEventSource.flagsState(.combinedSessionState) - Self.post(press.release) - self.press = nil - } - - private static var busy: NativeFailure { - NativeFailure(code: "INPUT_BUSY", message: "A system mouse button is held; release it before controlling another window or button") } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift index 77dd57c8f7..a1ee90caa1 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift @@ -15,12 +15,14 @@ final class WindowPointerInput { let release: CGEvent } + private let held: HeldInputs private let poster: PIDEventPoster private let systemKeyboard: SystemKeyboardInput private let checkCancellation: @Sendable () throws -> Void - init(poster: PIDEventPoster, systemKeyboard: SystemKeyboardInput = SystemKeyboardInput(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(poster: PIDEventPoster, held: HeldInputs = HeldInputs(), systemKeyboard: SystemKeyboardInput = SystemKeyboardInput(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { self.poster = poster + self.held = held self.systemKeyboard = systemKeyboard self.checkCancellation = checkCancellation } @@ -50,23 +52,30 @@ final class WindowPointerInput { } } - /// Send one window-directed transition at the current cursor. A release can be outside the window. - func toggleMouse(in route: WindowRoute, button: String, isDown: Bool, - isolation: isolated (any Actor)? = #isolation) async throws { + /// Save the exact window release before posting the down event. + func mouseDown(owner: HeldInputs.Owner, in route: WindowRoute, button: String, + isolation: isolated (any Actor)? = #isolation) async throws { let selected = try Self.button(button) try Self.validateWindow(route) guard let screen = CGEvent(source: nil)?.location else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not read the current pointer position") } + try await Self.checkSystemHit(route, at: screen) let point = WindowPoint(x: screen.x - route.bounds.x, y: screen.y - route.bounds.y) - if isDown { - try await Self.checkSystemHit(route, at: screen) - } - let event = try mouseEvent(source: Self.source(), route: route, screen: screen, local: point, - type: isDown ? Self.down(selected) : Self.up(selected), - button: selected, clickState: 1, subtype: 3, group: nil) + let pair = try mousePair(source: Self.source(), route: route, screen: screen, local: point, + button: selected, clickState: 1, group: Self.clickGroup()) try checkCancellation() - poster.post(event, to: route.owner.pid) + let poster = self.poster + try held.pointerDown(owner: owner, route: route, button: selected, system: false, down: pair.down, up: pair.up, + post: { poster.post($0, to: route.owner.pid) }, prepareRelease: { event in + guard let screen = CGEvent(source: nil)?.location else { return } + let current: WindowInfo + do { current = try NativePlatform.ownedWindow(route.owner.pid, route.windowID) } + catch let error as NativeFailure where error.code == "WINDOW_UNAVAILABLE" { return } + event.location = screen + try poster.stampWindow(event, pid: route.owner.pid, windowID: route.windowID, + point: WindowPoint(x: screen.x - current.bounds.x, y: screen.y - current.bounds.y)) + }) } /// Post balanced mouse presses; system input also holds and releases the requested keyboard modifiers. @@ -79,6 +88,7 @@ final class WindowPointerInput { } let source = try Self.source(system: useSystemInput) let selectedButton = try Self.button(button) + try held.requirePointerAvailable(route: route, button: selectedButton, system: useSystemInput) var flags = try KeyboardInput.modifierFlags(modifiers) if useSystemInput { flags.formUnion(CGEventSource.flagsState(.combinedSessionState)) } let group = Self.clickGroup() @@ -170,6 +180,7 @@ final class WindowPointerInput { } let source = try Self.source(system: useSystemInput) let selected = try Self.button(button) + try held.requirePointerAvailable(route: route, button: selected, system: useSystemInput) var flags = try KeyboardInput.modifierFlags(modifiers) if useSystemInput { flags.formUnion(CGEventSource.flagsState(.combinedSessionState)) } let group = Self.clickGroup() diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 74ce0f6e13..0a9ee3c049 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -19,18 +19,18 @@ export function renderNativeProtocol(): { json: string; swift: string } { const { fields, enums, json } = nativeProtocol({ getState: NativeResourceParameters.getState.extend(traversal), paste: NativeResourceParameters.paste.extend(traversal), - sendKeyEvent: z.object({ runId: z.string().min(1), ...systemInput }), + sendKeyEvent: z.object(systemInput), pressKey: z.object(systemInput), click: z.object(systemInput), mouseMove: z.object(systemInput), toggleMouse: z.object(systemInput), drag: NativeResourceParameters.drag.extend(systemInput), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, - }, [z.object({ - method: z.literal('releaseHeldKeys'), params: z.object({ runId: z.string().min(1) }).strict(), - }).strict(), z.object({ method: z.literal('takeWindowActivity'), params: z.object({ appHandle: z.string(), observations: z.record(z.string(), z.string().regex(/^[0-9]{1,20}$/)) }).strict() }).strict(), - z.object({ method: z.literal('clearWindowActivity'), params: z.object({}).strict() }).strict(), - z.object({ method: z.literal('releaseSystemButton'), params: z.object({}).strict() }).strict()]) + }, [ + z.object({ method: z.literal('takeWindowActivity'), params: z.object({ appHandle: z.string(), + observations: z.record(z.string(), z.string().regex(/^[0-9]{1,20}$/)) }).strict() }).strict(), + z.object({ method: z.literal('clearWindowActivity'), params: z.object({}).strict() }).strict(), + ]) const quoted = (values: Iterable) => [...values].sort().map(value => JSON.stringify(value)).join(', ') const swift = [ '// Generated by native/generate-protocol.ts from @deepseek-ai/dsh-cua/native-schema. Do not edit.', diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index a50d4c50a3..5312faf67b 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -1137,10 +1137,6 @@ "up" ] }, - "runId": { - "type": "string", - "minLength": 1 - }, "useSystemInput": { "type": "boolean" } @@ -1148,8 +1144,7 @@ "required": [ "appHandle", "key", - "direction", - "runId" + "direction" ], "additionalProperties": false } @@ -1558,19 +1553,34 @@ }, "method": { "type": "string", - "const": "releaseHeldKeys" + "const": "getHeldInputs" }, "params": { "type": "object", - "properties": { - "runId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "runId" - ], + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "releaseHeldInputs" + }, + "params": { + "type": "object", + "properties": {}, "additionalProperties": false } }, @@ -1644,29 +1654,6 @@ "params" ], "additionalProperties": false - }, - { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "method": { - "type": "string", - "const": "releaseSystemButton" - }, - "params": { - "type": "object", - "properties": {}, - "additionalProperties": false - } - }, - "required": [ - "id", - "method", - "params" - ], - "additionalProperties": false } ] } diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index dd6dc6ab12..a1b020742b 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -49,6 +49,8 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega var events: [[String: Any]] = [] var axPresses = 0 var axMenus = 0 + private var moveSignal: DispatchSourceSignal? + private var moved = false init(statePath: String) { self.statePath = statePath } func applicationDidFinishLaunching(_ notification: Notification) { let bar = NSMenu() @@ -66,6 +68,16 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega window.title = "DSH CUA capability checks" window.isReleasedWhenClosed = false window.animationBehavior = .none + signal(SIGUSR1, SIG_IGN) + let move = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main) + move.setEventHandler { [weak self] in + guard let self else { return } + self.window.setFrameOrigin(NSPoint(x: self.window.frame.minX + (self.moved ? -40 : 40), y: self.window.frame.minY)) + self.moved.toggle() + self.persist() + } + move.resume() + moveSignal = move window.collectionBehavior = [.canJoinAllApplications, .stationary] text = CapabilityTextView(frame: NSRect(x: 20, y: 230, width: 600, height: 235)) text.isRichText = true @@ -84,6 +96,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega pad.received = { [weak self] event in guard let self else { return } var value: [String: Any] = ["type": event.type.rawValue, "timestamp": event.timestamp, "flags": event.modifierFlags.rawValue, + "sourcePid": event.cgEvent?.getIntegerValueField(.eventSourceUnixProcessID) ?? 0, "shift": event.modifierFlags.contains(.shift), "command": event.modifierFlags.contains(.command), "systemShift": CGEventSource.keyState(.combinedSessionState, key: 56), "systemW": CGEventSource.keyState(.combinedSessionState, key: 13)] @@ -136,7 +149,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega let frame = pad.convert(pad.bounds, to: nil) let selection = text.selectedRange() let result: [String: Any] = ["pid": ProcessInfo.processInfo.processIdentifier, "windowId": window.windowNumber > 0 ? String(window.windowNumber) as Any : NSNull(), - "active": NSApplication.shared.isActive, "keyWindow": window.isKeyWindow, + "windowX": window.frame.minX, "active": NSApplication.shared.isActive, "keyWindow": window.isKeyWindow, "textFocused": window.firstResponder === text, "pasteAttempts": pasteAttempts, "text": text.string, "selection": [selection.location, selection.length], "runs": runs, "events": events, "axPresses": axPresses, "axMenus": axMenus, "pad": [frame.minX, window.frame.height - frame.maxY, frame.width, frame.height]] @@ -159,6 +172,11 @@ if CommandLine.arguments.dropFirst().first == "--cursor" { print("[\(position.x),\(position.y)]") exit(0) } +if CommandLine.arguments.dropFirst().first == "--buttons" { + let values = [CGMouseButton.left, .right, .center].map { CGEventSource.buttonState(.combinedSessionState, button: $0) } + print(String(data: try! JSONSerialization.data(withJSONObject: values), encoding: .utf8)!) + exit(0) +} let statePath = CommandLine.arguments.dropFirst().first ?? Bundle.main.object(forInfoDictionaryKey: "DSHFixtureStatePath") as? String if let statePath { let application = NSApplication.shared diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index fff4d56b87..2b79ad4dd4 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -48,10 +48,21 @@ def stop_application(pid): def check_toggle_mouse(helper, owner, state_file, executable): call = helper.call + source_pid = call("permissionStatus", {})["helper"]["pid"] + + def observed(value): + return {**value, "events": [event for event in value["events"] if event.get("sourcePid") == source_pid]} + + def read_owned(): + return observed(json.loads(state_file.read_text())) + + def wait_owned(predicate): + return observed(wait_for_state(state_file, lambda value: predicate(observed(value)))) + def cursor(*position): return json.loads(subprocess.check_output([executable, "--cursor", *map(str, position)], text=True)) - state = json.loads(state_file.read_text()) + state = read_owned() window = {**owner, "windowId": state["windowId"]} def toggle(button, direction, error=None): result = call("toggleMouse", {**window, "mouseButton": button, "direction": direction}, error) @@ -59,9 +70,9 @@ def check_toggle_mouse(helper, owner, state_file, executable): assert result == {"dispatched": True}, result toggle("left", "down", "FOREGROUND_REQUIRED") - assert json.loads(state_file.read_text())["events"] == state["events"] + assert read_owned()["events"] == state["events"] call("activate", owner) - state = wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) + state = wait_owned(lambda s: s["active"] and s["keyWindow"]) bounds = next(w["bounds"] for w in call("listWindows", owner) if w["windowId"] == window["windowId"]) inside = [bounds["x"] + state["pad"][0] + 80, bounds["y"] + state["pad"][1] + 70] outside = [bounds["x"] - 8, inside[1]] @@ -70,72 +81,95 @@ def check_toggle_mouse(helper, owner, state_file, executable): try: assert cursor(*outside) == outside toggle("left", "down", "FOREGROUND_REQUIRED") - assert json.loads(state_file.read_text())["events"] == state["events"] + assert read_owned()["events"] == state["events"] for index, (button, down, up) in enumerate([("left", 1, 2), ("right", 3, 4), ("middle", 25, 26)]): assert cursor(*inside) == inside call("activate", owner) - wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) + wait_owned(lambda s: s["active"] and s["keyWindow"]) count = len(state["events"]) toggle(button, "down") try: - state = wait_for_state(state_file, lambda s: len(s["events"]) > count) + state = wait_owned(lambda s: len(s["events"]) > count) assert [(e["type"], e["button"]) for e in state["events"][count:]] == [(down, index)], state assert cursor() == inside assert not state["events"][-1]["pressedButtons"] & (1 << index), state assert cursor(*outside) == outside + if button == "right": + os.kill(state["pid"], signal.SIGUSR1) + wait_owned(lambda s: s["windowX"] == bounds["x"] + 40) if button == "middle": other_state = state_file.with_name("other.json") other = subprocess.Popen([executable, other_state]) wait_for_state(other_state, lambda s: bool(s["windowId"])) other_app = call("getApp", {"selector": str(other.pid)}) call("activate", {"appHandle": other_app["appHandle"]}) - wait_for_state(state_file, lambda s: not s["active"]) + wait_owned(lambda s: not s["active"]) finally: + assert cursor(*outside) == outside toggle(button, "up") - state = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 2) + state = wait_owned(lambda s: len(s["events"]) >= count + 2) events = state["events"][count:] assert [(e["type"], e["button"]) for e in events] == [(down, index), (up, index)], events assert events[1]["point"][0] < 0, events + if button == "right": + assert events[1]["point"][0] == outside[0] - bounds["x"] - 40, events + os.kill(state["pid"], signal.SIGUSR1) + wait_owned(lambda s: s["windowX"] == bounds["x"]) if button != "middle": assert cursor() == outside call("activate", owner) - wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) + wait_owned(lambda s: s["active"] and s["keyWindow"]) call("getState", {**window, "maxElements": 300, "maxDepth": 20}) key = hashlib.sha256(Path(helper.process.args[0]).read_bytes()).hexdigest() socket = Path(f"/tmp/dsh-cua-{os.getuid()}/{key}.sock") for index, (button, down, moved, up) in enumerate([("left", 1, 6, 2), ("right", 3, 7, 4), ("middle", 25, 27, 26)]): assert cursor(*inside) == inside params = {**window, "mouseButton": button, "useSystemInput": True} - count = len(json.loads(state_file.read_text())["events"]) + count = len(read_owned()["events"]) call("toggleMouse", {**params, "direction": "down"}) try: - state = wait_for_state(state_file, lambda s: len(s["events"]) > count) + state = wait_owned(lambda s: len(s["events"]) > count) assert state["events"][-1]["pressedButtons"] & (1 << index), state call("toggleMouse", {**params, "direction": "down"}, "INPUT_BUSY") call("mouseMove", {**window, "x": inside[0] - bounds["x"] + 15, "y": inside[1] - bounds["y"], "useSystemInput": True}) - state = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 2) + state = wait_owned(lambda s: len(s["events"]) >= count + 2) assert state["events"][-1]["type"] == moved, state assert cursor() == [inside[0] + 15, inside[1]] finally: call("toggleMouse", {**params, "direction": "up"}) - events = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 3)["events"][count:] + events = wait_owned(lambda s: len(s["events"]) >= count + 3)["events"][count:] assert [e["type"] for e in events] == [down, moved, up], events assert len({e["eventNumber"] for e in events}) == 1 and not events[-1]["pressedButtons"] & (1 << index), events - for ending in ("releaseSystemButton", "disconnect"): + def wait_button(pressed): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + buttons = json.loads(subprocess.check_output([executable, "--buttons"], text=True)) + if buttons[0] == pressed: + return + time.sleep(0.025) + raise AssertionError(f"System left button did not become {pressed}") + + for ending in ("releaseHeldInputs", "disconnect"): + call("activate", owner) + wait_owned(lambda s: s["active"] and s["keyWindow"]) + assert cursor(*inside) == inside connection = Connection(socket, key) try: app = connection.call("getApp", {"selector": str(state["pid"])}) - count = len(json.loads(state_file.read_text())["events"]) + params = {**window, "mouseButton": "left", "useSystemInput": True} connection.call("toggleMouse", {**params, "appHandle": app["appHandle"], "direction": "down"}) - wait_for_state(state_file, lambda s: len(s["events"]) > count) + wait_button(True) call("toggleMouse", {**params, "direction": "up"}, "INVALID_ARGUMENT") + wait_button(True) + call("activate", {"appHandle": other_app["appHandle"]}) + wait_owned(lambda s: not s["active"]) if ending != "disconnect": connection.call(ending, {}) finally: connection.close() - events = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 2)["events"][count:] - assert [e["type"] for e in events] == [25, 26] and events[-1]["pressedButtons"] == 0, events + wait_button(False) + finally: run_cleanup(lambda: cursor(*original), *([lambda: stop(other)] if other else [])) @@ -265,6 +299,37 @@ def check_clicks(helper, window, point, state_file): return state +def check_mixed_input(call, owner, state_file, executable): + def cursor(*position): + return json.loads(subprocess.check_output([executable, "--cursor", *map(str, position)], text=True)) + source_pid = call("permissionStatus", {})["helper"]["pid"] + call("activate", owner) + state = wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) + window = {**owner, "windowId": state["windowId"]} + bounds = next(w["bounds"] for w in call("listWindows", owner) if w["windowId"] == window["windowId"]) + original = cursor() + try: + cursor(bounds["x"] + state["pad"][0] + 80, bounds["y"] + state["pad"][1] + 70) + for system, system_key in ((False, False), (True, False), (False, True), (True, True)): + count = len(json.loads(state_file.read_text())["events"]) + call("sendKeyEvent", {**owner, "key": "a", "direction": "down"}) + call("toggleMouse", {**window, "mouseButton": "left", "direction": "down", "useSystemInput": system}) + call("sendKeyEvent", {**owner, "key": "w", "direction": "down", "useSystemInput": system_key}) + assert call("getHeldInputs", {}) == [ + {"kind": "key", "key": "a", "appHandle": owner["appHandle"], "mode": "application"}, + {"kind": "mouse", "button": "left", "appHandle": owner["appHandle"], + "windowId": window["windowId"], "mode": "system" if system else "window"}, + {"kind": "key", "key": "w", "appHandle": owner["appHandle"], "mode": "system" if system_key else "application"}, + ] + call("releaseHeldInputs", {}) + assert call("getHeldInputs", {}) == [] + state = wait_for_state(state_file, lambda s: sum(e.get("sourcePid") == source_pid for e in s["events"][count:]) >= 6) + events = [(e["type"], e.get("keyCode")) for e in state["events"][count:] if e.get("sourcePid") == source_pid] + assert events == [(10, 0), (1, None), (10, 13), (11, 13), (2, None), (11, 0)], events + finally: + run_cleanup(lambda: call("releaseHeldInputs", {}), lambda: cursor(*original)) + + def check_keyboard(call, owner, state_file, state): count = len(state["events"]) call("pressKey", {**owner, "key": ["w", "d"]}, "INVALID_ARGUMENT") @@ -276,7 +341,7 @@ def check_keyboard(call, owner, state_file, state): count = len(state["events"]) def key(name, direction): - call("sendKeyEvent", {**owner, "runId": "held-input", "key": name, "direction": direction}) + call("sendKeyEvent", {**owner, "key": name, "direction": direction}) key("w", "down") key("d", "down") @@ -288,7 +353,7 @@ def check_keyboard(call, owner, state_file, state): held = state["events"][count:] assert [(event["type"], event["keyCode"]) for event in held] == [(10, 13), (10, 2), (11, 2)], held assert held[2]["timestamp"] - held[1]["timestamp"] >= 2, held - call("releaseHeldKeys", {"runId": "held-input"}) + call("releaseHeldInputs", {}) state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) assert [(e["type"], e["keyCode"]) for e in state["events"][count:]] == [(10, 13), (10, 2), (11, 2), (11, 13)] @@ -298,7 +363,7 @@ def check_keyboard(call, owner, state_file, state): key("w", "down") if explicit_up: key("w", "up") - call("releaseHeldKeys", {"runId": "held-input"}) + call("releaseHeldInputs", {}) state = wait_for_state(state_file, lambda value: any( e["type"] == 11 and e.get("keyCode") == 13 for e in value["events"][count:])) view_events = [(e["type"], e["keyCode"], e["repeat"]) for e in state["events"][count:]] @@ -327,7 +392,7 @@ def check_system_input(helper, owner, state_file, executable): events = wait_for_state(state_file, lambda value: any(event["type"] == 11 for event in value["events"][count:]))["events"][count:] assert [(event["type"], event.get("keyCode")) for event in events] == [(10, 2), (11, 2)], events assert all(event["shift"] for event in events) and not any(keys().values()), events - held = {**owner, "key": "w", "runId": "system-input-e2e", "useSystemInput": True} + held = {**owner, "key": "w", "useSystemInput": True} for cleanup in (False, True): count = len(json.loads(state_file.read_text())["events"]) call("sendKeyEvent", {**held, "direction": "down"}) @@ -338,7 +403,7 @@ def check_system_input(helper, owner, state_file, executable): assert down["systemW"], down finally: if cleanup: - call("releaseHeldKeys", {"runId": held["runId"]}) + call("releaseHeldInputs", {}) else: call("sendKeyEvent", {**held, "direction": "up"}) state = wait_for_state(state_file, lambda value: any( @@ -393,6 +458,7 @@ def main(): only.add_argument("--keyboard-only", action="store_true") only.add_argument("--drag-only", action="store_true") only.add_argument("--toggle-only", action="store_true") + only.add_argument("--mixed-only", action="store_true") only.add_argument("--system-input-only", action="store_true") args = parser.parse_args() transcript = [] @@ -407,8 +473,8 @@ def main(): info = {"CFBundleName": "Capabilities Fixture", "CFBundleDisplayName": "Capabilities Fixture", "CFBundleIdentifier": "test.dsh.cua." + uuid.uuid4().hex, "CFBundleExecutable": "CapabilitiesFixture", "CFBundlePackageType": "APPL", - "DSHFixtureStatePath": str(state_file), "DSHFixtureBackground": args.click_only or args.keyboard_only or args.drag_only or args.toggle_only or args.system_input_only, - "DSHFixtureKeyboard": args.keyboard_only} + "DSHFixtureStatePath": str(state_file), "DSHFixtureBackground": args.click_only or args.keyboard_only or args.drag_only or args.toggle_only or args.mixed_only or args.system_input_only, + "DSHFixtureKeyboard": args.keyboard_only or args.mixed_only} (application / "Contents/Info.plist").write_bytes(plistlib.dumps(info)) subprocess.run(["swiftc", str(ROOT / "tests/CapabilitiesFixture.swift"), "-o", str(executable)], check=True) try: @@ -425,6 +491,10 @@ def main(): app = call("launchApp", owner) assert app["running"] is True, app pid = wait_for_state(state_file, lambda value: bool(value["windowId"]))["pid"] + if args.mixed_only: + check_mixed_input(call, owner, state_file, executable) + print("PASS: receiver observes mixed keyboard/window and keyboard/system input in reverse release order") + return if args.system_input_only: check_system_input(helper, owner, state_file, executable) print("PASS: system clicks, keyboard chords, held-key state and cancellation release of mouse and modifiers") diff --git a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py index 3196677143..5f0550a0aa 100644 --- a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py +++ b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py @@ -299,6 +299,12 @@ def main(): assert b.call("listWindows", {"appHandle": app_b}) timed.close() clients.remove(timed) + a.call("sendKeyEvent", {"appHandle": app_a, "key": "w", "direction": "down"}) + assert b.call("getHeldInputs", {}) == [] + b.call("sendKeyEvent", {"appHandle": app_b, "key": "w", "direction": "up"}, error="INVALID_ARGUMENT") + assert b.call("releaseHeldInputs", {}) == [] + assert [entry["key"] for entry in a.call("getHeldInputs", {})] == ["w"] + b.call("sendKeyEvent", {"appHandle": app_b, "key": "d", "direction": "down"}) a.close() clients.remove(a) b.call("protocol-still-open", {}, error="UNSUPPORTED") @@ -306,6 +312,9 @@ def main(): if not args.without_desktop: assert b.call("listWindows", {"appHandle": app_b}) capture((b, app_b)) + assert [entry["key"] for entry in b.call("getHeldInputs", {})] == ["d"] + b.call("sendKeyEvent", {"appHandle": app_b, "key": "w", "direction": "down"}) + assert [entry["key"] for entry in b.call("releaseHeldInputs", {})] == ["w", "d"] b.close() clients.remove(b) if not args.without_desktop: diff --git a/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift new file mode 100644 index 0000000000..58abbb9ddf --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift @@ -0,0 +1,113 @@ +// Observe native CGEvents at dispatch without injecting input into the developer's desktop. +import CoreGraphics +import Darwin +import Foundation +import Testing +@testable import CuaNative + + +private func pointer(_ type: CGEventType) throws -> CGEvent { + let event = try #require(CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: .zero, mouseButton: .left)) + event.flags = .maskAlternate + return event +} + +@Test(arguments: [false, true], [false, true]) +func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws { + let held = HeldInputs() + let connection = UUID() + let target = try NativePlatform.identity(getpid()) + let owner = HeldInputs.Owner(connection: connection, app: "editor") + let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) + var events: [String] = [] + let keyboard = SystemKeyboardInput(post: { event in + events.append("hid:\(event.getIntegerValueField(.keyboardEventKeycode)):\(event.type.rawValue)") + }, keyState: { _ in false }, foreground: { target.pid }) + let input = KeyboardInput(post: { event, pid in + #expect(pid == target.pid) + events.append("key:\(event.getIntegerValueField(.keyboardEventKeycode)):\(event.type.rawValue)") + }, textEventInterval: 0, held: held, connection: connection, system: keyboard) + try input.keyDown("shift", app: "editor", recipient: { target }) + try held.pointerDown(owner: owner, route: route, button: .left, system: system, + down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append("mouse:\($0.type.rawValue)") }) + try input.keyDown("w", app: "editor", useSystemInput: systemKey, recipient: { target }) + let state = try held.held(connection: connection) + #expect(state == .array([ + .object(["kind": .string("key"), "key": .string("shift"), "appHandle": .string("editor"), "mode": .string("application")]), + .object(["kind": .string("mouse"), "button": .string("left"), "appHandle": .string("editor"), "windowId": .string("7"), "mode": .string(system ? "system" : "window")]), + .object(["kind": .string("key"), "key": .string("w"), "appHandle": .string("editor"), "mode": .string(systemKey ? "system" : "application")]), + ])) + #expect(try held.held(connection: UUID()) == .array([])) + try held.release(connection: connection) + #expect(try held.held(connection: connection) == .array([])) + try held.release(connection: connection) + let wRoute = systemKey ? "hid" : "key" + #expect(events == ["key:56:12", "mouse:1", "\(wRoute):13:10", "\(wRoute):13:11", "mouse:2", "key:56:12"]) +} + +@Test func explicitReleaseRepeatAndRepressKeepOnlyTheLatestPress() throws { + let held = HeldInputs() + let connection = UUID() + let target = try NativePlatform.identity(getpid()) + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held, connection: connection) + func changedFocus() throws -> ProcessIdentity { throw RequestParameters.invalid("Unexpected focus lookup") } + try input.keyDown("w", app: "editor", recipient: { target }) + try input.keyDown("w", app: "editor", recipient: changedFocus) + #expect(try input.keyUp("w", app: "editor", recipientIfUnheld: changedFocus)) + try input.keyDown("d", app: "editor", recipient: { target }) + try input.keyDown("w", app: "editor", recipient: { target }) + try held.release(connection: connection) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [13, 13, 13, 2, 13, 13, 2]) + #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp, .keyDown, .keyDown, .keyUp, .keyUp]) + #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0, 0, 0, 0, 0]) +} + +@Test func connectionsReleaseOnlyTheirOwnInput() throws { + let held = HeldInputs() + let a = UUID(), b = UUID() + let target = try NativePlatform.identity(getpid()) + var eventsA: [CGEventType] = [], eventsB: [CGEventType] = [] + let input = KeyboardInput(post: { event, _ in eventsA.append(event.type) }, textEventInterval: 0, held: held, connection: a) + let peer = KeyboardInput(post: { event, _ in eventsB.append(event.type) }, textEventInterval: 0, held: held, connection: b) + try input.keyDown("w", app: "editor", recipient: { target }) + #expect(try held.held(connection: b) == .array([])) + #expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", recipient: { target }) } + #expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", recipientIfUnheld: { target }) } + try peer.keyDown("d", app: "editor", recipient: { target }) + try held.release(connection: a) + #expect(eventsA == [.keyDown, .keyUp]) + #expect(eventsB == [.keyDown]) + #expect(try peer.keyUp("d", app: "editor", recipientIfUnheld: { target })) + #expect(eventsB == [.keyDown, .keyUp]) +} + +@Test(arguments: [false, true]) +func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) throws { + let held = HeldInputs() + let target = try NativePlatform.identity(getpid()) + // The current PID with a different start identity models a reused process identifier. + let stale = ProcessIdentity(pid: target.pid, startedSeconds: target.startedSeconds + 1, startedMicroseconds: target.startedMicroseconds) + let owner = HeldInputs.Owner(connection: UUID(), app: "old-window") + let route = WindowRoute(owner: stale, windowID: 987654, bounds: .init(x: 0, y: 0, width: 100, height: 100)) + var events: [CGEventType] = [] + try held.pointerDown(owner: owner, route: route, button: .left, system: system, + down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append($0.type) }) + #expect(try held.pointerUp(owner: owner, window: route.windowID, button: .left) == system) + try held.release(connection: owner.connection) + #expect(events == (system ? [.leftMouseDown, .leftMouseUp] : [.leftMouseDown])) +} + +@Test func balancedGestureCannotReleaseAWindowHold() throws { + let held = HeldInputs() + let target = try NativePlatform.identity(getpid()) + let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) + let owner = HeldInputs.Owner(connection: UUID(), app: "editor") + try held.pointerDown(owner: owner, route: route, button: .left, system: false, + down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { _ in }) + #expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .left, system: false) } + #expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .right, system: true) } + try held.requirePointerAvailable(route: route, button: .right, system: false) + try held.release(connection: owner.connection) + try held.requirePointerAvailable(route: route, button: .left, system: false) +} diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift index a971328ce3..22e904d386 100644 --- a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -63,75 +63,3 @@ func plusAlonePressesShiftEquals(_ alias: String) throws { #expect(events.map(\.type) == [.flagsChanged, .flagsChanged]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, false]) } - -@Test func directionalReleaseUsesOriginalRecipientAndPreservesOtherRuns() throws { - let target = try NativePlatform.identity(getpid()) - let held = HeldKeys() - var events: [CGEvent] = [] - let input = KeyboardInput(post: { event, pid in - #expect(pid == target.pid) - events.append(event) - }, textEventInterval: 0, held: held) - try input.keyDown("shift", app: "editor", run: "one", recipient: { target }) - #expect(throws: NativeFailure.self) { try input.keyDown("shift", app: "editor", run: "one", recipient: { target }) } - try input.keyDown("w", app: "editor", run: "two", recipient: { target }) - #expect(throws: NativeFailure.self) { try input.keyDown("W", app: "editor", run: "one", recipient: { target }) } - #expect(throws: NativeFailure.self) { try input.keyUp("w", app: "other", run: "two", recipientIfUnheld: { target }) } - #expect(throws: NativeFailure.self) { try input.pressKey("w", modifiers: [], to: target.pid) } - try input.pressKey("d", modifiers: ["shift"], to: target.pid) - try input.releaseHeldKeys(run: "one") - #expect(try input.keyUp("w", app: "editor", run: "two", recipientIfUnheld: { target })) - try input.releaseHeldKeys(run: "two") - #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 13, 2, 2, 56, 13]) - #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, false, false]) -} - -@Test(arguments: [true, false]) -func repeatedDownUsesOriginalRecipientAndOneRelease(_ explicitUp: Bool) throws { - let target = try NativePlatform.identity(getpid()) - var events: [CGEvent] = [] - let input = KeyboardInput(post: { event, pid in - #expect(pid == target.pid) - events.append(event) - }, textEventInterval: 0) - func changedFocus() throws -> ProcessIdentity { - throw RequestParameters.invalid("The repeat or release looked up a new recipient") - } - try input.keyDown("w", app: "editor", run: "one", recipient: { target }) - try input.keyDown("W", app: "editor", run: "one", recipient: changedFocus) - if explicitUp { #expect(try input.keyUp("w", app: "editor", run: "one", recipientIfUnheld: changedFocus)) } - try input.releaseHeldKeys(run: "one") - #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp]) - #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0]) -} - -@Test func foreignSessionCannotRepeatOrReleaseTheOwnersKey() throws { - let target = try NativePlatform.identity(getpid()) - let held = HeldKeys() - var events: [CGEvent] = [] - let a = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held) - let b = KeyboardInput(post: { _, _ in Issue.record("Non-owner dispatched an event") }, textEventInterval: 0, held: held) - try a.keyDown("w", app: "a", run: "same-run-id", recipient: { target }) - for direction in ["down", "up"] { - do { - if direction == "down" { try b.keyDown("W", app: "b", run: "same-run-id", recipient: { target }) } - else { _ = try b.keyUp("W", app: "b", run: "same-run-id", recipientIfUnheld: { target }) } - Issue.record("Non-owner was allowed to send an event") - } catch let failure as NativeFailure { - #expect(failure.code == "INVALID_ARGUMENT") - #expect(failure.message.contains("Key 'W' is held for this target by another session")) - #expect(failure.message.contains("Wait for the holder to release it")) - } - } - try b.releaseHeldKeys() - try a.keyDown("W", app: "a", run: "same-run-id", recipient: { target }) - try a.releaseHeldKeys() - #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp]) - do { - _ = try b.keyUp("W", app: "b", run: "same-run-id", recipientIfUnheld: { target }) - Issue.record("Unheld key was released") - } catch let failure as NativeFailure { - #expect(failure.code == "INVALID_ARGUMENT") - #expect(failure.message.contains("Key 'W' is not held for this target")) - } -} diff --git a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift index 71bb93ce97..e5e64b39f4 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift @@ -1,6 +1,7 @@ // Record synthesized events and desktop state queries without posting input to the user's desktop. import CoreGraphics import Darwin +import Foundation import Testing @testable import CuaNative @@ -67,15 +68,17 @@ import Testing var events: [CGEvent] = [] var foreground = target.pid let system = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { [] }, foreground: { foreground }) - let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, system: system) - try keyboard.keyDown("shift", app: "app", run: "run", useSystemInput: true, recipient: { target }) - #expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", run: "run", recipientIfUnheld: { target }) } + let held = HeldInputs() + let connection = UUID() + let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, connection: connection, system: system) + try keyboard.keyDown("shift", app: "app", useSystemInput: true, recipient: { target }) + #expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", recipientIfUnheld: { target }) } foreground = 99 - #expect(try keyboard.keyUp("shift", app: "app", run: "run", useSystemInput: true, recipientIfUnheld: { target })) + #expect(try keyboard.keyUp("shift", app: "app", useSystemInput: true, recipientIfUnheld: { target })) foreground = target.pid - try keyboard.keyDown("w", app: "app", run: "run", useSystemInput: true, recipient: { target }) + try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target }) foreground = 99 - try keyboard.releaseHeldKeys() + try held.release(connection: connection) #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 56, 13, 13]) } @@ -89,16 +92,17 @@ import Testing @Test func systemDirectionalEventsPreserveExternalModifiers() throws { let target = try NativePlatform.identity(getpid()) var ambient: CGEventFlags = .maskAlternate - let held = HeldKeys(systemFlags: { ambient }) + let connection = UUID() + let held = HeldInputs(systemFlags: { ambient }) var events: [CGEvent] = [] let system = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { ambient }, foreground: { target.pid }) - let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, system: system) - try keyboard.keyDown("w", app: "app", run: "run", useSystemInput: true, recipient: { target }) - try keyboard.keyDown("w", app: "app", run: "run", useSystemInput: true, recipient: { target }) - #expect(try keyboard.keyUp("w", app: "app", run: "run", useSystemInput: true, recipientIfUnheld: { target })) + let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, connection: connection, system: system) + try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target }) + try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target }) + #expect(try keyboard.keyUp("w", app: "app", useSystemInput: true, recipientIfUnheld: { target })) #expect(events.allSatisfy { $0.flags.contains(.maskAlternate) }) - try keyboard.keyDown("command", app: "app", run: "run", useSystemInput: true, recipient: { target }) + try keyboard.keyDown("command", app: "app", useSystemInput: true, recipient: { target }) ambient.formUnion(.maskCommand) - try keyboard.releaseHeldKeys() + try held.release(connection: connection) #expect(events.last?.flags == .maskAlternate) } diff --git a/packages/experimental/cua-macos/native/tests/test_ax_projection.py b/packages/experimental/cua-macos/native/tests/test_ax_projection.py index e795c9916d..8b245a7cdb 100644 --- a/packages/experimental/cua-macos/native/tests/test_ax_projection.py +++ b/packages/experimental/cua-macos/native/tests/test_ax_projection.py @@ -49,7 +49,7 @@ def check_input(executable, helper_path, root): ("click", {**scoped, "x": 20, "y": 40}), ("typeText", {**owner, "text": "a"}), ("pressKey", {**owner, "key": "a"}), - ("sendKeyEvent", {**owner, "key": "a", "direction": "down", "runId": "fixture"})]: + ("sendKeyEvent", {**owner, "key": "a", "direction": "down"})]: failure = helper.call(method, params, "PANEL_NOT_READY") assert failure["message"] == "File panel recipient discovery is incomplete. No input was dispatched. Read fresh state before retrying.", failure assert json.loads(log.read_text()) == expected diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 631e4223e0..de54f89688 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -10,10 +10,10 @@ function operationGuidance(treeAdvice: string): string { const methodDetails = new Map([ ['cua.listApps', 'Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp.'], ['cua.findApps', 'Running installation matches include their process ID. Stopped matches have no pid.'], - ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], + ['sendKeyEvent', "For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], - ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold.'], + ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements.'], ['pressKey', 'System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order.'], ['drag', 'Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying.'], diff --git a/packages/experimental/cua-macos/src/held-keys.ts b/packages/experimental/cua-macos/src/held-keys.ts deleted file mode 100644 index ee57cffb5a..0000000000 --- a/packages/experimental/cua-macos/src/held-keys.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** Directional input belongs to the enclosing program, including while its worker calls other tools. */ -import { randomUUID } from 'node:crypto' -import type { Context } from '@deepseek-ai/cordis' -import type { CuaBackend } from '@deepseek-ai/dsh-cua' -import { NativeError, type NativeClient } from '@deepseek-ai/dsh-cua/native-client' -import { RUN_CODE_NAME, type ToolExecutionToken } from '@deepseek-ai/dsh-tools' - -interface HeldKeyRun { - id: string - client?: NativeClient - removeCleanup?: () => void - released: boolean - release(canRequest?: boolean): Promise -} - -/** - * Keep native key ownership until program settlement or its Agent's native connection closes. - * @param ctx - Provider scope owning the tool execution listener. - * @returns Directional input handler; each native connection owns cleanup of the runs that use it. - */ -export function installHeldKeys(ctx: Context): NonNullable { - const runs = new Map() - ctx.on('tools/execute', async (execution, next) => { - if (execution.name !== RUN_CODE_NAME && execution.name !== 'cua_run_code') return next() - let cleanup: Promise | undefined - const run: HeldKeyRun = { - id: randomUUID(), released: false, - release(canRequest = true) { - run.released = true - return cleanup ??= Promise.resolve().then(async () => { - try { if (canRequest) await run.client?.requestCleanup('releaseHeldKeys', { runId: run.id }) } - finally { run.removeCleanup?.(); runs.delete(execution.token) } - }) - }, - } - runs.set(execution.token, run) - // Pause may arrive while an unrelated subtool is still settling. - const onAbort = () => { void run.release().catch(() => undefined) } - const signal = execution.signal - signal.addEventListener('abort', onAbort, { once: true }) - try { - return await next() - } finally { - signal.removeEventListener('abort', onAbort) - await run.release() - } - }) - return (client, params, execution) => { - const run = execution.parent && runs.get(execution.parent) - if (!run || run.released) throw new NativeError('INVALID_ARGUMENT', 'Use sendKeyEvent inside an active run_code or cua_run_code execution') - if (run.client !== undefined && run.client !== client) { - throw new NativeError('INVALID_ARGUMENT', 'The native connection changed; start a new program before holding keys') - } - if (run.client === undefined) { - run.removeCleanup = client.registerCleanup(canRequest => run.release(canRequest)) - run.client = client - } - return client.request('sendKeyEvent', { ...params, runId: run.id }, execution.signal, execution.callId) - } -} diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index db06e9dda4..ab244ed9a6 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -8,7 +8,6 @@ import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' import { createPermissionParameters } from './permission-guide.ts' import { nativeHostArchitecture, prepareNativeExecutable, type SourceSigning } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' -import { installHeldKeys } from './held-keys.ts' import type { NativeChannelFactory } from '@deepseek-ai/dsh-cua/native-client' import { watchWindowActivity } from './recent-activity.ts' import { AX_TRAVERSAL_MAX } from './ax-limits.ts' @@ -71,7 +70,7 @@ export const Config = Schema.object({ export async function apply(ctx: Context, config: Config): Promise { const createChannel: NativeChannelFactory = (owner, native) => createSharedNativeChannel(owner, native, config.recentActivityWindowMs) const backend = { createChannel, ...config.recentActivityWindowMs === 'off' ? {} : { windowRead: watchWindowActivity(ctx) }, - sendKeyEvent: installHeldKeys(ctx), + heldInputState: true, getGuidance: (kind: 'raw' | 'standalone') => macosGuidance(kind, config.recentActivityWindowMs !== 'off'), capabilities: CAPABILITIES, acceptsPidSelector: true, permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) } if (config.helperPath !== undefined) { diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index bf46dbc5a0..10c3e508b2 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,7 +1,7 @@ /** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' -import { COMMON_GUIDANCE, withSystemInputGuidance } from '@deepseek-ai/dsh-cua/guidance' +import { COMMON_GUIDANCE, withHeldInputGuidance, withSystemInputGuidance } from '@deepseek-ai/dsh-cua/guidance' import { GUIDANCE, PLATFORM_GUIDANCE, PROGRAM_GUIDANCE } from '../src/guidance.ts' const apiNames: Array = ['getCapabilities', 'listApps', 'findApps', 'getState', 'getApp'] @@ -41,7 +41,7 @@ it.each([GUIDANCE, PROGRAM_GUIDANCE])('explains when macOS mouse input needs a s expect(instructions).toContain('When approval is enabled, the first explicit system input requests permission;') expect(instructions).toContain('Omitting the option or passing false uses the provider default.') expect(instructions).toContain("direction: 'down' | 'up', options?: { useSystemInput?: boolean }") - expect(instructions).toContain('pass useSystemInput: true on both down and up') + expect(instructions).toContain('pass useSystemInput: true on down') const drag = instructions.split('\n').find(line => line.startsWith('- drag(')) expect(drag).toContain('useSystemInput?: boolean') expect(drag).toContain('Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control.') @@ -54,7 +54,9 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") - expect(GUIDANCE).toContain('returns, throws, or the user pauses') + expect(COMMON_GUIDANCE).not.toContain('sendKeyEvent and toggleMouse remain held across programs and turns') + expect(withHeldInputGuidance(COMMON_GUIDANCE)).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') + expect(withHeldInputGuidance(COMMON_GUIDANCE)).toContain('a system reminder lists any remaining keys and mouse buttons') const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) @@ -75,7 +77,7 @@ it('documents explicit mouse-button events immediately after mouseMove', () => { const lines = COMMON_GUIDANCE.split('\n') const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) expect(lines[index - 1]).toMatch(/^- mouseMove\(/) - expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately.") expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) }) @@ -83,7 +85,7 @@ it('documents explicit mouse-button events immediately after mouseMove', () => { it.each([GUIDANCE, PROGRAM_GUIDANCE])('documents the default window release and the optional system hold', (catalog) => { const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) expect(entry).toContain('By default the window receives the events, even a release outside it, and the system button stays up.') - expect(entry).toContain('pass useSystemInput: true on both down and up') + expect(entry).toContain('pass useSystemInput: true on down') }) it('enumerates every public method once in its catalog entry', () => { diff --git a/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts new file mode 100644 index 0000000000..e79e7aff3f --- /dev/null +++ b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts @@ -0,0 +1,145 @@ +/** Opt-in desktop receiver checks through the real program tools, AgentLoop, and signed helper. */ +import { execFile, spawn } from 'node:child_process' +import { once } from 'node:events' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { Context } from '@deepseek-ai/cordis' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import { brandString } from '@deepseek-ai/dsh-brand' +import ComputerUse from '@deepseek-ai/dsh-computer-use' +import { createUserMessage, LlmAdapter, type GenerateOptions, type StreamChunk, type ToolCallId } from '@deepseek-ai/dsh-llm' +import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' +import Sandbox from '@deepseek-ai/dsh-sandbox-local' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' +import type { SessionId } from '@deepseek-ai/dsh-session' +import Subprocess from '@deepseek-ai/dsh-subprocess-local' +import UserQuestions from '@deepseek-ai/dsh-user-questions' +import { expect, it } from 'vitest' +import { z } from 'zod' +import * as Provider from '../src/index.ts' + +const run = promisify(execFile) +const helperPath = process.env.DSH_CUA_TEST_HELPER +const State = z.object({ + pid: z.number(), windowId: z.string().nullable(), active: z.boolean(), keyWindow: z.boolean(), + pad: z.tuple([z.number(), z.number(), z.number(), z.number()]), + events: z.array(z.object({ type: z.number(), keyCode: z.number().optional(), sourcePid: z.number() })), +}) + +// These cases share the real desktop and deliberately run in order. Run this opt-in file alone. +it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['completed', 'error', 'thinking-stop', 'tool-stop'] as const)( + 'receives mixed releases after %s through cua_run_code', async (ending) => { + if (helperPath === undefined) throw new Error('Set DSH_CUA_TEST_HELPER to a signed helper application executable') + const directory = await mkdtemp(join(tmpdir(), 'dsh-turn-input-desktop-')) + const appDirectory = join(directory, 'Input Receiver.app') + const executable = join(appDirectory, 'Contents/MacOS/InputReceiver') + const stateFile = join(directory, 'state.json') + const ctx = new Context() + let fixture: ReturnType | undefined + let exited: Promise | undefined + let cursor: number[] | undefined + try { + await mkdir(join(appDirectory, 'Contents/MacOS'), { recursive: true }) + await writeFile(join(appDirectory, 'Contents/Info.plist'), ` + + +CFBundleIdentifiertest.dsh.turn-input +CFBundleNameInput Receiver +CFBundleExecutableInputReceiver +CFBundlePackageTypeAPPL +DSHFixtureBackground +DSHFixtureKeyboard +`) + await run('swiftc', [fileURLToPath(new URL('../native/tests/CapabilitiesFixture.swift', import.meta.url)), '-o', executable]) + cursor = z.array(z.number()).parse(JSON.parse((await run(executable, ['--cursor'])).stdout)) + fixture = spawn(executable, [stateFile], { stdio: 'ignore' }) + exited = once(fixture, 'exit') + const observe = async () => State.parse(JSON.parse(await readFile(stateFile, 'utf8'))) + await expect.poll(async () => { + try { return (await observe()).windowId } + catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error } + }, { timeout: 30_000 }).toBeTruthy() + const initial = await observe() + const pad = initial.pad + const programs = [ + `var app = await cua.getApp(${JSON.stringify(String(initial.pid))}); await app.activate(); var win = await app.getWindow(${JSON.stringify(initial.windowId)}); await win.getAccessibilityTree(); var bounds = (await app.getWindows()).find(w => w.windowId === win.windowId).bounds; await win.mouseMove([Math.round(${pad[0] + 80} / bounds.width * 999), Math.round(${pad[1] + 70} / bounds.height * 999)], { relative: true, useSystemInput: true }); await app.sendKeyEvent('a', 'down')`, + `await win.toggleMouse('left', 'down', { useSystemInput: true }); await app.sendKeyEvent('w', 'down'); ${ending === 'tool-stop' ? 'await new Promise(() => {})' : ''}`, + ] + const thinking: PromiseWithResolvers = Promise.withResolvers() + class Model extends LlmAdapter { + private index = 0 + async * stream(options: GenerateOptions): AsyncIterable { + const code = programs[this.index++] + if (code !== undefined) { + yield { type: 'block-start', index: 0, blockType: 'tool-call' } + yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString(`input-${this.index}`), + name: 'cua_run_code', arguments: JSON.stringify({ code, description: 'Exercise the owned desktop input receiver' }) } } + yield { type: 'finish', reason: { kind: 'tool-calls' } } + return + } + if (ending === 'error') throw new Error('Controlled model failure after input') + if (ending === 'thinking-stop') { + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + yield { type: 'finish', reason: { kind: 'stop' } } + } + } + await mountAgentLoopTestDependencies(ctx, { workingDirectory: true }) + await ctx.plugin(Subprocess) + await ctx.plugin(Sandbox) + await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access' }) + await ctx.plugin(NodeRuntime) + await ctx.plugin(ComputerUse) + await ctx.plugin(UserQuestions) + ctx.on('user-questions/request', async () => ({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] })) + await ctx.plugin(Provider, { helperPath, requireSystemInputApproval: false }) + const permissions = await ctx.cuaAccess.systemStatus() + if (permissions.platform !== 'darwin') throw new Error('Expected macOS permission metadata') + const sourcePid = permissions.helper.pid + const received = async () => (await observe()).events.filter(event => event.sourcePid === sourcePid) + await mountAgentLoopTestHarness(ctx) + ctx.llm.registerAdapter(['desktop-fixture'], new Model()) + const handle = await ctx.agents.create({ sessionId: brandString(`desktop-${ending}`), meta: { cwd: directory }, + agentOptions: { provider: 'desktop-fixture', model: 'fixture' } }) + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Exercise owned input' }], source: { kind: 'user' } })) + if (ending === 'thinking-stop') { await thinking.promise; handle.agent.cancel({ kind: 'user' }) } + if (ending === 'tool-stop') { + await expect.poll(async () => (await received()).length, { timeout: 30_000 }).toBe(3) + handle.agent.cancel({ kind: 'user' }) + } + await handle.agent.whenIdle() + if (ending !== 'tool-stop') { + const failures = handle.agent.session.deriveMessages().filter(message => message.role === 'tool' && message.isError) + expect(failures, JSON.stringify(failures)).toEqual([]) + } + if (ending === 'completed') { + await expect.poll(async () => (await received()).map(event => event.type), { timeout: 30_000 }).toEqual([10, 1, 10]) + expect(JSON.stringify(handle.agent.session.snapshotEvents())).toContain('CUA inputs are still held') + programs[3] = "await app.sendKeyEvent('w', 'up'); await win.toggleMouse('left', 'up', { useSystemInput: true }); await app.sendKeyEvent('a', 'up')" + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Release held input' }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + } + await expect.poll(async () => (await received()).map(event => [event.type, event.keyCode ?? null]), { timeout: 30_000 }).toEqual([ + [10, 0], [1, null], [10, 13], [11, 13], [2, null], [11, 0], + ]) + const outcomes = handle.agent.session.snapshotEvents().filter(event => event.type === 'turn/end') + expect(outcomes).toHaveLength(ending === 'completed' ? 2 : 1) + expect(outcomes[0]?.data.reason.kind).toBe(ending === 'completed' ? 'completed' : ending === 'error' ? 'error' : 'aborted') + await handle.dispose() + } finally { + try { await ctx.fiber.dispose() } finally { + if (cursor) await run(executable, ['--cursor', ...cursor.map(String)]) + if (fixture && exited && fixture.exitCode === null && fixture.signalCode === null) { + fixture.kill('SIGTERM') + const deadline = setTimeout(() => { fixture?.kill('SIGKILL') }, 5000) + try { await exited } finally { clearTimeout(deadline) } + } + await rm(directory, { recursive: true, force: true }) + } + } + }, +) diff --git a/packages/experimental/cua-macos/tests/held-keys.spec.ts b/packages/experimental/cua-macos/tests/held-keys.spec.ts deleted file mode 100644 index 76667df75f..0000000000 --- a/packages/experimental/cua-macos/tests/held-keys.spec.ts +++ /dev/null @@ -1,158 +0,0 @@ -/** Held-key cleanup through real native byte streams and the tool execution wrapper. */ -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { PassThrough, Writable } from 'node:stream' -import { finished } from 'node:stream/promises' -import { Context } from '@deepseek-ai/cordis' -import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' -import type { ToolCallId } from '@deepseek-ai/dsh-llm' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import Tools, { defineTool } from '@deepseek-ai/dsh-tools' -import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import { expect, it, onTestFinished, vi } from 'vitest' -import { z } from 'zod' -import { installHeldKeys } from '../src/held-keys.ts' -import { brandString } from '@deepseek-ai/dsh-brand' - -const Request = z.object({ id: z.string(), method: z.string(), params: z.record(z.string(), z.json()) }) - -function nativeConnection(holdRelease = false) { - const requests: z.infer[] = [] - const events: string[] = [] - const held = new Set() - const releasing: PromiseWithResolvers = Promise.withResolvers() - const stdout = new PassThrough() - let releaseId: string | undefined - const acknowledge = (): void => { - if (releaseId === undefined) return - held.clear() - events.push('released') - stdout.write(JSON.stringify({ id: releaseId, result: { dispatched: true } }) + '\n') - releaseId = undefined - } - const stdin = new Writable({ write(chunk, _encoding, callback) { - const request = Request.parse(JSON.parse(String(chunk))) - requests.push(request) - if (request.method === 'releaseHeldKeys') { - events.push('release requested') - releaseId = request.id - releasing.resolve() - if (!holdRelease) acknowledge() - } else { - held.add(z.string().parse(request.params.key)) - events.push('key held') - stdout.write(JSON.stringify({ id: request.id, result: { dispatched: true } }) + '\n') - } - callback() - } }) - const done = Promise.all([finished(stdin, { cleanup: true }), finished(stdout, { cleanup: true })]).then(() => undefined) - const close = vi.fn(() => { - events.push('connection closed') - held.clear() - stdin.end() - stdout.end() - }) - const client = new NativeClient({ subprocess: { spawn() { throw new Error('The byte-stream fixture does not spawn a helper') } } }, { - helperPath: '/fixture/helper', cwd: '/fixture', timeoutMs: 60_000, connectTimeoutMs: 5000, - screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 4096, maxResponseBytes: 4096, - graceMs: 1000, textEventIntervalMs: 1, maxClickHoldMs: 5000, - }, () => ({ stdin, stdout, done, close, waitForClose: () => done })) - onTestFinished(async () => { client.invalidate(); await client.dispose().catch(() => undefined) }) - return { client, requests, events, held, releasing: releasing.promise, acknowledge, close } -} - -async function program(body: (send: (client: NativeClient) => Promise) => Promise) { - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(SystemPrompt) - await ctx.plugin(Tools) - const sendKeyEvent = installHeldKeys(ctx) - ctx.tools.register(defineTool({ name: 'cua_run_code', description: 'Exercise native key ownership.', parameters: {}, - output: { schema: { type: 'json' }, render: () => [] }, - async execute(_args, execution) { - await body(async (client) => { - await sendKeyEvent(client, { key: 'w', direction: 'down' }, { - ...execution, name: 'cua', callId: brandString('held-key'), parent: execution.token, - }) - }) - return null - }, - })) - return { run: () => executeToolFixture(ctx, { name: 'cua_run_code', callId: brandString('held-program'), arguments: {}, signal: new AbortController().signal }) } -} - -it('releases native keys before connection closure without waiting for unrelated program work', async () => { - const native = nativeConnection(true) - const entered: PromiseWithResolvers = Promise.withResolvers() - const finishProgram: PromiseWithResolvers = Promise.withResolvers() - const fixture = await program(async (send) => { - await send(native.client) - entered.resolve() - await finishProgram.promise - }) - let programEnded = false - const running = fixture.run().then((result) => { programEnded = true; return result }) - let closing: Promise | undefined - try { - await entered.promise - closing = native.client.dispose() - await native.releasing - expect(native.held).toEqual(new Set(['w'])) - expect(native.close).not.toHaveBeenCalled() - native.acknowledge() - await closing - expect(programEnded).toBe(false) - expect(native.events).toEqual(['key held', 'release requested', 'released', 'connection closed']) - expect(native.held.size).toBe(0) - finishProgram.resolve() - expect((await running).isError).toBe(false) - expect(native.requests.map(request => request.method)).toEqual(['sendKeyEvent', 'releaseHeldKeys']) - expect(native.close).toHaveBeenCalledTimes(1) - } finally { - finishProgram.resolve() - native.acknowledge() - await running - await closing - } -}) - -it('cleans up local held-key ownership after forced connection closure without sending another request', async () => { - const native = nativeConnection() - const entered: PromiseWithResolvers = Promise.withResolvers() - const finishProgram: PromiseWithResolvers = Promise.withResolvers() - const fixture = await program(async (send) => { - await send(native.client) - entered.resolve() - await finishProgram.promise - await expect(send(native.client)).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' }) - }) - const running = fixture.run() - try { - await entered.promise - native.client.invalidate() - await native.client.dispose() - expect(native.held.size).toBe(0) - finishProgram.resolve() - expect((await running).isError).toBe(false) - expect(native.requests.map(request => request.method)).toEqual(['sendKeyEvent']) - expect(native.close).toHaveBeenCalledTimes(1) - } finally { finishProgram.resolve(); await running } -}) - -it('keeps a held-key run on its first connection and unregisters after normal release', async () => { - const first = nativeConnection() - const second = nativeConnection() - const register = vi.spyOn(second.client, 'registerCleanup') - onTestFinished(() => { register.mockRestore() }) - const fixture = await program(async (send) => { - await send(first.client) - await expect(send(second.client)).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' }) - }) - expect((await fixture.run()).isError).toBe(false) - expect(register).not.toHaveBeenCalled() - expect(second.requests).toEqual([]) - expect(first.requests.map(request => request.method)).toEqual(['sendKeyEvent', 'releaseHeldKeys']) - await first.client.dispose() - expect(first.requests).toHaveLength(2) - expect(first.close).toHaveBeenCalledTimes(1) -}) diff --git a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts index a7d87a7f28..4d5ca12cf2 100644 --- a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts +++ b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts @@ -12,6 +12,14 @@ describe('native protocol generation', () => { expect(await readFile(new URL('../native/Sources/CuaNative/NativeProtocol.generated.swift', import.meta.url), 'utf8')).toBe(generated.swift) }) + it('uses the requesting connection for held-input queries and cleanup', () => { + const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json)) + for (const method of ['getHeldInputs', 'releaseHeldInputs']) { + expect(validate({ id: 'held', method, params: {} })).toBe(true) + expect(validate({ id: 'foreign', method, params: { taskId: 'other' } })).toBe(false) + } + }) + it('resolves recursive JSON arguments in the complete native request schema', () => { const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json)) const target = { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' } @@ -74,9 +82,10 @@ describe('native protocol generation', () => { { method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } }, { method: 'mouseMove', params: { appHandle: 'app', windowId: '1', x: 0, y: 0, allowSystemPointer: true } }, { method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } }, + { method: 'getHeldInputs', params: {} }, + { method: 'releaseHeldInputs', params: {} }, { method: 'takeWindowActivity', params: { appHandle: 'app', observations: { '7': '123' } } }, { method: 'clearWindowActivity', params: {} }, - { method: 'releaseHeldKeys', params: { runId: 'execution' } }, { method: 'launchApp', params: { appHandle: 'pending' } }, { method: 'applicationIcons', params: { paths: ['/Applications/Fixture.app'] } }, { method: 'permissionStatus', params: {} }, diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index f0dd06c268..e7f8f09790 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -1,4 +1,5 @@ /** Native helper replacement is synchronized with Agent and provider disposal. */ +import { randomUUID } from 'node:crypto' import { executeModelToolFixture, executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -27,7 +28,7 @@ import NodeRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh- import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' -import { LlmAdapter, LlmError, type ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { LlmAdapter, LlmError, type ToolCallId, type LlmResolvedModelInfo, type StreamChunk, createUserMessage } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' import Subprocess from '@deepseek-ai/dsh-subprocess' import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' @@ -163,7 +164,7 @@ async function setup( model?: { provider: string; model: string }, ptc?: PtcMode, overrides: Parameters[0] = {}, ) { native.connect.mockClear() - native.cleanup.mockReset().mockResolvedValue({ dispatched: true }) + native.cleanup.mockReset().mockResolvedValue([]) native.request.mockReset().mockResolvedValue([]) native.dispose.mockReset() native.instances.length = 0 @@ -188,6 +189,26 @@ async function setup( return { ctx, provider, handle, execute } } +async function thinkingTurn(f: Awaited>) { + const entered: PromiseWithResolvers = Promise.withResolvers() + class WaitingModel extends LlmAdapter { + async * stream(options: import('@deepseek-ai/dsh-llm').GenerateOptions): AsyncIterable { + entered.resolve() + await new Promise((resolve) => { + if (options.signal?.aborted) resolve() + else options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) + }) + yield { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'Fixture cancelled' } } } + } + } + const provider = `thinking-${randomUUID()}` + f.ctx.llm.registerAdapter([provider], new WaitingModel()) + Object.assign(f.handle.agent.options, { provider, model: 'fixture' }) + f.handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Wait for input' }], source: { kind: 'user' } })) + onTestFinished(async () => { f.handle.agent.cancel({ kind: 'user' }); await f.handle.agent.whenIdle() }) + await entered.promise +} + async function executeProgram( f: Awaited>, name: 'run_code' | 'cua_run_code', code: string, description: string, signal = new AbortController().signal, @@ -199,7 +220,7 @@ async function executeProgram( })) } const execute = name === 'run_code' ? executeModelToolFixture : executeToolFixture - return execute(f.ctx, { agent: f.handle.agent, callId: brandString('keyboard-run'), name, + return execute(f.ctx, { agent: f.handle.agent, callId: brandString(`keyboard-${name}`), name, arguments: { code, description }, signal }) } @@ -253,175 +274,40 @@ it('delivers window activity at the next accepted step and clears it at turn end expect(native.request).not.toHaveBeenCalled() }) -it('requires an enclosing run_code before sending a directional key', async () => { +it('accepts directional input on the Agent connection outside a turn', async () => { const f = await setup() await selectApplication(f) - native.request.mockClear() + native.request.mockResolvedValueOnce({ dispatched: true }) const result = await f.execute('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }) - expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain('active run_code') - expect(native.request).not.toHaveBeenCalled() -}) - -const PROGRAM_TOOLS = PTC_MODES.flatMap(mode => (['run_code', 'cua_run_code'] as const).map(name => ({ mode, name }))) - -it.each(PROGRAM_TOOLS)('finishes a shortcut-only $name in $mode.mode without requesting held-key cleanup', async ({ mode, name }) => { - const f = await setup(undefined, mode) - await selectApplication(f) - native.request.mockClear().mockResolvedValue({ dispatched: true }) - const result = await executeProgram(f, name, - mode.complete("await tools.cua({ method: 'pressKey', params: { appHandle: 'app-one', key: 'a', modifiers: ['command'] } })"), - 'Press Command+A') expect(result.isError).toBe(false) - expect(native.request.mock.calls.map(([method]) => method)).toEqual(['pressKey']) - expect(native.cleanup).not.toHaveBeenCalled() + expect(native.request).toHaveBeenLastCalledWith('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }, expect.any(AbortSignal), expect.any(String)) }) -it.each(PROGRAM_TOOLS.flatMap(tool => - ['return', 'throw', 'pause', 'pause with cleanup error'].map(ending => ({ ...tool, ending })), -))('cleans up only the held W when $name in $mode.mode ends by $ending', async ({ mode, name, ending }) => { +it.each(PTC_MODES)('holds a key across $mode programs in the same turn', async (mode) => { const f = await setup(undefined, mode) + await thinkingTurn(f) await selectApplication(f) const held = new Set() - const events: string[] = [] - const controller = new AbortController() - const runIds = new Set() - native.request.mockImplementation(async (method, params) => { + native.request.mockClear().mockImplementation(async (method, params) => { + if (method === 'getHeldInputs') return [...held].map(key => ({ kind: 'key', key, appHandle: 'app-one', mode: 'application' })) expect(method).toBe('sendKeyEvent') - runIds.add(params.runId) - const { key, direction } = params - if (typeof key !== 'string' || (direction !== 'down' && direction !== 'up')) throw new Error('Invalid directional event') - if (direction === 'down') held.add(key) - else held.delete(key) - events.push(`${key}:${direction}`) + const key = params.key + if (typeof key !== 'string') throw new Error('The native fixture requires a key name') + if (params.direction === 'down') held.add(key) + else { expect(held.has(key)).toBe(true); held.delete(key) } return { dispatched: true } }) - native.cleanup.mockImplementation(async (method, params) => { - expect(method).toBe('releaseHeldKeys') - expect(runIds).toEqual(new Set([params.runId])) - if (ending === 'pause with cleanup error') throw new Error('release acknowledgement failed') - for (const key of held) events.push(`${key}:up`) - held.clear() - return { dispatched: true } - }) - f.ctx.tools.register({ - name: 'check_held_keys', description: 'Observe the keys held by the test receiver.', - parameters: { type: 'object', properties: {} }, - output: { schema: {}, render: () => [] }, - async execute() { - const keys = [...held] - if (ending.startsWith('pause') && keys.length === 1) { - controller.abort() - await setImmediate() - expect(held.size).toBe(ending === 'pause' ? 0 : 1) - } - return keys - }, - }) - const code = [ - "const key = (key, direction) => tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key, direction } });", - "await key('w', 'down'); await key('d', 'down');", - "if ((await tools.check_held_keys({})).join(',') !== 'w,d') throw Error('lost held keys');", - "await key('d', 'up');", - "if ((await tools.check_held_keys({})).join(',') !== 'w') throw Error('lost W');", - ending === 'throw' ? "throw Error('program failed');" : mode.complete("'done'"), - ].join('\n') - const result = await executeProgram(f, name, code, 'Exercise held keys', controller.signal) - expect(events, JSON.stringify(result.content)).toEqual(['w:down', 'd:down', 'd:up', ...ending === 'pause with cleanup error' ? [] : ['w:up']]) - expect(native.cleanup).toHaveBeenCalledTimes(1) - expect(result.isError).toBe(ending !== 'return') - if (ending === 'throw') expect(JSON.stringify(result.content)).toContain('program failed') -}) - -const UNLOAD_PHASES = PTC_MODES.flatMap(mode => (['running', 'settling'] as const).map(phase => ({ mode, phase }))) - -it.each(UNLOAD_PHASES)('awaits held-key cleanup before unloading native resources while the raw $mode.mode program is $phase', async ({ mode, phase }) => { - const f = await setup(undefined, mode) - await selectApplication(f) - const entered: PromiseWithResolvers = Promise.withResolvers() - const programRelease: PromiseWithResolvers = Promise.withResolvers() - const cleanupEntered: PromiseWithResolvers = Promise.withResolvers() - const cleanupRelease: PromiseWithResolvers = Promise.withResolvers() - const events: string[] = [] - native.request.mockClear().mockImplementation(async () => { events.push('key down'); return { dispatched: true } }) - native.cleanup.mockImplementation(async () => { - events.push('release entered') - cleanupEntered.resolve() - await cleanupRelease.promise - expect(native.dispose).not.toHaveBeenCalled() - events.push('release finished') - return { dispatched: true } - }) - native.dispose.mockImplementation(async () => { events.push('native closed') }) - f.ctx.tools.register({ name: 'hold_program', description: 'Wait for the test program release.', - parameters: { type: 'object', properties: {} }, output: { schema: {}, render: () => [] }, - async execute() { entered.resolve(); await programRelease.promise; return null }, - }) - const controller = new AbortController() - let settled = false - const running = executeProgram(f, 'run_code', - "await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'down' } }); await tools.hold_program({}); " + mode.complete("'finished'"), - 'Hold a key during provider unload', controller.signal).then((result) => { settled = true; return result }) - let closing: Promise | undefined - try { - await entered.promise - if (phase === 'settling') { - programRelease.resolve() - await cleanupEntered.promise - } - closing = f.provider.dispose() - expect(await Promise.race([cleanupEntered.promise.then(() => 'cleanup'), closing.then(() => 'closed')])).toBe('cleanup') - expect(native.dispose).not.toHaveBeenCalled() - expect(events).toEqual(['key down', 'release entered']) - cleanupRelease.resolve() - await closing - expect(events).toEqual(['key down', 'release entered', 'release finished', 'native closed']) - if (phase === 'running') expect(settled).toBe(false) - programRelease.resolve() - expect((await running).isError).toBe(false) - expect(native.cleanup).toHaveBeenCalledTimes(1) - expect(native.dispose).toHaveBeenCalledTimes(1) - } finally { - controller.abort() - programRelease.resolve() - cleanupRelease.resolve() - await running - await closing - } -}) - -it.each(PTC_MODES)('closes the native connection after a $mode program held-key cleanup failure and reuses that failure at program settlement', async (mode) => { - const f = await setup(undefined, mode) - await selectApplication(f) - const entered: PromiseWithResolvers = Promise.withResolvers() - const programRelease: PromiseWithResolvers = Promise.withResolvers() - native.request.mockClear().mockResolvedValue({ dispatched: true }) - const failure = new Error('Held-key release was not acknowledged') - native.cleanup.mockRejectedValue(failure) - const reported: unknown[] = [] - const log = vi.spyOn(f.provider.ctx.logger, 'error').mockImplementation((error) => { reported.push(error) }) - onTestFinished(() => { log.mockRestore() }) - f.ctx.tools.register({ name: 'hold_program', description: 'Wait for the test program release.', - parameters: { type: 'object', properties: {} }, output: { schema: {}, render: () => [] }, - async execute() { entered.resolve(); await programRelease.promise; return null }, - }) - const controller = new AbortController() - const running = executeProgram(f, 'run_code', - "await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'down' } }); await tools.hold_program({});", - 'Hold a key before cleanup fails', controller.signal) - try { - await entered.promise - await f.provider.dispose() - expect(native.dispose).toHaveBeenCalledTimes(1) - expect(native.cleanup).toHaveBeenCalledTimes(1) - const aggregate = reported.find(error => error instanceof AggregateError) - expect(aggregate?.errors).toContain(failure) - programRelease.resolve() - const result = await running - expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain(failure.message) - expect(native.cleanup).toHaveBeenCalledTimes(1) - } finally { controller.abort(); programRelease.resolve(); await running } + expect((await executeProgram(f, 'run_code', + mode.complete("await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'down' } })"), 'Hold W')).isError).toBe(false) + expect(held).toEqual(new Set(['w'])) + expect(native.cleanup).not.toHaveBeenCalled() + expect((await executeProgram(f, 'cua_run_code', + mode.complete("await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'up' } })"), 'Release W')).isError).toBe(false) + expect(held.size).toBe(0) + expect(native.cleanup).not.toHaveBeenCalled() + f.handle.agent.cancel({ kind: 'user' }) + await f.handle.agent.whenIdle() + expect(native.cleanup).not.toHaveBeenCalled() }) it('rejects a relative helper path before publishing computer-use operations', async () => { @@ -495,7 +381,7 @@ it('correlates a native request with its logged tool invocation', async () => { expect(native.request).toHaveBeenCalledExactlyOnceWith('listApps', {}, expect.any(AbortSignal), brandString('lifecycle-1')) }) -it('merges startup capabilities into runtime native fields', async () => { +it('reports declared methods outside a turn while merging runtime native fields', async () => { const f = await setup() const runtime = { permissions: { accessibility: true, screenRecording: false }, sessionLocked: false } native.request.mockResolvedValueOnce(runtime) @@ -673,6 +559,7 @@ it('reports failed cleanup after waiting for other owners and releasing their Ag expect(native.dispose).toHaveBeenCalledTimes(2) const aggregate = reported.find(error => error instanceof AggregateError) expect(aggregate?.errors).toContain(failure) + expect(f.ctx.computerUse.providerName).toBeUndefined() const errorsBeforeAgentDisposal = errors.mock.calls.length await Promise.all([f.handle.dispose(), other.dispose()]) expect(native.dispose).toHaveBeenCalledTimes(2) @@ -1286,6 +1173,7 @@ async function hoverFixture(requireApproval = true) { await f.provider.dispose() await f.ctx.plugin(NativeProvider, { ...config, requireSystemInputApproval: false }) } + await thinkingTurn(f) const questions = await f.ctx.plugin(UserQuestions) const questionId = 'cua-system-input' const approved = { answers: [{ id: questionId, selected: ['Allow for this session'] }] } @@ -1354,43 +1242,18 @@ it.each([true, false])('shares the system input decision for a system button wit if (allow) { expect(results.every(result => !result.isError)).toBe(true) expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemInput])) - .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', true]]) - f.handle.agent.session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } }) - expect(native.cleanup).toHaveBeenCalledWith('releaseSystemButton', {}) + .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', undefined]]) + f.handle.agent.cancel({ kind: 'user' }) + await f.handle.agent.whenIdle() + expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', {}) } else { - for (const result of results) expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED') - expect(native.request).not.toHaveBeenCalled() + for (const result of results.slice(0, 2)) expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED') + expect(results[2]?.isError).toBe(false) + expect(native.request.mock.calls.map(([method]) => method)).toEqual(['toggleMouse']) } expect(f.ask).toHaveBeenCalledOnce() }) -it('reports a failed turn-end button release once and forgets the hold', async () => { - const f = await hoverFixture() - const failure = new Error('The release was not acknowledged') - native.cleanup.mockRejectedValueOnce(failure) - const warn = vi.spyOn(f.provider.ctx.logger, 'warn').mockImplementation(() => {}) - onTestFinished(() => { warn.mockRestore() }) - expect((await f.execute('toggleMouse', { appHandle: 'app-one', windowId: '7', mouseButton: 'left', - direction: 'down', useSystemInput: true })).isError).toBe(false) - const session = f.handle.agent.session - session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } }) - await vi.waitFor(() => { - expect(warn).toHaveBeenCalledWith('Could not release system input at turn end: %s', failure) - }) - session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) - expect(native.cleanup).toHaveBeenCalledExactlyOnceWith('releaseSystemButton', {}) -}) - -it('leaves button release to disconnect when application access was revoked before turn end', async () => { - const f = await hoverFixture() - expect((await f.execute('toggleMouse', { appHandle: 'app-one', windowId: '7', mouseButton: 'left', - direction: 'down', useSystemInput: true })).isError).toBe(false) - await f.ctx.cuaAccess.revoke('a'.repeat(64) as Parameters[0]) - expect(native.dispose).toHaveBeenCalled() - f.handle.agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - expect(native.cleanup).not.toHaveBeenCalled() -}) - it.each([true, false])('asks before a system drag and shares the session decision with hover (allow=%s)', async (allow) => { const f = await hoverFixture() const target = { appHandle: 'app-one', windowId: '7', relative: true, fromX: 100, fromY: 200, toX: 300, toY: 400 } @@ -1434,6 +1297,7 @@ it('keeps refusals and grants separate and forgets a closed session on reopen', const sessionId = f.handle.agent.id await f.handle.dispose() const reopened = await f.ctx.agents.create({ sessionId }) + await thinkingTurn({ ...f, handle: reopened }) await f.select(reopened.agent) expect((await f.call(reopened.agent, 'mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: false }, expect.any(AbortSignal), expect.any(String)) @@ -1553,6 +1417,16 @@ it.each([true, false])('uses the declared systemInput capability for a non-macOS expect.any(AbortSignal), expect.any(String)) }) +it('keeps complete system moves available outside a turn without registering a persistent hold', async () => { + const f = await setup(undefined, undefined, { requireSystemInputApproval: false }) + await selectApplication(f) + native.request.mockClear() + expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) + expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) + await f.handle.dispose() + expect(native.cleanup).not.toHaveBeenCalled() +}) + it.each([true, false])('shares approval between system clicks and keyboard chords (allow=%s)', async (allow) => { const f = await hoverFixture() f.ask.mockResolvedValue(allow ? f.approved : { answers: [{ id: 'cua-system-input', selected: ['Deny'] }] }) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index d6b4890821..02dea6227d 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -45,14 +45,14 @@ en: b4b85192e7287a64 zh: 82457adbaa7c2454 /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/token-effect: - en: eea25b57964fd62e - zh: fbd23924f1562960 + en: a1e565f3662c01d9 + zh: 26467072decb772b /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/kv-cache-effect: en: 0b0c63281111993b zh: 45716a56b5a5ad12 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: - en: 7d592e6b49063ae8 - zh: 6f58f0e3a00dd2a8 + en: b1ce029c37a771af + zh: 42390a45e6c440e4 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index a4c7b4e6cb..1fcae5a636 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -157,7 +157,7 @@ The connected harness's model sees `cua_get_api_reference`, the Agent's `cua_run #### Token effect -The tool description carries the registration's execution rules, about 3,200 characters; a `cua_get_api_reference` result is the API reference, about 13,000 characters with the current macOS provider, about 3,300 tokens by the repository's four-character estimate, spent once per call. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the documented Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions and server instructions: Claude Code 2.1.309 forwards the first 4,096 characters of either and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description and the instructions, about 500 characters, fit that budget; the reference does not and travels as a tool result. +The tool description carries the registration's execution rules, about 3,200 characters; a `cua_get_api_reference` result is the API reference, about 13,000 characters with the current macOS provider, about 3,300 tokens by the repository's four-character estimate, spent once per call. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the documented Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions and server instructions: Claude Code 2.1.309 forwards the first 4,096 characters of either and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description and the instructions, about 600 characters, fit that budget; the reference does not and travels as a tool result. #### KV Cache effect @@ -167,6 +167,7 @@ The tool catalog and instructions are stable for one installation. The reference +- Successful programs retain held keys and mouse buttons across calls and report them in a system reminder. Program failure, a received cancellation of an active cua_run_code request, reset and connection closure release owned input. If a call sends down and returns, and the client pauses while its model is thinking, this server receives no cancellation: that input can remain pressed until explicit up or later cleanup. - macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`. - On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`. - Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index 808785398f..b3b7674590 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -157,7 +157,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 #### Token 影响 -工具描述携带注册项的执行规则,约 3,200 个字符;一次 `cua_get_api_reference` 的结果就是 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token,每次调用支付一次。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;文档给出的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述和服务器说明:Claude Code 2.1.309 对二者都只转发前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述和约 500 个字符的服务器说明都在该预算之内;参考超出预算,因此作为工具结果传递。 +工具描述携带注册项的执行规则,约 3,200 个字符;一次 `cua_get_api_reference` 的结果就是 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token,每次调用支付一次。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;文档给出的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述和服务器说明:Claude Code 2.1.309 对二者都只转发前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述和约 600 个字符的服务器说明都在该预算之内;参考超出预算,因此作为工具结果传递。 #### KV Cache 影响 @@ -167,6 +167,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 +- 成功结束的程序跨调用保持键盘键和鼠标按钮,并通过 system reminder 报告。程序失败、执行中的 cua_run_code 请求收到取消、重置和断连会释放所属输入。如果一次调用发送 down 后返回,客户端随后在模型思考期间暂停,服务端收不到取消:该输入可能持续按住,直到显式 up 或后续清理。 - macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。 - 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。 - Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index 6d173e7478..f9c55bef29 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -97,6 +97,7 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop + 'object; program state persists across calls on this connection. A call may ask the user for application or pointer ' + 'consent before it proceeds. Call cua_reset to discard program state.' + const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.' @@ -202,21 +203,48 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti } // The program runtime rejects a run while the Agent's previous process is still exiting. while (resetting !== undefined) await resetting - // The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested - // calls, to settle before the Agent's scope and Session close. - const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({ - calls: [{ - type: 'tool-call', id: brandString(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args), - }], - agent, signal: AbortSignal.any([signal, maintenance]), - }))) - const outcome = batch.results[0] - if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`) const programs = ctx.get('cuaPrograms') - return projectToolResult(outcome.result, batch.additionalContexts, { - attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image), - }, signal) + let cleanup: Promise | undefined + const cancel = (): void => { + cleanup ??= programs?.releaseInputs(agent) ?? Promise.resolve() + void cleanup.catch(() => undefined) // The native owner reports failure; finally joins this same cleanup. + } + signal.addEventListener('abort', cancel, { once: true }) + if (signal.aborted) cancel() + try { + // The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested + // calls, to settle before the Agent's scope and Session close. + const response = await agent.runMaintenance(async (maintenance) => { + const operation = AbortSignal.any([signal, maintenance]) + const batch = await ctx.agents.withInitiator(agent, () => ctx.tools.execute({ + calls: [{ + type: 'tool-call', id: brandString(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args), + }], + agent, signal: operation, + })) + const outcome = batch.results[0] + if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`) + const result = await projectToolResult(outcome.result, batch.additionalContexts, { + attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image), + }, operation) + if (!outcome.result.isError) operation.throwIfAborted() + return result + }) + await cleanup + return response + } catch (error) { + cancel() + try { await cleanup } + catch (failure) { + if (failure === error) throw error + throw new AggregateError([error, failure], `Computer Use request failed: ${String(error)}. Held-input cleanup failed: ${String(failure)}`) + } + throw error + } finally { + signal.removeEventListener('abort', cancel) + } } + const resetEnvironment = (): CallToolResult | Promise => { const programs = ctx.get('cuaPrograms') if (programs === undefined) return failure(NO_PROVIDER) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 5599fe4017..4eb28d6039 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -108,12 +108,12 @@ async function setup(options: SetupOptions = {}) { cua: { inject: ['computerUse', 'subprocess', 'tools', 'systemPrompt', 'agents'], Config: CuaConfig, apply(owner: Context, config: CuaConfig) { - installCua(owner, config, { helperPath: process.execPath, + installCua(owner, config, { helperPath: process.execPath, heldInputState: true, createChannel: options.cancellationAcknowledgementMs === undefined ? native.createChannel : delayCancellation(native.createChannel, options.cancellationAcknowledgementMs, () => { native.events.push('cancellation-acknowledged') }), getGuidance: () => 'Fixture CUA guidance: select test.fixture and operate window 7.', - capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot'], + capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) @@ -182,6 +182,134 @@ async function setup(options: SetupOptions = {}) { } describe('Computer Use MCP composition', () => { + it('retains input across successful MCP programs and reports remaining holds', async () => { + const { native, run } = await setup() + const held = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down"); await win.toggleMouse("left", "down")') + expect(held.isError).not.toBe(true) + expect(native.held.map(press => press.key)).toEqual(['w', 'left']) + expect(native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + expect(texts(held).join('')).toContain('CUA inputs are still held') + expect(texts(await run('inspect("next program")')).join('')).toContain('Key "w"') + const released = await run('await win.toggleMouse("left", "up"); await app.sendKeyEvent("w", "up")') + expect(texts(released).join('')).not.toContain('') + expect(native.held).toEqual([]) + const failed = await run('await win.toggleMouse("left", "down"); throw Error("failed program")') + expect(failed.isError).toBe(true) + expect(native.held).toEqual([]) + expect((await run('await win.click("0")')).isError).not.toBe(true) + }) + + it('waits for cleanup after a failed MCP program and reports native refusal', async () => { + const { native, run } = await setup() + const release = native.controlNext('releaseHeldInputs') + let settled = false + const running = run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down"); throw Error("program failed")').then((value) => { settled = true; return value }) + await release.entered + expect(settled).toBe(false) + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'MCP release refused' }) + const result = await running + expect(result.isError).toBe(true) + const message = texts(result).join('') + expect(message).toContain('program failed') + expect(message.match(/MCP release refused/g)).toHaveLength(1) + }) + + it('cleans up a cancelled MCP request even after its program has finished and image delivery is pending', async () => { + const { ctx, native, run } = await setup() + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + const original = ctx.attachments.readImageRequest.bind(ctx.attachments) + const read = vi.spyOn(ctx.attachments, 'readImageRequest').mockImplementation(async (...args) => { + if (native.calls.some(call => call.method === 'getHeldInputs')) { entered.resolve(); await finish.promise } + return original(...args) + }) + onTestFinished(() => { finish.resolve(); read.mockRestore() }) + const controller = new AbortController() + const running = run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await app.sendKeyEvent("w", "down"); inspect(await win.getScreenshot())', {}, controller.signal) + const cancelled = expect(running).rejects.toThrow(/abort/i) + await entered.promise + const release = native.controlNext('releaseHeldInputs') + try { + controller.abort() + await release.entered + expect(native.held.map(press => press.key)).toEqual(['w']) + release.reply() + } finally { finish.resolve() } + await cancelled + await run('inspect("after cancellation")') + expect(native.held).toEqual([]) + }) + + it.each(['reset', 'image failure', 'cleanup failure'] as const)('cleans up held input when %s interrupts response delivery', async (ending) => { + const { ctx, native, client, run } = await setup() + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + const original = ctx.attachments.readImageRequest.bind(ctx.attachments) + const read = vi.spyOn(ctx.attachments, 'readImageRequest').mockImplementation(async (...args) => { + if (native.calls.some(call => call.method === 'getHeldInputs')) { + entered.resolve() + await finish.promise + if (ending !== 'reset') throw new Error('Fixture screenshot could not be delivered') + } + return original(...args) + }) + onTestFinished(() => { finish.resolve(); read.mockRestore() }) + const running = run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await app.sendKeyEvent("w", "down"); inspect(await win.getScreenshot())') + .then(value => texts(value).join(' '), (error: unknown) => String(error)) + await entered.promise + let reset: ReturnType | undefined + try { + expect(native.held.map(press => press.key)).toEqual(['w']) + if (ending === 'reset') { + let resetDone = false + const release = native.controlNext('releaseHeldInputs') + reset = client.callTool({ name: 'cua_reset', arguments: {} }).then((result) => { resetDone = true; return result }) + await release.entered + release.reply() + expect(resetDone).toBe(false) + } + if (ending === 'cleanup failure') { + const release = native.controlNext('releaseHeldInputs') + finish.resolve() + await release.entered + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Fixture cleanup refused during response delivery' }) + } + } finally { finish.resolve() } + const result = await running + expect(result).not.toContain('CUA inputs are still held') + if (ending !== 'reset') expect(result).toContain('Fixture screenshot could not be delivered') + if (ending === 'cleanup failure') { + expect(result).toContain('Fixture cleanup refused during response delivery') + const next = await run('await win.sendKeyEvent("w", "down")') + expect(texts(next).join(' ')).toContain('INPUT_CLEANUP_UNCONFIRMED') + } else expect(native.held).toEqual([]) + expect((await reset)?.isError).not.toBe(true) + }) + + it('reports refused cleanup after a cancelled MCP request and prevents further native input', async () => { + const { ctx, native, run } = await setup() + await run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")') + const entered: PromiseWithResolvers = Promise.withResolvers() + ctx.on('tools/execute', (execution, next) => { + if (execution.name === 'cua_run_code' && execution.parent === undefined) entered.resolve() + return next() + }) + const release = native.controlNext('releaseHeldInputs') + const controller = new AbortController() + const running = run('await new Promise(() => {})', {}, controller.signal) + const cancelled = expect(running).rejects.toThrow(/abort/i) + await entered.promise + controller.abort() + await release.entered + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Cancellation release refused' }) + await cancelled + const count = native.calls.length + const result = await run('await cua.getApp("test.fixture")') + expect(result.isError).toBe(true) + expect(texts(result).join('')).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(native.calls).toHaveLength(count) + }) + it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => { const { ctx, native, client, run, adapter, directory } = await setup() expect(client.getInstructions()).toContain('Start every conversation by calling cua_get_api_reference') @@ -268,6 +396,26 @@ describe('Computer Use MCP composition', () => { expect(texts(invalid)).toEqual(['invalid arguments: missing required property "description"']) }) + it.each([[true, false], [false, true], [true, true]])('reports reset failures (environment: %s, input: %s)', async (environmentFails, refused) => { + const { native, client, run } = await setup() + await run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")') + const environment = vi.spyOn(NodeRuntime.prototype, 'release') + if (environmentFails) environment.mockRejectedValueOnce(new Error('Fixture process failed to exit')) + onTestFinished(() => { environment.mockRestore() }) + const release = native.controlNext('releaseHeldInputs') + const resetting = client.callTool({ name: 'cua_reset', arguments: {} }) + await release.entered + try { expect(environment).toHaveBeenCalledTimes(1) } finally { + release.reply(refused ? { code: 'INPUT_CLEANUP_FAILED', message: 'Fixture release refused' } : undefined) + } + const result = await resetting + expect(result.isError).toBe(true) + const message = texts(result).join(' ') + if (environmentFails) expect(message).toContain('Fixture process failed to exit') + if (refused) expect(message).toContain('Fixture release refused') + else expect(native.events).toEqual(['w:down', 'w:up']) + }) + it('resets only the program environment: a fresh process and cua object, the same Agent and native connection', async () => { const { ctx, native, run, client, adapter } = await setup() const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); inspect(process.pid)') diff --git a/packages/experimental/cua-mcp/tests/server.spec.ts b/packages/experimental/cua-mcp/tests/server.spec.ts index ac75b00aa4..80e11960cf 100644 --- a/packages/experimental/cua-mcp/tests/server.spec.ts +++ b/packages/experimental/cua-mcp/tests/server.spec.ts @@ -60,11 +60,15 @@ interface SetupOptions { function fixture(options: SetupOptions = {}) { const ctx = new Context() - // The Agent runs a maintenance task at once and cancels it through this controller, as its cancel and disposal do. - const maintenance = new AbortController() + let active: AbortController | undefined const members: Pick = { - id: brandString('cua-mcp-fake'), ctx: new Context(), runMaintenance: task => task(maintenance.signal), - cancel: (cause) => { maintenance.abort(cause) }, whenIdle: async () => {}, + id: brandString('cua-mcp-fake'), ctx: new Context(), + runMaintenance: async (task) => { + const controller = new AbortController() + active = controller + try { return await task(controller.signal) } finally { active = undefined } + }, + cancel: (cause) => { active?.abort(cause) }, whenIdle: async () => {}, } const runMaintenance = vi.spyOn(members, 'runMaintenance') const cancel = vi.spyOn(members, 'cancel') @@ -102,10 +106,10 @@ function fixture(options: SetupOptions = {}) { ctx.provide('tools', { execute, get } as never) ctx.provide('systemPrompt', { assemble } as never) ctx.provide('attachments', {} as never) - if (options.programs !== false) ctx.provide('cuaPrograms', { release, screenshotRequestTarget: () => undefined, ...options.programs } as never) + if (options.programs !== false) ctx.provide('cuaPrograms', { release, releaseInputs: vi.fn(async () => {}), screenshotRequestTarget: () => undefined, ...options.programs } as never) onTestFinished(async () => { await ctx.fiber.dispose() }) return { - ctx, agent, maintenance, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble, + ctx, agent, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble, release, dispose, } } @@ -141,7 +145,7 @@ function texts(result: CallToolResult): string[] { describe('Computer Use MCP server', () => { it('creates the Agent before serving, projects its registration verbatim, and runs programs as Agent maintenance inside the initiator scope', async () => { - const { adapter, client, run, create, mount, execute, withInitiator, initiators, agent, runMaintenance, maintenance } = await setup() + const { adapter, client, run, create, mount, execute, withInitiator, initiators, agent, runMaintenance } = await setup() expect(create).toHaveBeenCalledOnce() expect(create.mock.calls[0]?.[0]).toMatchObject({ meta: { cwd: '/workspace', agentPreset: 'cua-mcp' } }) expect(mount).toHaveBeenCalledWith(agent.ctx) @@ -170,10 +174,6 @@ describe('Computer Use MCP server', () => { expect(withInitiator).toHaveBeenCalledOnce() expect(initiators).toEqual([agent]) expect(texts(await run({ code: '2', description: 'Again' }))).toEqual(['program output']) - // Cancelling the Agent's maintenance activity, as its disposal does, cancels the program's execution. - expect(input.signal.aborted).toBe(false) - maintenance.abort() - expect(input.signal.aborted).toBe(true) }) it('fails the listing when the registration is not representable as an MCP tool', async () => { @@ -347,4 +347,24 @@ describe('Computer Use MCP server', () => { expect(served.dispose).toHaveBeenCalledOnce() await served.client.close() }) + + it('settles a queued request cancelled before admission even without optional input controls', async () => { + const served = await setup({ programs: false }) + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + served.execute.mockImplementationOnce(async () => { entered.resolve(); await finish.promise; return batch('first') }) + const first = served.run({ code: 'first' }) + await entered.promise + const controller = new AbortController() + const queued = served.client.callTool({ name: 'cua_run_code', arguments: { code: 'queued' } }, { signal: controller.signal }) + const cancelled = expect(queued).rejects.toThrow(/abort/i) + try { + await served.client.listTools() + controller.abort() + } finally { finish.resolve() } + await Promise.all([first, cancelled]) + await served.run({ code: 'after cancellation' }) + expect(served.execute.mock.calls[1]?.[0].signal.aborted).toBe(true) + }) + }) diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 9bff802478..d8f5691b5c 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -27,8 +27,8 @@ en: fc5753d540e79693 zh: 3f1fb40c623c6df1 /deepseek-ai-dsh-cua-windows/interaction-rules: - en: f482aa2488612eff - zh: c821c006a36e8f27 + en: f76e73e5ef38aced + zh: ad00327ec3607e0f /deepseek-ai-dsh-cua-windows/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -36,8 +36,8 @@ en: 38b3250d6ae0f3d6 zh: 33d056c416e11d75 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/what-the-model-sees: - en: 8445a0a43022223e - zh: 48d5a3c726bc4bb6 + en: 8949441c259efd34 + zh: 5526a527eb02a0ac /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/token-effect: en: 39eebd53ee226af7 zh: ba7b352cf1e23c3c @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: 68a4a406d55758f3 - zh: 53467eaf88fddb94 + en: ff80ed2855470176 + zh: d3ff1f845594caa1 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 2262041d91..9b3fb24228 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -56,7 +56,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i 4. Treat `dispatched` as dispatch evidence, not confirmation of the intended effect. Observe the result before continuing. On a changed window, stale snapshot, timeout, or cancellation, do not blindly repeat input or switch to another window. 5. Consent applies to the application within the conversation. Respect denial and revocation; do not use another tool to bypass them. Reconnects invalidate retained handles, so select the application again before further operations. -`win.toggleMouse(button, direction)` sends one system mouse button event at the current pointer. The selected window must be in the foreground for both directions. A press also requires a pointer hit on that window; a release can occur outside it. +`win.toggleMouse(button, direction)` sends one system mouse button event at the current pointer. A down requires the selected window to be in the foreground and under the pointer. Release through the original Window object. An up releases the desktop button without switching focus or moving the pointer. ## Model Experience @@ -65,7 +65,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i #### What the model sees -The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. +The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. While one connection holds a key or button, another connection can use different keys or buttons. Program failure, cancellation and reset request release in reverse dispatch order. At disconnect, the helper makes a final bounded release attempt. If it fails or times out, the helper silently discards that connection’s records. #### Token effect @@ -82,7 +82,9 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). - Hover, click, scroll and drag use the system pointer. `requireSystemInputApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. -- The helper does not check each key or button release during cleanup. If an input remains held after a failure, release it manually before continuing. +- Held-input reminders and cleanup use the helper's own dispatches. If you press the same key or button while the helper holds it, its next up can also interrupt your press. +- Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. Releasing a held input does not check the current foreground window or lock state. The release uses the saved up event and reports `foregroundChanged: null` for an explicit up. If Windows refuses an explicit cleanup request, further CUA input for the task is blocked. Inspect the desktop before starting another task. +- Cleanup of temporary input inside complete actions does not check each key or button release. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. - `findApps`, application launch, and app-level accessibility are unavailable. Ask the user to open the required application or window. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index f3c1964d24..5d4f5e18fa 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -56,7 +56,7 @@ kind: "package-reference" 4. `dispatched` 只表示分派情况,不证明预期效果已经发生。继续操作前先观察结果。窗口变化、快照过期、超时或取消后,不要盲目重放输入,也不要自动切换目标窗口。 5. 授权针对当前会话中的应用。尊重拒绝和撤销,不使用其他工具绕过。重新连接会使已保留的句柄失效,继续操作前必须重新选择应用。 -`win.toggleMouse(button, direction)` 在当前指针位置发送一次系统按键事件。按下和松开时,所选窗口都必须在前台。按下时指针还必须命中该窗口,松开时可以移出窗口。 +`win.toggleMouse(button, direction)` 在当前指针位置发送一次系统按键事件。按下时,所选窗口必须在前台,指针也必须命中该窗口。请通过原 Window 对象松开;松开只释放桌面按钮,不切换焦点,也不移动指针。 ## 模型体验 @@ -65,7 +65,7 @@ kind: "package-reference" #### 模型看到什么 -程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。 +程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。一条连接持有按键或鼠标按钮时,其他连接仍可使用不同的键或按钮。程序异常、取消或重置时会请求按派发顺序的反序释放。断连时,helper 会在关闭时限内最后尝试一次。失败或超时后,它会静默丢弃这条连接的持有记录。 #### Token 影响 @@ -82,7 +82,9 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemInputApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 -- 清理输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 +- 持有提醒和清理只依据 helper 自己派发的输入。如果你也按住同一个键或按钮,helper 之后发送的 up 可能打断你的按压。 +- Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。释放时直接发送保存的 up 事件,无需检查当前前台窗口或锁屏状态。显式 up 返回 `foregroundChanged: null`。若 Windows 在处理显式清理请求时拒绝 up,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 +- 清理完整动作内的临时输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 - Windows 握手要求 `maxClickHoldMs` 为正整数。设为 0 会使连接以 `INVALID_CONFIG` 失败,连普通点击和状态查询也不可用。 - 不支持 `findApps`、启动应用和应用级辅助功能。请让用户打开所需应用或窗口。 diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 3371433909..7d82b6da8b 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -11,6 +11,8 @@ internal sealed class FixtureForm : Form internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; + private readonly List inputEvents = []; + private MouseButtons receivedButtons; private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); @@ -20,6 +22,9 @@ internal sealed class FixtureForm : Form StartPosition = FormStartPosition.Manual; Location = new(100, 100); ClientSize = new(500, 300); + KeyPreview = true; + KeyDown += (_, e) => WatchKey(e.KeyCode, "down"); + KeyUp += (_, e) => WatchKey(e.KeyCode, "up"); Controls.Add(Editor); Controls.Add(button); button.Click += (_, _) => clicks++; @@ -30,8 +35,15 @@ internal sealed class FixtureForm : Form tooltip.SetToolTip(button, "CUA hover is retained"); } + private void WatchKey(Keys key, string direction) + { + if (key is Keys.W or Keys.ShiftKey) inputEvents.Add($"{key}:{direction}"); + } + private void Count(MouseButtons pressed, bool down) { + receivedButtons = down ? receivedButtons | pressed : receivedButtons & ~pressed; + inputEvents.Add($"{pressed}:{(down ? "down" : "up")}"); switch (pressed) { case MouseButtons.Left: if (down) leftDowns++; else leftUps++; break; @@ -74,7 +86,8 @@ internal sealed class FixtureForm : Form ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, - buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, + inputEvents = inputEvents.ToArray(), + buttons = receivedButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, }; protected override void Dispose(bool disposing) @@ -92,13 +105,12 @@ internal static class Program { private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } - private static void ReleaseButtons() + private static void SendMouse(params uint[] flags) { - var inputs = new[] { 0x0004u, 0x0010u, 0x0040u } - .Select(flags => new Input { Type = 0, Data = new MouseInput { Flags = flags } }).ToArray(); + var inputs = flags.Select(flag => new Input { Type = 0, Data = new MouseInput { Flags = flag } }).ToArray(); if (SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()) != inputs.Length) { - Console.Error.WriteLine("Fixture could not release every mouse button"); + Console.Error.WriteLine("Fixture could not dispatch all requested mouse events"); Environment.ExitCode = 1; } } @@ -129,12 +141,14 @@ internal static class Program { case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; + case "inspect-sibling": Write(sibling.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; case "pointer": form.PointAtButton(); Write(form.Inspect()); break; case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; case "cover": form.Cover(sibling); Write(new { form = form.Inspect(), sibling = sibling.Inspect() }); break; case "uncover": form.Uncover(sibling); Write(form.Inspect()); break; - case "release-input": ReleaseButtons(); Write(form.Inspect()); break; + case "left-up": SendMouse(0x0004); Write(form.Inspect()); break; + case "release-input": SendMouse(0x0004, 0x0010, 0x0040); Write(form.Inspect()); break; case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; case "hide": form.Hide(); Write(form.Inspect()); break; case "resize": form.Width += 50; Write(form.Inspect()); break; diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 8a308efc90..a3fcba8c11 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -8,6 +8,7 @@ namespace DeepSeek.Cua.Windows; internal sealed class ClientState { + internal Guid Connection { get; } = Guid.NewGuid(); internal Dictionary Apps { get; } = new(StringComparer.Ordinal); internal AppState App(string handle) => Apps.GetValueOrDefault(handle) ?? throw new NativeFailure("STALE_APP", "Select the application again on this connection"); @@ -16,11 +17,12 @@ internal sealed class ClientState internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IAsyncDisposable { + private readonly HeldInputs inputs = new(input => Input.Send(input)); private readonly WindowCapture capture = new(); private readonly ClipboardPaste clipboard = new(); private readonly SemaphoreSlim queue = new(1); - private static object ActionResult(nint before, bool dispatched = true) => new + private static object ActionResult(nint before = 0, bool dispatched = true) => new { dispatched, foregroundChanged = before == 0 || Win32.GetForegroundWindow() == 0 ? (bool?)null : before != Win32.GetForegroundWindow(), @@ -51,7 +53,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation, Action reportFailure) { - var context = new RequestContext(config, cancellation, mta, sta, reportFailure); + var context = new RequestContext(config, cancellation, mta, sta, reportFailure, inputs); if (request.Method == "screenshot") { AppState app; @@ -84,6 +86,28 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA if (request.Method == "getActionSchema") return PatternActions.Schema(String(parameters, "action")); if (request.Method is "requestPermission" or "openPermissionSettings") throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); + if (request.Method == "getHeldInputs") return inputs.Get(state.Connection); + if (request.Method == "releaseHeldInputs") + return inputs.Release(state.Connection, cancellation); + + if (request.Method is "sendKeyEvent" or "toggleMouse") + { + var handle = String(parameters, "appHandle"); + var keyboard = request.Method == "sendKeyEvent"; + var name = keyboard ? Input.HoldKeyName(String(parameters, "key")) : String(parameters, "mouseButton"); + if (String(parameters, "direction") == "up") + { + inputs.Up(state.Connection, handle, WindowId(parameters), name, keyboard); + return ActionResult(); + } + var recipient = state.App(handle); + var before = Win32.GetForegroundWindow(); + var target = Selected(recipient, parameters, context); + var dispatched = keyboard + ? Input.KeyDown(state.Connection, recipient, target, name, context) + : Input.ButtonDown(state.Connection, recipient, target, name, context); + return ActionResult(before, dispatched); + } DesktopSession.RequireInteractive(); if (request.Method == "listApps") return await DesktopWindows.ListApps(context); if (request.Method == "findApps") @@ -140,12 +164,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA Input.Press(app, target, String(parameters, "key"), Modifiers(parameters), context); return ActionResult(foreground); } - case "sendKeyEvent": - { - var target = Selected(app, parameters, context); - var dispatched = Input.KeyEvent(app, target, String(parameters, "key"), String(parameters, "direction"), context); - return ActionResult(foreground, dispatched); - } case "paste": { var target = Selected(app, parameters, context); @@ -171,12 +189,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var pointed = Coordinate(app, parameters, context); return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); } - case "toggleMouse": - { - var target = Selected(app, parameters, context); - Input.ToggleMouse(app, target, String(parameters, "mouseButton"), String(parameters, "direction"), context); - return ActionResult(foreground); - } case "scroll": { var target = Coordinate(app, parameters, context); @@ -279,9 +291,12 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA finally { queue.Release(); } } + internal Task ReleaseConnection(ClientState state, int graceMs) => + inputs.ReleaseOnDisconnect(state.Connection, queue, graceMs); + public ValueTask DisposeAsync() { queue.Dispose(); - return default; + return ValueTask.CompletedTask; } } diff --git a/packages/experimental/cua-windows/native/entry/Dispatchers.cs b/packages/experimental/cua-windows/native/entry/Dispatchers.cs index 4fec3bd8a0..406420cd9a 100644 --- a/packages/experimental/cua-windows/native/entry/Dispatchers.cs +++ b/packages/experimental/cua-windows/native/entry/Dispatchers.cs @@ -157,12 +157,13 @@ internal sealed class StaDispatcher : IAsyncDisposable } internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta, - Action reportFailure) + Action reportFailure, HeldInputs heldInputs) { internal NativeConfig Config { get; } = config; internal CancellationToken Cancellation { get; } = cancellation; internal MtaDispatcher Mta { get; } = mta; internal StaDispatcher Sta { get; } = sta; + internal HeldInputs HeldInputs { get; } = heldInputs; internal void Check() => Cancellation.ThrowIfCancellationRequested(); internal T Ax(Func call) diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs new file mode 100644 index 0000000000..1ba8f89d10 --- /dev/null +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -0,0 +1,117 @@ +// Held keys and buttons share one dispatch order across all connections to this desktop executor. +using System.Globalization; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class HeldInputs(Action send) +{ + internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted); + private sealed record Press(Guid Connection, Target Target, ushort Control, string Name, Win32.Input Up) + { + internal object Describe() => new + { + kind = Up.Type == 1 ? "key" : "mouse", key = Up.Type == 1 ? Name : null, + button = Up.Type == 0 ? Name : null, appHandle = Target.AppHandle, + windowId = Target.Window.ToString(CultureInfo.InvariantCulture), mode = "system", + }; + } + + private readonly object gate = new(); + private readonly List pressed = []; + + internal void RequireAvailable(ushort control) + { + lock (gate) + if (pressed.Any(press => press.Control == control)) + throw new NativeFailure("INPUT_BUSY", "This key or button is already held; release it before a complete action uses it"); + } + + internal bool Down(Guid connection, Target target, ushort control, string name, Win32.Input down, + Win32.Input up, CancellationToken cancellation) + { + lock (gate) + { + cancellation.ThrowIfCancellationRequested(); + var existing = pressed.Find(press => press.Control == control); + if (existing is not null) + { + if (existing.Connection == connection && existing.Target == target && existing.Name == name) + return false; + throw new NativeFailure("INPUT_BUSY", "This key or button is already held by another input target"); + } + + var press = new Press(connection, target, control, name, up); + pressed.Add(press); + try { send(down); } + catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") + { + // SendInput accepted zero events, so there is no corresponding up to send. + pressed.Remove(press); + throw; + } + return true; + } + } + + internal void Up(Guid connection, string app, nint? window, string name, bool keyboard) + { + lock (gate) + { + var index = pressed.FindIndex(press => press.Connection == connection && press.Target.AppHandle == app + && press.Target.Window == window && press.Name == name && (press.Up.Type == 1) == keyboard); + if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This connection did not hold that input on the selected window"); + ReleaseAt(index); + } + } + + internal object[] Get(Guid connection) + { + lock (gate) + return pressed.Where(press => press.Connection == connection).Select(press => press.Describe()).ToArray(); + } + + internal async Task ReleaseOnDisconnect(Guid connection, SemaphoreSlim desktopQueue, int graceMs) + { + lock (gate) + if (!pressed.Exists(press => press.Connection == connection)) return; + + using var deadline = new CancellationTokenSource(graceMs); + try + { + await desktopQueue.WaitAsync(deadline.Token); + try { Release(connection, deadline.Token); } + finally { desktopQueue.Release(); } + } + catch (Exception error) + { + _ = error; // The disconnected owner cannot retry or receive a cleanup result. + lock (gate) pressed.RemoveAll(press => press.Connection == connection); + } + } + + internal object[] Release(Guid connection, CancellationToken cancellation) + { + lock (gate) + { + var released = new List(); + var failures = new List(); + for (var index = pressed.Count - 1; index >= 0; index--) + { + var press = pressed[index]; + if (press.Connection != connection) continue; + cancellation.ThrowIfCancellationRequested(); + try { ReleaseAt(index); released.Add(press.Describe()); } + catch (NativeFailure error) { failures.Add(error.Message); } + } + if (failures.Count != 0) throw new NativeFailure("INPUT_CLEANUP_FAILED", string.Join("; ", failures)); + return released.ToArray(); + } + } + + private void ReleaseAt(int index) + { + send(pressed[index].Up); + pressed.RemoveAt(index); + } +} diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 9d186055d5..4463387700 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -22,21 +22,31 @@ internal static class Input private static Win32.Input Mouse(uint flags, int x = 0, int y = 0, uint data = 0) => new() { Type = 0, Data = new() { Mouse = new() { X = x, Y = y, Data = data, Flags = flags } } }; - private static void Send(params Win32.Input[] events) + internal static void Send(params Win32.Input[] events) => SendSequence(events); + + private static void SendSequence(Win32.Input[] events, Action? partial = null) { - if (Win32.SendInput((uint)events.Length, events, Marshal.SizeOf()) != events.Length) - throw new NativeFailure("INPUT_BLOCKED", "Windows did not dispatch all input; privileges or user input may have intervened. Observe before retrying"); + var dispatched = Win32.SendInput((uint)events.Length, events, Marshal.SizeOf()); + if (dispatched == events.Length) return; + partial?.Invoke((int)dispatched); + throw new NativeFailure("INPUT_BLOCKED", "Windows did not dispatch all input; privileges or user input may have intervened. Observe before retrying"); } private static void Release(Win32.Input input) => Win32.SendInput(1, [input], Marshal.SizeOf()); - private static void WithModifiers(IEnumerable modifiers, Action action) + private static void WithModifiers(IEnumerable modifiers, RequestContext context, Action action) { var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); var attempted = new List(); try { - foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); } + foreach (var key in keys) + { + context.Check(); + context.HeldInputs.RequireAvailable(key); + Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); + attempted.Add(key); + } action(); } finally { foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == VkLeftWin ? 1u : 0))); } @@ -83,16 +93,26 @@ internal static class Input return ((ushort)(mapped & 0xFF), false, modifiers.ToArray()); } - internal static bool KeyEvent(AppState app, WindowState window, string name, string direction, RequestContext context) + internal static string HoldKeyName(string name) => name.ToLowerInvariant() switch + { + "control" => "ctrl", + "return" => "enter", + "esc" => "escape", + "forwarddelete" => "delete", + "arrowleft" => "left", "arrowright" => "right", "arrowup" => "up", "arrowdown" => "down", + "kp_plus" => "kp_add", "kp_minus" => "kp_subtract", "kp_period" => "kp_decimal", + var key => key, + }; + + internal static bool KeyDown(Guid connection, AppState app, WindowState window, string name, RequestContext context) { Windows.RequireForeground(app, window, context); var key = ResolveKey(name, includeModifiers: true); if (key.Modifiers.Length != 0) throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately"); - var down = direction == "down"; - if (((Win32.GetAsyncKeyState(key.Key) & 0x8000) != 0) == down) return false; - Send(Keyboard(key.Key, flags: (key.Extended ? 1u : 0) | (down ? 0u : 2u))); - return true; + var flags = key.Extended ? 1u : 0; + return context.HeldInputs.Down(connection, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), + key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation); } internal static void Press(AppState app, WindowState window, string key, string[] modifiers, RequestContext context) @@ -100,12 +120,13 @@ internal static class Input Windows.RequireForeground(app, window, context); var held = KeyChord.ModifiersForPress(key, modifiers); var resolved = ResolveKey(key); - WithModifiers(held.Concat(resolved.Modifiers), () => + WithModifiers(held.Concat(resolved.Modifiers), context, () => { Windows.RequireForeground(app, window, context); + context.HeldInputs.RequireAvailable(resolved.Key); var flags = resolved.Extended ? 1u : 0; - try { Send(Keyboard(resolved.Key, flags: flags), Keyboard(resolved.Key, flags: flags | 2)); } - catch { Release(Keyboard(resolved.Key, flags: flags | 2)); throw; } + SendSequence([Keyboard(resolved.Key, flags: flags), Keyboard(resolved.Key, flags: flags | 2)], + accepted => { if (accepted == 1) Release(Keyboard(resolved.Key, flags: flags | 2)); }); }); } @@ -123,8 +144,8 @@ internal static class Input } else { - try { Send(Keyboard(0, character, 4), Keyboard(0, character, 6)); } - catch { Release(Keyboard(0, character, 6)); throw; } + SendSequence([Keyboard(0, character, 4), Keyboard(0, character, 6)], + accepted => { if (accepted == 1) Release(Keyboard(0, character, 6)); }); } if (context.Config.TextEventIntervalMs > 0) await Task.Delay(TimeSpan.FromMilliseconds(context.Config.TextEventIntervalMs * 2), context.Cancellation); @@ -140,9 +161,9 @@ internal static class Input (int)Math.Round((point.X - left) * 65535d / (width - 1)), (int)Math.Round((point.Y - top) * 65535d / (height - 1))); } - private static (uint Down, uint Up) Button(string button) => button switch + private static (ushort Control, uint Down, uint Up) Button(string button) => button switch { - "left" => (0x0002, 0x0004), "right" => (0x0008, 0x0010), "middle" => (0x0020, 0x0040), + "left" => (1, 0x0002, 0x0004), "right" => (2, 0x0008, 0x0010), "middle" => (4, 0x0020, 0x0040), _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown mouse button"), }; @@ -162,16 +183,13 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } - internal static void ToggleMouse(AppState app, WindowState window, string button, string direction, RequestContext context) + internal static bool ButtonDown(Guid connection, AppState app, WindowState window, string button, RequestContext context) { var flags = Button(button); - if (direction == "down") - { - if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); - Hit(app, window, point, context); - } - else Windows.RequireForeground(app, window, context); - Send(Mouse(direction == "down" ? flags.Down : flags.Up)); + if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Hit(app, window, point, context); + return context.HeldInputs.Down(connection, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), + flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation); } internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) @@ -180,14 +198,15 @@ internal static class Input var geometry = window.RequireObservation(app, context); var point = WindowState.Point(geometry, x, y); var flags = Button(button); + context.HeldInputs.RequireAvailable(flags.Control); Hit(app, window, point, context); - WithModifiers(modifiers, () => + WithModifiers(modifiers, context, () => { point = WindowState.Point(window.RequireObservation(app, context), x, y); Hit(app, window, point, context); var events = new List { Move(point) }; for (var click = 0; click < count; click++) { events.Add(Mouse(flags.Down)); events.Add(Mouse(flags.Up)); } - try { Send(events.ToArray()); } catch { Release(Mouse(flags.Up)); throw; } + SendSequence(events.ToArray(), accepted => { if (accepted >= 2 && accepted % 2 == 0) Release(Mouse(flags.Up)); }); }); } @@ -197,20 +216,27 @@ internal static class Input var point = WindowState.Point(window.RequireObservation(app, context), x, y); var flags = Button(button); var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + context.HeldInputs.RequireAvailable(flags.Control); Hit(app, window, point, context); var attempted = new List(); var buttonAttempted = false; try { - foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); } + foreach (var key in keys) + { + context.Check(); + context.HeldInputs.RequireAvailable(key); + Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); + attempted.Add(key); + } point = WindowState.Point(window.RequireObservation(app, context), x, y); Hit(app, window, point, context); Send(Move(point)); for (var click = 0; click < count; click++) { Hit(app, window, point, context); - buttonAttempted = true; Send(Mouse(flags.Down)); + buttonAttempted = true; await Task.Delay(holdMs, context.Cancellation); Windows.RequireForeground(app, window, context); Send(Mouse(flags.Up)); @@ -241,22 +267,29 @@ internal static class Input internal static async Task Drag(AppState app, WindowState window, double fromX, double fromY, double toX, double toY, string button, string[] modifiers, int durationMs, int steps, RequestContext context) { + var flags = Button(button); + context.HeldInputs.RequireAvailable(flags.Control); var geometry = window.RequireObservation(app, context); var from = WindowState.Point(geometry, fromX, fromY); _ = WindowState.Point(geometry, toX, toY); Hit(app, window, from, context); - var flags = Button(button); var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); var attempted = new List(); var buttonAttempted = false; try { - foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); } + foreach (var key in keys) + { + context.Check(); + context.HeldInputs.RequireAvailable(key); + Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); + attempted.Add(key); + } geometry = window.RequireObservation(app, context); from = WindowState.Point(geometry, fromX, fromY); Hit(app, window, from, context); - buttonAttempted = true; Send(Move(from), Mouse(flags.Down)); + buttonAttempted = true; for (var step = 1; step <= steps; step++) { await Task.Delay(TimeSpan.FromMilliseconds(durationMs / (double)steps), context.Cancellation); diff --git a/packages/experimental/cua-windows/native/entry/NativeServer.cs b/packages/experimental/cua-windows/native/entry/NativeServer.cs index 9f973a8840..2b4941c723 100644 --- a/packages/experimental/cua-windows/native/entry/NativeServer.cs +++ b/packages/experimental/cua-windows/native/entry/NativeServer.cs @@ -97,6 +97,7 @@ internal static class NativeServer { var state = new ClientState(); Task? active = null; + TaskCompletionSource? replying = null; CancellationTokenSource? cancellation = null; string? latestRequestId = null; var closeRequested = false; @@ -136,7 +137,7 @@ internal static class NativeServer continue; } var request = NativeRequest.Parse(value); - if (active is { IsCompleted: false }) + if (active is { IsCompleted: false } && replying?.Task.IsCompleted != true) { await Write(pipe, writer, Failure(request.Id, "NATIVE_BUSY", "The previous native operation has not stopped; do not send further input until it finishes"), config.MaxResponseBytes, config.GraceMs, lifetime.Token); @@ -147,7 +148,8 @@ internal static class NativeServer cancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); cancellation.CancelAfter(request.Method == "screenshot" ? Math.Min(config.TimeoutMs, config.ScreenshotTimeoutMs) : config.TimeoutMs); latestRequestId = request.Id; - active = Dispatch(request, state, executor, config, pipe, writer, cancellation.Token, lifetime.Token); + replying = new(TaskCreationOptions.RunContinuationsAsynchronously); + active = Dispatch(request, state, executor, config, pipe, writer, replying, cancellation.Token, lifetime.Token); } } catch (Exception error) @@ -164,7 +166,11 @@ internal static class NativeServer } catch (NativeFailure error) when (error.Code == "NATIVE_CLEANUP") { throw; } catch (Exception error) { Report("NATIVE_CONNECTION", error); } - finally { cancellation?.Dispose(); } + finally + { + cancellation?.Dispose(); + await executor.ReleaseConnection(state, cleanupTimeoutMs); + } state.Clear(); if (closeRequested) await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); @@ -173,16 +179,16 @@ internal static class NativeServer } private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, - Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) + Stream pipe, SemaphoreSlim writer, TaskCompletionSource replying, CancellationToken cancellation, CancellationToken connection) { var operationStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); var failure = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // A synchronous native call must not block the pipe reader or its timeout response. var operation = Task.Run(() => executor.Execute(request, state, config, operationStop.Token, error => { failure.TrySetResult(error); })); + object response; try { - object response; try { response = new { id = request.Id, result = await WatchOperation(operation, failure.Task, operationStop.Token, config.GraceMs) }; } catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } catch (NativeFailure error) @@ -195,9 +201,6 @@ internal static class NativeServer catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } - var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); - if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); - await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); } finally { @@ -217,6 +220,10 @@ internal static class NativeServer }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } + replying.SetResult(); + var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); + if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); + await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); } private static object Failure(string id, string code, string message) => new { id, error = new { code, message } }; diff --git a/packages/experimental/cua-windows/native/entry/Win32.cs b/packages/experimental/cua-windows/native/entry/Win32.cs index 65ce6f8b58..7f15ab66c4 100644 --- a/packages/experimental/cua-windows/native/entry/Win32.cs +++ b/packages/experimental/cua-windows/native/entry/Win32.cs @@ -62,7 +62,6 @@ internal static class Win32 [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ShowWindowAsync(nint window, int command); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info); [DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint count, Input[] inputs, int size); - [DllImport("user32.dll")] internal static extern short GetAsyncKeyState(int key); [DllImport("user32.dll")] internal static extern nint GetKeyboardLayout(uint thread); [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern short VkKeyScanEx(char character, nint layout); [DllImport("user32.dll")] internal static extern int GetSystemMetrics(int index); diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index a7e177c875..a0f3e7e40e 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -1484,6 +1484,52 @@ "params" ], "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getHeldInputs" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "releaseHeldInputs" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false } ] } diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs new file mode 100644 index 0000000000..3b3b017ef3 --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -0,0 +1,101 @@ +// The receiver records accepted dispatches and can refuse an individual down or up. +using System.Text.Json; +using DeepSeek.Cua.Protocol; +using DeepSeek.Cua.Windows; + +internal static class HeldInputChecks +{ + internal static void Run(Action check, Action refuses) + { + var a = Guid.NewGuid(); + var b = Guid.NewGuid(); + var target = new HeldInputs.Target("app", 72, 122, 100); + var events = new List(); + var blocked = false; + void Receive(Win32.Input input) + { + if (blocked) throw new NativeFailure("INPUT_BLOCKED", "SendInput returned zero"); + var isKey = input.Type == 1; + var control = isKey ? input.Data.Keyboard.Key : (ushort)1; + var up = isKey ? (input.Data.Keyboard.Flags & 2) != 0 : input.Data.Mouse.Flags == 4; + events.Add($"{control}:{(up ? "up" : "down")}"); + } + var inputs = new HeldInputs(Receive); + + bool Key(Guid connection, ushort key, string name, CancellationToken cancellation = default) + => inputs.Down(connection, target, key, name, + new() { Type = 1, Data = new() { Keyboard = new() { Key = key } } }, + new() { Type = 1, Data = new() { Keyboard = new() { Key = key, Flags = 2 } } }, + cancellation); + + refuses(() => inputs.Up(a, "app", 72, "shift", true), "INPUT_NOT_HELD"); + check(events.Count == 0, "No up is sent for a key the helper never pressed"); + blocked = true; + refuses(() => Key(a, 16, "shift"), "INPUT_BLOCKED"); + check(inputs.Get(a).Length == 0, "A refused down does not cause an up"); + blocked = false; + check(Key(a, 16, "shift"), "Record the accepted keyboard down"); + check(inputs.Down(a, target, 1, "left", + new() { Data = new() { Mouse = new() { Flags = 2 } } }, + new() { Data = new() { Mouse = new() { Flags = 4 } } }, default), "Record the accepted mouse down"); + check(Key(a, 87, "w") && !Key(a, 87, "w"), "A repeated key does not duplicate a hold"); + refuses(() => Key(b, 87, "w"), "INPUT_BUSY"); + refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY"); + refuses(() => inputs.Up(b, "app", 72, "w", true), "INPUT_NOT_HELD"); + refuses(() => inputs.Up(a, "app", 73, "w", true), "INPUT_NOT_HELD"); + check(inputs.Release(b, default).Length == 0, "Another connection releases nothing"); + check(inputs.Get(b).Length == 0 && inputs.Get(a).Length == 3, "State query is connection-scoped"); + var described = JsonSerializer.SerializeToElement(inputs.Get(a), WireJson.Options); + check(described[0].GetProperty("windowId").GetString() == "72" && described[0].GetProperty("mode").GetString() == "system", + "Keyboard reminders identify the window and actual desktop mode"); + inputs.Up(a, "app", 72, "shift", true); + check(Key(a, 16, "shift"), "Explicit up and repress update the dispatch order"); + check(inputs.Release(a, default).Length == 3 + && events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress"); + check(inputs.Release(a, default).Length == 0, "Duplicate connection cleanup sends no up"); + Key(a, 87, "w"); + Key(b, 68, "d"); + var beforeRelease = events.Count; + inputs.Up(a, "app", 72, "w", true); + check(inputs.Get(b).Length == 1 && events.Skip(beforeRelease).SequenceEqual(["87:up"]), + "One connection can release W while another holds D"); + inputs.Up(b, "app", 72, "d", true); + using (var cancelled = new CancellationTokenSource()) + { + cancelled.Cancel(); + try { Key(a, 87, "w", cancelled.Token); throw new Exception("Expected cancelled down"); } + catch (OperationCanceledException) { check(inputs.Get(a).Length == 0, "Cancelled down never dispatches"); } + } + Key(a, 87, "w"); + blocked = true; + refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED"); + check(inputs.Get(a).Length == 1, "A refused release stays recorded for disconnect fallback"); + blocked = false; + // Another source releases W and presses D at the same receiver. + Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 87, Flags = 2 } } }); + Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 68 } } }); + described = JsonSerializer.SerializeToElement(inputs.Get(a), WireJson.Options); + check(described.GetArrayLength() == 1 && described[0].GetProperty("key").GetString() == "w", + "The reminder still reports only the helper's W down"); + var count = events.Count; + using var desktopQueue = new SemaphoreSlim(1, 1); + inputs.ReleaseOnDisconnect(a, desktopQueue, 1000).GetAwaiter().GetResult(); + check(inputs.Get(a).Length == 0 && events.Skip(count).SequenceEqual(["87:up"]), + "Disconnect retries the helper's W release and leaves D alone"); + + Key(b, 68, "d"); + foreach (var occupied in new[] { false, true }) + { + Key(a, 87, "w"); + if (occupied) desktopQueue.Wait(); + blocked = !occupied; + inputs.ReleaseOnDisconnect(a, desktopQueue, occupied ? 0 : 1000).GetAwaiter().GetResult(); + blocked = false; + check(inputs.Get(a).Length == 0 && inputs.Get(b).Length == 1, + "Refused or expired disconnect cleanup drops only the disconnected owner's records"); + if (occupied) desktopQueue.Release(); + } + check(Key(b, 87, "w"), "The remaining connection can use W after disconnect cleanup fails"); + inputs.Release(b, default); + } +} diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index d717dc3937..ec1512f315 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -74,6 +74,7 @@ foreach (var direction in new[] { "down", "up" }) } foreach (var invalid in new[] { + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","taskId":"other"}""", """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", """{"appHandle":"app","windowId":"1","direction":"down"}""", """{"appHandle":"app","mouseButton":"left","direction":"down"}""", @@ -83,6 +84,14 @@ foreach (var invalid in new[] }) Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); +foreach (var method in new[] { "getHeldInputs", "releaseHeldInputs" }) +{ + var query = $$$"""{"id":"holds","method":"{{{method}}}","params":{}}"""; + Check(NativeRequest.Parse(WireJson.Parse(query)).Method == method, "Held-input operations use the requesting connection"); + Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"other"}}""")), "INVALID_ARGUMENT"); +} +HeldInputChecks.Run(Check, Refuses); + var actionSchema = NativeRequest.Parse(WireJson.Parse("""{"id":"schema","method":"getActionSchema","params":{"action":"Invoke.Invoke"}}""")); Check(actionSchema.Params.EnumerateObject().Select(item => item.Name).SequenceEqual(["action"]), "Action schema requests carry only the exact action name"); diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj index 7d1a1ef893..f919e04987 100644 --- a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -11,6 +11,8 @@ + + diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts index 166581fae9..a3e6b7cab9 100644 --- a/packages/experimental/cua-windows/src/guidance.ts +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** Windows operation levels, application selectors, and input availability. */ -export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl.' +export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl. Key and mouse holds use desktop input. Keep the target in front while holding inputs. Release through the same window. After focus changes, an up releases desktop input without restoring focus; the original window may not receive that event.' const methodDetails = new Map([ ['cua.getApp', 'Windows accepts an exact AUMID returned by listApps or an existing absolute .exe path, including an executable absent from listApps. Display names and PIDs are not alternative selectors. Selection uses the existing application consent flow and starts the application only when it is not running.'], diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index a45cb2a8b2..f5f6270aa4 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -86,9 +86,9 @@ export async function apply(ctx: Context, config: Config): Promise { const helperPath = await prepared controller.signal.throwIfAborted() const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, config.timeoutMs, host === 'wsl' ? 'stdio' : 'pipe') - ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') installCua(ctx, config, { helperPath, createChannel: (_owner, native) => runtime.connect(native), getGuidance: () => GUIDANCE, capabilities: CAPABILITIES, + disposeNative: () => runtime.dispose(), heldInputState: true, permissionParameters: (_method, permission) => ({ permission }), }) } diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index 25a37bb8e2..53b8ac4d8f 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -15,6 +15,7 @@ const Counts = z.object({ left: z.number().int(), right: z.number().int(), middl const FixtureState = z.object({ window: z.string(), foreground: z.string(), cursor: z.object({ x: z.number().int(), y: z.number().int() }), + inputEvents: z.array(z.string()), under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, }) const Initial = z.object({ pid: z.number().int(), state: FixtureState }) @@ -65,7 +66,7 @@ async function releaseAndClose(fixture: Fixture): Promise { } it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( - 'toggles mouse buttons without movement, observation, or implicit release', + 'holds Windows keys and buttons through the helper and releases owned input in dispatch order', async ({ onTestFinished, signal }) => { const fixture = fixtureProcess(fixturePath!) const ctx = new Context() @@ -73,7 +74,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( onTestFinished(async () => { const errors: unknown[] = [] for (const cleanup of [ - () => releaseAndClose(fixture), ...cleanups.toReversed(), () => ctx.fiber.dispose(), + ...cleanups.toReversed(), () => releaseAndClose(fixture), () => ctx.fiber.dispose(), ]) { try { await cleanup() } catch (error) { errors.push(error) } } @@ -142,4 +143,57 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( expect(outside.under).not.toBe(outside.window) expect((await toggle('left', 'up')).dispatched).toBe(true) await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) + + const target = { appHandle: app.appHandle, windowId } + const key = (key: string, direction: 'down' | 'up') => native.request('sendKeyEvent', { ...target, key, direction }, signal) + const holds = () => native.request('getHeldInputs', {}, signal) + const released = z.array(z.object({ kind: z.string(), key: z.string().nullable(), button: z.string().nullable(), mode: z.literal('system') })) + await fixture.command('pointer', FixtureState) + const offset = (await inspect()).inputEvents.length + await key('shift', 'down') + await toggle('left', 'down') + await expect(native.request('drag', { appHandle: app.appHandle, windowId, fromX: 20, fromY: 20, toX: 30, toY: 30, + mouseButton: 'left', durationMs: 100, steps: 2 }, signal)).rejects.toMatchObject({ code: 'INPUT_BUSY' }) + await key('w', 'down') + expect(released.parse(await holds()).map(input => input.key ?? input.button)).toEqual(['shift', 'left', 'w']) + + const other = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => nativeRuntime.connect(config)) + cleanups.push(() => other.dispose()) + const otherApp = App.parse(await other.request('getApp', { selector: fixturePath! }, signal)) + expect(await other.request('getHeldInputs', {}, signal)).toEqual([]) + expect(await other.requestCleanup('releaseHeldInputs', {})).toEqual([]) + await expect(other.request('sendKeyEvent', { ...target, appHandle: otherApp.appHandle, key: 'w', direction: 'up' }, signal)) + .rejects.toMatchObject({ code: 'INPUT_NOT_HELD' }) + const release = await native.requestCleanup('releaseHeldInputs', {}) + expect(released.parse(release).map(input => input.key ?? input.button)).toEqual(['w', 'left', 'shift']) + await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual( + ['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up']) + + const beforeExternal = await inspect() + await toggle('left', 'down') + await observed({ downs: { left: beforeExternal.downs.left + 1 } }) + await fixture.command('left-up', FixtureState) + await observed({ ups: { left: beforeExternal.ups.left + 1 } }) + expect(released.parse(await holds()).map(input => input.button)).toEqual(['left']) + const afterExternal = await native.requestCleanup('releaseHeldInputs', {}) + expect(released.parse(afterExternal).map(input => input.button)).toEqual(['left']) + expect(await holds()).toEqual([]) + + const beforeSwitch = (await inspect()).inputEvents.length + await key('w', 'down') + await expect.poll(async () => (await inspect()).inputEvents.slice(beforeSwitch)).toContain('W:down') + const switched = await fixture.command('sibling', FixtureState) + expect(switched.foreground).toBe(switched.window) + const peerTarget = { appHandle: otherApp.appHandle, windowId: switched.window, key: 'd' } + await other.request('sendKeyEvent', { ...peerTarget, direction: 'down' }, signal) + await native.dispose() + await expect.poll(async () => { + const sibling = await fixture.command('inspect-sibling', FixtureState) + return { foreground: sibling.foreground, events: sibling.inputEvents.slice(switched.inputEvents.length) } + }).toEqual({ foreground: switched.window, events: ['W:up'] }) + expect(released.parse(await other.request('getHeldInputs', {}, signal)).map(input => input.key)).toEqual(['d']) + await fixture.command('focus', FixtureState) + expect(await other.request('sendKeyEvent', { ...peerTarget, direction: 'up' }, signal)) + .toMatchObject({ dispatched: true, foregroundChanged: null }) }, 120_000) diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index 5bcdc13377..4825461900 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -31,10 +31,11 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemInput') + expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('a system reminder lists any remaining keys and mouse buttons') const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text .split('\n').find(line => line.startsWith('- toggleMouse(')) expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") - expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(toggleMouse).toContain("Send 'up' to release a held button immediately.") expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') expect(toggleMouse).not.toContain('Not implemented') expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemInput') diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts index 081906f6fd..77e6c022b7 100644 --- a/packages/experimental/cua-windows/tests/protocol.spec.ts +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -1,12 +1,14 @@ /** Both native languages admit the same generated model and Host operation fields. */ -import { readFile } from 'node:fs/promises' import { expect, it } from 'vitest' -import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { ActionResult, NativeScreenshotResult } from '@deepseek-ai/dsh-cua/protocol' import { Config } from '../src/index.ts' -it('keeps the C# admission schema identical to the shared generated schema', async () => { - expect(await readFile(new URL('../native/protocol.schema.json', import.meta.url), 'utf8')).toBe(nativeProtocol().json) +it('keeps the C# admission schema current with the Windows generator', () => { + const result = spawnSync(process.execPath, ['--import', 'tsx', fileURLToPath(new URL('../native/generate-protocol.ts', import.meta.url)), '--check'], + { encoding: 'utf8' }) + expect(result.status, result.stderr).toBe(0) }) it('preserves Windows physical capture units and observed foreground changes', () => { diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index c66cb7edb9..3ef2198327 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -36,7 +36,7 @@ it('rejects relative overrides before installing a native provider', async () => await expect(apply(owner(), Config({ helperPath: 'relative.exe' }))).rejects.toThrow('must be absolute') expect(native.install).not.toHaveBeenCalled() }) -it('uses an absolute fixture without compiling and disposes the Host runtime', async () => { +it('provides the Host runtime cleanup to CUA when using an absolute helper override', async () => { const ctx = owner(), config = Config({ helperPath: resolve('fixture.exe'), pollIntervalMs: 13 }) await apply(ctx, config) expect(native.prepare).not.toHaveBeenCalled() @@ -51,13 +51,14 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.capabilities.methods).toContain('getActionSchema') expect(backend.capabilities.methods).toContain('sendKeyEvent') expect(backend.capabilities.methods).toContain('toggleMouse') - expect(backend.sendKeyEvent).toBeUndefined() + expect(backend.heldInputState).toBe(true) + expect(GUIDANCE).toContain('Key and mouse holds use desktop input.') const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } expect(backend.createChannel(ctx, options)).toBe(channel) expect(native.connect).toHaveBeenCalledWith(options) - await ctx.fiber.dispose() + await backend.disposeNative?.() expect(native.dispose).toHaveBeenCalledOnce() }) it('prepares before installation and aborts the completed preparation scope on unload', async () => { diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 85f44167f9..b4fc257373 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: e063496a8a67584f - zh: ba25b0fc57affe94 + en: 7754a370ed7e54ff + zh: a3fa369e265746ad /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 zh: 039340042676881d diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 00d15d8841..c898816811 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,6 +91,10 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership +Providers implementing `CuaBackend.heldInputState` return the requesting connection’s holds through `getHeldInputs({})` and acknowledge their release through `releaseHeldInputs({})`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. + +Each Agent uses its own native input connection across programs and turns. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A final tool error after successful dispatch starts cleanup of that invocation’s input owner. The original tool error can return while native release is pending. Any cleanup failure is reported separately. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. + The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. Legacy `allowedApps` are imported on first store access and never reapplied after migration. The old configuration can be removed after checking the permission page. Grants, denials and the option to ask again are durable; the page still omits conversation-only grants. Standalone compositions without a profile retain only process-local decisions; a profile without domain storage refuses authorization operations. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c2c904ecd3..4a3cc98123 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,6 +91,10 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 +实现 `CuaBackend.heldInputState` 的提供方通过 `getHeldInputs({})` 返回当前连接的持有记录,通过 `releaseHeldInputs({})` 释放这些输入并返回结果。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 + +每个 Agent 使用独立的原生输入连接,多个程序和回合可以复用这条连接。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。程序执行成功后,如果最终工具结果失败,CUA 立即清理这次调用所属的输入。原工具错误可以先返回,清理失败会另行报告。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 + [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 旧 `allowedApps` 只在首次访问存储时导入,迁移后不再应用。确认权限页显示正确后,可以删除旧配置。授权、拒绝和允许再次询问均持久化,页面仍不显示仅对某个会话生效的许可。没有 profile 的独立组合只保留进程内决定;有 profile 但缺少域存储的组合会拒绝授权操作。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 426d042d73..63d4424cd8 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -102,7 +102,8 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*" + "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -110,7 +111,8 @@ "zod": "4.6.6", "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-computer-use": "workspace:*", @@ -126,7 +128,6 @@ "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", "@deepseek-ai/dsh-error": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 93de1e3c52..423bac6de7 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -44,7 +44,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -60,6 +60,16 @@ Available at app or window level depending on the platform. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.` +/** Add held-input behavior where the provider supplies native ownership and cleanup. + * @param guidance - Provider instructions including the shared operation catalog. + * @returns Instructions for a provider with held-input state support. + */ +export function withHeldInputGuidance(guidance: string): string { + return guidance.replace('click, drag, and pressKey are convenience operations;', `Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + +click, drag, and pressKey are convenience operations;`) +} + /** * Describe the system-input option for a provider that declares the capability. * @param guidance Provider instructions including the shared operation catalog. diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts new file mode 100644 index 0000000000..b21eea76a8 --- /dev/null +++ b/packages/experimental/cua/src/held-inputs.ts @@ -0,0 +1,222 @@ +/** Native-owned held input, program-end reminders, and failure/cancellation cleanup. */ +import type { Context } from '@deepseek-ai/cordis' +import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { RUN_CODE_NAME, type ToolExecution } from '@deepseek-ai/dsh-tools' +import { z } from 'zod' +import { NativeError, type NativeClient } from './native-client.ts' + +const target = { appHandle: z.string(), mode: z.enum(['application', 'window', 'system']) } +const heldInputs = z.array(z.discriminatedUnion('kind', [ + z.object({ ...target, kind: z.literal('key'), key: z.string(), windowId: z.string().optional() }), + z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }), +])) + +function renderInputs(inputs: z.infer, state: 'held' | 'released'): string { + const rows = inputs.map(input => input.kind === 'key' + ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)}${input.windowId === undefined ? '' : `, windowId ${JSON.stringify(input.windowId)}`} (${input.mode} input).` + : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) + const title = state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were released during cleanup:' + return ['', title, ...rows, + state === 'held' + ? "They remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down." + : 'These inputs are no longer held.', + ''].join('\n') +} + +class InputOwner { + readonly controller = new AbortController() + private client: NativeClient | undefined + private removeCleanup: (() => void) | undefined + private notifySessionOnRelease = false + closing: Promise> | undefined + + constructor(private readonly failed: (error: unknown) => void, + private readonly released: (inputs: z.infer) => void) {} + + track(client: NativeClient, inTurn: boolean): void { + this.controller.signal.throwIfAborted() + this.notifySessionOnRelease ||= inTurn + if (this.client) return + this.removeCleanup = client.registerCleanup(async (canRequest) => { await this.close(canRequest) }) + this.client = client + } + + async reminder(inTurn: boolean): Promise { + if (this.closing || !this.client) return + const inputs = heldInputs.parse(await this.client.request('getHeldInputs', {}, this.controller.signal)) + if (inputs.length === 0) { + this.removeCleanup?.() + this.removeCleanup = undefined + this.client = undefined + return + } + this.notifySessionOnRelease ||= inTurn + return renderInputs(inputs, 'held') + } + + close(canRequest = true): Promise> { + this.controller.abort() + return this.closing ??= Promise.resolve().then(async () => { + try { + if (!this.client) return [] + if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task') + const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', {})) + if (this.notifySessionOnRelease) this.released(released) + return released + } catch (error) { + this.failed(error) + throw error + } finally { + this.removeCleanup?.() + this.removeCleanup = undefined + } + }) + } + + async settled(): Promise { + try { await this.closing } + catch (_cleanupFailed) { /* close reports the failure and disables this task's CUA operations. */ } + } +} + +/** One provider's held input owners; the helper remains the authority for which inputs are pressed. */ +export class CuaHeldInputs { + private readonly owners = new WeakMap() + // Post-execute policy may fail after a newer owner has acquired input for the same Agent. + private readonly programOwners = new WeakMap() + private readonly failures = new WeakMap() + private readonly turnSignals = new Map void }>() + + /** @param ctx - Provider scope owning input observers and program middleware. */ + constructor(private readonly ctx: Context) {} + + /** + * Wait for cleanup and obtain an owner for a new operation. + * @param agent - Agent issuing a CUA operation. + * @returns Ownership and cancellation shared by its held inputs. + */ + async ready(agent: Agent): Promise { + const previous = this.owners.get(agent) + if (previous?.closing) await previous.settled() + if (this.failures.has(agent)) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', + 'CUA cleanup was not confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task', { cause: this.failures.get(agent) }) + const current = this.owners.get(agent) + if (current && !current.closing) return current + const owner = new InputOwner((error) => { + this.failures.set(agent, error) + this.ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', agent.id, error) + emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) + }, (inputs) => { + try { + for (const message of [...agent.inbox.nextStep, ...agent.inbox.nextTurn]) { + if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) + } + if (inputs.length === 0) return + agent.inject(createUserMessage({ + content: [{ type: 'text', text: renderInputs(inputs, 'released') }], + source: { kind: 'cua-inputs-released', form: 'notice', summary: 'CUA inputs released' }, + })) + } catch (error) { + this.ctx.logger.error('CUA inputs were released but their notice could not be recorded for task %s: %s', agent.id, error) + emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, + error: new NativeError('INPUT_NOTICE_FAILED', 'CUA inputs were released, but their notice could not be recorded', { cause: error }) }) + } + }) + this.owners.set(agent, owner) + return owner + } + + /** + * Stop owned dispatch and release held input with an independent bounded native request. + * @param agent - Agent whose input must be released. + * @returns Completion after native acknowledgement, or rejection if cleanup is unconfirmed. + */ + async release(agent: Agent): Promise { await this.owners.get(agent)?.close() } + + private stop(owner: InputOwner | undefined): void { + if (!owner) return + void owner.close().catch(() => undefined) // close records and reports the failure; waiters join the same promise. + } + + /** + * Observe program outcomes and cancellation while retaining native cleanup dependencies. + * @returns Exact disposers retained until programs and native connections have drained. + */ + *install(): Generator<() => void> { + const ctx = this.ctx + yield ctx.on('tools/execute', async (execution, next) => { + if (!execution.agent || (execution.name !== RUN_CODE_NAME && execution.name !== 'cua_run_code')) return next() + const agent = execution.agent + const signal = execution.signal + const abort = (): void => { this.stop(this.owners.get(agent)) } + signal.addEventListener('abort', abort, { once: true }) + const releaseAfter = async (message: string): Promise => { + signal.removeEventListener('abort', abort) + try { await this.release(agent) } + catch (error) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', + `${message}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } + } + try { + let result: Awaited> + try { result = await next() } + catch (error) { + await releaseAfter(`Program failed: ${String(error)}`) + throw error + } + if (result.isError || signal.aborted) { + await releaseAfter(result.isError ? result.error.message : 'Program cancelled') + } else { + const owner = this.owners.get(agent) + let text: string | undefined + if (execution.parent === undefined) { + const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null + text = await owner?.reminder(inTurn).catch(async (error: unknown) => { + await releaseAfter(signal.aborted ? 'Program cancelled' : `Held-input query failed: ${String(error)}`) + throw error + }) + // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. + if (signal.aborted) { await releaseAfter('Program cancelled'); return result } + } + if (owner) this.programOwners.set(execution, owner) + if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], + createUserMessage({ content: [{ type: 'text', text }], + source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), + ] } + } + return result + } finally { + signal.removeEventListener('abort', abort) + await this.owners.get(agent)?.settled() + } + }) + yield ctx.on('tools/result', (execution, result) => { + const owner = this.programOwners.get(execution) + this.programOwners.delete(execution) + if (result.isError) this.stop(owner) + }) + yield ctx.on('agent/pre-step', (event, next) => { + const previous = this.turnSignals.get(event.agent) + if (previous?.signal !== event.signal) { + previous?.remove() + const abort = (): void => { this.stop(this.owners.get(event.agent)) } + event.signal.addEventListener('abort', abort, { once: true }) + this.turnSignals.set(event.agent, { signal: event.signal, remove: () => { event.signal.removeEventListener('abort', abort) } }) + } + return next() + }) + yield ctx.on('agent/inbox/inserted', ({ agent, message }) => { + // This live notification runs after append publication, so removal can safely write its own event. + if (message.source.kind === 'cua-held-inputs' && this.owners.get(agent)?.closing) agent.inbox.remove(message.id) + }, { prepend: true }) + yield ctx.on('session/event', (session, event) => { + if (event.type !== 'turn/end') return + const agent = ctx.agents.get(session.id) + if (agent?.session !== session) return + this.turnSignals.get(agent)?.remove() + this.turnSignals.delete(agent) + if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(this.owners.get(agent)) + }) + yield () => { for (const value of this.turnSignals.values()) value.remove(); this.turnSignals.clear() } + } +} diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index b5ff76231d..17971d8f16 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -14,7 +14,8 @@ import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' import { SystemInputControl } from './system-input.ts' -import { withSystemInputGuidance } from './guidance.ts' +import { CuaHeldInputs } from './held-inputs.ts' +import { withHeldInputGuidance, withSystemInputGuidance } from './guidance.ts' import { CuaPermissionStore } from './permission-store.ts' import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts' @@ -185,6 +186,11 @@ export interface CuaWindowRead { export interface CuaBackend { helperPath: string createChannel: NativeChannelFactory + /** + * Stop the provider's shared transport after every Agent and permission connection has closed. + * @returns Transport shutdown completion. + */ + disposeNative?(): Promise /** * Select platform operation instructions for the exposed tool form. * @param kind Raw cua calls or standalone cua_run_code programs. @@ -194,11 +200,10 @@ export interface CuaBackend { capabilities: CuaStartupCapabilities /** Preserve discovery PIDs when getApp accepts a decimal PID as an exact process selector. */ acceptsPidSelector?: boolean + /** Opt in to connection-scoped getHeldInputs and releaseHeldInputs; omission preserves the provider's existing protocol. */ + heldInputState?: boolean /** Registers a window read. The returned receipt handler sees the native reply only after Host decoding succeeds. */ windowRead?: (read: CuaWindowRead) => (reply: JsonValue) => void - /** Dispatch a directional key through the provider's execution-scoped input owner, after application authorization. */ - sendKeyEvent?: (client: NativeClient, params: Record, - execution: Readonly) => Promise /** * Build native permission parameters for the selected action and Client language. * @param method Native permission action. @@ -217,11 +222,13 @@ export interface CuaBackend { */ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend): void { const { helperPath } = backend + const heldInputs = backend.heldInputState ? new CuaHeldInputs(ctx) : undefined const systemInput = backend.capabilities.systemInput === true const systemInputControl = systemInput ? new SystemInputControl(ctx, config.requireSystemInputApproval) : undefined const requestSchema = systemInput ? SystemInputRequest : Request const formatGuidance = (text: string): string => { - const instructions = systemInput ? withSystemInputGuidance(text) : text + const inputGuidance = heldInputs ? withHeldInputGuidance(text) : text + const instructions = systemInput ? withSystemInputGuidance(inputGuidance) : inputGuidance return `${instructions}\n\nAX read defaults: maxElements=${config.maxElements}, maxDepth=${config.maxDepth}.\n\nMaximum click holdMs: ${config.maxClickHoldMs} ms.` } const guidance = formatGuidance(backend.getGuidance('raw')) @@ -273,6 +280,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) return owner } ctx.effect(function* () { + if (heldInputs) yield* heldInputs.install() yield ctx.computerUse.register(brandString('dsh-cua')) yield async () => { lifetime.abort() @@ -283,7 +291,8 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const releases = await Promise.allSettled(owners.map(owner => owner.release())) const errors: unknown[] = [] for (const result of [...await permissions, ...results, ...releases]) if (result.status === 'rejected') errors.push(result.reason) - if (errors.length > 0) throw new AggregateError(errors, 'dsh-cua helper cleanup failed') + try { await backend.disposeNative?.() } catch (error) { errors.push(error) } + if (errors.length > 0) ctx.logger.error(new AggregateError(errors, 'dsh-cua helper cleanup failed')) } const callNative = async (request: CuaOperation, execution: Readonly, useSystemInput?: boolean) => { const { method, params: parsedParams } = request @@ -292,10 +301,13 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const signal = execution.signal signal.throwIfAborted() const client = execution.nativeClient + // Earlier helpers accept an explicit false only for mouseMove. if (method !== 'mouseMove' && !useSystemInput) delete params.useSystemInput else if (useSystemInput !== undefined) params.useSystemInput = useSystemInput - if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, params, execution) - if (method === 'toggleMouse' && useSystemInput && params.direction === 'down') systemInputControl?.trackPress(agent, client) + if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse') && params.direction === 'down') { + const owner = await heldInputs.ready(agent) + owner.track(client, ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null) + } const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' @@ -397,7 +409,10 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) execution.signal.throwIfAborted() lifetime.signal.throwIfAborted() const owner = ownerFor(agent) - const signal = AbortSignal.any([execution.signal, lifetime.signal, owner.signal]) + const inputOwner = await heldInputs?.ready(agent) + const signal = AbortSignal.any([ + execution.signal, lifetime.signal, owner.signal, ...inputOwner ? [inputOwner.controller.signal] : [], + ]) signal.throwIfAborted() const operation = (async () => { const previous = clients.get(agent) @@ -425,7 +440,8 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) owner.coordinates = new CuaCoordinates() } const nativeClient = client - const route = systemInputControl?.resolve(agent, 'useSystemInput' in request.params && request.params.useSystemInput === true) + const route = heldInputs && request.method === 'toggleMouse' && request.params.direction === 'up' + ? undefined : systemInputControl?.resolve(agent, 'useSystemInput' in request.params && request.params.useSystemInput === true) if (route?.prepare) owner.coordinates.parameters(request) const dispatch = async (signal: AbortSignal) => { const scoped = { ...execution, agent, signal, nativeClient, coordinates: owner.coordinates } @@ -448,7 +464,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) } }, } - yield installCuaTools(ctx, config, tool, guidance, programGuidance) + yield installCuaTools(ctx, config, tool, guidance, programGuidance, agent => heldInputs?.release(agent) ?? Promise.resolve()) }, 'dsh-cua.runtime') } diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 345c04067a..32a7ce9068 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -116,12 +116,13 @@ export const NativeResourceParameters = { }).strict(), findApps: z.object({ maxAppMatches: z.number().int().min(1).max(1000) }).strict(), } -/** Host-only launch continuation and user-facing system permission controls; absent from model arguments. */ +/** Host-only launch, permission, and held-input operations; absent from model arguments. */ export const NativeOnlyOperations = [ operation('launchApp', app), operation('permissionStatus', {}), operation('applicationIcons', { paths: z.array(z.string().min(1)) }), operation('requestPermission', { permission: z.enum(['accessibility', 'screenRecording']) }), operation('openPermissionSettings', { permission: z.enum(['accessibility', 'screenRecording']) }), + operation('getHeldInputs', {}), operation('releaseHeldInputs', {}), ] as const /** Application selection returned only after a successful app selection. */ diff --git a/packages/experimental/cua/src/system-input.ts b/packages/experimental/cua/src/system-input.ts index c142700adf..13989489c4 100644 --- a/packages/experimental/cua/src/system-input.ts +++ b/packages/experimental/cua/src/system-input.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { UserQuestionError } from '@deepseek-ai/dsh-user-questions' -import { NativeError, type NativeClient } from './native-client.ts' +import { NativeError } from './native-client.ts' import { applicationAccessDisplay } from './locales.ts' import { systemInputControlPrompt } from './system-input-locales.ts' @@ -10,29 +10,7 @@ import { systemInputControlPrompt } from './system-input-locales.ts' export class SystemInputControl { private readonly decisions = new WeakMap() - private readonly pressed = new WeakMap() - - constructor(private readonly ctx: Context, private readonly requireApproval: boolean) { - ctx.on('session/event', (session, event) => { - if (event.type !== 'turn/end') return - const client = this.pressed.get(session) - this.pressed.delete(session) - if (client && !client.disposed) { - void client.requestCleanup('releaseSystemButton', {}).catch((error: unknown) => { - ctx.logger.warn('Could not release system input at turn end: %s', error) - }) - } - }) - } - - /** - * Arm turn-end cleanup before posting; cancellation can hide an already dispatched press. - * @param agent Owner of the current turn. - * @param client Connection that owns and can release the native button. - */ - trackPress(agent: Agent, client: NativeClient): void { - this.pressed.set(agent.session, client) - } + constructor(private readonly ctx: Context, private readonly requireApproval: boolean) {} /** * Select the per-call route and any approval required before dispatch. diff --git a/packages/experimental/cua/src/tool-registration.ts b/packages/experimental/cua/src/tool-registration.ts index 8b2e3a87c9..ae7adb0930 100644 --- a/packages/experimental/cua/src/tool-registration.ts +++ b/packages/experimental/cua/src/tool-registration.ts @@ -25,14 +25,21 @@ export interface CuaPrograms { * Release one Agent's retained program environment with the dedicated runtime's owner release. The program * process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` * call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native - * connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's + * connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent's * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. - * @returns Completion after the process has exited and its output has drained. - * @throws When the process cleanup fails. + * @returns Completion after the process has exited, its output has drained, and held-input cleanup has settled. + * @throws When environment or input cleanup fails, reporting both causes if both fail. */ release(agent: Agent): Promise + /** + * Release the Agent's tracked input while retaining its program variables and application grants. + * Providers without held-input state support retain their existing cancellation behavior. + * @param agent - Owner of the input to release. + * @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed. + */ + releaseInputs(agent: Agent): Promise /** * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. * A host that forwards screenshots outside a model request reads the same request version with it, so the @@ -71,10 +78,12 @@ export function fixedScreenshotTarget(configured: CuaScreenshotTargetConfig, ima * @param tool Internal native tool; Agents off the configured preset can reach it only through the program. * @param guidance Raw-tool operation instructions for the configured preset. * @param programGuidance Operation instructions available inside cua_run_code. + * @param releaseInputs Release tracked input on cancellation or environment reset. * @returns Exact registration disposer, draining programs before native resources can close. */ export function installCuaTools( ctx: Context, config: CuaConfig, tool: ToolDefinition, guidance: string, programGuidance: string, + releaseInputs: (agent: Agent) => Promise, ): () => void | Promise { // PTC publishes the installed JS entry; automatic CUA initialization follows the Host's code format. const ptcBridgeUrl = JSON.stringify(new URL('../lib/bridge.js', import.meta.url).href) @@ -158,7 +167,18 @@ var cua = connectCua(() => tools.cua); }) // Hosts without a model (MCP frontends) end an Agent's environment with the runtime's owner release. consumer.provide('cuaPrograms', { - release: (agent: Agent) => consumer.ptcRuntime.release(agent), + release: async (agent: Agent) => { + try { await consumer.ptcRuntime.release(agent) } + catch (error) { + try { await releaseInputs(agent) } + catch (cleanup) { + throw new AggregateError([error, cleanup], `Environment release failed: ${String(error)}. Held-input cleanup failed: ${String(cleanup)}`) + } + throw error + } + await releaseInputs(agent) + }, + releaseInputs, screenshotRequestTarget: image => config.screenshotTarget === undefined ? undefined : fixedScreenshotTarget(config.screenshotTarget, image), } satisfies CuaPrograms) diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index ea00515df0..3f86cc584a 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -1,10 +1,18 @@ /** Native application objects independent of evaluator ownership and persistence. */ import type { Branded } from '@deepseek-ai/dsh-brand' +import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { z } from 'zod' import type { ActionResult, CapabilitiesResult, FoundAppsResult, HoverResult, SystemInputRequest, ShowResult, WindowsResult } from './protocol.ts' +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + 'cua-held-inputs': { kind: 'cua-held-inputs' } & Extract + 'cua-inputs-released': { kind: 'cua-inputs-released' } & Extract + } +} + /** Helper-issued application selection; public app objects hold only this opaque handle. */ export type CuaAppHandle = Branded<'CuaAppHandle'> /** Helper-issued accessibility observation identity. */ @@ -181,10 +189,12 @@ export interface CuaSurface { pressKey(key: string, modifiers?: string[], options?: CuaSystemInputOptions): Promise /** * Send one key-down or key-up event at the current input focus. - * Does not send the opposite event. + * Explicit downs persist across programs and turns; successful programs remind about remaining holds. + * MCP client pauses between completed calls do not notify the provider and leave held input unchanged. + * Program failure, cancellation, connection closure and disposal release owned input on supported providers. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. - * @param direction - Explicit event direction; the opposite event is never sent implicitly. + * @param direction - Down establishes a hold; up immediately releases owned input through its original input route. * @param options - Input selection, matching the corresponding down or up; omitted uses the provider default. * @returns Whether the provider successfully executed the requested operation. */ @@ -217,7 +227,8 @@ export interface CuaWindow extends CuaSurface { options?: CuaCoordinateOptions & CuaSystemInputOptions): Promise /** * Send one mouse-button down or up event without moving the pointer. - * Does not send the opposite event; callers explicitly release a pressed button. + * Uses the same held-input lifecycle as {@link CuaSurface.sendKeyEvent}; up uses the saved window and input route. + * Error and cancellation cleanup releases keys and buttons together in reverse dispatch order. * @param mouseButton - Mouse button to press or release. * @param direction - Explicit event direction. * @param options - Request a system button on a provider reporting systemInput. @@ -271,8 +282,8 @@ export interface CuaApp extends CuaSurface { /** Native app API; its caller owns global bindings and variable persistence. */ export interface CuaApi { /** - * Inspect permissions without requesting them. - * @returns reported native capabilities. + * Inspect permissions and the provider’s supported methods without requesting access. + * @returns Reported native capabilities. */ getCapabilities(): Promise /** diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 8b5037341a..e28316d702 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -22,15 +22,17 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import Subprocess from '@deepseek-ai/dsh-subprocess-local' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc' import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools' import WorkingDirectory from '@deepseek-ai/dsh-working-directory' -import { expect, it, onTestFinished } from 'vitest' +import { expect, it, onTestFinished, vi } from 'vitest' import { z } from 'zod' import { createNativeFixture, png } from '../../../../snapshots/session/cua-run-code/native-channel.mjs' import { CuaConfig, installCua } from '../src/index.ts' import { COMMON_GUIDANCE } from '../src/guidance.ts' import { Request } from '../src/protocol.ts' +import { NativeClient } from '../src/native-client.ts' import { brandString } from '@deepseek-ai/dsh-brand' const programs = [ @@ -41,20 +43,24 @@ const programs = [ class ProgramModel extends LlmAdapter { readonly requests: GenerateOptions[] = [] + toolName = 'cua_run_code' + beforeStream?: (index: number, options: GenerateOptions) => Promise /** Requests a test holds back until it has finished acting between two model steps. */ readonly gates = new Map>() - constructor(private readonly programs: readonly string[]) { super() } + constructor(private programs: readonly string[]) { super() } + restart(programs: readonly string[]): void { this.programs = programs; this.requests.length = 0 } override resolveModel(provider: string, model: string): Promise { return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) } async * stream(options: GenerateOptions): AsyncIterable { + await this.beforeStream?.(this.requests.length, options) await this.gates.get(this.requests.length) const code = this.programs[this.requests.length] this.requests.push(options) if (code !== undefined) { yield { type: 'block-start', index: 0, blockType: 'tool-call' } yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString(`cua-program-${this.requests.length}`), - name: 'cua_run_code', arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } + name: this.toolName, arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } yield { type: 'finish', reason: { kind: 'tool-calls' } } return } @@ -64,7 +70,7 @@ class ProgramModel extends LlmAdapter { } } -async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false) { +async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, heldInputState = false, timeoutMs = 30_000, disposeNative?: (state: { closedChannels: number }) => Promise) { const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-')) const ctx = new Context() onTestFinished(async () => { @@ -104,9 +110,10 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi apply(owner: Context, config: CuaConfig) { installCua(owner, config, { helperPath: process.execPath, createChannel: native.createChannel, getGuidance: () => COMMON_GUIDANCE, - acceptsPidSelector: selectorPid !== undefined, - capabilities: { platform, methods: ['getCapabilities', 'listApps', 'getApp', 'getState', 'click', 'screenshot'], - appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, + acceptsPidSelector: selectorPid !== undefined, heldInputState, + ...disposeNative ? { disposeNative: () => disposeNative(native.state) } : {}, + capabilities: { platform, methods: ['getCapabilities', 'listApps', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], + appLevelAccessibility: platform !== 'windows', keyboard: platform === 'windows' ? ['window'] : ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) }, @@ -120,7 +127,7 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi ...name === 'sandboxPolicy' ? { config: { mode: 'danger-full-access', workspaceRoot: directory } } : {}, ...name === 'sharedRuntime' ? { config: { executionMode: 'per-call' } } : {}, ...name === 'attachments' ? { config: { dshHome: directory } } : {}, - ...name === 'cua' ? { config: { allowedApps: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }] } } : {}, + ...name === 'cua' ? { config: { timeoutMs, allowedApps: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }] } } : {}, })) const configPath = join(directory, 'cordis.yml') await writeFile(configPath, JSON.stringify(entries, null, 2) + '\n') @@ -137,14 +144,12 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi ...presetFree ? {} : { setup: async (owner: Context) => { await ctx.agentPresets.mount(owner, 'standard') } }, }) const agent = handle.agent - const idle: PromiseWithResolvers = Promise.withResolvers() - ctx.on('agent/status', ({ agent: subject, status }) => { if (subject === agent && status === 'idle') idle.resolve() }) const provider = [...ctx.loader.entries()].find(entry => entry.options.id === 'cua') if (provider?.fiber === undefined) throw new Error('Loader did not activate the CUA fixture provider') - return { ctx, native, guarded, model, agent, provider: provider.fiber, + return { ctx, native, guarded, model, agent, handle, provider: provider.fiber, run: () => { agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Inspect and increment the fixture counter.' }], source: { kind: 'user' } })) - return idle.promise + return agent.whenIdle() }, } } @@ -365,3 +370,561 @@ it('forwards per-read accessibility limits to the Windows backend', async () => expect(native.calls.find(call => call.method === 'getState')?.params) .toMatchObject({ maxElements: 30, maxDepth: 3 }) }) + +const holdProgram = 'var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")' +const holdWindowProgram = 'var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.sendKeyEvent("w", "down")' + +function reminders(agent: { session: { snapshotEvents(): readonly import('@deepseek-ai/dsh-session').SessionEvent[] } }, + kind: 'cua-held-inputs' | 'cua-inputs-released' = 'cua-held-inputs') { + return agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === kind) + .flatMap(event => event.type === 'user/message' ? event.data.content.filter(block => block.type === 'text').map(block => block.text) : []) +} + +it('reports native held input after programs, keeps it across turns, and stops reminding after explicit up', async () => { + const f = await setup([holdProgram, 'inspect("still holding")'], 'macos', undefined, true, true) + await f.run() + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.events).toEqual(['w:down']) + expect(reminders(f.agent)).toHaveLength(2) + expect(reminders(f.agent)[0]).toContain('Key "w", appHandle "fixture-app"') + expect(f.model.requests[1]?.messages.some(message => JSON.stringify(message).includes('CUA inputs are still held'))).toBe(true) + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + f.model.restart(['await app.sendKeyEvent("w", "up")']) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(reminders(f.agent)).toHaveLength(2) +}) + +it('reports the Windows keyboard window and desktop input mode and supports a later explicit up', async () => { + const f = await setup([holdWindowProgram], 'windows', undefined, true, true) + await f.run() + expect(f.native.events).toEqual(['w:down']) + expect(reminders(f.agent)[0]).toContain('Key "w", appHandle "fixture-app", windowId "7" (system input)') + f.model.restart(['await win.sendKeyEvent("w", "up")']) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(reminders(f.agent)).toHaveLength(1) +}) + +it.each([ + ['run_code', 'confirmed'], ['cua_run_code', 'confirmed'], ['cua_run_code', 'refused'], +] as const)('publishes the %s policy error while subsequent CUA waits for cleanup (%s)', async (tool, cleanup) => { + const program = (code: string) => tool === 'run_code' + ? `await tools.cua_run_code({ code: ${JSON.stringify(code)}, description: "Use the fixture" })` : code + const f = await setup([program(holdProgram)], 'macos', undefined, true, true) + if (tool === 'run_code') await f.agent.ctx.plugin(PtcToolExecutor) + f.model.toolName = tool + const removePolicy = f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === tool + ? { kind: 'block', feedback: [{ type: 'text', text: 'Policy rejected output' }], info: { name: 'HookError', code: 'HOOK_BLOCKED' } } + : next(), { prepend: true }) + const calls = vi.spyOn(NativeClient.prototype, 'request') + onTestFinished(() => { calls.mockRestore() }) + let stoppedAtResult: boolean | undefined + f.ctx.on('tools/result', (exec, result) => { + if (exec.name === tool && result.isError) { + stoppedAtResult = calls.mock.calls.find(([name]) => name === 'sendKeyEvent')?.[2].aborted + } + }) + const reported: unknown[] = [] + f.ctx.on('agent/error', ({ error }) => { reported.push(error) }) + const notice = nextReleaseNotice(f) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await release.entered + let following: Promise + const before = f.native.calls.length + try { + await running + expect(stoppedAtResult).toBe(true) + expect(f.native.held.map(input => input.key)).toEqual(['w']) + const result = f.agent.session.snapshotEvents().find(event => event.type === 'tool/result') + expect(result?.data).toMatchObject({ error: { code: 'HOOK_BLOCKED' }, message: { + isError: true, content: [{ type: 'text', text: 'Policy rejected output' }], + } }) + expect(JSON.stringify(f.model.requests[1]?.messages)).not.toContain('CUA inputs were released') + expect(reminders(f.agent)).toEqual([]) + removePolicy() + const admitted: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/execute', (exec, next) => { + const result = next() + if (exec.name === 'cua') admitted.resolve() + return result + }) + f.model.restart([program('await app.sendKeyEvent("d", "down")')]) + following = f.run() + await admitted.promise + expect(f.native.calls.length).toBe(before) + } finally { + release.reply(cleanup === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Fixture refused release' } : undefined) + } + await following + if (cleanup === 'confirmed') { + await notice + expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down']) + expect(JSON.stringify(f.model.requests.at(-1)?.messages)).toContain('CUA inputs were released during cleanup') + } else { + expect(reported).toEqual([expect.objectContaining({ code: 'INPUT_CLEANUP_FAILED' })]) + expect(f.native.calls.length).toBe(before) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(f.agent.session.snapshotEvents().some(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.source.kind === 'cua-inputs-released'))).toBe(false) + } +}) + +it('cleans up a rejected nested program even when its enclosing run_code handles the failure', async () => { + const f = await setup([`try { await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" }) } catch { inspect("handled") }`], + 'macos', undefined, true, true) + await f.agent.ctx.plugin(PtcToolExecutor) + f.model.toolName = 'run_code' + f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === 'cua_run_code' && exec.parent + ? { kind: 'block', feedback: [{ type: 'text', text: 'Nested policy refusal' }] } : next()) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(f.agent.session.snapshotEvents().find(event => event.type === 'tool/result')?.data.message.isError).toBe(false) +}) + +it('a late policy refusal closes only the owner captured by that execution', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/post-execute', async (exec, _result, next) => { + if (exec.callId !== 'cua-program-1') return next() + entered.resolve() + await finish.promise + return { kind: 'block', feedback: [{ type: 'text', text: 'Late refusal' }] } + }) + const running = f.run() + await entered.promise + const openedChannels = f.native.state.openedChannels + const execute = (id: string, code: string) => f.ctx.agents.withInitiator(f.agent, () => f.ctx.tools.execute({ + agent: f.agent, signal: new AbortController().signal, + calls: [{ type: 'tool-call', id: brandString(id), name: 'cua_run_code', arguments: JSON.stringify({ code, description: id }) }], + })) + try { + await f.ctx.cuaPrograms.releaseInputs(f.agent) + expect((await execute('hold-d', 'await app.sendKeyEvent("d", "down")')).results[0]?.result.isError).toBe(false) + f.ctx.on('tools/pre-execute', async (exec, next) => exec.callId === 'denied' + ? { kind: 'deny', reason: 'Not admitted' } : next()) + expect((await execute('denied', 'inspect("unused")')).results[0]?.result.isError).toBe(true) + } finally { finish.resolve(); await running } + expect((await execute('release-d', 'await app.sendKeyEvent("d", "up")')).results[0]?.result.isError).toBe(false) + expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down', 'd:up']) + expect(f.native.state.openedChannels).toBe(openedChannels) + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) +}) + +it('releases keyboard and mouse in mixed reverse order on program failure', async () => { + const f = await setup([holdProgram, + 'await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down"); throw Error("program failed")', 'inspect("recovered")'], + 'macos', undefined, true, true) + await f.run() + expect(f.native.events).toEqual(['w:down', 'shift:down', 'left:down', 'd:down', 'd:up', 'left:up', 'shift:up', 'w:up']) + expect(f.native.held).toEqual([]) + expect(reminders(f.agent)).toHaveLength(1) + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) + const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') + expect(results.map(result => result.isError)).toEqual([false, true, false]) +}) + +it('releases a previous hold when downstream execution throws before producing a result', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + f.model.restart(['inspect("unreachable")']) + f.ctx.on('tools/execute', (execution, next) => { + if (execution.name === 'cua_run_code') throw new Error('Executor middleware failed') + return next() + }) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Executor middleware failed') +}) + +it('reminders name the actual mouse target and omit explicitly released inputs', async () => { + const f = await setup([holdProgram, 'await app.sendKeyEvent("w", "up"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down")'], + 'macos', undefined, true, true) + await f.run() + expect(reminders(f.agent)[1]).toContain('Mouse left, appHandle "fixture-app", windowId "7" (window input)') + expect(reminders(f.agent)[1]).not.toContain('Key "w"') + await f.handle.dispose() + expect(f.native.held).toEqual([]) +}) + +function nextReleaseNotice(f: Awaited>): Promise { + const recorded: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/inbox/inserted', ({ agent, message }) => { + if (agent === f.agent && message.source.kind === 'cua-inputs-released') recorded.resolve() + }) + return recorded.promise +} + +it.each([ + ['model failure', 'confirmed'], + ['thinking stop', 'confirmed'], + ['thinking stop', 'refused'], +] as const)('returns to idle after %s while new CUA input waits for cleanup (%s)', async (ending, outcome) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const thinking: PromiseWithResolvers = Promise.withResolvers() + if (ending === 'model failure') { + await f.run() + f.model.restart([]) + } + f.model.beforeStream = async (index, options) => { + if (ending === 'model failure') throw new Error('Model failed with W held from an earlier turn') + if (index !== 1) return + thinking.resolve() + const signal = options.signal! + await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + const release = f.native.controlNext('releaseHeldInputs') + const notice = nextReleaseNotice(f).then(() => [...f.native.events]) + const reported: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/error', ({ error }) => { + if (error instanceof Error && error.message.includes('Release refused after idle')) reported.resolve(error) + }) + const idle = f.run() + if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }, { keepInbox: true }) } + await release.entered + let following: Promise + const before = f.native.calls.length + try { + await idle + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(false) + const terminal = f.agent.session.snapshotEvents().findLast(event => event.type === 'turn/end') + expect(terminal?.data.reason.kind).toBe(ending === 'thinking stop' ? 'aborted' : 'error') + + const admitted: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/execute', (execution, next) => { + const result = next() + if (execution.name === 'cua') admitted.resolve() + return result + }) + delete f.model.beforeStream + f.model.restart(['await app.sendKeyEvent("d", "down")']) + following = f.run() + await admitted.promise + expect(f.native.calls).toHaveLength(before) + } finally { + release.reply(outcome === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Release refused after idle' } : undefined) + } + await following + if (outcome === 'confirmed') { + expect(await notice).toEqual(['w:down', 'w:up']) + expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down']) + } else { + expect(await reported.promise).toMatchObject({ code: 'INPUT_CLEANUP_FAILED' }) + expect(f.native.calls).toHaveLength(before) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(f.agent.session.snapshotEvents().some(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.source.kind === 'cua-inputs-released'))).toBe(false) + } +}) + +it('cancels an in-flight down before releasing input and allows later programs after confirmed cleanup', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true, waitForCancellation: true }) + let finished = false + const running = f.run().then(() => { finished = true }) + await down.entered + f.agent.cancel({ kind: 'user' }) + await down.cancelled + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + const release = f.native.controlNext('releaseHeldInputs') + down.reply({ code: 'NATIVE_CANCELLED', message: 'Stopped after dispatch' }) + await release.entered + try { expect(finished).toBe(false) } finally { release.reply() } + await running + expect(f.native.held).toEqual([]) + f.model.requests.length = 0 + await f.run() + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(1) +}) + +it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and disables further CUA operations', async (failure) => { + const f = await setup([holdProgram + '; throw Error("program failed")'], 'macos', undefined, true, true, failure === 'timeout' ? 200 : 30_000) + const errors: unknown[] = [] + f.ctx.on('agent/error', (event) => { errors.push(event.error) }) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await release.entered + if (failure === 'refusal') release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Release rejected' }) + if (failure === 'disconnect') release.disconnect() + await running + expect(errors).toHaveLength(1) + const count = f.native.calls.length + f.model.requests.length = 0 + await f.run() + expect(f.native.calls).toHaveLength(count) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') +}) + +it('reports failed native state inspection and releases held input instead of claiming it is empty', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const query = f.native.controlNext('getHeldInputs') + const running = f.run() + await query.entered + query.reply({ code: 'NATIVE_ERROR', message: 'Held state unavailable' }) + await running + expect(reminders(f.agent)).toEqual([]) + expect(f.native.held).toEqual([]) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Held state unavailable') +}) + +it.each(['closes', 'fails to close'] as const)('waits for Agent release before the Windows helper runtime %s', async (outcome) => { + const failure = new Error('Windows helper lease could not close') + const disposed = vi.fn(async (state: { closedChannels: number }) => { + expect(state.closedChannels).toBe(1) + if (outcome === 'fails to close') throw failure + }) + const f = await setup([holdWindowProgram], 'windows', undefined, true, true, undefined, disposed) + const report = vi.spyOn(f.provider.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { report.mockRestore() }) + await f.run() + const release = f.native.controlNext('releaseHeldInputs') + const closing = f.provider.dispose() + await release.entered + try { expect(disposed).not.toHaveBeenCalled() } finally { release.reply() } + await closing + expect(disposed).toHaveBeenCalledOnce() + expect(f.native.held).toEqual([]) + if (outcome === 'fails to close') expect(report).toHaveBeenCalledWith(expect.objectContaining({ errors: [failure] })) + else expect(report).not.toHaveBeenCalled() +}) + +it.each([ + ['model error', 'confirmed'], ['model error', 'refused'], ['post-policy error', 'confirmed'], ['post-policy error', 'refused'], +] as const)('joins background cleanup on concurrent provider disposal (%s, %s)', async (ending, outcome) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + if (ending === 'model error') f.model.beforeStream = async (index) => { if (index === 1) throw new Error('Model failed') } + else f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === 'cua_run_code' + ? { kind: 'block', feedback: [{ type: 'text', text: 'Policy rejected output' }] } : next()) + const errors: unknown[] = [] + f.ctx.on('agent/error', ({ error }) => { errors.push(error) }) + const registered = vi.spyOn(NativeClient.prototype, 'registerCleanup') + onTestFinished(() => { registered.mockRestore() }) + const release = f.native.controlNext('releaseHeldInputs') + const idle = f.run() + await release.entered + await idle + + const entered: PromiseWithResolvers = Promise.withResolvers() + const [client] = registered.mock.contexts + if (!(client instanceof NativeClient)) throw new Error('Expected a native connection with a registered input owner') + client.registerCleanup(async () => { entered.resolve() }) + let disposed = false + const closing = f.provider.dispose().then(() => { disposed = true }) + try { + await entered.promise + expect(disposed).toBe(false) + expect(f.native.state.closedChannels).toBe(0) + } finally { + release.reply(outcome === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Release refused during disposal' } : undefined) + await closing + } + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) + expect(f.native.state.closedChannels).toBe(1) + if (outcome === 'confirmed') expect(f.native.events).toEqual(['w:down', 'w:up', 'native-close']) + else { + expect(errors).toContainEqual(expect.objectContaining({ code: 'INPUT_CLEANUP_FAILED' })) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(false) + } +}) + +it.each(['agent', 'provider', 'context'] as const)('awaits native release when the %s is disposed after a completed turn', async (owner) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + expect(f.native.held).toHaveLength(1) + const release = f.native.controlNext('releaseHeldInputs') + let disposed = false + const closing = (owner === 'agent' ? f.handle.dispose() : owner === 'provider' ? f.provider.dispose() : f.ctx.fiber.dispose()).then(() => { disposed = true }) + await release.entered + expect(disposed).toBe(false) + expect(f.native.state.closedChannels).toBe(0) + release.reply() + await closing + expect(f.native.held).toEqual([]) + expect(f.native.state.closedChannels).toBe(1) +}) + +it('leaves providers without held-input state support on their existing protocol', async () => { + const f = await setup([holdWindowProgram, 'await win.sendKeyEvent("w", "up")'], 'windows', undefined, true) + await f.run() + for (const call of f.native.calls.filter(call => call.method === 'sendKeyEvent')) expect(call.params).not.toHaveProperty('taskId') + expect(f.native.calls.some(call => ['getHeldInputs', 'releaseHeldInputs'].includes(call.method))).toBe(false) + expect(reminders(f.agent)).toEqual([]) +}) + +it('reports and releases only the owning task inputs', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const peerModel = new ProgramModel([holdProgram.replace('"w"', '"d"')]) + f.ctx.llm.registerAdapter(['peer-fixture'], peerModel) + const peer = await f.ctx.agents.create({ sessionId: brandString('peer-held-input'), meta: { cwd: process.cwd() }, + agentOptions: { provider: 'peer-fixture', model: 'vision' } }) + await f.run() + peer.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Hold D' }], source: { kind: 'user' } })) + await peer.agent.whenIdle() + expect(reminders(f.agent).join('')).not.toContain('Key "d"') + expect(reminders(peer.agent).join('')).not.toContain('Key "w"') + await f.handle.dispose() + expect(f.native.held.map(press => press.key)).toEqual(['d']) + await peer.dispose() + expect(f.native.held).toEqual([]) +}) + +it('reports native connection loss after a dispatched down and rejects further input', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true }) + const running = f.run() + await down.entered + down.disconnect() + await running + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') + const calls = f.native.calls.length + f.model.restart([holdProgram]) + await f.run() + expect(f.native.calls).toHaveLength(calls) +}) + +it('waits and reports cleanup refusal when user stop arrives as the program returns', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + f.ctx.on('tools/execute', async (execution, next) => { + const result = await next() + if (execution.name === 'cua_run_code' && execution.parent === undefined) f.agent.cancel({ kind: 'user' }) + return result + }) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await release.entered + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Release refused during stop' }) + await running + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Release refused during stop') +}) + +it('emits only the final outer reminder for a nested CUA program', async () => { + const f = await setup([`await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" })`], 'macos', undefined, true, true) + await f.agent.ctx.plugin(PtcToolExecutor) + f.model.toolName = 'run_code' + await f.run() + expect(reminders(f.agent)).toHaveLength(1) + expect(f.native.calls.filter(call => call.method === 'getHeldInputs')).toHaveLength(1) + expect(f.native.held.map(press => press.key)).toEqual(['w']) +}) + +it('ignores turn endings from Sessions without an Agent', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + const session = f.ctx.sessions.create(brandString('unattached-input-session')) + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'error', error: { code: 'UNKNOWN', message: 'Unrelated failure' } } }) + expect(f.native.held.map(press => press.key)).toEqual(['w']) +}) + +it('records release after a thinking pause so the resumed model sees the new input state', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const thinking: PromiseWithResolvers = Promise.withResolvers() + f.model.beforeStream = async (index, options) => { + if (index !== 1) return + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + const release = f.native.controlNext('releaseHeldInputs') + const notice = nextReleaseNotice(f) + const running = f.run() + await thinking.promise + f.agent.cancel({ kind: 'user' }) + await release.entered + release.reply() + await Promise.all([running, notice]) + expect(f.native.held).toEqual([]) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(true) + delete f.model.beforeStream + f.model.restart(['inspect("resumed")']) + await f.run() + expect(reminders(f.agent, 'cua-inputs-released')).toHaveLength(1) + expect(JSON.stringify(f.model.requests[0]?.messages)).toContain('CUA inputs were released during cleanup') +}) + +it('removes a pending held reminder when a pause preserves the inbox', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const inserted: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/inbox/inserted', ({ agent, message }) => { + if (agent !== f.agent || message.source.kind !== 'cua-held-inputs') return + inserted.resolve() + agent.cancel({ kind: 'user' }, { keepInbox: true }) + }) + const release = f.native.controlNext('releaseHeldInputs') + const notice = nextReleaseNotice(f) + const running = f.run() + await inserted.promise + await release.entered + f.agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Keep this pending instruction' }], source: { kind: 'user' } })) + release.reply() + await Promise.all([running, notice]) + expect(f.agent.inbox.nextStep.map(message => message.source.kind)).toContain('cua-inputs-released') + expect(f.agent.inbox.nextStep.map(message => message.source.kind)).not.toContain('cua-held-inputs') + f.model.restart(['inspect("resumed")']) + await f.run() + const resumed = JSON.stringify(f.model.requests[0]?.messages) + expect(resumed).toContain('Keep this pending instruction') + expect(resumed).toContain('CUA inputs were released during cleanup') + expect(resumed).not.toContain('CUA inputs are still held') +}) + +it('drops a delayed held-state reminder after cancellation has already released the input', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const post: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + const released: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/post-execute', async (execution, _result, next) => { + const decision = await next() + if (execution.name === 'cua_run_code' && execution.parent === undefined) { post.resolve(); await finish.promise } + return decision + }) + f.ctx.on('session/event', (_session, event) => { + if (event.type === 'agent/inbox/spliced' && event.data.inserted.some(message => message.source.kind === 'cua-inputs-released')) released.resolve() + }) + const running = f.run() + await post.promise + try { + f.agent.cancel({ kind: 'user' }) + await released.promise + expect(f.native.held).toEqual([]) + } finally { finish.resolve(); await running } + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-held-inputs')).toBe(false) + f.model.restart(['inspect("resumed")']) + await f.run() + expect(reminders(f.agent)).toEqual([]) + expect(reminders(f.agent, 'cua-inputs-released')).toHaveLength(1) +}) + +it.each(['reply before stop', 'stop before reply'] as const)('does not report held input on %s', async (order) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const query = f.native.controlNext('getHeldInputs', { afterDispatch: true, waitForCancellation: order === 'stop before reply' }) + const running = f.run() + await query.entered + if (order === 'reply before stop') query.reply() + f.agent.cancel({ kind: 'user' }) + if (order === 'stop before reply') { + await query.cancelled + query.reply({ code: 'NATIVE_CANCELLED', message: 'Held-state query cancelled' }) + } + await running + expect(f.native.held).toEqual([]) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-held-inputs')).toBe(false) +}) + +it('reports notice-write failure without treating confirmed native release as unknown', async () => { + const f = await setup([holdProgram + '; throw Error("failed program")'], 'macos', undefined, true, true) + const errors: unknown[] = [] + f.ctx.on('agent/error', (event) => { errors.push(event.error) }) + const inject = vi.spyOn(f.agent, 'inject').mockImplementationOnce(() => { throw new Error('Notice write failed') }) + onTestFinished(() => { inject.mockRestore() }) + await f.run() + expect(errors).toEqual([expect.objectContaining({ code: 'INPUT_NOTICE_FAILED' })]) + expect(f.native.held).toEqual([]) + f.model.restart([holdProgram]) + await f.run() + expect(f.native.held.map(press => press.key)).toEqual(['w']) +}) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 1d59a60492..0eb429a24b 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1050,10 +1050,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'release(agent: Agent): Promise', - description: 'Release one Agent\'s retained program environment with the dedicated runtime\'s owner release. The program process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent\'s programs until the release settles, so the caller holds them back; after a failed release it rejects them until a later release succeeds. Resolves when no environment exists.', + description: 'Release one Agent\'s retained program environment with the dedicated runtime\'s owner release. The program process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent\'s programs until the release settles, so the caller holds them back; after a failed release it rejects them until a later release succeeds. Resolves when no environment exists.', parameters: [{ name: 'agent', description: 'Agent whose `cua_run_code` state owner is released.' }], - returns: 'Completion after the process has exited and its output has drained.', - throws: ['When the process cleanup fails.'], + returns: 'Completion after the process has exited, its output has drained, and held-input cleanup has settled.', + throws: ['When environment or input cleanup fails, reporting both causes if both fail.'], + }, + { + signature: 'releaseInputs(agent: Agent): Promise', + description: 'Release the Agent\'s tracked input while retaining its program variables and application grants. Providers without held-input state support retain their existing cancellation behavior.', + parameters: [{ name: 'agent', description: 'Owner of the input to release.' }], + returns: 'Completion after native acknowledgement, or rejection when cleanup is unconfirmed.', }, { signature: 'screenshotRequestTarget(image: ImageAttachmentRef): ImageRequestTarget | undefined', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cdc3d4c98b..3a9c98d5fe 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10889,6 +10889,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain @@ -10992,9 +10995,6 @@ importers: '@deepseek-ai/dsh-hmr': specifier: workspace:* version: link:../../boot/hmr - '@deepseek-ai/dsh-llm': - specifier: workspace:* - version: link:../../llm/llm '@deepseek-ai/dsh-llm-deepseek': specifier: workspace:* version: link:../../llm/llm-deepseek diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 2ca9246e7f..8dade0e31c 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -76,6 +76,8 @@ const SAFE_HOST_DEPENDENCY_EXPORTS = { /** Runtime exports that require every consumer to resolve the provider's shared peer instance. */ const PEER_REQUIRED_HOST_EXPORTS = { + // Agent notifications must use the installed Agent and scope dispatch implementation. + '@deepseek-ai/dsh-agent': ['emitAgentEvent'], // Profile settings must match the installed Node provider's configuration schema. '@deepseek-ai/dsh-ptc-runtime-node/configuration': ['resolvePersistentExecution'], // CUA mounts the installed provider and shares executor error classes with PTC. @@ -106,7 +108,7 @@ const PEER_REQUIRED_HOST_EXPORTS = { // Imported titles follow the installed title service's normalization. '@deepseek-ai/dsh-session-title': ['normalizeSessionTitle'], // Error classes have instance identity; CUA and Liveshare throw the registry's own copy so `instanceof` against it matches. - '@deepseek-ai/dsh-tools': ['defineTool', 'ToolArgsError', 'ToolContextUnavailableError'], + '@deepseek-ai/dsh-tools': ['defineTool', 'ToolArgsError', 'ToolContextUnavailableError', 'RUN_CODE_NAME'], // Readers recognize a deadline's TimeoutReason only by `instanceof` against their own copy. '@deepseek-ai/dsh-timeout': ['deadline', 'timeoutOf'], // Imported web tool results must render exactly like the installed web tools' results and cards. diff --git a/snapshots/sdk/cua-run-code/session.v4.jsonl b/snapshots/sdk/cua-run-code/session.v4.jsonl index 5ebd9e1fc9..52686edd48 100644 --- a/snapshots/sdk/cua-run-code/session.v4.jsonl +++ b/snapshots/sdk/cua-run-code/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 1429bb4737..12a5233554 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -73,7 +73,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -87,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-native-scoped/system-prompt.expected.md b/snapshots/session/cua-native-scoped/system-prompt.expected.md index e754d2f50b..be6e2cff7b 100644 --- a/snapshots/session/cua-native-scoped/system-prompt.expected.md +++ b/snapshots/session/cua-native-scoped/system-prompt.expected.md @@ -75,7 +75,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -87,7 +87,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index ad63740eb0..728313151e 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -75,7 +75,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -87,7 +87,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 250fc0b17c..00cb4c3406 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -123,7 +123,7 @@ function createApplicationState(socket, record, application, captureBroker, conn const activity = existsSync(activityFile) ? JSON.parse(readFileSync(activityFile, 'utf8')) : undefined const pendingActivity = new Set(activity ?? []) const snapshots = new Map() - const heldKeys = new Map() + const heldInputs = new Map() const observedWindows = new Set() let acquired = false let generation = 0 @@ -135,7 +135,12 @@ function createApplicationState(socket, record, application, captureBroker, conn function refuse(code, message) { throw Object.assign(new Error(message), { code }) } function call(requestId, method, params) { record('call', { requestId, method, params }) - if (method === 'releaseHeldKeys') { heldKeys.delete(params.runId); return { dispatched: true } } + if (method === 'getHeldInputs') return [...heldInputs.values()] + if (method === 'releaseHeldInputs') { + const released = [...heldInputs.values()].reverse() + heldInputs.clear() + return released + } if (method === 'applicationIcons') return Object.fromEntries(params.paths.map(path => [path, `data:image/png;base64,${png}`])) if (method === 'openPermissionSettings') return { opened: true } if (method === 'permissionStatus' || method === 'requestPermission') { @@ -283,11 +288,13 @@ function createApplicationState(socket, record, application, captureBroker, conn application.value += params.text return { dispatched: true } } - if (method === 'sendKeyEvent') { - const keys = heldKeys.get(params.runId) ?? new Set() - if (params.direction === 'down') keys.add(params.key) - else if (!keys.delete(params.key)) refuse('INVALID_ARGUMENT', 'Key was not held by this program') - heldKeys.set(params.runId, keys) + if (method === 'sendKeyEvent' || method === 'toggleMouse') { + const input = method === 'sendKeyEvent' + ? { kind: 'key', key: params.key, appHandle: params.appHandle, mode: params.useSystemInput ? 'system' : 'application' } + : { kind: 'mouse', button: params.mouseButton, appHandle: params.appHandle, windowId: params.windowId, mode: params.useSystemInput ? 'system' : 'window' } + const id = JSON.stringify([params.appHandle, params.windowId, method, params.key ?? params.mouseButton]) + if (params.direction === 'down') heldInputs.set(id, input) + else if (!heldInputs.delete(id)) refuse('INVALID_ARGUMENT', 'Input was not held by this connection') return { dispatched: true } } if (method === 'typeText') application.value += params.text diff --git a/snapshots/session/cua-posttool-block/provider.mjs b/snapshots/session/cua-posttool-block/provider.mjs new file mode 100644 index 0000000000..56198ada39 --- /dev/null +++ b/snapshots/session/cua-posttool-block/provider.mjs @@ -0,0 +1,16 @@ +/** This policy scenario holds native confirmation until the model has received the final tool error. */ +import { installFixture } from '../cua-run-code/provider.mjs' +import { createNativeFixture } from '../cua-run-code/native-channel.mjs' +export { Config, inject, name } from '../cua-run-code/provider.mjs' + +/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig} config */ +export function apply(ctx, config) { + const fixture = createNativeFixture() + const release = fixture.controlNext('releaseHeldInputs') + const remove = ctx.on('session/event', (_session, event) => { + if (event.type !== 'turn/end') return + remove() + release.reply() + }) + installFixture(ctx, config, fixture) +} diff --git a/snapshots/session/cua-posttool-block/runtime.cordis.yml b/snapshots/session/cua-posttool-block/runtime.cordis.yml new file mode 100644 index 0000000000..93c86ab966 --- /dev/null +++ b/snapshots/session/cua-posttool-block/runtime.cordis.yml @@ -0,0 +1,11 @@ +# Computer Use with the provider's default preset selection under the PTC tool executor, on a profile that composes no presets. +- insert: + - id: computer-use + name: '@deepseek-ai/dsh-computer-use' + - id: cua-run-code-fixture + name: './provider.mjs' + config: + allowedApps: + - id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + name: Fixture + executablePath: /fixture/app diff --git a/snapshots/session/cua-posttool-block/session.v4.jsonl b/snapshots/session/cua-posttool-block/session.v4.jsonl new file mode 100644 index 0000000000..a844e4860e --- /dev/null +++ b/snapshots/session/cua-posttool-block/session.v4.jsonl @@ -0,0 +1,34 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1794200000000,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Hold W in test.fixture using a CUA program. Report the result and any confirmed cleanup."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tools:ptc-only","order":800,"state":"active","contentIndex":2},{"name":"tool:bash","order":1000,"state":"active","contentIndex":3},{"name":"tool:read","order":1100,"state":"active","contentIndex":4},{"name":"tool:write","order":1200,"state":"active","contentIndex":5},{"name":"tool:edit","order":1300,"state":"active","contentIndex":6},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":7},{"name":"tool:glob","order":1400,"state":"active","contentIndex":8},{"name":"tool:grep","order":1500,"state":"active","contentIndex":9},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":10},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":11},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":12},{"name":"tool:goal","order":2400,"state":"active","contentIndex":13},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":14},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":15},{"name":"computer-use:dsh-cua","order":3000,"state":"active","contentIndex":16},{"name":"tools:sdk","order":5000,"state":"active","contentIndex":17}]},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Hold W in test.fixture using a CUA program. Report the result and any confirmed cleanup."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Hold W in test.fixture using","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795148927697,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795148927697,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}}},{"type":"chunk","time":1795148927697,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"}}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"},"isError":false,"content":[{"type":"text","text":"(cua_run_code completed with no output)"}]}} +{"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"codex","handlerId":"codex:PostToolUse:1","matcher":"^run_code$"}} +{"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"codex:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by codex policy: summarize instead","durationMs":5.269749999999931}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1795148928147,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795148928147,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}}},{"type":"chunk","time":1795148928147,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:7}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} diff --git a/snapshots/session/cua-posttool-block/snapshot.yml b/snapshots/session/cua-posttool-block/snapshot.yml new file mode 100644 index 0000000000..7b92a41d4f --- /dev/null +++ b/snapshots/session/cua-posttool-block/snapshot.yml @@ -0,0 +1,8 @@ +version: 1 +scenario: cua-posttool-block +profile: headless +composition: ptc +recording: authored +header: + class: cua-run-code-ptc +permission: danger-full-access diff --git a/snapshots/session/cua-posttool-block/workspace/codex-hooks.json b/snapshots/session/cua-posttool-block/workspace/codex-hooks.json new file mode 100644 index 0000000000..cb9ec4d11c --- /dev/null +++ b/snapshots/session/cua-posttool-block/workspace/codex-hooks.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "^run_code$", + "hooks": [ + { + "type": "command", + "command": "echo 'tool output rejected by codex policy: summarize instead' >&2; exit 2" + } + ] + } + ] + } +} diff --git a/snapshots/session/cua-ptc-scoped/system-prompt.expected.md b/snapshots/session/cua-ptc-scoped/system-prompt.expected.md index c3e975f0d5..f002fde79b 100644 --- a/snapshots/session/cua-ptc-scoped/system-prompt.expected.md +++ b/snapshots/session/cua-ptc-scoped/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -89,7 +89,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ddc65920fc..fd6b45241e 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -89,7 +89,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl index a6866a4282..e4380520e5 100644 --- a/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md index 5046017207..012d55a6c4 100644 --- a/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md @@ -73,7 +73,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -87,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code-ptc/session.v4.jsonl b/snapshots/session/cua-run-code-ptc/session.v4.jsonl index a6866a4282..c64184299b 100644 --- a/snapshots/session/cua-run-code-ptc/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc/session.v4.jsonl @@ -12,34 +12,41 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"From run_code, call tools.cua_run_code t","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794479327867,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479327867,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1794479327867,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795057088827,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057088827,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1795057088827,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"},"isError":false,"content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"},"isError":false,"content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":1,\\\"bindings\\\":[\\\"cua\\\"],\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\"}\\n\"]}\n"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} {"type":"step/end","data":{"turn":1,"step":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794479328103,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479328103,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794479328103,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"},"isError":false,"content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":2,\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\",\\\"tree\\\":\\\"- [0] AXButton \\\\\\\"Increment\\\\\\\"\\\\n- AXStaticText \\\\\\\"Count: 2\\\\\\\"\\\",\\\"bindings\\\":[\\\"cua\\\"]}\\n\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795057089246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057089246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795057089246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"},"isError":false,"content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":2,\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\",\\\"tree\\\":\\\"- [0] AXButton \\\\\\\"Increment\\\\\\\"\\\\n- AXStaticText \\\\\\\"Count: 2\\\\\\\"\\\",\\\"bindings\\\":[\\\"cua\\\"]}\\n\"]}\n"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794479328211,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794479328211,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}}},{"type":"chunk","time":1794479328211,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1795057089410,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795057089410,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}}},{"type":"chunk","time":1795057089410,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index ae05d4cea8..d34be5205c 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -73,7 +73,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -87,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-scoped/session.v4.jsonl index c227cc91ce..a9d670cd72 100644 --- a/snapshots/session/cua-run-code-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-scoped/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-run-code/native-channel.d.mts b/snapshots/session/cua-run-code/native-channel.d.mts index c50d91e559..a4c3a35136 100644 --- a/snapshots/session/cua-run-code/native-channel.d.mts +++ b/snapshots/session/cua-run-code/native-channel.d.mts @@ -12,6 +12,14 @@ export function createNativeFixture(selectorPid?: number): { createChannel: NativeChannelFactory calls: Array<{ id: string; method: string; params: Record }> events: string[] + held: Array<{ connection: number; key: string }> + /** Control one native reply or cancellation acknowledgement at a deterministic barrier. */ + controlNext(method: string, options?: { afterDispatch?: boolean; waitForCancellation?: boolean }): { + entered: Promise + cancelled: Promise + reply(error?: { code: string; message: string }): void + disconnect(): void + } state: { count: number; openedChannels: number; closedChannels: number } /** @returns A barrier reached when the next click waits for native cancellation. */ holdNextClick(): Promise diff --git a/snapshots/session/cua-run-code/native-channel.mjs b/snapshots/session/cua-run-code/native-channel.mjs index 2e276b16bf..7999648cfb 100644 --- a/snapshots/session/cua-run-code/native-channel.mjs +++ b/snapshots/session/cua-run-code/native-channel.mjs @@ -12,18 +12,36 @@ export function createNativeFixture(selectorPid) { const calls = [] const events = [] const state = { count: 0, openedChannels: 0, closedChannels: 0 } + const held = [] + let controlled let nextHeldClick const bounds = { x: 40, y: 60, width: 320, height: 200 } const window = { windowId: '7', appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } function createChannel() { - state.openedChannels++ + const connection = ++state.openedChannels const stdout = new PassThrough() let acquired = false let generation = 0 let observed + let blocked let heldCallId function dispatch(method, params) { + if (method === 'getHeldInputs') return held.filter(press => press.connection === connection).map(press => press.kind === 'key' + ? { kind: 'key', key: press.key, appHandle: press.appHandle, ...press.windowId === undefined + ? { mode: 'application' } : { windowId: press.windowId, mode: 'system' } } + : { kind: 'mouse', button: press.key, appHandle: press.appHandle, windowId: press.windowId, mode: press.mode }) + if (method === 'releaseHeldInputs') { + const released = dispatch('getHeldInputs', params).reverse() + for (let index = held.length - 1; index >= 0; index--) { + const press = held[index] + if (press.connection === connection) { + events.push(`${press.key}:up`) + held.splice(index, 1) + } + } + return released + } if (method === 'getCapabilities') return { sessionLocked: false, permissions: { accessibility: true, screenRecording: true } } if (method === 'listApps') return [{ id: 'test.fixture', name: 'Fixture', isRunning: true, pid: selectorPid ?? 4 }] if (method === 'getApp') { @@ -35,6 +53,18 @@ export function createNativeFixture(selectorPid) { authorization: { id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app', persistable: true } } } if (!acquired || params.appHandle !== 'fixture-app') throw new Error('Acquire the application before using its handle') + if (method === 'sendKeyEvent' || method === 'toggleMouse') { + const key = params.key ?? params.mouseButton + const index = held.findIndex(press => press.connection === connection && press.key === key) + if (params.direction === 'down' && index < 0) held.push({ connection, key, appHandle: params.appHandle, + kind: method === 'sendKeyEvent' ? 'key' : 'mouse', windowId: params.windowId, mode: params.useSystemInput ? 'system' : 'window' }) + if (params.direction === 'up') { + if (index < 0) throw new Error('Input was not held by this connection') + held.splice(index, 1) + } + events.push(`${key}:${params.direction}`) + return { dispatched: true } + } if (method === 'listWindows') return [window] if (method === 'getState') { observed = `fixture-snapshot-${++generation}` @@ -53,13 +83,33 @@ export function createNativeFixture(selectorPid) { const stdin = new Writable({ write(chunk, _encoding, callback) { try { const { type, id, method, params } = JSON.parse(chunk.toString()) - if (type === 'cancel' && id === heldCallId) { + if (type === 'cancel' && blocked?.id === id) { + events.push('native-cancelled') + blocked.control.cancelled.resolve() + if (!blocked.control.waitForCancellation) blocked.finish({ code: 'NATIVE_CANCELLED', message: 'Fixture input cancelled.' }) + } else if (type === 'cancel' && id === heldCallId) { heldCallId = undefined events.push('native-cancelled') stdout.write(JSON.stringify({ id, error: { code: 'NATIVE_CANCELLED', message: 'Fixture click cancelled.' } }) + '\n') + } else if (type === 'cancel') { + // A reply can settle immediately before the caller's cancellation reaches the helper. } else { calls.push({ id, method, params }) - if (method === 'click' && nextHeldClick !== undefined) { + if (controlled?.method === method) { + const control = controlled + controlled = undefined + const result = control.afterDispatch ? dispatch(method, params) : undefined + const finish = error => { + if (!blocked) return + blocked = undefined + const response = error ? { id, error } : { id, result: result ?? dispatch(method, params) } + stdout.write(JSON.stringify(response) + '\n') + } + blocked = { id, control, finish } + control.reply = finish + control.disconnect = () => { stdout.end() } + control.entered.resolve() + } else if (method === 'click' && nextHeldClick !== undefined) { heldCallId = id const started = nextHeldClick nextHeldClick = undefined @@ -80,13 +130,23 @@ export function createNativeFixture(selectorPid) { if (closed) return closed = true events.push('native-close') + for (let index = held.length - 1; index >= 0; index--) if (held[index].connection === connection) held.splice(index, 1) stdin.end() stdout.end() }, waitForClose: () => done, } } - return { createChannel, calls, events, state, + return { createChannel, calls, events, state, held, + controlNext(method, { afterDispatch = false, waitForCancellation = false } = {}) { + if (controlled) throw new Error('Another request is already controlled') + const entered = Promise.withResolvers(), cancelled = Promise.withResolvers() + const control = { method, afterDispatch, waitForCancellation, entered, cancelled, + reply: () => { throw new Error('Request has not arrived') }, disconnect: () => { throw new Error('Request has not arrived') } } + controlled = control + return { entered: entered.promise, cancelled: cancelled.promise, + reply: error => control.reply(error), disconnect: () => control.disconnect() } + }, holdNextClick() { if (nextHeldClick !== undefined) throw new Error('A fixture click is already held') nextHeldClick = Promise.withResolvers() diff --git a/snapshots/session/cua-run-code/provider.mjs b/snapshots/session/cua-run-code/provider.mjs index 10f864cabb..50dab3e1f0 100644 --- a/snapshots/session/cua-run-code/provider.mjs +++ b/snapshots/session/cua-run-code/provider.mjs @@ -9,12 +9,21 @@ export const Config = CuaConfig /** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig} config */ export function apply(ctx, config) { - const fixture = createNativeFixture() + installFixture(ctx, config, createNativeFixture()) +} + +/** + * @param {import('@deepseek-ai/cordis').Context} ctx - Provider scope. + * @param {import('@deepseek-ai/dsh-cua').CuaConfig} config - CUA provider options. + * @param {ReturnType} fixture - Native request receiver for this scenario. + */ +export function installFixture(ctx, config, fixture) { installCua(ctx, config, { helperPath: process.execPath, + heldInputState: true, createChannel: fixture.createChannel, getGuidance: () => COMMON_GUIDANCE, - capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot'], + capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index c227cc91ce..576f4fe563 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -13,32 +13,47 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795061770766,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795061770766,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795061770767,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":\"7\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":\"7\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} {"type":"step/end","data":{"turn":1,"step":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[30],"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795061771077,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795061771077,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795061771077,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:5","name":"cua","arguments":{"method":"toggleMouse","params":{"appHandle":"fixture-app","windowId":"7","mouseButton":"left","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:5","name":"cua","arguments":{"method":"toggleMouse","params":{"appHandle":"fixture-app","windowId":"7","mouseButton":"left","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"}]}} {"type":"step/end","data":{"turn":1,"step":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794291763343,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794291763343,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1794291763343,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795061771116,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795061771116,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795061771116,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs were released during cleanup:\n- Key \"d\", appHandle \"fixture-app\" (application input).\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:11}}"}]}} diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index d004db325f..1b3c4b96c2 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -71,7 +71,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -85,6 +85,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index d660b9c964..e387577d3f 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -89,7 +89,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/web/cua-run-code/code.expected.md b/snapshots/web/cua-run-code/code.expected.md index 24f68a7612..442b8ef667 100644 --- a/snapshots/web/cua-run-code/code.expected.md +++ b/snapshots/web/cua-run-code/code.expected.md @@ -3,4 +3,4 @@ - button "Wrap lines" [pressed] - button "Original JSON" - button "Copy code" - - code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" + - code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" diff --git a/snapshots/web/cua-run-code/ui.expected.md b/snapshots/web/cua-run-code/ui.expected.md index 70299ccafd..8c873862f4 100644 --- a/snapshots/web/cua-run-code/ui.expected.md +++ b/snapshots/web/cua-run-code/ui.expected.md @@ -20,18 +20,24 @@ - text: typescript - button "Wrap lines" [pressed] - button "Copy" -- code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" +- code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" - text: "OUT {\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"} sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee (1x1px, 90 bytes)" - button "Inspect" - button "Tool call cua · getCapabilities" - button "Tool call cua · getApp" +- button "Tool call cua · sendKeyEvent" - button "Tool call cua · getState" - button "Tool call cua · click" - button "Tool call cua · screenshot" +- button "Context injection cua-held-inputs CUA inputs remain held" - button "Code Reuse the retained application and window" +- button "Tool call cua · sendKeyEvent" - button "Tool call cua · getState" - button "Tool call cua · click" - button "Tool call cua · getState" +- button "Tool call cua · toggleMouse" +- button "Tool call cua · sendKeyEvent" +- button "Context injection cua-held-inputs CUA inputs remain held" - paragraph: "The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call." - button "Copy" - button "Good response"