diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index ab2fae6ee9..c3d4ce57a1 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -9,8 +9,8 @@ en: 94ba725bef6684b7 zh: f113745a4a07952a /ptc-runtime/bindings-host-functions-as-program-globals: - en: 182147ddf388c600 - zh: c0a7d77602c78bcd + en: 29085a8c6f939161 + zh: 2dbda3ba96965ed2 /ptc-runtime/captured-output-and-the-failure-taxonomy: en: ef553620e77bd638 zh: 40ff2f5ba3de5ed5 diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index 60c694b13d..a31e09a5fc 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -115,7 +115,7 @@ type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl' ## Bindings: host functions as program globals -Each `PtcBindingNamespace` becomes a global object of async callables; PTC passes `tools`. Arguments and resolutions must be lossless JSON. Providers enforce their own transport caps; the seam sets no uniform binding-byte limit. An optional error-class descriptor creates program-visible typed rejections without naming a consumer inside the runtime. Binding names are own properties, so `__proto__` cannot traverse a prototype: +Each `PtcBindingNamespace` becomes a global object of async callables; PTC passes `tools`. Arguments and resolutions must be lossless JSON, with host-issued `PtcImage` and `PtcInspectableValue` descriptors adapted by the provider. Providers enforce their own transport caps; the seam sets no uniform binding-byte limit. An optional error-class descriptor creates program-visible typed rejections without naming a consumer inside the runtime. Binding names are own properties, so `__proto__` cannot traverse a prototype: ```ts type-equiv /** @@ -168,15 +168,19 @@ type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a - * lossy or non-cloneable value with a descriptive error rather than corrupting - * the run. No seam-level byte cap applies to a binding resolution. A rejection - * of this function surfaces inside the program as a rejection of the - * corresponding call. + * `args` must be lossless JSON; resolutions also support host-issued PtcImage and + * PtcInspectableValue values. An inspectable resolution delivers its JSON object + * or array to the program and uses its text only when that unchanged value is + * inspected directly. A runtime rejects a lossy or non-cloneable value with a + * descriptive error rather than corrupting the run. No seam-level byte cap + * applies to a binding resolution. A rejection of this function surfaces inside + * the program as a rejection of the corresponding call. */ type PtcBindingFunction = (args: unknown) => Promise ``` +`PtcInspectableValue`, exported from `@deepseek-ai/dsh-ptc-runtime`, associates a lossless JSON object or array with host-authored text through `new PtcInspectableValue(value, text)`. The provider delivers the data itself to the program, without exposing the descriptor or adding program-visible properties. Direct `inspect` of the original result uses its text only while the data matches its initial snapshot; empty text emits nothing. Copies, field selections, modified results, and nested values use ordinary formatting. The Node process owns this association, which is neither serialized into Session logs nor transferred by copying a program value. See [`src/inspectable-value.ts`](../../packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts). + ## Captured output and the failure taxonomy `output` contains text and image entries in emission order: `{ type: 'text', text }` or `{ type: 'image', attachment }`. Text entries retain emitted newline characters; concatenate adjacent text without separators. Each source channel preserves emission order; interleaving across independent channels is backend-dependent. Host bindings return `PtcImage` descriptors containing the attachment reference and a readable execution-world `path`; the program receives an `Image` with that path and the stored pixel dimensions. The Node provider caps serialized text, image descriptors, and completion or diagnostic payloads together; overflow is an explicit failure. diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index cc077a243d..2f18872911 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -115,7 +115,7 @@ type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl' ## 绑定:宿主函数作为程序全局变量 -每个 `PtcBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: +每个 `PtcBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON,宿主签发的 `PtcImage` 和 `PtcInspectableValue` 描述符由提供方适配。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: ```ts type-equiv /** @@ -168,15 +168,19 @@ type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a - * lossy or non-cloneable value with a descriptive error rather than corrupting - * the run. No seam-level byte cap applies to a binding resolution. A rejection - * of this function surfaces inside the program as a rejection of the - * corresponding call. + * `args` must be lossless JSON; resolutions also support host-issued PtcImage and + * PtcInspectableValue values. An inspectable resolution delivers its JSON object + * or array to the program and uses its text only when that unchanged value is + * inspected directly. A runtime rejects a lossy or non-cloneable value with a + * descriptive error rather than corrupting the run. No seam-level byte cap + * applies to a binding resolution. A rejection of this function surfaces inside + * the program as a rejection of the corresponding call. */ type PtcBindingFunction = (args: unknown) => Promise ``` +`@deepseek-ai/dsh-ptc-runtime` 导出的 `PtcInspectableValue` 通过 `new PtcInspectableValue(value, text)`,为无损 JSON 对象或数组关联宿主提供的文本。提供方向程序交付数据本身,不暴露描述符,也不添加程序可见属性。只有直接 `inspect` 原结果,且其数据仍与初始快照一致时,才使用附带文本;空文本不产生输出。拷贝、字段选择、修改后的结果和嵌套值使用普通格式。该关联由 Node 进程拥有,不序列化到 Session 日志,复制程序值也不会传递该关联。参见 [`src/inspectable-value.ts`](../../packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts)。 + ## 捕获的输出与失败分类体系 `output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;超限会显式失败。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml new file mode 100644 index 0000000000..09406694d8 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md +/: + en: 31e27f1eb83f9740 + zh: 85c7c3637222f1d8 +/ptc-tool-result-inspection-and-bootstrap-protocol-4: + en: 2509c4fe8d208eb8 + zh: 5f5dfd41fd29cd55 +/ptc-tool-result-inspection-and-bootstrap-protocol-4/change: + en: 14d531566c61b5cf + zh: eeb7a3867b27a918 +/ptc-tool-result-inspection-and-bootstrap-protocol-4/migration: + en: bfb868b271b5113d + zh: 597c95d985891d43 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md new file mode 100644 index 0000000000..416f3351b6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md @@ -0,0 +1,32 @@ +--- +kind: upgrade-guide +description: "Direct inspection of unchanged PTC object and array tool results uses tool-rendered text, and custom Node bootstraps require protocol 4." +--- + +# PTC tool-result inspection and bootstrap protocol 4 + +English | [中文](guide.zh.md) + +## Change + +PTC tools keep their declared JSON return values. With or without inspection metadata, field access, copying, and JSON serialization operate on the original data; the host-only descriptor is not exposed to the program. Previously, `inspect(result)` formatted an object or array with Node's generic object formatter. It now displays the tool's final rendered text when the original result is unchanged and its output contains only text. The text includes completed output-policy changes; inspection neither reruns the tool nor calls `output.render` again. Log-only replacements do not affect it. + +Field selections, copies, modified results, and results nested inside another value still use generic formatting. Scalar results, Images, and mixed text/image outputs keep their behavior. This affects programs and checks that depend on the exact text produced by inspecting a complete tool result. + +The Node bootstrap protocol changes from 3 to 4. `HostMethods.invoke` replies now use `{ value: flatWire, inspection?: string }`. Custom `launch.bootstrapPath` deployments must update their bootstrap; the bundled bootstrap updates with the host. + +## Migration + +1. Keep `inspect(result)` to display the tool's rendered text. To display an object's structure, inspect a copy or selected fields: + + ```js + const result = await tools.read({ file_path: "README.md" }); + inspect(result); + inspect({ ...result }); + inspect(result.lines); + ``` + +2. For an array result, use `inspect([...result])` to display its elements with generic formatting. Update any expected output that relied on the previous full-result object formatting. +3. If you implement a third-party `PtcRuntime`, recognize `PtcInspectableValue` binding results from `@deepseek-ai/dsh-ptc-runtime`. Deliver `.value` as the program's object or array, and associate `.text` with that unchanged value for direct `inspect`. Do not expose the wrapper or add inspection metadata to program fields. +4. If you configure `launch.bootstrapPath`, deploy the matching `@deepseek-ai/dsh-ptc-runtime-node` bootstrap and its dependencies in that execution environment. Use the package's built `lib/process.js`, or `lib/persistent-process.js` for a REPL default. A custom protocol implementation must handle the new reply envelope as well as announce protocol 4; changing the version alone is insufficient. +5. Run the example above. Confirm that the first inspection shows the tool's rendered file text, while the other two show object and array data. For a custom provider, also confirm that field access and `JSON.stringify(result)` use the original data. For a custom bootstrap, confirm that a PTC program starts without a protocol-mismatch error. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md new file mode 100644 index 0000000000..edc10f6ee4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md @@ -0,0 +1,32 @@ +--- +kind: upgrade-guide +description: "直接展示未修改的 PTC 工具对象和数组结果时使用工具渲染文本,自定义 Node bootstrap 须升级到协议 4。" +--- + +# PTC 工具结果展示与 bootstrap 协议 4 + +[English](guide.md) | 中文 + +## 变更 + +PTC 工具保留声明的 JSON 返回值。无论是否附带展示元数据,字段访问、拷贝和 JSON 序列化都操作原有数据;只供宿主使用的描述符不会暴露给程序。此前,`inspect(result)` 使用 Node 的通用对象格式展示对象或数组。现在,原结果未被修改且其输出仅包含文本时,会展示工具最终渲染的文本。该文本包含已完成的输出策略修改;展示不会重新运行工具或再次调用 `output.render`。仅针对日志的替换不影响此文本。 + +字段选择、拷贝、修改后的结果,以及嵌套在其他值中的结果,仍使用通用格式。标量结果、Image 和混合文本与图片的输出保持原有行为。依赖完整工具结果展示文本的程序和检查会受到影响。 + +Node bootstrap 协议从 3 升至 4。`HostMethods.invoke` 的回复现在使用 `{ value: flatWire, inspection?: string }`。自定义 `launch.bootstrapPath` 部署必须更新 bootstrap;内置 bootstrap 随宿主一同更新。 + +## 迁移 + +1. 保留 `inspect(result)` 可展示工具渲染的文本。如需展示对象结构,改为展示拷贝或选定字段: + + ```js + const result = await tools.read({ file_path: "README.md" }); + inspect(result); + inspect({ ...result }); + inspect(result.lines); + ``` + +2. 对数组结果,使用 `inspect([...result])` 以通用格式展示元素。更新依赖此前完整结果对象格式的预期输出。 +3. 如果实现了第三方 `PtcRuntime`,请识别绑定返回的 `@deepseek-ai/dsh-ptc-runtime` 包中的 `PtcInspectableValue`。将 `.value` 作为程序的对象或数组,并为该未修改的原值关联 `.text`,供直接 `inspect` 使用。不要暴露包装对象,也不要向程序字段添加展示元数据。 +4. 如果配置了 `launch.bootstrapPath`,请在执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node` bootstrap 及其依赖。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`。自定义协议实现必须处理新的回复信封并声明协议 4;只改版本号并不足够。 +5. 运行上面的示例。确认第一次展示工具渲染的文件文本,后两次分别展示对象和数组数据。对于自定义提供方,还须确认字段访问和 `JSON.stringify(result)` 使用原有数据。对于自定义 bootstrap,确认 PTC 程序启动时不再报告协议不匹配。 diff --git a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts index 0cee57d7bf..077baefc03 100644 --- a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts +++ b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts @@ -5,7 +5,7 @@ import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc' import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client' -import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcRunRequest, PtcRunSpec, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import { estimateContent } from '@deepseek-ai/dsh-token-meter/estimate' import type { ToolCallId } from '@deepseek-ai/dsh-llm' @@ -61,7 +61,8 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl async run(spec: PtcRunSpec): Promise { const tool = spec.bindings.find(binding => binding.global === 'tools')?.functions[name] if (tool === undefined) throw new Error('missing fixture binding') - const blocks = await tool(shellArgs) + const resolved = await tool(shellArgs) + const blocks = resolved instanceof PtcInspectableValue ? resolved.value : resolved expect(blocks).toEqual([{ type: 'text', text }]) return { output: [{ type: 'text', text: 'true' }] } } diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 1974e1e0f9..076e8b9d12 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-executor-ptc/use-this-package: - en: a883aa8ddca03a66 - zh: c926a9100d2b506f + en: 5e30a05bb69e7ebe + zh: caecedba18dcae4f /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation: en: 78708b3779d999a9 zh: ad6173f9f01630de /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode: - en: d93c8f10d1247f80 - zh: a35d953631ca1c83 + en: 7a333c47e918dc37 + zh: b310c87b9ed3900b /deepseek-ai-dsh-tool-executor-ptc/further-exploration: en: ee69078c38c655a9 zh: fb0873407f23c8c5 diff --git a/packages/core/tool-executor-ptc/README.md b/packages/core/tool-executor-ptc/README.md index 3cdbebcf8c..b9a809566e 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -40,6 +40,8 @@ Root `run_code` calls are exclusive and execute serially. `maxParallelSubCalls` `PtcRuntime` providers must report `language: 'typescript'`. The selected executor rejects other languages during prompt assembly and execution, without falling back to native tools; the `/run-code` factory rejects them when creating a program tool. Schema reads and execution also validate the current provider. The executor generates a TypeScript SDK and tool schema; the provider supplies execution. +Tool calls retain their declared JSON return values. Passing an unchanged object or array result directly to `inspect` displays the tool's final text-only output. Fields, copies, modified results, and results nested inside another value use ordinary Node formatting. Use `inspect({ ...result })` for an object's raw structure or `inspect(result.lines)` for selected fields. Scalar results use ordinary formatting; Images and mixed text/image outputs follow the image rules below. + This package declares `ctx.ptcRuntime` and `ctx.systemPrompt` as required injections; Agent-owned programs need `ctx.workingDirectory`. The executor activates only after its runtime is available and withdraws when that runtime unloads. An enabled PTC executor without a runtime stops application startup. A withdrawn PTC selection never falls back to native execution. 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. @@ -64,6 +66,8 @@ The executor receives the entire raw call batch and owns parsing, scheduling, ca The PTC executor exposes the reserved `run_code` transport and a deterministic TypeScript SDK. Each SDK binding captures a frozen ToolSchema and passes it through the scheduler to its execution context. Before policy, a started call records only pairing ids, name, and normalized arguments; its settle event preserves the rendered result, optional presentation metadata, and structured error. Metadata is projected from that call’s canonical value and frozen; it changes neither the program value nor model content. Description and parameters remain transient and never enter Session events or SDK output. Calls are scheduled through a per-run pool that reuses the native concurrency contract. Under `ptc` alone, a model-direct call naming a program-only SDK tool resolves to `UNKNOWN_TOOL` before policy — the announced surface and the callable surface stay the same. Intermediate binding values are execution-local; only the outer `run_code` result has a hard size cap. +Text inspection reuses the completed pipeline's `output.render` result after content policies. It neither executes the tool nor renders it again. Replacements made only for the dispatch log do not change the program's inspection text. + New sub-calls use `:ptc:` ids. Consumers treat these ids as opaque and correlate events by exact equality; restored historical ids retain their original bytes. The [PTC mode decision](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) owns durable naming and restoration rules. TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution. diff --git a/packages/core/tool-executor-ptc/README.zh.md b/packages/core/tool-executor-ptc/README.zh.md index ab4de1124c..e5581f62b5 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -40,6 +40,8 @@ kind: "package-reference" `PtcRuntime` 提供方必须报告 `language: 'typescript'`。已选中的执行器在提示词组装与执行时拒绝其他语言,不回落到 native 工具;`/run-code` 工厂在创建程序工具时拒绝其他语言。读取 schema 和执行时也会验证当前提供方。执行器生成 TypeScript SDK 与工具 schema;提供方负责执行。 +工具调用保留声明的 JSON 返回值。将未修改的对象或数组结果直接传给 `inspect`,会展示工具最终的纯文本输出。字段、拷贝、修改后的结果,以及嵌套在其他值中的结果,使用普通 Node 格式。可用 `inspect({ ...result })` 查看对象的原始结构,或用 `inspect(result.lines)` 展示选定字段。标量结果使用普通格式;Image 和混合文本与图片的输出遵循下文的图片规则。 + 本包将 `ctx.ptcRuntime` 和 `ctx.systemPrompt` 声明为必需注入;带 Agent 的程序要求 `ctx.workingDirectory`。执行器在运行时可用后才激活,并在运行时卸载时撤回。启用 PTC 执行器但未提供运行时会阻止应用启动。已撤回的 PTC 选择不会回退到原生执行。 共享分派事件与 `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`,无需挂载执行器。 @@ -64,6 +66,8 @@ kind: "package-reference" PTC 执行器公开保留的 `run_code` 传输,以及确定性的 TypeScript SDK。每个 SDK 绑定捕获冻结的 ToolSchema,经由调度器传入该次执行上下文。已开始的调用在策略之前只记录配对 id、名称和规范化参数;其结算事件保留渲染结果、可选展示元数据与结构化错误;元数据由该次调用的规范值投影并冻结,不改变程序读取的值或模型内容。描述与参数 schema 仅临时存活,不进入 Session 事件或 SDK 输出。调用通过复用原生并发约定的每次运行独有池调度。在纯 `ptc` 下,模型直呼仅供程序使用的 SDK 工具都会在策略之前解析为 `UNKNOWN_TOOL`——通告面与可调用面保持一致。中间绑定值只存在于执行局部;只有外层 `run_code` 结果有硬大小上限。 +文本展示复用已完成流水线中经过内容策略处理的 `output.render` 结果,不会再次执行工具或渲染。仅针对派发日志的替换不改变程序的展示文本。 + 新子调用使用 `:ptc:` 标识。消费方将这些标识视为不透明值,并通过精确相等关联事件;恢复的历史标识保留原始字节。[PTC mode 决策](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md) 负责持久化命名与恢复规则。 TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。 diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index aa8158d8ad..734971cf82 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -13,7 +13,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' -import { PtcImage } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcImage, PtcInspectableValue } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcOutput } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcBindingFunction, PtcRunResult, PtcRunSandbox, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import { approveEscalation, ESCALATION_TARGETS, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' @@ -609,6 +609,10 @@ export function createRunCodeTransport( } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } + if (outcome.value !== null && typeof outcome.value === 'object' + && outcome.content.every(block => block.type === 'text')) { + return new PtcInspectableValue(outcome.value, outcome.content.map(block => block.text).join('\n')) + } return outcome.value } diff --git a/packages/core/tool-executor-ptc/tests/ptc.spec.ts b/packages/core/tool-executor-ptc/tests/ptc.spec.ts index 72776d464d..f6934e052d 100644 --- a/packages/core/tool-executor-ptc/tests/ptc.spec.ts +++ b/packages/core/tool-executor-ptc/tests/ptc.spec.ts @@ -14,7 +14,7 @@ import type { ToolSchema } from '@deepseek-ai/dsh-llm' import { createScope } from '@deepseek-ai/dsh-scope' import type { Scope } from '@deepseek-ai/dsh-scope' import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcRuntime, PtcRuntimeError, PtcInspectableValue } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcRunFailure, PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import ToolRuntime, { RUN_CODE_NAME, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, defineTool } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' @@ -175,6 +175,66 @@ async function runCode( }) } +it('carries final tool rendering with structured binding values independently of the durable log copy', async () => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + try { + const render = vi.fn((_args: unknown, value: { count: number }) => [{ type: 'text' as const, text: `Count: ${value.count}` }]) + ctx.tools.register(defineTool({ + name: 'count', description: 'Count a fixture.', parameters: {}, + output: { + schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'number', required: true } } }, + render, + }, + execute: async () => ({ count: 2 }), + finalizeContent: () => [{ type: 'text', text: 'Final count: 2' }], + })) + ctx.on('tools/ptc-dispatch-log', async () => [{ type: 'text', text: 'Durable preview' }]) + const session = Session.create(brandString('ptc-inspection')) + const agent = { ctx, session } as Agent + runtime.behavior = async (request) => { + const result = await request.bindings[0]!.functions.count!({}) + expect(result).toBeInstanceOf(PtcInspectableValue) + if (!(result instanceof PtcInspectableValue)) throw new Error('Expected rendered binding value') + expect(result.value).toEqual({ count: 2 }) + expect(result.text).toBe('Final count: 2') + return printed(result.text) + } + const result = await runCode(ctx, 'inspect(await tools.count({}))', { agent }) + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: 'Final count: 2' }]) + expect(render).toHaveBeenCalledOnce() + expect(session.snapshotEvents().find(event => event.type === 'tool/ptc-dispatch')?.data.content) + .toEqual([{ type: 'text', text: 'Durable preview' }]) + } finally { + await ctx.fiber.dispose() + } +}) + +it.each([{ value: [] }, { value: [1, 2] }])('carries rendered text for array binding value $value', async ({ value }) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + try { + ctx.tools.register(defineTool({ + name: 'list', description: 'List a fixture.', parameters: {}, + output: { + schema: { type: 'array', items: { type: 'number' } }, + render: () => [{ type: 'text', text: 'List:' }, { type: 'text', text: `${value.length} items` }], + }, + execute: async () => value, + })) + runtime.behavior = async (request) => { + const result = await request.bindings[0]!.functions.list!({}) + expect(result).toBeInstanceOf(PtcInspectableValue) + if (!(result instanceof PtcInspectableValue)) throw new Error('Expected rendered binding value') + expect(result.value).toEqual(value) + expect(result.text).toBe(`List:\n${value.length} items`) + return printed(result.text) + } + expect((await runCode(ctx, 'inspect(await tools.list({}))')).isError).toBe(false) + } finally { + await ctx.fiber.dispose() + } +}) + it('logs detached frozen nested metadata without changing the binding value or log-content policy', async () => { const { ctx, runtime } = await setup({ mode: 'ptc' }) try { @@ -1715,7 +1775,13 @@ describe('the run_code dispatch bridge', () => { name: 'cua', description: 'Return a text observation.', parameters: {}, execute: () => Promise.resolve([{ type: 'text', text: 'Window selected' }]), })) - runtime.behavior = async request => printed(await request.bindings[0]!.functions.cua!({})) + runtime.behavior = async (request) => { + const result = await request.bindings[0]!.functions.cua!({}) + expect(result).toBeInstanceOf(PtcInspectableValue) + if (!(result instanceof PtcInspectableValue)) throw new Error('Expected rendered binding value') + expect(result.text).toBe('Window selected') + return printed(result.value) + } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) diff --git a/packages/document/tool-office/tests/activation.spec.ts b/packages/document/tool-office/tests/activation.spec.ts index fdbf5a7bd8..b2f2f0703c 100644 --- a/packages/document/tool-office/tests/activation.spec.ts +++ b/packages/document/tool-office/tests/activation.spec.ts @@ -9,7 +9,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, LlmAdapter, type ToolCallId, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' -import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { type SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SkillRegistry from '@deepseek-ai/dsh-skill' @@ -56,7 +56,8 @@ class SkillRuntime extends PtcRuntime { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } async run(request: PtcRunRequest): Promise { - return { output: [], value: await request.bindings[0]!.functions.skill!({ name: this.skill }) } + const resolved = await request.bindings[0]!.functions.skill!({ name: this.skill }) + return { output: [], value: resolved instanceof PtcInspectableValue ? resolved.value : resolved } } } diff --git a/packages/fs/tool-fs/tests/apply-patch.spec.ts b/packages/fs/tool-fs/tests/apply-patch.spec.ts index 4bda7ba731..db8bc0930f 100644 --- a/packages/fs/tool-fs/tests/apply-patch.spec.ts +++ b/packages/fs/tool-fs/tests/apply-patch.spec.ts @@ -5,7 +5,7 @@ import type { Context } from '@deepseek-ai/cordis' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import { expect, it, vi } from 'vitest' import { FsError } from '@deepseek-ai/dsh-fs' -import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import { executeModelToolFixture, executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' import type { PtcRunRequest, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { add, move, patch, remove, setup, update } from './patch/harness.ts' @@ -163,7 +163,9 @@ class PatchPtcRuntime extends PtcRuntime { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } async run(request: PtcRunSpec) { - return { output: [{ type: 'text' as const, text: JSON.stringify(await request.bindings[0]!.functions.apply_patch!({ input: this.patch })) }] } + const resolved = await request.bindings[0]!.functions.apply_patch!({ input: this.patch }) + const value = resolved instanceof PtcInspectableValue ? resolved.value : resolved + return { output: [{ type: 'text' as const, text: JSON.stringify(value) }] } } } diff --git a/packages/fs/tool-fs/tests/integration.spec.ts b/packages/fs/tool-fs/tests/integration.spec.ts index 1ac0cb35b2..572d9b5591 100644 --- a/packages/fs/tool-fs/tests/integration.spec.ts +++ b/packages/fs/tool-fs/tests/integration.spec.ts @@ -16,7 +16,7 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy' import type { ToolCallId } from '@deepseek-ai/dsh-llm' import type { FsVersion } from '@deepseek-ai/dsh-fs' @@ -639,7 +639,8 @@ describe('current working directory', () => { async run(spec: PtcRunSpec): Promise { const read = spec.bindings.find(binding => binding.global === 'tools')?.functions.read if (read === undefined) throw new Error('missing read binding') - const value = await read({ file_path: 'note.txt' }) + const resolved = await read({ file_path: 'note.txt' }) + const value = resolved instanceof PtcInspectableValue ? resolved.value : resolved expect(JSON.stringify(value)).toContain('current') return { output: [], value } } diff --git a/packages/mcp/mcp-resources/tests/resources.spec.ts b/packages/mcp/mcp-resources/tests/resources.spec.ts index 780ef7d81b..ffdaabff8c 100644 --- a/packages/mcp/mcp-resources/tests/resources.spec.ts +++ b/packages/mcp/mcp-resources/tests/resources.spec.ts @@ -9,7 +9,7 @@ import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools' import type { ToolCallId } from '@deepseek-ai/dsh-llm' import type { Agent } from '@deepseek-ai/dsh-agent' import { bindScopeParent, createScope, type Scope } from '@deepseek-ai/dsh-scope' -import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import McpResources, { type McpResourceProvider } from '../src/index.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -211,7 +211,8 @@ describe('MCP resource tools', () => { const runtime = ctx.ptcRuntime as BindingProbe runtime.behavior = async (spec) => { const binding = spec.bindings[0]!.functions['list_mcp_resources']! - expect(await binding({ server: 'docs' })).toEqual({ resources: [] }) + const resolved = await binding({ server: 'docs' }) + expect(resolved instanceof PtcInspectableValue ? resolved.value : resolved).toEqual({ resources: [] }) remove() await expect(binding({ server: 'docs' })).rejects.toThrow('unknown tool') return { output: [] } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 190d0444b9..1821f0a62d 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -18,7 +18,7 @@ import UserQuestionService, { UserQuestionError, type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' import CommandRuntime from '@deepseek-ai/dsh-commands' -import { PtcRuntime, type PtcRunRequest, type PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import PlanModeController, { EXIT_PLAN_MODE, planProjectionDefinition, resolveConfig } from '../src/index.ts' import type { PlanModeConfig } from '../src/index.ts' @@ -954,7 +954,8 @@ describe('exit_plan_mode', () => { async run(request: PtcRunRequest): Promise { const exit = request.bindings[0]?.functions[EXIT_PLAN_MODE] if (exit === undefined) throw new Error('missing exit_plan_mode binding') - return { output: [], value: await exit({ plan }) } + const resolved = await exit({ plan }) + return { output: [], value: resolved instanceof PtcInspectableValue ? resolved.value : resolved } } } const ctx = new Context() diff --git a/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml index 671ffd09cf..f3da7d7e31 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2be5e2e5d17c7c7f zh: 4de138d85dea1614 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/execution-and-results: - en: b1a7149f2981cf2e - zh: a218e2ab9a23465c + en: 94885c3faa76ca2b + zh: 80cb05e367ffd5ff /deepseek-ai-dsh-ptc-runtime-node/use-this-package/in-memory-modes: en: a8550e22c243b40d zh: 59847954dd88f24d @@ -39,8 +39,8 @@ en: 5c93014a885ed89e zh: 21daedcd9de8cd7f /deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation/source-and-built-bootstraps: - en: b944263ce0b1d200 - zh: c25a99f01a0d9af5 + en: 12a242c6d56ef7dd + zh: a5a1a0811c266fcc /deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation/runner-import-handling: en: ccde763016c0e039 zh: fd881e88391a9d90 @@ -57,8 +57,8 @@ en: 40294c1c31b74824 zh: d91e7b78c0619c7e /deepseek-ai-dsh-ptc-runtime-node/known-limitations-and-deferred-work: - en: 3d260b70ab60f6c5 - zh: ac70d40071966711 + en: 66d2a67411aecb34 + zh: 9ccb065e98f432b5 /deepseek-ai-dsh-ptc-runtime-node/known-limitations-and-deferred-work/dev-note: en: 6373aba4e08f7205 zh: 2a8c33d1f2839df4 diff --git a/packages/ptc-runtime/ptc-runtime-node/README.md b/packages/ptc-runtime/ptc-runtime-node/README.md index a1734d88ae..03cb435628 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.md @@ -70,7 +70,9 @@ Profile editors can import `resolvePersistentExecution` from `@deepseek-ai/dsh-p In `per-call` mode, programs are async function bodies: top-level `await` and `return` work, and only erasable TypeScript is accepted. Node globals remain available, and a function body may declare a local `process`, including `const process = await import("node:process")`. A successful call returns its lossless-JSON value as `result.value` and captured text and images as ordered `result.output` entries. `result.sandbox` reports the selected mode, observed denial and the backend's full or partial enforcement independently of the program outcome. -`inspect(...values)` renders strings directly and other values with Node's `util.inspect`, without depth, array-length or string-length preview limits. Undefined properties, Error objects and circular references remain visible. Registered Images are emitted directly or when Node's formatting reaches them in nested values, including Map entries, Set values and enumerable Symbol properties. Custom inspection methods determine which nested values are visited. Text and selected images follow argument order within the shared output budget. If object formatting throws, preceding inspected arguments remain visible. Each emitted text group ends in a newline; raw stream writes retain their original text. +`inspect(...values)` uses binding-supplied text for an unchanged result passed directly as an argument. A host binding supplies this text through `PtcInspectableValue`; the program still receives the JSON object or array. Copies, selected fields, modified results, and results nested inside another value use ordinary formatting. The process owns the association with the original value and its initial snapshot; program properties do not carry it. + +For other values, `inspect(...values)` renders strings directly and uses Node's `util.inspect`, without depth, array-length or string-length preview limits. Undefined properties, Error objects and circular references remain visible. Registered Images are emitted directly or when Node's formatting reaches them in nested values, including Map entries, Set values and enumerable Symbol properties. Custom inspection methods determine which nested values are visited. Text and selected images follow argument order within the shared output budget. If object formatting throws, preceding inspected arguments remain visible. Each emitted text group ends in a newline; raw stream writes retain their original text. All execution modes provide the complete native Node console, whose stdout and stderr writes enter the captured output. Model instructions say: "Use inspect(...values) to display output. Do not use console." @@ -154,6 +156,8 @@ Per-call completion leaves unfinished binding waits pending and stops binding ca Source execution loads an erasable-only bootstrap closure without relying on sibling built exports; its evaluator modules and installed Acorn and birpc dependencies must be available in the execution world. Built script execution uses `process.js` for every mode; `persistent-process.js` delegates to the same loop with a REPL default for hosts that omit program syntax. Embedded carriers launch their private worker through `launch.executable` and carry the program format and retention flag in each evaluation. A remote script deployment supplies the matching `launch.bootstrapPath`. `resolveLaunch()` selects the local default during construction; an explicit remote invocation never depends on whether the client itself is packaged. A host path is never assumed to name the same remote file. +Custom `launch.bootstrapPath` deployments must use bootstrap protocol 4. `HostMethods.invoke` replies contain `{ value: flatWire, inspection?: string }`; the optional text is associated with the decoded object or array for direct inspection. Deploy the matching bootstrap with the host; the [upgrade guide](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md) covers migration from protocol 3. + Source containing `await` is checked for top-level await before native compilation, which can otherwise treat `await` as an identifier. Acorn parses an async wrapper, and acorn-walk traverses it using Node's REPL visitors, declaration hoisting and character-position edits. Computed class-method keys are traversed while method bodies remain separate evaluations. The transform boxes the final expression; the evaluator unwraps and awaits its value. Source that needs no lowering uses native compilation; submissions without `await` retain native syntax diagnostics. Syntax errors preserve the parser message and available source location and caret, without compiler or transformer stack frames. Dynamic `import()` expressions remain native and use the compiling Script's `importModuleDynamically` option. Both private process bundles include Acorn, acorn-walk and birpc; source execution imports the installed packages. @@ -243,6 +247,7 @@ These limits qualify the execution guarantees and retained output. - **In-memory environments retain one process per live owner** — idle owners keep their process and heap until explicit release, owner disposal or failure. Fan-out can retain many processes; idle expiration remains deferred. - **Output caps reject rather than retain every byte** — spill can preserve only the bounded result delivered by this provider. - **Formatting allocates before output accounting** — complete object and TypedArray formatting can require much more memory than the retained output. The output budget does not cap these temporary allocations; exhausting the configured heap can end the run with `worker-exit`. +- **Tool-result inspection retains extra data** — retaining an original tool result also retains its initial JSON snapshot and rendered text within the same heap budget; direct `inspect` compares the complete data. - **Bindings are bounded at transport admission** — control limits do not bound the memory a host binding allocates while producing its result. - **Preinstalled bootstraps require a compatible protocol revision** — readiness rejects a missing or mismatched revision before dispatching code. Upgrade `launch.bootstrapPath` with the host; the runtime does not install remote bootstrap updates. - **Image references live with the process** — every acquired image retains host metadata until the process terminates or its owner is released, including images that the program never displays. Long capture loops in retained environments accumulate these references. diff --git a/packages/ptc-runtime/ptc-runtime-node/README.zh.md b/packages/ptc-runtime/ptc-runtime-node/README.zh.md index ae96cab0a7..7ff8815e4d 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.zh.md @@ -70,7 +70,9 @@ profile 编辑器可从 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 导入 `per-call` 模式中的程序是异步函数体:支持顶层 `await` 与 `return`,且只接受可擦除 TypeScript。Node 全局变量仍然可用,函数体可声明局部 `process`,例如 `const process = await import("node:process")`。成功调用以 `result.value` 返回无损 JSON 值,以 `result.output` 按顺序返回捕获的文本和图片。`result.sandbox` 独立于程序结果报告所选模式、观察到的拒绝,以及后端完整或部分的强制能力。 -`inspect(...values)` 直接渲染字符串,其他值使用 Node 的 `util.inspect` 格式,不限制预览深度、数组项数或字符串长度。undefined 属性、Error 对象和循环引用均会展示。注册的 Image 可以直接输出,也可以在 Node 格式化嵌套值时输出,包括 Map 条目、Set 的值以及可枚举的 Symbol 属性。自定义 inspect 方法决定会访问哪些嵌套值。文本和所选图片在共享输出预算内遵循参数顺序。如果对象格式化抛错,此前 inspect 的参数仍然可见。每个文本输出组以换行结尾,原始流写入则保留实际文本。 +将未修改的原结果直接作为参数传给 `inspect(...values)` 时,会使用绑定附带的文本。宿主绑定通过 `PtcInspectableValue` 提供文本;程序仍收到 JSON 对象或数组。拷贝、选定字段、修改后的结果,以及嵌套在其他值中的结果,使用普通格式。进程保存原值、初始快照与展示文本的关联;程序对象的属性不携带该关联。 + +对于其他值,`inspect(...values)` 直接渲染字符串,并使用 Node 的 `util.inspect` 格式化其他类型,不限制预览深度、数组项数或字符串长度。undefined 属性、Error 对象和循环引用均会展示。注册的 Image 可以直接输出,也可以在 Node 格式化嵌套值时输出,包括 Map 条目、Set 的值以及可枚举的 Symbol 属性。自定义 inspect 方法决定会访问哪些嵌套值。文本和所选图片在共享输出预算内遵循参数顺序。如果对象格式化抛错,此前 inspect 的参数仍然可见。每个文本输出组以换行结尾,原始流写入则保留实际文本。 所有执行模式都提供完整的 Node 原生 console,其 stdout 和 stderr 写入会进入捕获输出。模型指引要求:“使用 inspect(...values) 展示输出,不要使用 console。” @@ -154,6 +156,8 @@ Host 通过有序控制管道上的 birpc 调用子进程的 `run()`。同一时 源代码执行加载仅含可擦除语法的 bootstrap 依赖,不依赖同级包的构建后导出;执行世界中必须提供求值器模块和已安装的 Acorn 与 birpc 依赖。构建后脚本对所有模式使用 `process.js`;`persistent-process.js` 委托同一个循环,并为未指定程序语法的宿主提供 REPL 默认值。内嵌载体通过 `launch.executable` 启动私有 worker,并在每次执行中携带程序格式和保留标志。远端脚本部署提供对应的 `launch.bootstrapPath`。`resolveLaunch()` 在构造时选择本地默认值;显式的远端调用不依赖客户端自身是否打包。不会假设 Host 路径对应同一个远程文件。 +自定义 `launch.bootstrapPath` 部署必须使用 bootstrap 协议 4。`HostMethods.invoke` 的回复包含 `{ value: flatWire, inspection?: string }`;可选文本与解码后的对象或数组关联,供直接展示使用。请与宿主一起部署匹配的 bootstrap;[升级指南](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md)说明了从协议 3 迁移的步骤。 + 包含 `await` 的源码会在原生编译前检查顶层 await,否则原生编译可能将 `await` 当作标识符。Acorn 解析包住源码的异步函数,acorn-walk 沿用 Node REPL 的 visitor、声明提升和按字符位置修改源码的方式进行遍历。类方法的计算属性名参与遍历,方法体仍独立求值。转换包装末尾表达式,求值器解包并等待其值。无需转换的源码使用原生编译;不含 `await` 的提交保留原生语法诊断。语法错误保留解析器消息、可用的源码位置与光标,不包含编译器或转换器的调用帧。动态 `import()` 表达式保持原生形式,使用编译该 Script 时的 `importModuleDynamically` 选项。两个私有进程 bundle 都包含 Acorn、acorn-walk 和 birpc;源码执行导入已安装的包。 @@ -243,6 +247,7 @@ AsyncFunction 和 Node REPL 共用同步 `registerHooks` 和以 symbol 为键的 - **内存保留环境为每个存活所有者保留一个进程**——空闲所有者保留进程及堆内存,直到显式释放、所有者销毁或执行失败。并行创建多个所有者会保留多个进程;空闲过期机制留待后续处理。 - **输出上限拒绝超量内容,而不保留每个字节**——溢出只能保存本提供方交付的有界结果。 - **格式化先分配内存再核算输出**——完整格式化对象和 TypedArray 所需的内存可能远大于保留的输出。输出预算不限制这些临时分配;耗尽配置的堆上限可能以 `worker-exit` 结束执行。 +- **工具结果展示保留额外数据**——保留原工具结果时,也会在同一堆预算内保留其初始 JSON 快照和渲染文本;直接 `inspect` 会比较完整数据。 - **绑定在传输接纳时受限**——控制限制不约束 Host 绑定生成结果期间分配的内存。 - **预装 bootstrap 需要兼容的协议版本**——就绪握手会在派发代码前拒绝缺失或不匹配的版本。请将 `launch.bootstrapPath` 与宿主一同升级;运行时不会安装远端 bootstrap 更新。 - **图片引用随进程保留**——每张已获取图片的宿主元数据保留到进程终止或所有者释放,包括程序尚未展示的图片。保留环境中的长截图循环会累积这些引用。 diff --git a/packages/ptc-runtime/ptc-runtime-node/src/bindings.ts b/packages/ptc-runtime/ptc-runtime-node/src/bindings.ts index 422fb97657..f9b49509ac 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/bindings.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/bindings.ts @@ -1,7 +1,8 @@ /** Validate and capture the binding names available to one program. */ -import { PtcImage, RESERVED_BINDING_WORDS, PtcRuntimeError, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcImage, PtcInspectableValue, RESERVED_BINDING_WORDS, PtcRuntimeError, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcBindingFunction, PtcBindingNamespace, PtcJsonValue, PtcProgramFormat, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime' -import { snapshotPtcJsonValue, encodePtcJsonWire, type PtcJsonWire, type PtcImageWire } from './json-wire.ts' +import { snapshotPtcJsonValue, encodePtcJsonWire, type PtcImageWire } from './json-wire.ts' +import type { BindingResult } from './protocol.ts' import { RESERVED_PREFIX } from './evaluators/scoped-repl.ts' const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/ /** @@ -58,9 +59,15 @@ export function validateBindings(request: PtcRunRequest, programFormat: PtcProgr */ export async function invokeBinding( binding: PtcBindingFunction | undefined, args: PtcJsonValue, image?: (value: PtcImage) => PtcImageWire, -): Promise { +): Promise { if (!binding) throw new Error('binding is unavailable in this evaluation; reacquire the current tool') - const value = snapshotPtcJsonValue(await binding(args), value => image !== undefined && value instanceof PtcImage) + const resolved = await binding(args) + const inspection = resolved instanceof PtcInspectableValue ? resolved.text : undefined + const value = snapshotPtcJsonValue(resolved instanceof PtcInspectableValue ? resolved.value : resolved, + value => image !== undefined && value instanceof PtcImage) if (value === undefined) throw new Error('binding resolution must be lossless JSON') - return encodePtcJsonWire(value, candidate => candidate instanceof PtcImage ? image?.(candidate) : undefined) + return { + value: encodePtcJsonWire(value, candidate => candidate instanceof PtcImage ? image?.(candidate) : undefined), + ...inspection === undefined ? {} : { inspection }, + } } diff --git a/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts b/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts index 73ccb89989..38226e85fd 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts @@ -10,11 +10,43 @@ import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from import { decodePtcJsonWire, encodePtcJsonWire, snapshotPtcJsonValue, type PtcImageWire } from './json-wire.ts' const CapturedError = Error -const { isNativeError } = types +const { isNativeError, isProxy } = types const { create: capturedObjectCreate, defineProperty: capturedObjectDefineProperty, + getOwnPropertyDescriptor: capturedObjectGetOwnPropertyDescriptor, + getPrototypeOf: capturedObjectGetPrototypeOf, + is: capturedObjectIs, } = Object +const capturedOwnKeys = Reflect.ownKeys + +/** Text and the original JSON data associated with one binding result. */ +export interface BindingInspection { + /** Detached data used to detect changes before selecting the text. */ + snapshot: PtcJsonValue + /** Host-authored text for direct inspection of the unchanged value. */ + text: string +} + +/** Compare data properties without invoking accessors or traversing model-created proxies. */ +function matchesInspection(value: object, snapshot: PtcJsonValue): boolean { + const pending: [unknown, PtcJsonValue][] = [[value, snapshot]] + for (let pair = pending.pop(); pair !== undefined; pair = pending.pop()) { + const [current, original] = pair + if (capturedObjectIs(current, original)) continue + if (current === null || typeof current !== 'object' || original === null || typeof original !== 'object' + || isProxy(current) || capturedObjectGetPrototypeOf(current) !== capturedObjectGetPrototypeOf(original)) return false + const keys = capturedOwnKeys(current) + if (keys.length !== capturedOwnKeys(original).length) return false + for (const key of keys) { + const actual = capturedObjectGetOwnPropertyDescriptor(current, key) as PropertyDescriptor + const expected = capturedObjectGetOwnPropertyDescriptor(original, key) + if (!expected || !('value' in actual) || actual.enumerable !== expected.enumerable) return false + pending.push([actual.value, expected.value as PtcJsonValue]) + } + } + return true +} /** Node formatting options shared with the runtime-owned Image hook. */ export interface ImageInspectOptions extends InspectOptions { @@ -107,11 +139,13 @@ export class LogBuffer { * @param logs - the buffer every rendered line is pushed into. * @param images - Image identities owned by the execution process. * @param emitImage - Emits a registered image in the current evaluation. + * @param inspections - Process-owned text associated with original binding result identities. * @returns The program's inspect function and its matching Image collection hook. * @throws If object formatting fails; preceding arguments remain visible. */ export function makeInspect( logs: Pick, images: Pick, 'get'>, emitImage: (id: string) => void, + inspections?: Pick, 'get'>, ): { inspect: (...args: unknown[]) => void collectImage: (image: object, options: ImageInspectOptions) => void @@ -125,6 +159,12 @@ export function makeInspect( pending.length = 0 } for (const arg of args) { + const inspection = arg !== null && typeof arg === 'object' ? inspections?.get(arg) : undefined + if (inspection !== undefined && matchesInspection(arg as object, inspection.snapshot)) { + flush() + if (inspection.text.length > 0) logs.push(inspection.text.endsWith('\n') ? inspection.text : inspection.text + '\n') + continue + } const directImage = arg !== null && typeof arg === 'object' ? images.get(arg) : undefined if (directImage !== undefined) { flush() @@ -303,6 +343,7 @@ function bindingFailure(errorClass: BindingErrorConstructor | undefined, memberN * @param host - Evaluation-scoped remote binding calls. * @param errorClasses - Constructors shared with program globals, resolved per invocation. * @param decodeImage - Optional decoder for host-issued images. + * @param inspections - Process-owned inspection text indexed by decoded result identity. * @returns One namespace object per declaration. */ export function makeNamespaces( @@ -310,6 +351,7 @@ export function makeNamespaces( host: Pick, errorClasses: Pick, 'get'>, decodeImage?: (wire: PtcImageWire) => PtcJsonValue, + inspections?: Pick, 'set'>, ): Record[] { return data.namespaces.map(({ global, names }) => { const namespace = Object.create(null) as Record @@ -325,11 +367,20 @@ export function makeNamespaces( detached = undefined } if (detached === undefined) throw new CapturedError('binding arguments must be lossless JSON') - const result = decodePtcJsonWire( - await host.invoke(global, name, encodePtcJsonWire(detached)), - decodeImage, - ) + const resolution: unknown = await host.invoke(global, name, encodePtcJsonWire(detached)) + if (resolution === null || typeof resolution !== 'object' || Array.isArray(resolution) || !('value' in resolution)) { + throw new CapturedError('binding resolution must be lossless JSON') + } + const inspection = 'inspection' in resolution ? resolution.inspection : undefined + if (inspection !== undefined && typeof inspection !== 'string') throw new CapturedError('binding resolution must be lossless JSON') + const result = decodePtcJsonWire(resolution.value, decodeImage) if (result === undefined) throw new CapturedError('binding resolution must be lossless JSON') + if (inspection !== undefined) { + if (result === null || typeof result !== 'object') throw new CapturedError('binding inspection requires an object or array') + const snapshot = snapshotPtcJsonValue(result) + if (snapshot === undefined) throw new CapturedError('binding inspection requires lossless JSON data') + inspections?.set(result, { snapshot, text: inspection }) + } return result } catch (error: unknown) { throw bindingFailure(errorClass, name, error instanceof CapturedError ? error.message : String(error)) diff --git a/packages/ptc-runtime/ptc-runtime-node/src/process.ts b/packages/ptc-runtime/ptc-runtime-node/src/process.ts index 3aff251105..d2341a8041 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/process.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/process.ts @@ -5,7 +5,7 @@ import type { Duplex } from 'node:stream' import type { PtcProgramFormat, PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' import { createProcessRpc } from './rpc.ts' import { captureStreamWrites, LogBuffer, makeInspect, makeBindingErrorClass, makeNamespaces, outputLimit, prepareCompletion, prepareException } from './bootstrap.ts' -import type { BindingErrorConstructor, ImageInspectOptions, PatchableStream } from './bootstrap.ts' +import type { BindingErrorConstructor, BindingInspection, ImageInspectOptions, PatchableStream } from './bootstrap.ts' import type { PtcImageWire } from './json-wire.ts' import { clearProgramEnvironment, filterRuntimeWarnings } from './environment.ts' import { createProgramEvaluator } from './evaluators/index.ts' @@ -79,6 +79,7 @@ export async function runNodeMain( }, } const images = new WeakMap() + const inspections = new WeakMap() class Image { readonly [key: string]: PtcJsonValue declare readonly attachmentId: string @@ -111,7 +112,7 @@ export async function runNodeMain( const evaluation = context.getStore() if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text) } } - const { inspect: programInspect, collectImage } = makeInspect(logSink, images, imageSink) + const { inspect: programInspect, collectImage } = makeInspect(logSink, images, imageSink, inspections) captureStreamWrites(logSink, processState.stdout) captureStreamWrites(logSink, processState.stderr) const connection = createProcessRpc(stream, maxMessageBytes, { @@ -176,7 +177,7 @@ export async function runNodeMain( const constructor = makeBindingErrorClass(descriptor) errors.set(namespace.global, { name: descriptor.name, memberNameProperty: descriptor.memberNameProperty, constructor }) } - const namespaces = makeNamespaces(data, host, errorLookup, decodeImage) + const namespaces = makeNamespaces(data, host, errorLookup, decodeImage, inspections) for (const [index, namespace] of data.namespaces.entries()) { Object.defineProperty(evaluator.globals, namespace.global, { configurable: true, enumerable: true, value: namespaces[index] }) if (namespace.errorClass) { diff --git a/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts b/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts index cf3834de53..7e8cb05d6c 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts @@ -3,7 +3,15 @@ import type { PtcProgramFormat, PtcJsonValue, PtcRunFailure } from '@deepseek-ai import { decodePtcJsonWire, type PtcJsonWire } from './json-wire.ts' /** Wire revision required before the host dispatches program code. */ -export const PROGRAM_PROTOCOL_VERSION = 3 +export const PROGRAM_PROTOCOL_VERSION = 4 + +/** One binding's JSON value and optional host-authored inspection text. */ +export interface BindingResult { + /** Flat lossless JSON data returned to the program. */ + value: PtcJsonWire + /** Direct inspection text for an unchanged object or array. */ + inspection?: string +} /** Inputs for one program; host functions remain in the parent process. */ export interface ProgramBootData { @@ -51,9 +59,9 @@ export interface HostMethods { * @param global - Namespace global. * @param name - Function name within the namespace. * @param args - Flat lossless JSON arguments. - * @returns Flat lossless JSON result; binding failures and cancellation reject. + * @returns JSON data with optional inspection text; binding failures and cancellation reject. */ - invoke(global: string, name: string, args: PtcJsonWire): Promise + invoke(global: string, name: string, args: PtcJsonWire): Promise /** * Admit captured output before completion or interruption. * @param text - Captured text. diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts index 8af23ca126..6200b6c641 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts @@ -4,10 +4,11 @@ import { describe, expect, it, vi } from 'vitest' import { LogBuffer, makeBindingErrorClass, makeInspect, makeNamespaces, captureStreamWrites, prepareCompletion, prepareException } from '../src/bootstrap.ts' import type { BindingErrorConstructor, ImageInspectOptions, PatchableStream } from '../src/bootstrap.ts' import type { HostMethods } from '../src/protocol.ts' -import { encodePtcJsonWire } from '../src/json-wire.ts' +import { encodePtcJsonWire, snapshotPtcJsonValue } from '../src/json-wire.ts' +import type { BindingInspection } from '../src/bootstrap.ts' function host(): Pick { - return { invoke: vi.fn(async () => encodePtcJsonWire(42)) } + return { invoke: vi.fn(async () => ({ value: encodePtcJsonWire(42) })) } } const TOOL_ERROR_CLASS = { name: 'ToolCallError', memberNameProperty: 'toolName' } as const function toolNamespace(names: string[]) { return { global: 'tools', names, errorClass: TOOL_ERROR_CLASS } } @@ -33,6 +34,7 @@ describe('LogBuffer', () => { buffer.push('dropped') expect(seen).toEqual(['12345', '123']) expect(limits).toBe(1) + expect(buffer.overflowed).toBe(true) expect(buffer.remainingOutputBytes()).toBe(0) const exactlyFull: string[] = [] @@ -262,6 +264,74 @@ describe('makeInspect', () => { }) }) +describe('binding inspection metadata', () => { + it('emits unchanged object and array renderings in order with normalized newlines', () => { + const object = { value: 1 } + const array = [1, 2] + const empty = {} + const inspections = new WeakMap([ + [object, { snapshot: { value: 1 }, text: 'object rendering' }], + [array, { snapshot: [1, 2], text: 'array rendering\n' }], + [empty, { snapshot: {}, text: '' }], + ]) + const seen: string[] = [] + const { inspect } = makeInspect({ push: text => seen.push(text) }, new WeakMap(), () => {}, inspections) + inspect('before', object, array, empty, 'after') + expect(seen).toEqual(['before\n', 'object rendering\n', 'array rendering\n', 'after\n']) + expect(Reflect.ownKeys(object)).toEqual(['value']) + }) + + it.each([ + ['null field', (value: Record) => { value.value = null }], + ['scalar field', (value: Record) => { value.value = 'one' }], + ['object replacing a scalar', (value: Record) => { value.value = {} }], + ['object replacing null', (value: Record) => { value.nullable = {} }], + ['proxy', (value: Record) => { value.nested = new Proxy({}, {}) }], + ['prototype', (value: Record) => { Object.setPrototypeOf(value.nested, null) }], + ['renamed field', (value: Record) => { delete value.value; value.changed = 1 }], + ['removed field', (value: Record) => { delete value.value }], + ['hidden field', (value: Record) => { Object.defineProperty(value, 'value', { enumerable: false }) }], + ] as const)('formats current data after changing a %s', (_name, change) => { + const value: Record = { value: 1, nested: { answer: 42 }, nullable: null } + const snapshot = snapshotPtcJsonValue(value)! + const inspections = new WeakMap([[value, { snapshot, text: 'original rendering' }]]) + const seen: string[] = [] + const { inspect } = makeInspect({ push: text => seen.push(text) }, new WeakMap(), () => {}, inspections) + change(value) + inspect(value) + expect(seen.join('')).not.toContain('original rendering') + expect(seen).toHaveLength(1) + }) + + it.each([null, 42, [], {}, { value: [undefined] }, { value: encodePtcJsonWire({}), inspection: 42 }])('rejects malformed binding result %j', async (resolution) => { + const remote = host() + remote.invoke = async () => resolution as never + const [tools] = makeNamespaces({ namespaces: [toolNamespace(['x'])] }, remote, new Map()) as [Record Promise>] + await expect(tools.x?.({})).rejects.toThrow('binding resolution must be lossless JSON') + }) + + it.each([null, 42])('rejects inspection metadata for scalar %j', async (value) => { + const remote = host() + remote.invoke = async () => ({ value: encodePtcJsonWire(value), inspection: 'text' }) + const [tools] = makeNamespaces({ namespaces: [toolNamespace(['x'])] }, remote, new Map()) as [Record Promise>] + await expect(tools.x?.({})).rejects.toThrow('binding inspection requires an object or array') + }) + + it('rejects inspection metadata for non-JSON image identities', async () => { + const remote = host() + remote.invoke = async () => ({ value: [{ kind: 'image', id: 'one', attachmentId: 'one', path: '/one.png', width: 1, height: 1 }], inspection: 'text' }) + const [tools] = makeNamespaces({ namespaces: [toolNamespace(['x'])] }, remote, new Map(), () => Object.create({ image: true }) as Record) as [Record Promise>] + await expect(tools.x?.({})).rejects.toThrow('binding inspection requires lossless JSON data') + }) + + it('returns unchanged JSON when no inspection registry is requested', async () => { + const remote = host() + remote.invoke = async () => ({ value: encodePtcJsonWire({ answer: 42 }), inspection: 'answer' }) + const [tools] = makeNamespaces({ namespaces: [toolNamespace(['x'])] }, remote, new Map()) as [Record Promise>] + await expect(tools.x?.({})).resolves.toEqual({ answer: 42 }) + }) +}) + describe('captureStreamWrites', () => { it('redirects writes into the buffer and restores on request', () => { const seen: string[] = [] @@ -377,7 +447,7 @@ describe('prepareException', () => { describe('makeNamespaces', () => { it('rejects malformed remote results and keeps prototype-colliding function names callable', async () => { const remote = host() - remote.invoke = vi.fn(async (_global, name) => name === 'bad' ? [undefined] as never : encodePtcJsonWire(`${name}-ok`)) + remote.invoke = vi.fn(async (_global, name) => name === 'bad' ? { value: [undefined] as never } : { value: encodePtcJsonWire(`${name}-ok`) }) const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['bad', '__proto__', 'constructor', 'toString'] }] }, remote, new Map()) as [Record Promise>] expect(Object.getPrototypeOf(tools)).toBeNull() for (const name of ['__proto__', 'constructor', 'toString']) await expect(tools[name]?.({})).resolves.toBe(`${name}-ok`) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts b/packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts index b1a10e5cad..5c2b7d6eaf 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts @@ -34,10 +34,11 @@ describe.skipIf(!built)('built lib real load path (plain node)', () => { }) it.each(['per-call', 'vm-script'] as const)('runs TypeScript and bindings through published exports in %s mode', async (executionMode) => { - const program = 'const doubled: number = await tools.double({ n: 21 }); inspect("halfway", doubled); let failure; try { await tools.fail({}) } catch (error) { failure = { typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } }; const env = Object.keys((await import("node:process")).env); ' + (executionMode === 'per-call' ? 'return { doubled, failure, env };' : '({ doubled, failure, env })') + const program = 'const doubled: number = await tools.double({ n: 21 }); inspect("halfway", doubled); const structured = await tools.structured({}); inspect(structured); let failure; try { await tools.fail({}) } catch (error) { failure = { typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } }; const env = Object.keys((await import("node:process")).env); ' + (executionMode === 'per-call' ? 'return { doubled, structured, failure, env };' : '({ doubled, structured, failure, env })') const script = ` const { Context } = await import('@deepseek-ai/cordis') const { NodePtcRuntime } = await import('@deepseek-ai/dsh-ptc-runtime-node') + const { PtcInspectableValue } = await import('@deepseek-ai/dsh-ptc-runtime') const ctx = new Context() for (const name of ['session-projection', 'fs-local', 'subprocess-local', 'sandbox-local']) { const plugin = await import('@deepseek-ai/dsh-' + name) @@ -52,6 +53,7 @@ describe.skipIf(!built)('built lib real load path (plain node)', () => { global: 'tools', functions: { double: async args => args.n * 2, + structured: async () => new PtcInspectableValue({ value: 42 }, 'rendered result 42'), fail: async () => { throw new Error('denied') }, }, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, @@ -76,9 +78,11 @@ describe.skipIf(!built)('built lib real load path (plain node)', () => { expect(result.error).toBeUndefined() expect(result.value).toEqual({ doubled: 42, + structured: { value: 42 }, failure: { typed: true, name: 'ToolCallError', toolName: 'fail', message: 'denied' }, env: [], }) expect(result.output).toContainEqual({ type: 'text', text: 'halfway 42\n' }) + expect(result.output).toContainEqual({ type: 'text', text: 'rendered result 42\n' }) }) }) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts index b7e1aff825..dfab317387 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts @@ -540,7 +540,7 @@ it('preserves execution context for bindings delivered by an external control st h.receive((raw) => { const message = raw as { t: string; m?: string; r?: unknown } if ('m' in message && message.m === 'run') booted.resolve(undefined) - if (message.t === 's') h.complete({ value: message.r }) + if (message.t === 's') h.complete(message.r) }) const context = new AsyncLocalStorage() const pending = context.run('binding context', () => h.start({ ...request, sandboxPolicy: h.ctx.sandboxPolicy.resolve({ session }), diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts new file mode 100644 index 0000000000..94bfc9641a --- /dev/null +++ b/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts @@ -0,0 +1,141 @@ +import { Context } from '@deepseek-ai/cordis' +import { PtcInspectableValue, type PtcBindingNamespace, type PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' +import { describe, expect, it } from 'vitest' +import { mountRuntime } from './setup.ts' + +const modes = [ + { executionMode: 'per-call' }, + { executionMode: 'vm-script' }, + { executionMode: 'vm-script', scriptPersistence: true }, + { executionMode: 'persistent-in-memory', replScoped: false }, + { executionMode: 'persistent-in-memory', replScoped: true }, +] as const + +const data = { path: '/a.txt', lines: [{ number: 1, text: 'alpha' }], totalLines: 1 } +const text = '/a.txt\n1: alpha' +function bindings(): PtcBindingNamespace[] { + return [{ global: 'tools', functions: { + read: async () => new PtcInspectableValue(data, text), + list: async () => new PtcInspectableValue([1, 2, 3], 'three items\n'), + scalar: async () => 42, + empty: async () => new PtcInspectableValue({}, ''), + echo: async args => args as PtcJsonValue, + } }] +} + + +describe.each(modes)('binding inspection in $executionMode with script retention $scriptPersistence and scoped REPL $replScoped', (mode) => { + it('uses binding text while preserving data fields, JSON, and subsequent binding arguments', async () => { + const { runtime } = await mountRuntime(new Context(), mode) + const result = await runtime.run(runtime.resolve({ + program: ` + const result = await tools.read({}); + if (Reflect.ownKeys(result).join() !== 'path,lines,totalLines') throw new Error('unexpected fields'); + if (result.lines[0].text !== 'alpha' || result.totalLines + 2 !== 3) throw new Error('data access failed'); + const echoed = await tools.echo(result); + if (JSON.stringify(result) !== JSON.stringify(echoed)) throw new Error('data changed'); + inspect(result); + inspect(await tools.list({})); + inspect(await tools.scalar({})); + inspect(await tools.empty({})); + `, + bindings: bindings(), discardCompletion: true, + })) + expect(result.error).toBeUndefined() + expect(result.output).toEqual([ + { type: 'text', text: text + '\n' }, + { type: 'text', text: 'three items\n' }, + { type: 'text', text: '42\n' }, + ]) + }) + + it('formats modified, copied, selected, and nested data without reusing the original text', async () => { + const { runtime } = await mountRuntime(new Context(), mode) + const result = await runtime.run(runtime.resolve({ + program: ` + const result = await tools.read({}); + inspect({ ...result }); + inspect({ result }); + inspect(result.lines); + result.lines[0].text = 'changed'; + inspect(result); + result.lines[0].text = 'alpha'; + inspect(result); + delete result.totalLines; + inspect(result); + `, + bindings: bindings(), discardCompletion: true, + })) + expect(result.error).toBeUndefined() + const output = result.output.filter(block => block.type === 'text').map(block => block.text) + expect(output).toHaveLength(6) + expect(output.slice(0, 4).join('')).not.toContain('') + expect(output[2]).toBe("[ { number: 1, text: 'alpha' } ]\n") + expect(output[3]).toContain("text: 'changed'") + expect(output[4]).toBe(text + '\n') + expect(output[5]).not.toContain('totalLines') + }) + + it('falls back for accessors and cycles without invoking getters', async () => { + const { runtime } = await mountRuntime(new Context(), mode) + const result = await runtime.run(runtime.resolve({ + program: ` + const result = await tools.read({}); + let reads = 0; + Object.defineProperty(result, 'totalLines', { enumerable: true, get() { reads++; return 1; } }); + inspect(result); + inspect(reads); + delete result.totalLines; + result.self = result; + inspect(result); + `, + bindings: bindings(), discardCompletion: true, + })) + expect(result.error).toBeUndefined() + expect(result.output[0]).toMatchObject({ type: 'text', text: expect.stringContaining('[Getter]') as string }) + expect(result.output[1]).toEqual({ type: 'text', text: '0\n' }) + expect(result.output[2]).toMatchObject({ type: 'text', text: expect.stringContaining('[Circular *1]') as string }) + }) +}) + +it.each(modes.filter(mode => mode.executionMode === 'persistent-in-memory' || 'scriptPersistence' in mode))('retains inspection text with data across calls in %j', async (mode) => { + const { runtime } = await mountRuntime(new Context(), mode) + const stateOwner = {} + const first = await runtime.run(runtime.resolve({ + program: 'var retained = await tools.read({});', bindings: bindings(), stateOwner, discardCompletion: true, + })) + expect(first.error).toBeUndefined() + expect(first.output).toEqual([]) + const second = await runtime.run(runtime.resolve({ + program: 'inspect(retained);', bindings: [], stateOwner, discardCompletion: true, + })) + expect(second.error).toBeUndefined() + expect(second.output).toEqual([{ type: 'text', text: text + '\n' }]) +}) + +it('charges inspection text only when emitted and bounds its complete output', async () => { + const { runtime } = await mountRuntime(new Context(), { maxOutputBytes: 64 }) + const binding: PtcBindingNamespace[] = [{ global: 'tools', functions: { + read: async () => new PtcInspectableValue({ value: 1 }, '€'.repeat(100)), + } }] + const hidden = await runtime.run(runtime.resolve({ + program: 'await tools.read({});', bindings: binding, discardCompletion: true, + })) + expect(hidden.error).toBeUndefined() + expect(hidden.output).toEqual([]) + const shown = await runtime.run(runtime.resolve({ + program: 'inspect(await tools.read({}));', bindings: binding, discardCompletion: true, + })) + expect(shown.error?.kind).toBe('output-limit') +}) + +it('rejects a non-JSON wrapped binding value instead of replacing it with rendered text', async () => { + const { runtime } = await mountRuntime(new Context()) + const result = await runtime.run(runtime.resolve({ + program: 'try { await tools.read({}); } catch (error) { inspect(error.message); }', + bindings: [{ global: 'tools', functions: { read: async () => new PtcInspectableValue({ value: Infinity }, 'hidden invalid data') } }], + discardCompletion: true, + })) + expect(result.error).toBeUndefined() + expect(result.output).toEqual([{ type: 'text', text: 'binding resolution must be lossless JSON\n' }]) +}) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts index d41d17bbf3..5255d8bea2 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts @@ -24,7 +24,7 @@ async function setup(limit = 4096, chdir: (cwd: string) => void = () => {}, prog initialized: async () => {}, invoke: async (global, name, args) => { seen.push({ type: 'call', global, name, args }) - return encodePtcJsonWire(42) + return { value: encodePtcJsonWire(42) } }, log: (text) => { seen.push({ type: 'log', text }) }, image: () => {}, @@ -54,7 +54,7 @@ it('runs initialization before the program in the same REPL and discards its com const namespaces = [{ global: 'tools', names: ['echo'] }] const initialization = 'globalThis.helper ??= { read: () => tools.echo({}) }; inspect("initialize"); helper' expect(decodePtcJsonWire((await h.run('var saved = helper; await helper.read()', namespaces, 1024, initialization)).value)).toBe(42) - h.setCall(async () => encodePtcJsonWire(43)) + h.setCall(async () => ({ value: encodePtcJsonWire(43) })) expect(decodePtcJsonWire((await h.run('({ value: await helper.read(), same: helper === saved })', namespaces)).value)) .toEqual({ value: 43, same: true }) expect(h.seen.filter(item => item.type === 'log').map(item => item.text)).toEqual(['initialize\n']) @@ -104,8 +104,8 @@ it('does not resume the program after initialization reports an asynchronous fai it('does not start the program when initialization catches a revoked binding', async () => { const h = await setup() const entered: PromiseWithResolvers = Promise.withResolvers() - const pending = Promise.withResolvers>() - onTestFinished(() => { pending.resolve(encodePtcJsonWire(null)) }) + const pending = Promise.withResolvers>>() + onTestFinished(() => { pending.resolve({ value: encodePtcJsonWire(null) }) }) h.setCall(() => { entered.resolve(); return pending.promise }) const first = h.run('globalThis.programRan = true', [{ global: 'tools', names: ['echo'] }], 1024, 'try { await tools.echo({}) } catch {}') @@ -264,11 +264,11 @@ it('ignores output and rejects new tool calls from a completed evaluation', asyn it.each(['resolve', 'reject'] as const)('rejects an unfinished binding once when a completed program receives a late %s', async (outcome) => { const h = await setup() - const pending = Promise.withResolvers>() - onTestFinished(() => { pending.resolve(encodePtcJsonWire(null)) }) + const pending = Promise.withResolvers>>() + onTestFinished(() => { pending.resolve({ value: encodePtcJsonWire(null) }) }) h.setCall(() => pending.promise) await h.run('let effects = []; void tools.echo({}).then(() => effects.push("then")).catch(() => effects.push("catch")).finally(() => effects.push("finally"));', [{ global: 'tools', names: ['echo'] }]) - if (outcome === 'resolve') pending.resolve(encodePtcJsonWire(42)) + if (outcome === 'resolve') pending.resolve({ value: encodePtcJsonWire(42) }) else pending.reject(new Error('late failure')) await setImmediate() expect(decodePtcJsonWire((await h.run('effects')).value)).toEqual(['catch', 'finally']) @@ -276,9 +276,9 @@ it.each(['resolve', 'reject'] as const)('rejects an unfinished binding once when it.each([['resolve', 'repl'], ['reject', 'repl'], ['resolve', 'script'], ['reject', 'script']] as const)('revokes an awaiting program after a late %s in %s', async (outcome, format) => { const h = await setup(4096, undefined, format) - const pending = Promise.withResolvers>() + const pending = Promise.withResolvers>>() const started: PromiseWithResolvers = Promise.withResolvers() - onTestFinished(() => { pending.resolve(encodePtcJsonWire(null)) }) + onTestFinished(() => { pending.resolve({ value: encodePtcJsonWire(null) }) }) h.setCall(() => { started.resolve(); return pending.promise }) const declarations = [{ global: 'tools', names: ['echo'] }] await h.peer.revoke() @@ -287,7 +287,7 @@ it.each([['resolve', 'repl'], ['reject', 'repl'], ['resolve', 'script'], ['rejec await h.peer.revoke() expect(await first).toEqual({}) await h.peer.revoke() - if (outcome === 'resolve') pending.resolve(encodePtcJsonWire(42)) + if (outcome === 'resolve') pending.resolve({ value: encodePtcJsonWire(42) }) else pending.reject(new Error('late failure')) await setImmediate() expect(decodePtcJsonWire((await h.run('({ kept, effects })')).value)).toEqual({ kept: 42, effects: ['catch', 'finally'] }) @@ -298,7 +298,7 @@ it.each([['resolve', 'repl'], ['reject', 'repl'], ['resolve', 'script'], ['rejec it.each(['repl', 'script'] as const)('rejects a binding result followed by revocation before %s user code resumes', async (format) => { const h = await setup(4096, undefined, format) const request = Promise.withResolvers() - const response = Promise.withResolvers>() + const response = Promise.withResolvers>>() h.setCall(() => response.promise) const wire = rawPeer(h.host, (message) => { if (typeof message === 'object' && message !== null && 'm' in message && message.m === 'invoke' @@ -308,13 +308,13 @@ it.each(['repl', 'script'] as const)('rejects a binding result followed by revoc try { const id = await request.promise await Promise.all([ - wire.send({ t: 's', i: id, r: encodePtcJsonWire(42) }), + wire.send({ t: 's', i: id, r: { value: encodePtcJsonWire(42) } }), wire.send({ t: 'q', m: 'revoke', a: [] }), ]) expect(await first).toEqual({}) expect(decodePtcJsonWire((await h.run('effects')).value)).toEqual(['catch', 'finally']) } finally { - response.resolve(encodePtcJsonWire(null)) + response.resolve({ value: encodePtcJsonWire(null) }) wire.close() await first } diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts index d00e715f08..85e3c3f5a5 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts @@ -29,7 +29,7 @@ async function setup(limit = 4096, namespaces: ProgramBootData['namespaces'] = [ const methods: HostMethods = { ready: () => { ready.resolve(undefined) }, initialized: async () => {}, - invoke: async () => encodePtcJsonWire(42), + invoke: async () => ({ value: encodePtcJsonWire(42) }), log: (text) => { logs.push(text) }, image: () => {}, outputLimit: () => {}, @@ -49,7 +49,7 @@ it('clears the environment and returns a binding result after captured output', const h = await setup() h.methods.invoke = async (_global, _name, wire) => { const args = decodePtcJsonWire(wire) as { n: number } - return encodePtcJsonWire(args.n * 2) + return { value: encodePtcJsonWire(args.n * 2) } } const result = await h.run('const doubled = await tools.echo({ n: 21 }); inspect("got", doubled); return { doubled };') expect(decodePtcJsonWire(result.value)).toEqual({ doubled: 42 }) @@ -75,16 +75,16 @@ it.each(['function-body', 'repl', 'script'] as const)('provides console in the o it('keeps unfinished temporary calls pending and suppresses later logs while awaiting host shutdown', async () => { const h = await setup() - const release = Promise.withResolvers>() + const release = Promise.withResolvers>>() h.methods.invoke = () => release.promise try { expect(decodePtcJsonWire((await h.run('void tools.echo({}).catch(() => {}); void tools.echo({}).catch(() => inspect("late rejection")); setImmediate(() => inspect("late timer")); return 42;')).value)).toBe(42) await nextTurn() expect(h.child.destroyed).toBe(false) - release.resolve(encodePtcJsonWire(42)) + release.resolve({ value: encodePtcJsonWire(42) }) await nextTurn() expect(h.logs).toEqual([]) - } finally { release.resolve(encodePtcJsonWire(null)) } + } finally { release.resolve({ value: encodePtcJsonWire(null) }) } }) it('rejects a binding call that the host fails during the run', async () => { @@ -96,8 +96,8 @@ it('rejects a binding call that the host fails during the run', async () => { it.each(['function-body', 'repl', 'script'] as const)('leaves an unawaited call pending when a temporary %s process closes after the result', async (format) => { const h = await setup() - const pending = Promise.withResolvers>() - onTestFinished(() => { pending.resolve(encodePtcJsonWire(null)) }) + const pending = Promise.withResolvers>>() + onTestFinished(() => { pending.resolve({ value: encodePtcJsonWire(null) }) }) h.methods.invoke = () => pending.promise const code = format === 'function-body' ? 'void tools.echo({}).catch(() => {}); return 42' : 'void tools.echo({}).catch(() => {}); 42' expect(decodePtcJsonWire((await h.run(code, 1024, format)).value)).toBe(42) @@ -147,7 +147,7 @@ it.each([ it('sends no binding calls or output notifications after returning its result', async () => { const h = await setup() - const invoked = vi.fn(async () => encodePtcJsonWire(1)) + const invoked = vi.fn(async () => ({ value: encodePtcJsonWire(1) })) const limited = vi.fn() h.methods.invoke = invoked h.methods.outputLimit = limited @@ -200,7 +200,7 @@ it('records malformed host traffic after completion', async () => { it('captures image selection during execution and revokes it for late or external calls', async () => { const h = await setup() - h.methods.invoke = async () => [{ kind: 'image', id: 'one', attachmentId: 'sha256:image', path: '/image.png', width: 8, height: 4 }] + h.methods.invoke = async () => ({ value: [{ kind: 'image', id: 'one', attachmentId: 'sha256:image', path: '/image.png', width: 8, height: 4 }] }) const selected = vi.fn() h.methods.image = selected const done = Promise.withResolvers() diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts index a8cf68a10f..482d971585 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts @@ -54,7 +54,7 @@ it.each(['awaited', 'unawaited', 'unawaited script'] as const)('boots an unbuilt async initialized() {}, async invoke(_global, _name, args) { expect(decodePtcJsonWire(args)).toEqual({ n: 21 }) - return scenario === 'awaited' ? encodePtcJsonWire(42) : await new Promise(() => {}) + return scenario === 'awaited' ? { value: encodePtcJsonWire(42) } : await new Promise(() => {}) }, log(text) { logs.push(text) }, image() {}, diff --git a/packages/ptc-runtime/ptc-runtime/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml index 5a849da35f..737cc6e6ad 100644 --- a/packages/ptc-runtime/ptc-runtime/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml @@ -18,8 +18,8 @@ en: 346f62bbfd0e6d9d zh: bf86b2d7a26e8193 /deepseek-ai-dsh-ptc-runtime/use-this-package/run-a-program: - en: cc02624f3e84fba5 - zh: 0294523cc7ebbbd9 + en: e96bebf033e14a85 + zh: aab4e264d8a33a61 /deepseek-ai-dsh-ptc-runtime/use-this-package/choose-a-backend: en: a7ffbb6dfe129164 zh: 110a800394ef7d26 diff --git a/packages/ptc-runtime/ptc-runtime/README.md b/packages/ptc-runtime/ptc-runtime/README.md index c8b99d9c72..f9adeb31a4 100644 --- a/packages/ptc-runtime/ptc-runtime/README.md +++ b/packages/ptc-runtime/ptc-runtime/README.md @@ -35,6 +35,8 @@ Set `discardCompletion: true` to omit the successful completion without JSON val Host bindings can return `new PtcImage(path, attachment)` to expose a stored image in Node programs. Explicit inspection appends `{ type: 'image', attachment }` entries to `result.output`, alongside `{ type: 'text', text }` entries in emission order. Text entries retain emitted newline characters; concatenate adjacent text without separators. +Host bindings can return `new PtcInspectableValue(value, text)` to attach inspection text to a JSON object or array. The Node provider exposes the original data to the program and uses the supplied text only when that unchanged result is passed directly to `inspect`. The descriptor is host-only; copies, selected fields, modified results, and nested values use ordinary formatting. The [runtime reference](../../../docs/subsystems/ptc-runtime.md) defines the provider obligations. + ```text const spec = ctx.ptcRuntime.resolve({ program: 'return await tools.add({ a: 1, b: 2 })', diff --git a/packages/ptc-runtime/ptc-runtime/README.zh.md b/packages/ptc-runtime/ptc-runtime/README.zh.md index a2a16b428d..2358fe3c6c 100644 --- a/packages/ptc-runtime/ptc-runtime/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime/README.zh.md @@ -35,6 +35,8 @@ kind: "package-reference" 宿主绑定可以返回 `new PtcImage(path, attachment)`,向 Node 程序提供已存储的图片。显式展示会将 `{ type: 'image', attachment }` 条目追加到 `result.output`,与 `{ type: 'text', text }` 条目按发出顺序排列。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。 +宿主绑定可以返回 `new PtcInspectableValue(value, text)`,为 JSON 对象或数组附加展示文本。Node 提供方向程序提供原有数据,仅在把未修改的原结果直接传给 `inspect` 时使用附带文本。该描述符只供宿主使用;拷贝、选定字段、修改后的结果和嵌套值使用普通格式。[运行时参考](../../../docs/subsystems/ptc-runtime.zh.md)定义提供方的义务。 + ```text const spec = ctx.ptcRuntime.resolve({ program: 'return await tools.add({ a: 1, b: 2 })', diff --git a/packages/ptc-runtime/ptc-runtime/src/index.ts b/packages/ptc-runtime/ptc-runtime/src/index.ts index 4489adc332..90438f45df 100644 --- a/packages/ptc-runtime/ptc-runtime/src/index.ts +++ b/packages/ptc-runtime/ptc-runtime/src/index.ts @@ -10,6 +10,7 @@ import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from ' import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' export { PtcImage } from './image.ts' +export { PtcInspectableValue } from './inspectable-value.ts' export type { PtcBindingErrorClass, diff --git a/packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts b/packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts new file mode 100644 index 0000000000..1fe354cb31 --- /dev/null +++ b/packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts @@ -0,0 +1,22 @@ +/** Structured binding values with host-authored text for explicit inspection. */ +import type { PtcJsonValue } from './types.ts' + +/** A binding result whose unchanged object or array displays the supplied text when inspected directly. */ +export class PtcInspectableValue { + readonly [key: string]: PtcJsonValue + /** The JSON object or array delivered unchanged to the program. */ + readonly value: PtcJsonValue[] | { [key: string]: PtcJsonValue } + /** Text shown by a direct inspection of the unchanged value; empty text emits nothing. */ + readonly text: string + + /** + * Associate an object or array with its host-authored inspection text. + * @param value - Lossless JSON data retained for programmatic access. + * @param text - Text to display instead of generic object formatting. + */ + constructor(value: PtcJsonValue[] | { [key: string]: PtcJsonValue }, text: string) { + this.value = value + this.text = text + Object.freeze(this) + } +} diff --git a/packages/ptc-runtime/ptc-runtime/src/types.ts b/packages/ptc-runtime/ptc-runtime/src/types.ts index 8a0c92e6c8..afe402c4f2 100644 --- a/packages/ptc-runtime/ptc-runtime/src/types.ts +++ b/packages/ptc-runtime/ptc-runtime/src/types.ts @@ -18,11 +18,13 @@ export type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-rep /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a - * lossy or non-cloneable value with a descriptive error rather than corrupting - * the run. No seam-level byte cap applies to a binding resolution. A rejection - * of this function surfaces inside the program as a rejection of the - * corresponding call. + * `args` must be lossless JSON; resolutions also support host-issued PtcImage and + * PtcInspectableValue values. An inspectable resolution delivers its JSON object + * or array to the program and uses its text only when that unchanged value is + * inspected directly. A runtime rejects a lossy or non-cloneable value with a + * descriptive error rather than corrupting the run. No seam-level byte cap + * applies to a binding resolution. A rejection of this function surfaces inside + * the program as a rejection of the corresponding call. */ export type PtcBindingFunction = (args: unknown) => Promise diff --git a/packages/shell/tool-bash/tests/integration.spec.ts b/packages/shell/tool-bash/tests/integration.spec.ts index e1685b5e77..e388e0f53b 100644 --- a/packages/shell/tool-bash/tests/integration.spec.ts +++ b/packages/shell/tool-bash/tests/integration.spec.ts @@ -11,7 +11,7 @@ import type { SessionId, SessionEvent } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' import * as ToolJobs from '@deepseek-ai/dsh-tool-jobs' @@ -115,7 +115,8 @@ describe('bash tool through the agent loop', () => { async run(spec: PtcRunSpec): Promise { const bash = spec.bindings.find(binding => binding.global === 'tools')?.functions.bash if (bash === undefined) throw new Error('missing bash binding') - const value = await bash({ command: 'pwd', description: 'Print launch directory' }) + const resolved = await bash({ command: 'pwd', description: 'Print launch directory' }) + const value = resolved instanceof PtcInspectableValue ? resolved.value : resolved expect(value).toMatchObject({ cwd: selected, stdout: { text: `${selected}\n` } }) return { output: [], value } } diff --git a/packages/skill/skill-office/tests/progressive-loading.spec.ts b/packages/skill/skill-office/tests/progressive-loading.spec.ts index 4d9a2890e3..15907f46ca 100644 --- a/packages/skill/skill-office/tests/progressive-loading.spec.ts +++ b/packages/skill/skill-office/tests/progressive-loading.spec.ts @@ -11,7 +11,7 @@ import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' -import { PtcRuntime, type PtcRunRequest, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import SkillRegistry from '@deepseek-ai/dsh-skill' import * as ToolSkill from '../../tool-skill/src/index.ts' import * as SkillOffice from '../src/index.ts' @@ -27,7 +27,9 @@ class SkillProgram extends PtcRuntime { readonly isolation = 'fixture' resolve(request: PtcRunRequest): PtcRunSpec { return { ...request, cwd: process.cwd(), timeoutMs: 120_000 } } async run(request: PtcRunSpec) { - return { output: [{ type: 'text' as const, text: JSON.stringify(await request.bindings[0]!.functions.skill!({ name: request.program })) }] } + const resolved = await request.bindings[0]!.functions.skill!({ name: request.program }) + const value = resolved instanceof PtcInspectableValue ? resolved.value : resolved + return { output: [{ type: 'text' as const, text: JSON.stringify(value) }] } } } diff --git a/packages/spill/spill-policy/tests/multimodal.spec.ts b/packages/spill/spill-policy/tests/multimodal.spec.ts index 1033f1eaa2..93c627af46 100644 --- a/packages/spill/spill-policy/tests/multimodal.spec.ts +++ b/packages/spill/spill-policy/tests/multimodal.spec.ts @@ -24,7 +24,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' import LocalSpillStore from '@deepseek-ai/dsh-spill-local' -import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcRunRequest, PtcRunSpec, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import * as SpillPolicy from '../src/index.ts' @@ -207,7 +207,10 @@ describe('multimodal spill', () => { const binding = spec.bindings.find(item => item.global === 'tools')?.functions.inspect if (binding === undefined) throw new Error('missing inspect binding') if (failure) await expect(binding({})).rejects.toThrow('capture failed') - else expect(await binding({})).toEqual({ content: original }) + else { + const resolved = await binding({}) + expect(resolved instanceof PtcInspectableValue ? resolved.value : resolved).toEqual({ content: original }) + } return { output: [], value: 'complete' } } } diff --git a/snapshots/session/ptc-node-workspace/replay.override.json b/snapshots/session/ptc-node-workspace/replay.override.json index c0a9af88a3..b4b81feed6 100644 --- a/snapshots/session/ptc-node-workspace/replay.override.json +++ b/snapshots/session/ptc-node-workspace/replay.override.json @@ -12,7 +12,7 @@ "index": 0, "id": "call_node_policy", "name": "run_code", - "argumentsDelta": "{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}" + "argumentsDelta": "{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect(shell); const file = await tools.read({ file_path: 'ptc-created.txt' }); inspect(file); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}" }, { "type": "block-end", @@ -21,7 +21,7 @@ "type": "tool-call", "id": "call_node_policy", "name": "run_code", - "arguments": "{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}" + "arguments": "{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect(shell); const file = await tools.read({ file_path: 'ptc-created.txt' }); inspect(file); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}" } }, { diff --git a/snapshots/session/ptc-node-workspace/session.v4.jsonl b/snapshots/session/ptc-node-workspace/session.v4.jsonl index 62de68f862..1dd3a1f762 100644 --- a/snapshots/session/ptc-node-workspace/session.v4.jsonl +++ b/snapshots/session/ptc-node-workspace/session.v4.jsonl @@ -12,15 +12,17 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Use one run_code program to","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_node_policy","name":"run_code","arguments":"{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427867917,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427867917,"index":0,"dt":[],"id":"call_node_policy","name":"run_code","args":["{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"]},{"type":"chunk","time":1791427867917,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_node_policy","name":"run_code","arguments":"{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"}}},{"type":"chunk","time":1791427867917,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427867917,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_node_policy","name":"run_code","arguments":"{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_node_policy","name":"run_code","arguments":"{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect(shell); const file = await tools.read({ file_path: 'ptc-created.txt' }); inspect(file); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1794560713588,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1794560713588,"index":0,"dt":[],"id":"call_node_policy","name":"run_code","args":["{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect(shell); const file = await tools.read({ file_path: 'ptc-created.txt' }); inspect(file); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"]},{"type":"chunk","time":1794560713588,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_node_policy","name":"run_code","arguments":"{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect(shell); const file = await tools.read({ file_path: 'ptc-created.txt' }); inspect(file); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"}}},{"type":"chunk","time":1794560713588,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1794560713588,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_node_policy","name":"run_code","arguments":"{\"code\":\"const fs = await import('node:fs/promises'); await fs.writeFile('ptc-created.txt', 'created by sandboxed Node\\\\n'); const written = await fs.readFile('ptc-created.txt', 'utf8') === 'created by sandboxed Node\\\\n'; const shell = await tools.bash({ command: 'pwd', description: 'Report the current workspace directory' }); inspect(shell); const file = await tools.read({ file_path: 'ptc-created.txt' }); inspect(file); inspect({ written, emptyEnvironment: Object.keys(process.env).length === 0, sameWorkspace: process.cwd() === shell.stdout.text.trim() }); return;\",\"description\":\"Verify Node file policy and execution context\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"call_node_policy","parentCallId":"call_node_policy","subCallId":"call_node_policy:ptc:1","name":"bash","arguments":{"command":"pwd","description":"Report the current workspace directory"}}} -{"type":"job/registered","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"pwd","startedAt":1791427868009,"toolCall":{"callId":"call_node_policy:ptc:1","rootCallId":"call_node_policy"}}} -{"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"pwd","startedAt":1791427868009,"toolCall":{"callId":"call_node_policy:ptc:1","rootCallId":"call_node_policy"},"finishedAt":1791427868019,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} +{"type":"job/registered","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"pwd","startedAt":1794560713673,"toolCall":{"callId":"call_node_policy:ptc:1","rootCallId":"call_node_policy"}}} +{"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"pwd","startedAt":1794560713673,"toolCall":{"callId":"call_node_policy:ptc:1","rootCallId":"call_node_policy"},"finishedAt":1794560713693,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"call_node_policy","parentCallId":"call_node_policy","subCallId":"call_node_policy:ptc:1","name":"bash","arguments":{"command":"pwd","description":"Report the current workspace directory"},"isError":false,"content":[{"type":"text","text":"{{cwd}}\n"}],"meta":{"cwd":"{{cwd}}"}}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_node_policy"},"toolCallId":"call_node_policy","content":[{"type":"text","text":"{ written: true, emptyEnvironment: true, sameWorkspace: true }\n"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"call_node_policy","parentCallId":"call_node_policy","subCallId":"call_node_policy:ptc:2","name":"read","arguments":{"file_path":"ptc-created.txt"}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"call_node_policy","parentCallId":"call_node_policy","subCallId":"call_node_policy:ptc:2","name":"read","arguments":{"file_path":"ptc-created.txt"},"isError":false,"content":[{"type":"text","text":"{{cwd}}/ptc-created.txt\nfile\n\n1: created by sandboxed Node\n\n(End of file - total 1 lines)\n"}],"meta":{"path":"{{cwd}}/ptc-created.txt","offset":1,"lines":[{"number":1,"text":"created by sandboxed Node"}],"totalLines":1}}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_node_policy"},"toolCallId":"call_node_policy","content":[{"type":"text","text":"{{cwd}}\n{{cwd}}/ptc-created.txt\nfile\n\n1: created by sandboxed Node\n\n(End of file - total 1 lines)\n\n{ written: true, emptyEnvironment: true, sameWorkspace: true }\n"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"Node policy and execution context verified."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1791427868053,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791427868053,"index":0,"dt":[],"texts":["Node policy and execution context verified."]},{"type":"chunk","time":1791427868053,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Node policy and execution context verified."}}},{"type":"chunk","time":1791427868053,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1791427868053,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"Node policy and execution context verified."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1794560713749,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794560713749,"index":0,"dt":[],"texts":["Node policy and execution context verified."]},{"type":"chunk","time":1794560713749,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Node policy and execution context verified."}}},{"type":"chunk","time":1794560713749,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1794560713749,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}