diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml index 5daab483a8..b5f5d4e3dd 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md -2026-07-10-single-file-executable-sdk-runtime-distribution.md: 1ef8059e23a414588e9d6d421a07058dfb362fe1 -2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: e1f24a809d2527bf5c69eacffc183ddf3badbc59 +2026-07-10-single-file-executable-sdk-runtime-distribution.md: 7a3d9e2fd5a7f61decdd91da687e652d6be1e6f1 +2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: 04d705925788ada2f7e59d85614c75d594d0ba5a diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md index 1ef8059e23..7a3d9e2fd5 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md @@ -62,7 +62,7 @@ The Python client launches the packaged `dsh` command with the selected profile ## Packaged workflow and code execution -`dsh-workflow-worker-thread` uses a built sibling `lib/worker.cjs` inside the executable's VFS; its host passes a filesystem path because pkg's Worker hook reads and compiles that entry as CommonJS. Its unbuilt source launch retains a data-URL bootstrap. `dsh-code-runtime-node` instead starts a managed child through the executable's private Node bootstrap dispatch, with a dedicated control channel. The [sandboxed Node decision](2026-09-11-sandboxed-node-code-runtime.md) owns that process and policy lifecycle. +`dsh-workflow-worker-thread` uses a built sibling `lib/worker.cjs` inside the executable's VFS; its host passes a filesystem path because pkg's Worker hook reads and compiles that entry as CommonJS. Its unbuilt source launch retains a data-URL bootstrap. `dsh-ptc-runtime-node` instead starts a managed child through the executable's private Node bootstrap dispatch, with a dedicated control channel. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns that process and policy lifecycle. ## Testing diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md index e1f24a809d..04d7059257 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md @@ -62,7 +62,7 @@ Python 客户端使用所选 profile(默认 `sdk`)、有序 patch 文件和 ## 打包后的工作流与代码执行 -`dsh-workflow-worker-thread` 使用可执行文件 VFS 内构建后的同级 `lib/worker.cjs`;Host 传入文件系统路径,因为 pkg 的 Worker hook 会读取该入口并按 CommonJS 编译。未构建的源代码启动保留 data-URL bootstrap。`dsh-code-runtime-node` 则通过可执行文件的私有 Node bootstrap 分派启动受管子进程,使用专用控制通道。[沙箱 Node 决策](2026-09-11-sandboxed-node-code-runtime.zh.md)负责其进程与策略生命周期。 +`dsh-workflow-worker-thread` 使用可执行文件 VFS 内构建后的同级 `lib/worker.cjs`;Host 传入文件系统路径,因为 pkg 的 Worker hook 会读取该入口并按 CommonJS 编译。未构建的源代码启动保留 data-URL bootstrap。`dsh-ptc-runtime-node` 则通过可执行文件的私有 Node bootstrap 分派启动受管子进程,使用专用控制通道。[沙箱 Node 决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责其进程与策略生命周期。 ## 测试 diff --git a/.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml similarity index 55% rename from .agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.i18n.yaml rename to .agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml index f656d54418..bf32b5d927 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.md -2026-07-31-code-runtime-python-fd3-protocol.md: 7f928b9cc996b545538e86a67399d5441509471a -2026-07-31-code-runtime-python-fd3-protocol.zh.md: 568b6ff3d7025ba55080e9677375c4b88303f621 +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md +2026-07-31-ptc-runtime-python-fd3-protocol.md: 18ce7b44b116eee3a11528a5b515c4e02e955ee6 +2026-07-31-ptc-runtime-python-fd3-protocol.zh.md: d5eea4cfd80f10dc1d99c7c43090ca6b0ff6e19e diff --git a/.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.md b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md similarity index 77% rename from .agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.md rename to .agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md index 7f928b9cc9..18ce7b44b1 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.md +++ b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md @@ -1,16 +1,16 @@ -# Agent Note: the code-runtime-python fd-3 frame protocol +# Agent Note: the ptc-runtime-python fd-3 frame protocol Status: implemented -The CPython code runtime now lives at `packages/experimental/code-runtime-python` (private, npm name `@deepseek-ai/dsh-experimental-code-runtime-python`); promotion to a released package follows the experimental-packages decision. +The CPython PTC runtime now lives at `packages/experimental/ptc-runtime-python` (private, npm name `@deepseek-ai/dsh-experimental-ptc-runtime-python`); promotion to a released package follows the experimental-packages decision. -English | [中文](2026-07-31-code-runtime-python-fd3-protocol.zh.md) +English | [中文](2026-07-31-ptc-runtime-python-fd3-protocol.zh.md) ## Problem -`@deepseek-ai/dsh-experimental-code-runtime-python` owns the wire protocol intended for a CPython code-runtime provider. Such a provider runs each model program in a fresh `python3 -I` subprocess and bridges binding calls and completion values over the child's fd 3. The host cannot trust that channel: model code has full access to fd 3 and can forge any frame, so every inbound frame is hostile input that the host must validate and rebuild before reading. The protocol also has to carry lossless JSON without the depth limit `JSON.stringify` and `json.dumps` impose, because the seam's `CodeJsonValue` is depth-unbounded. +`@deepseek-ai/dsh-experimental-ptc-runtime-python` owns the wire protocol intended for a CPython ptc-runtime provider. Such a provider runs each model program in a fresh `python3 -I` subprocess and bridges binding calls and completion values over the child's fd 3. The host cannot trust that channel: model code has full access to fd 3 and can forge any frame, so every inbound frame is hostile input that the host must validate and rebuild before reading. The protocol also has to carry lossless JSON without the depth limit `JSON.stringify` and `json.dumps` impose, because the seam's `PtcJsonValue` is depth-unbounded. -The private experimental package contains both the protocol and runtime implementation: `PythonCodeRuntime` (the plugin's default export), the `python3 -I` subprocess path, and the Python-side JSON codec all live in `@deepseek-ai/dsh-experimental-code-runtime-python`. The protocol builds on the [portable identifier seam](../../archived/architecture/2026-07-31-code-runtime-portable-identifier-seam.md). +The private experimental package contains both the protocol and runtime implementation: `PythonPtcRuntime` (the plugin's default export), the `python3 -I` subprocess path, and the Python-side JSON codec all live in `@deepseek-ai/dsh-experimental-ptc-runtime-python`. The protocol builds on the [portable identifier seam](../../archived/architecture/2026-07-31-code-runtime-portable-identifier-seam.md). ## Decision @@ -42,4 +42,4 @@ Frames are JSON-lines on fd 3, one object per line, leaving stdout/stderr free f Bought: the fd-3 protocol and its hostile-input codec form a self-contained, fully unit-covered layer, with an executing guard against TypeScript/Python field-set drift. The runtime built on it (`bootstrap.py`) consumes the reviewed wire contract. -Cost: the package name denotes a Python runtime family and `src/index.ts` exports the full `PythonCodeRuntime` implementation, so the protocol vocabulary is only one part of the package surface. The mirror e2e compares field names and required/optional status across the two sides but not field types; comparing type declarations across TypeScript and Python has no mechanical equivalent, so review and the runtime's real-subprocess suite retain that responsibility. +Cost: the package name denotes a Python runtime family and `src/index.ts` exports the full `PythonPtcRuntime` implementation, so the protocol vocabulary is only one part of the package surface. The mirror e2e compares field names and required/optional status across the two sides but not field types; comparing type declarations across TypeScript and Python has no mechanical equivalent, so review and the runtime's real-subprocess suite retain that responsibility. diff --git a/.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.zh.md b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md similarity index 77% rename from .agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.zh.md rename to .agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md index 568b6ff3d7..d5eea4cfd8 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md @@ -1,16 +1,16 @@ -# Agent Note: the code-runtime-python fd-3 frame protocol +# Agent Note: the ptc-runtime-python fd-3 frame protocol Status: implemented -CPython 代码运行时现在位于 `packages/experimental/code-runtime-python`(私有,npm 名 `@deepseek-ai/dsh-experimental-code-runtime-python`);提升为发布包遵循 experimental-packages 决策。 +CPython PTC 运行时现在位于 `packages/experimental/ptc-runtime-python`(私有,npm 名 `@deepseek-ai/dsh-experimental-ptc-runtime-python`);提升为发布包遵循 experimental-packages 决策。 -[English](2026-07-31-code-runtime-python-fd3-protocol.md) | 中文 +[English](2026-07-31-ptc-runtime-python-fd3-protocol.md) | 中文 ## Problem -`@deepseek-ai/dsh-experimental-code-runtime-python` 负责供 CPython code-runtime 提供方使用的 wire protocol。这样的提供方会在全新的 `python3 -I` 子进程中运行每个模型程序,并通过子进程 fd 3 桥接 binding 调用与完成值。Host 不能信任这条通道:模型代码可以完全访问 fd 3 并伪造任意帧,因此 host 必须把每个入站帧视为敌意输入,先校验并重建后才能读取。协议还必须承载无深度限制的 lossless JSON,因为 seam 的 `CodeJsonValue` 深度无界,而 `JSON.stringify` 和 `json.dumps` 都有递归深度限制。 +`@deepseek-ai/dsh-experimental-ptc-runtime-python` 负责供 CPython ptc-runtime 提供方使用的 wire protocol。这样的提供方会在全新的 `python3 -I` 子进程中运行每个模型程序,并通过子进程 fd 3 桥接 binding 调用与完成值。Host 不能信任这条通道:模型代码可以完全访问 fd 3 并伪造任意帧,因此 host 必须把每个入站帧视为敌意输入,先校验并重建后才能读取。协议还必须承载无深度限制的 lossless JSON,因为 seam 的 `PtcJsonValue` 深度无界,而 `JSON.stringify` 和 `json.dumps` 都有递归深度限制。 -这个私有实验包同时包含协议与 runtime 实现:`PythonCodeRuntime`(插件的默认导出)、`python3 -I` 子进程路径与 Python 侧 JSON codec 都在 `@deepseek-ai/dsh-experimental-code-runtime-python` 中。协议建立在[可移植标识符 seam](../../archived/architecture/2026-07-31-code-runtime-portable-identifier-seam.md)之上。 +这个私有实验包同时包含协议与 runtime 实现:`PythonPtcRuntime`(插件的默认导出)、`python3 -I` 子进程路径与 Python 侧 JSON codec 都在 `@deepseek-ai/dsh-experimental-ptc-runtime-python` 中。协议建立在[可移植标识符 seam](../../archived/architecture/2026-07-31-code-runtime-portable-identifier-seam.md)之上。 ## Decision @@ -42,4 +42,4 @@ CPython 代码运行时现在位于 `packages/experimental/code-runtime-python` 收获:fd-3 协议及其敌意输入 codec 构成自包含、unit 全覆盖的一层,并由执行中的 guard 防止 TypeScript/Python 字段集漂移。基于它构建的 runtime(`bootstrap.py`)消费经过评审的 wire contract。 -代价:包名表示 Python runtime 家族,而 `src/index.ts` 导出完整的 `PythonCodeRuntime` 实现,协议 vocabulary 只是包表面的一部分。mirror e2e 会比较两侧字段名与必填/可选状态,但不比较字段类型;跨 TypeScript 与 Python 比较类型声明没有机械等价物,因此评审与 runtime 的真实子进程套件继续负责这项检查。 +代价:包名表示 Python runtime 家族,而 `src/index.ts` 导出完整的 `PythonPtcRuntime` 实现,协议 vocabulary 只是包表面的一部分。mirror e2e 会比较两侧字段名与必填/可选状态,但不比较字段类型;跨 TypeScript 与 Python 比较类型声明没有机械等价物,因此评审与 runtime 的真实子进程套件继续负责这项检查。 diff --git a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml index eb701400a4..aad1a96be8 100644 --- a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md -2026-08-09-client-conversation-node-assembly.md: 842dfb0218478591f975c97064f101a35ea2f211 -2026-08-09-client-conversation-node-assembly.zh.md: 6ab64c25957d33487461fe56e122faedb19f9421 +2026-08-09-client-conversation-node-assembly.md: 43f9f0359822f7d7c5b52c09646fd3ffbf80f783 +2026-08-09-client-conversation-node-assembly.zh.md: d7475f5ff8218419743448d455d5d5ffe3cc4091 diff --git a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md index 842dfb0218..43f9f03598 100644 --- a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md +++ b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md @@ -263,7 +263,7 @@ Page size, record packing, the number of history loads, and RAF coalescing affec | Message / `input-message` | Message ID | Append-surface `user/message` | None | Use source for a context message, or read the nearest next-step Inbox to distinguish user from steering | | Request Prompt / `request-prompt` | Header Event seq | Each `request/header` | None | Read the preceding Request Prompt through Reader, retain the full prompt state, and classify system/tool changes | | Assistant / `assistant-step` | `turn:step` | `step/start` | Live `assistant/live-chunk`, durable `assistant/message` or `assistant/attempt`, and same-step Retry | Aggregate blocks, usage, first-token time, settlement evidence, and retry-hidden state, then publish same-key Step data | -| Tool / `tool-call` | Root call ID | Root `tool/call` | Root result and Code Dispatch start/result | Aggregate the root, children, and parent Map; Dispatch Events route exactly through `rootCallId` | +| Tool / `tool-call` | Root call ID | Root `tool/call` | Root result and PTC dispatch start/result | Aggregate the root, children, and parent Map; Dispatch Events route exactly through `rootCallId` | | Command / `command` | Command ID | `command/run` | `command/done` and compact lifecycle/checkpoint Events carrying a source command ID | Aggregate command outcome and manual-compaction evidence | | Automatic Compaction / `compaction` | Compaction ID | `compaction/start` without a source command ID | Summary, end, and replacement checkpoint | Aggregate summary/checkpoint; sufficient checkpoint evidence supports fallback without a start | | Retry / `model-retry` | Retry ID | Attempt 1 `llm/retry` | Later `llm/retry` and `llm/retry-started` | Aggregate one RetryId's attempts and scheduled/started state | @@ -360,7 +360,7 @@ SessionEventLike window Runtime tests pin Definition lifecycle registration, exact-ID append, update-before-start collection followed by forward replay after start, prepend identity, Reader window-gap repair, transitive dependencies, Location closure, Step→Turn data phase order, Location data replacement, publication cadence, illegal withdrawal, first-subscription activation, monotonic active targets, and per-target Builders. -Conversation tests cover every built-in Chat Definition, Assistant Step data, Turn Tail and Deliverables Turn data, Chat ordering and structural sharing, selector isolation, Assistant and Tool running-to-settled identity, nested Code Dispatch, steering, Compaction, Retry, interruption, load-older anchoring, and slot dispatch. Trajectory tests cover its independently registered Message, Assistant, Tool, Compaction, Request-header, and boundary Definitions together with the preserved stage-oriented view model. +Conversation tests cover every built-in Chat Definition, Assistant Step data, Turn Tail and Deliverables Turn data, Chat ordering and structural sharing, selector isolation, Assistant and Tool running-to-settled identity, nested PTC dispatch, steering, Compaction, Retry, interruption, load-older anchoring, and slot dispatch. Trajectory tests cover its independently registered Message, Assistant, Tool, Compaction, Request-header, and boundary Definitions together with the preserved stage-oriented view model. Slot type/runtime tests pin required parent-provided common inject, the `hookContext` type, Hook isolation across Node contexts, stable factory/Hook identity, and the absence of business-renderer rerenders for unrelated Session publications. Existing entry-owned Observable Hook tests continue to pin the path that does not use a contextual factory. diff --git a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md index 6ab64c2595..d7475f5ff8 100644 --- a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md @@ -263,7 +263,7 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新 | Message / `input-message` | message ID | append-surface `user/message` | 无 | 根据 source 生成 context message,或读取最近 next-step Inbox 判断 user/steering | | Request Prompt / `request-prompt` | header Event seq | 每条 `request/header` | 无 | 通过 Reader 读取前一条 Request Prompt,保留完整 prompt 状态,并判定 system/tool 变化 | | Assistant / `assistant-step` | `turn:step` | `step/start` | Live `assistant/live-chunk`、持久 `assistant/message` 或 `assistant/attempt`、同 step Retry | 聚合 block、usage、首 token 时间、settlement 证据与 retry-hidden state,再发布同 key Step data | -| Tool / `tool-call` | root call ID | root `tool/call` | root result、Code Dispatch start/result | 聚合 root、children 和 parent Map;Dispatch Event 用 `rootCallId` 精确路由 | +| Tool / `tool-call` | root call ID | root `tool/call` | root result、PTC dispatch start/result | 聚合 root、children 和 parent Map;Dispatch Event 用 `rootCallId` 精确路由 | | Command / `command` | command ID | `command/run` | `command/done`、带 source command ID 的 compact lifecycle/checkpoint | 聚合 command outcome 和手动压缩证据 | | Automatic Compaction / `compaction` | compaction ID | 无 source command ID 的 `compaction/start` | summary、end、replacement checkpoint | 聚合 summary/checkpoint;checkpoint 足够时可在缺 start 下 fallback | | Retry / `model-retry` | retry ID | attempt 1 的 `llm/retry` | 后续 `llm/retry` 与 `llm/retry-started` | 聚合同一 RetryId 的 attempts 与 scheduled/started 状态 | @@ -360,7 +360,7 @@ SessionEventLike window Runtime tests 固定 Definition 生命周期注册、exact-ID append、update-before-start 收集与 start 后正序 replay、prepend identity、Reader window-gap 修复、传递依赖、Location closure、Step→Turn data phase order、Location data replacement、publication cadence、非法撤回、首次订阅 activation、单调 active target 和 per-target Builder。 -Conversation tests 覆盖全部内建 Chat Definition、Assistant Step data、Turn Tail 与 Deliverables Turn data、Chat 排序和结构共享、selector isolation、Assistant/Tool running-to-settled identity、nested Code Dispatch、steering、Compaction、Retry、interruption、load-older anchoring 和 slot dispatch。Trajectory tests 则覆盖它独立注册的 Message、Assistant、Tool、Compaction、Request-header 与 boundary Definition,以及继续保留的 stage-oriented view model。 +Conversation tests 覆盖全部内建 Chat Definition、Assistant Step data、Turn Tail 与 Deliverables Turn data、Chat 排序和结构共享、selector isolation、Assistant/Tool running-to-settled identity、nested PTC dispatch、steering、Compaction、Retry、interruption、load-older anchoring 和 slot dispatch。Trajectory tests 则覆盖它独立注册的 Message、Assistant、Tool、Compaction、Request-header 与 boundary Definition,以及继续保留的 stage-oriented view model。 Slot type/runtime tests 固定父注册必须提供声明的 common inject、`hookContext` 类型、不同 Node context 的 Hook 隔离、factory/Hook identity 稳定,以及无关 Session publication 不重渲染业务 renderer。原 entry-owned Observable Hook 测试继续固定未使用 contextual factory 的路径。 diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml index 6f20df4af6..0e53dfc6d6 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md -2026-08-23-client-derived-tool-presentation.md: 6b19dc881d572bfece345cbbd5eca688b2e05aab -2026-08-23-client-derived-tool-presentation.zh.md: 98ada31627398f317e4c41336af56e8c6cf0837e +2026-08-23-client-derived-tool-presentation.md: 895618099c6669058d23fc0a58335a90d5fbe4ca +2026-08-23-client-derived-tool-presentation.zh.md: 38572f17c41ea9b68dc8c8c8cdc26a74d9dbb757 diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md index 6b19dc881d..895618099c 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md @@ -12,13 +12,13 @@ A `tool/result` does not repeat the tool name or arguments. Host-side result pre Host projection would also duplicate structured data. Read, diff, search, and web results already persist bounded facts in `tool/result.data.meta`; another view object increases Remote payload size and Client decoding without adding durable meaning. -The Client already owns a complete tool-presentation entry point. `ui-chat` assembles `tool/call`, `tool/result`, and Code Dispatch events into stable `ToolCallBlock` values. `ui-tool` owns the recursive call tree, the `tool.call.toolview` keyed slot dispatched by tool name, the Generic fallback, card models, and details output. A business Client plugin can register a renderer for its own tool names. +The Client already owns a complete tool-presentation entry point. `ui-chat` assembles `tool/call`, `tool/result`, and PTC dispatch events into stable `ToolCallBlock` values. `ui-tool` owns the recursive call tree, the `tool.call.toolview` keyed slot dispatched by tool name, the Generic fallback, card models, and details output. A business Client plugin can register a renderer for its own tool names. Splitting presentation between Host presenters and Client keyed renderers creates two interpretations of the same event. The keyed renderer is the Web extension point, so an intermediate Host view provides no independent Web capability. `ToolDefinition.presentCall` and `presentResult` remain useful Host APIs even though ACP is automation-only and the repository has no production TUI consumer. Removing their definitions is a separate decision from keeping Session reads independent of presentation. -The required result is one raw Session journal and one Client presentation owner without visual degradation or incidental enhancement. Specialized cards, interactions, and Code Dispatch topology remain stable while the transport stops carrying transient views. +The required result is one raw Session journal and one Client presentation owner without visual degradation or incidental enhancement. Specialized cards, interactions, and PTC dispatch topology remain stable while the transport stops carrying transient views. ## Decision @@ -26,7 +26,7 @@ The visual-equivalence requirements below exclude the separately approved [neste The Session Remote journal sends only raw, validated, persistable Session events. `session.page` and `session.follow` do not parse tool arguments, query the Tools registry, restore a presenter scope, execute `presentCall` or `presentResult`, or construct or clone any tool view. -The Client Conversation layer continues to own tool call/result identity, pairing, lifecycle, Code Dispatch topology, and stable Chat Nodes. It does not interpret individual tool names or produce terminal, diff, read, search, or web component props. +The Client Conversation layer continues to own tool call/result identity, pairing, lifecycle, PTC dispatch topology, and stable Chat Nodes. It does not interpret individual tool names or produce terminal, diff, read, search, or web component props. Client `ui-tool` continues to own card models and concrete renderers. Each card model directly reads the tool name, raw arguments, result content, error, durable metadata, Session cwd, and Host home from `ToolCallBlock`, and produces the same component props as the current page. @@ -51,7 +51,7 @@ The Host `ToolDefinition.presentCall`, `ToolDefinition.presentResult`, `ToolCall | Retained | the Session log format, Remote journal lifecycle, and Conversation identity/topology | | Retained | the existing keyed slot, Generic fallback, and Chat, Details, and Trajectory structure | | Forbidden | a new Client presenter service, parallel registry, or wire renderer id | -| Forbidden | new cards, visual redesign, interaction redesign, or Code Dispatch rich-card enhancements except the [nested terminal-card exception](../bug-fix/2026-09-05-nested-terminal-cards.md) | +| Forbidden | new cards, visual redesign, interaction redesign, or PTC dispatch rich-card enhancements except the [nested terminal-card exception](../bug-fix/2026-09-05-nested-terminal-cards.md) | | Forbidden | compatibility dual-writing, version negotiation, or retention of the old `view` field | ## Terminology @@ -96,7 +96,7 @@ The Host `ToolDefinition.presentCall`, `ToolDefinition.presentResult`, `ToolCall 1. The Client Session stores one contiguous raw event window. 2. `SessionEventSource` publishes `SessionEventEntry` values containing only events. 3. `ui-conversation` folds each event without a presentation companion. -4. The Chat and Trajectory Tool Definitions pair top-level calls and results by callId and assemble Code Dispatch subtrees. +4. The Chat and Trajectory Tool Definitions pair top-level calls and results by callId and assemble PTC dispatch subtrees. 5. `RunningToolCall` and `ToolResultNode` retain raw facts, metadata, and existing parent identity. 6. `ToolCallTree` dispatches `tool.call.toolview` by wire tool name. 7. `ui-tool` derives card component props from the block at the render site. @@ -132,7 +132,7 @@ Session page/follow Client SessionEventSource -> Conversation Tool Definition - -> root call/result pairing + Code Dispatch topology + -> root call/result pairing + PTC dispatch topology -> ToolCallBlock(name, argsRaw, content, error, meta) -> tool.call.toolview keyed dispatch -> Client card model @@ -242,11 +242,11 @@ The Chat and Trajectory Tool Definitions read no views. They derive the followin `ToolCallBlock` does not gain a generic `view`, `card`, `kind`, or `locations` field to replace the deleted fields. Concrete presentation remains the responsibility of `ui-tool` and keyed renderers. -### Root and Code Dispatch subcalls +### Root and PTC dispatch subcalls -Host presenter APIs describe top-level calls and results. Code Dispatch subcalls retain Generic, flattened presentation for the diff, read, search, and web models covered here; supported terminal calls use the same eligibility rules as roots. +Host presenter APIs describe top-level calls and results. PTC dispatch subcalls retain Generic, flattened presentation for the diff, read, search, and web models covered here; supported terminal calls use the same eligibility rules as roots. -Code Dispatch start and result events already carry `parentCallId`. Conversation preserves that existing fact on each child `ToolCallBlock`; root Session calls omit it. The diff, read, search, and web models accept only blocks without `parentCallId`; the terminal model and existing renderers that intentionally support nested calls accept child blocks. +PTC dispatch start and result events already carry `parentCallId`. Conversation preserves that existing fact on each child `ToolCallBlock`; root Session calls omit it. The diff, read, search, and web models accept only blocks without `parentCallId`; the terminal model and existing renderers that intentionally support nested calls accept child blocks. Shared card models apply the same terminal eligibility and nonterminal child restrictions wherever a block renders, so no second presentation surface needs a placement field; the details panel that once delegated a selected block was removed with the right-hand details column ([decision](../feature/2026-09-04-right-sidebar-docking-infrastructure.md)). @@ -308,7 +308,7 @@ The Client terminal model derives existing `TerminalBlock` props from the tool n | settled persistent `bash`/`pwsh` | Generic flattened result, with no new exit card | | foreground `terminal_send` | terminal prompt and output | | background/error `terminal_send` | Generic result | -| Code Dispatch child | same terminal eligibility and fallback rules as a root call | +| PTC dispatch child | same terminal eligibility and fallback rules as a root call | Standard shell results parse trailing `[exit code: N]` and `[killed by signal: X]` markers. A final recognized spill-policy notice selects Generic output instead: expandable in shell rows and raw in Details, because the exit marker may be displaced or omitted. A parsed marker is removed from the terminal body; timeout, sandbox denial, and markers without a pill remain in the body. @@ -331,7 +331,7 @@ Standard and persistent providers sharing the same tool name are a special compa | successful settled `write`/`edit` | applied contextual hunks from `meta.diffs` | | settled `str_replace_editor` | Generic, because the tool defines no result presenter | | write create or missing/malformed/empty applied metadata | current argument fallback | -| error, malformed arguments, edit with malformed metadata, or Code Dispatch child | Generic | +| error, malformed arguments, edit with malformed metadata, or PTC dispatch child | Generic | Paths, `oldText:null`, `newText`, result-over-call diff precedence, the eight-line Chat limit, full-height Details presentation, and file-opening behavior remain unchanged. @@ -339,7 +339,7 @@ Paths, `oldText:null`, `newText`, result-over-call diff precedence, the eight-li A running `read` continues to show only the summary row. A successful settled `read` reads path, offset, lines, totalLines, and lang from result metadata and confirms that the result is one text block matching the read envelope. -Missing metadata, malformed fields, a mismatched result envelope, an error, a missing call head, or a Code Dispatch child all use Generic. Cwd-relative path labels, home abbreviation, syntax language, total line count, the eight-line Chat limit, and full-height Details presentation remain unchanged. +Missing metadata, malformed fields, a mismatched result envelope, an error, a missing call head, or a PTC dispatch child all use Generic. Cwd-relative path labels, home abbreviation, syntax language, total line count, the eight-line Chat limit, and full-height Details presentation remain unchanged. The Client does not need to construct Host `ReadResultView.content`; Generic fallback can always read raw result content directly. @@ -347,7 +347,7 @@ The Client does not need to construct Host `ReadResultView.content`; Generic fal A running `grep` or `glob` continues to show only the argument summary. Successful results produce grouped matches or a path list from `meta.shape:'matches'` and `meta.shape:'paths'`, respectively. -The Client validates path, lineNumber, line, truncated, and total. Empty matches or paths form a valid card. Missing or malformed metadata, an unknown shape, an error, a missing call head, or a Code Dispatch child uses Generic. +The Client validates path, lineNumber, line, truncated, and total. Empty matches or paths form a valid card. Missing or malformed metadata, an unknown shape, an error, a missing call head, or a PTC dispatch child uses Generic. When `truncated:true`, the card continues to show a recovery locator from raw result content. It does not show one when untruncated. The eight-line Chat limit, full-height Details presentation, and expansion behavior remain unchanged. @@ -355,7 +355,7 @@ When `truncated:true`, the card continues to show a recovery locator from raw re A running `web_search` or `web_fetch` continues to show only the summary row. A successful search builds the card from `meta.sources`, `meta.answer`, and `meta.truncated`; a successful fetch builds it from `meta.url`, `meta.statusCode`, and `meta.truncated`. -The Client validates every source's url, title, snippet, and publishedAt, and continues rendering only http/https URLs as links. Missing or malformed metadata, an error, a missing call head, or a Code Dispatch child uses Generic. +The Client validates every source's url, title, snippet, and publishedAt, and continues rendering only http/https URLs as links. Missing or malformed metadata, an error, a missing call head, or a PTC dispatch child uses Generic. Search answer text, source ordering, label fallback, and truncation notice remain unchanged. The fetch final URL, status, truncation notice, and raw body below Details remain unchanged. @@ -420,7 +420,7 @@ The fixture does not import Host tool packages to compute page presentation and | grep/glob | current grouped/path card, truncation, and recovery | | web_search/web_fetch | current source/summary card and raw body | | Todo/Question/Skill/Cordis | current specialized rows | -| Code Dispatch subcall | terminal cards when eligible; diff/read/search/web remain Generic/flattened | +| PTC dispatch subcall | terminal cards when eligible; diff/read/search/web remain Generic/flattened | | Chat and Details | identical card fields for the same call | | Trajectory | current identity, tree, selection, and details | | Deliverables | current successful-mutation chips and links | @@ -478,7 +478,7 @@ This change does not promise to preserve differences expressed only through a Ho - Conversation input and Tool blocks contain no view fields. - Chat and Trajectory Tool Definitions read raw events. - Event pairing, Context replay, trees, and target snapshots remain unchanged. -- Child Tool blocks preserve the existing Code Dispatch `parentCallId`; row and Details slot owner props add no separate placement field. +- Child Tool blocks preserve the existing PTC dispatch `parentCallId`; row and Details slot owner props add no separate placement field. ### UI Tool and Deliverables @@ -515,7 +515,7 @@ This change does not promise to preserve differences expressed only through a Ho - replace, prepend, and append accept entries without views. - Chat and Trajectory root call/result pairing remains unchanged. -- The Code Dispatch tree remains unchanged. +- The PTC dispatch tree remains unchanged. - Result-only fallback remains unchanged. - A synthetic interruption result copies no view. - Node identity across registry rebuild, older prepend, and live append remains unchanged. @@ -589,7 +589,7 @@ Changes to this decision use `dsh-pre-push-checks` to select commands for the fi - Deliverables does not depend on render intent and preserves current paths. - Text, components, expanded content, states, links, and ordering for all first-party top-level tools remain unchanged. - Malformed, missing-metadata, error, orphan, and unknown-tool cases continue to fall back safely. -- Code Dispatch diff, read, search, and web subcalls remain Generic and flattened; terminal subcalls follow root eligibility. +- PTC dispatch diff, read, search, and web subcalls remain Generic and flattened; terminal subcalls follow root eligibility. - Chat, Details, and Trajectory behavior remains unchanged. - Existing Web browser expected outputs pass without refresh. - Host presenter APIs, implementations, and direct tests remain unchanged. @@ -634,7 +634,7 @@ An on-demand RPC would turn one page read into N network calls and would still r ### Allow presentation enhancements -Bundling richer Code Dispatch cards, missing-call-head inference, or other historical presentation enhancements with the ownership change would prevent snapshots from proving equivalence. This decision rejects that coupling; the [nested terminal-card exception](../bug-fix/2026-09-05-nested-terminal-cards.md) does not relax nonterminal child restrictions. +Bundling richer PTC dispatch cards, missing-call-head inference, or other historical presentation enhancements with the ownership change would prevent snapshots from proving equivalence. This decision rejects that coupling; the [nested terminal-card exception](../bug-fix/2026-09-05-nested-terminal-cards.md) does not relax nonterminal child restrictions. ### Accept temporary Generic degradation @@ -703,7 +703,7 @@ This note preserves result metadata from the [canonical tool output contract](20 ## Deferred - A separate explicit decision may evaluate deleting Host presenters if they remain without production consumers; this decision does not prejudge it. -- Specialized diff, read, search, and web cards for Code Dispatch subcalls require a separate design and visible-snapshot updates; terminal calls are covered by the linked partial supersession. +- Specialized diff, read, search, and web cards for PTC dispatch subcalls require a separate design and visible-snapshot updates; terminal calls are covered by the linked partial supersession. - A third-party mutation tool that joins Deliverables requires a new Client-owned contribution; this decision does not create a registry for an absent consumer. - Distinct Client presentation for same-named providers first requires a stable, non-presentational identity; it must not restore per-page Host views. - If Client card-model performance needs measurement, an immutable-block microbenchmark can be added; the shipped architecture already prohibits scanning the Session window. diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md index 98ada31627..38572f17c4 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md @@ -12,13 +12,13 @@ Session 历史是持久 journal 接口,工具卡片属于 Client 展示。在 Host 投影还会重复结构化数据。read、diff、search 与 web 结果已在 `tool/result.data.meta` 中持久化有界事实;另一份 view 只增加 Remote payload 与 Client 解码成本,不增加持久语义。 -Client 已经拥有完整的工具展示入口。`ui-chat` 将 `tool/call`、`tool/result` 与 Code Dispatch 事件组装成稳定的 `ToolCallBlock`;`ui-tool` 拥有递归调用树、按工具名称分发的 `tool.call.toolview` keyed slot、Generic fallback、卡片模型和 details output;业务 Client 插件可以为自己的工具名称注册 renderer。 +Client 已经拥有完整的工具展示入口。`ui-chat` 将 `tool/call`、`tool/result` 与 PTC dispatch 事件组装成稳定的 `ToolCallBlock`;`ui-tool` 拥有递归调用树、按工具名称分发的 `tool.call.toolview` keyed slot、Generic fallback、卡片模型和 details output;业务 Client 插件可以为自己的工具名称注册 renderer。 Host presenter 与 Client keyed renderer 分担展示会形成对同一事件的两套解释。keyed renderer 是 Web 扩展点,因此中间 Host view 不提供独立 Web 能力。 `ToolDefinition.presentCall`/`presentResult` 仍是保留的 Host API;ACP 采用 automation-only 协议,仓库也没有生产 TUI consumer。是否删除这些定义与 Session 读取是否独立于展示是两个决定。 -所需结果是一条原始 Session journal 和一个 Client 展示 owner,且不发生可见退化或顺带增强。专用卡片、交互和 Code Dispatch 拓扑保持稳定,transport 不再携带临时 view。 +所需结果是一条原始 Session journal 和一个 Client 展示 owner,且不发生可见退化或顺带增强。专用卡片、交互和 PTC dispatch 拓扑保持稳定,transport 不再携带临时 view。 ## Decision @@ -26,7 +26,7 @@ Host presenter 与 Client keyed renderer 分担展示会形成对同一事件的 Session Remote journal 只下发原始、已验证、可持久化的 Session event。`session.page` 和 `session.follow` 不解析工具参数,不查询 Tools registry,不恢复 presenter scope,不执行 `presentCall`/`presentResult`,也不构造或克隆任何 tool view。 -Client Conversation 层继续负责工具调用与结果的 identity、配对、生命周期、Code Dispatch 拓扑和稳定 Chat Node。它不解释具体工具名称,也不生成 terminal、diff、read、search 或 web 组件 props。 +Client Conversation 层继续负责工具调用与结果的 identity、配对、生命周期、PTC dispatch 拓扑和稳定 Chat Node。它不解释具体工具名称,也不生成 terminal、diff、read、search 或 web 组件 props。 Client `ui-tool` 继续负责 card model 和具体 renderer。每个 card model 改为直接读取 `ToolCallBlock` 中的工具名称、原始参数、结果内容、错误、持久 metadata、Session cwd 与 Host home,并生成与现有页面相同的组件 props。 @@ -51,7 +51,7 @@ Host 的 `ToolDefinition.presentCall`、`ToolDefinition.presentResult`、`ToolCa | 保留 | Session 日志格式、Remote journal 生命周期与 Conversation identity/topology | | 保留 | 现有 keyed slot、Generic fallback、Chat、Details 与 Trajectory 结构 | | 禁止 | 新 Client presenter service、平行 registry 或 wire renderer id | -| 禁止 | 新卡片、视觉改版、交互改版或 Code Dispatch rich-card 增强,[嵌套 terminal 卡片例外](../bug-fix/2026-09-05-nested-terminal-cards.zh.md)除外 | +| 禁止 | 新卡片、视觉改版、交互改版或 PTC dispatch rich-card 增强,[嵌套 terminal 卡片例外](../bug-fix/2026-09-05-nested-terminal-cards.zh.md)除外 | | 禁止 | 为兼容保留双写、版本协商或旧 `view` 字段 | ## 术语 @@ -96,7 +96,7 @@ Host 的 `ToolDefinition.presentCall`、`ToolDefinition.presentResult`、`ToolCa 1. Client Session 保存一个连续 raw event window。 2. `SessionEventSource` 发布只含 event 的 `SessionEventEntry`。 3. `ui-conversation` 在没有 presentation companion 的情况下 fold 每个事件。 -4. Chat 与 Trajectory Tool Definition 按 callId 配对顶层 call/result,并组装 Code Dispatch 子树。 +4. Chat 与 Trajectory Tool Definition 按 callId 配对顶层 call/result,并组装 PTC dispatch 子树。 5. `RunningToolCall` 与 `ToolResultNode` 保存 raw facts、metadata 与既有 parent identity。 6. `ToolCallTree` 按 wire tool name 分发 `tool.call.toolview`。 7. `ui-tool` 在 render site 从 block 派生 card component props。 @@ -132,7 +132,7 @@ Session page/follow Client SessionEventSource -> Conversation Tool Definition - -> root call/result pairing + Code Dispatch topology + -> root call/result pairing + PTC dispatch topology -> ToolCallBlock(name, argsRaw, content, error, meta) -> tool.call.toolview keyed dispatch -> Client card model @@ -242,11 +242,11 @@ Chat 和 Trajectory 的 Tool Definition 都不读取 view,而从事件生成 `ToolCallBlock` 不新增通用 `view`、`card`、`kind` 或 `locations` 字段替代被删除字段。具体展示仍只属于 `ui-tool` 与 keyed renderer。 -### Root 与 Code Dispatch 子调用 +### Root 与 PTC dispatch 子调用 -Host presenter API 描述顶层 call/result。本决定覆盖的 diff、read、search 和 web model 对 Code Dispatch 子调用保留 Generic/flattened 展示;受支持的 terminal 调用使用与根调用相同的适用规则。 +Host presenter API 描述顶层 call/result。本决定覆盖的 diff、read、search 和 web model 对 PTC dispatch 子调用保留 Generic/flattened 展示;受支持的 terminal 调用使用与根调用相同的适用规则。 -Code Dispatch start 与 result event 已经携带 `parentCallId`。Conversation 在每个 child `ToolCallBlock` 上保留这项现有事实,root Session call 则不携带它。diff、read、search 和 web model 只接受没有 `parentCallId` 的 block;terminal model 与原本有意支持嵌套调用的 renderer 接受 child block。 +PTC dispatch start 与 result event 已经携带 `parentCallId`。Conversation 在每个 child `ToolCallBlock` 上保留这项现有事实,root Session call 则不携带它。diff、read、search 和 web model 只接受没有 `parentCallId` 的 block;terminal model 与原本有意支持嵌套调用的 renderer 接受 child block。 共享的 card model 在 block 渲染到哪里都施加同样的终端资格与非终端子调用限制,因此不需要第二个展示面带 placement 字段;曾经原样委托选中 block 的详情面板已随右侧详情列一并删除([决策](../feature/2026-09-04-right-sidebar-docking-infrastructure.zh.md))。 @@ -308,7 +308,7 @@ Client terminal model 从工具名称、调用参数、结果 content、error | persistent `bash`/`pwsh` settled | Generic flattened result,不新增 exit card | | `terminal_send` 前台 | terminal prompt 与 output | | `terminal_send` background/error | Generic 结果 | -| Code Dispatch child | 与根调用相同的 terminal 适用规则与 fallback 规则 | +| PTC dispatch child | 与根调用相同的 terminal 适用规则与 fallback 规则 | 标准 shell 结果解析末尾 `[exit code: N]` 与 `[killed by signal: X]`。末尾已识别的 spill 策略提示会改用 Generic 输出:在 shell 行中可展开,在 Details 中显示原文,因为退出标记可能被移位或省略。已解析的 marker 从 terminal 正文移除;timeout、sandbox denial 与没有 pill 的 marker 留在正文。 @@ -331,7 +331,7 @@ TerminalBlock 的 ANSI、光标重放、宽字符、行数上限、展开、复 | settled `write`/`edit` success | 从 `meta.diffs` 生成 applied contextual hunks | | settled `str_replace_editor` | Generic,因为该工具没有 result presenter | | write create 或 applied metadata 缺失、畸形、为空 | 当前 args fallback | -| error、畸形 args、edit 的 metadata 畸形、Code Dispatch child | Generic | +| error、畸形 args、edit 的 metadata 畸形、PTC dispatch child | Generic | 路径、`oldText:null`、`newText`、结果覆盖调用时 diff、Chat 8 行上限、Details 全高显示和文件打开行为不变。 @@ -339,7 +339,7 @@ TerminalBlock 的 ANSI、光标重放、宽字符、行数上限、展开、复 running `read` 继续只有摘要行。成功 settled `read` 从 result meta 读取 path、offset、lines、totalLines 与 lang,并确认结果是单个文本块且符合 read envelope。 -meta 缺失、字段畸形、result envelope 不匹配、error、缺失 call head 或 Code Dispatch child 都走 Generic。路径 label 的 cwd 相对化、home 缩写、语法语言、总行数、Chat 8 行上限与 Details 全高显示不变。 +meta 缺失、字段畸形、result envelope 不匹配、error、缺失 call head 或 PTC dispatch child 都走 Generic。路径 label 的 cwd 相对化、home 缩写、语法语言、总行数、Chat 8 行上限与 Details 全高显示不变。 Client 不需要构造 Host `ReadResultView.content`;Generic fallback 始终可直接读取原始 result content。 @@ -347,7 +347,7 @@ Client 不需要构造 Host `ReadResultView.content`;Generic fallback 始终 running `grep`/`glob` 继续只有参数摘要。成功结果分别从 `meta.shape:'matches'` 与 `meta.shape:'paths'` 生成 grouped matches 或 path list。 -Client 校验 path、lineNumber、line、truncated 与 total。空 matches/paths 是有效卡片;缺失/畸形 meta、未知 shape、error、缺失 call head 与 Code Dispatch child 走 Generic。 +Client 校验 path、lineNumber、line、truncated 与 total。空 matches/paths 是有效卡片;缺失/畸形 meta、未知 shape、error、缺失 call head 与 PTC dispatch child 走 Generic。 `truncated:true` 时继续从原始 result content 显示 recovery locator;未截断时不显示。Chat 8 行上限、Details 全高显示和展开行为不变。 @@ -355,7 +355,7 @@ Client 校验 path、lineNumber、line、truncated 与 total。空 matches/paths running `web_search`/`web_fetch` 继续只有摘要行。成功 search 从 `meta.sources`、`meta.answer`、`meta.truncated` 生成卡片;成功 fetch 从 `meta.url`、`meta.statusCode`、`meta.truncated` 生成卡片。 -Client 校验每个 source 的 url、title、snippet 与 publishedAt,并继续只把 http/https URL 渲染为链接。meta 缺失或畸形、error、缺失 call head 与 Code Dispatch child 走 Generic。 +Client 校验每个 source 的 url、title、snippet 与 publishedAt,并继续只把 http/https URL 渲染为链接。meta 缺失或畸形、error、缺失 call head 与 PTC dispatch child 走 Generic。 search 的 answer、来源顺序、label fallback 与截断提示不变;fetch 的最终 URL、状态、截断提示与 Details 下方原始正文不变。 @@ -420,7 +420,7 @@ fixture 不导入 Host 工具包来计算页面展示,也不保留 presenter | grep/glob | 当前 grouped/path card、截断与 recovery | | web_search/web_fetch | 当前来源/摘要 card 与原始正文 | | Todo/Question/Skill/Cordis | 当前专用行 | -| Code Dispatch subcall | 满足条件时显示 terminal 卡片;diff/read/search/web 保持 Generic/flattened | +| PTC dispatch subcall | 满足条件时显示 terminal 卡片;diff/read/search/web 保持 Generic/flattened | | Chat 与 Details | 同一调用使用相同 card fields | | Trajectory | 当前 identity、树、选择和 details | | Deliverables | 当前成功 mutation chips 与链接 | @@ -478,7 +478,7 @@ Host registry 允许不同 scope 为同一 tool name 提供不同定义;Sessio - Conversation input 与 Tool block 不含 view 字段。 - Chat/Trajectory Tool Definition 读取 raw event。 - event pairing、Context replay、树与 target snapshot 保持不变。 -- child Tool block 保留现有 Code Dispatch `parentCallId`;row 与 Details slot owner props 都不增加独立 placement 字段。 +- child Tool block 保留现有 PTC dispatch `parentCallId`;row 与 Details slot owner props 都不增加独立 placement 字段。 ### UI Tool 与 Deliverables @@ -515,7 +515,7 @@ Host registry 允许不同 scope 为同一 tool name 提供不同定义;Sessio - replace、prepend 与 append 接受无 view entry。 - Chat 与 Trajectory root call/result 配对不变。 -- Code Dispatch 树不变。 +- PTC dispatch 树不变。 - result-only fallback 不变。 - interruption synthetic result 不复制 view。 - registry rebuild、older prepend 与 live append 的 Node identity 不变。 @@ -589,7 +589,7 @@ Host registry 允许不同 scope 为同一 tool name 提供不同定义;Sessio - Deliverables 不依赖 render intent 且保持当前 paths。 - 所有第一方顶层工具的文本、组件、展开内容、状态、链接与排序不变。 - malformed、missing-meta、error、orphan 与 unknown-tool 继续安全 fallback。 -- Code Dispatch 的 diff、read、search 和 web 子调用保持 Generic/flattened;terminal 子调用遵循根调用适用规则。 +- PTC dispatch 的 diff、read、search 和 web 子调用保持 Generic/flattened;terminal 子调用遵循根调用适用规则。 - Chat、Details 与 Trajectory 行为不变。 - 现有 Web browser expected 无需刷新即可通过。 - Host presenter API、实现与直接测试不变。 @@ -634,7 +634,7 @@ read 行结构、applied diff、search 分组、web sources 和有效 truncation ### 允许展示增强 -将更丰富的 Code Dispatch 卡片、缺失 call head 的推断或其他历史展示增强与所有权变更捆绑,会使快照无法证明对等。本决定拒绝这种捆绑;[嵌套 terminal 卡片例外](../bug-fix/2026-09-05-nested-terminal-cards.zh.md)不放宽非 terminal 子调用限制。 +将更丰富的 PTC dispatch 卡片、缺失 call head 的推断或其他历史展示增强与所有权变更捆绑,会使快照无法证明对等。本决定拒绝这种捆绑;[嵌套 terminal 卡片例外](../bug-fix/2026-09-05-nested-terminal-cards.zh.md)不放宽非 terminal 子调用限制。 ### 接受临时 Generic 退化 @@ -703,7 +703,7 @@ optional `view` 的缺失是所有 consumer 共同遵守的预发布 wire 类型 ## Deferred - Host presenter 若长期没有生产消费者,可由另一项明确决策评估删除;本决定不预判。 -- Code Dispatch 子调用的 diff、read、search 和 web 专用卡片仍需独立设计并更新可见快照;terminal 调用由链接的部分取代决策负责。 +- PTC dispatch 子调用的 diff、read、search 和 web 专用卡片仍需独立设计并更新可见快照;terminal 调用由链接的部分取代决策负责。 - 第三方 mutation tool 若要加入 Deliverables,需新增 Client-owned 贡献;本决定不为尚无消费者的扩展性建 registry。 - 同名 provider 若要不同 Client 展示,需先定义稳定、非展示性的 identity;不得恢复按页 Host view。 - Client card model 若需量化性能,可以增加 immutable-block 微基准;已交付架构禁止扫描 Session window。 diff --git a/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.i18n.yaml index 27a96b45f7..ad9576252c 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.md -2026-08-27-outbound-proxy-policy.md: 719bcac2f1c2322977d381a315de43b62e8b6951 -2026-08-27-outbound-proxy-policy.zh.md: ad1bfce85a1c4d4140863722c84b42d62932080a +2026-08-27-outbound-proxy-policy.md: 9db894c45bd1c816e7394ac621e4be18a8a94e74 +2026-08-27-outbound-proxy-policy.zh.md: 30e30e725ade9d6daf94129fa45b81a6aeb97f96 diff --git a/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.md b/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.md index 719bcac2f1..9db894c45b 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.md +++ b/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.md @@ -40,7 +40,7 @@ This keeps `proxyForUrl()` and the dispatcher answering from one set of values. The URL-level policy is untouched: `http(s)` only, no embedded credentials, the length cap, and the cross-origin redirect refusal all still apply on every hop. -**A spawned child gets the policy through its environment; a model-executing worker gets nothing.** `proxyEnvironmentForChild()` merges into `scrubbedParentEnv()`, the one function every spawner already shares. The workflow worker does NOT receive it: it executes the model-authored script body, and a proxy URL may carry `user:password`. That is the same containment the code runtime keeps and `docs/defensive-patterns.md` requires, so a workflow's own requests go direct. +**A spawned child gets the policy through its environment; a model-executing worker gets nothing.** `proxyEnvironmentForChild()` merges into `scrubbedParentEnv()`, the one function every spawner already shares. The workflow worker does NOT receive it: it executes the model-authored script body, and a proxy URL may carry `user:password`. That is the same containment the PTC runtime keeps and `docs/defensive-patterns.md` requires, so a workflow's own requests go direct. The child keeps the user's own values, and that is what once broke it. Node parses `HTTP_PROXY` and `HTTPS_PROXY` under `NODE_USE_ENV_PROXY` before running the program and exits on any scheme other than `http:` or `https:`; a `socks4://` kept for `curl` therefore ended every Node child — MCP servers, subagent CLIs, `npm` — before its first line, while this process had reported only that the scheme stayed direct. Measured on Node 24.17: `socks4://`, `ftp://`, and a malformed value all exit 1; `socks5://` happens to be accepted there. The flag is now withheld whenever a value the child receives is one this package refused, so such a child connects directly and `curl` still reads the value it was kept for. Handing the child the resolved value instead would have kept Node proxied at the price of silently rewriting what the user set for another tool. @@ -70,7 +70,7 @@ Weighed against that, telemetry is the one outbound channel whose loss costs the **Read the operating system's proxy settings.** Rejected for this change. Only Codex and Reasonix among six surveyed products do it, and Codex keeps it behind a default-off flag. Measured on the author's machine, it would have found nothing: the proxy application had written the setting to the Wi-Fi service while the primary interface was a USB ethernet adapter with no proxy, so `scutil --proxy` reported none while the exported variables worked. It also needs its own bypass matcher, because an operating system list carries CIDR entries that neither undici nor Node matches. -**Give model-authored code the proxy too.** Rejected because a proxy URL may carry credentials. Node code-runtime processes and workflow workers keep those settings outside the program environment; direct network use remains subject to the program's execution policy. +**Give model-authored code the proxy too.** Rejected because a proxy URL may carry credentials. Node ptc-runtime processes and workflow workers keep those settings outside the program environment; direct network use remains subject to the program's execution policy. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.zh.md b/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.zh.md index ad1bfce85a..30e30e725a 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-27-outbound-proxy-policy.zh.md @@ -40,7 +40,7 @@ Node 内置的 `fetch` 会忽略 `HTTP_PROXY` 与 `HTTPS_PROXY`。开发者运 URL 层策略未受影响:仅 `http(s)`、禁止内嵌凭据、长度上限与跨域重定向拒绝在每一跳上依然生效。 -**派生的子进程通过环境获得策略;执行模型代码的 worker 什么也不获得。** `proxyEnvironmentForChild()` 并入 `scrubbedParentEnv()`——每个 spawner 本就共享的那一个函数。workflow worker **不**接收它:它执行的是模型编写的脚本体,而代理 URL 可能携带 `user:password`。这与 code runtime 保持的隔离相同,也是 `docs/defensive-patterns.md` 的要求,因此 workflow 自身的请求直连。 +**派生的子进程通过环境获得策略;执行模型代码的 worker 什么也不获得。** `proxyEnvironmentForChild()` 并入 `scrubbedParentEnv()`——每个 spawner 本就共享的那一个函数。workflow worker **不**接收它:它执行的是模型编写的脚本体,而代理 URL 可能携带 `user:password`。这与 PTC runtime 保持的隔离相同,也是 `docs/defensive-patterns.md` 的要求,因此 workflow 自身的请求直连。 子进程拿到的是用户自己的值,而这恰恰曾把它弄坏。Node 在 `NODE_USE_ENV_PROXY` 下会在运行程序之前先解析 `HTTP_PROXY` 与 `HTTPS_PROXY`,遇到 `http:`/`https:` 之外的协议直接退出;于是一个为 `curl` 保留的 `socks4://` 会让每个 Node 子进程——MCP server、subagent CLI、`npm`——在第一行之前就终结,而本进程此前只报告过该协议保持直连。在 Node 24.17 上实测:`socks4://`、`ftp://` 与畸形值均以 1 退出;`socks5://` 恰好在该版本被接受。现在只要子进程收到的某个值是本包拒绝过的,就扣下该标志,这样的子进程直连,`curl` 仍读到为它保留的值。若改为把解析后的值交给子进程,Node 固然能继续走代理,代价却是悄悄改写用户为另一工具设置的值。 @@ -70,7 +70,7 @@ URL 层策略未受影响:仅 `http(s)`、禁止内嵌凭据、长度上限与 **读取操作系统的代理设置。** 本次变更中被否决。所调研的六个产品中只有 Codex 与 Reasonix 这样做,且 Codex 把它放在默认关闭的开关之后。在作者机器上实测,它什么也读不到:代理软件把设置写在了 Wi-Fi 服务上,而主接口是一块没有代理的 USB 以太网卡,因此 `scutil --proxy` 报告无代理,而导出的环境变量却工作正常。它还需要自带的绕过匹配器,因为操作系统的列表含有 undici 与 Node 都不匹配的 CIDR 条目。 -**也把代理配置交给模型编写的代码。** 不采纳,因为代理 URL 可能携带凭据。Node code-runtime 进程与 workflow worker 不在程序环境中提供这些设置;直接网络访问仍受程序执行策略约束。 +**也把代理配置交给模型编写的代码。** 不采纳,因为代理 URL 可能携带凭据。Node ptc-runtime 进程与 workflow worker 不在程序环境中提供这些设置;直接网络访问仍受程序执行策略约束。 ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml index 3e7b57be41..d7adb64692 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md -2026-09-11-posix-ssh-runtime.md: 9f5de9d2efe09779989c54ba03b0b2b5badacf05 -2026-09-11-posix-ssh-runtime.zh.md: 76184c0d88764552626744ac5b138ff56fa28be3 +2026-09-11-posix-ssh-runtime.md: d54600faa68524b569f219627537ce250158d9b1 +2026-09-11-posix-ssh-runtime.zh.md: a6b3a84c37b0d7b4438e8c766ef4e010443fe744 diff --git a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md index 9f5de9d2ef..d54600faa6 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md +++ b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md @@ -54,4 +54,4 @@ Security evidence requires both a same-user connector and a replaced socket list ## Deferred work -Persistent remote reconnection needs a separate operation-identity and recovery design; it cannot reuse live callback handles after disconnect. Broader Web support needs provider-owned workspace resources. Stronger resource accounting or revised PTC yield/wait and timeout policy belongs to the [Node runtime reference](../../../../packages/code-runtime/code-runtime-node/README.md), not the SSH administrative request deadline. +Persistent remote reconnection needs a separate operation-identity and recovery design; it cannot reuse live callback handles after disconnect. Broader Web support needs provider-owned workspace resources. Stronger resource accounting or revised PTC yield/wait and timeout policy belongs to the [Node runtime reference](../../../../packages/ptc-runtime/ptc-runtime-node/README.md), not the SSH administrative request deadline. diff --git a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md index 76184c0d88..a6b3a84c37 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md @@ -54,4 +54,4 @@ SSH 提供经过认证的字节通道及逐通道流量控制,但普通 exec ## 延后工作 -持久远端重连需要独立的操作身份与恢复设计,不能在断连后复用活跃回调句柄。更广泛的 Web 支持需要由提供方负责的工作区资源。更强的资源计量或修订后的 PTC yield/wait 与超时策略属于 [Node 运行时参考](../../../../packages/code-runtime/code-runtime-node/README.zh.md),不属于 SSH 管理请求截止时限。 +持久远端重连需要独立的操作身份与恢复设计,不能在断连后复用活跃回调句柄。更广泛的 Web 支持需要由提供方负责的工作区资源。更强的资源计量或修订后的 PTC yield/wait 与超时策略属于 [Node 运行时参考](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md),不属于 SSH 管理请求截止时限。 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml similarity index 56% rename from .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.i18n.yaml rename to .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml index 63da95ac4e..bfcb5aef48 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md -2026-09-11-sandboxed-node-code-runtime.md: 6f28b3c4656797388366e63dd334597d23a23b84 -2026-09-11-sandboxed-node-code-runtime.zh.md: 2c3d19fbdf261d984fd30baf2c347b4e6c15f64b +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md +2026-09-11-sandboxed-node-ptc-runtime.md: 02d76bd607ab8352e208d78f3cf0442fc0794917 +2026-09-11-sandboxed-node-ptc-runtime.zh.md: 40390243b6a15404a2bd9fd2f9d5f9700ad883e6 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md similarity index 79% rename from .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md rename to .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md index 6f28b3c465..02d76bd607 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md @@ -2,7 +2,7 @@ Status: implemented -English | [中文](2026-09-11-sandboxed-node-code-runtime.zh.md) +English | [中文](2026-09-11-sandboxed-node-ptc-runtime.zh.md) ## Problem @@ -12,13 +12,13 @@ The [PTC foundation](../feature/2026-06-15-ptc.md) remains responsible for regis ## Decision -`dsh-code-runtime-node` runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains inside this provider. +`dsh-ptc-runtime-node` runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains inside this provider. ### Resolved inputs and policy -`CodeRuntime.resolve(request)` validates supported options and supplies a complete `CodeRunSpec`; `run(spec)` does not introduce defaults. PTC passes the calling Session's cwd and resolved standing policy. Direct runtime callers receive deployment defaults through the same resolver. The filesystem and subprocess providers share one execution world, and bootstrap paths cross through the filesystem's explicit host-file mapping or a configured preinstalled bootstrap. +`PtcRuntime.resolve(request)` validates supported options and supplies a complete `PtcRunSpec`; `run(spec)` does not introduce defaults. PTC passes the calling Session's cwd and resolved standing policy. Direct runtime callers receive deployment defaults through the same resolver. The filesystem and subprocess providers share one execution world, and bootstrap paths cross through the filesystem's explicit host-file mapping or a configured preinstalled bootstrap. -File mode, observed denial and enforcement completeness travel in `CodeRunResult.sandbox` separately from the program outcome. Restricted execution fails if the required sandbox backend cannot launch. Full access is an explicit policy mode. Program success does not prove full enforcement, and neither the `process` descriptor nor the extra control pipe claims multi-tenant isolation. +File mode, observed denial and enforcement completeness travel in `PtcRunResult.sandbox` separately from the program outcome. Restricted execution fails if the required sandbox backend cannot launch. Full access is an explicit policy mode. Program success does not prove full enforcement, and neither the `process` descriptor nor the extra control pipe claims multi-tenant isolation. The private Python provider keeps its existing execution implementation and configured wall deadline. Its resolver accepts cwd but rejects an explicit file policy or per-call timeout override; a capability descriptor never silently grants unsupported protection. diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.zh.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md similarity index 78% rename from .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.zh.md rename to .agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md index 2c3d19fbdf..40390243b6 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md @@ -2,7 +2,7 @@ Status: implemented -[English](2026-09-11-sandboxed-node-code-runtime.md) | 中文 +[English](2026-09-11-sandboxed-node-ptc-runtime.md) | 中文 ## 问题 @@ -12,13 +12,13 @@ Node worker 隔离 JavaScript 状态,但不应用调用 Session 的 OS 沙箱 ## 决策 -`dsh-code-runtime-node` 在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。本提供方不保留 worker 或持久内核。 +`dsh-ptc-runtime-node` 在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。本提供方不保留 worker 或持久内核。 ### 已解析输入与策略 -`CodeRuntime.resolve(request)` 验证支持的选项并补全 `CodeRunSpec`;`run(spec)` 不引入默认值。PTC 传入调用 Session 的 cwd 与已解析常设策略。直接运行时调用方通过同一解析器取得部署默认值。文件系统与子进程提供方共享一个执行世界,bootstrap 路径通过文件系统的显式宿主文件映射或配置的预安装 bootstrap 传递。 +`PtcRuntime.resolve(request)` 验证支持的选项并补全 `PtcRunSpec`;`run(spec)` 不引入默认值。PTC 传入调用 Session 的 cwd 与已解析常设策略。直接运行时调用方通过同一解析器取得部署默认值。文件系统与子进程提供方共享一个执行世界,bootstrap 路径通过文件系统的显式宿主文件映射或配置的预安装 bootstrap 传递。 -文件模式、观察到的拒绝与强制完整性通过 `CodeRunResult.sandbox` 独立于程序结果传递。所需沙箱后端无法启动时,受限执行失败。完整访问是显式策略模式。程序成功不证明完整强制能力,`process` 描述符与额外控制管道也不声明多租户隔离。 +文件模式、观察到的拒绝与强制完整性通过 `PtcRunResult.sandbox` 独立于程序结果传递。所需沙箱后端无法启动时,受限执行失败。完整访问是显式策略模式。程序成功不证明完整强制能力,`process` 描述符与额外控制管道也不声明多租户隔离。 私有 Python 提供方保留现有执行实现与配置的经过时间截止。其解析器接受 cwd,但拒绝显式文件策略或单次 timeout 覆盖;能力描述符不会静默授予不受支持的保护。 diff --git a/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.i18n.yaml new file mode 100644 index 0000000000..e3c7879089 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.md +2026-09-12-ptc-runtime-vocabulary.md: baea77053b9de684f17b77392ba857e032ef899f +2026-09-12-ptc-runtime-vocabulary.zh.md: 5b76318af011b32f47592a69d00dd2e0eda0a1be diff --git a/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.md b/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.md new file mode 100644 index 0000000000..baea77053b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.md @@ -0,0 +1,27 @@ +# Agent Note: PTC runtime vocabulary + +Status: implemented + +English | [中文](2026-09-12-ptc-runtime-vocabulary.zh.md) + +## Problem + +PTC mode and its execution providers need one searchable name across package manifests, service lookup, public types, configuration, and documentation. Mixed runtime prefixes make it difficult to trace a provider from a profile to its implementation and packaged bootstrap. + +## Decision + +The execution capability uses the `ptc-runtime` package family, `PtcRuntime` types, and `ctx.ptcRuntime`. The Node and private experimental Python providers share this vocabulary. Profile entry identifiers, internal bootstrap selectors, compiler references, package exports, and generated catalogs use the same names; no compatibility package or second service registration is supplied. + +The model-facing `run_code` operation, its `code` source argument, and its stable failure identity keep their descriptive names. General source-code terminology, error codes, external project names and URLs, historical migration identifiers, and sealed Agent Notes retain their meanings and recorded spelling. The naming decision does not change program execution, sandbox authority, deadlines, bindings, or Session formats. + +## Alternatives considered + +**Keep a separate generic runtime prefix.** The providers remain independent of tool and Session ownership, but their package and service names identify the PTC execution capability. A separate prefix adds a second name without separating an independently evolving feature. + +**Replace every occurrence of “code.”** Program source, operation names, external references, and historical records describe different subjects. Replacing them would change public operations or recorded facts beyond the runtime naming decision. + +**Publish old-name aliases.** The APIs are pre-stable and every repository consumer moves together. Aliases would preserve duplicate package and service identities and make subsequent discovery ambiguous. + +## Consequences + +Deployments and source consumers use the PTC package names and configuration identifiers together. Existing `run_code` transcripts and error routing remain readable. Mechanical audits compare renamed source tokens, preserve external URLs and frozen records, and inspect every residual old runtime name; built profile, package, and snapshot checks exercise the consumers that static imports cannot cover. diff --git a/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.zh.md new file mode 100644 index 0000000000..5b76318af0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-12-ptc-runtime-vocabulary.zh.md @@ -0,0 +1,27 @@ +# Agent Note: PTC 运行时词汇 + +Status: implemented + +[English](2026-09-12-ptc-runtime-vocabulary.md) | 中文 + +## Problem + +PTC 模式及其执行提供方需要在包清单、服务查找、公共类型、配置和文档中使用同一个可搜索的名称。混合的运行时前缀使维护者难以从 profile 追踪到提供方实现及打包后的引导程序。 + +## Decision + +执行能力使用 `ptc-runtime` 包族、`PtcRuntime` 类型和 `ctx.ptcRuntime`。Node 与私有实验性 Python 提供方共享这套词汇。Profile 条目标识符、内部引导选择器、编译器引用、包导出和生成目录使用相同名称;不提供兼容包或第二份服务注册。 + +面向模型的 `run_code` 操作、其 `code` 源码参数和稳定失败标识保留描述性名称。一般源码术语、错误码、外部项目名称与 URL、历史迁移标识符以及封存 Agent Note 保留原有含义和记录拼写。这一命名决定不改变程序执行、沙箱权限、期限、绑定或 Session 格式。 + +## Alternatives considered + +**保留单独的通用运行时前缀。** 提供方仍独立于工具和 Session 的所有权,但其包名与服务名标识 PTC 执行能力。单独的前缀会增加第二个名称,却没有分离出独立演进的功能。 + +**替换每一处“code”。** 程序源码、操作名称、外部引用和历史记录描述不同对象。替换这些内容会改变运行时命名决定之外的公共操作或已记录事实。 + +**发布旧名称别名。** API 尚未稳定,仓库中的每个消费方共同迁移。别名会保留重复的包和服务身份,使后续查找含糊不清。 + +## Consequences + +部署配置和源码消费方共同使用 PTC 包名与配置标识符。已有的 `run_code` 记录与错误路由仍可读取。机械审计比较重命名前后的源码 token,保留外部 URL 和冻结记录,并检查每一处残留旧运行时名称;构建后的 profile、包和 snapshot 检查覆盖静态导入无法验证的消费方。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.i18n.yaml index caf0d668d6..d62438d1f3 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.md -2026-09-05-nested-terminal-cards.md: 03b80382a00c2302d25d2b572c3b06aedff0e1b3 -2026-09-05-nested-terminal-cards.zh.md: bf97fffa2a8d92562e982d498d17b830e1e25f48 +2026-09-05-nested-terminal-cards.md: c5946a332f2879588cb6ee334404fdaa92a8cb28 +2026-09-05-nested-terminal-cards.zh.md: 74056014ce5b9ac38574c5551420a4e25808b9b4 diff --git a/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.md b/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.md index 03b80382a0..c5946a332f 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.md +++ b/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.md @@ -10,7 +10,7 @@ A shell command dispatched through `run_code` carries the arguments and rendered ## Decision -`terminalCardModel` applies the same eligibility checks to root and Code Dispatch calls, without rejecting `parentCallId`. Supported running and settled `bash`, `pwsh`, and `terminal_send` calls use the existing terminal card. Background calls, tool errors, malformed inputs, missing call heads, and unsupported result content retain generic fallback. Persistent shells remain eligible while running and generic when settled; a nonzero process exit remains terminal result data rather than a tool error. +`terminalCardModel` applies the same eligibility checks to root and PTC dispatch calls, without rejecting `parentCallId`. Supported running and settled `bash`, `pwsh`, and `terminal_send` calls use the existing terminal card. Background calls, tool errors, malformed inputs, missing call heads, and unsupported result content retain generic fallback. Persistent shells remain eligible while running and generic when settled; a nonzero process exit remains terminal result data rather than a tool error. This partially supersedes only the terminal child-card prohibition in [Client-derived tool presentation](../architecture/2026-08-23-client-derived-tool-presentation.md). That note remains active for Client presentation ownership and the diff/read/search/web child restrictions. No Host presenter, event, schema, metadata, call-tree, or model-context change is required. The metadata and execution-local value decisions in [canonical tool output](../architecture/2026-07-20-canonical-tool-output-contract.md) and [PTC typed returns](../feature/2026-07-20-ptc-typed-tool-returns.md) remain intact; metadata omission does not prohibit Client-derived terminal cards. @@ -32,4 +32,4 @@ Rows and Details share terminal derivation for nested calls without a second ren ## Verification -The [terminal card specs](../../../../packages/client/ui-tool/tests/terminal-card.client.spec.tsx) cover root/child eligibility, running and settled Details, and fallback cases. The [assembled Code Dispatch specs](../../../../packages/client/ui-tool/tests/chat-code-subcalls.client.spec.tsx) cover nested terminal rendering through the conversation tree. The [notice specs](../../../../packages/spill/spill-policy/tests/notice.spec.ts) pin the historical spelling with a literal fixture independent of the formatter. The [spill-policy-to-UI specs](../../../../packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts) exercise actual root and PTC spill production, unchanged full text and programmatic values, byte caps, notice-only output, and terminal fallback. Browser replay owns the visible nested-card change; nonterminal child behavior remains outside this fix. +The [terminal card specs](../../../../packages/client/ui-tool/tests/terminal-card.client.spec.tsx) cover root/child eligibility, running and settled Details, and fallback cases. The [assembled PTC dispatch specs](../../../../packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx) cover nested terminal rendering through the conversation tree. The [notice specs](../../../../packages/spill/spill-policy/tests/notice.spec.ts) pin the historical spelling with a literal fixture independent of the formatter. The [spill-policy-to-UI specs](../../../../packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts) exercise actual root and PTC spill production, unchanged full text and programmatic values, byte caps, notice-only output, and terminal fallback. Browser replay owns the visible nested-card change; nonterminal child behavior remains outside this fix. diff --git a/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.zh.md b/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.zh.md index bf97fffa2a..74056014ce 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-09-05-nested-terminal-cards.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`terminalCardModel` 对根调用与 Code Dispatch 调用应用相同的适用检查,不因 `parentCallId` 拒绝调用。受支持的运行中与已完成的 `bash`、`pwsh` 和 `terminal_send` 调用使用现有 terminal 卡片。后台调用、工具错误、格式错误的输入、缺失的调用头和不受支持的结果内容保留通用回退。持久 shell 在运行中仍可使用 terminal,完成后使用通用展示;非零进程退出仍是 terminal 结果数据,而非工具错误。 +`terminalCardModel` 对根调用与 PTC dispatch 调用应用相同的适用检查,不因 `parentCallId` 拒绝调用。受支持的运行中与已完成的 `bash`、`pwsh` 和 `terminal_send` 调用使用现有 terminal 卡片。后台调用、工具错误、格式错误的输入、缺失的调用头和不受支持的结果内容保留通用回退。持久 shell 在运行中仍可使用 terminal,完成后使用通用展示;非零进程退出仍是 terminal 结果数据,而非工具错误。 本文仅部分取代 [Client 派生工具展示](../architecture/2026-08-23-client-derived-tool-presentation.zh.md)中的 terminal 子调用卡片禁令。该文继续负责 Client 展示所有权及 diff/read/search/web 子调用限制。无需更改 Host 展示转换器、事件、schema、元数据、调用树或模型上下文。[规范工具输出](../architecture/2026-07-20-canonical-tool-output-contract.zh.md)与 [PTC 类型化返回值](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)中的元数据和执行期值决策保持不变;省略元数据不禁止 Client 派生 terminal 卡片。 @@ -32,4 +32,4 @@ Status: implemented ## 验证 -[Terminal 卡片测试](../../../../packages/client/ui-tool/tests/terminal-card.client.spec.tsx)覆盖根/子调用适用性、运行中与已完成的 Details 以及回退情况。[组装后的 Code Dispatch 测试](../../../../packages/client/ui-tool/tests/chat-code-subcalls.client.spec.tsx)覆盖经对话树渲染的嵌套 terminal。[通知测试](../../../../packages/spill/spill-policy/tests/notice.spec.ts)使用独立于格式化函数的字面量 fixture(测试前置数据)固定历史拼写。[spill-policy 到 UI 的测试](../../../../packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts)覆盖真实的根调用与 PTC spill 生成、保持不变的完整文本和程序化值、字节上限、仅含通知的输出以及 terminal 回退。浏览器回放负责验证可见的嵌套卡片变化;非 terminal 子调用行为不属于本修复。 +[Terminal 卡片测试](../../../../packages/client/ui-tool/tests/terminal-card.client.spec.tsx)覆盖根/子调用适用性、运行中与已完成的 Details 以及回退情况。[组装后的 PTC dispatch 测试](../../../../packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx)覆盖经对话树渲染的嵌套 terminal。[通知测试](../../../../packages/spill/spill-policy/tests/notice.spec.ts)使用独立于格式化函数的字面量 fixture(测试前置数据)固定历史拼写。[spill-policy 到 UI 的测试](../../../../packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts)覆盖真实的根调用与 PTC spill 生成、保持不变的完整文本和程序化值、字节上限、仅含通知的输出以及 terminal 回退。浏览器回放负责验证可见的嵌套卡片变化;非 terminal 子调用行为不属于本修复。 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml index 098256e7ce..0e6c3a467b 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-06-15-ptc.md -2026-06-15-ptc.md: 44736d2c48ffc60548a678ed751051d56de25fb1 -2026-06-15-ptc.zh.md: d436c33e402280ca2da3776110ab4751e4e18ff1 +2026-06-15-ptc.md: d5ed3fc79d4586d3754b7273e08970fb066fe6e9 +2026-06-15-ptc.zh.md: 1434db5c352cdb14b857dc5d4ca3bb2f5332e98e diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.md b/.agents/notes/implemented/feature/2026-06-15-ptc.md index 44736d2c48..d5ed3fc79d 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.md @@ -19,16 +19,16 @@ Tool presentation belongs to the registry that owns tool visibility: implementin Three decisions, each elaborated in its own section below: 1. **PTC mode is a first-class presentation mode of `ToolRuntime`** (`dsh-tools`), selected by a validated `mode` config: `'native'` (the default, contributing the visible capability schemas), `'ptc'` (the registry contributes only its reserved `run_code` transport plus a generated SDK `.d.ts` in the system prompt), or `'both'` (native schemas and the transport + SDK). The registry constructs its canonical contribution at the source; the cooperative prompt-assembly result remains authoritative, and the logged request header records exactly that returned presentation. -2. **Code execution is a capability seam** — `packages/code-runtime/` contains the Service Definition package `@deepseek-ai/dsh-code-runtime`, which owns `ctx.codeRuntime` ([capability seams](../architecture/2026-06-13-capability-seams.md); Consumer = `dsh-tools`, with core-consumes-a-seam precedent in `agent-loop` → `dsh-llm`). The runtime knows nothing about tools: it is handed a program and named async bindings, runs the program, and reports `{ value, logs, error? }`. Language and substrate are backend properties, so a future Python or container backend is another Service Provider package, not a redesign. -3. **The shipped implementation is `@deepseek-ai/dsh-code-runtime-node`**: each program runs in a fresh managed Node process under the calling Session's resolved sandbox policy. Direct Node APIs remain available within that policy; named host bindings cross a separately validated control channel. +2. **Code execution is a capability seam** — `packages/ptc-runtime/` contains the Service Definition package `@deepseek-ai/dsh-ptc-runtime`, which owns `ctx.ptcRuntime` ([capability seams](../architecture/2026-06-13-capability-seams.md); Consumer = `dsh-tools`, with core-consumes-a-seam precedent in `agent-loop` → `dsh-llm`). The runtime knows nothing about tools: it is handed a program and named async bindings, runs the program, and reports `{ value, logs, error? }`. Language and substrate are backend properties, so a future Python or container backend is another Service Provider package, not a redesign. +3. **The shipped implementation is `@deepseek-ai/dsh-ptc-runtime-node`**: each program runs in a fresh managed Node process under the calling Session's resolved sandbox policy. Direct Node APIs remain available within that policy; named host bindings cross a separately validated control channel. -This note owns PTC presentation, composition and settlement. The [typed tool-return decision](2026-07-20-ptc-typed-tool-returns.md) owns generated outputs, canonical binding values, `ToolCallError` and lossless outer output. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-code-runtime.md) supersedes the worker execution, trust posture and budget realization while preserving this note's consumer rules. +This note owns PTC presentation, composition and settlement. The [typed tool-return decision](2026-07-20-ptc-typed-tool-returns.md) owns generated outputs, canonical binding values, `ToolCallError` and lossless outer output. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md) supersedes the worker execution, trust posture and budget realization while preserving this note's consumer rules. ### Per-program execution controls The consumer advertises `timeoutMs` from the runtime's readonly `timeout` descriptor and passes explicit values through its resolver. Unsupported providers expose no timeout field and reject an explicit request. Sandbox escalation uses the shared strict-widening approval helper before runtime resolution and launch; replacing only the resolved policy's mode keeps the grant local to one program. Nested dispatches retain the original Agent and Session, so their approvals and file policy remain independent. No failed program is replayed implicitly because earlier effects may already have committed. -The [Node execution decision](../architecture/2026-09-11-sandboxed-node-code-runtime.md#deferred-timeout-design) owns elapsed-budget accounting and deferred lifetime questions. +The [Node execution decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md#deferred-timeout-design) owns elapsed-budget accounting and deferred lifetime questions. ### The registry owns the mode @@ -38,7 +38,7 @@ The [Node execution decision](../architecture/2026-09-11-sandboxed-node-code-run **Interaction with `toolOrder`:** a configured `systemPrompt.toolOrder` naming native capabilities rejects every assembly under `mode: 'ptc'`, because those names are outside that mode's wire-validation universe. This is correct behavior, not a bug: a deployment using PTC mode updates its order config or drops it. -**SDK prompt section.** In `'ptc'` and `'both'`, the lazy `tools:sdk` section in the tool-guidance order band renders the loaded runtime's language declarations plus fixed usage instructions for the scope's visible capabilities (TypeScript by default; the [language-dispatch note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) added Python and the `ctx.codeRuntime.language` renderer table). It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output. +**SDK prompt section.** In `'ptc'` and `'both'`, the lazy `tools:sdk` section in the tool-guidance order band renders the loaded runtime's language declarations plus fixed usage instructions for the scope's visible capabilities (TypeScript by default; the [language-dispatch note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) added Python and the `ctx.ptcRuntime.language` renderer table). It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output. **Assembly ownership.** `run_code` and `tools:sdk` enter the trusted `system-prompt/assemble` waterfall as normal assembly inputs. A scoped `tools:sdk` section may shadow the global default before dispatch, and a listener may remove or replace either contribution. The waterfall's returned assembly is final, so whoever changes these inputs owns preserving a viable PTC mode protocol when the deployment expects PTC mode to remain usable; no restoration pass overrides deliberate composition. @@ -49,7 +49,7 @@ The [Node execution decision](../architecture/2026-09-11-sandboxed-node-code-run Under `'ptc'` and `'both'` the registry owns `run_code` as a reserved presentation transport with two required parameters, `{ code: string; description: string }` (the description labels the call in UIs, the bash precedent). It is represented by a normal `ToolDefinition` for dispatch but stays outside the filterable capability layers, so restrictions cannot accidentally remove PTC mode's only entry point. Calls traverse the complete tool pipeline — `tools/pre-execute` → monotonic guards → `tools/execute` around dispatch → `tools/post-execute` → optional definition-owned `finalizeContent` → immutable `tools/result` notification — exactly like native calls; a permission plugin can inspect the program text before it runs, and final-result observers see the normalized outer outcome. Its `execute(args, exec)`: 1. **Build bindings.** One run-scoped signal follows outer cancellation and is aborted whenever the run settles. Each visible tool binding snapshots lossless-JSON arguments, enters the native-contract dispatch pool (the [live-parallel note](2026-07-26-ptc-live-parallel-dispatch.md) owns the scheduling design), executes with a deterministic call id and the outer token as `parent`, defers returned contexts through the outer execution, and logs the `tool/ptc-dispatch-start`/`tool/ptc-dispatch` pair, the settle side carrying the full rendered result content. Success returns the tool's final canonical JSON value; failure becomes the program-visible `ToolCallError`. Every sub-call retains its own immutable execution identity and traverses the full tool pipeline. -2. **Runs resolved inputs:** `ctx.codeRuntime.run(ctx.codeRuntime.resolve(request))`. The request carries the program, bindings, run-scoped signal, calling Session cwd and applicable resolved file policy. The run-scoped signal connects outer settlement to execution cancellation. +2. **Runs resolved inputs:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`. The request carries the program, bindings, run-scoped signal, calling Session cwd and applicable resolved file policy. The run-scoped signal connects outer settlement to execution cancellation. 3. **Settle after quiescence.** When the runtime settles, the bridge aborts outstanding work and drains the dispatch queue before returning. Success returns captured logs and the completion value as canonical output; the registry renders that value into durable `tool/result.content`, which the result card reads directly. A runtime failure becomes `CodeRunFailedError`; backend rejection uses the registry's normal error boundary. Both produce structured error results, and no sub-call can append after `run_code` settles. **Sub-call contexts are deferred through the parent.** Injecting inside `run_code` would break parent call/result adjacency, so `ToolRunContext.deferContext()` collects every sub-result `additionalContexts` entry in dispatch order. The registry carries that array even when the program later throws, and the loop appends each entry only after the outer result and every sibling result in the step. An outer post-execute block discards tool-deferred entries and exposes only contexts explicitly attached by the blocking decision. @@ -66,9 +66,9 @@ New sub-calls use `:ptc:` ids, numbered in submission order. All call The [V2-to-V3 PTC specification](../../../../packages/session/session-format-v2-to-v3/README.md#ptc-vocabulary) owns exact historical tag and attribution conversion; [native V3 admission](../../../../packages/session/session-format-v2-to-v3/README.md#native-v3-admission) owns predecessor-tag refusal. These are not runtime aliases: an opaque extension must not acquire PTC lifecycle meaning merely through a version change. -### The code-runtime seam +### The ptc-runtime seam -`dsh-code-runtime` owns `CodeRuntime` and the [request, resolved-spec, binding and result types](../../../../docs/subsystems/code-runtime.md). `resolve(request)` validates supported cwd, timeout and policy choices and supplies deployment defaults; `run(spec)` executes complete inputs. Named async bindings and optional rejection constructors keep registry-specific tool names outside the runtime. +`dsh-ptc-runtime` owns `PtcRuntime` and the [request, resolved-spec, binding and result types](../../../../docs/subsystems/ptc-runtime.md). `resolve(request)` validates supported cwd, timeout and policy choices and supplies deployment defaults; `run(spec)` executes complete inputs. Named async bindings and optional rejection constructors keep registry-specific tool names outside the runtime. `language` selects the SDK renderer and `run_code` flavor; an unsupported language fails assembly. `isolation` identifies the substrate, not its authority. `sandboxMode` indicates whether the consumer can pass a resolved Session file policy. Missing runtimes fail PTC assembly, while native presentation does not require one. @@ -127,7 +127,7 @@ Deployments switching to `'ptc'` must update any native-only `toolOrder`. Assemb **Prompt cost of the SDK, especially under `'both'`.** The `.d.ts` can rival the native schemas it complements; `'both'` carries two representations. Prefix stability + provider caching amortize per-session cost; the mode is per-deployment; the Agent Note makes no unconditional-savings claim. Measured guidance (when to prefer which mode) is explicitly post-ship learning. -**Registry scope growth.** `dsh-tools` absorbs codegen, a tool, a bridge, and an event. Package modules separate these responsibilities (`ts-types.ts` and `ptc.ts` beside `schema.ts`, `json-schema.ts`, and `presentation.ts`), while `ctx.codeRuntime` owns all code-runtime-specific implementation. +**Registry scope growth.** `dsh-tools` absorbs codegen, a tool, a bridge, and an event. Package modules separate these responsibilities (`ts-types.ts` and `ptc.ts` beside `schema.ts`, `json-schema.ts`, and `presentation.ts`), while `ctx.ptcRuntime` owns all ptc-runtime-specific implementation. **Large binding values can still exhaust memory.** The Node provider bounds control frames, outstanding arguments and queued writes, while a host binding can allocate its result before those checks. Lossless JSON transfer and the outer output ledger do not create a process-wide allocation quota. diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md index d436c33e40..1434db5c35 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md @@ -19,16 +19,16 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 三项决策,各自在下方独立小节中展开: 1. **PTC mode 是 `ToolRuntime`(`dsh-tools`)的一等呈现模式**,通过经校验的 `mode` 配置选择:`'native'`(默认,贡献可见能力 schema)、`'ptc'`(注册表仅贡献其保留的 `run_code` 传输通道加一份生成的 SDK `.d.ts` 到系统提示词中)或 `'both'`(原生 schema 加传输通道 + SDK)。注册表在源头构建其规范贡献;协作式提示词组装的结果仍具权威性,记录在日志中的请求头精确反映该返回的呈现。 -2. **代码执行是一个能力 seam**——`packages/code-runtime/` 包含 Service Definition 包 `@deepseek-ai/dsh-code-runtime`,拥有 `ctx.codeRuntime`([能力 seam](../architecture/2026-06-13-capability-seams.zh.md);消费方 = `dsh-tools`,core 消费 seam 的先例见 `agent-loop` → `dsh-llm`)。运行时对工具一无所知:它接收一段程序和命名的异步绑定,执行程序,报告 `{ value, logs, error? }`。语言和基底是后端属性,因此未来的 Python 或容器后端只是另一个 Service Provider 包,而非重新设计。 -3. **交付的实现是 `@deepseek-ai/dsh-code-runtime-node`**:每个程序在全新的受管 Node 进程中,按调用 Session 的已解析沙箱策略运行。直接 Node API 在该策略内仍可使用;具名 Host 绑定通过单独验证的控制通道调用。 +2. **代码执行是一个能力 seam**——`packages/ptc-runtime/` 包含 Service Definition 包 `@deepseek-ai/dsh-ptc-runtime`,拥有 `ctx.ptcRuntime`([能力 seam](../architecture/2026-06-13-capability-seams.zh.md);消费方 = `dsh-tools`,core 消费 seam 的先例见 `agent-loop` → `dsh-llm`)。运行时对工具一无所知:它接收一段程序和命名的异步绑定,执行程序,报告 `{ value, logs, error? }`。语言和基底是后端属性,因此未来的 Python 或容器后端只是另一个 Service Provider 包,而非重新设计。 +3. **交付的实现是 `@deepseek-ai/dsh-ptc-runtime-node`**:每个程序在全新的受管 Node 进程中,按调用 Session 的已解析沙箱策略运行。直接 Node API 在该策略内仍可使用;具名 Host 绑定通过单独验证的控制通道调用。 -本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、规范绑定值、`ToolCallError` 与无损外层输出。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-code-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。 +本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、规范绑定值、`ToolCallError` 与无损外层输出。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。 ### 每段程序的执行控制 消费方根据运行时只读 `timeout` 描述符通告 `timeoutMs`,并把显式值交给其解析器。不支持的提供方不公开超时字段,并拒绝显式请求。沙箱提升在运行时解析和启动前使用共享的严格扩大权限审批辅助函数;仅替换已解析策略的模式,使授权只作用于一段程序。嵌套分发保留原始 Agent 和 Session,因此其审批与文件策略保持独立。失败程序不会隐式重放,因为先前效果可能已提交。 -[Node 执行决策](../architecture/2026-09-11-sandboxed-node-code-runtime.zh.md#deferred-timeout-design) 负责经过时间预算核算与延期的生命周期问题。 +[Node 执行决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md#deferred-timeout-design) 负责经过时间预算核算与延期的生命周期问题。 ### 注册表拥有模式 @@ -38,7 +38,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 **与 `toolOrder` 的交互:** 如果配置的 `systemPrompt.toolOrder` 引用了原生能力名称,在 `mode: 'ptc'` 下会拒绝所有组装,因为那些名称不在该模式的协议校验范围内。这是正确行为而非 bug:使用 PTC mode 的部署需要更新其 order 配置或移除它。 -**SDK 提示词段。** 在 `'ptc'` 和 `'both'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染所加载运行时语言的声明加固定的使用说明(默认 TypeScript;[语言分发 note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) 加入了 Python 与按 `ctx.codeRuntime.language` 选择的渲染器表)。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。 +**SDK 提示词段。** 在 `'ptc'` 和 `'both'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染所加载运行时语言的声明加固定的使用说明(默认 TypeScript;[语言分发 note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) 加入了 Python 与按 `ctx.ptcRuntime.language` 选择的渲染器表)。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。 **组装所有权。** `run_code` 和 `tools:sdk` 作为正常的组装输入进入受信任的 `system-prompt/assemble` waterfall。一个 scoped 的 `tools:sdk` 段可以在分发前遮蔽全局默认值,监听器也可以移除或替换任一贡献。waterfall 返回的组装结果是最终的,因此修改这些输入的人有责任在部署期望 PTC mode 可用时保持协议面的完整性;没有恢复 pass 会覆盖有意的组合。 @@ -49,7 +49,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 在 `'ptc'` 和 `'both'` 下,注册表拥有 `run_code` 作为保留的呈现传输通道,带两个必需参数 `{ code: string; description: string }`(description 为 UI 标注该调用,沿用 bash 的先例)。它由一个正常的 `ToolDefinition` 表示以供分发,但位于可过滤的能力层之外,因此限制规则不会意外移除 PTC mode 的唯一入口。调用遍历完整的工具流水线——`tools/pre-execute` → 单调性守卫 → `tools/execute` 包裹分发 → `tools/post-execute` → 由定义拥有的可选 `finalizeContent` → 不可变的 `tools/result` 通知——与原生调用完全一致;权限插件可以在程序运行前检查程序文本,最终结果观察者看到的是规范化的外层结果。其 `execute(args, exec)`: 1. **构建绑定。** 一个 run 级别的 signal 跟随外层取消,并在 run 结算时被 abort。每个可见工具绑定都会对无损 JSON 参数创建快照,进入原生约定的分发池(调度设计由[实时并行 Agent Note](2026-07-26-ptc-live-parallel-dispatch.zh.md) 负责),以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/ptc-dispatch-start`/`tool/ptc-dispatch` 事件对,其中结算侧携带完整渲染后的结果内容。成功时返回工具最终的规范 JSON 值;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。 -2. **运行已解析输入:** `ctx.codeRuntime.run(ctx.codeRuntime.resolve(request))`。请求携带程序、绑定、运行级信号、调用 Session 的 cwd 与适用的已解析文件策略。运行级信号将外层结算与执行取消关联。 +2. **运行已解析输入:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`。请求携带程序、绑定、运行级信号、调用 Session 的 cwd 与适用的已解析文件策略。运行级信号将外层结算与执行取消关联。 3. **完全停稳后结算。** 运行时结算后,桥 abort 未完成的工作并排空分发队列后再返回。成功时返回捕获的日志和完成值,将其作为规范输出;注册表再把该值渲染为持久化的 `tool/result.content`,供结果卡片直接读取。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。 **子调用上下文通过父调用延后。** 在 `run_code` 内部注入会破坏父调用/结果的相邻性,因此 `ToolRunContext.deferContext()` 按分发顺序收集每个子结果的 `additionalContexts` 条目。即使程序后来抛出异常,注册表仍携带该数组;循环只在外层结果与步骤中所有兄弟结果之后追加每个条目。外层 post-execute 阻止会丢弃工具延后的条目,只暴露阻止 decision 显式附加的上下文。 @@ -66,9 +66,9 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 [V2 到 V3 PTC 规范](../../../../packages/session/session-format-v2-to-v3/README.zh.md#ptc-vocabulary)负责精确的历史标签与归属转换;[原生 V3 准入](../../../../packages/session/session-format-v2-to-v3/README.zh.md#native-v3-admission)负责前代标签拒绝。这些不是运行时别名:不透明扩展不能仅因版本变化就获得 PTC 生命周期含义。 -### code-runtime seam +### ptc-runtime seam -`dsh-code-runtime` 负责 `CodeRuntime` 与[请求、已解析 spec、绑定及结果类型](../../../../docs/subsystems/code-runtime.zh.md)。`resolve(request)` 验证支持的 cwd、timeout 与策略选择并补全部署默认值;`run(spec)` 执行完整输入。具名异步绑定和可选拒绝构造器使运行时不必了解注册表特定的工具名称。 +`dsh-ptc-runtime` 负责 `PtcRuntime` 与[请求、已解析 spec、绑定及结果类型](../../../../docs/subsystems/ptc-runtime.zh.md)。`resolve(request)` 验证支持的 cwd、timeout 与策略选择并补全部署默认值;`run(spec)` 执行完整输入。具名异步绑定和可选拒绝构造器使运行时不必了解注册表特定的工具名称。 `language` 选择 SDK 渲染器与 `run_code` flavor;不支持的语言使组装失败。`isolation` 标识执行基底,不标识权限。`sandboxMode` 表示消费方能否传入已解析 Session 文件策略。缺少运行时使 PTC 组装失败,native 呈现则不需要运行时。 @@ -127,7 +127,7 @@ SDK 指示模型编写一个所加载运行时语言的异步函数体(默认 **SDK 的提示词成本,尤其在 `'both'` 下。** `.d.ts` 可能与它补充的原生 schema 体量相当;`'both'` 携带两种表示。前缀稳定性 + 提供方缓存摊销了每会话成本;mode 按部署配置;本 Agent Note 不做无条件节省的声明。何时优先使用哪种模式的量化指导明确属于上线后学习。 -**注册表 scope 增长。** `dsh-tools` 吸收了代码生成、一个工具、一个桥和一个事件。包内模块把这些职责分开(`ts-types.ts`、`ptc.ts` 与 `schema.ts`、`json-schema.ts`、`presentation.ts` 并列),所有 code-runtime 专用实现都由 `ctx.codeRuntime` 提供。 +**注册表 scope 增长。** `dsh-tools` 吸收了代码生成、一个工具、一个桥和一个事件。包内模块把这些职责分开(`ts-types.ts`、`ptc.ts` 与 `schema.ts`、`json-schema.ts`、`presentation.ts` 并列),所有 ptc-runtime 专用实现都由 `ctx.ptcRuntime` 提供。 **大型绑定值仍可能耗尽内存。** Node 提供方限制控制帧、未完成参数和排队写入,而 Host 绑定可以在这些检查前分配其结果。无损 JSON 传输与外层输出账本不构成进程级分配配额。 diff --git a/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.i18n.yaml b/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.i18n.yaml index 705088a400..021837de21 100644 --- a/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md -2026-07-14-cross-family-fs-sandbox.md: 08b95541770b3c150a694a3f0731cdc42fe3c3fd -2026-07-14-cross-family-fs-sandbox.zh.md: 5ee4f4f5d6b9193f83a243b49bc9ae2627d63920 +2026-07-14-cross-family-fs-sandbox.md: 0fe1d4078797eceb9f3f0f9c319bba62acd6b08c +2026-07-14-cross-family-fs-sandbox.zh.md: 021923c7e3c4653991377cd9b5bccf18c9a4bf65 diff --git a/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md b/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md index 08b9554177..0fe1d40787 100644 --- a/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md +++ b/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md @@ -37,7 +37,7 @@ Three coordinated pieces, all composed from the leaf `cordis.yml`, none touching A denial is the structured `FS_SANDBOX_DENIED` carrying the effective mode — distinct from `FS_PERMISSION_DENIED` (a host EACCES is the world refusing; this is policy refusing). No text inference: an in-process fence knows exactly what it denied. The per-call carrier is a trailing optional `SandboxExecutionPolicy` on `writeText`/`editText` (the filesystem twin of `ShellExecRequest.sandboxPolicy`); the seam stays session-free, and the bare local backend ignores it. `FileSystem.sandboxMode` is the capability fact (`undefined` on the base and `fs-local`, the default on `SandboxedFileSystem`), so the tool layer advertises escalation from composition truth. -The threat model is stated in the package README: a policy fence in trusted code over model-controlled paths, not a kernel boundary — the operations are the seam's own, only the target path is untrusted, so canonicalize-then-contain is the complete answer to this surface (the `code-runtime` "containment, not a security boundary" precedent). Kernel-grade isolation of untrusted CODE stays `ctx.shell`'s job. The residual resolve-to-syscall race is narrowed by the in-place re-canonicalization and eliminated only by platform primitives (`openat2` `RESOLVE_BENEATH`) not worth their portability cost here. +The threat model is stated in the package README: a policy fence in trusted code over model-controlled paths, not a kernel boundary — the operations are the seam's own, only the target path is untrusted, so canonicalize-then-contain is the complete answer to this surface (the `ptc-runtime` "containment, not a security boundary" precedent). Kernel-grade isolation of untrusted CODE stays `ctx.shell`'s job. The residual resolve-to-syscall race is narrowed by the in-place re-canonicalization and eliminated only by platform primitives (`openat2` `RESOLVE_BENEATH`) not worth their portability cost here. ### Tool parity — one denial marker, one escalation flow diff --git a/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.zh.md b/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.zh.md index 5ee4f4f5d6..021923c7e3 100644 --- a/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.zh.md +++ b/.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.zh.md @@ -37,7 +37,7 @@ Status: implemented 拒绝是结构化的 `FS_SANDBOX_DENIED`,携带生效模式——区别于 `FS_PERMISSION_DENIED`(宿主 EACCES 是世界在拒绝;这里是策略在拒绝)。无文本推断:进程内围栏确切知道它拒绝了什么。per-call 载体是 `writeText`/`editText` 上一个末尾可选的 `SandboxExecutionPolicy`(文件系统侧对应 `ShellExecRequest.sandboxPolicy`);该 seam 保持无会话依赖,而裸的本地后端会忽略它。`FileSystem.sandboxMode` 是能力事实(在基类与 `fs-local` 上为 `undefined`,在 `SandboxedFileSystem` 上为默认值),所以工具层按组合真相来宣告升级。 -威胁模型写在包 README 里:一道位于可信代码中、针对模型可控路径的策略围栏,而非内核边界——操作是 seam 自身的,只有目标路径不可信,所以「先规范化再判包含」足以完整覆盖这一调用面(`code-runtime` 的「containment, not a security boundary」先例)。对不可信代码的内核级隔离仍是 `ctx.shell` 的职责。resolve 到系统调用之间残留的竞态被就地重新规范化收窄,只有平台原语(`openat2` `RESOLVE_BENEATH`)能彻底消除它,而在此不值得为其付出可移植性代价。 +威胁模型写在包 README 里:一道位于可信代码中、针对模型可控路径的策略围栏,而非内核边界——操作是 seam 自身的,只有目标路径不可信,所以「先规范化再判包含」足以完整覆盖这一调用面(`ptc-runtime` 的「containment, not a security boundary」先例)。对不可信代码的内核级隔离仍是 `ctx.shell` 的职责。resolve 到系统调用之间残留的竞态被就地重新规范化收窄,只有平台原语(`openat2` `RESOLVE_BENEATH`)能彻底消除它,而在此不值得为其付出可移植性代价。 ### 工具对等——一个拒绝标记、一条升级流程 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml index d52ab39af4..b083ea6a1e 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md -2026-07-20-ptc-typed-tool-returns.md: 1fec707bc6c5da3a013f1dc6a311f4e5beda6e60 -2026-07-20-ptc-typed-tool-returns.zh.md: af58812941b4de1570f5762c8fa704f0680dfa5d +2026-07-20-ptc-typed-tool-returns.md: 08e760b95a40386bccc8c7a2722d289da10e3dff +2026-07-20-ptc-typed-tool-returns.zh.md: c2883740e1eeadbf6fb2413496104ff08a9bd1f7 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md index 1fec707bc6..08e760b95a 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md @@ -53,13 +53,13 @@ Before dispatch the bridge snapshots binding arguments as lossless JSON and snap PTC mode declares its rejection capability on the runtime request as `{ name: "ToolCallError", memberNameProperty: "toolName" }`. The runtime Service Definition treats those names as data: the worker materializes and injects the actual constructor used for `tools` binding failures, so `error instanceof ToolCallError` works without making a generic runtime know about tools. The worker constructs failures and defines their public fields through module-captured error and property-definition intrinsics plus null-prototype descriptors, so model mutations cannot replace the promised rejection with a worker failure. The error has the standard `Error` message plus the exact `toolName`; it deliberately omits `ToolFailure.info`, error codes, and Native content. This is an exception contract for control flow, not a failure union for programmatic classification. -Binding arguments and resolutions are revalidated as lossless JSON on both sides of the hostile worker protocol and have no byte cap. Before crossing through structured clone, each detached value is encoded as a flat pre-order token stream whose transport nesting is bounded; the receiver rebuilds it iteratively. Valid application nesting therefore has neither a JavaScript call-stack depth cap nor a platform-specific nested structured-clone limit. At module initialization the worker captures its own realm's `Array.prototype` and `Object.prototype` identities, the native function-source intrinsic used only to recognize foreign-realm plain-container prototypes, and every structural and metering intrinsic used by the JSON boundary. Property writes use null-prototype descriptors, while private array and set operations invoke captured methods without consulting mutable global or prototype slots. Model code can therefore replace helpers such as `Object.keys`, `Array.isArray`, collection methods, string methods, or `Buffer.byteLength`, rewrite intrinsic-prototype constructor slots, or add descriptor-shaped fields to `Object.prototype` without changing validation, wire transport, or byte accounting. The foreign-realm native function-source check still rejects user-authored constructors that imitate `Object` or `Array`. The dependency-light runtime Service Definition names its structural equivalent `CodeJsonValue` so it need not depend on the session-owned canonical type; the generated SDK and tool API use `JsonValue`. Intermediate values are not prompt-truncated, context-spilled, or persisted. This preserves full acquired search, workflow, task, filesystem, and MCP values for programmatic filtering while leaving provider and executor acquisition limits truthful. +Binding arguments and resolutions are revalidated as lossless JSON on both sides of the hostile worker protocol and have no byte cap. Before crossing through structured clone, each detached value is encoded as a flat pre-order token stream whose transport nesting is bounded; the receiver rebuilds it iteratively. Valid application nesting therefore has neither a JavaScript call-stack depth cap nor a platform-specific nested structured-clone limit. At module initialization the worker captures its own realm's `Array.prototype` and `Object.prototype` identities, the native function-source intrinsic used only to recognize foreign-realm plain-container prototypes, and every structural and metering intrinsic used by the JSON boundary. Property writes use null-prototype descriptors, while private array and set operations invoke captured methods without consulting mutable global or prototype slots. Model code can therefore replace helpers such as `Object.keys`, `Array.isArray`, collection methods, string methods, or `Buffer.byteLength`, rewrite intrinsic-prototype constructor slots, or add descriptor-shaped fields to `Object.prototype` without changing validation, wire transport, or byte accounting. The foreign-realm native function-source check still rejects user-authored constructors that imitate `Object` or `Array`. The dependency-light runtime Service Definition names its structural equivalent `PtcJsonValue` so it need not depend on the session-owned canonical type; the generated SDK and tool API use `JsonValue`. Intermediate values are not prompt-truncated, context-spilled, or persisted. This preserves full acquired search, workflow, task, filesystem, and MCP values for programmatic filtering while leaving provider and executor acquisition limits truthful. ### Outer result and output ledger The runtime accepts an exact lossless JSON completion of any root. Returning `undefined` omits the completion; returning `null` is an explicit result. `run_code` exposes the canonical outer value `{ logs: string[], result?: JsonValue }`. Its Native renderer emits logs first, renders a string result raw, and renders every other JSON root with an iterative pretty printer. Total indentation is capped at ten characters and deeper subtrees remain compact, preserving the established shallow text while keeping traversal stack-safe and formatted size linear in the canonical JSON size. -`NodeCodeRuntime` replaces the former independent log and value caps with configurable `maxOutputBytes`, defaulting to `67_108_864` bytes. The worker charges captured logs by their exact JSON-string serialization and preflights the detached completion or program exception against the remaining combined budget before posting a terminal message. A giant thrown string or stack therefore crosses the worker port only as the fixed `output-limit` diagnostic. The host repeats the hostile-peer ledger for forged traffic and native pipe writes the worker cannot observe. Fixed `CodeRunResult` field names, braces, the bounded error-kind tag, and later presentation whitespace are deliberately outside this variable-payload ledger. Neither stage materializes an over-limit serialized completion. A result at or below the cap is exact. A completion that cannot survive lossless JSON snapshotting fails as `invalid-output`; a value, diagnostic, or combined outcome over the cap fails as `output-limit` rather than becoming inspected or truncated text. +`NodePtcRuntime` replaces the former independent log and value caps with configurable `maxOutputBytes`, defaulting to `67_108_864` bytes. The worker charges captured logs by their exact JSON-string serialization and preflights the detached completion or program exception against the remaining combined budget before posting a terminal message. A giant thrown string or stack therefore crosses the worker port only as the fixed `output-limit` diagnostic. The host repeats the hostile-peer ledger for forged traffic and native pipe writes the worker cannot observe. Fixed `PtcRunResult` field names, braces, the bounded error-kind tag, and later presentation whitespace are deliberately outside this variable-payload ledger. Neither stage materializes an over-limit serialized completion. A result at or below the cap is exact. A completion that cannot survive lossless JSON snapshotting fails as `invalid-output`; a value, diagnostic, or combined outcome over the cap fails as `output-limit` rather than becoming inspected or truncated text. Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, the runtime returns an explicit bounded failure with the fitting captured prefix. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap. diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md index af58812941..c2883740e1 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md @@ -53,13 +53,13 @@ declare const tools: { PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNameProperty: "toolName" }` 声明其以异常拒绝 Promise 的能力。运行时 Service Definition 只把这些名称视为数据:worker 会动态生成并注入真正用于 `tools` 绑定失败的构造函数,因此无需让通用运行时了解工具,`error instanceof ToolCallError` 也能成立。worker 使用模块初始化时捕获的 Error 构造函数与属性定义内建方法,配合原型为 null 的属性描述符,构造失败对象并定义其公开字段,因此模型代码的修改不会把约定承诺的 reject 变成 worker 失败。该错误包含标准的 `Error` 消息和确切的 `toolName`,并有意省略 `ToolFailure.info`、错误代码与 Native 内容。这是一项用于控制流的异常约定,而不是供程序分类的失败联合。 -绑定参数与绑定返回值会在不可信 worker 协议的两端重新校验为无损 JSON,且不设字节上限。每个分离后的值在通过结构化克隆跨越边界前,都会编码为扁平的前序 token 流,其传输结构的嵌套深度有界;接收方再以迭代方式重建该值。因此,有效应用数据的嵌套深度既不受 JavaScript 调用栈深度上限限制,也不受特定平台对嵌套结构化克隆施加的上限限制。模块初始化时,worker 会捕获自身 JavaScript 运行域中 `Array.prototype` 和 `Object.prototype` 的引用、仅用于识别其他运行域普通容器原型、可获取原生函数源码的内建函数,以及 JSON 边界用于结构处理和计量的全部内建方法。属性写入使用原型为 null 的属性描述符;内部的数组与集合操作直接调用捕获的方法,不会访问可变的全局或原型槽位。因此,即使模型代码替换 `Object.keys`、`Array.isArray`、集合方法、字符串方法或 `Buffer.byteLength` 等辅助方法,重写内建原型的构造函数槽位,或向 `Object.prototype` 添加形如属性描述符的字段,也不会改变校验、协议传输或字节计量。面向其他运行域的原生函数源码检查仍会拒绝由用户编写、冒充 `Object` 或 `Array` 的构造函数。为保持依赖轻量,运行时 Service Definition 将结构等价类型命名为 `CodeJsonValue`,从而无需依赖会话侧拥有的规范类型;生成的 SDK 和工具 API 则使用 `JsonValue`。这些值不会经过提示词截断、上下文 spill 或持久化。因此,程序可以完整筛选已经采集的搜索、工作流、任务、文件系统与 MCP 值,同时提供方和执行器的采集上限仍会实际生效。 +绑定参数与绑定返回值会在不可信 worker 协议的两端重新校验为无损 JSON,且不设字节上限。每个分离后的值在通过结构化克隆跨越边界前,都会编码为扁平的前序 token 流,其传输结构的嵌套深度有界;接收方再以迭代方式重建该值。因此,有效应用数据的嵌套深度既不受 JavaScript 调用栈深度上限限制,也不受特定平台对嵌套结构化克隆施加的上限限制。模块初始化时,worker 会捕获自身 JavaScript 运行域中 `Array.prototype` 和 `Object.prototype` 的引用、仅用于识别其他运行域普通容器原型、可获取原生函数源码的内建函数,以及 JSON 边界用于结构处理和计量的全部内建方法。属性写入使用原型为 null 的属性描述符;内部的数组与集合操作直接调用捕获的方法,不会访问可变的全局或原型槽位。因此,即使模型代码替换 `Object.keys`、`Array.isArray`、集合方法、字符串方法或 `Buffer.byteLength` 等辅助方法,重写内建原型的构造函数槽位,或向 `Object.prototype` 添加形如属性描述符的字段,也不会改变校验、协议传输或字节计量。面向其他运行域的原生函数源码检查仍会拒绝由用户编写、冒充 `Object` 或 `Array` 的构造函数。为保持依赖轻量,运行时 Service Definition 将结构等价类型命名为 `PtcJsonValue`,从而无需依赖会话侧拥有的规范类型;生成的 SDK 和工具 API 则使用 `JsonValue`。这些值不会经过提示词截断、上下文 spill 或持久化。因此,程序可以完整筛选已经采集的搜索、工作流、任务、文件系统与 MCP 值,同时提供方和执行器的采集上限仍会实际生效。 ### 外层结果与输出账本 运行时接受以任意 JSON 类型为根的精确无损完成值。返回 `undefined` 表示省略完成值;返回 `null` 则是显式结果。`run_code` 暴露规范外层值 `{ logs: string[], result?: JsonValue }`。其 Native 渲染器先输出日志;字符串结果保持原文,其他所有 JSON 根值则使用迭代式美化渲染器。总缩进长度上限为 10 个字符,更深的子树保持紧凑格式,既保留既有的浅层文本,又确保遍历不受调用栈深度限制,且格式化输出大小与规范 JSON 大小呈线性关系。 -`NodeCodeRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `CodeRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。 +`NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。 日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,运行时会返回一个显式的有界失败,并携带可容纳的已捕获前缀。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。 diff --git a/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml b/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml index 0ff12acf48..22bebef751 100644 --- a/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml +++ b/.agents/notes/implemented/process/2026-06-11-quality-gates.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-06-11-quality-gates.md -2026-06-11-quality-gates.md: f3e70f843eca1fb59e10704523d42c200d44de69 -2026-06-11-quality-gates.zh.md: efcf840ad8cb4189c0de268ccf315319c5639453 +2026-06-11-quality-gates.md: b4bcbcbb6e47ccbb3ed193300c4a8b2daa3901c0 +2026-06-11-quality-gates.zh.md: 397ead6a1d6ee73bded312d810133e59f5a8ec29 diff --git a/.agents/notes/implemented/process/2026-06-11-quality-gates.md b/.agents/notes/implemented/process/2026-06-11-quality-gates.md index f3e70f843e..b4bcbcbb6e 100644 --- a/.agents/notes/implemented/process/2026-06-11-quality-gates.md +++ b/.agents/notes/implemented/process/2026-06-11-quality-gates.md @@ -19,7 +19,7 @@ Every mechanically checkable AGENTS.md promise gets a command that exits non-zer - jscpd detects cross-file clones in package production TypeScript and repository scripts; narrow source-range exceptions document deliberately parallel implementations. - Per-file 100% coverage on `packages/*/*/src` (v8); unreachable defensive guards carry `/* v8 ignore */ ` with stated reasons instead of deletion. - publint (package correctness), workspace constraints (workspace rules: private, cordis peer+dev, uniform version, ESM), and a NodeNext consumer typecheck for built package declarations. [The unused-code gate removal](2026-08-19-remove-knip.md) records why static dead-code scanning is outside this suite. -- lefthook pre-commit applies project-free Oxlint validation and [safe fixes with a bounded retry](../../archived/process/2026-08-09-oxlint-only-fix-workflow.md), rejects staged whitespace, and checks the vendor manifest; pre-push runs incremental typecheck. CI runs the full matrix on node 22.19/24/26 plus built application smokes for the Headless, TUI, ACP, JSON-RPC, workflow, and code-runtime entry paths. +- lefthook pre-commit applies project-free Oxlint validation and [safe fixes with a bounded retry](../../archived/process/2026-08-09-oxlint-only-fix-workflow.md), rejects staged whitespace, and checks the vendor manifest; pre-push runs incremental typecheck. CI runs the full matrix on node 22.19/24/26 plus built application smokes for the Headless, TUI, ACP, JSON-RPC, workflow, and ptc-runtime entry paths. ## Consequences diff --git a/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md b/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md index efcf840ad8..397ead6a1d 100644 --- a/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md +++ b/.agents/notes/implemented/process/2026-06-11-quality-gates.zh.md @@ -19,7 +19,7 @@ Status: implemented - jscpd 检测包的生产 TypeScript 代码与仓库脚本中的跨文件克隆;窄范围的源码区间例外用于记录有意为之的并行实现。 - `packages/*/*/src` 下按文件 100% 覆盖率(v8);不可达的防御性守卫使用 `/* v8 ignore */ ` 并注明理由,而非删除。 - publint(包的正确性)、workspace 约束(workspace 规则:private、cordis peer+dev、统一版本、ESM),以及对构建出的包声明文件进行 NodeNext 消费方类型检查。[移除未使用代码门禁的决策](2026-08-19-remove-knip.zh.md)说明了静态死代码扫描为何不属于这套门禁。 -- lefthook pre-commit 执行不加载项目的 Oxlint 验证,并应用带[一次有界重试](../../archived/process/2026-08-09-oxlint-only-fix-workflow.md)的安全修复,拒绝已暂存的空白问题并检查 vendor manifest(元数据清单);pre-push 运行增量类型检查。CI 在 Node 22.19/24/26 上运行完整矩阵,并对 Headless、TUI、ACP(Agent Client Protocol)、JSON-RPC、工作流和代码运行时入口路径执行已构建应用的冒烟测试。 +- lefthook pre-commit 执行不加载项目的 Oxlint 验证,并应用带[一次有界重试](../../archived/process/2026-08-09-oxlint-only-fix-workflow.md)的安全修复,拒绝已暂存的空白问题并检查 vendor manifest(元数据清单);pre-push 运行增量类型检查。CI 在 Node 22.19/24/26 上运行完整矩阵,并对 Headless、TUI、ACP(Agent Client Protocol)、JSON-RPC、工作流和PTC 运行时入口路径执行已构建应用的冒烟测试。 ## 后果 diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.i18n.yaml b/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.i18n.yaml index 76be707cbd..68a90bd984 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md -2026-09-08-ci-completion-observations.md: 5b40b92ac19156a017aaafeffc162895eb6db2ae -2026-09-08-ci-completion-observations.zh.md: 9a73f5351721371493b019f8d8faa69d0085ef99 +2026-09-08-ci-completion-observations.md: 368d3b2f644ca3f7f850dd0ffbd56db19a1dca64 +2026-09-08-ci-completion-observations.zh.md: 1529361fb07b661f7152da9566900e3782cdb67f diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md b/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md index 5b40b92ac1..368d3b2f64 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md +++ b/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.md @@ -22,7 +22,7 @@ The [whole-queue steering test](../../../../apps/web/tests/steering.e2e.ts) wait The [workspace-management test](../../../../apps/web/tests/workspace-management.e2e.ts) waits for restored composer focus before the next directory-dialog gesture. Its archive case gives the known seed id an explicit user title through the Session controller, then uses that exact title to identify the row across reload. An unrelated restored row cannot satisfy that locator; the durable archive assertion still checks the seed id and retained log. -The [Node runtime tests](../../../../packages/code-runtime/code-runtime-node/tests/runtime.spec.ts) exercise real managed-process execution, binding transport, elapsed deadlines and cancellation. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-code-runtime.md) supersedes the worker ELU budget and its controlled-sample tests; real process and transport evidence remains necessary. +The [Node runtime tests](../../../../packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts) exercise real managed-process execution, binding transport, elapsed deadlines and cancellation. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md) supersedes the worker ELU budget and its controlled-sample tests; real process and transport evidence remains necessary. The [detached-launch tests](../../../../packages/host/open-in-app/tests/launch-detached.spec.ts) control watch time and deliver late process events through the real launcher's registered callbacks. They check one settlement, one unref, and no child kill. Real-process environment and early-exit cases remain in the [resolver tests](../../../../packages/host/open-in-app/tests/resolver.spec.ts). diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md b/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md index 9a73f53517..1529361fb0 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md +++ b/.agents/notes/implemented/testing/2026-09-08-ci-completion-observations.zh.md @@ -22,7 +22,7 @@ Status: implemented [Workspace 管理测试](../../../../apps/web/tests/workspace-management.e2e.ts)在下一次目录对话框操作前等待恢复后的 composer 焦点。归档用例通过 Session controller 为已知 seed id 设置显式用户标题,再用该精确标题跨重载定位行。无关的恢复行无法匹配该定位器;持久化归档断言仍检查 seed id 和保留的日志。 -[Node 运行时测试](../../../../packages/code-runtime/code-runtime-node/tests/runtime.spec.ts)执行真实受管进程、绑定传输、经过时间截止与取消。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-code-runtime.zh.md)取代 worker ELU 预算及其受控样本测试;真实进程与传输证据仍然必要。 +[Node 运行时测试](../../../../packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts)执行真实受管进程、绑定传输、经过时间截止与取消。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker ELU 预算及其受控样本测试;真实进程与传输证据仍然必要。 [分离启动测试](../../../../packages/host/open-in-app/tests/launch-detached.spec.ts)控制观察时间,并通过真实 launcher 登记的回调发送迟到进程事件。测试检查仅完成一次、仅 unref 一次且不终止子进程。[Resolver 测试](../../../../packages/host/open-in-app/tests/resolver.spec.ts)保留真实进程的环境变量和提前退出用例。 diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml index 7f6b5e05bc..fd33fa9ecc 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md -2026-09-08-ci-readiness-and-completion.md: dc483e0daba361eae2cd74bb6fd8fef360e4d257 -2026-09-08-ci-readiness-and-completion.zh.md: a5b8374e208e0f13e6c14f8bb621c06059a49ad8 +2026-09-08-ci-readiness-and-completion.md: 9afc8f7ecc3036acdf9ec2d5c87a50ef74ac9b69 +2026-09-08-ci-readiness-and-completion.zh.md: f3d72276a9160dd040e2b332d8579df98afec8fc diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md index dc483e0dab..9afc8f7ecc 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md +++ b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md @@ -28,7 +28,7 @@ The [ACP disconnect tests](../../../../packages/acp/acp/tests/dispose.spec.ts) a The [subagent teardown decision](2026-09-07-subagent-teardown-test-budgets.md) owns lifecycle cleanup budgets. The [persistent PowerShell decision](2026-09-07-pwsh-ci-observable-completion.md) owns exact versus inferred terminal readiness; a one-shot process's completion promise has different semantics. -The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-code-runtime.md) supersedes worker active-time accounting. The [Node runtime suite](../../../../packages/code-runtime/code-runtime-node/tests/runtime.spec.ts) exercises the replacement elapsed deadline through real managed processes. The other completion observations and fixture lifecycle rules in this note remain in force. +The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md) supersedes worker active-time accounting. The [Node runtime suite](../../../../packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts) exercises the replacement elapsed deadline through real managed processes. The other completion observations and fixture lifecycle rules in this note remain in force. The [SDK subagent protocol-error test](../../../../packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts) uses the provider's normal shutdown and exit grace periods and registers disposal before its assertions. The [Inspector tree tests](../../../../packages/experimental/inspector/tests/cordis-tree.host.spec.ts) pass the active test budget to Worker startup and register cleanup while startup is still pending. A cancelled test cannot receive a late-ready handle; cleanup awaits initialization and closes a successfully started Worker. Failed initialization already terminates the Worker before rejecting. A controlled late-start test verifies cancellation and closure through the real Worker's HTTP endpoint. Production defaults remain unchanged. diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md index a5b8374e20..f3d72276a9 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md +++ b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md @@ -28,7 +28,7 @@ Status: implemented [子 Agent 拆卸决策](2026-09-07-subagent-teardown-test-budgets.zh.md)负责生命周期清理预算。[持久 PowerShell 决策](2026-09-07-pwsh-ci-observable-completion.zh.md)负责精确与推断的终端就绪状态;一次性进程的完成 Promise 具有不同语义。 -[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-code-runtime.zh.md)取代 worker 活跃时间计量。[Node 运行时套件](../../../../packages/code-runtime/code-runtime-node/tests/runtime.spec.ts)通过真实受管进程验证替代的经过时间截止。本说明中其他完成观测与测试生命周期规则保持有效。 +[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker 活跃时间计量。[Node 运行时套件](../../../../packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts)通过真实受管进程验证替代的经过时间截止。本说明中其他完成观测与测试生命周期规则保持有效。 [SDK 子 Agent 协议错误测试](../../../../packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts)使用提供方正常的关闭和退出等待时间,并在断言前登记清理。[Inspector 树测试](../../../../packages/experimental/inspector/tests/cordis-tree.host.spec.ts)将当前测试预算传给 Worker 启动,并在启动尚未完成时登记清理。取消后的测试不会收到随后才就绪的实例;清理等待初始化完成,并关闭成功启动的 Worker。初始化失败时,启动操作会在拒绝前终止 Worker。受控的延迟启动测试通过真实 Worker 的 HTTP 端点验证取消和关闭。生产默认值不变。 diff --git a/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.i18n.yaml b/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.i18n.yaml index 241a9e9d5f..994003d599 100644 --- a/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.md -2026-09-10-hosted-image-test-assumptions.md: 5cf3b14503162d67d0fbb27743228cb1a8d7ffe2 -2026-09-10-hosted-image-test-assumptions.zh.md: db82566c11b50b9203d30f7be6aec1378512f94b +2026-09-10-hosted-image-test-assumptions.md: 1053b43514c87e73a756e8cd5eeb26facc483a51 +2026-09-10-hosted-image-test-assumptions.zh.md: 9061ceb696101c08e644a256c54e2ffaa09d4b29 diff --git a/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.md b/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.md index 5cf3b14503..1053b43514 100644 --- a/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.md +++ b/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.md @@ -18,9 +18,9 @@ Terminal cases that drive a mocked PTY exit pin the containment they need (`inte `plugin-config dispose graces reach the real ACP run` configures 5000ms dispose graces. At 150ms the hosted image escalated while the scope could not take the signal — `systemctl` failed the kill (`Failed to send signal SIGKILL to auxiliary processes: Invalid argument`) and the teardown reported a failure the configuration never asked for. Its mock refuses stdin EOF and `SIGTERM` by design, so the case waits out both graces (~10s) and carries a 30s case budget, above the 5000ms default the local unit entry grants. -Both illegal-UTF-8 residual cases in `packages/experimental/code-runtime-python/tests/runtime.spec.ts` pace their writes with `time.sleep(0.001)`: `os.sched_yield()` lets a loaded reader coalesce the writes into one chunk, and the coalesced chunk is what the wrapped `Buffer.concat` measures (the hosted image measured 2563 against the 2048 bound with a correct implementation). Their payloads stay above that bound — 3200 bytes for the `0xFF` case and 1100 `ED A0 80` sequences, 3300 raw bytes, for the CESU-8 case, past the 3072-byte budget a raw-byte undercount reaches — so the undercount still flushes above 2048. Each carries a 20s case budget for the paced writes plus the interpreter start. +Both illegal-UTF-8 residual cases in `packages/experimental/ptc-runtime-python/tests/runtime.spec.ts` pace their writes with `time.sleep(0.001)`: `os.sched_yield()` lets a loaded reader coalesce the writes into one chunk, and the coalesced chunk is what the wrapped `Buffer.concat` measures (the hosted image measured 2563 against the 2048 bound with a correct implementation). Their payloads stay above that bound — 3200 bytes for the `0xFF` case and 1100 `ED A0 80` sequences, 3300 raw bytes, for the CESU-8 case, past the 3072-byte budget a raw-byte undercount reaches — so the undercount still flushes above 2048. Each carries a 20s case budget for the paced writes plus the interpreter start. -The stray-output sealing test in `packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts` keeps a real Python child but splits its stdout reads into single-byte events. OS pipe coalescing cannot guarantee the 1024 fragments needed to seal a block: [run 34465259316](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34465259316) passed all assertions but missed that branch. The controlled reads exercise repeated sealing and the final newline merge; exact output and bounded copy volume detect dropped bytes and repeated prefix copies. +The stray-output sealing test in `packages/experimental/ptc-runtime-python/tests/stray-fragments.spec.ts` keeps a real Python child but splits its stdout reads into single-byte events. OS pipe coalescing cannot guarantee the 1024 fragments needed to seal a block: [run 34465259316](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34465259316) passed all assertions but missed that branch. The controlled reads exercise repeated sealing and the final newline merge; exact output and bounded copy volume detect dropped bytes and repeated prefix copies. The Linux coverage lane grants `DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'`, matching the Windows coverage lane, because the disposal cases in `subprocess-local` and `bash-sandbox` exceed the 5000ms default when the lane's partitions, workers, and sibling gates share one host. diff --git a/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.zh.md b/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.zh.md index db82566c11..9061ceb696 100644 --- a/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.zh.md +++ b/.agents/notes/implemented/testing/2026-09-10-hosted-image-test-assumptions.zh.md @@ -18,9 +18,9 @@ Status: implemented `plugin-config dispose graces reach the real ACP run` 配置 5000ms 的 dispose 宽限。在 150ms 时,托管镜像在 scope 还无法接受信号时就升级了信号——`systemctl` 的 kill 失败(`Failed to send signal SIGKILL to auxiliary processes: Invalid argument`),teardown 上报了一个配置从未要求的失败。该用例的 mock 按设计既拒绝 stdin EOF 也拒绝 `SIGTERM`,因此用例会等满两个宽限(约 10s),并自带 30s 的用例预算,高于本地单测入口授予的 5000ms 默认值。 -`packages/experimental/code-runtime-python/tests/runtime.spec.ts` 的两个非法 UTF-8 残余用例都用 `time.sleep(0.001)` 控制写入节奏:`os.sched_yield()` 会让被抢占的读端把多次写入合并成一个分块,而被包裹的 `Buffer.concat` 测量的正是该分块(在正确实现下,托管镜像测得 2563,超过了 2048 的界)。两个用例的载荷都保持在该界之上——`0xFF` 用例 3200 字节,CESU-8 用例 1100 个 `ED A0 80` 序列(3300 原始字节,超过按原始字节计费会触及的 3072 字节预算)——因此少计仍然会在 2048 之上触发 flush。两者各自带有 20s 的用例预算,容纳带节奏的写入与解释器启动。 +`packages/experimental/ptc-runtime-python/tests/runtime.spec.ts` 的两个非法 UTF-8 残余用例都用 `time.sleep(0.001)` 控制写入节奏:`os.sched_yield()` 会让被抢占的读端把多次写入合并成一个分块,而被包裹的 `Buffer.concat` 测量的正是该分块(在正确实现下,托管镜像测得 2563,超过了 2048 的界)。两个用例的载荷都保持在该界之上——`0xFF` 用例 3200 字节,CESU-8 用例 1100 个 `ED A0 80` 序列(3300 原始字节,超过按原始字节计费会触及的 3072 字节预算)——因此少计仍然会在 2048 之上触发 flush。两者各自带有 20s 的用例预算,容纳带节奏的写入与解释器启动。 -`packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts` 的原生输出分块封存测试保留真实 Python 子进程,但把 stdout 读取拆成单字节事件。操作系统的管道合并无法保证达到封存一块所需的 1024 个片段:[run 34465259316](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34465259316) 的全部断言通过,却未覆盖该分支。可控读取覆盖反复封存和末尾换行合并;精确输出与复制总量上限检测字节丢失和前缀反复复制。 +`packages/experimental/ptc-runtime-python/tests/stray-fragments.spec.ts` 的原生输出分块封存测试保留真实 Python 子进程,但把 stdout 读取拆成单字节事件。操作系统的管道合并无法保证达到封存一块所需的 1024 个片段:[run 34465259316](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34465259316) 的全部断言通过,却未覆盖该分支。可控读取覆盖反复封存和末尾换行合并;精确输出与复制总量上限检测字节丢失和前缀反复复制。 Linux coverage 通道授予 `DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'`,与 Windows coverage 通道一致,因为当该通道的分区、worker 与同级门禁共用一个宿主时,`subprocess-local` 与 `bash-sandbox` 的处置用例会超过 5000ms 默认值。 diff --git a/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.i18n.yaml index cf960a29b2..48b4108c99 100644 --- a/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.md -2026-07-19-required-cancellation-through-tool-capability-seams.md: 478cd887d84ceae8a5a0cd455fb7cf4b4d562950 -2026-07-19-required-cancellation-through-tool-capability-seams.zh.md: 0ce5956da11ef5144254325f0499d85b817ccfa6 +2026-07-19-required-cancellation-through-tool-capability-seams.md: 722eefc3c79d3c1c589696bc1876d10ccbce77ea +2026-07-19-required-cancellation-through-tool-capability-seams.zh.md: 80d751e22cebd16d878f09ae9a5c15996c337603 diff --git a/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.md b/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.md index 478cd887d8..722eefc3c7 100644 --- a/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.md +++ b/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.md @@ -18,7 +18,7 @@ Require an `AbortSignal` on every asynchronous same-process capability operation Each direct caller supplies a signal it owns or propagates from its own required operation context. Implementations may derive a child deadline or cancellation scope, but the derived signal remains linked to the upstream signal for the delegated lifetime. Capability implementations do not synthesize never-abort signals, use ambient async-local cancellation, or validate `AbortSignal` at runtime solely to repeat the typed same-process contract. -The migration begins with an inventory from every first-party `ToolDefinition.execute()` through the capability calls it awaits. It then changes each coherent Service Definition / Service Provider / Consumer seam together, including tests and generated API documentation. Separate PRs may migrate filesystem, shell/task, web/provider, workflow/subagent, code-runtime, and similar families so each change remains reviewable, but no migrated interface keeps an optional compatibility overload under the repository's pre-release policy. +The migration begins with an inventory from every first-party `ToolDefinition.execute()` through the capability calls it awaits. It then changes each coherent Service Definition / Service Provider / Consumer seam together, including tests and generated API documentation. Separate PRs may migrate filesystem, shell/task, web/provider, workflow/subagent, ptc-runtime, and similar families so each change remains reviewable, but no migrated interface keeps an optional compatibility overload under the repository's pre-release policy. ### Scope boundary diff --git a/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.zh.md b/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.zh.md index 0ce5956da1..80d751e22c 100644 --- a/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.zh.md +++ b/.agents/notes/proposed/architecture/2026-07-19-required-cancellation-through-tool-capability-seams.zh.md @@ -18,7 +18,7 @@ Status: proposed 每个直接调用方提供自己持有的信号,或从自身必填的操作上下文继续传递信号。实现可以派生子截止时间或取消作用域,但派生信号在委托期间仍须与上游信号关联。能力实现不得生成永不中止信号、使用环境式异步本地取消,也不得仅为重复类型化同进程约定而在运行时校验 `AbortSignal`。 -迁移首先从每个第一方 `ToolDefinition.execute()` 出发,沿其等待的能力调用进行清点;随后按内聚的 Service Definition/Service Provider/Consumer seam,将测试与生成的 API 文档一并修改。文件系统、Bash 与任务、Web 与提供方、工作流与 subagent、代码运行时等能力族可以通过独立 PR(Pull Request)迁移,以保持每项变更可审查;但根据仓库的预发布原则,已经迁移的接口不得保留可选兼容重载。 +迁移首先从每个第一方 `ToolDefinition.execute()` 出发,沿其等待的能力调用进行清点;随后按内聚的 Service Definition/Service Provider/Consumer seam,将测试与生成的 API 文档一并修改。文件系统、Bash 与任务、Web 与提供方、工作流与 subagent、PTC 运行时等能力族可以通过独立 PR(Pull Request)迁移,以保持每项变更可审查;但根据仓库的预发布原则,已经迁移的接口不得保留可选兼容重载。 ### 范围边界 diff --git a/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.i18n.yaml b/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.i18n.yaml index 0fe27915cd..52d12170a2 100644 --- a/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.i18n.yaml +++ b/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.md -2026-07-04-prune-dead-core-spine-api.md: e2f38579a5bd0e195a0951da4bc56d6b4cd23b51 -2026-07-04-prune-dead-core-spine-api.zh.md: 071f594ad70bdd886a7f2036f3c249a281d082b5 +2026-07-04-prune-dead-core-spine-api.md: 35130b1af2a2245ff575604466e098dcae7776cc +2026-07-04-prune-dead-core-spine-api.zh.md: d2782b733b76a29b48f74e81d4a76a0f90575fdb diff --git a/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.md b/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.md index e2f38579a5..35130b1af2 100644 --- a/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.md +++ b/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.md @@ -16,7 +16,7 @@ The production corpus is `packages/*/*/src`, example sources/config, and runtime | `ToolExecutionResult.callId` | Every hook already receives the immutable `ToolExecution`; the loop and ACP correlate through the call/session event. No consumer reads the duplicate result field. | Remove the field, copy/mismatch guards, and tests that prove the duplicate cannot disagree. | | `ReactLoopAgent` root export | Outside-package named imports are tests; production programs against `Agent` and creates/resumes through `ctx.agents`. | Return/interface-type `Agent` and make the concrete loop class package-internal; keep the deliberate synchronous config-only `AgentLoop.create()` path. | | `workflow-worker-thread` protocol/runtime/session re-exports and named `WorkerThreadWorkflowEngine` | Every package-name consumer uses the default engine; the workflow Agent Note already defines the worker wire protocol as private. | Keep the default plugin class/config contract; drop the duplicate named class export and keep protocol modules source-private. | -| `code-runtime-worker` protocol/bootstrap re-exports | Outside-package production/e2e consumers use `NodeCodeRuntime` and config, not `BootstrapPort`, `PatchableStream`, or worker message/boot types. | Keep the runtime class/config contract and make its wire/bootstrap vocabulary source-private. | +| `ptc-runtime-worker` protocol/bootstrap re-exports | Outside-package production/e2e consumers use `NodePtcRuntime` and config, not `BootstrapPort`, `PatchableStream`, or worker message/boot types. | Keep the runtime class/config contract and make its wire/bootstrap vocabulary source-private. | | ACP `agentOptions` root export | The helper has only same-file and ACP-test consumers; the sole outside-package production consumer mounts the plugin namespace. | Keep `name`, `inject`, `Config`, `AcpConfig`, and `apply`; make `agentOptions` source-private and test it through bridge behavior. | | `providerWording` and `completedTurnPrefix` root exports | Each has one same-package production caller; only the balanced-prefix helper has a same-package white-box test. | Make them source-private and test provider behavior. | | `depthOf`, `SubagentDepthError`, `waitForExit`, and `exitsWithin` root exports | Production subagent backends consume the in-process runner and subprocess construction/disposal helpers, not these enforcement/test internals. `SENSITIVE_ENV_PATTERN` is excluded because the SDK helper applies it to caller-supplied environments. | Keep depth and exit behavior but make the remaining helpers and error source-private; test through spawn and disposal. Keep the shared credential pattern public. | @@ -25,8 +25,8 @@ The production corpus is `packages/*/*/src`, example sources/config, and runtime | `compactRegion`'s separate `session` argument | The fixed caller passes the same object already present as `agent.session`; the model-visible mount API can also call the method, but accepting two identities permits a mounted plugin to provide an incoherent pair. | Keep the manual-region API while deliberately narrowing it to `agent.session` as the one source of truth. | | `CompactionResult.startSeq`, `summarySeq`, `endSeq`, and `summary` | The production consumer reads only shadowed range/seq/token accounting; the durable log owns summary and event identity. | Remove the four result echoes while keeping both shared transcript renderers. | | `BasicCompactionEngine` estimation/summarization visibility | No outside production caller invokes the five methods; the implemented Agent Note names only `estimateContentTokens()` and `summarize()` as subclass hooks. | Make those two `protected` and the three orchestration-only estimators private. | -| `CodeLogEntry.source`/`level` and `RunCodeMeta.dispatches` | Every production consumer maps logs to text; no presenter/model path reads the other fields or the persisted dispatch count. | Make code-runtime logs strings (or text-only entries) and remove result-meta dispatch plumbing; keep the local counter that mints deterministic dispatch ids. | -| `CodeRuntime.language` and `CodeRuntime.isolation` | The worker backend supplies the only production values, while PTC mode and every other production caller invoke only `run()`. | Remove the unread descriptors while preserving the worker's language, isolation, budgets, cancellation, and disposal behavior. | +| `CodeLogEntry.source`/`level` and `RunCodeMeta.dispatches` | Every production consumer maps logs to text; no presenter/model path reads the other fields or the persisted dispatch count. | Make ptc-runtime logs strings (or text-only entries) and remove result-meta dispatch plumbing; keep the local counter that mints deterministic dispatch ids. | +| `PtcRuntime.language` and `PtcRuntime.isolation` | The worker backend supplies the only production values, while PTC mode and every other production caller invoke only `run()`. | Remove the unread descriptors while preserving the worker's language, isolation, budgets, cancellation, and disposal behavior. | | `ToolNotFoundError.toolName`, `SystemPrompt.config`, and `BashTask.command` | Each stored public value has no production reader. | Drop the unread field while retaining error messages, resolved configuration behavior, and task lifecycle. | | Backend package-root implementation helpers | The exact inventory below is called only through relative same-package imports. Production namespace imports mount the retained plugin contract without reading these properties; named root consumers are tests. | Retain each adapter/provider/service and its config/error contract; stop exporting the listed helper functions/constants at package roots. | | Consumer package-root implementation helpers | The exact inventory below has only same-package production callers. Production namespace imports mount plugin contracts without reading helper properties; named root consumers are tests. | Retain plugin contracts and stable error codes; move tests to package-local modules or public behavior and stop exporting the listed helpers at package roots. | diff --git a/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.zh.md b/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.zh.md index 071f594ad7..d2782b733b 100644 --- a/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.zh.md +++ b/.agents/notes/rejected/simplification/2026-07-04-prune-dead-core-spine-api.zh.md @@ -16,7 +16,7 @@ Status: rejected — stale 2026-07 inventory: rows were pruned piecemeal or gain | `ToolExecutionResult.callId` | 每个钩子已经接收不可变的 `ToolExecution`;循环和 ACP(Agent Client Protocol)通过调用/会话事件关联。没有消费方读取这个重复的结果字段。 | 移除该字段、复制/不匹配守卫,以及证明该重复不可能不一致的测试。 | | `ReactLoopAgent` 根导出 | 包外的命名导入都是测试;生产代码面向 `Agent` 编程,通过 `ctx.agents` 创建/恢复。 | 将返回类型和接口类型设为 `Agent`,将具体循环类改为包内部;保留有意设计的同步、仅配置的 `AgentLoop.create()` 路径。 | | `workflow-worker-thread` 的 protocol/runtime/session 再导出与命名的 `WorkerThreadWorkflowEngine` | 所有通过包名导入的消费方都使用默认引擎;工作流 Agent Note 已将 worker 协议格式(wire format)定义为私有。 | 保留默认插件类/配置约定;移除重复的命名类导出,将协议模块保持为源码私有。 | -| `code-runtime-worker` 的 protocol/bootstrap 再导出 | 包外的生产/e2e 消费方使用 `NodeCodeRuntime` 和配置,而非 `BootstrapPort`、`PatchableStream` 或 worker 消息/启动类型。 | 保留运行时类/配置约定,将其协议格式/bootstrap 词汇改为源码私有。 | +| `ptc-runtime-worker` 的 protocol/bootstrap 再导出 | 包外的生产/e2e 消费方使用 `NodePtcRuntime` 和配置,而非 `BootstrapPort`、`PatchableStream` 或 worker 消息/启动类型。 | 保留运行时类/配置约定,将其协议格式/bootstrap 词汇改为源码私有。 | | ACP 的 `agentOptions` 根导出 | 该辅助函数只有同文件和 ACP 测试消费方;唯一的包外生产消费方挂载的是插件命名空间。 | 保留 `name`、`inject`、`Config`、`AcpConfig` 和 `apply`;将 `agentOptions` 改为源码私有,通过桥接层行为测试。 | | `providerWording` 与 `completedTurnPrefix` 根导出 | 各有一个同包生产调用者;只有 balanced-prefix 辅助函数有一个同包白盒测试。 | 改为源码私有,测试提供方行为。 | | `depthOf`、`SubagentDepthError`、`waitForExit` 与 `exitsWithin` 根导出 | 生产 subagent 后端消费的是进程内 runner 和子进程构造/dispose(资源释放)辅助函数,而非这些强制机制和测试内部实现。`SENSITIVE_ENV_PATTERN` 不在其中,因为 SDK helper 会将它应用于调用方传入的环境。 | 保留深度与退出行为,但将剩余辅助函数和 error 改为源码私有;通过 spawn 和 dispose 测试。保持共享凭据正则公开。 | @@ -25,8 +25,8 @@ Status: rejected — stale 2026-07 inventory: rows were pruned piecemeal or gain | `compactRegion` 的独立 `session` 参数 | 固定调用方传入的对象就是 `agent.session` 中已有的对象;模型可见的 mount API 也可以调用该方法,但同时接受两个独立对象,会让挂载的插件传入不一致的组合。 | 保留手动 region API,同时有意将其收窄为以 `agent.session` 为唯一真源。 | | `CompactionResult.startSeq`、`summarySeq`、`endSeq` 与 `summary` | 生产消费方只读取 shadowed range/seq/token 统计;持久日志拥有 summary 和事件标识。 | 移除四个结果回显,保留两个共享的 transcript(文本记录)渲染器。 | | `BasicCompactionEngine` 的估算/摘要方法可见性 | 没有包外生产调用者调用这五个方法;已实现的 Agent Note 只将 `estimateContentTokens()` 和 `summarize()` 命名为子类钩子。 | 将这两个方法改为 `protected`,其余三个编排专用的估算器改为 private。 | -| `CodeLogEntry.source`/`level` 与 `RunCodeMeta.dispatches` | 每个生产消费方都将日志映射为文本;没有 presenter/模型路径读取其他字段或持久化的 dispatch 计数。 | 将 code-runtime 日志改为字符串(或纯文本条目),移除 result-meta 的 dispatch 管道;保留用于生成确定性 dispatch id 的本地计数器。 | -| `CodeRuntime.language` 与 `CodeRuntime.isolation` | worker 后端提供唯一的生产值,而 PTC mode 及其他所有生产调用方只调用 `run()`。 | 移除未读描述符,同时保留 worker 的语言、隔离、预算、取消与资源释放行为。 | +| `CodeLogEntry.source`/`level` 与 `RunCodeMeta.dispatches` | 每个生产消费方都将日志映射为文本;没有 presenter/模型路径读取其他字段或持久化的 dispatch 计数。 | 将 ptc-runtime 日志改为字符串(或纯文本条目),移除 result-meta 的 dispatch 管道;保留用于生成确定性 dispatch id 的本地计数器。 | +| `PtcRuntime.language` 与 `PtcRuntime.isolation` | worker 后端提供唯一的生产值,而 PTC mode 及其他所有生产调用方只调用 `run()`。 | 移除未读描述符,同时保留 worker 的语言、隔离、预算、取消与资源释放行为。 | | `ToolNotFoundError.toolName`、`SystemPrompt.config` 与 `BashTask.command` | 每个存储的公开值都没有生产读取者。 | 移除未读字段,保留错误消息、已解析的配置行为和任务生命周期。 | | 后端包根实现辅助函数 | 下方精确清单仅通过相对路径的同包导入调用。生产命名空间导入挂载的是保留的插件约定,不读取这些属性;包根命名导入的消费方都是测试。 | 保留每个适配器/提供方/服务及其配置/错误约定;停止在包根导出所列辅助函数/常量。 | | 消费方包根实现辅助函数 | 下方精确清单只有同包生产调用者。生产命名空间导入挂载的是插件约定,不读取辅助属性;包根命名导入的消费方都是测试。 | 保留插件约定和稳定的错误码;将测试迁移到包内模块或公开行为,停止在包根导出所列辅助函数。 | diff --git a/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.i18n.yaml b/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.i18n.yaml index 2a5c5fab6f..5b19f5d40c 100644 --- a/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.i18n.yaml +++ b/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.md -2026-07-26-dependency-swaps-rejected-by-nih-audit.md: 06b884d78105c23c5c489a10e0c1489aa5f95eee -2026-07-26-dependency-swaps-rejected-by-nih-audit.zh.md: 0cff8b10109919b5e6be96e1f0c26de3e4d3bbf8 +2026-07-26-dependency-swaps-rejected-by-nih-audit.md: 1ea01d96c5e817440c1daca871603d9cec78c06a +2026-07-26-dependency-swaps-rejected-by-nih-audit.zh.md: d7140b88a75d1af045fd32e4b1048554071d68e8 diff --git a/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.md b/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.md index 06b884d781..1ea01d96c5 100644 --- a/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.md +++ b/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.md @@ -31,7 +31,7 @@ Adopt the following dependency swaps. Rejected — per-item evidence below; a fu **Data and validation:** - **Ajv for the tools JSON Schema validator**: the [schema-DSL note](../../implemented/architecture/2026-07-20-unified-json-value-schema-dsl.md) explicitly rejected accepting a larger schema language; the validator also does realm-intrinsic prototype checks Ajv does not. -- **`structuredClone` for session `snapshotJsonValue`/`isJsonValue`**: it is a validator + detacher enforcing the lossless-JSON boundary with single-read-per-getter and cross-realm intrinsic checks; `structuredClone` accepts Map/Date/-0 and enforces nothing. Same for the deliberately dependency-free `code-runtime-worker` mirror hardened against a model-mutated realm. +- **`structuredClone` for session `snapshotJsonValue`/`isJsonValue`**: it is a validator + detacher enforcing the lossless-JSON boundary with single-read-per-getter and cross-realm intrinsic checks; `structuredClone` accepts Map/Date/-0 and enforces nothing. Same for the deliberately dependency-free `ptc-runtime-worker` mirror hardened against a model-mutated realm. - **`fast-deep-equal` for session surface `isDeepEqualJson`** and **`safe-stable-stringify` for repeat-tool-reminder canonicalization**: both swaps work mechanically but each trades ~17–20 commented, tested lines for the first external runtime dependency of a core package — negative net at this size. - **zod/valibot for durable-event strict decoders** (goal fold, tool-ralph, session): exact-key fail-loud decoders at durable boundaries with event-specific messages; a second schema library beside repo-standard schemastery is a policy change, not a deletion. - **`gpt-tokenizer`/tiktoken for token-meter**: the [replay-token-meter note](../../archived/architecture/2026-07-15-replay-token-meter-service.md) explicitly rejected tokenizer backends; a GPT BPE is also the wrong tokenizer for DeepSeek models, and ~350 of the package's lines are replay-fold bookkeeping no tokenizer covers. diff --git a/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.zh.md b/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.zh.md index 0cff8b1010..d7140b88a7 100644 --- a/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.zh.md +++ b/.agents/notes/rejected/simplification/2026-07-26-dependency-swaps-rejected-by-nih-audit.zh.md @@ -31,7 +31,7 @@ Status: rejected — 下列每一项替换在证据上都未达到净简化门 **数据与校验:** - **以 Ajv 承担 tools 的 JSON Schema 校验器**:[schema DSL 决策](../../implemented/architecture/2026-07-20-unified-json-value-schema-dsl.zh.md)已明确否决接纳更大的 schema 语言;这个校验器还会做 Ajv 不做的、针对 realm 内建原型的检查。 -- **以 `structuredClone` 替换会话的 `snapshotJsonValue`/`isJsonValue`**:它是校验器加分离器,以「每个 getter 只读一次」和跨 realm 内建对象检查强制执行无损 JSON 边界;`structuredClone` 接受 Map/Date/-0,什么都不强制。有意保持零依赖、针对被模型篡改的 realm 做过加固的 `code-runtime-worker` 镜像实现同理。 +- **以 `structuredClone` 替换会话的 `snapshotJsonValue`/`isJsonValue`**:它是校验器加分离器,以「每个 getter 只读一次」和跨 realm 内建对象检查强制执行无损 JSON 边界;`structuredClone` 接受 Map/Date/-0,什么都不强制。有意保持零依赖、针对被模型篡改的 realm 做过加固的 `ptc-runtime-worker` 镜像实现同理。 - **以 `fast-deep-equal` 替换会话接口面的 `isDeepEqualJson`**、**以 `safe-stable-stringify` 承担 repeat-tool-reminder 的规范化**:两项替换在机械层面都可行,但每一项都是拿约 17–20 行带注释、有测试的代码,去换一个核心包的第一个外部运行时依赖——在这个体量上是净亏损。 - **以 zod/valibot 承担持久事件的严格解码器**(goal fold、tool-ralph、session):它们是位于持久化边界、键集精确匹配、失败即明确报错、带事件专属报错信息的解码器;在仓库标准 schemastery 之外再放一个 schema 库是政策变更,不是删除。 - **以 `gpt-tokenizer`/tiktoken 替换 token-meter**:[回放 token 计量决策](../../archived/architecture/2026-07-15-replay-token-meter-service.md)已明确否决分词器后端;GPT 的 BPE 对 DeepSeek 模型来说也是错误的分词器,而且这个包约 350 行是回放折叠簿记,任何分词器都覆盖不了。 diff --git a/apps/cli/package.json b/apps/cli/package.json index 97881b4cfa..706e061ff9 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -113,7 +113,7 @@ "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^", "@deepseek-ai/dsh-experimental-agent-team": "workspace:^", "@deepseek-ai/dsh-experimental-agent-team-profile": "workspace:^", - "@deepseek-ai/dsh-experimental-code-runtime-python": "workspace:^", + "@deepseek-ai/dsh-experimental-ptc-runtime-python": "workspace:^", "@deepseek-ai/dsh-experimental-tool-agent-team": "workspace:^", "@deepseek-ai/dsh-fs-observation-policy": "workspace:^", "@deepseek-ai/dsh-fs-sandbox": "workspace:^", diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index d84121c665..ef7ec771b7 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -18,7 +18,7 @@ import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' -import NodeRuntime from '@deepseek-ai/dsh-code-runtime-node' +import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' @@ -44,7 +44,7 @@ let workdir: string | undefined afterEach(async () => { // Always dispose, even on failure/retry/timeout: agent-loop teardown stops - // the loop, the executor kills stray processes, and the code runtime's + // the loop, the executor kills stray processes, and the PTC runtime's // dispose awaits worker exits. await ctx?.fiber.dispose() ctx = undefined diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 8e53b59dca..3d8beb5458 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -348,7 +348,7 @@ export interface LaunchOptions { /** * Tool presentation mode patched onto the shipped `tools` row (`code` * collapses the wire to run_code + the SDK prompt section). Omit for the - * yml default. The code runtime row is always in the tree, so no extra + * yml default. The PTC runtime row is always in the tree, so no extra * insertion is needed. */ toolsMode?: 'native' | 'ptc' | 'both' diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index b164274335..b78248425e 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/capability-seams.md -capability-seams.md: 1e97a1a95974ca91c2039b1ab5cb6739fb10d96d -capability-seams.zh.md: 15ee35f38f70d863d5ada9d4019895c08319c284 +capability-seams.md: e38a0d649b3e6b8b9df9535468b4d3180ed5f8c1 +capability-seams.zh.md: 92c2ad85b98c0fec4fb43c6003fbd623d7ae39f7 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 1e97a1a959..e38a0d649b 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -166,10 +166,10 @@ flowchart LR svc_approval["ctx.approval
Approval seam"] pkg_permission_presets["permission-presets"] svc_permissionPresets["ctx.permissionPresets
Permission presets"] - pkg_code_runtime["code-runtime"] - svc_codeRuntime["ctx.codeRuntime
Code-execution seam"] - pkg_code_runtime_node["code-runtime-node"] - pkg_experimental_code_runtime_python["experimental-code-runtime-python"] + pkg_ptc_runtime["ptc-runtime"] + svc_ptcRuntime["ctx.ptcRuntime
PTC execution seam"] + pkg_ptc_runtime_node["ptc-runtime-node"] + pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"] pkg_fs["fs"] svc_fs["ctx.fs
Filesystem provider seam"] pkg_fs_local["fs-local"] @@ -245,8 +245,6 @@ flowchart LR pkg_bash_sandbox --> svc_shell pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules - pkg_code_runtime --> svc_codeRuntime - pkg_code_runtime_node --> svc_codeRuntime pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -258,7 +256,7 @@ flowchart LR pkg_credentials_local --> svc_credentials pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions pkg_experimental_agent_team --> svc_agentTeams - pkg_experimental_code_runtime_python --> svc_codeRuntime + pkg_experimental_ptc_runtime_python --> svc_ptcRuntime pkg_file_reference --> svc_fileReferences pkg_file_reference_local --> svc_fileReferences pkg_fs --> svc_fs @@ -284,6 +282,8 @@ flowchart LR pkg_permission_presets --> svc_permissionPresets pkg_plan_mode --> svc_planMode pkg_plugin_package_inventory_deepseek --> svc_deepseekLlmApiExtensions + pkg_ptc_runtime --> svc_ptcRuntime + pkg_ptc_runtime_node --> svc_ptcRuntime pkg_pwsh_local --> svc_shell pkg_sandbox --> svc_sandbox pkg_sandbox_local --> svc_sandbox @@ -363,7 +363,6 @@ flowchart LR svc_attachments --> pkg_tool_fs svc_authorization --> pkg_llm_pi_ai svc_clientModules --> pkg_client_hmr - svc_codeRuntime --> pkg_tools svc_compaction --> pkg_compaction_basic svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller @@ -386,6 +385,7 @@ flowchart LR svc_llm --> pkg_agent_loop svc_llm --> pkg_compaction_basic svc_lsp --> pkg_tool_lsp + svc_ptcRuntime --> pkg_tools svc_sandbox --> pkg_bash_sandbox svc_sandbox --> pkg_terminal_bash svc_sandboxPolicy --> pkg_bash_sandbox @@ -532,7 +532,7 @@ flowchart LR | `ctx.sandboxPolicy` | `core` | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | - | [`bash-sandbox`](../packages/shell/bash-sandbox), [`fs-sandbox`](../packages/fs/fs-sandbox), [`terminal-bash`](../packages/terminal/terminal-bash) | - | The one home for the deployment default mode + workspace root; only the sandboxed executor and provider read the service (the tool layers use the pure `sandbox/mode` fold it also exports). Both enforcing families read it so bash and fs cannot confine to different roots. | | `ctx.approval` | `seam` | [`user-approval`](../packages/interaction/user-approval) | - | [`tools`](../packages/core/tools), [`tool-bash`](../packages/shell/tool-bash), [`acp`](../packages/acp/acp) | - | One-shot permission decisions dispatched over the `approval/request` waterfall; answerers are listeners (the ACP bridge for its own agents), absence fails closed to `unavailable`. | | `ctx.permissionPresets` | `core` | [`permission-presets`](../packages/interaction/permission-presets) | - | - | - | User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events. | -| `ctx.codeRuntime` | `seam` | [`code-runtime`](../packages/code-runtime/code-runtime) | [`code-runtime-node`](../packages/code-runtime/code-runtime-node), [`experimental-code-runtime-python`](../packages/experimental/code-runtime-python) | [`tools`](../packages/core/tools) | - | Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for PTC mode). | +| `ctx.ptcRuntime` | `seam` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | [`tools`](../packages/core/tools) | - | Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for PTC mode). | | `ctx.fs` | `seam` | [`fs`](../packages/fs/fs) | [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`fs-ssh`](../packages/ssh/fs-ssh) | [`tool-fs`](../packages/fs/tool-fs) | [`fs-observation-policy`](../packages/fs/fs-observation-policy) | tool-fs executes read/write/edit through ctx.fs; fs-sandbox fences mutations by the shared sandbox mode; fs-observation-policy contributes observed-state checks through the fs/* event gate. | | `ctx.compaction` | `seam` | [`compaction`](../packages/compaction/compaction) | [`compaction-basic`](../packages/compaction/compaction-basic) | [`compaction-basic`](../packages/compaction/compaction-basic) | - | The basic backend consumes post-step pressure and request-error recovery events; there is no model-facing compact tool. | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process), [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code), [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control), [`tool-ralph`](../packages/workflow/tool-ralph) | - | Providers implement transports; the service also owns optional Activation-based continuation orchestration, tool-subagent selects one-shot or continuable delegation, tool-subagent-control delivers follow-ups, and tool-ralph requires one fresh structured-output route. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 15ee35f38f..92c2ad85b9 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -168,10 +168,10 @@ flowchart LR svc_approval["ctx.approval
Approval seam"] pkg_permission_presets["permission-presets"] svc_permissionPresets["ctx.permissionPresets
Permission presets"] - pkg_code_runtime["code-runtime"] - svc_codeRuntime["ctx.codeRuntime
Code-execution seam"] - pkg_code_runtime_node["code-runtime-node"] - pkg_experimental_code_runtime_python["experimental-code-runtime-python"] + pkg_ptc_runtime["ptc-runtime"] + svc_ptcRuntime["ctx.ptcRuntime
PTC execution seam"] + pkg_ptc_runtime_node["ptc-runtime-node"] + pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"] pkg_fs["fs"] svc_fs["ctx.fs
Filesystem provider seam"] pkg_fs_local["fs-local"] @@ -247,8 +247,6 @@ flowchart LR pkg_bash_sandbox --> svc_shell pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules - pkg_code_runtime --> svc_codeRuntime - pkg_code_runtime_node --> svc_codeRuntime pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands pkg_compaction --> svc_compaction @@ -260,7 +258,7 @@ flowchart LR pkg_credentials_local --> svc_credentials pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions pkg_experimental_agent_team --> svc_agentTeams - pkg_experimental_code_runtime_python --> svc_codeRuntime + pkg_experimental_ptc_runtime_python --> svc_ptcRuntime pkg_file_reference --> svc_fileReferences pkg_file_reference_local --> svc_fileReferences pkg_fs --> svc_fs @@ -286,6 +284,8 @@ flowchart LR pkg_permission_presets --> svc_permissionPresets pkg_plan_mode --> svc_planMode pkg_plugin_package_inventory_deepseek --> svc_deepseekLlmApiExtensions + pkg_ptc_runtime --> svc_ptcRuntime + pkg_ptc_runtime_node --> svc_ptcRuntime pkg_pwsh_local --> svc_shell pkg_sandbox --> svc_sandbox pkg_sandbox_local --> svc_sandbox @@ -365,7 +365,6 @@ flowchart LR svc_attachments --> pkg_tool_fs svc_authorization --> pkg_llm_pi_ai svc_clientModules --> pkg_client_hmr - svc_codeRuntime --> pkg_tools svc_compaction --> pkg_compaction_basic svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller @@ -388,6 +387,7 @@ flowchart LR svc_llm --> pkg_agent_loop svc_llm --> pkg_compaction_basic svc_lsp --> pkg_tool_lsp + svc_ptcRuntime --> pkg_tools svc_sandbox --> pkg_bash_sandbox svc_sandbox --> pkg_terminal_bash svc_sandboxPolicy --> pkg_bash_sandbox @@ -534,7 +534,7 @@ flowchart LR | `ctx.sandboxPolicy` | `core` | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | - | [`bash-sandbox`](../packages/shell/bash-sandbox), [`fs-sandbox`](../packages/fs/fs-sandbox), [`terminal-bash`](../packages/terminal/terminal-bash) | - | 统一保存部署默认模式和工作区根目录;只有沙箱执行器和提供方读取该服务(工具层使用它同时导出的纯 `sandbox/mode` 折叠区)。两类强制执行组件都读取该服务,因此 bash 与 fs 不会限制到不同的根目录。 | | `ctx.approval` | `seam` | [`user-approval`](../packages/interaction/user-approval) | - | [`tools`](../packages/core/tools), [`tool-bash`](../packages/shell/tool-bash), [`acp`](../packages/acp/acp) | - | 一次性权限决策通过 `approval/request` waterfall(瀑布式事件)分派;回答方是监听器(即 ACP 为自身 agent 提供的桥接),没有回答方时以 `unavailable` 关闭失败。 | | `ctx.permissionPresets` | `core` | [`permission-presets`](../packages/interaction/permission-presets) | - | - | - | 面向用户的预设表(`workspace-write`/`danger-full-access`),将沙箱模式与审批策略选项组合在一起;一次切换会写入一个 `permission/preset` 事件,并贯通到两个选项事件。 | -| `ctx.codeRuntime` | `seam` | [`code-runtime`](../packages/code-runtime/code-runtime) | [`code-runtime-node`](../packages/code-runtime/code-runtime-node), [`experimental-code-runtime-python`](../packages/experimental/code-runtime-python) | [`tools`](../packages/core/tools) | - | 使用 Host 提供的异步绑定运行一段由模型编写的程序;各后端采用不同的基础环境和语言(工具注册表在 PTC mode 下消费该服务)。 | +| `ctx.ptcRuntime` | `seam` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | [`tools`](../packages/core/tools) | - | 使用 Host 提供的异步绑定运行一段由模型编写的程序;各后端采用不同的基础环境和语言(工具注册表在 PTC mode 下消费该服务)。 | | `ctx.fs` | `seam` | [`fs`](../packages/fs/fs) | [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`fs-ssh`](../packages/ssh/fs-ssh) | [`tool-fs`](../packages/fs/tool-fs) | [`fs-observation-policy`](../packages/fs/fs-observation-policy) | tool-fs 通过 ctx.fs 执行读取/写入/编辑;fs-sandbox 按共享沙箱模式限制变更;fs-observation-policy 通过 fs/* 事件门禁贡献基于观测状态的检查。 | | `ctx.compaction` | `seam` | [`compaction`](../packages/compaction/compaction) | [`compaction-basic`](../packages/compaction/compaction-basic) | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 基础后端消费步骤后的压力事件和请求错误恢复事件;不存在面向模型的压缩工具。 | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process), [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code), [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control), [`tool-ralph`](../packages/workflow/tool-ralph) | - | 提供方实现传输;该服务还负责可选的、基于 Activation 的延续编排,tool-subagent 选择一次性或可延续委派,tool-subagent-control 传递后续消息,而 tool-ralph 要求一条全新的结构化输出路由。 | diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index fac1a23bf2..c749149f83 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 3e059313adf369beecf27add1988db9ca154f5ab -config-catalog.zh.md: 5c43feafd88432c9dbfb61a59dae4a5d51cfb522 +config-catalog.md: 6ca1208e1214124c597e6fb070c55e50313238b0 +config-catalog.zh.md: bd1733e25307be74b053e24f79b61e975450dac6 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3e059313ad..6ca1208e12 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -401,42 +401,6 @@ export interface Config { Source: [`packages/client/hmr/src/index.ts:31`](../packages/client/hmr/src/index.ts) - - -## `@deepseek-ai/dsh-code-runtime-node` - -Requires: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` - -```ts config-catalog -/** Deployment-varying runtime bounds and launch choices. */ -export interface Config extends LaunchConfig { - /** Default elapsed deadline, including nested tool and approval waits. */ - timeoutMs?: number - /** Maximum elapsed deadline accepted by resolve. */ - maxTimeoutMs?: number - /** Combined serialized logs, completion and diagnostic byte cap. */ - maxOutputBytes?: number - /** V8 old-generation heap limit in MiB; native allocations are excluded. */ - maxOldGenerationSizeMb?: number - /** Maximum control frame, outstanding argument and queued control-output bytes. */ - maxMessageBytes?: number - /** Maximum simultaneous host binding calls accepted from a program. */ - maxPendingCalls?: number - /** Managed process termination and output-drain grace in milliseconds. */ - graceMs?: number -} - -/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ -export interface LaunchConfig { - /** Executable in the subprocess world; defaults to the current Node executable. */ - nodeExecutable?: string - /** Absolute preinstalled built bootstrap in the execution world. */ - bootstrapPath?: string -} -``` - -Source: [`packages/code-runtime/code-runtime-node/src/index.ts:26`](../packages/code-runtime/code-runtime-node/src/index.ts) - ## `@deepseek-ai/dsh-compaction-basic` @@ -563,72 +527,6 @@ export interface Config { Source: [`packages/experimental/agent-team/src/types.ts:130`](../packages/experimental/agent-team/src/types.ts) - - -## `@deepseek-ai/dsh-experimental-code-runtime-python` - -```ts config-catalog -/** Plugin config: every cap, changeable from `cordis.yml` (no hardcoded tunables). */ -export interface Config { - /** - * RLIMIT_CPU in whole seconds (a positive integer — `setrlimit` in the child - * rejects a float). The child sets the soft limit to `cpuSeconds` and the - * hard limit to `cpuSeconds + 1`: the kernel delivers SIGXCPU at the soft - * limit, which the host classifies as a `timeout`; the +1s hard limit is a - * SIGKILL backstop for a program that traps SIGXCPU. Granularity is whole seconds. - */ - cpuSeconds?: number - /** Wall-clock ceiling in milliseconds; backstops CPU time for programs awaiting a promise nobody resolves. */ - maxWallMs?: number - /** - * RLIMIT_AS in mebibytes; caps address space so a runaway allocation fails - * cleanly. Not applied on Darwin, where the dyld shared cache mapped into - * every process at exec exceeds any practical cap and the kernel rejects - * the call; `cpuSeconds` and `maxWallMs` still bound the run there. Bounds - * `maxLogBytes`/`maxValueBytes` at load on EVERY platform (this static check - * runs on Darwin too, where only the runtime `setrlimit` is skipped): each - * budget times a worst-case Unicode expansion must fit this byte count minus a - * fixed interpreter baseline, so a near-budget output cannot breach the address - * space during the child's build-and-encode. - */ - addressSpaceMb?: number - /** - * Shared byte budget for captured log text (host-side ledger). Bounded at load - * against `addressSpaceMb`: the child builds and encodes a near-budget entry - * under RLIMIT_AS with several copies live at once, so this cap times the - * worst-case Unicode expansion must fit the address space left after the - * interpreter baseline (see `addressSpaceMb`) — a load-time rejection, not a - * runtime clamp. Also bounded at load by the host's configured heap like - * `maxValueBytes` (see its JSDoc): the effective frame cap minus the frame - * envelope. - */ - maxLogBytes?: number - /** - * Byte cap for the completion value. Bounded at load against `addressSpaceMb` - * the same way `maxLogBytes` is: the child builds and encodes a near-budget - * value under RLIMIT_AS with several copies live at once, so this cap times the - * worst-case Unicode expansion must fit the address space left after the - * interpreter baseline. Both budgets are ALSO bounded at load by the host's - * configured heap: the effective frame cap (the protocol cap, or a lower - * heap-derived ceiling when the host heap cannot safely parse a near-cap - * frame — see `hostFrameParseCeiling`) minus the frame envelope, so a budget - * whose honest frame could OOM the host's own JSON.parse is rejected up - * front. - */ - maxValueBytes?: number - /** SIGTERM→SIGKILL grace period on kill, matching bash-local's default. */ - graceMs?: number - /** - * Absolute path, relative path, or basename of a CPython 3.10+ interpreter. - * Resolved and validated once at plugin load under a five-second force-kill - * deadline; a basename searches `PATH`. - */ - pythonBin?: string -} -``` - -Source: [`packages/experimental/code-runtime-python/src/index.ts:42`](../packages/experimental/code-runtime-python/src/index.ts) - ## `@deepseek-ai/dsh-experimental-inspector` @@ -697,6 +595,72 @@ export interface InspectorOptions { Source: [`packages/experimental/inspector/src/index.ts:66`](../packages/experimental/inspector/src/index.ts) + + +## `@deepseek-ai/dsh-experimental-ptc-runtime-python` + +```ts config-catalog +/** Plugin config: every cap, changeable from `cordis.yml` (no hardcoded tunables). */ +export interface Config { + /** + * RLIMIT_CPU in whole seconds (a positive integer — `setrlimit` in the child + * rejects a float). The child sets the soft limit to `cpuSeconds` and the + * hard limit to `cpuSeconds + 1`: the kernel delivers SIGXCPU at the soft + * limit, which the host classifies as a `timeout`; the +1s hard limit is a + * SIGKILL backstop for a program that traps SIGXCPU. Granularity is whole seconds. + */ + cpuSeconds?: number + /** Wall-clock ceiling in milliseconds; backstops CPU time for programs awaiting a promise nobody resolves. */ + maxWallMs?: number + /** + * RLIMIT_AS in mebibytes; caps address space so a runaway allocation fails + * cleanly. Not applied on Darwin, where the dyld shared cache mapped into + * every process at exec exceeds any practical cap and the kernel rejects + * the call; `cpuSeconds` and `maxWallMs` still bound the run there. Bounds + * `maxLogBytes`/`maxValueBytes` at load on EVERY platform (this static check + * runs on Darwin too, where only the runtime `setrlimit` is skipped): each + * budget times a worst-case Unicode expansion must fit this byte count minus a + * fixed interpreter baseline, so a near-budget output cannot breach the address + * space during the child's build-and-encode. + */ + addressSpaceMb?: number + /** + * Shared byte budget for captured log text (host-side ledger). Bounded at load + * against `addressSpaceMb`: the child builds and encodes a near-budget entry + * under RLIMIT_AS with several copies live at once, so this cap times the + * worst-case Unicode expansion must fit the address space left after the + * interpreter baseline (see `addressSpaceMb`) — a load-time rejection, not a + * runtime clamp. Also bounded at load by the host's configured heap like + * `maxValueBytes` (see its JSDoc): the effective frame cap minus the frame + * envelope. + */ + maxLogBytes?: number + /** + * Byte cap for the completion value. Bounded at load against `addressSpaceMb` + * the same way `maxLogBytes` is: the child builds and encodes a near-budget + * value under RLIMIT_AS with several copies live at once, so this cap times the + * worst-case Unicode expansion must fit the address space left after the + * interpreter baseline. Both budgets are ALSO bounded at load by the host's + * configured heap: the effective frame cap (the protocol cap, or a lower + * heap-derived ceiling when the host heap cannot safely parse a near-cap + * frame — see `hostFrameParseCeiling`) minus the frame envelope, so a budget + * whose honest frame could OOM the host's own JSON.parse is rejected up + * front. + */ + maxValueBytes?: number + /** SIGTERM→SIGKILL grace period on kill, matching bash-local's default. */ + graceMs?: number + /** + * Absolute path, relative path, or basename of a CPython 3.10+ interpreter. + * Resolved and validated once at plugin load under a five-second force-kill + * deadline; a basename searches `PATH`. + */ + pythonBin?: string +} +``` + +Source: [`packages/experimental/ptc-runtime-python/src/index.ts:42`](../packages/experimental/ptc-runtime-python/src/index.ts) + ## `@deepseek-ai/dsh-experimental-tool-agent-team` @@ -1687,6 +1651,42 @@ export interface Config { Source: [`packages/llm/plugin-package-inventory-deepseek/src/index.ts:31`](../packages/llm/plugin-package-inventory-deepseek/src/index.ts) + + +## `@deepseek-ai/dsh-ptc-runtime-node` + +Requires: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` + +```ts config-catalog +/** Deployment-varying runtime bounds and launch choices. */ +export interface Config extends LaunchConfig { + /** Default elapsed deadline, including nested tool and approval waits. */ + timeoutMs?: number + /** Maximum elapsed deadline accepted by resolve. */ + maxTimeoutMs?: number + /** Combined serialized logs, completion and diagnostic byte cap. */ + maxOutputBytes?: number + /** V8 old-generation heap limit in MiB; native allocations are excluded. */ + maxOldGenerationSizeMb?: number + /** Maximum control frame, outstanding argument and queued control-output bytes. */ + maxMessageBytes?: number + /** Maximum simultaneous host binding calls accepted from a program. */ + maxPendingCalls?: number + /** Managed process termination and output-drain grace in milliseconds. */ + graceMs?: number +} + +/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ +export interface LaunchConfig { + /** Executable in the subprocess world; defaults to the current Node executable. */ + nodeExecutable?: string + /** Absolute preinstalled built bootstrap in the execution world. */ + bootstrapPath?: string +} +``` + +Source: [`packages/ptc-runtime/ptc-runtime-node/src/index.ts:26`](../packages/ptc-runtime/ptc-runtime-node/src/index.ts) + ## `@deepseek-ai/dsh-pwsh-local` @@ -3180,7 +3180,7 @@ export interface Config { * sends only `run_code` plus a generated SDK prompt and collapses the * executor to the same surface (a model-direct call may only name * `run_code`; `run_code` SDK sub-dispatches keep every visible tool); `both` - * sends both forms. PTC mode requires a `ctx.codeRuntime` whose `language` + * sends both forms. PTC mode requires a `ctx.ptcRuntime` whose `language` * has a registered SDK renderer (TypeScript or Python) and fail prompt * assembly when it is absent or has no renderer. Under `ptc`, native names * in `toolOrder` are invalid. @@ -3544,13 +3544,13 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co Abstract service classes — a deployment loads a concrete implementation package instead ([capability seams](../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)). - `@deepseek-ai/dsh-attachment` — abstract `AttachmentStore` ([`packages/attachment/attachment/src/index.ts`](../packages/attachment/attachment/src/index.ts)) -- `@deepseek-ai/dsh-code-runtime` — abstract `CodeRuntime` ([`packages/code-runtime/code-runtime/src/index.ts`](../packages/code-runtime/code-runtime/src/index.ts)) - `@deepseek-ai/dsh-compaction` — abstract `CompactionEngine` ([`packages/compaction/compaction/src/index.ts`](../packages/compaction/compaction/src/index.ts)) - `@deepseek-ai/dsh-credentials` — abstract `CredentialProvider` ([`packages/credentials/credentials/src/index.ts`](../packages/credentials/credentials/src/index.ts)) - `@deepseek-ai/dsh-file-reference` — abstract `FileReferenceService` ([`packages/context/file-reference/src/index.ts`](../packages/context/file-reference/src/index.ts)) - `@deepseek-ai/dsh-fs` — abstract `FileSystem` ([`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts)) - `@deepseek-ai/dsh-host-directory-picker` — abstract `DirectoryPicker` ([`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts)) - `@deepseek-ai/dsh-jobs` — abstract `JobRegistry` ([`packages/jobs/jobs/src/index.ts`](../packages/jobs/jobs/src/index.ts)) +- `@deepseek-ai/dsh-ptc-runtime` — abstract `PtcRuntime` ([`packages/ptc-runtime/ptc-runtime/src/index.ts`](../packages/ptc-runtime/ptc-runtime/src/index.ts)) - `@deepseek-ai/dsh-sandbox` — abstract `SandboxProvider` ([`packages/sandbox/sandbox/src/index.ts`](../packages/sandbox/sandbox/src/index.ts)) - `@deepseek-ai/dsh-session-persistence` — abstract `SessionPersistence` ([`packages/session/session-persistence/src/index.ts`](../packages/session/session-persistence/src/index.ts)) - `@deepseek-ai/dsh-session-query` — abstract `SessionQueryEngine` ([`packages/session-query/session-query/src/index.ts`](../packages/session-query/session-query/src/index.ts)) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5c43feafd8..bd1733e253 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -403,42 +403,6 @@ export interface Config { 来源:[`packages/client/hmr/src/index.ts:31`](../packages/client/hmr/src/index.ts) - - -## `@deepseek-ai/dsh-code-runtime-node` - -需要: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` - -```ts config-catalog -/** Deployment-varying runtime bounds and launch choices. */ -export interface Config extends LaunchConfig { - /** Default elapsed deadline, including nested tool and approval waits. */ - timeoutMs?: number - /** Maximum elapsed deadline accepted by resolve. */ - maxTimeoutMs?: number - /** Combined serialized logs, completion and diagnostic byte cap. */ - maxOutputBytes?: number - /** V8 old-generation heap limit in MiB; native allocations are excluded. */ - maxOldGenerationSizeMb?: number - /** Maximum control frame, outstanding argument and queued control-output bytes. */ - maxMessageBytes?: number - /** Maximum simultaneous host binding calls accepted from a program. */ - maxPendingCalls?: number - /** Managed process termination and output-drain grace in milliseconds. */ - graceMs?: number -} - -/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ -export interface LaunchConfig { - /** Executable in the subprocess world; defaults to the current Node executable. */ - nodeExecutable?: string - /** Absolute preinstalled built bootstrap in the execution world. */ - bootstrapPath?: string -} -``` - -来源: [`packages/code-runtime/code-runtime-node/src/index.ts:26`](../packages/code-runtime/code-runtime-node/src/index.ts) - ## `@deepseek-ai/dsh-compaction-basic` @@ -565,72 +529,6 @@ export interface Config { 来源:[`packages/experimental/agent-team/src/types.ts:130`](../packages/experimental/agent-team/src/types.ts) - - -## `@deepseek-ai/dsh-experimental-code-runtime-python` - -```ts config-catalog -/** Plugin config: every cap, changeable from `cordis.yml` (no hardcoded tunables). */ -export interface Config { - /** - * RLIMIT_CPU in whole seconds (a positive integer — `setrlimit` in the child - * rejects a float). The child sets the soft limit to `cpuSeconds` and the - * hard limit to `cpuSeconds + 1`: the kernel delivers SIGXCPU at the soft - * limit, which the host classifies as a `timeout`; the +1s hard limit is a - * SIGKILL backstop for a program that traps SIGXCPU. Granularity is whole seconds. - */ - cpuSeconds?: number - /** Wall-clock ceiling in milliseconds; backstops CPU time for programs awaiting a promise nobody resolves. */ - maxWallMs?: number - /** - * RLIMIT_AS in mebibytes; caps address space so a runaway allocation fails - * cleanly. Not applied on Darwin, where the dyld shared cache mapped into - * every process at exec exceeds any practical cap and the kernel rejects - * the call; `cpuSeconds` and `maxWallMs` still bound the run there. Bounds - * `maxLogBytes`/`maxValueBytes` at load on EVERY platform (this static check - * runs on Darwin too, where only the runtime `setrlimit` is skipped): each - * budget times a worst-case Unicode expansion must fit this byte count minus a - * fixed interpreter baseline, so a near-budget output cannot breach the address - * space during the child's build-and-encode. - */ - addressSpaceMb?: number - /** - * Shared byte budget for captured log text (host-side ledger). Bounded at load - * against `addressSpaceMb`: the child builds and encodes a near-budget entry - * under RLIMIT_AS with several copies live at once, so this cap times the - * worst-case Unicode expansion must fit the address space left after the - * interpreter baseline (see `addressSpaceMb`) — a load-time rejection, not a - * runtime clamp. Also bounded at load by the host's configured heap like - * `maxValueBytes` (see its JSDoc): the effective frame cap minus the frame - * envelope. - */ - maxLogBytes?: number - /** - * Byte cap for the completion value. Bounded at load against `addressSpaceMb` - * the same way `maxLogBytes` is: the child builds and encodes a near-budget - * value under RLIMIT_AS with several copies live at once, so this cap times the - * worst-case Unicode expansion must fit the address space left after the - * interpreter baseline. Both budgets are ALSO bounded at load by the host's - * configured heap: the effective frame cap (the protocol cap, or a lower - * heap-derived ceiling when the host heap cannot safely parse a near-cap - * frame — see `hostFrameParseCeiling`) minus the frame envelope, so a budget - * whose honest frame could OOM the host's own JSON.parse is rejected up - * front. - */ - maxValueBytes?: number - /** SIGTERM→SIGKILL grace period on kill, matching bash-local's default. */ - graceMs?: number - /** - * Absolute path, relative path, or basename of a CPython 3.10+ interpreter. - * Resolved and validated once at plugin load under a five-second force-kill - * deadline; a basename searches `PATH`. - */ - pythonBin?: string -} -``` - -来源:[`packages/experimental/code-runtime-python/src/index.ts:42`](../packages/experimental/code-runtime-python/src/index.ts) - ## `@deepseek-ai/dsh-experimental-inspector` @@ -699,6 +597,72 @@ export interface InspectorOptions { 来源:[`packages/experimental/inspector/src/index.ts:66`](../packages/experimental/inspector/src/index.ts) + + +## `@deepseek-ai/dsh-experimental-ptc-runtime-python` + +```ts config-catalog +/** Plugin config: every cap, changeable from `cordis.yml` (no hardcoded tunables). */ +export interface Config { + /** + * RLIMIT_CPU in whole seconds (a positive integer — `setrlimit` in the child + * rejects a float). The child sets the soft limit to `cpuSeconds` and the + * hard limit to `cpuSeconds + 1`: the kernel delivers SIGXCPU at the soft + * limit, which the host classifies as a `timeout`; the +1s hard limit is a + * SIGKILL backstop for a program that traps SIGXCPU. Granularity is whole seconds. + */ + cpuSeconds?: number + /** Wall-clock ceiling in milliseconds; backstops CPU time for programs awaiting a promise nobody resolves. */ + maxWallMs?: number + /** + * RLIMIT_AS in mebibytes; caps address space so a runaway allocation fails + * cleanly. Not applied on Darwin, where the dyld shared cache mapped into + * every process at exec exceeds any practical cap and the kernel rejects + * the call; `cpuSeconds` and `maxWallMs` still bound the run there. Bounds + * `maxLogBytes`/`maxValueBytes` at load on EVERY platform (this static check + * runs on Darwin too, where only the runtime `setrlimit` is skipped): each + * budget times a worst-case Unicode expansion must fit this byte count minus a + * fixed interpreter baseline, so a near-budget output cannot breach the address + * space during the child's build-and-encode. + */ + addressSpaceMb?: number + /** + * Shared byte budget for captured log text (host-side ledger). Bounded at load + * against `addressSpaceMb`: the child builds and encodes a near-budget entry + * under RLIMIT_AS with several copies live at once, so this cap times the + * worst-case Unicode expansion must fit the address space left after the + * interpreter baseline (see `addressSpaceMb`) — a load-time rejection, not a + * runtime clamp. Also bounded at load by the host's configured heap like + * `maxValueBytes` (see its JSDoc): the effective frame cap minus the frame + * envelope. + */ + maxLogBytes?: number + /** + * Byte cap for the completion value. Bounded at load against `addressSpaceMb` + * the same way `maxLogBytes` is: the child builds and encodes a near-budget + * value under RLIMIT_AS with several copies live at once, so this cap times the + * worst-case Unicode expansion must fit the address space left after the + * interpreter baseline. Both budgets are ALSO bounded at load by the host's + * configured heap: the effective frame cap (the protocol cap, or a lower + * heap-derived ceiling when the host heap cannot safely parse a near-cap + * frame — see `hostFrameParseCeiling`) minus the frame envelope, so a budget + * whose honest frame could OOM the host's own JSON.parse is rejected up + * front. + */ + maxValueBytes?: number + /** SIGTERM→SIGKILL grace period on kill, matching bash-local's default. */ + graceMs?: number + /** + * Absolute path, relative path, or basename of a CPython 3.10+ interpreter. + * Resolved and validated once at plugin load under a five-second force-kill + * deadline; a basename searches `PATH`. + */ + pythonBin?: string +} +``` + +来源:[`packages/experimental/ptc-runtime-python/src/index.ts:42`](../packages/experimental/ptc-runtime-python/src/index.ts) + ## `@deepseek-ai/dsh-experimental-tool-agent-team` @@ -1689,6 +1653,42 @@ export interface Config { 来源:[`packages/llm/plugin-package-inventory-deepseek/src/index.ts:31`](../packages/llm/plugin-package-inventory-deepseek/src/index.ts) + + +## `@deepseek-ai/dsh-ptc-runtime-node` + +需要: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` + +```ts config-catalog +/** Deployment-varying runtime bounds and launch choices. */ +export interface Config extends LaunchConfig { + /** Default elapsed deadline, including nested tool and approval waits. */ + timeoutMs?: number + /** Maximum elapsed deadline accepted by resolve. */ + maxTimeoutMs?: number + /** Combined serialized logs, completion and diagnostic byte cap. */ + maxOutputBytes?: number + /** V8 old-generation heap limit in MiB; native allocations are excluded. */ + maxOldGenerationSizeMb?: number + /** Maximum control frame, outstanding argument and queued control-output bytes. */ + maxMessageBytes?: number + /** Maximum simultaneous host binding calls accepted from a program. */ + maxPendingCalls?: number + /** Managed process termination and output-drain grace in milliseconds. */ + graceMs?: number +} + +/** Deployment-owned Node executable and optional preinstalled built bootstrap. */ +export interface LaunchConfig { + /** Executable in the subprocess world; defaults to the current Node executable. */ + nodeExecutable?: string + /** Absolute preinstalled built bootstrap in the execution world. */ + bootstrapPath?: string +} +``` + +来源: [`packages/ptc-runtime/ptc-runtime-node/src/index.ts:26`](../packages/ptc-runtime/ptc-runtime-node/src/index.ts) + ## `@deepseek-ai/dsh-pwsh-local` @@ -3182,7 +3182,7 @@ export interface Config { * sends only `run_code` plus a generated SDK prompt and collapses the * executor to the same surface (a model-direct call may only name * `run_code`; `run_code` SDK sub-dispatches keep every visible tool); `both` - * sends both forms. PTC mode requires a `ctx.codeRuntime` whose `language` + * sends both forms. PTC mode requires a `ctx.ptcRuntime` whose `language` * has a registered SDK renderer (TypeScript or Python) and fail prompt * assembly when it is absent or has no renderer. Under `ptc`, native names * in `toolOrder` are invalid. @@ -3546,13 +3546,13 @@ export interface Config { 抽象服务类——部署时应改为加载具体的实现包(参见[能力 seam](../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md))。 - `@deepseek-ai/dsh-attachment` — 抽象 `AttachmentStore`([`packages/attachment/attachment/src/index.ts`](../packages/attachment/attachment/src/index.ts)) -- `@deepseek-ai/dsh-code-runtime` — 抽象 `CodeRuntime`([`packages/code-runtime/code-runtime/src/index.ts`](../packages/code-runtime/code-runtime/src/index.ts)) - `@deepseek-ai/dsh-compaction` — 抽象 `CompactionEngine`([`packages/compaction/compaction/src/index.ts`](../packages/compaction/compaction/src/index.ts)) - `@deepseek-ai/dsh-credentials` — 抽象 `Credentials`([`packages/credentials/credentials/src/index.ts`](../packages/credentials/credentials/src/index.ts)) - `@deepseek-ai/dsh-file-reference` — 抽象 `FileReferenceService`([`packages/context/file-reference/src/index.ts`](../packages/context/file-reference/src/index.ts)) - `@deepseek-ai/dsh-fs` — 抽象 `FileSystem`([`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts)) - `@deepseek-ai/dsh-host-directory-picker` — 抽象 `DirectoryPicker`([`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts)) - `@deepseek-ai/dsh-jobs` — 抽象 `JobRegistry`([`packages/jobs/jobs/src/index.ts`](../packages/jobs/jobs/src/index.ts)) +- `@deepseek-ai/dsh-ptc-runtime` — 抽象 `PtcRuntime`([`packages/ptc-runtime/ptc-runtime/src/index.ts`](../packages/ptc-runtime/ptc-runtime/src/index.ts)) - `@deepseek-ai/dsh-sandbox` — 抽象 `SandboxProvider`([`packages/sandbox/sandbox/src/index.ts`](../packages/sandbox/sandbox/src/index.ts)) - `@deepseek-ai/dsh-session-persistence` — 抽象 `SessionPersistence`([`packages/session/session-persistence/src/index.ts`](../packages/session/session-persistence/src/index.ts)) - `@deepseek-ai/dsh-session-query` — 抽象 `SessionQueryEngine`([`packages/session-query/session-query/src/index.ts`](../packages/session-query/session-query/src/index.ts)) diff --git a/docs/cookbook/adding-a-tool.i18n.yaml b/docs/cookbook/adding-a-tool.i18n.yaml index 9aea28f222..cc1209ff9e 100644 --- a/docs/cookbook/adding-a-tool.i18n.yaml +++ b/docs/cookbook/adding-a-tool.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/cookbook/adding-a-tool.md -adding-a-tool.md: d1957fc5419a4f59fe6c2f54fd2a5f5f9c9dbb22 -adding-a-tool.zh.md: 8513ca09fef4548ab8806d489d9f91f5eb22159a +adding-a-tool.md: 659f87bf88ac7fc4b8bc7dd65672c86e6b4326f6 +adding-a-tool.zh.md: 4804c22b22e5761e27c59392d76a322a7407af99 diff --git a/docs/cookbook/adding-a-tool.md b/docs/cookbook/adding-a-tool.md index d1957fc541..659f87bf88 100644 --- a/docs/cookbook/adding-a-tool.md +++ b/docs/cookbook/adding-a-tool.md @@ -92,7 +92,7 @@ The neutral vocabulary lives in `dsh-tools`; tools never import a UI or transpor ## Web Client presentation -The built-in Web Client does not consume `presentCall` or `presentResult`. Session `page` and `follow` transport raw `tool/call` and `tool/result` events, including persisted `result.meta`. A Client plugin registers its wire tool name in the `tool.call.toolview` keyed slot and derives component props from the `ToolCallBlock` arguments, content, error, metadata, existing Code Dispatch `parentCallId`, and Session path facts. It validates these wire values locally and returns the generic row for malformed or unsupported input. +The built-in Web Client does not consume `presentCall` or `presentResult`. Session `page` and `follow` transport raw `tool/call` and `tool/result` events, including persisted `result.meta`. A Client plugin registers its wire tool name in the `tool.call.toolview` keyed slot and derives component props from the `ToolCallBlock` arguments, content, error, metadata, existing PTC dispatch `parentCallId`, and Session path facts. It validates these wire values locally and returns the generic row for malformed or unsupported input. Use `output.presentationMeta(args, value)` when an existing Web card needs bounded structured result facts that model-facing content cannot preserve losslessly. Do not store React props or a selected card in metadata, import a Host tool implementation into a browser bundle, or create another Client presenter registry. Defining Host presentation methods alone does not add a specialized Web card. The [Client-derived presentation Agent Note](../../.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md) defines ownership, fallback, and equivalence requirements. diff --git a/docs/cookbook/adding-a-tool.zh.md b/docs/cookbook/adding-a-tool.zh.md index 8513ca09fe..4804c22b22 100644 --- a/docs/cookbook/adding-a-tool.zh.md +++ b/docs/cookbook/adding-a-tool.zh.md @@ -94,7 +94,7 @@ producer 提供同步的 `cancel`、在资源清理后 settle 且不 reject 的 ## Web Client 展示 -内置 Web Client 不消费 `presentCall` 或 `presentResult`。Session `page` 与 `follow` 运输原始 `tool/call` 和 `tool/result` 事件,包括持久化的 `result.meta`。Client 插件在 keyed slot `tool.call.toolview` 中注册自己的 wire 工具名称,并从 `ToolCallBlock` 的参数、内容、错误、metadata、现有 Code Dispatch `parentCallId` 与 Session 路径事实派生组件 props。插件在本地校验这些 wire 值,并让格式错误或不受支持的输入回退到 generic 行。 +内置 Web Client 不消费 `presentCall` 或 `presentResult`。Session `page` 与 `follow` 运输原始 `tool/call` 和 `tool/result` 事件,包括持久化的 `result.meta`。Client 插件在 keyed slot `tool.call.toolview` 中注册自己的 wire 工具名称,并从 `ToolCallBlock` 的参数、内容、错误、metadata、现有 PTC dispatch `parentCallId` 与 Session 路径事实派生组件 props。插件在本地校验这些 wire 值,并让格式错误或不受支持的输入回退到 generic 行。 现有 Web 卡片需要模型可见内容无法无损保存的有界结构化结果事实时,使用 `output.presentationMeta(args, value)`。不要在 metadata 中保存 React props 或预选卡片,不要把 Host 工具实现导入浏览器 bundle,也不要建立另一套 Client presenter registry。只定义 Host 展示方法不会增加专用 Web 卡片。[Client 派生展示 Agent Note](../../.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md)规定 owner、fallback 与对等要求。 diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index 3ef936586a..c0fad973ab 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: b06e5f18607d104f8c7e008da878ae9d58258c47 -module-graph.zh.md: 0b31ebeb97d1b388f698703461dbedddbc9ada5b +module-graph.md: df83828143fad0291ccf5f8e2537f308e52cacaa +module-graph.zh.md: 2ceba7c9176346a956f42c469babd5cc4dd0b1d7 diff --git a/docs/module-graph.md b/docs/module-graph.md index b06e5f1860..df83828143 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -187,10 +187,6 @@ flowchart TD pkg_client_ui_workspace["client-ui-workspace"] pkg_client_web["client-web"] end - subgraph group_code_runtime["packages/code-runtime"] - pkg_code_runtime["code-runtime"] - pkg_code_runtime_node["code-runtime-node"] - end subgraph group_compaction["packages/compaction"] pkg_command_compact["command-compact"] pkg_compaction["compaction"] @@ -215,8 +211,8 @@ flowchart TD pkg_experimental_agent_team_profile["experimental-agent-team-profile"] pkg_experimental_agent_team_web_profile["experimental-agent-team-web-profile"] pkg_experimental_client_ui_agent_team["experimental-client-ui-agent-team"] - pkg_experimental_code_runtime_python["experimental-code-runtime-python"] pkg_experimental_inspector["experimental-inspector"] + pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"] pkg_experimental_tool_agent_team["experimental-tool-agent-team"] pkg_experimental_webworker_packer["experimental-webworker-packer"] pkg_experimental_webworker_runtime["experimental-webworker-runtime"] @@ -272,6 +268,10 @@ flowchart TD pkg_agent_presets["agent-presets"] pkg_persona["persona"] end + subgraph group_ptc_runtime["packages/ptc-runtime"] + pkg_ptc_runtime["ptc-runtime"] + pkg_ptc_runtime_node["ptc-runtime-node"] + end subgraph group_runtime_diagnostics["packages/runtime-diagnostics"] pkg_invariants["invariants"] end @@ -467,7 +467,7 @@ flowchart TD pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence - pkg_code_runtime --> pkg_sandbox + pkg_ptc_runtime --> pkg_sandbox pkg_sandbox_local --> pkg_llm pkg_sandbox_local --> pkg_sandbox pkg_sandbox_local --> pkg_session @@ -562,9 +562,9 @@ flowchart TD pkg_tmux_context --> pkg_session pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell - pkg_experimental_code_runtime_python --> pkg_code_runtime - pkg_experimental_code_runtime_python --> pkg_timeout - pkg_experimental_code_runtime_python --> pkg_util_values + pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime + pkg_experimental_ptc_runtime_python --> pkg_timeout + pkg_experimental_ptc_runtime_python --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -627,9 +627,9 @@ flowchart TD pkg_workflow --> pkg_llm pkg_workflow --> pkg_session pkg_tools --> pkg_agent - pkg_tools --> pkg_code_runtime pkg_tools --> pkg_invariants pkg_tools --> pkg_llm + pkg_tools --> pkg_ptc_runtime pkg_tools --> pkg_sandbox pkg_tools --> pkg_sandbox_policy pkg_tools --> pkg_scope @@ -648,13 +648,6 @@ flowchart TD pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_code_runtime_node --> pkg_code_runtime - pkg_code_runtime_node --> pkg_fs - pkg_code_runtime_node --> pkg_sandbox - pkg_code_runtime_node --> pkg_sandbox_policy - pkg_code_runtime_node --> pkg_session - pkg_code_runtime_node --> pkg_subprocess - pkg_code_runtime_node --> pkg_timeout pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_invariants @@ -677,6 +670,13 @@ flowchart TD pkg_jobs_local --> pkg_jobs pkg_jobs_local --> pkg_scope pkg_jobs_local --> pkg_timeout + pkg_ptc_runtime_node --> pkg_fs + pkg_ptc_runtime_node --> pkg_ptc_runtime + pkg_ptc_runtime_node --> pkg_sandbox + pkg_ptc_runtime_node --> pkg_sandbox_policy + pkg_ptc_runtime_node --> pkg_session + pkg_ptc_runtime_node --> pkg_subprocess + pkg_ptc_runtime_node --> pkg_timeout pkg_session_title_llm --> pkg_llm pkg_session_title_llm --> pkg_session pkg_session_title_llm --> pkg_session_title @@ -1349,7 +1349,7 @@ flowchart TD | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | -| [`code-runtime`](../packages/code-runtime/code-runtime) | `code-runtime` | [`sandbox`](../packages/sandbox/sandbox) | +| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) | @@ -1372,7 +1372,7 @@ flowchart TD | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`experimental-code-runtime-python`](../packages/experimental/code-runtime-python) | `experimental` | [`code-runtime`](../packages/code-runtime/code-runtime), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | +| [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | @@ -1386,15 +1386,15 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | +| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`code-runtime-node`](../packages/code-runtime/code-runtime-node) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`user-approval`](../packages/interaction/user-approval) | | [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | +| [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node) | `ptc-runtime` | [`fs`](../packages/fs/fs), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 0b31ebeb97..2ceba7c917 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -189,10 +189,6 @@ flowchart TD pkg_client_ui_workspace["client-ui-workspace"] pkg_client_web["client-web"] end - subgraph group_code_runtime["packages/code-runtime"] - pkg_code_runtime["code-runtime"] - pkg_code_runtime_node["code-runtime-node"] - end subgraph group_compaction["packages/compaction"] pkg_command_compact["command-compact"] pkg_compaction["compaction"] @@ -217,8 +213,8 @@ flowchart TD pkg_experimental_agent_team_profile["experimental-agent-team-profile"] pkg_experimental_agent_team_web_profile["experimental-agent-team-web-profile"] pkg_experimental_client_ui_agent_team["experimental-client-ui-agent-team"] - pkg_experimental_code_runtime_python["experimental-code-runtime-python"] pkg_experimental_inspector["experimental-inspector"] + pkg_experimental_ptc_runtime_python["experimental-ptc-runtime-python"] pkg_experimental_tool_agent_team["experimental-tool-agent-team"] pkg_experimental_webworker_packer["experimental-webworker-packer"] pkg_experimental_webworker_runtime["experimental-webworker-runtime"] @@ -274,6 +270,10 @@ flowchart TD pkg_agent_presets["agent-presets"] pkg_persona["persona"] end + subgraph group_ptc_runtime["packages/ptc-runtime"] + pkg_ptc_runtime["ptc-runtime"] + pkg_ptc_runtime_node["ptc-runtime-node"] + end subgraph group_runtime_diagnostics["packages/runtime-diagnostics"] pkg_invariants["invariants"] end @@ -469,7 +469,7 @@ flowchart TD pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence - pkg_code_runtime --> pkg_sandbox + pkg_ptc_runtime --> pkg_sandbox pkg_sandbox_local --> pkg_llm pkg_sandbox_local --> pkg_sandbox pkg_sandbox_local --> pkg_session @@ -564,9 +564,9 @@ flowchart TD pkg_tmux_context --> pkg_session pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell - pkg_experimental_code_runtime_python --> pkg_code_runtime - pkg_experimental_code_runtime_python --> pkg_timeout - pkg_experimental_code_runtime_python --> pkg_util_values + pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime + pkg_experimental_ptc_runtime_python --> pkg_timeout + pkg_experimental_ptc_runtime_python --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -629,9 +629,9 @@ flowchart TD pkg_workflow --> pkg_llm pkg_workflow --> pkg_session pkg_tools --> pkg_agent - pkg_tools --> pkg_code_runtime pkg_tools --> pkg_invariants pkg_tools --> pkg_llm + pkg_tools --> pkg_ptc_runtime pkg_tools --> pkg_sandbox pkg_tools --> pkg_sandbox_policy pkg_tools --> pkg_scope @@ -650,13 +650,6 @@ flowchart TD pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_code_runtime_node --> pkg_code_runtime - pkg_code_runtime_node --> pkg_fs - pkg_code_runtime_node --> pkg_sandbox - pkg_code_runtime_node --> pkg_sandbox_policy - pkg_code_runtime_node --> pkg_session - pkg_code_runtime_node --> pkg_subprocess - pkg_code_runtime_node --> pkg_timeout pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_invariants @@ -679,6 +672,13 @@ flowchart TD pkg_jobs_local --> pkg_jobs pkg_jobs_local --> pkg_scope pkg_jobs_local --> pkg_timeout + pkg_ptc_runtime_node --> pkg_fs + pkg_ptc_runtime_node --> pkg_ptc_runtime + pkg_ptc_runtime_node --> pkg_sandbox + pkg_ptc_runtime_node --> pkg_sandbox_policy + pkg_ptc_runtime_node --> pkg_session + pkg_ptc_runtime_node --> pkg_subprocess + pkg_ptc_runtime_node --> pkg_timeout pkg_session_title_llm --> pkg_llm pkg_session_title_llm --> pkg_session pkg_session_title_llm --> pkg_session_title @@ -1351,7 +1351,7 @@ flowchart TD | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | -| [`code-runtime`](../packages/code-runtime/code-runtime) | `code-runtime` | [`sandbox`](../packages/sandbox/sandbox) | +| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) | @@ -1374,7 +1374,7 @@ flowchart TD | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`experimental-code-runtime-python`](../packages/experimental/code-runtime-python) | `experimental` | [`code-runtime`](../packages/code-runtime/code-runtime), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | +| [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | @@ -1388,15 +1388,15 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | +| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`code-runtime-node`](../packages/code-runtime/code-runtime-node) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`user-approval`](../packages/interaction/user-approval) | | [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | +| [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node) | `ptc-runtime` | [`fs`](../packages/fs/fs), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | diff --git a/docs/subsystems/README.i18n.yaml b/docs/subsystems/README.i18n.yaml index 14804f99f7..d64b6b4a7f 100644 --- a/docs/subsystems/README.i18n.yaml +++ b/docs/subsystems/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/README.md -README.md: 55777b67508469dcaa0139cddd73b5101616b902 -README.zh.md: f58eef405fa22bcebce4996ec392d5ffc6e87b1b +README.md: a2f3b1e0d0f0078d04b8542292a9f6a6bf0a4325 +README.zh.md: 93228fb5cb3094e574facf74bf530e7168198842 diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index 55777b6750..a2f3b1e0d0 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -33,7 +33,7 @@ One page per subsystem of the DeepSeek Harness: what it is, the data structures | [ssh.md](ssh.md) | the POSIX SSH connection and remote filesystem, subprocess and sandbox providers | | [terminal.md](terminal.md) | persistent terminal ids, backend/session contracts, send readiness, bounded reads, and owner-visible snapshots | | [sandbox.md](sandbox.md) | per-session policy resolution and the process-confinement seam: file-effect modes, execution/provider policies, `ConfinedArgv`, enforcement and fail-closed errors | -| [code-runtime.md](code-runtime.md) | the code-execution seam: `CodeRunRequest`/`Result`, binding namespaces, captured logs, the `CodeRunFailure` taxonomy | +| [ptc-runtime.md](ptc-runtime.md) | the code-execution seam: `PtcRunRequest`/`Result`, binding namespaces, captured logs, the `PtcRunFailure` taxonomy | | [extensions.md](extensions.md) | versioned dynamic Cordis Plugins and Packages, Host/Client activation, approval, runtime inspection, and lifecycle teardown | | [filesystem.md](filesystem.md) | the filesystem seam: `FsTarget`, read/write/edit outcomes, observed-file state, `FsErrorCode` | | [lsp.md](lsp.md) | the LSP navigation seam: `LspQueryRequest`/`Result`, `LspProvider`/`Service`, four operations, `LspError` | diff --git a/docs/subsystems/README.zh.md b/docs/subsystems/README.zh.md index f58eef405f..93228fb5cb 100644 --- a/docs/subsystems/README.zh.md +++ b/docs/subsystems/README.zh.md @@ -33,7 +33,7 @@ | [ssh.md](ssh.zh.md) | POSIX SSH 连接与远程文件系统、子进程和沙箱提供方 | | [terminal.md](terminal.zh.md) | 持久化终端 ID、后端/会话约定、发送就绪状态、有界读取与 owner 可见快照 | | [sandbox.md](sandbox.zh.md) | 每会话策略解析与进程约束 seam:文件效果模式、执行/提供方策略、`ConfinedArgv`、强制执行与故障关闭错误 | -| [code-runtime.md](code-runtime.zh.md) | 代码执行 seam:`CodeRunRequest`/`Result`、绑定命名空间、捕获日志、`CodeRunFailure` 分类体系 | +| [ptc-runtime.md](ptc-runtime.zh.md) | 代码执行 seam:`PtcRunRequest`/`Result`、绑定命名空间、捕获日志、`PtcRunFailure` 分类体系 | | [extensions.md](extensions.zh.md) | 带版本的动态 Cordis 插件与包、Host/Client 激活、审批、运行时检查和生命周期清理 | | [filesystem.md](filesystem.zh.md) | 文件系统 seam:`FsTarget`、读/写/编辑结果、观测到的文件状态、`FsErrorCode` | | [lsp.md](lsp.zh.md) | LSP 导航 seam:`LspQueryRequest`/`Result`、`LspProvider`/`Service`、四种操作、`LspError` | diff --git a/docs/subsystems/code-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml similarity index 69% rename from docs/subsystems/code-runtime.i18n.yaml rename to docs/subsystems/ptc-runtime.i18n.yaml index e19e14e90e..0a5d51f423 100644 --- a/docs/subsystems/code-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/subsystems/code-runtime.md -code-runtime.md: 19eb28750cddc6b2660d74f24927f65888ba175e -code-runtime.zh.md: a8fa809846f5ecb57c1bf29fc30f53b42c5b4fdf +# pnpm run verify-translation-pairing --write docs/subsystems/ptc-runtime.md +ptc-runtime.md: 98032c564954bdae3f8f940b6d6246d36560ca0c +ptc-runtime.zh.md: 15e64cace278b9ddea541f5d821785aba2c1ace1 diff --git a/docs/subsystems/code-runtime.md b/docs/subsystems/ptc-runtime.md similarity index 65% rename from docs/subsystems/code-runtime.md rename to docs/subsystems/ptc-runtime.md index 19eb28750c..98032c5649 100644 --- a/docs/subsystems/code-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -1,30 +1,30 @@ -# Code Runtime +# PTC runtime -English | [中文](code-runtime.zh.md) +English | [中文](ptc-runtime.zh.md) -The code-execution [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) supplies `ctx.codeRuntime` through [dsh-code-runtime](../../packages/code-runtime/code-runtime). It runs one program against host bindings and reports output, failure and applicable sandbox facts. Code execution is optional rather than part of [the agent-loop spine](core.md). The [PTC foundation](../../.agents/notes/implemented/feature/2026-06-15-ptc.md) owns registry presentation, the [typed-return contract](../../.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md) owns binding values, and the [sandboxed Node decision](../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md) owns the shipped execution provider. +The PTC execution [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) supplies `ctx.ptcRuntime` through [dsh-ptc-runtime](../../packages/ptc-runtime/ptc-runtime). It runs one program against host bindings and reports output, failure and applicable sandbox facts. PTC execution is optional rather than part of [the agent-loop spine](core.md). The [PTC foundation](../../.agents/notes/implemented/feature/2026-06-15-ptc.md) owns registry presentation, the [typed-return contract](../../.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md) owns binding values, and the [sandboxed Node decision](../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md) owns the shipped execution provider. -Source: [`packages/code-runtime/code-runtime/src/types.ts`](../../packages/code-runtime/code-runtime/src/types.ts) +Source: [`packages/ptc-runtime/ptc-runtime/src/types.ts`](../../packages/ptc-runtime/ptc-runtime/src/types.ts) ## The run: request in, result out -`CodeRunRequest` contains the program, bindings, cancellation and optional execution choices. The provider's `resolve` validates supported choices and applies its deployment defaults; `run` receives a `CodeRunSpec` with an explicit directory and deadline. A provider that cannot enforce a requested policy rejects it before program execution: +`PtcRunRequest` contains the program, bindings, cancellation and optional execution choices. The provider's `resolve` validates supported choices and applies its deployment defaults; `run` receives a `PtcRunSpec` with an explicit directory and deadline. A provider that cannot enforce a requested policy rejects it before program execution: ```ts type-equiv /** * Caller inputs for one program. The provider's resolve method validates supported * options and supplies directory, deadline, and authority before execution. */ -interface CodeRunRequest { +interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * runs as the body of an async function: top-level `await` and `return` * are available, and the completion value becomes - * {@link CodeRunResult.value}. + * {@link PtcRunResult.value}. */ program: string /** Host functions exposed to the program, one global object per namespace. */ - bindings: CodeBindingNamespace[] + bindings: PtcBindingNamespace[] /** Working directory in the mounted filesystem and subprocess execution world. */ cwd?: string /** Requested elapsed execution time; the provider's resolver validates and caps it. */ @@ -33,7 +33,7 @@ interface CodeRunRequest { sandboxPolicy?: SandboxExecutionPolicy /** * Abort the run: the runtime stops the program (hard, even mid-loop) and - * resolves with a {@link CodeRunFailure} of kind `'abort'`. In-flight + * resolves with a {@link PtcRunFailure} of kind `'abort'`. In-flight * binding calls are the CALLER's to settle — the runtime only stops asking. */ signal?: AbortSignal @@ -42,7 +42,7 @@ interface CodeRunRequest { ```ts type-equiv /** Fully resolved execution inputs; run never supplies a missing directory or timeout. */ -interface CodeRunSpec extends CodeRunRequest { +interface PtcRunSpec extends PtcRunRequest { /** Absolute directory in the provider's execution world. */ cwd: string /** Positive finite execution deadline in milliseconds, after provider capping. */ @@ -52,7 +52,7 @@ interface CodeRunSpec extends CodeRunRequest { ```ts type-equiv /** File confinement applied to a program, independently of its terminal outcome. */ -interface CodeRunSandbox { +interface PtcRunSandbox { /** File-effect mode used for this execution. */ mode: SandboxMode /** Program failure text matched backend diagnostics; not enforcement proof or an exhaustive denial record. */ @@ -62,7 +62,7 @@ interface CodeRunSandbox { } ``` -Program failures resolve through `CodeRunResult.error`; invalid caller inputs may reject before execution. Sandbox mode, observed denial and enforcement completeness are separate facts, so a successful program does not by itself prove that every requested restriction was enforced: +Program failures resolve through `PtcRunResult.error`; invalid caller inputs may reject before execution. Sandbox mode, observed denial and enforcement completeness are separate facts, so a successful program does not by itself prove that every requested restriction was enforced: ```ts type-equiv /** @@ -70,30 +70,30 @@ Program failures resolve through `CodeRunResult.error`; invalid caller inputs ma * rejection of `run()` — reporting a failed program is the caller's job, not * an exception path. */ -interface CodeRunResult { +interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ - sandbox?: CodeRunSandbox + sandbox?: PtcRunSandbox /** * The program's completion value (its top-level `return`), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. */ - value?: CodeJsonValue + value?: PtcJsonValue /** * Captured text. Each source channel preserves emission order; interleaving * across independent channels is backend-dependent. Bounded only as part of * the outer result. */ logs: string[] - /** Present iff the run failed; see {@link CodeRunFailure} for the taxonomy. */ - error?: CodeRunFailure + /** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */ + error?: PtcRunFailure } ``` ## Bindings: host functions as program globals -Each `CodeBindingNamespace` 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. 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 /** @@ -103,8 +103,8 @@ Each `CodeBindingNamespace` becomes a global object of async callables; PTC pass * `memberNameProperty`. Both strings are runtime data rather than knowledge * of a particular consumer such as PTC mode. */ -interface CodeBindingErrorClass { - /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link CodeBindingNamespace.global}. */ +interface PtcBindingErrorClass { + /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link PtcBindingNamespace.global}. */ name: string /** * Non-empty own property for the member name. The portable exclusion set is @@ -118,13 +118,13 @@ interface CodeBindingErrorClass { ```ts type-equiv /** - * A named group of {@link CodeBindingFunction}s the runtime exposes to the + * A named group of {@link PtcBindingFunction}s the runtime exposes to the * program as one global object (e.g. `tools`). Function names are arbitrary * strings — a runtime must treat names like `__proto__` or `constructor` as * ordinary own properties (null-prototype construction), never as prototype * collisions. */ -interface CodeBindingNamespace { +interface PtcBindingNamespace { /** * The global identifier the program sees. Must match the LANGUAGE-PORTABLE * identifier subset `[A-Za-z_][A-Za-z0-9_]*` and no language's reserved @@ -137,15 +137,15 @@ interface CodeBindingNamespace { */ global: string /** The callable members, keyed by the exact name the program calls. */ - functions: Record + functions: Record /** Optional program-visible typed rejection contract for this namespace. */ - errorClass?: CodeBindingErrorClass + errorClass?: PtcBindingErrorClass } ``` ```ts type-equiv /** A lossless JSON value transferable through the dependency-light Service Definition. */ -type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | { [key: string]: CodeJsonValue } +type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: string]: PtcJsonValue } ``` ```ts type-equiv @@ -158,7 +158,7 @@ type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | { [key * of this function surfaces inside the program as a rejection of the * corresponding call. */ -type CodeBindingFunction = (args: unknown) => Promise +type PtcBindingFunction = (args: unknown) => Promise ``` ## Captured output and the failure taxonomy @@ -175,14 +175,14 @@ Failure kinds are **orthogonal outcomes reported independently** (per [defensive * * - `'exception'` — the program threw or failed to parse/transform. * - `'timeout'` — an implementation-owned budget expired; the message says which. - * - `'abort'` — {@link CodeRunRequest.signal} fired. + * - `'abort'` — {@link PtcRunRequest.signal} fired. * - `'worker-exit'` — the execution substrate died without settling (e.g. OOM). * - `'invalid-output'` — the completion value was not lossless JSON. * - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap. * - `'protocol'` — the program sent invalid or over-budget control traffic. * - `'sandbox-unavailable'` — required confinement could not be established. */ -interface CodeRunFailure { +interface PtcRunFailure { /** The failure class (see the interface doc for each kind's meaning). */ kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit' | 'protocol' | 'sandbox-unavailable' /** Human-readable detail, suitable for feeding back to a model to self-correct. */ @@ -192,7 +192,7 @@ interface CodeRunFailure { ## The service -`CodeRuntime` is defined in [`src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts). `resolve(request)` returns complete execution inputs, and `run(spec)` executes them. `executionInstructions` supplies provider-owned usage guidance for consumer presentation. `timeout` reports the configured elapsed-time default and maximum when per-call overrides are supported; `resolve` still validates and caps each request. `language` selects supported program presentation; `isolation` describes the substrate without claiming security. `sandboxMode` advertises file-policy support, with `undefined` for a provider that does not supply confinement. Each implementation keeps program state separate between runs and terminates and awaits active executions during disposal. +`PtcRuntime` is defined in [`src/index.ts`](../../packages/ptc-runtime/ptc-runtime/src/index.ts). `resolve(request)` returns complete execution inputs, and `run(spec)` executes them. `executionInstructions` supplies provider-owned usage guidance for consumer presentation. `timeout` reports the configured elapsed-time default and maximum when per-call overrides are supported; `resolve` still validates and caps each request. `language` selects supported program presentation; `isolation` describes the substrate without claiming security. `sandboxMode` advertises file-policy support, with `undefined` for a provider that does not supply confinement. Each implementation keeps program state separate between runs and terminates and awaits active executions during disposal. @@ -202,11 +202,11 @@ interface CodeRunFailure { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). - + -### `ctx.codeRuntime` — `CodeRuntime` (abstract seam) +### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam) -Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and substrate failures resolve in CodeRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. +Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. ```ts cordis-catalog /** @@ -215,15 +215,15 @@ Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and subs * @returns Complete directory, deadline and supported authority for run. * @throws When an explicit choice is invalid or unsupported by this provider. */ -abstract resolve(request: CodeRunRequest): CodeRunSpec +abstract resolve(request: PtcRunRequest): PtcRunSpec /** * Execute resolved inputs; program outcomes resolve as result fields. * @param spec - directory, deadline, program, bindings, cancellation and supported policy. * @returns Captured output and the execution outcome. */ -abstract run(spec: CodeRunSpec): Promise +abstract run(spec: PtcRunSpec): Promise ``` -Source: [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts) +Source: [`packages/ptc-runtime/ptc-runtime/src/index.ts`](../../packages/ptc-runtime/ptc-runtime/src/index.ts) diff --git a/docs/subsystems/code-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md similarity index 66% rename from docs/subsystems/code-runtime.zh.md rename to docs/subsystems/ptc-runtime.zh.md index a8fa809846..15e64cace2 100644 --- a/docs/subsystems/code-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -1,30 +1,30 @@ -# 代码运行时 +# PTC 运行时 -[English](code-runtime.md) | 中文 +[English](ptc-runtime.md) | 中文 -代码执行[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)通过 [dsh-code-runtime](../../packages/code-runtime/code-runtime) 提供 `ctx.codeRuntime`。它针对 Host 绑定运行一个程序,报告输出、失败与适用的沙箱事实。代码执行是可选能力,不属于[智能体循环主干](core.zh.md)。[PTC 基础](../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)负责注册表呈现,[类型化返回约定](../../.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md)负责绑定值,[沙箱 Node 决策](../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.zh.md)负责已发布的执行提供方。 +PTC 执行[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)通过 [dsh-ptc-runtime](../../packages/ptc-runtime/ptc-runtime) 提供 `ctx.ptcRuntime`。它针对 Host 绑定运行一个程序,报告输出、失败与适用的沙箱事实。PTC 执行是可选能力,不属于[智能体循环主干](core.zh.md)。[PTC 基础](../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)负责注册表呈现,[类型化返回约定](../../.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md)负责绑定值,[沙箱 Node 决策](../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责已发布的执行提供方。 -源码:[`packages/code-runtime/code-runtime/src/types.ts`](../../packages/code-runtime/code-runtime/src/types.ts) +源码:[`packages/ptc-runtime/ptc-runtime/src/types.ts`](../../packages/ptc-runtime/ptc-runtime/src/types.ts) ## 运行:请求进,结果出 -`CodeRunRequest` 包含程序、绑定、取消和可选执行选择。提供方的 `resolve` 验证支持的选择并应用部署默认值;`run` 接收目录与截止时间明确的 `CodeRunSpec`。无法强制执行所请求策略的提供方在程序执行前拒绝请求: +`PtcRunRequest` 包含程序、绑定、取消和可选执行选择。提供方的 `resolve` 验证支持的选择并应用部署默认值;`run` 接收目录与截止时间明确的 `PtcRunSpec`。无法强制执行所请求策略的提供方在程序执行前拒绝请求: ```ts type-equiv /** * Caller inputs for one program. The provider's resolve method validates supported * options and supplies directory, deadline, and authority before execution. */ -interface CodeRunRequest { +interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * runs as the body of an async function: top-level `await` and `return` * are available, and the completion value becomes - * {@link CodeRunResult.value}. + * {@link PtcRunResult.value}. */ program: string /** Host functions exposed to the program, one global object per namespace. */ - bindings: CodeBindingNamespace[] + bindings: PtcBindingNamespace[] /** Working directory in the mounted filesystem and subprocess execution world. */ cwd?: string /** Requested elapsed execution time; the provider's resolver validates and caps it. */ @@ -33,7 +33,7 @@ interface CodeRunRequest { sandboxPolicy?: SandboxExecutionPolicy /** * Abort the run: the runtime stops the program (hard, even mid-loop) and - * resolves with a {@link CodeRunFailure} of kind `'abort'`. In-flight + * resolves with a {@link PtcRunFailure} of kind `'abort'`. In-flight * binding calls are the CALLER's to settle — the runtime only stops asking. */ signal?: AbortSignal @@ -42,7 +42,7 @@ interface CodeRunRequest { ```ts type-equiv /** Fully resolved execution inputs; run never supplies a missing directory or timeout. */ -interface CodeRunSpec extends CodeRunRequest { +interface PtcRunSpec extends PtcRunRequest { /** Absolute directory in the provider's execution world. */ cwd: string /** Positive finite execution deadline in milliseconds, after provider capping. */ @@ -52,7 +52,7 @@ interface CodeRunSpec extends CodeRunRequest { ```ts type-equiv /** File confinement applied to a program, independently of its terminal outcome. */ -interface CodeRunSandbox { +interface PtcRunSandbox { /** File-effect mode used for this execution. */ mode: SandboxMode /** Program failure text matched backend diagnostics; not enforcement proof or an exhaustive denial record. */ @@ -62,7 +62,7 @@ interface CodeRunSandbox { } ``` -程序失败通过 `CodeRunResult.error` 返回;无效调用输入可能在执行前拒绝。沙箱模式、观察到的拒绝与强制完整性是独立事实,因此程序成功本身不能证明每项请求限制均已强制执行: +程序失败通过 `PtcRunResult.error` 返回;无效调用输入可能在执行前拒绝。沙箱模式、观察到的拒绝与强制完整性是独立事实,因此程序成功本身不能证明每项请求限制均已强制执行: ```ts type-equiv /** @@ -70,30 +70,30 @@ interface CodeRunSandbox { * rejection of `run()` — reporting a failed program is the caller's job, not * an exception path. */ -interface CodeRunResult { +interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ - sandbox?: CodeRunSandbox + sandbox?: PtcRunSandbox /** * The program's completion value (its top-level `return`), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. */ - value?: CodeJsonValue + value?: PtcJsonValue /** * Captured text. Each source channel preserves emission order; interleaving * across independent channels is backend-dependent. Bounded only as part of * the outer result. */ logs: string[] - /** Present iff the run failed; see {@link CodeRunFailure} for the taxonomy. */ - error?: CodeRunFailure + /** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */ + error?: PtcRunFailure } ``` ## 绑定:宿主函数作为程序全局变量 -每个 `CodeBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: +每个 `PtcBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: ```ts type-equiv /** @@ -103,8 +103,8 @@ interface CodeRunResult { * `memberNameProperty`. Both strings are runtime data rather than knowledge * of a particular consumer such as PTC mode. */ -interface CodeBindingErrorClass { - /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link CodeBindingNamespace.global}. */ +interface PtcBindingErrorClass { + /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link PtcBindingNamespace.global}. */ name: string /** * Non-empty own property for the member name. The portable exclusion set is @@ -118,13 +118,13 @@ interface CodeBindingErrorClass { ```ts type-equiv /** - * A named group of {@link CodeBindingFunction}s the runtime exposes to the + * A named group of {@link PtcBindingFunction}s the runtime exposes to the * program as one global object (e.g. `tools`). Function names are arbitrary * strings — a runtime must treat names like `__proto__` or `constructor` as * ordinary own properties (null-prototype construction), never as prototype * collisions. */ -interface CodeBindingNamespace { +interface PtcBindingNamespace { /** * The global identifier the program sees. Must match the LANGUAGE-PORTABLE * identifier subset `[A-Za-z_][A-Za-z0-9_]*` and no language's reserved @@ -137,15 +137,15 @@ interface CodeBindingNamespace { */ global: string /** The callable members, keyed by the exact name the program calls. */ - functions: Record + functions: Record /** Optional program-visible typed rejection contract for this namespace. */ - errorClass?: CodeBindingErrorClass + errorClass?: PtcBindingErrorClass } ``` ```ts type-equiv /** A lossless JSON value transferable through the dependency-light Service Definition. */ -type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | { [key: string]: CodeJsonValue } +type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: string]: PtcJsonValue } ``` ```ts type-equiv @@ -158,7 +158,7 @@ type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | { [key * of this function surfaces inside the program as a rejection of the * corresponding call. */ -type CodeBindingFunction = (args: unknown) => Promise +type PtcBindingFunction = (args: unknown) => Promise ``` ## 捕获的输出与失败分类体系 @@ -175,14 +175,14 @@ type CodeBindingFunction = (args: unknown) => Promise * * - `'exception'` — the program threw or failed to parse/transform. * - `'timeout'` — an implementation-owned budget expired; the message says which. - * - `'abort'` — {@link CodeRunRequest.signal} fired. + * - `'abort'` — {@link PtcRunRequest.signal} fired. * - `'worker-exit'` — the execution substrate died without settling (e.g. OOM). * - `'invalid-output'` — the completion value was not lossless JSON. * - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap. * - `'protocol'` — the program sent invalid or over-budget control traffic. * - `'sandbox-unavailable'` — required confinement could not be established. */ -interface CodeRunFailure { +interface PtcRunFailure { /** The failure class (see the interface doc for each kind's meaning). */ kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit' | 'protocol' | 'sandbox-unavailable' /** Human-readable detail, suitable for feeding back to a model to self-correct. */ @@ -192,7 +192,7 @@ interface CodeRunFailure { ## 服务 -`CodeRuntime` 定义于 [`src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts)。`resolve(request)` 返回完整执行输入,`run(spec)` 执行它们。`executionInstructions` 提供由运行时拥有的使用说明,供消费方呈现。支持逐次覆盖时,`timeout` 报告配置的经过时间默认值和上限;每次请求仍由 `resolve` 验证并截断。`language` 选择支持的程序呈现;`isolation` 描述执行基底,不作安全声明。`sandboxMode` 声明文件策略支持,不提供约束的提供方返回 `undefined`。每个实现将各次运行的程序状态分离,并在资源释放期间终止且等待活跃执行。 +`PtcRuntime` 定义于 [`src/index.ts`](../../packages/ptc-runtime/ptc-runtime/src/index.ts)。`resolve(request)` 返回完整执行输入,`run(spec)` 执行它们。`executionInstructions` 提供由运行时拥有的使用说明,供消费方呈现。支持逐次覆盖时,`timeout` 报告配置的经过时间默认值和上限;每次请求仍由 `resolve` 验证并截断。`language` 选择支持的程序呈现;`isolation` 描述执行基底,不作安全声明。`sandboxMode` 声明文件策略支持,不提供约束的提供方返回 `undefined`。每个实现将各次运行的程序状态分离,并在资源释放期间终止且等待活跃执行。 @@ -202,11 +202,11 @@ interface CodeRunFailure { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). - + -### `ctx.codeRuntime` — `CodeRuntime` (abstract seam) +### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam) -Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and substrate failures resolve in CodeRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. +Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. ```ts cordis-catalog /** @@ -215,15 +215,15 @@ Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and subs * @returns Complete directory, deadline and supported authority for run. * @throws When an explicit choice is invalid or unsupported by this provider. */ -abstract resolve(request: CodeRunRequest): CodeRunSpec +abstract resolve(request: PtcRunRequest): PtcRunSpec /** * Execute resolved inputs; program outcomes resolve as result fields. * @param spec - directory, deadline, program, bindings, cancellation and supported policy. * @returns Captured output and the execution outcome. */ -abstract run(spec: CodeRunSpec): Promise +abstract run(spec: PtcRunSpec): Promise ``` -Source: [`packages/code-runtime/code-runtime/src/index.ts`](../../packages/code-runtime/code-runtime/src/index.ts) +Source: [`packages/ptc-runtime/ptc-runtime/src/index.ts`](../../packages/ptc-runtime/ptc-runtime/src/index.ts) diff --git a/docs/subsystems/ssh.i18n.yaml b/docs/subsystems/ssh.i18n.yaml index 843a245941..c6fb295188 100644 --- a/docs/subsystems/ssh.i18n.yaml +++ b/docs/subsystems/ssh.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/ssh.md -ssh.md: 37110a6de59e19fc14ec2583c6f3f8c320c339f6 -ssh.zh.md: 6ae088a0f249474572fd98768019221864280c8a +ssh.md: 04480e6ec397490f2e61851c956b9d318c1ef54f +ssh.zh.md: b6906921353ea7cf8c6906aba6c0ebe98b0e6bb7 diff --git a/docs/subsystems/ssh.md b/docs/subsystems/ssh.md index 37110a6de5..04480e6ec3 100644 --- a/docs/subsystems/ssh.md +++ b/docs/subsystems/ssh.md @@ -8,7 +8,7 @@ The [SSH provider family](../../packages/ssh/README.md) supplies one remote file Filesystem identities, executable lookup, process cwd, sandbox workspace roots and language-server file URLs refer to the SSH host. Providers canonicalize paths where the files exist, preserving filesystem interpretation of `symlink/..`. The policy resolver carries absolute execution-world spelling without trying to resolve remote paths on the Harness host. -`processPath()` supplies a path usable by the paired subprocess provider. `processPathFromHostPath()` remains unavailable for SSH; installing a remote artifact does not make an arbitrary host path portable. [`NodeCodeRuntime`](../../packages/code-runtime/code-runtime-node/README.md) therefore takes an explicitly installed, digest-verified remote bootstrap. +`processPath()` supplies a path usable by the paired subprocess provider. `processPathFromHostPath()` remains unavailable for SSH; installing a remote artifact does not make an arbitrary host path portable. [`NodePtcRuntime`](../../packages/ptc-runtime/ptc-runtime-node/README.md) therefore takes an explicitly installed, digest-verified remote bootstrap. ## Transport and trust @@ -20,7 +20,7 @@ Deployment authentication, installed artifact verification and per-stream TLS au A process is reserved before its streams are connected, and launch is accepted at most once. `done` reports the direct result; `waitForExit` observes the remote managed range. Terminal operations retain the asynchronous shared API. Preparation cancellation, launched-process termination and provider disposal release their owned resources through the helper. -Administrative deadlines bound individual RPC observations; they do not replace the execution deadline chosen by a Bash or code-runtime consumer. Remote waits can remain pending while other requests progress. SSH loss invalidates pending operations; helper EOF, signals and lease expiry start remote cleanup. The client reports unconfirmed outcomes honestly and never reconnects to replay a possibly executed action. +Administrative deadlines bound individual RPC observations; they do not replace the execution deadline chosen by a Bash or ptc-runtime consumer. Remote waits can remain pending while other requests progress. SSH loss invalidates pending operations; helper EOF, signals and lease expiry start remote cleanup. The client reports unconfirmed outcomes honestly and never reconnects to replay a possibly executed action. ## Composition scope @@ -67,7 +67,7 @@ declare class SshConnection extends Service { constructor(ctx: Context, config: Config); /** Hold plugin readiness until the remote identity and helper digest are verified. */ async [Service.init](): Promise; - /** Verified remote Node executable for the paired code runtime. */ + /** Verified remote Node executable for the paired PTC runtime. */ get nodeExecutable(): string; /** Verified preinstalled PTC entry; unconfigured runtimes fail before program execution. */ get bootstrapPath(): string; diff --git a/docs/subsystems/ssh.zh.md b/docs/subsystems/ssh.zh.md index 6ae088a0f2..b690692135 100644 --- a/docs/subsystems/ssh.zh.md +++ b/docs/subsystems/ssh.zh.md @@ -8,7 +8,7 @@ 文件系统身份、可执行文件查找、进程 cwd、沙箱工作区根目录及语言服务器文件 URL 都指向 SSH 主机。提供方在文件实际存在的位置规范化路径,保留文件系统对 `symlink/..` 的解释。策略解析器保留执行环境中的绝对路径写法,不尝试在 Harness 主机上解析远端路径。 -`processPath()` 提供配套子进程提供方可用的路径。SSH 的 `processPathFromHostPath()` 仍不可用;安装远端产物不意味着任意主机路径可移植。因此 [`NodeCodeRuntime`](../../packages/code-runtime/code-runtime-node/README.zh.md) 使用显式安装并经过摘要验证的远端引导程序。 +`processPath()` 提供配套子进程提供方可用的路径。SSH 的 `processPathFromHostPath()` 仍不可用;安装远端产物不意味着任意主机路径可移植。因此 [`NodePtcRuntime`](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md) 使用显式安装并经过摘要验证的远端引导程序。 ## 传输与信任 @@ -20,7 +20,7 @@ 进程先预留,再连接流,且启动最多接受一次。`done` 报告直接结果,`waitForExit` 观察远端托管进程范围。终端操作保留共享异步 API。准备阶段取消、已启动进程终止及提供方释放都通过辅助进程释放各自资源。 -管理截止时限约束单次 RPC 观察,不替代 Bash 或代码运行时消费方选择的执行截止时限。远端等待可以持续挂起,同时其他请求继续推进。SSH 丢失会使待处理操作失效;辅助进程 EOF、信号及租期到期会启动远端清理。客户端如实报告未确认结果,绝不通过重连重放可能已执行的操作。 +管理截止时限约束单次 RPC 观察,不替代 Bash 或PTC 运行时消费方选择的执行截止时限。远端等待可以持续挂起,同时其他请求继续推进。SSH 丢失会使待处理操作失效;辅助进程 EOF、信号及租期到期会启动远端清理。客户端如实报告未确认结果,绝不通过重连重放可能已执行的操作。 ## 组合范围 @@ -67,7 +67,7 @@ declare class SshConnection extends Service { constructor(ctx: Context, config: Config); /** Hold plugin readiness until the remote identity and helper digest are verified. */ async [Service.init](): Promise; - /** Verified remote Node executable for the paired code runtime. */ + /** Verified remote Node executable for the paired PTC runtime. */ get nodeExecutable(): string; /** Verified preinstalled PTC entry; unconfigured runtimes fail before program execution. */ get bootstrapPath(): string; diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index 228c3bcc8b..a044baf3b1 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/testing.md -testing.md: f976b2cad238bc9bacee488f7168e5deb5e9b1a7 -testing.zh.md: 88784b16ae8b5b104de2f3cb20c7f285585871d6 +testing.md: 95badfd66ba49151a64dad3f5959a12265449f97 +testing.zh.md: a715fb0a6f285a908857a90e848213f42cc040cf diff --git a/docs/testing.md b/docs/testing.md index f976b2cad2..95badfd66b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -38,7 +38,7 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword - Product-visible plugins require a non-unit REAL-composition test. Hand-built `ctx.plugin(...)` suites are insufficient: boot test-only `cordis.yml` through Loader and app/process, mock only external services or nondeterministic inputs, and assert model-visible request/log, durable state, or user-visible output. Keep opt-ins out of shipped defaults. - A guard only guards if the regression fails it. For a plugin without `inject` (bundle/composition plugins), a Loader smoke stays green when a default export replaces the required named exports — add an explicit `expect('default' in mod).toBe(false)` plus an `unwrapExports` round-trip assertion, and prove it: introduce the regression, watch red, revert. -- "Real entry path" means the published artifact: a package `bin` runs built `lib/bin.js` under plain `node`, exposing failures tsx masks (settle races, module resolution, swallowed load failures). The same applies to non-index runtime entries (the Node program bootstrap `lib/process.js`) and singleton modules shared across bundles (`packages/sdk/server/tests/built-scope-carrier.e2e.ts`). Keep the built-artifact smokes green (`packages/examples/*/tests/built-bin.e2e.ts`, `packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts`), and assert a genuinely-missing config exits non-zero. +- "Real entry path" means the published artifact: a package `bin` runs built `lib/bin.js` under plain `node`, exposing failures tsx masks (settle races, module resolution, swallowed load failures). The same applies to non-index runtime entries (the Node program bootstrap `lib/process.js`) and singleton modules shared across bundles (`packages/sdk/server/tests/built-scope-carrier.e2e.ts`). Keep the built-artifact smokes green (`packages/examples/*/tests/built-bin.e2e.ts`, `packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts`), and assert a genuinely-missing config exits non-zero. ## Test resolution: source plane only diff --git a/docs/testing.zh.md b/docs/testing.zh.md index 88784b16ae..a715fb0a6f 100644 --- a/docs/testing.zh.md +++ b/docs/testing.zh.md @@ -38,7 +38,7 @@ e2e 断言应重新运行命令或从外部重新读取文件;对 agent 自身 - 产品可见的插件必须有一个非单元的真实组合测试。手动构建的 `ctx.plugin(...)` 套件不够:通过 Loader 和 app/process 启动仅用于测试的 `cordis.yml`,只 mock 外部服务或非确定性输入,断言模型可见的请求/日志、持久状态或用户可见输出。不要把 opt-in 选项混入交付默认值。 - 一个守卫只有在回归能让它失败时才有效。对于没有 `inject` 的插件(bundle/组合插件),Loader 冒烟测试在默认导出替换必需的具名导出时仍然绿着——需要添加显式的 `expect('default' in mod).toBe(false)` 加 `unwrapExports` 往返断言,并证明它有效:引入回归、观察变红、回退。 -- 「真实入口路径」指已发布的产物:包的 `bin` 所运行的是构建后的 `lib/bin.js`,并由普通 `node` 执行,从而暴露 tsx 会掩盖的失败(结算竞态、模块解析、被吞掉的加载失败)。同样的规则适用于非 index 运行时入口(Node 程序 bootstrap `lib/process.js`),也适用于多个 bundle 共享的单例模块(`packages/sdk/server/tests/built-scope-carrier.e2e.ts`)。保持构建产物冒烟测试绿色(`packages/examples/*/tests/built-bin.e2e.ts`、`packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts`),并断言真正缺失的配置以非零状态退出。 +- 「真实入口路径」指已发布的产物:包的 `bin` 所运行的是构建后的 `lib/bin.js`,并由普通 `node` 执行,从而暴露 tsx 会掩盖的失败(结算竞态、模块解析、被吞掉的加载失败)。同样的规则适用于非 index 运行时入口(Node 程序 bootstrap `lib/process.js`),也适用于多个 bundle 共享的单例模块(`packages/sdk/server/tests/built-scope-carrier.e2e.ts`)。保持构建产物冒烟测试绿色(`packages/examples/*/tests/built-bin.e2e.ts`、`packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts`),并断言真正缺失的配置以非零状态退出。 ## 测试解析:仅限源码 diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 6f1aec6569..763af88266 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/tool-catalog.md -tool-catalog.md: f89d8983844cd8f0b4e95e1460515b61919f323b -tool-catalog.zh.md: 68449c7b016f0a034fc7efa7e007f578db505ecf +tool-catalog.md: 18625b06b2dbbb6f131754b36ab04f7f8ae0c7b2 +tool-catalog.zh.md: ffb827532acd1b6cdf083bec0d8a3485f9ee0b02 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index f89d898384..18625b06b2 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -16,7 +16,7 @@ This table connects model-visible tool names to the plugin package and service s | Tool package | Model-visible names | Requires | Writes / affects | Shipped aliases | Deployment note | | --- | --- | --- | --- | --- | --- | | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userQuestions` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. | -| `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: ptc` / `mode: both` (see the PTC mode Agent Note). Under `ptc` it is the registry's only wire contribution; the other visible capabilities are declared in a generated SDK section in the loaded runtime's language, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | +| `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.ptcRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: ptc` / `mode: both` (see the PTC mode Agent Note). Under `ptc` it is the registry's only wire contribution; the other visible capabilities are declared in a generated SDK section in the loaded runtime's language, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userQuestions (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-questions seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | | `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.shell`, `ctx.systemPrompt`, `ctx.shellEnv`, `ctx.jobs at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.jobs` runtime and is collected/stopped through the `job_*` tools from `@deepseek-ai/dsh-tool-jobs`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | | `@deepseek-ai/dsh-tool-present` | `present` | `ctx.tools`, `ctx.fs`, `ctx.sessionProjections` | `tool/call`, `deliverables/presented after a successful final result`, `tool/result` | - | Deliveries belong to the calling Session; Web ui-deliverables supplies source-file opening and cards. | diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 68449c7b01..ffb827532a 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -20,7 +20,7 @@ | 工具包 | 模型可见名称 | 依赖 | 写入/影响 | 随产品发布的别名 | 部署说明 | | --- | --- | --- | --- | --- | --- | | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`、`ctx.userQuestions` | `tool/call`、`tool/result after a UI/provider answers the question` | - | ask_user_question 会暂停工具调用,直到当前 UI 提供方返回人类答案。 | -| `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`、`ctx.codeRuntime (execution time)`、`ctx.systemPrompt` | `tool/call`、`one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call`、`tool/result` | - | 在 `mode: ptc`/`mode: both` 下,它由工具注册表所有,作为可过滤能力层之外的保留传输机制(参见 PTC mode Agent Note)。在 `ptc` 下,它是注册表对协议格式(wire format)的唯一贡献;其他可见能力在使用已加载运行时语言生成的 SDK 章节中声明。程序通过 binding 调用这些能力,调用按照原生并发约定调度:启动顺序和策略遵循提交顺序,并发安全的函数体最多重叠执行 `maxParallelSubCalls` 个。调用会重新进入完整且受守卫保护的工具流水线,并将每个嵌套执行关联到此外层结果。 | +| `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`、`ctx.ptcRuntime (execution time)`、`ctx.systemPrompt` | `tool/call`、`one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call`、`tool/result` | - | 在 `mode: ptc`/`mode: both` 下,它由工具注册表所有,作为可过滤能力层之外的保留传输机制(参见 PTC mode Agent Note)。在 `ptc` 下,它是注册表对协议格式(wire format)的唯一贡献;其他可见能力在使用已加载运行时语言生成的 SDK 章节中声明。程序通过 binding 调用这些能力,调用按照原生并发约定调度:启动顺序和策略遵循提交顺序,并发安全的函数体最多重叠执行 `maxParallelSubCalls` 个。调用会重新进入完整且受守卫保护的工具流水线,并将每个嵌套执行关联到此外层结果。 | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`、`ctx.systemPrompt`、`ctx.userQuestions (execution time, opportunistic)` | `tool/call`、`plan/mode inactive on an approved review`、`tool/result` | - | 规划未激活时,exit_plan_mode 仍保留在面向模型的 schema 中,这样状态转换不会在规划策略变更之外额外造成工具目录变动。其执行路径会拒绝规划模式之外的调用;在规划模式下,它通过用户交互 seam 提交计划(批准/根据反馈继续规划),批准后会在步骤边界记录规划模式已停用。 | | `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`、`ctx.shell`、`ctx.systemPrompt`、`ctx.shellEnv`、`ctx.jobs at call time for run_in_background` | `tool/call`、`tool/result` | - | bash 工具是 bash 执行器 seam 面向模型的消费方。使用 `run_in_background` 的运行会注册到通用 `ctx.jobs` 运行时,并通过 `job_*` 工具(来自 `@deepseek-ai/dsh-tool-jobs`)收集/停止;禁用 `enableRunInBackground` 配置(默认为 true)后,该参数会被完全移除。 | | `@deepseek-ai/dsh-tool-present` | `present` | `ctx.tools`, `ctx.fs`, `ctx.sessionProjections` | `tool/call`, `deliverables/presented 在成功的最终结果之后`, `tool/result` | - | 交付归调用方 Session 所有;Web ui-deliverables 提供源文件打开与卡片。 | diff --git a/docs/user/guide/network-proxy.i18n.yaml b/docs/user/guide/network-proxy.i18n.yaml index e501e4b6c6..e66710fbe7 100644 --- a/docs/user/guide/network-proxy.i18n.yaml +++ b/docs/user/guide/network-proxy.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/user/guide/network-proxy.md -network-proxy.md: 5696cf6e42e2a1e2c5f817a3544b279dce15565e -network-proxy.zh.md: 6fbe2669e2105c9d297c3a63eb8f280e0d431325 +network-proxy.md: 78c0dad3635de5a7aa4d39d9616f7ca5eb25a11e +network-proxy.zh.md: 1743e06ea6be25b6c9d44308cf81f51fa94cb700 diff --git a/docs/user/guide/network-proxy.md b/docs/user/guide/network-proxy.md index 5696cf6e42..78c0dad363 100644 --- a/docs/user/guide/network-proxy.md +++ b/docs/user/guide/network-proxy.md @@ -66,7 +66,7 @@ Node reads that variable only at process start, so export it before running `dsh Not every request DSH makes goes through the proxy: - **Anything on this machine.** Loopback is always direct: `localhost`, the whole `127.0.0.0/8` range, `::1`, and `0.0.0.0`. A proxy cannot usefully reach a service that only listens locally. -- **Code the model writes.** Workflow workers and Node code-runtime processes receive no proxy settings, so model-authored scripts cannot read a proxy URL that may carry a password. Direct requests must configure any required proxy themselves and remain subject to the execution sandbox. +- **Code the model writes.** Workflow workers and Node ptc-runtime processes receive no proxy settings, so model-authored scripts cannot read a proxy URL that may carry a password. Direct requests must configure any required proxy themselves and remain subject to the execution sandbox. - **Usage telemetry.** The OTLP exporter uses Node's own HTTP client rather than the one a proxy configures, so telemetry connects directly and simply fails where direct egress is blocked. Nothing you do in DSH depends on it. Set `DSH_TELEMETRY_MODE=DISABLED` to turn it off entirely. - **`web_fetch` to a literal private address.** A URL naming an address like `http://10.0.0.5/` is refused rather than handed to the proxy, the same refusal it gets with no proxy configured. diff --git a/docs/user/guide/network-proxy.zh.md b/docs/user/guide/network-proxy.zh.md index 6fbe2669e2..1743e06ea6 100644 --- a/docs/user/guide/network-proxy.zh.md +++ b/docs/user/guide/network-proxy.zh.md @@ -66,7 +66,7 @@ Node 只在进程启动时读取该变量,所以要在运行 `dsh` 之前导 并非 DSH 发出的每个请求都会走代理: - **本机上的一切。** loopback 始终直连:`localhost`、整个 `127.0.0.0/8` 段、`::1` 与 `0.0.0.0`。代理无法有意义地访问一个只在本地监听的服务。 -- **模型编写的代码。** Workflow worker 与 Node code-runtime 进程不接收代理配置,因此模型脚本读不到可能携带密码的代理 URL。直接请求必须自行配置所需代理,并继续受到执行沙箱的约束。 +- **模型编写的代码。** Workflow worker 与 Node ptc-runtime 进程不接收代理配置,因此模型脚本读不到可能携带密码的代理 URL。直接请求必须自行配置所需代理,并继续受到执行沙箱的约束。 - **使用情况遥测。** OTLP 导出器用的是 Node 自带的 HTTP 客户端,而不是代理所配置的那个,因此遥测直连;在禁止直连出网的环境里它只会失败。DSH 的任何功能都不依赖它。设 `DSH_TELEMETRY_MODE=DISABLED` 可完全关闭。 - **`web_fetch` 访问字面量私网地址。** 形如 `http://10.0.0.5/` 的 URL 会被拒绝而非交给代理,与未配置代理时得到的拒绝相同。 diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 8df79d495e..cb1acbd34e 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/README.md -README.md: 05fc85febe0430db6c30c320e3446e6e2f51a7ba -README.zh.md: 04217adef5dbbcd31b9dab0178f4078b30fa4a8d +README.md: 04285079d1ffe22ad4fca0b5331554663bf1af1e +README.zh.md: 90bb71068b40c61f03d67db778a24409445ac721 diff --git a/packages/README.md b/packages/README.md index 05fc85febe..04285079d1 100644 --- a/packages/README.md +++ b/packages/README.md @@ -40,7 +40,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`ssh/`](ssh/README.md) | POSIX remote connection with paired filesystem, subprocess and sandbox providers | | [`shell/`](shell/README.md) | Bash capability family: executor seam, local impl, model-facing tools | | [`terminal/`](terminal/README.md) | Persistent PTY capability family: owner-scoped sessions, local implementation, model-facing tools | -| [`code-runtime/`](code-runtime/README.md) | Code-execution capability family: Service Definition + sandboxed Node provider + PTC mode Consumer | +| [`ptc-runtime/`](ptc-runtime/README.md) | Code-execution capability family: Service Definition + sandboxed Node provider + PTC mode Consumer | | [`sandbox/`](sandbox/README.md) | Process-confinement seam; bwrap/Landlock/Seatbelt backends | | [`fs/`](fs/README.md) | Filesystem capability family: seam, local impl, model-facing file tools, discovery tools | | [`lsp/`](lsp/README.md) | LSP capability family: seam, generic stdio provider, and the `lsp` tool | diff --git a/packages/README.zh.md b/packages/README.zh.md index 04217adef5..90bb71068b 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -40,7 +40,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`ssh/`](ssh/README.zh.md) | POSIX 远端连接及配套文件系统、子进程与沙箱提供方 | | [`shell/`](shell/README.zh.md) | Bash 能力系列:执行器 seam、本地实现、面向模型的工具 | | [`terminal/`](terminal/README.zh.md) | 持久 PTY 能力系列:限定所有者范围的会话、本地实现、面向模型的工具 | -| [`code-runtime/`](code-runtime/README.zh.md) | 代码执行能力族:Service Definition + 沙箱 Node 提供方 + PTC mode Consumer | +| [`ptc-runtime/`](ptc-runtime/README.zh.md) | 代码执行能力族:Service Definition + 沙箱 Node 提供方 + PTC mode Consumer | | [`sandbox/`](sandbox/README.zh.md) | 进程限制 seam;bwrap、Landlock、Seatbelt 后端 | | [`fs/`](fs/README.zh.md) | 文件系统能力系列:seam、本地实现、面向模型的文件工具、发现工具 | | [`lsp/`](lsp/README.zh.md) | LSP 能力系列:seam、通用 stdio 提供方和 `lsp` 工具 | diff --git a/packages/bundle/headless/README.i18n.yaml b/packages/bundle/headless/README.i18n.yaml index 2f28ba6cac..84720b316c 100644 --- a/packages/bundle/headless/README.i18n.yaml +++ b/packages/bundle/headless/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/bundle/headless/README.md -README.md: 54ad7a9384f6e6d9e0e987e860816577c6976388 -README.zh.md: a3fc5e2cc831090598c5bcb61cee41f9a17f6538 +README.md: 731c7c987fa3b9e2768dad4f3960cf1d4e5d080c +README.zh.md: e3d0757da12c235c4943168e03411255ac6cb4d6 diff --git a/packages/bundle/headless/README.md b/packages/bundle/headless/README.md index 54ad7a9384..731c7c987f 100644 --- a/packages/bundle/headless/README.md +++ b/packages/bundle/headless/README.md @@ -81,7 +81,7 @@ The runner awaits the complete application (`ctx.get('loader')?.await()`) so the ### Patch surface over base -The patch rides over `dsh-base`: it inherits the projection cache, sets the coding persona prefix and separate cwd suffix on the base `system-prompt` row, keeps the same temporary process-wide PTC mode opt-in (`DSH_TOOLS_MODE`) as the Web surface, disables the shared HMR row, inserts PTC mode's code runtime as a core execution capability, and mounts the startup provider and the runner. The cache checkpoints each persisted one-shot session for later consumers; its durability barrier flushes each covered log prefix before publishing the cache row and may split otherwise coalesced JSONL runs. The startup provider ([`src/startup.ts`](src/startup.ts)) injects `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), reads the positional argument and the `--session-id`/`--json` options, prints the app's `--help`, and provides `headlessStartup`; the runner injects that service and reads its task and run options from lazy config. +The patch rides over `dsh-base`: it inherits the projection cache, sets the coding persona prefix and separate cwd suffix on the base `system-prompt` row, keeps the same temporary process-wide PTC mode opt-in (`DSH_TOOLS_MODE`) as the Web surface, disables the shared HMR row, inserts PTC mode's PTC runtime as a core execution capability, and mounts the startup provider and the runner. The cache checkpoints each persisted one-shot session for later consumers; its durability barrier flushes each covered log prefix before publishing the cache row and may split otherwise coalesced JSONL runs. The startup provider ([`src/startup.ts`](src/startup.ts)) injects `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), reads the positional argument and the `--session-id`/`--json` options, prints the app's `--help`, and provides `headlessStartup`; the runner injects that service and reads its task and run options from lazy config. ### Exit mapping diff --git a/packages/bundle/headless/README.zh.md b/packages/bundle/headless/README.zh.md index a3fc5e2cc8..e3d0757da1 100644 --- a/packages/bundle/headless/README.zh.md +++ b/packages/bundle/headless/README.zh.md @@ -81,7 +81,7 @@ runner 等待整个应用结算(`ctx.get('loader')?.await()`),确保已组 ### 基于 base 的 patch 内容 -patch 叠加在 `dsh-base` 之上:继承投影缓存,在基础 `system-prompt` 行上设置编码 persona 前缀与独立的 cwd 后缀,保留与 Web 表层相同的临时进程级 PTC mode 开关(`DSH_TOOLS_MODE`),禁用共享的 HMR(热模块替换)行,把 PTC mode 的代码运行时作为核心执行能力插入,并挂载启动提供方与 runner。缓存为每个已持久化的一次性会话写入检查点,供后续消费方使用;其持久性屏障会在发布缓存行前 flush 所覆盖的日志前缀,因此可能拆分原本会合并的 JSONL 连续段。启动提供方([`src/startup.ts`](src/startup.ts))注入 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.zh.md)),读取位置参数与 `--session-id`/`--json` 选项、打印应用自己的 `--help`,并提供 `headlessStartup`;runner 注入该服务,再从惰性配置中读取任务与运行选项。 +patch 叠加在 `dsh-base` 之上:继承投影缓存,在基础 `system-prompt` 行上设置编码 persona 前缀与独立的 cwd 后缀,保留与 Web 表层相同的临时进程级 PTC mode 开关(`DSH_TOOLS_MODE`),禁用共享的 HMR(热模块替换)行,把 PTC mode 的PTC 运行时作为核心执行能力插入,并挂载启动提供方与 runner。缓存为每个已持久化的一次性会话写入检查点,供后续消费方使用;其持久性屏障会在发布缓存行前 flush 所覆盖的日志前缀,因此可能拆分原本会合并的 JSONL 连续段。启动提供方([`src/startup.ts`](src/startup.ts))注入 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.zh.md)),读取位置参数与 `--session-id`/`--json` 选项、打印应用自己的 `--help`,并提供 `headlessStartup`;runner 注入该服务,再从惰性配置中读取任务与运行选项。 ### 退出映射 diff --git a/packages/bundle/headless/cordis.patch.yml b/packages/bundle/headless/cordis.patch.yml index d0deeca879..55d8e5b097 100644 --- a/packages/bundle/headless/cordis.patch.yml +++ b/packages/bundle/headless/cordis.patch.yml @@ -19,8 +19,8 @@ - insert: # PTC mode is a core execution capability, not a Web component. - - id: code-runtime - name: '@deepseek-ai/dsh-code-runtime-node' + - id: ptc-runtime + name: '@deepseek-ai/dsh-ptc-runtime-node' - id: headless-startup name: '@deepseek-ai/dsh-headless/startup' diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index ed8f5e7a30..3bb48450c6 100644 --- a/packages/bundle/headless/package.json +++ b/packages/bundle/headless/package.json @@ -42,7 +42,7 @@ "dependencies": { "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-cmdline": "workspace:^", - "@deepseek-ai/dsh-code-runtime-node": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:^", "@deepseek-ai/dsh-util-values": "workspace:^", "@deepseek-ai/schemastery": "workspace:^", "commander": "^15.0.0" diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 2f71fad7a6..8910f4b954 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -47,8 +47,8 @@ - id: subagent-model-selection-settings name: '@deepseek-ai/dsh-tool-subagent/model-selection-settings' - - id: code-runtime - name: '@deepseek-ai/dsh-code-runtime-node' + - id: ptc-runtime + name: '@deepseek-ai/dsh-ptc-runtime-node' - id: message-feedback name: '@deepseek-ai/dsh-message-feedback' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 1c3cbf0e39..e25ab746b4 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -94,7 +94,7 @@ "@deepseek-ai/dsh-client-ui-workflow-run": "workspace:^", "@deepseek-ai/dsh-client-ui-workspace": "workspace:^", "@deepseek-ai/dsh-cmdline": "workspace:^", - "@deepseek-ai/dsh-code-runtime-node": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:^", "@deepseek-ai/dsh-cordis-client-runner": "workspace:^", "@deepseek-ai/dsh-cordis-host-runner": "workspace:^", "@deepseek-ai/dsh-file-reference": "workspace:^", diff --git a/packages/client/ui-conversation/src/client/contract/records.ts b/packages/client/ui-conversation/src/client/contract/records.ts index f639a1f16a..6a285d8d32 100644 --- a/packages/client/ui-conversation/src/client/contract/records.ts +++ b/packages/client/ui-conversation/src/client/contract/records.ts @@ -158,7 +158,7 @@ export interface ToolResultNode { /** Unix epoch ms from the tool/result session event. */ time: number callId: string - /** Parent Tool call for a Code Dispatch result; absent on a root Session result. */ + /** Parent Tool call for a PTC dispatch result; absent on a root Session result. */ parentCallId?: string /** Call head backfilled from the in-window tool/call; null when window truncation left the call outside (card head shows callId). */ call: { name: string; argsRaw: string } | null @@ -264,7 +264,7 @@ export type ConversationNode = /** In-flight tool card material: tool/call seen, tool/result not yet. */ export interface RunningToolCall { callId: string - /** Parent Tool call for a Code Dispatch start; absent on a root Session call. */ + /** Parent Tool call for a PTC dispatch start; absent on a root Session call. */ parentCallId?: string name: string argsRaw: string diff --git a/packages/client/ui-deliverables/src/client/turn-deliverables.ts b/packages/client/ui-deliverables/src/client/turn-deliverables.ts index 31c78d9e57..0b762d7a96 100644 --- a/packages/client/ui-deliverables/src/client/turn-deliverables.ts +++ b/packages/client/ui-deliverables/src/client/turn-deliverables.ts @@ -41,7 +41,7 @@ interface DeliverablesState extends DeliverablesTurnData { /** * Extract the path from a supported first-party mutation call. Session - * `tool/call` events are root calls; Code Dispatch children do not enter this + * `tool/call` events are root calls; PTC dispatch children do not enter this * Definition independently. * @param name - wire tool name. * @param argsRaw - model-produced JSON arguments. diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index ad0a426ba6..0b3115ae38 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-tool/README.md -README.md: b8dd2a5e3c6743e496d585a2de238714f00e9f6b -README.zh.md: 0f777981ff6ccc6945e516d3c9853a236cde82d7 +README.md: f2a51bfbbe26fbedae210a80eb164a858767b40f +README.zh.md: f0a823290735f9f60b0d2844d57935b0d017cb4f diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index b8dd2a5e3c..f2a51bfbbe 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-client-ui-tool` is the client Tool presentation plugin of the dsh web client: it renders every tool call in the conversation. `ui-conversation` dispatches each ordered `tool-call` Conversation Node through the matching key of `conversation.chat.node`; this package renders its root and Code Dispatch children, then dispatches every atomic call through the keyed `tool.call.toolview` slot. Unregistered Tool names use the generic card. Business UI packages register only their wire Tool names and atomic views — they do not pair Session events, rebuild the transcript, or own root/subcall topology, because the Runtime remains authoritative for call/result pairing, lifecycle, and recursive `subCalls` projection. +`dsh-client-ui-tool` is the client Tool presentation plugin of the dsh web client: it renders every tool call in the conversation. `ui-conversation` dispatches each ordered `tool-call` Conversation Node through the matching key of `conversation.chat.node`; this package renders its root and PTC dispatch children, then dispatches every atomic call through the keyed `tool.call.toolview` slot. Unregistered Tool names use the generic card. Business UI packages register only their wire Tool names and atomic views — they do not pair Session events, rebuild the transcript, or own root/subcall topology, because the Runtime remains authoritative for call/result pairing, lifecycle, and recursive `subCalls` projection. ## Table of Contents @@ -39,11 +39,11 @@ ctx.slots.inject('tool.call.toolview', () => }, BusinessToolRow)) ``` -The owner payload is `ToolCallOwnerProps`: `callId`, `toolName`, the frozen `block`, optional `cwd` and `home`, the session-authorized `loadImage` loader (for a view whose result carries durable images), and plain `openFile`/`inspect` callbacks. A Code Dispatch block retains its event's `parentCallId`; a root Session call has no such field, so descendants route through the same keyed dispatch — a registered view such as `read_image` renders its card there, and unregistered descendants keep the generic flattened form. Path summaries relativize to the Session cwd first, then replace a leftover POSIX Host home with `~`; `filePath` and Host open keep the authored filesystem path. The registration receives the normal Session slot runtime share but no React node or Runtime service. +The owner payload is `ToolCallOwnerProps`: `callId`, `toolName`, the frozen `block`, optional `cwd` and `home`, the session-authorized `loadImage` loader (for a view whose result carries durable images), and plain `openFile`/`inspect` callbacks. A PTC dispatch block retains its event's `parentCallId`; a root Session call has no such field, so descendants route through the same keyed dispatch — a registered view such as `read_image` renders its card there, and unregistered descendants keep the generic flattened form. Path summaries relativize to the Session cwd first, then replace a leftover POSIX Host home with `~`; `filePath` and Host open keep the authored filesystem path. The registration receives the normal Session slot runtime share but no React node or Runtime service. ### Built-in views -This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and Code Dispatch presentations. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in Code Dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable, while background acknowledgements remain collapsed. A successful question row pairs call questions with result answers by their stable ids and shows readable question/answer lines when expanded. A cancelled or interrupted row shows its verdict and original questions without inventing answers. Unsupported, malformed, or ambiguous inputs fall back to flattened Tool input/result text. `ui-skill` demonstrates a business-owned registration for `skill`. +This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable, while background acknowledgements remain collapsed. A successful question row pairs call questions with result answers by their stable ids and shows readable question/answer lines when expanded. A cancelled or interrupted row shows its verdict and original questions without inventing answers. Unsupported, malformed, or ambiguous inputs fall back to flattened Tool input/result text. `ui-skill` demonstrates a business-owned registration for `skill`. ----- @@ -62,7 +62,7 @@ The package realizes one dispatch rule: atomic Tool views are keyed by wire Tool ### Cards -Every card is read in place in the call tree; there is no second, full-height presentation of a selected call. Row renderers share one pure card model for each terminal, read, diff, search, and web card, and the image card's gallery renders through the tool-owned `tool.call.images` slot. These models validate raw call arguments, result content, failure state, persisted metadata, Code Dispatch `parentCallId`, and Session path facts. Unsupported or malformed inputs use flattened Tool result text. A file-path summary opens the file through the owner's `openFile`, which the chat view routes to the right Sidebar's text preview; `inspect` opens the trajectory view. Card-specific limits and fallback rules for the terminal, diff, read, search, and web cards remain in [the ui-primitives README](../ui-primitives/README.md); the image card's model in this package carries its own fallback rules. +Every card is read in place in the call tree; there is no second, full-height presentation of a selected call. Row renderers share one pure card model for each terminal, read, diff, search, and web card, and the image card's gallery renders through the tool-owned `tool.call.images` slot. These models validate raw call arguments, result content, failure state, persisted metadata, PTC dispatch `parentCallId`, and Session path facts. Unsupported or malformed inputs use flattened Tool result text. A file-path summary opens the file through the owner's `openFile`, which the chat view routes to the right Sidebar's text preview; `inspect` opens the trajectory view. Card-specific limits and fallback rules for the terminal, diff, read, search, and web cards remain in [the ui-primitives README](../ui-primitives/README.md); the image card's model in this package carries its own fallback rules. The terminal model uses `hasSpillNotice` from the browser-safe `@deepseek-ai/dsh-spill-policy/notice` entry, not an independent UI pattern. The [spill-policy README](../../spill/spill-policy/README.md#shared-notice-ownership) owns notice formatting and recognition. This check conservatively selects generic output; matching text cannot authenticate its source, and replay leaves recorded result bytes untouched. diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 0f777981ff..f0a8232907 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`dsh-client-ui-tool` 是 dsh Web 客户端的 Client 工具展示插件:它渲染对话中的每一次工具调用。`ui-conversation` 通过 `conversation.chat.node` 的匹配 key 分发每个已排序的 `tool-call` Conversation Node;本包渲染其中的 root 及其 Code Dispatch 子调用,并把每个原子调用通过 keyed slot `tool.call.toolview` 分发。没有注册的工具名称使用通用卡片。业务 UI 包只注册 wire 工具名称和原子视图——它们不配对会话事件、不重建 transcript(文本记录),也不拥有 root/subcall 拓扑,因为运行时仍对 call/result 配对、生命周期与递归 `subCalls` 投影拥有最终决定权。 +`dsh-client-ui-tool` 是 dsh Web 客户端的 Client 工具展示插件:它渲染对话中的每一次工具调用。`ui-conversation` 通过 `conversation.chat.node` 的匹配 key 分发每个已排序的 `tool-call` Conversation Node;本包渲染其中的 root 及其 PTC dispatch 子调用,并把每个原子调用通过 keyed slot `tool.call.toolview` 分发。没有注册的工具名称使用通用卡片。业务 UI 包只注册 wire 工具名称和原子视图——它们不配对会话事件、不重建 transcript(文本记录),也不拥有 root/subcall 拓扑,因为运行时仍对 call/result 配对、生命周期与递归 `subCalls` 投影拥有最终决定权。 ## 目录 @@ -39,11 +39,11 @@ ctx.slots.inject('tool.call.toolview', () => }, BusinessToolRow)) ``` -owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、冻结的 `block`、可选 `cwd` 与 `home`、会话授权的 `loadImage` loader(供结果携带持久图像的视图使用),以及普通的 `openFile`/`inspect` 回调。Code Dispatch 块保留事件的 `parentCallId`;根会话调用没有该字段,因此后代调用都走同一条按 key 分发路径:已注册视图的调用(如 `read_image`)也会在嵌套处渲染对应卡片,未注册的后代调用则保持通用压平形式。路径摘要先相对会话 cwd 缩短,再把剩余的 POSIX Host home 写成 `~`;`filePath` 与 Host 打开仍使用作者给出的文件系统路径。注册项会收到常规的会话 slot 运行时共享数据,但不会收到 React 节点或运行时服务。 +owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、冻结的 `block`、可选 `cwd` 与 `home`、会话授权的 `loadImage` loader(供结果携带持久图像的视图使用),以及普通的 `openFile`/`inspect` 回调。PTC dispatch 块保留事件的 `parentCallId`;根会话调用没有该字段,因此后代调用都走同一条按 key 分发路径:已注册视图的调用(如 `read_image`)也会在嵌套处渲染对应卡片,未注册的后代调用则保持通用压平形式。路径摘要先相对会话 cwd 缩短,再把剩余的 POSIX Host home 写成 `~`;`filePath` 与 Host 打开仍使用作者给出的文件系统路径。注册项会收到常规的会话 slot 运行时共享数据,但不会收到 React 节点或运行时服务。 ### 内置视图 -本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 Code Dispatch 的内置展示。结构化卡片直接从第一方原始事件字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 Code Dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开,后台启动回执则保持折叠。成功的问题行按稳定 id 配对调用中的问题与结果中的回答,展开后显示可读的问答行。已取消或已中断的问题行显示其裁决与原始问题,不虚构回答。不受支持、格式错误或含糊的输入回退为压平的工具输入/结果文本。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。 +本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。结构化卡片直接从第一方原始事件字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开,后台启动回执则保持折叠。成功的问题行按稳定 id 配对调用中的问题与结果中的回答,展开后显示可读的问答行。已取消或已中断的问题行显示其裁决与原始问题,不虚构回答。不受支持、格式错误或含糊的输入回退为压平的工具输入/结果文本。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。 ----- @@ -62,7 +62,7 @@ owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、冻结的 `block` ### 卡片 -每张卡片都直接在调用树中查看;选中调用后不会再显示第二个全高视图。行 renderer 为 terminal、read、diff、search 和 web 卡片各复用同一个纯 card model,image 卡片的图库经由工具自有 `tool.call.images` slot 渲染。这些 model 校验原始调用参数、结果内容、失败状态、持久 metadata、Code Dispatch 的 `parentCallId` 与会话路径信息。不受支持或格式错误的输入使用压平的工具结果文本。文件路径摘要经属主的 `openFile` 打开文件,chat 视图把它路由到右侧 Sidebar 的文本预览;`inspect` 打开轨迹视图。terminal、diff、read、search 与 web 卡片的上限与 fallback 规则仍由 [ui-primitives README](../ui-primitives/README.zh.md) 负责;image 卡片的 fallback 规则由本包内的 card model 自行承载。 +每张卡片都直接在调用树中查看;选中调用后不会再显示第二个全高视图。行 renderer 为 terminal、read、diff、search 和 web 卡片各复用同一个纯 card model,image 卡片的图库经由工具自有 `tool.call.images` slot 渲染。这些 model 校验原始调用参数、结果内容、失败状态、持久 metadata、PTC dispatch 的 `parentCallId` 与会话路径信息。不受支持或格式错误的输入使用压平的工具结果文本。文件路径摘要经属主的 `openFile` 打开文件,chat 视图把它路由到右侧 Sidebar 的文本预览;`inspect` 打开轨迹视图。terminal、diff、read、search 与 web 卡片的上限与 fallback 规则仍由 [ui-primitives README](../ui-primitives/README.zh.md) 负责;image 卡片的 fallback 规则由本包内的 card model 自行承载。 terminal model 使用浏览器安全入口 `@deepseek-ai/dsh-spill-policy/notice` 的 `hasSpillNotice`,而非独立的 UI 匹配规则。[spill-policy README](../../spill/spill-policy/README.zh.md#shared-notice-ownership) 负责提示文本的格式化与识别。该检查保守地选择通用输出;匹配的文本无法证明其来源,回放也不改变已记录的结果字节。 diff --git a/packages/client/ui-tool/package.json b/packages/client/ui-tool/package.json index d15118d41e..7722edfaa0 100644 --- a/packages/client/ui-tool/package.json +++ b/packages/client/ui-tool/package.json @@ -71,7 +71,7 @@ "@deepseek-ai/dsh-util-workspace-path": "workspace:^", "@deepseek-ai/dsh-attachment": "workspace:^", "clsx": "^2.0.0", - "@deepseek-ai/dsh-code-runtime": "workspace:^" + "@deepseek-ai/dsh-ptc-runtime": "workspace:^" }, "files": [ "lib/index.js", diff --git a/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts b/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts index 935829ece1..4ccd522d99 100644 --- a/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts @@ -272,7 +272,7 @@ function parseExitStatus(text: string): { output: string; exitCode?: number; sig /** * Derive terminal props for supported shell and terminal-send calls, including - * nested Code Dispatch calls. Standard shell results parse their final status + * nested PTC dispatch calls. Standard shell results parse their final status * marker; persistent shell results, spill previews, background calls, errors, * and malformed input use the generic path. {@link isSettledPersistentShellCall} lets that generic * persistent result remain expandable without inventing one process status. diff --git a/packages/client/ui-tool/tests/chat-code-subcalls.client.spec.tsx b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx similarity index 100% rename from packages/client/ui-tool/tests/chat-code-subcalls.client.spec.tsx rename to packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx 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 ccb6a78a82..df505c9b76 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 @@ -2,8 +2,8 @@ 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 { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeRunRequest, CodeRunSpec, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcRunRequest, PtcRunSpec, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' import { SpillLocator, SpillStore, type SaveTextSpill, type SpillRef } from '@deepseek-ai/dsh-spill' @@ -43,13 +43,13 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl await ctx.plugin(SpillPolicy, { maxInlineBytes }) if (nested) { // The real registry and spill policy own nested output; evaluator execution has its own process suite. - class BindingRuntime extends CodeRuntime { + class BindingRuntime extends PtcRuntime { readonly language = 'typescript' readonly isolation = 'fixture' - resolve(request: CodeRunRequest): CodeRunSpec { + resolve(request: PtcRunRequest): PtcRunSpec { return { ...request, cwd: process.cwd(), timeoutMs: 120_000 } } - async run(spec: CodeRunSpec): Promise { + 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) diff --git a/packages/client/ui-tool/tests/terminal-card.client.spec.tsx b/packages/client/ui-tool/tests/terminal-card.client.spec.tsx index 1cfe3b869c..11a9ebe63e 100644 --- a/packages/client/ui-tool/tests/terminal-card.client.spec.tsx +++ b/packages/client/ui-tool/tests/terminal-card.client.spec.tsx @@ -211,7 +211,7 @@ describe('terminalCardModel', () => { expect(terminalCardModel(settled({ call: null }))).toBeNull() }) - it('derives the same terminal card for root calls and Code Dispatch children', () => { + it('derives the same terminal card for root calls and PTC dispatch children', () => { expect(terminalCardModel(settled({ parentCallId: 'parent' }))).toEqual(terminalCardModel(settled())) expect(terminalCardModel(running({ parentCallId: 'parent' }))).toEqual(terminalCardModel(running())) }) diff --git a/packages/code-runtime/README.md b/packages/code-runtime/README.md deleted file mode 100644 index 13c0d0e168..0000000000 --- a/packages/code-runtime/README.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -description: "Package map for the code-execution capability family: what program execution does for you, and which package owns each part." -kind: "package-group" ---- - -# code-runtime/ — code-execution capability family - -English | [中文](README.zh.md) - -## Summary - -The `code-runtime/` group lets a model write one program that calls host-provided functions as ordinary async calls, then returns only the program's printed output and return value. Choose the TypeScript backend for execution in a fresh Node process under the configured sandbox policy, or the experimental Python backend when a CPython process is required. Each run starts without state from earlier programs. Failures are returned as results so callers can diagnose them or provide them to the model. - -## Table of Contents - -- [Packages](#packages) -- [Related documentation](#related-documentation) -- [Dev Note](#dev-note) - ------ - - -## Packages - -These three packages together provide program execution; each README describes what its part does. - -| Package | Role | ctx key | -|---|---|---| -| [`code-runtime/`](code-runtime/README.md) | Defines what a code runtime does: run one program against host-provided bindings and report what it printed and returned | `ctx.codeRuntime` | -| [`code-runtime-node/`](code-runtime-node/README.md) | Executes TypeScript in fresh managed Node processes under the resolved sandbox policy | registers `ctx.codeRuntime` | -| [`experimental/code-runtime-python/`](../experimental/code-runtime-python/README.md) | The experimental Python backend: owns the fd-3 wire protocol between a Node host and a CPython subprocess and the CPython runtime implementation | — | - ------ - - -## Related documentation - -Start with the subsystem reference for the service contract, then the PTC mode design that consumes this capability and the capability-seam model it follows. - -- [Code runtime subsystem reference](../../docs/subsystems/code-runtime.md) — request/result vocabulary, bindings, and the `ctx.codeRuntime` Cordis surface. -- [PTC mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-ptc.md) — how the tool registry presents `run_code` to the model. -- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. - - -## Dev Note - -
-Working context for maintainers — click to expand - -None. - -
diff --git a/packages/code-runtime/README.zh.md b/packages/code-runtime/README.zh.md deleted file mode 100644 index cb69ed488f..0000000000 --- a/packages/code-runtime/README.zh.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -description: "代码执行能力族的包映射:程序执行能为你做什么,以及每个部分由哪个包负责。" -kind: "package-group" ---- - -# code-runtime/——代码执行能力族 - -[English](README.md) | 中文 - -## 概述 - -`code-runtime/` 组让模型编写一个程序,以普通异步调用的方式调用宿主提供的函数,然后只返回程序的打印输出和返回值。如需在全新 Node 进程中按所配沙箱策略执行,请选择 TypeScript 后端;如需 CPython 进程,请选择实验性 Python 后端。每次运行都不会保留之前程序的状态。失败会作为结果返回,供调用方诊断或提供给模型。 - -## 目录 - -- [包](#packages) -- [相关文档](#related-documentation) -- [开发备注](#dev-note) - ------ - - -## 包 - -这三个包共同提供程序执行能力;每个 README 描述其各自部分做什么。 - -| 包 | 角色 | ctx 键 | -|---|---|---| -| [`code-runtime/`](code-runtime/README.zh.md) | 定义代码运行时做什么:针对宿主提供的绑定运行一个程序,并报告其打印和返回的内容 | `ctx.codeRuntime` | -| [`code-runtime-node/`](code-runtime-node/README.zh.md) | 在全新受管 Node 进程中按已解析沙箱策略执行 TypeScript | 注册 `ctx.codeRuntime` | -| [`experimental/code-runtime-python/`](../experimental/code-runtime-python/README.zh.md) | 实验性 Python 后端:负责 Node 宿主与 CPython 子进程之间的 fd-3 协议,以及 CPython 运行时实现 | — | - ------ - - -## 相关文档 - -先从子系统参考了解服务约定,再看消费此能力的 PTC mode 设计,以及它所遵循的能力 seam 模型。 - -- [代码运行时子系统参考](../../docs/subsystems/code-runtime.zh.md)——请求/结果词汇、绑定与 `ctx.codeRuntime` 的 Cordis 接口面。 -- [PTC mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)——工具注册表如何把 `run_code` 呈现给模型。 -- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 - - -## 开发备注 - -
-维护者的工作上下文——点击展开 - -无。 - -
diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 3aeabad540..19a17de8a3 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -14,8 +14,8 @@ import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop, { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse } from './mock-adapter.ts' -import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' async function harness(adapter: MockAdapter, maxParallelToolCalls?: number) { const ctx = new Context() @@ -697,13 +697,13 @@ describe('tool-call scheduler: failure quiescence', () => { }) describe('PTC mode native-tool denial through the agent loop', () => { - /** A minimal in-process code runtime for test purposes — never actually runs. */ - class FakeCodeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + /** A minimal in-process PTC runtime for test purposes — never actually runs. */ + class FakePtcRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' as const - async run(_request: CodeRunRequest): Promise { + async run(_request: PtcRunRequest): Promise { return { logs: [] } } } @@ -715,8 +715,8 @@ describe('PTC mode native-tool denial through the agent loop', () => { await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await ctx.plugin(ToolRuntime, { mode: 'ptc' }) - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FakeCodeRuntime is an internal test helper with an opaque type shape - await ctx.plugin(FakeCodeRuntime as any) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FakePtcRuntime is an internal test helper with an opaque type shape + await ctx.plugin(FakePtcRuntime as any) await ctx.plugin(AgentRegistry) await ctx.plugin(AgentLoop, { agents: [] }) ctx.llm.registerAdapter(['mock'], adapter) diff --git a/packages/core/agent-tool-presentation/README.i18n.yaml b/packages/core/agent-tool-presentation/README.i18n.yaml index bed75acdcf..4e74218578 100644 --- a/packages/core/agent-tool-presentation/README.i18n.yaml +++ b/packages/core/agent-tool-presentation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-tool-presentation/README.md -README.md: ccada947d31f7e6ae1df248fd11839845b1df59e -README.zh.md: 9b36edc9e15fd98e1e2492e40c199fb6ea55731d +README.md: c7aadfc9f409392718d7f044168c5de48dd33ee5 +README.zh.md: c3efd06c46a0624c6364ef4069ff5da87941c665 diff --git a/packages/core/agent-tool-presentation/README.md b/packages/core/agent-tool-presentation/README.md index ccada947d3..c7aadfc9f4 100644 --- a/packages/core/agent-tool-presentation/README.md +++ b/packages/core/agent-tool-presentation/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use `dsh-agent-tool-presentation` in an [agent preset](../../preset/agent-presets/README.md) to fix whether models see every native tool schema, only `run_code` with a generated SDK, or both forms. Each preset can choose independently, so native and PTC agents can share one process without sharing tool catalogs. Selecting `ptc` or `both` requires a compatible code runtime; a deployment without one rejects the preset at mount time before its first prompt. The `mode` field is required when this package is present, while omitting the package keeps the deployment default. +Use `dsh-agent-tool-presentation` in an [agent preset](../../preset/agent-presets/README.md) to fix whether models see every native tool schema, only `run_code` with a generated SDK, or both forms. Each preset can choose independently, so native and PTC agents can share one process without sharing tool catalogs. Selecting `ptc` or `both` requires a compatible PTC runtime; a deployment without one rejects the preset at mount time before its first prompt. The `mode` field is required when this package is present, while omitting the package keeps the deployment default. ## Table of Contents @@ -43,7 +43,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### What PTC mode requires -Selecting `ptc` or `both` needs a composed code runtime (`ctx.codeRuntime`) whose language has a registered SDK renderer — the TypeScript runtime ships via [`dsh-code-runtime-node`](../../code-runtime/code-runtime-node/README.md), and both the TypeScript and Python SDK renderers are built into `dsh-tools`. A preset that selects a PTC mode against a deployment composing no such runtime refuses to mount, naming this row, so the failure lands where the operator can act instead of at the session's first request. +Selecting `ptc` or `both` needs a composed PTC runtime (`ctx.ptcRuntime`) whose language has a registered SDK renderer — the TypeScript runtime ships via [`dsh-ptc-runtime-node`](../../ptc-runtime/ptc-runtime-node/README.md), and both the TypeScript and Python SDK renderers are built into `dsh-tools`. A preset that selects a PTC mode against a deployment composing no such runtime refuses to mount, naming this row, so the failure lands where the operator can act instead of at the session's first request. ### One presentation per agent @@ -72,7 +72,7 @@ The tool registry cannot move into a preset: its consumers are all host-plane ### Behavior notes -`native` applies immediately. A PTC mode instead waits for `ctx.codeRuntime`, a host-plane service: a preset selecting PTC mode against a deployment composing no runtime holds this row pending, and `dsh-agent-presets` refuses the mount naming this id. `presentAs` is itself the effect, so the declaration unwinds with this row without a second wrapper owning it. +`native` applies immediately. A PTC mode instead waits for `ctx.ptcRuntime`, a host-plane service: a preset selecting PTC mode against a deployment composing no runtime holds this row pending, and `dsh-agent-presets` refuses the mount naming this id. `presentAs` is itself the effect, so the declaration unwinds with this row without a second wrapper owning it. @@ -85,7 +85,7 @@ The package-level contract is enough for most consumers; read these when you nee - [tools package](../tools/README.md) — the tool presentation modes and `presentAs` API. - [agent-presets package](../../preset/agent-presets/README.md) — how presets compose agents and their standing mounts. -- [Node code-runtime package](../../code-runtime/code-runtime-node/README.md) — the TypeScript runtime a PTC mode needs. +- [Node ptc-runtime package](../../ptc-runtime/ptc-runtime-node/README.md) — the TypeScript runtime a PTC mode needs. - [PTC mode executor-collapse note](../../../.agents/notes/implemented/bug-fix/2026-08-07-ptc-executor-collapse.md) — why the announced and callable surfaces stay the same. - [Core group map](../README.md) — how the core packages compose. diff --git a/packages/core/agent-tool-presentation/README.zh.md b/packages/core/agent-tool-presentation/README.zh.md index 9b36edc9e1..c3efd06c46 100644 --- a/packages/core/agent-tool-presentation/README.zh.md +++ b/packages/core/agent-tool-presentation/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -在 [agent preset](../../preset/agent-presets/README.zh.md) 中使用 `dsh-agent-tool-presentation`,可固定模型看到全部原生工具 schema、只有带生成 SDK 的 `run_code`,还是同时看到两种形态。每个 preset 可独立选择,因此 native 与 PTC agent 可以共享同一进程,而不共享工具目录。选择 `ptc` 或 `both` 需要兼容的代码运行时;没有该运行时的部署会在挂载时拒绝 preset,不会等到收到第一条提示词。使用本包时 `mode` 字段为必填;省略本包则沿用部署默认值。 +在 [agent preset](../../preset/agent-presets/README.zh.md) 中使用 `dsh-agent-tool-presentation`,可固定模型看到全部原生工具 schema、只有带生成 SDK 的 `run_code`,还是同时看到两种形态。每个 preset 可独立选择,因此 native 与 PTC agent 可以共享同一进程,而不共享工具目录。选择 `ptc` 或 `both` 需要兼容的PTC 运行时;没有该运行时的部署会在挂载时拒绝 preset,不会等到收到第一条提示词。使用本包时 `mode` 字段为必填;省略本包则沿用部署默认值。 ## 目录 @@ -43,7 +43,7 @@ kind: "package-reference" ### PTC 模式需要什么 -选择 `ptc` 或 `both` 需要已组合的代码运行时(`ctx.codeRuntime`),且其语言有已注册的 SDK 渲染器——TypeScript 运行时经 [`dsh-code-runtime-node`](../../code-runtime/code-runtime-node/README.zh.md) 交付,TypeScript 与 Python 的 SDK 渲染器都内置在 `dsh-tools` 中。针对未组装此类运行时的部署选择 PTC 模式的 preset 会拒绝挂载并点名这一行,使失败落在操作者可以行动的地方,而不是落在会话的第一次请求上。 +选择 `ptc` 或 `both` 需要已组合的PTC 运行时(`ctx.ptcRuntime`),且其语言有已注册的 SDK 渲染器——TypeScript 运行时经 [`dsh-ptc-runtime-node`](../../ptc-runtime/ptc-runtime-node/README.zh.md) 交付,TypeScript 与 Python 的 SDK 渲染器都内置在 `dsh-tools` 中。针对未组装此类运行时的部署选择 PTC 模式的 preset 会拒绝挂载并点名这一行,使失败落在操作者可以行动的地方,而不是落在会话的第一次请求上。 ### 每个 agent 只声明一次呈现方式 @@ -72,7 +72,7 @@ kind: "package-reference" ### 行为说明 -`native` 立即生效。PTC 模式则等待 `ctx.codeRuntime`——这是一个宿主平面服务:针对未组装运行时的部署选择 PTC mode 的 preset 会让这一行停在 pending,`dsh-agent-presets` 会指名此 id 拒绝挂载。`presentAs` 本身就是 effect,因此该声明随这一行撤销,无需第二个包装层拥有它。 +`native` 立即生效。PTC 模式则等待 `ctx.ptcRuntime`——这是一个宿主平面服务:针对未组装运行时的部署选择 PTC mode 的 preset 会让这一行停在 pending,`dsh-agent-presets` 会指名此 id 拒绝挂载。`presentAs` 本身就是 effect,因此该声明随这一行撤销,无需第二个包装层拥有它。 @@ -85,7 +85,7 @@ kind: "package-reference" - [tools 包](../tools/README.zh.md)——工具呈现模式与 `presentAs` API。 - [agent-presets 包](../../preset/agent-presets/README.zh.md)——preset 如何组合 agent 及其常驻挂载。 -- [Node code-runtime 包](../../code-runtime/code-runtime-node/README.zh.md)——PTC 模式所需的 TypeScript 运行时。 +- [Node ptc-runtime 包](../../ptc-runtime/ptc-runtime-node/README.zh.md)——PTC 模式所需的 TypeScript 运行时。 - [PTC mode 执行器塌缩 note](../../../.agents/notes/implemented/bug-fix/2026-08-07-ptc-executor-collapse.zh.md)——通告面与可调用面为何保持一致。 - [core 分组地图](../README.zh.md)——core 各包如何组合。 diff --git a/packages/core/agent-tool-presentation/package.json b/packages/core/agent-tool-presentation/package.json index 10109f5ef1..09c088d5d4 100644 --- a/packages/core/agent-tool-presentation/package.json +++ b/packages/core/agent-tool-presentation/package.json @@ -35,7 +35,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", diff --git a/packages/core/agent-tool-presentation/src/index.ts b/packages/core/agent-tool-presentation/src/index.ts index ded8ff157c..221f424386 100644 --- a/packages/core/agent-tool-presentation/src/index.ts +++ b/packages/core/agent-tool-presentation/src/index.ts @@ -10,8 +10,8 @@ * joined to that preset and a PTC mode preset runs beside native ones in one * process. One row per composition, not one per session. * - * A PTC mode needs a TypeScript code runtime, which is a host-plane service - * ([`dsh-code-runtime-node`](../../../code-runtime/code-runtime-node/README.md)). + * A PTC mode needs a TypeScript PTC runtime, which is a host-plane service + * ([`dsh-ptc-runtime-node`](../../../ptc-runtime/ptc-runtime-node/README.md)). * This row therefore waits for it rather than assuming it: a preset selecting * PTC mode against a deployment that composes no runtime fails at mount, named * in the preset's own activation audit, instead of at the first prompt. @@ -28,7 +28,7 @@ import type {} from '@deepseek-ai/dsh-tools' export const name = 'tool-presentation' /** - * Required services. `codeRuntime` is NOT listed: a `native` row must mount in + * Required services. `ptcRuntime` is NOT listed: a `native` row must mount in * a deployment that composes no runtime, and the mode-dependent wait is * declared inside {@link apply} instead. */ @@ -64,9 +64,9 @@ export function apply(ctx: Context, config: Config): void { ctx.tools.presentAs('native') return } - // The wait is the loud failure: an entry still pending on `codeRuntime` is + // The wait is the loud failure: an entry still pending on `ptcRuntime` is // what `dsh-agent-presets` reports as an unusable row, naming this id. - ctx.inject(['codeRuntime'], (runtimeCtx: Context) => { + ctx.inject(['ptcRuntime'], (runtimeCtx: Context) => { runtimeCtx.tools.presentAs(config.mode) }) } diff --git a/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts b/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts index 51f6062a10..3621223528 100644 --- a/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts +++ b/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts @@ -1,7 +1,7 @@ /** * The row an agent preset carries to pick its tool presentation. What it owes * its caller: the choice reaches THIS agent and no other, it unwinds with the - * agent, and a code mode composed against a deployment with no code runtime + * agent, and a code mode composed against a deployment with no PTC runtime * stops at mount — where a preset's activation audit can name it — rather * than at the first prompt assembly. */ @@ -10,26 +10,26 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { createScope } from '@deepseek-ai/dsh-scope' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import ToolRuntime, { RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import { SessionId } from '@deepseek-ai/dsh-session' import { apply, Config, inject, name } from '@deepseek-ai/dsh-agent-tool-presentation' /** A runtime that never runs anything: presentation never dispatches. */ -class StubRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } +class StubRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'stub' - run(_request: CodeRunRequest): Promise { + run(_request: PtcRunRequest): Promise { return Promise.resolve({ logs: [] }) } } -/** A host plane with one tool, optionally carrying a code runtime. */ +/** A host plane with one tool, optionally carrying a PTC runtime. */ async function host(options: { runtime?: boolean } = {}) { const ctx = new Context() await ctx.plugin(SystemPrompt, {}) @@ -59,7 +59,7 @@ async function mount(ctx: Context, config: Config, id = 'agent') { } describe('the tool-presentation row', () => { - it('declares the services it uses without holding a code runtime hostage', () => { + it('declares the services it uses without holding a PTC runtime hostage', () => { // A `native` row must mount where no runtime is composed, so the wait is // conditional inside apply rather than static metadata. expect(inject).toEqual(['tools']) @@ -100,7 +100,7 @@ describe('the tool-presentation row', () => { expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false) }) - it('waits for a code runtime the deployment does not compose', async () => { + it('waits for a PTC runtime the deployment does not compose', async () => { const ctx = await host({ runtime: false }) const { agent, row } = await mount(ctx, { mode: 'ptc' }) @@ -108,7 +108,7 @@ describe('the tool-presentation row', () => { // Pending, not applied: `dsh-agent-presets` rejects a mount holding a row // that never reached a usable state, naming this id — so the preset fails // where the operator can act, instead of at the first request. - expect(row.ctx.get('codeRuntime')).toBeUndefined() + expect(row.ctx.get('ptcRuntime')).toBeUndefined() const assembly = await ctx.systemPrompt.assemble({ scope: agent }) expect(assembly.tools.map(tool => tool.name)).toEqual(['echo']) }) diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index c9f8f5ba93..b74c9d7017 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/tools/README.md -README.md: 4304e447a57bbd87a6661ffe8cff574fadb8a3d5 -README.zh.md: fbe49361fcd742911eb98aa62a905eb84fd151d4 +README.md: 47c66882e15b21d710bf6a464ad9e457ba6b4d92 +README.zh.md: c176b7e1f5f906b4708f916cae98911ad3175a5d diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 4304e447a5..47c66882e1 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -74,7 +74,7 @@ The `mode` config decides what the model sees: `native` (every visible schema), | `mode` | `native` | How visible tools are presented to the model: `native`, `ptc`, or `both` | | `maxParallelSubCalls` | `10` | Concurrency cap for a `run_code` program's overlapping sub-calls; `1` restores strictly serial dispatch | -The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tools) is the exhaustive source for every accepted field. Non-native modes require a composed `ctx.codeRuntime` whose language has a registered SDK renderer; an agent preset selects its own presentation with [`dsh-agent-tool-presentation`](../agent-tool-presentation/README.md), and one agent can shadow the default with `presentAs(mode)`. +The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tools) is the exhaustive source for every accepted field. Non-native modes require a composed `ctx.ptcRuntime` whose language has a registered SDK renderer; an agent preset selects its own presentation with [`dsh-agent-tool-presentation`](../agent-tool-presentation/README.md), and one agent can shadow the default with `presentAs(mode)`. ### Restrict tools per agent @@ -226,7 +226,7 @@ These limits define when the registry needs special care. They are current packa - **`tools/pre-execute` deliberately cannot rewrite `exec.arguments`** — logged and rendered args would desync from what ran; the rewrite design is [a proposed Agent Note](../../../.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.md). - **Caller-defined subagent and workflow structured outputs remain object-rooted** — this is a consumer-level guard; the shared schema vocabulary and tool outputs support every JSON root. - **`timeoutMs` on a definition is declarative only** — the registry never enforces deadlines; enforcement requires the `@deepseek-ai/dsh-tool-call-timeout-policy` wrapper. -- **PTC mode's SDK language follows the one loaded runtime, and a presentation is per agent rather than per tool** — `mode: ptc`/`both` rejects prompt assembly unless `ctx.codeRuntime.language` has a registered SDK renderer; within one agent no tool can be native-only while another is ptc-only. +- **PTC mode's SDK language follows the one loaded runtime, and a presentation is per agent rather than per tool** — `mode: ptc`/`both` rejects prompt assembly unless `ctx.ptcRuntime.language` has a registered SDK renderer; within one agent no tool can be native-only while another is ptc-only. - **PTC mode intermediate values are execution-local and unbounded by bytes** — they cannot be reconstructed from session replay and may exhaust process or worker memory; only the outer `run_code` output has the worker's configurable hard cap. - **`run_code` state is fresh per run** — a persistent REPL-style kernel is rejected for the MVP, because cross-call state would be invisible to the log. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index fbe49361fc..c176b7e1f5 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -74,7 +74,7 @@ ctx.tools.register(defineTool({ | `mode` | `native` | 可见工具向模型呈现的方式:`native`、`ptc` 或 `both` | | `maxParallelSubCalls` | `10` | `run_code` 程序重叠子调用的并发上限;`1` 恢复严格串行分发 | -生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tools)是每个受支持字段的穷尽式真源。非原生模式要求已组合的 `ctx.codeRuntime` 且其语言有已注册的 SDK 渲染器;agent preset 通过 [`dsh-agent-tool-presentation`](../agent-tool-presentation/README.zh.md) 自行选择呈现方式,单个 agent 可用 `presentAs(mode)` 遮蔽默认值。 +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tools)是每个受支持字段的穷尽式真源。非原生模式要求已组合的 `ctx.ptcRuntime` 且其语言有已注册的 SDK 渲染器;agent preset 通过 [`dsh-agent-tool-presentation`](../agent-tool-presentation/README.zh.md) 自行选择呈现方式,单个 agent 可用 `presentAs(mode)` 遮蔽默认值。 ### 按 agent 限制工具 @@ -226,7 +226,7 @@ Program-only SDK bindings: - **`tools/pre-execute` 有意不允许改写 `exec.arguments`**:否则日志记录与呈现的参数会与实际运行内容失去同步;改写设计记录在[拟议的 Agent Note](../../../.agents/notes/proposed/feature/2026-06-30-pre-tool-input-rewrite.zh.md)中。 - **调用方定义的 subagent 与工作流结构化输出仍要求对象根**:这是消费方层面的守卫;共享 schema 词汇与工具输出支持任意 JSON 根。 - **定义中的 `timeoutMs` 仅作声明之用**:注册表绝不会强制执行截止时间;要强制执行,必须使用 `@deepseek-ai/dsh-tool-call-timeout-policy` 包装层。 -- **PTC mode 的 SDK 语言由当前加载的运行时决定,且呈现方式按 agent 而非按工具**:`mode: ptc`/`both` 会拒绝组装提示词,除非 `ctx.codeRuntime.language` 有已注册的 SDK 渲染器;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 +- **PTC mode 的 SDK 语言由当前加载的运行时决定,且呈现方式按 agent 而非按工具**:`mode: ptc`/`both` 会拒绝组装提示词,除非 `ctx.ptcRuntime.language` 有已注册的 SDK 渲染器;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 - **PTC mode 中间值只存在于执行局部,且没有字节上限**:它们无法从会话回放重建,并可能耗尽进程或 worker 内存;只有外层 `run_code` 输出受 worker 可配置的硬上限约束。 - **每次运行都会获得全新的 `run_code` 状态**:MVP 不采用持久 REPL 风格内核,因为跨调用状态不会出现在日志中。 diff --git a/packages/core/tools/package.json b/packages/core/tools/package.json index c501d07d90..80b2511eaa 100644 --- a/packages/core/tools/package.json +++ b/packages/core/tools/package.json @@ -43,7 +43,7 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", @@ -61,7 +61,7 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 47dad9bb02..7ed44bbbda 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -14,7 +14,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type { UserMessage } from '@deepseek-ai/dsh-session' import { assertNever, deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import type { PromptSection, ToolProviderResult } from '@deepseek-ai/dsh-system-prompt' -import type { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import type {} from '@deepseek-ai/dsh-sandbox-policy' // Type-only: makes `ctx.get('approval')` resolve to the ApprovalService // augmentation. The seam stays optional at runtime — see `serviceAsk`. @@ -23,24 +23,24 @@ import type { ToolCallView, ToolResultView } from './presentation.ts' import { assertSupportedJsonSchema, validateJsonSchemaValue } from './json-schema.ts' import type { JsonSchemaNode } from './json-schema.ts' import { createRunCodeTool, RUN_CODE_NAME } from './ptc.ts' -import type { CodeSdkLanguage } from './ptc.ts' +import type { PtcSdkLanguage } from './ptc.ts' import { renderToolsSdk } from './ts-types.ts' import type { ToolSdkSchema } from './ts-types.ts' import { renderToolsSdkPy } from './py-types.ts' /** * Language → SDK-section renderer. The registry looks up the loaded - * `ctx.codeRuntime.language` in this table when assembling the `tools:sdk` + * `ctx.ptcRuntime.language` in this table when assembling the `tools:sdk` * section under a non-native mode; a runtime whose language is not a key * fails the assembly loudly (same idiom as `toolOrder` violations). Adding a - * new backend language is three parallel edits — a {@link CodeSdkLanguage} + * new backend language is three parallel edits — a {@link PtcSdkLanguage} * member, an entry here, and a `RUN_CODE_FLAVORS` entry in `ptc.ts` for * its `run_code` schema strings — plus the renderer function this table points * at. The `satisfies` clause pins this table's key set to that union, which * the flavor table is checked against too, so any of the three left out is a * typecheck failure. What no check reaches is the prose that names the values - * instead of deriving them: the seam's `dsh-code-runtime` README pair, its - * `CodeRuntime.language` JSDoc, and `docs/subsystems/code-runtime.md` + * instead of deriving them: the seam's `dsh-ptc-runtime` README pair, its + * `PtcRuntime.language` JSDoc, and `docs/subsystems/ptc-runtime.md` * with its zh pair, plus this package's own README pair and the * {@link Config.mode} JSDoc. */ @@ -54,7 +54,7 @@ const PTC_ONLY_INSTRUCTION = `\`${RUN_CODE_NAME}\` is the only tool you can call const SDK_RENDERERS: Record string> = { typescript: renderToolsSdk, python: renderToolsSdkPy, -} satisfies Record string> +} satisfies Record string> export { defineTool, @@ -651,7 +651,7 @@ export interface Config { * sends only `run_code` plus a generated SDK prompt and collapses the * executor to the same surface (a model-direct call may only name * `run_code`; `run_code` SDK sub-dispatches keep every visible tool); `both` - * sends both forms. PTC mode requires a `ctx.codeRuntime` whose `language` + * sends both forms. PTC mode requires a `ctx.ptcRuntime` whose `language` * has a registered SDK renderer (TypeScript or Python) and fail prompt * assembly when it is absent or has no renderer. Under `ptc`, native names * in `toolOrder` are invalid. @@ -874,11 +874,11 @@ export class ToolRuntime extends Service { text: (context) => { const mode = this.modeFor(context.scope) if (mode === 'native') return '' - const runtime = this.requireCodeRuntime(mode) + const runtime = this.requirePtcRuntime(mode) // Own-property read: a language like `toString`/`constructor` would // otherwise resolve an inherited Object.prototype member as a renderer. const render = SDK_RENDERERS[runtime.language] - /* v8 ignore next -- requireCodeRuntime rejects an unknown language before this runs. */ + /* v8 ignore next -- requirePtcRuntime rejects an unknown language before this runs. */ if (render === undefined) throw new Error(`dsh-tools: no SDK renderer for ${runtime.language}`) return render(this.sdkSchemas(context.scope)) }, @@ -913,19 +913,19 @@ export class ToolRuntime extends Service { * and only for scopes whose mode actually presents it. * @returns the shared transport definition. */ - private requireCodeTransport(): ToolDefinition { + private requirePtcTransport(): ToolDefinition { this.ptcTransport ??= createRunCodeTool(this, { - requireRuntime: () => this.requireCodeRuntime(this.defaultMode), + requireRuntime: () => this.requirePtcRuntime(this.defaultMode), peekApprover: () => this.ctx.get('approval'), resolveSandboxPolicy: (exec) => { const policy = this.ctx.get('sandboxPolicy') - if (policy === undefined) throw new Error('dsh-tools: confined code runtime requires sandboxPolicy') + if (policy === undefined) throw new Error('dsh-tools: confined PTC runtime requires sandboxPolicy') return policy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session }) }, // The language-aware description/parameters getters read the runtime // without demanding one, so a native-default process can still project // the transport for an agent that chose code. - peekRuntime: () => this.ctx.get('codeRuntime'), + peekRuntime: () => this.ctx.get('ptcRuntime'), maxParallel: this.maxParallelSubCalls, shapeDispatchLog: dispatch => this.shapeDispatchLog(dispatch), }) @@ -989,7 +989,7 @@ export class ToolRuntime extends Service { // flavor-table guard would otherwise surface first. This keeps the // renderer-table rejection the canonical assembly-time error for a // language with no SDK renderer. - this.requireCodeRuntime(mode) + this.requirePtcRuntime(mode) const schemas = [...view.visible.values()].map(definition => this.schemaOf(definition, false)) if (mode === 'ptc') { return { @@ -1001,10 +1001,10 @@ export class ToolRuntime extends Service { } /** - * Resolve the code runtime or throw the actionable misconfiguration error. + * Resolve the PTC runtime or throw the actionable misconfiguration error. * Read at use time (assembly / run_code execution), NOT via static * `inject`: an inject entry would hold `ctx.tools` — and every tool plugin - * behind it — hostage to a code runtime existing even under `mode: + * behind it — hostage to a PTC runtime existing even under `mode: * 'native'`. * * Assembly and `run_code` execution read separately, so the language is not @@ -1014,10 +1014,10 @@ export class ToolRuntime extends Service { * other. Binding it is deferred until a second backend ships (the first * point it is testable). */ - private requireCodeRuntime(mode: ToolPresentationMode): CodeRuntime { - const runtime = this.ctx.get('codeRuntime') + private requirePtcRuntime(mode: ToolPresentationMode): PtcRuntime { + const runtime = this.ctx.get('ptcRuntime') if (!runtime) { - throw new Error(`dsh-tools: mode "${mode}" requires a code runtime — load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-node) or set tools mode to "native"`) + throw new Error(`dsh-tools: mode "${mode}" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or set tools mode to "native"`) } if (!Object.hasOwn(SDK_RENDERERS, runtime.language)) { const known = Object.keys(SDK_RENDERERS).map(name => JSON.stringify(name)).join(', ') @@ -1185,7 +1185,7 @@ export class ToolRuntime extends Service { // changes. Per scope: a native agent must not find `run_code` in its // dispatch table because some other agent in the process presents it. if (this.modeFor(scope) !== 'native') { - visible.set(RUN_CODE_NAME, this.requireCodeTransport()) + visible.set(RUN_CODE_NAME, this.requirePtcTransport()) } return { visible, knownNames, restrictableNames } } diff --git a/packages/core/tools/src/ptc.ts b/packages/core/tools/src/ptc.ts index e36d2653cc..079cff6dd6 100644 --- a/packages/core/tools/src/ptc.ts +++ b/packages/core/tools/src/ptc.ts @@ -9,7 +9,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId } from '@deepseek-ai/dsh-llm' -import type { CodeBindingFunction, CodeRunResult, CodeRunSandbox, CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type { PtcBindingFunction, PtcRunResult, PtcRunSandbox, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import { approveEscalation, ESCALATION_TARGETS, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import type { ApprovalService } from '@deepseek-ai/dsh-user-approval' @@ -25,7 +25,7 @@ export const RUN_CODE_NAME = 'run_code' /** * The language-specific `run_code` schema text: the tool `description` and its * `code` parameter description, kept together so a language's two model-facing - * strings share one source of truth. Keyed by `CodeRuntime.language`, mirroring + * strings share one source of truth. Keyed by `PtcRuntime.language`, mirroring * `SDK_RENDERERS` in {@link ./index.ts}. The emitted flavor MUST match the * semantics the same language's SDK instructions promise, so the model never * receives a TypeScript schema beside a Python SDK (or vice versa). @@ -75,17 +75,17 @@ const PYTHON_FLAVOR: RunCodeFlavor = { * {@link RUN_CODE_FLAVORS} here and `SDK_RENDERERS` in {@link ./index.ts} — are * checked against this union with `satisfies`, so a language added to one and * not the other fails `typecheck` instead of waiting for a runtime that reports - * it. The tables stay declared `Record` because `CodeRuntime.language` + * it. The tables stay declared `Record` because `PtcRuntime.language` * is an unconstrained `string`: this union pins what the harness ships, while the * `Object.hasOwn` guards reject what a mounted runtime may report. */ -export type CodeSdkLanguage = 'typescript' | 'python' +export type PtcSdkLanguage = 'typescript' | 'python' -/** Per-language `run_code` schema flavors (see {@link RunCodeFlavor}); one entry per {@link CodeSdkLanguage}. */ +/** Per-language `run_code` schema flavors (see {@link RunCodeFlavor}); one entry per {@link PtcSdkLanguage}. */ const RUN_CODE_FLAVORS: Record = { typescript: TYPESCRIPT_FLAVOR, python: PYTHON_FLAVOR, -} satisfies Record +} satisfies Record /** * The `description` parameter's model-facing description: language-independent @@ -104,7 +104,7 @@ const RUN_CODE_CONTROLS = { justification: { type: 'string', description: 'Reason this complete program needs wider access, shown to the user for approval.' }, } as const -function controlParameters(runtime: CodeRuntime | undefined) { +function controlParameters(runtime: PtcRuntime | undefined) { // Catalog readers have no mounted runtime; real model assembly requires one. if (runtime === undefined) return RUN_CODE_CONTROLS return { @@ -119,7 +119,7 @@ function controlParameters(runtime: CodeRuntime | undefined) { } } -function escalationGuidance(runtime: CodeRuntime | undefined): string { +function escalationGuidance(runtime: PtcRuntime | undefined): string { return runtime?.sandboxMode === undefined ? '' : ' A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.' } @@ -130,20 +130,20 @@ function escalationGuidance(runtime: CodeRuntime | undefined): string { * the SDK section's language. `peekRuntime` returns `undefined` only when no * runtime is mounted, which reaches this function through definition readers * and `schemas()` — the doc-catalog harvest is the only shipped one, and none - * of them feeds a model, because `wireSchemas` calls `requireCodeRuntime` + * of them feeds a model, because `wireSchemas` calls `requirePtcRuntime` * before projecting — so that path degrades to {@link TYPESCRIPT_FLAVOR}. A * mounted runtime whose language has no flavor entry fails loud, exactly as - * `requireCodeRuntime` rejects it at assembly. Keeping this table in step with - * `SDK_RENDERERS` is the compiler's job ({@link CodeSdkLanguage}); what this + * `requirePtcRuntime` rejects it at assembly. Keeping this table in step with + * `SDK_RENDERERS` is the compiler's job ({@link PtcSdkLanguage}); what this * guard owns is the runtime-supplied language neither table knows, which never * yields a wrong-language schema for a real runtime. */ -function resolveFlavor(peekRuntime: () => CodeRuntime | undefined): RunCodeFlavor { +function resolveFlavor(peekRuntime: () => PtcRuntime | undefined): RunCodeFlavor { const runtime = peekRuntime() if (runtime === undefined) { // No runtime mounted: reached by definition readers and `schemas()`, of // which the doc-catalog harvest is the only shipped one. None feeds a - // model — `wireSchemas` calls `requireCodeRuntime` before projecting, so + // model — `wireSchemas` calls `requirePtcRuntime` before projecting, so // the assembly path never arrives here. Degrade to the TS default. return TYPESCRIPT_FLAVOR } @@ -285,7 +285,7 @@ function renderValue(value: JsonValue): string { } /** Canonical value returned by the outer PTC mode transport. */ -type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: CodeRunSandbox } +type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: PtcRunSandbox } /** * Registry-private capabilities the bridge receives at construction — the @@ -297,15 +297,15 @@ export interface RunCodeBridgeOptions { peekApprover: () => ApprovalService | undefined /** Resolves standing Session authority only for a runtime that enforces file policy. */ resolveSandboxPolicy: (exec: ToolRunContext) => SandboxExecutionPolicy - /** Resolves `ctx.codeRuntime` or throws the loud misconfiguration error (shared with the registry's assembly-time checks). */ - requireRuntime: () => CodeRuntime + /** Resolves `ctx.ptcRuntime` or throws the loud misconfiguration error (shared with the registry's assembly-time checks). */ + requireRuntime: () => PtcRuntime /** - * Reads `ctx.codeRuntime` without throwing: `undefined` when none is mounted. + * Reads `ctx.ptcRuntime` without throwing: `undefined` when none is mounted. * Lets schema emission tell "no runtime" (degrade to TS; the readers that * reach it are {@link resolveFlavor}'s) apart from "unknown language" (fail * loud). */ - peekRuntime: () => CodeRuntime | undefined + peekRuntime: () => PtcRuntime | undefined /** The run's overlap cap for parallel-classified sub-calls (the registry passes its validated `maxParallelSubCalls`). */ maxParallel: number /** Runs the contained `tools/ptc-dispatch-log` waterfall over one settled sub-dispatch (the registry's private invoker). */ @@ -376,7 +376,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO const runtime = requireRuntime() validateEscalationArgs(args.sandbox_permissions, args.justification) if (args.timeoutMs !== undefined && runtime.timeout === undefined) { - throw new Error('timeoutMs is not available for this code runtime') + throw new Error('timeoutMs is not available for this PTC runtime') } if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) { throw new Error('invalid timeoutMs: expected a positive finite number') @@ -384,7 +384,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO const standingPolicy = runtime.sandboxMode === undefined ? undefined : options.resolveSandboxPolicy(exec) let policy = standingPolicy if (args.sandbox_permissions !== undefined && args.justification !== undefined) { - if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this code runtime') + if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime') const approvedMode = await approveEscalation({ requestedMode: args.sandbox_permissions, justification: args.justification, @@ -528,7 +528,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO // would be narrowed away by control flow analysis. const runOver = (): boolean => runController.signal.aborted - const binding = (name: string): CodeBindingFunction => async (rawArgs: unknown): Promise => { + const binding = (name: string): PtcBindingFunction => async (rawArgs: unknown): Promise => { if (runOver()) { throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`) } @@ -671,7 +671,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO // own key (a plain-object assignment would hit the prototype setter, // silently dropping the binding), and the runtime host resolves // binding names as own properties only. - const functions: Record = Object.create(null) as Record + const functions: Record = Object.create(null) as Record // Enumerate the CALLING AGENT's visible set (scoped tools join, // restricted globals vanish) — the same view the SDK section declared, // so a program can bind exactly what its prompt promised; sub-dispatch @@ -682,7 +682,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO } try { - let result: CodeRunResult + let result: PtcRunResult try { result = await runtime.run(runtime.resolve({ program: args.code, diff --git a/packages/core/tools/src/py-types.ts b/packages/core/tools/src/py-types.ts index 74669a9739..cbdf23f38c 100644 --- a/packages/core/tools/src/py-types.ts +++ b/packages/core/tools/src/py-types.ts @@ -2,7 +2,7 @@ * PTC mode codegen — Python flavor. The pure projection from registered tool schemas to the * Python SDK text the model programs against under `runtime.language === 'python'`. Sibling of * {@link ./ts-types.ts | ts-types.ts}; the two files are two projections of the same registry - * store, keyed by the loaded {@link @deepseek-ai/dsh-code-runtime#CodeRuntime.language | code + * store, keyed by the loaded {@link @deepseek-ai/dsh-ptc-runtime#PtcRuntime.language | code * runtime's language}. * * Under `mode: 'ptc'` the native tool schemas are omitted from the request, so this generated diff --git a/packages/core/tools/tests/invariant.spec.ts b/packages/core/tools/tests/invariant.spec.ts index 202963379e..3cf19afa5c 100644 --- a/packages/core/tools/tests/invariant.spec.ts +++ b/packages/core/tools/tests/invariant.spec.ts @@ -126,7 +126,7 @@ describe('tool-pipeline invariants', () => { })).not.toThrow() }) - it('rejects a nested code dispatch that changes its parent chain root before append', async () => { + it('rejects a nested PTC dispatch that changes its parent chain root before append', async () => { const ctx = await setup() const session = ctx.sessions.create() session.append('turn/start', { turn: 1 }) diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index ddc1ac9cb3..fcf324af67 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -4,8 +4,8 @@ import { createUserMessage, ToolCallId } 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 { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import ToolRuntime, { CodeRunFailedError, RUN_CODE_NAME, TOOL_ABORTED_BEFORE_DISPATCH, defineContentToolFixture, defineTool } from '@deepseek-ai/dsh-tools' import type { Config, JsonSchemaNode, PostToolDecision, ToolExecutionResult } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' @@ -26,21 +26,21 @@ const testToolSignal = new AbortController().signal * Service Definition / Service Provider / Consumer roles the seam promises. */ -/** A scriptable in-repo CodeRuntime: each test sets `behavior` to drive the bindings however it needs. */ -class FakeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } +/** A scriptable in-repo PtcRuntime: each test sets `behavior` to drive the bindings however it needs. */ +class FakeRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language: string readonly isolation = 'fake' - behavior: (request: CodeRunRequest) => Promise = () => Promise.resolve({ logs: [] }) - lastRequest?: CodeRunRequest + behavior: (request: PtcRunRequest) => Promise = () => Promise.resolve({ logs: [] }) + lastRequest?: PtcRunRequest constructor(ctx: Context, config: { language?: string } = {}) { super(ctx) this.language = config.language ?? 'typescript' } - run(request: CodeRunRequest): Promise { + run(request: PtcRunRequest): Promise { this.lastRequest = request return this.behavior(request) } @@ -60,7 +60,7 @@ async function setup(options: SetupOptions = {}) { let runtime: FakeRuntime | undefined if (options.runtime !== false) { await ctx.plugin(FakeRuntime, options.runtime ?? {}) - runtime = ctx.codeRuntime as FakeRuntime + runtime = ctx.ptcRuntime as FakeRuntime } return { ctx, tools: ctx.tools, systemPrompt: ctx.systemPrompt, runtime: runtime! } } @@ -407,9 +407,9 @@ describe('mode-aware wire contribution', () => { expect(text(first)).toBe(text(second)) }) - it('rejects every assembly when a non-native mode has no code runtime', async () => { + it('rejects every assembly when a non-native mode has no PTC runtime', async () => { const { systemPrompt } = await setup({ mode: 'ptc', runtime: false }) - await expect(systemPrompt.assemble()).rejects.toThrow(/requires a code runtime/) + await expect(systemPrompt.assemble()).rejects.toThrow(/requires a PTC runtime/) }) it('rejects every assembly when the runtime language has no registered SDK renderer', async () => { @@ -428,7 +428,7 @@ describe('mode-aware wire contribution', () => { }) it("assembles under a python runtime in mode 'both' as well, SDK and schema together", async () => { - // `both` reaches the same wireSchemas/requireCodeRuntime/SDK-section code + // `both` reaches the same wireSchemas/requirePtcRuntime/SDK-section code // as `ptc`, so this pins the mode-by-language matrix rather than a // separate path — including that the `wireSchemas` projection behind // `assembly.tools` picks the Python flavor under `both` instead of hitting @@ -473,12 +473,12 @@ describe('mode-aware wire contribution', () => { it('resolves the run_code schema flavor lazily and fails loud on a language absent from the flavor table', async () => { // The flavor getter reads the runtime directly (peekRuntime), so it — not - // requireCodeRuntime — owns the flavor-table guard. Keeping + // requirePtcRuntime — owns the flavor-table guard. Keeping // RUN_CODE_FLAVORS in step with SDK_RENDERERS is the compiler's job (both - // are `satisfies`-checked against CodeSdkLanguage), so what the guard + // are `satisfies`-checked against PtcSdkLanguage), so what the guard // covers is a mounted runtime naming a language absent from both tables, // which throws when the schema is projected. Assembly's - // requireCodeRuntime rejects such a language earlier; this reaches the + // requirePtcRuntime rejects such a language earlier; this reaches the // guard on its own. const { ctx } = await setup({ mode: 'ptc', runtime: { language: 'ruby' } }) const definition = ctx.tools.get(RUN_CODE_NAME) @@ -1369,7 +1369,7 @@ describe('the run_code dispatch bridge', () => { await ctx.plugin(ToolRuntime, { mode: 'ptc' }) const result = await runCode(ctx, 'program') expect(result.isError).toBe(true) - expect((result.content[0] as { text: string }).text).toContain('requires a code runtime') + expect((result.content[0] as { text: string }).text).toContain('requires a PTC runtime') }) it('presents the model-authored description as the execute-card title over the program input', async () => { @@ -1397,7 +1397,7 @@ describe('the run_code dispatch bridge', () => { ['result only', { logs: [], value: 'returned' }, 'returned'], ['logs plus result', { logs: ['printed'], value: 'returned' }, 'printed\nreturned'], ['no output', { logs: [] }, '(run_code completed with no output)'], - ] as [string, CodeRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => { + ] as [string, PtcRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => { const { ctx, runtime } = await setup({ mode: 'ptc' }) runtime.behavior = () => Promise.resolve(output) @@ -1652,7 +1652,7 @@ describe('the run_code dispatch bridge', () => { expect(text.length).toBeLessThan(11_000) }) - it('short-circuits a pre-aborted outer signal before the code runtime', async () => { + it('short-circuits a pre-aborted outer signal before the PTC runtime', async () => { const { ctx, runtime } = await setup({ mode: 'ptc' }) const calls = registerEcho(ctx) runtime.behavior = (request) => { @@ -1937,7 +1937,7 @@ describe('per-agent presentation', () => { scope.ctx.tools.presentAs('both') await expect(systemPrompt.assemble({ scope: agent })) - .rejects.toThrow('mode "both" requires a code runtime') + .rejects.toThrow('mode "both" requires a PTC runtime') }) }) @@ -1953,8 +1953,8 @@ describe('PTC standing file policy and sandbox outcomes', () => { await ctx.plugin(ConfinedFakeRuntime) const result = await runCode(ctx, 'return 1') expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: dsh-tools: confined code runtime requires sandboxPolicy' }]) - expect((ctx.codeRuntime as ConfinedFakeRuntime).lastRequest).toBeUndefined() + expect(result.content).toEqual([{ type: 'text', text: 'Error: dsh-tools: confined PTC runtime requires sandboxPolicy' }]) + expect((ctx.ptcRuntime as ConfinedFakeRuntime).lastRequest).toBeUndefined() } finally { await ctx.fiber.dispose() } }) @@ -1966,7 +1966,7 @@ describe('PTC standing file policy and sandbox outcomes', () => { await ctx.plugin(ConfinedFakeRuntime) const result = await runCode(ctx, 'return 1') expect(result.isError).not.toBe(true) - expect((ctx.codeRuntime as ConfinedFakeRuntime).lastRequest?.sandboxPolicy).toEqual(ctx.sandboxPolicy.resolve()) + expect((ctx.ptcRuntime as ConfinedFakeRuntime).lastRequest?.sandboxPolicy).toEqual(ctx.sandboxPolicy.resolve()) } finally { await ctx.fiber.dispose() } }) @@ -2060,7 +2060,7 @@ describe('per-program execution controls', () => { arguments: { code: 'return 1', description: 'Try an unsupported mode', sandbox_permissions: 'workspace-write', justification: 'Need file writes' }, }) expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this code runtime') + expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this PTC runtime') expect(runtime.lastRequest).toBeUndefined() } finally { await ctx.fiber.dispose() } }) diff --git a/packages/core/tools/tsconfig.json b/packages/core/tools/tsconfig.json index c3e80174bc..669b55d8d4 100644 --- a/packages/core/tools/tsconfig.json +++ b/packages/core/tools/tsconfig.json @@ -12,7 +12,7 @@ "path": "../../core/session" }, { - "path": "../../code-runtime/code-runtime" + "path": "../../ptc-runtime/ptc-runtime" }, { "path": "../../../vendor/cosmokit" diff --git a/packages/experimental/README.i18n.yaml b/packages/experimental/README.i18n.yaml index 851883eb5e..88b97c83be 100644 --- a/packages/experimental/README.i18n.yaml +++ b/packages/experimental/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/README.md -README.md: c4a95f903b8025d4823276bfd5811e94e6a2c419 -README.zh.md: 2ba1ae534b43a666fc424d0783e4c09188857274 +README.md: 2c79f67ce679bc8d463cef14fb39dcb612fa3c77 +README.zh.md: 63773cde1dba439da90f5744223a63a0ee005a53 diff --git a/packages/experimental/README.md b/packages/experimental/README.md index c4a95f903b..2c79f67ce6 100644 --- a/packages/experimental/README.md +++ b/packages/experimental/README.md @@ -28,7 +28,7 @@ The experimental group contains prototype capabilities whose contracts can chang | [`agent-team`](agent-team/README.md) | Named teammates with durable messages and a shared task board | `ctx.agentTeams` | | [`agent-team-web-profile`](agent-team-web-profile/README.md) | Published opt-in Web layer for Agent Teams | — | | [`client-ui-agent-team`](client-ui-agent-team/README.md) | Team roster, task board, and teammate navigation for Web | — | -| [`code-runtime-python`](code-runtime-python/README.md) | CPython subprocess backend for the code-execution seam | `ctx.codeRuntime` | +| [`ptc-runtime-python`](ptc-runtime-python/README.md) | CPython subprocess backend for the code-execution seam | `ctx.ptcRuntime` | | [`inspector`](inspector/README.md) | Cross-realm CDP hub for Host debugging, Client Runtime inspection, network capture, and Cordis trees | `ctx.inspector` | | [`tool-agent-team`](tool-agent-team/README.md) | Nine tools that let the model create, message, and coordinate teammates | registers scoped tools on `ctx.tools` | | [`webworker-packer`](webworker-packer/README.md) | Builds the gzip-compressed VFS image consumed by the browser worker preview | library and CLI — no ctx key | diff --git a/packages/experimental/README.zh.md b/packages/experimental/README.zh.md index 2ba1ae534b..63773cde1d 100644 --- a/packages/experimental/README.zh.md +++ b/packages/experimental/README.zh.md @@ -28,7 +28,7 @@ kind: "package-group" | [`agent-team`](agent-team/README.zh.md) | 具名 teammate,成员之间持久消息与共享任务板 | `ctx.agentTeams` | | [`agent-team-web-profile`](agent-team-web-profile/README.zh.md) | Agent Teams 的公开 opt-in Web 层 | — | | [`client-ui-agent-team`](client-ui-agent-team/README.zh.md) | Web Team roster、任务板与 teammate 导航 | — | -| [`code-runtime-python`](code-runtime-python/README.zh.md) | 代码执行 seam 的 CPython 子进程后端 | `ctx.codeRuntime` | +| [`ptc-runtime-python`](ptc-runtime-python/README.zh.md) | 代码执行 seam 的 CPython 子进程后端 | `ctx.ptcRuntime` | | [`inspector`](inspector/README.zh.md) | 用于 Host 调试、Client Runtime 检查、网络采集与 Cordis 树的跨 realm CDP hub | `ctx.inspector` | | [`tool-agent-team`](tool-agent-team/README.zh.md) | 让模型创建、发消息与协调 teammate 的九个工具 | 按作用域注册工具到 `ctx.tools` | | [`webworker-packer`](webworker-packer/README.zh.md) | 构建浏览器 worker 预览所消费的 gzip 压缩虚拟文件系统(VFS)镜像 | 库与 CLI(命令行界面),不使用 ctx key | diff --git a/packages/experimental/code-runtime-python/README.i18n.yaml b/packages/experimental/ptc-runtime-python/README.i18n.yaml similarity index 68% rename from packages/experimental/code-runtime-python/README.i18n.yaml rename to packages/experimental/ptc-runtime-python/README.i18n.yaml index ea58090eee..d47630790c 100644 --- a/packages/experimental/code-runtime-python/README.i18n.yaml +++ b/packages/experimental/ptc-runtime-python/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/experimental/code-runtime-python/README.md -README.md: 123f53fba415a28dff0730bd5b6e5ed45debfcd7 -README.zh.md: 8de7cc3cfd10b23650285ab23469d4509fc12c4a +# pnpm run verify-translation-pairing --write packages/experimental/ptc-runtime-python/README.md +README.md: 53fded2e42be72c87a9675beb1e48d8b8ed59c6d +README.zh.md: 8c9a18d5cc910960700deeb65bf1c77e60439115 diff --git a/packages/experimental/code-runtime-python/README.md b/packages/experimental/ptc-runtime-python/README.md similarity index 78% rename from packages/experimental/code-runtime-python/README.md rename to packages/experimental/ptc-runtime-python/README.md index 123f53fba4..53fded2e42 100644 --- a/packages/experimental/code-runtime-python/README.md +++ b/packages/experimental/ptc-runtime-python/README.md @@ -1,9 +1,9 @@ --- -description: "CPython-subprocess code runtime: the dsh-code-runtime seam implementation for Python model code, with the fd-3 wire protocol it speaks." +description: "CPython-subprocess PTC runtime: the dsh-ptc-runtime seam implementation for Python model code, with the fd-3 wire protocol it speaks." kind: "package-reference" --- -# @deepseek-ai/dsh-experimental-code-runtime-python +# @deepseek-ai/dsh-experimental-ptc-runtime-python English | [中文](README.zh.md) @@ -25,13 +25,13 @@ This private experimental package lets source-checkout compositions run model-ge ## Use this package -Choose this private experimental package only in an explicit source-checkout composition. Register `PythonCodeRuntime` beside `dsh-tools`; `run(resolve(request))` executes each program in a fresh CPython 3.10+ subprocess, resolving with `result.value` on success and `result.error` on failure (the orthogonal `CodeRunFailure.kind` taxonomy classifies parse failures, thrown exceptions, invalid completions, output overflows, budget expiry, aborts, and substrate death). It rejects only for seam misuse — a malformed binding namespace, or a call after disposal. Configuration is rejected at load: a non-Unix platform; an explicit `pythonBin` that is not an executable regular file or a bare name that does not resolve on `PATH`; a non-CPython, pre-3.10, or probe-failing interpreter; a non-positive or non-integer budget; a `maxLogBytes` below the truncation-marker floor (64); a timer value `setTimeout` would clamp; a budget larger than the effective fd-3 frame cap (lowered when the host heap cannot safely parse a near-cap frame); or an `addressSpaceMb`/output-budget pair whose worst-case peak would breach `RLIMIT_AS`. +Choose this private experimental package only in an explicit source-checkout composition. Register `PythonPtcRuntime` beside `dsh-tools`; `run(resolve(request))` executes each program in a fresh CPython 3.10+ subprocess, resolving with `result.value` on success and `result.error` on failure (the orthogonal `PtcRunFailure.kind` taxonomy classifies parse failures, thrown exceptions, invalid completions, output overflows, budget expiry, aborts, and substrate death). It rejects only for seam misuse — a malformed binding namespace, or a call after disposal. Configuration is rejected at load: a non-Unix platform; an explicit `pythonBin` that is not an executable regular file or a bare name that does not resolve on `PATH`; a non-CPython, pre-3.10, or probe-failing interpreter; a non-positive or non-integer budget; a `maxLogBytes` below the truncation-marker floor (64); a timer value `setTimeout` would clamp; a budget larger than the effective fd-3 frame cap (lowered when the host heap cannot safely parse a near-cap frame); or an `addressSpaceMb`/output-budget pair whose worst-case peak would breach `RLIMIT_AS`. `resolve(request)` accepts an absolute `cwd` and uses the provider's configured `maxWallMs` deadline (600,000 ms by default). Explicit `timeoutMs` overrides and sandbox policies are unsupported and reject before execution. This provider does not advertise `sandboxMode` or return confinement facts. ### What you get -The package's default export is the `PythonCodeRuntime` plugin. Its public surface also re-exports the host-side protocol vocabulary: `validateChildFrame` (rebuilds every inbound frame), the lossless-JSON codec and meters (`encodeJsonPlain`, `checkDoneValue`, `hasUnsafeIntegerToken`, `hasNonLosslessNumber`), `logTruncationMarker` (the shared truncation-marker text), plus `resolvePythonBin` (interpreter lookup against the current `PATH`), `readProcessStart` (process-start statistics for tests), `detachResidual` (a test seam for the settled run's resource cleanup), and `hostFrameParseCeiling` (the heap-derived frame parse cap a given heap limit admits). Every cap is a validated `Config` field with a default: `cpuSeconds` (60), `maxWallMs` (600000), `addressSpaceMb` (512, not applied on Darwin), `maxLogBytes` (65536), `maxValueBytes` (32768), `graceMs` (3000), and `pythonBin` (`python3`, resolved, executable-checked, version-probed under a five-second force-kill deadline, and frozen at load). Each child receives only `TMPDIR`; ambient credentials, `PATH`, `HOME`, and other host state stay unavailable. +The package's default export is the `PythonPtcRuntime` plugin. Its public surface also re-exports the host-side protocol vocabulary: `validateChildFrame` (rebuilds every inbound frame), the lossless-JSON codec and meters (`encodeJsonPlain`, `checkDoneValue`, `hasUnsafeIntegerToken`, `hasNonLosslessNumber`), `logTruncationMarker` (the shared truncation-marker text), plus `resolvePythonBin` (interpreter lookup against the current `PATH`), `readProcessStart` (process-start statistics for tests), `detachResidual` (a test seam for the settled run's resource cleanup), and `hostFrameParseCeiling` (the heap-derived frame parse cap a given heap limit admits). Every cap is a validated `Config` field with a default: `cpuSeconds` (60), `maxWallMs` (600000), `addressSpaceMb` (512, not applied on Darwin), `maxLogBytes` (65536), `maxValueBytes` (32768), `graceMs` (3000), and `pythonBin` (`python3`, resolved, executable-checked, version-probed under a five-second force-kill deadline, and frozen at load). Each child receives only `TMPDIR`; ambient credentials, `PATH`, `HOME`, and other host state stay unavailable. ### The wire @@ -71,7 +71,7 @@ Completion values and binding arguments cross as exact JSON: values serialize wi | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | Plugin entry: `PythonCodeRuntime` — spawn, frame pump, budgets, containment, teardown; re-exports the protocol vocabulary | +| [`src/index.ts`](src/index.ts) | Plugin entry: `PythonPtcRuntime` — spawn, frame pump, budgets, containment, teardown; re-exports the protocol vocabulary | | [`src/protocol.ts`](src/protocol.ts) | Host side: frame codec, hostile-frame validators, lossless-JSON meters, shared marker text | | [`py/bootstrap.py`](py/bootstrap.py) | Child side: fd-3 channel, program execution, binding dispatch, ledger and settlement | | [`py/protocol.py`](py/protocol.py) | Python side: `PROTOCOL_FD`, `TypedDict` frame mirrors, `log_truncation_marker` | @@ -88,11 +88,11 @@ Completion values and binding arguments cross as exact JSON: values serialize wi Read these when the runtime contract is not enough. They move from the seam definition to the design record and the companion backend. -- [Code runtime seam](../../code-runtime/code-runtime/README.md) — the abstract contract this backend implements. -- [fd-3 protocol Agent Note](../../../.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.md) — design rationale and wire contract. +- [PTC runtime seam](../../ptc-runtime/ptc-runtime/README.md) — the abstract contract this backend implements. +- [fd-3 protocol Agent Note](../../../.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md) — design rationale and wire contract. - [Settlement-fixes Agent Note](../../../.agents/notes/archived/bug-fix/2026-07-31-code-runtime-python-settlement-fixes.md) — settlement, metering, and containment fixes and their regression cases. -- [Node process backend](../../code-runtime/code-runtime-node/README.md) — the released TypeScript sibling. -- [Code runtime subsystem reference](../../../docs/subsystems/code-runtime.md) — request/result vocabulary, bindings, and failure taxonomy. +- [Node process backend](../../ptc-runtime/ptc-runtime-node/README.md) — the released TypeScript sibling. +- [PTC runtime subsystem reference](../../../docs/subsystems/ptc-runtime.md) — request/result vocabulary, bindings, and failure taxonomy. ----- @@ -118,9 +118,9 @@ These limits define what the package does and does not cover; they are current p - **A binding REPLY value has no seam-level byte or depth cap** — `maxValueBytes` meters only the done frame's completion value; a wide binding reply is rebuilt host-side (`snapshotJsonValue` traversal) and encoded whole, bounded on both sides only by process memory (like a binding argument, which has no child-side budget either). - **No shipped profile mounts this provider** — the keyless `ptc-python-turn` snapshot replaces the headless PTC runtime through the real Loader; released profiles use the sandboxed Node process backend. - **Cross-channel log interleaving is backend-dependent** — Python stdout, stderr, and fd-3 log frames travel independently; each channel preserves its own order, while their total order in `result.logs` may differ. -- **CPython 3.10 or newer is required** — the configured executable is resolved and version-probed at load; unsupported interpreters fail before `ctx.codeRuntime` is registered. -- **The truncation-marker text and the tempdir prefix keep the pre-rename short names** — the marker `[dsh-code-runtime-python] log capture truncated at bytes` and the `dsh-code-runtime-python-` tempdir prefix are byte-anchored by tests and are independent of the npm package name; promotion (dropping the `experimental-` prefix) does not rename them. -- **`run()` is one-shot** — `logs` become available only after `CodeRunResult` resolves; there is no streaming-log or progress interface for output produced by a running program. +- **CPython 3.10 or newer is required** — the configured executable is resolved and version-probed at load; unsupported interpreters fail before `ctx.ptcRuntime` is registered. +- **Diagnostic and temporary-directory prefixes omit the package's experimental qualifier** — the marker `[dsh-ptc-runtime-python] log capture truncated at bytes` and the `dsh-ptc-runtime-python-` directory prefix identify this provider independently of its npm package name. The protocol mirror verifies identical marker bytes in TypeScript and Python. +- **`run()` is one-shot** — `logs` become available only after `PtcRunResult` resolves; there is no streaming-log or progress interface for output produced by a running program. - **No state persists across runs** — every request executes in a fresh subprocess; a persistent REPL-style kernel stays deferred until a backend brings its own logging scheme. - **An fd-3 frame whose raw length exceeds the effective frame parse cap settles the run as a worker-exit** — the cap is 64 MiB, or lower when the host's configured heap cannot safely parse a near-cap frame (`hostFrameParseCeiling`); `maxLogBytes`/`maxValueBytes` are load-bounded to the same cap so an honest child's frames always fit; a model-constructed binding ARGUMENT above the cap (a value with no seam-level budget) trips it too — an accepted residual of the OOM guard. - **A child that stops reading its replies settles the run as a worker-exit once the reply backlog passes 1024 frames** — the host writes replies one at a time, waiting for `drain` when the pipe is full; a child that keeps sending calls without consuming replies would otherwise grow the retained backlog (and the binding results it pins) until the wall clock, so the backlog cap fails the run early. Binding results carry no seam-level byte cap, so this is a count bound, not a byte bound. diff --git a/packages/experimental/code-runtime-python/README.zh.md b/packages/experimental/ptc-runtime-python/README.zh.md similarity index 77% rename from packages/experimental/code-runtime-python/README.zh.md rename to packages/experimental/ptc-runtime-python/README.zh.md index 8de7cc3cfd..8c9a18d5cc 100644 --- a/packages/experimental/code-runtime-python/README.zh.md +++ b/packages/experimental/ptc-runtime-python/README.zh.md @@ -1,9 +1,9 @@ --- -description: "CPython 子进程代码 runtime:为 Python 模型代码实现 dsh-code-runtime seam,及其使用的 fd-3 wire 协议。" +description: "CPython 子进程 PTC 运行时:为 Python 模型代码实现 dsh-ptc-runtime seam,及其使用的 fd-3 wire 协议。" kind: "package-reference" --- -# @deepseek-ai/dsh-experimental-code-runtime-python +# @deepseek-ai/dsh-experimental-ptc-runtime-python [English](README.md) | 中文 @@ -25,13 +25,13 @@ kind: "package-reference" ## 使用本包 -仅在显式源码检出组合中选择这个私有实验包。将 `PythonCodeRuntime` 与 `dsh-tools` 一起注册后,`run(resolve(request))` 会在全新的 CPython 3.10+ 子进程中执行每个程序;成功时以 `result.value` resolve,失败时以 `result.error` resolve(正交的 `CodeRunFailure.kind` 分类涵盖解析失败、抛出异常、无效完成值、输出溢出、预算到期、中止与执行基底终止)。仅有 seam 误用会 reject——binding 命名空间不合法,或在 dispose 后调用。配置在加载期拒绝:非 Unix 平台;不是可执行普通文件的显式 `pythonBin`,或无法在 `PATH` 上解析的裸名;非 CPython、低于 3.10 或探测失败的解释器;非正或非整数预算;低于截断标记下限(64)的 `maxLogBytes`;会被 `setTimeout` 截断的定时器值;超过有效 fd-3 帧上限的预算(宿主堆无法安全解析接近上限的帧时,该上限会降低);或最坏峰值会突破 `RLIMIT_AS` 的 `addressSpaceMb`/输出预算组合。 +仅在显式源码检出组合中选择这个私有实验包。将 `PythonPtcRuntime` 与 `dsh-tools` 一起注册后,`run(resolve(request))` 会在全新的 CPython 3.10+ 子进程中执行每个程序;成功时以 `result.value` resolve,失败时以 `result.error` resolve(正交的 `PtcRunFailure.kind` 分类涵盖解析失败、抛出异常、无效完成值、输出溢出、预算到期、中止与执行基底终止)。仅有 seam 误用会 reject——binding 命名空间不合法,或在 dispose 后调用。配置在加载期拒绝:非 Unix 平台;不是可执行普通文件的显式 `pythonBin`,或无法在 `PATH` 上解析的裸名;非 CPython、低于 3.10 或探测失败的解释器;非正或非整数预算;低于截断标记下限(64)的 `maxLogBytes`;会被 `setTimeout` 截断的定时器值;超过有效 fd-3 帧上限的预算(宿主堆无法安全解析接近上限的帧时,该上限会降低);或最坏峰值会突破 `RLIMIT_AS` 的 `addressSpaceMb`/输出预算组合。 `resolve(request)` 接受绝对 `cwd`,并使用提供方配置的 `maxWallMs` 截止时间(默认 600,000 ms)。显式 `timeoutMs` 覆盖与沙箱策略不受支持,会在执行前拒绝。本提供方不声明 `sandboxMode`,也不返回约束事实。 ### 你得到什么 -包的默认导出是 `PythonCodeRuntime` 插件。其公开面还重新导出宿主侧协议词汇:`validateChildFrame`(重建每条入站帧)、无损 JSON codec 与计量器(`encodeJsonPlain`、`checkDoneValue`、`hasUnsafeIntegerToken`、`hasNonLosslessNumber`)、`logTruncationMarker`(共享截断标记文本),以及 `resolvePythonBin`(对照当前 `PATH` 的解释器查找)、`readProcessStart`(供测试用的进程启动统计)、`detachResidual`(已结算运行的资源清理测试 seam)与 `hostFrameParseCeiling`(给定堆上限可容纳的堆推导帧解析上限)。每个上限都是带默认值并经校验的 `Config` 字段:`cpuSeconds`(60)、`maxWallMs`(600000)、`addressSpaceMb`(512,Darwin 上不生效)、`maxLogBytes`(65536)、`maxValueBytes`(32768)、`graceMs`(3000)与 `pythonBin`(`python3`,在加载期解析、检查可执行性,在五秒强制终止期限内探测版本并固定)。每个子进程只接收 `TMPDIR`;环境中的凭证、`PATH`、`HOME` 与其他宿主状态均不可见。 +包的默认导出是 `PythonPtcRuntime` 插件。其公开面还重新导出宿主侧协议词汇:`validateChildFrame`(重建每条入站帧)、无损 JSON codec 与计量器(`encodeJsonPlain`、`checkDoneValue`、`hasUnsafeIntegerToken`、`hasNonLosslessNumber`)、`logTruncationMarker`(共享截断标记文本),以及 `resolvePythonBin`(对照当前 `PATH` 的解释器查找)、`readProcessStart`(供测试用的进程启动统计)、`detachResidual`(已结算运行的资源清理测试 seam)与 `hostFrameParseCeiling`(给定堆上限可容纳的堆推导帧解析上限)。每个上限都是带默认值并经校验的 `Config` 字段:`cpuSeconds`(60)、`maxWallMs`(600000)、`addressSpaceMb`(512,Darwin 上不生效)、`maxLogBytes`(65536)、`maxValueBytes`(32768)、`graceMs`(3000)与 `pythonBin`(`python3`,在加载期解析、检查可执行性,在五秒强制终止期限内探测版本并固定)。每个子进程只接收 `TMPDIR`;环境中的凭证、`PATH`、`HOME` 与其他宿主状态均不可见。 ### wire @@ -71,7 +71,7 @@ kind: "package-reference" | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | 插件入口:`PythonCodeRuntime`——spawn、帧 pump、预算、隔离、拆卸;重新导出协议词汇 | +| [`src/index.ts`](src/index.ts) | 插件入口:`PythonPtcRuntime`——spawn、帧 pump、预算、隔离、拆卸;重新导出协议词汇 | | [`src/protocol.ts`](src/protocol.ts) | 宿主侧:帧 codec、不可信帧校验器、无损 JSON 计量器、共享标记文本 | | [`py/bootstrap.py`](py/bootstrap.py) | 子进程侧:fd-3 通道、程序执行、binding 分发、账本与结算 | | [`py/protocol.py`](py/protocol.py) | Python 侧:`PROTOCOL_FD`、`TypedDict` 帧镜像、`log_truncation_marker` | @@ -88,11 +88,11 @@ kind: "package-reference" 当 runtime 契约不够时阅读这些。它们从 seam 定义走向设计记录与配套后端。 -- [Code runtime seam](../../code-runtime/code-runtime/README.zh.md) — 本后端实现的抽象契约。 -- [fd-3 协议 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-31-code-runtime-python-fd3-protocol.zh.md) — 设计理由与 wire 契约。 +- [PTC 运行时 seam](../../ptc-runtime/ptc-runtime/README.zh.md) — 本后端实现的抽象契约。 +- [fd-3 协议 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md) — 设计理由与 wire 契约。 - [结算修复 Agent Note](../../../.agents/notes/archived/bug-fix/2026-07-31-code-runtime-python-settlement-fixes.md) — 结算、计量与隔离修复及其回归用例。 -- [Node 进程后端](../../code-runtime/code-runtime-node/README.zh.md) — 已发布的 TypeScript 兄弟。 -- [Code runtime 子系统参考](../../../docs/subsystems/code-runtime.zh.md) — 请求/结果词汇、binding 与失败分类。 +- [Node 进程后端](../../ptc-runtime/ptc-runtime-node/README.zh.md) — 已发布的 TypeScript 兄弟。 +- [PTC 运行时子系统参考](../../../docs/subsystems/ptc-runtime.zh.md) — 请求/结果词汇、binding 与失败分类。 ----- @@ -118,9 +118,9 @@ kind: "package-reference" - **binding 回复值没有 seam 级字节或深度上限**——`maxValueBytes` 只计量 done 帧的完成值;宽 binding 回复在宿主侧重建(`snapshotJsonValue` 遍历)并整帧编码,两侧都只受进程内存约束(与没有子进程侧预算的 binding 实参一样)。 - **已发布 profile 均不挂载本提供方**——keyless `ptc-python-turn` 快照通过真实 Loader 替换 headless PTC 运行时;已发布 profile 使用沙箱 Node 进程后端。 - **跨通道日志交错由后端决定**——Python stdout、stderr 与 fd-3 日志帧彼此独立传输;每个通道保留自身顺序,但它们在 `result.logs` 中的总顺序可能不同。 -- **需要 CPython 3.10 或更高版本**——配置的可执行文件会在加载期完成解析与版本探测;不受支持的解释器会在 `ctx.codeRuntime` 注册前失败。 -- **截断标记文本与临时目录前缀保留改名前的短名**——标记 `[dsh-code-runtime-python] log capture truncated at bytes` 与 `dsh-code-runtime-python-` 临时目录前缀被测试逐字节锚定,且独立于 npm 包名;promotion(去掉 `experimental-` 前缀)不会重命名它们。 -- **`run()` 是一次性的**——`logs` 只有在 `CodeRunResult` resolve 后才能获得;没有为运行中程序产生的输出提供流式日志或进度接口。 +- **需要 CPython 3.10 或更高版本**——配置的可执行文件会在加载期完成解析与版本探测;不受支持的解释器会在 `ctx.ptcRuntime` 注册前失败。 +- **诊断与临时目录前缀省略包名中的 experimental 限定词**——标记 `[dsh-ptc-runtime-python] log capture truncated at bytes` 与 `dsh-ptc-runtime-python-` 目录前缀独立于 npm 包名来标识本提供方。协议镜像检查 TypeScript 与 Python 的标记字节完全相同。 +- **`run()` 是一次性的**——`logs` 只有在 `PtcRunResult` resolve 后才能获得;没有为运行中程序产生的输出提供流式日志或进度接口。 - **运行之间不保留状态**——每次请求都在全新子进程中执行;持久 REPL 风格内核在某个后端带来自己的日志方案之前保持延期。 - **原始长度超过有效帧解析上限的 fd-3 帧会让本次运行以 worker-exit 结算**——上限为 64 MiB,或当宿主的配置堆无法安全解析接近上限的帧时更低(`hostFrameParseCeiling`);`maxLogBytes`/`maxValueBytes` 在加载期被限制到同一上限,因此诚实子进程的帧总能放得下;模型构造的超过该上限的 binding 实参(一个在 seam 层没有预算的值)会触发同一上限——这是该 OOM 防护的已接受残余。 - **停止读取回复的子进程会在回复积压超过 1024 帧时以 worker-exit 结算运行**——宿主每次写一条回复,管道满时等待 `drain`;只持续发送调用而不消费回复的子进程会让保留的积压(及其钉住的 binding 结果)一直增长到墙钟,因此积压上限让运行提前失败。binding 结果在 seam 层没有字节上限,所以这是计数上限而非字节上限。 diff --git a/packages/experimental/code-runtime-python/package.json b/packages/experimental/ptc-runtime-python/package.json similarity index 78% rename from packages/experimental/code-runtime-python/package.json rename to packages/experimental/ptc-runtime-python/package.json index 2fb430b5a8..c7038fe4b0 100644 --- a/packages/experimental/code-runtime-python/package.json +++ b/packages/experimental/ptc-runtime-python/package.json @@ -1,11 +1,11 @@ { - "name": "@deepseek-ai/dsh-experimental-code-runtime-python", - "description": "CPython subprocess implementation of the DeepSeek Harness code-execution seam", + "name": "@deepseek-ai/dsh-experimental-ptc-runtime-python", + "description": "CPython subprocess implementation of the DeepSeek Harness PTC execution seam", "version": "0.1.5-rc.2", "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/experimental/code-runtime-python" + "directory": "packages/experimental/ptc-runtime-python" }, "type": "module", "main": "lib/index.js", @@ -24,13 +24,13 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-util-values": "workspace:^" }, "devDependencies": { - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-util-values": "workspace:^" diff --git a/packages/experimental/code-runtime-python/py/bootstrap.py b/packages/experimental/ptc-runtime-python/py/bootstrap.py similarity index 99% rename from packages/experimental/code-runtime-python/py/bootstrap.py rename to packages/experimental/ptc-runtime-python/py/bootstrap.py index 9533a89dae..88e5da682f 100644 --- a/packages/experimental/code-runtime-python/py/bootstrap.py +++ b/packages/experimental/ptc-runtime-python/py/bootstrap.py @@ -1,4 +1,4 @@ -"""CPython bootstrap for dsh-code-runtime-python. +"""CPython bootstrap for dsh-ptc-runtime-python. Reads a :class:`BootMessage` on fd 3, applies resource limits and log capture, reads a :class:`RunMessage`, runs the model program as the body of an async @@ -780,7 +780,7 @@ class ProtocolChannel: Encoded with the iterative :func:`_encode_json_plain` (not ``json.dumps``, whose per-level recursion would raise ``RecursionError`` on a deeply nested completion or call argument the - depth-unbounded ``CodeJsonValue`` contract admits). NaN/Infinity still + depth-unbounded ``PtcJsonValue`` contract admits). NaN/Infinity still raise ``ValueError`` — they would serialize as non-standard tokens that Node's ``JSON.parse`` rejects, silently dropping the frame, and a call would then hang until the wall clock instead of failing fast. @@ -894,7 +894,7 @@ def _make_error_class( _setattr: Any = setattr, ) -> type: """Mint one program-visible rejection class per the seam's - ``CodeBindingErrorClass`` contract: instances carry the failed member name + ``PtcBindingErrorClass`` contract: instances carry the failed member name under ``member_name_property`` and render as their message.""" def __init__(self, member_name: str, message: str) -> None: # noqa: N807 @@ -1256,7 +1256,7 @@ async def _run(channel: ProtocolChannel) -> None: _stderr_orig = sys.__stderr__.flush if sys.__stderr__ is not None else None # 6. Compile the program as the body of an async function, matching the - # seam contract (`CodeRunRequest.program` is an async-function body: top-level + # seam contract (`PtcRunRequest.program` is an async-function body: top-level # `await` and `return` both work, and the returned value is the completion). # AST-splicing the parsed body into an `async def` keeps every statement's # original line number, so a traceback points at the model's own source. @@ -1528,7 +1528,7 @@ def _encode_json_plain(value: Any) -> str: ``json.dumps`` recurses one Python frame per nesting level and raises ``RecursionError`` a few thousand levels deep, but the seam's - ``CodeJsonValue`` has no depth limit — a valid deeply nested completion or + ``PtcJsonValue`` has no depth limit — a valid deeply nested completion or call argument below the byte budget must cross intact (the host uses the same iterative idiom in ``protocol.ts``). Accepts what the callers already validated or constructed: ``None``/``bool``/``int``/finite ``float``/ @@ -1658,7 +1658,7 @@ def _dump_string(text: str) -> str: until the wall clock. JSON carries it as the ASCII escape ``\\ud800``, which the host's ``JSON.parse`` reads back as the same UTF-16 code unit and its ``JSON.stringify`` re-emits identically — so the shared seam - (``CodeJsonValue``, ``snapshotJsonValue``, the worker backend) keeps a + (``PtcJsonValue``, ``snapshotJsonValue``, the worker backend) keeps a lone-surrogate string instead of failing the value. An adjacent high-low pair is folded into its astral code point FIRST: the host holds strings as UTF-16, where those two code units and the single character are the same @@ -2089,7 +2089,7 @@ def _lossless_json_violation(value: Any) -> str | None: # but JSON carries the code unit as its ASCII ``\uXXXX`` escape and # :func:`_dump_string` emits exactly that, so the host receives the # same code unit the program passed — the same acceptance - # ``CodeJsonValue``, ``snapshotJsonValue``, and the worker backend + # ``PtcJsonValue``, ``snapshotJsonValue``, and the worker backend # already give it. continue if type(current) is int: @@ -2287,7 +2287,7 @@ def _cap_message(message: str, max_bytes: int) -> str: This is the PRODUCING-side cap. The host's receive-side ``capMessage`` (``src/index.ts``) bills the same field by RAW bytes instead, because its - output goes into ``CodeRunResult.error.message`` and never re-crosses a + output goes into ``PtcRunResult.error.message`` and never re-crosses a frame-bounded channel — see that function's JSDoc for the split. """ @@ -2393,7 +2393,7 @@ def _model_traceback(exc: BaseException, max_bytes: int) -> str: else: yield from traceback.format_exception_only(type(exc), exc) if truncated: - yield f"[dsh-code-runtime-python] exception chain truncated at {_MAX_TRACEBACK_CHAIN} links\n" + yield f"[dsh-ptc-runtime-python] exception chain truncated at {_MAX_TRACEBACK_CHAIN} links\n" return _join_bounded(emit(), max_bytes) diff --git a/packages/experimental/code-runtime-python/py/protocol.py b/packages/experimental/ptc-runtime-python/py/protocol.py similarity index 96% rename from packages/experimental/code-runtime-python/py/protocol.py rename to packages/experimental/ptc-runtime-python/py/protocol.py index 816fc77022..fb2878777b 100644 --- a/packages/experimental/code-runtime-python/py/protocol.py +++ b/packages/experimental/ptc-runtime-python/py/protocol.py @@ -1,4 +1,4 @@ -"""Wire protocol vocabulary for the Python side of dsh-code-runtime-python. +"""Wire protocol vocabulary for the Python side of dsh-ptc-runtime-python. Mirrors ``src/protocol.ts``. Frames travel on fd 3 as JSON-lines (one JSON object per line). The host validates every inbound frame; this side trusts @@ -136,4 +136,4 @@ def log_truncation_marker(max_bytes: int) -> str: same however the cap was hit. """ - return f"[dsh-code-runtime-python] log capture truncated at {max_bytes} bytes" + return f"[dsh-ptc-runtime-python] log capture truncated at {max_bytes} bytes" diff --git a/packages/experimental/code-runtime-python/src/index.ts b/packages/experimental/ptc-runtime-python/src/index.ts similarity index 94% rename from packages/experimental/code-runtime-python/src/index.ts rename to packages/experimental/ptc-runtime-python/src/index.ts index 9e2b461ac1..07d7536aae 100644 --- a/packages/experimental/code-runtime-python/src/index.ts +++ b/packages/experimental/ptc-runtime-python/src/index.ts @@ -1,5 +1,5 @@ /** - * CPython subprocess code runtime: a fresh `python3` process runs each model program under an + * CPython subprocess PTC runtime: a fresh `python3` process runs each model program under an * asyncio event loop with top-level ``await``. Binding calls travel on fd 3 as JSON-lines, * leaving stdout/stderr free for the program's own output. This is containment, not a security * boundary: model code has bash-equivalent trust, contained by a tempdir-only environment, @@ -7,7 +7,7 @@ * * The package also owns the versionless fd-3 wire protocol itself; its host-side codec and * hostile-frame validators are re-exported so every consumer of the wire shares one vocabulary. - * @module @deepseek-ai/dsh-experimental-code-runtime-python + * @module @deepseek-ai/dsh-experimental-ptc-runtime-python */ import { execFileSync, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' @@ -19,8 +19,8 @@ import { getHeapStatistics } from 'node:v8' import type { Duplex } from 'node:stream' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { CodeRuntime, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-code-runtime' -import type { CodeBindingErrorClass, CodeBindingFunction, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult, CodeRunSpec } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcBindingErrorClass, PtcBindingFunction, PtcJsonValue, PtcRunFailure, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { BootMessage, ChildToHost, ReplyMessage } from './protocol.ts' @@ -101,7 +101,7 @@ type ResolvedConfig = Required /** * The seam's language-portable identifier subset (see - * `CodeBindingNamespace.global`) — identical to Python's identifier grammar, + * `PtcBindingNamespace.global`) — identical to Python's identifier grammar, * so the shared contract needs no per-backend mapping here. */ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/ @@ -179,7 +179,7 @@ const PY_SCRIPTS = ['bootstrap.py', 'protocol.py'] * @returns the absolute path of the materialized entry script. */ function materializePyScripts(): string { - const dir = mkdtempSync(join(tmpdir(), 'dsh-code-runtime-python-')) + const dir = mkdtempSync(join(tmpdir(), 'dsh-ptc-runtime-python-')) const source = fileURLToPath(new URL('../py/', import.meta.url)) try { for (const name of PY_SCRIPTS) copyFileSync(join(source, name), join(dir, name)) @@ -250,12 +250,12 @@ const FRAME_ENVELOPE_BYTES = 64 * Smallest `maxLogBytes` the backend can honor. The truncation marker alone * (`logTruncationMarker`) must serialize within the budget, or a marker-only * truncated run returns more than the configured cap: the marker text is - * `[dsh-code-runtime-python] log capture truncated at bytes` — 51 fixed - * characters (the bracketed prefix `[dsh-code-runtime-python] log capture + * `[dsh-ptc-runtime-python] log capture truncated at bytes` — 50 fixed + * characters (the bracketed prefix `[dsh-ptc-runtime-python] log capture * truncated at ` counts both square brackets) plus the digits of N plus 6 — * and its serialized form adds 4 (two quotes, two array brackets), so the - * smallest N that admits its own marker is 63 (51 + 2 + 6 + 4 = 63); 64 is the - * floor with one byte of room. The marker itself remains envelope, not + * smallest N that admits its own marker is 62 (50 + 2 + 6 + 4 = 62); 64 is the + * floor with two bytes of room. The marker itself remains envelope, not * payload, so a truncated run with admitted entries serializes to at most * `maxLogBytes + marker + envelope`. * `maxValueBytes` has no floor beyond the positive-integer requirement: a @@ -267,7 +267,7 @@ const MIN_LOG_BYTES = 64 /** * Extra time added to `graceMs` before the post-kill close-deadline force-settles * a run whose `close` never fires (a setsid-escaped orphan holds our inherited - * stdio; see the `closeDeadline` arm in {@link PythonCodeRuntime.execute}). It + * stdio; see the `closeDeadline` arm in {@link PythonPtcRuntime.execute}). It * covers the OS reaping the killed child itself after SIGKILL — not a deployment * choice but a fixed safety margin, so it is a constant rather than a config knob. */ @@ -368,7 +368,7 @@ export function hostFrameParseCeiling(heapLimit: number = getHeapStatistics().he /** * Interval between process-group liveness probes while settlement waits for an * escalated SIGKILL to empty the group (see the `killing` branch in - * {@link PythonCodeRuntime.execute}'s settle). A poll rather than an event + * {@link PythonPtcRuntime.execute}'s settle). A poll rather than an event * because the group members are the model's own descendants, which the host does * not `wait()` for and gets no exit signal from; the probe is a signal-0 * `process.kill(-pid, 0)`, so the interval only bounds how promptly a now-empty @@ -521,20 +521,20 @@ function validatePythonBin(bin: string): void { maxBuffer: 1_024, }).trim() } catch (error: unknown) { - throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} failed the CPython version probe: ${messageOf(error)}`) + throw new Error(`dsh-ptc-runtime-python: config.pythonBin ${JSON.stringify(bin)} failed the CPython version probe: ${messageOf(error)}`) } const match = /^(\S+) (\d+) (\d+) (\d+)$/.exec(output) if (match === null) { - throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} did not report a CPython version`) + throw new Error(`dsh-ptc-runtime-python: config.pythonBin ${JSON.stringify(bin)} did not report a CPython version`) } const [, implementation, majorText, minorText, patchText] = match const major = Number(majorText) const minor = Number(minorText) if (implementation !== 'cpython') { - throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} must be CPython, got ${implementation}`) + throw new Error(`dsh-ptc-runtime-python: config.pythonBin ${JSON.stringify(bin)} must be CPython, got ${implementation}`) } if (major < MIN_CPYTHON.major || (major === MIN_CPYTHON.major && minor < MIN_CPYTHON.minor)) { - throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(bin)} must be CPython ${MIN_CPYTHON.major}.${MIN_CPYTHON.minor} or newer, got ${implementation} ${majorText}.${minorText}.${patchText}`) + throw new Error(`dsh-ptc-runtime-python: config.pythonBin ${JSON.stringify(bin)} must be CPython ${MIN_CPYTHON.major}.${MIN_CPYTHON.minor} or newer, got ${implementation} ${majorText}.${minorText}.${patchText}`) } } @@ -700,7 +700,7 @@ function accrueStrayCost(buf: Buffer, state: Utf8CostState): number { * SERIALIZED (JSON-escaped) cost. The split is deliberate: `_cap_message`'s * output has to cross fd 3 as a JSON string, so its escaped width is what the * frame ceiling bounds; this function's output goes straight into - * `CodeRunResult.error.message` and never re-crosses a frame-bounded channel, so + * `PtcRunResult.error.message` and never re-crosses a frame-bounded channel, so * the honest measure of what it retains is the raw length. An honest child has * already capped the diagnostic by serialized cost, and raw length ≤ serialized * cost, so a well-formed message passes through unchanged. A forged message with @@ -782,8 +782,8 @@ export function detachResidual(residual: Buffer): Buffer[] { /** One namespace after seam validation: its callables plus the optional typed-rejection contract. */ interface ValidatedNamespace { - functions: Record - errorClass?: CodeBindingErrorClass + functions: Record + errorClass?: PtcBindingErrorClass } /** @@ -792,16 +792,16 @@ interface ValidatedNamespace { */ interface LiveRun { kill(sig: NodeJS.Signals): void - settle(failure: CodeRunFailure): void + settle(failure: PtcRunFailure): void finished: Promise } /** - * The experimental {@link CodeRuntime} backend (private, not released) registering as `codeRuntime`. Every + * The experimental {@link PtcRuntime} backend (private, not released) registering as `ptcRuntime`. Every * cap is validated config; every long-running operation honors the request's * `AbortSignal`; every disposer awaits child-process exit. */ -export class PythonCodeRuntime extends CodeRuntime { +export class PythonPtcRuntime extends PtcRuntime { static Config: z = z.object({ cpuSeconds: z.number().default(60), maxWallMs: z.number().default(600_000), @@ -825,22 +825,22 @@ export class PythonCodeRuntime extends CodeRuntime { private readonly live = new Set() private disposed = false - /* jscpd:ignore-start -- parallel to code-runtime-node: sibling backends keep symmetric constructor/teardown/run shapes. */ + /* jscpd:ignore-start -- parallel to ptc-runtime-node: sibling backends keep symmetric constructor/teardown/run shapes. */ constructor(ctx: Context, config: Config) { super(ctx) // Reject at load on Windows: the bootstrap imports the POSIX-only `resource` // module for RLIMIT_CPU/RLIMIT_AS, spawns with a positional fd 3, and // terminates via negative-PID process-group signals — none of which exist - // on Windows. Registering ctx.codeRuntime there would let assembly succeed + // on Windows. Registering ctx.ptcRuntime there would let assembly succeed // and defer the failure to the first run. The asymmetry with the worker // backend is intentional: that backend is cross-platform; this one is not. if (process.platform === 'win32') { - throw new Error('dsh-code-runtime-python: this backend requires a Unix platform (POSIX rlimits, fd-3 stdio, process-group signals); it cannot run on Windows') + throw new Error('dsh-ptc-runtime-python: this backend requires a Unix platform (POSIX rlimits, fd-3 stdio, process-group signals); it cannot run on Windows') } this.config = config as ResolvedConfig for (const [key, value] of Object.entries(this.config)) { if (typeof value === 'number' && !(Number.isFinite(value) && value > 0)) { - throw new Error(`dsh-code-runtime-python: config.${key} must be a positive number, got ${String(value)}`) + throw new Error(`dsh-ptc-runtime-python: config.${key} must be a positive number, got ${String(value)}`) } } // cpuSeconds crosses to the child's setrlimit(RLIMIT_CPU) raw; a float @@ -850,7 +850,7 @@ export class PythonCodeRuntime extends CodeRuntime { // maxWallMs/graceMs/addressSpaceMb are consumed as numbers where a fraction // is harmless. if (!Number.isInteger(this.config.cpuSeconds)) { - throw new Error(`dsh-code-runtime-python: config.cpuSeconds must be a positive integer, got ${String(this.config.cpuSeconds)}`) + throw new Error(`dsh-ptc-runtime-python: config.cpuSeconds must be a positive integer, got ${String(this.config.cpuSeconds)}`) } // Finite is not the same as representable as an rlimit. `cpuSeconds` and its // `+ 1` hard limit both cross to `setrlimit` as integers, and `1e100` clears @@ -858,7 +858,7 @@ export class PythonCodeRuntime extends CodeRuntime { // -trip: the child sees a different number than was configured. The `+ 1` is // what gets checked because that is the larger of the two values sent. if (!Number.isSafeInteger(this.config.cpuSeconds + 1)) { - throw new Error(`dsh-code-runtime-python: config.cpuSeconds must be at most ${Number.MAX_SAFE_INTEGER - 1} (it and its +1 hard limit cross to setrlimit as exact integers), got ${String(this.config.cpuSeconds)}`) + throw new Error(`dsh-ptc-runtime-python: config.cpuSeconds must be at most ${Number.MAX_SAFE_INTEGER - 1} (it and its +1 hard limit cross to setrlimit as exact integers), got ${String(this.config.cpuSeconds)}`) } // `addressSpaceMb` is multiplied by 1 MiB before it is framed, and a large // finite value overflows to `Infinity` there — which `encodeJsonPlain` @@ -868,7 +868,7 @@ export class PythonCodeRuntime extends CodeRuntime { // ordinary. Safe-integer, not merely finite, since the value must survive // the JSON round trip exactly. if (!Number.isSafeInteger(this.config.addressSpaceMb * 1024 * 1024)) { - throw new Error(`dsh-code-runtime-python: config.addressSpaceMb must be at most ${Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024))} (its byte count crosses the wire as an exact integer), got ${String(this.config.addressSpaceMb)}`) + throw new Error(`dsh-ptc-runtime-python: config.addressSpaceMb must be at most ${Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024))} (its byte count crosses the wire as an exact integer), got ${String(this.config.addressSpaceMb)}`) } // `pythonBin` reaches `spawn` as the executable path, where values the // string schema admits fail late and unhelpfully. An empty string makes @@ -881,7 +881,7 @@ export class PythonCodeRuntime extends CodeRuntime { // too. All three are self-contained configuration errors that fail at // load. if (this.config.pythonBin === '' || this.config.pythonBin.includes('\0')) { - throw new Error(`dsh-code-runtime-python: config.pythonBin must be a non-empty path without NUL bytes, got ${JSON.stringify(this.config.pythonBin)}`) + throw new Error(`dsh-ptc-runtime-python: config.pythonBin must be a non-empty path without NUL bytes, got ${JSON.stringify(this.config.pythonBin)}`) } // `maxWallMs` and `graceMs` are armed with setTimeout, which clamps any // delay past MAX_TIMER_DELAY_MS to 1 ms without a word — turning a @@ -889,10 +889,10 @@ export class PythonCodeRuntime extends CodeRuntime { // an instant SIGKILL. `graceMs` is checked against the margin the // close-deadline adds on top, since that sum is what gets armed. if (this.config.maxWallMs > MAX_TIMER_DELAY_MS) { - throw new Error(`dsh-code-runtime-python: config.maxWallMs must not exceed ${MAX_TIMER_DELAY_MS} (setTimeout clamps a larger delay to 1ms), got ${String(this.config.maxWallMs)}`) + throw new Error(`dsh-ptc-runtime-python: config.maxWallMs must not exceed ${MAX_TIMER_DELAY_MS} (setTimeout clamps a larger delay to 1ms), got ${String(this.config.maxWallMs)}`) } if (this.config.graceMs + CLOSE_REAP_MARGIN_MS > MAX_TIMER_DELAY_MS) { - throw new Error(`dsh-code-runtime-python: config.graceMs must not exceed ${MAX_TIMER_DELAY_MS - CLOSE_REAP_MARGIN_MS} (its close deadline adds ${CLOSE_REAP_MARGIN_MS}ms, and setTimeout clamps a larger delay to 1ms), got ${String(this.config.graceMs)}`) + throw new Error(`dsh-ptc-runtime-python: config.graceMs must not exceed ${MAX_TIMER_DELAY_MS - CLOSE_REAP_MARGIN_MS} (its close deadline adds ${CLOSE_REAP_MARGIN_MS}ms, and setTimeout clamps a larger delay to 1ms), got ${String(this.config.graceMs)}`) } // The output caps are budgets for a payload that has to cross fd 3 inside // one frame, and the framing ceiling is fixed. A cap above what a frame can @@ -909,7 +909,7 @@ export class PythonCodeRuntime extends CodeRuntime { // already inside the charge and must not be multiplied in again. The // receive-side `capMessage` backstop is the one exception to this argument: // it bills a forged `done.error.message` by RAW bytes, but that output goes - // into `CodeRunResult.error.message` and never re-crosses a frame-bounded + // into `PtcRunResult.error.message` and never re-crosses a frame-bounded // channel, so it is not part of the wire-width bound (see its JSDoc). The // admissible cap is therefore `parse-cap - envelope`: the receive path // rejects raw frames past the effective parse cap (`frameParseCapBytes` — @@ -925,7 +925,7 @@ export class PythonCodeRuntime extends CodeRuntime { // enforcing different public config. Reject the float at load, as the // Node backend does for its byte budgets. if (!Number.isInteger(this.config[key])) { - throw new Error(`dsh-code-runtime-python: config.${key} must be a positive integer (the child reads it as an int, so a float diverges from the host), got ${String(this.config[key])}`) + throw new Error(`dsh-ptc-runtime-python: config.${key} must be a positive integer (the child reads it as an int, so a float diverges from the host), got ${String(this.config[key])}`) } const limit = this.frameParseCapBytes - FRAME_ENVELOPE_BYTES if (this.config[key] > limit) { @@ -936,7 +936,7 @@ export class PythonCodeRuntime extends CodeRuntime { // instrumented suite (whose heap never binds). /* v8 ignore next -- the heap-constrained message arm needs a host heap below the protocol cap. */ const heapNote = this.frameParseCapBytes < FRAME_PARSE_CAP_BYTES ? ` — this host's heap limits the parse to ${this.frameParseCapBytes} bytes, so the protocol cap of ${FRAME_PARSE_CAP_BYTES} would be unsafe` : '' - throw new Error(`dsh-code-runtime-python: config.${key} must not exceed ${limit} (a payload that large cannot cross the fd-3 frame PARSER, which rejects raw frames past ${this.frameParseCapBytes} bytes before decoding to bound host memory${heapNote} — a larger budget would admit a config whose honest child frames the host then rejects as a worker-exit), got ${String(this.config[key])}`) + throw new Error(`dsh-ptc-runtime-python: config.${key} must not exceed ${limit} (a payload that large cannot cross the fd-3 frame PARSER, which rejects raw frames past ${this.frameParseCapBytes} bytes before decoding to bound host memory${heapNote} — a larger budget would admit a config whose honest child frames the host then rejects as a worker-exit), got ${String(this.config[key])}`) } // Reject a log budget too small to honor: the truncation marker alone // must serialize within the budget, or a marker-only truncated run @@ -944,7 +944,7 @@ export class PythonCodeRuntime extends CodeRuntime { // marker is envelope, so the serialized logs run to // `maxLogBytes + marker + envelope`.) if (key === 'maxLogBytes' && this.config[key] < MIN_LOG_BYTES) { - throw new Error(`dsh-code-runtime-python: config.maxLogBytes must be at least ${MIN_LOG_BYTES} (a smaller budget cannot serialize the truncation marker itself, so a marker-only truncated run would return more than the configured cap), got ${String(this.config[key])}`) + throw new Error(`dsh-ptc-runtime-python: config.maxLogBytes must be at least ${MIN_LOG_BYTES} (a smaller budget cannot serialize the truncation marker itself, so a marker-only truncated run would return more than the configured cap), got ${String(this.config[key])}`) } } // The child builds, charges, and frames a `maxLogBytes` log entry or a @@ -984,12 +984,12 @@ export class PythonCodeRuntime extends CodeRuntime { // naming `maxLogBytes` -- pointing the operator at the knob that is not the // problem. The baseline is what `addressSpaceMb` must clear here. if (budgetableBytes <= 0) { - throw new Error(`dsh-code-runtime-python: config.addressSpaceMb must exceed the ${INTERPRETER_BASELINE_BYTES}-byte interpreter baseline with room for the output budgets, so the child has address space left to build and encode them; got ${String(this.config.addressSpaceMb)} MiB (${addressSpaceBytes} bytes)`) + throw new Error(`dsh-ptc-runtime-python: config.addressSpaceMb must exceed the ${INTERPRETER_BASELINE_BYTES}-byte interpreter baseline with room for the output budgets, so the child has address space left to build and encode them; got ${String(this.config.addressSpaceMb)} MiB (${addressSpaceBytes} bytes)`) } const admissibleBudget = Math.ceil(budgetableBytes / OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE) - 1 for (const key of ['maxLogBytes', 'maxValueBytes'] as const) { if (this.config[key] * OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE >= budgetableBytes) { - throw new Error(`dsh-code-runtime-python: config.${key} times the ${OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE}x worst-case Unicode expansion must fit within the ${budgetableBytes} bytes left after the ${INTERPRETER_BASELINE_BYTES}-byte interpreter baseline within the ${addressSpaceBytes}-byte addressSpaceMb, so a near-budget output truncates rather than breaching RLIMIT_AS as worker-exit; got ${String(this.config[key])} against a limit of ${admissibleBudget}`) + throw new Error(`dsh-ptc-runtime-python: config.${key} times the ${OUTPUT_BUDGET_WORST_CASE_ADDRESS_SPACE_MULTIPLE}x worst-case Unicode expansion must fit within the ${budgetableBytes} bytes left after the ${INTERPRETER_BASELINE_BYTES}-byte interpreter baseline within the ${addressSpaceBytes}-byte addressSpaceMb, so a near-budget output truncates rather than breaching RLIMIT_AS as worker-exit; got ${String(this.config[key])} against a limit of ${admissibleBudget}`) } } // Resolve and validate the executable ONCE, after the pure config checks. @@ -1001,11 +1001,11 @@ export class PythonCodeRuntime extends CodeRuntime { const pythonBin = resolvePythonBin(this.config.pythonBin) if (pythonBin === undefined) { const explicit = isAbsolute(this.config.pythonBin) || this.config.pythonBin.includes('/') - throw new Error(`dsh-code-runtime-python: config.pythonBin ${JSON.stringify(this.config.pythonBin)} ${explicit ? 'is not an executable regular file' : 'does not resolve on PATH'}`) + throw new Error(`dsh-ptc-runtime-python: config.pythonBin ${JSON.stringify(this.config.pythonBin)} ${explicit ? 'is not an executable regular file' : 'does not resolve on PATH'}`) } validatePythonBin(pythonBin) this.pythonBin = pythonBin - ctx.effect(() => () => this.teardown(), 'python code-runtime teardown') + ctx.effect(() => () => this.teardown(), 'python ptc-runtime teardown') } /** @@ -1034,11 +1034,11 @@ export class PythonCodeRuntime extends CodeRuntime { * @returns Complete inputs for the provider's run method. * @throws When a requested override is unsupported or cwd is relative. */ - resolve(request: CodeRunRequest): CodeRunSpec { - if (request.sandboxPolicy !== undefined) throw new Error('dsh-code-runtime-python: sandbox policy is unsupported') - if (request.timeoutMs !== undefined) throw new Error('dsh-code-runtime-python: per-call timeout is unsupported') + resolve(request: PtcRunRequest): PtcRunSpec { + if (request.sandboxPolicy !== undefined) throw new Error('dsh-ptc-runtime-python: sandbox policy is unsupported') + if (request.timeoutMs !== undefined) throw new Error('dsh-ptc-runtime-python: per-call timeout is unsupported') const cwd = request.cwd ?? process.cwd() - if (!isAbsolute(cwd)) throw new Error('dsh-code-runtime-python: cwd must be absolute') + if (!isAbsolute(cwd)) throw new Error('dsh-ptc-runtime-python: cwd must be absolute') return { ...request, cwd, timeoutMs: this.config.maxWallMs } } @@ -1047,9 +1047,9 @@ export class PythonCodeRuntime extends CodeRuntime { * @param request - Resolved cwd, provider deadline, program and bindings. * @returns Captured output and the program outcome. */ - async run(request: CodeRunSpec): Promise { - if (request.sandboxPolicy !== undefined || request.timeoutMs !== this.config.maxWallMs) throw new Error('dsh-code-runtime-python: unsupported execution policy or timeout') - if (this.disposed) throw new Error('dsh-code-runtime-python: run() after disposal') + async run(request: PtcRunSpec): Promise { + if (request.sandboxPolicy !== undefined || request.timeoutMs !== this.config.maxWallMs) throw new Error('dsh-ptc-runtime-python: unsupported execution policy or timeout') + if (this.disposed) throw new Error('dsh-ptc-runtime-python: run() after disposal') const bindings = this.validateBindings(request) if (request.signal?.aborted) { return { logs: [], error: { kind: 'abort', message: messageOf(request.signal.reason) } } @@ -1077,7 +1077,7 @@ export class PythonCodeRuntime extends CodeRuntime { * reserved globals/error classes, duplicates, and colliding or * runtime-owned injected globals. */ - private validateBindings(request: CodeRunRequest): Map { + private validateBindings(request: PtcRunRequest): Map { const bindings = new Map() // Every name the bootstrap injects into the program's one global namespace: // namespace globals plus error-class names. They must be a collision-free @@ -1087,10 +1087,10 @@ export class PythonCodeRuntime extends CodeRuntime { const injectedGlobals = new Set() const claimGlobal = (name: string, role: string): void => { if (RUNTIME_OWNED_GLOBALS.has(name)) { - throw new Error(`dsh-code-runtime-python: ${role} ${JSON.stringify(name)} collides with a runtime-owned global`) + throw new Error(`dsh-ptc-runtime-python: ${role} ${JSON.stringify(name)} collides with a runtime-owned global`) } if (injectedGlobals.has(name)) { - throw new Error(`dsh-code-runtime-python: ${role} ${JSON.stringify(name)} collides with another injected global`) + throw new Error(`dsh-ptc-runtime-python: ${role} ${JSON.stringify(name)} collides with another injected global`) } injectedGlobals.add(name) } @@ -1106,32 +1106,32 @@ export class PythonCodeRuntime extends CodeRuntime { // the plain copy makes validation and the boot frame agree. const global = namespace.global if (!IDENTIFIER.test(global) || RESERVED_NAMES.has(global)) { - throw new Error(`dsh-code-runtime-python: binding global ${JSON.stringify(global)} is not a usable Python identifier`) + throw new Error(`dsh-ptc-runtime-python: binding global ${JSON.stringify(global)} is not a usable Python identifier`) } if (bindings.has(global)) { - throw new Error(`dsh-code-runtime-python: duplicate binding global ${JSON.stringify(global)}`) + throw new Error(`dsh-ptc-runtime-python: duplicate binding global ${JSON.stringify(global)}`) } claimGlobal(global, 'binding global') // The error class becomes a program global and its member property an // attribute name, so both face the Python identifier rules; the member // additionally must be assignable on a BaseException instance. const errorClass = namespace.errorClass - let validatedErrorClass: CodeBindingErrorClass | undefined + let validatedErrorClass: PtcBindingErrorClass | undefined if (errorClass) { const name = errorClass.name const memberNameProperty = errorClass.memberNameProperty if (!IDENTIFIER.test(name) || RESERVED_NAMES.has(name)) { - throw new Error(`dsh-code-runtime-python: errorClass.name ${JSON.stringify(name)} is not a usable Python identifier`) + throw new Error(`dsh-ptc-runtime-python: errorClass.name ${JSON.stringify(name)} is not a usable Python identifier`) } // Any non-empty own attribute name is settable via setattr (the // program reads exotic names like `tool-name` with getattr), matching // the seam contract and the Node backend — only the seam-excluded // and protocol-reserved members below are refused. if (memberNameProperty.length === 0) { - throw new Error('dsh-code-runtime-python: errorClass.memberNameProperty must be a non-empty attribute name') + throw new Error('dsh-ptc-runtime-python: errorClass.memberNameProperty must be a non-empty attribute name') } if (EXCEPTION_RESERVED_MEMBERS.has(memberNameProperty) || DUNDER.test(memberNameProperty)) { - throw new Error(`dsh-code-runtime-python: errorClass.memberNameProperty ${JSON.stringify(memberNameProperty)} is a reserved error member and cannot be assigned`) + throw new Error(`dsh-ptc-runtime-python: errorClass.memberNameProperty ${JSON.stringify(memberNameProperty)} is a reserved error member and cannot be assigned`) } claimGlobal(name, 'errorClass.name') validatedErrorClass = { name, memberNameProperty } @@ -1150,7 +1150,7 @@ export class PythonCodeRuntime extends CodeRuntime { // contract treats member names like `__proto__` or `constructor` as // ordinary own properties, and a plain `{}` assignment of `__proto__` // would hit the prototype setter instead of creating the own property. - const functions = Object.create(null) as Record + const functions = Object.create(null) as Record for (const name of Object.keys(namespace.functions)) { // Only callables enter the snapshot: a getter exposing a non-function // member would otherwise assign a value the dispatcher's `typeof fn @@ -1167,10 +1167,10 @@ export class PythonCodeRuntime extends CodeRuntime { /** Spawn the child for one validated run and drive it to settlement. */ private execute( - request: CodeRunSpec, + request: PtcRunSpec, bindings: Map, bootstrapPath: string, - ): Promise { + ): Promise { // This run's own staging directory, removed at settlement. const bootstrapDir = dirname(bootstrapPath) // Explicit pipe count of 4 puts the framed-JSON channel at fd 3 in the child. @@ -1209,7 +1209,7 @@ export class PythonCodeRuntime extends CodeRuntime { proto = child.stdio[3] as Duplex | null /* v8 ignore next 3 -- `'pipe'` stdio always populates fd 3; guarding Node's `Stream | null` typing widening. */ if (proto === null) { - throw new Error('dsh-code-runtime-python: python subprocess spawned without a fd-3 pipe') + throw new Error('dsh-ptc-runtime-python: python subprocess spawned without a fd-3 pipe') } // Close the host's stdin write handle immediately: the program is an // async body that reads nothing from fd 0, and a live pipe here would @@ -1230,7 +1230,7 @@ export class PythonCodeRuntime extends CodeRuntime { return Promise.resolve({ logs: [], error: { kind: 'worker-exit' as const, message: `python spawn error: ${messageOf(error)}` } }) } - return new Promise((resolve) => { + return new Promise((resolve) => { let settled = false const logs: string[] = [] // An unterminated line flushed with the `open` flag: the next log frame @@ -1859,7 +1859,7 @@ export class PythonCodeRuntime extends CodeRuntime { // the value (an unbounded scan would push every member of a wide // forgery before any cap ran). checkDoneValue folds both jobs into // one bounded, iterative traversal — iterative because the seam's - // CodeJsonValue has no depth limit and an honest deep-but-small + // PtcJsonValue has no depth limit and an honest deep-but-small // completion must cross intact rather than dying on stringify // recursion; bounded because it stops at the cap without // materializing the encoding, rejecting a forged value anywhere @@ -1875,7 +1875,7 @@ export class PythonCodeRuntime extends CodeRuntime { : { error: { kind: 'invalid-output', message: 'completion value contained a non-lossless number' } }) return } - finish({ value: message.value as CodeJsonValue }) + finish({ value: message.value as PtcJsonValue }) return } case 'call': { @@ -2186,12 +2186,12 @@ export class PythonCodeRuntime extends CodeRuntime { let resolved = false // The decided terminal result for a live child, recorded by finish() and // read by the `close` handler that settles it once the pipes have drained. - let decided: Omit + let decided: Omit // The single settlement point: resolve run() with the decided result and // mark the fiber quiescent. Idempotent — the first call wins, so a later // `close` after done/timeout/abort is absorbed as a no-op. - const settle = (result: Omit): void => { + const settle = (result: Omit): void => { if (resolved) return resolved = true if (closeDeadline !== undefined) clearTimeout(closeDeadline) @@ -2298,7 +2298,7 @@ export class PythonCodeRuntime extends CodeRuntime { pollGroup() } - const finish = (result: Omit): void => { + const finish = (result: Omit): void => { if (settled) return settled = true decided = result @@ -2389,7 +2389,7 @@ export class PythonCodeRuntime extends CodeRuntime { child.stdout.on('error', silenceStreamError) child.stderr.on('error', silenceStreamError) - /* jscpd:ignore-start -- wall-timer/abort/live-run wiring deliberately parallels code-runtime-node; see the constructor note. */ + /* jscpd:ignore-start -- wall-timer/abort/live-run wiring deliberately parallels ptc-runtime-node; see the constructor note. */ const wallTimer = setTimeout(() => { finish({ error: { kind: 'timeout', message: `wall-clock ceiling reached (${this.config.maxWallMs}ms)` } }) }, this.config.maxWallMs) @@ -2402,7 +2402,7 @@ export class PythonCodeRuntime extends CodeRuntime { const live: LiveRun = { kill, finished, - settle: (failure: CodeRunFailure) => { finish({ error: failure }) }, + settle: (failure: PtcRunFailure) => { finish({ error: failure }) }, } this.live.add(live) /* jscpd:ignore-end */ @@ -2451,4 +2451,4 @@ export class PythonCodeRuntime extends CodeRuntime { } } -export default PythonCodeRuntime +export default PythonPtcRuntime diff --git a/packages/experimental/code-runtime-python/src/protocol.ts b/packages/experimental/ptc-runtime-python/src/protocol.ts similarity index 99% rename from packages/experimental/code-runtime-python/src/protocol.ts rename to packages/experimental/ptc-runtime-python/src/protocol.ts index 44f634329a..05644dc702 100644 --- a/packages/experimental/code-runtime-python/src/protocol.ts +++ b/packages/experimental/ptc-runtime-python/src/protocol.ts @@ -3,7 +3,7 @@ * travel on the child's fd 3 (one JSON object per line), leaving stdout/stderr free for the * program's own output. Host treats every inbound frame as hostile because model code can post * anything through the same fd; the Python bootstrap trusts host replies. - * @module @deepseek-ai/dsh-experimental-code-runtime-python/src/protocol + * @module @deepseek-ai/dsh-experimental-ptc-runtime-python/src/protocol */ /** @@ -271,13 +271,13 @@ export const WIRE_FRAME_FIELDS = * @returns the marker line. */ export function logTruncationMarker(maxBytes: number): string { - return `[dsh-code-runtime-python] log capture truncated at ${maxBytes} bytes` + return `[dsh-ptc-runtime-python] log capture truncated at ${maxBytes} bytes` } /** * Serialize one JSON-parse-produced value without recursion. `JSON.stringify` * recurses per nesting level and throws `RangeError` a few thousand levels - * deep, but the seam's `CodeJsonValue` has no depth limit — an honest deep + * deep, but the seam's `PtcJsonValue` has no depth limit — an honest deep * completion or binding resolution below the byte budget must cross intact * (the worker backend's wire is equally stack-safe). Callers must pass a value * produced by `JSON.parse` (or equally JSON-plain): only `null`, finite diff --git a/packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts b/packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts similarity index 92% rename from packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts rename to packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts index ba2b1cddc4..66a658a6d3 100644 --- a/packages/experimental/code-runtime-python/tests/boot-write-failure.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/boot-write-failure.spec.ts @@ -17,7 +17,7 @@ vi.mock('node:child_process', async (importOriginal) => { return { ...original, execFileSync: execFileSyncMock, spawn: spawnMock } }) -const { PythonCodeRuntime } = await import('../src/index.ts') +const { PythonPtcRuntime } = await import('../src/index.ts') /** A `child_process.ChildProcess` stand-in whose fd-3 pipe rejects every write. */ function fakeChildWithThrowingFd3(): EventEmitter { @@ -125,7 +125,7 @@ function fakeChildBackpressuredThenDestroyed(): { child: EventEmitter; proto: Pa return { child, proto } } -describe('PythonCodeRuntime — controlled subprocess pipes', () => { +describe('PythonPtcRuntime — controlled subprocess pipes', () => { it('preserves pending replies across compaction while the pipe stays backpressured', async () => { const spawned = Promise.withResolvers() let written = Promise.withResolvers() @@ -144,8 +144,8 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { } spawnMock.mockImplementation(() => { spawned.resolve(undefined); return child }) const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime) - const runtime = ctx.codeRuntime as InstanceType + const fiber = await ctx.plugin(PythonPtcRuntime) + const runtime = ctx.ptcRuntime as InstanceType const run = runtime.run(runtime.resolve({ program: 'return 1', bindings: [{ global: 'tools', functions: { echo: async (value: unknown) => value as number } }], @@ -188,7 +188,7 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { it('force-kills a version probe that exceeds its load-time deadline', async () => { const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime) + const fiber = await ctx.plugin(PythonPtcRuntime) expect(execFileSyncMock).toHaveBeenCalledWith( expect.any(String), @@ -207,8 +207,8 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { // constructs. This test would see that rejection; the fix makes it resolve. spawnMock.mockImplementation(() => fakeChildWithThrowingFd3()) const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime) - const runtime = ctx.codeRuntime as InstanceType + const fiber = await ctx.plugin(PythonPtcRuntime) + const runtime = ctx.ptcRuntime as InstanceType const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) @@ -229,7 +229,7 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { // received (`['-I', /bootstrap.py]`) and assert only that path is gone. // A tmpdir scan — even a set difference against a pre-run snapshot — would // flake under vitest's forks pool: a sibling worker creating its own - // `dsh-code-runtime-python-*` dir in the window reads as a leak here. Keying + // `dsh-ptc-runtime-python-*` dir in the window reads as a leak here. Keying // off our own argv is fully isolated from concurrent staging. let stagedBootstrap: string | undefined spawnMock.mockImplementation((_bin: string, args: string[]) => { @@ -237,8 +237,8 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { throw Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' }) }) const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime) - const runtime = ctx.codeRuntime as InstanceType + const fiber = await ctx.plugin(PythonPtcRuntime) + const runtime = ctx.ptcRuntime as InstanceType const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) @@ -255,8 +255,8 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { // worker-exit rather than reject run() or leave it hanging. spawnMock.mockImplementation(() => fakeChildWithAckThenThrowingFd3()) const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime) - const runtime = ctx.codeRuntime as InstanceType + const fiber = await ctx.plugin(PythonPtcRuntime) + const runtime = ctx.ptcRuntime as InstanceType const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) @@ -272,8 +272,8 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { // worker-exit from that event. spawnMock.mockImplementation(() => fakeChildWithAsyncSpawnError()) const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime) - const runtime = ctx.codeRuntime as InstanceType + const fiber = await ctx.plugin(PythonPtcRuntime) + const runtime = ctx.ptcRuntime as InstanceType const result = await runtime.run(runtime.resolve({ program: 'return 1', bindings: [] })) @@ -299,8 +299,8 @@ describe('PythonCodeRuntime — controlled subprocess pipes', () => { return fake.child }) const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime, { maxWallMs: 3000 }) - const runtime = ctx.codeRuntime as InstanceType + const fiber = await ctx.plugin(PythonPtcRuntime, { maxWallMs: 3000 }) + const runtime = ctx.ptcRuntime as InstanceType const result = await runtime.run(runtime.resolve({ program: 'return 1', diff --git a/packages/experimental/code-runtime-python/tests/protocol-mirror.e2e.ts b/packages/experimental/ptc-runtime-python/tests/protocol-mirror.e2e.ts similarity index 100% rename from packages/experimental/code-runtime-python/tests/protocol-mirror.e2e.ts rename to packages/experimental/ptc-runtime-python/tests/protocol-mirror.e2e.ts diff --git a/packages/experimental/code-runtime-python/tests/protocol.spec.ts b/packages/experimental/ptc-runtime-python/tests/protocol.spec.ts similarity index 99% rename from packages/experimental/code-runtime-python/tests/protocol.spec.ts rename to packages/experimental/ptc-runtime-python/tests/protocol.spec.ts index 75812a2be4..df91900abb 100644 --- a/packages/experimental/code-runtime-python/tests/protocol.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/protocol.spec.ts @@ -3,8 +3,8 @@ import { checkDoneValue, encodeJsonPlain, hasNonLosslessNumber, hasUnsafeInteger describe('logTruncationMarker', () => { it('names the configured byte budget', () => { - expect(logTruncationMarker(65536)).toBe('[dsh-code-runtime-python] log capture truncated at 65536 bytes') - expect(logTruncationMarker(1)).toBe('[dsh-code-runtime-python] log capture truncated at 1 bytes') + expect(logTruncationMarker(65536)).toBe('[dsh-ptc-runtime-python] log capture truncated at 65536 bytes') + expect(logTruncationMarker(1)).toBe('[dsh-ptc-runtime-python] log capture truncated at 1 bytes') }) }) diff --git a/packages/experimental/code-runtime-python/tests/residual-detach.spec.ts b/packages/experimental/ptc-runtime-python/tests/residual-detach.spec.ts similarity index 100% rename from packages/experimental/code-runtime-python/tests/residual-detach.spec.ts rename to packages/experimental/ptc-runtime-python/tests/residual-detach.spec.ts diff --git a/packages/experimental/code-runtime-python/tests/runtime.spec.ts b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts similarity index 97% rename from packages/experimental/code-runtime-python/tests/runtime.spec.ts rename to packages/experimental/ptc-runtime-python/tests/runtime.spec.ts index 2780004a8b..4853f72187 100644 --- a/packages/experimental/code-runtime-python/tests/runtime.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import { basename, dirname, join, relative, resolve } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { PythonCodeRuntime, hostFrameParseCeiling, readProcessStart, resolvePythonBin } from '../src/index.ts' +import { PythonPtcRuntime, hostFrameParseCeiling, readProcessStart, resolvePythonBin } from '../src/index.ts' import { logTruncationMarker } from '../src/protocol.ts' import type { Config } from '../src/index.ts' @@ -13,7 +13,7 @@ import type { Config } from '../src/index.ts' // child only TMPDIR, so a bare `python3` inside a wrapper would resolve against // /bin/sh's default PATH rather than the caller's selected interpreter. const PYABS = resolvePythonBin('python3') ?? 'python3' -import type { CodeBindingFunction, CodeJsonValue, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import type { PtcBindingFunction, PtcJsonValue, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' /** * Names one `py/` script whose `copyFileSync` must fail, for the partial-staging @@ -23,7 +23,7 @@ import type { CodeBindingFunction, CodeJsonValue, CodeRunResult } from '@deepsee * `stagedDirs` records every staging directory THIS test file creates, so the * leak assertions check the exact paths instead of a global tmpdir diff: a * parallel vitest worker running the same prefix could create or remove - * `dsh-code-runtime-python-*` directories inside the sampling window, which a + * `dsh-ptc-runtime-python-*` directories inside the sampling window, which a * readdir diff would misattribute to this test. `boot-write-failure.spec.ts` * records the same race and solves it with argv-based identity; recording the * mkdtempSync results is the fs-mock equivalent. @@ -52,7 +52,7 @@ vi.mock('node:fs', async (importOriginal) => { }, mkdtempSync(prefix: string): string { const dir = actual.mkdtempSync(prefix) - if (basename(prefix).startsWith('dsh-code-runtime-python-')) stagedDirs.push(dir) + if (basename(prefix).startsWith('dsh-ptc-runtime-python-')) stagedDirs.push(dir) return dir }, } @@ -66,13 +66,13 @@ vi.mock('node:fs', async (importOriginal) => { */ async function setup(config: Config = {}) { const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime, config) - const runtime = ctx.codeRuntime as PythonCodeRuntime + const fiber = await ctx.plugin(PythonPtcRuntime, config) + const runtime = ctx.ptcRuntime as PythonPtcRuntime return { ctx, fiber, runtime } } /** Convenience: one namespace `tools` with the given functions. */ -function tools(functions: Record) { +function tools(functions: Record) { return [{ global: 'tools', functions }] } @@ -97,7 +97,7 @@ afterEach(() => { for (const file of tempFiles.splice(0)) rmSync(file, { force: true }) }) -describe('PythonCodeRuntime — seam descriptors and misuse', () => { +describe('PythonPtcRuntime — seam descriptors and misuse', () => { it('registers the seam descriptors', async () => { const { runtime } = await setup() expect(runtime.language).toBe('python') @@ -127,15 +127,15 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { it('rejects non-positive config as seam misuse', async () => { const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { cpuSeconds: 0 })) + await expect(ctx.plugin(PythonPtcRuntime, { cpuSeconds: 0 })) .rejects.toThrow(/cpuSeconds must be a positive number/) - await expect(ctx.plugin(PythonCodeRuntime, { maxWallMs: -1 })) + await expect(ctx.plugin(PythonPtcRuntime, { maxWallMs: -1 })) .rejects.toThrow(/maxWallMs must be a positive number/) }) it('rejects a non-integer cpuSeconds at load (setrlimit needs an int)', async () => { const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { cpuSeconds: 1.5 })) + await expect(ctx.plugin(PythonPtcRuntime, { cpuSeconds: 1.5 })) .rejects.toThrow(/cpuSeconds must be a positive integer, got 1.5/) }) @@ -144,10 +144,10 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // int(...): a float would floor there while the host meters the fraction, so // the two sides would enforce different public config. Reject at load. const ctxLog = new Context() - await expect(ctxLog.plugin(PythonCodeRuntime, { maxLogBytes: 3.5 })) + await expect(ctxLog.plugin(PythonPtcRuntime, { maxLogBytes: 3.5 })) .rejects.toThrow(/maxLogBytes must be a positive integer/) const ctxValue = new Context() - await expect(ctxValue.plugin(PythonCodeRuntime, { maxValueBytes: 1024.5 })) + await expect(ctxValue.plugin(PythonPtcRuntime, { maxValueBytes: 1024.5 })) .rejects.toThrow(/maxValueBytes must be a positive integer/) }) @@ -160,15 +160,15 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // configured. Both used to end every run in a bootstrap exception instead of // failing at load, where a self-contained configuration error belongs. const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { addressSpaceMb: 1e308 })) + await expect(ctx.plugin(PythonPtcRuntime, { addressSpaceMb: 1e308 })) .rejects.toThrow(/addressSpaceMb must be at most \d+ .*exact integer/) - await expect(ctx.plugin(PythonCodeRuntime, { cpuSeconds: 1e100 })) + await expect(ctx.plugin(PythonPtcRuntime, { cpuSeconds: 1e100 })) .rejects.toThrow(/cpuSeconds must be at most \d+ .*exact integers/) // The boundary values still load: the bound rejects what cannot be encoded, // not everything large. - const okMb = await ctx.plugin(PythonCodeRuntime, { addressSpaceMb: Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)) }) + const okMb = await ctx.plugin(PythonPtcRuntime, { addressSpaceMb: Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)) }) await okMb.dispose() - const okCpu = await ctx.plugin(PythonCodeRuntime, { cpuSeconds: Number.MAX_SAFE_INTEGER - 1 }) + const okCpu = await ctx.plugin(PythonPtcRuntime, { cpuSeconds: Number.MAX_SAFE_INTEGER - 1 }) await okCpu.dispose() }) @@ -186,16 +186,16 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // child frames the host then rejects. const admissible = 64 * 1024 * 1024 - 64 const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { maxLogBytes: admissible + 1 })) + await expect(ctx.plugin(PythonPtcRuntime, { maxLogBytes: admissible + 1 })) .rejects.toThrow(/maxLogBytes must not exceed 67108800/) - await expect(ctx.plugin(PythonCodeRuntime, { maxValueBytes: admissible + 1 })) + await expect(ctx.plugin(PythonPtcRuntime, { maxValueBytes: admissible + 1 })) .rejects.toThrow(/maxValueBytes must not exceed 67108800/) // The boundary value itself loads: the bound is the largest cap a frame can // still carry, not one below it. It needs an address space large enough to // clear the separate maxValueBytes/addressSpaceMb worst-case gate (the cap // times the 12x Unicode expansion must fit), so this pairs it with a 4 GiB // addressSpaceMb — the two load-time bounds are independent. - const boundary = await ctx.plugin(PythonCodeRuntime, { maxValueBytes: admissible, addressSpaceMb: 4096 }) + const boundary = await ctx.plugin(PythonPtcRuntime, { maxValueBytes: admissible, addressSpaceMb: 4096 }) await boundary.dispose() }) @@ -208,10 +208,10 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // would admit it (50 MiB * 12 = 600 MiB < 1 GiB - 64 MiB). const script = [ "import { Context } from '@deepseek-ai/cordis'", - "import { PythonCodeRuntime } from './packages/experimental/code-runtime-python/src/index.ts'", + "import { PythonPtcRuntime } from './packages/experimental/ptc-runtime-python/src/index.ts'", 'const ctx = new Context()', 'try {', - ' await ctx.plugin(PythonCodeRuntime, { maxValueBytes: 50 * 1024 * 1024, addressSpaceMb: 1024 })', + ' await ctx.plugin(PythonPtcRuntime, { maxValueBytes: 50 * 1024 * 1024, addressSpaceMb: 1024 })', " console.log('LOADED')", ' process.exit(1)', '} catch (error) {', @@ -266,9 +266,9 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // resolving the worker-exit the seam promises for a child that cannot // start. Both are self-contained configuration errors, so they fail here. const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { pythonBin: '' })) + await expect(ctx.plugin(PythonPtcRuntime, { pythonBin: '' })) .rejects.toThrow(/pythonBin must be a non-empty path without NUL bytes/) - await expect(ctx.plugin(PythonCodeRuntime, { pythonBin: 'py\u0000thon3' })) + await expect(ctx.plugin(PythonPtcRuntime, { pythonBin: 'py\u0000thon3' })) .rejects.toThrow(/pythonBin must be a non-empty path without NUL bytes/) }) @@ -288,19 +288,19 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { mkdirSync(directory) try { const missing = new Context() - await expect(missing.plugin(PythonCodeRuntime, { pythonBin: nodePath.join(dir, 'missing') })) + await expect(missing.plugin(PythonPtcRuntime, { pythonBin: nodePath.join(dir, 'missing') })) .rejects.toThrow(/is not an executable regular file/) const noX = new Context() - await expect(noX.plugin(PythonCodeRuntime, { pythonBin: notExecutable })) + await expect(noX.plugin(PythonPtcRuntime, { pythonBin: notExecutable })) .rejects.toThrow(/is not an executable regular file/) const isDir = new Context() - await expect(isDir.plugin(PythonCodeRuntime, { pythonBin: directory })) + await expect(isDir.plugin(PythonPtcRuntime, { pythonBin: directory })) .rejects.toThrow(/is not an executable regular file/) // A relative explicit path fails the same way, resolved against the host // CWD: `dir` is absolute, so a slash-containing relative form of it is // the dirname prefix plus the file, which does not exist as such. const rel = new Context() - await expect(rel.plugin(PythonCodeRuntime, { pythonBin: './definitely-not-there-python' })) + await expect(rel.plugin(PythonPtcRuntime, { pythonBin: './definitely-not-there-python' })) .rejects.toThrow(/is not an executable regular file/) } finally { const { rmSync } = await import('node:fs') @@ -310,7 +310,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { it('rejects a non-CPython, outdated, or probe-failing interpreter at load', async () => { const nonPython = new Context() - await expect(nonPython.plugin(PythonCodeRuntime, { pythonBin: '/bin/echo' })) + await expect(nonPython.plugin(PythonPtcRuntime, { pythonBin: '/bin/echo' })) .rejects.toThrow(/did not report a CPython version/) const dir = await mkdtemp(join(tmpdir(), 'dsh-python-probe-')) @@ -327,19 +327,19 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { try { expect(resolvePythonBin(relative(process.cwd(), old))).toBe(old) const obsolete = new Context() - await expect(obsolete.plugin(PythonCodeRuntime, { pythonBin: oldMajor })) + await expect(obsolete.plugin(PythonPtcRuntime, { pythonBin: oldMajor })) .rejects.toThrow(/must be CPython 3\.10 or newer, got cpython 2\.99\.0/) const outdated = new Context() - await expect(outdated.plugin(PythonCodeRuntime, { pythonBin: old })) + await expect(outdated.plugin(PythonPtcRuntime, { pythonBin: old })) .rejects.toThrow(/must be CPython 3\.10 or newer, got cpython 3\.9\.6/) const forwardCompatible = new Context() - const fiber = await forwardCompatible.plugin(PythonCodeRuntime, { pythonBin: future }) + const fiber = await forwardCompatible.plugin(PythonPtcRuntime, { pythonBin: future }) await fiber.dispose() const alternative = new Context() - await expect(alternative.plugin(PythonCodeRuntime, { pythonBin: pypy })) + await expect(alternative.plugin(PythonPtcRuntime, { pythonBin: pypy })) .rejects.toThrow(/must be CPython, got pypy/) const probeFailure = new Context() - await expect(probeFailure.plugin(PythonCodeRuntime, { pythonBin: failed })) + await expect(probeFailure.plugin(PythonPtcRuntime, { pythonBin: failed })) .rejects.toThrow(/failed the CPython version probe/) } finally { rmSync(dir, { recursive: true, force: true }) @@ -367,7 +367,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // bindings — the child is never spawned. const { runtime } = await setup() const exploding = { - get explode(): CodeBindingFunction { + get explode(): PtcBindingFunction { throw new Error('getter blew up') }, } @@ -383,7 +383,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // getter whose keys differ between reads cannot desynchronize the two. let reads = 0 const countReads = { - get first(): CodeBindingFunction { + get first(): PtcBindingFunction { reads += 1 return async () => 1 }, @@ -518,27 +518,27 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { // would time every run out at once, and a huge graceMs would SIGKILL one // millisecond after SIGTERM. Both must fail at load instead. const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { maxWallMs: 2_147_483_648 })) + await expect(ctx.plugin(PythonPtcRuntime, { maxWallMs: 2_147_483_648 })) .rejects.toThrow(/maxWallMs must not exceed 2147483647/) // graceMs is bounded by the close deadline's added margin, not by the raw // timer maximum, because that sum is what gets armed. - await expect(ctx.plugin(PythonCodeRuntime, { graceMs: 2_147_481_648 })) + await expect(ctx.plugin(PythonPtcRuntime, { graceMs: 2_147_481_648 })) .rejects.toThrow(/graceMs must not exceed 2147481647/) // The exact maxima still load. - await expect(ctx.plugin(PythonCodeRuntime, { maxWallMs: 2_147_483_647, graceMs: 2_147_481_647 })) + await expect(ctx.plugin(PythonPtcRuntime, { maxWallMs: 2_147_483_647, graceMs: 2_147_481_647 })) .resolves.toBeDefined() }) it('rejects loading this Unix-only backend on Windows', async () => { // The bootstrap needs the POSIX `resource` module, a positional fd 3, and // negative-PID process-group signals — none on Windows. The constructor - // must throw at load rather than register ctx.codeRuntime and defer the + // must throw at load rather than register ctx.ptcRuntime and defer the // failure to the first run. const original = process.platform Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) try { const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, {})).rejects.toThrow(/requires a Unix platform/) + await expect(ctx.plugin(PythonPtcRuntime, {})).rejects.toThrow(/requires a Unix platform/) } finally { Object.defineProperty(process, 'platform', { value: original, configurable: true }) } @@ -567,12 +567,12 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { }))).rejects.toThrow(/duplicate binding global/) }) - it('rejects run() after disposal, and unregisters ctx.codeRuntime', async () => { + it('rejects run() after disposal, and unregisters ctx.ptcRuntime', async () => { const { ctx, fiber, runtime } = await setup() await fiber.dispose() await expect(runtime.run(runtime.resolve({ program: 'return 1', bindings: [] }))) .rejects.toThrow(/after disposal/) - expect(ctx.get('codeRuntime')).toBeUndefined() + expect(ctx.get('ptcRuntime')).toBeUndefined() }) it('short-circuits when the request signal is already aborted', async () => { @@ -622,7 +622,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { expect(entry.endsWith('/bootstrap.py')).toBe(true) const dir = dirname(entry) expect(realpathSync(dirname(dir))).toBe(realpathSync(tmpdir())) - expect(basename(dir)).toMatch(/^dsh-code-runtime-python-/) + expect(basename(dir)).toMatch(/^dsh-ptc-runtime-python-/) expect(dir).not.toContain('/packages/') // Staging is per RUN and removed at settlement, so by the time `run()` // resolved the directory is already gone — nothing survives to be rewritten @@ -758,7 +758,7 @@ describe('PythonCodeRuntime — seam descriptors and misuse', () => { }, 15_000) }) -describe('PythonCodeRuntime — process identity', () => { +describe('PythonPtcRuntime — process identity', () => { it('reads a live process start time and distinguishes it from an absent pid', () => { // The teardown guard signals `-child.pid` with a RAW `process.kill`, which // (unlike `child.kill()`) has no handle check, so it would reach a recycled @@ -791,7 +791,7 @@ describe('PythonCodeRuntime — process identity', () => { }) }) -describe('PythonCodeRuntime — inherited resource limits', () => { +describe('PythonPtcRuntime — inherited resource limits', () => { // Darwin deliberately does not apply RLIMIT_AS, and its shell rejects `ulimit -v`. it.skipIf(process.platform === 'darwin')('runs under an inherited hard limit tighter than addressSpaceMb', async () => { // An unprivileged process may lower a hard rlimit but never raise it. Under @@ -1035,7 +1035,7 @@ describe('PythonCodeRuntime — inherited resource limits', () => { }, 20_000) }) -describe('PythonCodeRuntime — programs and bindings', () => { +describe('PythonPtcRuntime — programs and bindings', () => { it('runs a top-level script, captures print output, and returns `result`', async () => { const { runtime } = await setup() const result = await runtime.run(runtime.resolve({ @@ -1090,7 +1090,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return {"first": first, "caught": caught}', ].join('\n'), bindings: tools({ - echo: async (args) => { calls.push(args); return { echoed: args as CodeJsonValue } }, + echo: async (args) => { calls.push(args); return { echoed: args as PtcJsonValue } }, fail: async () => { throw new Error('nope') }, }), })) @@ -1114,7 +1114,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return first', ].join('\n'), bindings: tools({ - echo: async args => ({ echoed: args as CodeJsonValue }), + echo: async args => ({ echoed: args as PtcJsonValue }), }), })) expect(result.error).toBeUndefined() @@ -1142,7 +1142,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return first', ].join('\n'), bindings: tools({ - echo: async args => ({ echoed: args as CodeJsonValue }), + echo: async args => ({ echoed: args as PtcJsonValue }), }), })) expect(result.error).toBeUndefined() @@ -1167,7 +1167,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'return first', ].join('\n'), bindings: tools({ - echo: async args => ({ echoed: args as CodeJsonValue }), + echo: async args => ({ echoed: args as PtcJsonValue }), }), })) expect(result.error).toBeUndefined() @@ -1484,10 +1484,10 @@ describe('PythonCodeRuntime — programs and bindings', () => { // 512 MiB are not. Both budgets are gated symmetrically — the value case sets // a default-fitting maxLogBytes so the maxValueBytes check is what fires. const ctxLog = new Context() - await expect(ctxLog.plugin(PythonCodeRuntime, { maxLogBytes: 50_000_000, addressSpaceMb: 256 })) + await expect(ctxLog.plugin(PythonPtcRuntime, { maxLogBytes: 50_000_000, addressSpaceMb: 256 })) .rejects.toThrow(/maxLogBytes times the 12x worst-case Unicode expansion must fit/) const ctxValue = new Context() - await expect(ctxValue.plugin(PythonCodeRuntime, { maxValueBytes: 50_000_000, addressSpaceMb: 256 })) + await expect(ctxValue.plugin(PythonPtcRuntime, { maxValueBytes: 50_000_000, addressSpaceMb: 256 })) .rejects.toThrow(/maxValueBytes times the 12x worst-case Unicode expansion must fit/) // Discriminates 12 from 8: a 48 MiB maxLogBytes against a 512 MiB address // space leaves 448 MiB budgetable. 48*8 = 384 MiB fits (the old 8x multiple @@ -1497,21 +1497,21 @@ describe('PythonCodeRuntime — programs and bindings', () => { // flush is no longer the binding case: `flush_line` drops the pending chunks // before its push, so it holds two copies, not three. const ctxTwelve = new Context() - await expect(ctxTwelve.plugin(PythonCodeRuntime, { maxLogBytes: 48 * 1024 * 1024, addressSpaceMb: 512 })) + await expect(ctxTwelve.plugin(PythonPtcRuntime, { maxLogBytes: 48 * 1024 * 1024, addressSpaceMb: 512 })) .rejects.toThrow(/maxLogBytes times the 12x worst-case Unicode expansion must fit/) // An addressSpaceMb at or below the interpreter baseline leaves nothing // budgetable, so no budget value can pass. It is rejected on its own terms: // the budget loop would otherwise report "a limit of -1" (or -2796203 at // 32 MiB) while naming maxLogBytes, sending the operator to the wrong knob. const ctxBaseline = new Context() - await expect(ctxBaseline.plugin(PythonCodeRuntime, { addressSpaceMb: 64 })) + await expect(ctxBaseline.plugin(PythonPtcRuntime, { addressSpaceMb: 64 })) .rejects.toThrow(/addressSpaceMb must exceed the 67108864-byte interpreter baseline/) const ctxBelow = new Context() - await expect(ctxBelow.plugin(PythonCodeRuntime, { addressSpaceMb: 32 })) + await expect(ctxBelow.plugin(PythonPtcRuntime, { addressSpaceMb: 32 })) .rejects.toThrow(/addressSpaceMb must exceed the 67108864-byte interpreter baseline/) // The default caps against the default 512 MiB address space load. const ok = new Context() - const fiber = await ok.plugin(PythonCodeRuntime, { maxLogBytes: 65536, maxValueBytes: 32768, addressSpaceMb: 512 }) + const fiber = await ok.plugin(PythonPtcRuntime, { maxLogBytes: 65536, maxValueBytes: 32768, addressSpaceMb: 512 }) await fiber.dispose() }) @@ -2669,7 +2669,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { globalReads += 1 return globalReads === 1 ? 'tools' : 'evil' }, - functions: { echo: async (args: unknown) => args as CodeJsonValue }, + functions: { echo: async (args: unknown) => args as PtcJsonValue }, } const { runtime } = await setup() const result = await runtime.run(runtime.resolve({ @@ -2749,7 +2749,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // platform default PATH and starting a system interpreter the caller never // asked for. const ctx = new Context() - await expect(ctx.plugin(PythonCodeRuntime, { pythonBin: 'definitely-no-such-python-xyz' })) + await expect(ctx.plugin(PythonPtcRuntime, { pythonBin: 'definitely-no-such-python-xyz' })) .rejects.toThrow(/does not resolve on PATH/) }) @@ -2758,7 +2758,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { // `__traceback__` — setattr of a string raises TypeError while // constructing the rejection — so every dunder is refused at the seam. const { runtime } = await setup() - // name/message/stack are the seam's own exclusions (CodeBindingErrorClass + // name/message/stack are the seam's own exclusions (PtcBindingErrorClass // forbids replacing them; the worker backend rejects them identically). for (const member of ['__traceback__', '__dict__', '__class__', 'args', 'name', 'message', 'stack']) { await expect(runtime.run(runtime.resolve({ @@ -2808,7 +2808,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { }) it('preserves a deeply nested completion value below the byte budget', async () => { - // CodeJsonValue has no depth limit: a 10000-deep nested list is only + // PtcJsonValue has no depth limit: a 10000-deep nested list is only // ~20 kB — under maxValueBytes — and must cross intact. That depth // overflows BOTH recursive serializers the pipeline used to rely on // (CPython's json.dumps recursion limit ~1000s, V8's JSON.stringify), so @@ -2913,7 +2913,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { ' caught = str(e)', 'return caught', ].join('\n'), - bindings: tools({ echo: async args => args as CodeJsonValue }), + bindings: tools({ echo: async args => args as PtcJsonValue }), })) expect(result.error).toBeUndefined() expect(result.value).toContain('lossless JSON') @@ -3006,7 +3006,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { 'r = await tools["my-tool"]({"n": 7})', 'return r', ].join('\n'), - bindings: tools({ 'my-tool': async args => ({ got: args as CodeJsonValue }) }), + bindings: tools({ 'my-tool': async args => ({ got: args as PtcJsonValue }) }), })) expect(result.error).toBeUndefined() expect(result.value).toEqual({ got: { n: 7 } }) @@ -3030,7 +3030,7 @@ describe('PythonCodeRuntime — programs and bindings', () => { }) }) -describe('PythonCodeRuntime — budgets, termination, disposal', () => { +describe('PythonPtcRuntime — budgets, termination, disposal', () => { it('kills a wall-clock runaway program via SIGTERM/SIGKILL and reports timeout', async () => { const { runtime } = await setup({ maxWallMs: 500, graceMs: 200 }) const start = Date.now() @@ -3048,7 +3048,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { it('aborts a run when the outer signal fires mid-flight', async () => { const { runtime } = await setup({ maxWallMs: 10_000 }) const controller = new AbortController() - const settled: Promise = runtime.run(runtime.resolve({ + const settled: Promise = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [], signal: controller.signal, @@ -3071,7 +3071,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { try { const { runtime } = await setup({ maxWallMs: 4_000, graceMs: 200 }) const controller = new AbortController() - const settled: Promise = runtime.run(runtime.resolve({ + const settled: Promise = runtime.run(runtime.resolve({ program: 'import time\nwhile True: time.sleep(0.1)', bindings: [], signal: controller.signal, @@ -3299,7 +3299,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { 'echoed = await tools.echo({"ping": True})', 'return {"before": before, "after": mapped(), "echoed": echoed}', ].join('\n'), - bindings: tools({ echo: async args => args as CodeJsonValue }), + bindings: tools({ echo: async args => args as PtcJsonValue }), })) expect(result.error).toBeUndefined() const value = result.value as { before: number; after: number; echoed: unknown } @@ -3780,7 +3780,7 @@ describe('PythonCodeRuntime — budgets, termination, disposal', () => { }, 20_000) }) -describe('PythonCodeRuntime — hostile peer', () => { +describe('PythonPtcRuntime — hostile peer', () => { it('drops garbage bytes and unknown-shape frames posted directly to fd 3', async () => { // The model program can reach fd 3 and write anything. We inject a // non-JSON line, a valid JSON but unknown-shape frame, and a broken done @@ -3818,7 +3818,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return x', ].join('\n'), bindings: tools({ - echo: async (args) => { seenLegitCall = true; return args as CodeJsonValue }, + echo: async (args) => { seenLegitCall = true; return args as PtcJsonValue }, }), })) expect(result.error).toBeUndefined() @@ -3842,7 +3842,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return x', ].join('\n'), bindings: tools({ - echo: async args => args as CodeJsonValue, + echo: async args => args as PtcJsonValue, }), })) expect(result.error).toBeUndefined() @@ -3871,7 +3871,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return x', ].join('\n'), bindings: tools({ - echo: async (args) => { echoCalls += 1; return args as CodeJsonValue }, + echo: async (args) => { echoCalls += 1; return args as PtcJsonValue }, }), })) expect(result.error).toBeUndefined() @@ -3897,7 +3897,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return {"caught": caught, "after": after}', ].join('\n'), bindings: tools({ - echo: async (args) => { seen.push(args); return args as CodeJsonValue }, + echo: async (args) => { seen.push(args); return args as PtcJsonValue }, }), })) expect(result.error).toBeUndefined() @@ -3926,7 +3926,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return x', ].join('\n'), bindings: tools({ - echo: async (args) => { dispatched = args; return args as CodeJsonValue }, + echo: async (args) => { dispatched = args; return args as PtcJsonValue }, }), })) expect(result.error).toBeUndefined() @@ -3968,7 +3968,7 @@ describe('PythonCodeRuntime — hostile peer', () => { it('carries a lone-surrogate completion string across the wire as its JSON escape', async () => { // UTF-8 has no encoding for a lone surrogate, but JSON does: the ASCII // `\ud800` escape, which JSON.parse reads back as the same UTF-16 code - // unit. `CodeJsonValue`, `snapshotJsonValue`, and the worker backend all + // unit. `PtcJsonValue`, `snapshotJsonValue`, and the worker backend all // accept such a string, so this backend must not narrow the shared seam. const { runtime } = await setup() const result = await runtime.run(runtime.resolve({ @@ -4021,7 +4021,7 @@ describe('PythonCodeRuntime — hostile peer', () => { const { runtime } = await setup() const result = await runtime.run(runtime.resolve({ program: String.raw`return await tools.echo({"text": "x\udfff"})`, - bindings: tools({ echo: async (args: unknown) => { seen.push(args); return args as CodeJsonValue } }), + bindings: tools({ echo: async (args: unknown) => { seen.push(args); return args as PtcJsonValue } }), })) expect(result.error).toBeUndefined() expect(seen).toEqual([{ text: 'x\udfff' }]) @@ -4161,7 +4161,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'return result["value"]', ].join('\n'), bindings: tools({ - echo: async (args) => { seen.push(args); return args as CodeJsonValue }, + echo: async (args) => { seen.push(args); return args as PtcJsonValue }, }), })) expect(result.error).toBeUndefined() @@ -4434,7 +4434,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // the call fails through its rejection contract instead of dispatching a // float whose digits come from an override. const { runtime } = await setup() - const seen: CodeJsonValue[] = [] + const seen: PtcJsonValue[] = [] const result = await runtime.run(runtime.resolve({ program: [ 'class F(float):', @@ -4445,7 +4445,7 @@ describe('PythonCodeRuntime — hostile peer', () => { ' return str(exc)', ].join('\n'), bindings: tools({ echo: async (args) => { - seen.push(args as CodeJsonValue) + seen.push(args as PtcJsonValue) return null } }), })) @@ -4459,7 +4459,7 @@ describe('PythonCodeRuntime — hostile peer', () => { // exact-type rule: the call fails descriptively instead of dispatching a // value whose serialization disagrees with what was validated. const { runtime } = await setup() - const seen: CodeJsonValue[] = [] + const seen: PtcJsonValue[] = [] const result = await runtime.run(runtime.resolve({ program: [ 'class Sneaky(dict):', @@ -4470,7 +4470,7 @@ describe('PythonCodeRuntime — hostile peer', () => { ' return str(exc)', ].join('\n'), bindings: tools({ echo: async (args) => { - seen.push(args as CodeJsonValue) + seen.push(args as PtcJsonValue) return null } }), })) @@ -4657,7 +4657,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'print("after-trickle")', 'return "done"', ].join('\n') - let result: CodeRunResult + let result: PtcRunResult try { const { runtime } = await setup({ maxWallMs: 30_000 }) result = await runtime.run(runtime.resolve({ program, bindings: [] })) @@ -5249,7 +5249,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'time.sleep(30)', 'return "unreachable"', ].join('\n'), - bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }], + bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as PtcJsonValue } }], })) expect(result.error?.kind).toBe('worker-exit') expect(result.error?.message).toContain('reply queue exceeded') @@ -5296,7 +5296,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'import asyncio', 'return len(await asyncio.gather(*[tools.echo(i) for i in range(1025)]))', ].join('\n'), - bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }], + bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as PtcJsonValue } }], })) expect(result.error).toBeUndefined() expect(result.value).toBe(1025) @@ -5366,7 +5366,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'import asyncio', 'return len(await asyncio.gather(*[t.e(i) for i in range(1300)]))', ].join('\n'), - bindings: [{ global: 't', functions: { e: async (args: unknown) => args as CodeJsonValue } }], + bindings: [{ global: 't', functions: { e: async (args: unknown) => args as PtcJsonValue } }], })) expect(result.error).toBeUndefined() expect(result.value).toBe(1300) @@ -5426,7 +5426,7 @@ describe('PythonCodeRuntime — hostile peer', () => { 'except Exception as e:', ' return str(e)', ].join('\n'), - bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as CodeJsonValue } }], + bindings: [{ global: 'tools', functions: { echo: async (args: unknown) => args as PtcJsonValue } }], })) expect(result.error).toBeUndefined() expect(result.value).toContain('duplicate dict key') diff --git a/packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts b/packages/experimental/ptc-runtime-python/tests/stray-fragments.spec.ts similarity index 88% rename from packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts rename to packages/experimental/ptc-runtime-python/tests/stray-fragments.spec.ts index fd74737e12..9e0a2fa153 100644 --- a/packages/experimental/code-runtime-python/tests/stray-fragments.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/stray-fragments.spec.ts @@ -25,11 +25,11 @@ vi.mock('node:child_process', async (importOriginal) => { } }) -const { PythonCodeRuntime } = await import('../src/index.ts') +const { PythonPtcRuntime } = await import('../src/index.ts') it('seals stray fragments without recopying the sealed prefix', async () => { const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime, { maxLogBytes: 200_000, maxWallMs: 30_000 }) + const fiber = await ctx.plugin(PythonPtcRuntime, { maxLogBytes: 200_000, maxWallMs: 30_000 }) const realConcat = Buffer.concat.bind(Buffer) let copied = 0 let maxFragments = 0 @@ -39,7 +39,7 @@ it('seals stray fragments without recopying the sealed prefix', async () => { return realConcat(list, total) }) try { - const result = await ctx.codeRuntime.run(ctx.codeRuntime.resolve({ + const result = await ctx.ptcRuntime.run(ctx.ptcRuntime.resolve({ program: 'import os\nos.write(1, b"x" * 60000 + b"\\n")\nreturn "done"', bindings: [], })) @@ -61,7 +61,7 @@ it.each([ { name: 'CESU-8 lone surrogates', payload: 'b"\\xed\\xa0\\x80" * 1100' }, ])('bounds $name by their U+FFFD-decoded cost', async ({ payload }) => { const ctx = new Context() - const fiber = await ctx.plugin(PythonCodeRuntime, { maxLogBytes: 3072, maxWallMs: 30_000 }) + const fiber = await ctx.plugin(PythonPtcRuntime, { maxLogBytes: 3072, maxWallMs: 30_000 }) const realConcat = Buffer.concat.bind(Buffer) let maxConcat = 0 const concat = vi.spyOn(Buffer, 'concat').mockImplementation((list, total) => { @@ -70,7 +70,7 @@ it.each([ return merged }) try { - const result = await ctx.codeRuntime.run(ctx.codeRuntime.resolve({ + const result = await ctx.ptcRuntime.run(ctx.ptcRuntime.resolve({ program: `import os\nos.write(1, ${payload})\nreturn None`, bindings: [], })) diff --git a/packages/experimental/code-runtime-python/tsconfig.json b/packages/experimental/ptc-runtime-python/tsconfig.json similarity index 90% rename from packages/experimental/code-runtime-python/tsconfig.json rename to packages/experimental/ptc-runtime-python/tsconfig.json index bda0b1b01b..256dc0d162 100644 --- a/packages/experimental/code-runtime-python/tsconfig.json +++ b/packages/experimental/ptc-runtime-python/tsconfig.json @@ -18,7 +18,7 @@ "path": "../../../vendor/schemastery" }, { - "path": "../../code-runtime/code-runtime" + "path": "../../ptc-runtime/ptc-runtime" }, { "path": "../../util/timeout" diff --git a/packages/experimental/code-runtime-python/tsdown.config.ts b/packages/experimental/ptc-runtime-python/tsdown.config.ts similarity index 100% rename from packages/experimental/code-runtime-python/tsdown.config.ts rename to packages/experimental/ptc-runtime-python/tsdown.config.ts diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 413afe17ba..5188f274d8 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -642,36 +642,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, - { - key: 'codeRuntime', - summary: 'Registers one `ctx.codeRuntime` implementation.', - description: 'Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and substrate failures resolve in CodeRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal.', - methods: [ - { - signature: 'abstract readonly language: string', - description: 'The source language run expects `program` to be written in, as a lowercase identifier. Informational, not gating — a consumer that generates language-specific presentation (typed SDK stubs, usage instructions) switches on it and fails loud on a language it cannot present. Well-known values: `\'typescript\'` and `\'python\'`, those `dsh-tools` presents; the TypeScript backend is released, the Python backend is experimental and private (not published).', - parameters: [], - }, - { - signature: 'abstract readonly isolation: string', - description: 'The execution substrate, as a lowercase identifier. Informational, not gating — a descriptor so deployments and diagnostics can tell backends apart, not a security claim. Well-known values: `\'worker-thread\'`, `\'process\'`, `\'container\'`.', - parameters: [], - }, - { - signature: 'abstract resolve(request: CodeRunRequest): CodeRunSpec', - description: 'Resolve supported options and provider defaults before execution.', - parameters: [{ name: 'request', description: 'Program, bindings, cancellation and optional execution choices.' }], - returns: 'Complete directory, deadline and supported authority for run.', - throws: ['When an explicit choice is invalid or unsupported by this provider.'], - }, - { - signature: 'abstract run(spec: CodeRunSpec): Promise', - description: 'Execute resolved inputs; program outcomes resolve as result fields.', - parameters: [{ name: 'spec', description: 'directory, deadline, program, bindings, cancellation and supported policy.' }], - returns: 'Captured output and the execution outcome.', - }, - ], - }, { key: 'commands', summary: 'Human-command registry.', @@ -1381,6 +1351,36 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'ptcRuntime', + summary: 'Registers one `ctx.ptcRuntime` implementation.', + description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal.', + methods: [ + { + signature: 'abstract readonly language: string', + description: 'The source language run expects `program` to be written in, as a lowercase identifier. Informational, not gating — a consumer that generates language-specific presentation (typed SDK stubs, usage instructions) switches on it and fails loud on a language it cannot present. Well-known values: `\'typescript\'` and `\'python\'`, those `dsh-tools` presents; the TypeScript backend is released, the Python backend is experimental and private (not published).', + parameters: [], + }, + { + signature: 'abstract readonly isolation: string', + description: 'The execution substrate, as a lowercase identifier. Informational, not gating — a descriptor so deployments and diagnostics can tell backends apart, not a security claim. Well-known values: `\'worker-thread\'`, `\'process\'`, `\'container\'`.', + parameters: [], + }, + { + signature: 'abstract resolve(request: PtcRunRequest): PtcRunSpec', + description: 'Resolve supported options and provider defaults before execution.', + parameters: [{ name: 'request', description: 'Program, bindings, cancellation and optional execution choices.' }], + returns: 'Complete directory, deadline and supported authority for run.', + throws: ['When an explicit choice is invalid or unsupported by this provider.'], + }, + { + signature: 'abstract run(spec: PtcRunSpec): Promise', + description: 'Execute resolved inputs; program outcomes resolve as result fields.', + parameters: [{ name: 'spec', description: 'directory, deadline, program, bindings, cancellation and supported policy.' }], + returns: 'Captured output and the execution outcome.', + }, + ], + }, { key: 'sandbox', summary: 'Abstract process-sandbox service.', @@ -3827,42 +3827,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ClientArtifactBaseline', declaration: 'export interface ClientArtifactBaseline {\n readonly path: string;\n readonly mtimeMs: number;\n readonly size: number;\n}', }, - { - name: 'CodeBindingErrorClass', - declaration: 'export interface CodeBindingErrorClass {\n name: string;\n memberNameProperty: string;\n}', - }, - { - name: 'CodeBindingFunction', - declaration: 'export type CodeBindingFunction = (args: unknown) => Promise;', - }, - { - name: 'CodeBindingNamespace', - declaration: 'export interface CodeBindingNamespace {\n global: string;\n functions: Record;\n errorClass?: CodeBindingErrorClass;\n}', - }, - { - name: 'CodeJsonValue', - declaration: 'export type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | {\n [key: string]: CodeJsonValue;\n};', - }, - { - name: 'CodeRunFailure', - declaration: 'export interface CodeRunFailure {\n kind: \'exception\' | \'timeout\' | \'abort\' | \'worker-exit\' | \'invalid-output\' | \'output-limit\' | \'protocol\' | \'sandbox-unavailable\';\n message: string;\n}', - }, - { - name: 'CodeRunRequest', - declaration: 'export interface CodeRunRequest {\n program: string;\n bindings: CodeBindingNamespace[];\n cwd?: string;\n timeoutMs?: number;\n sandboxPolicy?: SandboxExecutionPolicy;\n signal?: AbortSignal;\n}', - }, - { - name: 'CodeRunResult', - declaration: 'export interface CodeRunResult {\n sandbox?: CodeRunSandbox;\n value?: CodeJsonValue;\n logs: string[];\n error?: CodeRunFailure;\n}', - }, - { - name: 'CodeRunSandbox', - declaration: 'export interface CodeRunSandbox {\n mode: SandboxMode;\n denied: boolean;\n enforcement?: SandboxEnforcement;\n}', - }, - { - name: 'CodeRunSpec', - declaration: 'export interface CodeRunSpec extends CodeRunRequest {\n cwd: string;\n timeoutMs: number;\n}', - }, { name: 'CollectedOutput', declaration: 'export interface CollectedOutput {\n text: string;\n truncated: boolean;\n spillPath?: string;\n}', @@ -4879,10 +4843,46 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PruneResult', declaration: 'export interface PruneResult {\n readonly pruned: readonly PrunedEntry[];\n readonly charsRemoved: number;\n}', }, + { + name: 'PtcBindingErrorClass', + declaration: 'export interface PtcBindingErrorClass {\n name: string;\n memberNameProperty: string;\n}', + }, + { + name: 'PtcBindingFunction', + declaration: 'export type PtcBindingFunction = (args: unknown) => Promise;', + }, + { + name: 'PtcBindingNamespace', + declaration: 'export interface PtcBindingNamespace {\n global: string;\n functions: Record;\n errorClass?: PtcBindingErrorClass;\n}', + }, { name: 'PtcDispatchLog', declaration: 'export interface PtcDispatchLog {\n readonly exec: ToolExecution;\n readonly agent?: Agent;\n readonly subCallId: ToolCallId;\n readonly name: string;\n readonly isError: boolean;\n readonly content: ContentBlock[];\n}', }, + { + name: 'PtcJsonValue', + declaration: 'export type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | {\n [key: string]: PtcJsonValue;\n};', + }, + { + name: 'PtcRunFailure', + declaration: 'export interface PtcRunFailure {\n kind: \'exception\' | \'timeout\' | \'abort\' | \'worker-exit\' | \'invalid-output\' | \'output-limit\' | \'protocol\' | \'sandbox-unavailable\';\n message: string;\n}', + }, + { + name: 'PtcRunRequest', + declaration: 'export interface PtcRunRequest {\n program: string;\n bindings: PtcBindingNamespace[];\n cwd?: string;\n timeoutMs?: number;\n sandboxPolicy?: SandboxExecutionPolicy;\n signal?: AbortSignal;\n}', + }, + { + name: 'PtcRunResult', + declaration: 'export interface PtcRunResult {\n sandbox?: PtcRunSandbox;\n value?: PtcJsonValue;\n logs: string[];\n error?: PtcRunFailure;\n}', + }, + { + name: 'PtcRunSandbox', + declaration: 'export interface PtcRunSandbox {\n mode: SandboxMode;\n denied: boolean;\n enforcement?: SandboxEnforcement;\n}', + }, + { + name: 'PtcRunSpec', + declaration: 'export interface PtcRunSpec extends PtcRunRequest {\n cwd: string;\n timeoutMs: number;\n}', + }, { name: 'ReadFileLine', declaration: 'export interface ReadFileLine {\n number: number;\n text: string;\n}', diff --git a/packages/fs/tool-fs/package.json b/packages/fs/tool-fs/package.json index 3486c30fd1..c98e205477 100644 --- a/packages/fs/tool-fs/package.json +++ b/packages/fs/tool-fs/package.json @@ -61,6 +61,6 @@ "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^" + "@deepseek-ai/dsh-ptc-runtime": "workspace:^" } } diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index ba1128fe30..8b1378fb7f 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -11,8 +11,8 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import { ToolCallId, LlmAdapter, LlmRuntime } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, LlmModelInfo, LlmResolvedModelInfo, Message, StreamChunk } from '@deepseek-ai/dsh-llm' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' @@ -70,14 +70,14 @@ class CatalogAdapter extends LlmAdapter { } /** In-process PTC mode seam fake that invokes the real registry bindings. */ -class FakeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } +class FakeRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' - behavior: (request: CodeRunRequest) => Promise = () => Promise.resolve({ logs: [] }) + behavior: (request: PtcRunRequest) => Promise = () => Promise.resolve({ logs: [] }) - run(request: CodeRunRequest): Promise { + run(request: PtcRunRequest): Promise { return this.behavior(request) } } @@ -290,7 +290,7 @@ describe('read_image happy path', () => { it('forwards a nested PTC mode image through the outer run_code context', async () => { await writeFile(join(dir, 'red.png'), PNG_1X1) const ctx = await setup({ toolMode: 'ptc' }) - const runtime = ctx.codeRuntime as FakeRuntime + const runtime = ctx.ptcRuntime as FakeRuntime runtime.behavior = async (request) => { const value = await request.bindings[0]!.functions.read_image!({ file_path: 'red.png' }) return { logs: [], value } diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index a4c216cae3..298bdd6a4d 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -1047,8 +1047,8 @@ function withPersona(...sections: string[]): string { } /** Schema assembly only: these cases never execute user code. */ -class GuidanceCodeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } +class GuidancePtcRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' @@ -1059,7 +1059,7 @@ describe('scope-aware PTC guidance', () => { it.each(['ptc', 'both'] as const)('uses capability visibility in %s mode', async (mode) => { const ctx = new Context() await ctx.plugin(SystemPrompt) - await ctx.plugin(GuidanceCodeRuntime) + await ctx.plugin(GuidancePtcRuntime) await ctx.plugin(ToolRuntime, { mode }) await ctx.plugin(FakeFs) await ctx.plugin(ToolFs) diff --git a/packages/plan/plan-mode/package.json b/packages/plan/plan-mode/package.json index d8f289b113..fd8ca71888 100644 --- a/packages/plan/plan-mode/package.json +++ b/packages/plan/plan-mode/package.json @@ -64,7 +64,7 @@ "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index e5dadf312f..5bfa464fb1 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -10,7 +10,7 @@ import UserQuestionService, { UserQuestionError, type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' import CommandRuntime from '@deepseek-ai/dsh-commands' -import { CodeRuntime, type CodeRunRequest, type CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime, type PtcRunRequest, type PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' import PlanModeController, { EXIT_PLAN_MODE, planProjectionDefinition, resolveConfig } from '../src/index.ts' @@ -159,7 +159,7 @@ function registerNamedTools(ctx: Context, names: string[]): void { } /** Assert the mapped PTC mode SDK includes the stable plan exit binding and test tools. */ -function expectPlanCodeSdkBindings(sdk: string): void { +function expectPlanPtcSdkBindings(sdk: string): void { expect(sdk).toContain('interface ToolArgsMap {') expect(sdk).toContain('read: Record;') expect(sdk).toContain('write: Record;') @@ -506,14 +506,14 @@ describe('the soft layer', () => { }) it('keeps run_code the only wire tool in plan mode under the registry PTC mode; the SDK gains the exit binding', async () => { - // Minimal scriptable runtime: the SDK section resolves ctx.codeRuntime at + // Minimal scriptable runtime: the SDK section resolves ctx.ptcRuntime at // assembly time (the ptc.spec fake's shape). - class FakeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + class FakeRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' - run(_request: CodeRunRequest): Promise { return Promise.resolve({ logs: [] }) } + run(_request: PtcRunRequest): Promise { return Promise.resolve({ logs: [] }) } } const ctx = new Context() await ctx.plugin(SystemPrompt) @@ -528,16 +528,16 @@ describe('the soft layer', () => { // The SDK documents the full binding set plus the exit; plan mode never // prunes capabilities and restrains through guidance alone. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' - expectPlanCodeSdkBindings(sdk) + expectPlanPtcSdkBindings(sdk) }) it('keeps native wire schemas and the SDK in step under mode both', async () => { - class FakeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + class FakeRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' - run(_request: CodeRunRequest): Promise { return Promise.resolve({ logs: [] }) } + run(_request: PtcRunRequest): Promise { return Promise.resolve({ logs: [] }) } } const ctx = new Context() await ctx.plugin(SystemPrompt) @@ -552,16 +552,16 @@ describe('the soft layer', () => { // is present on the wire AND in the SDK alongside the untouched toolset. expect(assembly.tools.map(tool => tool.name).sort()).toEqual(['exit_plan_mode', 'read', 'run_code', 'write']) const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' - expectPlanCodeSdkBindings(sdk) + expectPlanPtcSdkBindings(sdk) }) it('keeps the PTC mode SDK byte-identical across mode switches', async () => { - class FakeRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + class FakeRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' - run(_request: CodeRunRequest): Promise { return Promise.resolve({ logs: [] }) } + run(_request: PtcRunRequest): Promise { return Promise.resolve({ logs: [] }) } } const withPlanMode = new Context() await withPlanMode.plugin(SystemPrompt) @@ -572,7 +572,7 @@ describe('the soft layer', () => { registerNamedTools(withPlanMode, ['read', 'write']) const agent = await agentWithSession(withPlanMode) const defaultSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? '' - expectPlanCodeSdkBindings(defaultSdk) + expectPlanPtcSdkBindings(defaultSdk) agent.session.append('plan/mode', { active: true }) const planSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? '' expect(planSdk).toBe(defaultSdk) @@ -931,12 +931,12 @@ describe('exit_plan_mode', () => { it('carries the exact plan through a PTC mode review and logs the nested dispatch', async () => { const plan = '# PTC mode plan\n\nUse the existing seam.' - class ExitRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } + class ExitRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'fake' - async run(request: CodeRunRequest): Promise { + 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 { logs: [], value: await exit({ plan }) } diff --git a/packages/preset/agent-presets/presets/ptc/agent.cordis.yml b/packages/preset/agent-presets/presets/ptc/agent.cordis.yml index 7773f64109..8dae1bed93 100644 --- a/packages/preset/agent-presets/presets/ptc/agent.cordis.yml +++ b/packages/preset/agent-presets/presets/ptc/agent.cordis.yml @@ -263,7 +263,7 @@ # ── presentation ──────────────────────────────────────────────────────────── -# PTC mode for this agent alone. The row waits for the host's `codeRuntime` +# PTC mode for this agent alone. The row waits for the host's `ptcRuntime` # rather than assuming it: a deployment that composes no TypeScript runtime # fails this preset at mount, naming this id, instead of at the first request. - id: tool-presentation diff --git a/packages/code-runtime/README.i18n.yaml b/packages/ptc-runtime/README.i18n.yaml similarity index 56% rename from packages/code-runtime/README.i18n.yaml rename to packages/ptc-runtime/README.i18n.yaml index bd8f6131cc..72225e26fd 100644 --- a/packages/code-runtime/README.i18n.yaml +++ b/packages/ptc-runtime/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/code-runtime/README.md -README.md: 13c0d0e16816a8f50376658fb943a12068909997 -README.zh.md: cb69ed488f83a61776d383225e61a86b61d2d433 +# pnpm run verify-translation-pairing --write packages/ptc-runtime/README.md +README.md: 049624bade5dac3d70e9916a37eb3639a1a31ed4 +README.zh.md: 715d454615b61288e04e25d9dd72f40ce3dc1844 diff --git a/packages/ptc-runtime/README.md b/packages/ptc-runtime/README.md new file mode 100644 index 0000000000..049624bade --- /dev/null +++ b/packages/ptc-runtime/README.md @@ -0,0 +1,52 @@ +--- +description: "Package map for the PTC execution capability family: what program execution does for you, and which package owns each part." +kind: "package-group" +--- + +# ptc-runtime/ — PTC execution capability family + +English | [中文](README.zh.md) + +## Summary + +The `ptc-runtime/` group lets a model write one program that calls host-provided functions as ordinary async calls, then returns only the program's printed output and return value. Choose the TypeScript backend for execution in a fresh Node process under the configured sandbox policy, or the experimental Python backend when a CPython process is required. Each run starts without state from earlier programs. Failures are returned as results so callers can diagnose them or provide them to the model. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +These three packages together provide program execution; each README describes what its part does. + +| Package | Role | ctx key | +|---|---|---| +| [`ptc-runtime/`](ptc-runtime/README.md) | Defines what a PTC runtime does: run one program against host-provided bindings and report what it printed and returned | `ctx.ptcRuntime` | +| [`ptc-runtime-node/`](ptc-runtime-node/README.md) | Executes TypeScript in fresh managed Node processes under the resolved sandbox policy | registers `ctx.ptcRuntime` | +| [`experimental/ptc-runtime-python/`](../experimental/ptc-runtime-python/README.md) | The experimental Python backend: owns the fd-3 wire protocol between a Node host and a CPython subprocess and the CPython runtime implementation | — | + +----- + + +## Related documentation + +Start with the subsystem reference for the service contract, then the PTC mode design that consumes this capability and the capability-seam model it follows. + +- [PTC runtime subsystem reference](../../docs/subsystems/ptc-runtime.md) — request/result vocabulary, bindings, and the `ctx.ptcRuntime` Cordis surface. +- [PTC mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-ptc.md) — how the tool registry presents `run_code` to the model. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/ptc-runtime/README.zh.md b/packages/ptc-runtime/README.zh.md new file mode 100644 index 0000000000..715d454615 --- /dev/null +++ b/packages/ptc-runtime/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "PTC 执行能力族的包映射:程序执行能为你做什么,以及每个部分由哪个包负责。" +kind: "package-group" +--- + +# ptc-runtime/——PTC 执行能力族 + +[English](README.md) | 中文 + +## 概述 + +`ptc-runtime/` 组让模型编写一个程序,以普通异步调用的方式调用宿主提供的函数,然后只返回程序的打印输出和返回值。如需在全新 Node 进程中按所配沙箱策略执行,请选择 TypeScript 后端;如需 CPython 进程,请选择实验性 Python 后端。每次运行都不会保留之前程序的状态。失败会作为结果返回,供调用方诊断或提供给模型。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +这三个包共同提供程序执行能力;每个 README 描述其各自部分做什么。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`ptc-runtime/`](ptc-runtime/README.zh.md) | 定义PTC 运行时做什么:针对宿主提供的绑定运行一个程序,并报告其打印和返回的内容 | `ctx.ptcRuntime` | +| [`ptc-runtime-node/`](ptc-runtime-node/README.zh.md) | 在全新受管 Node 进程中按已解析沙箱策略执行 TypeScript | 注册 `ctx.ptcRuntime` | +| [`experimental/ptc-runtime-python/`](../experimental/ptc-runtime-python/README.zh.md) | 实验性 Python 后端:负责 Node 宿主与 CPython 子进程之间的 fd-3 协议,以及 CPython 运行时实现 | — | + +----- + + +## 相关文档 + +先从子系统参考了解服务约定,再看消费此能力的 PTC mode 设计,以及它所遵循的能力 seam 模型。 + +- [PTC 运行时子系统参考](../../docs/subsystems/ptc-runtime.zh.md)——请求/结果词汇、绑定与 `ctx.ptcRuntime` 的 Cordis 接口面。 +- [PTC mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)——工具注册表如何把 `run_code` 呈现给模型。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/code-runtime/code-runtime-node/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml similarity index 54% rename from packages/code-runtime/code-runtime-node/README.i18n.yaml rename to packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml index 48089fd887..ce631ed79c 100644 --- a/packages/code-runtime/code-runtime-node/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/code-runtime/code-runtime-node/README.md -README.md: d312ee329b0245c35ef25c6de9c516c34848f2ab -README.zh.md: 7488532ec78622b0e6c197c7fea1a6ab9f813c67 +# pnpm run verify-translation-pairing --write packages/ptc-runtime/ptc-runtime-node/README.md +README.md: 3f8cdee44d863a8f7539b0975a95695692da4e58 +README.zh.md: 76f975bc752ee89e1b2b56ad30b118787e45e0b4 diff --git a/packages/code-runtime/code-runtime-node/README.md b/packages/ptc-runtime/ptc-runtime-node/README.md similarity index 93% rename from packages/code-runtime/code-runtime-node/README.md rename to packages/ptc-runtime/ptc-runtime-node/README.md index d312ee329b..3f8cdee44d 100644 --- a/packages/code-runtime/code-runtime-node/README.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.md @@ -3,7 +3,7 @@ description: "Run TypeScript programs in fresh Node processes with the session f kind: "package-reference" --- -# @deepseek-ai/dsh-code-runtime-node +# @deepseek-ai/dsh-ptc-runtime-node English | [中文](README.zh.md) @@ -32,7 +32,7 @@ Mount this provider in a composition that supplies `fs`, `subprocess`, `sandbox` Configure the provider row after its required services are available: ```yaml -- name: '@deepseek-ai/dsh-code-runtime-node' +- name: '@deepseek-ai/dsh-ptc-runtime-node' config: timeoutMs: 120000 maxTimeoutMs: 600000 @@ -55,7 +55,7 @@ Configure the provider row after its required services are available: | `nodeExecutable` | Current Node executable | Executable resolved in the subprocess execution world | | `bootstrapPath` | Package bootstrap | Optional absolute path to a preinstalled built bootstrap in that world | -The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-code-runtime-node) defines accepted config fields. `resolve(request)` supplies cwd, the capped timeout and the execution policy; `run(spec)` accepts those resolved inputs and does not fill missing values. +The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-ptc-runtime-node) defines accepted config fields. `resolve(request)` supplies cwd, the capped timeout and the execution policy; `run(spec)` accepts those resolved inputs and does not fill missing values. ### Execution and results @@ -114,8 +114,8 @@ Source execution loads an erasable-only bootstrap closure without relying on sib Read the service contract before using the provider directly; the decisions explain policy and consumer ownership. -- [Code runtime service](../code-runtime/README.md) — requests, resolved specs and results. -- [Sandboxed Node decision](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md) — security, lifecycle and timeout tradeoffs. +- [PTC runtime service](../ptc-runtime/README.md) — requests, resolved specs and results. +- [Sandboxed Node decision](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md) — security, lifecycle and timeout tradeoffs. - [PTC foundation](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) — registry presentation and nested tool dispatch. - [Subprocess provider](../../subprocess/subprocess-local/README.md) — managed process ranges and platform limitations. @@ -150,6 +150,6 @@ These limits qualify the execution guarantees and retained output.
Working context for maintainers — click to expand -The [timeout discussion](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.md#deferred-timeout-design) records open choices about yielding, total lifetime, approval wait accounting and process-tree CPU/RSS limits. Those choices do not change the configured elapsed deadline. +The [timeout discussion](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md#deferred-timeout-design) records open choices about yielding, total lifetime, approval wait accounting and process-tree CPU/RSS limits. Those choices do not change the configured elapsed deadline.
diff --git a/packages/code-runtime/code-runtime-node/README.zh.md b/packages/ptc-runtime/ptc-runtime-node/README.zh.md similarity index 92% rename from packages/code-runtime/code-runtime-node/README.zh.md rename to packages/ptc-runtime/ptc-runtime-node/README.zh.md index 7488532ec7..76f975bc75 100644 --- a/packages/code-runtime/code-runtime-node/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.zh.md @@ -3,7 +3,7 @@ description: "在全新 Node 进程中运行 TypeScript 程序,使用会话文 kind: "package-reference" --- -# @deepseek-ai/dsh-code-runtime-node +# @deepseek-ai/dsh-ptc-runtime-node [English](README.md) | 中文 @@ -32,7 +32,7 @@ kind: "package-reference" 在所需服务可用后,配置提供方条目: ```yaml -- name: '@deepseek-ai/dsh-code-runtime-node' +- name: '@deepseek-ai/dsh-ptc-runtime-node' config: timeoutMs: 120000 maxTimeoutMs: 600000 @@ -55,7 +55,7 @@ kind: "package-reference" | `nodeExecutable` | 当前 Node 可执行文件 | 在子进程执行世界中解析的可执行文件 | | `bootstrapPath` | 包内 bootstrap | 该执行世界中预先安装的构建后 bootstrap 的可选绝对路径 | -[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-code-runtime-node)定义可接受的配置字段。`resolve(request)` 补全 cwd、封顶后的 timeout 与执行策略;`run(spec)` 接受这些已解析输入,不补缺省值。 +[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-ptc-runtime-node)定义可接受的配置字段。`resolve(request)` 补全 cwd、封顶后的 timeout 与执行策略;`run(spec)` 接受这些已解析输入,不补缺省值。 ### 执行与结果 @@ -114,8 +114,8 @@ Host 擦除可擦除类型,在配置的执行世界中解析可执行文件与 直接使用提供方前先读服务约定;决策记录解释策略与消费方职责。 -- [代码运行时服务](../code-runtime/README.zh.md)——请求、已解析 spec 与结果。 -- [沙箱 Node 决策](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.zh.md)——安全、生命周期与 timeout 取舍。 +- [PTC 运行时服务](../ptc-runtime/README.zh.md)——请求、已解析 spec 与结果。 +- [沙箱 Node 决策](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)——安全、生命周期与 timeout 取舍。 - [PTC 基础](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)——注册表呈现与嵌套工具分派。 - [子进程提供方](../../subprocess/subprocess-local/README.zh.md)——受管进程范围与平台限制。 @@ -150,6 +150,6 @@ Host 擦除可擦除类型,在配置的执行世界中解析可执行文件与
维护者工作上下文——点击展开 -[timeout 讨论](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-code-runtime.zh.md#deferred-timeout-design)记录 yield、总生命周期、审批等待计时和进程树 CPU/RSS 上限的开放选择。这些选择不改变已配置的经过时间截止。 +[timeout 讨论](../../../.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md#deferred-timeout-design)记录 yield、总生命周期、审批等待计时和进程树 CPU/RSS 上限的开放选择。这些选择不改变已配置的经过时间截止。
diff --git a/packages/code-runtime/code-runtime-node/package.json b/packages/ptc-runtime/ptc-runtime-node/package.json similarity index 87% rename from packages/code-runtime/code-runtime-node/package.json rename to packages/ptc-runtime/ptc-runtime-node/package.json index a163f942e8..e2bce8414a 100644 --- a/packages/code-runtime/code-runtime-node/package.json +++ b/packages/ptc-runtime/ptc-runtime-node/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-code-runtime-node", - "description": "Sandboxed Node process implementation of the DeepSeek Harness code-execution capability", + "name": "@deepseek-ai/dsh-ptc-runtime-node", + "description": "Sandboxed Node process implementation of the DeepSeek Harness PTC execution capability", "version": "0.1.5-rc.2", "publishConfig": { "access": "public" @@ -8,7 +8,7 @@ "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/code-runtime/code-runtime-node" + "directory": "packages/ptc-runtime/ptc-runtime-node" }, "type": "module", "main": "lib/index.js", @@ -32,7 +32,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", "@deepseek-ai/dsh-fs": "workspace:^", @@ -46,7 +46,7 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", "@deepseek-ai/dsh-fs": "workspace:^", diff --git a/packages/code-runtime/code-runtime-node/src/bindings.ts b/packages/ptc-runtime/ptc-runtime-node/src/bindings.ts similarity index 61% rename from packages/code-runtime/code-runtime-node/src/bindings.ts rename to packages/ptc-runtime/ptc-runtime-node/src/bindings.ts index ce7d50153a..f23ec35948 100644 --- a/packages/code-runtime/code-runtime-node/src/bindings.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/bindings.ts @@ -1,17 +1,17 @@ /** Validate and capture the binding names available to one program. */ -import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-code-runtime' -import type { CodeBindingNamespace, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime' +import { DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcBindingNamespace, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime' const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/ /** * Reject unusable namespaces before starting a process. * @param request - Host-owned binding declarations. * @returns Namespaces keyed by their declared global. */ -export function validateBindings(request: CodeRunRequest): Map { - const bindings = new Map() +export function validateBindings(request: PtcRunRequest): Map { + const bindings = new Map() for (const namespace of request.bindings) { if (!IDENTIFIER.test(namespace.global) || PORTABLE_RESERVED_WORDS.has(namespace.global)) { - throw new Error(`dsh-code-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`) + throw new Error(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`) } // RESERVED_BINDING_GLOBALS is the seam's shared backend-owned set: // `console` is THIS backend's log-capture slot; the dunder entries exist @@ -20,10 +20,10 @@ export function validateBindings(request: CodeRunRequest): Map { if (value === undefined) return {} - let snapshot: ReturnType + let snapshot: ReturnType try { - snapshot = snapshotCodeJsonValue(value) + snapshot = snapshotPtcJsonValue(value) } catch { snapshot = undefined } @@ -184,7 +184,7 @@ export function prepareCompletion( if (jsonValueBytesUpTo(snapshot, remainingOutputBytes) === undefined) { return outputLimit(maxOutputBytes) } - return { value: encodeCodeJsonWire(snapshot) } + return { value: encodePtcJsonWire(snapshot) } } /** Build the fixed overflow fragment without carrying rejected variable bytes. */ @@ -287,7 +287,7 @@ export function wireReplies(port: BootstrapPort, pending: Map => { - let detached: ReturnType + let detached: ReturnType try { - detached = snapshotCodeJsonValue(args) + detached = snapshotPtcJsonValue(args) } catch { detached = undefined } @@ -342,7 +342,7 @@ export function makeNamespaces( }, }) try { - port.postMessage({ type: 'call', id, global, name, args: encodeCodeJsonWire(detached) }) + port.postMessage({ type: 'call', id, global, name, args: encodePtcJsonWire(detached) }) } catch (error: unknown) { pending.delete(id) const message = `binding arguments must be structured-cloneable: ${error instanceof CapturedError ? error.message : String(error)}` diff --git a/packages/code-runtime/code-runtime-node/src/channel.ts b/packages/ptc-runtime/ptc-runtime-node/src/channel.ts similarity index 97% rename from packages/code-runtime/code-runtime-node/src/channel.ts rename to packages/ptc-runtime/ptc-runtime-node/src/channel.ts index 9836a2a2d3..71e89e7570 100644 --- a/packages/code-runtime/code-runtime-node/src/channel.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/channel.ts @@ -1,7 +1,7 @@ /** Length-prefixed JSON transport with bounded input and queued writes. */ import { Buffer } from 'node:buffer' import type { Duplex } from 'node:stream' -import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' +import type { PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' import { jsonValueBytesUpTo } from './output-json.ts' const stringify = JSON.stringify @@ -89,7 +89,7 @@ export class JsonChannel { */ send(message: unknown): Promise { if (this.closed) return Promise.reject(new Error('control channel is closed')) - const size = jsonValueBytesUpTo(message as CodeJsonValue, this.maxBytes) + const size = jsonValueBytesUpTo(message as PtcJsonValue, this.maxBytes) if (size === undefined || this.queuedBytes + size > this.maxBytes) { return Promise.reject(new Error(`control output exceeds ${this.maxBytes} queued bytes`)) } diff --git a/packages/code-runtime/code-runtime-node/src/environment.ts b/packages/ptc-runtime/ptc-runtime-node/src/environment.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/src/environment.ts rename to packages/ptc-runtime/ptc-runtime-node/src/environment.ts diff --git a/packages/code-runtime/code-runtime-node/src/index.ts b/packages/ptc-runtime/ptc-runtime-node/src/index.ts similarity index 88% rename from packages/code-runtime/code-runtime-node/src/index.ts rename to packages/ptc-runtime/ptc-runtime-node/src/index.ts index ddd59de6f9..ef9ea51523 100644 --- a/packages/code-runtime/code-runtime-node/src/index.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/index.ts @@ -3,8 +3,8 @@ import { stripTypeScriptTypes } from 'node:module' import { isAbsolute } from 'node:path' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeBindingNamespace, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult, CodeRunSandbox, CodeRunSpec } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcBindingNamespace, PtcJsonValue, PtcRunFailure, PtcRunRequest, PtcRunResult, PtcRunSandbox, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { MAX_TIMER_DELAY_MS, clampTimeout } from '@deepseek-ai/dsh-timeout' import { SandboxUnavailableError, classifyRunnerFailure, isRunnerSpawnFailure } from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv, SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' @@ -19,7 +19,7 @@ import type { LaunchConfig } from './launch.ts' import { OutputLedger } from './output-ledger.ts' import { drainOutput } from './output-stream.ts' import { STARTUP_ENVIRONMENT_NAMES } from './environment.ts' -import { decodeCodeJsonWire, encodeCodeJsonWire } from './json-wire.ts' +import { decodePtcJsonWire, encodePtcJsonWire } from './json-wire.ts' import type { ProgramBootData } from './protocol.ts' /** Deployment-varying runtime bounds and launch choices. */ @@ -49,7 +49,7 @@ function messageOf(error: unknown): string { return error instanceof Error ? err function record(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } /** Node provider; direct file effects use the same sandbox service as Bash. */ -export class NodeCodeRuntime extends CodeRuntime { +export class NodePtcRuntime extends PtcRuntime { static inject = ['fs', 'subprocess', 'sandbox', 'sandboxPolicy'] static Config: z = z.object({ timeoutMs: z.number().default(120_000), @@ -75,23 +75,23 @@ export class NodeCodeRuntime extends CodeRuntime { super(ctx) this.config = { ...config, nodeExecutable: config.nodeExecutable ?? process.execPath } as ResolvedConfig for (const [key, value] of Object.entries(this.config)) { - if (typeof value === 'number' && (!Number.isFinite(value) || value <= 0)) throw new Error(`code-runtime-node: ${key} must be positive and finite`) + if (typeof value === 'number' && (!Number.isFinite(value) || value <= 0)) throw new Error(`ptc-runtime-node: ${key} must be positive and finite`) } for (const key of ['timeoutMs', 'maxTimeoutMs', 'graceMs'] as const) { - if (this.config[key] > MAX_TIMER_DELAY_MS) throw new Error(`code-runtime-node: ${key} exceeds the supported timer range`) + if (this.config[key] > MAX_TIMER_DELAY_MS) throw new Error(`ptc-runtime-node: ${key} exceeds the supported timer range`) } - if (!Number.isSafeInteger(this.config.maxOutputBytes) || this.config.maxOutputBytes < 4) throw new Error('code-runtime-node: maxOutputBytes must be an integer of at least 4') - if (!Number.isSafeInteger(this.config.maxMessageBytes) || this.config.maxMessageBytes > 0xffff_ffff) throw new Error('code-runtime-node: maxMessageBytes must fit an unsigned 32-bit frame length') - if (!Number.isSafeInteger(this.config.maxPendingCalls)) throw new Error('code-runtime-node: maxPendingCalls must be an integer') - if (!Number.isSafeInteger(this.config.maxOldGenerationSizeMb)) throw new Error('code-runtime-node: maxOldGenerationSizeMb must be an integer') - if (this.config.nodeExecutable.length === 0) throw new Error('code-runtime-node: nodeExecutable must be non-empty') - if (this.config.bootstrapPath !== undefined && !isAbsolute(this.config.bootstrapPath)) throw new Error('code-runtime-node: bootstrapPath must be absolute') + if (!Number.isSafeInteger(this.config.maxOutputBytes) || this.config.maxOutputBytes < 4) throw new Error('ptc-runtime-node: maxOutputBytes must be an integer of at least 4') + if (!Number.isSafeInteger(this.config.maxMessageBytes) || this.config.maxMessageBytes > 0xffff_ffff) throw new Error('ptc-runtime-node: maxMessageBytes must fit an unsigned 32-bit frame length') + if (!Number.isSafeInteger(this.config.maxPendingCalls)) throw new Error('ptc-runtime-node: maxPendingCalls must be an integer') + if (!Number.isSafeInteger(this.config.maxOldGenerationSizeMb)) throw new Error('ptc-runtime-node: maxOldGenerationSizeMb must be an integer') + if (this.config.nodeExecutable.length === 0) throw new Error('ptc-runtime-node: nodeExecutable must be non-empty') + if (this.config.bootstrapPath !== undefined && !isAbsolute(this.config.bootstrapPath)) throw new Error('ptc-runtime-node: bootstrapPath must be absolute') ctx.effect(() => async () => { this.disposed = true const active = [...this.live] for (const run of active) run.controller.abort('runtime disposed') await Promise.all(active.map(run => run.finished)) - }, 'Node code-runtime cleanup') + }, 'Node ptc-runtime cleanup') } override get sandboxMode(): SandboxMode { return this.ctx.sandboxPolicy.defaultMode } @@ -105,15 +105,15 @@ export class NodeCodeRuntime extends CodeRuntime { * @param request - Program, bindings, optional cwd/deadline, and resolved authority. * @returns Complete execution inputs with a capped deadline. */ - resolve(request: CodeRunRequest): CodeRunSpec { - if (this.disposed) throw new Error('code-runtime-node: resolve after disposal') + resolve(request: PtcRunRequest): PtcRunSpec { + if (this.disposed) throw new Error('ptc-runtime-node: resolve after disposal') const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve() const cwd = request.cwd ?? sandboxPolicy.workspaceRoot - if (!isAbsolute(cwd)) throw new Error('code-runtime-node: cwd must be absolute') + if (!isAbsolute(cwd)) throw new Error('ptc-runtime-node: cwd must be absolute') return { ...request, cwd, - timeoutMs: clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, 'code-runtime-node: timeoutMs'), + timeoutMs: clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, 'ptc-runtime-node: timeoutMs'), sandboxPolicy, } } @@ -123,10 +123,10 @@ export class NodeCodeRuntime extends CodeRuntime { * @param spec - Inputs returned by resolve; missing authority is caller misuse. * @returns Output and file-confinement facts after managed cleanup. */ - async run(spec: CodeRunSpec): Promise { - if (this.disposed) throw new Error('code-runtime-node: run after disposal') - if (spec.sandboxPolicy === undefined) throw new Error('code-runtime-node: run requires a resolved sandbox policy') - if (!isAbsolute(spec.cwd) || !Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs) throw new Error('code-runtime-node: run requires resolved cwd and timeout') + async run(spec: PtcRunSpec): Promise { + if (this.disposed) throw new Error('ptc-runtime-node: run after disposal') + if (spec.sandboxPolicy === undefined) throw new Error('ptc-runtime-node: run requires a resolved sandbox policy') + if (!isAbsolute(spec.cwd) || !Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs) throw new Error('ptc-runtime-node: run requires resolved cwd and timeout') const bindings = validateBindings(spec) const controller = new AbortController() const completion = Promise.withResolvers() @@ -141,15 +141,15 @@ export class NodeCodeRuntime extends CodeRuntime { } private async execute( - spec: CodeRunSpec, + spec: PtcRunSpec, policy: SandboxExecutionPolicy, - bindings: Map, + bindings: Map, controller: AbortController, - ): Promise { + ): Promise { const output = new OutputLedger(this.config.maxOutputBytes) const logs: string[] = [] - const sandbox: CodeRunSandbox = { mode: policy.mode, denied: false } - const result = Promise.withResolvers() + const sandbox: PtcRunSandbox = { mode: policy.mode, denied: false } + const result = Promise.withResolvers() const signal = spec.signal === undefined ? controller.signal : AbortSignal.any([spec.signal, controller.signal]) let handle: SubprocessHandle | undefined let channel: JsonChannel | undefined @@ -157,11 +157,11 @@ export class NodeCodeRuntime extends CodeRuntime { let settled = false let timedOut = false let outputOverflow = false - let overflowResult: CodeRunResult | undefined + let overflowResult: PtcRunResult | undefined let stderr = '' let parsing = true const wallTimer = setTimeout(() => { timedOut = true; controller.abort('execution deadline reached') }, spec.timeoutMs) - const finish = (failure?: CodeRunFailure, value?: CodeJsonValue): void => { + const finish = (failure?: PtcRunFailure, value?: PtcJsonValue): void => { if (settled) return settled = true clearTimeout(wallTimer) @@ -229,7 +229,7 @@ export class NodeCodeRuntime extends CodeRuntime { .filter(key => !STARTUP_ENVIRONMENT_NAMES.has(key.toUpperCase())) .map(key => [key, undefined])) if (packaged) { - env.DSH_CODE_RUNTIME_NODE = '1' + env.DSH_PTC_RUNTIME_NODE = '1' env.NODE_OPTIONS = heapFlag } handle = this.ctx.subprocess.spawn({ argv: confined?.argv ?? argv, cwd: spec.cwd, env, stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', control: 'pipe' }, graceMs: this.config.graceMs, signal }) @@ -294,7 +294,7 @@ export class NodeCodeRuntime extends CodeRuntime { case 'done': { if (raw.error !== undefined) { if (!record(raw.error) || typeof raw.error.message !== 'string' || (raw.error.kind !== 'exception' && raw.error.kind !== 'invalid-output' && raw.error.kind !== 'output-limit')) { protocolFailure('invalid terminal error'); return } - const failure = { kind: raw.error.kind, message: raw.error.message } as CodeRunFailure + const failure = { kind: raw.error.kind, message: raw.error.message } as PtcRunFailure if (confined !== undefined) { sandbox.denied = confined.denialSignatures.some(signature => failure.message.toLowerCase().includes(signature.toLowerCase())) @@ -303,7 +303,7 @@ export class NodeCodeRuntime extends CodeRuntime { finish(failure) return } - const value = raw.value === undefined ? undefined : decodeCodeJsonWire(raw.value) + const value = raw.value === undefined ? undefined : decodePtcJsonWire(raw.value) if (raw.value !== undefined && value === undefined) finish({ kind: 'invalid-output', message: 'program completion must be lossless JSON' }) else finish(undefined, value) return @@ -314,7 +314,7 @@ export class NodeCodeRuntime extends CodeRuntime { const functions = bindings.get(raw.global)?.functions const fn = functions !== undefined && Object.hasOwn(functions, raw.name) ? functions[raw.name] : undefined if (typeof fn !== 'function') { protocolFailure('program requested an undeclared binding'); return } - const args = decodeCodeJsonWire(raw.args) + const args = decodePtcJsonWire(raw.args) if (args === undefined) { protocolFailure('binding arguments must be lossless JSON'); return } if (++pending > this.config.maxPendingCalls || (pendingBytes += bytes) > this.config.maxMessageBytes) { protocolFailure('pending binding calls exceed configured limits'); return } const id = raw.id @@ -323,7 +323,7 @@ export class NodeCodeRuntime extends CodeRuntime { try { const value = snapshotJsonValue(await fn(args)) if (value === undefined) throw new Error('binding resolution must be lossless JSON') - reply = { type: 'reply', id, ok: true, value: encodeCodeJsonWire(value) } + reply = { type: 'reply', id, ok: true, value: encodePtcJsonWire(value) } } catch (error: unknown) { reply = { type: 'reply', id, ok: false, message: messageOf(error) } } finally { @@ -353,4 +353,4 @@ export class NodeCodeRuntime extends CodeRuntime { } } -export default NodeCodeRuntime +export default NodePtcRuntime diff --git a/packages/code-runtime/code-runtime-node/src/json-wire.ts b/packages/ptc-runtime/ptc-runtime-node/src/json-wire.ts similarity index 91% rename from packages/code-runtime/code-runtime-node/src/json-wire.ts rename to packages/ptc-runtime/ptc-runtime-node/src/json-wire.ts index a0578e62be..2a15d68383 100644 --- a/packages/code-runtime/code-runtime-node/src/json-wire.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/json-wire.ts @@ -1,9 +1,9 @@ /** * Lossless-JSON snapshots for the dependency-free source bootstrap closure. - * @module @deepseek-ai/dsh-code-runtime-node/json-wire + * @module @deepseek-ai/dsh-ptc-runtime-node/json-wire */ -import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' +import type { PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' /* jscpd:ignore-start -- the source bootstrap mirrors session JSON helpers without workspace runtime imports */ type IntrinsicCallable = (this: unknown, ...args: unknown[]) => unknown @@ -129,13 +129,13 @@ function enumerableStringKeys(value: object): string[] | undefined { type SnapshotDestination = | { kind: 'root' } - | { kind: 'array'; target: CodeJsonValue[]; index: number } - | { kind: 'object'; target: Record; key: string } + | { kind: 'array'; target: PtcJsonValue[]; index: number } + | { kind: 'object'; target: Record; key: string } type SnapshotTask = | { kind: 'visit'; value: unknown; destination: SnapshotDestination } - | { kind: 'array-item'; source: unknown[]; index: number; target: CodeJsonValue[] } - | { kind: 'object-property'; source: Record; key: string; target: Record } + | { kind: 'array-item'; source: unknown[]; index: number; target: PtcJsonValue[] } + | { kind: 'object-property'; source: Record; key: string; target: Record } | { kind: 'leave'; source: object } /** @@ -147,10 +147,10 @@ type SnapshotTask = * @param value - the candidate completion value. * @returns a detached lossless-JSON snapshot, or `undefined` when invalid. */ -export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined { +export function snapshotPtcJsonValue(value: unknown): PtcJsonValue | undefined { const active = new IntrinsicSet() - let root: CodeJsonValue | undefined - const assign = (destination: SnapshotDestination, item: CodeJsonValue): void => { + let root: PtcJsonValue | undefined + const assign = (destination: SnapshotDestination, item: PtcJsonValue): void => { if (destination.kind === 'root') { root = item } else if (destination.kind === 'array') { @@ -205,7 +205,7 @@ export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined if (!hasPlainArrayPrototype(candidate)) return undefined const length = candidate.length if (intrinsicReflectOwnKeys(candidate).length !== length + 1) return undefined - const target: CodeJsonValue[] = [] + const target: PtcJsonValue[] = [] assign(task.destination, target) setAdd(active, candidate) append(tasks, { kind: 'leave', source: candidate }) @@ -218,7 +218,7 @@ export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined if (!hasPlainObjectPrototype(candidate)) return undefined const keys = enumerableStringKeys(candidate) if (keys === undefined) return undefined - const target: Record = {} + const target: Record = {} assign(task.destination, target) setAdd(active, candidate) append(tasks, { kind: 'leave', source: candidate }) @@ -242,23 +242,23 @@ interface ObjectWireToken { keys: string[] } -type CodeJsonToken = null | boolean | number | string | ArrayWireToken | ObjectWireToken +type PtcJsonToken = null | boolean | number | string | ArrayWireToken | ObjectWireToken /** * A pre-order, bounded-depth transport for one lossless JSON value. Container * markers and scalar leaves share one flat token array, so JSON serialization * does not recurse through the value's application nesting. */ -export type CodeJsonWire = CodeJsonToken[] +export type PtcJsonWire = PtcJsonToken[] /** * Flatten one validated JSON value for the process control channel. * @param value - the lossless JSON value to transport. * @returns a pre-order token stream whose own nesting is bounded. */ -export function encodeCodeJsonWire(value: CodeJsonValue): CodeJsonWire { - const wire: CodeJsonWire = [] - const pending: CodeJsonValue[] = [value] +export function encodePtcJsonWire(value: PtcJsonValue): PtcJsonWire { + const wire: PtcJsonWire = [] + const pending: PtcJsonValue[] = [value] for (let current = takeLast(pending); current !== undefined; current = takeLast(pending)) { if (current === null || typeof current === 'boolean' || typeof current === 'number' || typeof current === 'string') { append(wire, current) @@ -288,8 +288,8 @@ export function encodeCodeJsonWire(value: CodeJsonValue): CodeJsonWire { } type DecodeFrame = - | { kind: 'array'; target: CodeJsonValue[]; length: number; index: number } - | { kind: 'object'; target: Record; keys: string[]; index: number } + | { kind: 'array'; target: PtcJsonValue[]; length: number; index: number } + | { kind: 'object'; target: Record; keys: string[]; index: number } /** Whether an array contains exactly its dense indexed slots and `length`. */ function isDenseArray(value: unknown[]): boolean { @@ -346,15 +346,15 @@ function containerToken(value: object): ArrayWireToken | ObjectWireToken | undef * @param input - untrusted message-port payload. * @returns the detached JSON value, or `undefined` when the wire is invalid. */ -export function decodeCodeJsonWire(input: unknown): CodeJsonValue | undefined { +export function decodePtcJsonWire(input: unknown): PtcJsonValue | undefined { try { if (!intrinsicArrayIsArray(input) || !isDenseArray(input) || input.length === 0) return undefined const wire = input as unknown[] const frames: DecodeFrame[] = [] - let root: CodeJsonValue | undefined + let root: PtcJsonValue | undefined let rootAssigned = false - const attach = (value: CodeJsonValue): boolean => { + const attach = (value: PtcJsonValue): boolean => { const parent = frames[frames.length - 1] if (!parent) { if (rootAssigned) return false @@ -378,7 +378,7 @@ export function decodeCodeJsonWire(input: unknown): CodeJsonValue | undefined { for (let tokenIndex = 0; tokenIndex < wire.length; tokenIndex++) { const token = wire[tokenIndex] - let value: CodeJsonValue + let value: PtcJsonValue let frame: DecodeFrame | undefined if (token === null || typeof token === 'boolean' || typeof token === 'string') { value = token @@ -392,12 +392,12 @@ export function decodeCodeJsonWire(input: unknown): CodeJsonValue | undefined { const remainingTokens = wire.length - tokenIndex - 1 if (marker.kind === 'array') { if (marker.length > remainingTokens) return undefined - const target: CodeJsonValue[] = [] + const target: PtcJsonValue[] = [] value = target if (marker.length > 0) frame = { kind: 'array', target, length: marker.length, index: 0 } } else { if (marker.keys.length > remainingTokens) return undefined - const target: Record = {} + const target: Record = {} value = target if (marker.keys.length > 0) frame = { kind: 'object', target, keys: marker.keys, index: 0 } } diff --git a/packages/code-runtime/code-runtime-node/src/launch.ts b/packages/ptc-runtime/ptc-runtime-node/src/launch.ts similarity index 94% rename from packages/code-runtime/code-runtime-node/src/launch.ts rename to packages/ptc-runtime/ptc-runtime-node/src/launch.ts index ab6646c491..7a88482197 100644 --- a/packages/code-runtime/code-runtime-node/src/launch.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/launch.ts @@ -23,7 +23,7 @@ export function bootstrapArgs(fs: FileSystem, config: LaunchConfig, maxMessageBy if ('pkg' in process) return [String(maxMessageBytes)] const mapped = (path: string): string => { const result = fs.processPathFromHostPath(path) - if (result === undefined) throw new Error(`code runtime bootstrap is unavailable in the subprocess execution world: ${path}`) + if (result === undefined) throw new Error(`PTC runtime bootstrap is unavailable in the subprocess execution world: ${path}`) return result } /* v8 ignore next 3 -- built-lib.e2e.ts executes the bundled provider and sibling process.js under plain Node. */ diff --git a/packages/code-runtime/code-runtime-node/src/output-json.ts b/packages/ptc-runtime/ptc-runtime-node/src/output-json.ts similarity index 94% rename from packages/code-runtime/code-runtime-node/src/output-json.ts rename to packages/ptc-runtime/ptc-runtime-node/src/output-json.ts index 1b3145bfbd..6db423345a 100644 --- a/packages/code-runtime/code-runtime-node/src/output-json.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/output-json.ts @@ -1,6 +1,6 @@ -/** JSON string-prefix accounting for the outer-output ledger. @module @deepseek-ai/dsh-code-runtime-node/output-json */ +/** JSON string-prefix accounting for the outer-output ledger. @module @deepseek-ai/dsh-ptc-runtime-node/output-json */ -import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' +import type { PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' type IntrinsicCallable = (this: unknown, ...args: unknown[]) => unknown @@ -96,11 +96,11 @@ export function jsonStringBytesUpTo(text: string, maxBytes: number): number | un * @param maxBytes - largest serialized size the caller can admit. * @returns Exact serialized bytes, or `undefined` as soon as the cap is crossed. */ -export function jsonValueBytesUpTo(value: CodeJsonValue, maxBytes: number): number | undefined { +export function jsonValueBytesUpTo(value: PtcJsonValue, maxBytes: number): number | undefined { type Task = - | { kind: 'value'; value: CodeJsonValue } - | { kind: 'array'; value: CodeJsonValue[]; index: number } - | { kind: 'object'; value: Record; keys: string[]; index: number } + | { kind: 'value'; value: PtcJsonValue } + | { kind: 'array'; value: PtcJsonValue[]; index: number } + | { kind: 'object'; value: Record; keys: string[]; index: number } let bytes = 0 const add = (cost: number): boolean => { diff --git a/packages/code-runtime/code-runtime-node/src/output-ledger.ts b/packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts similarity index 91% rename from packages/code-runtime/code-runtime-node/src/output-ledger.ts rename to packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts index ec3ae4b2dc..572d089dc1 100644 --- a/packages/code-runtime/code-runtime-node/src/output-ledger.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts @@ -1,5 +1,5 @@ /** Combined byte accounting for retained program output. */ -import type { CodeJsonValue, CodeRunFailure, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import type { PtcJsonValue, PtcRunFailure, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts' /** One run's combined outer-output ledger; binding values never enter it. */ @@ -21,19 +21,19 @@ export class OutputLedger { } /** Finalize a successful absent-or-JSON completion against the combined cap. */ - success(logs: string[], value?: CodeJsonValue): CodeRunResult { + success(logs: string[], value?: PtcJsonValue): PtcRunResult { if (value !== undefined && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === undefined) return this.limit(logs) return { logs, ...value !== undefined ? { value } : {} } } /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */ - failure(logs: string[], error: CodeRunFailure): CodeRunResult { + failure(logs: string[], error: PtcRunFailure): PtcRunResult { if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === undefined) return this.limit(logs) return { logs, error } } /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */ - limit(logs: string[]): CodeRunResult { + limit(logs: string[]): PtcRunResult { const fullMessage = `outer output exceeded ${this.maxBytes} bytes` // The fixed diagnostic is ASCII, so every character is one byte plus the quotes. const messageBytes = fullMessage.length + 2 diff --git a/packages/code-runtime/code-runtime-node/src/output-stream.ts b/packages/ptc-runtime/ptc-runtime-node/src/output-stream.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/src/output-stream.ts rename to packages/ptc-runtime/ptc-runtime-node/src/output-stream.ts diff --git a/packages/code-runtime/code-runtime-node/src/process-entry.ts b/packages/ptc-runtime/ptc-runtime-node/src/process-entry.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/src/process-entry.ts rename to packages/ptc-runtime/ptc-runtime-node/src/process-entry.ts diff --git a/packages/code-runtime/code-runtime-node/src/process.ts b/packages/ptc-runtime/ptc-runtime-node/src/process.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/src/process.ts rename to packages/ptc-runtime/ptc-runtime-node/src/process.ts diff --git a/packages/code-runtime/code-runtime-node/src/protocol.ts b/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts similarity index 91% rename from packages/code-runtime/code-runtime-node/src/protocol.ts rename to packages/ptc-runtime/ptc-runtime-node/src/protocol.ts index cc2bef5365..01cd1f5bd5 100644 --- a/packages/code-runtime/code-runtime-node/src/protocol.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts @@ -1,10 +1,10 @@ /** * JSON message vocabulary carried by the bounded process channel. The host validates every * message because model code can write directly to the inherited descriptor. - * @module @deepseek-ai/dsh-code-runtime-node/src/protocol + * @module @deepseek-ai/dsh-ptc-runtime-node/src/protocol */ -import type { CodeJsonWire } from './json-wire.ts' +import type { PtcJsonWire } from './json-wire.ts' /** What the host hands the program at spawn, after the readiness handshake. */ export interface ProgramBootData { @@ -30,7 +30,7 @@ interface CallMessage { /** The function name within the namespace. */ name: string /** The single argument as a flat lossless-JSON wire value. */ - args: CodeJsonWire + args: PtcJsonWire } /** Program → host: captured text, streamed eagerly so output survives a mid-run termination (timeout, abort, OOM). */ @@ -54,7 +54,7 @@ interface OutputLimitMessage { */ export interface DoneMessage { type: 'done' - value?: CodeJsonWire + value?: PtcJsonWire error?: { kind: 'exception' | 'invalid-output' | 'output-limit'; message: string } } @@ -63,5 +63,5 @@ export type ProgramToHost = CallMessage | LogMessage | OutputLimitMessage | Done /** Host → program: the answer to one {@link CallMessage}. */ export type ReplyMessage = - | { type: 'reply'; id: number; ok: true; value: CodeJsonWire } + | { type: 'reply'; id: number; ok: true; value: PtcJsonWire } | { type: 'reply'; id: number; ok: false; message: string } diff --git a/packages/code-runtime/code-runtime-node/tests/bindings.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/bindings.spec.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/tests/bindings.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/bindings.spec.ts diff --git a/packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts similarity index 97% rename from packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts index fe898e5dcc..bd8e333ef0 100644 --- a/packages/code-runtime/code-runtime-node/tests/bootstrap.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts @@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events' import { LogBuffer, makeBindingErrorClasses, makeConsoleShim, makeNamespaces, captureStreamWrites, prepareCompletion, prepareException, runProgram, wireReplies } from '../src/bootstrap.ts' import type { BootstrapPort, PatchableStream, PendingCall } from '../src/bootstrap.ts' import type { ReplyMessage, ProgramToHost } from '../src/protocol.ts' -import { decodeCodeJsonWire, encodeCodeJsonWire } from '../src/json-wire.ts' +import { decodePtcJsonWire, encodePtcJsonWire } from '../src/json-wire.ts' /** * An in-process stand-in for the worker's parentPort: the test plays the @@ -41,7 +41,7 @@ class FakePort implements BootstrapPort { doneValue(): unknown { const done = this.done() - return done?.type === 'done' && done.value !== undefined ? decodeCodeJsonWire(done.value) : undefined + return done?.type === 'done' && done.value !== undefined ? decodePtcJsonWire(done.value) : undefined } } @@ -140,7 +140,7 @@ describe('captureStreamWrites', () => { describe('prepareCompletion', () => { it('omits undefined and passes lossless JSON values exactly', () => { expect(prepareCompletion(undefined, 100)).toEqual({}) - expect(prepareCompletion({ a: [1, 'two'] }, 100)).toEqual({ value: encodeCodeJsonWire({ a: [1, 'two'] }) }) + expect(prepareCompletion({ a: [1, 'two'] }, 100)).toEqual({ value: encodePtcJsonWire({ a: [1, 'two'] }) }) }) it('turns every lossy completion shape into invalid-output', () => { @@ -162,7 +162,7 @@ describe('prepareCompletion', () => { }) it('measures the exact JSON serialization at and over the boundary', () => { - expect(prepareCompletion('€', 5)).toEqual({ value: encodeCodeJsonWire('€') }) + expect(prepareCompletion('€', 5)).toEqual({ value: encodePtcJsonWire('€') }) expect(prepareCompletion('€', 4)).toEqual({ error: { kind: 'output-limit', message: 'outer output exceeded 4 bytes' }, }) @@ -216,7 +216,7 @@ describe('makeNamespaces', () => { it('exposes prototype-colliding names as ordinary own properties', async () => { const port = new FakePort() port.respond = message => message.type === 'call' - ? { type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(`${message.name}-ok`) } + ? { type: 'reply', id: message.id, ok: true, value: encodePtcJsonWire(`${message.name}-ok`) } : undefined const pending = new Map() wireReplies(port, pending) @@ -316,8 +316,8 @@ describe('runProgram', () => { const port = new FakePort() port.respond = (message) => { if (message.type !== 'call') return undefined - const args = decodeCodeJsonWire(message.args) as { n: number } - return { type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(args.n * 2) } + const args = decodePtcJsonWire(message.args) as { n: number } + return { type: 'reply', id: message.id, ok: true, value: encodePtcJsonWire(args.n * 2) } } await runProgram(port, { ...BOOT, @@ -420,8 +420,8 @@ describe('runProgram', () => { port.respond = (message) => { if (message.type !== 'call') return undefined // Deliver a stray reply first; the real one follows. - port.deliver({ type: 'reply', id: 9_999, ok: true, value: encodeCodeJsonWire('stray') }) - return { type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire('real') } + port.deliver({ type: 'reply', id: 9_999, ok: true, value: encodePtcJsonWire('stray') }) + return { type: 'reply', id: message.id, ok: true, value: encodePtcJsonWire('real') } } await runProgram(port, { ...BOOT, diff --git a/packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts b/packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts similarity index 91% rename from packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts index 27c02a176a..3988267aad 100644 --- a/packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts @@ -13,13 +13,13 @@ import { describe, expect, it } from 'vitest' const pkgDir = fileURLToPath(new URL('..', import.meta.url)) const built = ['lib/index.js', 'lib/process.js'].every(file => existsSync(join(pkgDir, file))) - && existsSync(join(pkgDir, '../code-runtime/lib/index.js')) + && existsSync(join(pkgDir, '../ptc-runtime/lib/index.js')) describe.skipIf(!built)('built lib real load path (plain node)', () => { it('runs a TypeScript program with a binding through lib/index.js and its lib/process.js entry', async () => { const script = ` const { Context } = await import('@deepseek-ai/cordis') - const { NodeCodeRuntime } = await import('@deepseek-ai/dsh-code-runtime-node') + const { NodePtcRuntime } = await import('@deepseek-ai/dsh-ptc-runtime-node') const ctx = new Context() for (const name of ['session-projection', 'fs-local', 'subprocess-local', 'sandbox-local']) { const plugin = await import('@deepseek-ai/dsh-' + name) @@ -27,8 +27,8 @@ describe.skipIf(!built)('built lib real load path (plain node)', () => { } const { default: SandboxPolicy } = await import('@deepseek-ai/dsh-sandbox-policy') await ctx.plugin(SandboxPolicy, { mode: 'read-only' }) - await ctx.plugin(NodeCodeRuntime, {}) - const result = await ctx.codeRuntime.run(ctx.codeRuntime.resolve({ + await ctx.plugin(NodePtcRuntime, {}) + const result = await ctx.ptcRuntime.run(ctx.ptcRuntime.resolve({ program: 'const doubled: number = await tools.double({ n: 21 }); console.log("halfway", doubled); let failure; try { await tools.fail({}) } catch (error) { failure = { typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } } return { doubled, failure };', bindings: [{ global: 'tools', diff --git a/packages/code-runtime/code-runtime-node/tests/channel.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/channel.spec.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/tests/channel.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/channel.spec.ts diff --git a/packages/code-runtime/code-runtime-node/tests/host-failures.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts similarity index 96% rename from packages/code-runtime/code-runtime-node/tests/host-failures.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts index a31ea316fc..c2b31d88e5 100644 --- a/packages/code-runtime/code-runtime-node/tests/host-failures.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts @@ -2,17 +2,17 @@ import { Duplex, PassThrough } from 'node:stream' import { setImmediate } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, onTestFinished, vi } from 'vitest' -import type { CodeBindingFunction, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime' +import type { PtcBindingFunction, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime' import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv } from '@deepseek-ai/dsh-sandbox' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { Config } from '../src/index.ts' import { JsonChannel } from '../src/channel.ts' -import { encodeCodeJsonWire } from '../src/json-wire.ts' +import { encodePtcJsonWire } from '../src/json-wire.ts' import { mountRuntime } from './setup.ts' -const request: CodeRunRequest = { program: 'return 1', bindings: [] } +const request: PtcRunRequest = { program: 'return 1', bindings: [] } const NO_INITIAL_FRAME = Symbol('no initial frame') async function setup(config: Config = {}, mode: 'read-only' | 'danger-full-access' = 'danger-full-access') { @@ -74,7 +74,7 @@ async function setup(config: Config = {}, mode: 'read-only' | 'danger-full-acces direct.resolve({ exitCode: 0, signal: null }) await Promise.all(writes) }) - const start = (input: CodeRunRequest = request, first: unknown = { type: 'ready' }) => { + const start = (input: PtcRunRequest = request, first: unknown = { type: 'ready' }) => { const result = runtime.run(runtime.resolve(input)) if (first !== NO_INITIAL_FRAME) queueMicrotask(() => { emit(first) }) return result @@ -92,10 +92,10 @@ async function setup(config: Config = {}, mode: 'read-only' | 'danger-full-acces } function call(id: number, value: string = '') { - return { type: 'call', id, global: 'tools', name: 'test', args: encodeCodeJsonWire(value) } + return { type: 'call', id, global: 'tools', name: 'test', args: encodePtcJsonWire(value) } } -function withBinding(fn: CodeBindingFunction): CodeRunRequest { +function withBinding(fn: PtcBindingFunction): PtcRunRequest { return { ...request, bindings: [{ global: 'tools', functions: { test: fn } }] } } @@ -146,7 +146,7 @@ describe('Node runtime host failures', () => { it('keeps partial enforcement separate from a successful program', async () => { const h = await setup({}, 'read-only') vi.spyOn(h.ctx.sandbox, 'confine').mockImplementation(async argv => confinement([...argv])) - h.onBoot(() => { h.emit({ type: 'done', value: encodeCodeJsonWire(42) }) }) + h.onBoot(() => { h.emit({ type: 'done', value: encodePtcJsonWire(42) }) }) expect(await h.start()).toEqual({ logs: [], value: 42, sandbox: { mode: 'read-only', denied: false, enforcement: 'partial' } }) }) @@ -352,7 +352,7 @@ describe('Node runtime host failures', () => { it('reports failed managed cleanup even when the program returns successfully', async () => { const h = await setup() vi.mocked(h.waitForExit).mockRejectedValue(new Error('range cannot be observed')) - h.onBoot(() => { h.emit({ type: 'done', value: encodeCodeJsonWire(42) }) }) + h.onBoot(() => { h.emit({ type: 'done', value: encodePtcJsonWire(42) }) }) expect((await h.start()).error).toEqual({ kind: 'worker-exit', message: 'managed process cleanup failed: range cannot be observed' }) }) @@ -476,11 +476,11 @@ describe('Node runtime host failures', () => { Object.defineProperty(process, 'pkg', { configurable: true, value: {} }) expect((await h.start()).error).toBeUndefined() const spec = h.spawn.mock.calls[0]?.[0] - expect(spec?.env?.DSH_CODE_RUNTIME_NODE).toBe('1') + expect(spec?.env?.DSH_PTC_RUNTIME_NODE).toBe('1') expect(Object.hasOwn(spec?.env ?? {}, 'PATH')).toBe(false) expect(spec?.argv).toEqual([process.execPath, '134217728']) expect(Object.fromEntries(Object.entries(spec?.env ?? {}).filter(([, value]) => value !== undefined))) - .toEqual({ DSH_CODE_RUNTIME_NODE: '1', NODE_OPTIONS: '--max-old-space-size=512' }) + .toEqual({ DSH_PTC_RUNTIME_NODE: '1', NODE_OPTIONS: '--max-old-space-size=512' }) } finally { if (prior === undefined) Reflect.deleteProperty(process, 'pkg') else Object.defineProperty(process, 'pkg', prior) diff --git a/packages/code-runtime/code-runtime-node/tests/json-wire.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/json-wire.spec.ts similarity index 85% rename from packages/code-runtime/code-runtime-node/tests/json-wire.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/json-wire.spec.ts index 4b0cb1cee5..ae9d757d98 100644 --- a/packages/code-runtime/code-runtime-node/tests/json-wire.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/json-wire.spec.ts @@ -1,13 +1,13 @@ import { runInNewContext } from 'node:vm' import { describe, expect, it } from 'vitest' import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' -import { decodeCodeJsonWire, encodeCodeJsonWire, snapshotCodeJsonValue } from '../src/json-wire.ts' +import { decodePtcJsonWire, encodePtcJsonWire, snapshotPtcJsonValue } from '../src/json-wire.ts' -describe('snapshotCodeJsonValue', () => { +describe('snapshotPtcJsonValue', () => { it('matches the canonical scalar boundary', () => { const unsupported = [undefined, 1n, Symbol('value'), () => 1] for (const value of [null, false, 'text', 1.25, -0, Number.NaN, Number.POSITIVE_INFINITY, ...unsupported]) { - expect(snapshotCodeJsonValue(value)).toEqual(snapshotJsonValue(value)) + expect(snapshotPtcJsonValue(value)).toEqual(snapshotJsonValue(value)) } }) @@ -16,7 +16,7 @@ describe('snapshotCodeJsonValue', () => { const nullPrototype = Object.assign(Object.create(null) as Record, { shared }) const source = { list: [nullPrototype, shared], alias: shared } - const snapshot = snapshotCodeJsonValue(source) as Record + const snapshot = snapshotPtcJsonValue(source) as Record shared.value = 2 expect(snapshot).toEqual({ list: [{ shared: { value: 1 } }, { value: 1 }], alias: { value: 1 } }) @@ -31,8 +31,8 @@ describe('snapshotCodeJsonValue', () => { array: unknown } - expect(snapshotCodeJsonValue(foreign.object)).toEqual({ nested: [1] }) - expect(snapshotCodeJsonValue(foreign.array)).toEqual([2, { ok: true }]) + expect(snapshotPtcJsonValue(foreign.object)).toEqual({ nested: [1] }) + expect(snapshotPtcJsonValue(foreign.array)).toEqual([2, { ok: true }]) }) it('reads each accepted slot once and preserves a literal __proto__ key', () => { @@ -55,7 +55,7 @@ describe('snapshotCodeJsonValue', () => { }, }) - const snapshot = snapshotCodeJsonValue(array) as Record[] + const snapshot = snapshotPtcJsonValue(array) as Record[] expect(objectReads).toBe(1) expect(arrayReads).toBe(1) @@ -68,7 +68,7 @@ describe('snapshotCodeJsonValue', () => { let value: unknown = 'leaf' for (let depth = 0; depth < 5_000; depth++) value = [value] - let cursor = snapshotCodeJsonValue(value) + let cursor = snapshotPtcJsonValue(value) for (let depth = 0; depth < 5_000; depth++) { expect(Array.isArray(cursor)).toBe(true) cursor = Array.isArray(cursor) ? cursor[0] : undefined @@ -139,7 +139,7 @@ describe('snapshotCodeJsonValue', () => { ]) { const canonical = snapshotJsonValue(value) expect(canonical).toBeUndefined() - expect(snapshotCodeJsonValue(value)).toEqual(canonical) + expect(snapshotPtcJsonValue(value)).toEqual(canonical) } }) @@ -153,7 +153,7 @@ describe('snapshotCodeJsonValue', () => { }, }) - expect(snapshotCodeJsonValue(array)).toBeUndefined() + expect(snapshotPtcJsonValue(array)).toBeUndefined() }) it('propagates a throwing getter and releases its recursion guard', () => { @@ -163,8 +163,8 @@ describe('snapshotCodeJsonValue', () => { get: () => { throw failure }, }) - expect(() => snapshotCodeJsonValue(source)).toThrow(failure) - expect(snapshotCodeJsonValue({ after: true })).toEqual({ after: true }) + expect(() => snapshotPtcJsonValue(source)).toThrow(failure) + expect(snapshotPtcJsonValue({ after: true })).toEqual({ after: true }) }) }) @@ -174,11 +174,11 @@ describe('flat worker JSON wire', () => { withPrototypeKey.__proto__ = { safe: true } const values = [null, false, true, 1.25, 'text', [], {}, [1, { nested: [2] }], withPrototypeKey] for (const value of values) { - const snapshot = snapshotCodeJsonValue(value) + const snapshot = snapshotPtcJsonValue(value) expect(snapshot).not.toBeUndefined() - expect(decodeCodeJsonWire(encodeCodeJsonWire(snapshot!))).toEqual(snapshot) + expect(decodePtcJsonWire(encodePtcJsonWire(snapshot!))).toEqual(snapshot) } - const decoded = decodeCodeJsonWire(encodeCodeJsonWire(snapshotCodeJsonValue(withPrototypeKey)!)) as Record + const decoded = decodePtcJsonWire(encodePtcJsonWire(snapshotPtcJsonValue(withPrototypeKey)!)) as Record expect(Object.hasOwn(decoded, '__proto__')).toBe(true) expect(decoded.__proto__).toEqual({ safe: true }) }) @@ -186,11 +186,11 @@ describe('flat worker JSON wire', () => { it('round-trips deep values through a bounded-depth token array', () => { let value: unknown = 'leaf' for (let depth = 0; depth < 5_000; depth++) value = [value] - const snapshot = snapshotCodeJsonValue(value)! - const wire = encodeCodeJsonWire(snapshot) + const snapshot = snapshotPtcJsonValue(value)! + const wire = encodePtcJsonWire(snapshot) expect(wire).toHaveLength(5_001) - let cursor = decodeCodeJsonWire(wire) + let cursor = decodePtcJsonWire(wire) for (let depth = 0; depth < 5_000; depth++) { expect(Array.isArray(cursor)).toBe(true) cursor = Array.isArray(cursor) ? cursor[0] : undefined @@ -246,12 +246,12 @@ describe('flat worker JSON wire', () => { [{ kind: 'object', keys: ['x'] }], [{ kind: 'object', keys: [], extra: true }], ]) { - expect(decodeCodeJsonWire(value)).toBeUndefined() + expect(decodePtcJsonWire(value)).toBeUndefined() } }) it('rejects invalid values passed through a forged static type', () => { - expect(() => encodeCodeJsonWire([undefined] as never)).toThrow(/sparse JSON array/) - expect(() => encodeCodeJsonWire({ value: undefined } as never)).toThrow(/undefined JSON object property/) + expect(() => encodePtcJsonWire([undefined] as never)).toThrow(/sparse JSON array/) + expect(() => encodePtcJsonWire({ value: undefined } as never)).toThrow(/undefined JSON object property/) }) }) diff --git a/packages/code-runtime/code-runtime-node/tests/launch.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/launch.spec.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/tests/launch.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/launch.spec.ts diff --git a/packages/code-runtime/code-runtime-node/tests/output-json.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/output-json.spec.ts similarity index 95% rename from packages/code-runtime/code-runtime-node/tests/output-json.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/output-json.spec.ts index 9d3bc4d5ef..10b19f0851 100644 --- a/packages/code-runtime/code-runtime-node/tests/output-json.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/output-json.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime' +import type { PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from '../src/output-json.ts' describe('truncateJsonStringBytes', () => { @@ -58,11 +58,11 @@ describe('jsonValueBytesUpTo', () => { expect(jsonValueBytesUpTo({ long: null }, 2)).toBeUndefined() expect(jsonValueBytesUpTo({ '': null }, 4)).toBeUndefined() expect(jsonValueBytesUpTo({ a: null }, 9)).toBeUndefined() - expect(jsonValueBytesUpTo({ a: undefined } as unknown as CodeJsonValue, 100)).toBeUndefined() + expect(jsonValueBytesUpTo({ a: undefined } as unknown as PtcJsonValue, 100)).toBeUndefined() }) it('meters deeply nested arrays without recursive stack growth', () => { - let value: CodeJsonValue = null + let value: PtcJsonValue = null for (let depth = 0; depth < 5_000; depth++) value = [value] expect(jsonValueBytesUpTo(value, 10_004)).toBe(10_004) @@ -70,7 +70,7 @@ describe('jsonValueBytesUpTo', () => { }) it('uses module-captured intrinsics after model-visible globals are mutated', () => { - const value: CodeJsonValue = { payload: ['€', 42] } + const value: PtcJsonValue = { payload: ['€', 42] } const bytes = Buffer.byteLength(JSON.stringify(value), 'utf8') const arrayIsArrayDescriptor = Object.getOwnPropertyDescriptor(Array, 'isArray')! const arrayPopDescriptor = Object.getOwnPropertyDescriptor(Array.prototype, 'pop')! diff --git a/packages/code-runtime/code-runtime-node/tests/output-ledger.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/output-ledger.spec.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/tests/output-ledger.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/output-ledger.spec.ts diff --git a/packages/code-runtime/code-runtime-node/tests/output-stream.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/output-stream.spec.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/tests/output-stream.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/output-stream.spec.ts diff --git a/packages/code-runtime/code-runtime-node/tests/process-main.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts similarity index 93% rename from packages/code-runtime/code-runtime-node/tests/process-main.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts index 998967ecd6..1bab6abee9 100644 --- a/packages/code-runtime/code-runtime-node/tests/process-main.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts @@ -3,7 +3,7 @@ import { expect, it, onTestFinished } from 'vitest' import { JsonChannel } from '../src/channel.ts' import { runNodeMain } from '../src/process.ts' import type { ProgramProcess } from '../src/process.ts' -import { decodeCodeJsonWire, encodeCodeJsonWire } from '../src/json-wire.ts' +import { decodePtcJsonWire, encodePtcJsonWire } from '../src/json-wire.ts' function endpoints() { const first = new PassThrough() @@ -30,7 +30,7 @@ it('clears process environment, dispatches a binding reply and flushes the termi const message = raw as Record messages.push(message) if (message.type === 'ready') void peer.send({ type: 'boot', data: { code: 'console.log("ready"); return await tools.echo({});', namespaces: [{ global: 'tools', names: ['echo'] }], maxOutputBytes: 1024 } }) - if (message.type === 'call') void peer.send({ type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(42) }) + if (message.type === 'call') void peer.send({ type: 'reply', id: message.id, ok: true, value: encodePtcJsonWire(42) }) }, () => {}) onTestFinished(() => { peer.close() }) await runNodeMain(child, 4096, state) @@ -39,7 +39,7 @@ it('clears process environment, dispatches a binding reply and flushes the termi expect(Object.getPrototypeOf(state.env)).toBeNull() expect(nativeEnvironment).toEqual({ SystemRoot: 'C:\\Windows', PATH: '/native/bin', TMP: 'C:\\sandbox-temp', TEMP: 'C:\\sandbox-temp' }) expect(state.exitCode).toBeUndefined() - expect(decodeCodeJsonWire(messages.find(message => message.type === 'done')?.value)).toBe(42) + expect(decodePtcJsonWire(messages.find(message => message.type === 'done')?.value)).toBe(42) }) it.each([0, -1, 1.5, 4294967296])('rejects an invalid bootstrap frame limit %i', async (limit) => { diff --git a/packages/code-runtime/code-runtime-node/tests/process.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts similarity index 90% rename from packages/code-runtime/code-runtime-node/tests/process.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts index d18ba98e11..eedadce8d1 100644 --- a/packages/code-runtime/code-runtime-node/tests/process.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/process.spec.ts @@ -6,7 +6,7 @@ import { pathToFileURL } from 'node:url' import { Duplex } from 'node:stream' import { expect, it, onTestFinished } from 'vitest' import { JsonChannel } from '../src/channel.ts' -import { decodeCodeJsonWire, encodeCodeJsonWire } from '../src/json-wire.ts' +import { decodePtcJsonWire, encodePtcJsonWire } from '../src/json-wire.ts' it('boots an unbuilt source closure outside the workspace and exchanges tool replies', async () => { const directory = await mkdtemp(join(tmpdir(), 'dsh-node-source-')) @@ -36,11 +36,11 @@ it('boots an unbuilt source closure outside the workspace and exchanges tool rep maxOutputBytes: 10_000, } }).catch((error: unknown) => { completed.reject(error) }) } else if (message.type === 'call') { - expect(decodeCodeJsonWire(message.args)).toEqual({ n: 21 }) - void channel.send({ type: 'reply', id: message.id, ok: true, value: encodeCodeJsonWire(42) }).catch((error: unknown) => { completed.reject(error) }) + expect(decodePtcJsonWire(message.args)).toEqual({ n: 21 }) + void channel.send({ type: 'reply', id: message.id, ok: true, value: encodePtcJsonWire(42) }).catch((error: unknown) => { completed.reject(error) }) } else if (message.type === 'done') { if (message.error !== undefined) completed.reject(new Error(JSON.stringify(message.error))) - else completed.resolve(decodeCodeJsonWire(message.value)) + else completed.resolve(decodePtcJsonWire(message.value)) } }, (error) => { completed.reject(error) }) onTestFinished(async () => { channel.close(); child.kill(); await finished }) diff --git a/packages/code-runtime/code-runtime-node/tests/runtime.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts similarity index 98% rename from packages/code-runtime/code-runtime-node/tests/runtime.spec.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts index 6f53e93dc7..f83a39213d 100644 --- a/packages/code-runtime/code-runtime-node/tests/runtime.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts @@ -6,7 +6,7 @@ import { Context } from '@deepseek-ai/cordis' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' import { describe, expect, it, onTestFinished, vi } from 'vitest' -import type { CodeBindingFunction, CodeBindingNamespace, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime' +import type { PtcBindingFunction, PtcBindingNamespace, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime' import type { Config } from '../src/index.ts' import { mountRuntime } from './setup.ts' @@ -30,11 +30,11 @@ async function setup(config: Config = {}, mode: 'read-only' | 'workspace-write' const ctx = new Context() onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) const runtime = await mountRuntime(ctx, config, { mode, workspaceRoot: cwd }) - const run = (request: CodeRunRequest) => runtime.run(runtime.resolve(request)) + const run = (request: PtcRunRequest) => runtime.run(runtime.resolve(request)) return { ctx, runtime, root, cwd, run } } -function bindings(functions: Record): CodeBindingNamespace[] { +function bindings(functions: Record): PtcBindingNamespace[] { return [{ global: 'tools', functions, errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' } }] } diff --git a/packages/code-runtime/code-runtime-node/tests/setup.ts b/packages/ptc-runtime/ptc-runtime-node/tests/setup.ts similarity index 96% rename from packages/code-runtime/code-runtime-node/tests/setup.ts rename to packages/ptc-runtime/ptc-runtime-node/tests/setup.ts index 8db371915d..bc1504713f 100644 --- a/packages/code-runtime/code-runtime-node/tests/setup.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/setup.ts @@ -19,5 +19,5 @@ export async function mountRuntime(ctx: Context, config: Config = {}, policy: { if (!ctx.get('sessionProjections')) await ctx.plugin(SessionProjections) if (!ctx.get('sandboxPolicy')) await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access', ...policy }) await ctx.plugin(NodeRuntime, config) - return ctx.codeRuntime as NodeRuntime + return ctx.ptcRuntime as NodeRuntime } diff --git a/packages/code-runtime/code-runtime-node/tsconfig.json b/packages/ptc-runtime/ptc-runtime-node/tsconfig.json similarity index 95% rename from packages/code-runtime/code-runtime-node/tsconfig.json rename to packages/ptc-runtime/ptc-runtime-node/tsconfig.json index 99dc9c158f..4cfa9e11ba 100644 --- a/packages/code-runtime/code-runtime-node/tsconfig.json +++ b/packages/ptc-runtime/ptc-runtime-node/tsconfig.json @@ -21,7 +21,7 @@ "path": "../../../vendor/schemastery" }, { - "path": "../code-runtime" + "path": "../ptc-runtime" }, { "path": "../../util/timeout" diff --git a/packages/code-runtime/code-runtime-node/tsdown.config.ts b/packages/ptc-runtime/ptc-runtime-node/tsdown.config.ts similarity index 100% rename from packages/code-runtime/code-runtime-node/tsdown.config.ts rename to packages/ptc-runtime/ptc-runtime-node/tsdown.config.ts diff --git a/packages/code-runtime/code-runtime/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml similarity index 54% rename from packages/code-runtime/code-runtime/README.i18n.yaml rename to packages/ptc-runtime/ptc-runtime/README.i18n.yaml index 5fe41e8ac3..da6b760267 100644 --- a/packages/code-runtime/code-runtime/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/code-runtime/code-runtime/README.md -README.md: 162d875966b0225b629a722986757035e30082e9 -README.zh.md: 9f794d1c65b165e302e1d2349dc169bd672d00c3 +# pnpm run verify-translation-pairing --write packages/ptc-runtime/ptc-runtime/README.md +README.md: e02e38a614ba50fc22db8fe357419b3c2a8e1708 +README.zh.md: 3c7b7fad9d62e6459cf7e75a9d8544e61757eeb4 diff --git a/packages/code-runtime/code-runtime/README.md b/packages/ptc-runtime/ptc-runtime/README.md similarity index 64% rename from packages/code-runtime/code-runtime/README.md rename to packages/ptc-runtime/ptc-runtime/README.md index 162d875966..e02e38a614 100644 --- a/packages/code-runtime/code-runtime/README.md +++ b/packages/ptc-runtime/ptc-runtime/README.md @@ -1,15 +1,15 @@ --- -description: "Abstract code-execution seam (`ctx.codeRuntime`) for users and maintainers composing, consuming, or building a backend that runs one model-written program against host-provided bindings." +description: "Abstract PTC execution seam (`ctx.ptcRuntime`) for users and maintainers composing, consuming, or building a backend that runs one model-written program against host-provided bindings." kind: "package-reference" --- -# @deepseek-ai/dsh-code-runtime +# @deepseek-ai/dsh-ptc-runtime English | [中文](README.zh.md) ## Summary -Use `dsh-code-runtime` to run one model-written program against host-provided asynchronous functions through a configured backend. A request returns a lossless-JSON value, ordered per-channel logs, or a structured error; program failures resolve in the result, while rejected promises indicate caller misuse. Each run is isolated from prior runs, and the runtime has no knowledge of tools or sessions. Choose an execution backend separately; its language and isolation descriptors identify the required source language and execution substrate but do not themselves promise a security boundary. +Use `dsh-ptc-runtime` to run one model-written program against host-provided asynchronous functions through a configured backend. A request returns a lossless-JSON value, ordered per-channel logs, or a structured error; program failures resolve in the result, while rejected promises indicate caller misuse. Each run is isolated from prior runs, and the runtime has no knowledge of tools or sessions. Choose an execution backend separately; its language and isolation descriptors identify the required source language and execution substrate but do not themselves promise a security boundary. ## Table of Contents @@ -25,24 +25,24 @@ Use `dsh-code-runtime` to run one model-written program against host-provided as ## Use this package -Choose this package when you compose a deployment that executes model-written programs, consume `ctx.codeRuntime` directly, or build a backend that runs programs. In the shipped composition, PTC mode in `dsh-tools` is the consumer: only what the program printed and returned re-enters the conversation. +Choose this package when you compose a deployment that executes model-written programs, consume `ctx.ptcRuntime` directly, or build a backend that runs programs. In the shipped composition, PTC mode in `dsh-tools` is the consumer: only what the program printed and returned re-enters the conversation. ### Run a program Give the runtime a program and binding namespaces, then call `resolve(request)` followed by `run(spec)`. Resolution validates optional cwd, timeout and sandbox policy against the provider's capabilities and fills deployment defaults. The program runs as an async function body, so top-level `await` and `return` work; a lossless-JSON completion becomes `result.value`, captured text becomes `result.logs`, and program failures become `result.error`. Each output channel preserves its own order, while cross-channel interleaving is backend-dependent. ```text -const spec = ctx.codeRuntime.resolve({ +const spec = ctx.ptcRuntime.resolve({ program: 'return await tools.add({ a: 1, b: 2 })', bindings: [{ global: 'tools', functions: { add: async (args) => args.a + args.b } }], }) -const result = await ctx.codeRuntime.run(spec) +const result = await ctx.ptcRuntime.run(spec) // result.value === 3 ``` ### Choose a backend -Backends expose `language` and `isolation` as diagnostic descriptors; neither grants authority or proves confinement. [`dsh-code-runtime-node`](../code-runtime-node/README.md) executes erasable TypeScript in a fresh managed Node process under the resolved sandbox policy. The private [`dsh-experimental-code-runtime-python`](../../experimental/code-runtime-python/README.md) provider executes Python in a fresh CPython subprocess without file confinement. `sandboxMode` advertises a provider's deployment file-policy mode, or is absent when that capability is unsupported. +Backends expose `language` and `isolation` as diagnostic descriptors; neither grants authority or proves confinement. [`dsh-ptc-runtime-node`](../ptc-runtime-node/README.md) executes erasable TypeScript in a fresh managed Node process under the resolved sandbox policy. The private [`dsh-experimental-ptc-runtime-python`](../../experimental/ptc-runtime-python/README.md) provider executes Python in a fresh CPython subprocess without file confinement. `sandboxMode` advertises a provider's deployment file-policy mode, or is absent when that capability is unsupported. ### Name your bindings portably @@ -64,7 +64,7 @@ This section explains the design behind the seam; observable behavior is fully c ### Design concept -The package is the Service Definition role of the code-execution capability seam ([capability seams](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): an abstract `CodeRuntime extends Service` registered as `ctx.codeRuntime`, plus the vocabulary both backends and the consumer share. Providers subclass `CodeRuntime`, implement `resolve` and `run`, and register the service; the consumer (PTC mode in `dsh-tools`) generates the model-facing SDK and bridges tool dispatch. The runtime stays ignorant of tools and sessions by contract: it receives a program, named async bindings and resolved execution options, then returns captured output, the outcome and applicable sandbox facts. +The package is the Service Definition role of the PTC execution capability seam ([capability seams](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): an abstract `PtcRuntime extends Service` registered as `ctx.ptcRuntime`, plus the vocabulary both backends and the consumer share. Providers subclass `PtcRuntime`, implement `resolve` and `run`, and register the service; the consumer (PTC mode in `dsh-tools`) generates the model-facing SDK and bridges tool dispatch. The runtime stays ignorant of tools and sessions by contract: it receives a program, named async bindings and resolved execution options, then returns captured output, the outcome and applicable sandbox facts. ### Service API @@ -74,11 +74,11 @@ The readonly `timeout` descriptor exposes `{ defaultMs, maxMs }` for a provider `resolve(request)` owns supported option validation and deployment defaulting. `run(spec)` executes the complete inputs and resolves program outcomes after cleanup. Language and substrate descriptors guide presentation; `sandboxMode` indicates whether the consumer can pass a resolved file policy. Neither descriptors nor a successful program result substitute for the backend's reported enforcement facts. -The exhaustive semantics live in the [code runtime subsystem reference](../../../docs/subsystems/code-runtime.md); the exact signatures are in [`src/index.ts`](src/index.ts). +The exhaustive semantics live in the [PTC runtime subsystem reference](../../../docs/subsystems/ptc-runtime.md); the exact signatures are in [`src/index.ts`](src/index.ts). ### Vocabulary -`CodeRunRequest` carries the program, host bindings, cancellation and optional execution choices. `CodeRunSpec` requires the resolved cwd and elapsed deadline. `CodeBindingNamespace` declares program globals and optional typed rejection constructors. `CodeRunResult` separates logs/value, failure and `CodeRunSandbox` facts; exact fields and provider obligations live in [`src/types.ts`](src/types.ts). +`PtcRunRequest` carries the program, host bindings, cancellation and optional execution choices. `PtcRunSpec` requires the resolved cwd and elapsed deadline. `PtcBindingNamespace` declares program globals and optional typed rejection constructors. `PtcRunResult` separates logs/value, failure and `PtcRunSandbox` facts; exact fields and provider obligations live in [`src/types.ts`](src/types.ts). ### Portable identifiers @@ -88,8 +88,8 @@ Binding-global and error-class names are language-portable: they must match the | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | Plugin entry: abstract `CodeRuntime` service and the portable-identifier exclusion sets | -| [`src/types.ts`](src/types.ts) | Vocabulary: `CodeRunRequest`, `CodeRunSpec`, bindings, results, failures and sandbox facts | +| [`src/index.ts`](src/index.ts) | Plugin entry: abstract `PtcRuntime` service and the portable-identifier exclusion sets | +| [`src/types.ts`](src/types.ts) | Vocabulary: `PtcRunRequest`, `PtcRunSpec`, bindings, results, failures and sandbox facts | | — | No runtime invariant companion is published; this package exposes no independent event sequence or mutable data relation beyond contracts enforced at its owning seam. | @@ -101,10 +101,10 @@ Binding-global and error-class names are language-portable: they must match the Read these when the package-level contract is not enough. They move from the PTC mode consumer to the backends and the capability-seam model. -- [PTC mode Agent Note](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) — how the tool registry consumes `ctx.codeRuntime` and presents `run_code` to the model. -- [Node process backend](../code-runtime-node/README.md) — the shipped TypeScript execution backend. -- [Experimental Python backend](../../experimental/code-runtime-python/README.md) — the private CPython subprocess provider and its fd-3 protocol. -- [Code runtime subsystem reference](../../../docs/subsystems/code-runtime.md) — request/result vocabulary, bindings, and the `ctx.codeRuntime` cordis surface. +- [PTC mode Agent Note](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) — how the tool registry consumes `ctx.ptcRuntime` and presents `run_code` to the model. +- [Node process backend](../ptc-runtime-node/README.md) — the shipped TypeScript execution backend. +- [Experimental Python backend](../../experimental/ptc-runtime-python/README.md) — the private CPython subprocess provider and its fd-3 protocol. +- [PTC runtime subsystem reference](../../../docs/subsystems/ptc-runtime.md) — request/result vocabulary, bindings, and the `ctx.ptcRuntime` cordis surface. - [Capability seams](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) — the Service Definition / Service Provider / Consumer split. ----- @@ -125,7 +125,7 @@ No direct invalidation; the named consumer owns any request-prefix changes. These limits define what the seam cannot do; they are current package constraints, not a task backlog. -- **`run()` is one-shot** — `logs` arrive only on the resolved `CodeRunResult`; the seam exposes no streaming-log or progress API for a live program's output. +- **`run()` is one-shot** — `logs` arrive only on the resolved `PtcRunResult`; the seam exposes no streaming-log or progress API for a live program's output. - **No state survives between runs** — every request runs against a fresh world; a persistent REPL-style kernel is deferred until a backend brings its own logging story. - **Providers have different confinement capabilities** — the shipped Node provider enforces a resolved file policy, while the private experimental Python provider rejects an explicit policy. No container provider is supplied. - **No uniform binding byte cap applies across providers** — each provider owns its transport limits; a binding can still allocate memory before its result reaches those limits. diff --git a/packages/code-runtime/code-runtime/README.zh.md b/packages/ptc-runtime/ptc-runtime/README.zh.md similarity index 63% rename from packages/code-runtime/code-runtime/README.zh.md rename to packages/ptc-runtime/ptc-runtime/README.zh.md index 9f794d1c65..3c7b7fad9d 100644 --- a/packages/code-runtime/code-runtime/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime/README.zh.md @@ -1,15 +1,15 @@ --- -description: "抽象代码执行 seam(`ctx.codeRuntime`),供用户与维护者组合、消费或构建后端,以针对宿主提供的绑定运行一段模型编写的程序。" +description: "抽象 PTC 执行 seam(`ctx.ptcRuntime`),供用户与维护者组合、消费或构建后端,以针对宿主提供的绑定运行一段模型编写的程序。" kind: "package-reference" --- -# @deepseek-ai/dsh-code-runtime +# @deepseek-ai/dsh-ptc-runtime [English](README.md) | 中文 ## 概述 -使用 `dsh-code-runtime`,可通过已配置的后端,针对宿主提供的异步函数运行一段模型编写的程序。请求返回无损 JSON 值、通道内有序的日志或结构化错误;程序失败在结果中 resolve,而 Promise reject 表示调用方误用。每次运行都与先前运行隔离,且运行时不了解工具或会话。执行后端需另行选择;其语言与隔离描述符标明所需的源语言和执行基底,但这些描述符本身不承诺安全边界。 +使用 `dsh-ptc-runtime`,可通过已配置的后端,针对宿主提供的异步函数运行一段模型编写的程序。请求返回无损 JSON 值、通道内有序的日志或结构化错误;程序失败在结果中 resolve,而 Promise reject 表示调用方误用。每次运行都与先前运行隔离,且运行时不了解工具或会话。执行后端需另行选择;其语言与隔离描述符标明所需的源语言和执行基底,但这些描述符本身不承诺安全边界。 ## 目录 @@ -25,24 +25,24 @@ kind: "package-reference" ## 使用本包 -当你要组合一个执行模型程序的部署、直接消费 `ctx.codeRuntime`,或构建运行程序的后端时,选择本包。在已发布的组合中,`dsh-tools` 里的 PTC mode 是消费方:只有程序打印和返回的内容重新进入对话。 +当你要组合一个执行模型程序的部署、直接消费 `ctx.ptcRuntime`,或构建运行程序的后端时,选择本包。在已发布的组合中,`dsh-tools` 里的 PTC mode 是消费方:只有程序打印和返回的内容重新进入对话。 ### 运行一个程序 向运行时提供程序与绑定命名空间,然后依次调用 `resolve(request)` 和 `run(spec)`。解析根据提供方能力验证可选 cwd、timeout 与沙箱策略,并填入部署默认值。程序作为异步函数体运行,支持顶层 `await` 与 `return`;无损 JSON 完成值成为 `result.value`,捕获文本成为 `result.logs`,程序失败成为 `result.error`。每个输出通道保持自身顺序,跨通道交错由后端决定。 ```text -const spec = ctx.codeRuntime.resolve({ +const spec = ctx.ptcRuntime.resolve({ program: 'return await tools.add({ a: 1, b: 2 })', bindings: [{ global: 'tools', functions: { add: async (args) => args.a + args.b } }], }) -const result = await ctx.codeRuntime.run(spec) +const result = await ctx.ptcRuntime.run(spec) // result.value === 3 ``` ### 选择后端 -后端以 `language` 与 `isolation` 提供诊断描述符;两者都不授予权限或证明约束。[`dsh-code-runtime-node`](../code-runtime-node/README.zh.md) 在全新的受管 Node 进程中按已解析沙箱策略执行可擦除 TypeScript。私有的 [`dsh-experimental-code-runtime-python`](../../experimental/code-runtime-python/README.zh.md) 提供方在全新 CPython 子进程中执行 Python,不提供文件约束。`sandboxMode` 声明提供方的部署文件策略模式;不支持该能力时则缺省。 +后端以 `language` 与 `isolation` 提供诊断描述符;两者都不授予权限或证明约束。[`dsh-ptc-runtime-node`](../ptc-runtime-node/README.zh.md) 在全新的受管 Node 进程中按已解析沙箱策略执行可擦除 TypeScript。私有的 [`dsh-experimental-ptc-runtime-python`](../../experimental/ptc-runtime-python/README.zh.md) 提供方在全新 CPython 子进程中执行 Python,不提供文件约束。`sandboxMode` 声明提供方的部署文件策略模式;不支持该能力时则缺省。 ### 可移植地命名绑定 @@ -64,7 +64,7 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配 `[A-Za ### 设计理念 -本包是代码执行能力 seam 的 Service Definition 角色([能力 seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)):一个注册为 `ctx.codeRuntime` 的抽象 `CodeRuntime extends Service`,加上两个后端与消费方共享的词汇。提供方继承 `CodeRuntime`、实现 `resolve` 和 `run` 并注册服务;消费方(`dsh-tools` 中的 PTC mode)生成面向模型的 SDK 并桥接工具分发。按约定,运行时不了解工具与会话:它接收程序、具名异步绑定和已解析执行选项,然后返回捕获输出、执行结果与适用的沙箱事实。 +本包是PTC 执行能力 seam 的 Service Definition 角色([能力 seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)):一个注册为 `ctx.ptcRuntime` 的抽象 `PtcRuntime extends Service`,加上两个后端与消费方共享的词汇。提供方继承 `PtcRuntime`、实现 `resolve` 和 `run` 并注册服务;消费方(`dsh-tools` 中的 PTC mode)生成面向模型的 SDK 并桥接工具分发。按约定,运行时不了解工具与会话:它接收程序、具名异步绑定和已解析执行选项,然后返回捕获输出、执行结果与适用的沙箱事实。 ### 服务 API @@ -74,11 +74,11 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配 `[A-Za `resolve(request)` 负责支持选项的验证与部署默认值。`run(spec)` 执行完整输入,并在清理后返回程序结果。语言和执行基底描述符指导呈现;`sandboxMode` 表示消费方能否传入已解析文件策略。描述符与程序成功结果都不能代替后端报告的强制能力事实。 -穷尽式语义见[代码运行时子系统参考](../../../docs/subsystems/code-runtime.zh.md);确切签名见 [`src/index.ts`](src/index.ts)。 +穷尽式语义见[PTC 运行时子系统参考](../../../docs/subsystems/ptc-runtime.zh.md);确切签名见 [`src/index.ts`](src/index.ts)。 ### 词汇 -`CodeRunRequest` 携带程序、Host 绑定、取消和可选执行选择。`CodeRunSpec` 要求已解析的 cwd 与经过时间截止。`CodeBindingNamespace` 声明程序全局对象与可选的类型化拒绝构造器。`CodeRunResult` 将日志/值、失败与 `CodeRunSandbox` 事实分开;确切字段与提供方义务见 [`src/types.ts`](src/types.ts)。 +`PtcRunRequest` 携带程序、Host 绑定、取消和可选执行选择。`PtcRunSpec` 要求已解析的 cwd 与经过时间截止。`PtcBindingNamespace` 声明程序全局对象与可选的类型化拒绝构造器。`PtcRunResult` 将日志/值、失败与 `PtcRunSandbox` 事实分开;确切字段与提供方义务见 [`src/types.ts`](src/types.ts)。 ### 可移植标识符 @@ -88,8 +88,8 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配标识 | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | 插件入口:抽象 `CodeRuntime` 服务与可移植标识符排除集 | -| [`src/types.ts`](src/types.ts) | 词汇:`CodeRunRequest`、`CodeRunSpec`、绑定、结果、失败与沙箱事实 | +| [`src/index.ts`](src/index.ts) | 插件入口:抽象 `PtcRuntime` 服务与可移植标识符排除集 | +| [`src/types.ts`](src/types.ts) | 词汇:`PtcRunRequest`、`PtcRunSpec`、绑定、结果、失败与沙箱事实 | | — | 不发布运行时不变式伴生入口;本包不公开任何独立的事件序列或可变数据关系,相关约束仅由其所属 seam 的约定实施。 | @@ -101,10 +101,10 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配标识 当包级约定不够用时阅读以下内容。它们从 PTC mode 消费方进入后端与能力 seam 模型。 -- [PTC mode Agent Note](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)——工具注册表如何消费 `ctx.codeRuntime` 并把 `run_code` 呈现给模型。 -- [Node 进程后端](../code-runtime-node/README.zh.md)——已发布的 TypeScript 执行后端。 -- [实验性 Python 后端](../../experimental/code-runtime-python/README.zh.md)——私有的 CPython 子进程提供方及其 fd-3 协议。 -- [代码运行时子系统参考](../../../docs/subsystems/code-runtime.zh.md)——请求/结果词汇、绑定与 `ctx.codeRuntime` 的 cordis 接口面。 +- [PTC mode Agent Note](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)——工具注册表如何消费 `ctx.ptcRuntime` 并把 `run_code` 呈现给模型。 +- [Node 进程后端](../ptc-runtime-node/README.zh.md)——已发布的 TypeScript 执行后端。 +- [实验性 Python 后端](../../experimental/ptc-runtime-python/README.zh.md)——私有的 CPython 子进程提供方及其 fd-3 协议。 +- [PTC 运行时子系统参考](../../../docs/subsystems/ptc-runtime.zh.md)——请求/结果词汇、绑定与 `ctx.ptcRuntime` 的 cordis 接口面。 - [能力 seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)——Service Definition / Service Provider / Consumer 拆分。 ----- @@ -125,7 +125,7 @@ binding-global 与 error-class 名称是语言可移植的:必须匹配标识 这些限制说明 seam 不能做什么;它们是当前包约束,不是任务积压。 -- **`run()` 是一次性的**——`logs` 只有在 `CodeRunResult` resolve 后才能获得;seam 不提供正在运行的程序所产生输出的流式日志或进度接口。 +- **`run()` 是一次性的**——`logs` 只有在 `PtcRunResult` resolve 后才能获得;seam 不提供正在运行的程序所产生输出的流式日志或进度接口。 - **运行之间不保留状态**——每次请求都在全新环境中运行;持久 REPL 风格内核在某个后端带来自己的日志方案之前保持延期。 - **提供方的约束能力不同**——已发布 Node 提供方强制执行已解析文件策略,私有实验性 Python 提供方拒绝显式策略。不提供容器提供方。 - **提供方之间没有统一的绑定字节上限**——各提供方负责自己的传输限制;绑定仍可能在结果到达这些限制前分配内存。 diff --git a/packages/code-runtime/code-runtime/package.json b/packages/ptc-runtime/ptc-runtime/package.json similarity index 80% rename from packages/code-runtime/code-runtime/package.json rename to packages/ptc-runtime/ptc-runtime/package.json index f9cd506334..6d34c19b64 100644 --- a/packages/code-runtime/code-runtime/package.json +++ b/packages/ptc-runtime/ptc-runtime/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-code-runtime", - "description": "Abstract code-execution seam (ctx.codeRuntime) for the DeepSeek Harness", + "name": "@deepseek-ai/dsh-ptc-runtime", + "description": "Abstract PTC execution seam (ctx.ptcRuntime) for the DeepSeek Harness", "version": "0.1.5-rc.2", "publishConfig": { "access": "public" @@ -8,7 +8,7 @@ "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/code-runtime/code-runtime" + "directory": "packages/ptc-runtime/ptc-runtime" }, "type": "module", "main": "lib/index.js", diff --git a/packages/code-runtime/code-runtime/src/index.ts b/packages/ptc-runtime/ptc-runtime/src/index.ts similarity index 84% rename from packages/code-runtime/code-runtime/src/index.ts rename to packages/ptc-runtime/ptc-runtime/src/index.ts index cce7a79545..f98b069e56 100644 --- a/packages/code-runtime/code-runtime/src/index.ts +++ b/packages/ptc-runtime/ptc-runtime/src/index.ts @@ -1,23 +1,23 @@ /** - * Service Definition for the code-execution capability seam that runs one model-written program against host async bindings. + * Service Definition for the PTC execution capability seam that runs one model-written program against host async bindings. * Runtimes know nothing about tools or sessions; consumers own those concerns. - * @module @deepseek-ai/dsh-code-runtime + * @module @deepseek-ai/dsh-ptc-runtime */ import { Context, Service } from '@deepseek-ai/cordis' -import type { CodeRunRequest, CodeRunResult, CodeRunSpec } from './types.ts' +import type { PtcRunRequest, PtcRunResult, PtcRunSpec } from './types.ts' import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' export type { - CodeBindingErrorClass, - CodeBindingFunction, - CodeBindingNamespace, - CodeJsonValue, - CodeRunFailure, - CodeRunRequest, - CodeRunResult, - CodeRunSpec, - CodeRunSandbox, + PtcBindingErrorClass, + PtcBindingFunction, + PtcBindingNamespace, + PtcJsonValue, + PtcRunFailure, + PtcRunRequest, + PtcRunResult, + PtcRunSpec, + PtcRunSandbox, } from './types.ts' /** @@ -30,7 +30,7 @@ export type { * one backend is valid on all, so a caller cannot pick a name that works on * Node and collides on Python (or vice versa). `__name__` et al. ARE * valid portable identifiers, so the identifier rule on - * `CodeBindingNamespace.global` never rejects them — hence this explicit set. + * `PtcBindingNamespace.global` never rejects them — hence this explicit set. * (Error members differ: {@link DUNDER_MEMBER} refuses every dunder form * wholesale; binding globals refuse only the names listed here.) `__debug__` * is listed for a different reason than a collision: CPython compiles a bare @@ -45,7 +45,7 @@ export const RESERVED_BINDING_GLOBALS: ReadonlySet = new Set([ ]) /** - * `CodeBindingErrorClass.memberNameProperty` names EVERY backend refuses, as + * `PtcBindingErrorClass.memberNameProperty` names EVERY backend refuses, as * one shared contract so a request valid on one backend is valid on all. The * JS `Error` exclusions (`name`, `message`, `stack`) and Python's * exception-protocol members (`args`, `with_traceback`, `add_note`) are @@ -67,7 +67,7 @@ export const DUNDER_MEMBER = /^__.+__$/ /** * Reserved words of every portable target language (ECMAScript ∪ Python), - * refused as {@link CodeBindingNamespace.global} / error-class names by all + * refused as {@link PtcBindingNamespace.global} / error-class names by all * backends, one per language: the released TypeScript Node process and the * experimental, private CPython subprocess. The portable-identifier contract * promises a namespace list valid on one backend is valid on every backend; a @@ -90,18 +90,18 @@ export const PORTABLE_RESERVED_WORDS: ReadonlySet = new Set([ declare module '@deepseek-ai/cordis' { interface Context { - codeRuntime: CodeRuntime + ptcRuntime: PtcRuntime } } /** - * Registers one `ctx.codeRuntime` implementation. Program, budget, abort, and substrate - * failures resolve in {@link CodeRunResult}; only Service Definition contract misuse rejects. Implementations bridge + * Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate + * failures resolve in {@link PtcRunResult}; only Service Definition contract misuse rejects. Implementations bridge * structured-cloneable bindings, materialize each declared namespace rejection * class, treat programs as hostile peers, isolate runs from one another, and * terminate and await in-flight runs during disposal. */ -export abstract class CodeRuntime extends Service { +export abstract class PtcRuntime extends Service { /** * The source language {@link run} expects `program` to be written in, as a * lowercase identifier. Informational, not gating — a consumer that @@ -131,7 +131,7 @@ export abstract class CodeRuntime extends Service { get timeout(): { defaultMs: number; maxMs: number } | undefined { return undefined } constructor(ctx: Context) { - super(ctx, 'codeRuntime') + super(ctx, 'ptcRuntime') } /** @@ -140,14 +140,14 @@ export abstract class CodeRuntime extends Service { * @returns Complete directory, deadline and supported authority for run. * @throws When an explicit choice is invalid or unsupported by this provider. */ - abstract resolve(request: CodeRunRequest): CodeRunSpec + abstract resolve(request: PtcRunRequest): PtcRunSpec /** * Execute resolved inputs; program outcomes resolve as result fields. * @param spec - directory, deadline, program, bindings, cancellation and supported policy. * @returns Captured output and the execution outcome. */ - abstract run(spec: CodeRunSpec): Promise + abstract run(spec: PtcRunSpec): Promise } -export default CodeRuntime +export default PtcRuntime diff --git a/packages/code-runtime/code-runtime/src/types.ts b/packages/ptc-runtime/ptc-runtime/src/types.ts similarity index 83% rename from packages/code-runtime/code-runtime/src/types.ts rename to packages/ptc-runtime/ptc-runtime/src/types.ts index 96da20baed..6e7cf89b02 100644 --- a/packages/code-runtime/code-runtime/src/types.ts +++ b/packages/ptc-runtime/ptc-runtime/src/types.ts @@ -1,9 +1,9 @@ /** - * Vocabulary types for the code-execution seam: what a caller hands a - * {@link ../index.ts | CodeRuntime} and what it gets back. Pure types — no + * Vocabulary types for the PTC execution seam: what a caller hands a + * {@link ../index.ts | PtcRuntime} and what it gets back. Pure types — no * runtime code lives here. * - * @module @deepseek-ai/dsh-code-runtime/src/types + * @module @deepseek-ai/dsh-ptc-runtime/src/types */ import type { SandboxEnforcement, SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' @@ -17,10 +17,10 @@ import type { SandboxEnforcement, SandboxExecutionPolicy, SandboxMode } from '@d * of this function surfaces inside the program as a rejection of the * corresponding call. */ -export type CodeBindingFunction = (args: unknown) => Promise +export type PtcBindingFunction = (args: unknown) => Promise /** A lossless JSON value transferable through the dependency-light Service Definition. */ -export type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | { [key: string]: CodeJsonValue } +export type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: string]: PtcJsonValue } /** * Program-visible typed rejection for one binding namespace. The runtime @@ -29,8 +29,8 @@ export type CodeJsonValue = null | boolean | number | string | CodeJsonValue[] | * `memberNameProperty`. Both strings are runtime data rather than knowledge * of a particular consumer such as PTC mode. */ -export interface CodeBindingErrorClass { - /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link CodeBindingNamespace.global}. */ +export interface PtcBindingErrorClass { + /** Constructor global and resulting `Error.name`; same portable identifier rule as {@link PtcBindingNamespace.global}. */ name: string /** * Non-empty own property for the member name. The portable exclusion set is @@ -42,13 +42,13 @@ export interface CodeBindingErrorClass { } /** - * A named group of {@link CodeBindingFunction}s the runtime exposes to the + * A named group of {@link PtcBindingFunction}s the runtime exposes to the * program as one global object (e.g. `tools`). Function names are arbitrary * strings — a runtime must treat names like `__proto__` or `constructor` as * ordinary own properties (null-prototype construction), never as prototype * collisions. */ -export interface CodeBindingNamespace { +export interface PtcBindingNamespace { /** * The global identifier the program sees. Must match the LANGUAGE-PORTABLE * identifier subset `[A-Za-z_][A-Za-z0-9_]*` and no language's reserved @@ -61,25 +61,25 @@ export interface CodeBindingNamespace { */ global: string /** The callable members, keyed by the exact name the program calls. */ - functions: Record + functions: Record /** Optional program-visible typed rejection contract for this namespace. */ - errorClass?: CodeBindingErrorClass + errorClass?: PtcBindingErrorClass } /** * Caller inputs for one program. The provider's resolve method validates supported * options and supplies directory, deadline, and authority before execution. */ -export interface CodeRunRequest { +export interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * runs as the body of an async function: top-level `await` and `return` * are available, and the completion value becomes - * {@link CodeRunResult.value}. + * {@link PtcRunResult.value}. */ program: string /** Host functions exposed to the program, one global object per namespace. */ - bindings: CodeBindingNamespace[] + bindings: PtcBindingNamespace[] /** Working directory in the mounted filesystem and subprocess execution world. */ cwd?: string /** Requested elapsed execution time; the provider's resolver validates and caps it. */ @@ -88,14 +88,14 @@ export interface CodeRunRequest { sandboxPolicy?: SandboxExecutionPolicy /** * Abort the run: the runtime stops the program (hard, even mid-loop) and - * resolves with a {@link CodeRunFailure} of kind `'abort'`. In-flight + * resolves with a {@link PtcRunFailure} of kind `'abort'`. In-flight * binding calls are the CALLER's to settle — the runtime only stops asking. */ signal?: AbortSignal } /** Fully resolved execution inputs; run never supplies a missing directory or timeout. */ -export interface CodeRunSpec extends CodeRunRequest { +export interface PtcRunSpec extends PtcRunRequest { /** Absolute directory in the provider's execution world. */ cwd: string /** Positive finite execution deadline in milliseconds, after provider capping. */ @@ -103,7 +103,7 @@ export interface CodeRunSpec extends CodeRunRequest { } /** File confinement applied to a program, independently of its terminal outcome. */ -export interface CodeRunSandbox { +export interface PtcRunSandbox { /** File-effect mode used for this execution. */ mode: SandboxMode /** Program failure text matched backend diagnostics; not enforcement proof or an exhaustive denial record. */ @@ -119,14 +119,14 @@ export interface CodeRunSandbox { * * - `'exception'` — the program threw or failed to parse/transform. * - `'timeout'` — an implementation-owned budget expired; the message says which. - * - `'abort'` — {@link CodeRunRequest.signal} fired. + * - `'abort'` — {@link PtcRunRequest.signal} fired. * - `'worker-exit'` — the execution substrate died without settling (e.g. OOM). * - `'invalid-output'` — the completion value was not lossless JSON. * - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap. * - `'protocol'` — the program sent invalid or over-budget control traffic. * - `'sandbox-unavailable'` — required confinement could not be established. */ -export interface CodeRunFailure { +export interface PtcRunFailure { /** The failure class (see the interface doc for each kind's meaning). */ kind: 'exception' | 'timeout' | 'abort' | 'worker-exit' | 'invalid-output' | 'output-limit' | 'protocol' | 'sandbox-unavailable' /** Human-readable detail, suitable for feeding back to a model to self-correct. */ @@ -138,22 +138,22 @@ export interface CodeRunFailure { * rejection of `run()` — reporting a failed program is the caller's job, not * an exception path. */ -export interface CodeRunResult { +export interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ - sandbox?: CodeRunSandbox + sandbox?: PtcRunSandbox /** * The program's completion value (its top-level `return`), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. */ - value?: CodeJsonValue + value?: PtcJsonValue /** * Captured text. Each source channel preserves emission order; interleaving * across independent channels is backend-dependent. Bounded only as part of * the outer result. */ logs: string[] - /** Present iff the run failed; see {@link CodeRunFailure} for the taxonomy. */ - error?: CodeRunFailure + /** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */ + error?: PtcRunFailure } diff --git a/packages/code-runtime/code-runtime/tests/reserved.spec.ts b/packages/ptc-runtime/ptc-runtime/tests/reserved.spec.ts similarity index 98% rename from packages/code-runtime/code-runtime/tests/reserved.spec.ts rename to packages/ptc-runtime/ptc-runtime/tests/reserved.spec.ts index c2df873fc4..77c810bff8 100644 --- a/packages/code-runtime/code-runtime/tests/reserved.spec.ts +++ b/packages/ptc-runtime/ptc-runtime/tests/reserved.spec.ts @@ -4,7 +4,7 @@ import { PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS, -} from '@deepseek-ai/dsh-code-runtime' +} from '@deepseek-ai/dsh-ptc-runtime' /** * The Service Definition owns the portable-identifier exclusion sets so every backend diff --git a/packages/code-runtime/code-runtime/tests/service.spec.ts b/packages/ptc-runtime/ptc-runtime/tests/service.spec.ts similarity index 76% rename from packages/code-runtime/code-runtime/tests/service.spec.ts rename to packages/ptc-runtime/ptc-runtime/tests/service.spec.ts index 7e1ac04f47..209a972e76 100644 --- a/packages/code-runtime/code-runtime/tests/service.spec.ts +++ b/packages/ptc-runtime/ptc-runtime/tests/service.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' -import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' /** * Minimal concrete runtime: records requests, "executes" by invoking every @@ -9,15 +9,15 @@ import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtim * Service Definition package ships no provider, so the contract is exercised through * the smallest subclass that honors it. */ -class StubRuntime extends CodeRuntime { - resolve(request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest): import('@deepseek-ai/dsh-code-runtime').CodeRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } +class StubRuntime extends PtcRuntime { + resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } readonly language = 'typescript' readonly isolation = 'in-process-stub' - requests: CodeRunRequest[] = [] - nextResult: CodeRunResult = { logs: [] } + requests: PtcRunRequest[] = [] + nextResult: PtcRunResult = { logs: [] } - async run(request: CodeRunRequest): Promise { + async run(request: PtcRunRequest): Promise { this.requests.push(request) if (request.signal?.aborted) { return { logs: [], error: { kind: 'abort', message: String(request.signal.reason) } } @@ -34,12 +34,12 @@ class StubRuntime extends CodeRuntime { async function setup() { const ctx = new Context() await ctx.plugin(StubRuntime) - const runtime = ctx.codeRuntime as StubRuntime + const runtime = ctx.ptcRuntime as StubRuntime return { ctx, runtime } } -describe('CodeRuntime service seam', () => { - it('registers as ctx.codeRuntime and serves the abstract API', async () => { +describe('PtcRuntime service seam', () => { + it('registers as ctx.ptcRuntime and serves the abstract API', async () => { const { runtime } = await setup() expect(runtime.language).toBe('typescript') expect(runtime.isolation).toBe('in-process-stub') @@ -77,10 +77,10 @@ describe('CodeRuntime service seam', () => { it('is removed from the context when the providing fiber disposes (HMR safety)', async () => { const ctx = new Context() const fiber = await ctx.plugin(StubRuntime) - expect(ctx.get('codeRuntime')).toBeInstanceOf(StubRuntime) + expect(ctx.get('ptcRuntime')).toBeInstanceOf(StubRuntime) await fiber.dispose() - expect(ctx.get('codeRuntime')).toBeUndefined() + expect(ctx.get('ptcRuntime')).toBeUndefined() }) it('rejects a second implementation in the same context (duplicate service)', async () => { diff --git a/packages/code-runtime/code-runtime/tsconfig.json b/packages/ptc-runtime/ptc-runtime/tsconfig.json similarity index 100% rename from packages/code-runtime/code-runtime/tsconfig.json rename to packages/ptc-runtime/ptc-runtime/tsconfig.json diff --git a/packages/spill/spill-policy/package.json b/packages/spill/spill-policy/package.json index 96a806808a..3aa64c3270 100644 --- a/packages/spill/spill-policy/package.json +++ b/packages/spill/spill-policy/package.json @@ -44,7 +44,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", - "@deepseek-ai/dsh-code-runtime-node": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-output-retention": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", diff --git a/packages/spill/spill-policy/tests/spill-policy.spec.ts b/packages/spill/spill-policy/tests/spill-policy.spec.ts index 1c70bc8954..add76c1882 100644 --- a/packages/spill/spill-policy/tests/spill-policy.spec.ts +++ b/packages/spill/spill-policy/tests/spill-policy.spec.ts @@ -21,7 +21,7 @@ import type { PostToolDecision, ToolExecution, ToolExecutionToken } from '@deeps import { SpillLocator, SpillStore } from '@deepseek-ai/dsh-spill' import type { SaveTextSpill, SpillRef } from '@deepseek-ai/dsh-spill' import * as SpillPolicy from '@deepseek-ai/dsh-spill-policy' -import NodeRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-code-runtime-node' +import NodeRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-ptc-runtime-node' import FileSystem from '@deepseek-ai/dsh-fs-local' import Subprocess from '@deepseek-ai/dsh-subprocess-local' import Sandbox from '@deepseek-ai/dsh-sandbox-local' diff --git a/packages/ssh/ssh/README.i18n.yaml b/packages/ssh/ssh/README.i18n.yaml index 8129a1ac8e..2c6e2311f7 100644 --- a/packages/ssh/ssh/README.i18n.yaml +++ b/packages/ssh/ssh/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/ssh/ssh/README.md -README.md: 20e73a03aac8b22d6d2be2013ccf914de4340692 -README.zh.md: 4a03b591effa801ecab362e368d735d085a9a5cd +README.md: 727ab6eefae6bf8361f41b2f1a4a7f85e7225226 +README.zh.md: 5548886d1c95e551330ecae9aaf24b4015cb3197 diff --git a/packages/ssh/ssh/README.md b/packages/ssh/ssh/README.md index 20e73a03aa..727ab6eefa 100644 --- a/packages/ssh/ssh/README.md +++ b/packages/ssh/ssh/README.md @@ -44,7 +44,7 @@ Install the built helper and its matching runtime dependencies on the remote hos | `maxPending` | `128` | Ordinary outstanding requests; heartbeat and bounded cleanup requests have reserved capacity | | `leaseMs` | `30000` | Helper heartbeat lease, from 3000 to 600000 ms | -For PTC, configure both bootstrap fields and pass the verified `ctx.ssh.nodeExecutable` and `ctx.ssh.bootstrapPath` to [`NodeCodeRuntime`](../../code-runtime/code-runtime-node/README.md). Basic filesystem and Bash use may omit the pair. The `bootstrapPath` getter refuses an unconfigured PTC deployment. +For PTC, configure both bootstrap fields and pass the verified `ctx.ssh.nodeExecutable` and `ctx.ssh.bootstrapPath` to [`NodePtcRuntime`](../../ptc-runtime/ptc-runtime-node/README.md). Basic filesystem and Bash use may omit the pair. The `bootstrapPath` getter refuses an unconfigured PTC deployment. ----- diff --git a/packages/ssh/ssh/README.zh.md b/packages/ssh/ssh/README.zh.md index 4a03b591ef..5548886d1c 100644 --- a/packages/ssh/ssh/README.zh.md +++ b/packages/ssh/ssh/README.zh.md @@ -44,7 +44,7 @@ kind: "package-reference" | `maxPending` | `128` | 普通未完成请求的数量上限;心跳与有界清理请求使用预留容量 | | `leaseMs` | `30000` | 辅助进程心跳租期,范围为 3000 至 600000 毫秒 | -使用 PTC 时,配置两个引导字段,并将验证后的 `ctx.ssh.nodeExecutable` 与 `ctx.ssh.bootstrapPath` 传给 [`NodeCodeRuntime`](../../code-runtime/code-runtime-node/README.zh.md)。仅使用文件系统和 Bash 时可以省略这对字段。未配置 PTC 部署时,`bootstrapPath` getter 会拒绝访问。 +使用 PTC 时,配置两个引导字段,并将验证后的 `ctx.ssh.nodeExecutable` 与 `ctx.ssh.bootstrapPath` 传给 [`NodePtcRuntime`](../../ptc-runtime/ptc-runtime-node/README.zh.md)。仅使用文件系统和 Bash 时可以省略这对字段。未配置 PTC 部署时,`bootstrapPath` getter 会拒绝访问。 ----- diff --git a/packages/ssh/ssh/package.json b/packages/ssh/ssh/package.json index a939bba1e0..725a6da222 100644 --- a/packages/ssh/ssh/package.json +++ b/packages/ssh/ssh/package.json @@ -72,7 +72,7 @@ "@deepseek-ai/dsh-sandbox-local": "workspace:^", "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-session-projection": "workspace:^", - "@deepseek-ai/dsh-code-runtime-node": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:^", "@deepseek-ai/dsh-fs-ssh": "workspace:^", "@deepseek-ai/dsh-subprocess-ssh": "workspace:^", "@deepseek-ai/dsh-sandbox-ssh": "workspace:^", diff --git a/packages/ssh/ssh/src/index.ts b/packages/ssh/ssh/src/index.ts index 80b46b650d..40dd59253a 100644 --- a/packages/ssh/ssh/src/index.ts +++ b/packages/ssh/ssh/src/index.ts @@ -91,7 +91,7 @@ export class SshConnection extends Service { /** Hold plugin readiness until the remote identity and helper digest are verified. */ async [Service.init](): Promise { await this.ready } - /** Verified remote Node executable for the paired code runtime. */ + /** Verified remote Node executable for the paired PTC runtime. */ get nodeExecutable(): string { if (this.remote === undefined) throw new Error('SSH helper is not ready') return this.remote.node diff --git a/packages/ssh/ssh/tests/live.e2e.ts b/packages/ssh/ssh/tests/live.e2e.ts index 9ee31c1c87..045ea794d6 100644 --- a/packages/ssh/ssh/tests/live.e2e.ts +++ b/packages/ssh/ssh/tests/live.e2e.ts @@ -7,7 +7,7 @@ import { setTimeout as delay } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it } from 'vitest' import { z } from 'zod' -import { NodeCodeRuntime } from '@deepseek-ai/dsh-code-runtime-node' +import { NodePtcRuntime } from '@deepseek-ai/dsh-ptc-runtime-node' import Lsp from '@deepseek-ai/dsh-lsp' import * as LspStdio from '@deepseek-ai/dsh-lsp-stdio' import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection' @@ -247,12 +247,12 @@ describe.skipIf(!enabled)('POSIX SSH runtime acceptance', () => { it.skipIf(bootstrap === undefined)('runs PTC remotely with empty environment, bindings, denial and a bounded hot loop', async () => { const test = await setup() - const fiber = test.ctx.plugin(NodeCodeRuntime, { + const fiber = test.ctx.plugin(NodePtcRuntime, { nodeExecutable: test.ctx.ssh.nodeExecutable, bootstrapPath: test.ctx.ssh.bootstrapPath, }) try { await fiber - const runtime = test.ctx.codeRuntime + const runtime = test.ctx.ptcRuntime const bindings = [{ global: 'tools', functions: { echo: async (input: unknown) => String(input) } }] const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: test.root } const result = await runtime.run(runtime.resolve({ diff --git a/packages/ssh/subprocess-ssh/README.i18n.yaml b/packages/ssh/subprocess-ssh/README.i18n.yaml index 6c3340c35f..c8ea85e02b 100644 --- a/packages/ssh/subprocess-ssh/README.i18n.yaml +++ b/packages/ssh/subprocess-ssh/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/ssh/subprocess-ssh/README.md -README.md: 018919acd3aa6c898cfd7bcfa11cf3af6cf3b8f8 -README.zh.md: af26dbdd11ee62cb3469d5cfe4133f868eea04ad +README.md: ea647cd15b97ae281e145c5ac3afbf1e4cc4740c +README.zh.md: 85692d2f1ef1fc16477541fa789d542f6e41e6fc diff --git a/packages/ssh/subprocess-ssh/README.md b/packages/ssh/subprocess-ssh/README.md index 018919acd3..ea647cd15b 100644 --- a/packages/ssh/subprocess-ssh/README.md +++ b/packages/ssh/subprocess-ssh/README.md @@ -58,7 +58,7 @@ Remote execution delegates to [`subprocess-local`](../../subprocess/subprocess-l ## Model Experience -Indirectly, through Bash, terminal, LSP and code-runtime consumers, which present their existing results and remote paths. +Indirectly, through Bash, terminal, LSP and ptc-runtime consumers, which present their existing results and remote paths. #### KV Cache effect diff --git a/packages/ssh/subprocess-ssh/README.zh.md b/packages/ssh/subprocess-ssh/README.zh.md index af26dbdd11..85692d2f1e 100644 --- a/packages/ssh/subprocess-ssh/README.zh.md +++ b/packages/ssh/subprocess-ssh/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ## 模型体验 -间接通过 Bash、终端、LSP 和代码运行时消费方产生影响,由它们展示既有结果与远端路径。 +间接通过 Bash、终端、LSP 和PTC 运行时消费方产生影响,由它们展示既有结果与远端路径。 #### KV Cache 影响 diff --git a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts index 0521638fa9..1ec0b16852 100644 --- a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts @@ -33,13 +33,13 @@ async function mountInvariants(ctx: Context): Promise { await ctx.plugin(AgentLoopInvariant) } -interface CodeRunRequestLike { +interface PtcRunRequestLike { bindings: { global: string; functions: Record Promise> }[] } interface SetupOptions { toolMode?: ToolConfig['mode'] - codeRun?: (request: CodeRunRequestLike) => Promise<{ logs: never[]; value?: unknown }> + codeRun?: (request: PtcRunRequestLike) => Promise<{ logs: never[]; value?: unknown }> } const SCHEMA: ObjectJsonSchema = { @@ -60,10 +60,10 @@ async function setup(script: Script, options: SetupOptions = {}) { tools: { mode: options.toolMode ?? 'native' }, }) if (options.toolMode === 'ptc' || options.toolMode === 'both') { - ctx.provide('codeRuntime', { + ctx.provide('ptcRuntime', { language: 'typescript', isolation: 'test', - resolve: (request: import('@deepseek-ai/dsh-code-runtime').CodeRunRequest) => ({ ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: 120_000 }), + resolve: (request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest) => ({ ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: 120_000 }), run: options.codeRun ?? (() => Promise.resolve({ logs: [] })), } as never) } diff --git a/packages/util/http-proxy/README.i18n.yaml b/packages/util/http-proxy/README.i18n.yaml index 325fc4e048..bf46fb0186 100644 --- a/packages/util/http-proxy/README.i18n.yaml +++ b/packages/util/http-proxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/util/http-proxy/README.md -README.md: 75a5326407b00031aa7c9f079c8c0c875c61ab5d -README.zh.md: c390174d7e61d3ff45a9e7820fb60e7be6858faa +README.md: 9b098432f3aaa3f351e48060a9336d0fa4cb2e9e +README.zh.md: 70b81429bcb45074a2a0c5f5a9a36f09c290270b diff --git a/packages/util/http-proxy/README.md b/packages/util/http-proxy/README.md index 75a5326407..9b098432f3 100644 --- a/packages/util/http-proxy/README.md +++ b/packages/util/http-proxy/README.md @@ -108,7 +108,7 @@ These limits define when the package is a poor fit. They are current package con - **No custom certificate authority** — a TLS-intercepting corporate proxy needs `NODE_EXTRA_CA_CERTS` set on the process before launch, which this package neither sets nor validates. - **A spawned child honors the policy only on a new enough runtime, and only when every value it inherits is one Node accepts** — it reads the published environment through Node's `NODE_USE_ENV_PROXY` (22.21+, 24+), and the engines range admits 22.19 and 22.20, where such a child stays direct. A user whose environment also names a SOCKS or otherwise refused proxy leaves every child Node direct: the flag is withheld so the child can start at all. A child also matches bypass entries with Node's own `NO_PROXY` rules, which differ from this package's in their separators and IPv4-range support. Nothing in this process depends on a Node version: every in-process request reaches the global dispatcher. - **Telemetry is direct by design** — the OTLP exporter posts through `node:http`, which no global dispatcher reaches. Routing it would need either an `http.Agent` whose `proxyEnv` option post-dates the lowest supported Node, or the SDK's `fetch` transport, which has no compression while the shipped profile enables gzip. Telemetry is the one channel whose loss costs the user nothing, so it stays where it was; `DSH_TELEMETRY_MODE=DISABLED` turns it off. -- **Model-authored programs receive no proxy settings** — the Node code-runtime process and workflow worker do not inherit a proxy URL that may contain `user:password`. Their direct requests need their own configuration and remain subject to the execution sandbox. +- **Model-authored programs receive no proxy settings** — the Node ptc-runtime process and workflow worker do not inherit a proxy URL that may contain `user:password`. Their direct requests need their own configuration and remain subject to the execution sandbox. - **The regression gate sees source, not dependencies** — `verify-no-bare-dispatcher` parses `packages/*/*/src` and `apps/*/src`; tests, scripts, and the internals of a third-party SDK are outside it. That is why every outbound call site also carries an `egress.spec.ts`. diff --git a/packages/util/http-proxy/README.zh.md b/packages/util/http-proxy/README.zh.md index c390174d7e..70b81429bc 100644 --- a/packages/util/http-proxy/README.zh.md +++ b/packages/util/http-proxy/README.zh.md @@ -108,7 +108,7 @@ loopback 始终被绕过——`localhost`、整个 `127.0.0.0/8` 段、`::1`、` - **不支持自定义证书颁发机构**——做 TLS 拦截的企业代理需要在启动前为进程设置 `NODE_EXTRA_CA_CERTS`,本包既不设置也不校验它。 - **spawn 出的子进程只在足够新的运行时上遵循策略,且仅当它继承的每个值都是 Node 接受的**——它通过 Node 的 `NODE_USE_ENV_PROXY` 读取已发布的环境(22.21+、24+),而 engines 范围允许 22.19 与 22.20,在这两个版本上这样的子进程保持直连。若用户环境里还有 SOCKS 或其他被拒的代理,所有子 Node 都保持直连:不设置该标志,子进程才起得来。子进程还会按 Node 自己的 `NO_PROXY` 规则匹配绕过条目,其分隔符与 IPv4 区间处理与本包不同。本进程内不依赖任何 Node 版本:每一次进程内请求都会落到全局 dispatcher。 - **遥测按设计直连**——OTLP 导出器通过 `node:http` 投递,全局 dispatcher 触及不到。要让它走代理,要么依赖 `http.Agent` 的 `proxyEnv`,而该选项晚于本项目支持的最低 Node 版本;要么改用 SDK 的 `fetch` 传输,但它没有压缩能力,而随附配置启用了 gzip。遥测是唯一一条丢失后不会让用户付出任何代价的通道,因此维持原状;`DSH_TELEMETRY_MODE=DISABLED` 可关闭它。 -- **模型编写的程序不接收代理配置**——Node code-runtime 进程与 workflow worker 不继承可能含有 `user:password` 的代理 URL。其直接请求需要自行配置,并继续受到执行沙箱的约束。 +- **模型编写的程序不接收代理配置**——Node ptc-runtime 进程与 workflow worker 不继承可能含有 `user:password` 的代理 URL。其直接请求需要自行配置,并继续受到执行沙箱的约束。 - **防回归门禁只看源码,看不到依赖内部**——`verify-no-bare-dispatcher` 解析 `packages/*/*/src` 与 `apps/*/src`;测试、脚本以及第三方 SDK 的内部都在其之外。这正是每个出网点还各配一份 `egress.spec.ts` 的原因。 diff --git a/packages/util/http-proxy/src/install.ts b/packages/util/http-proxy/src/install.ts index 1bd05bbcd3..b3aacad2da 100644 --- a/packages/util/http-proxy/src/install.ts +++ b/packages/util/http-proxy/src/install.ts @@ -165,7 +165,7 @@ async function createPolicyDispatcher(policy: ProxyPolicy): Promise * * A worker thread has its own `globalThis` and so its own dispatcher; installing here does not * reach it. No worker installs one today: both this repository ships — the workflow engine and the - * code runtime — evaluate model-authored scripts, which must not receive a proxy URL that may carry + * PTC runtime — evaluate model-authored scripts, which must not receive a proxy URL that may carry * credentials. A worker that needs the policy has to be handed one explicitly and install it itself. * * @param policy - the resolved policy to install. diff --git a/packages/workflow/workflow-worker-thread/src/host.ts b/packages/workflow/workflow-worker-thread/src/host.ts index 2cd5ac4a7c..0940e82775 100644 --- a/packages/workflow/workflow-worker-thread/src/host.ts +++ b/packages/workflow/workflow-worker-thread/src/host.ts @@ -33,7 +33,7 @@ interface ChildRecord { * proxy policy. A worker thread does not inherit the host's global dispatcher, so a workflow's own * requests go direct — the alternative is handing the worker a proxy URL that may carry * `user:password`, and this worker executes the model-authored script body. That is the same - * containment the code runtime keeps, and `docs/defensive-patterns.md` requires it. + * containment the PTC runtime keeps, and `docs/defensive-patterns.md` requires it. * Windows derives `os.tmpdir()` from `TMP`/`TEMP` and falls back to the * literal relative path `undefined\temp` when the environment is empty, so * tsx's transform cache would land in a cwd-relative `undefined/temp` diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8e9b79930b..f639e9da36 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -381,9 +381,9 @@ importers: '@deepseek-ai/dsh-experimental-agent-team-profile': specifier: workspace:^ version: link:../../packages/experimental/agent-team-profile - '@deepseek-ai/dsh-experimental-code-runtime-python': + '@deepseek-ai/dsh-experimental-ptc-runtime-python': specifier: workspace:^ - version: link:../../packages/experimental/code-runtime-python + version: link:../../packages/experimental/ptc-runtime-python '@deepseek-ai/dsh-experimental-tool-agent-team': specifier: workspace:^ version: link:../../packages/experimental/tool-agent-team @@ -1604,9 +1604,9 @@ importers: '@deepseek-ai/dsh-cmdline': specifier: workspace:^ version: link:../../boot/cmdline - '@deepseek-ai/dsh-code-runtime-node': + '@deepseek-ai/dsh-ptc-runtime-node': specifier: workspace:^ - version: link:../../code-runtime/code-runtime-node + version: link:../../ptc-runtime/ptc-runtime-node '@deepseek-ai/dsh-util-values': specifier: workspace:^ version: link:../../util/values @@ -1925,9 +1925,9 @@ importers: '@deepseek-ai/dsh-cmdline': specifier: workspace:^ version: link:../../boot/cmdline - '@deepseek-ai/dsh-code-runtime-node': + '@deepseek-ai/dsh-ptc-runtime-node': specifier: workspace:^ - version: link:../../code-runtime/code-runtime-node + version: link:../../ptc-runtime/ptc-runtime-node '@deepseek-ai/dsh-cordis-client-runner': specifier: workspace:^ version: link:../../extensions/cordis-client-runner @@ -4245,9 +4245,9 @@ importers: '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:^ version: link:../ui-slots - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../code-runtime/code-runtime + version: link:../../ptc-runtime/ptc-runtime '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm @@ -4582,7 +4582,7 @@ importers: specifier: ^6.0.3 version: 6.0.3 - packages/code-runtime/code-runtime: + packages/ptc-runtime/ptc-runtime: devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ @@ -4591,7 +4591,7 @@ importers: specifier: workspace:^ version: link:../../sandbox/sandbox - packages/code-runtime/code-runtime-node: + packages/ptc-runtime/ptc-runtime-node: dependencies: '@deepseek-ai/dsh-util-values': specifier: workspace:^ @@ -4603,9 +4603,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:^ version: link:../../../vendor/cordis - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../code-runtime + version: link:../ptc-runtime '@deepseek-ai/dsh-fs': specifier: workspace:^ version: link:../../fs/fs @@ -5156,9 +5156,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../agent - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../code-runtime/code-runtime + version: link:../../ptc-runtime/ptc-runtime '@deepseek-ai/dsh-scope': specifier: workspace:^ version: link:../scope @@ -5246,9 +5246,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../agent - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../code-runtime/code-runtime + version: link:../../ptc-runtime/ptc-runtime '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -5481,7 +5481,7 @@ importers: specifier: ^18.2.0 version: 18.3.1(react@18.3.1) - packages/experimental/code-runtime-python: + packages/experimental/ptc-runtime-python: dependencies: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery @@ -5490,9 +5490,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:^ version: link:../../../vendor/cordis - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../code-runtime/code-runtime + version: link:../../ptc-runtime/ptc-runtime '@deepseek-ai/dsh-timeout': specifier: workspace:^ version: link:../../util/timeout @@ -6030,9 +6030,9 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:^ version: link:../../attachment/attachment - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../code-runtime/code-runtime + version: link:../../ptc-runtime/ptc-runtime '@deepseek-ai/dsh-fs': specifier: workspace:^ version: link:../fs @@ -7419,9 +7419,9 @@ importers: '@deepseek-ai/dsh-agent-loop': specifier: workspace:^ version: link:../../core/agent-loop - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../code-runtime/code-runtime + version: link:../../ptc-runtime/ptc-runtime '@deepseek-ai/dsh-commands': specifier: workspace:^ version: link:../../interaction/commands @@ -9086,9 +9086,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent - '@deepseek-ai/dsh-code-runtime-node': + '@deepseek-ai/dsh-ptc-runtime-node': specifier: workspace:^ - version: link:../../code-runtime/code-runtime-node + version: link:../../ptc-runtime/ptc-runtime-node '@deepseek-ai/dsh-fs-local': specifier: workspace:^ version: link:../../fs/fs-local @@ -9179,9 +9179,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:^ version: link:../../util/brand - '@deepseek-ai/dsh-code-runtime-node': + '@deepseek-ai/dsh-ptc-runtime-node': specifier: workspace:^ - version: link:../../code-runtime/code-runtime-node + version: link:../../ptc-runtime/ptc-runtime-node '@deepseek-ai/dsh-fs': specifier: workspace:^ version: link:../../fs/fs @@ -11104,12 +11104,12 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:^ version: link:../../packages/util/brand - '@deepseek-ai/dsh-code-runtime': + '@deepseek-ai/dsh-ptc-runtime': specifier: workspace:^ - version: link:../../packages/code-runtime/code-runtime - '@deepseek-ai/dsh-code-runtime-node': + version: link:../../packages/ptc-runtime/ptc-runtime + '@deepseek-ai/dsh-ptc-runtime-node': specifier: workspace:^ - version: link:../../packages/code-runtime/code-runtime-node + version: link:../../packages/ptc-runtime/ptc-runtime-node '@deepseek-ai/dsh-command-compact': specifier: workspace:^ version: link:../../packages/compaction/command-compact diff --git a/python/sdk-runtime/package.json b/python/sdk-runtime/package.json index 7350c7c415..319548aa9f 100644 --- a/python/sdk-runtime/package.json +++ b/python/sdk-runtime/package.json @@ -24,8 +24,8 @@ "@deepseek-ai/dsh-authorization": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-brand": "workspace:^", - "@deepseek-ai/dsh-code-runtime": "workspace:^", - "@deepseek-ai/dsh-code-runtime-node": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime": "workspace:^", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:^", "@deepseek-ai/dsh-command-compact": "workspace:^", "@deepseek-ai/dsh-command-goal": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", diff --git a/python/sdk-runtime/runtime-bootstrap.mjs b/python/sdk-runtime/runtime-bootstrap.mjs index 144b943d58..6ca1c1da82 100644 --- a/python/sdk-runtime/runtime-bootstrap.mjs +++ b/python/sdk-runtime/runtime-bootstrap.mjs @@ -11,9 +11,9 @@ const aclRunner = process.platform === 'win32' if (aclRunner !== undefined && process.argv[2] === aclRunner) { process.argv.splice(1, 1) await import('@deepseek-ai/dsh-sandbox-windows-acl/runner') -} else if (process.env.DSH_CODE_RUNTIME_NODE === '1') { - Reflect.deleteProperty(process.env, 'DSH_CODE_RUNTIME_NODE') - await import('@deepseek-ai/dsh-code-runtime-node/process') +} else if (process.env.DSH_PTC_RUNTIME_NODE === '1') { + Reflect.deleteProperty(process.env, 'DSH_PTC_RUNTIME_NODE') + await import('@deepseek-ai/dsh-ptc-runtime-node/process') } else if (selection === undefined) { const { runCli } = await import('@deepseek-ai/dsh/lib/bin.js') await runCli() diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 878fa038d5..90957ccc35 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -160,9 +160,9 @@ const packageFileExtras: Readonly> = { '@deepseek-ai/dsh-client-web': ['lib/**/*.css'], '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'], // The CPython side ships as source .py files, published as-is rather than built. - '@deepseek-ai/dsh-experimental-code-runtime-python': ['py/**/*.py'], + '@deepseek-ai/dsh-experimental-ptc-runtime-python': ['py/**/*.py'], // The isolated Node bootstrap is a separately launched bundle. - '@deepseek-ai/dsh-code-runtime-node': ['lib/process.js'], + '@deepseek-ai/dsh-ptc-runtime-node': ['lib/process.js'], // The shipped preset compositions travel inside the roster package. '@deepseek-ai/dsh-agent-presets': ['presets'], // The Web Host mounts the default-off settings owner independently of each diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index f9539aeeea..72f4352985 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -63,7 +63,7 @@ export const SERVICE_PAGE: Record = { shell: 'shell.md', shellEnv: 'shell.md', clientModules: 'client-modules.md', - codeRuntime: 'code-runtime.md', + ptcRuntime: 'ptc-runtime.md', commands: 'commands.md', compaction: 'compaction.md', cordisInspect: 'extensions.md', @@ -396,10 +396,10 @@ export const LINK_MAP: Readonly> = { SubprocessSpawnSpec: 'subprocess.md', SubprocessTerminalHandle: 'subprocess.md', SubprocessTerminalSpawnSpec: 'subprocess.md', - CodeRunRequest: 'code-runtime.md', - CodeRunSpec: 'code-runtime.md', - CodeRunSandbox: 'code-runtime.md', - CodeRunResult: 'code-runtime.md', + PtcRunRequest: 'ptc-runtime.md', + PtcRunSpec: 'ptc-runtime.md', + PtcRunSandbox: 'ptc-runtime.md', + PtcRunResult: 'ptc-runtime.md', CompactionResult: 'compaction.md', CompactionTrigger: 'compaction.md', PruneResult: 'compaction.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index d336422a7f..6e9270d74c 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -541,11 +541,11 @@ const SERVICE_ROLES: ServiceRole[] = [ note: 'User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events.', }, { - key: 'codeRuntime', - pkg: 'code-runtime', - title: 'Code-execution seam', + key: 'ptcRuntime', + pkg: 'ptc-runtime', + title: 'PTC execution seam', mode: 'seam', - implementations: ['code-runtime-node', 'experimental-code-runtime-python'], + implementations: ['ptc-runtime-node', 'experimental-ptc-runtime-python'], consumers: ['tools'], note: 'Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for PTC mode).', }, diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index d8be7d7445..5988f69575 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -205,10 +205,10 @@ const TOOL_PACKAGES: ToolPackage[] = [ pkg: '@deepseek-ai/dsh-tools', dir: 'tools', source: 'packages/core/tools/src/ptc.ts', - requires: ['ctx.tools', 'ctx.codeRuntime (execution time)', 'ctx.systemPrompt'], + requires: ['ctx.tools', 'ctx.ptcRuntime (execution time)', 'ctx.systemPrompt'], writes: ['tool/call', 'one tool/ptc-dispatch-start + tool/ptc-dispatch pair per bridged sub-call', 'tool/result'], // The registry's OWN tool: run_code exists only under a non-native mode - // (the registry registers it in its constructor; the code runtime is read + // (the registry registers it in its constructor; the PTC runtime is read // at assembly/execution time, so the schema harvest needs none mounted). toolsConfig: { mode: 'ptc' }, async mount() {}, diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index ada159a6a8..d2acf1b644 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -798,7 +798,7 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate { // imports reach their lib/ entrypoints under plain Node. The e2e lane runs // unbuilt, so these files self-skip there. 'packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts', - 'packages/code-runtime/code-runtime-node/tests/built-lib.e2e.ts', + 'packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts', 'packages/session/session-persistence-jsonl/tests/built-migration-worker.e2e.ts', 'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts', ], { diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 915a8f5718..22b79bc9bd 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -264,7 +264,7 @@ def write_advanced_profile_patch(root: Path, name: str, sessions: Path) -> Path: }, }, {"insert": [ - {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-node"}, + {"id": "ptc-runtime", "name": "@deepseek-ai/dsh-ptc-runtime-node"}, {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"}, {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"}, ]}, diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 13302f23b0..81e63c01ae 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1147,39 +1147,39 @@ "source": "packages/sandbox/sandbox/src/index.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeJsonValue", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcJsonValue", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeRunRequest", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcRunRequest", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeRunResult", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcRunResult", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeBindingNamespace", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcBindingNamespace", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeBindingErrorClass", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcBindingErrorClass", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeBindingFunction", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcBindingFunction", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeRunFailure", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcRunFailure", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { "doc": "docs/subsystems/filesystem.md", @@ -2112,14 +2112,14 @@ "source": "packages/client/ui-conversation/src/client/contract/slots.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeRunSpec", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcRunSpec", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { - "doc": "docs/subsystems/code-runtime.md", - "symbol": "CodeRunSandbox", - "source": "packages/code-runtime/code-runtime/src/types.ts" + "doc": "docs/subsystems/ptc-runtime.md", + "symbol": "PtcRunSandbox", + "source": "packages/ptc-runtime/ptc-runtime/src/types.ts" }, { "doc": "docs/subsystems/ssh.md", diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index e471bb4f8a..4f276fe98c 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -46,7 +46,7 @@ const NO_MODEL_EXPERIENCE_SECTION: Readonly> = { const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/ssh/ssh': { kind: 'none', reason: 'The connection owner transports private provider operations; consumers own all model-facing content.' }, 'packages/ssh/fs-ssh': { kind: 'indirect', reason: 'The remote filesystem delegates model rendering to the existing filesystem consumers.' }, - 'packages/ssh/subprocess-ssh': { kind: 'indirect', reason: 'The remote process provider delegates model rendering to Bash, terminal, LSP and code-runtime consumers.' }, + 'packages/ssh/subprocess-ssh': { kind: 'indirect', reason: 'The remote process provider delegates model rendering to Bash, terminal, LSP and ptc-runtime consumers.' }, 'packages/ssh/sandbox-ssh': { kind: 'indirect', reason: 'The remote confinement provider returns enforcement facts to its existing tool consumers.' }, 'packages/attachment/attachment': { kind: 'indirect', reason: 'The storage seam delegates model request rendering to provider adapters.' }, 'packages/attachment/attachment-local': { kind: 'indirect', reason: 'The local backend delegates model request rendering to provider adapters.' }, @@ -54,10 +54,10 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/shell/shell-env': { kind: 'indirect', reason: 'The env service exposes managed DSH_* facts through the shell tools (dsh-tool-bash/dsh-tool-pwsh); it registers no prompt or schema of its own.' }, 'packages/shell/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' }, 'packages/shell/pwsh-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-pwsh.' }, - 'packages/code-runtime/code-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to PTC mode in dsh-tools.' }, + 'packages/ptc-runtime/ptc-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to PTC mode in dsh-tools.' }, 'packages/core/agent-tool-presentation': { kind: 'indirect', reason: 'The row only selects between the two projections dsh-tools owns; it registers no prompt, schema, or result of its own.' }, - 'packages/code-runtime/code-runtime-node': { kind: 'indirect', reason: 'The Node process backend delegates model rendering to PTC mode in dsh-tools.' }, - 'packages/experimental/code-runtime-python': { kind: 'indirect', reason: 'Explicit source-checkout compositions delegate model rendering to PTC mode in dsh-tools.' }, + 'packages/ptc-runtime/ptc-runtime-node': { kind: 'indirect', reason: 'The Node process backend delegates model rendering to PTC mode in dsh-tools.' }, + 'packages/experimental/ptc-runtime-python': { kind: 'indirect', reason: 'Explicit source-checkout compositions delegate model rendering to PTC mode in dsh-tools.' }, 'packages/client/ui-agent-preset': { kind: 'indirect', reason: 'Browser-side settings row; the preset it selects owns every model-facing effect.' }, 'packages/util/crypto': { kind: 'indirect', reason: 'Pure identifier minting; the ids consumers mint with it never enter prompts as semantic content.' }, 'packages/util/deque': { kind: 'none', reason: 'In-process collection primitive; registers nothing model-facing.' }, diff --git a/snapshots/sdk/ptc-turn/runtime.cordis.yml b/snapshots/sdk/ptc-turn/runtime.cordis.yml index de6967053d..2d106681ff 100644 --- a/snapshots/sdk/ptc-turn/runtime.cordis.yml +++ b/snapshots/sdk/ptc-turn/runtime.cordis.yml @@ -1,3 +1,3 @@ - insert: - - id: code-runtime - name: '@deepseek-ai/dsh-code-runtime-node' + - id: ptc-runtime + name: '@deepseek-ai/dsh-ptc-runtime-node' diff --git a/snapshots/session/both-mode-turn/cordis.yml b/snapshots/session/both-mode-turn/cordis.yml index 1b2789d83f..9c1b13d55f 100644 --- a/snapshots/session/both-mode-turn/cordis.yml +++ b/snapshots/session/both-mode-turn/cordis.yml @@ -1,4 +1,4 @@ -# Both mode adds `ctx.codeRuntime` while keeping native tools on the wire and +# Both mode adds `ctx.ptcRuntime` while keeping native tools on the wire and # adding `run_code` plus its generated TypeScript SDK prompt. Recording applies # this profile patch; replay applies its sibling patch. - id: agent-default-model diff --git a/snapshots/session/ptc-node-read-only/cordis.yml b/snapshots/session/ptc-node-read-only/cordis.yml index a9f85a8e1c..4ffc7dc0c5 100644 --- a/snapshots/session/ptc-node-read-only/cordis.yml +++ b/snapshots/session/ptc-node-read-only/cordis.yml @@ -1,4 +1,4 @@ -# PTC mode adds `ctx.codeRuntime` and changes the registry to one wire tool, +# PTC mode adds `ctx.ptcRuntime` and changes the registry to one wire tool, # `run_code`, plus its generated TypeScript SDK prompt. The demo and snapshot # recorder apply this profile patch; replay applies its sibling patch. - insert: diff --git a/snapshots/session/ptc-node-workspace/cordis.yml b/snapshots/session/ptc-node-workspace/cordis.yml index a9f85a8e1c..4ffc7dc0c5 100644 --- a/snapshots/session/ptc-node-workspace/cordis.yml +++ b/snapshots/session/ptc-node-workspace/cordis.yml @@ -1,4 +1,4 @@ -# PTC mode adds `ctx.codeRuntime` and changes the registry to one wire tool, +# PTC mode adds `ctx.ptcRuntime` and changes the registry to one wire tool, # `run_code`, plus its generated TypeScript SDK prompt. The demo and snapshot # recorder apply this profile patch; replay applies its sibling patch. - insert: diff --git a/snapshots/session/ptc-python-turn/cordis.snapshot.yml b/snapshots/session/ptc-python-turn/cordis.snapshot.yml index 18164cf772..656355627c 100644 --- a/snapshots/session/ptc-python-turn/cordis.snapshot.yml +++ b/snapshots/session/ptc-python-turn/cordis.snapshot.yml @@ -28,12 +28,12 @@ config: mode: ptc -- id: code-runtime +- id: ptc-runtime disabled: true - insert: - - id: code-runtime-python - name: '@deepseek-ai/dsh-experimental-code-runtime-python' + - id: ptc-runtime-python + name: '@deepseek-ai/dsh-experimental-ptc-runtime-python' - id: system-prompt name: '@deepseek-ai/dsh-system-prompt' diff --git a/snapshots/session/ptc-python-turn/cordis.yml b/snapshots/session/ptc-python-turn/cordis.yml index 17fa637a42..b93803cc0c 100644 --- a/snapshots/session/ptc-python-turn/cordis.yml +++ b/snapshots/session/ptc-python-turn/cordis.yml @@ -22,12 +22,12 @@ config: mode: ptc -- id: code-runtime +- id: ptc-runtime disabled: true - insert: - - id: code-runtime-python - name: '@deepseek-ai/dsh-experimental-code-runtime-python' + - id: ptc-runtime-python + name: '@deepseek-ai/dsh-experimental-ptc-runtime-python' - id: system-prompt name: '@deepseek-ai/dsh-system-prompt' diff --git a/snapshots/session/ptc-turn/cordis.yml b/snapshots/session/ptc-turn/cordis.yml index a9f85a8e1c..4ffc7dc0c5 100644 --- a/snapshots/session/ptc-turn/cordis.yml +++ b/snapshots/session/ptc-turn/cordis.yml @@ -1,4 +1,4 @@ -# PTC mode adds `ctx.codeRuntime` and changes the registry to one wire tool, +# PTC mode adds `ctx.ptcRuntime` and changes the registry to one wire tool, # `run_code`, plus its generated TypeScript SDK prompt. The demo and snapshot # recorder apply this profile patch; replay applies its sibling patch. - insert: diff --git a/tsconfig.base.json b/tsconfig.base.json index d90e160239..c00dbc3102 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -247,7 +247,7 @@ "@deepseek-ai/dsh-experimental-webworker-packer": ["./packages/experimental/webworker-packer/src"], "@deepseek-ai/dsh-experimental-inspector": ["./packages/experimental/inspector/src"], "@deepseek-ai/dsh-experimental-inspector/client": ["./packages/experimental/inspector/src/client/index.ts"], - "@deepseek-ai/dsh-experimental-code-runtime-python": ["./packages/experimental/code-runtime-python/src"], + "@deepseek-ai/dsh-experimental-ptc-runtime-python": ["./packages/experimental/ptc-runtime-python/src"], "@deepseek-ai/dsh-util-crypto": ["./packages/util/crypto/src"], "@deepseek-ai/dsh-util-values": ["./packages/util/values/src"], // util/ folders are role-named without the util- prefix their npm names carry, @@ -280,8 +280,6 @@ "@deepseek-ai/dsh-brand": ["./packages/util/brand/src"], "@deepseek-ai/dsh-chunked-list": ["./packages/util/chunked-list/src"], "@deepseek-ai/dsh-cmdline": ["./packages/boot/cmdline/src"], - "@deepseek-ai/dsh-code-runtime": ["./packages/code-runtime/code-runtime/src"], - "@deepseek-ai/dsh-code-runtime-node": ["./packages/code-runtime/code-runtime-node/src"], "@deepseek-ai/dsh-command-compact": ["./packages/compaction/command-compact/src"], "@deepseek-ai/dsh-command-feedback": ["./packages/feedback/command-feedback/src"], "@deepseek-ai/dsh-command-goal": ["./packages/goal/command-goal/src"], @@ -341,6 +339,8 @@ "@deepseek-ai/dsh-plan-mode": ["./packages/plan/plan-mode/src"], "@deepseek-ai/dsh-plan-mode/invariant": ["./packages/plan/plan-mode/src/invariant.ts"], "@deepseek-ai/dsh-plugin-package-inventory-deepseek": ["./packages/llm/plugin-package-inventory-deepseek/src"], + "@deepseek-ai/dsh-ptc-runtime": ["./packages/ptc-runtime/ptc-runtime/src"], + "@deepseek-ai/dsh-ptc-runtime-node": ["./packages/ptc-runtime/ptc-runtime-node/src"], "@deepseek-ai/dsh-pwsh-sandbox": ["./packages/shell/pwsh-sandbox/src"], "@deepseek-ai/dsh-remote-mock": ["./packages/test-support/remote-mock/src"], "@deepseek-ai/dsh-repeat-tool-reminder": ["./packages/guard/repeat-tool-reminder/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index da709bf506..400b9bbf33 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -41,8 +41,8 @@ "packages/client/*/tests/**/*.host.spec.ts" ], "references": [ - // Producer-to-UI spill tests use the code-runtime contract with the real tool registry. - { "path": "./packages/code-runtime/code-runtime" }, + // Producer-to-UI spill tests use the ptc-runtime contract with the real tool registry. + { "path": "./packages/ptc-runtime/ptc-runtime" }, // Shared leaf: web e2e boots the real host webserver (fixture + real-host // smoke policy). webserver has zero workspace deps and no cordis merge, // so it cannot drag host-side Context augmentation into this program. diff --git a/tsconfig.host.json b/tsconfig.host.json index b67bef6abd..3c05e6412d 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -255,9 +255,9 @@ { "path": "./packages/shell/tool-bash-persistent" }, { "path": "./packages/shell/tool-pwsh-persistent" }, { "path": "./packages/terminal/tool-terminal" }, - { "path": "./packages/code-runtime/code-runtime" }, - { "path": "./packages/experimental/code-runtime-python" }, - { "path": "./packages/code-runtime/code-runtime-node" }, + { "path": "./packages/ptc-runtime/ptc-runtime" }, + { "path": "./packages/experimental/ptc-runtime-python" }, + { "path": "./packages/ptc-runtime/ptc-runtime-node" }, { "path": "./packages/llm/llm-deepseek" }, { "path": "./packages/llm/llm-pi-ai" }, { "path": "./packages/shell/bash-local" }, diff --git a/vitest.config.ts b/vitest.config.ts index 101e71c2f0..f7af4a7bde 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -31,7 +31,7 @@ const windowsUnsupportedPackages = process.platform === 'win32' 'packages/shell/tool-bash', 'packages/hooks/*', 'packages/terminal/terminal-bash', - 'packages/experimental/code-runtime-python', + 'packages/experimental/ptc-runtime-python', 'packages/sandbox/sandbox-local', // OpenSSH multiplexing and Unix-socket helper streams require POSIX endpoints. 'packages/ssh/*', @@ -213,7 +213,7 @@ export default defineConfig({ 'packages/*/*/src/bin.ts', 'packages/*/*/src/worker.ts', // The built Node entry invokes the independently covered process bootstrap through fd 7. - 'packages/code-runtime/code-runtime-node/src/process-entry.ts', + 'packages/ptc-runtime/ptc-runtime-node/src/process-entry.ts', // Dynamic Host/Client composition is covered by its focused lifecycle // tests and assembled application checks rather than per-file coverage. 'packages/self-modification/*/src/**/*.{ts,tsx}', diff --git a/website/docs.ts b/website/docs.ts index c9823653d9..029139b92f 100644 --- a/website/docs.ts +++ b/website/docs.ts @@ -326,7 +326,7 @@ const subsystemGroups = [ ['jobs.md', '后台任务', 'Background jobs'], ['filesystem.md', '文件系统', 'Filesystem'], ['lsp.md', 'LSP 导航', 'LSP navigation'], - ['code-runtime.md', '代码运行时', 'Code runtime'], + ['ptc-runtime.md', 'PTC 运行时', 'PTC runtime'], ['web.md', 'Web 访问', 'Web access'], ['skills.md', '技能', 'Skills'], ['workflow.md', '工作流', 'Workflows'],