Merge remote-tracking branch 'origin/master' into codex/session-control-message
This commit is contained in:
commit
cde825ee5e
140 files changed
+4291
-460
No files matched your search
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: a22ddcfb339e503d
|
||||
zh: a1f4fadb46fce1e7
|
||||
/agent-note-native-cua-objects-independent-of-evaluator-ownership/decision:
|
||||
en: 176a9c2f6040f2a1
|
||||
zh: 2617ec13d25de998
|
||||
en: bbde2baca9167362
|
||||
zh: 69e6eb14818aed25
|
||||
/agent-note-native-cua-objects-independent-of-evaluator-ownership/alternatives-considered:
|
||||
en: 3d0bc77e3c432cb9
|
||||
zh: 50a20eda1811f16c
|
||||
|
||||
@@ -14,7 +14,7 @@ The shared `cua` library owns application/window objects, consent, and logged di
|
||||
|
||||
The experimental CUA package owns a native-app subset of the Codex-style object interface and selected MIT-licensed macOS behavior adapted from Cua Driver in a Swift helper. A source manifest records the adapted upstream files and local implementation. The helper is locally compiled; the package has no external Cua Driver runtime dependency. The existing [provider registration](2026-09-12-computer-use-provider-registration.md) prevents competing computer-use providers within one composition.
|
||||
|
||||
The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. CUA defines no persistence directive, worker or run_code replacement.
|
||||
The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. The object API defines no persistence directive or evaluator; [CUA programs outside PTC](2026-11-09-cua-program-tool.md) supersedes the original exclusion of a dedicated program entry by composing the shared PTC factory and Node runtime.
|
||||
|
||||
Native process ownership follows the [shared helper decision](2026-10-09-cua-shared-native-helper.md), with isolated Agent connections. App handles bind process identity and kernel start time; replacing the process or helper never revives old handles. The native helper retains per-app and per-window snapshots. The [object API](2026-11-05-cua-scoped-surfaces-and-input.md) keeps the latest successful observation per application handle. Coordinate actions select an owned window; the Host maps [screenshot coordinates](2026-10-13-cua-hover-routes-and-coordinates.md) to native window-local points. Providers declare keyboard scopes in `keyboard`. macOS supports keyboard input at the application's current focus.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Computer-use 程序需要一致的应用和窗口操作。将这些操作与 CUA
|
||||
|
||||
实验 CUA 包提供 Codex 风格的原生应用对象接口,并在 Swift 辅助进程中改写 Cua Driver 中选取的 MIT 许可 macOS 行为。源码清单记录改写的上游文件和本地实现。辅助进程在本地编译,本包不依赖外部 Cua Driver 运行时。已有的 [provider 注册机制](2026-09-12-computer-use-provider-registration.zh.md)防止同一组合中出现竞争 provider。
|
||||
|
||||
对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。CUA 不定义持久化指令、执行 worker 或 run_code 替代实现。
|
||||
对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。对象 API 不定义持久化指令或求值器;[PTC 之外的 CUA 程序](2026-11-09-cua-program-tool.zh.md)通过组合共享 PTC 工厂和 Node 运行时,取代原先不提供专用程序入口的决定。
|
||||
|
||||
原生进程归属遵循[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md),Agent 连接保持隔离。应用句柄绑定进程身份及内核启动时间,替换进程或辅助进程不会使旧句柄重新有效。原生 helper 按应用和可选窗口保存快照。[对象 API](2026-11-05-cua-scoped-surfaces-and-input.zh.md) 为每个应用句柄保留最近一次成功读取的快照。坐标操作选择属于该应用的窗口;Host 按[截图坐标规则](2026-10-13-cua-hover-routes-and-coordinates.zh.md)换算为原生窗口内 point。提供方通过 `keyboard` 声明可用范围。macOS 仅支持向应用当前焦点发送键盘输入。
|
||||
|
||||
|
||||
+2
-2
@@ -15,5 +15,5 @@
|
||||
en: d6f40bf02df37ab7
|
||||
zh: e5b85ce9d41e8754
|
||||
/agent-note-ship-experimental-capabilities-as-optional-bundles/consequences:
|
||||
en: 3064da835e892958
|
||||
zh: bfcf967b6acc6f85
|
||||
en: 49e2c3f9f641c38b
|
||||
zh: 3aa772fb43c4bb6e
|
||||
+1
-1
@@ -34,4 +34,4 @@ Computer Use is a shipped optional bundle in the experimental group. Its bundle
|
||||
|
||||
Official discovery does not imply experimental status or a different plugin lifecycle. Switching a bundle off keeps its installed files; failed activation retains the existing saved-selection behavior. Bundle rows are ordinary Host rows with their usual switches. Individual and combined composition tests cover the Host rows and every preset's tool catalog; live switching and recorded Sessions cover activation and model-visible behavior.
|
||||
|
||||
Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes whose bound preset is `ptc`. Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution.
|
||||
Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes. The preset named by `agentPreset` receives raw `cua`; other composed presets receive the [CUA program tool](2026-11-09-cua-program-tool.md). Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution.
|
||||
+1
-1
@@ -34,4 +34,4 @@ Computer Use 是 experimental 包组内随安装提供的可选组合包。组
|
||||
|
||||
官方发现不表示实验性状态,也不引入不同的插件生命周期。关闭 bundle 保留已安装文件;激活失败保留现有的已保存选择行为。Bundle 行是普通 Host 行,使用常规开关。独立与组合测试覆盖 Host 行及每个预设的工具目录;实时切换与已记录 Session 覆盖激活和模型可见行为。
|
||||
|
||||
Computer Use 将权限服务和原生提供方保留在 Host,在已绑定 `ptc` preset 的 Agent 作用域中注册工具。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。
|
||||
Computer Use 将权限服务和原生提供方保留在 Host,并在 Agent 作用域中注册工具。`agentPreset` 指定的 preset 获得原始 `cua`;其他已组合的 preset 获得 [CUA 程序工具](2026-11-09-cua-program-tool.zh.md)。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-cua-program-tool.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 .agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md
|
||||
/agent-note-cua-programs-outside-the-ptc-preset:
|
||||
en: a283f005c51274e7
|
||||
zh: 1f697efb2dbac3ba
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/problem:
|
||||
en: 87ce83e36a6ab68e
|
||||
zh: 8aa98dc7dae03c41
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/decision:
|
||||
en: 98e4a571dc7d4c10
|
||||
zh: 2465f2abff5eb64c
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/alternatives-considered:
|
||||
en: b5d8e00cbe4b53ae
|
||||
zh: 4ef81611150a8d75
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/consequences:
|
||||
en: 22f25d54373ba06b
|
||||
zh: ee335578caaf1ab3
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: CUA programs outside the PTC preset
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-cua-program-tool.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Computer Use needs reusable application and window objects in Standard and other presets without changing their ordinary tool calls or requiring users to change the profile's PTC runtime. Experimental CUA packages cannot appear in shipped preset definitions. Program dispatch must retain the same permission checks, cancellation, nested logs, and screenshots as PTC.
|
||||
|
||||
## Decision
|
||||
|
||||
CUA keeps `agentPreset: ptc` as the default selector for its raw `cua` tool. Every other composed preset receives `cua_run_code`; Agents without a composed preset receive neither tool. `agentPreset: false` retains global raw-tool registration. A base owner uses Agent scopes for registration and disposal, so enabling and disabling the provider affects existing and later Agents without editing presets. Raw registration depends only on base CUA services and preset selection. The private program producer publishes and withdraws its definition by identity; private dependency loss or startup failure leaves raw tools and prompts available.
|
||||
|
||||
`cua_run_code` composes the shared [program-tool factory](../../../../packages/core/tool-executor-ptc/README.md) with one isolated Node `persistent-in-memory` runtime owned by the CUA provider. Agent `stateOwner` identities select separate retained processes. Its only binding is the private `tools.cua` definition; the model calls ordinary session tools directly. Nested CUA operations retain tool policy, guards, dispatch events, and image admission. The provider releases held keys when either program tool settles. Provider unload drains its own CUA programs before native teardown; releasing input held by other PTC programs does not wait for their unrelated work. State is in memory, separate from the profile's PTC state, and released with its Agent or provider.
|
||||
|
||||
CUA registers a source program through `registerEnvironmentInitializer` before its isolated runtime admits a run. Each new environment evaluates it once after installing current bindings, including temporary escalated environments. The child awaits Host acceptance before starting model code. Initialization shares the first run's time and output budgets; failure discards the environment and prevents model execution without rolling back external effects. Separate evaluation preserves model source locations. An initializer-owning scope depends only on the runtime, so program-tool dependency reloads retain the registration. PTC keeps its explicit bridge initialization.
|
||||
|
||||
This partially supersedes the exclusion of a CUA program entry in [native CUA objects](2026-09-17-experimental-cua-object-api.md). That note still owns the object API's independence from an evaluator and the split between shared objects and native operations. The shared Node provider owns evaluation; CUA supplies its restricted bindings and initialization. The [optional bundle decision](2026-09-21-experimental-capabilities-as-optional-bundles.md) still owns delivery and activation.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A CUA-specific evaluator** duplicates execution lifecycle policy. Reusing the PTC factory and runtime keeps cancellation, limits, sandboxing, and result handling with their existing owners.
|
||||
|
||||
**The profile's shared runtime** couples CUA state to unrelated PTC and workflow settings. Its default per-call mode cannot retain objects. A separate CUA runtime preserves the profile's chosen execution mode.
|
||||
|
||||
**Global registration of both tool forms** exposes a program runner inside PTC programs and exposes raw CUA calls to other presets. Selecting one form per Agent keeps each mode's intended tool list. Binding every session tool inside `cua_run_code` would duplicate ordinary direct calls and their declarations.
|
||||
|
||||
**Prepending initialization to model code** shifts source locations. Running initialization as a separate tool call fails for temporary escalated environments because the next call starts another process. A separate program within the first runtime execution supports both retained and temporary environments. Passing initialization with every program couples environment setup to tool requests and repeats work in existing environments; registration keeps setup and cleanup with the runtime owner.
|
||||
|
||||
## Consequences
|
||||
|
||||
CUA adds no preset list or shipped preset dependency. Preset IDs select the tool form; custom PTC presets must match `agentPreset`. PTC and CUA share the public factory; CUA owns a runtime initializer registration and drains its program tools before unregistering it. Older custom Node bootstraps require the matching protocol revision, as described in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md).
|
||||
|
||||
The private binding limits callable Harness tools, not Node APIs. File and process access still follow the selected sandbox policy. Retained variables do not reserve applications or survive process loss; callers recreate objects and observe state before continuing. Composition and recorded-session tests cover tool selection, automatic initialization, retained state, nested output, and removal; native fixtures remain responsible for platform input behavior.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: PTC preset 之外的 CUA 程序
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-cua-program-tool.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Computer Use 需要在标准及其他 preset 中复用应用和窗口对象,同时保留普通工具的调用方式,也不要求用户更改 profile 的 PTC 运行时。实验性 CUA 包不能出现在随产品提供的 preset 定义中。程序派发必须保留与 PTC 相同的权限检查、取消、嵌套日志和截图行为。
|
||||
|
||||
## 决策
|
||||
|
||||
CUA 保留 `agentPreset: ptc`,用默认选择器指定获得原始 `cua` 工具的 preset。其他已组合的 preset 获得 `cua_run_code`;未组合 preset 的 agent(智能体)不获得这两个工具。`agentPreset: false` 保留全局原始工具注册。基础注册的所有者通过 Agent 作用域管理注册和销毁,因此启停提供方会影响已有和后续 Agent,无需修改 preset。原始工具的注册只依赖基础 CUA 服务和 preset 选择。私有程序工具的提供方按定义对象的身份发布和撤回其定义;私有依赖缺失或启动失败时,原始工具和提示词仍然可用。
|
||||
|
||||
`cua_run_code` 将共享[程序工具工厂](../../../../packages/core/tool-executor-ptc/README.zh.md)与 CUA 提供方持有的单个隔离 Node `persistent-in-memory` 运行时组合。Agent 的 `stateOwner` 身份选择各自独立的保留进程。它只绑定私有 `tools.cua` 定义;模型直接调用其他普通会话工具。嵌套 CUA 操作保留工具策略、guard、派发事件和图像接纳。任一程序工具结束时,提供方都会释放该程序仍按住的键。提供方卸载时,先等待自己持有的 CUA 程序结束再清理原生资源;释放其他 PTC 程序持有的输入时,不等待这些程序中的其他工作。状态保存在内存中,独立于 profile 的 PTC 状态,随所属 Agent 或提供方释放。
|
||||
|
||||
CUA 在隔离运行时首次接纳运行前,通过 `registerEnvironmentInitializer` 注册一段源码。每个新环境安装本次绑定后执行该程序一次,包括临时提权环境。子进程等待 Host 确认后才开始执行模型代码。初始化与首次运行共享时间和输出预算;失败会丢弃环境并阻止模型代码执行,但不回滚外部效果。独立求值保留模型源码位置。初始化程序所属的作用域只依赖运行时,因此程序工具的依赖重载时仍保留这项注册。PTC 保留显式 bridge 初始化。
|
||||
|
||||
这部分取代[原生 CUA 对象](2026-09-17-experimental-cua-object-api.zh.md)中不提供 CUA 程序入口的决定。原记录继续负责对象 API 独立于求值器,以及共享对象与原生操作之间的职责划分。共享 Node 提供方负责求值,CUA 提供受限的绑定和初始化。[可选组合包决策](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)继续负责分发和启用方式。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**CUA 专用求值器**会重复实现执行生命周期策略。复用 PTC 工厂和运行时,使取消、限制、沙箱和结果处理继续由现有实现负责。
|
||||
|
||||
**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。其默认逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。
|
||||
|
||||
**全局注册两种工具形态**会在 PTC 程序中暴露另一个程序执行器,并向其他 preset 暴露原始 CUA 调用。按 Agent 选择一种形态,可以保留各模式预期的工具列表。在 `cua_run_code` 内绑定所有会话工具,会重复普通的直接调用及其声明。
|
||||
|
||||
**把初始化拼到模型代码前**会偏移源码位置。通过单独的工具调用执行初始化无法适用于临时提权环境,因为下次调用会启动另一个进程。首次运行时执行中的独立程序同时支持保留环境和临时环境。每次提交程序都传入初始化,会使环境准备依赖工具请求,并在已有环境中重复执行;注册使准备和清理继续由运行时所有者负责。
|
||||
|
||||
## 后果
|
||||
|
||||
CUA 不增加 preset 列表,也不向内置 preset 添加依赖。工具形态按 preset ID 选择;自定义 PTC preset 必须与 `agentPreset` 匹配。PTC 与 CUA 共享公开工厂;CUA 拥有运行时初始化程序的注册,注销前会等待自己的程序工具执行结束。旧版自定义 Node bootstrap 需要匹配协议版本,详见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md)。
|
||||
|
||||
私有绑定限制可调用的 Harness 工具,不限制 Node API。文件与进程访问仍遵循所选沙箱策略。保留变量不会独占应用,也不能跨进程丢失保留;调用方应重建对象并观察状态后再继续。组合测试和已记录会话测试覆盖工具选择、自动初始化、状态保留、嵌套输出及移除;平台输入行为仍由原生 fixture(测试前置数据)负责验证。
|
||||
@@ -1,4 +1,4 @@
|
||||
/** CUA follows PTC Agent scopes and changes the default only from its detail page. */
|
||||
/** CUA selects each Agent's tool form and changes the default only from its detail page. */
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -110,7 +110,7 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
expect(profileManifest().dependencies).toEqual(dependencies)
|
||||
expect(await card.getByText('实验性', { exact: true }).count()).toBe(1)
|
||||
expect(await card.textContent()).not.toContain('将 PTC 模式改为可持久化')
|
||||
expect(await card.textContent()).toContain('请切换到 PTC 模式')
|
||||
expect(await card.textContent()).not.toContain('请切换到 PTC 模式')
|
||||
expect(await card.textContent()).toContain('Windows 支持正在开发中')
|
||||
expect(await card.textContent()).not.toContain('Swift')
|
||||
const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => {
|
||||
@@ -126,11 +126,14 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true)
|
||||
expect(scaffold.ctx.agentPresets.composedPreset(originalAgent.ctx)).toBe(initialDefault)
|
||||
expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(false)
|
||||
expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua_run_code')).toBe(true)
|
||||
expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua_run_code')).toBe(false)
|
||||
expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(true)
|
||||
expect((await scaffold.ctx.systemPrompt.assemble({ scope: ptcAgent })).tools.map(tool => tool.name)).toEqual(['run_code'])
|
||||
for (const preset of ['ptc', 'standard', 'ptc', initialDefault]) {
|
||||
await scaffold.ctx.agentPresets.select(originalAgent, preset)
|
||||
expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(preset === 'ptc')
|
||||
expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua_run_code')).toBe(preset !== 'ptc')
|
||||
}
|
||||
const child = await scaffold.ctx.agents.create({
|
||||
sessionId: SessionId('cua-child'),
|
||||
@@ -163,6 +166,7 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
})).agent
|
||||
expect(scaffold.ctx.agentPresets.composedPreset(freshDefault.ctx)).toBe(initialDefault)
|
||||
expect(scaffold.ctx.tools.schemas(freshDefault).some(tool => tool.name === 'cua')).toBe(false)
|
||||
expect(scaffold.ctx.tools.schemas(freshDefault).some(tool => tool.name === 'cua_run_code')).toBe(true)
|
||||
const fresh = (await scaffold.ctx.agents.create({
|
||||
sessionId: SessionId('cua-new-ptc'),
|
||||
setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') },
|
||||
@@ -172,6 +176,27 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
await card.getByRole('button', { name: '查看 Computer Use', exact: true }).click()
|
||||
toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true })
|
||||
const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true })
|
||||
if (!codingTools) {
|
||||
const panel = page.locator('[data-cua-settings]')
|
||||
await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false')
|
||||
expect(await panel.textContent()).toContain('标准、创造和 PTC 模式均可使用 Computer Use')
|
||||
expect(await persistent.textContent()).toContain('其他模式始终单独保留 Computer Use 状态')
|
||||
for (const width of [1680, 390]) {
|
||||
await page.setViewportSize({ width, height: 1000 })
|
||||
for (const colorScheme of ['light', 'dark'] as const) {
|
||||
await page.emulateMedia({ colorScheme })
|
||||
await expect.poll(() => page.evaluate(() => document.body.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark')
|
||||
await expect.poll(() => panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
|
||||
if (webSnapshotMode() === 'refresh') {
|
||||
const directory = fileURLToPath(new URL('../../../.playwright-mcp/cua-run-code-ui', import.meta.url))
|
||||
await mkdir(directory, { recursive: true })
|
||||
await panel.screenshot({ path: join(directory, `details-zh-${width}-${colorScheme}.png`), animations: 'disabled' })
|
||||
}
|
||||
}
|
||||
}
|
||||
await page.emulateMedia({ colorScheme: null })
|
||||
await page.setViewportSize({ width: 1680, height: 1000 })
|
||||
}
|
||||
const beforePersistent = scaffold.ctx.ptcRuntime
|
||||
await persistent.getByRole('button', { name: '设为持久化', exact: true }).click()
|
||||
await persistent.getByRole('button', { name: '已设为持久化', exact: true }).waitFor()
|
||||
@@ -192,6 +217,9 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
expect(runtimeFiber() === persistentRuntimeFiber).toBe(true)
|
||||
expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault)
|
||||
expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true)
|
||||
for (const agent of [originalAgent, freshDefault, ptcAgent, fresh]) {
|
||||
expect(scaffold.ctx.tools.schemas(agent).some(tool => tool.name === 'cua_run_code')).toBe(false)
|
||||
}
|
||||
for (const agent of [ptcAgent, fresh]) {
|
||||
expect(scaffold.ctx.tools.schemas(agent).some(tool => tool.name === 'cua')).toBe(false)
|
||||
expect((await scaffold.ctx.systemPrompt.assemble({ scope: agent })).tools.map(tool => tool.name)).toEqual(['run_code'])
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/** Standard-mode CUA programs retain code cards, nested calls, images, and source inspection. */
|
||||
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 { chromium, type Browser } from 'playwright'
|
||||
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-tools'
|
||||
import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types'
|
||||
import {
|
||||
assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
|
||||
launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
|
||||
const fixture = fileURLToPath(new URL('../../../snapshots/session/cua-run-code/session.v4.jsonl', import.meta.url))
|
||||
const snapshotDirectory = fileURLToPath(new URL('../../../snapshots/web/cua-run-code', import.meta.url))
|
||||
const mode = webSnapshotMode()
|
||||
|
||||
it.skipIf(mode === 'record')('shows standard CUA programs and their recorded source through the Web composition', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'cua-run-code-web-'))
|
||||
const resources: { scaffold?: WebScaffold; browser?: Browser } = {}
|
||||
onTestFinished(async () => {
|
||||
try { await resources.browser?.close() } finally {
|
||||
try { await resources.scaffold?.close() } finally { await rm(directory, { recursive: true, force: true }) }
|
||||
}
|
||||
})
|
||||
const patch = join(directory, 'cua-fixture.yml')
|
||||
await writeFile(patch, JSON.stringify([{ id: 'agent-default-model', config: {
|
||||
provider: 'deepseek-official', model: 'deepseek-v4-flash-vision-exp',
|
||||
} }, { insert: [
|
||||
{ id: 'computer-use', name: '@deepseek-ai/dsh-computer-use' },
|
||||
{ id: 'cua-run-code-fixture', name: fileURLToPath(new URL('../../../snapshots/session/cua-run-code/provider.mjs', import.meta.url)),
|
||||
config: { allowedApps: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }] } },
|
||||
] }]))
|
||||
const scaffold = resources.scaffold = await launchWebScaffold({
|
||||
replayFixture: fixture, compareReplaySession: false, extraOverlayPath: patch,
|
||||
})
|
||||
const events: SessionEvent[] = []
|
||||
scaffold.ctx.on('session/event', (_session, event) => { events.push(event) })
|
||||
const browser = resources.browser = await chromium.launch()
|
||||
const page = await newEnglishPage(browser), tripwire = watchConsole(page)
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-cua-run-code'))
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
const agent = scaffold.ctx.agents.list()[0]!
|
||||
expect(scaffold.ctx.agentPresets.composedPreset(agent.ctx)).toBe('standard')
|
||||
expect(scaffold.ctx.tools.schemas(agent).map(tool => tool.name)).toContain('cua_run_code')
|
||||
expect(scaffold.ctx.tools.schemas(agent).map(tool => tool.name)).not.toContain('cua')
|
||||
const prompts = fixtureUserPrompts(await readFile(await selectedSessionFixture(fixture), 'utf8'))
|
||||
expect(prompts).toHaveLength(1)
|
||||
const prompt = prompts.at(0)
|
||||
if (prompt === undefined) throw new Error('The CUA recording must contain a user prompt')
|
||||
const settled = scaffold.whenTurnSettled()
|
||||
const input = page.locator('[data-composer-input]').first()
|
||||
await input.fill(prompt)
|
||||
await input.press('Enter')
|
||||
await settled
|
||||
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)
|
||||
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"]')
|
||||
await turnControl.waitFor({ state: 'visible' })
|
||||
await expect.poll(() => turnControl.getAttribute('aria-expanded')).toBe('false')
|
||||
await turnControl.click()
|
||||
await expect.poll(() => turnControl.getAttribute('aria-expanded')).toBe('true')
|
||||
const group = calls.first().locator('xpath=ancestor::*[@data-chat-group-key][1]')
|
||||
const groupControl = group.locator('[data-process-activity]').first()
|
||||
await groupControl.waitFor({ state: 'visible' })
|
||||
if (await groupControl.getAttribute('aria-expanded') === 'false') await groupControl.click()
|
||||
await expect.poll(() => groupControl.getAttribute('aria-expanded')).toBe('true')
|
||||
await expect.poll(() => calls.count()).toBe(2)
|
||||
await calls.first().getByRole('button', { name: `Code ${description}`, exact: true }).click()
|
||||
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(events.filter(event => event.type === 'tool/ptc-dispatch' && event.data.content.some(block => block.type === 'image'))).toHaveLength(1)
|
||||
expect(events.filter(event => event.type === 'user/message' && event.data.source.kind === 'ptc-mode'
|
||||
&& event.data.content.some(block => block.type === 'image'))).toHaveLength(1)
|
||||
await compareOrRefreshGolden(join(snapshotDirectory, 'ui.expected.md'),
|
||||
await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), mode)
|
||||
if (mode === 'refresh') {
|
||||
const evidence = fileURLToPath(new URL('../../../.playwright-mcp/cua-run-code-ui', import.meta.url))
|
||||
await mkdir(evidence, { recursive: true })
|
||||
await page.screenshot({ path: join(evidence, 'standard-code-cards.png'), animations: 'disabled' })
|
||||
}
|
||||
await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
|
||||
const row = page.getByRole('row', { name: new RegExp(`cua_run_code ${description}`) })
|
||||
await row.click()
|
||||
await page.getByRole('tab', { name: 'Code', exact: true }).click()
|
||||
expect(await page.getByRole('tabpanel').textContent()).toContain('var app = await cua.getApp("test.fixture")')
|
||||
await page.getByRole('button', { name: 'Wrap lines', exact: true }).click()
|
||||
await compareOrRefreshGolden(join(snapshotDirectory, 'code.expected.md'),
|
||||
await captureStableAria(page, '[role="tabpanel"]', scaffold.workspaceCwd), mode)
|
||||
if (mode === 'refresh') {
|
||||
await page.screenshot({ path: fileURLToPath(new URL('../../../.playwright-mcp/cua-run-code-ui/source-inspector.png', import.meta.url)), animations: 'disabled' })
|
||||
}
|
||||
const screenshot = page.locator('tr[data-kind="subtool"]').filter({ hasText: '"method":"screenshot"' })
|
||||
await screenshot.click()
|
||||
await page.getByRole('tab', { name: 'Result', exact: true }).click()
|
||||
const image = page.getByRole('tabpanel').locator('img').first()
|
||||
await image.waitFor({ state: 'visible' })
|
||||
await expect.poll(() => image.evaluate((element: HTMLImageElement) => element.naturalWidth)).toBe(1)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
await assertFixtureInventory(snapshotDirectory, ['ui.expected.md', 'code.expected.md'])
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
- group "新会话默认模式":
|
||||
- strong: 新会话默认模式
|
||||
- paragraph: Computer Use 仅在 PTC 模式中可用。
|
||||
- paragraph: 标准、创造和 PTC 模式均可使用 Computer Use。在此选择 PTC,可将其设为新会话的默认模式
|
||||
- button "设为 PTC"
|
||||
@@ -2,11 +2,11 @@
|
||||
- heading "Authorize computer use" [level=3]
|
||||
- group "Default mode for new sessions":
|
||||
- strong: Default mode for new sessions
|
||||
- paragraph: Computer use is available only in PTC mode.
|
||||
- paragraph: Computer use is available in Standard, Creator, and PTC modes. Choose PTC here to make it the default for new sessions.
|
||||
- button "Set to PTC"
|
||||
- group "PTC execution mode":
|
||||
- strong: PTC execution mode
|
||||
- paragraph: Keep variables and application objects across tool calls. Switching restarts the PTC runtime.
|
||||
- paragraph: Keep variables and application objects across PTC tool calls. Switching restarts the PTC runtime. Other modes always keep their computer use state separately.
|
||||
- button "Use persistent mode"
|
||||
- group "Accessibility":
|
||||
- strong: Accessibility
|
||||
|
||||
@@ -108,6 +108,7 @@
|
||||
"tests/cua-optin.e2e.ts",
|
||||
"tests/bundle-platform.e2e.ts",
|
||||
"tests/cua-permissions.e2e.ts",
|
||||
"tests/cua-run-code.e2e.ts",
|
||||
"tests/schedule-header.e2e.ts",
|
||||
"tests/schedule-phone.e2e.ts",
|
||||
"tests/schedule-pickers.e2e.ts",
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
en: bf79c6acf35c90a5
|
||||
zh: 9f2ce6c7f6493b17
|
||||
/package-surface-rules/package-json-exports-uses-the-standard-key-set:
|
||||
en: 692ded0ff903609d
|
||||
zh: c871ab58ca92ad70
|
||||
en: 37d7728d42231610
|
||||
zh: ba27dd3935f50572
|
||||
/package-surface-rules/dependency-declarations-and-version-consistency-are-enforced-by-the-dependency-scan:
|
||||
en: e68bfcde70f845b4
|
||||
zh: 73e5c4fb067c4fa1
|
||||
|
||||
@@ -79,6 +79,7 @@ A `package.json` `exports` map uses only the standard key set, in which every ke
|
||||
- Standard keys, each with one meaning repo-wide, across `packages/*/*/package.json` and `apps/*/package.json`: `.` (the package entry), `./package.json` (toolchain access, not a semantic export), `./src/*` (source passthrough for tests and tools, whose documented status is still open), `./client` (the browser entry, paired with the `dsh.client` declaration), `./types` (the type entry), `./typert` (the typert type runtime), `./remote` (the `@Remote` call surface), `./locale/*.json` (locale resources), `./cordis.patch.yml` (the bundle patch layer declared by `dsh.bundle`). Counts are not listed here because they rot on the next package; the recompute command below prints them.
|
||||
- Keys outside that set (`./brand` in 5 packages, `./worker` in 4, `./startup`, `./runner`, and `./protocol` in 2 each, plus many one-off keys) have no documented meaning; they are pending review, not a pattern to copy.
|
||||
- `dsh-tools` additionally exposes `./pipeline` for reusable invocation stages and batch scheduling. Its main and pipeline bundles share runtime chunks to preserve error-class identity; workspace constraints check the export targets and publication files.
|
||||
- `dsh-tool-executor-ptc` exposes `./run-code` for the shared program-tool factory, explicit runtime and call limits, and private callable tool definitions. Workspace constraints check its export targets and publication files.
|
||||
- Judged condition: does a change add an export key outside the standard set?
|
||||
- Exception: none by default; a new key changes the owning document and the check first, with the domain owner's confirmation.
|
||||
- Recompute the distribution:
|
||||
|
||||
@@ -79,6 +79,7 @@ import { isSurfaceEligibleType } from '../../core/session/src/surface.ts'
|
||||
- 标准键,每个键在全仓只有一个含义,统计口径是 `packages/*/*/package.json` 与 `apps/*/package.json`:`.`(包主入口)、`./package.json`(工具链访问,不是语义导出)、`./src/*`(测试与工具的源码透传,文档状态仍待定)、`./client`(浏览器入口,与 `dsh.client` 声明配对)、`./types`(类型入口)、`./typert`(typert 类型运行时)、`./remote`(`@Remote` 调用面)、`./locale/*.json`(本地化资源)、`./cordis.patch.yml`(`dsh.bundle` 声明的 bundle 补丁层)。这里不列各键的包数,因为下一个包就会让它过期;下面的复算命令会打印当前数字。
|
||||
- 集合之外的键(`./brand` 5 个包、`./worker` 4 个、`./startup`、`./runner`、`./protocol` 各 2 个,另有大量一次性键)没有文档含义,属待核项,不是可照抄的先例。
|
||||
- `dsh-tools` 另行提供 `./pipeline`,用于复用调用阶段与批量调度。主入口与 pipeline bundle 共享运行时 chunk,以保持错误类的身份一致;工作区检查验证导出目标与发布文件。
|
||||
- `dsh-tool-executor-ptc` 提供 `./run-code`,用于共享程序工具工厂、显式指定运行时及调用上限,并传入私有可调用工具定义。工作区检查验证其导出目标与发布文件。
|
||||
- 判定条件:改动是否新增了标准集合以外的 export 键?
|
||||
- 例外:无默认例外;新增键须先改正家文档与检查,并取得对应领域专家确认。
|
||||
- 复算分布:
|
||||
|
||||
@@ -958,10 +958,6 @@ flowchart TD
|
||||
pkg_creation_recommendations --> pkg_session
|
||||
pkg_creation_recommendations --> pkg_skill
|
||||
pkg_creation_recommendations --> pkg_tools
|
||||
pkg_cua --> pkg_attachment
|
||||
pkg_cua --> pkg_ptc_runtime_node
|
||||
pkg_cua --> pkg_scope
|
||||
pkg_cua --> pkg_user_questions
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt
|
||||
@@ -1129,6 +1125,11 @@ flowchart TD
|
||||
pkg_api_settings_controller --> pkg_settings
|
||||
pkg_api_settings_controller --> pkg_typert_protocol
|
||||
pkg_web_app --> pkg_shell_env
|
||||
pkg_cua --> pkg_attachment
|
||||
pkg_cua --> pkg_ptc_runtime_node
|
||||
pkg_cua --> pkg_scope
|
||||
pkg_cua --> pkg_tool_executor_ptc
|
||||
pkg_cua --> pkg_user_questions
|
||||
pkg_experimental_auto_review --> pkg_agent
|
||||
pkg_experimental_auto_review --> pkg_agent_instructions
|
||||
pkg_experimental_auto_review --> pkg_llm
|
||||
@@ -1831,7 +1832,6 @@ flowchart TD
|
||||
| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) |
|
||||
| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) |
|
||||
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
|
||||
@@ -1865,6 +1865,7 @@ flowchart TD
|
||||
| [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`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), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`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), [`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) |
|
||||
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
|
||||
|
||||
@@ -960,10 +960,6 @@ flowchart TD
|
||||
pkg_creation_recommendations --> pkg_session
|
||||
pkg_creation_recommendations --> pkg_skill
|
||||
pkg_creation_recommendations --> pkg_tools
|
||||
pkg_cua --> pkg_attachment
|
||||
pkg_cua --> pkg_ptc_runtime_node
|
||||
pkg_cua --> pkg_scope
|
||||
pkg_cua --> pkg_user_questions
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt
|
||||
@@ -1131,6 +1127,11 @@ flowchart TD
|
||||
pkg_api_settings_controller --> pkg_settings
|
||||
pkg_api_settings_controller --> pkg_typert_protocol
|
||||
pkg_web_app --> pkg_shell_env
|
||||
pkg_cua --> pkg_attachment
|
||||
pkg_cua --> pkg_ptc_runtime_node
|
||||
pkg_cua --> pkg_scope
|
||||
pkg_cua --> pkg_tool_executor_ptc
|
||||
pkg_cua --> pkg_user_questions
|
||||
pkg_experimental_auto_review --> pkg_agent
|
||||
pkg_experimental_auto_review --> pkg_agent_instructions
|
||||
pkg_experimental_auto_review --> pkg_llm
|
||||
@@ -1833,7 +1834,6 @@ flowchart TD
|
||||
| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) |
|
||||
| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) |
|
||||
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
|
||||
@@ -1867,6 +1867,7 @@ flowchart TD
|
||||
| [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`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), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`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), [`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) |
|
||||
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
|
||||
|
||||
@@ -237,6 +237,21 @@ Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and subst
|
||||
*/
|
||||
release(owner: object): Promise<void>
|
||||
|
||||
/**
|
||||
* Register source evaluated once when each execution environment is created.
|
||||
* Registration must precede the first run admission; only one initializer may
|
||||
* be registered. Current bindings are installed before initialization. Its
|
||||
* completion is discarded; logs, timeout, cancellation and output bounds share
|
||||
* the first run. Initialization failure discards the environment without
|
||||
* executing the user program or rolling back external effects.
|
||||
* @param program - Initialization source in the provider's language and format.
|
||||
* @returns An idempotent async disposer that stops admission, cancels and drains
|
||||
* admitted runs, and releases environments. Failed cleanup blocks execution
|
||||
* until the disposer succeeds on retry. The caller owns this disposer.
|
||||
* @throws When unsupported, registered twice, registered after admission, or invalid.
|
||||
*/
|
||||
registerEnvironmentInitializer(program: string): () => Promise<void>
|
||||
|
||||
/**
|
||||
* Resolve supported options and provider defaults before execution.
|
||||
* @param request - Program, bindings, cancellation and optional execution choices.
|
||||
|
||||
@@ -237,6 +237,21 @@ Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and subst
|
||||
*/
|
||||
release(owner: object): Promise<void>
|
||||
|
||||
/**
|
||||
* Register source evaluated once when each execution environment is created.
|
||||
* Registration must precede the first run admission; only one initializer may
|
||||
* be registered. Current bindings are installed before initialization. Its
|
||||
* completion is discarded; logs, timeout, cancellation and output bounds share
|
||||
* the first run. Initialization failure discards the environment without
|
||||
* executing the user program or rolling back external effects.
|
||||
* @param program - Initialization source in the provider's language and format.
|
||||
* @returns An idempotent async disposer that stops admission, cancels and drains
|
||||
* admitted runs, and releases environments. Failed cleanup blocks execution
|
||||
* until the disposer succeeds on retry. The caller owns this disposer.
|
||||
* @throws When unsupported, registered twice, registered after admission, or invalid.
|
||||
*/
|
||||
registerEnvironmentInitializer(program: string): () => Promise<void>
|
||||
|
||||
/**
|
||||
* Resolve supported options and provider defaults before execution.
|
||||
* @param request - Program, bindings, cancellation and optional execution choices.
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 207c515390c5e529
|
||||
zh: bd4d90881efb011d
|
||||
/native-cua-application-and-window-api/change:
|
||||
en: e5d1027faa55adba
|
||||
zh: 4b88ad6a70977fb3
|
||||
en: d3b7e02c362b0049
|
||||
zh: 49f1a190495e813d
|
||||
/native-cua-application-and-window-api/migration:
|
||||
en: 071b67613c512b84
|
||||
zh: 7ee32d8dbcf7a0f2
|
||||
en: 90d4d985da7e6618
|
||||
zh: 9d9b4d3444cf0e3b
|
||||
@@ -9,15 +9,15 @@ English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
CUA scripts use an explicit window for screenshots and pointer input. App and Window objects share the latest accessibility snapshot for their application handle. Their identifiers are `appHandle` and `windowId` respectively. Application discovery still reports the PID of a running match.
|
||||
Screenshots and pointer input require explicit windows. App (`appHandle`) and Window (`windowId`) objects share their application handle's latest accessibility snapshot. Discovery reports running matches' PIDs.
|
||||
|
||||
Providers supply startup capabilities alongside their platform guidance. The native helper reports runtime permissions and session lock state. The Host combines both in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `win32` platform tag.
|
||||
Providers supply startup capabilities and implement `getGuidance(kind)` instead of supplying a `guidance` string. `raw` selects instructions for the raw `cua` tool; `standalone` selects instructions for `cua_run_code`. The native helper reports runtime permissions and session lock state; the Host combines these with startup capabilities in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `win32` platform tag.
|
||||
|
||||
## Migration
|
||||
|
||||
1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action.
|
||||
2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Application and window selection does not read AX. Before using element IDs, call `getAccessibilityTree()` explicitly; use `{ emit: false }` to retain the snapshot without displaying it. A screenshot does not require a successful AX read. Before coordinate input, including relative coordinates, obtain a successful AX observation covering the window or a screenshot; absolute coordinates require a screenshot. See [macOS AX read limits](../cua-ax-read-limits/guide.md) for changes to traversal defaults and configuration.
|
||||
3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active.
|
||||
4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying.
|
||||
4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` or `cua_run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying.
|
||||
5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID.
|
||||
6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls.
|
||||
6. Custom providers replace `CuaBackend.description` with `capabilities` and `guidance` with `getGuidance(kind)`, and supply `permissionParameters` to `installCua`. Both kinds may return identical text. Rebuild custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart and verify both tool forms' guidance, advertised methods, keyboard scopes, and platform controls on the Computer Use permission page.
|
||||
@@ -9,15 +9,15 @@ description: "迁移 CUA 脚本和自定义原生提供方,使用显式窗口
|
||||
|
||||
## 变更
|
||||
|
||||
CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享同一应用句柄最近读取的辅助功能快照。App 用 `appHandle` 标识,Window 用 `windowId` 标识。查找应用时,运行中的匹配项仍提供 PID。
|
||||
截图和指针输入要求显式选择窗口。App(`appHandle`)和 Window(`windowId`)对象共享所属应用句柄的最新辅助功能快照。应用发现返回运行中匹配项的 PID。
|
||||
|
||||
提供方在安装时声明固定的平台能力并提供操作指引。原生 helper 返回实际的权限和会话锁定状态。Host 合并两者,作为 `getCapabilities()` 的结果。供权限页面使用的响应带有 `darwin` 或 `win32` 平台标记。
|
||||
提供方声明启动能力,并实现 `getGuidance(kind)`,不再传入 `guidance` 字符串。`raw` 选择原始 `cua` 工具的指引,`standalone` 选择 `cua_run_code` 的指引。原生 helper 返回运行时权限和会话锁定状态,Host 将其与启动能力合并到 `getCapabilities()` 中。供权限页面使用的响应带有 `darwin` 或 `win32` 平台标记。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。
|
||||
2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择应用或窗口不读取 AX。使用元素 ID 前须显式调用 `getAccessibilityTree()`;使用 `{ emit: false }` 可保留快照但不显示树。截图不要求 AX 读取成功。所有坐标输入(包括相对坐标)之前都须成功读取覆盖该窗口的 AX 或取得截图;绝对坐标要求截图。[读取上限的迁移说明](../cua-ax-read-limits/guide.zh.md)列出了 macOS 默认值和配置含义的变化。
|
||||
3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。
|
||||
4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。
|
||||
4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 或 `cua_run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。
|
||||
5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。
|
||||
6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。
|
||||
6. 自定义提供方将 `CuaBackend.description` 改为 `capabilities`,将 `guidance` 改为 `getGuidance(kind)`,并向 `installCua` 传入 `permissionParameters`。两种形态可以返回相同文本。按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建自定义 `helperPath` 对应的 helper。重启后验证两种工具形态的指引、声明的方法、键盘输入范围及 Computer Use 权限页的平台控件。
|
||||
@@ -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.1/ptc-bootstrap-protocol/guide.md
|
||||
/:
|
||||
en: 200e3531fb831ad1
|
||||
zh: b529f83a2f83ef6d
|
||||
/node-ptc-bootstrap-protocol-version-3:
|
||||
en: 5c10a48d83f56e19
|
||||
zh: 1c8d8832764d558f
|
||||
/node-ptc-bootstrap-protocol-version-3/change:
|
||||
en: 09a683eb8a4ec57c
|
||||
zh: 7b702b0011ac83b8
|
||||
/node-ptc-bootstrap-protocol-version-3/migration:
|
||||
en: 4c25b296ed471589
|
||||
zh: 46071ce14e092f48
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Update custom Node PTC bootstraps to protocol version 3 before running them with the upgraded Host."
|
||||
---
|
||||
|
||||
# Node PTC bootstrap protocol version 3
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
The Node PTC Host requires bootstrap protocol version 3 instead of version 2. It rejects an older bootstrap before dispatching a program, with `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`. This affects custom `launch.bootstrapPath` deployments in every execution mode. The bootstrap bundled with DSH updates with the Host and needs no configuration change.
|
||||
|
||||
Version 3 carries optional `ProgramBootData.initialization` source for each new environment. The bootstrap evaluates it separately after installing current bindings, then awaits the Host's `initialized()` RPC acceptance and rechecks cancellation before running the model program. Initialization failure discards the environment and prevents model execution. The Node provider supports initializer registration only in `persistent-in-memory` mode.
|
||||
|
||||
## Migration
|
||||
|
||||
1. If your Node PTC configuration sets `launch.bootstrapPath`, deploy the matching version of `@deepseek-ai/dsh-ptc-runtime-node` in its execution environment. Use the package's built `lib/process.js` or REPL-default `lib/persistent-process.js` with its dependencies. Keep the Host and bootstrap versions aligned; changing only the advertised version is insufficient.
|
||||
2. Update `launch.bootstrapPath` to the matching entry and restart the provider. For local deployments that need no custom bootstrap, remove that override to use the installed default. The [Node runtime documentation](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) describes retained execution and remote launch.
|
||||
3. Run a program in each configured execution mode and confirm that it completes without the protocol error. Consumers using `registerEnvironmentInitializer(program)` must also verify that initialization runs once per new environment and that an initialization error prevents the model program's effects.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "自定义 Node PTC bootstrap 必须升级到协议版本 3,才能与新版 Host 一起运行。"
|
||||
---
|
||||
|
||||
# Node PTC bootstrap 协议版本 3
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
Node PTC Host 要求 bootstrap 协议版本从 2 升至 3。它会在派发程序前拒绝旧 bootstrap,并报告 `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`。这影响所有执行模式下自定义 `launch.bootstrapPath` 的部署。DSH 内置 bootstrap 随 Host 更新,无需修改配置。
|
||||
|
||||
版本 3 为每个新环境携带可选的 `ProgramBootData.initialization` 源码。bootstrap 安装本次绑定后独立执行初始化,随后等待 Host 对 `initialized()` RPC 的确认,再次检查取消状态后才执行模型程序。初始化失败会丢弃环境并阻止模型代码执行。Node 提供方仅在 `persistent-in-memory` 模式下支持注册初始化程序。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 如果 Node PTC 配置设置了 `launch.bootstrapPath`,请在其执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node`。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`,并保留其依赖。Host 与 bootstrap 版本必须匹配;只修改声明的版本号并不够。
|
||||
2. 将 `launch.bootstrapPath` 指向匹配的入口并重启提供方。本地部署若不需要自定义 bootstrap,可以移除此覆盖项以使用安装默认值。[Node 运行时文档](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)说明状态保留和远程启动方式。
|
||||
3. 在每种已配置的执行模式中运行一个程序,确认正常完成且没有协议错误。使用 `registerEnvironmentInitializer(program)` 的消费方还须验证:初始化在每个新环境中只执行一次,且初始化出错时模型程序不会产生效果。
|
||||
@@ -54,11 +54,11 @@
|
||||
en: 131811a8a12c9d81
|
||||
zh: f8a8c1e02a5787f8
|
||||
/chat-conversation-node-rules/activity-summaries/tool-name-classification:
|
||||
en: a962c232f916bfff
|
||||
zh: 2e80754623c3f14d
|
||||
en: 28760f1caab0763b
|
||||
zh: 2d0eb175509096e7
|
||||
/chat-conversation-node-rules/activity-summaries/subagents-background-jobs-and-nested-calls:
|
||||
en: e7796e7ba825c3d6
|
||||
zh: c377d9eab0a8869f
|
||||
en: da0c896564c0d78e
|
||||
zh: 6ff7b8a3b2f2de8c
|
||||
/chat-conversation-node-rules/activity-summaries/live-activity-and-detail:
|
||||
en: e0ca09c305690be7
|
||||
zh: fb35d0238b1a827b
|
||||
@@ -269,7 +269,7 @@ Classification uses the recorded tool name exactly: no case folding, namespace s
|
||||
| `write` | `write` |
|
||||
| `edit` | `edit`, `apply_patch` |
|
||||
| `commands` | `bash`, `pwsh`, `exec_command`, `write_stdin`, or prefix `terminal_` |
|
||||
| `code` | `run_code` |
|
||||
| `code` | `run_code`, `cua_run_code` |
|
||||
| `webSearch` | `web_search` |
|
||||
| `webFetch` | `web_fetch` |
|
||||
| `subagents` | `subagent` or prefix `subagent_` |
|
||||
@@ -290,7 +290,7 @@ A subagent tool follows ordinary group boundaries: it does not create a group me
|
||||
| Background subagent startup has returned its tool result, while the child is still running | Keep its category count, but remove that call from running-activity candidates. The child does not keep the parent's group in the subagent activity state. |
|
||||
| Tool calls recorded only in a child Session | Do not include them in the parent group's counts or live detail. Only calls actually attached to a member's `subCalls` participate recursively. |
|
||||
|
||||
A `run_code` root counts once as `code`; its recorded PTC subcalls each count in their own categories. The wrapper is not replaced by leaf-call counts, and children are not all classified as `code`. With distinct call ids, `run_code → [read, bash, subagent_codex]` produces `code=1, read=1, commands=1, subagents=1`, in that tie order. A subcall can supply the live category while the outer `run_code` remains running.
|
||||
A `run_code` or `cua_run_code` root counts once as `code`; its recorded PTC subcalls each count in their own categories. The wrapper is not replaced by leaf-call counts, and children are not all classified as `code`. With distinct call ids, `run_code → [read, bash, subagent_codex]` produces `code=1, read=1, commands=1, subagents=1`, in that tie order. A subcall can supply the live category while the outer `run_code` remains running.
|
||||
|
||||
Exact-name rules also mean that a recorded name such as `functions.read`, `mcp.read`, or `Read` falls into `tools`, while `browser_inspect` falls into `search`. A `terminal_*` name follows the command rule even when its operation only inspects or closes a terminal, unless the earlier `_inspect` rule matches.
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ description: "Chat 过程分组与活动摘要的明细业务规则。"
|
||||
| `write` | `write` |
|
||||
| `edit` | `edit`、`apply_patch` |
|
||||
| `commands` | `bash`、`pwsh`、`exec_command`、`write_stdin`,或以 `terminal_` 开头 |
|
||||
| `code` | `run_code` |
|
||||
| `code` | `run_code`、`cua_run_code` |
|
||||
| `webSearch` | `web_search` |
|
||||
| `webFetch` | `web_fetch` |
|
||||
| `subagents` | `subagent`,或以 `subagent_` 开头 |
|
||||
@@ -290,7 +290,7 @@ Subagent 工具遵循普通分组边界,不会仅因委派任务就单独成
|
||||
| 后台 subagent 的启动调用已返回工具结果,但子代理仍在运行 | 保留类别次数,但该调用不再参与运行中活动选择;子代理的执行不会维持父组的 subagent 活动状态。 |
|
||||
| 工具调用只记录在子 Session 中 | 不纳入父组计数或实时详情;只有实际附在本组成员 `subCalls` 中的调用才递归参与。 |
|
||||
|
||||
`run_code` 根调用自身计一次 `code`,已记录的每个 PTC 子调用另按自己的类别计数。不会用叶子调用替代包装调用,也不会把子调用统一归为 `code`。各调用 id 不同时,`run_code → [read, bash, subagent_codex]` 得到 `code=1, read=1, commands=1, subagents=1`,同次数时按此顺序排列。外层 `run_code` 仍在运行时,组的实时类别可以由子调用决定。
|
||||
`run_code` 或 `cua_run_code` 根调用自身计一次 `code`,已记录的每个 PTC 子调用另按自己的类别计数。不会用叶子调用替代包装调用,也不会把子调用统一归为 `code`。各调用 id 不同时,`run_code → [read, bash, subagent_codex]` 得到 `code=1, read=1, commands=1, subagents=1`,同次数时按此顺序排列。外层 `run_code` 仍在运行时,组的实时类别可以由子调用决定。
|
||||
|
||||
精确名称规则也意味着:记录为 `functions.read`、`mcp.read` 或 `Read` 的名称归 `tools`,`browser_inspect` 归 `search`。`terminal_*` 即使只检查或关闭终端,也按命令规则分类,除非先命中 `_inspect` 规则。
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ function activity(name: string): RunningProcessActivity {
|
||||
if (name === 'write') return 'write'
|
||||
if (name === 'edit' || name === 'apply_patch') return 'edit'
|
||||
if (['bash', 'pwsh', 'exec_command', 'write_stdin'].includes(name) || name.startsWith('terminal_')) return 'commands'
|
||||
if (name === 'run_code') return 'code'
|
||||
if (name === 'run_code' || name === 'cua_run_code') return 'code'
|
||||
if (name === 'web_search') return 'webSearch'
|
||||
if (name === 'web_fetch') return 'webFetch'
|
||||
if (name === 'subagent' || name.startsWith('subagent_')) return 'subagents'
|
||||
|
||||
@@ -211,6 +211,7 @@ describe('Definition-owned Chat process groups', () => {
|
||||
|
||||
it.each([
|
||||
['read', 'read'], ['read_image', 'readImage'], ['write', 'write'], ['edit', 'edit'], ['apply_patch', 'edit'],
|
||||
['run_code', 'code'], ['cua_run_code', 'code'],
|
||||
['todo_write', 'plan'], ['create_goal', 'plan'], ['update_goal', 'plan'], ['get_goal', 'plan'],
|
||||
['list_mcp_resources', 'tools'], ['list_mcp_resource_templates', 'tools'], ['read_mcp_resource', 'tools'],
|
||||
] as const)('%s keeps its activity category through preparation, dispatch, and result', (name, kind) => {
|
||||
|
||||
@@ -62,6 +62,7 @@ const TOOL_VARIANTS: Record<string, ToolRowVariant> = {
|
||||
edit: 'edit',
|
||||
apply_patch: 'edit',
|
||||
run_code: 'code',
|
||||
cua_run_code: 'code',
|
||||
cordis_package_inspect: 'read',
|
||||
cordis_runtime_inspect: 'read',
|
||||
// The three run-control verbs take one package id and produce a receipt, so
|
||||
|
||||
@@ -45,17 +45,17 @@ beforeEach(() => {
|
||||
const PROGRAM = 'const listing = await tools.bash({ command: "ls notes", description: "List notes" })\nreturn listing'
|
||||
const RUN_CODE_ARGS = JSON.stringify({ code: PROGRAM, description: 'List the notes directory' })
|
||||
|
||||
const codeResult = (seq: number, callId: string): ToolResultNode => ({
|
||||
const codeResult = (seq: number, callId: string, name = 'run_code', argsRaw = RUN_CODE_ARGS): ToolResultNode => ({
|
||||
kind: 'tool-result', seq, time: seq * 1_000, callId,
|
||||
name: 'run_code', args: PartialArguments.fromText(RUN_CODE_ARGS),
|
||||
call: { name: 'run_code', argsRaw: RUN_CODE_ARGS },
|
||||
name, args: PartialArguments.fromText(argsRaw),
|
||||
call: { name, argsRaw },
|
||||
callTime: seq * 1_000 - 500,
|
||||
content: [{ type: 'text', text: 'demo.txt' }], isError: false,
|
||||
subCalls: [],
|
||||
})
|
||||
|
||||
const runningCode = (callId: string): StartedToolCall => ({
|
||||
phase: 'start' as const, args: PartialArguments.fromText(RUN_CODE_ARGS), callId, name: 'run_code', argsRaw: RUN_CODE_ARGS, turn: 9, step: 0, time: 9_000,
|
||||
const runningCode = (callId: string, name = 'run_code', argsRaw = RUN_CODE_ARGS): StartedToolCall => ({
|
||||
phase: 'start' as const, args: PartialArguments.fromText(argsRaw), callId, name, argsRaw, turn: 9, step: 0, time: 9_000,
|
||||
subCalls: [],
|
||||
})
|
||||
|
||||
@@ -155,7 +155,24 @@ function mountApp(runtime: SlotTestRuntime) {
|
||||
return runtime.renderRoot()
|
||||
}
|
||||
|
||||
describe('run_code sub-calls through the real chat machinery', () => {
|
||||
describe('program sub-calls through the real chat machinery', () => {
|
||||
it.each([false, true])('renders the CUA program and its nested calls while running=%s', async (running) => {
|
||||
const parent = 'cua-program'
|
||||
const program = "var app = await cua.getApp('Calculator')\nconsole.log(app)"
|
||||
const argsRaw = JSON.stringify({ code: program, description: 'Select Calculator' })
|
||||
const child = subCall(11, parent, 1, 'cua', { method: 'getApp', params: { selector: 'Calculator' } }, 'Calculator')
|
||||
const b = await bench(snapshotWith(
|
||||
running ? [] : [codeResult(10, parent, 'cua_run_code', argsRaw)], [child],
|
||||
running ? [runningCode(parent, 'cua_run_code', argsRaw)] : [],
|
||||
))
|
||||
const view = mountApp(b.runtime)
|
||||
expect(view.getByText('Code')).toBeTruthy()
|
||||
expect(view.getByText('Select Calculator')).toBeTruthy()
|
||||
expect(view.container.querySelector('[data-subcalls] [data-tool="cua"]')).not.toBeNull()
|
||||
fireEvent.click(view.getByText('Select Calculator'))
|
||||
expect(view.container.querySelector('pre.shiki')?.textContent).toBe(program)
|
||||
})
|
||||
|
||||
it('renders the code-variant parent row with the description summary and nested sub-rows', async () => {
|
||||
const parent = 'call-64'
|
||||
const subCalls = [
|
||||
|
||||
@@ -53,6 +53,9 @@ describe('tool-call-model', () => {
|
||||
expect(classifyTool('grep')).toBe('search')
|
||||
expect(classifyTool('write')).toBe('write')
|
||||
expect(classifyTool('edit')).toBe('edit')
|
||||
expect(classifyTool('run_code')).toBe('code')
|
||||
expect(classifyTool('cua_run_code')).toBe('code')
|
||||
expect(classifyTool('cua_run_code_extra')).toBe('others')
|
||||
expect(classifyTool('cordis_runtime_inspect')).toBe('read')
|
||||
// The v3 run-control verbs: `others` is the decided intent, not an
|
||||
// unclassified default (there is no program to show and no file to open).
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 4bd17d05b8385675
|
||||
zh: 5174e27f754f2a03
|
||||
/deepseek-ai-dsh-client-ui-trajectory/use-this-package/inspecting-records:
|
||||
en: 4bf16077921c643c
|
||||
zh: 08ded05f8f0afded
|
||||
en: dc86f133fbc74633
|
||||
zh: 289fa88898ac3e55
|
||||
/deepseek-ai-dsh-client-ui-trajectory/use-this-package/the-timing-overview:
|
||||
en: 0f4ee2189324ac06
|
||||
zh: 12e76fed22c09bc1
|
||||
|
||||
@@ -31,7 +31,7 @@ Open the Trajectory tab in the conversation's view ring to inspect agent activit
|
||||
|
||||
The toolbar folds turns, calls, and subcalls independently. Subcalls fold into a summary beneath their parent tool; click the summary or press Enter or Space to expand it. Search includes folded subcalls, and cross-view inspection expands the requested call. Toolbar controls and search wrap onto additional lines when the pane is narrow.
|
||||
|
||||
Calls are identified by their recorded tool name. For `run_code`, the row shows the program description and the inspector opens numbered, highlighted source. The Code tab provides wrapping, a `{}` toggle for the original JSON arguments, and exact source copying, including trailing newlines. Copying the original arguments retains their recorded JSON whitespace. Each newly opened code view takes the last wrapping choice; changing it leaves other open views as they are. Output preserves the recorded text, using a tree for complete JSON objects or arrays. Highlighting reads the leading `Execute a program in` language declaration and the legacy `code` parameter description from the recorded tool schema. Only TypeScript and Python are supported. Missing or conflicting hints, or an explicit declaration of another language, leave plain source; later examples in the tool description do not affect language selection.
|
||||
Calls are identified by their recorded tool name. For `run_code` and `cua_run_code`, the row shows the program description and the inspector opens numbered, highlighted source. The Code tab provides wrapping, a `{}` toggle for the original JSON arguments, and exact source copying, including trailing newlines. Copying the original arguments retains their recorded JSON whitespace. Each newly opened code view takes the last wrapping choice; changing it leaves other open views as they are. Output preserves the recorded text, using a tree for complete JSON objects or arrays. Highlighting reads the leading `Execute a program in` language declaration and the legacy `code` parameter description from the recorded tool schema. Only TypeScript and Python are supported. Missing or conflicting hints, or an explicit declaration of another language, leave plain source; later examples in the tool description do not affect language selection.
|
||||
|
||||
Selection, timeline navigation, folding, and search cover the React-visible window. Request numbers and cumulative usage cover the complete resident snapshot. Selecting a record opens a local inspector for token usage, duration, Input, Output, Timing, and durable images. Image URLs use the Conversation-owned per-session cache, so Chat and Trajectory share one authorized read per attachment. The Trajectory view declares `conversation.trajectory.images`; ledger children call this Slot through the framework `renderSlot` seat, passing image references, display options, and the authorized loader explicitly. Its official `MessageImages` entry calls the shared `conversation.images.content` Factory. A user record shows both nonzero image and ordinary-file counts beside its text, including attachment-only records. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn.
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ Trajectory 标签页让你以按轮次组织的事件记录表和交互式时间
|
||||
|
||||
工具栏可以分别折叠轮次、调用和子调用。子调用收起后,在父工具下保留一条摘要;点击摘要或按 Enter、空格键即可展开。搜索包含已折叠的子调用,从其他视图检查调用时会自动展开目标调用。 面板较窄时,工具栏按钮与搜索框会自动换行。
|
||||
|
||||
调用按已记录的工具名识别。对于 `run_code`,记录行展示程序说明,检查器显示带行号和语法高亮的源码。“代码”页提供换行、查看原始 JSON 参数的 `{}` 切换按钮,以及保留末尾换行的源码原样复制。复制原始参数时保留记录中 JSON 的空白。每个新打开的代码视图采用上次选择的换行状态;切换时,其他已打开视图保持原状。输出保留记录中的文本,完整 JSON 对象或数组使用树形展示。高亮从已记录的工具 Schema 中读取开头的 `Execute a program in` 语言声明及旧式 `code` 参数说明,仅支持 TypeScript 和 Python。提示缺失或冲突,或明确声明了其他语言时,显示纯文本源码;工具说明后文的示例不影响语言选择。
|
||||
调用按已记录的工具名识别。对于 `run_code` 和 `cua_run_code`,记录行展示程序说明,检查器显示带行号和语法高亮的源码。“代码”页提供换行、查看原始 JSON 参数的 `{}` 切换按钮,以及保留末尾换行的源码原样复制。复制原始参数时保留记录中 JSON 的空白。每个新打开的代码视图采用上次选择的换行状态;切换时,其他已打开视图保持原状。输出保留记录中的文本,完整 JSON 对象或数组使用树形展示。高亮从已记录的工具 Schema 中读取开头的 `Execute a program in` 语言声明及旧式 `code` 参数说明,仅支持 TypeScript 和 Python。提示缺失或冲突,或明确声明了其他语言时,显示纯文本源码;工具说明后文的示例不影响语言选择。
|
||||
|
||||
选择、时间线导航、折叠与搜索只覆盖 React 可见窗口。请求编号与累计用量覆盖完整的驻留快照。选择记录会打开局部检查器,查看 token 用量、耗时、输入、输出、计时与持久保留的图片。图片 URL 使用 Conversation 拥有的逐会话缓存,因此 Chat 与 Trajectory 对每个附件共享一次已授权读取。Trajectory 视图声明 `conversation.trajectory.images`;账本子组件通过框架 `renderSlot` 席位调用该 Slot,显式传入图片引用、显示参数及授权 loader。官方 `MessageImages` 条目调用共享的 `conversation.images.content` Factory。用户记录会在文本旁同时显示非零的图片与普通文件数量,仅含附件的记录也显示这些数量。独立运行的压缩请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ import type { TrajectoryTurnModel } from './layout.ts'
|
||||
import { trajectoryPreviewText } from './trajectory-preview.ts'
|
||||
import type { TrajectoryKey, TrajectoryTranslate } from './locales.ts'
|
||||
import { COMPACTION_INTERRUPTED_ERROR } from './copy-codes.ts'
|
||||
import { codeProgram, PTC_TOOL_NAME, type CodeProgram } from './code-program.ts'
|
||||
import { codeProgram, isProgramTool, type CodeProgram } from './code-program.ts'
|
||||
import css from './TrajectoryTable.module.css'
|
||||
|
||||
const BOTTOM_FOLLOW_THRESHOLD_PX = 2
|
||||
@@ -1030,7 +1030,7 @@ function detailTabs(record: TableRecord): readonly DetailTabItem[] {
|
||||
function recordDisplayText(cell: TrajectoryCellProps, t: TrajectoryTranslate): string {
|
||||
if (isToolCallOnly(cell, t)) return ''
|
||||
const program = codeProgram(cell)
|
||||
if (program !== undefined) return `${PTC_TOOL_NAME} · ${program.description.replace(/\s+/g, ' ')}`
|
||||
if (program !== undefined) return `${cell.toolName} · ${program.description.replace(/\s+/g, ' ')}`
|
||||
if (cell.previewMarkdown !== undefined) {
|
||||
const preview = trajectoryPreviewText(cell.previewMarkdown)
|
||||
if (cell.text === '') return preview
|
||||
@@ -1056,7 +1056,7 @@ function toolCallTextParts(
|
||||
text: string,
|
||||
): ToolCallTextParts | undefined {
|
||||
if (cell.kind !== 'tool' && cell.kind !== 'subtool') return undefined
|
||||
const program = cell.toolName === PTC_TOOL_NAME
|
||||
const program = isProgramTool(cell.toolName)
|
||||
const separator = text.indexOf(' · ')
|
||||
if (separator === -1) return { name: text, program }
|
||||
return {
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
/** Read replayable PTC source and language hints from recorded tool arguments and schemas. */
|
||||
/** Read program source and language hints from recorded tool arguments and schemas. */
|
||||
import type { TrajectoryCellProps } from './trajectory-record.ts'
|
||||
|
||||
/** Recorded name of the programmatic tool-calling entry point. */
|
||||
export const PTC_TOOL_NAME = 'run_code'
|
||||
/**
|
||||
* Identify tools supported by the trajectory code inspector.
|
||||
* @param name - Recorded tool name, absent when the call is outside the loaded window.
|
||||
* @returns Whether this tool executes a program shown by the code inspector.
|
||||
*/
|
||||
export function isProgramTool(name: string | undefined): boolean {
|
||||
return name === 'run_code' || name === 'cua_run_code'
|
||||
}
|
||||
|
||||
/** Validated source and original arguments for one recorded run_code call. */
|
||||
/** Validated source and original arguments for one recorded program call. */
|
||||
export interface CodeProgram {
|
||||
rawInput: string
|
||||
source: string
|
||||
@@ -46,14 +52,14 @@ function recordedLanguage(schemaRaw: string | undefined): CodeProgram['language'
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a PTC program without guessing its language from source or current runtime settings.
|
||||
* Resolve a program without guessing its language from source or current runtime settings.
|
||||
* Unknown explicit languages or conflicting recorded hints leave the source unhighlighted.
|
||||
* @param cell - Recorded tool arguments and the schema visible at call time.
|
||||
* @returns The program, or undefined for another tool or unsupported arguments.
|
||||
*/
|
||||
export function codeProgram(cell: TrajectoryCellProps): CodeProgram | undefined {
|
||||
if (cell.kind !== 'tool' && cell.kind !== 'subtool') return undefined
|
||||
if (cell.toolName !== PTC_TOOL_NAME || cell.inputDetail === undefined) return undefined
|
||||
if (!isProgramTool(cell.toolName) || cell.inputDetail === undefined) return undefined
|
||||
const args = parseRecord(cell.inputDetail)
|
||||
if (typeof args?.code !== 'string') return undefined
|
||||
if (args.description !== undefined && typeof args.description !== 'string') return undefined
|
||||
|
||||
@@ -143,10 +143,10 @@ describe('PTC trajectory inspector', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('shows the description, numbered source, original arguments, and verbatim output', () => {
|
||||
const view = render(<Harness />)
|
||||
it.each(['run_code', 'cua_run_code'])('shows the %s description, numbered source, original arguments, and verbatim output', (toolName) => {
|
||||
const view = render(<Harness cell={{ ...CELL, toolName, text: `${toolName} · ${ARGS}` }} />)
|
||||
const ui = within(view.container)
|
||||
fireEvent.click(ui.getByRole('row', { name: /run_code Read the working directory/ }))
|
||||
fireEvent.click(ui.getByRole('row', { name: new RegExp(`${toolName} Read the working directory`) }))
|
||||
expect(ui.getAllByRole('tab').map(tab => tab.textContent)).toEqual(['Summary', 'Code', 'Result', 'Schema', 'Timing'])
|
||||
expect(ui.getByRole('tabpanel').textContent).toContain('Read the working directory')
|
||||
expect(view.container.querySelector('[data-line-numbers] pre')?.textContent).toBe(SOURCE.trimEnd())
|
||||
|
||||
@@ -9,8 +9,8 @@ const CELL: TrajectoryCellProps = {
|
||||
}
|
||||
|
||||
describe('recorded code programs', () => {
|
||||
it('keeps the program and arguments verbatim', () => {
|
||||
expect(codeProgram(CELL)).toEqual({
|
||||
it.each(['run_code', 'cua_run_code'])('keeps the %s program and arguments verbatim', (toolName) => {
|
||||
expect(codeProgram({ ...CELL, toolName })).toEqual({
|
||||
rawInput: CELL.inputDetail,
|
||||
source: 'return 42\n', description: 'Compute the answer',
|
||||
arguments: { code: 'return 42\n', description: 'Compute the answer' }, language: undefined,
|
||||
@@ -122,6 +122,7 @@ describe('recorded code programs', () => {
|
||||
it('does not specialize other tools or non-tool records', () => {
|
||||
expect(codeProgram({ ...CELL, kind: 'message' })).toBeUndefined()
|
||||
expect(codeProgram({ ...CELL, toolName: 'run_code_extra' })).toBeUndefined()
|
||||
expect(codeProgram({ ...CELL, toolName: 'cua_run_code_extra' })).toBeUndefined()
|
||||
expect(codeProgram({ ...CELL, kind: 'subtool' })?.source).toBe('return 42\n')
|
||||
})
|
||||
})
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
/deepseek-ai-dsh-tool-executor-ptc/use-this-package:
|
||||
en: 2db07bc05f05d202
|
||||
zh: 4efdaab79fcc00af
|
||||
en: 90ceb23f80ce7b26
|
||||
zh: 01ecb606d4e8fb6f
|
||||
/deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation:
|
||||
en: 78708b3779d999a9
|
||||
zh: ad6173f9f01630de
|
||||
@@ -47,6 +47,18 @@
|
||||
/deepseek-ai-dsh-tool-executor-ptc/model-experience/ptc-mode-schema-and-system-prompt/kv-cache-effect:
|
||||
en: 4bf1cd2890cfe6c4
|
||||
zh: 5b230b0adc09ddfb
|
||||
/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools:
|
||||
en: 9253b0d52c38cad9
|
||||
zh: e2d41d32791c46b1
|
||||
/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools/what-the-model-sees:
|
||||
en: 71ee0ac3a10cd438
|
||||
zh: cc8a730e4589510a
|
||||
/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools/token-effect:
|
||||
en: b9f8f6c9ee03641c
|
||||
zh: 64e2a8d7f6f58021
|
||||
/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools/kv-cache-effect:
|
||||
en: f4703836365dc3d4
|
||||
zh: a09ff48a6550fd69
|
||||
/deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work:
|
||||
en: 86d79fbb28aced73
|
||||
zh: aac0ffa1c3ad5e9a
|
||||
|
||||
@@ -42,6 +42,10 @@ This package declares `ctx.ptcRuntime` and `ctx.systemPrompt` as required inject
|
||||
|
||||
Shared dispatch events and the `ptc-mode` message-source declaration live in `@deepseek-ai/dsh-tool-executor-ptc/types`; Client code imports the same declarations through `@deepseek-ai/dsh-tool-executor-ptc/client`. Both entries exclude Host service declarations. Host policy extensions use `import type` from the package entry for `PtcDispatchLog` and `tools/ptc-dispatch-log` without mounting the executor.
|
||||
|
||||
The `/run-code` entry exports `createRunCodeTool` for plugins that register a named program tool alongside native tools. Supply an explicit runtime and the complete private `ToolDefinition` list, then register the returned definition in the owning scope. Programs can call only that list, even when the Agent can call other native tools; the private definitions do not enter the tool registry. Nested calls retain normal approvals, guards, dispatch logs, screenshots, deferred context, and turn completion. `RunCodeConfig` exposes the same validated call-allowance and concurrency settings as this executor.
|
||||
|
||||
The caller owns the supplied runtime and must keep it available until the factory's context finishes disposal. For runtimes that retain state or enforce a sandbox, disposal cancels active Agent programs and waits for nested calls; Agent disposal releases its retained environment. Environment initialization belongs to the supplied [runtime's registration API](../../ptc-runtime/ptc-runtime/README.md#choose-a-backend); register it before exposing the program tool. The factory appends runtime syntax and execution guidance to the caller's description; the caller supplies instructions for the private bindings.
|
||||
|
||||
[Configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tool-executor-ptc)
|
||||
|
||||
-----
|
||||
@@ -126,6 +130,20 @@ Fixed per-request cost proportional to the visible definitions. PTC mode trades
|
||||
|
||||
Prefix-stable while the PTC mode selection, generated SDK, transport schema, and visible tool set are unchanged. Mode or filter changes may invalidate reuse from the first changed prompt or schema token. Changing `maxSubCallsPerMinute` does not change prompt or schema tokens.
|
||||
|
||||
### Registered program tools
|
||||
|
||||
#### What the model sees
|
||||
|
||||
A factory-created tool presents its caller-supplied name and description with the same program parameters, runtime instructions, and result rendering as `run_code`. Its private bindings do not produce direct tool schemas or an SDK prompt section. The consumer owns its binding guidance.
|
||||
|
||||
#### Token effect
|
||||
|
||||
One program tool schema joins the existing native schemas. The caller's binding guidance adds its own prompt cost; intermediate values remain outside model history unless the program emits them or a nested tool defers context.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
The schema remains stable while the caller's description and runtime settings remain unchanged. Initialization runs inside the runtime and does not add program source to model requests.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
@@ -42,6 +42,10 @@ kind: "package-reference"
|
||||
|
||||
共享分派事件与 `ptc-mode` 消息来源声明位于 `@deepseek-ai/dsh-tool-executor-ptc/types`;Client 代码通过 `@deepseek-ai/dsh-tool-executor-ptc/client` 导入同一组声明。两个入口都不引入 Host 服务声明。Host 策略扩展通过包主入口的 `import type` 获取 `PtcDispatchLog` 与 `tools/ptc-dispatch-log`,无需挂载执行器。
|
||||
|
||||
`/run-code` 入口导出 `createRunCodeTool`,供插件在原生工具旁注册具名程序工具。调用方显式传入运行时及完整的私有 `ToolDefinition` 列表,再将返回的定义注册到所属作用域。即使 Agent 能直接调用其他原生工具,程序也只能调用该列表中的工具;私有定义不进入工具注册表。嵌套调用保留正常审批、guard、派发日志、截图、延后上下文和轮次结束行为。`RunCodeConfig` 提供与本执行器相同且经过校验的调用额度与并发设置。
|
||||
|
||||
调用方拥有传入的运行时,必须使其可用至工厂上下文完成销毁。对于保留状态或实施沙箱的运行时,销毁会取消活动的 Agent 程序并等待嵌套调用;Agent 销毁时释放其保留环境。环境初始化由传入[运行时的注册 API](../../ptc-runtime/ptc-runtime/README.zh.md#choose-a-backend)负责;应在提供程序工具前完成注册。工厂将运行时语法和执行说明追加到调用方提供的描述后;私有绑定的说明由调用方提供。
|
||||
|
||||
[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tool-executor-ptc)
|
||||
|
||||
-----
|
||||
@@ -126,6 +130,20 @@ Error: code run failed (abort): run_code exceeded its limit of 2048 tool calls (
|
||||
|
||||
只要 PTC mode 选择、生成的 SDK、传输 schema 与可见工具集合不变,前缀就保持稳定。模式或筛选器变更可能从第一个改变的提示词或 schema token 起使复用失效。修改 `maxSubCallsPerMinute` 不会改变提示词或 schema token。
|
||||
|
||||
### 注册的程序工具
|
||||
|
||||
#### 模型可见内容
|
||||
|
||||
工厂创建的工具显示调用方提供的名称和描述,并使用与 `run_code` 相同的程序参数、运行时说明和结果渲染。私有绑定不生成直接工具 schema 或 SDK 提示词段落。绑定指引由消费方负责。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
现有原生工具 schema 中加入一个程序工具 schema。调用方的绑定指引产生相应提示词成本;中间值只有在程序输出它们或嵌套工具提供延后上下文时才进入模型历史。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
只要调用方描述和运行时设置不变,schema 就保持稳定。初始化在运行时内部执行,不向模型请求添加程序源码。
|
||||
|
||||
## 已知限制与延期工作
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./run-code": {
|
||||
"types": "./lib/types/run-code.d.ts",
|
||||
"default": "./lib/run-code.js"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./lib/types/types.d.ts",
|
||||
"default": "./lib/types/types.js"
|
||||
@@ -34,6 +38,8 @@
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
"lib/index.js",
|
||||
"lib/run-code.js",
|
||||
"lib/_chunks/*.js",
|
||||
"lib/types/**/*.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
@@ -69,6 +75,7 @@
|
||||
"@deepseek-ai/dsh-scope": "workspace:*",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:*",
|
||||
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
|
||||
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
|
||||
"@deepseek-ai/dsh-tools": "workspace:*",
|
||||
|
||||
@@ -8,14 +8,15 @@ import { HarnessError } from '@deepseek-ai/dsh-llm'
|
||||
export class ToolCallLimitExceededError extends Error {
|
||||
/**
|
||||
* Describe the rejected call and how to correct the program.
|
||||
* @param limit - Timeout-derived maximum tool-call attempts for one run_code invocation.
|
||||
* @param limit - Timeout-derived maximum tool-call attempts for one program.
|
||||
* @param callNumber - One-based attempt rejected without invoking the tool.
|
||||
* @param callsPerMinute - Attempts granted per minute of run_code timeout.
|
||||
* @param callsPerMinute - Attempts granted per minute of program timeout.
|
||||
* @param toolName - Program tool name.
|
||||
*/
|
||||
constructor(limit: number, callNumber: number, callsPerMinute: number) {
|
||||
super(`run_code exceeded its limit of ${limit} tool calls (${callsPerMinute} per minute of its timeout); `
|
||||
+ `call ${callNumber} was not dispatched. The run_code program may contain an infinite loop. `
|
||||
+ 'Check loop termination or split the work into smaller run_code calls.')
|
||||
constructor(limit: number, callNumber: number, callsPerMinute: number, toolName: string) {
|
||||
super(`${toolName} exceeded its limit of ${limit} tool calls (${callsPerMinute} per minute of its timeout); `
|
||||
+ `call ${callNumber} was not dispatched. The ${toolName} program may contain an infinite loop. `
|
||||
+ `Check loop termination or split the work into smaller ${toolName} calls.`)
|
||||
this.name = 'ToolCallLimitExceededError'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import { RUN_CODE_NAME, ToolNotFoundError, projectToolSchema } from '@deepseek-ai/dsh-tools'
|
||||
import type { ToolDefinition, ToolExecutor, ToolModelInput, ToolPromptSection, ToolBatchInput, ToolBatchResult } from '@deepseek-ai/dsh-tools'
|
||||
import { ToolExecutionPipeline, executeToolBatch, toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
|
||||
import { createRunCodeTool, requirePtcRuntime, type PtcSdkLanguage } from './ptc.ts'
|
||||
import { createRunCodeTransport, requirePtcRuntime, type PtcSdkLanguage } from './ptc.ts'
|
||||
import { renderToolsSdk, type ToolSdkSchema } from './ts-types.ts'
|
||||
import { renderToolsSdkPy } from './py-types.ts'
|
||||
import { Config } from './config.ts'
|
||||
@@ -87,7 +87,7 @@ export class PtcExecutor implements ToolExecutor {
|
||||
|
||||
/** Keep the reserved transport outside registered capabilities and their restrictions. */
|
||||
private requirePtcTransport(): ToolDefinition {
|
||||
this.ptcTransport ??= createRunCodeTool(this.ctx, this.pipeline, this.config, this.calls)
|
||||
this.ptcTransport ??= createRunCodeTransport(this.ctx, this.pipeline, this.config, this.calls)
|
||||
return this.ptcTransport
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* PTC mode `run_code` transport. Programs call the registry's agent-visible
|
||||
* tools through nested executions scheduled under the native concurrency
|
||||
* contract; each sub-dispatch is logged for reconstruction, while only the
|
||||
* outer curated result enters model history.
|
||||
* Shared program transport. Programs call their admitted tools through nested
|
||||
* executions scheduled under the native concurrency contract; each sub-dispatch
|
||||
* is logged for reconstruction, while only the outer curated result enters model
|
||||
* history.
|
||||
* @module
|
||||
*/
|
||||
|
||||
@@ -19,13 +19,14 @@ import type {} from '@deepseek-ai/dsh-user-approval'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import { deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
|
||||
import { defineTool, parameterSchemaSpecToJsonSchema, RUN_CODE_NAME, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
|
||||
import { defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
|
||||
import type { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
|
||||
import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
|
||||
import { scopeTarget } from '@deepseek-ai/dsh-scope'
|
||||
import type { PtcCalls } from './ptc-calls.ts'
|
||||
import { CodeRunFailedError, ToolCallLimitExceededError } from './errors.ts'
|
||||
import type { Config } from './config.ts'
|
||||
import type { RunCodeToolOptions } from './run-code.ts'
|
||||
import type { ToolDefinition, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools'
|
||||
import type {} from './types.ts'
|
||||
|
||||
@@ -83,6 +84,11 @@ export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
|
||||
if (runtime === undefined) {
|
||||
throw new Error('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
|
||||
}
|
||||
return requireRuntimeLanguage(runtime)
|
||||
}
|
||||
|
||||
/** Resolve the SDK flavor for a mounted or explicitly supplied provider. */
|
||||
function requireRuntimeLanguage(runtime: PtcRuntime): SupportedPtcRuntime {
|
||||
if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language)) {
|
||||
const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ')
|
||||
throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
|
||||
@@ -265,20 +271,24 @@ function resolveSandboxPolicy(ctx: Context, exec: ToolRunContext): SandboxExecut
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the reserved `run_code` transport outside registered capabilities.
|
||||
* Build a program transport using the shared nested-call scheduler.
|
||||
* @param ctx - executor context owning policy listeners and active program cleanup.
|
||||
* @param executor - shared invocation pipeline for nested calls.
|
||||
* @param config - validated timeout-based tool-call allowance and concurrency limits.
|
||||
* @param calls - Executor-owned cancellation and reset coordination.
|
||||
* @param options - Fixed runtime and tools for a registered program tool; omission selects PTC's visible registry and current runtime.
|
||||
* @returns the transport definition with runtime-dependent schema text.
|
||||
*/
|
||||
export function createRunCodeTool(
|
||||
export function createRunCodeTransport(
|
||||
ctx: Context,
|
||||
executor: ToolExecutionPipeline,
|
||||
config: Config,
|
||||
calls: PtcCalls,
|
||||
options?: Omit<RunCodeToolOptions, 'limits'>,
|
||||
): ToolDefinition {
|
||||
const { maxSubCallsPerMinute, maxParallelSubCalls: maxParallel } = config
|
||||
const toolName = options?.name ?? RUN_CODE_NAME
|
||||
const getRuntime = options === undefined ? () => requirePtcRuntime(ctx) : () => requireRuntimeLanguage(options.runtime)
|
||||
// Retain services for log settlement after the executor context becomes inactive.
|
||||
const tools = ctx.tools
|
||||
const logger = ctx.logger
|
||||
@@ -298,7 +308,7 @@ export function createRunCodeTool(
|
||||
|
||||
const stateOwners = new WeakMap<object, WeakSet<PtcRuntime>>()
|
||||
const definition = defineTool({
|
||||
name: RUN_CODE_NAME,
|
||||
name: toolName,
|
||||
// The description and `code` parameter description are placeholders here:
|
||||
// the language-aware getters installed below replace both, resolving the
|
||||
// loaded runtime's flavor at schema-emission time so the schema the MODEL
|
||||
@@ -337,15 +347,15 @@ export function createRunCodeTool(
|
||||
const rendered = value.result === undefined ? '' : renderValue(value.result)
|
||||
const parts = [value.logs.join('\n'), rendered].filter(part => part.length > 0)
|
||||
if (value.sandbox?.enforcement === 'partial') parts.push('File sandbox enforcement is partial on this host.')
|
||||
if (value.sandbox?.denied) parts.push(`The ${value.sandbox.mode} file sandbox denied an operation.${escalationGuidance(ctx.get('ptcRuntime')?.sandboxMode)}`)
|
||||
return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }]
|
||||
if (value.sandbox?.denied) parts.push(`The ${value.sandbox.mode} file sandbox denied an operation.${escalationGuidance(options === undefined ? ctx.get('ptcRuntime')?.sandboxMode : options.runtime.sandboxMode)}`)
|
||||
return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : `(${toolName} completed with no output)` }]
|
||||
},
|
||||
},
|
||||
async execute(args, exec): Promise<RunCodeOutput> {
|
||||
if (args.description.trim().length === 0) {
|
||||
throw new Error('invalid description: expected a non-empty string')
|
||||
}
|
||||
const runtime = requirePtcRuntime(ctx)
|
||||
const runtime = getRuntime()
|
||||
const run = async (callSignal: AbortSignal): Promise<RunCodeOutput> => {
|
||||
validateEscalationArgs(args.sandbox_permissions, args.justification)
|
||||
if (args.timeoutMs !== undefined && runtime.timeout === undefined) {
|
||||
@@ -365,7 +375,7 @@ export function createRunCodeTool(
|
||||
subject: 'program',
|
||||
}, {
|
||||
approver: ctx.get('approval'), agent: exec.agent, callId: exec.callId,
|
||||
toolName: RUN_CODE_NAME, signal: callSignal,
|
||||
toolName, signal: callSignal,
|
||||
})
|
||||
policy = { ...standingPolicy, mode: approvedMode }
|
||||
}
|
||||
@@ -506,12 +516,12 @@ export function createRunCodeTool(
|
||||
const binding = (schema: ToolSchema): PtcBindingFunction => async (rawArgs: unknown): Promise<JsonValue> => {
|
||||
const { name } = schema
|
||||
if (runOver()) {
|
||||
throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`)
|
||||
throw new Error(`${toolName} run is over (${String(runController.signal.reason)}); ${name} not dispatched`)
|
||||
}
|
||||
// Count before validation and queuing so repeated failed calls also exhaust the allowance.
|
||||
const n = ++toolCallAttempts
|
||||
if (n > maxSubCalls) {
|
||||
const error = new ToolCallLimitExceededError(maxSubCalls, n, maxSubCallsPerMinute)
|
||||
const error = new ToolCallLimitExceededError(maxSubCalls, n, maxSubCallsPerMinute, toolName)
|
||||
runController.abort(error)
|
||||
throw error
|
||||
}
|
||||
@@ -581,7 +591,7 @@ export function createRunCodeTool(
|
||||
// declared; fail-closed exclusive when undeclared/invalid.
|
||||
classify: () => executor.executionMode(input).kind,
|
||||
abandon: () => {
|
||||
reject(new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`))
|
||||
reject(new Error(`${toolName} run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`))
|
||||
},
|
||||
async start(): Promise<void> {
|
||||
exec.agent?.session.append('tool/ptc-dispatch-start', {
|
||||
@@ -640,7 +650,7 @@ export function createRunCodeTool(
|
||||
// flight already aborted the dispatch; stop the program now rather
|
||||
// than hand it a result from a run that is over.
|
||||
if (runOver()) {
|
||||
throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`)
|
||||
throw new Error(`${toolName} run is over (${String(runController.signal.reason)}); ${name} result discarded`)
|
||||
}
|
||||
// The worker turns a binding rejection into ToolCallError and adds
|
||||
// only the binding name. Native content and internal error metadata
|
||||
@@ -655,11 +665,11 @@ export function createRunCodeTool(
|
||||
// silently dropping the binding), and the runtime host resolves
|
||||
// binding names as own properties only.
|
||||
const functions: Record<string, PtcBindingFunction> = Object.create(null) as Record<string, PtcBindingFunction>
|
||||
// Enumerate the CALLING AGENT's visible set (scoped tools join,
|
||||
// restricted globals vanish) — the same view the SDK section declared,
|
||||
// so a program can bind exactly what its prompt promised; sub-dispatch
|
||||
// re-resolves per call through the same view (exec.agent threads down).
|
||||
for (const schema of tools.schemas(exec.agent, exec.toolSet)) {
|
||||
// PTC uses step-admitted registry tools; a registered program tool uses
|
||||
// only its private definitions, resolved by its own pipeline on each call.
|
||||
const schemas = options === undefined ? tools.schemas(exec.agent, exec.toolSet)
|
||||
: options.tools.map(definition => projectToolSchema(definition, true))
|
||||
for (const schema of schemas) {
|
||||
Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(deepFreeze(schema)) })
|
||||
}
|
||||
|
||||
@@ -702,7 +712,7 @@ export function createRunCodeTool(
|
||||
// Abort sub-dispatches and drain every in-flight dispatch before
|
||||
// closing the turn (queued-unstarted ones are abandoned unlogged).
|
||||
// Binding failures remain observable through their individual promises.
|
||||
runController.abort('run_code settled')
|
||||
runController.abort(`${toolName} settled`)
|
||||
await drainDispatches()
|
||||
}
|
||||
|
||||
@@ -751,9 +761,9 @@ export function createRunCodeTool(
|
||||
Object.defineProperty(definition, 'description', {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
const runtime = requirePtcRuntime(ctx)
|
||||
const runtime = getRuntime()
|
||||
const instructions = runtime.executionInstructions
|
||||
return resolveFlavor(runtime).description
|
||||
return (options?.description ?? resolveFlavor(runtime).description)
|
||||
+ (instructions ? ` ${instructions}` : '')
|
||||
+ " Each program starts in the Session's current directory. Running programs keep their initial directory."
|
||||
+ escalationGuidance(runtime.sandboxMode)
|
||||
@@ -764,7 +774,7 @@ export function createRunCodeTool(
|
||||
// Recompile through the same spec→schema projection defineTool used, so
|
||||
// the emitted schema always matches the validated specification.
|
||||
get: () => {
|
||||
const runtime = requirePtcRuntime(ctx)
|
||||
const runtime = getRuntime()
|
||||
return parameterSchemaSpecToJsonSchema({
|
||||
code: { type: 'string', required: true, description: resolveFlavor(runtime).codeDescription },
|
||||
description: { type: 'string', required: true, description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION },
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/** Registered program tools with an explicit runtime and private tool bindings. @module */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
||||
import { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
|
||||
import { Config } from './config.ts'
|
||||
import { PtcCalls } from './ptc-calls.ts'
|
||||
import { createRunCodeTransport } from './ptc.ts'
|
||||
|
||||
export { Config as RunCodeConfig } from './config.ts'
|
||||
|
||||
/** Fixed capabilities and presentation for one registered program tool. */
|
||||
export interface RunCodeToolOptions {
|
||||
/** Model-facing tool name, distinct from the reserved `run_code` transport. */
|
||||
readonly name: string
|
||||
/** Capability instructions; runtime syntax, working directory, and escalation guidance are appended. */
|
||||
readonly description: string
|
||||
/** Caller-owned provider; the factory never selects or replaces the scope's shared runtime. */
|
||||
readonly runtime: PtcRuntime
|
||||
/** Complete private binding set, with unique names; definitions need not be registered. */
|
||||
readonly tools: readonly ToolDefinition[]
|
||||
/** Nested-call limits; omitted fields use RunCodeConfig defaults. */
|
||||
readonly limits?: Partial<Config>
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a tool whose programs can call only the supplied private definitions.
|
||||
* Nested calls retain approvals, guards, result policy, dispatch logs, and deferred contexts.
|
||||
* The owning context cancels and drains active Agent programs when disposed if the runtime
|
||||
* retains state or enforces a sandbox. Agent disposal releases retained runtime state.
|
||||
* @param ctx - Context with tools, lifecycle ownership, and policies; Agent calls also require workingDirectory.
|
||||
* @param options - Fixed runtime, tools, presentation, and configurable limits.
|
||||
* @returns An unregistered definition; register it in the owning scope with ctx.tools.register.
|
||||
* @throws Error if private tool names repeat or configured limits are invalid.
|
||||
*/
|
||||
export function createRunCodeTool(ctx: Context, options: RunCodeToolOptions): ToolDefinition {
|
||||
const definitions = new Map<string, ToolDefinition>()
|
||||
for (const definition of options.tools) {
|
||||
if (definitions.has(definition.name)) throw new Error(`Program tool ${options.name} has duplicate binding ${definition.name}`)
|
||||
definitions.set(definition.name, definition)
|
||||
}
|
||||
const pipeline = new ToolExecutionPipeline(ctx, { get: name => definitions.get(name) })
|
||||
return createRunCodeTransport(ctx, pipeline, Config(options.limits ?? {}), new PtcCalls(ctx), {
|
||||
...options,
|
||||
tools: [...definitions.values()],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/** Published program-tool and plugin entries share configuration and error identities. */
|
||||
import { execFile } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { promisify } from 'node:util'
|
||||
import { expect, it } from 'vitest'
|
||||
|
||||
const packageRoot = fileURLToPath(new URL('..', import.meta.url))
|
||||
const factoryBundle = fileURLToPath(new URL('../lib/run-code.js', import.meta.url))
|
||||
const execFileAsync = promisify(execFile)
|
||||
const probe = String.raw`
|
||||
import assert from 'node:assert/strict'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as ptc from '@deepseek-ai/dsh-tool-executor-ptc'
|
||||
import { createRunCodeTool, RunCodeConfig } from '@deepseek-ai/dsh-tool-executor-ptc/run-code'
|
||||
import Tools, { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
|
||||
assert.equal(Object.hasOwn(ptc, 'createRunCodeTool'), false)
|
||||
assert.equal(RunCodeConfig, ptc.Config)
|
||||
const ctx = new Context()
|
||||
try {
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(Tools)
|
||||
const runtime = {
|
||||
language: 'typescript', programFormat: 'repl', retainsState: false,
|
||||
resolve(request) { return { ...request, cwd: process.cwd(), timeoutMs: 60000 } },
|
||||
async run() { return { logs: [], error: { kind: 'exception', message: 'probe failure' } } },
|
||||
}
|
||||
const capability = defineTool({
|
||||
name: 'private_probe', description: 'Probe private binding.', parameters: {},
|
||||
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
||||
async execute() { return 'private result' },
|
||||
})
|
||||
const definition = createRunCodeTool(ctx, {
|
||||
name: 'program_probe', description: 'Run the probe program.', runtime, tools: [capability],
|
||||
})
|
||||
const execution = {
|
||||
name: 'program_probe', callId: 'probe', rootCallId: 'probe', token: Symbol('probe'),
|
||||
signal: new AbortController().signal, deferContext() {}, concludeTurn() {},
|
||||
}
|
||||
await assert.rejects(definition.execute({ code: 'probe', description: 'Check shared error identity' }, execution),
|
||||
error => error instanceof ptc.CodeRunFailedError && error.code === 'CODE_RUN_FAILED')
|
||||
runtime.run = async (spec) => {
|
||||
assert.deepEqual(Object.keys(spec.bindings[0].functions), ['private_probe'])
|
||||
return { logs: [], value: await spec.bindings[0].functions.private_probe({}) }
|
||||
}
|
||||
const result = await definition.execute({ code: 'probe', description: 'Check the private binding' }, execution)
|
||||
assert.deepEqual(result, { logs: [], result: 'private result' })
|
||||
assert.equal(ctx.tools.get('private_probe'), undefined)
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
}
|
||||
console.log('shared program entries verified')
|
||||
`
|
||||
|
||||
it.skipIf(!existsSync(factoryBundle))('loads private program tools through published exports with shared errors', { retry: 0 }, async ({ signal }) => {
|
||||
const { stdout } = await execFileAsync(process.execPath, ['--input-type=module', '-e', probe], { cwd: packageRoot, signal })
|
||||
expect(stdout.trim()).toBe('shared program entries verified')
|
||||
})
|
||||
@@ -0,0 +1,259 @@
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { createUserMessage, ToolCallId, type ContentBlock } from '@deepseek-ai/dsh-llm'
|
||||
import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
|
||||
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import SessionProjections from '@deepseek-ai/dsh-session-projection'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import { NativeToolExecutor } from '@deepseek-ai/dsh-tool-executor-native'
|
||||
import ToolRuntime, { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'
|
||||
import ApprovalService, { type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { createRunCodeTool, RunCodeConfig } from '../src/run-code.ts'
|
||||
|
||||
class ControlledRuntime extends PtcRuntime {
|
||||
readonly language = 'typescript'
|
||||
readonly isolation = 'fixture'
|
||||
override get retainsState() { return true }
|
||||
override get programFormat() { return 'repl' as const }
|
||||
override get executionInstructions() { return 'Top-level await is supported; the last expression is returned.' }
|
||||
override get timeout() { return { defaultMs: 120_000, maxMs: 600_000 } }
|
||||
behavior: (spec: PtcRunSpec) => Promise<PtcRunResult> = async () => ({ logs: [] })
|
||||
|
||||
resolve(request: PtcRunRequest): PtcRunSpec {
|
||||
return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? this.timeout.defaultMs }
|
||||
}
|
||||
|
||||
run(spec: PtcRunSpec): Promise<PtcRunResult> { return this.behavior(spec) }
|
||||
}
|
||||
|
||||
function privateTool(execute = vi.fn(async () => 'private result')) {
|
||||
return defineTool({
|
||||
name: 'cua', description: 'Operate the test computer.', parameters: {},
|
||||
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
||||
execute,
|
||||
})
|
||||
}
|
||||
|
||||
async function setup(definition: ToolDefinition, limits?: Partial<RunCodeConfig>) {
|
||||
const ctx = new Context()
|
||||
const runtimeContext = new Context()
|
||||
const agentContext = new Context()
|
||||
onTestFinished(async () => {
|
||||
await ctx.fiber.dispose()
|
||||
await agentContext.fiber.dispose()
|
||||
await runtimeContext.fiber.dispose()
|
||||
})
|
||||
provideWorkingDirectoryFixture(ctx)
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(ToolRuntime)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjections)
|
||||
ctx.tools.setExecutor(new NativeToolExecutor(ctx))
|
||||
await runtimeContext.plugin(ControlledRuntime)
|
||||
const runtime = runtimeContext.ptcRuntime as ControlledRuntime
|
||||
const session = ctx.sessions.create(SessionId('private-program'))
|
||||
session.append('turn/start', { turn: 1 })
|
||||
const agent = { ctx: agentContext, id: session.id, session } as Agent
|
||||
const fiber = await ctx.plugin(Object.assign((owner: Context) => {
|
||||
owner.tools.register(createRunCodeTool(owner, {
|
||||
name: 'cua_run_code', description: 'Run computer operations through cua.',
|
||||
runtime, tools: [definition],
|
||||
...limits === undefined ? {} : { limits },
|
||||
}))
|
||||
}, { inject: ['tools'] }))
|
||||
const execute = async (args: Record<string, unknown> = {}, name = 'cua_run_code') => {
|
||||
const signal = new AbortController().signal
|
||||
const toolSet = await ctx.tools.resolve({ agent, modelSelection: { provider: 'test', model: 'test' }, signal })
|
||||
try {
|
||||
return await ctx.tools.execute({
|
||||
calls: [{ type: 'tool-call', id: ToolCallId('program'), name, arguments: JSON.stringify({ code: 'await cua.inspect()', description: 'Inspect the current computer', ...args }) }],
|
||||
agent, toolSet, signal,
|
||||
})
|
||||
} finally { toolSet.dispose() }
|
||||
}
|
||||
return { ctx, runtime, agent, agentContext, session, fiber, execute }
|
||||
}
|
||||
|
||||
describe('registered program tool factory', () => {
|
||||
it('uses the explicit runtime and binds only private definitions under native execution', async () => {
|
||||
const body = vi.fn(async () => 'private result')
|
||||
const definition = privateTool(body)
|
||||
const { ctx, runtime, agent, execute } = await setup(definition)
|
||||
const unrelated = vi.fn(async () => 'unrelated')
|
||||
ctx.tools.register({ ...privateTool(unrelated), name: 'other' })
|
||||
expect(ctx.get('ptcRuntime')).toBeUndefined()
|
||||
expect(ctx.tools.get('cua')).toBeUndefined()
|
||||
expect((await execute({}, 'cua')).results[0]?.result).toMatchObject({ isError: true, error: { info: { code: 'UNKNOWN_TOOL' } } })
|
||||
const schema = ctx.tools.schemas().find(tool => tool.name === 'cua_run_code')!
|
||||
expect(schema.description).toContain('Run computer operations through cua.')
|
||||
expect(schema.description).toContain(runtime.executionInstructions)
|
||||
expect(JSON.stringify(schema.parameters)).toContain('Default 120000; capped at 600000')
|
||||
runtime.behavior = async (request) => {
|
||||
expect(request.program).toBe('await cua.inspect()')
|
||||
expect(request.stateOwner).toBe(agent)
|
||||
expect(Object.keys(request.bindings[0]!.functions)).toEqual(['cua'])
|
||||
return { logs: [], value: await request.bindings[0]!.functions.cua!({}) }
|
||||
}
|
||||
expect((await execute()).results[0]?.result).toMatchObject({ isError: false, value: { logs: [], result: 'private result' } })
|
||||
expect(body).toHaveBeenCalledOnce()
|
||||
expect(unrelated).not.toHaveBeenCalled()
|
||||
expect(Object.isFrozen(definition.parameters)).toBe(false)
|
||||
})
|
||||
|
||||
it('preserves approval rejection and guard identity for unregistered nested tools', async () => {
|
||||
const body = vi.fn(async () => 'private result')
|
||||
const { ctx, runtime, session, execute } = await setup(privateTool(body))
|
||||
await ctx.plugin(ApprovalService, { policy: 'ask' })
|
||||
let approval: ApprovalOutcome = 'rejected'
|
||||
let guarded = false
|
||||
ctx.on('approval/request', () => Promise.resolve(approval))
|
||||
ctx.on('tools/pre-execute', (exec, next) => exec.name === 'cua'
|
||||
? Promise.resolve({ kind: 'ask', reason: 'Confirm computer operation' }) : next())
|
||||
ctx.tools.guard(exec => exec.name === 'cua' && guarded
|
||||
? { reason: 'Computer operation blocked', info: { name: 'ComputerGuardError', code: 'COMPUTER_BLOCKED' } } : undefined)
|
||||
runtime.behavior = async (request) => {
|
||||
await expect(request.bindings[0]!.functions.cua!({})).rejects.toThrow()
|
||||
return { logs: [] }
|
||||
}
|
||||
expect((await execute()).results[0]?.result.isError).toBe(false)
|
||||
approval = 'allowed-once'
|
||||
guarded = true
|
||||
expect((await execute()).results[0]?.result.isError).toBe(false)
|
||||
expect(body).not.toHaveBeenCalled()
|
||||
expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch').map(event => event.data.error))
|
||||
.toEqual([{ name: 'ApprovalError', code: 'APPROVAL_REJECTED' }, { name: 'ComputerGuardError', code: 'COMPUTER_BLOCKED' }])
|
||||
})
|
||||
|
||||
it('uses its own name for escalation and omits the retained owner', async () => {
|
||||
const { ctx, runtime, execute } = await setup(privateTool())
|
||||
await ctx.plugin(SandboxPolicy, { mode: 'read-only', workspaceRoot: process.cwd() })
|
||||
await ctx.plugin(ApprovalService, { policy: 'ask' })
|
||||
vi.spyOn(runtime, 'sandboxMode', 'get').mockReturnValue('read-only')
|
||||
const requested: string[] = []
|
||||
ctx.on('approval/request', (request) => {
|
||||
requested.push(request.toolName)
|
||||
return Promise.resolve<ApprovalOutcome>('allowed-once')
|
||||
})
|
||||
runtime.behavior = async (request) => {
|
||||
expect(request.stateOwner).toBeUndefined()
|
||||
expect(request.sandboxPolicy?.mode).toBe('workspace-write')
|
||||
return { logs: [], sandbox: { mode: 'workspace-write', denied: true } }
|
||||
}
|
||||
const result = (await execute({ sandbox_permissions: 'workspace-write', justification: 'Write computer output' })).results[0]!.result
|
||||
expect(result.isError).toBe(false)
|
||||
expect(requested).toEqual(['cua_run_code'])
|
||||
expect(JSON.stringify(result.content)).toContain('Nested tools retain their own policies and approvals')
|
||||
})
|
||||
|
||||
it('records nested results while forwarding screenshots and deferred context after the program', async () => {
|
||||
type Attachment = Extract<ContentBlock, { type: 'image' }>['attachment']
|
||||
const image: ContentBlock = { type: 'image', attachment: {
|
||||
attachmentId: brandString<Attachment['attachmentId']>('sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
|
||||
mediaType: 'image/png', width: 1, height: 1, bytes: 1,
|
||||
} }
|
||||
const definition = defineTool({
|
||||
name: 'cua', description: 'Capture the test computer.', parameters: {},
|
||||
output: {
|
||||
schema: { type: 'string' }, render: () => [image], presentationMeta: () => ({ screen: 1 }),
|
||||
},
|
||||
execute: async (_args, exec) => {
|
||||
exec.deferContext(createUserMessage({ source: { kind: 'ptc-mode' }, content: [{ type: 'text', text: 'capture context' }] }))
|
||||
exec.concludeTurn()
|
||||
return 'raw snapshot'
|
||||
},
|
||||
})
|
||||
const { ctx, runtime, session, execute } = await setup(definition)
|
||||
ctx.on('tools/ptc-dispatch-log', async () => [{ type: 'text', text: 'durable screenshot preview' }])
|
||||
runtime.behavior = async (request) => {
|
||||
expect(await request.bindings[0]!.functions.cua!({})).toBe('raw snapshot')
|
||||
return { logs: ['inspection complete'] }
|
||||
}
|
||||
const batch = await execute()
|
||||
expect(batch.results[0]?.result.content).toEqual([{ type: 'text', text: 'inspection complete' }])
|
||||
expect(batch.concluded).toBe(true)
|
||||
expect(batch.additionalContexts.map(context => context.content)).toEqual([[image], [{ type: 'text', text: 'capture context' }]])
|
||||
const events = session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch')
|
||||
expect(events.map(event => event.type)).toEqual(['tool/ptc-dispatch-start', 'tool/ptc-dispatch'])
|
||||
expect(events[1]?.data).toMatchObject({
|
||||
rootCallId: 'program', parentCallId: 'program', subCallId: 'program:ptc:1', name: 'cua', arguments: {},
|
||||
isError: false, content: [{ type: 'text', text: 'durable screenshot preview' }], meta: { screen: 1 },
|
||||
})
|
||||
})
|
||||
|
||||
it('cancels on owner disposal and awaits nested cleanup before releasing the factory', async () => {
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const aborted = Promise.withResolvers<undefined>()
|
||||
const cleanup = Promise.withResolvers<undefined>()
|
||||
const definition = defineTool({
|
||||
name: 'cua', description: 'Wait for computer cleanup.', parameters: {},
|
||||
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
||||
execute: async (_args, exec) => {
|
||||
exec.signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true })
|
||||
entered.resolve(undefined)
|
||||
await cleanup.promise
|
||||
return 'cleaned'
|
||||
},
|
||||
})
|
||||
const { ctx, runtime, agent, agentContext, session, fiber, execute } = await setup(definition)
|
||||
const release = vi.spyOn(runtime, 'release')
|
||||
runtime.behavior = async (request) => {
|
||||
void request.bindings[0]!.functions.cua!({}).catch(() => undefined)
|
||||
await new Promise<void>((resolve) => {
|
||||
request.signal?.addEventListener('abort', () => { resolve() }, { once: true })
|
||||
})
|
||||
return { logs: [], error: { kind: 'abort', message: 'runtime cancelled' } }
|
||||
}
|
||||
const running = execute()
|
||||
let disposing: Promise<void> | undefined
|
||||
try {
|
||||
await entered.promise
|
||||
let disposed = false
|
||||
disposing = fiber.dispose().then(() => { disposed = true })
|
||||
await aborted.promise
|
||||
expect(disposed).toBe(false)
|
||||
expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(0)
|
||||
cleanup.resolve(undefined)
|
||||
expect((await running).results[0]?.result).toMatchObject({ isError: true, error: { info: { code: 'CODE_RUN_FAILED' } } })
|
||||
await disposing
|
||||
expect(ctx.tools.get('cua_run_code')).toBeUndefined()
|
||||
expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch')).toMatchObject([
|
||||
{ data: { isError: true, error: { name: 'AbortError', code: 'ABORTED' } } },
|
||||
])
|
||||
await agentContext.fiber.dispose()
|
||||
expect(release).toHaveBeenCalledExactlyOnceWith(agent)
|
||||
} finally {
|
||||
cleanup.resolve(undefined)
|
||||
await running
|
||||
await disposing
|
||||
}
|
||||
})
|
||||
|
||||
it('applies configurable call allowances using the registered tool name', async () => {
|
||||
const body = vi.fn(async () => 'private result')
|
||||
const { runtime, session, execute } = await setup(privateTool(body), { maxSubCallsPerMinute: 60, maxParallelSubCalls: 1 })
|
||||
runtime.behavior = async (request) => {
|
||||
await request.bindings[0]!.functions.cua!({})
|
||||
await expect(request.bindings[0]!.functions.cua!({})).rejects.toThrow('cua_run_code exceeded its limit of 1 tool calls')
|
||||
return { logs: [], error: { kind: 'abort', message: 'allowance exhausted' } }
|
||||
}
|
||||
const result = (await execute({ timeoutMs: 1000 })).results[0]!.result
|
||||
expect(result).toMatchObject({ isError: true, error: { info: { code: 'CODE_RUN_FAILED' } } })
|
||||
expect(JSON.stringify(result.content)).toContain('smaller cua_run_code calls')
|
||||
expect(body).toHaveBeenCalledOnce()
|
||||
expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch-start')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects duplicate private bindings and invalid limits before registering effects', async () => {
|
||||
const definition = privateTool()
|
||||
const { ctx, runtime } = await setup(definition)
|
||||
const options = { name: 'duplicate_program', description: 'Duplicate bindings.', runtime, tools: [definition, definition] }
|
||||
expect(() => createRunCodeTool(ctx, options)).toThrow('duplicate binding cua')
|
||||
expect(() => createRunCodeTool(ctx, { ...options, tools: [definition], limits: { maxParallelSubCalls: 0 } })).toThrow()
|
||||
expect(RunCodeConfig({})).toEqual({ maxSubCallsPerMinute: 1024, maxParallelSubCalls: 10 })
|
||||
expect(ctx.tools.get('duplicate_program')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
|
||||
export default defineConfig({
|
||||
entry: { index: 'lib/types/index.js', 'run-code': 'lib/types/run-code.js' },
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
outputOptions: { chunkFileNames: '_chunks/[name]-[hash].js' },
|
||||
})
|
||||
@@ -9,38 +9,38 @@
|
||||
en: 9084fb48d0f6489c
|
||||
zh: ce692972d91cf663
|
||||
/deepseek-ai-dsh-cua-bundle/summary:
|
||||
en: 0d93f44a8ce7404c
|
||||
zh: 6a73ed42d0efc9ea
|
||||
en: b41b219a02db6311
|
||||
zh: f4783578e83b37d4
|
||||
/deepseek-ai-dsh-cua-bundle/table-of-contents:
|
||||
en: b563e4ec4727d0de
|
||||
zh: d0228da978238e05
|
||||
/deepseek-ai-dsh-cua-bundle/use-this-package:
|
||||
en: 5c025a58990bb2eb
|
||||
zh: c3d1280ccbdfe214
|
||||
en: 022c613bacd82557
|
||||
zh: 8ec0c26b28a5dc1d
|
||||
/deepseek-ai-dsh-cua-bundle/understand-the-implementation:
|
||||
en: b1011db52cfc17cd
|
||||
zh: 6fa8798fedc5c0b6
|
||||
en: 5a006473d96c9348
|
||||
zh: db73ed336b9bb63c
|
||||
/deepseek-ai-dsh-cua-bundle/further-exploration:
|
||||
en: 9f15d56b5b16e1ca
|
||||
zh: 75eb08e8828c8877
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience:
|
||||
en: 215e7ba838619b7b
|
||||
zh: a311da3843709f90
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-in-ptc-sessions:
|
||||
en: e8f11f45b375771e
|
||||
zh: e8f11f45b375771e
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-in-ptc-sessions/what-the-model-sees:
|
||||
en: 591af735d1eb92f6
|
||||
zh: 3632bffa33c77b28
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-in-ptc-sessions/token-effect:
|
||||
en: e8de232e96220fe7
|
||||
zh: 5c791307e2123667
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-in-ptc-sessions/kv-cache-effect:
|
||||
en: 417c40acd93df532
|
||||
zh: 69cc5cf7140c75a9
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-across-presets:
|
||||
en: b59f3023a8494477
|
||||
zh: 72f91459a6b94e0a
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-across-presets/what-the-model-sees:
|
||||
en: 77980b01353c73e4
|
||||
zh: 591a21158fc5d094
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-across-presets/token-effect:
|
||||
en: dd5821cb31405880
|
||||
zh: d3b529cee8233dbf
|
||||
/deepseek-ai-dsh-cua-bundle/model-experience/computer-use-across-presets/kv-cache-effect:
|
||||
en: f818723a618d1917
|
||||
zh: 362d5d51d05e56b1
|
||||
/deepseek-ai-dsh-cua-bundle/known-limitations-and-deferred-work:
|
||||
en: 559776e398bb7c47
|
||||
zh: 27adfd2cacad1ee6
|
||||
en: 482e888d935cacda
|
||||
zh: 3fc4750507cca5c8
|
||||
/deepseek-ai-dsh-cua-bundle/known-limitations-and-deferred-work/dev-note:
|
||||
en: 0a1253c6f7b5e8b9
|
||||
zh: ce96645b3e75874e
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Enable macOS Computer Use from Plugins for existing and new PTC sessions. Windows support is in development. This bundle remains in `experimental` until that support is complete, then moves to the `computer-use` group. It ships with DSH switched off and appears in the Experimental plugins list on macOS Hosts; disabled profiles prepare no native components and register neither CUA tools nor their model guidance.
|
||||
Enable macOS Computer Use from Plugins for existing and new sessions. Standard, Creator, Minimal, and custom presets receive `cua_run_code`; PTC keeps its `cua` binding through `run_code`. Windows support is in development. The bundle remains in `experimental` until that support is complete, then moves to `computer-use`. It ships with DSH switched off and appears in the Experimental plugins list on macOS Hosts; disabled profiles prepare no native components and register neither CUA tools nor their model guidance.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -24,7 +24,7 @@ Enable macOS Computer Use from Plugins for existing and new PTC sessions. Window
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
On macOS, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open its details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root:
|
||||
On macOS, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open its details and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root:
|
||||
|
||||
```sh
|
||||
pnpm run build
|
||||
@@ -33,7 +33,7 @@ pnpm dsh web
|
||||
|
||||
For the source Desktop launcher and its separate development profile, follow [Desktop development](../../../apps/desktop/README.md). Enable Computer Use in each profile that needs it.
|
||||
|
||||
The switch saves bundle selection in the profile’s `package.json`. Computer Use is installed only in PTC sessions. Enabling through its card or detail page offers setup guidance when system permissions need attention. The detail page offers **Set to PTC** for the new-session default; existing sessions keep their preset. The switch leaves PTC execution mode and other settings unchanged. The detail page’s **Use persistent mode** action separately enables in-memory state across PTC calls; its effects and reload behavior are described in the [permission page](../cua/README.md). Native preparation runs when the provider loads and reuses the source-hashed executable when available.
|
||||
The switch saves bundle selection in the profile’s `package.json`. PTC sessions receive the raw `cua` binding; other composed presets receive `cua_run_code` with an automatically initialized `cua` object and separate persistent state. Enabling through its card or detail page offers setup guidance when system permissions need attention. The detail page offers **Set to PTC** for the new-session default; existing sessions keep their preset. The switch leaves PTC execution mode and other settings unchanged. The detail page’s **Use persistent mode** action separately enables in-memory state across PTC calls; its effects and reload behavior are described in the [permission page](../cua/README.md). Other presets keep their CUA program state independently of this setting. Native preparation runs when the provider loads and reuses the source-hashed executable when available.
|
||||
|
||||
Disabling unloads the provider and withdraws CUA tools from its Agent scopes. Runtime configuration, the new-session default and saved grants remain.
|
||||
|
||||
@@ -51,7 +51,7 @@ Explicit activation runs a read-only permission check, which may start a helper
|
||||
<details>
|
||||
<summary>Maintainer details</summary>
|
||||
|
||||
The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level condition skips the optional macOS provider on other Hosts. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal.
|
||||
The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`, selecting raw CUA for that preset and `cua_run_code` for the others. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level condition skips the optional macOS provider on other Hosts. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -67,26 +67,26 @@ The bundle patch mounts the native provider and permission UI with `agentPreset:
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
### Computer Use in PTC sessions
|
||||
### Computer Use across presets
|
||||
|
||||
#### What the model sees
|
||||
|
||||
Existing and new PTC sessions receive `cua` through the generated SDK and `run_code`, plus CUA guidance. Disabling withdraws these contributions and keeps PTC presentation. Other presets receive no CUA contributions. [CUA](../cua/README.md) and [PTC](../../ptc-runtime/ptc-runtime-node/README.md#persistent-repl) own the interfaces and output semantics.
|
||||
Existing and new PTC sessions receive `cua` through the generated SDK and `run_code`, plus CUA guidance. Other composed presets receive `cua_run_code` and the same operation guidance. Disabling withdraws these contributions and disposes the dedicated CUA runtime. [CUA](../cua/README.md) and [PTC](../../ptc-runtime/ptc-runtime-node/README.md#persistent-repl) own the interfaces and output semantics.
|
||||
|
||||
#### Token effect
|
||||
|
||||
CUA activation adds its guidance. Disabling removes that guidance; the existing PTC execution instructions remain.
|
||||
CUA activation adds its tool schema and guidance for the selected preset. Disabling removes those contributions; existing PTC execution instructions remain.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
CUA activation and removal change the PTC SDK and system guidance; subsequent requests use the updated prefix. The top-level `run_code` transport remains present.
|
||||
CUA activation and removal change tool schemas and system guidance; subsequent requests use the updated prefix. PTC keeps its top-level `run_code` transport.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- System permissions require the user’s approval in macOS; enabling the bundle does not grant them.
|
||||
- PTC execution is shared by the profile and is configured independently. A Host without HMR applies saved changes at restart.
|
||||
- PTC execution is shared by the profile and configured independently of the CUA provider's program runtime. A Host without HMR applies saved changes at restart.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-bundle"
|
||||
|
||||
## 概述
|
||||
|
||||
从插件页为已有和新建 PTC 会话开启 macOS Computer Use。Windows 支持正在开发中。本组合包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。随 DSH 提供且默认关闭,在 macOS Host 的实验性插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。
|
||||
从插件页为已有和新建会话开启 macOS Computer Use。标准、创造、极简及自定义 preset 获得 `cua_run_code`;PTC 继续通过 `run_code` 使用 `cua` 绑定。Windows 支持正在开发中。组合包保留在 `experimental`,待 Windows 支持完成后迁入 `computer-use`。它随 DSH 提供且默认关闭,在 macOS Host 的实验性插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -24,7 +24,7 @@ kind: "package-bundle"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开它的详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令:
|
||||
在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开它的详情,为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令:
|
||||
|
||||
```sh
|
||||
pnpm run build
|
||||
@@ -33,7 +33,7 @@ pnpm dsh web
|
||||
|
||||
源码 Desktop 的启动方式和独立开发配置档见[桌面开发说明](../../../apps/desktop/README.zh.md)。需要使用 Computer Use 的配置档分别开启该功能。
|
||||
|
||||
开关将组合包选择保存到 profile 的 `package.json`。Computer Use 仅安装在 PTC 会话中。通过卡片或详情页启用时,系统权限未就绪会显示设置引导。详情页提供“设为 PTC”按钮来修改新会话默认模式,已有会话保留原 preset。开关保持 PTC 执行方式和其他设置不变。详情页的“设为持久化”按钮单独开启 PTC 跨调用的内存状态保留,作用范围和重载行为见[权限页面](../cua/README.zh.md)。提供方加载时准备本机组件,已有与源码摘要匹配的可执行文件时直接复用。
|
||||
开关将组合包选择保存到 profile 的 `package.json`。PTC 会话获得原始 `cua` 绑定;其他已组合的 preset 获得 `cua_run_code`,其中自动初始化 `cua` 对象,并保留独立的持久状态。通过卡片或详情页启用时,系统权限未就绪会显示设置引导。详情页提供“设为 PTC”按钮来修改新会话默认模式,已有会话保留原 preset。开关保持 PTC 执行方式和其他设置不变。详情页的“设为持久化”按钮单独开启 PTC 跨调用的内存状态保留,作用范围和重载行为见[权限页面](../cua/README.zh.md)。其他 preset 的 CUA 程序状态独立于此设置。提供方加载时准备本机组件,已有与源码摘要匹配的可执行文件时直接复用。
|
||||
|
||||
关闭会卸载提供方,并从其 Agent 作用域中撤回 CUA 工具。执行器配置、新会话默认值和已保存的授权保留。
|
||||
|
||||
@@ -51,7 +51,7 @@ Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的
|
||||
<details>
|
||||
<summary>维护者说明</summary>
|
||||
|
||||
组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件会在其他 Host 上跳过可选的 macOS 提供方。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。
|
||||
组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面,为该 preset 选择原始 CUA,为其他 preset 选择 `cua_run_code`。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件会在其他 Host 上跳过可选的 macOS 提供方。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -67,26 +67,26 @@ Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
### Computer Use in PTC sessions
|
||||
### 各 preset 中的 Computer Use
|
||||
|
||||
#### What the model sees
|
||||
|
||||
已有和新建 PTC 会话通过生成的 SDK 与 `run_code` 使用 `cua`,并获得 CUA 指引。关闭撤回这些贡献,保留 PTC 展示方式。其他 preset 不获得 CUA 贡献。完整接口与输出约定由 [CUA](../cua/README.zh.md) 和 [PTC](../../ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl) 说明。
|
||||
已有和新建 PTC 会话通过生成的 SDK 与 `run_code` 使用 `cua`,并获得 CUA 指引。其他已组合的 preset 获得 `cua_run_code` 和相同的操作指引。关闭会撤回这些贡献,并释放专用 CUA 运行时。完整接口与输出约定由 [CUA](../cua/README.zh.md) 和 [PTC](../../ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl) 说明。
|
||||
|
||||
#### Token effect
|
||||
|
||||
CUA 生效时添加其指引。关闭撤回这些指引,现有 PTC 执行说明保留。
|
||||
CUA 生效时添加所选 preset 对应的工具 schema 和指引。关闭会撤回这些贡献,现有 PTC 执行说明保留。
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
CUA 生效和卸载会改变 PTC SDK 与系统指引,后续请求使用更新后的前缀。顶层 `run_code` 工具保持存在。
|
||||
CUA 生效和卸载会改变工具 schema 与系统指引,后续请求使用更新后的前缀。PTC 保留其顶层 `run_code` 工具。
|
||||
|
||||
## 已知限制与延后工作
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- 系统权限需用户在 macOS 中确认,开启组合包不会自动授予权限。
|
||||
- PTC 执行方式由 profile 共享,需单独配置。未启用 HMR 的 Host 在重启时应用已保存的变更。
|
||||
- PTC 执行方式由 profile 共享,与 CUA 提供方持有的程序运行时分别配置。未启用 HMR 的 Host 在重启时应用已保存的变更。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Computernutzung",
|
||||
"description": "Unterstützt derzeit macOS; Die Windows-Unterstützung befindet sich in der Entwicklung. Lädt die Computernutzung für bestehende und neue PTC-Sitzungen. Wechseln Sie in den PTC-Modus und erteilen Sie die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung, um ihn zu verwenden.",
|
||||
"description": "Unterstützt derzeit macOS; die Windows-Unterstützung befindet sich in Entwicklung. Ermöglicht die Computernutzung in bestehenden und neuen Sitzungen im Standardmodus, Erstellermodus, PTC-Modus und weiteren Modi. Erteilen Sie vor der Verwendung die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung.",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Computer use",
|
||||
"description": "Currently supports macOS; Windows support is in development. Loads computer use for existing and new PTC sessions. Switch to PTC mode and grant Accessibility and Screen Recording permissions to use it.",
|
||||
"description": "Currently supports macOS; Windows support is in development. Adds computer use to existing and new sessions in Standard, Creator, PTC, and other modes. Grant Accessibility and Screen Recording permissions before use.",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Uso de la computadora",
|
||||
"description": "Actualmente es compatible con macOS; El soporte para Windows está en desarrollo. Carga el uso de la computadora para sesiones PTC nuevas y existentes. Cambie al modo PTC y otorgue permisos de Accesibilidad y Grabación de pantalla para usarlo.",
|
||||
"description": "Actualmente es compatible con macOS; la compatibilidad con Windows está en desarrollo. Añade el uso de la computadora a sesiones existentes y nuevas en los modos estándar, creador, PTC y otros. Concede permisos de Accesibilidad y Grabación de pantalla antes de usarlo.",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Utilisation de l'ordinateur",
|
||||
"description": "Prend actuellement en charge macOS ; La prise en charge de Windows est en cours de développement. Charge l'utilisation de l'ordinateur pour les sessions PTC existantes et nouvelles. Passez en mode PTC et accordez les autorisations d’accessibilité et d’enregistrement d’écran pour l’utiliser.",
|
||||
"description": "Compatible actuellement avec macOS ; la prise en charge de Windows est en cours de développement. Ajoute le contrôle de l’ordinateur aux sessions existantes et nouvelles dans les modes standard, créateur, PTC et autres. Accordez les autorisations d’accessibilité et d’enregistrement de l’écran avant utilisation.",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Computer Use",
|
||||
"description": "現在は macOS のみ対応し、Windows 対応は開発中です。既存および新規の PTC セッションに Computer Use を読み込みます。PTC モードに切り替え、アクセシビリティと画面収録の権限を許可して使用してください。",
|
||||
"description": "現在は macOS のみ対応し、Windows 対応は開発中です。標準、クリエイター、PTC などのモードで、既存および新規セッションに Computer Use を追加します。使用前にアクセシビリティと画面収録の権限を許可してください。",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Uso do computador",
|
||||
"description": "Atualmente suporta macOS; O suporte Windows está em desenvolvimento. Carrega o uso do computador para sessões PTC novas e existentes. Mude para o modo PTC e conceda permissões de acessibilidade e gravação de tela para usá-lo.",
|
||||
"description": "Atualmente oferece suporte ao macOS; o suporte ao Windows está em desenvolvimento. Adiciona o uso do computador a sessões existentes e novas nos modos padrão, criador, PTC e outros. Conceda permissões de Acessibilidade e Gravação de tela antes de usar.",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Использование компьютера",
|
||||
"description": "В настоящее время поддерживается macOS; Поддержка Windows находится в разработке. Загружает использование компьютера для существующих и новых сеансов PTC. Переключитесь в режим PTC и предоставьте разрешения на доступность и запись экрана для его использования.",
|
||||
"description": "Сейчас поддерживается macOS; поддержка Windows находится в разработке. Добавляет управление компьютером в существующие и новые сеансы в стандартном режиме, режиме автора, PTC и других режимах. Перед использованием предоставьте разрешения на универсальный доступ и запись экрана.",
|
||||
"detail": "docs/DETAIL.md"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Computer Use",
|
||||
"description": "目前仅支持 macOS,Windows 支持正在开发中。为已有及新建 PTC 会话加载 Computer Use。请切换到 PTC 模式来使用,并授予辅助功能和屏幕录制权限。",
|
||||
"description": "目前仅支持 macOS,Windows 支持正在开发中。为标准、创造、PTC 及其他模式的已有和新建会话提供 Computer Use。使用前请授予辅助功能和屏幕录制权限。",
|
||||
"detail": "docs/DETAIL.zh.md"
|
||||
}
|
||||
}
|
||||
@@ -9,17 +9,17 @@
|
||||
en: 022ca213425e11ee
|
||||
zh: d64631748ed91cc2
|
||||
/deepseek-ai-dsh-experimental-cua-macos/summary:
|
||||
en: 7ffb2f01c0b05f32
|
||||
zh: 74dac288fa7f7690
|
||||
en: 02bf160f22823a31
|
||||
zh: 48ba17cc62debce2
|
||||
/deepseek-ai-dsh-experimental-cua-macos/table-of-contents:
|
||||
en: 1777e7bf6785f986
|
||||
zh: e3daac1074ebb74d
|
||||
/deepseek-ai-dsh-experimental-cua-macos/use-this-package:
|
||||
en: 233423a8675de85d
|
||||
zh: faf5cecb9999cfa7
|
||||
en: e4f0f5a00c340b32
|
||||
zh: 87cf71f755ca29b7
|
||||
/deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment:
|
||||
en: 1bf907f257ef6f90
|
||||
zh: ed71613b8de260aa
|
||||
en: 8bd8e80f83dd2599
|
||||
zh: 7d4988effe28c40a
|
||||
/deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation:
|
||||
en: 4e82b85a5aa72eee
|
||||
zh: 4e004b7a205d8688
|
||||
@@ -33,11 +33,11 @@
|
||||
en: ab7cba4a42334ab9
|
||||
zh: f77cd9d84624b6c2
|
||||
/deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/what-the-model-sees:
|
||||
en: c221fa5ce647b1dd
|
||||
zh: 9388c91a9f89e029
|
||||
/deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/what-the-model-sees/operation-guidance-verbatim:
|
||||
en: 2dbc22ffd1f8a717
|
||||
zh: d4458872e75305d9
|
||||
en: 0acecc785a72c0c2
|
||||
zh: db46d8eb88f9620c
|
||||
/deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/what-the-model-sees/ptc-operation-guidance-verbatim:
|
||||
en: 9142df90fd94ef91
|
||||
zh: cad17384c7f7452b
|
||||
/deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/token-effect:
|
||||
en: 86b0b7e406627a47
|
||||
zh: 53ad627fb3521f28
|
||||
@@ -45,8 +45,8 @@
|
||||
en: a2c9acb5a4320dda
|
||||
zh: e8d1586af60215c4
|
||||
/deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work:
|
||||
en: b362f9357fe79293
|
||||
zh: a74f0e9cffb647bc
|
||||
en: 791f3b5da2e8826d
|
||||
zh: 9fdab4ccba5ed76a
|
||||
/deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work/dev-note:
|
||||
en: b836f01bd0bceb4a
|
||||
zh: 8122fa08b2aa95fa
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Inspect macOS permissions, select running applications and windows, read accessibility trees, capture screenshots from a selected window, and send input. The object API can be retained by an external persistent execution environment. The Swift helper uses macOS frameworks directly and adapts selected MIT-licensed Cua Driver behavior. This package owns neither a PTC runtime nor variable persistence.
|
||||
Inspect macOS permissions, select running applications and windows, read accessibility trees, capture screenshots from a selected window, and send input. Standard and other non-PTC presets use retained objects through `cua_run_code`; PTC uses its existing runtime. The Swift helper uses macOS frameworks directly and adapts selected MIT-licensed Cua Driver behavior. The [shared CUA package](../cua/README.md) owns tool registration and the dedicated runtime; this provider owns native operations.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -57,7 +57,8 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates
|
||||
|
||||
| Field | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `agentPreset` | `ptc` | Register tools and guidance only for Agents bound to this preset; `false` registers globally. |
|
||||
| `agentPreset` | `ptc` | Give this preset raw `cua` and other composed presets `cua_run_code`; `false` registers raw `cua` globally. |
|
||||
| `standaloneRunCode.runtime` / `standaloneRunCode.executor` | shared Node / PTC limits | Resource, launch, and nested-call settings for the dedicated CUA runtime; see [CUA](../cua/README.md). |
|
||||
| `allowedApps` | `[]` | Legacy path/signature grants, imported once for removal; they do not authorize new bundle-ID identities. |
|
||||
| `helperPath` | package-owned executable | Absolute executable inside the signed helper `.app`; a bare binary fails with `NATIVE_APPLICATION_REQUIRED`. |
|
||||
| `requireSystemPointerApproval` | `true` | Ask on the first explicit request to move the system pointer. With `false`, only explicitly requested moves use it. |
|
||||
@@ -81,7 +82,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-exper
|
||||
|
||||
`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+=. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. 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`. 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')` 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -93,7 +94,7 @@ AX observations show menu-bar entries by default. Use `app.getAccessibilityTree(
|
||||
|
||||
Values and placeholders are separate. Named, stateful or actionable groups and scroll areas retain their own rows. Repeated names, descriptions and help text on one node are shown once. Values, placeholders and URLs keep their distinct meanings even when their text matches; body text shared by distinct nodes remains intact. Writability is explicit on relevant controls, including `AXIncrementor`; `unknown` means the system did not report it. Missing optional state fields do not imply false. During tree observation, an AXValue or AXSelectedTextRange writability probe returning -25200 leaves that field unknown and preserves the remaining nodes. Actual writes remain strict; permission, communication and invalid-element errors still propagate. UTF-16 ranges outside the observed value are marked unavailable. Compact tree labels can omit AppKit target and selector details. Pass the exact name returned by `listActions(elementId)` to `performAction`.
|
||||
|
||||
Observations emit by default and also return their value. In persistent PTC, use `void await app.getAccessibilityTree()` for one emitted copy, or `emit:false` and one explicit print. Capturing a screenshot after an emitted tree can fail independently; retain the successful AX output.
|
||||
Observations emit by default and also return their value. In persistent PTC or `cua_run_code`, use `void await app.getAccessibilityTree()` for one emitted copy, or `emit:false` and one explicit print. Capturing a screenshot after an emitted tree can fail independently; retain the successful AX output.
|
||||
|
||||
Screenshot diagnostics use `[cua-screenshot]` records keyed by the tool request ID. Native phase records return over the originating Agent connection and cover window/AX geometry checks, system capture, PNG/Base64 encoding and response writing. Host debug logs add dispatch, reply and cleanup timings. Each request retains at most 8192 bytes of complete diagnostic records, with explicit truncation; screenshot failures append these records to the error for Session export. Records contain stages, timings and error codes, not window titles, AX text or image bytes.
|
||||
|
||||
@@ -101,7 +102,7 @@ Native preparation serializes building and signing with a file lock. It retains
|
||||
|
||||
### Connect an external execution environment
|
||||
|
||||
To run through persistent PTC, add `--patch packages/experimental/cua-macos/examples/persistent-ptc.cordis.yml` after the macOS overlay. This provider keeps variables for the live Agent and applies the selected file sandbox policy. The caller imports the bridge and supplies the current authorized `tools.cua` binding. Persistent PTC receives an installation-owned bridge file URL in its CUA instructions, so the project does not need to install this package. The example below is for an external host that resolves the package from its own installation and supplies `tools`; the package does not install a global object or keep variables alive:
|
||||
To run through persistent PTC, add `--patch packages/experimental/cua-macos/examples/persistent-ptc.cordis.yml` after the macOS overlay. This provider keeps variables for the live Agent and applies the selected file sandbox policy. The caller imports the bridge and supplies the current authorized `tools.cua` binding. Persistent PTC receives an installation-owned bridge file URL in its CUA instructions, so the project does not need to install this package. The example below is for an external host that resolves the package from its own installation and supplies `tools`. In other composed presets, `cua_run_code` already supplies the global object and retains variables through the [shared CUA package](../cua/README.md):
|
||||
|
||||
```javascript
|
||||
import { connectCua } from '@deepseek-ai/dsh-cua/bridge'
|
||||
@@ -175,16 +176,16 @@ Node roles and metadata share one AX batch per observation. Group and scroll-are
|
||||
|
||||
#### What the model sees
|
||||
|
||||
The plugin contributes one `cua` operation tool with method-specific parameters. Standard PTC presentation exposes it as `tools.cua` through `run_code`. The following package-owned guidance is emitted verbatim:
|
||||
The configured PTC preset receives one `cua` operation tool with method-specific parameters through `run_code`. Other composed presets receive `cua_run_code`, with the global `cua` object ready to use and only `tools.cua` bound inside the program. The verbatim block below shows the PTC operation guidance, which uses `tools.write`, `tools.grep`, and `tools.read` for large AX trees. The `cua_run_code` variant uses `node:fs/promises` to save a tree and ordinary session tools outside the program to search it; initialization and program instructions are selected by the [shared CUA package](../cua/README.md#model-experience).
|
||||
|
||||
##### Operation guidance (verbatim)
|
||||
##### PTC operation guidance (verbatim)
|
||||
|
||||
```markdown
|
||||
macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.
|
||||
|
||||
Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation.
|
||||
|
||||
In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes.
|
||||
Use void await for observations that emit, and never stringify screenshot image bytes.
|
||||
|
||||
Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid.
|
||||
|
||||
@@ -226,7 +227,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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier 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 'down' to hold a key across tool calls in one run_code, 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. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — 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. 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.
|
||||
|
||||
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
|
||||
|
||||
@@ -261,7 +262,7 @@ The queue orders individual native requests. Holding an app object does not rese
|
||||
- Release packaging does not automatically verify GUI startup, helper identity or exit cleanup. Release maintainers can run the [distribution smoke](native/README.md#build-and-service) on a logged-in Mac before publication; a successful package build does not establish those runtime results.
|
||||
- Saved permission rows show the name, path and icon of one approved copy, not an inventory of every installation sharing its identity. Removing that copy can leave its icon unavailable. Revocation still applies to every copy with the same identity.
|
||||
- If macOS does not expose a running application’s bundle identifier, the helper checks its reported bundle only when its executable matches the observed process path, then falls back to that path. Consent identity creation fails only when both the bundle identifier and actual executable path are unavailable; process-instance verification can still fail independently.
|
||||
- Persistent PTC is an external dependency assumption, not an implementation in this package. Real-model task success requires separate evaluation beyond native and protocol fixtures.
|
||||
- The shared CUA package and PTC providers own program execution and retained state; this package owns native operations. Real-model task success requires separate evaluation beyond native and protocol fixtures.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
检查 macOS 权限,选择运行中的应用和窗口,读取辅助功能树,从选定窗口截图并发送输入。外部持久执行环境可以保留这些对象。Swift 辅助进程直接使用 macOS 框架,并改写选取的 MIT 许可 Cua Driver 行为。本包不提供 PTC 运行时或变量持久化。
|
||||
检查 macOS 权限,选择运行中的应用和窗口,读取辅助功能树,从选定窗口截图并发送输入。标准及其他非 PTC preset 通过 `cua_run_code` 使用保留对象;PTC 使用已有运行时。Swift 辅助进程直接使用 macOS 框架,并改写选取的 MIT 许可 Cua Driver 行为。[共享 CUA 包](../cua/README.zh.md)负责工具注册和专用运行时;本提供方负责原生操作。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -57,7 +57,8 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.
|
||||
|
||||
| 字段 | 默认值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `agentPreset` | `ptc` | 仅为绑定该 preset 的 Agent 注册工具和指引;`false` 表示全局注册。 |
|
||||
| `agentPreset` | `ptc` | 为该 preset 提供原始 `cua`,为其他已组合的 preset 提供 `cua_run_code`;`false` 表示全局注册原始 `cua`。 |
|
||||
| `standaloneRunCode.runtime` / `standaloneRunCode.executor` | 共享 Node / PTC 上限 | 专用 CUA 运行时的资源、启动和嵌套调用设置;参见 [CUA](../cua/README.zh.md)。 |
|
||||
| `allowedApps` | `[]` | 旧路径和签名许可,只导入 profile 存储一次供撤销,不授予新 Bundle ID 身份访问权限。 |
|
||||
| `helperPath` | 包内可执行文件 | 已签名 helper `.app` 内可执行文件的绝对路径;裸二进制会触发 `NATIVE_APPLICATION_REQUIRED`。 |
|
||||
| `requireSystemPointerApproval` | `true` | 主任务首次显式请求移动系统指针时询问用户。设为 `false` 时仅本次显式移动免询问。 |
|
||||
@@ -81,7 +82,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.
|
||||
|
||||
`pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。
|
||||
|
||||
长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久。控件可能过滤模拟的重复事件,可通过控件的实际变化确认效果。松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。
|
||||
长按时,在 `run_code` 或 `cua_run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久。控件可能过滤模拟的重复事件,可通过控件的实际变化确认效果。松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。
|
||||
|
||||
Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。
|
||||
|
||||
@@ -93,7 +94,7 @@ AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ inc
|
||||
|
||||
实际值与占位文字分别展示。有名称、状态或可用动作的分组和滚动区域保留独立行。同一节点中重复的名称、描述和帮助只显示一次。实际值、占位文字和 URL 即使文字相同也保留各自含义,不删除不同节点共有的正文。相关控件明确展示可写性,包括 `AXIncrementor`;`unknown` 表示系统未报告。缺少可选状态字段不代表 false。读树时,AXValue 或 AXSelectedTextRange 的可写性探测返回 -25200,会将该字段保留为未知并继续读取其他节点。实际写入仍严格校验;权限、通信和失效元素错误仍向上传播。超出当前值长度的 UTF-16 选区标为不可用。树中的动作简称可能省略 AppKit 的 target 和 selector 信息。调用 `performAction` 时使用 `listActions(elementId)` 返回的完整名称。
|
||||
|
||||
观察方法默认自动输出,同时返回结果。在 persistent PTC 中使用 `void await app.getAccessibilityTree()` 输出一次,或指定 `emit:false` 后自行打印一次。AX 输出后的截图可能单独失败,已成功取得的 AX 输出仍保留。
|
||||
观察方法默认自动输出,同时返回结果。在 persistent PTC 或 `cua_run_code` 中使用 `void await app.getAccessibilityTree()` 输出一次,或指定 `emit:false` 后自行打印一次。AX 输出后的截图可能单独失败,已成功取得的 AX 输出仍保留。
|
||||
|
||||
截图诊断使用带工具请求 ID 的 `[cua-screenshot]` 记录。原生阶段记录经本次 Agent 连接返回,覆盖窗口及 AX 几何检查、系统截图、PNG/Base64 编码和响应写出。Host 调试日志补充发送、响应和清理耗时。每次请求最多保留 8192 字节完整诊断记录,超限会明确标记;截图失败时附在错误中,保留到 Session trace。记录只含阶段、耗时和错误码,不含窗口标题、AX 正文或图片内容。
|
||||
|
||||
@@ -101,7 +102,7 @@ AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ inc
|
||||
|
||||
### 接入外部执行环境
|
||||
|
||||
使用 persistent PTC 时,在 macOS 配置后追加 `--patch packages/experimental/cua-macos/examples/persistent-ptc.cordis.yml`。该 provider 为存活的 Agent 保留变量,并遵守当前选择的文件沙箱策略。调用方导入适配模块,并提供当前执行中已授权的 `tools.cua` 绑定。persistent PTC 会在 CUA 指引中收到安装目录内 bridge 的文件 URL,项目无须安装本包。下面的例子用于能从自身安装目录解析本包、且已提供 `tools` 的外部宿主;本包不安装全局对象,也不负责保留变量:
|
||||
使用 persistent PTC 时,在 macOS 配置后追加 `--patch packages/experimental/cua-macos/examples/persistent-ptc.cordis.yml`。该 provider 为存活的 Agent 保留变量,并遵守当前选择的文件沙箱策略。调用方导入适配模块,并提供当前执行中已授权的 `tools.cua` 绑定。persistent PTC 会在 CUA 指引中收到安装目录内 bridge 的文件 URL,项目无须安装本包。下面的例子用于能从自身安装目录解析本包、且已提供 `tools` 的外部宿主。在其他已组合的 preset 中,`cua_run_code` 已经提供全局对象,并通过[共享 CUA 包](../cua/README.zh.md)保留变量:
|
||||
|
||||
```javascript
|
||||
import { connectCua } from '@deepseek-ai/dsh-cua/bridge'
|
||||
@@ -175,16 +176,16 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID
|
||||
|
||||
#### 模型可见内容
|
||||
|
||||
插件提供一个 `cua` 操作工具,定义各方法的参数。标准 PTC 呈现通过 `run_code` 将它暴露为 `tools.cua`。以下是本包逐字输出的指导文本:
|
||||
配置指定的 PTC preset 通过 `run_code` 获得一个定义各方法参数的 `cua` 操作工具。其他已组合的 preset 获得 `cua_run_code`,其中全局 `cua` 对象可直接使用,程序内只绑定 `tools.cua`。下方逐字引用 PTC 操作指引,其中使用 `tools.write`、`tools.grep` 和 `tools.read` 处理较大的 AX 树。`cua_run_code` 版本使用 `node:fs/promises` 保存树,再在程序外直接调用普通会话工具搜索;初始化和程序说明由[共享 CUA 包](../cua/README.zh.md#model-experience)选择。
|
||||
|
||||
##### 操作指导文本(原文)
|
||||
##### PTC 操作指引(原文)
|
||||
|
||||
```markdown
|
||||
macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.
|
||||
|
||||
Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation.
|
||||
|
||||
In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes.
|
||||
Use void await for observations that emit, and never stringify screenshot image bytes.
|
||||
|
||||
Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid.
|
||||
|
||||
@@ -226,7 +227,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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier 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 'down' to hold a key across tool calls in one run_code, 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. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — 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. 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.
|
||||
|
||||
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
|
||||
|
||||
@@ -261,7 +262,7 @@ Only if the task cannot be completed without moving the user’s pointer, call a
|
||||
- 发布打包不自动验证 GUI 启动、helper 身份或退出清理。发布维护者可在发布前,在已登录桌面的 Mac 上执行[分发 smoke](native/README.zh.md#build-and-service);打包成功不能证明这些运行行为已通过验收。
|
||||
- 已保存许可的条目显示一个已批准副本的名称、路径和图标,不枚举共享身份的所有安装副本。删除该副本后图标可能不可用,撤销仍作用于同一身份的所有副本。
|
||||
- macOS 无法提供运行中应用的 Bundle ID 时,helper 仅在其报告的 bundle 可执行路径与实际进程路径相同时读取该 bundle,仍无标识则使用路径。只有 Bundle ID 和实际可执行路径均不可用时才拒绝生成授权身份;进程实例验证仍可能独立失败。
|
||||
- 持久 PTC 是对外部运行环境的假设,本包不实现它。真实模型任务成功率需要在原生测试和协议测试之外单独评估。
|
||||
- 共享 CUA 包及 PTC 提供方负责程序执行和状态保留,本包负责原生操作。真实模型任务成功率需要在原生测试和协议测试之外单独评估。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 60db6c41c868f7db
|
||||
zh: 1de5d504b2d84e61
|
||||
/dsh-cua-native-helper/observation-and-input:
|
||||
en: e632562614b20e7b
|
||||
zh: 254e70199bf151c8
|
||||
en: b09c8a07f0e867d3
|
||||
zh: ad588ba8c838d76b
|
||||
/dsh-cua-native-helper/verification:
|
||||
en: d1c47a2f63350417
|
||||
zh: 5277d8245529b5a3
|
||||
|
||||
@@ -107,7 +107,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` 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
|
||||
|
||||
`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。
|
||||
|
||||
宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,向接收进程发送一次带 `keyboardEventAutorepeat` 标志的按下事件。AppKit 视图可能只收到首次按下和最终松开,过滤中间的重复事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。
|
||||
宿主为每次 `run_code` 或 `cua_run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,向接收进程发送一次带 `keyboardEventAutorepeat` 标志的按下事件。AppKit 视图可能只收到首次按下和最终松开,过滤中间的重复事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。
|
||||
|
||||
所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。
|
||||
|
||||
@@ -165,7 +165,6 @@ Blender 键盘检查使用 `python3 packages/experimental/cua-macos/native/tests
|
||||
|
||||
运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、带修饰键的中键手势、W 和 D 同时按住时的事件顺序及数字键盘键码。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。添加 `--keyboard-only` 可用后台窗口验证 W、D 同时按住两秒、单独释放 D 和收尾时释放 W。添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。
|
||||
|
||||
|
||||
运行 `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence`,验证自有 AppKit 应用在后台接收 Paste 动作但不读取数据时返回 `PASTE_NOT_CONSUMED`,以及前台读取同一次粘贴后成功。测试要求 Mac 已解锁并已授予辅助功能权限,只激活自有的两个应用,并独立记录收到的动作和文本以核对 helper 回复。
|
||||
|
||||
-----
|
||||
|
||||
@@ -4,18 +4,24 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance'
|
||||
/** macOS operation levels, permissions, selectors, and native measurement units. */
|
||||
export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.'
|
||||
|
||||
const methodDetails = new Map<string, string>([
|
||||
['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. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current.'],
|
||||
['mouseMove', 'Default hover 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.'],
|
||||
['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. Verify the expected effect, such as a changed selection, before typing or retrying.'],
|
||||
])
|
||||
|
||||
/** Native operation instructions; the shared Host adds guidance for declared capabilities. */
|
||||
export const GUIDANCE = `${PLATFORM_GUIDANCE}
|
||||
function operationGuidance(treeAdvice: string): string {
|
||||
const methodDetails = new Map<string, string>([
|
||||
['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', 'Default hover 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.'],
|
||||
['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. Verify the expected effect, such as a changed selection, before typing or retrying.'],
|
||||
])
|
||||
return `${PLATFORM_GUIDANCE}
|
||||
|
||||
${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => {
|
||||
if (method === 'pressKey') return `${entry}
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, 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. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.`
|
||||
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — 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. 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.`
|
||||
const detail = methodDetails.get(method)
|
||||
return detail ? `${entry} ${detail}` : entry
|
||||
})}`
|
||||
}
|
||||
|
||||
/** Native PTC operation instructions with registered file tools for large observations. */
|
||||
export const GUIDANCE = operationGuidance('In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need.')
|
||||
|
||||
/** CUA-only program instructions; other session tools remain outside the program. */
|
||||
export const PROGRAM_GUIDANCE = operationGuidance('Capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory and print only the matches you need. If needed, save it to a new workspace file with node:fs/promises and use the session’s file tools to search it.')
|
||||
@@ -1,42 +1,60 @@
|
||||
/** Directional input belongs to the enclosing run_code, including while its worker calls other tools. */
|
||||
/** 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<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep native key ownership alive until its program returns, throws, or is interrupted.
|
||||
* Keep native key ownership until program settlement or its Agent's native connection closes.
|
||||
* @param ctx - Provider scope owning the tool execution listener.
|
||||
* @returns Handler for authorized directional keyboard requests.
|
||||
* @returns Directional input handler; each native connection owns cleanup of the runs that use it.
|
||||
*/
|
||||
export function installHeldKeys(ctx: Context): NonNullable<CuaBackend['sendKeyEvent']> {
|
||||
const runs = new Map<ToolExecutionToken, { id: string; client?: NativeClient }>()
|
||||
const runs = new Map<ToolExecutionToken, HeldKeyRun>()
|
||||
ctx.on('tools/execute', async (execution, next) => {
|
||||
if (execution.name !== RUN_CODE_NAME) return next()
|
||||
const run: { id: string; client?: NativeClient } = { id: randomUUID() }
|
||||
runs.set(execution.token, run)
|
||||
let cleanup: Promise<unknown> | undefined
|
||||
const release = () => {
|
||||
runs.delete(execution.token)
|
||||
if (run.client) cleanup ??= run.client.requestCleanup('releaseHeldKeys', { runId: run.id })
|
||||
return cleanup
|
||||
if (execution.name !== RUN_CODE_NAME && execution.name !== 'cua_run_code') return next()
|
||||
let cleanup: Promise<void> | 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 release()?.catch(() => undefined) }
|
||||
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 release()
|
||||
await run.release()
|
||||
}
|
||||
})
|
||||
return (client, params, execution) => {
|
||||
const run = execution.parent && runs.get(execution.parent)
|
||||
if (!run) throw new NativeError('INVALID_ARGUMENT', 'Use sendKeyEvent inside an active run_code execution')
|
||||
run.client = client
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { nativeHostArchitecture, prepareNativeExecutable, type SourceSigning } f
|
||||
import { createSharedNativeChannel } from './shared-native.ts'
|
||||
import { installHeldKeys } from './held-keys.ts'
|
||||
import { AX_TRAVERSAL_MAX } from './ax-limits.ts'
|
||||
import { GUIDANCE } from './guidance.ts'
|
||||
import { GUIDANCE, PROGRAM_GUIDANCE } from './guidance.ts'
|
||||
export { GUIDANCE } from './guidance.ts'
|
||||
|
||||
const CAPABILITIES: CuaStartupCapabilities = {
|
||||
@@ -65,7 +65,7 @@ export const Config = Schema.object({
|
||||
*/
|
||||
export async function apply(ctx: Context, config: Config): Promise<void> {
|
||||
const backend = { createChannel: createSharedNativeChannel, sendKeyEvent: installHeldKeys(ctx),
|
||||
guidance: GUIDANCE, capabilities: CAPABILITIES,
|
||||
getGuidance: (kind: 'raw' | 'standalone') => kind === 'raw' ? GUIDANCE : PROGRAM_GUIDANCE, capabilities: CAPABILITIES,
|
||||
permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) }
|
||||
if (config.helperPath !== undefined) {
|
||||
if (!isAbsolute(config.helperPath)) throw new Error('dsh-cua helperPath must be absolute')
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api'
|
||||
import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance'
|
||||
import { GUIDANCE, PLATFORM_GUIDANCE } from '../src/guidance.ts'
|
||||
import { GUIDANCE, PLATFORM_GUIDANCE, PROGRAM_GUIDANCE } from '../src/guidance.ts'
|
||||
|
||||
const apiNames: Array<keyof CuaApi> = ['getCapabilities', 'listApps', 'findApps', 'getState', 'getApp']
|
||||
const accessibilityNames: Array<Exclude<keyof CuaSurface, 'sendKeyEvent'>> = [
|
||||
@@ -11,6 +11,15 @@ const accessibilityNames: Array<Exclude<keyof CuaSurface, 'sendKeyEvent'>> = [
|
||||
const appNames: Array<keyof CuaApp> = ['appHandle', 'activate', 'getWindows', 'getWindow']
|
||||
const windowNames: Array<keyof CuaWindow> = ['windowId', 'getScreenshot', 'mouseMove', 'click', 'scroll', 'drag']
|
||||
|
||||
it('keeps file-tool instructions in PTC and limits the program guidance to available bindings', () => {
|
||||
for (const name of ['tools.write', 'tools.grep', 'tools.read']) {
|
||||
expect(GUIDANCE).toContain(name)
|
||||
expect(PROGRAM_GUIDANCE).not.toContain(name)
|
||||
}
|
||||
expect(PROGRAM_GUIDANCE).toContain('node:fs/promises')
|
||||
expect(PROGRAM_GUIDANCE).toContain('session’s file tools')
|
||||
})
|
||||
|
||||
it('keeps exactly three ordered operation headings', () => {
|
||||
const heads = COMMON_GUIDANCE.match(/^## .+$/gm)
|
||||
expect(heads).toEqual(['## Accessibility tree', '## Simulated mouse', '## Simulated keyboard'])
|
||||
@@ -132,9 +141,8 @@ it('separates facade options from raw RPC parameters', () => {
|
||||
expect(COMMON_GUIDANCE).toContain('raw operation schema')
|
||||
})
|
||||
|
||||
it('documents facade initialization, emitted observations, and separate key arguments', () => {
|
||||
expect(COMMON_GUIDANCE).toContain('host-provided bridge initialization once')
|
||||
expect(COMMON_GUIDANCE).toContain('not a preinstalled global')
|
||||
it('documents emitted observations and key arguments without assuming a transport', () => {
|
||||
expect(COMMON_GUIDANCE).not.toContain('not a preinstalled global')
|
||||
expect(COMMON_GUIDANCE).toContain('void await')
|
||||
expect(COMMON_GUIDANCE).toContain('do not pack them into a chord string')
|
||||
expect(COMMON_GUIDANCE).toContain('perform a left-button double-click')
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/** Held-key cleanup through real native byte streams and the tool execution wrapper. */
|
||||
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 { 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'
|
||||
|
||||
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<typeof Request>[] = []
|
||||
const events: string[] = []
|
||||
const held = new Set<string>()
|
||||
const releasing: PromiseWithResolvers<void> = 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<void>) => Promise<void>) {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
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: ToolCallId('held-key'), parent: execution.token,
|
||||
})
|
||||
})
|
||||
return null
|
||||
},
|
||||
}))
|
||||
return { run: () => executeToolFixture(ctx, { name: 'cua_run_code', callId: ToolCallId('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<void> = Promise.withResolvers()
|
||||
const finishProgram: PromiseWithResolvers<void> = 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<void> | 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<void> = Promise.withResolvers()
|
||||
const finishProgram: PromiseWithResolvers<void> = 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)
|
||||
})
|
||||
@@ -24,6 +24,7 @@ import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local'
|
||||
import FileSystem from '@deepseek-ai/dsh-fs-local'
|
||||
import UserQuestions, { UserQuestionError } from '@deepseek-ai/dsh-user-questions'
|
||||
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
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, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm'
|
||||
@@ -60,16 +61,34 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({
|
||||
native.reportDiagnostic = args[3]
|
||||
native.instances.push(this)
|
||||
}
|
||||
private readonly cleanups = new Set<Parameters<NativeClient['registerCleanup']>[0]>()
|
||||
private cleaning?: Promise<void>
|
||||
requestCleanup = native.cleanup
|
||||
request = native.request
|
||||
registerCleanup(cleanup: Parameters<NativeClient['registerCleanup']>[0]) {
|
||||
if (this.disposed) throw new Error('The fixture connection is closing')
|
||||
this.cleanups.add(cleanup)
|
||||
return () => { this.cleanups.delete(cleanup) }
|
||||
}
|
||||
invalidate() { this.disposed = true }
|
||||
async dispose() { this.disposed = true; await native.dispose() }
|
||||
async dispose() {
|
||||
const canRequest = !this.disposed
|
||||
this.disposed = true
|
||||
this.cleaning ??= Promise.resolve().then(async () => {
|
||||
const results = await Promise.allSettled([...this.cleanups].map(cleanup => Promise.resolve().then(() => cleanup(canRequest))))
|
||||
this.cleanups.clear()
|
||||
const failed = results.find(result => result.status === 'rejected')
|
||||
if (failed?.status === 'rejected') throw failed.reason
|
||||
})
|
||||
try { await this.cleaning } finally { await native.dispose() }
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const config = {
|
||||
permissionPollIntervalMs: 1000, requireSystemPointerApproval: true,
|
||||
agentPreset: false,
|
||||
standaloneRunCode: CuaConfig({}).standaloneRunCode,
|
||||
helperPath: resolve('fixture-helper'), sourceSigning: 'ad-hoc', buildTimeoutMs: 300_000, timeoutMs: 10_000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1024, maxResponseBytes: 4096, maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxAppMatches: 20,
|
||||
graceMs: 10, textEventIntervalMs: 8, maxClickHoldMs: 7000, maxElements: 64, maxDepth: 8, dragDurationMs: 200, dragSteps: 10,
|
||||
} satisfies Omit<NativeProvider.Config, 'allowedApps'>
|
||||
@@ -150,6 +169,21 @@ async function setup(model?: { provider: string; model: string }, ptc = false) {
|
||||
return { ctx, provider, handle, execute }
|
||||
}
|
||||
|
||||
async function executeProgram(
|
||||
f: Awaited<ReturnType<typeof setup>>, name: 'run_code' | 'cua_run_code',
|
||||
code: string, description: string, signal = new AbortController().signal,
|
||||
) {
|
||||
if (name === 'cua_run_code') {
|
||||
f.ctx.tools.register(createRunCodeTool(f.ctx, {
|
||||
name, description: 'Run a computer use program.', runtime: f.ctx.ptcRuntime,
|
||||
tools: f.ctx.tools.definitions(),
|
||||
}))
|
||||
}
|
||||
const execute = name === 'run_code' ? executeModelToolFixture : executeToolFixture
|
||||
return execute(f.ctx, { agent: f.handle.agent, callId: ToolCallId('keyboard-run'), name,
|
||||
arguments: { code, description }, signal })
|
||||
}
|
||||
|
||||
async function selectApplication(f: Awaited<ReturnType<typeof setup>>) {
|
||||
await f.ctx.plugin(UserQuestions)
|
||||
f.ctx.on('user-questions/request', async () => ({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] }))
|
||||
@@ -168,21 +202,21 @@ it('requires an enclosing run_code before sending a directional key', async () =
|
||||
expect(native.request).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('finishes a shortcut-only run_code without requesting held-key cleanup', async () => {
|
||||
it.each(['run_code', 'cua_run_code'] as const)('finishes a shortcut-only %s without requesting held-key cleanup', async (name) => {
|
||||
const f = await setup(undefined, true)
|
||||
await selectApplication(f)
|
||||
native.request.mockClear().mockResolvedValue({ dispatched: true })
|
||||
const result = await executeModelToolFixture(f.ctx, { agent: f.handle.agent, callId: ToolCallId('shortcut-run'),
|
||||
name: 'run_code', signal: new AbortController().signal, arguments: {
|
||||
code: "return await tools.cua({ method: 'pressKey', params: { appHandle: 'app-one', key: 'a', modifiers: ['command'] } });",
|
||||
description: 'Press Command+A',
|
||||
} })
|
||||
const result = await executeProgram(f, name,
|
||||
"return 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()
|
||||
})
|
||||
|
||||
it.each(['return', 'throw', 'pause', 'pause with cleanup error'])('cleans up only the held W when run_code ends by %s', async (ending) => {
|
||||
it.each((['run_code', 'cua_run_code'] as const).flatMap(name =>
|
||||
['return', 'throw', 'pause', 'pause with cleanup error'].map(ending => ({ name, ending })),
|
||||
))('cleans up only the held W when $name ends by $ending', async ({ name, ending }) => {
|
||||
const f = await setup(undefined, true)
|
||||
await selectApplication(f)
|
||||
const held = new Set<string>()
|
||||
@@ -229,14 +263,102 @@ it.each(['return', 'throw', 'pause', 'pause with cleanup error'])('cleans up onl
|
||||
"if ((await tools.check_held_keys({})).join(',') !== 'w') throw Error('lost W');",
|
||||
ending === 'throw' ? "throw Error('program failed');" : "return 'done';",
|
||||
].join('\n')
|
||||
const result = await executeModelToolFixture(f.ctx, { agent: f.handle.agent, callId: ToolCallId('keyboard-run'),
|
||||
name: 'run_code', arguments: { code, description: 'Exercise held keys' }, signal: controller.signal })
|
||||
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')
|
||||
})
|
||||
|
||||
it.each(['running', 'settling'] as const)('awaits held-key cleanup before unloading native resources while the raw program is %s', async (phase) => {
|
||||
const f = await setup(undefined, true)
|
||||
await selectApplication(f)
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const programRelease: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const cleanupEntered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const cleanupRelease: PromiseWithResolvers<void> = 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({}); return 'finished';",
|
||||
'Hold a key during provider unload', controller.signal).then((result) => { settled = true; return result })
|
||||
let closing: Promise<void> | 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('closes the native connection after a held-key cleanup failure and reuses that failure at program settlement', async () => {
|
||||
const f = await setup(undefined, true)
|
||||
await selectApplication(f)
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const programRelease: PromiseWithResolvers<void> = 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 }
|
||||
})
|
||||
|
||||
it('rejects a relative helper path before publishing computer-use operations', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
@@ -1148,7 +1270,7 @@ it.each([true, false])('uses the declared systemPointer capability for a non-mac
|
||||
await f.provider.dispose()
|
||||
await f.ctx.plugin({ name: 'fixture-window-provider', inject: NativeProvider.inject, apply(ctx: Context) {
|
||||
installCua(ctx, CuaConfig(config), {
|
||||
helperPath: config.helperPath, createChannel: native.connect, guidance: COMMON_GUIDANCE,
|
||||
helperPath: config.helperPath, createChannel: native.connect, getGuidance: () => COMMON_GUIDANCE,
|
||||
permissionParameters: () => ({}),
|
||||
capabilities: { platform: 'fixture', methods: ['getApp', 'getCapabilities', 'mouseMove'], systemPointer,
|
||||
appLevelAccessibility: true, keyboard: ['app'], coordinateSpace: 'screenshot-pixels', browser: false },
|
||||
|
||||
@@ -9,20 +9,20 @@
|
||||
en: 00f8b591b74dfba6
|
||||
zh: e928ab13be2eebfa
|
||||
/deepseek-ai-dsh-cua/summary:
|
||||
en: 2ee2024dfc558d86
|
||||
zh: c3b5661be12923c4
|
||||
en: 23eb2a4f1cb71986
|
||||
zh: 62e2bec7155ed063
|
||||
/deepseek-ai-dsh-cua/table-of-contents:
|
||||
en: 5db4d4fea25493b9
|
||||
zh: 65ab64fc24eb0d09
|
||||
/deepseek-ai-dsh-cua/use-this-package:
|
||||
en: a16d6b7e0d6d13a1
|
||||
zh: a3fb53cffc92b706
|
||||
en: 8ca39a733b479dd3
|
||||
zh: 582c86bd18ef56fd
|
||||
/deepseek-ai-dsh-cua/use-this-package/permission-controls:
|
||||
en: d92d5948a7941e8d
|
||||
zh: d43491ae6521b87e
|
||||
en: 8941f2139fd1ca3a
|
||||
zh: 4c8fb953d821eaf1
|
||||
/deepseek-ai-dsh-cua/understand-the-implementation:
|
||||
en: a106924b505ff8b0
|
||||
zh: ad4fc148ef65e0e7
|
||||
en: d4393c136eba0fc6
|
||||
zh: 2f627de9d9c8fab4
|
||||
/deepseek-ai-dsh-cua/further-exploration:
|
||||
en: c174fb5a00ea3681
|
||||
zh: 039340042676881d
|
||||
@@ -33,17 +33,17 @@
|
||||
en: 0faf1e4d409d61aa
|
||||
zh: 1866dd0b702f2a26
|
||||
/deepseek-ai-dsh-cua/model-experience/authorized-application-operations/what-the-model-sees:
|
||||
en: 4f90c4a6b121bce0
|
||||
zh: c36ab4b80985c76e
|
||||
en: b613371a761f0ab8
|
||||
zh: 826a85089ee3518c
|
||||
/deepseek-ai-dsh-cua/model-experience/authorized-application-operations/token-effect:
|
||||
en: 88463f0304c207bd
|
||||
zh: 6d3ae2f1b8e45747
|
||||
en: 602a4ad8d6709512
|
||||
zh: de7ef79cc1abb442
|
||||
/deepseek-ai-dsh-cua/model-experience/authorized-application-operations/kv-cache-effect:
|
||||
en: 2d5df52dafa1d940
|
||||
zh: 06e815759b9150c3
|
||||
/deepseek-ai-dsh-cua/known-limitations-and-deferred-work:
|
||||
en: c2006a1c7bda783e
|
||||
zh: d018cd66d0ecbf7c
|
||||
en: 038cdfe9432c7979
|
||||
zh: cb48131a2f71b12b
|
||||
/deepseek-ai-dsh-cua/known-limitations-and-deferred-work/dev-note:
|
||||
en: 0a1253c6f7b5e8b9
|
||||
zh: 9f56528562c7c914
|
||||
@@ -11,7 +11,7 @@ Providers install the app/window object API with `installCua`; callers connect t
|
||||
|
||||
## Summary
|
||||
|
||||
Inspect and operate applications through retained objects: select an application, read its accessibility tree, capture explicit windows, and dispatch authorized input. Platform providers supply native execution; this library owns the object API, request validation, application consent, and image admission. The external PTC runtime owns variable persistence.
|
||||
Inspect and operate applications through retained objects: select an application, read its accessibility tree, capture explicit windows, and dispatch authorized input. Standard, Creator, and other non-PTC presets use `cua_run_code` with an automatically available `cua` object. Persistent PTC uses explicit bridge initialization. Platform providers supply native execution; CUA owns consent and image admission.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -31,9 +31,17 @@ Application consent supplies English, Chinese, and Japanese display text from `s
|
||||
|
||||
Mount the [macOS provider](../cua-macos/README.md) to enable native operations on macOS. External PTC hosts import `connectCua` from `@deepseek-ai/dsh-cua/bridge` and supply the current `tools.cua` binding. Source compositions and native preparation belong to the provider.
|
||||
|
||||
`cua_run_code` runs TypeScript in a separate persistent Node environment for each Agent. The global `cua` object is available before the program starts; `tools` contains only `cua`. Call ordinary tools directly outside the program. Use top-level `await` and a final expression for the result; top-level `return` is invalid. The tool accepts the same timeout and sandbox controls as `run_code`. A restarted runtime automatically recreates `cua`, but other variables and selected application objects must be created again.
|
||||
|
||||
Configure runtime resources and launch settings through the provider's `standaloneRunCode.runtime` and program call limits through `standaloneRunCode.executor`. Runtime execution is fixed to `persistent-in-memory`; setting `executionMode` or `scriptPersistence` there is rejected. These settings do not change the profile's shared PTC runtime.
|
||||
|
||||
Raw `cua` registration uses the base CUA services and preset selection, independently of the private Node runtime and program-only `workingDirectory` dependency. Other presets receive `cua_run_code` only while its program services are available. Only program-mode Agent creation awaits private startup and reports its failures. Correct invalid settings and explicitly reload a failed plugin; restoring a missing dependency resumes a pending plugin. `agentPreset: false` registers raw `cua` globally without creating the private runtime.
|
||||
|
||||
`cua` is installed once when its environment is created. Do not overwrite this global. To rebuild a damaged environment, run `process.exit(0)` in `cua_run_code`; that call reports a process-exit failure. The next call starts a fresh environment and restores `cua`. Recreate other variables and select applications and windows again.
|
||||
|
||||
Use `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` returns the object without a native request; window operations reject closed or foreign windows. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. App and window reads accept `maxElements` and `maxDepth` independently. Omitted limits use the provider configuration. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings.
|
||||
|
||||
Keyboard methods are available in the scopes a provider declares; the provider owns how input is delivered within each scope. A lost connection invalidates its handles and coordinates. Failed cleanup is reported before that connection is retired; select the application again and inspect fresh state, because earlier input may have partially executed. Screenshot image errors retain the failing stage and attachment error code. Invalid request arguments reject before dispatch with a readable method, parameter and requirement.
|
||||
Keyboard methods are available in the scopes a provider declares; the provider owns how input is delivered within each scope. A lost connection invalidates its handles and coordinates. Cleanup failures are reported and the connection is not reused; select the application again and inspect fresh state, because earlier input may have partially executed. Screenshot image errors retain the failing stage and attachment error code. Invalid request arguments reject before dispatch with a readable method, parameter and requirement.
|
||||
|
||||
Observation methods emit and return their result. Use `void await app.getAccessibilityTree()` for one visible copy, or use `emit:false` and print the returned text once. `window.getScreenshot()` returns `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink.
|
||||
|
||||
@@ -57,7 +65,7 @@ The page refreshes on entry, window focus, and completed actions. Query failures
|
||||
|
||||
System-permission operations affect the computer running DSH. When accessing DSH remotely, complete authorization on that computer.
|
||||
|
||||
Enabling from the plugin list or detail page shows setup guidance when system permissions need attention, with **Later** and **Open settings** actions. The detail page provides **Set to PTC** under **Default mode for new sessions**; only this action saves the default. Existing sessions keep their preset. **Use persistent mode** in the **PTC execution mode** row separately enables `ptc-runtime.scriptPersistence` when Script mode is selected; otherwise it saves `ptc-runtime.executionMode: persistent-in-memory`. Switching reloads the shared PTC runtime and may interrupt an active call; subsequent calls retain variables and application objects in memory. Already-persistent runtimes show a disabled **Persistent mode enabled** button.
|
||||
Enabling from the plugin list or detail page shows setup guidance when system permissions need attention, with **Later** and **Open settings** actions. Computer Use works in Standard, Creator, and PTC modes. The detail page provides **Set to PTC** under **Default mode for new sessions**; only this action saves the default. Existing sessions keep their preset. **Use persistent mode** in the **PTC execution mode** row separately enables `ptc-runtime.scriptPersistence` when Script mode is selected; otherwise it saves `ptc-runtime.executionMode: persistent-in-memory`. Switching reloads the shared PTC runtime and may interrupt an active call; subsequent calls retain variables and application objects in memory. Already-persistent runtimes show a disabled **Persistent mode enabled** button. Other presets retain their CUA program state separately and do not depend on this setting.
|
||||
|
||||
The page lists always-allowed applications and refusals from any session. A refusal in one session does not cancel another session’s grant or prevent a new session from asking. Session-only grants remain effective within their sessions and are omitted from this page. **Revoke** removes the selected application's access and cancels affected work. Input already delivered to an application cannot be undone; observe the application before any further action. **Allow asking again** clears that application’s refusal records across all sessions; the next application selection still requires a new decision.
|
||||
|
||||
@@ -83,9 +91,17 @@ Grant executable paths are optional display metadata. Missing paths omit the too
|
||||
|
||||
The permission Remote also exposes `ptcConfiguration()` and `enablePersistentPtc()` for the detail-page runtime setting. Reads inspect the existing runtime and editable profile entry. Explicit writes obtain execution settings from the Node provider's `resolvePersistentExecution` helper and use `configEditor.edit()` to preserve other fields and apply normal Loader reload; an already-persistent runtime is left intact. CUA declares the Node provider as a peer so these settings follow the installed provider version. This setting is separate from system and application authorization.
|
||||
|
||||
The provider calls [installCua](src/index.ts) with its prepared helper, connection factory, guidance, and startup capabilities. [NativeClient](src/native-client.ts) owns request correlation, byte limits, cancellation acknowledgement, and failure settlement. The platform connector owns startup and connection cleanup. Its typed startup failures preserve their code and diagnostic through request writes and connection shutdown. The shared executor retains one connection per Agent and joins in-flight image writes during disposal.
|
||||
The provider calls [installCua](src/index.ts) with its prepared helper, connection factory, guidance callback, and startup capabilities. [NativeClient](src/native-client.ts) owns request correlation, byte limits, cancellation acknowledgement, and failure settlement. The platform connector owns startup and connection cleanup. Its typed startup failures preserve their code and diagnostic through request writes and connection shutdown. The shared executor retains one connection per Agent and joins in-flight image writes during disposal.
|
||||
|
||||
`agentPreset` defaults to `ptc`, restricting tools and guidance to Agents bound to that preset. The provider uses the existing `agent/created` and `agent-preset/selected` events and Agent-owned scopes, including Agents already present when it loads. Provider unload and Agent disposal release those registrations. Preset definitions may register after the provider; a preset name filters bound Agents and supplies no tools until a matching Agent exists. Set `agentPreset: false` for global registration in standalone compositions without presets. The Host continues to own permissions, native connections and cancellation; preset definitions remain unchanged.
|
||||
Providers implement `CuaBackend.getGuidance(kind)` with `kind: 'raw' | 'standalone'`. Return the operation instructions for raw `cua` calls or `cua_run_code` programs respectively; both kinds may return the same text. Shared CUA applies the same capability-specific permission guidance, configured AX read defaults, and maximum click hold to both results.
|
||||
|
||||
Providers register connection-owned resource cleanup with `NativeClient.registerCleanup(cleanup)`; the returned disposer unregisters it. While the connection can send requests, the callback receives `canRequest: true` and uses `requestCleanup()` for native cleanup, awaiting its acknowledgement before returning. After forced closure, `canRequest: false` allows local cleanup only. Each resource reuses one cached cleanup Promise when program settlement and connection shutdown both request cleanup.
|
||||
|
||||
Graceful connection closure waits for registered cleanup. Native cleanup refusal or expiry invalidates the connection and its handles; cleanup failures remain visible while connection disposal proceeds. Ordinary native-request timeouts still request cancellation and wait for acknowledgement within `graceMs`. Provider unload drains its owned CUA programs; PTC programs using raw `cua` may continue unrelated work after their held input is released.
|
||||
|
||||
`agentPreset` defaults to `ptc`: matching Agents receive the raw `cua` tool and PTC guidance; every other composed preset receives only `cua_run_code` and its guidance. This includes Standard, Creator, Minimal, and custom presets. A base owner uses `agent/created`, `agent-preset/selected`, and Agent-owned scopes, including Agents already present when the provider loads. It replaces each tool and prompt pair synchronously by definition identity; unavailable program services withdraw only the program definition, leaving raw registrations intact. Agent disposal removes its registrations and releases its retained environment. Provider unload also disposes the dedicated CUA runtime. Agents without a composed preset receive neither tool. Set `agentPreset: false` to register the raw `cua` tool globally in standalone compositions. The Host owns permissions, native connections, and cancellation; preset definitions remain unchanged.
|
||||
|
||||
`cua_run_code` reuses the PTC program-tool factory with one isolated Node runtime owned by the CUA provider. Each Agent has a separate retained process selected by its `stateOwner`. CUA registers an environment initializer on that runtime; it installs `cua` once per new process, including temporary escalated runs. Its owner depends only on the runtime and retains the registration while program-tool dependencies reload. Program tools are disposed and drained before the initializer unregisters and the runtime closes. The factory binds only the private `cua` operation tool and preserves nested policy checks, guards, logs, cancellation, and screenshot delivery. The private tool is absent from the model's direct tool list.
|
||||
|
||||
[The operation schema](src/protocol.ts) is the authority for model parameters and Host-supplied request fields. [Native observations](src/native-observation.ts) decode private window reply fields before updating coordinates and returning public results. Native implementations enforce target identity, window geometry, resource limits, and operating-system access at execution. The permission store owns durable consent separately from the native protocol.
|
||||
|
||||
@@ -122,11 +138,11 @@ The detail page reads the effective default (`selectedDefault ?? default`) from
|
||||
|
||||
#### What the model sees
|
||||
|
||||
Platform providers mount the shared `cua` tool and supply operating instructions. Calls and observations use the same app/window interface and enter normal Session history. Platform guidance is documented by the [macOS provider](../cua-macos/README.md#model-experience).
|
||||
With the default preset selection, PTC receives `cua` through its existing `run_code` tool and other composed presets receive `cua_run_code`. Its description states: “The global cua object is ready to use; retain application and window objects across calls.” The program binds only `tools.cua`; ordinary tools remain directly callable. Calls and observations use the same app/window interface and enter normal Session history. The Web card shows the program, nested calls, and screenshots. Platform guidance is documented by the [macOS provider](../cua-macos/README.md#model-experience).
|
||||
|
||||
#### Token effect
|
||||
|
||||
Operation results and admitted images add model input. Retained JavaScript objects are not serialized into prompts. Duplicate caller printing can repeat observation text.
|
||||
The selected tool schema and CUA guidance add model input. Program output, operation results, and admitted images add history; only the CUA binding is described inside the program. Retained JavaScript objects are not serialized into prompts. Duplicate caller printing can repeat observation text.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
@@ -138,6 +154,8 @@ Results append to history. Retaining objects does not rewrite previous messages;
|
||||
|
||||
- Conversation decisions have no automatic retention limit or deletion when a conversation is removed. Revocation removes permission, while its generation remains to reject older handles and pending approvals.
|
||||
- Native behavior and desktop validation are platform-owned; consult each provider for supported applications, input restrictions and measured coverage.
|
||||
- `agentPreset` selects one preset ID and does not inspect executors. A custom PTC preset with a different ID receives `tools.cua_run_code` inside its outer `run_code`. The nested program uses the separate CUA environment and `standaloneRunCode` limits; the outer program’s deadline and cancellation still apply. Set `agentPreset` to the custom ID to expose raw `tools.cua` there. Only the matching ID receives the raw form.
|
||||
- `cua_run_code` state is in memory only and is separate from PTC state. Process loss, Agent disposal, or provider unload discards it; application consent remains independently stored.
|
||||
- Persistent variables do not reserve an application across a sequence of operations. Other Agents and the user can change its state. Pointer movement and observations do not restore the previous pointer position; [continuous interaction](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md) uses no cross-call ownership.
|
||||
- Element IDs are opaque strings from the application's current accessibility snapshot. A later read on any window of the same application replaces the current snapshot, so callers must use IDs from the latest tree; an old string may be reused for a different control. Screenshots or pointer input require an explicitly selected window.
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
通过保留对象检查并操作应用:选择应用、读取辅助功能树、截取显式窗口并派发已授权输入。平台提供方负责原生执行;本库负责对象 API、请求校验、应用授权和图像接纳。变量持久性由外部 PTC 运行时负责。
|
||||
通过保留对象检查并操作应用:选择应用、读取辅助功能树、截取显式窗口并派发已授权输入。标准、创造及其他非 PTC preset 使用 `cua_run_code`,其中自动提供 `cua` 对象。持久 PTC 使用显式 bridge 初始化。平台提供方负责原生执行;CUA 负责授权与图像接纳。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -31,9 +31,17 @@ kind: "package-reference"
|
||||
|
||||
挂载 [macOS 提供方](../cua-macos/README.zh.md)以在 macOS 上启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。
|
||||
|
||||
`cua_run_code` 为每个 agent(智能体)在独立的持久 Node 环境中运行 TypeScript。程序开始前即可使用全局 `cua` 对象;`tools` 中只有 `cua`。其他普通工具在程序外直接调用。使用顶层 `await`,以最后一个表达式作为结果;顶层 `return` 无效。工具接受与 `run_code` 相同的超时和沙箱控制参数。运行时重启会自动重建 `cua`,但其他变量和已选择的应用对象需要重新创建。
|
||||
|
||||
通过提供方的 `standaloneRunCode.runtime` 配置运行时资源和启动设置,通过 `standaloneRunCode.executor` 配置程序调用上限。运行时固定使用 `persistent-in-memory`,在其中设置 `executionMode` 或 `scriptPersistence` 会被拒绝。这些设置不改变 profile 的共享 PTC 运行时。
|
||||
|
||||
原始 `cua` 的注册使用基础 CUA 服务和 preset 选择,不依赖私有 Node 运行时,也不依赖仅供程序工具使用的 `workingDirectory`。其他 preset 仅在程序工具所需服务可用时获得 `cua_run_code`。只有创建使用程序形态的 Agent 时,才会等待私有运行时启动并报告其失败。修正无效设置后,显式重载已失败的插件;补齐缺失依赖会使等待中的插件继续启动。`agentPreset: false` 全局注册原始 `cua`,不创建私有运行时。
|
||||
|
||||
`cua` 在创建环境时安装一次。不要覆盖这个全局对象。需要重建损坏的环境时,在 `cua_run_code` 中执行 `process.exit(0)`;该次工具调用会因进程退出而返回失败。下一次调用启动新环境并恢复 `cua`。请重新创建其他变量,并重新选择应用和窗口。
|
||||
|
||||
使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 返回对象时不发送原生请求;窗口操作会拒绝已关闭或属于其他应用的窗口。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。读取应用或窗口时,可以单独传入 `maxElements` 或 `maxDepth`。省略的参数使用当前平台配置。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。
|
||||
|
||||
键盘方法可在 provider 声明的作用域中使用;每个作用域内的输入投递由 provider 负责。连接丢失会使其句柄和坐标失效。清理失败会先报告,再释放该连接;应重新选择应用并读取新状态,因为先前的输入可能已部分执行。截图图像错误会保留失败阶段和附件错误码。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。
|
||||
键盘方法可在 provider 声明的作用域中使用;每个作用域内的输入投递由 provider 负责。连接丢失会使其句柄和坐标失效。清理失败会被报告,该连接不再复用;应重新选择应用并读取新状态,因为先前的输入可能已部分执行。截图图像错误会保留失败阶段和附件错误码。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。
|
||||
|
||||
观察方法会输出并返回结果。使用 `void await app.getAccessibilityTree()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。`window.getScreenshot()` 返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。
|
||||
|
||||
@@ -57,7 +65,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
|
||||
系统权限操作作用于运行 DSH 的电脑。远程访问时,请在该电脑上完成授权。
|
||||
|
||||
从插件列表或详情页启用后,系统权限尚未就绪时会显示设置引导,提供“稍后”和“前往设置”。详情页的“新会话默认模式”提供“设为 PTC”按钮,仅点击此按钮才保存默认值。已有会话保留原 preset。“PTC 执行方式”一行的“设为持久化”在选用 Script 模式时单独启用 `ptc-runtime.scriptPersistence`;其他模式下保存 `ptc-runtime.executionMode: persistent-in-memory`。切换会重载共享 PTC 执行器,可能打断当前调用;后续调用在内存中保留变量和应用对象。已经使用持久化模式时,按钮显示“已设为持久化”并禁用。
|
||||
从插件列表或详情页启用后,系统权限尚未就绪时会显示设置引导,提供“稍后”和“前往设置”。标准、创造和 PTC 模式均可使用 Computer Use。详情页的“新会话默认模式”提供“设为 PTC”按钮,仅点击此按钮才保存默认值。已有会话保留原 preset。“PTC 执行方式”一行的“设为持久化”在选用 Script 模式时单独启用 `ptc-runtime.scriptPersistence`;其他模式下保存 `ptc-runtime.executionMode: persistent-in-memory`。切换会重载共享 PTC 执行器,可能打断当前调用;后续调用在内存中保留变量和应用对象。已经使用持久化模式时,按钮显示“已设为持久化”并禁用。其他 preset 单独保留自己的 CUA 程序状态,不依赖此设置。
|
||||
|
||||
页面展示“始终允许的应用”和“不允许访问的应用”。后者汇总任一会话的拒绝记录,不取消其他会话已有的授权,也不阻止新会话询问授权。会话授权仍在对应会话中生效,详情页不展示这类应用。“撤销”会移除对应应用的访问许可并取消相关操作。已发送到应用的输入无法撤回,继续操作前需重新观察应用。“允许再次询问”清除该应用在所有会话中的拒绝记录;下次选择应用时仍需用户重新决定。
|
||||
|
||||
@@ -83,9 +91,17 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
|
||||
权限 Remote 还通过 `ptcConfiguration()` 和 `enablePersistentPtc()` 支持详情页的执行方式设置。查询读取现有执行器和可编辑的 profile 条目。显式写入从 Node 提供方的 `resolvePersistentExecution` 辅助函数获取执行设置,再用 `configEditor.edit()` 保留其他字段并按正常 Loader 规则重载;已是持久化模式的执行器保持不变。CUA 将 Node 提供方声明为 peer 依赖,使这些设置与已安装的提供方版本一致。此设置独立于系统权限和应用授权。
|
||||
|
||||
提供方将准备好的 helper、连接工厂、指引和启动能力传给 [installCua](src/index.ts)。[NativeClient](src/native-client.ts) 负责请求关联、字节上限、取消确认和失败处理。平台连接器负责启动和连接清理。其带类型的启动失败在请求写入和连接关闭时保留错误码及诊断。共享执行器为每个 Agent 保留一个连接,并在销毁时等待进行中的图像写入。
|
||||
提供方将准备好的 helper、连接工厂、指引回调和启动能力传给 [installCua](src/index.ts)。[NativeClient](src/native-client.ts) 负责请求关联、字节上限、取消确认和失败处理。平台连接器负责启动和连接清理。其带类型的启动失败在请求写入和连接关闭时保留错误码及诊断。共享执行器为每个 Agent 保留一个连接,并在销毁时等待进行中的图像写入。
|
||||
|
||||
`agentPreset` 默认为 `ptc`,将工具和指引限制到绑定该 preset 的 Agent。提供方使用现有 `agent/created`、`agent-preset/selected` 事件及 Agent 拥有的作用域,也处理启用前已存在的 Agent。提供方卸载和 Agent 销毁都会释放这些注册。preset 定义可以晚于提供方注册;名称用于筛选已绑定的 Agent,在匹配的 Agent 出现前不提供工具。不使用 preset 的独立组合可设置 `agentPreset: false` 来全局注册。Host 仍拥有权限、本机连接和取消操作,preset 定义保持不变。
|
||||
提供方实现 `CuaBackend.getGuidance(kind)`,其中 `kind: 'raw' | 'standalone'`,分别返回原始 `cua` 调用和 `cua_run_code` 程序的操作指引;两种形态可以返回相同文本。共享 CUA 为两份结果统一补充对应能力的权限指引、配置的 AX 读取默认值和最大点击按住时长。
|
||||
|
||||
提供方通过 `NativeClient.registerCleanup(cleanup)` 注册归连接所有的资源清理;返回的 disposer 用于注销回调。连接仍可发送请求时,回调收到 `canRequest: true`,通过 `requestCleanup()` 执行原生清理,并等待确认后返回。连接被强制关闭后,`canRequest: false` 只允许清理本地状态。程序结束和连接关闭都触发清理时,每项资源复用同一个已缓存的清理 Promise。
|
||||
|
||||
正常关闭连接会等待已注册的清理结束。原生清理被拒绝或超时会使连接及其句柄失效;连接释放仍会继续,清理失败也会被报告。普通原生请求超时仍然请求取消,并在 `graceMs` 内等待确认。提供方卸载会等待自己持有的 CUA 程序结束;使用原始 `cua` 的 PTC 程序可在释放其持有的输入后继续其他工作。
|
||||
|
||||
`agentPreset` 默认为 `ptc`:匹配的 Agent 获得原始 `cua` 工具和 PTC 指引,其他已组合的 preset 只获得 `cua_run_code` 及其指引,包括标准、创造、极简和自定义 preset。基础注册的所有者使用 `agent/created`、`agent-preset/selected` 事件和 Agent 自有作用域,也处理提供方加载前已存在的 Agent。它按定义对象的身份同步替换每组工具及提示词;程序服务不可用时只撤回程序工具定义,保留原始工具的注册。Agent 销毁会移除其注册并释放保留环境,提供方卸载还会释放专用 CUA 运行时。未组合 preset 的 Agent 不获得这两个工具。在独立组合中设置 `agentPreset: false` 可全局注册原始 `cua` 工具。Host 负责权限、本机连接和取消;preset 定义保持不变。
|
||||
|
||||
`cua_run_code` 复用 PTC 程序工具工厂,由 CUA 提供方持有一个隔离的 Node 运行时。每个 Agent 通过自己的 `stateOwner` 选择独立的保留进程。CUA 在该运行时注册环境初始化程序,为每个新进程安装一次 `cua`,包括临时提权执行。初始化程序的所属作用域只依赖运行时,程序工具的依赖重载时仍保留这项注册。先销毁程序工具并等待其执行结束,再注销初始化程序并关闭运行时。工厂只绑定私有 `cua` 操作工具,保留嵌套策略检查、guard、日志、取消和截图交付。私有工具不会出现在模型可直接调用的工具列表中。
|
||||
|
||||
[操作 schema](src/protocol.ts) 定义模型参数,以及 Host 补充的请求字段。[原生观察](src/native-observation.ts) 解析窗口回复的私有字段,更新坐标记录后返回公开结果。原生实现在执行时检查目标身份、窗口几何、资源上限和操作系统访问条件。授权存储独立于原生协议保存持久许可。
|
||||
|
||||
@@ -122,11 +138,11 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
|
||||
#### 模型可见内容
|
||||
|
||||
平台提供方挂载共享的 `cua` 工具并提供操作指引。调用和观察使用同一套应用与窗口接口,进入正常 Session 历史。平台指引见 [macOS 提供方](../cua-macos/README.zh.md#model-experience)。
|
||||
默认 preset 配置下,PTC 通过已有 `run_code` 工具获得 `cua`,其他已组合的 preset 获得 `cua_run_code`。其描述说明:“The global cua object is ready to use; retain application and window objects across calls.” 程序只绑定 `tools.cua`,普通工具仍可直接调用。调用和观察使用同一套应用与窗口接口,进入正常 Session 历史。Web 卡片显示程序、嵌套调用和截图。平台指引见 [macOS 提供方](../cua-macos/README.zh.md#model-experience)。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
操作结果和接纳的图像增加模型输入。保留的 JavaScript 对象不会序列化进提示词。调用方重复打印会重复观察文本。
|
||||
选用的工具 schema 和 CUA 指引增加模型输入。程序输出、操作结果和接纳的图像增加历史;程序内只描述 CUA 绑定。保留的 JavaScript 对象不会序列化进提示词。调用方重复打印会重复观察文本。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
@@ -138,6 +154,8 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
|
||||
- 会话决定没有自动保留期限,也不会随对话删除而自动清理。撤销会移除许可,但保留撤销代次,用于拒绝旧句柄和先前尚未完成的审批。
|
||||
- 原生行为和桌面验证由各平台负责;支持的应用、输入限制和实测覆盖范围见对应提供方文档。
|
||||
- `agentPreset` 选择一个 preset ID,不检测执行器。ID 不匹配的自定义 PTC preset 会在外层 `run_code` 中获得 `tools.cua_run_code`。嵌套程序使用独立的 CUA 环境和 `standaloneRunCode` 上限,同时仍受外层程序的截止时间和取消约束。将 `agentPreset` 设为该自定义 ID,可在其中使用原始 `tools.cua`;只有匹配的 ID 获得原始形态。
|
||||
- `cua_run_code` 状态仅保存在内存中,且独立于 PTC 状态。进程丢失、Agent 销毁或提供方卸载都会丢弃它;应用授权仍独立保存。
|
||||
- 持久变量不会在一组连续操作期间独占应用。其他 Agent 和用户可能改变其状态。指针移动和观察不恢复先前的鼠标位置;[连续交互](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)不分配跨调用所有权。
|
||||
- 元素 ID 是应用当前辅助功能快照中的不透明字符串。之后读取同一应用的任一窗口会替换当前快照,因此调用方必须使用最新树中的 ID;旧字符串可能被复用于另一个控件。截图或指针输入要求显式选择窗口。
|
||||
|
||||
|
||||
@@ -99,7 +99,8 @@
|
||||
"@deepseek-ai/dsh-user-questions": "workspace:*",
|
||||
"@deepseek-ai/dsh-attachment": "workspace:*",
|
||||
"@deepseek-ai/dsh-scope": "workspace:*",
|
||||
"@deepseek-ai/dsh-ptc-runtime-node": "workspace:*"
|
||||
"@deepseek-ai/dsh-ptc-runtime-node": "workspace:*",
|
||||
"@deepseek-ai/dsh-tool-executor-ptc": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "workspace:~",
|
||||
@@ -111,6 +112,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-working-directory": "workspace:*",
|
||||
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
|
||||
"@deepseek-ai/dsh-tool-executor-ptc": "workspace:*",
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/cordis-plugin-include": "workspace:~",
|
||||
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
|
||||
|
||||
@@ -17,17 +17,17 @@ export const en = {
|
||||
windowsCapture: 'Window capture', available: 'Available', unavailable: 'Unavailable', locked: 'Locked or disconnected',
|
||||
elevated: 'The native component is running with administrator privileges.', standardPrivileges: 'The native component is running with standard user privileges.',
|
||||
setupTitle: 'Set up computer use before use',
|
||||
setupBody: 'computer use is enabled. Before using it, switch to PTC mode and grant Accessibility and Screen Recording permissions. Open the plugin details to complete setup.',
|
||||
setupBody: 'Computer use is enabled. Before using it, grant Accessibility and Screen Recording permissions. Open the plugin details to complete setup.',
|
||||
setupQueryFailed: 'computer use is enabled, but system permissions could not be checked. Open the plugin details to see the error and retry.',
|
||||
defaultTitle: 'Default mode for new sessions',
|
||||
defaultBody: 'Computer use is available only in PTC mode.',
|
||||
defaultBody: 'Computer use is available in Standard, Creator, and PTC modes. Choose PTC here to make it the default for new sessions.',
|
||||
defaultConfirm: 'Set to PTC', defaultSet: 'PTC is the default',
|
||||
defaultUnavailable: 'Could not read the default mode. Check it in Settings.',
|
||||
defaultReadOnly: 'Default-mode settings are read-only.',
|
||||
defaultNotSaved: 'The default mode was not saved. Try again.',
|
||||
defaultFailed: 'Could not change the default mode: {message}',
|
||||
persistentTitle: 'PTC execution mode',
|
||||
persistentBody: 'Keep variables and application objects across tool calls. Switching restarts the PTC runtime.',
|
||||
persistentBody: 'Keep variables and application objects across PTC tool calls. Switching restarts the PTC runtime. Other modes always keep their computer use state separately.',
|
||||
persistentConfirm: 'Use persistent mode', persistentSet: 'Persistent mode enabled',
|
||||
persistentUnavailable: 'Could not read the PTC execution mode. Check it in Settings.',
|
||||
persistentReadOnly: 'PTC execution settings are read-only.',
|
||||
@@ -56,7 +56,7 @@ export const zh: Record<CuaPermissionLocaleKey, string> = {
|
||||
approvalRiskTitle: 'Computer Use 风险提示',
|
||||
approvalRiskNotice: '智能体只能访问你已授权的应用,并可在后台读取应用内容、操作应用。\n\n网络游戏、即时通讯等应用可能对自动化操作有所限制。违反相关规则可能导致你在该应用中的账号被暂停使用或封禁。\n\n请自行承担使用风险。如需停止自动化操作,可随时点击 DeepSeek Harness 中的停止按钮。',
|
||||
title: '给 Computer Use 授权', applicationsTitle: '管理 Computer Use 可访问的应用', setupTitle: '使用 Computer Use 前需要设置',
|
||||
setupBody: 'Computer Use 插件已开启。使用前请切换到 PTC 模式,并授予辅助功能和屏幕录制权限。请前往插件详情页完成设置。',
|
||||
setupBody: 'Computer Use 插件已开启。使用前请授予辅助功能和屏幕录制权限。请前往插件详情页完成设置。',
|
||||
setupQueryFailed: 'Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。',
|
||||
windowsSetupTitle: '检查 Windows 桌面访问状态',
|
||||
windowsSetupBody: '请解锁 Windows 桌面,然后重新检测。DSH 会在访问每个应用前询问授权。',
|
||||
@@ -68,14 +68,14 @@ export const zh: Record<CuaPermissionLocaleKey, string> = {
|
||||
windowsCapture: '窗口截图', available: '可用', unavailable: '不可用', locked: '已锁定或断开连接',
|
||||
elevated: '本机组件正以管理员权限运行。', standardPrivileges: '本机组件正以普通用户权限运行。',
|
||||
defaultTitle: '新会话默认模式',
|
||||
defaultBody: 'Computer Use 仅在 PTC 模式中可用。',
|
||||
defaultBody: '标准、创造和 PTC 模式均可使用 Computer Use。在此选择 PTC,可将其设为新会话的默认模式',
|
||||
defaultConfirm: '设为 PTC', defaultSet: '已设为 PTC',
|
||||
defaultUnavailable: '无法读取默认模式,请在设置中检查',
|
||||
defaultReadOnly: '默认模式设置为只读',
|
||||
defaultNotSaved: '默认模式未保存,请重试',
|
||||
defaultFailed: '无法切换默认模式:{message}',
|
||||
persistentTitle: 'PTC 执行方式',
|
||||
persistentBody: '跨工具调用保留变量和应用对象。切换会重启 PTC 执行器。',
|
||||
persistentBody: '跨 PTC 工具调用保留变量和应用对象。切换会重启 PTC 运行时。其他模式始终单独保留 Computer Use 状态。',
|
||||
persistentConfirm: '设为持久化', persistentSet: '已设为持久化',
|
||||
persistentUnavailable: '无法读取 PTC 执行方式,请在设置中检查',
|
||||
persistentReadOnly: 'PTC 执行方式设置为只读',
|
||||
@@ -117,10 +117,10 @@ export const ja = {
|
||||
'title': 'コンピュータ操作を承認',
|
||||
'applicationsTitle': 'Computer Useがアクセスできるアプリを管理',
|
||||
'setupTitle': '使用前にComputer Useを設定',
|
||||
'setupBody': 'Computer Useは有効です。使用する前にPTCモードに切り替え、アクセシビリティと画面収録の権限を許可してください。セットアップを完了するにはプラグインの詳細を開いてください。',
|
||||
'setupBody': 'Computer Use は有効です。使用前にアクセシビリティと画面収録の権限を許可してください。プラグインの詳細を開いて設定を完了してください。',
|
||||
'setupQueryFailed': 'Computer Useは有効ですが、システム権限を確認できませんでした。プラグインの詳細を開いてエラーを確認し、再試行してください。',
|
||||
'defaultTitle': '新規セッションのデフォルトモード',
|
||||
'defaultBody': 'Computer UseはPTCモードでのみ利用できます。',
|
||||
'defaultBody': 'Computer Use は標準、クリエイター、PTC モードで利用できます。ここで PTC を選ぶと、新しいセッションの既定のモードになります。',
|
||||
'defaultConfirm': 'PTCに設定',
|
||||
'defaultSet': 'PTCがデフォルトです',
|
||||
'defaultUnavailable': 'デフォルトモードを読み取れませんでした。設定で確認してください。',
|
||||
@@ -128,7 +128,7 @@ export const ja = {
|
||||
'defaultNotSaved': 'デフォルトモードは保存されませんでした。もう一度お試しください。',
|
||||
'defaultFailed': 'デフォルトモードを変更できませんでした: {message}',
|
||||
'persistentTitle': 'PTC実行モード',
|
||||
'persistentBody': 'ツール呼び出し間で変数とアプリケーションオブジェクトを保持します。切り替えるとPTCランタイムが再起動します。',
|
||||
'persistentBody': 'PTC のツール呼び出し間で変数とアプリケーションオブジェクトを保持します。切り替えると PTC ランタイムが再起動します。他のモードでは Computer Use の状態が常に別に保持されます。',
|
||||
'persistentConfirm': '永続モードを使用',
|
||||
'persistentSet': '永続モードが有効になりました',
|
||||
'persistentUnavailable': 'PTC実行モードを読み取れませんでした。設定で確認してください。',
|
||||
@@ -187,17 +187,17 @@ export const es = {
|
||||
title: 'Autorizar el uso de la computadora',
|
||||
applicationsTitle: 'Administrar aplicaciones a las que puede acceder el uso de la computadora',
|
||||
setupTitle: 'Configurar el uso de la computadora antes de usarla',
|
||||
setupBody: 'El uso de la computadora está habilitado. Antes de usarlo, cambie al modo PTC y otorgue permisos de Accesibilidad y Grabación de pantalla. Abra los detalles del complemento para completar la configuración.',
|
||||
setupBody: 'El uso de la computadora está habilitado. Antes de usarlo, otorgue permisos de Accesibilidad y Grabación de pantalla. Abra los detalles del complemento para completar la configuración.',
|
||||
setupQueryFailed: 'El uso de la computadora está habilitado, pero no se pudieron verificar los permisos del sistema. Abra los detalles del complemento para ver el error y vuelva a intentarlo.',
|
||||
defaultTitle: 'Modo predeterminado para nuevas sesiones',
|
||||
defaultBody: 'El uso de la computadora está disponible solo en el modo PTC.',
|
||||
defaultBody: 'El uso de la computadora está disponible en los modos estándar, creador y PTC. Elija PTC aquí para establecerlo como modo predeterminado para las nuevas sesiones.',
|
||||
defaultConfirm: 'Establecer en PTC', defaultSet: 'PTC es el valor predeterminado',
|
||||
defaultUnavailable: 'No se pudo leer el modo predeterminado. Compruébalo en Configuración.',
|
||||
defaultReadOnly: 'La configuración del modo predeterminado es de sólo lectura.',
|
||||
defaultNotSaved: 'El modo predeterminado no se guardó. Intentar otra vez.',
|
||||
defaultFailed: 'No se pudo cambiar el modo predeterminado: {message}',
|
||||
persistentTitle: 'Modo de ejecución PTC',
|
||||
persistentBody: 'Mantenga variables y objetos de aplicación en todas las llamadas a herramientas. El cambio reinicia el tiempo de ejecución PTC.',
|
||||
persistentBody: 'Mantenga variables y objetos de aplicación entre llamadas a herramientas de PTC. El cambio reinicia el entorno de ejecución de PTC. Los demás modos siempre mantienen por separado su estado de uso de la computadora.',
|
||||
persistentConfirm: 'Usar modo persistente', persistentSet: 'Modo persistente habilitado',
|
||||
persistentUnavailable: 'No se pudo leer el modo de ejecución PTC. Compruébalo en Configuración.',
|
||||
persistentReadOnly: 'La configuración de ejecución de PTC es de solo lectura.',
|
||||
@@ -241,17 +241,17 @@ export const fr = {
|
||||
title: "Autoriser l'utilisation de l'ordinateur",
|
||||
applicationsTitle: "Gérer les applications auxquelles l'ordinateur peut accéder",
|
||||
setupTitle: "Configurer l'utilisation de l'ordinateur avant utilisation",
|
||||
setupBody: "L'utilisation de l'ordinateur est autorisée. Avant de l'utiliser, passez en mode PTC et accordez les autorisations d'accessibilité et d'enregistrement d'écran. Ouvrez les détails du plugin pour terminer la configuration.",
|
||||
setupBody: "L'utilisation de l'ordinateur est activée. Avant de l'utiliser, accordez les autorisations d'accessibilité et d'enregistrement d'écran. Ouvrez les détails du plugin pour terminer la configuration.",
|
||||
setupQueryFailed: "L'utilisation de l'ordinateur est activée, mais les autorisations système n'ont pas pu être vérifiées. Ouvrez les détails du plugin pour voir l'erreur et réessayez.",
|
||||
defaultTitle: 'Mode par défaut pour les nouvelles sessions',
|
||||
defaultBody: "L'utilisation de l'ordinateur est disponible uniquement en mode PTC.",
|
||||
defaultBody: "L'utilisation de l'ordinateur est disponible dans les modes standard, créateur et PTC. Choisissez PTC ici pour en faire le mode par défaut des nouvelles sessions.",
|
||||
defaultConfirm: 'Réglé sur PTC', defaultSet: 'PTC est la valeur par défaut',
|
||||
defaultUnavailable: 'Impossible de lire le mode par défaut. Vérifiez-le dans Paramètres.',
|
||||
defaultReadOnly: 'Les paramètres du mode par défaut sont en lecture seule.',
|
||||
defaultNotSaved: "Le mode par défaut n'a pas été enregistré. Essayer à nouveau.",
|
||||
defaultFailed: 'Impossible de modifier le mode par défaut : {message}',
|
||||
persistentTitle: "Mode d'exécution PTC",
|
||||
persistentBody: 'Conservez les variables et les objets d’application lors des appels d’outils. La commutation redémarre le runtime PTC.',
|
||||
persistentBody: "Conservez les variables et les objets d'application entre les appels d'outils PTC. Le changement redémarre le runtime PTC. Les autres modes conservent toujours séparément leur état d'utilisation de l'ordinateur.",
|
||||
persistentConfirm: 'Utiliser le mode persistant', persistentSet: 'Mode persistant activé',
|
||||
persistentUnavailable: "Impossible de lire le mode d'exécution PTC. Vérifiez-le dans Paramètres.",
|
||||
persistentReadOnly: "Les paramètres d'exécution PTC sont en lecture seule.",
|
||||
@@ -295,17 +295,17 @@ export const de = {
|
||||
title: 'Autorisieren Sie die Computernutzung',
|
||||
applicationsTitle: 'Verwalten Sie Anwendungen, auf die der Computer zugreifen kann',
|
||||
setupTitle: 'Richten Sie die Computernutzung vor der Nutzung ein',
|
||||
setupBody: 'Die Computernutzung ist aktiviert. Wechseln Sie vor der Verwendung in den PTC-Modus und erteilen Sie die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung. Öffnen Sie die Plugin-Details, um die Einrichtung abzuschließen.',
|
||||
setupBody: 'Die Computernutzung ist aktiviert. Erteilen Sie vor der Verwendung die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung. Öffnen Sie die Plugin-Details, um die Einrichtung abzuschließen.',
|
||||
setupQueryFailed: 'Die Computernutzung ist aktiviert, aber die Systemberechtigungen konnten nicht überprüft werden. Öffnen Sie die Plugin-Details, um den Fehler anzuzeigen, und versuchen Sie es erneut.',
|
||||
defaultTitle: 'Standardmodus für neue Sitzungen',
|
||||
defaultBody: 'Die Computernutzung ist nur im PTC-Modus verfügbar.',
|
||||
defaultBody: 'Die Computernutzung ist im Standardmodus, Erstellermodus und PTC-Modus verfügbar. Wählen Sie hier PTC als Standard für neue Sitzungen.',
|
||||
defaultConfirm: 'Auf PTC setzen', defaultSet: 'PTC ist die Standardeinstellung',
|
||||
defaultUnavailable: 'Der Standardmodus konnte nicht gelesen werden. Überprüfen Sie es in den Einstellungen.',
|
||||
defaultReadOnly: 'Die Standardmoduseinstellungen sind schreibgeschützt.',
|
||||
defaultNotSaved: 'Der Standardmodus wurde nicht gespeichert. Versuchen Sie es erneut.',
|
||||
defaultFailed: 'Der Standardmodus konnte nicht geändert werden: {message}',
|
||||
persistentTitle: 'PTC Ausführungsmodus',
|
||||
persistentBody: 'Behalten Sie Variablen und Anwendungsobjekte über Werkzeugaufrufe hinweg bei. Durch den Wechsel wird die PTC-Laufzeit neu gestartet.',
|
||||
persistentBody: 'Behalten Sie Variablen und Anwendungsobjekte über PTC-Werkzeugaufrufe hinweg bei. Durch den Wechsel wird die PTC-Laufzeit neu gestartet. Andere Modi behalten ihren Zustand für die Computernutzung immer getrennt bei.',
|
||||
persistentConfirm: 'Verwenden Sie den persistenten Modus', persistentSet: 'Persistenter Modus aktiviert',
|
||||
persistentUnavailable: 'Der PTC-Ausführungsmodus konnte nicht gelesen werden. Überprüfen Sie es in den Einstellungen.',
|
||||
persistentReadOnly: 'Die Ausführungseinstellungen von PTC sind schreibgeschützt.',
|
||||
@@ -349,17 +349,17 @@ export const ru = {
|
||||
title: 'Разрешить использование компьютера',
|
||||
applicationsTitle: 'Управление приложениями, к которым может иметь доступ компьютер',
|
||||
setupTitle: 'Настройте использование компьютера перед использованием',
|
||||
setupBody: 'Использование компьютера разрешено. Прежде чем использовать его, переключитесь в режим PTC и предоставьте разрешения на доступность и запись экрана. Откройте сведения о плагине, чтобы завершить настройку.',
|
||||
setupBody: 'Использование компьютера включено. Перед использованием предоставьте разрешения на универсальный доступ и запись экрана. Откройте сведения о плагине, чтобы завершить настройку.',
|
||||
setupQueryFailed: 'Использование компьютера разрешено, но системные разрешения проверить не удалось. Откройте сведения о плагине, чтобы увидеть ошибку, и повторите попытку.',
|
||||
defaultTitle: 'Режим по умолчанию для новых сеансов',
|
||||
defaultBody: 'Использование компьютера доступно только в режиме PTC.',
|
||||
defaultBody: 'Использование компьютера доступно в стандартном режиме, режиме автора и режиме PTC. Выберите здесь PTC, чтобы использовать его по умолчанию для новых сеансов.',
|
||||
defaultConfirm: 'Установить на PTC', defaultSet: 'PTC — значение по умолчанию.',
|
||||
defaultUnavailable: 'Не удалось прочитать режим по умолчанию. Проверьте это в настройках.',
|
||||
defaultReadOnly: 'Настройки режима по умолчанию доступны только для чтения.',
|
||||
defaultNotSaved: 'Режим по умолчанию не сохранился. Попробуйте еще раз.',
|
||||
defaultFailed: 'Не удалось изменить режим по умолчанию: {message}.',
|
||||
persistentTitle: 'Режим выполнения PTC',
|
||||
persistentBody: 'Сохраняйте переменные и объекты приложения при вызовах инструментов. Переключение перезапускает среду выполнения PTC.',
|
||||
persistentBody: 'Сохраняйте переменные и объекты приложений между вызовами инструментов PTC. Переключение перезапускает среду выполнения PTC. Другие режимы всегда сохраняют состояние управления компьютером отдельно.',
|
||||
persistentConfirm: 'Использовать постоянный режим', persistentSet: 'Постоянный режим включен',
|
||||
persistentUnavailable: 'Не удалось прочитать режим выполнения PTC. Проверьте это в настройках.',
|
||||
persistentReadOnly: 'Настройки выполнения PTC доступны только для чтения.',
|
||||
@@ -403,17 +403,17 @@ export const pt = {
|
||||
title: 'Autorizar o uso do computador',
|
||||
applicationsTitle: 'Gerenciar aplicativos que o computador pode acessar',
|
||||
setupTitle: 'Configure o uso do computador antes de usar',
|
||||
setupBody: 'O uso do computador está habilitado. Antes de usá-lo, alterne para o modo PTC e conceda permissões de acessibilidade e gravação de tela. Abra os detalhes do plugin para concluir a configuração.',
|
||||
setupBody: 'O uso do computador está ativado. Antes de usá-lo, conceda permissões de Acessibilidade e Gravação de tela. Abra os detalhes do plugin para concluir a configuração.',
|
||||
setupQueryFailed: 'O uso do computador está ativado, mas não foi possível verificar as permissões do sistema. Abra os detalhes do plugin para ver o erro e tente novamente.',
|
||||
defaultTitle: 'Modo padrão para novas sessões',
|
||||
defaultBody: 'O uso do computador está disponível somente no modo PTC.',
|
||||
defaultBody: 'O uso do computador está disponível nos modos padrão, criador e PTC. Escolha PTC aqui para defini-lo como padrão para novas sessões.',
|
||||
defaultConfirm: 'Definir como PTC', defaultSet: 'PTC é o padrão',
|
||||
defaultUnavailable: 'Não foi possível ler o modo padrão. Verifique em Configurações.',
|
||||
defaultReadOnly: 'As configurações do modo padrão são somente leitura.',
|
||||
defaultNotSaved: 'O modo padrão não foi salvo. Tente novamente.',
|
||||
defaultFailed: 'Não foi possível alterar o modo padrão: {message}',
|
||||
persistentTitle: 'PTC modo de execução',
|
||||
persistentBody: 'Mantenha variáveis e objetos de aplicação em todas as chamadas de ferramenta. A alternância reinicia o tempo de execução PTC.',
|
||||
persistentBody: 'Mantenha variáveis e objetos de aplicativos entre chamadas de ferramentas PTC. A mudança reinicia o ambiente de execução PTC. Os outros modos sempre mantêm seu estado de uso do computador separadamente.',
|
||||
persistentConfirm: 'Usar modo persistente', persistentSet: 'Modo persistente ativado',
|
||||
persistentUnavailable: 'Não foi possível ler o modo de execução PTC. Verifique em Configurações.',
|
||||
persistentReadOnly: 'PTC configurações de execução são somente leitura.',
|
||||
|
||||
@@ -1,10 +1,33 @@
|
||||
/** Schemastery fields for platform-specific native CUA configuration. */
|
||||
import Schema from '@deepseek-ai/schemastery'
|
||||
import NodePtcRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
import { RunCodeConfig } from '@deepseek-ai/dsh-tool-executor-ptc/run-code'
|
||||
|
||||
/** Resource bounds for the dedicated CUA program runtime and its nested tool calls. */
|
||||
export interface CuaStandaloneRunCodeConfig {
|
||||
/** Node limits and launch settings; setting executionMode or scriptPersistence is rejected. */
|
||||
runtime: Omit<NodeRuntimeConfig, 'executionMode' | 'scriptPersistence'>
|
||||
/** Timeout-scaled tool-call allowance and maximum concurrent subcalls. */
|
||||
executor: RunCodeConfig
|
||||
}
|
||||
|
||||
const runtimeFields: Record<string, Schema> = {
|
||||
...NodePtcRuntime.Config.dict,
|
||||
executionMode: Schema.never().hidden(),
|
||||
scriptPersistence: Schema.never().hidden(),
|
||||
}
|
||||
|
||||
/** Validate CUA program limits with the shared Node and executor defaults. */
|
||||
export const CuaStandaloneRunCodeConfig: Schema<Partial<CuaStandaloneRunCodeConfig>, CuaStandaloneRunCodeConfig> = Schema.object({
|
||||
runtime: Schema.object(runtimeFields).default({}),
|
||||
executor: RunCodeConfig.default({}),
|
||||
})
|
||||
|
||||
/** Shared configuration fields extended by native platform providers. */
|
||||
export const CuaConfigFields = {
|
||||
requireSystemPointerApproval: Schema.boolean().default(true),
|
||||
agentPreset: Schema.union([Schema.string().min(1), Schema.const(false)]).default('ptc'),
|
||||
standaloneRunCode: CuaStandaloneRunCodeConfig.default({}),
|
||||
allowedApps: Schema.array(Schema.object({
|
||||
id: Schema.string().pattern(/^[a-f0-9]{64}$/).required(),
|
||||
name: Schema.string().required(), executablePath: Schema.string().min(1),
|
||||
|
||||
@@ -4,7 +4,7 @@ const hoverSignature = 'mouseMove(target: string | [number, number], options?: {
|
||||
/** Async method catalog with consent and observation rules, grouped by observation, mouse, and keyboard. */
|
||||
export const COMMON_GUIDANCE = `Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation.
|
||||
|
||||
In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes.
|
||||
Use void await for observations that emit, and never stringify screenshot image bytes.
|
||||
|
||||
Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid.
|
||||
|
||||
|
||||
@@ -20,12 +20,10 @@ import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts'
|
||||
import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts'
|
||||
import type { CuaAppHandle, CuaOperation, CuaStartupCapabilities } from './types.ts'
|
||||
import { ApplicationIcon, AppResult, NativeScreenshotResult, Request, SystemPointerRequest, ScreenshotResult } from './protocol.ts'
|
||||
import { CuaConfigFields } from './config.ts'
|
||||
import { CuaConfigFields, type CuaStandaloneRunCodeConfig } from './config.ts'
|
||||
import { installCuaTools } from './tool-registration.ts'
|
||||
import { CuaCoordinates } from './coordinates.ts'
|
||||
import { observeNativeWindows } from './native-observation.ts'
|
||||
import { createScope, type Scope } from '@deepseek-ai/dsh-scope'
|
||||
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import type { PromptSection } from '@deepseek-ai/dsh-system-prompt'
|
||||
import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools'
|
||||
import type {} from '@deepseek-ai/dsh-subprocess'
|
||||
import type {} from '@deepseek-ai/dsh-computer-use'
|
||||
@@ -39,8 +37,10 @@ export type { CuaStartupCapabilities } from './types.ts'
|
||||
export interface CuaConfig {
|
||||
/** Ask once per live Session before an explicitly requested system-pointer move. */
|
||||
requireSystemPointerApproval: boolean
|
||||
/** Register tools for Agents using this preset; defaults to ptc. False enables global registration. */
|
||||
/** Preset receiving raw cua; other composed presets receive cua_run_code. False registers raw cua globally. */
|
||||
agentPreset: string | false
|
||||
/** Dedicated persistent program limits, independent of the profile's PTC runtime. */
|
||||
standaloneRunCode: CuaStandaloneRunCodeConfig
|
||||
/** Legacy grants imported once into profile-scoped storage; later edits are ignored. */
|
||||
allowedApps: Array<Omit<CuaApplicationGrant, 'id'> & {
|
||||
/** Unbranded digest at the profile configuration boundary; admitted by the Config schema. */
|
||||
@@ -129,7 +129,12 @@ async function screenshotStore(ctx: Context, execution: Readonly<CuaExecution>)
|
||||
export interface CuaBackend {
|
||||
helperPath: string
|
||||
createChannel: NativeChannelFactory
|
||||
guidance: string
|
||||
/**
|
||||
* Select platform operation instructions for the exposed tool form.
|
||||
* @param kind Raw cua calls or standalone cua_run_code programs.
|
||||
* @returns Instructions before shared capability guidance and configured limits are added.
|
||||
*/
|
||||
getGuidance(kind: 'raw' | 'standalone'): string
|
||||
capabilities: CuaStartupCapabilities
|
||||
/** Dispatch a directional key through the provider's execution-scoped input owner, after application authorization. */
|
||||
sendKeyEvent?: (client: NativeClient, params: Record<string, JsonValue>,
|
||||
@@ -155,8 +160,12 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
|
||||
const systemPointer = backend.capabilities.systemPointer === true
|
||||
const mouseControl = systemPointer ? new MouseControl(ctx, config.requireSystemPointerApproval) : undefined
|
||||
const requestSchema = systemPointer ? SystemPointerRequest : Request
|
||||
const instructions = systemPointer ? withSystemPointerGuidance(backend.guidance) : backend.guidance
|
||||
const guidance = `${instructions}\n\nAX read defaults: maxElements=${config.maxElements}, maxDepth=${config.maxDepth}.\n\nMaximum click holdMs: ${config.maxClickHoldMs} ms.`
|
||||
const formatGuidance = (text: string): string => {
|
||||
const instructions = systemPointer ? withSystemPointerGuidance(text) : text
|
||||
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'))
|
||||
const programGuidance = formatGuidance(backend.getGuidance('standalone'))
|
||||
const native: NativeClientConfig = {
|
||||
helperPath, cwd: process.cwd(), timeoutMs: config.timeoutMs, axTimeoutMs: config.axTimeoutMs,
|
||||
connectTimeoutMs: config.connectTimeoutMs, screenshotTimeoutMs: config.screenshotTimeoutMs,
|
||||
@@ -361,53 +370,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
|
||||
}
|
||||
},
|
||||
}
|
||||
const prompt: PromptSection = {
|
||||
name: 'computer-use:dsh-cua', order: ctx.systemPrompt.getSectionOrder('TOOL_COMPUTER_USE'),
|
||||
text: () => {
|
||||
const runtime = ctx.get('ptcRuntime')
|
||||
return !runtime?.retainsState ? guidance : `${guidance}
|
||||
|
||||
Persistent PTC initialization:
|
||||
|
||||
\`\`\`ts
|
||||
var { connectCua } = await import(${JSON.stringify(new URL('../lib/bridge.js', import.meta.url).href)});
|
||||
var cua = connectCua(() => tools.cua, text => console.log(text));
|
||||
\`\`\``
|
||||
},
|
||||
}
|
||||
const register = (scope: Context): void => {
|
||||
scope.tools.register(tool)
|
||||
scope.systemPrompt.section(prompt)
|
||||
}
|
||||
if (config.agentPreset === false) register(ctx)
|
||||
else {
|
||||
const consumer = ctx.inject(['agentPresets'], async (presetCtx) => {
|
||||
const scopes = new Map<Agent, Scope>()
|
||||
const sync = async (agent: Agent): Promise<void> => {
|
||||
const previous = scopes.get(agent)
|
||||
if (presetCtx.agentPresets.composedPreset(agent.ctx) !== config.agentPreset) {
|
||||
scopes.delete(agent)
|
||||
await previous?.dispose()
|
||||
return
|
||||
}
|
||||
if (previous !== undefined) return
|
||||
const scope = createScope(agent.ctx, agent)
|
||||
scopes.set(agent, scope)
|
||||
scope.ctx.effect(() => () => {
|
||||
if (scopes.get(agent) === scope) scopes.delete(agent)
|
||||
}, 'cua.agent-tools')
|
||||
register(scope.ctx)
|
||||
}
|
||||
presetCtx.effect(() => async () => { await Promise.all([...scopes.values()].map(scope => scope.dispose())) }, 'cua.agent-tools')
|
||||
presetCtx.on('agent/created', async ({ agent }) => { await sync(agent) })
|
||||
presetCtx.on('agent-preset/selected', (id) => {
|
||||
const agent = presetCtx.agents.get(id)
|
||||
if (agent !== undefined) void sync(agent).catch((error: unknown) => { presetCtx.logger.warn(`CUA tool scope update failed: ${String(error)}`) })
|
||||
})
|
||||
await Promise.all(presetCtx.agents.list().map(sync))
|
||||
})
|
||||
yield () => consumer.dispose()
|
||||
}
|
||||
yield installCuaTools(ctx, config, tool, guidance, programGuidance)
|
||||
}, 'dsh-cua.runtime')
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,14 @@ function connectionFailure(code: string, message: string, cause: unknown): Nativ
|
||||
return cause instanceof NativeError ? cause : new NativeError(code, message, { cause })
|
||||
}
|
||||
|
||||
/** Preserve the original failure together with any distinct cleanup failure. */
|
||||
function combineFailures(original: unknown, cleanup: unknown): unknown {
|
||||
if (original === cleanup) return original
|
||||
if (original instanceof AggregateError && original.errors.includes(cleanup)) return original
|
||||
if (cleanup instanceof AggregateError && cleanup.errors.includes(original)) return cleanup
|
||||
return new AggregateError([original, cleanup], `Native operation and cleanup failed.\nOperation: ${String(original)}\nCleanup: ${String(cleanup)}`, { cause: original })
|
||||
}
|
||||
|
||||
/** Resolved helper executable and bounded process/response configuration. */
|
||||
export interface NativeClientConfig {
|
||||
helperPath: string
|
||||
@@ -78,14 +86,18 @@ export class NativeClient {
|
||||
private bufferedBytes = 0
|
||||
private failure: NativeError | undefined
|
||||
private disposal: Promise<void> | undefined
|
||||
private transportClosed: Promise<void> | undefined
|
||||
private readonly cleanups = new Set<(canRequest: boolean) => Promise<void>>()
|
||||
private diagnostics: string[] = []
|
||||
private diagnosticBytes = 0
|
||||
private discardedDiagnostics = false
|
||||
private active: {
|
||||
kind: 'request' | 'cleanup'
|
||||
id: string
|
||||
outcome: Promise<JsonValue>
|
||||
resolve: (value: JsonValue) => void
|
||||
reject: (error: NativeError) => void
|
||||
cancel?: () => void
|
||||
} | undefined
|
||||
|
||||
/**
|
||||
@@ -123,6 +135,14 @@ export class NativeClient {
|
||||
await this.dispose()
|
||||
throw new NativeError('NATIVE_CLOSED', 'Helper is closed; acquire fresh application handles', { cause: this.failure })
|
||||
}
|
||||
return this.send('request', method, params, signal, callId)
|
||||
}
|
||||
|
||||
private async send(
|
||||
kind: 'request' | 'cleanup', method: string, params: Record<string, JsonValue>,
|
||||
signal: AbortSignal, callId?: ToolExecution['callId'],
|
||||
): Promise<JsonValue> {
|
||||
this.throwIfFailed()
|
||||
if (this.active) throw new NativeError('NATIVE_BUSY', 'Await native operations sequentially')
|
||||
const id = callId ?? randomUUID()
|
||||
const capture = method === 'screenshot'
|
||||
@@ -130,21 +150,18 @@ export class NativeClient {
|
||||
this.diagnosticBytes = 0
|
||||
this.discardedDiagnostics = false
|
||||
const started = performance.now()
|
||||
let nativeFailure: NativeError | undefined
|
||||
let interruption: NativeError | undefined
|
||||
let cancellationTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const frame = `${JSON.stringify({ id, method, params })}\n`
|
||||
if (Buffer.byteLength(frame) > this.config.maxRequestBytes) {
|
||||
throw new NativeError('NATIVE_REQUEST_LIMIT', 'Request exceeded the configured byte limit before dispatch')
|
||||
const error = new NativeError('NATIVE_REQUEST_LIMIT', 'Request exceeded the configured byte limit before dispatch')
|
||||
if (kind === 'cleanup') this.fail(error)
|
||||
throw error
|
||||
}
|
||||
const outcome = Promise.withResolvers<JsonValue>()
|
||||
this.active = {
|
||||
id, outcome: outcome.promise, resolve: outcome.resolve,
|
||||
reject: (error) => { nativeFailure = error; outcome.reject(error) },
|
||||
}
|
||||
if (capture) this.diagnostic(screenshotPrefix + JSON.stringify({ requestId: id, stage: 'host.dispatch', elapsedMs: 0 }))
|
||||
const interrupt = (error: NativeError): void => {
|
||||
if (interruption || this.active?.id !== id) return
|
||||
if (kind === 'cleanup') { this.fail(error); return }
|
||||
interruption = error
|
||||
cancellationTimer = setTimeout(() => {
|
||||
this.fail(new NativeError('NATIVE_CLEANUP', 'Native operation did not acknowledge cancellation; acquire fresh application handles', { cause: error }))
|
||||
@@ -158,58 +175,97 @@ export class NativeClient {
|
||||
}
|
||||
}
|
||||
const abort = (): void => { interrupt(new NativeError('NATIVE_CANCELLED', 'Operation cancelled; inspect fresh state before retrying input')) }
|
||||
this.active = {
|
||||
kind, id, outcome: outcome.promise, resolve: outcome.resolve,
|
||||
reject: outcome.reject,
|
||||
...kind === 'request' ? { cancel: abort } : {},
|
||||
}
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
const timeoutMs = capture ? Math.min(this.config.timeoutMs, this.config.screenshotTimeoutMs) : this.config.timeoutMs
|
||||
const timer = setTimeout(() => {
|
||||
interrupt(new NativeError('NATIVE_TIMEOUT', `Operation exceeded ${timeoutMs}ms`))
|
||||
}, timeoutMs)
|
||||
let diagnostics = ''
|
||||
try {
|
||||
try {
|
||||
this.handle.stdin.write(frame, (error) => {
|
||||
if (error) this.fail(connectionFailure('NATIVE_IO', 'Writing a helper request failed', error))
|
||||
})
|
||||
} catch (error) {
|
||||
this.fail(connectionFailure('NATIVE_IO', 'Writing a helper request failed', error))
|
||||
}
|
||||
const result = await outcome.promise
|
||||
if (this.failure) throw this.failure
|
||||
if (interruption) throw interruption
|
||||
if (capture) this.diagnostic(screenshotPrefix + JSON.stringify({
|
||||
requestId: id, stage: 'host.reply', elapsedMs: performance.now() - started,
|
||||
}))
|
||||
return result
|
||||
} catch (error) {
|
||||
if (interruption && !this.failure) throw interruption
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
clearTimeout(cancellationTimer)
|
||||
signal.removeEventListener('abort', abort)
|
||||
try {
|
||||
if (this.failure !== undefined) await this.dispose()
|
||||
} finally {
|
||||
if (capture) {
|
||||
const diagnostics = this.screenshotDiagnostics()
|
||||
const failure = this.failure ?? interruption ?? nativeFailure
|
||||
if (failure && diagnostics) failure.message += `\nScreenshot diagnostics:\n${diagnostics}`
|
||||
if (diagnostics) this.diagnostic(diagnostics)
|
||||
this.diagnostic(screenshotPrefix + JSON.stringify({
|
||||
requestId: id, stage: 'host.settled', elapsedMs: performance.now() - started,
|
||||
}))
|
||||
try {
|
||||
this.handle.stdin.write(frame, (error) => {
|
||||
if (error) this.fail(connectionFailure('NATIVE_IO', 'Writing a helper request failed', error))
|
||||
})
|
||||
if (capture) this.diagnostic(screenshotPrefix + JSON.stringify({ requestId: id, stage: 'host.dispatch', elapsedMs: 0 }))
|
||||
} catch (error) {
|
||||
this.fail(connectionFailure('NATIVE_IO', 'Writing a helper request failed', error))
|
||||
}
|
||||
const result = await outcome.promise
|
||||
this.throwIfFailed()
|
||||
if (interruption) throw interruption
|
||||
if (capture) this.diagnostic(screenshotPrefix + JSON.stringify({
|
||||
requestId: id, stage: 'host.reply', elapsedMs: performance.now() - started,
|
||||
}))
|
||||
return result
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
clearTimeout(cancellationTimer)
|
||||
signal.removeEventListener('abort', abort)
|
||||
if (capture) diagnostics = this.screenshotDiagnostics()
|
||||
}
|
||||
} catch (error) {
|
||||
// Native replies and transport callbacks reject with NativeError.
|
||||
const failure = (interruption && !this.failure ? interruption : error) as NativeError
|
||||
if (capture && diagnostics) failure.message += `\nScreenshot diagnostics:\n${diagnostics}`
|
||||
if (kind === 'cleanup') {
|
||||
this.fail(connectionFailure('NATIVE_CLEANUP', 'Native resource cleanup failed; acquire fresh application handles', failure))
|
||||
return await this.rejectAfterCleanup(failure, this.waitForTransportClose())
|
||||
}
|
||||
if (this.disposed) return await this.rejectAfterCleanup(failure, this.dispose())
|
||||
throw failure
|
||||
} finally {
|
||||
if (capture) {
|
||||
if (diagnostics) this.diagnostic(diagnostics)
|
||||
this.diagnostic(screenshotPrefix + JSON.stringify({
|
||||
requestId: id, stage: 'host.settled', elapsedMs: performance.now() - started,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch cleanup after any active request acknowledges completion or cancellation.
|
||||
* Available during graceful disposal. A refusal or timeout invalidates the connection; cleanup
|
||||
* awaits its closure before rejecting. Distinct operation and close failures are aggregated.
|
||||
* @param method - Host-only helper cleanup operation.
|
||||
* @param params - Resources owned by the enclosing execution.
|
||||
* @returns The native cleanup acknowledgement, bounded by the connection's request deadline.
|
||||
*/
|
||||
async requestCleanup(method: string, params: Record<string, JsonValue>): Promise<JsonValue> {
|
||||
while (this.active) await this.active.outcome.catch(() => undefined)
|
||||
return this.request(method, params, new AbortController().signal)
|
||||
try {
|
||||
while (this.active) await this.active.outcome.catch(() => undefined)
|
||||
return await this.send('cleanup', method, params, new AbortController().signal)
|
||||
} catch (error) {
|
||||
this.fail(connectionFailure('NATIVE_CLEANUP', 'Native resource cleanup failed; acquire fresh application handles', error))
|
||||
return this.rejectAfterCleanup(error, this.waitForTransportClose())
|
||||
}
|
||||
}
|
||||
|
||||
/** Await owned cleanup while retaining the operation's original failure. */
|
||||
private async rejectAfterCleanup(original: unknown, cleanup: Promise<void>): Promise<never> {
|
||||
try { await cleanup }
|
||||
catch (error) { throw combineFailures(original, error) }
|
||||
throw original
|
||||
}
|
||||
|
||||
/**
|
||||
* Register resource cleanup before graceful connection closure.
|
||||
* @param cleanup Stops resource admission and releases native state through requestCleanup.
|
||||
* canRequest is false after forced closure; then perform local cleanup only. A true value
|
||||
* does not guarantee that the transport survives the callback. Never call request or dispose here.
|
||||
* @returns Removal after the resource's normal cleanup settles; an admitted callback remains awaited.
|
||||
* @throws NativeError when the connection has failed or disposal has begun.
|
||||
*/
|
||||
registerCleanup(cleanup: (canRequest: boolean) => Promise<void>): () => void {
|
||||
if (this.disposed) throw new NativeError('NATIVE_CLOSED', 'Cannot register cleanup on a closing helper', { cause: this.failure })
|
||||
this.cleanups.add(cleanup)
|
||||
return () => { this.cleanups.delete(cleanup) }
|
||||
}
|
||||
|
||||
private screenshotDiagnostics(): string {
|
||||
@@ -239,24 +295,40 @@ export class NativeClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this Agent's connection has lost its retained native state. */
|
||||
get disposed(): boolean { return this.failure !== undefined }
|
||||
/** Whether this connection rejects new operations because it failed or is closing. */
|
||||
get disposed(): boolean { return this.failure !== undefined || this.disposal !== undefined }
|
||||
|
||||
/** Invalidate this Agent's handles and close its connection; await dispose for native cleanup. */
|
||||
invalidate(): void { this.fail(new NativeError('NATIVE_DISPOSED', 'Helper disposed')) }
|
||||
|
||||
/** Stop this Agent's pending work and await its native connection cleanup. */
|
||||
/** Stop new operations, settle registered resources, and await connection closure even when cleanup fails. */
|
||||
dispose(): Promise<void> {
|
||||
this.invalidate()
|
||||
this.disposal ??= (async () => {
|
||||
return this.disposal ??= Promise.resolve().then(async () => {
|
||||
this.active?.cancel?.()
|
||||
const results = await Promise.allSettled([...this.cleanups].map(cleanup =>
|
||||
Promise.resolve().then(() => cleanup(this.failure === undefined))))
|
||||
this.cleanups.clear()
|
||||
const errors = new Set<unknown>()
|
||||
for (const result of results) if (result.status === 'rejected') errors.add(result.reason)
|
||||
try {
|
||||
await this.handle.waitForClose()
|
||||
} finally {
|
||||
this.handle.stdout.destroy()
|
||||
this.handle.stdin.destroy()
|
||||
}
|
||||
})()
|
||||
return this.disposal
|
||||
this.invalidate()
|
||||
await this.waitForTransportClose()
|
||||
} catch (error) { errors.add(error) }
|
||||
if (errors.size > 0) throw [...errors].reduce(combineFailures)
|
||||
})
|
||||
}
|
||||
|
||||
/** Join transport closure without invoking resource callbacks or waiting on their disposal. */
|
||||
private waitForTransportClose(): Promise<void> {
|
||||
return this.transportClosed ??= Promise.resolve().then(() => this.handle.waitForClose()).finally(() => {
|
||||
this.handle.stdout.destroy()
|
||||
this.handle.stdin.destroy()
|
||||
})
|
||||
}
|
||||
|
||||
/** Reject execution after an asynchronous transport callback invalidates the connection. */
|
||||
private throwIfFailed(): void {
|
||||
if (this.failure !== undefined) throw this.failure
|
||||
}
|
||||
|
||||
private fail(error: NativeError): void {
|
||||
@@ -302,7 +374,7 @@ export class NativeClient {
|
||||
this.active = undefined
|
||||
if ('error' in reply) {
|
||||
const error = new NativeError(reply.error.code, reply.error.message)
|
||||
if (reply.error.code === 'NATIVE_RESPONSE_LIMIT') this.fail(error)
|
||||
if (active.kind === 'cleanup' || reply.error.code === 'NATIVE_RESPONSE_LIMIT') this.fail(error)
|
||||
active.reject(error)
|
||||
} else active.resolve(reply.result)
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
/** Agent-scoped raw CUA and persistent program tool registrations. */
|
||||
import { extname } from 'node:path'
|
||||
import type { Context, Fiber } from '@deepseek-ai/cordis'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { createScope, type Scope } from '@deepseek-ai/dsh-scope'
|
||||
import NodePtcRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code'
|
||||
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
||||
import type { PromptSection } from '@deepseek-ai/dsh-system-prompt'
|
||||
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import type { CuaConfig } from './index.ts'
|
||||
|
||||
const programDescription = 'Run a TypeScript program to observe and operate desktop applications. '
|
||||
+ 'The global cua object is ready to use; retain application and window objects across calls. '
|
||||
+ 'Only tools.cua is available inside the program. Call other session tools directly. '
|
||||
+ 'Print the values you need or leave a final expression; screenshots are attached after the program finishes.'
|
||||
|
||||
/**
|
||||
* Register raw CUA for its configured PTC preset and a persistent program tool for other presets.
|
||||
* @param ctx Provider context owning native calls and registrations.
|
||||
* @param config Validated preset selection and dedicated runtime bounds.
|
||||
* @param tool Internal native tool; non-PTC Agents can reach it only through the program.
|
||||
* @param guidance Raw-tool operation instructions for the configured PTC preset.
|
||||
* @param programGuidance Operation instructions available inside cua_run_code.
|
||||
* @returns Exact registration disposer, draining programs before native resources can close.
|
||||
*/
|
||||
export function installCuaTools(
|
||||
ctx: Context, config: CuaConfig, tool: ToolDefinition, guidance: string, programGuidance: string,
|
||||
): () => void | Promise<void> {
|
||||
// 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)
|
||||
const programBridgeUrl = JSON.stringify(new URL(`./bridge${extname(new URL(import.meta.url).pathname)}`, import.meta.url).href)
|
||||
const prompt = { name: 'computer-use:dsh-cua', order: ctx.systemPrompt.getSectionOrder('TOOL_COMPUTER_USE') }
|
||||
const rawPrompt: PromptSection = { ...prompt, text: () => {
|
||||
const runtime = ctx.get('ptcRuntime')
|
||||
return !runtime?.retainsState ? guidance : `${guidance}
|
||||
|
||||
In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global.
|
||||
|
||||
Persistent PTC initialization:
|
||||
|
||||
\`\`\`ts
|
||||
var { connectCua } = await import(${ptcBridgeUrl});
|
||||
var cua = connectCua(() => tools.cua, text => console.log(text));
|
||||
\`\`\``
|
||||
} }
|
||||
const register = (scope: Context, definition: ToolDefinition, instructions: PromptSection): (() => void) => {
|
||||
const removeTool = scope.tools.register(definition)
|
||||
let removePrompt: () => void
|
||||
try { removePrompt = scope.systemPrompt.section(instructions) }
|
||||
catch (error) { removeTool(); throw error }
|
||||
return () => { try { removePrompt() } finally { removeTool() } }
|
||||
}
|
||||
if (config.agentPreset === false) return register(ctx, tool, rawPrompt)
|
||||
return ctx.inject(['agentPresets', 'tools', 'agents', 'systemPrompt'], (base) => {
|
||||
const scopes = new Map<Agent, { scope: Scope; current?: { definition: ToolDefinition; remove: () => void } }>()
|
||||
let program: ToolDefinition | undefined
|
||||
let programs: Fiber | undefined
|
||||
let closing = false
|
||||
const modeOf = (agent: Agent): 'raw' | 'program' | undefined => {
|
||||
const preset = base.agentPresets.composedPreset(agent.ctx)
|
||||
return preset === undefined ? undefined : preset === config.agentPreset ? 'raw' : 'program'
|
||||
}
|
||||
const sync = (agent: Agent): void => {
|
||||
const mode = modeOf(agent)
|
||||
const definition = mode === 'raw' ? tool : mode === 'program' ? program : undefined
|
||||
let entry = scopes.get(agent)
|
||||
if (entry?.current?.definition === definition) return
|
||||
if (entry?.current !== undefined) { entry.current.remove(); delete entry.current }
|
||||
if (definition === undefined) return
|
||||
if (entry === undefined) {
|
||||
const scope = createScope(agent.ctx, agent)
|
||||
entry = { scope }
|
||||
scopes.set(agent, entry)
|
||||
scope.ctx.effect(() => () => { scopes.delete(agent) }, 'cua.agent-tools')
|
||||
}
|
||||
const remove = register(entry.scope.ctx, definition,
|
||||
mode === 'raw' ? rawPrompt : { ...prompt, text: programGuidance })
|
||||
entry.current = { definition, remove }
|
||||
}
|
||||
const syncAll = (): void => { for (const agent of base.agents.list()) sync(agent) }
|
||||
base.effect(function* () {
|
||||
yield async () => { await Promise.all([...scopes.values()].map(({ scope }) => scope.dispose())) }
|
||||
const runtimeCtx = base.isolate('ptcRuntime')
|
||||
const runtime = runtimeCtx.plugin(NodePtcRuntime, {
|
||||
...config.standaloneRunCode.runtime, executionMode: 'persistent-in-memory', scriptPersistence: false,
|
||||
})
|
||||
yield runtime.dispose
|
||||
const initializer = runtimeCtx.plugin({
|
||||
name: 'cua-program-initializer', inject: ['ptcRuntime'],
|
||||
apply(owner: Context) {
|
||||
owner.effect(function* () {
|
||||
yield owner.ptcRuntime.registerEnvironmentInitializer(
|
||||
`globalThis.cua = (await import(${programBridgeUrl})).connectCua(() => tools.cua, text => console.log(text));`,
|
||||
)
|
||||
const child = owner.plugin({
|
||||
name: 'cua-program-tools', inject: ['ptcRuntime', 'tools', 'workingDirectory'],
|
||||
apply(consumer: Context) {
|
||||
const definition = createRunCodeTool(consumer, {
|
||||
name: 'cua_run_code', description: programDescription, runtime: consumer.ptcRuntime,
|
||||
tools: [tool], limits: config.standaloneRunCode.executor,
|
||||
})
|
||||
consumer.effect(function* () {
|
||||
yield () => {
|
||||
if (program !== definition) return
|
||||
program = undefined
|
||||
syncAll()
|
||||
}
|
||||
program = definition
|
||||
syncAll()
|
||||
}, 'cua.program-publication')
|
||||
},
|
||||
})
|
||||
programs = child
|
||||
yield () => { programs = undefined }
|
||||
yield child.dispose
|
||||
}, 'cua.environment-initializer')
|
||||
},
|
||||
})
|
||||
yield initializer.dispose
|
||||
yield base.on('agent/created', async ({ agent }) => {
|
||||
if (closing) return
|
||||
if (modeOf(agent) === 'program') {
|
||||
if (runtime.uid !== null) await runtime.await()
|
||||
await initializer.await()
|
||||
await programs?.await()
|
||||
// oxlint-disable-next-line typescript/no-unnecessary-condition -- Provider teardown can run while readiness awaits.
|
||||
if (closing) return
|
||||
if (modeOf(agent) === 'program' && program === undefined) {
|
||||
throw new Error('CUA program tool is unavailable; restore its private runtime and workingDirectory services, or reload the provider')
|
||||
}
|
||||
}
|
||||
sync(agent)
|
||||
})
|
||||
yield base.on('agent-preset/selected', (id) => {
|
||||
const agent = base.agents.get(id)
|
||||
if (agent === undefined) return
|
||||
try { sync(agent) } catch (error) { base.logger.warn(`CUA tool scope update failed: ${String(error)}`) }
|
||||
})
|
||||
yield () => {
|
||||
closing = true
|
||||
program = undefined
|
||||
for (const entry of scopes.values()) {
|
||||
entry.current?.remove()
|
||||
delete entry.current
|
||||
}
|
||||
}
|
||||
syncAll()
|
||||
}, 'cua.program-runtime')
|
||||
}).dispose
|
||||
}
|
||||
@@ -1,15 +1,22 @@
|
||||
/** CUA tool and prompt ownership follows live Agent presets and provider disposal. */
|
||||
import { resolve } from 'node:path'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { Context, FiberState } from '@deepseek-ai/cordis'
|
||||
import Loader from '@deepseek-ai/cordis-plugin-loader'
|
||||
import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use'
|
||||
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
import Subprocess from '@deepseek-ai/dsh-subprocess'
|
||||
import Sandbox from '@deepseek-ai/dsh-sandbox-local'
|
||||
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import WorkingDirectory from '@deepseek-ai/dsh-working-directory'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { CuaConfig, installCua } from '../src/index.ts'
|
||||
|
||||
const programPrompt = 'Fixture CUA program guidance\n\nAX read defaults: maxElements=2000, maxDepth=25.\n\nMaximum click holdMs: 5000 ms.'
|
||||
|
||||
const provider = {
|
||||
name: 'test-cua-scopes',
|
||||
inject: ['computerUse', 'subprocess', 'tools', 'systemPrompt', 'agents'],
|
||||
@@ -19,7 +26,7 @@ const provider = {
|
||||
helperPath: resolve('unused-cua-helper'),
|
||||
createChannel() { throw new Error('Scope tests must not start a native helper') },
|
||||
permissionParameters: (_method, permission, locale) => ({ permission, locale }),
|
||||
guidance: 'Fixture CUA guidance',
|
||||
getGuidance: kind => kind === 'raw' ? 'Fixture CUA guidance' : 'Fixture CUA program guidance',
|
||||
capabilities: {
|
||||
platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState'], appLevelAccessibility: true,
|
||||
keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels',
|
||||
@@ -28,12 +35,14 @@ const provider = {
|
||||
},
|
||||
}
|
||||
|
||||
async function setup(presetIds = ['standard', 'ptc']) {
|
||||
async function setup(presetIds = ['standard', 'ptc'], withSandbox = true) {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
ctx.baseUrl = import.meta.url
|
||||
await ctx.plugin(Loader)
|
||||
await mountAgentLoopTestDependencies(ctx)
|
||||
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
|
||||
if (withSandbox) await ctx.plugin(Sandbox)
|
||||
await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access' })
|
||||
await mountAgentLoopTestHarness(ctx)
|
||||
await ctx.plugin(ComputerUseRegistry)
|
||||
await ctx.plugin(Subprocess, [])
|
||||
@@ -49,7 +58,52 @@ async function setup(presetIds = ['standard', 'ptc']) {
|
||||
return { ctx, create }
|
||||
}
|
||||
|
||||
it('adds and removes CUA for existing and new PTC Agents without changing other presets', async () => {
|
||||
async function cuaPrompts(ctx: Context, agent: Agent): Promise<string[]> {
|
||||
return (await ctx.systemPrompt.assemble({ scope: agent })).sections
|
||||
.filter(section => section.name === 'computer-use:dsh-cua').map(section => section.text)
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ executionMode: 'per-call' },
|
||||
{ executionMode: 'persistent-in-memory' },
|
||||
{ scriptPersistence: true },
|
||||
{ scriptPersistence: false },
|
||||
])('rejects explicit program evaluation settings %j', (unsupported) => {
|
||||
expect(() => CuaConfig({ standaloneRunCode: { runtime: { timeoutMs: 1000, ...unsupported } } })).toThrow()
|
||||
expect(CuaConfig({ standaloneRunCode: { runtime: { timeoutMs: 1000 } } }).standaloneRunCode.runtime.timeoutMs).toBe(1000)
|
||||
})
|
||||
|
||||
it('gives every other composed preset a program tool without changing the shared runtime', async () => {
|
||||
const { ctx, create } = await setup(['standard', 'ptc', 'cordis', 'minimal', 'custom'])
|
||||
const shared = { programFormat: 'function-body', retainsState: false }
|
||||
ctx.provide('ptcRuntime', shared)
|
||||
const mounted = await ctx.plugin(provider, {})
|
||||
for (const preset of ['standard', 'cordis', 'minimal', 'custom']) {
|
||||
const handle = await create(`cua-${preset}`, preset)
|
||||
expect(ctx.tools.schemas(handle.agent).map(tool => tool.name)).toContain('cua_run_code')
|
||||
expect(ctx.tools.get('cua', handle.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua_run_code', handle.agent)?.description).toContain('global cua object is ready')
|
||||
await handle.dispose()
|
||||
expect(ctx.tools.get('cua_run_code', handle.agent)).toBeUndefined()
|
||||
}
|
||||
const uncomposed = await ctx.agents.create({ sessionId: SessionId('cua-uncomposed') })
|
||||
expect(ctx.tools.get('cua_run_code', uncomposed.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua', uncomposed.agent)).toBeUndefined()
|
||||
expect(ctx.get('ptcRuntime')).toMatchObject(shared)
|
||||
await mounted.dispose()
|
||||
})
|
||||
|
||||
it('keeps explicitly configured global raw-tool registration', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const mounted = await ctx.plugin(provider, { agentPreset: false })
|
||||
const handle = await create('cua-global', 'standard')
|
||||
expect(ctx.tools.get('cua', handle.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua_run_code', handle.agent)).toBeUndefined()
|
||||
await mounted.dispose()
|
||||
expect(ctx.tools.get('cua', handle.agent)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('selects one CUA transport for existing and new Agents and removes both on unload', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const existing = await create('existing', 'ptc')
|
||||
const standard = await create('standard', 'standard')
|
||||
@@ -57,6 +111,9 @@ it('adds and removes CUA for existing and new PTC Agents without changing other
|
||||
const mounted = await ctx.plugin(provider, {})
|
||||
await expect.poll(() => ctx.tools.get('cua', existing.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua', standard.agent)).toBeUndefined()
|
||||
await expect.poll(() => ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua_run_code', existing.agent)).toBeUndefined()
|
||||
expect(ctx.get('ptcRuntime')).toBeUndefined()
|
||||
const { sections } = await ctx.systemPrompt.assemble({ scope: existing.agent })
|
||||
expect(sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Fixture CUA guidance')
|
||||
await ctx.agentPresets.select(existing.agent, 'ptc')
|
||||
@@ -65,13 +122,15 @@ it('adds and removes CUA for existing and new PTC Agents without changing other
|
||||
expect(ctx.tools.get('cua', fresh.agent)).toBeDefined()
|
||||
await ctx.agentPresets.select(existing.agent, 'standard')
|
||||
await expect.poll(() => ctx.tools.get('cua', existing.agent)).toBeUndefined()
|
||||
expect((await ctx.systemPrompt.assemble({ scope: existing.agent })).sections)
|
||||
.not.toContainEqual(expect.objectContaining({ name: 'computer-use:dsh-cua' }))
|
||||
await expect.poll(() => ctx.tools.get('cua_run_code', existing.agent)).toBeDefined()
|
||||
const standardSections = (await ctx.systemPrompt.assemble({ scope: existing.agent })).sections
|
||||
expect(standardSections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Fixture CUA program guidance')
|
||||
await ctx.agentPresets.select(existing.agent, 'ptc')
|
||||
await expect.poll(() => ctx.tools.get('cua', existing.agent)).toBeDefined()
|
||||
await fresh.dispose()
|
||||
expect(ctx.tools.get('cua', fresh.agent)).toBeUndefined()
|
||||
await mounted.dispose()
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua', existing.agent)).toBeUndefined()
|
||||
expect((await ctx.systemPrompt.assemble({ scope: existing.agent })).sections)
|
||||
.not.toContainEqual(expect.objectContaining({ name: 'computer-use:dsh-cua' }))
|
||||
@@ -81,6 +140,222 @@ it('adds and removes CUA for existing and new PTC Agents without changing other
|
||||
await reloaded.dispose()
|
||||
})
|
||||
|
||||
it('keeps initialization registered while program tools reload their directory dependency', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const register = vi.spyOn(NodeRuntime.prototype, 'registerEnvironmentInitializer')
|
||||
onTestFinished(() => { register.mockRestore() })
|
||||
await ctx.plugin(provider, {})
|
||||
expect(register).toHaveBeenCalledOnce()
|
||||
const standard = await create('cua-dependency-standard', 'standard')
|
||||
const ptc = await create('cua-dependency-ptc', 'ptc')
|
||||
const previous = ctx.tools.get('cua_run_code', standard.agent)
|
||||
const raw = ctx.tools.get('cua', ptc.agent)
|
||||
const rawPrompts = await cuaPrompts(ctx, ptc.agent)
|
||||
expect(previous).toBeDefined()
|
||||
expect(raw).toBeDefined()
|
||||
expect(rawPrompts).toHaveLength(1)
|
||||
const directoryProvider = [...ctx.registry.get(WorkingDirectory)?.fibers ?? []][0]
|
||||
expect(directoryProvider).toBeDefined()
|
||||
await directoryProvider?.dispose()
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
expect(await cuaPrompts(ctx, ptc.agent)).toEqual(rawPrompts)
|
||||
expect(await cuaPrompts(ctx, standard.agent)).toEqual([])
|
||||
await ctx.plugin(WorkingDirectory)
|
||||
await expect.poll(() => ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent) === previous).toBe(false)
|
||||
expect(register).toHaveBeenCalledOnce()
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
expect(await cuaPrompts(ctx, ptc.agent)).toEqual(rawPrompts)
|
||||
await ctx.agentPresets.select(standard.agent, 'ptc')
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua', standard.agent)).toBeDefined()
|
||||
await ctx.agentPresets.select(standard.agent, 'standard')
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua', standard.agent)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps raw CUA and the shared runtime while the private runtime is absent', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const shared = { programFormat: 'repl', retainsState: true }
|
||||
ctx.provide('ptcRuntime', shared)
|
||||
await ctx.plugin(provider, {})
|
||||
const standard = await create('private-loss-standard', 'standard')
|
||||
const ptc = await create('private-loss-ptc', 'ptc')
|
||||
const raw = ctx.tools.get('cua', ptc.agent)
|
||||
const rawPrompts = await cuaPrompts(ctx, ptc.agent)
|
||||
const previous = ctx.tools.get('cua_run_code', standard.agent)
|
||||
const privateRuntime = [...ctx.registry.get(NodeRuntime)?.fibers ?? []][0]
|
||||
if (privateRuntime === undefined) throw new Error('missing private runtime fixture')
|
||||
await privateRuntime.dispose()
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
expect(await cuaPrompts(ctx, ptc.agent)).toEqual(rawPrompts)
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeUndefined()
|
||||
expect(await cuaPrompts(ctx, standard.agent)).toEqual([])
|
||||
expect(ctx.get('ptcRuntime')).toBe(shared)
|
||||
const fresh = await create('private-loss-new-ptc', 'ptc')
|
||||
expect(ctx.tools.get('cua', fresh.agent)).toBe(raw)
|
||||
await privateRuntime.parent.plugin(NodeRuntime, { executionMode: 'persistent-in-memory' })
|
||||
await expect.poll(() => ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent) === previous).toBe(false)
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
expect(ctx.get('ptcRuntime')).toBe(shared)
|
||||
})
|
||||
|
||||
it('creates raw Agents while private runtime startup is pending', async () => {
|
||||
const { ctx, create } = await setup(undefined, false)
|
||||
await ctx.plugin(provider, {})
|
||||
const ptc = await create('private-pending-ptc', 'ptc')
|
||||
const raw = ctx.tools.get('cua', ptc.agent)
|
||||
expect(raw).toBeDefined()
|
||||
expect((await cuaPrompts(ctx, ptc.agent)).join('')).toContain('Fixture CUA guidance')
|
||||
await expect(create('private-pending-standard', 'standard')).rejects.toThrow('CUA program tool is unavailable')
|
||||
await ctx.plugin(Sandbox)
|
||||
const standard = await create('private-restored-standard', 'standard')
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
})
|
||||
|
||||
it('uses a corrected private runtime after the failed instance is replaced', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const report = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
|
||||
onTestFinished(() => { report.mockRestore() })
|
||||
await ctx.plugin(provider, { standaloneRunCode: { runtime: { maxOutputBytes: 1 } } })
|
||||
const ptc = await create('failed-node-ptc', 'ptc')
|
||||
const raw = ctx.tools.get('cua', ptc.agent)
|
||||
expect(raw).toBeDefined()
|
||||
const failed = [...ctx.registry.get(NodeRuntime)?.fibers ?? []][0]
|
||||
if (failed === undefined) throw new Error('missing failed private runtime')
|
||||
await expect(create('failed-node-standard', 'standard')).rejects.toThrow('maxOutputBytes')
|
||||
await failed.dispose()
|
||||
await failed.parent.plugin(NodeRuntime, { executionMode: 'persistent-in-memory' })
|
||||
const standard = await create('replacement-node-standard', 'standard')
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
expect((await cuaPrompts(ctx, ptc.agent)).join('')).toContain('Fixture CUA guidance')
|
||||
})
|
||||
|
||||
it('ignores a queued raw creation listener after optional CUA unload', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const mounted = await ctx.plugin(provider, {})
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const resume: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
ctx.on('agent/created', async () => { entered.resolve(); await resume.promise }, { prepend: true })
|
||||
const creating = create('queued-raw-unload', 'ptc')
|
||||
try {
|
||||
await entered.promise
|
||||
await mounted.dispose()
|
||||
resume.resolve()
|
||||
const handle = await creating
|
||||
expect(ctx.tools.get('cua', handle.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua_run_code', handle.agent)).toBeUndefined()
|
||||
expect(await cuaPrompts(ctx, handle.agent)).toEqual([])
|
||||
} finally { resume.resolve(); await creating }
|
||||
})
|
||||
|
||||
it('finishes Agent creation when optional CUA unloads during private readiness', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const mounted = await ctx.plugin(provider, {})
|
||||
const runtime = [...ctx.registry.get(NodeRuntime)?.fibers ?? []][0]
|
||||
if (runtime === undefined) throw new Error('missing private runtime fixture')
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const resume: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const ready = runtime.await.bind(runtime)
|
||||
const waiting = vi.spyOn(runtime, 'await').mockImplementationOnce(async () => {
|
||||
entered.resolve()
|
||||
await resume.promise
|
||||
return ready()
|
||||
})
|
||||
onTestFinished(() => { waiting.mockRestore(); resume.resolve() })
|
||||
const creating = create('waiting-program-unload', 'standard')
|
||||
try {
|
||||
await entered.promise
|
||||
await mounted.dispose()
|
||||
resume.resolve()
|
||||
const handle = await creating
|
||||
expect(ctx.tools.get('cua', handle.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua_run_code', handle.agent)).toBeUndefined()
|
||||
expect(await cuaPrompts(ctx, handle.agent)).toEqual([])
|
||||
} finally { resume.resolve(); await creating }
|
||||
})
|
||||
|
||||
it('creates raw Agents even when private initialization registration fails', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const register = vi.spyOn(NodeRuntime.prototype, 'registerEnvironmentInitializer')
|
||||
.mockImplementation(() => { throw new Error('private initializer failed') })
|
||||
const report = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
|
||||
onTestFinished(() => { register.mockRestore(); report.mockRestore() })
|
||||
await ctx.plugin(provider, {})
|
||||
const ptc = await create('private-failed-ptc', 'ptc')
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBeDefined()
|
||||
expect((await cuaPrompts(ctx, ptc.agent)).join('')).toContain('Fixture CUA guidance')
|
||||
await expect(create('private-failed-standard', 'standard')).rejects.toThrow('private initializer failed')
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBeDefined()
|
||||
})
|
||||
|
||||
it('switches modes synchronously without exposing both tools while programs are unavailable', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
await ctx.plugin(provider, {})
|
||||
const owner = await create('unavailable-switch', 'ptc')
|
||||
const directoryProvider = [...ctx.registry.get(WorkingDirectory)?.fibers ?? []][0]
|
||||
if (directoryProvider === undefined) throw new Error('missing directory fixture')
|
||||
await directoryProvider.dispose()
|
||||
const counts: number[] = []
|
||||
ctx.on('tools/change', () => {
|
||||
counts.push(ctx.tools.schemas(owner.agent).filter(tool => tool.name === 'cua' || tool.name === 'cua_run_code').length)
|
||||
})
|
||||
await ctx.agentPresets.select(owner.agent, 'standard')
|
||||
expect(ctx.tools.get('cua', owner.agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua_run_code', owner.agent)).toBeUndefined()
|
||||
expect(await cuaPrompts(ctx, owner.agent)).toEqual([])
|
||||
await ctx.agentPresets.select(owner.agent, 'ptc')
|
||||
expect(ctx.tools.get('cua', owner.agent)).toBeDefined()
|
||||
expect((await cuaPrompts(ctx, owner.agent)).join('')).toContain('Fixture CUA guidance')
|
||||
await ctx.plugin(WorkingDirectory)
|
||||
await ctx.agentPresets.select(owner.agent, 'standard')
|
||||
await expect.poll(() => ctx.tools.get('cua_run_code', owner.agent)).toBeDefined()
|
||||
expect(ctx.tools.get('cua', owner.agent)).toBeUndefined()
|
||||
expect(await cuaPrompts(ctx, owner.agent)).toEqual([programPrompt])
|
||||
expect(counts.length).toBeGreaterThan(0)
|
||||
expect(counts.every(count => count <= 1)).toBe(true)
|
||||
})
|
||||
|
||||
it('rolls back a partial program publication without withdrawing raw CUA', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
await ctx.plugin(provider, {})
|
||||
const standard = await create('publication-standard', 'standard')
|
||||
const ptc = await create('publication-ptc', 'ptc')
|
||||
const raw = ctx.tools.get('cua', ptc.agent)
|
||||
const directoryProvider = [...ctx.registry.get(WorkingDirectory)?.fibers ?? []][0]
|
||||
if (directoryProvider === undefined) throw new Error('missing directory fixture')
|
||||
await directoryProvider.dispose()
|
||||
const attempted: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const section = vi.spyOn(ctx.systemPrompt, 'section').mockImplementationOnce(() => {
|
||||
attempted.resolve()
|
||||
throw new Error('program prompt failed')
|
||||
})
|
||||
const report = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
|
||||
onTestFinished(() => { section.mockRestore(); report.mockRestore() })
|
||||
await ctx.plugin(WorkingDirectory)
|
||||
await attempted.promise
|
||||
expect(ctx.tools.get('cua_run_code', standard.agent)).toBeUndefined()
|
||||
expect(await cuaPrompts(ctx, standard.agent)).toEqual([])
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
expect((await cuaPrompts(ctx, ptc.agent)).join('')).toContain('Fixture CUA guidance')
|
||||
const fibers = [...ctx.registry.values()].flatMap(runtime => [...runtime.fibers])
|
||||
const failed = fibers.find(fiber => fiber.runtime?.name === 'cua-program-tools')
|
||||
const initializer = fibers.find(fiber => fiber.runtime?.name === 'cua-program-initializer')
|
||||
if (failed === undefined || initializer === undefined) throw new Error('missing program lifecycle fixture')
|
||||
await expect(failed.await()).rejects.toThrow('program prompt failed')
|
||||
expect(failed.state).toBe(FiberState.FAILED)
|
||||
expect(initializer.state).toBe(FiberState.ACTIVE)
|
||||
section.mockRestore()
|
||||
await failed.update(failed.rawConfig)
|
||||
await expect.poll(() => ctx.tools.get('cua_run_code', standard.agent)).toBeDefined()
|
||||
expect(await cuaPrompts(ctx, standard.agent)).toEqual([programPrompt])
|
||||
expect(ctx.tools.get('cua', ptc.agent)).toBe(raw)
|
||||
})
|
||||
|
||||
it('ignores unloaded Session selections and reports a failed live scope update', async () => {
|
||||
const { ctx, create } = await setup()
|
||||
const handle = await create('active', 'ptc')
|
||||
@@ -123,5 +398,7 @@ it.each([
|
||||
const prompt = (await ctx.systemPrompt.assemble({ scope: owner.agent })).sections.find(section => section.name === 'computer-use:dsh-cua')?.text
|
||||
expect(prompt).toBeDefined()
|
||||
expect(prompt?.includes('Persistent PTC initialization:')).toBe(runtime.retainsState)
|
||||
expect(prompt?.includes('use the host-provided bridge initialization once and retain the returned objects')).toBe(runtime.retainsState)
|
||||
expect(prompt?.includes('cua comes from that bridge and is not a preinstalled global')).toBe(runtime.retainsState)
|
||||
expect(prompt?.includes('var cua = connectCua(() => tools.cua, text => console.log(text));')).toBe(runtime.retainsState)
|
||||
})
|
||||
@@ -1,6 +1,10 @@
|
||||
/** Controlled connection streams exercise the platform-independent native protocol client. */
|
||||
import { PassThrough, Writable } from 'node:stream'
|
||||
import { ToolCallId } from '@deepseek-ai/dsh-llm'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import { NativeToolExecutor } from '@deepseek-ai/dsh-tool-executor-native'
|
||||
import Tools, { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import type { NativeChannel } from '../src/native-client.ts'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
@@ -24,17 +28,20 @@ function fixture(options: {
|
||||
} = {}) {
|
||||
const requests: z.infer<typeof Request>[] = []
|
||||
const cancellations: z.infer<typeof Cancel>[] = []
|
||||
const frames: z.infer<typeof Frame>[] = []
|
||||
const stdout = new PassThrough()
|
||||
const done: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const gone: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const stdin = new Writable({ write(chunk, _encoding, callback) {
|
||||
const frame = Frame.parse(JSON.parse(String(chunk)))
|
||||
frames.push(frame)
|
||||
if ('type' in frame) { cancellations.push(frame); callback(options.cancelWriteError) }
|
||||
else { requests.push(frame); callback(options.writeError) }
|
||||
} })
|
||||
const closed: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const close = vi.fn(() => { closed.resolve() })
|
||||
const waitForClose = vi.fn(() => gone.promise)
|
||||
const waiting: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const waitForClose = vi.fn(() => { waiting.resolve(); return gone.promise })
|
||||
const channel: NativeChannel = { stdin, stdout, done: done.promise, close, waitForClose }
|
||||
shared.create.mockClear().mockReturnValueOnce(channel)
|
||||
const owner = { subprocess: { spawn: vi.fn() } }
|
||||
@@ -58,8 +65,8 @@ function fixture(options: {
|
||||
stdout.destroy()
|
||||
stdin.destroy()
|
||||
})
|
||||
return { client, requests, cancellations, stdout, stdin, owner, config, connect: shared.create,
|
||||
close, closed: closed.promise, waitForClose, done, gone, finish, reply, id }
|
||||
return { client, requests, cancellations, frames, stdout, stdin, owner, config, connect: shared.create,
|
||||
close, closed: closed.promise, waiting: waiting.promise, waitForClose, done, gone, finish, reply, id }
|
||||
}
|
||||
|
||||
describe('native helper transport', () => {
|
||||
@@ -75,6 +82,273 @@ describe('native helper transport', () => {
|
||||
await expect(release).resolves.toEqual({ dispatched: true })
|
||||
})
|
||||
|
||||
it.each(['connection', 'resource'] as const)('shares %s-triggered cleanup and waits for its acknowledgement before closing', async (trigger) => {
|
||||
const f = fixture()
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
let cleanup: Promise<void> | undefined
|
||||
const release = (): Promise<void> => cleanup ??= f.client.requestCleanup('releaseHeldKeys', { runId: 'shared' })
|
||||
.then(() => undefined).finally(() => { remove() })
|
||||
const remove = f.client.registerCleanup((canRequest) => { expect(canRequest).toBe(true); entered.resolve(); return release() })
|
||||
const pending = trigger === 'resource' ? release() : undefined
|
||||
const closing = f.client.dispose()
|
||||
expect(f.client.dispose()).toBe(closing)
|
||||
expect(f.client.disposed).toBe(true)
|
||||
const denied = expect(f.client.request('click', {}, new AbortController().signal)).rejects.toMatchObject({ code: 'NATIVE_CLOSED' })
|
||||
expect(() => f.client.registerCleanup(async () => {})).toThrow('closing helper')
|
||||
await entered.promise
|
||||
expect(f.requests.map(request => request.method)).toEqual(['releaseHeldKeys'])
|
||||
expect(f.cancellations).toEqual([])
|
||||
expect(f.close).not.toHaveBeenCalled()
|
||||
f.reply({ id: f.id(), result: { dispatched: true } })
|
||||
await f.waiting
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
expect(f.stdout.destroyed).toBe(false)
|
||||
f.finish()
|
||||
await Promise.all([closing, pending, denied])
|
||||
await release()
|
||||
expect(f.requests).toHaveLength(1)
|
||||
expect(f.waitForClose).toHaveBeenCalledTimes(1)
|
||||
expect(f.stdout.destroyed).toBe(true)
|
||||
expect(f.stdin.destroyed).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps screenshot diagnostics on the cancellation returned during graceful disposal', async () => {
|
||||
const reportDiagnostic = vi.fn<(message: string) => void>()
|
||||
const f = fixture({ reportDiagnostic })
|
||||
const pending = f.client.request('screenshot', {}, new AbortController().signal, ToolCallId('graceful-capture'))
|
||||
const result = pending.catch((error: unknown) => error)
|
||||
f.reply({ type: 'diagnostic', requestId: 'graceful-capture', stage: 'capture-image.begin', elapsedMs: 2 })
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
f.client.registerCleanup(async () => {
|
||||
const release = f.client.requestCleanup('releaseHeldKeys', { runId: 'graceful' })
|
||||
entered.resolve()
|
||||
await release
|
||||
})
|
||||
const closing = f.client.dispose()
|
||||
await entered.promise
|
||||
expect(f.cancellations).toEqual([{ type: 'cancel', id: 'graceful-capture' }])
|
||||
f.reply({ id: 'graceful-capture', error: { code: 'NATIVE_CANCELLED', message: 'capture cancelled' } })
|
||||
await expect.poll(() => f.requests.map(request => request.method)).toEqual(['screenshot', 'releaseHeldKeys'])
|
||||
f.reply({ id: f.id(), result: { dispatched: true } })
|
||||
await f.waiting
|
||||
expect(reportDiagnostic.mock.calls.flat().join('\n')).not.toContain('host.settled')
|
||||
f.finish()
|
||||
await closing
|
||||
const failure = await result
|
||||
expect(failure).toMatchObject({ code: 'NATIVE_CANCELLED' })
|
||||
if (!(failure instanceof NativeError)) throw new Error('The screenshot cancellation must retain its native error')
|
||||
expect(failure.message).toContain('capture-image.begin')
|
||||
expect(failure.message).not.toContain('NATIVE_DISPOSED')
|
||||
expect(reportDiagnostic.mock.calls.flat().join('\n')).toContain('host.settled')
|
||||
})
|
||||
|
||||
it.each(['write', 'protocol', 'timeout'] as const)('settles a fatal cleanup %s without waiting recursively on disposal', async (kind) => {
|
||||
if (kind === 'timeout') vi.useFakeTimers()
|
||||
try {
|
||||
const f = fixture({ timeoutMs: 25, graceMs: 10,
|
||||
...kind === 'write' ? { writeError: new Error('cleanup pipe failed') } : {},
|
||||
})
|
||||
const joined: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
let cleanup: Promise<void> | undefined
|
||||
const release = (): Promise<void> => cleanup ??= f.client.requestCleanup('releaseHeldKeys', { runId: 'failing' }).then(() => undefined)
|
||||
f.client.registerCleanup(() => { joined.resolve(); return release() })
|
||||
const pending = release()
|
||||
const closing = f.client.dispose()
|
||||
const results = Promise.allSettled([pending, closing])
|
||||
await joined.promise
|
||||
if (kind === 'protocol') f.stdout.write('{invalid}\n')
|
||||
if (kind === 'timeout') await vi.advanceTimersByTimeAsync(25)
|
||||
await f.closed
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
expect(f.cancellations).toEqual([])
|
||||
f.finish()
|
||||
const [first, second] = await results
|
||||
const code = kind === 'write' ? 'NATIVE_IO' : kind === 'protocol' ? 'NATIVE_PROTOCOL' : 'NATIVE_TIMEOUT'
|
||||
expect(first).toMatchObject({ status: 'rejected', reason: { code } })
|
||||
expect(second).toMatchObject({ status: 'rejected', reason: { code } })
|
||||
if (first?.status !== 'rejected' || second?.status !== 'rejected') throw new Error('Both cleanup callers must settle')
|
||||
expect(second.reason).toBe(first.reason)
|
||||
expect(f.stdout.destroyed).toBe(true)
|
||||
expect(f.stdin.destroyed).toBe(true)
|
||||
} finally { if (kind === 'timeout') vi.useRealTimers() }
|
||||
})
|
||||
|
||||
it.each(['refusal', 'request-limit'] as const)('invalidates standalone cleanup on %s before another request can enter', async (kind) => {
|
||||
const f = fixture(kind === 'request-limit' ? { maxRequestBytes: 32 } : {})
|
||||
const cleanup = f.client.requestCleanup('releaseHeldKeys', { runId: 'standalone' })
|
||||
const rejected = expect(cleanup).rejects.toMatchObject({ code: kind === 'refusal' ? 'RELEASE_REFUSED' : 'NATIVE_REQUEST_LIMIT' })
|
||||
if (kind === 'refusal') f.reply({ id: f.id(), error: { code: 'RELEASE_REFUSED', message: 'release not acknowledged' } })
|
||||
// Admission is checked in the same stack as the failed reply or preflight.
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
const denied = expect(f.client.request('click', {}, new AbortController().signal)).rejects.toMatchObject({ code: 'NATIVE_CLOSED' })
|
||||
expect(f.requests).toHaveLength(kind === 'refusal' ? 1 : 0)
|
||||
await f.waiting
|
||||
f.finish()
|
||||
await Promise.all([rejected, denied])
|
||||
})
|
||||
|
||||
it('closes a timed-out standalone cleanup and ignores its late acknowledgement', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const f = fixture({ timeoutMs: 25, graceMs: 10 })
|
||||
const cleanup = f.client.requestCleanup('releaseHeldKeys', { runId: 'expired' })
|
||||
const rejected = expect(cleanup).rejects.toMatchObject({ code: 'NATIVE_TIMEOUT' })
|
||||
const id = f.id()
|
||||
await vi.advanceTimersByTimeAsync(25)
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
expect(f.cancellations).toEqual([])
|
||||
f.reply({ id, result: { dispatched: true } })
|
||||
f.finish()
|
||||
await rejected
|
||||
expect(f.client.disposed).toBe(true)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
} finally { vi.useRealTimers() }
|
||||
})
|
||||
|
||||
it.each(['request', 'cleanup'] as const)('retains the original %s failure when connection closure also fails', async (kind) => {
|
||||
const reportDiagnostic = vi.fn<(message: string) => void>()
|
||||
const f = fixture({ reportDiagnostic })
|
||||
const original = new NativeError('NATIVE_IO', 'original connection failure')
|
||||
const closeFailure = new Error('connection close acknowledgement failed')
|
||||
const pending = kind === 'request'
|
||||
? f.client.request('screenshot', {}, new AbortController().signal, ToolCallId('failed-capture'))
|
||||
: f.client.requestCleanup('releaseHeldKeys', { runId: 'both-failed' })
|
||||
const result = pending.catch((error: unknown) => error)
|
||||
if (kind === 'request') f.reply({ type: 'diagnostic', requestId: 'failed-capture', stage: 'capture-image.begin', elapsedMs: 2 })
|
||||
f.stdout.emit('error', original)
|
||||
await f.waiting
|
||||
expect(reportDiagnostic.mock.calls.flat().join('\n')).not.toContain('host.settled')
|
||||
f.gone.reject(closeFailure)
|
||||
f.done.resolve()
|
||||
const failure = await result
|
||||
if (!(failure instanceof AggregateError)) throw new Error('Both native and close failures must remain available')
|
||||
expect(failure.errors).toEqual([original, closeFailure])
|
||||
expect(failure.cause).toBe(original)
|
||||
if (kind === 'request') {
|
||||
expect(original.message).toContain('capture-image.begin')
|
||||
expect(reportDiagnostic.mock.calls.flat().join('\n')).toContain('host.settled')
|
||||
}
|
||||
expect(f.stdout.destroyed).toBe(true)
|
||||
expect(f.stdin.destroyed).toBe(true)
|
||||
})
|
||||
|
||||
it('reports the native and close failures with screenshot diagnostics through the tool pipeline', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(Tools)
|
||||
ctx.tools.setExecutor(new NativeToolExecutor(ctx))
|
||||
const f = fixture()
|
||||
ctx.tools.register(defineTool({ name: 'capture_fixture', description: 'Capture the fixture window.', parameters: {},
|
||||
output: { schema: { type: 'json' }, render: () => [] },
|
||||
execute: async (_args, execution) => f.client.request('screenshot', {}, execution.signal, execution.callId),
|
||||
}))
|
||||
const running = ctx.tools.execute({ calls: [{ type: 'tool-call', name: 'capture_fixture', id: ToolCallId('pipeline-capture'), arguments: '{}' }],
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
await expect.poll(() => f.requests.length).toBe(1)
|
||||
f.reply({ type: 'diagnostic', requestId: 'pipeline-capture', stage: 'capture-image.begin', elapsedMs: 2 })
|
||||
f.stdout.emit('error', new NativeError('NATIVE_IO', 'original connection failure'))
|
||||
await f.waiting
|
||||
f.gone.reject(new Error('connection close acknowledgement failed'))
|
||||
f.done.resolve()
|
||||
const result = (await running).results[0]?.result
|
||||
expect(result?.isError).toBe(true)
|
||||
const text = result?.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
||||
expect(text).toContain('NATIVE_IO: original connection failure')
|
||||
expect(text).toContain('connection close acknowledgement failed')
|
||||
expect(text).toContain('capture-image.begin')
|
||||
})
|
||||
|
||||
it('shares an aggregated cleanup failure with disposal without repeating its close failure', async () => {
|
||||
const f = fixture()
|
||||
const original = new NativeError('NATIVE_IO', 'cleanup dispatch failed')
|
||||
const closeFailure = new Error('transport close failed')
|
||||
let cleanup: Promise<void> | undefined
|
||||
const release = (): Promise<void> => cleanup ??= f.client.requestCleanup('releaseHeldKeys', { runId: 'shared-failure' }).then(() => undefined)
|
||||
f.client.registerCleanup(() => release())
|
||||
const pending = release()
|
||||
const closing = f.client.dispose()
|
||||
const results = Promise.allSettled([pending, closing])
|
||||
f.stdout.emit('error', original)
|
||||
await f.waiting
|
||||
f.gone.reject(closeFailure)
|
||||
f.done.resolve()
|
||||
const [first, second] = await results
|
||||
if (first?.status !== 'rejected' || second?.status !== 'rejected') throw new Error('Both callers must receive cleanup failure')
|
||||
const failure: unknown = first.reason
|
||||
if (!(failure instanceof AggregateError)) throw new Error('Both native and close failures must remain available')
|
||||
expect(failure.errors).toEqual([original, closeFailure])
|
||||
expect(failure.cause).toBe(original)
|
||||
expect(second.reason).toBe(failure)
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
expect(f.waitForClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('runs local cleanup after immediate invalidation without another native write', async () => {
|
||||
const f = fixture()
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const modes: boolean[] = []
|
||||
f.client.registerCleanup(async (canRequest) => { modes.push(canRequest); entered.resolve() })
|
||||
f.client.invalidate()
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
const closing = f.client.dispose()
|
||||
await entered.promise
|
||||
expect(modes).toEqual([false])
|
||||
expect(f.requests).toEqual([])
|
||||
f.finish()
|
||||
await closing
|
||||
await expect(f.client.requestCleanup('releaseHeldKeys', {})).rejects.toMatchObject({ code: 'NATIVE_DISPOSED' })
|
||||
expect(f.requests).toEqual([])
|
||||
})
|
||||
|
||||
it.each(['same', 'additional'] as const)('retains a native failure when registered cleanup reports the %s failure', async (kind) => {
|
||||
const f = fixture()
|
||||
const original = new NativeError('NATIVE_IO', 'transport failed')
|
||||
const local = new Error('local resource cleanup failed')
|
||||
const combined = kind === 'same' ? original : new AggregateError([original, local], 'Resource cleanup failed')
|
||||
f.client.registerCleanup(async () => { throw combined })
|
||||
const pending = f.client.request('getState', {}, new AbortController().signal)
|
||||
const rejected = expect(pending).rejects.toBe(combined)
|
||||
f.stdout.emit('error', original)
|
||||
await f.waiting
|
||||
f.finish()
|
||||
await rejected
|
||||
})
|
||||
|
||||
it('settles queued cleanup registrations without another write after a native refusal', async () => {
|
||||
const f = fixture()
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const settled: string[] = []
|
||||
for (const runId of ['first', 'second']) f.client.registerCleanup(async () => {
|
||||
const request = f.client.requestCleanup('releaseHeldKeys', { runId })
|
||||
if (runId === 'first') entered.resolve()
|
||||
try { await request } finally { settled.push(runId) }
|
||||
})
|
||||
const closing = f.client.dispose()
|
||||
const rejected = expect(closing).rejects.toMatchObject({ code: 'RELEASE_REFUSED' })
|
||||
await entered.promise
|
||||
f.reply({ id: f.id(), error: { code: 'RELEASE_REFUSED', message: 'first release failed' } })
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
f.finish()
|
||||
await rejected
|
||||
expect(f.requests.map(request => request.params.runId)).toEqual(['first'])
|
||||
expect(settled.toSorted()).toEqual(['first', 'second'])
|
||||
})
|
||||
|
||||
it('submits the screenshot before a diagnostic sink can synchronously cancel it', async () => {
|
||||
const controller = new AbortController()
|
||||
const f = fixture({ reportDiagnostic: (message) => {
|
||||
if (message.includes('host.dispatch')) controller.abort()
|
||||
} })
|
||||
const pending = f.client.request('screenshot', {}, controller.signal)
|
||||
const rejected = expect(pending).rejects.toMatchObject({ code: 'NATIVE_CANCELLED' })
|
||||
expect(f.frames.map(frame => 'type' in frame ? 'cancel' : frame.method)).toEqual(['screenshot', 'cancel'])
|
||||
f.reply({ id: f.id(), error: { code: 'NATIVE_CANCELLED', message: 'capture stopped' } })
|
||||
await rejected
|
||||
expect(f.close).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes transport limits and connection deadlines to the shared channel', () => {
|
||||
const f = fixture({ maxRequestBytes: 4096, maxResponseBytes: 8192, timeoutMs: 1234 })
|
||||
expect(f.connect).toHaveBeenCalledExactlyOnceWith(f.owner, f.config)
|
||||
@@ -285,13 +559,18 @@ describe('native helper transport', () => {
|
||||
try {
|
||||
const f = fixture({ timeoutMs: 25, graceMs: 10 })
|
||||
const pending = f.client.request('screenshot', {}, new AbortController().signal)
|
||||
const rejected = expect(pending).rejects.toMatchObject({ code: 'NATIVE_CLEANUP', cause: { code: 'NATIVE_TIMEOUT' } })
|
||||
const rejected = pending.catch((error: unknown) => error)
|
||||
f.reply({ type: 'diagnostic', requestId: f.id(), stage: 'capture-image.begin', elapsedMs: 1 })
|
||||
await vi.advanceTimersByTimeAsync(25)
|
||||
expect(f.close).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(f.close).toHaveBeenCalledTimes(1)
|
||||
f.finish()
|
||||
await rejected
|
||||
const failure = await rejected
|
||||
expect(failure).toMatchObject({ code: 'NATIVE_CLEANUP', cause: { code: 'NATIVE_TIMEOUT' } })
|
||||
if (!(failure instanceof NativeError) || !(failure.cause instanceof NativeError)) throw new Error('Cancellation cleanup must retain its native cause')
|
||||
expect(failure.message).toContain('capture-image.begin')
|
||||
expect(failure.cause.message).not.toContain('Screenshot diagnostics')
|
||||
expect(f.client.disposed).toBe(true)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
} finally { vi.useRealTimers() }
|
||||
@@ -377,6 +656,7 @@ describe('native helper transport', () => {
|
||||
const first = f.client.dispose()
|
||||
const second = f.client.dispose()
|
||||
expect(second).toBe(first)
|
||||
await f.waiting
|
||||
expect(f.waitForClose).toHaveBeenCalledTimes(1)
|
||||
f.finish()
|
||||
await first
|
||||
@@ -391,7 +671,7 @@ describe('native helper transport', () => {
|
||||
const f = fixture()
|
||||
const pending = f.client.request('getState', {}, new AbortController().signal)
|
||||
const failure = new Error('cannot close connection')
|
||||
const rejected = expect(pending).rejects.toBe(failure)
|
||||
const rejected = expect(pending).rejects.toMatchObject({ errors: [expect.objectContaining({ code: 'NATIVE_DISPOSED' }), failure] })
|
||||
const disposing = f.client.dispose()
|
||||
const disposalRejected = expect(disposing).rejects.toBe(failure)
|
||||
f.gone.reject(failure)
|
||||
|
||||
@@ -164,6 +164,9 @@ it('offers setup after inspection, permits dismissal, and dismisses once both pr
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
f.publish({ ...observe(value) })
|
||||
const dialog = screen.getByRole('dialog', { name: en.setupTitle })
|
||||
expect(within(dialog).getByText('Computer use is enabled. Before using it, grant Accessibility and Screen Recording permissions. Open the plugin details to complete setup.')).toBeTruthy()
|
||||
expect(f.props.setPtcDefault).not.toHaveBeenCalled()
|
||||
expect(f.props.setPersistentPtc).not.toHaveBeenCalled()
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: en.openSetup }))
|
||||
expect(onOpenDetails).toHaveBeenCalledOnce()
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: en.later }))
|
||||
@@ -377,6 +380,7 @@ it.each([en, zh])('saves persistent PTC only from its own row and retains failur
|
||||
const f = fixture()
|
||||
render(<PermissionPanel {...f.props} t={makeTranslate(dictionary)} />)
|
||||
const row = screen.getByRole('group', { name: dictionary.persistentTitle })
|
||||
expect(within(row).getByText(dictionary.persistentBody)).toBeTruthy()
|
||||
expect(f.props.setPersistentPtc).not.toHaveBeenCalled()
|
||||
const write = Promise.withResolvers<boolean>()
|
||||
f.props.setPersistentPtc.mockReturnValueOnce(write.promise)
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
/** Standard-mode CUA through Loader, the native executor, and real persistent Node programs. */
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import Include from '@deepseek-ai/cordis-plugin-include'
|
||||
import Loader from '@deepseek-ai/cordis-plugin-loader'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
|
||||
import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local'
|
||||
import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use'
|
||||
import FileSystem from '@deepseek-ai/dsh-fs-local'
|
||||
import LlmRuntime, { createUserMessage, LlmAdapter, ToolCallId } from '@deepseek-ai/dsh-llm'
|
||||
import type { GenerateOptions, LlmResolvedModelInfo, StreamChunk } 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 SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
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 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 { z } from 'zod'
|
||||
import { createNativeFixture, png } from '../../../../snapshots/session/cua-run-code/native-channel.mjs'
|
||||
import { CuaConfig, installCua } from '../src/index.ts'
|
||||
import { Request } from '../src/protocol.ts'
|
||||
|
||||
const programs = [
|
||||
'globalThis.visits = 1; var initialCua = cua; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.getAccessibilityTree({emit:false}); await win.click("0"); await win.getScreenshot(); ({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId, pid: process.pid })',
|
||||
'globalThis.visits++; await win.getAccessibilityTree({emit:false}); await win.click("0"); ({ visits, sameCua: cua === initialCua, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree({emit:false}), pid: process.pid })',
|
||||
'await win.click("0")',
|
||||
]
|
||||
|
||||
class ProgramModel extends LlmAdapter {
|
||||
readonly requests: GenerateOptions[] = []
|
||||
constructor(private readonly programs: readonly string[]) { super() }
|
||||
override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
|
||||
return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] })
|
||||
}
|
||||
async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
|
||||
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: ToolCallId(`cua-program-${this.requests.length}`),
|
||||
name: 'cua_run_code', arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } }
|
||||
yield { type: 'finish', reason: { kind: 'tool-calls' } }
|
||||
return
|
||||
}
|
||||
yield { type: 'block-start', index: 0, blockType: 'text' }
|
||||
yield { type: 'block-end', index: 0, block: { type: 'text', text: 'Fixture programs finished.' } }
|
||||
yield { type: 'finish', reason: { kind: 'stop' } }
|
||||
}
|
||||
}
|
||||
|
||||
async function setup(programs: readonly string[]) {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-'))
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => {
|
||||
try { await ctx.fiber.dispose() } finally { await rm(directory, { recursive: true, force: true }) }
|
||||
})
|
||||
const native = createNativeFixture()
|
||||
const guarded: string[] = []
|
||||
const modules = {
|
||||
llm: LlmRuntime, sessions: SessionStore, projections: SessionProjectionRegistry, systemPrompt: SystemPrompt,
|
||||
tools: ToolRuntime, agents: AgentRegistry, agentLoop: AgentLoop, agentPresets: AgentPresets,
|
||||
fs: FileSystem, workingDirectory: WorkingDirectory, subprocess: Subprocess,
|
||||
sandbox: Sandbox, sandboxPolicy: SandboxPolicy, sharedRuntime: NodeRuntime,
|
||||
attachments: LocalAttachmentStore, computerUse: ComputerUseRegistry, native: NativeToolExecutor,
|
||||
standard: {
|
||||
inject: ['agentPresets'],
|
||||
async * apply(owner: Context) {
|
||||
yield await owner.agentPresets.register({ id: 'standard', plugins: [{ name: 'cordis:native' }] })
|
||||
},
|
||||
},
|
||||
outside: {
|
||||
inject: ['tools'],
|
||||
apply(owner: Context) {
|
||||
owner.tools.register(defineTool({ name: 'outside_cua', description: 'A tool outside the CUA program.', parameters: {},
|
||||
output: { schema: { type: 'string' }, render: () => [] }, execute: async () => 'outside' }))
|
||||
owner.tools.guard((execution) => {
|
||||
if (execution.name !== 'cua') return
|
||||
const operation = Request.parse(execution.arguments)
|
||||
guarded.push(execution.callId)
|
||||
if (operation.method === 'click' && native.state.count === 2) {
|
||||
return { reason: 'The fixture allows two clicks.', info: { name: 'FixtureGuardError', code: 'FIXTURE_CLICK_DENIED' } }
|
||||
}
|
||||
})
|
||||
},
|
||||
},
|
||||
cua: {
|
||||
inject: ['computerUse', 'subprocess', 'tools', 'systemPrompt', 'agents'], Config: CuaConfig,
|
||||
apply(owner: Context, config: CuaConfig) {
|
||||
installCua(owner, config, { helperPath: process.execPath, createChannel: native.createChannel,
|
||||
getGuidance: () => 'Use the CUA object API to inspect and control the selected application.',
|
||||
capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot'],
|
||||
appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' },
|
||||
permissionParameters: (_method, permission, locale) => ({ permission, locale }),
|
||||
})
|
||||
},
|
||||
},
|
||||
}
|
||||
const entries = Object.keys(modules).filter(name => name !== 'native').map(name => ({
|
||||
id: name, name: `cordis:${name}`,
|
||||
...name === 'agentPresets' ? { config: { default: 'standard' } } : {},
|
||||
...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' }] } } : {},
|
||||
}))
|
||||
const configPath = join(directory, 'cordis.yml')
|
||||
await writeFile(configPath, JSON.stringify(entries, null, 2) + '\n')
|
||||
ctx.baseUrl = pathToFileURL(directory).href + '/'
|
||||
await ctx.plugin(Loader)
|
||||
Object.assign(ctx.loader.builtins, modules, { include: Include })
|
||||
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
|
||||
await ctx.loader.await()
|
||||
for (const entry of ctx.loader.entries()) await entry.fiber?.await()
|
||||
const model = new ProgramModel(programs)
|
||||
ctx.llm.registerAdapter(['cua-fixture'], model)
|
||||
const handle = await ctx.agents.create({ sessionId: SessionId('cua-standard-composition'), meta: { cwd: directory },
|
||||
agentOptions: { provider: 'cua-fixture', model: 'vision' },
|
||||
setup: async (owner) => { await ctx.agentPresets.mount(owner, 'standard') },
|
||||
})
|
||||
const agent = handle.agent
|
||||
const idle: PromiseWithResolvers<void> = 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,
|
||||
run: () => {
|
||||
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Inspect and increment the fixture counter.' }], source: { kind: 'user' } }))
|
||||
return idle.promise
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
it('retains CUA objects, guards and logs hidden subcalls, forwards screenshots, and releases the optional provider', async () => {
|
||||
const { ctx, native, guarded, model, agent, provider, run } = await setup(programs)
|
||||
expect(ctx.ptcRuntime.retainsState).toBe(false)
|
||||
expect(ctx.tools.get('cua', agent)).toBeUndefined()
|
||||
expect(ctx.tools.get('cua_run_code', agent)).toBeDefined()
|
||||
await run()
|
||||
|
||||
expect(model.requests).toHaveLength(4)
|
||||
expect(model.requests[0]?.tools?.map(tool => tool.name).sort()).toEqual(['cua_run_code', 'outside_cua'])
|
||||
const results = agent.session.deriveMessages().filter(message => message.role === 'tool')
|
||||
expect(results.map(result => result.isError), JSON.stringify(results)).toEqual([false, false, true])
|
||||
const first = z.object({ visits: z.number(), bindings: z.array(z.string()), app: z.string(), window: z.number(), pid: z.number() })
|
||||
.parse(JSON.parse(results[0]!.content.filter(block => block.type === 'text').map(block => block.text).join('\n')))
|
||||
expect(first).toMatchObject({ visits: 1, bindings: ['cua'], app: 'fixture-app', window: 7 })
|
||||
expect(first.pid).not.toBe(process.pid)
|
||||
expect(JSON.parse(results[1]!.content.filter(block => block.type === 'text').map(block => block.text).join('\n')))
|
||||
.toEqual({ visits: 2, sameCua: true, app: 'fixture-app', window: 7,
|
||||
tree: '- [0] AXButton "Increment"\n- AXStaticText "Count: 2"', pid: first.pid })
|
||||
expect(native.state.count).toBe(2)
|
||||
const dispatches = agent.session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch')
|
||||
expect(dispatches.map(event => event.data.subCallId)).toEqual(guarded)
|
||||
expect(dispatches.every(event => event.data.name === 'cua')).toBe(true)
|
||||
expect(dispatches.filter(event => event.data.rootCallId === 'cua-program-2')
|
||||
.map(event => Request.parse(event.data.arguments).method)).toEqual(['getState', 'click', 'getState'])
|
||||
expect(dispatches.at(-1)?.data).toMatchObject({ rootCallId: 'cua-program-3', isError: true,
|
||||
error: { name: 'FixtureGuardError', code: 'FIXTURE_CLICK_DENIED' } })
|
||||
expect(native.calls.map(call => call.id)).toEqual(guarded.slice(0, -1))
|
||||
const images = model.requests[1]!.messages.flatMap(message => message.content.filter(block => block.type === 'image'))
|
||||
expect(images).toHaveLength(1)
|
||||
const image = images[0]!
|
||||
expect(image.attachment).toMatchObject({ mediaType: 'image/png', width: 1, height: 1 })
|
||||
expect(Buffer.from((await ctx.attachments.readImage(image.attachment)).data).toString('base64')).toBe(png)
|
||||
expect(JSON.stringify(agent.session.deriveMessages())).not.toContain(png)
|
||||
|
||||
await provider.dispose()
|
||||
expect(ctx.tools.schemas(agent).map(tool => tool.name)).toEqual(['outside_cua'])
|
||||
expect((await ctx.systemPrompt.assemble({ scope: agent })).sections.some(section => section.name === 'computer-use:dsh-cua')).toBe(false)
|
||||
expect(native.state).toEqual({ count: 2, openedChannels: 1, closedChannels: 1 })
|
||||
expect(() => process.kill(first.pid, 0)).toThrow()
|
||||
expect(ctx.ptcRuntime.retainsState).toBe(false)
|
||||
})
|
||||
|
||||
it('recreates the automatic facade when its environment is rebuilt', async () => {
|
||||
const { agent, run } = await setup([
|
||||
'var previousCua = cua; "created"',
|
||||
'process.exit(0)',
|
||||
'({ ready: typeof cua.getApp === "function", previous: typeof previousCua })',
|
||||
])
|
||||
await run()
|
||||
const results = agent.session.deriveMessages().filter(message => message.role === 'tool')
|
||||
expect(results.map(result => result.isError), JSON.stringify(results)).toEqual([false, true, false])
|
||||
expect(JSON.parse(results[2]!.content.filter(block => block.type === 'text').map(block => block.text).join('\n')))
|
||||
.toEqual({ ready: true, previous: 'undefined' })
|
||||
})
|
||||
|
||||
it('settles an in-flight native call before releasing the provider connection and program process', async () => {
|
||||
const { ctx, native, agent, provider, run } = await setup([
|
||||
'var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.getAccessibilityTree({emit:false}); process.pid',
|
||||
'await win.click("0")',
|
||||
])
|
||||
const started = native.holdNextClick()
|
||||
let nestedSignalAborted: boolean | undefined
|
||||
ctx.on('tools/result', (execution) => {
|
||||
if (execution.agent === agent && execution.name === 'cua' && execution.rootCallId === 'cua-program-2') {
|
||||
nestedSignalAborted = execution.signal.aborted
|
||||
}
|
||||
})
|
||||
ctx.on('session/event', (session, event) => {
|
||||
if (session !== agent.session) return
|
||||
if (event.type === 'tool/ptc-dispatch' && event.data.rootCallId === 'cua-program-2') native.events.push('subcall-settled')
|
||||
})
|
||||
const completed = run()
|
||||
await Promise.race([
|
||||
started,
|
||||
completed.then(() => {
|
||||
const results = agent.session.deriveMessages().filter(message => message.role === 'tool')
|
||||
throw new Error(`CUA turn ended before the held native click: ${JSON.stringify(results)}`)
|
||||
}),
|
||||
])
|
||||
const first = agent.session.deriveMessages().find(message => message.role === 'tool')
|
||||
const pid = z.number().int().positive().parse(JSON.parse(first!.content.filter(block => block.type === 'text').map(block => block.text).join('\n')))
|
||||
expect(() => process.kill(pid, 0)).not.toThrow()
|
||||
expect(native.state.count).toBe(0)
|
||||
await provider.dispose()
|
||||
await completed
|
||||
|
||||
expect(native.events).toEqual(['native-cancelled', 'subcall-settled', 'native-close'])
|
||||
expect(native.state).toEqual({ count: 0, openedChannels: 1, closedChannels: 1 })
|
||||
const events = agent.session.snapshotEvents()
|
||||
const starts = events.filter(event => event.type === 'tool/ptc-dispatch-start')
|
||||
.filter(event => event.data.rootCallId === 'cua-program-2')
|
||||
const ends = events.filter(event => event.type === 'tool/ptc-dispatch')
|
||||
.filter(event => event.data.rootCallId === 'cua-program-2')
|
||||
expect(starts).toHaveLength(1)
|
||||
expect(ends).toHaveLength(1)
|
||||
// NativeClient owns cancellation diagnostics rather than throwing the signal's AbortError.
|
||||
expect(ends[0]?.data).toMatchObject({ subCallId: starts[0]?.data.subCallId, isError: true,
|
||||
content: [{ type: 'text', text: 'Error: NATIVE_CANCELLED: Operation cancelled; inspect fresh state before retrying input' }] })
|
||||
expect(nestedSignalAborted).toBe(true)
|
||||
const outer = events.filter(event => event.type === 'tool/result')
|
||||
.find(event => event.data.message.toolCallId === 'cua-program-2')
|
||||
expect(outer?.data).toMatchObject({ message: { isError: true },
|
||||
error: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } })
|
||||
expect(agent.session.deriveMessages().filter(message => message.role === 'tool').map(message => message.isError)).toEqual([false, true])
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
expect(ctx.tools.get('cua_run_code', agent)).toBeUndefined()
|
||||
})
|
||||
@@ -21,6 +21,9 @@
|
||||
{
|
||||
"path": "../../core/tools"
|
||||
},
|
||||
{
|
||||
"path": "../../core/tool-executor-ptc"
|
||||
},
|
||||
{
|
||||
"path": "../../core/system-prompt"
|
||||
},
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package:
|
||||
en: 4695160db934a010
|
||||
zh: 90dcd69e2aab43b3
|
||||
en: c5ae9318211c3fb9
|
||||
zh: f297045a12d54098
|
||||
/deepseek-ai-dsh-experimental-ptc-runtime-python/use-this-package/what-you-get:
|
||||
en: ca7b9cc958069c7f
|
||||
zh: 8a4ac72d02ad76eb
|
||||
|
||||
@@ -27,7 +27,7 @@ Run model-generated Python in a fresh CPython 3.10+ process on macOS or Linux un
|
||||
|
||||
Choose this published experimental package only in an explicit composition. Register `PythonPtcRuntime` beside `dsh-tools`; `run(resolve(request))` executes each program in a fresh CPython 3.10+ subprocess, resolving with `result.value` on success and `result.error` on failure (the orthogonal `PtcRunFailure.kind` taxonomy classifies parse failures, thrown exceptions, invalid completions, output overflows, budget expiry, aborts, unavailable confinement, and substrate death). It rejects only for caller misuse, such as malformed bindings, unresolved execution options, or a call after disposal. Configuration is rejected at load: a non-Unix platform; an explicit `pythonBin` that is not an executable regular file or a bare name that does not resolve on `PATH`; a non-CPython, pre-3.10, or probe-failing interpreter; a non-positive or non-integer budget; a `maxLogBytes` below the truncation-marker floor (64); a timer value `setTimeout` would clamp; a budget larger than the effective fd-3 frame cap (lowered when the host heap cannot safely parse a near-cap frame); or an `addressSpaceMb`/output-budget pair whose worst-case peak would breach `RLIMIT_AS`.
|
||||
|
||||
The composition must supply `sandbox` and `sandboxPolicy` for this local execution host. `resolve(request)` accepts an explicit `sandboxPolicy` or resolves the shared deployment policy, and defaults `cwd` to that policy's workspace root. PTC mode supplies the calling Session's policy and directory. The configured `maxWallMs` remains the execution deadline; explicit `timeoutMs` overrides are unsupported.
|
||||
The composition must supply `sandbox` and `sandboxPolicy` for this local execution host. `resolve(request)` accepts an explicit `sandboxPolicy` or resolves the shared deployment policy, and defaults `cwd` to that policy's workspace root. PTC mode supplies the calling Session's policy and directory. The configured `maxWallMs` remains the execution deadline; explicit `timeoutMs` overrides are unsupported and reject during resolution. Environment initializer registration is unsupported.
|
||||
|
||||
`read-only` and `workspace-write` execute through the configured sandbox provider; `danger-full-access` explicitly bypasses confinement. `result.sandbox` reports the mode, observed denial, and the backend's full or partial enforcement separately from the program outcome. The [sandbox service](../../sandbox/sandbox/README.md) defines the file restrictions and backend limits; these modes do not restrict network access or arbitrary file reads.
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ kind: "package-reference"
|
||||
|
||||
仅在显式组合中选择这个已发布的实验包。将 `PythonPtcRuntime` 与 `dsh-tools` 一起注册后,`run(resolve(request))` 会在全新的 CPython 3.10+ 子进程中执行每个程序;成功时以 `result.value` resolve,失败时以 `result.error` resolve(正交的 `PtcRunFailure.kind` 分类涵盖解析失败、抛出异常、无效完成值、输出溢出、预算到期、中止、约束不可用与执行基底终止)。仅有调用方误用会 reject,例如 binding 不合法、执行选项未解析,或在 dispose 后调用。配置在加载期拒绝:非 Unix 平台;不是可执行普通文件的显式 `pythonBin`,或无法在 `PATH` 上解析的裸名;非 CPython、低于 3.10 或探测失败的解释器;非正或非整数预算;低于截断标记下限(64)的 `maxLogBytes`;会被 `setTimeout` 截断的定时器值;超过有效 fd-3 帧上限的预算(宿主堆无法安全解析接近上限的帧时,该上限会降低);或最坏峰值会突破 `RLIMIT_AS` 的 `addressSpaceMb`/输出预算组合。
|
||||
|
||||
组合必须为此本地执行宿主提供 `sandbox` 和 `sandboxPolicy`。`resolve(request)` 接受显式 `sandboxPolicy`,或解析共享部署策略,并将 `cwd` 默认设为该策略的工作区根目录。PTC mode 提供调用 Session 的策略和目录。配置的 `maxWallMs` 仍是执行截止时间;不支持显式 `timeoutMs` 覆盖。
|
||||
组合必须为此本地执行宿主提供 `sandbox` 和 `sandboxPolicy`。`resolve(request)` 接受显式 `sandboxPolicy`,或解析共享部署策略,并将 `cwd` 默认设为该策略的工作区根目录。PTC mode 提供调用 Session 的策略和目录。配置的 `maxWallMs` 仍是执行截止时间;不支持显式 `timeoutMs` 覆盖,解析时会拒绝。不支持注册环境初始化程序。
|
||||
|
||||
`read-only` 和 `workspace-write` 通过配置的沙箱提供方执行;`danger-full-access` 显式绕过约束。`result.sandbox` 独立于程序结果报告模式、观察到的拒绝,以及后端的完整或部分强制能力。[沙箱服务](../../sandbox/sandbox/README.zh.md)定义文件限制与后端局限;这些模式不限制网络访问或任意文件读取。
|
||||
|
||||
|
||||
@@ -972,9 +972,9 @@ export class PythonPtcRuntime extends PtcRuntime {
|
||||
|
||||
/**
|
||||
* Resolve authority, directory, and the configured wall deadline.
|
||||
* @param request - Program inputs and optional resolved sandbox authority; timeout overrides are unsupported.
|
||||
* @param request - Program inputs and optional resolved sandbox authority.
|
||||
* @returns Complete inputs for the provider's run method.
|
||||
* @throws When a requested timeout is unsupported, cwd is relative, or the provider is disposed.
|
||||
* @throws When a timeout override is supplied, cwd is relative, or the provider is disposed.
|
||||
*/
|
||||
resolve(request: PtcRunRequest): PtcRunSpec {
|
||||
if (this.disposed) throw new Error('dsh-ptc-runtime-python: resolve() after disposal')
|
||||
|
||||
@@ -88,6 +88,7 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => {
|
||||
expect(() => runtime.resolve({ ...request, cwd: 'relative' })).toThrow('cwd must be absolute')
|
||||
expect(() => runtime.resolve({ ...request, timeoutMs: 1 })).toThrow('per-call timeout is unsupported')
|
||||
expect(() => runtime.resolve({ ...request, timeoutMs: null })).toThrow('per-call timeout is unsupported')
|
||||
expect(() => runtime.registerEnvironmentInitializer('helper = {}')).toThrow('environment initialization is unsupported')
|
||||
const sandboxPolicy = { mode: 'danger-full-access' as const, workspaceRoot: cwd }
|
||||
expect(runtime.resolve({ ...request, sandboxPolicy }).sandboxPolicy).toBe(sandboxPolicy)
|
||||
await expect(runtime.run({ ...request, cwd, timeoutMs: 30_000 })).rejects.toThrow('run requires a resolved sandbox policy')
|
||||
|
||||
@@ -2684,6 +2684,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
returns: 'Completion after all owned execution resources have been released.',
|
||||
throws: ['When managed resource cleanup fails.'],
|
||||
},
|
||||
{
|
||||
signature: 'registerEnvironmentInitializer(program: string): () => Promise<void>',
|
||||
description: 'Register source evaluated once when each execution environment is created. Registration must precede the first run admission; only one initializer may be registered. Current bindings are installed before initialization. Its completion is discarded; logs, timeout, cancellation and output bounds share the first run. Initialization failure discards the environment without executing the user program or rolling back external effects.',
|
||||
parameters: [{ name: 'program', description: 'Initialization source in the provider\'s language and format.' }],
|
||||
returns: 'An idempotent async disposer that stops admission, cancels and drains admitted runs, and releases environments. Failed cleanup blocks execution until the disposer succeeds on retry. The caller owns this disposer.',
|
||||
throws: ['When unsupported, registered twice, registered after admission, or invalid.'],
|
||||
},
|
||||
{
|
||||
signature: 'abstract resolve(request: PtcRunRequest): PtcRunSpec',
|
||||
description: 'Resolve supported options and provider defaults before execution.',
|
||||
|
||||
@@ -24,8 +24,8 @@
|
||||
en: 2a9fa3292bf07355
|
||||
zh: db0b5684820915eb
|
||||
/deepseek-ai-dsh-ptc-runtime-node/use-this-package/in-memory-modes:
|
||||
en: 41c54a052af70659
|
||||
zh: becb41300547089e
|
||||
en: 2de0a876701fc2c2
|
||||
zh: 330ca97a69528872
|
||||
/deepseek-ai-dsh-ptc-runtime-node/use-this-package/deadlines-and-cancellation:
|
||||
en: d383ec7aeab8afec
|
||||
zh: 7c9c49e205fbbcd8
|
||||
@@ -33,11 +33,11 @@
|
||||
en: 34a221d0f26b8e47
|
||||
zh: 2fd20ac9c9953c7f
|
||||
/deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation:
|
||||
en: 50e6cd38e298da31
|
||||
zh: c8b252b3acf59147
|
||||
en: 8a9dddeafde30b6d
|
||||
zh: d2c95d923f892cc8
|
||||
/deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation/launch-and-control:
|
||||
en: f27d477e3ccb10de
|
||||
zh: 0f14a4899bae6c39
|
||||
en: 5c93014a885ed89e
|
||||
zh: 21daedcd9de8cd7f
|
||||
/deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation/source-and-built-bootstraps:
|
||||
en: b944263ce0b1d200
|
||||
zh: c25a99f01a0d9af5
|
||||
|
||||
@@ -95,6 +95,10 @@ Save the patch and pass its path to `dsh headless --patch <path>` in a compositi
|
||||
|
||||
In REPL mode, each live Agent keeps its own process and top-level variables, functions, and imported modules across `run_code` calls and turns. Use `await import(...)`, `console.log(...)`, and a final JSON expression; top-level `return` is not supported. Assignments to undeclared names create retained globals under Node REPL’s non-strict evaluation. `_` and `_error` are ordinary retained globals, without interactive REPL result setters. Node REPL declaration rules apply, including errors on redeclaring existing `let`, `const`, or `class` names; assign to a mutable binding or choose a new name. A leading `{ ... }` is a statement block and can contain top-level await and temporary declarations; parenthesize an object expression to return it. Retained functions and saved tool methods call the current evaluation's bindings. All tool calls must be awaited; callbacks from a completed evaluation cannot invoke tools in a later evaluation.
|
||||
|
||||
In `persistent-in-memory` mode, call `registerEnvironmentInitializer(program)` before the first run is admitted to install REPL source that executes once per new environment. The runtime installs current bindings first and evaluates initialization separately from the user program, sharing the first call's deadline, cancellation and output limits. It discards the completion value and includes printed output in the result. New owners, owner-less execution, release and process loss create environments that run initialization again; ordinary calls reuse initialized state. Assigning to an initialized global does not trigger initialization. Initialization lines do not shift user-program locations. Other modes reject registration.
|
||||
|
||||
Initialization errors, cancellation, timeout or captured-output overflow prevent the user program from starting and terminate the environment before returning. Earlier external effects remain. Once the Host accepts initialization, user-program failures follow the ordinary retained-state rules below. The [runtime service](../ptc-runtime/README.md#choose-a-backend) defines registration and asynchronous unregistration.
|
||||
|
||||
Memory is best-effort and never saved to disk. Restart, Agent disposal, provider unload, protocol failure, output overflow, or process exit clears it. Missing variables raise normal reference errors; reacquire handles and recreate declarations. Exceptions in the active evaluation settle once and preserve earlier mutations. In REPL mode, exceptions from callbacks belonging to a completed evaluation are not reported in a later result. In Script mode, uncaught callback exceptions can terminate the retained process; await asynchronous work before completing an evaluation. The Session still records programs, tool dispatches and visible results; restoring a Session or forking an Agent starts with empty memory. Each evaluation resets the process working directory to its resolved cwd; program calls to `process.chdir()` do not persist across evaluations. Direct Node access follows the process launch policy. A retained owner cannot change mode, workspace root, or Session identity until its environment is released. Additional writable directories are fixed when the process starts: later grants and revocations apply only after release and recreation.
|
||||
|
||||
Service consumers pass an object as `stateOwner` to reuse its environment and await `release(owner)` when finished. Requests without an owner run in temporary processes. Their failures leave other owners' retained variables intact and do not report clearing them. Permission setters record the new mode synchronously. The runtime immediately invalidates affected processes and begins cancellation when the Session mode changes, including idle environments. The next program waits for their cleanup before starting; cleanup failure blocks that program and remains retryable. Permission-setting success does not mean old processes have finished stopping. A one-time approved escalation uses a separate environment and awaits its cleanup before returning; it cannot read the standing environment's variables or retain new declarations. Concurrent runs for one owner reject until execution and required cleanup complete; distinct owners may run concurrently. An idle environment has no expiration timer and keeps its process until release or failure. Raw stdout/stderr have no evaluation identity: bytes received during an evaluation share its output budget, even when written by an earlier child process; idle stdout is discarded and idle stderr retains only the bounded diagnostic tail. Await child-process completion before ending an evaluation. Process-exit diagnostics include the exit code and retained stderr tail; idle failures are written to the host logger. If process observation fails during cleanup, releasing the owner retries termination; new runs remain blocked until cleanup succeeds. Pipes that fail to drain after confirmed process exit produce a diagnostic but do not prevent releasing the environment.
|
||||
@@ -121,7 +125,7 @@ Program parse errors and thrown exceptions are `exception`; deadline expiry is `
|
||||
|
||||
The host owns policy, deadlines, binding lookup and process cleanup. The child owns program evaluation and binding proxies; model-written code is an untrusted peer even when its messages use the expected control descriptor.
|
||||
|
||||
`createExecution()` resolves the configured syntax, type erasure, model guidance and process lifetime once when the provider loads. The provider handles admission and cancellation. One execution owner creates temporary processes or reuses an enabled state owner's process; both use `ProgramWorker` for launch, deadlines, binding dispatch and cleanup. The shared child loop selects `createProgramEvaluator()` from the evaluation data; async-function, REPL and Script implementations expose globals, evaluation and cleanup operations independently of process lifetime.
|
||||
`createExecution()` resolves the configured syntax, type erasure, model guidance and process lifetime once when the provider loads. The provider handles admission and cancellation. One execution owner creates temporary processes or reuses an enabled state owner's process; both use `ProgramWorker` for launch, deadlines, binding dispatch and cleanup. The shared child loop selects `createProgramEvaluator()` from the evaluation data; async-function, REPL and Script implementations expose globals, evaluation and cleanup independently of process lifetime. Initialization is awaited without adopting its completion value, followed by Host acknowledgement and the user program. The evaluator's completion callback settles the user program immediately; subsequent microtasks cannot log or invoke bindings. REPL diagnostics can also settle the active run.
|
||||
|
||||
### Launch and control
|
||||
|
||||
@@ -129,7 +133,7 @@ The host strips erasable types and, when starting a process, resolves the execut
|
||||
|
||||
Control traffic uses newline-delimited JSON on an inherited pipe separate from stdout/stderr. The RPC adapter bounds each message and queued native writes, rejects pending transport calls on closure, and runs no further methods after closure. Unsupported methods receive error replies. The host validates binding names and lossless JSON before dispatch.
|
||||
|
||||
The host calls the child's `run()` method over birpc on the ordered control pipe. Only one evaluation runs at a time; its asynchronous context prevents ended callbacks from starting new bindings or emitting captured output. RPC requests associate completions and binding replies with their callers. On timeout or cancellation, the host rejects new binding calls and late results, sends a one-way `revoke()` notification, and waits for the original `run()` response within `stopGraceMs`. Revocation rejects unfinished tool calls normally, allowing user `catch` and `finally` handlers to run. A validated response confirms settlement without changing the selected timeout or cancellation outcome. A missing, rejected or malformed response triggers termination. Callers must await settlement or fallback termination and cleanup before starting another evaluation. A blocked event loop cannot process revocation, so synchronous loops require process termination and lose retained state.
|
||||
The host calls the child's `run()` method over birpc on the ordered control pipe. Only one evaluation runs at a time; its asynchronous context prevents ended callbacks from starting new bindings or emitting captured output. RPC requests associate completions and binding replies with their callers. A new environment completes initialization through the acknowledged `initialized()` RPC before user code starts; the Host accepts only while the first run remains active, and the child rechecks cancellation after the reply. On timeout or cancellation after initialization, the host rejects new binding calls and late results, sends a one-way `revoke()` notification, and waits for the original `run()` response within `stopGraceMs`. Revocation rejects unfinished tool calls normally, allowing user `catch` and `finally` handlers to run. A validated response confirms settlement without changing the selected timeout or cancellation outcome. A missing, rejected or malformed response triggers termination. Callers must await settlement or fallback termination and cleanup before starting another evaluation. A blocked event loop cannot process revocation, so synchronous loops require process termination and lose retained state.
|
||||
|
||||
Timers, arbitrary user-created Promises, I/O callbacks, Workers and child processes have no per-evaluation cancellation guarantee. Stop acknowledgment waits for the current evaluation to settle; it does not establish cleanup of those resources. Unmanaged asynchronous work may mutate retained globals after acknowledgment; captured output and completion from ended evaluations are ignored. Await required work before returning and use host reset when resources cannot be trusted.
|
||||
|
||||
|
||||
@@ -95,6 +95,10 @@ profile 编辑器可从 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 导入
|
||||
|
||||
在 REPL 模式下,每个存活 Agent 保留独立进程,跨 `run_code` 调用和轮次保留顶层变量、函数及导入模块。使用 `await import(...)`、`console.log(...)` 和末尾 JSON 表达式;不支持顶层 `return`。Node REPL 使用非严格模式,给未声明的名称赋值会创建保留的全局变量。`_` 和 `_error` 是普通的保留全局变量,不使用交互式 REPL 的结果设置器。声明遵循 Node REPL 规则,包括重复声明已有 `let`、`const` 或 `class` 名称时报错;应给可变绑定赋值或选择新名称。开头的 `{ ... }` 按语句块执行,可以包含顶层 await 和临时声明;需要返回对象表达式时,用圆括号包裹。保留的函数和工具方法引用调用当前执行的绑定。必须等待所有工具调用;已完成执行的回调不能在后续执行中调用工具。
|
||||
|
||||
在 `persistent-in-memory` 模式下,于运行时首次接纳运行前调用 `registerEnvironmentInitializer(program)`,注册在每个新环境中只执行一次的 REPL 源码。运行时先安装本次绑定,再独立于用户程序求值初始化;二者共享首次调用的截止时间、取消和输出上限。初始化的完成值会被丢弃,打印输出加入结果。新所有者、无所有者执行,以及释放或进程丢失后的运行会创建新环境并再次执行初始化;普通调用复用已初始化的状态。给已初始化的全局变量赋值不会触发初始化。初始化行不会偏移用户程序的位置。其他模式会拒绝注册。
|
||||
|
||||
初始化期间的错误、取消、超时或捕获输出超限会阻止用户程序启动,并在返回前终止该环境。此前的外部效果仍然保留。Host 确认初始化完成后,用户程序失败遵循下方的普通状态保留规则。[运行时服务](../ptc-runtime/README.zh.md#choose-a-backend)定义注册和异步注销行为。
|
||||
|
||||
内存按尽力保留处理,不保存到磁盘。重启、Agent 销毁、提供方卸载、协议失败、输出超限或进程退出都会清除内存。缺失变量产生普通引用错误,模型需要重新获取句柄和创建声明。当前执行中的异常只结算一次,并保留此前发生的修改。在 REPL 模式下,已完成执行的回调抛出的异常不会在后续结果中报告。在 Script 模式下,未捕获的回调异常可能终止保留进程;结束执行前应等待异步工作完成。Session 仍记录程序、工具分派和可见结果;恢复 Session 或派生 Agent 时从空内存开始。每次执行都会将进程工作目录重置为本次解析的 cwd;程序中的 `process.chdir()` 不跨执行保留。直接 Node 访问遵循进程启动时的文件策略。保留状态的所有者必须先释放环境,才能更改权限模式、工作区根目录或 Session 身份。额外可写目录在进程启动时固定:之后的授权和撤销仅在释放并重新创建环境后生效。
|
||||
|
||||
服务消费者通过 `stateOwner` 对象复用环境,并在结束时等待 `release(owner)`。没有所有者的请求在临时进程中执行。此类执行失败不影响其他所有者保留的变量,也不报告清空了这些变量。权限设置同步记录新模式。Session 模式变化时,运行时立即禁止复用受影响的进程并开始取消,包括空闲环境。下一次程序执行前等待这些进程清理;清理失败会阻止本次程序启动,并允许重试。权限设置成功时,旧进程可能仍在停止过程中。单次获准的提权使用独立环境,返回前等待清理;该次执行无法访问原环境的变量,也不会保留新声明。执行及必要清理完成之前,同一所有者的并发调用会被拒绝;不同所有者可以并发。空闲环境没有过期计时器,进程保留到释放或失败为止。原始 stdout/stderr 不携带执行标识:执行期间收到的字节计入本次输出预算,包括较早启动的子进程此时写出的内容;空闲期间丢弃 stdout,只保留限额内的 stderr 诊断尾部。结束本次执行前,应等待子进程完成。进程退出诊断包含退出码和保留的 stderr 尾部;空闲期间的失败写入宿主日志。清理期间无法观测进程范围时,释放所有者会重试终止;清理成功前拒绝新执行。确认进程退出后仍未排空的管道会产生诊断,但不阻止释放环境。
|
||||
@@ -121,7 +125,7 @@ PTC 消费方按 [dsh-tool-executor-ptc](../../core/tool-executor-ptc/README.zh.
|
||||
|
||||
Host 负责策略、截止时间、绑定查找和进程清理。子进程负责程序求值与绑定代理;即使使用预期的控制描述符,模型编写的代码仍是不可信对端。
|
||||
|
||||
`createExecution()` 在提供方加载时一次性确定配置对应的语法、类型擦除、模型指导和进程生命周期。提供方处理执行准入与取消。统一的执行所有者创建临时进程,或在启用状态保留时复用所有者的进程;二者都由 `ProgramWorker` 负责启动、截止时间、绑定分派和清理。共用的子进程循环根据本次执行数据选择 `createProgramEvaluator()`;异步函数、REPL 和 Script 实现提供全局变量、求值与清理操作,与进程生命周期独立。
|
||||
`createExecution()` 在提供方加载时一次性确定配置对应的语法、类型擦除、模型指导和进程生命周期。提供方处理执行准入与取消。统一的执行所有者创建临时进程,或在启用状态保留时复用所有者的进程;二者都由 `ProgramWorker` 负责启动、截止时间、绑定分派和清理。共用的子进程循环根据本次执行数据选择 `createProgramEvaluator()`;异步函数、REPL 和 Script 实现提供全局变量、求值与清理操作,与进程生命周期独立。运行时等待初始化求值结束,不等待或展开其完成值;随后等待 Host 确认,再执行用户程序。求值器报告完成时立即结算用户程序;随后运行的微任务不能再输出内容或调用绑定。REPL 诊断也可以结算当前运行。
|
||||
|
||||
### 启动与控制
|
||||
|
||||
@@ -129,7 +133,7 @@ Host 擦除可擦除类型;需要启动进程时,在配置的执行世界中
|
||||
|
||||
控制通信使用继承管道上的逐行 JSON,与 stdout/stderr 分离。RPC 适配层限制每条消息和原生写入队列的大小,在通道关闭时拒绝待完成的传输调用,关闭后不再执行方法。不支持的方法会收到错误回复。Host 在分派前校验绑定名称和无损 JSON。
|
||||
|
||||
Host 通过有序控制管道上的 birpc 调用子进程的 `run()`。同一时间只运行一次执行,其异步上下文阻止已结束执行的回调发起新绑定或发送捕获输出。RPC 请求将执行完成结果和绑定回复关联到各自的调用方。超时或取消时,Host 拒绝新绑定调用及迟到结果,发送单向 `revoke()` 通知,并在 `stopGraceMs` 内等待原 `run()` 响应。撤销会让未完成的工具调用正常抛错,允许用户的 `catch` 和 `finally` 运行。有效响应确认本次执行已结束,不改变已选定的超时或取消结果。未收到响应、请求被拒绝或响应格式无效时,终止进程。调用方必须等待执行结束,或兜底终止及清理完成后,才能开始下一次执行。阻塞的事件循环无法处理撤销,因此同步死循环需要终止进程并丢失保留状态。
|
||||
Host 通过有序控制管道上的 birpc 调用子进程的 `run()`。同一时间只运行一次执行,其异步上下文阻止已结束执行的回调发起新绑定或发送捕获输出。RPC 请求将执行完成结果和绑定回复关联到各自的调用方。新环境在用户代码启动前通过需要确认的 `initialized()` RPC 完成初始化;Host 仅在首次运行仍处于活动状态时接受该调用,子进程收到回复后再次检查取消状态。初始化完成后发生超时或取消时,Host 拒绝新绑定调用及迟到结果,发送单向 `revoke()` 通知,并在 `stopGraceMs` 内等待原 `run()` 响应。撤销会让未完成的工具调用正常抛错,允许用户的 `catch` 和 `finally` 运行。有效响应确认本次执行已结束,不改变已选定的超时或取消结果。未收到响应、请求被拒绝或响应格式无效时,终止进程。调用方必须等待执行结束,或兜底终止及清理完成后,才能开始下一次执行。阻塞的事件循环无法处理撤销,因此同步死循环需要终止进程并丢失保留状态。
|
||||
|
||||
定时器、任意用户创建的 Promise、I/O 回调、Worker 和子进程不承诺按执行取消。停止确认仅等待当前执行结束,不表示这些资源已清理。未受管异步工作在确认停止后仍可能修改保留的全局变量;已结束执行的捕获输出和完成通知会被忽略。返回前应等待必要工作完成,资源不可信时使用宿主重置。
|
||||
|
||||
|
||||
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user