diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index e1f13bb935..56e555a4c2 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -90,7 +90,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `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 b4d30dc8de..e588a55e62 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -92,7 +92,7 @@ | `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/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index e401698179..585e52c377 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1338,8 +1338,8 @@ en: 0080c345c319a4b5 zh: de1a8b3ed621ce21 /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: d7caf05599b9e837 - zh: 9ef405c0a4dc9b19 + en: b2488366535b5fdc + zh: b64d50345521eb99 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 9258f30a9c4e2a3a zh: c44d997d719e863c diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 485e5c1fff..2b3b3baa6a 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5369,7 +5369,7 @@ Sources: [`packages/llm/llm/src/types.ts:134`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/contracts.ts:402`](../packages/core/tools/src/contracts.ts) +Sources: [`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index e8808a31f7..ec3ecd47f0 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5371,7 +5371,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/contracts.ts:402`](../packages/core/tools/src/contracts.ts) +来源:[`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 6eb238d126..e87800d467 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -224,7 +224,7 @@ {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, - {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:402"]}, + {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, {"digest":"3d1339bcc98cb53714bf31ac4a6e7c9ce15a412dd58451778a383627367a4666","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:54"]}, {"digest":"3d7d07060a7be77984feb651ea2bf1925d3e0477911d9d3ed86330d1e8ca6182","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackItem"],"sources":["packages/feedback/message-feedback/src/types.ts:20"]}, {"digest":"3e0eff5946255ff05d88a10839c60305135801f97794ea48d409f8503303317e","names":[],"sources":[]}, diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index 062e525e01..bcefbfdd3b 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: f74b432c5ad7f78f - zh: 4e5487828ff17250 + en: a6d9db4237438b2a + zh: 1fe07dedc426c5eb /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index cfde7eee48..5a32c8e009 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -450,17 +450,10 @@ interface ToolExecution extends ToolExecutionInput { interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal - /** - * Register cleanup during dispatch for this invocation. If the final result is an error, the executor - * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. - * Cleanup failures add feedback to the original error. Successful calls discard the registrations. - * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. - */ - onFailure(cleanup: () => void | Promise): void } ``` -`ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. A dispatch wrapper can register `exec.onFailure(cleanup)` before returning. When the final outcome fails, including a post-execute block, the executor waits for that invocation’s cleanups before notifying result observers. A cleanup refusal appends feedback and preserves the original error code. +`ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. A `ToolGuard` is scope-aware final pre-dispatch policy. Its return type deliberately has no allow result: `undefined` preserves the waterfall decision, while a returned reason or `ToolGuardDenial` can only reduce permission, so a later listener cannot undo it. A denial's optional `info` becomes the failed result's structured error identity. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 411a46642e..1b82c3b678 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -450,17 +450,10 @@ interface ToolExecution extends ToolExecutionInput { interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal - /** - * Register cleanup during dispatch for this invocation. If the final result is an error, the executor - * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. - * Cleanup failures add feedback to the original error. Successful calls discard the registrations. - * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. - */ - onFailure(cleanup: () => void | Promise): void } ``` -`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 执行包装层可在返回前调用 `exec.onFailure(cleanup)`。若最终结果失败,包括被后置策略拒绝,执行器会先等待该次调用的清理,再通知结果观察者。清理失败时追加错误反馈,并保留原错误码。 +`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 `ToolGuard` 是感知作用域的最终预分派策略。其返回类型有意不包含 allow 结果:`undefined` 保留 waterfall 的决策,而返回的 reason 或 `ToolGuardDenial` 只能缩减权限,因此后续监听器无法撤销它。拒绝中可选的 `info` 会成为失败结果的结构化错误身份。 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 index b88312ff7a..a753c8369d 100644 --- 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 @@ -12,5 +12,5 @@ en: 2812241cf189be50 zh: ee90f8e5c6c55512 /cua-reports-held-input-after-programs/migration: - en: 23893a11333ff744 - zh: e1dae0e424d6420f + en: 1bd7668cac0efe0d + zh: 2122c9d5135283f7 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 index 2ff3e9e007..b6c7ff0426 100644 --- 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 @@ -14,4 +14,4 @@ On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` 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 implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. -3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. A failed or cancelled program waits for its cleanup. This includes a program that sends input successfully before a post-execute policy rejects its result. Execution middleware can register call-scoped cleanup with `exec.onFailure(cleanup)`. 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. +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 index 5377e222a5..a342f3d78a 100644 --- 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 @@ -14,4 +14,4 @@ macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨 1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 -3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败或取消时会等待自身的清理,已发送输入、随后被后置策略拒绝的程序也适用。工具执行包装层可用 `exec.onFailure(cleanup)` 登记该次调用的失败清理。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 +3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序执行中失败或取消时,会等待自身的清理。如果程序执行成功,但后置策略拒绝结果,工具返回策略错误,CUA 单独等待原生释放确认。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 6bfdcf15a3..ff22c17d80 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -30,8 +30,8 @@ en: c6f98b2283cc2e47 zh: c2cdce5d13473f15 /deepseek-ai-dsh-tools/use-this-package/enforce-policy-on-calls: - en: 979aa454c0c8705a - zh: 00bfbbedc9e43b10 + en: cbfe8317565ac62d + zh: 1e71c66941e50881 /deepseek-ai-dsh-tools/use-this-package/host-presentation-descriptors: en: 258e16bb367229e5 zh: 7c1eb91062b4e4ad diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 119988a8ab..50732a3159 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -91,7 +91,7 @@ Agent-step concurrency uses the [agent-loop configuration](../agent-loop/README. `ctx.tools.guard(guard)` registers a monotonic synchronous guard after the extensible `tools/pre-execute` waterfall: a returned reason denies the call, and no later listener can turn that denial back into permission. The pipeline's events give plugins more control — `tools/pre-execute` decides allow/deny/ask, `tools/execute` wraps dispatch for timeout or retry, `tools/post-execute` inspects or replaces the result, and `tools/result` observes the frozen final outcome. -A tool’s `projectContent` installs execution-prepared content before post-execute policies. Policies may still replace or block it; `finalizeContent` remains the final content transform after those policies. A dispatch wrapper can register `exec.onFailure(cleanup)` before returning. When the final outcome fails, including a post-execute block, the executor waits for that invocation’s cleanups before notifying result observers. A cleanup refusal appends feedback and preserves the original error code. +A tool’s `projectContent` installs execution-prepared content before post-execute policies. Policies may still replace or block it; `finalizeContent` remains the final content transform after those policies. ### Host presentation descriptors diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index f9c68321da..28abce32f4 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -91,7 +91,7 @@ Agent 步骤的并发上限使用 [agent-loop 配置](../agent-loop/README.zh.md `ctx.tools.guard(guard)` 在可扩展的 `tools/pre-execute` waterfall(瀑布式事件)之后注册单调同步守卫:返回的理由会拒绝调用,后续监听器无法把该拒绝重新变为允许。流水线事件给插件更多控制——`tools/pre-execute` 决定允许/拒绝/询问,`tools/execute` 为超时或重试包装分发,`tools/post-execute` 检查或替换结果,`tools/result` 观测冻结的最终结果。 -工具的 `projectContent` 在执行后策略之前安装执行期间准备的图文内容。策略仍可替换或阻止这些内容;`finalizeContent` 保留为策略之后的最终内容处理。 执行包装层可在返回前调用 `exec.onFailure(cleanup)`。若最终结果失败,包括被后置策略拒绝,执行器会先等待该次调用的清理,再通知结果观察者。清理失败时追加错误反馈,并保留原错误码。 +工具的 `projectContent` 在执行后策略之前安装执行期间准备的图文内容。策略仍可替换或阻止这些内容;`finalizeContent` 保留为策略之后的最终内容处理。 ### Host 展示描述 diff --git a/packages/core/tools/src/contracts.ts b/packages/core/tools/src/contracts.ts index 9f939f98aa..51597b4107 100644 --- a/packages/core/tools/src/contracts.ts +++ b/packages/core/tools/src/contracts.ts @@ -232,13 +232,6 @@ export interface ToolExecution extends ToolExecutionInput { export interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal - /** - * Register cleanup during dispatch for this invocation. If the final result is an error, the executor - * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. - * Cleanup failures add feedback to the original error. Successful calls discard the registrations. - * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. - */ - onFailure(cleanup: () => void | Promise): void } /** diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index ef54d39eca..9db8bfc610 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -11,7 +11,7 @@ import { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, ToolNotFoundError, ToolOutp import { APPROVAL_CANCELLED, APPROVAL_ERROR_NAME, APPROVAL_REJECTED, APPROVAL_UNAVAILABLE, type ApprovalErrorCode } from './error-codes.ts' import { validateJsonSchemaValue } from './json-schema.ts' import type { ToolsService } from './index.ts' -import type { ResolvedToolSet, ToolDefinition, ToolExecutionInput, ToolExecutionMode, ToolExecution, ToolRunContext, ToolExecutionResult, ToolExecutionSuccess, ToolExecutionFailure, ToolErrorInfo, ToolExecutionToken, PreToolDecision, PostToolDecision } from './contracts.ts' +import type { ResolvedToolSet, ToolDefinition, ToolExecutionInput, ToolExecutionMode, ToolExecution, ToolRunContext, ToolExecutionResult, ToolExecutionSuccess, ToolErrorInfo, ToolExecutionToken, PreToolDecision, PostToolDecision } from './contracts.ts' /** Executor-owned lookup and restrictions applied before extensible execution policy. */ export interface ToolExecutionSource { @@ -90,8 +90,6 @@ export class ToolExecutionPipeline { /** Original caller cancellation, kept outside the wrapper-mutable execution object. */ private cancellationStates = new WeakMap() - private readonly failureCleanups = new WeakMap void | Promise)[]>() - /** Definition-owned final content transform snapshotted before policy begins. */ private contentFinalizers = new WeakMap() @@ -306,16 +304,8 @@ export class ToolExecutionPipeline { * @returns whether the result still needs post-execute. */ async dispatch(exec: ToolRunContext): Promise { - let dispatching = true try { - const mutableExec = Object.assign(exec as MutableToolRunContext, { - onFailure: (cleanup: () => void | Promise) => { - if (!dispatching) throw new Error('Tool failure cleanup must be registered during dispatch') - const registered = this.failureCleanups.get(exec) - if (registered) registered.push(cleanup) - else this.failureCleanups.set(exec, [cleanup]) - }, - }) + const mutableExec = exec as MutableToolRunContext const carrier = scopeTarget(this.tools, exec.agent) const result = await this.ctx.waterfall( carrier, 'tools/execute', mutableExec, @@ -342,8 +332,6 @@ export class ToolExecutionPipeline { } } catch (error: unknown) { return { kind: 'final-result', result: this.wrapperFailureResult(exec, error) } - } finally { - dispatching = false } } @@ -376,7 +364,6 @@ export class ToolExecutionPipeline { return assertNever(outcome, 'scheduled tool outcome') } const { result } = outcome - let final: ToolExecutionResult try { const project = this.contentProjectors.get(exec) this.contentProjectors.delete(exec) @@ -385,13 +372,15 @@ export class ToolExecutionPipeline { ? result : this.markCanonical(exec, this.materializeFinalResult({ ...result, content })) const postResult = await this.postExecute(exec, projected) - final = this.callerCancelled(exec) && !postResult.isError - ? this.cancellationResult(exec, postResult) - : postResult + return this.finish( + exec, + this.callerCancelled(exec) && !postResult.isError + ? this.cancellationResult(exec, postResult) + : postResult, + ) } catch (error: unknown) { - final = toolErrorResult(error) + return this.finish(exec, toolErrorResult(error)) } - return this.finish(exec, final) } /** @@ -402,7 +391,7 @@ export class ToolExecutionPipeline { * @returns the materialized final result. * @internal */ - private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult | Promise { + private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult { let materializedResult: ToolExecutionResult try { materializedResult = this.materializeFinalResult(result) @@ -415,28 +404,6 @@ export class ToolExecutionPipeline { } catch (error: unknown) { finalResult = this.materializeFinalResult(toolErrorResult(error)) } - const cleanups = this.failureCleanups.get(exec) - this.failureCleanups.delete(exec) - if (finalResult.isError && cleanups) return this.finishFailure(exec, finalResult, cleanups) - this.notifyResult(exec, finalResult) - return finalResult - } - - /** Await all cleanup for this failed call and preserve the original error identity and policy feedback. */ - private async finishFailure(exec: ToolRunContext, result: ToolExecutionFailure, - cleanups: readonly (() => void | Promise)[]): Promise { - const errors: string[] = [] - for (const cleanup of cleanups) { - try { await cleanup() } catch (error) { errors.push(toolErrorMessage(error)) } - } - let finalResult: ToolExecutionResult = result - if (errors.length) { - const feedback = `Tool cleanup failed: ${errors.join('\n')}` - finalResult = this.materializeFinalResult({ - ...result, error: { ...result.error, message: `${result.error.message}\n${feedback}` }, - content: [...result.content, { type: 'text', text: feedback }], - }) - } this.notifyResult(exec, finalResult) return finalResult } diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index d77ffb8b7a..3952e42194 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -573,39 +573,6 @@ describe('ToolRuntime', () => { expect(result.error?.message).toBe(message) }) - it('settles registered cleanups only on final failure, before reporting the policy result', async () => { - const ctx = await setup() - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - const events: string[] = [] - try { - ctx.tools.register(echoTool) - let registerLate: (() => void) | undefined - ctx.on('tools/execute', (exec, next) => { - registerLate = () => { exec.onFailure(() => {}) } - exec.onFailure(() => { events.push('first'); throw new Error('first cleanup failed') }) - exec.onFailure(async () => { entered.resolve(undefined); await release.promise; events.push('second') }) - return next() - }) - ctx.on('tools/result', (_exec, result) => { events.push(result.isError ? 'failed' : 'succeeded') }) - const call = (id: string) => executeToolFixture(ctx, { signal: testToolSignal, callId: brandString(id), name: 'echo', arguments: {} }) - expect((await call('ok')).isError).toBe(false) - expect(events).toEqual(['succeeded']) - expect(() => { registerLate!() }).toThrow('during dispatch') - ctx.on('tools/post-execute', async (): Promise => ({ - kind: 'block', feedback: [{ type: 'text', text: 'rejected' }], info: { name: 'PolicyError', code: 'BLOCKED' }, - }), { prepend: true }) - const blocked = call('block') - await entered.promise - expect(events).toEqual(['succeeded', 'first']) - release.resolve(undefined) - expect(await blocked).toMatchObject({ isError: true, error: { info: { code: 'BLOCKED' }, - message: 'rejected\nTool cleanup failed: first cleanup failed' }, - content: [{ text: 'rejected' }, { text: 'Tool cleanup failed: first cleanup failed' }] }) - expect(events).toEqual(['succeeded', 'first', 'second', 'failed']) - } finally { release.resolve(undefined); await ctx.fiber.dispose() } - }) - it('records the structured identity of a post-execute block', async () => { const ctx = await setup() ctx.tools.register(echoTool) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 64c069db3f..58f4e9537d 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: 2be36ce22ba367e0 - zh: ad4599b1cd5b4de3 + en: 60892f557adb5d01 + zh: 2e8483610017484a /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 f38fa04d53..b36d1a544d 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -93,7 +93,7 @@ Permission responses identify their platform and report only the state that plat Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. 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. -Held input belongs to the task and native connection, outside program processes. 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 program rejected by post-execute policy releases its held input before the tool returns the rejection. If release also fails, the result reports both causes. 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. +Held input belongs to the task and native connection, outside program processes. 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. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 2a2ecab14e..a7f270f27c 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -93,7 +93,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 -持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。后置策略拒绝程序结果时,工具等待持有输入释放后再返回拒绝原因。如果释放也失败,结果同时报告两个原因。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 +持有输入属于任务和原生连接,保存在程序进程之外。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 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 845b8150fc..074c08cce6 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -2,7 +2,7 @@ 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 ToolDispatchExecution } from '@deepseek-ai/dsh-tools' +import { RUN_CODE_NAME, type ToolExecution } from '@deepseek-ai/dsh-tools' import { z } from 'zod' import { NativeError, type NativeClient } from './native-client.ts' @@ -55,10 +55,6 @@ class InputOwner { return renderInputs(inputs, 'held') } - registerFailureCleanup(execution: ToolDispatchExecution): void { - if (this.client) execution.onFailure(async () => { await this.close() }) - } - close(canRequest = true): Promise> { this.controller.abort() return this.closing ??= Promise.resolve().then(async () => { @@ -87,6 +83,8 @@ class InputOwner { /** 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 }>() @@ -136,8 +134,7 @@ export class CuaHeldInputs { */ async release(agent: Agent): Promise { await this.owners.get(agent)?.close() } - private stop(agent: Agent): void { - const owner = this.owners.get(agent) + 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. } @@ -152,7 +149,7 @@ export class CuaHeldInputs { 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(agent) } + 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) @@ -181,7 +178,7 @@ export class CuaHeldInputs { // 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 } } - owner?.registerFailureCleanup(execution) + 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' } }), @@ -193,11 +190,16 @@ export class CuaHeldInputs { 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(event.agent) } + 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) } }) } @@ -213,7 +215,7 @@ export class CuaHeldInputs { 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(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/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 41e68200ff..da0dcb4e1f 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -408,39 +408,109 @@ it('reports the Windows keyboard window and desktop input mode and supports a la it.each([ ['run_code', 'confirmed'], ['cua_run_code', 'confirmed'], ['cua_run_code', 'refused'], -] as const)('settles %s post-policy failure after native cleanup (%s)', async (tool, cleanup) => { - const code = tool === 'run_code' - ? `await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" })` : holdProgram - const f = await setup([code], 'macos', undefined, true, true) +] 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 - f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === 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']) - expect(f.agent.session.snapshotEvents().some(event => event.type === 'tool/result')).toBe(false) + 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 running } - const result = f.agent.session.snapshotEvents().find(event => event.type === 'tool/result') - expect(result?.data).toMatchObject({ error: { code: 'HOOK_BLOCKED' }, message: { isError: true } }) - const shown = JSON.stringify(f.model.requests[1]?.messages) - expect(shown).toContain('Policy rejected output') - expect(shown).not.toContain('CUA inputs are still held:') + await following if (cleanup === 'confirmed') { - expect(f.native.events).toEqual(['w:down', 'w:up']) - expect(shown).toContain('CUA inputs were released during cleanup') + 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(shown).toContain('Fixture refused release') - expect(shown).not.toContain('CUA inputs were released during cleanup') + 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 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.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")'], @@ -621,9 +691,13 @@ it.each(['closes', 'fails to close'] as const)('waits for Agent release before t else expect(report).not.toHaveBeenCalled() }) -it.each(['confirmed', 'refused'] as const)('joins background cleanup on concurrent provider disposal (%s)', async (outcome) => { +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) - f.model.beforeStream = async (index) => { if (index === 1) throw new Error('Model failed') } + 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') diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 13e207dff5..3491fbaa74 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -11202,7 +11202,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolDispatchExecution', - declaration: 'export interface ToolDispatchExecution extends Omit {\n signal: AbortSignal;\n onFailure(cleanup: () => void | Promise): void;\n}', + declaration: 'export interface ToolDispatchExecution extends Omit {\n signal: AbortSignal;\n}', }, { name: 'ToolErrorInfo', diff --git a/snapshots/session/cua-posttool-block/runtime.cordis.yml b/snapshots/session/cua-posttool-block/runtime.cordis.yml index 0a38b473eb..e01fd12b60 100644 --- a/snapshots/session/cua-posttool-block/runtime.cordis.yml +++ b/snapshots/session/cua-posttool-block/runtime.cordis.yml @@ -5,6 +5,7 @@ - id: cua-run-code-fixture name: '../cua-run-code/provider.mjs' config: + confirmReleaseAtTurnEnd: true allowedApps: - id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa name: Fixture diff --git a/snapshots/session/cua-posttool-block/session.v4.jsonl b/snapshots/session/cua-posttool-block/session.v4.jsonl index ddfb71b416..bb19188640 100644 --- a/snapshots/session/cua-posttool-block/session.v4.jsonl +++ b/snapshots/session/cua-posttool-block/session.v4.jsonl @@ -30,6 +30,6 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"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:5}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The post-tool policy rejected the program output. Cleanup confirmed W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795095785319,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795095785319,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The post-tool policy rejected the program output. Cleanup confirmed W was released."}}},{"type":"chunk","time":1795095785319,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"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:7}}"},"stream":[{"type":"chunk","time":1795095785319,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795095785319,"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":1795095785319,"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"}}} diff --git a/snapshots/session/cua-run-code/provider.mjs b/snapshots/session/cua-run-code/provider.mjs index 6667f7fb6c..a2d1c35aca 100644 --- a/snapshots/session/cua-run-code/provider.mjs +++ b/snapshots/session/cua-run-code/provider.mjs @@ -1,15 +1,25 @@ /** Real CUA registration with an isolated fixture at the native byte-stream boundary. */ -import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' +import Schema from '@deepseek-ai/schemastery' +import { installCua } from '@deepseek-ai/dsh-cua' +import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' import { createNativeFixture } from './native-channel.mjs' export const name = 'cua-run-code-fixture' export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] -export const Config = CuaConfig +export const Config = Schema.object({ ...CuaConfigFields, confirmReleaseAtTurnEnd: Schema.boolean().default(false) }) -/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig} config */ -export function apply(ctx, config) { +/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig & { confirmReleaseAtTurnEnd: boolean }} config */ +export function apply(ctx, { confirmReleaseAtTurnEnd, ...config }) { const fixture = createNativeFixture() + if (confirmReleaseAtTurnEnd) { + const release = fixture.controlNext('releaseHeldInputs') + const remove = ctx.on('session/event', (_session, event) => { + if (event.type !== 'turn/end') return + remove() + release.reply() + }) + } installCua(ctx, config, { helperPath: process.execPath, heldInputState: true,