Merge remote-tracking branch 'origin/master' into chore/cordis-core-rc12
This commit is contained in:
commit
fc1710a167
2968 files changed
+78179
-33497
No files matched your search
+6
@@ -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/archived/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md
|
||||
2026-07-31-ptc-runtime-python-fd3-protocol.md: 514f4dd7c7b214e95474e9f5d9c7ba6af4bfeb8b
|
||||
2026-07-31-ptc-runtime-python-fd3-protocol.zh.md: e959dd75491ed1dd1e66f9ca4de856712054e31c
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
# Agent Note: the ptc-runtime-python fd-3 frame protocol
|
||||
|
||||
Status: implemented
|
||||
Archived: 2026-11-11
|
||||
|
||||
The CPython PTC runtime lives at `packages/experimental/ptc-runtime-python` and publishes as `@deepseek-ai/dsh-experimental-ptc-runtime-python`; the [publication policy](../../../../packages/experimental/README.md) preserves its experimental status.
|
||||
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
# Agent Note: the ptc-runtime-python fd-3 frame protocol
|
||||
|
||||
Status: implemented
|
||||
Archived: 2026-11-11
|
||||
|
||||
CPython PTC 运行时位于 `packages/experimental/ptc-runtime-python`,以 `@deepseek-ai/dsh-experimental-ptc-runtime-python` 名称发布;[发布策略](../../../../packages/experimental/README.zh.md)保留其实验性状态。
|
||||
|
||||
@@ -220,6 +220,9 @@
|
||||
"architecture/2026-07-31-code-runtime-portable-identifier-seam.i18n.yaml": "sha256:e243a62d3b468b6a65c80b284fe934fad09099a42d33c1dca47f435427a851b7",
|
||||
"architecture/2026-07-31-code-runtime-portable-identifier-seam.md": "sha256:d7a050d3a654b7b0445b8dbe6e87331bbd91ce0bf6ad23c6d83ee32ada85fc2f",
|
||||
"architecture/2026-07-31-code-runtime-portable-identifier-seam.zh.md": "sha256:286c53e0000bd0a109b67bf3ce5f190197fa674f103075461168768d78ea6770",
|
||||
"architecture/2026-07-31-ptc-runtime-python-fd3-protocol.i18n.yaml": "sha256:dc4a9f7f26a6cc8d27499f6bc4da505a5be72c5c1d2ded93adcbbbfe818860d7",
|
||||
"architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md": "sha256:a6525121a528190309ad1da498f919676355d7bbff90875800c6f33c31ff93fa",
|
||||
"architecture/2026-07-31-ptc-runtime-python-fd3-protocol.zh.md": "sha256:fa381eb718c9c4c78e40be9b1930a9b0b6571bf0be446bcc4f784228c0ef32b8",
|
||||
"architecture/2026-08-01-packaged-ripgrep-search.i18n.yaml": "sha256:43c9128079955e974fe1da3ce1a10779b4f5a25ac3629f92e3b1de847ad45050",
|
||||
"architecture/2026-08-01-packaged-ripgrep-search.md": "sha256:36cf2d6daa654abced690965338aec4628069dc77be3a1da6368a9b097a59ff4",
|
||||
"architecture/2026-08-01-packaged-ripgrep-search.zh.md": "sha256:45b2fe8e0d492eeff313d2ef3c98fd69761b3257eee3476b8bf53312e8b6095f",
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
# Bilingual-pair consistency record for 2026-07-31-ptc-runtime-python-fd3-protocol.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-ptc-runtime-python-fd3-protocol.md
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol:
|
||||
en: 0130850e16ce6f60
|
||||
zh: 7b70b03b5019277f
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol/problem:
|
||||
en: 2c36946bbff637b7
|
||||
zh: f290de0866ba7caa
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol/decision:
|
||||
en: f0d0d5ba5a9066ad
|
||||
zh: fbdab3731c33eb26
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol/wire-contract:
|
||||
en: 1225a32af91fcf84
|
||||
zh: 1dab4ecbd9ff7e34
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol/mirror-alignment:
|
||||
en: 26128b65f2763920
|
||||
zh: df24359faebcbfed
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol/alternatives-considered:
|
||||
en: 2f52b91980d013ed
|
||||
zh: 12dc9a24c03c3c68
|
||||
/agent-note-the-ptc-runtime-python-fd-3-frame-protocol/consequences:
|
||||
en: 16df6efd46d71e85
|
||||
zh: 4062475bec04ab5f
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: d94bb81479bfa4a1
|
||||
zh: af44ceaecf84ee51
|
||||
/agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide/decision:
|
||||
en: aea80ece13f2905b
|
||||
zh: a880bc1a7839cf12
|
||||
en: f2e0559e9cf0eddd
|
||||
zh: 704138e08a93979d
|
||||
/agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide/consequences:
|
||||
en: 41ebe22077560090
|
||||
zh: da3475e4c196c3f9
|
||||
en: 15d57cfa8c37ddc9
|
||||
zh: e16becb173d87579
|
||||
/agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide/alternatives-considered:
|
||||
en: ac43499cfe7b8495
|
||||
zh: e5ab599e7d3ed753
|
||||
@@ -42,9 +42,9 @@ inherited process environment (read-only, wins)
|
||||
|
||||
The launching environment wins because `DEEPSEEK_API_KEY=… dsh`, a CI secret, and a container `-e` are the one override an operator must be able to apply per run without editing machine state, and because it cannot be edited from inside it must be *visibly* read-only. Configuration is meant to carry only the *reference* — which name to resolve — and that name follows the non-secret ordering above.
|
||||
|
||||
**The project the harness is launched in is trusted, by default and without a prompt.** A checkout may carry its own endpoint, its own ordinary variables, and its own key; the key ranks below the managed store, so a key stored through the Models page is never displaced by one a checkout happens to contain. `LaunchEnvironmentSnapshot.getFrom(name, sources)` still searches only the layers a caller names, and omitting one is a refusal rather than a demotion — the mechanism exists for decisions where a layer must be unreachable; this decision includes the project layer.
|
||||
**The project the harness is launched in is trusted, by default and without a prompt.** A checkout may carry its own ordinary variables and its own key, but not the launch-only names the next paragraph lists, which include the DeepSeek endpoints; the key ranks below the managed store, so a key stored through the Models page is never displaced by one a checkout happens to contain. `LaunchEnvironmentSnapshot.getFrom(name, sources)` still searches only the layers a caller names, and omitting one is a refusal rather than a demotion — the mechanism exists for decisions where a layer must be unreachable; this decision includes the project layer.
|
||||
|
||||
**Trust does not extend to changing the harness itself.** `loadLayeredEnv` rejects, at load and before anything is materialized, any `.env` that sets a variable governing how a process launches (`PATH`, `SHELL`, `NODE_OPTIONS`, `LD_PRELOAD`), which ambient program handles an operation (`EDITOR`, `PAGER`, `BROWSER`), what code a runtime executes before the program it was asked to run (`BASH_ENV`, `PERL5OPT`, `PYTHONSTARTUP`, `RUBYOPT`, `JAVA_TOOL_OPTIONS`, the Git hook commands), where model-visible instructions load from (the whole `DSH_*` namespace, `HOME`, `XDG_*`), or how the network is reached and trusted (proxy and CA variables). Matching is case-insensitive, so `https_proxy` is not a bypass. One exemption, recorded in [the proxy policy note](2026-08-27-outbound-proxy-policy.md): the four proxy names are accepted from `$DSH_HOME/.env`, which no `.env` can relocate, and still refused from the invoking directory's file.
|
||||
**Trust does not extend to changing the harness itself.** `loadLayeredEnv` rejects, at load and before anything is materialized, any `.env` that sets a variable governing how a process launches (`PATH`, `SHELL`, `NODE_OPTIONS`, `LD_PRELOAD`), which ambient program handles an operation (`EDITOR`, `PAGER`, `BROWSER`), what code a runtime executes before the program it was asked to run (`BASH_ENV`, `PERL5OPT`, `PYTHONSTARTUP`, `RUBYOPT`, `JAVA_TOOL_OPTIONS`, the Git hook commands), where model-visible instructions load from (the whole `DSH_*` namespace, `HOME`, `XDG_*`), or how the network is reached and trusted (proxy, CA, and DeepSeek endpoint variables). Matching is case-insensitive, so `https_proxy` is not a bypass. Two exemptions accept names from `$DSH_HOME/.env`, which no `.env` can relocate, and still refuse them from the invoking directory's file: the four proxy names, recorded in [the proxy policy note](2026-08-27-outbound-proxy-policy.md), and `DEEPSEEK_BASE_URL` and `DEEPSEEK_SEARCH_BASE_URL`. The endpoint names choose where the model and search requests that carry the user's DeepSeek credential go. The profile patches in the same home can already set those endpoints as plugin `baseURL` fields, so accepting the names from the home file gives a writer of that directory nothing it lacks.
|
||||
|
||||
The line is that these take effect with no user action, before any turn, outside the permission policy and the sandbox. `DSH_PERMISSION_MODE` would switch off the approvals that make trusting a project meaningful at all, and `BASH_ENV` runs a file of the project's choosing on every single `bash -c` the bash tool issues — the project's code running under the agent's policy is the deal; the project rewriting that policy is not. Enumerating these is a losing game one variable at a time, which is why the whole `DSH_*` namespace is denied rather than an audited subset, and why the list is organised by what a variable *does* rather than by which runtime owns it. There is no opt-out: an escape hatch would have to be readable from somewhere, and anything a discovered file could set is the hole itself.
|
||||
|
||||
@@ -55,7 +55,7 @@ The line is that these take effect with no user action, before any turn, outside
|
||||
## Consequences
|
||||
|
||||
- The web credential form now takes effect against an older key in the user's `.env`; only a key exported in the launching shell still makes it read-only, and the diagnostic says so.
|
||||
- A `.env` holding `DSH_*`, `PATH`, `BROWSER`, or — in the invoking directory — a proxy variable fails the launch instead of being applied. Developers keeping switches in a repository `.env` move them to their shell — a deliberate, loud break.
|
||||
- A `.env` holding `DSH_*`, `PATH`, `BROWSER`, or — in the invoking directory — a proxy or DeepSeek endpoint variable fails the launch instead of being applied. Developers keeping switches in a repository `.env` move them to their shell — a deliberate, loud break.
|
||||
- Composition is no longer overridable by a stale shell endpoint. It is still overridable by a user's stored `settings.yaml`, which is the settings seam's layering and not something this note changes; the product CLI offers no flag above it, so a deployment that must win against stored settings owns its own bin or loader tree.
|
||||
- Not solved: the layers are still materialized into `process.env`, so ordinary project variables continue to reach child processes under the subprocess scrub. Bootstrap variables cannot come from a file at all; the environment package records the remaining subprocess reach as a limitation.
|
||||
|
||||
|
||||
+3
-3
@@ -43,9 +43,9 @@ inherited process environment (read-only, wins)
|
||||
|
||||
继承环境优先,因为 `DEEPSEEK_API_KEY=… dsh`、CI 机密与容器 `-e` 是运维必须能按次施加、且无需改动机器状态的那一种覆盖;而它无法从进程内部修改,就必须*可见地*只读。配置本应只携带*引用*——解析哪个名字——该名字本身遵循上面的非机密顺序。
|
||||
|
||||
**harness 被启动于其中的项目默认可信,且不做询问。** 一个 checkout 可以携带自己的 endpoint、自己的普通变量和自己的密钥;密钥排在受管存储之下,因此通过 Models 页存下的密钥绝不会被 checkout 中恰好带有的那一个顶掉。`LaunchEnvironmentSnapshot.getFrom(name, sources)` 仍然只搜索调用方点名的层,省略某层仍是拒绝而不是降级——该机制供要求某一层不可达的决策使用;本决策包含项目层。
|
||||
**harness 被启动于其中的项目默认可信,且不做询问。** 一个 checkout 可以携带自己的普通变量和自己的密钥,但不能设置下一段列出的启动专用变量名,其中包括 DeepSeek 端点;密钥排在受管存储之下,因此通过 Models 页存下的密钥绝不会被 checkout 中恰好带有的那一个顶掉。`LaunchEnvironmentSnapshot.getFrom(name, sources)` 仍然只搜索调用方点名的层,省略某层仍是拒绝而不是降级——该机制供要求某一层不可达的决策使用;本决策包含项目层。
|
||||
|
||||
**信任不延伸到改变 harness 本身。** `loadLayeredEnv` 会在加载时、且在物化任何内容之前,拒绝任何设置了下列变量的 `.env`:决定进程如何启动的(`PATH`、`SHELL`、`NODE_OPTIONS`、`LD_PRELOAD`)、决定由哪个环境程序处理一项操作的(`EDITOR`、`PAGER`、`BROWSER`)、决定运行时在执行被要求运行的程序之前先执行哪些代码的(`BASH_ENV`、`PERL5OPT`、`PYTHONSTARTUP`、`RUBYOPT`、`JAVA_TOOL_OPTIONS`、Git 的钩子命令)、决定模型可见指令从哪里加载的(整个 `DSH_*` 命名空间、`HOME`、`XDG_*`),以及决定网络如何访问以及如何建立信任的(proxy 与 CA 变量)。匹配不区分大小写,因此 `https_proxy` 不是绕过手段。唯一的豁免记录在[代理策略笔记](2026-08-27-outbound-proxy-policy.zh.md)中:四个代理名可从 `$DSH_HOME/.env` 接受——没有任何 `.env` 能挪动该文件——但仍拒绝来自调用目录文件的同名变量。
|
||||
**信任不延伸到改变 harness 本身。** `loadLayeredEnv` 会在加载时、且在物化任何内容之前,拒绝任何设置了下列变量的 `.env`:决定进程如何启动的(`PATH`、`SHELL`、`NODE_OPTIONS`、`LD_PRELOAD`)、决定由哪个环境程序处理一项操作的(`EDITOR`、`PAGER`、`BROWSER`)、决定运行时在执行被要求运行的程序之前先执行哪些代码的(`BASH_ENV`、`PERL5OPT`、`PYTHONSTARTUP`、`RUBYOPT`、`JAVA_TOOL_OPTIONS`、Git 的钩子命令)、决定模型可见指令从哪里加载的(整个 `DSH_*` 命名空间、`HOME`、`XDG_*`),以及决定网络如何访问以及如何建立信任的(proxy、CA 与 DeepSeek 端点变量)。匹配不区分大小写,因此 `https_proxy` 不是绕过手段。有两项豁免从 `$DSH_HOME/.env` 接受变量名——没有任何 `.env` 能挪动该文件——但仍拒绝来自调用目录文件的同名变量:四个代理名,记录在[代理策略笔记](2026-08-27-outbound-proxy-policy.zh.md)中;以及 `DEEPSEEK_BASE_URL` 与 `DEEPSEEK_SEARCH_BASE_URL`。这两个端点变量名决定携带用户 DeepSeek 凭据的模型请求与搜索请求发往何处。同一 home 中的 profile patch 本就能以插件 `baseURL` 字段设置这些端点,因此从 home 文件接受它们,不会给能写入该目录的一方任何它原本没有的能力。
|
||||
|
||||
这条界线在于:它们无需任何用户动作、在任何轮次开始之前、且在权限策略与沙箱之外就生效。`DSH_PERMISSION_MODE` 会关掉让「信任项目」根本成立的那道审批,而 `BASH_ENV` 会在 bash 工具每次发出 `bash -c` 时执行项目指定的文件——项目的代码在 agent(智能体)的策略下运行是约定,项目改写那份策略不是。一个变量一个变量地枚举是必输的游戏,所以整个 `DSH_*` 命名空间被拒绝而不是只拒绝一份经审查的子集,也所以这份清单是按变量*做什么*而不是按哪个运行时拥有它来组织的。不设逃生门:逃生门本身总得从某处读取,而任何被发现的文件能设置的东西,就是那个漏洞本身。
|
||||
|
||||
@@ -56,7 +56,7 @@ inherited process environment (read-only, wins)
|
||||
## Consequences
|
||||
|
||||
- Web 凭据表单现在能压过用户 `.env` 里更旧的密钥;只有在启动 shell 里 export 的密钥才会让它变成只读,诊断信息也会这么说。
|
||||
- 含 `DSH_*`、`PATH`、`BROWSER` 或(在调用目录中)proxy 变量的 `.env` 会导致启动失败而不是被应用。把开关放在仓库 `.env` 里的开发者需要改放到 shell——这是一次刻意且响亮的破坏。
|
||||
- 含 `DSH_*`、`PATH`、`BROWSER` 或(在调用目录中)proxy 或 DeepSeek 端点变量的 `.env` 会导致启动失败而不是被应用。把开关放在仓库 `.env` 里的开发者需要改放到 shell——这是一次刻意且响亮的破坏。
|
||||
- composition 不再会被陈旧的 shell endpoint 覆盖。但它仍然会被用户已存的 `settings.yaml` 覆盖,这是 settings seam 的分层方式,本 Note 不改变它;产品 CLI 没有高于它的标志,因此需要压过已存 settings 的部署方要自带 bin 或 loader 配置树。
|
||||
- 未解决的:各层仍然会被物化进 `process.env`,因此普通项目变量继续按子进程清洗规则抵达子进程。bootstrap 变量完全不能来自文件;环境包将其余变量仍可抵达子进程这一点记录为一项限制。
|
||||
|
||||
|
||||
+10
-10
@@ -18,17 +18,17 @@
|
||||
en: 821989170ad76994
|
||||
zh: 0ed142bea166fc3a
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/layering-principles/ui-adapters-own-react-integration:
|
||||
en: 4d032e048364fb97
|
||||
zh: 82a435531efdaa78
|
||||
en: 4caab5487c8545f8
|
||||
zh: 77fa93f76b6fb65f
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/layering-principles/slot-scopes-and-standard-props-are-separate:
|
||||
en: b6f585ca87e1fc6f
|
||||
zh: 53fd58c3e93cf17c
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/package-ownership:
|
||||
en: 2fc4b50a651b1847
|
||||
zh: 7dceeecb9c58e838
|
||||
en: 89f75f7cc2fe0e6c
|
||||
zh: e50974fad3baf69c
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/overall-data-flow:
|
||||
en: e7c11e82db080dd4
|
||||
zh: 5a8a501a128366d6
|
||||
en: 002d9f406580684b
|
||||
zh: a86742c6c943ac85
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/session-controller-client:
|
||||
en: b88f651b1bfb8b5e
|
||||
zh: b88f651b1bfb8b5e
|
||||
@@ -48,8 +48,8 @@
|
||||
en: 860315b96703371d
|
||||
zh: 860315b96703371d
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/ui-session/service-responsibilities:
|
||||
en: d075ba28fd37bff2
|
||||
zh: e2d430d1f3e89b15
|
||||
en: 40e598676f2d7f46
|
||||
zh: acc8e028978a5419
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/ui-session/standard-source-registration:
|
||||
en: e4be6d4b1d79b342
|
||||
zh: 7cb0e8c0f6358b50
|
||||
@@ -60,8 +60,8 @@
|
||||
en: 5d9bdb1f784f97f2
|
||||
zh: a4b3de7a21b84fce
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/ui-session/pending-interactions:
|
||||
en: 85e358a03ffac4ba
|
||||
zh: 54b1d5ed6197f2c2
|
||||
en: 54b65fef1667278f
|
||||
zh: cf46a8ad738a0a55
|
||||
/agent-note-client-session-conversation-and-ui-ownership-layers/workspace-controller-and-ui-workspace:
|
||||
en: 45e5f41550e62a3d
|
||||
zh: d4e6d8f5b397bb51
|
||||
|
||||
+7
-6
@@ -57,7 +57,7 @@ Each standard hook belongs to the `ui-*` package closest to its data semantics.
|
||||
| `useSessions` | `client/ui-session` | Session Controller global list |
|
||||
| `useSession` | `client/ui-session` | Bound Session snapshot |
|
||||
| `useProjection` | `client/ui-session` | Bound Session keyed projection |
|
||||
| `useSessionStatus` | `client/ui-session` | Running, effective pending request, and unread completion |
|
||||
| `useSessionStatus` | `client/ui-session-status` | Running, effective pending request, and unread completion |
|
||||
| `useSessionRetainInfo` | `client/ui-session` | Read-only Controller reference-source counts |
|
||||
| `useWorkspaces` | `client/ui-workspace` | Workspace Controller list |
|
||||
| `useConversation` | `client/ui-conversation` | Conversation binding snapshot |
|
||||
@@ -80,7 +80,8 @@ Adding a target does not add a branch to the renderer or Session Controller. The
|
||||
| --- | --- | --- |
|
||||
| `api/session-controller/client` | Session objects, catalog, references, source counts, commands, projections, event windows, and Agent Contexts | Navigation, completion reminders, Conversation targets, React, Slots, Workspace |
|
||||
| `api/workspace-controller/client` | Workspace objects, ordering, archive state, commands, and snapshots | React, Session navigation policy, directory UI |
|
||||
| `client/ui-session` | Explicit Session scope, standard sources, `SessionProvider`, and unified UI status | Session transport, reference ownership, Conversation assembly, Approval/Question results |
|
||||
| `client/ui-session` | Explicit Session scope, standard sources, `SessionProvider`, and effective pending interactions | Session transport, reference ownership, Conversation assembly, Approval/Question results, unified UI status |
|
||||
| `client/ui-session-status` | Unified UI status: running state, effective pending request, and completion reminders | Pending-interaction registration, Session transport, React |
|
||||
| `client/ui-workspace` | Workspace hook, browser UI, main-area reference, and cross-Controller navigation policy | Workspace transport, copies of Session data |
|
||||
| `client/ui-conversation` | Conversation core, registries, bindings, shell, input, composer, queue, and View navigation | Session transport, Chat/Trajectory snapshots |
|
||||
| `client/ui-chat` | Chat target, Node definitions, renderers, selection, details, and locale | Session lifecycle, generic View navigation, Trajectory, historical-image cache |
|
||||
@@ -120,7 +121,7 @@ Session data reaches the UI through this path:
|
||||
|
||||
Workspace data enters the Workspace Controller from `ctx.remote.workspace`, then `ui-workspace` exposes it as `useWorkspaces`. `ui-workspace` reads explicit targets for cross-domain navigation and owns the main-area reference without making it a default business Context.
|
||||
|
||||
Approval and Question arrive from the Host waterfall through `ctx.remote.$on` at their respective UI owners. Each owner publishes a Pending object; `ui-session.sessionStatus` supplies the same effective object to Workspace indicators and Conversation composer selection.
|
||||
Approval and Question arrive from the Host waterfall through `ctx.remote.$on` at their respective UI owners. Each owner publishes a Pending object through `ui-session`; `ctx.uiSession.sessionStatus` from `ui-session-status` supplies the same effective object to Workspace indicators and Conversation composer selection.
|
||||
|
||||
## Session Controller Client
|
||||
|
||||
@@ -178,9 +179,9 @@ This cleanup does not require the Session Controller to know the roster of upper
|
||||
- supplies `SessionProvider` rendering semantics;
|
||||
- supplies built-in Session snapshot, projection, and sessionId sources;
|
||||
- accepts Session-scoped source contributions from other domain packages;
|
||||
- aggregates domain-owned pending interactions with running and completion-reminder facts in `sessionStatus`.
|
||||
- selects each Session's effective domain-owned pending interaction and publishes it read-only as `pendingInteractions`.
|
||||
|
||||
It does not own Session transport, event folding, Conversation targets, or concrete business results.
|
||||
It does not own Session transport, event folding, Conversation targets, or concrete business results. `client/ui-session-status` combines the effective pending interactions with running and completion-reminder facts in the `uiSession.sessionStatus` service, read as `ctx.uiSession.sessionStatus`.
|
||||
|
||||
### Standard source registration
|
||||
|
||||
@@ -221,7 +222,7 @@ Concurrent objects with the same key are rejected; replacement requests use a ne
|
||||
|
||||
`ui-session` selects each Session's effective object using domain precedence. Higher precedence wins; at equal precedence, the later valid object in traversal order wins.
|
||||
|
||||
The pending aggregate is private to `ui-session`; its effective request appears unchanged as `sessionStatus.getSnapshot().get(id)?.pendingInteraction`. `useSessionStatus` is the public UI read face.
|
||||
The pending aggregate is private to `ui-session`; `pendingInteractions` exposes each Session's effective request read-only, and the same object appears as `ctx.uiSession.sessionStatus.getSnapshot().get(id)?.pendingInteraction`. `useSessionStatus` is the public UI read face.
|
||||
|
||||
Session navigation state and composer takeover read the same effective object. They do not maintain separate status maps or takeover rosters.
|
||||
|
||||
|
||||
+7
-6
@@ -57,7 +57,7 @@ UI 层可以同时读取多个 Controller 做一次导航决定,但不得把
|
||||
| `useSessions` | `client/ui-session` | Session Controller 全局列表 |
|
||||
| `useSession` | `client/ui-session` | 已绑定会话快照 |
|
||||
| `useProjection` | `client/ui-session` | 已绑定会话的键控投影 |
|
||||
| `useSessionStatus` | `client/ui-session` | 运行状态、有效待处理请求和未读完成提醒 |
|
||||
| `useSessionStatus` | `client/ui-session-status` | 运行状态、有效待处理请求和未读完成提醒 |
|
||||
| `useSessionRetainInfo` | `client/ui-session` | 控制器的只读引用来源计数 |
|
||||
| `useWorkspaces` | `client/ui-workspace` | Workspace Controller 列表 |
|
||||
| `useConversation` | `client/ui-conversation` | Conversation binding snapshot |
|
||||
@@ -80,7 +80,8 @@ UI 层可以同时读取多个 Controller 做一次导航决定,但不得把
|
||||
| --- | --- | --- |
|
||||
| `api/session-controller/client` | 会话对象、目录、引用、来源计数、命令、投影、事件窗口与 Agent Context | 导航、完成提醒、Conversation target、React、Slot、Workspace |
|
||||
| `api/workspace-controller/client` | Workspace 对象、顺序、归档、命令和 snapshot | React、Session 导航策略、目录 UI |
|
||||
| `client/ui-session` | 显式会话作用域、标准数据源、`SessionProvider` 与统一 UI 状态 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果 |
|
||||
| `client/ui-session` | 显式会话作用域、标准数据源、`SessionProvider` 与有效待处理交互 | 会话传输、引用所有权、Conversation 组装、Approval/Question 结果、统一 UI 状态 |
|
||||
| `client/ui-session-status` | 统一 UI 状态:运行状态、有效待处理请求与完成提醒 | 待处理交互登记、会话传输、React |
|
||||
| `client/ui-workspace` | Workspace 钩子、浏览器 UI、主区域引用与跨控制器导航策略 | Workspace 传输、会话数据副本 |
|
||||
| `client/ui-conversation` | Conversation core、registry、binding、shell、input、composer、queue 和 View 导航 | Session transport、Chat/Trajectory snapshot |
|
||||
| `client/ui-chat` | Chat target、Node definitions、renderer、selection、details 和 locale | Session 生命周期、通用 View 导航、Trajectory、历史图片 cache |
|
||||
@@ -120,7 +121,7 @@ Session 数据按以下路径进入 UI:
|
||||
|
||||
Workspace 数据由 `ctx.remote.workspace` 进入 Workspace 控制器,再由 `ui-workspace` 通过 `useWorkspaces` 提供。`ui-workspace` 为跨领域导航读取显式目标并持有主区域引用,不把它变为默认业务 Context。
|
||||
|
||||
Approval 与 Question 通过 `ctx.remote.$on` 从 Host waterfall 到达各自的 UI owner。各 owner 发布 Pending 对象;`ui-session.sessionStatus` 向 Workspace 标识和 Conversation composer 选择提供同一个有效对象。
|
||||
Approval 与 Question 通过 `ctx.remote.$on` 从 Host waterfall 到达各自的 UI owner。各 owner 通过 `ui-session` 发布 Pending 对象;`ui-session-status` 提供的 `ctx.uiSession.sessionStatus` 向 Workspace 标识和 Conversation composer 选择提供同一个有效对象。
|
||||
|
||||
## Session Controller Client
|
||||
|
||||
@@ -178,9 +179,9 @@ Session Controller 对外提供三个互不替代的读取面:
|
||||
- 提供 `SessionProvider` 的呈现语义;
|
||||
- 内建 session snapshot、projection 和 sessionId source;
|
||||
- 接收其他领域 package 的 Session-scoped source contribution;
|
||||
- 在 `sessionStatus` 中组合领域持有的待处理交互、运行事实和完成提醒。
|
||||
- 为每个会话选出领域持有的有效待处理交互,并以只读的 `pendingInteractions` 发布。
|
||||
|
||||
它不拥有 Session transport、event folding、Conversation target 或具体业务结果。
|
||||
它不拥有 Session transport、event folding、Conversation target 或具体业务结果。`client/ui-session-status` 在 `uiSession.sessionStatus` 服务中把有效待处理交互与运行事实、完成提醒组合起来,以 `ctx.uiSession.sessionStatus` 读取。
|
||||
|
||||
### 标准 source 注册
|
||||
|
||||
@@ -221,7 +222,7 @@ Contribution roster 变化会重建已 materialize 的 binding 并发布新的 s
|
||||
|
||||
`ui-session` 使用各 domain 的 precedence 选出每个 Session 当前生效的对象。较高 precedence 胜出,相同 precedence 下后遍历到的有效对象胜出。
|
||||
|
||||
待处理聚合是 `ui-session` 的私有实现;其有效请求原样出现在 `sessionStatus.getSnapshot().get(id)?.pendingInteraction` 中。`useSessionStatus` 是公开 UI 读取接口。
|
||||
待处理聚合是 `ui-session` 的私有实现;`pendingInteractions` 以只读方式提供每个会话的有效请求,同一个对象原样出现在 `ctx.uiSession.sessionStatus.getSnapshot().get(id)?.pendingInteraction` 中。`useSessionStatus` 是公开 UI 读取接口。
|
||||
|
||||
Session 导航状态和 composer takeover 必须读取同一个 effective object,不得分别维护 status map 或 takeover roster。
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 6379f0a2522f4c46
|
||||
zh: c45ffeb5089be274
|
||||
/agent-note-one-outbound-proxy-policy-installed-before-anything-can-request/decision:
|
||||
en: 6435c336ab53ca0f
|
||||
zh: 57070799a7061f85
|
||||
en: 5168301af05473ed
|
||||
zh: 30b840cb41998bee
|
||||
/agent-note-one-outbound-proxy-policy-installed-before-anything-can-request/alternatives-considered:
|
||||
en: df6c078f239a11f5
|
||||
zh: 914da26836aa373b
|
||||
|
||||
@@ -16,7 +16,7 @@ That sentence could not have worked anyway, for three measured reasons. `NODE_US
|
||||
|
||||
**One policy, resolved once from the launch environment, installed as the global dispatcher.** `packages/util/http-proxy` resolves a `ProxyPolicy` and installs it in `runProfile` immediately after the environment snapshot is provided and before any entry mounts. Node's `fetch` resolves undici's global dispatcher, so every plain `fetch()` and every SDK that reaches `globalThis.fetch` is covered without touching its code — nine call sites at the time of writing, and every future one for free. `loadLayeredEnv` has exactly one caller and `apps/web` ships no bin, so this single site covers every profile including `sdk-minimal`, which does not layer over `base`.
|
||||
|
||||
Resolution reads the launcher's snapshot rather than `process.env`, which is what makes a proxy in `$DSH_HOME/.env` work — the capability the environment-variable approach cannot have. Only that file: `loadLayeredEnv` refuses a proxy name in the project `.env` exactly as it refuses `PATH` or `NODE_OPTIONS` there, because that file arrives with a clone and must not choose the harness's route. The home file is exempt for the four proxy names alone, and `DSH_HOME` is itself bootstrap-only, so no `.env` can point the exemption at a directory a repository controls.
|
||||
Resolution reads the launcher's snapshot rather than `process.env`, which is what makes a proxy in `$DSH_HOME/.env` work — the capability the environment-variable approach cannot have. Only that file: `loadLayeredEnv` refuses a proxy name in the project `.env` exactly as it refuses `PATH` or `NODE_OPTIONS` there, because that file arrives with a clone and must not choose the harness's route. The home file is exempt for the four proxy names, and `DSH_HOME` is itself bootstrap-only, so no `.env` can point the exemption at a directory a repository controls.
|
||||
|
||||
**A library in `util/`, not a plugin.** Transport policy has one answer per process: nothing to swap, and no scope narrower than the process to give one. The package exports functions and mounts nothing — `boot`, `web`, `subprocess`, and `workflow` all consume it, and `util/` is the group every other group may depend on.
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ Node 内置的 `fetch` 会忽略 `HTTP_PROXY` 与 `HTTPS_PROXY`。开发者运
|
||||
|
||||
**一份策略,从启动环境解析一次,装为全局 dispatcher。** `packages/util/http-proxy` 解析出 `ProxyPolicy`,并在 `runProfile` 中于环境快照提供之后、任何 entry 挂载之前完成安装。Node 的 `fetch` 解析的正是 undici 的全局 dispatcher,因此每一处普通 `fetch()` 以及每一个最终落到 `globalThis.fetch` 的 SDK 都无需改动即被覆盖——撰写时是九个调用点,未来新增的也自动覆盖。`loadLayeredEnv` 只有一个调用方,且 `apps/web` 不提供 bin,因此这一处即覆盖全部 profile,包括不叠加 `base` 的 `sdk-minimal`。
|
||||
|
||||
解析读取的是启动器的快照而非 `process.env`,这正是让 `$DSH_HOME/.env` 中的代理生效的原因——也是环境变量方案不可能具备的能力。仅限该文件:`loadLayeredEnv` 拒绝项目 `.env` 里的代理名,正如它在那里拒绝 `PATH` 或 `NODE_OPTIONS`,因为那个文件随 clone 一起到来,不得替 Harness 选择路由。home 文件仅对这四个代理名豁免,而 `DSH_HOME` 本身是 bootstrap-only,因此没有任何 `.env` 能把这份豁免指向仓库控制的目录。
|
||||
解析读取的是启动器的快照而非 `process.env`,这正是让 `$DSH_HOME/.env` 中的代理生效的原因——也是环境变量方案不可能具备的能力。仅限该文件:`loadLayeredEnv` 拒绝项目 `.env` 里的代理名,正如它在那里拒绝 `PATH` 或 `NODE_OPTIONS`,因为那个文件随 clone 一起到来,不得替 Harness 选择路由。home 文件对这四个代理名豁免,而 `DSH_HOME` 本身是 bootstrap-only,因此没有任何 `.env` 能把这份豁免指向仓库控制的目录。
|
||||
|
||||
**放在 `util/` 的库,而非插件。** 传输策略每个进程只有一个答案:没有可替换的实现,也没有比进程更窄的作用域可赋予。因此本包只导出函数、不挂载任何东西——`boot`、`web`、`subprocess` 与 `workflow` 都消费它,而 `util/` 正是其他所有组都可以依赖的那一组。
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 990d46f713fb6303
|
||||
zh: 592cd6128a9640b1
|
||||
/agent-note-one-remote-failure-vocabulary-for-ctx-remote/decision:
|
||||
en: 120e2fb97ac765d8
|
||||
zh: 5d5f110db4a9b717
|
||||
en: b54b9d98a34eeaa1
|
||||
zh: ac8e3d493b554c2d
|
||||
/agent-note-one-remote-failure-vocabulary-for-ctx-remote/code-ownership:
|
||||
en: cc1d8b88f7349b77
|
||||
zh: 70f010e3310e2667
|
||||
|
||||
@@ -16,12 +16,12 @@ Fixed Host facts bypassed `ctx.remote` too: the Host home came from `(ctx.get('c
|
||||
|
||||
## Decision
|
||||
|
||||
`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError<Code>`: a real `Error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult<T>` keeps its shape.
|
||||
`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError<Code>`: a `HarnessError` from the dependency-free `@deepseek-ai/dsh-error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult<T>` keeps its shape.
|
||||
|
||||
```text
|
||||
export class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends Error {
|
||||
export class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends HarnessError {
|
||||
readonly isDSHRemoteError: true = true
|
||||
constructor(readonly code: Code, message: string,
|
||||
constructor(override readonly code: Code, message: string,
|
||||
readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions)
|
||||
}
|
||||
export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError<C> }[RemoteErrorCode]
|
||||
|
||||
+3
-3
@@ -16,12 +16,12 @@ Host 固定事实同样绕过了 `ctx.remote`:Host home 取自 `(ctx.get('conn
|
||||
|
||||
## Decision
|
||||
|
||||
`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError<Code>`:一个真 `Error`,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult<T>` 形状不变。
|
||||
`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError<Code>`:一个继承无依赖包 `@deepseek-ai/dsh-error` 中 `HarnessError` 的错误,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult<T>` 形状不变。
|
||||
|
||||
```text
|
||||
export class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends Error {
|
||||
export class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends HarnessError {
|
||||
readonly isDSHRemoteError: true = true
|
||||
constructor(readonly code: Code, message: string,
|
||||
constructor(override readonly code: Code, message: string,
|
||||
readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions)
|
||||
}
|
||||
export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError<C> }[RemoteErrorCode]
|
||||
|
||||
+2
-2
@@ -12,8 +12,8 @@
|
||||
en: d6b9c22603a4f933
|
||||
zh: f324b91830078d9a
|
||||
/agent-note-sandboxed-node-execution-for-ptc/decision/resolved-inputs-and-policy:
|
||||
en: 3aef37bb4f8a8e53
|
||||
zh: a7b477324d486ab3
|
||||
en: e544f1a5b7f5b0ec
|
||||
zh: 3195e0008313a5c6
|
||||
/agent-note-sandboxed-node-execution-for-ptc/decision/control-and-lifetime:
|
||||
en: a8897bae00f5f674
|
||||
zh: 2c959353c5a885a4
|
||||
|
||||
@@ -22,8 +22,6 @@ The host preserves `ELECTRON_RUN_AS_NODE` for child startup; the bootstrap remov
|
||||
|
||||
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 [experimental Python provider](../../../../packages/experimental/ptc-runtime-python/README.md) shares the resolved file policy and sandbox diagnostics while retaining its local Unix execution and configured wall deadline. Per-call timeout overrides remain unsupported.
|
||||
|
||||
### Control and lifetime
|
||||
|
||||
The subprocess owner supplies a dedicated inherited binary control channel, separate from program stdout/stderr and launcher lifecycle IPC. The host bounds frames, queued writes, pending calls and outstanding argument bytes, then validates call identity and the binding allowlist before dispatch. Model code can write to that channel, so its bytes remain untrusted.
|
||||
|
||||
@@ -22,8 +22,6 @@ Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前
|
||||
|
||||
文件模式、观察到的拒绝与强制完整性通过 `PtcRunResult.sandbox` 独立于程序结果传递。所需沙箱后端无法启动时,受限执行失败。完整访问是显式策略模式。程序成功不证明完整强制能力,`process` 描述符与额外控制管道也不声明多租户隔离。
|
||||
|
||||
[实验性 Python 提供方](../../../../packages/experimental/ptc-runtime-python/README.zh.md)共享已解析文件策略与沙箱诊断,同时保留本地 Unix 执行和配置的经过时间截止。仍不支持单次 timeout 覆盖。
|
||||
|
||||
### 控制与生命周期
|
||||
|
||||
子进程所有者提供专用的继承式二进制控制通道,与程序 stdout/stderr 及 launcher 生命周期 IPC 分开。Host 限制帧、排队写入、待处理调用和未完成参数字节,然后在分派前验证调用身份与绑定允许列表。模型代码可以写入该通道,因此其中字节仍不可信。
|
||||
|
||||
+4
-4
@@ -12,8 +12,8 @@
|
||||
en: a15c7c13f167e5ac
|
||||
zh: 63bcc2ef60c2f344
|
||||
/agent-note-client-session-references-reference-sources-and-ui-status/decision/scope-and-ownership:
|
||||
en: 3f04f9c2b7b0fc2b
|
||||
zh: ebfcbac3de8463a3
|
||||
en: 9ff7f15985d06986
|
||||
zh: fe27ef687594c124
|
||||
/agent-note-client-session-references-reference-sources-and-ui-status/decision/addresses-bindings-and-references:
|
||||
en: 3743abc8bca00348
|
||||
zh: d79e6a9311f0a2fe
|
||||
@@ -24,8 +24,8 @@
|
||||
en: e2de83d10542f93b
|
||||
zh: 3855b38fc8c48ea3
|
||||
/agent-note-client-session-references-reference-sources-and-ui-status/decision/unified-ui-session-status:
|
||||
en: 2d75aef5cf5f1fc8
|
||||
zh: 87a7051f24f9871a
|
||||
en: 07ea04b9ca50dd8f
|
||||
zh: e025fcea4c9f0fb9
|
||||
/agent-note-client-session-references-reference-sources-and-ui-status/decision/explicit-providers-and-consumer-lifetimes:
|
||||
en: 04802baa0147fec1
|
||||
zh: b86037bf2e4bc936
|
||||
|
||||
@@ -21,7 +21,8 @@ Client Session objects, Agent-scoped Client Contexts, references, consumer-sourc
|
||||
| Owner | Responsibility |
|
||||
| --- | --- |
|
||||
| Client Session Controller | Catalog, live generations, references, source counts, bindings, history windows, and existing Session control state |
|
||||
| `ui-session` | Explicit Session Provider integration and the unified UI status source |
|
||||
| `ui-session` | Explicit Session Provider integration and the effective pending-interaction source |
|
||||
| `ui-session-status` | The unified UI status source |
|
||||
| View or operation | Its own reference, target, source identifier, and release point |
|
||||
| Workspace UI | Main-area target and reference, navigation, persisted target, and creation flow |
|
||||
| UI composition boundary | Supplies an owner-provided reference to one explicit `SessionProvider` |
|
||||
@@ -89,7 +90,7 @@ Window-level consumers may inspect source markers. Session business operations s
|
||||
|
||||
### Unified UI Session status
|
||||
|
||||
`ui-session` owns a React-free `sessionStatus` source and exposes it through the standard `useSessionStatus` hook. The snapshot is indexed by Session identity and supplies one UI status record per known Session. It combines these independent facts rather than reducing them to one mutually exclusive phase:
|
||||
`ui-session-status` owns the React-free `uiSession.sessionStatus` service, read as `ctx.uiSession.sessionStatus`, and exposes it through the standard `useSessionStatus` hook. The snapshot is indexed by Session identity and supplies one UI status record per known Session. It combines these independent facts rather than reducing them to one mutually exclusive phase:
|
||||
|
||||
| Field | Value | Meaning and owner |
|
||||
| --- | --- | --- |
|
||||
@@ -99,7 +100,7 @@ Window-level consumers may inspect source markers. Session business operations s
|
||||
|
||||
Source counts remain authoritative in `SessionListState.byId[id].retainedBy`; UI status reads them for acknowledgement policy without owning another reference registry. Titles, Workspace associations, history, queues, and projection data remain with their existing owners.
|
||||
|
||||
Pending domains retain `SessionPendingInteractionMap`, request identities, precedence, publication disposers, and teardown delegation. The unified status includes the same effective request object; it does not copy requests or create a second pending registry. Workspace status indicators and Conversation composer selection read `useSessionStatus` instead of separate `useSessionPendingInteraction` and `useCompletedSessionIds` hooks.
|
||||
Pending domains retain `SessionPendingInteractionMap`, request identities, precedence, publication disposers, and teardown delegation in `ui-session`, which publishes each Session's effective request read-only as `ctx.uiSession.pendingInteractions`. The unified status includes the same effective request object; it does not copy requests or create a second pending registry. Workspace status indicators and Conversation composer selection read `useSessionStatus` instead of separate `useSessionPendingInteraction` and `useCompletedSessionIds` hooks.
|
||||
|
||||
Completion tracking subscribes to the existing `api-session/status` events so a running-to-idle transition is not lost in batched catalog snapshots. Host-list rows (`ids`) establish initial and reconnect running baselines; synthetic catalog and retained rows preserve independently observed status. A pending empty catalog is not evidence that Sessions disappeared. The update rules are:
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ Client Session 对象、Agent 作用域的 Client Context、引用、使用方
|
||||
| 所有者 | 职责 |
|
||||
| --- | --- |
|
||||
| Client Session Controller | 目录、活跃代、引用、来源计数、binding、历史窗口与既有 Session 控制状态 |
|
||||
| `ui-session` | 显式 Session Provider 集成与统一 UI 状态来源 |
|
||||
| `ui-session` | 显式 Session Provider 集成与有效待处理交互来源 |
|
||||
| `ui-session-status` | 统一 UI 状态来源 |
|
||||
| 视图或操作 | 自己的引用、目标、来源标识与释放时机 |
|
||||
| Workspace UI | 主区域目标与引用、导航、持久目标及创建流程 |
|
||||
| UI 组合边界 | 将所有者提供的引用交给一个明确的 `SessionProvider` |
|
||||
@@ -89,7 +90,7 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源
|
||||
|
||||
### 统一的 UI Session 状态
|
||||
|
||||
`ui-session` 拥有不依赖 React 的 `sessionStatus` 来源,通过标准 `useSessionStatus` 钩子公开。快照按 Session 身份索引,为每个已知 Session 提供一条 UI 状态记录。它组合下列独立事实,不将它们压缩成互斥的单一阶段:
|
||||
`ui-session-status` 拥有不依赖 React 的 `uiSession.sessionStatus` 服务,以 `ctx.uiSession.sessionStatus` 读取,并通过标准 `useSessionStatus` 钩子公开。快照按 Session 身份索引,为每个已知 Session 提供一条 UI 状态记录。它组合下列独立事实,不将它们压缩成互斥的单一阶段:
|
||||
|
||||
| 字段 | 取值 | 含义与所有者 |
|
||||
| --- | --- | --- |
|
||||
@@ -99,7 +100,7 @@ Controller 将来源计数与每个活跃代的引用共同管理。每个来源
|
||||
|
||||
来源计数以 `SessionListState.byId[id].retainedBy` 为准;UI 状态读取它以执行确认策略,不维护另一套引用注册表。标题、Workspace 关联、历史、队列和投影数据保留在各自的既有所有者中。
|
||||
|
||||
待处理领域保留 `SessionPendingInteractionMap`、请求身份、优先级、发布清理函数与卸载委托。统一状态包含同一个有效请求对象,不复制请求,也不创建第二套待处理注册表。Workspace 状态指示器与 Conversation composer 选择读取 `useSessionStatus`,不再分别读取 `useSessionPendingInteraction` 和 `useCompletedSessionIds` 钩子。
|
||||
待处理领域在 `ui-session` 中保留 `SessionPendingInteractionMap`、请求身份、优先级、发布清理函数与卸载委托,`ui-session` 以只读的 `ctx.uiSession.pendingInteractions` 发布每个 Session 的有效请求。统一状态包含同一个有效请求对象,不复制请求,也不创建第二套待处理注册表。Workspace 状态指示器与 Conversation composer 选择读取 `useSessionStatus`,不再分别读取 `useSessionPendingInteraction` 和 `useCompletedSessionIds` 钩子。
|
||||
|
||||
完成跟踪订阅已有 `api-session/status` 事件,避免 running 到 idle 的变化在合批目录快照中丢失。Host 列表行(`ids`)建立初始与重连的 running 基线;目录合成行与 retained 行保留独立观察到的状态。pending 状态下的空目录不能证明 Session 已消失。更新规则如下:
|
||||
|
||||
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: a22ddcfb339e503d
|
||||
zh: a1f4fadb46fce1e7
|
||||
/agent-note-native-cua-objects-independent-of-evaluator-ownership/decision:
|
||||
en: 176a9c2f6040f2a1
|
||||
zh: 2617ec13d25de998
|
||||
en: d08345b0b22b0884
|
||||
zh: 18a843df211bcabc
|
||||
/agent-note-native-cua-objects-independent-of-evaluator-ownership/alternatives-considered:
|
||||
en: 3d0bc77e3c432cb9
|
||||
zh: 50a20eda1811f16c
|
||||
en: f2bb7165b7c168a0
|
||||
zh: e6234e3464d971ee
|
||||
/agent-note-native-cua-objects-independent-of-evaluator-ownership/consequences:
|
||||
en: 528c644d5810e60b
|
||||
zh: 9649dfc3b1172a6d
|
||||
@@ -14,7 +14,7 @@ The shared `cua` library owns application/window objects, consent, and logged di
|
||||
|
||||
The experimental CUA package owns a native-app subset of the Codex-style object interface and selected MIT-licensed macOS behavior adapted from Cua Driver in a Swift helper. A source manifest records the adapted upstream files and local implementation. The helper is locally compiled; the package has no external Cua Driver runtime dependency. The existing [provider registration](2026-09-12-computer-use-provider-registration.md) prevents competing computer-use providers within one composition.
|
||||
|
||||
The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. CUA defines no persistence directive, worker or run_code replacement.
|
||||
The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. The object API defines no persistence directive or evaluator; [CUA programs outside PTC](2026-11-09-cua-program-tool.md) supersedes the original exclusion of a dedicated program entry by composing the shared PTC factory and Node runtime.
|
||||
|
||||
Native process ownership follows the [shared helper decision](2026-10-09-cua-shared-native-helper.md), with isolated Agent connections. App handles bind process identity and kernel start time; replacing the process or helper never revives old handles. The native helper retains per-app and per-window snapshots. The [object API](2026-11-05-cua-scoped-surfaces-and-input.md) keeps the latest successful observation per application handle. Coordinate actions select an owned window; the Host maps [screenshot coordinates](2026-10-13-cua-hover-routes-and-coordinates.md) to native window-local points. Providers declare keyboard scopes in `keyboard`. macOS supports keyboard input at the application's current focus.
|
||||
|
||||
@@ -22,7 +22,7 @@ The operation schema owns shared data declarations. Host-only limits and launch
|
||||
|
||||
Clipboard paste is distinct from Unicode key input: Return and Tab key events can trigger actions instead of inserting clipboard content. Pasteboard access runs on the AppKit main actor and retains promised data until a reader requests it. AX command completion alone does not establish that the application has fetched the data. Restoration checks ownership before replacing contents; the caller still verifies the application result. After successful command dispatch, `pasteReadTimeoutMs` bounds waiting for a data request, with a default of 1000 ms. Expiry returns `PASTE_NOT_CONSUMED`, closes the data provider against late delivery, and restores the clipboard only while still owned. The failure reports no read within that interval; it does not prove the application will never process its queued Paste command. A delayed command may read restored clipboard contents, so callers inspect the target and never retry automatically. Foreground-dependent consumption was observed in the installed ChatGPT/Codex application (`com.openai.codex`); other applications need their own validation. Guidance presents this as an example and applies recovery instructions to any `PASTE_NOT_CONSUMED` result.
|
||||
|
||||
CUA registers its own Harness tool and returns operation values directly. Screenshot capture requires a resolved image-capable model and the shared attachment service. The tool admits each screenshot once and renders its durable image reference; the window object and image sink retain the same `CuaScreenshot` containing encoded `bytes`, `mimeType`, `pixelWidth`, `pixelHeight` and `windowId` from the validated screenshot result. The bridge preserves this metadata without another upload or image emission. Callers use the reported format and dimensions when saving or declaring images.
|
||||
CUA registers its own Harness tool and returns operation values directly. Screenshot capture requires a resolved image-capable model and the shared attachment service. The attachment pipeline stores the screenshot at the dimensions used for coordinate mapping; the native tool result describes its encoded format and pixels. The program facade returns observation results, including the stored Image for a screenshot. The [explicit PTC output decision](2026-11-09-explicit-ptc-output.md) owns image identity and caller-selected display.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -32,7 +32,7 @@ A CUA-specific persistent evaluator duplicates execution lifecycle policy and pr
|
||||
|
||||
Reusing the MCP result adapter would impose MCP envelopes and wire validation on native CUA operations. Direct Harness tool output and shared attachment admission provide the needed logging and images without a second protocol.
|
||||
|
||||
**Fixing the screenshot format** would require otherwise unnecessary re-encoding and discard the attachment pipeline’s pass-through optimization. A format convention alone still forces callers to guess, and cannot tell them when encoding policy changes. Returning the already computed format and dimensions preserves pass-through and makes each result describe its actual bytes.
|
||||
**Fixing the screenshot format** would require otherwise unnecessary re-encoding and discard the attachment pipeline’s pass-through optimization. The native result describes its encoding; program Images expose the stored file and its pixel dimensions, so callers can use the file without a facade-specific byte representation.
|
||||
|
||||
**Waiting until the full native-operation timeout** hides successful command dispatch behind a generic timeout. A separate configurable read budget reports the missing acknowledgement without treating slow applications as unsupported. Requiring every application to be foreground would claim a prerequisite that the available observations do not establish.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Computer-use 程序需要一致的应用和窗口操作。将这些操作与 CUA
|
||||
|
||||
实验 CUA 包提供 Codex 风格的原生应用对象接口,并在 Swift 辅助进程中改写 Cua Driver 中选取的 MIT 许可 macOS 行为。源码清单记录改写的上游文件和本地实现。辅助进程在本地编译,本包不依赖外部 Cua Driver 运行时。已有的 [provider 注册机制](2026-09-12-computer-use-provider-registration.zh.md)防止同一组合中出现竞争 provider。
|
||||
|
||||
对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。CUA 不定义持久化指令、执行 worker 或 run_code 替代实现。
|
||||
对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。对象 API 不定义持久化指令或求值器;[PTC 之外的 CUA 程序](2026-11-09-cua-program-tool.zh.md)通过组合共享 PTC 工厂和 Node 运行时,取代原先不提供专用程序入口的决定。
|
||||
|
||||
原生进程归属遵循[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md),Agent 连接保持隔离。应用句柄绑定进程身份及内核启动时间,替换进程或辅助进程不会使旧句柄重新有效。原生 helper 按应用和可选窗口保存快照。[对象 API](2026-11-05-cua-scoped-surfaces-and-input.zh.md) 为每个应用句柄保留最近一次成功读取的快照。坐标操作选择属于该应用的窗口;Host 按[截图坐标规则](2026-10-13-cua-hover-routes-and-coordinates.zh.md)换算为原生窗口内 point。提供方通过 `keyboard` 声明可用范围。macOS 仅支持向应用当前焦点发送键盘输入。
|
||||
|
||||
@@ -22,7 +22,7 @@ Computer-use 程序需要一致的应用和窗口操作。将这些操作与 CUA
|
||||
|
||||
剪贴板粘贴与 Unicode 按键输入分别实现,因为 Return 和 Tab 按键可能触发动作,而不是插入剪贴板内容。剪贴板访问使用 AppKit 主线程,保留延迟提供的数据直到读取方请求。AX 命令完成本身不能证明应用已取得数据。恢复前检查剪贴板归属;调用方仍需验证应用中的结果。 命令成功分派后,`pasteReadTimeoutMs` 限制等待数据请求的时间,默认 1000 毫秒。到期返回 `PASTE_NOT_CONSUMED`,关闭数据提供方以阻止迟到的数据交付,并仅在仍持有剪贴板时恢复原内容。该失败只说明这段时间内没有读取,不证明应用以后不会处理已排队的 Paste 命令。迟到的命令可能读取恢复后的剪贴板内容,因此调用方必须检查目标,不能自动重试。已安装的 ChatGPT/Codex 应用(`com.openai.codex`)已观察到依赖前台才能读取的行为,其他应用需要分别验证。指引将其写为例子,并对任何 `PASTE_NOT_CONSUMED` 结果提供恢复步骤。
|
||||
|
||||
CUA 注册自己的 Harness 工具,直接返回操作结果。截图要求解析到支持图片输入的模型,并提供共享附件服务。工具只接入一次截图,再渲染持久图片引用;窗口对象和图片输出回调保留同一个 `CuaScreenshot`,其中的编码 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 来自已校验的截图结果。桥接保留这些元数据,不再次上传或输出图片。调用方落盘或声明图片时使用返回的格式和尺寸。
|
||||
CUA 注册自己的 Harness 工具,直接返回操作结果。截图要求解析到支持图片输入的模型,并提供共享附件服务。附件流水线按坐标换算使用的尺寸保存截图,原生工具结果描述编码格式和像素。程序对象接口返回观察结果,截图操作返回已存储的 `Image`。[PTC 显式输出决策](2026-11-09-explicit-ptc-output.zh.md)负责图片身份及调用方选择展示的规则。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
@@ -32,7 +32,7 @@ CUA 专用持久执行器会重复实现执行生命周期规则,使 PTC 无
|
||||
|
||||
复用 MCP 结果适配器会给原生 CUA 操作引入 MCP 信封和协议校验。直接使用 Harness 工具输出与共享附件接入,即可取得所需的日志和图片能力,无需再经过一种协议。
|
||||
|
||||
**固定截图格式**会要求原本不需要的重新编码,并失去附件处理的原样直通优化。仅约定格式仍要求调用方猜测,也无法告知编码策略的变化。返回已经算出的格式和尺寸,既保留直通优化,也让每个结果说明其实际字节。
|
||||
**固定截图格式**会要求原本不需要的重新编码,并失去附件处理的原样直通优化。原生结果描述编码格式;程序 Image 提供已存储文件及其像素尺寸,使调用方直接使用文件,无需对象接口专属的字节表示。
|
||||
|
||||
**等到原生操作的总超时**会用一条通用超时掩盖命令已经成功分派的事实。独立、可配置的读取等待上限能报告缺失的读取确认,而不将响应慢的应用认定为不支持粘贴。要求所有应用都必须位于前台,则超出了现有观察能支持的结论。
|
||||
|
||||
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: 2ba6c43b20a3d347
|
||||
zh: 5647179ddaa38ad9
|
||||
/agent-note-ship-experimental-capabilities-as-optional-bundles/decision:
|
||||
en: 191ca8bffb101db2
|
||||
zh: 1365bef5cd830a5c
|
||||
en: b11a4c9cb060d4bb
|
||||
zh: a5250cfaba937e71
|
||||
/agent-note-ship-experimental-capabilities-as-optional-bundles/alternatives-considered:
|
||||
en: d6f40bf02df37ab7
|
||||
zh: e5b85ce9d41e8754
|
||||
/agent-note-ship-experimental-capabilities-as-optional-bundles/consequences:
|
||||
en: 3064da835e892958
|
||||
zh: bfcf967b6acc6f85
|
||||
en: 49e2c3f9f641c38b
|
||||
zh: 3aa772fb43c4bb6e
|
||||
+2
-2
@@ -12,7 +12,7 @@ The Web plugin page offered two optional bundles, Agent Teams and voice input. A
|
||||
|
||||
`OPTIONAL_BUNDLES` owns the installation's default-off selections, including maintained optional capabilities and experimental capabilities. Every bundle declares `icon` and exports `./locale/*.json` with `meta.title` and `meta.description`; the [plugin manager page](../../../../packages/client/ui-plugin-manager/README.md#use-this-package) displays that metadata for eligible bundles and retains explicit activation for default-hidden ones. A bundle's presentation does not determine its [experimental status](../../../../packages/experimental/README.md#status). The isolation check validates admission and still rejects experimental dependencies of nonexperimental bundles.
|
||||
|
||||
An optional bundle's dependencies are downloaded with every `dsh` installation. [Reasoning translation](2026-10-05-anonymous-reasoning-translation.md) uses three experimental packages without adding third-party runtime dependencies. Admission therefore considers installation cost and whether a switch supplies a usable composition without an additional configuration form. External browser and Cua Driver providers remain explicit compositions because they add substantial runtimes or require an external executable. Stagehand requires model credentials; Python PTC replaces a core provider and conflicts with TypeScript workflow consumers. Demonstrative hooks, webhooks, and mods stay outside the list. [Session Inspector](../feature/2026-09-24-session-inspector.md) owns the Inspector's distinct activation behavior.
|
||||
An optional bundle's dependencies are downloaded with every `dsh` installation. [Reasoning translation](2026-10-05-anonymous-reasoning-translation.md) uses three experimental packages without adding third-party runtime dependencies. Admission therefore considers installation cost and whether a switch supplies a usable composition without an additional configuration form. External browser and Cua Driver providers remain explicit compositions because they add substantial runtimes or require an external executable. Stagehand requires model credentials. Demonstrative hooks, webhooks, and mods stay outside the list. [Session Inspector](../feature/2026-09-24-session-inspector.md) owns the Inspector's distinct activation behavior.
|
||||
|
||||
Bundles insert ordinary Host rows; optional model tools register in the global tool layer, so every preset, including minimal, receives them. Plugin management, profile composition, and reload need no bundle-specific behavior. Search, Ralph, and terminals supply their own isolated services in a Host group. Search opens one in-memory index on demand; the Host search policy stays unchanged. Badge skills and title providers act on the Host. Switching a bundle registers or removes its tools for live Agents, and later user patch layers retain precedence. A replacement title provider may register once the previous provider's disposal starts; the previous provider's late results never commit.
|
||||
|
||||
@@ -34,4 +34,4 @@ Computer Use is a shipped optional bundle in the experimental group. Its bundle
|
||||
|
||||
Official discovery does not imply experimental status or a different plugin lifecycle. Switching a bundle off keeps its installed files; failed activation retains the existing saved-selection behavior. Bundle rows are ordinary Host rows with their usual switches. Individual and combined composition tests cover the Host rows and every preset's tool catalog; live switching and recorded Sessions cover activation and model-visible behavior.
|
||||
|
||||
Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes whose bound preset is `ptc`. Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution.
|
||||
Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes. The preset named by `agentPreset` receives raw `cua`; other composed presets receive the [CUA program tool](2026-11-09-cua-program-tool.md). Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution.
|
||||
+2
-2
@@ -12,7 +12,7 @@ Web 插件页只提供两个可选 bundle:Agent Teams 与语音输入。Auto r
|
||||
|
||||
`OPTIONAL_BUNDLES` 管理安装随附且默认关闭的选项,包括维护中的可选能力与实验性能力。每个 bundle 声明 `icon`,并导出带 `meta.title` 与 `meta.description` 的 `./locale/*.json`;[插件管理页](../../../../packages/client/ui-plugin-manager/README.zh.md#use-this-package)为符合展示条件的组合包显示这些元数据,并保留默认隐藏项的显式启用入口。Bundle 的展示方式不决定其[实验性状态](../../../../packages/experimental/README.zh.md#status)。隔离检查校验准入,并继续拒绝非实验 bundle 的实验性依赖。
|
||||
|
||||
可选 bundle 的依赖随每次 `dsh` 安装下载。[思考过程翻译](2026-10-05-anonymous-reasoning-translation.zh.md)使用三个实验包,不增加第三方运行时依赖。因此准入需要考虑安装成本,以及开关能否在不增加配置表单的情况下提供可用组合。外部浏览器与 Cua Driver 提供方仍使用显式组合,因为它们会增加较大的运行时或要求外部可执行文件。Stagehand 需要模型凭据;Python PTC 替换核心提供方,并与 TypeScript workflow 消费方冲突。演示性钩子、webhook 与模组不进入名单。[Session Inspector](../feature/2026-09-24-session-inspector.zh.md) 管理 Inspector 特有的激活行为。
|
||||
可选 bundle 的依赖随每次 `dsh` 安装下载。[思考过程翻译](2026-10-05-anonymous-reasoning-translation.zh.md)使用三个实验包,不增加第三方运行时依赖。因此准入需要考虑安装成本,以及开关能否在不增加配置表单的情况下提供可用组合。外部浏览器与 Cua Driver 提供方仍使用显式组合,因为它们会增加较大的运行时或要求外部可执行文件。Stagehand 需要模型凭据。演示性钩子、webhook 与模组不进入名单。[Session Inspector](../feature/2026-09-24-session-inspector.zh.md) 管理 Inspector 特有的激活行为。
|
||||
|
||||
Bundle 插入普通 Host 行;可选模型工具注册到全局工具层,因此包括 minimal 在内的所有预设都会获得它们。插件管理、profile 组合与重载无需针对 bundle 的特殊行为。搜索、Ralph 与终端在 Host 组内提供自己的隔离服务。搜索按需打开一个内存索引;Host 搜索策略保持不变。徽章技能与标题提供方作用于 Host。切换 bundle 会为运行中的 Agent 注册或移除其工具,后续用户 patch 层继续优先。前一个标题提供方开始清理后,替代提供方即可注册;前一个提供方的迟到结果不会提交。
|
||||
|
||||
@@ -34,4 +34,4 @@ Computer Use 是 experimental 包组内随安装提供的可选组合包。组
|
||||
|
||||
官方发现不表示实验性状态,也不引入不同的插件生命周期。关闭 bundle 保留已安装文件;激活失败保留现有的已保存选择行为。Bundle 行是普通 Host 行,使用常规开关。独立与组合测试覆盖 Host 行及每个预设的工具目录;实时切换与已记录 Session 覆盖激活和模型可见行为。
|
||||
|
||||
Computer Use 将权限服务和原生提供方保留在 Host,在已绑定 `ptc` preset 的 Agent 作用域中注册工具。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。
|
||||
Computer Use 将权限服务和原生提供方保留在 Host,并在 Agent 作用域中注册工具。`agentPreset` 指定的 preset 获得原始 `cua`;其他已组合的 preset 获得 [CUA 程序工具](2026-11-09-cua-program-tool.zh.md)。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: ab63c8127d68d294
|
||||
zh: d3f99489c96ff1d4
|
||||
/agent-note-open-the-session-when-migration-is-required/decision:
|
||||
en: 32627d744a6e7410
|
||||
zh: 2836a95ee5390111
|
||||
en: 310ff84cece51901
|
||||
zh: a9a29e3ba30e03a8
|
||||
/agent-note-open-the-session-when-migration-is-required/alternatives-considered:
|
||||
en: baea781018a49252
|
||||
zh: bcc452029bf229fd
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ Other fork callers omit that option and allow automatic migration.
|
||||
|
||||
The `formatStatus` returned by `stat` carries the migration library's existing classification; `header` remains the current logical format. It describes the stored format, not migration-task progress or prepared in-memory history.
|
||||
|
||||
When migration is required and `subagentCatalog` is absent, Web marks the Session's row “Migration required” and keeps its history-opening actions without descendant expansion or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
|
||||
When migration is required and `subagentCatalog` is absent, Web keeps the Session row's history-opening actions without a format notice, descendant expansion, or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
|
||||
|
||||
Create/adopt, full-text search, and ordinary history opening allow automatic migration.
|
||||
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Ho
|
||||
|
||||
`stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。
|
||||
|
||||
在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
|
||||
在需要迁移且缺少 `subagentCatalog` 时,Web 保留该会话行打开历史的操作,不显示格式提示,不展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
|
||||
|
||||
create/adopt、全文搜索和普通历史打开允许自动迁移。
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
en: cdc04139c8d69415
|
||||
zh: a3fe3e78ada08d95
|
||||
/agent-note-continuous-cua-hover-without-cross-call-ownership/decision:
|
||||
en: 125c860c1c568960
|
||||
zh: 8a2ece1101358200
|
||||
en: 193acf8c23672457
|
||||
zh: e614884d52585b16
|
||||
/agent-note-continuous-cua-hover-without-cross-call-ownership/alternatives-considered:
|
||||
en: 18d917ee2e909b93
|
||||
en: df67e547bce2f289
|
||||
zh: 5b5ad0530f138cda
|
||||
/agent-note-continuous-cua-hover-without-cross-call-ownership/consequences:
|
||||
en: 714789d0a472a308
|
||||
|
||||
@@ -10,7 +10,7 @@ Hover interactions span movement, delayed content, observation and input inside
|
||||
|
||||
## Decision
|
||||
|
||||
An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement with `systemPointerHover` enabled. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before allowing opt-in system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check.
|
||||
An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button. With session approval, system-pointer movement also works on disabled controls. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) requires foreground and mouse-hit checks for system movement. It never activates or raises the app implicitly. Other input or window changes can race that check.
|
||||
|
||||
The [shared helper](2026-10-09-cua-shared-native-helper.md) serializes complete individual operations. It grants no application ownership across calls. Earlier arrival, a retained app object and Session lifetime do not establish task priority. Waiting for the model does not reserve the application. Explicit task coordination determines any required execution order.
|
||||
|
||||
@@ -20,7 +20,7 @@ The [shared helper](2026-10-09-cua-shared-native-helper.md) serializes complete
|
||||
|
||||
**Click or drag as hover** introduces button input that can activate a control, select text or dismiss a popup. Hover requires a separate unpressed movement operation.
|
||||
|
||||
**PID-directed virtual movement** can display Chromium hover content after prior interaction, but a fresh window can ignore it, and later pointer checks can dismiss the content. Native AppKit tracking also requires real pointer movement in the measured fixture. The system-pointer fallback avoids reporting this unreliable event route as continuous hover.
|
||||
**PID-directed virtual movement** can display Chromium hover content after prior interaction, but a fresh window can ignore it, and later pointer checks can dismiss the content. Native AppKit tracking also requires real pointer movement in the measured fixture. The approved system-pointer route avoids reporting this unreliable event route as continuous hover.
|
||||
|
||||
## Consequences
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,启用 `systemPointerHover` 后可通过系统鼠标悬停禁用控件。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,只有启用该配置时才回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。
|
||||
显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,用户授权当前会话移动鼠标后,也可悬停在禁用的控件上。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)要求移动系统鼠标前检查前台应用和鼠标命中的窗口,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。
|
||||
|
||||
[共享 helper](2026-10-09-cua-shared-native-helper.zh.md)串行执行完整的单次操作,不分配跨调用的应用所有权。先发起请求、持有 app 对象和 Session 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: f96bf1ebc0719fb0
|
||||
zh: e9a1144f0e76572d
|
||||
/agent-note-background-hover-and-screenshot-coordinates/decision:
|
||||
en: bdf4d3386521ce00
|
||||
zh: 96db93177ad96a76
|
||||
en: 36188669cfa9af11
|
||||
zh: f1f0cba1ebb18f49
|
||||
/agent-note-background-hover-and-screenshot-coordinates/alternatives-considered:
|
||||
en: 5fc4beaf79761c50
|
||||
zh: 4948333b0020be28
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ Hover-only controls can sometimes be revealed without moving the user's pointer.
|
||||
|
||||
## Decision
|
||||
|
||||
Native hover first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route returns `HOVER_UNAVAILABLE` by default. Enabling `systemPointerHover` permits the real system pointer fallback. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md).
|
||||
By default, native hover uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route returns `HOVER_UNAVAILABLE` by default. With `requireSystemPointerApproval` enabled, the first explicit `mouseMove(target, { useSystemPointer: true })` asks the user. Each physical move requires an explicit request, even after approval. The live session remembers the decision until the session closes or DSH restarts. This lets a caller reach pointer-tracking controls even when the same target also advertises AX alternate UI. The Host selects real input only for a move that requests it and meets the approval policy. Physical movement leaves the visibility of previously revealed controls to the application, so switching routes cannot dismiss a target before dispatch. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md).
|
||||
|
||||
Model-facing coordinate input defaults to pixels in the returned screenshot. `relative: true` accepts integer thousandths from 0 to 999 for `click`, `mouseMove`, `scroll` and `drag`; it does not apply to opaque element IDs. The Host owns the mapping to native window points. An application-wide observation refreshes its inventory; a scoped observation preserves other windows' image mappings. Window resizing invalidates the old image, while movement preserves local coordinates. Relative endpoints remain inside the window and do not depend on screenshot resolution.
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时默认返回 `HOVER_UNAVAILABLE`。启用 `systemPointerHover` 后才允许移动系统光标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。
|
||||
默认情况下,原生悬停会寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时默认返回 `HOVER_UNAVAILABLE`。启用 `requireSystemPointerApproval` 时,首次显式调用 `mouseMove(target, { useSystemPointer: true })` 会询问用户。即使用户已授权,每次移动系统光标仍需显式请求。会话记住授权决定,直到关闭会话或重启 DSH。有些控件既支持 AX 备用界面,又跟踪真实鼠标。只有本次调用显式请求系统鼠标并满足授权条件时,Host 才使用真实鼠标触发跟踪。切换到系统鼠标后,由应用决定是否收起先前展开的控件,以免派发前目标消失。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。
|
||||
|
||||
面向模型的坐标默认使用返回截图中的像素。`click`、`mouseMove`、`scroll` 和 `drag` 传入 `relative: true` 时接受 0~999 的千分比整数,仅用于坐标目标。Host 负责换算原生窗口 point。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。
|
||||
|
||||
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: f72db0b79aa02fb5
|
||||
zh: b91c1f177dc93ab4
|
||||
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision:
|
||||
en: ec115e11f96ffe60
|
||||
zh: c1fe9eb2866196d0
|
||||
en: 41fd533d5be7642b
|
||||
zh: c6fcbabec22bdbb7
|
||||
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered:
|
||||
en: 32c970ae153e0f6c
|
||||
zh: 8431be0a10ffed15
|
||||
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences:
|
||||
en: 5c6ec60b77f1bff0
|
||||
zh: e1ae568ef3501b7b
|
||||
en: c4b12ca80865e670
|
||||
zh: 396426fad0105eaa
|
||||
@@ -16,7 +16,7 @@ Provider startup capabilities are static. Platform, supported methods, applicati
|
||||
|
||||
Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names.
|
||||
|
||||
Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime.
|
||||
Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; native window operations reject closed or foreign windows. An explicit `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps
|
||||
|
||||
Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first.
|
||||
|
||||
Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, because the API never sends the opposite event. Keyboard modifier names are provider-defined, so the same string may have different support across providers.
|
||||
Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, during execution. macOS releases that run’s remaining keys when the program ends or the user pauses it. Keyboard modifier names are provider-defined, so the same string may have different support across providers.
|
||||
|
||||
Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock.
|
||||
+2
-2
@@ -16,7 +16,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
|
||||
|
||||
键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。
|
||||
|
||||
在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。
|
||||
在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;原生窗口操作会拒绝已关闭或属于其他应用的窗口。显式 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
@@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
|
||||
|
||||
元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。
|
||||
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
|
||||
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-computer-use-mcp-server.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server:
|
||||
en: 1e4562a8dd533e1f
|
||||
zh: 4e41a369a3a88f02
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/problem:
|
||||
en: 6050884223e0e491
|
||||
zh: eb808c298c9fb652
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/decision:
|
||||
en: ab004152e8a43f7d
|
||||
zh: 2eb2de8b91d8c405
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/alternatives-considered:
|
||||
en: 7bba46bed1b1baa3
|
||||
zh: 54f31bd327ee222d
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/consequences:
|
||||
en: 74494a208b1909f9
|
||||
zh: 0e4378667c751f54
|
||||
@@ -0,0 +1,55 @@
|
||||
# Agent Note: Serve Computer Use to other harnesses as an MCP server
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-computer-use-mcp-server.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Computer Use training data should come from several agent harnesses, not only from DSH sessions. Codex, Claude Code, and in-house harnesses connect to capabilities through MCP stdio servers; Codex's own Computer Use is a stdio server with a persistent JavaScript REPL. DSH's `cua_run_code` already composes a retained program environment, consent, screenshots, and native connections per Agent, but only a DSH model turn could call it. The MCP form must keep those owners, persist program state across calls, and start from one documented command on every DSH distribution.
|
||||
|
||||
## Decision
|
||||
|
||||
`@deepseek-ai/dsh-cua-mcp` is an experimental bundle in `OPTIONAL_BUNDLES` that composes the standalone `cua-mcp` profile from one insert over the empty root. A profile manifest that selects it as the only bundle is the whole installation step: the launcher loads an existing manifest without consulting `PROFILE_TEMPLATES`, and the installation already ships the bundle, so no pnpm or registry access is involved. It is the only MCP application path; no package bin or SDK escape exists, and the bundle stays out of `PROFILE_TEMPLATES` because templates cannot name experimental packages.
|
||||
|
||||
The server runs inside the profile process and calls `ctx.tools.execute` with the connection's Agent and no model step. One stdio connection owns one Agent: creation before the stdio transport opens, disposal at stdin EOF. Each program call runs as that Agent's maintenance activity, so Agent disposal cancels an in-flight call and waits for it and its nested calls before the Session closes. Agent ownership already selects the retained program process, native connection, and session-scoped grants, so connection lifetime and state lifetime coincide. The empty default preset `cua-mcp` gives that Agent `cua_run_code` and nothing else, because the provider registers program tools only for composed presets. The Agent works in a dedicated workspace, `DSH_CUA_WORKSPACE` or `cua-mcp/workspace` under the Harness home: an Agent's working directory is the `workspace-write` root of its programs, and the directory a client launches the server from can be `/`.
|
||||
|
||||
Three tools form the surface. `cua_run_code` is the Agent's DSH registration served through the protocol server's low-level `tools/list` and `tools/call` handlers: each listing projects name, description, and parameters from the tool registry, and a call passes its arguments to the tool executor unchanged inside the Agent's initiator scope, so the provider's definition is the only schema, `description` is required as that definition declares, and validation and unknown names are answered by DSH; the one trim is the registration's sandbox-escalation fields, which the projection omits and a call may not name. `cua_get_api_reference` returns the `cua` API reference, the provider's guidance registered for the Agent, and keeps no state, so any conversation on the connection can read it at any time. `cua_reset` ends the Agent's program environment and keeps the Agent: the frontend cancels the running program and calls `ctx.cuaPrograms.release`, with which the provider's program runtime releases the environment of that state owner and which the CUA provider exposes beside `screenshotRequestTarget`; the next program starts a fresh process, while the native connection and the session's consent decisions stay. The frontend orders its own calls around the release: a reset answers after the cancelled program has settled, and programs wait for a release in progress. The projection delivers each inspected screenshot as the request version the program observed, so coordinates in program text match the delivered image. The provider's new `screenshotTarget` configuration replaces the model-route lookup that a profile without a model cannot satisfy.
|
||||
|
||||
Consent has two modes. `DSH_CUA_CONSENT=allow` answers every approval question of the connection's Agent with its approving label for the session. The default `elicit` forwards each question to the client as a form elicitation whose enum is the question's labels. No Session event is added: the training side consumes MCP tool results, and the connected harness's transcript records calls; DSH retains nested `tool/ptc-dispatch` events for diagnosis.
|
||||
|
||||
The composition lists its dependency closure, twenty-six rows, instead of layering on `dsh-base`: no model adapter, prompt-side tool, telemetry, or session-management row loads. `cua-mcp` is not a required startup entry, so a row that cannot activate is reported by the launcher on stderr: an inactive provider leaves `cua_run_code` out of the listing, and an inactive frontend serves nothing. Client entries are documented in the README instead of generated.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**An MCP server that launches `dsh --profile sdk` through the TypeScript SDK.** The SDK protocol has no request that runs a tool without a model turn; adding one changes the protocol and both SDK clients, and screenshots would cross a second process boundary.
|
||||
|
||||
**A standalone CUA server outside the harness, like Codex's REPL.** Consent, sandboxing, logging, screenshot admission, and helper lifecycle would be rewritten. The in-profile server reuses those owners and remains the basis for a later extraction.
|
||||
|
||||
**A `turn_ended` hidden tool with client hooks.** Its only use would be writing the client's turn boundaries into a log nobody consumes; held keys already release when a program settles.
|
||||
|
||||
**Session events for root MCP calls.** The data consumers need only MCP results; a `tool/call` without a model step would invent a step the Session never ran.
|
||||
|
||||
**Exposing the raw `cua` tool or program sandbox escalation.** Raw operations need per-method schemas the external model would relearn, and escalation needs an approval answerer the profile does not have.
|
||||
|
||||
**A profile frontend layered on `dsh-base` with model rows disabled.** The composed profile carried about a hundred rows without a consumer: model adapters, web tools, subagents, compaction, telemetry, and session management. The explicit closure is a quarter of that and fails loud on drift.
|
||||
|
||||
**A `dsh plugin enable|disable` subcommand that selects the shipped bundle.** It duplicated the plugin manager's manifest-only selection inside the launcher and still produced a base-backed profile; the documented manifest is three lines and needs no launcher change.
|
||||
|
||||
**A `dsh.bundle.profile` declaration that app-boot initializes on the first `dsh --profile cua-mcp`.** It made the first start zero-step, at the price of a new manifest field and a `shippedProfileTemplate` lookup in app-boot, the CLI `dsh plugin` command, and the plugin manager for one experimental bundle; the plain manifest costs one documented step and leaves those packages untouched. Once CUA graduates from experimental, a `PROFILE_TEMPLATES` entry gives the same zero-step start.
|
||||
|
||||
**A hand-written MCP schema and description for `cua_run_code`.** The second copy drifted within days: 663 against 2,164 characters of description and an optional against a required `description`. Projecting the registration removes the copy; the SDK's `registerTool` accepts only Standard Schema values and refuses to share `tools/list` and `tools/call` with custom handlers, so both tools use the low-level handlers.
|
||||
|
||||
**The `cua` API reference inside the tool description or the server instructions.** Claude Code 2.1.309 forwards the first 4,096 characters of an MCP tool description, and of the server instructions, and appends `… [truncated]`, measured on 2026-11-10 with 20,000-character probe texts; `dsh-mcp-client` forwards the same description intact. The reference is about 13,000 characters, so it travels as a tool result, and the registration's 3,200-character description stays within the budget.
|
||||
|
||||
**The reference at the head of the first program result of each environment.** The server cannot observe which results a model keeps: a client such as `dsh-mcp-client` holds one connection for several conversations, a cancelled or failed first call discards its result, and context compaction drops the text later. The flag that recorded delivery was written by program calls and by resets without a common ordering point. A read tool without state lets the model that lacks the reference ask for it; in fifteen probe conversations on 2026-11-11, through `dsh-mcp-client` with a DeepSeek model and through Claude Code 2.1.309, every model called it before its first program.
|
||||
|
||||
**A reset operation on the PTC program-tool factory.** A factory handle with `reset(agent)` made the tool executor a second owner of environment recovery, with its own blocked state after a failed cleanup. The program runtime's owner release already ends an environment, and the next run for the same owner starts a new one; the frontend serializes the connection's calls, so it is the caller that orders them around the release.
|
||||
|
||||
**Replacing the connection's Agent on reset.** A new Agent has a new Session: the native connection closes, session consent is asked again, and a refusal is forgotten, which is what reconnecting does. A reset discards what programs hold; consent and the native connection belong to the connection and are no part of the program environment. Disposing an Agent also waits for the runtime's stop grace, three seconds by default, when the running program cannot be interrupted.
|
||||
|
||||
**A `--print-client-config codex|claude-code|json` option.** Rendering the exact command of an installation needs `node:sea` to tell a single-file executable from a script launch, and the browser worker image, which packs every optional bundle, registers no `node:sea`; the documented entries carry the same timeouts and output budget without that dependency.
|
||||
|
||||
## Consequences
|
||||
|
||||
Every installation carries the bundle; its native providers, macOS and Windows, are optional dependencies, each mounted by a row that loads only on its own Host, and `verify-default-product-isolation` keeps the bundle out of default templates. A profile that layers the bundle over `dsh-base` duplicates row ids and is unsupported; the Web plugin page hides the bundle through `HIDDEN_BUNDLES` while the Host inventory still reports it as optional. Hosts without a provider list `cua_get_api_reference` and `cua_reset`, which both name the missing provider, and a `cua_run_code` call fails as `unknown tool`. Clients see state loss on process exit, `cua_reset`, or Agent disposal and recreate objects. Consent elicitation depends on the 2025 MCP request model; clients on the 2026-07-28 revision use `allow`. The tool descriptions, the server instructions, and the reference text are pinned by the profile's expected-output test; the program description and the reference change with the installed CUA packages. A model receives the reference only by calling `cua_get_api_reference`, so a client that withholds that tool leaves it with the execution rules alone. A provider description longer than 4,096 characters reaches Claude Code models cut.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Agent Note: 以 MCP 服务器向其他 harness 提供 Computer Use
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-computer-use-mcp-server.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会话。Codex、Claude Code 以及内部 harness 通过 MCP stdio 服务器接入能力;Codex 自己的 Computer Use 就是一个带持久 JavaScript REPL 的 stdio 服务器。DSH 的 `cua_run_code` 已经按 Agent 组合了保留的程序环境、授权、截图和本机连接,但只有 DSH 的模型回合能调用它。MCP 形态必须保留这些所有者,在多次调用间持久化程序状态,并且在每种 DSH 分发中都能从一条有文档的命令启动。
|
||||
|
||||
## 决策
|
||||
|
||||
`@deepseek-ai/dsh-cua-mcp` 是 `OPTIONAL_BUNDLES` 中的实验性组合包:它在空 profile 根上用一次 insert 组成独立的 `cua-mcp` profile。只选它这一个组合包的 profile manifest 就是全部安装步骤:启动器加载已存在的 manifest 时不查 `PROFILE_TEMPLATES`,而安装本身已自带该组合包,因此不涉及 pnpm 或 registry。这是唯一的 MCP 应用路径;没有包 bin 或 SDK 逃逸,该组合包不进入 `PROFILE_TEMPLATES`,因为模板不能引用实验包。
|
||||
|
||||
服务器运行在 profile 进程内,带着连接的 Agent、不经模型步骤地调用 `ctx.tools.execute`。一个 stdio 连接拥有一个 Agent:在 stdio 传输打开之前创建,stdin EOF 时销毁。每次程序调用都作为该 Agent 的维护活动运行,因此 Agent 销毁时会取消进行中的调用,并等它及其嵌套调用结算之后才关闭 Session。Agent 归属已经决定了保留的程序进程、本机连接和会话级授权,因此连接生命周期与状态生命周期重合。空的默认 preset `cua-mcp` 让该 Agent 只获得 `cua_run_code`,因为提供方只为已组合 preset 注册程序工具。该 Agent 在专用工作区中工作,即 `DSH_CUA_WORKSPACE`,未设置时为 Harness home 下的 `cua-mcp/workspace`:Agent 的工作目录就是其程序的 `workspace-write` 根,而客户端启动服务器的目录可能是 `/`。
|
||||
|
||||
工具面由三个工具构成。`cua_run_code` 就是该 Agent 的 DSH 注册项,经协议服务器的低层 `tools/list` 与 `tools/call` handler 提供:每次列表都从工具注册表投影名称、描述和参数,调用则在 Agent 的 initiator 作用域内把参数原样交给工具执行器,因此提供方的定义是唯一 schema,`description` 按该定义必填,校验与未知名称由 DSH 回答;唯一的剪裁是注册项中的沙箱提权字段,投影省略它们,调用也不得指定。`cua_get_api_reference` 返回 `cua` API 参考,即提供方为该 Agent 注册的指引;它不保存状态,因此连接上的任何对话随时都能读取。`cua_reset` 结束该 Agent 的程序环境并保留 Agent:前端取消正在运行的程序,再调用 `ctx.cuaPrograms.release`,由提供方的程序运行时释放该 state owner 的环境,CUA 提供方把它与 `screenshotRequestTarget` 一起暴露;下一个程序在新进程中启动,本机连接和本会话的授权决定保留。前端围绕这次释放安排自己的调用:reset 在被取消的程序结算之后才返回,程序则等待进行中的释放。投影把每张被 inspect 的截图按程序观察到的请求版本交付,使程序文本中的坐标与交付的图片一致。提供方新增的 `screenshotTarget` 配置取代了没有模型的 profile 无法满足的模型路由查询。
|
||||
|
||||
授权有两种模式。`DSH_CUA_CONSENT=allow` 以批准标签为本会话回答连接 Agent 的每个审批问题。默认的 `elicit` 把每个问题作为表单 elicitation 转发给客户端,枚举即问题的选项标签。不新增任何 Session 事件:训练侧只消费 MCP 工具结果,接入 harness 的 transcript 记录调用;DSH 保留嵌套的 `tool/ptc-dispatch` 事件以供诊断。
|
||||
|
||||
组合列出自己的依赖闭包(26 行),而不是叠在 `dsh-base` 之上:不加载任何模型适配器、提示侧工具、遥测或会话管理行。`cua-mcp` 不是启动必需条目,无法激活的行由启动器在 stderr 上报告:提供方行未激活时列表里没有 `cua_run_code`,前端未激活时不提供任何服务。客户端配置项由 README 给出,而不是由程序生成。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**通过 TypeScript SDK 启动 `dsh --profile sdk` 的 MCP 服务器。** SDK 协议没有不经模型回合直接运行工具的请求;补上它要改协议和两个 SDK 客户端,截图还要再跨一次进程边界。
|
||||
|
||||
**像 Codex 的 REPL 那样在 harness 之外的独立 CUA 服务器。** 授权、沙箱、日志、截图接入和 helper 生命周期都要重写。profile 内的服务器复用这些所有者,并仍是日后剥离的基础。
|
||||
|
||||
**带客户端 hook 的隐藏工具 `turn_ended`。** 它唯一的用途是把客户端的回合边界写进无人消费的日志;按键在程序结束时已经释放。
|
||||
|
||||
**为根 MCP 调用写 Session 事件。** 数据消费方只需要 MCP 结果;没有模型步骤的 `tool/call` 会虚构一个 Session 从未运行的步骤。
|
||||
|
||||
**暴露原始 `cua` 工具或程序沙箱提权。** 原始操作需要外部模型重新学习的逐方法 schema,提权需要该 profile 不具备的审批应答者。
|
||||
|
||||
**叠在 `dsh-base` 之上、禁用模型行的 profile 前端。** 组合出的 profile 带着约一百行没有消费者的插件:模型适配器、web 工具、子代理、压缩、遥测和会话管理。显式闭包只有四分之一,且在漂移时大声失败。
|
||||
|
||||
**用 `dsh plugin enable|disable` 子命令选中随附组合包。** 它在启动器里重复了插件管理器的仅改 manifest 选择,而且仍然产生以 base 为底的 profile;文档给出的 manifest 只有三行,不需要改启动器。
|
||||
|
||||
**由 app-boot 在首次 `dsh --profile cua-mcp` 时初始化的 `dsh.bundle.profile` 声明。** 它让首次启动零步可用,代价是为一个实验组合包在 manifest 新增字段,并在 app-boot、CLI `dsh plugin` 命令和插件管理器里加入 `shippedProfileTemplate` 查找;普通 manifest 只多一个有文档的步骤,且不触碰这些包。CUA 从实验状态毕业后,一条 `PROFILE_TEMPLATES` 条目就能得到同样的零步启动。
|
||||
|
||||
**为 `cua_run_code` 手写 MCP schema 与描述。** 第二份定义几天内就漂移了:描述 663 对 2,164 个字符,`description` 可选对必填。投影注册项去掉了这份副本;SDK 的 `registerTool` 只接受 Standard Schema 值,且不允许 `tools/list`、`tools/call` 与自定义 handler 混用,所以两个工具都走低层 handler。
|
||||
|
||||
**把 `cua` API 参考放进工具描述或服务器说明。** Claude Code 2.1.309 对 MCP 工具描述和服务器说明都只转发前 4,096 个字符并追加 `… [truncated]`,2026-11-10 用 20,000 个字符的探针文本测得;`dsh-mcp-client` 原样转发同一描述。参考约 13,000 个字符,因此作为工具结果传递,注册项 3,200 个字符的描述留在预算之内。
|
||||
|
||||
**把参考放在每个环境首个程序结果的开头。** 服务器观察不到模型保留了哪些结果:`dsh-mcp-client` 这类客户端用一个连接承载多次对话,被取消或失败的首次调用会丢弃其结果,上下文压缩之后这段文本也会消失。记录已交付的标志由程序调用和重置两处写入,二者没有共同的排序点。无状态的只读工具让缺少参考的模型自己去取;2026-11-11 的十五次探针对话中,经 `dsh-mcp-client` 的 DeepSeek 模型与 Claude Code 2.1.309 都在首个程序之前调用了它。
|
||||
|
||||
**在 PTC 程序工具工厂上提供 reset 操作。** 带 `reset(agent)` 的工厂句柄让工具执行器成为环境恢复的第二个所有者,清理失败后还带着自己的阻塞状态。程序运行时的 owner release 本来就能结束一个环境,同一所有者的下一次运行会启动新环境;前端串行化该连接的调用,因此由它这个调用方围绕释放来安排这些调用。
|
||||
|
||||
**reset 时更换连接的 Agent。** 新 Agent 意味着新 Session:本机连接关闭,会话授权要重新询问,拒绝记录也被遗忘,这正是重新连接的效果。reset 丢弃的是程序持有的东西;授权和本机连接属于连接,不是程序环境的一部分。销毁 Agent 时,如果正在运行的程序无法被中断,还要等待运行时的停止宽限期,默认三秒。
|
||||
|
||||
**`--print-client-config codex|claude-code|json` 选项。** 为当前安装渲染准确命令需要 `node:sea` 来区分单文件可执行程序与脚本启动,而打包全部可选组合包的浏览器 worker 镜像没有注册 `node:sea`;文档给出的配置项带有同样的超时与输出预算,不需要这项依赖。
|
||||
|
||||
## 后果
|
||||
|
||||
每个安装都携带该组合包;macOS 与 Windows 两个原生提供方是它的可选依赖,各由一行挂载,且只在对应的 Host 上加载,`verify-default-product-isolation` 让该组合包留在默认模板之外。把组合包叠在 `dsh-base` 之上的 profile 会出现重复的行 id,不受支持;Web 插件页通过 `HIDDEN_BUNDLES` 隐藏该组合包,而 Host 清单仍把它报告为可选组合包。没有提供方的 Host 列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方,调用 `cua_run_code` 以 `unknown tool` 失败。客户端会在进程退出、`cua_reset` 或 Agent 销毁时看到状态丢失并重新创建对象。授权 elicitation 依赖 2025 版 MCP 请求模型;使用 2026-07-28 修订版的客户端改用 `allow`。工具描述、服务器说明与参考文本由 profile 的期望输出测试固定;程序工具的描述和参考随已安装的 CUA 包变化。模型只有调用 `cua_get_api_reference` 才能得到参考,因此不放行该工具的客户端,其模型只有执行规则可用。提供方描述超过 4,096 个字符时,Claude Code 的模型只看到被截断的部分。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-cua-ax-traversal-defaults.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md
|
||||
/agent-note-ax-traversal-defaults-and-per-read-limits:
|
||||
en: 71a088b589135b94
|
||||
zh: 40a0accb1f6d100b
|
||||
/agent-note-ax-traversal-defaults-and-per-read-limits/problem:
|
||||
en: 18405553f792f64c
|
||||
zh: 1b6891403539c2f8
|
||||
/agent-note-ax-traversal-defaults-and-per-read-limits/decision:
|
||||
en: 89cb2b1f33b0551c
|
||||
zh: b57839093a735c2a
|
||||
/agent-note-ax-traversal-defaults-and-per-read-limits/alternatives-considered:
|
||||
en: c15d84e0bbb18b39
|
||||
zh: 4799291d7a66fa04
|
||||
/agent-note-ax-traversal-defaults-and-per-read-limits/consequences:
|
||||
en: 687f4ba2af13e847
|
||||
zh: ae5777022619b71d
|
||||
@@ -0,0 +1,21 @@
|
||||
# Agent Note: AX traversal defaults and per-read limits
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-cua-ax-traversal-defaults.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
A shallow read can omit a control in a deeply nested window. Increasing the profile settings to reach it also increases the work and possible output of subsequent reads.
|
||||
|
||||
## Decision
|
||||
|
||||
For an accessibility tree read, the Host takes each of `maxElements` and `maxDepth` from the request when present and from the provider configuration otherwise. A caller can raise or lower either value for one read. The native provider enforces its traversal ceilings. On macOS, Paste menu discovery always uses the configured values because the paste operation has no traversal options.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Cap each read at the configured values.** With a profile tuned for small reads, recovering a truncated branch would require changing the profile even when the provider can handle a larger request. Per-read overrides let the caller inspect that window and return to the usual limits on the next read.
|
||||
|
||||
## Consequences
|
||||
|
||||
Lowering a profile default reduces the budget for ordinary reads. An explicit larger request can take longer and produce more text. The native operation deadline and response size limit still apply. The [macOS configuration table](../../../../packages/experimental/cua-macos/README.md#use-this-package) lists the defaults.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Agent Note: AX 树遍历的默认值和单次读取上限
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-cua-ax-traversal-defaults.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
读取深度较小时,控件可能位于窗口中被截断的分支里。为了找到这个控件而调高配置值,会让以后的读取也可能访问更多节点、返回更多文本。
|
||||
|
||||
## 决策
|
||||
|
||||
读取辅助功能树时,Host 分别处理 `maxElements` 和 `maxDepth`。调用方显式传入的值只对本次读取生效,可以高于或低于配置值。省略的参数使用平台配置。原生实现在遍历时执行自身的硬上限。macOS 的粘贴操作没有遍历参数,查找粘贴菜单时始终使用配置值。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**把配置值作为每次读取的硬上限。** 如果日常读取使用较小的配置值,即使平台支持读取更大的树,调用方也必须先修改配置才能看到被截断的分支。允许单次覆盖后,调用方可以单独扩大这次读取的范围,下次读取继续使用原有配置。
|
||||
|
||||
## 影响
|
||||
|
||||
调低配置值可以缩小常规读取的范围。显式请求更大的树可能耗时更长,也可能返回更多文本。原生调用仍受超时和响应大小限制。默认值见 [macOS 配置表](../../../../packages/experimental/cua-macos/README.zh.md#use-this-package)。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-cua-program-tool.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md
|
||||
/agent-note-cua-programs-outside-the-ptc-preset:
|
||||
en: a283f005c51274e7
|
||||
zh: 1f697efb2dbac3ba
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/problem:
|
||||
en: 87ce83e36a6ab68e
|
||||
zh: 8aa98dc7dae03c41
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/decision:
|
||||
en: 13e079e19b5f2d6d
|
||||
zh: 2ce9b6aa981162d7
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/alternatives-considered:
|
||||
en: b5d8e00cbe4b53ae
|
||||
zh: 4ef81611150a8d75
|
||||
/agent-note-cua-programs-outside-the-ptc-preset/consequences:
|
||||
en: 22f25d54373ba06b
|
||||
zh: ee335578caaf1ab3
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: CUA programs outside the PTC preset
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-cua-program-tool.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Computer Use needs reusable application and window objects in Standard and other presets without changing their ordinary tool calls or requiring users to change the profile's PTC runtime. Experimental CUA packages cannot appear in shipped preset definitions. Program dispatch must retain the same permission checks, cancellation, nested logs, and screenshots as PTC.
|
||||
|
||||
## Decision
|
||||
|
||||
CUA keeps `agentPreset: ptc` as the default selector for its raw `cua` tool. Every other composed preset receives `cua_run_code`; Agents without a composed preset receive neither tool. `agentPreset: false` retains global raw-tool registration. A base owner uses Agent scopes for registration and disposal, so enabling and disabling the provider affects existing and later Agents without editing presets. Raw registration depends only on base CUA services and preset selection. The private program producer publishes and withdraws its definition by identity; private dependency loss or startup failure leaves raw tools and prompts available.
|
||||
|
||||
`cua_run_code` composes the shared [program-tool factory](../../../../packages/core/tool-executor-ptc/README.md) with one isolated Node `persistent-in-memory` runtime owned by the CUA provider. Agent `stateOwner` identities select separate retained processes. Its only binding is the private `tools.cua` definition; the model calls ordinary session tools directly. Nested CUA operations retain tool policy, guards, dispatch events, and image admission. Programs select text and screenshots through `inspect(...values)`, following the [explicit output decision](2026-11-09-explicit-ptc-output.md). The provider releases held keys when either program tool settles. Provider unload drains its own CUA programs before native teardown; releasing input held by other PTC programs does not wait for their unrelated work. State is in memory, separate from the profile's PTC state, and released with its Agent or provider.
|
||||
|
||||
CUA registers a source program through `registerEnvironmentInitializer` before its isolated runtime admits a run. Each new environment evaluates it once after installing current bindings, including temporary escalated environments. The child awaits Host acceptance before starting model code. Initialization shares the first run's time and output budgets; failure discards the environment and prevents model execution without rolling back external effects. Separate evaluation preserves model source locations. An initializer-owning scope depends only on the runtime, so program-tool dependency reloads retain the registration. PTC keeps its explicit bridge initialization.
|
||||
|
||||
This partially supersedes the exclusion of a CUA program entry in [native CUA objects](2026-09-17-experimental-cua-object-api.md). That note still owns the object API's independence from an evaluator and the split between shared objects and native operations. The shared Node provider owns evaluation; CUA supplies its restricted bindings and initialization. The [optional bundle decision](2026-09-21-experimental-capabilities-as-optional-bundles.md) still owns delivery and activation.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A CUA-specific evaluator** duplicates execution lifecycle policy. Reusing the PTC factory and runtime keeps cancellation, limits, sandboxing, and result handling with their existing owners.
|
||||
|
||||
**The profile's shared runtime** couples CUA state to unrelated PTC and workflow settings. Its default per-call mode cannot retain objects. A separate CUA runtime preserves the profile's chosen execution mode.
|
||||
|
||||
**Global registration of both tool forms** exposes a program runner inside PTC programs and exposes raw CUA calls to other presets. Selecting one form per Agent keeps each mode's intended tool list. Binding every session tool inside `cua_run_code` would duplicate ordinary direct calls and their declarations.
|
||||
|
||||
**Prepending initialization to model code** shifts source locations. Running initialization as a separate tool call fails for temporary escalated environments because the next call starts another process. A separate program within the first runtime execution supports both retained and temporary environments. Passing initialization with every program couples environment setup to tool requests and repeats work in existing environments; registration keeps setup and cleanup with the runtime owner.
|
||||
|
||||
## Consequences
|
||||
|
||||
CUA adds no preset list or shipped preset dependency. Preset IDs select the tool form; custom PTC presets must match `agentPreset`. PTC and CUA share the public factory; CUA owns a runtime initializer registration and drains its program tools before unregistering it. Older custom Node bootstraps require the matching protocol revision, as described in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md).
|
||||
|
||||
The private binding limits callable Harness tools, not Node APIs. File and process access still follow the selected sandbox policy. Retained variables do not reserve applications or survive process loss; callers recreate objects and observe state before continuing. Composition and recorded-session tests cover tool selection, automatic initialization, retained state, nested output, and removal; native fixtures remain responsible for platform input behavior.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: PTC preset 之外的 CUA 程序
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-cua-program-tool.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Computer Use 需要在标准及其他 preset 中复用应用和窗口对象,同时保留普通工具的调用方式,也不要求用户更改 profile 的 PTC 运行时。实验性 CUA 包不能出现在随产品提供的 preset 定义中。程序派发必须保留与 PTC 相同的权限检查、取消、嵌套日志和截图行为。
|
||||
|
||||
## 决策
|
||||
|
||||
CUA 保留 `agentPreset: ptc`,用默认选择器指定获得原始 `cua` 工具的 preset。其他已组合的 preset 获得 `cua_run_code`;未组合 preset 的 agent(智能体)不获得这两个工具。`agentPreset: false` 保留全局原始工具注册。基础注册的所有者通过 Agent 作用域管理注册和销毁,因此启停提供方会影响已有和后续 Agent,无需修改 preset。原始工具的注册只依赖基础 CUA 服务和 preset 选择。私有程序工具的提供方按定义对象的身份发布和撤回其定义;私有依赖缺失或启动失败时,原始工具和提示词仍然可用。
|
||||
|
||||
`cua_run_code` 将共享[程序工具工厂](../../../../packages/core/tool-executor-ptc/README.zh.md)与 CUA 提供方持有的单个隔离 Node `persistent-in-memory` 运行时组合。Agent 的 `stateOwner` 身份选择各自独立的保留进程。它只绑定私有 `tools.cua` 定义;模型直接调用其他普通会话工具。嵌套 CUA 操作保留工具策略、guard、派发事件和图像接纳。程序通过 `inspect(...values)` 选择文字和截图,遵循[显式输出决策](2026-11-09-explicit-ptc-output.zh.md)。任一程序工具结束时,提供方都会释放该程序仍按住的键。提供方卸载时,先等待自己持有的 CUA 程序结束再清理原生资源;释放其他 PTC 程序持有的输入时,不等待这些程序中的其他工作。状态保存在内存中,独立于 profile 的 PTC 状态,随所属 Agent 或提供方释放。
|
||||
|
||||
CUA 在隔离运行时首次接纳运行前,通过 `registerEnvironmentInitializer` 注册一段源码。每个新环境安装本次绑定后执行该程序一次,包括临时提权环境。子进程等待 Host 确认后才开始执行模型代码。初始化与首次运行共享时间和输出预算;失败会丢弃环境并阻止模型代码执行,但不回滚外部效果。独立求值保留模型源码位置。初始化程序所属的作用域只依赖运行时,因此程序工具的依赖重载时仍保留这项注册。PTC 保留显式 bridge 初始化。
|
||||
|
||||
这部分取代[原生 CUA 对象](2026-09-17-experimental-cua-object-api.zh.md)中不提供 CUA 程序入口的决定。原记录继续负责对象 API 独立于求值器,以及共享对象与原生操作之间的职责划分。共享 Node 提供方负责求值,CUA 提供受限的绑定和初始化。[可选组合包决策](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)继续负责分发和启用方式。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**CUA 专用求值器**会重复实现执行生命周期策略。复用 PTC 工厂和运行时,使取消、限制、沙箱和结果处理继续由现有实现负责。
|
||||
|
||||
**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。其默认逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。
|
||||
|
||||
**全局注册两种工具形态**会在 PTC 程序中暴露另一个程序执行器,并向其他 preset 暴露原始 CUA 调用。按 Agent 选择一种形态,可以保留各模式预期的工具列表。在 `cua_run_code` 内绑定所有会话工具,会重复普通的直接调用及其声明。
|
||||
|
||||
**把初始化拼到模型代码前**会偏移源码位置。通过单独的工具调用执行初始化无法适用于临时提权环境,因为下次调用会启动另一个进程。首次运行时执行中的独立程序同时支持保留环境和临时环境。每次提交程序都传入初始化,会使环境准备依赖工具请求,并在已有环境中重复执行;注册使准备和清理继续由运行时所有者负责。
|
||||
|
||||
## 后果
|
||||
|
||||
CUA 不增加 preset 列表,也不向内置 preset 添加依赖。工具形态按 preset ID 选择;自定义 PTC preset 必须与 `agentPreset` 匹配。PTC 与 CUA 共享公开工厂;CUA 拥有运行时初始化程序的注册,注销前会等待自己的程序工具执行结束。旧版自定义 Node bootstrap 需要匹配协议版本,详见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md)。
|
||||
|
||||
私有绑定限制可调用的 Harness 工具,不限制 Node API。文件与进程访问仍遵循所选沙箱策略。保留变量不会独占应用,也不能跨进程丢失保留;调用方应重建对象并观察状态后再继续。组合测试和已记录会话测试覆盖工具选择、自动初始化、状态保留、嵌套输出及移除;平台输入行为仍由原生 fixture(测试前置数据)负责验证。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-explicit-ptc-output.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.md
|
||||
/agent-note-explicit-text-and-image-output-in-ptc:
|
||||
en: b62f1fc259e6f4a7
|
||||
zh: 340942c222a38e2a
|
||||
/agent-note-explicit-text-and-image-output-in-ptc/problem:
|
||||
en: 51667474a3f9053d
|
||||
zh: 70c6af69e943f4f5
|
||||
/agent-note-explicit-text-and-image-output-in-ptc/decision:
|
||||
en: ec82c0ce9f6a371d
|
||||
zh: 74596c0ab6a3cdd7
|
||||
/agent-note-explicit-text-and-image-output-in-ptc/alternatives-considered:
|
||||
en: cfbca328947567f3
|
||||
zh: 3b2f619365d2250e
|
||||
/agent-note-explicit-text-and-image-output-in-ptc/consequences:
|
||||
en: 636609d91f12a960
|
||||
zh: b26397c72f972827
|
||||
@@ -0,0 +1,43 @@
|
||||
# Agent Note: Explicit text and image output in PTC
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-explicit-ptc-output.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
PTC lets a program acquire and filter intermediate tool results before choosing what the model sees. A final expression or return value can expose incidental data, while automatically attaching every acquired image defeats that selection. Separate screenshot bytes and image-output callbacks also make programs convert images before comparing or displaying them.
|
||||
|
||||
## Decision
|
||||
|
||||
TypeScript `run_code` programs select text, objects and images through top-level `inspect(...values)`. Arguments are rendered independently: strings appear directly, and other values use Node's object formatting without depth, array-length or string-length preview limits. Inspection displays undefined properties, Error objects and circular references; requiring lossless JSON for display would interrupt subsequent work after tools have already executed. Images can occur inside arrays or objects. The runtime Image's custom inspection hook collects images reached by Node's formatter; each formatting call owns its collector. One output sequence preserves the relationship between explanatory text and selected images.
|
||||
|
||||
The tool executor requests `discardCompletion: true`, so completion values are discarded before JSON validation and serialization. This is a consumer choice: direct runtime and workflow consumers retain completion values when their protocols require them. The [PTC foundation](../feature/2026-06-15-ptc.md) owns dispatch and settlement. The [typed-return decision](../feature/2026-07-20-ptc-typed-tool-returns.md) continues to own ordinary JSON binding values, failures and output accounting; this note owns TypeScript output selection and image projection.
|
||||
|
||||
The Node environment supplies `inspect` alongside the complete native console. Native console methods remain available to programs and imported libraries, and their stdout and stderr writes share the captured output sequence. Model instructions direct programs to select output through `inspect`.
|
||||
|
||||
`read_image` and CUA screenshot bindings expose stored `Image` values. Readonly `attachmentId`, `path`, `width` and `height` identify the stored image and its readable execution-world file. The dimensions describe that file's pixels, including the image used for CUA coordinate mapping. The [CUA object API](2026-09-17-experimental-cua-object-api.md) returns screenshot Images and text observations directly to the program. The program passes selected values to `inspect` for display.
|
||||
|
||||
The host carries the attachment reference with the program-readable path. The runtime transports image metadata and keeps the attachment reference behind a process-owned image ID. Inspection resolves that ID directly to the registered reference. Image identity is established by the runtime; matching object properties alone do not grant access to an image output. Retained program Images follow their owning process's lifetime.
|
||||
|
||||
Nested tool dispatches retain their complete rendered content in the Session log. Successful outer `run_code` results interleave inspected images with text in emission order, where model history and UI rendering use the same durable attachment references. Successful outer-result replacement remains authoritative over the selected output.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Display the completion value alongside printed output.** The last expression or return then controls context admission as well as program control flow. Discarding it before validation lets a program finish with an arbitrary internal value while explicitly selecting a smaller visible result.
|
||||
|
||||
**Automatically forward every acquired image.** Acquisition then implies model-context cost, even when the program needs several screenshots to select one. Explicit inspection gives text and images the same selection rule.
|
||||
|
||||
**Keep a CUA byte-returning facade and image sink.** This maintains a separate screenshot representation and a second image-emission path. Returning the runtime's Image lets file reads and screenshots share inspection and preserves the stored attachment reference through display.
|
||||
|
||||
**Discover images with a separate object traversal.** A separate traversal must duplicate Node's handling of collections, symbols and custom formatters and can emit images absent from the text representation. The Image hook ties collection to Node's formatting.
|
||||
|
||||
**Bounded object previews.** Item and string preview limits can omit file contents that a program explicitly selected. Removing those limits keeps selected contents complete within the shared output budget.
|
||||
|
||||
**Restrict console availability.** Missing bindings and incomplete replacements can break program code and imported libraries. The native console preserves Node methods while prompt guidance directs output selection through `inspect`.
|
||||
|
||||
## Consequences
|
||||
|
||||
Programs explicitly choose the output needed for the next model request, including image comparisons and selected nested results. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md) owns caller migration. Acquiring an image still performs storage and processing work; selection controls its presentation to the model.
|
||||
|
||||
The runtime owns process-local image identity and output ordering; the tool executor owns attachment projection and durable result content. Text and image-reference metadata share the outer output budget. Runtime teardown releases retained image identities, while stored attachments follow the attachment store's lifetime.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Agent Note: PTC 显式文本与图片输出
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-explicit-ptc-output.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
PTC 允许程序先获取和筛选中间工具结果,再选择模型看到的内容。末尾表达式或返回值可能暴露偶然产生的数据,而自动附加每张已获取的图片会使这种筛选失效。独立的截图字节和图片输出回调也要求程序先转换图片,再进行比较或展示。
|
||||
|
||||
## 决策
|
||||
|
||||
TypeScript `run_code` 程序通过顶层 `inspect(...values)` 选择文本、对象和图片。各参数独立渲染:字符串直接展示,其他值使用 Node 的对象格式,不限制预览深度、数组项数或字符串长度。inspect 展示 undefined 属性、Error 对象和循环引用;要求展示值必须是无损 JSON,会在工具已经执行后中断后续工作。图片也可以嵌入数组或对象。运行时 Image 的自定义 inspect 钩子收集 Node 格式化函数访问到的图片;每次格式化调用拥有自己的收集器。同一输出序列保留说明文字与所选图片的对应关系。
|
||||
|
||||
工具执行器请求 `discardCompletion: true`,在 JSON 校验和序列化前丢弃完成值。这是消费方的选择:直接运行时调用方和工作流消费方在其协议需要时保留完成值。[PTC 基础](../feature/2026-06-15-ptc.zh.md)负责分发与结算。[类型化返回值决策](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)继续负责普通 JSON 绑定值、失败和输出计量;本记录负责 TypeScript 输出选择与图片投影。
|
||||
|
||||
Node 环境同时提供 `inspect` 和完整的原生 console。程序与导入的库均可使用原生 console 方法,其 stdout 和 stderr 写入共用捕获输出序列。模型指引要求程序通过 `inspect` 选择输出。
|
||||
|
||||
`read_image` 和 CUA 截图绑定提供已存储的 `Image` 值。只读的 `attachmentId`、`path`、`width` 和 `height` 标识已存储图片及其在执行环境中可读取的文件。尺寸描述该文件的像素,也对应 CUA 坐标换算所用的图片。[CUA 对象 API](2026-09-17-experimental-cua-object-api.zh.md)将截图的 `Image` 和观察文本直接返回给程序。程序将选中的值传给 `inspect` 展示。
|
||||
|
||||
宿主将附件引用与程序可读取的路径一起传递。运行时传输图片元数据,并用进程拥有的图片 ID 保存对应的附件引用。展示时,该 ID 直接解析为已登记的引用。图片身份由运行时建立,仅有相同对象属性不能取得图片输出权限。保留在程序中的 Image 跟随其所属进程的生命周期。
|
||||
|
||||
嵌套工具分发将完整渲染内容保留在 Session 日志中。成功的外层 `run_code` 结果按输出顺序穿插显式展示的图片和文本,模型历史和 UI 渲染使用相同的持久附件引用。成功外层结果的替换仍对所选输出具有最终决定权。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**同时展示完成值与打印输出。** 末尾表达式或返回值会同时控制上下文纳入和程序控制流。在校验前丢弃完成值,使程序可以用任意内部值结束,并显式选择更小的可见结果。
|
||||
|
||||
**自动转发每张已获取的图片。** 即使程序需要先获取多张截图才能选出一张,获取动作本身也会产生模型上下文成本。显式展示让文本和图片遵循同一选择规则。
|
||||
|
||||
**保留返回字节的 CUA 对象接口和图片输出回调。** 这会维护独立的截图表示和第二条图片输出路径。返回运行时 Image,使文件读取和截图共用展示方式,并在展示过程中保留已存储附件引用。
|
||||
|
||||
**单独遍历对象以发现图片。** 独立遍历必须重复实现 Node 对集合、Symbol 和自定义格式化的处理,还可能输出文本表示中未出现的图片。Image 钩子让收集跟随 Node 的格式化。
|
||||
|
||||
**限制对象预览。** 条目和字符串的预览上限可能省略程序已明确选中的文件内容。取消这些限制,在共享输出预算内完整保留选中的内容。
|
||||
|
||||
**限制 console 的可用性。** 缺失的绑定和不完整的替代实现可能使程序及导入的库出错。原生 console 保留 Node 方法,提示词指引程序通过 `inspect` 选择输出。
|
||||
|
||||
## 后果
|
||||
|
||||
程序显式选择下一次模型请求需要的输出,包括图片比较和嵌套结果中的所选内容。[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md)负责调用方迁移。获取图片仍会执行存储和处理工作,选择控制的是向模型展示的内容。
|
||||
|
||||
运行时负责进程内图片身份和输出排序;工具执行器负责附件投影和持久结果内容。文本和图片引用元数据共用外层输出预算。运行时拆卸释放保留的图片身份,已存储附件则遵循附件存储的生命周期。
|
||||
@@ -0,0 +1,73 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-retained-ptc-scoped-repl.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.md
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc:
|
||||
en: ea465612c52ff8a6
|
||||
zh: 1c4021aecb7550c6
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/problem:
|
||||
en: 9e115eb5c8b8d168
|
||||
zh: d47b2a783e154664
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision:
|
||||
en: 02e060e10da7bb75
|
||||
zh: d4b01038283943bd
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior:
|
||||
en: 14dff09dd91c1533
|
||||
zh: d199bef553f9439c
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/syntax-and-results:
|
||||
en: 4f0c54f87042943e
|
||||
zh: 34b88dbb1d50a2c6
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/across-calls:
|
||||
en: d389222669ca94d7
|
||||
zh: cf19a71bce644ee4
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/environment:
|
||||
en: b1d35c4055c7f381
|
||||
zh: 404b3843b2348fec
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/errors:
|
||||
en: 5b4209a69447bfac
|
||||
zh: 3b1cb6297962b6c1
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/asynchronous-failures-and-lifecycle:
|
||||
en: 70c47aba7a23fc4f
|
||||
zh: 1d7d5f0809e748aa
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/comparison-with-node-repl-and-vm-script:
|
||||
en: 013bfbf3d3944637
|
||||
zh: eba400efadf6229b
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/context-and-options:
|
||||
en: 14fc1abb8e437555
|
||||
zh: 38a37fdb8ca7e17c
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/wrapper:
|
||||
en: d886821f764b6804
|
||||
zh: a073534825d639a2
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/kernel-scope-chain-acorn-scan-and-compilation:
|
||||
en: 10d0459a356cd33d
|
||||
zh: 07e7cd70119c4d4d
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/scope-chain-state-and-the-steps-of-a-call:
|
||||
en: fbb63be77e727e07
|
||||
zh: 12f24e0d0672907c
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/failed-calls:
|
||||
en: 64937f1d5acd7147
|
||||
zh: f262dff89139086f
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/asynchronous-failures-aligned-with-the-repl:
|
||||
en: 7f867b69623f3652
|
||||
zh: 551a456448700171
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/dynamic-import:
|
||||
en: 2607ffb07f5c4b4b
|
||||
zh: 5882d8c58d5a775b
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/redeclaration-notice-reserved:
|
||||
en: c3eef0f99686acfe
|
||||
zh: 9093c1e84abff335
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/out-of-scope:
|
||||
en: 725a4139f28961c3
|
||||
zh: b32da1bf86095e65
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/integration:
|
||||
en: b05235293c504467
|
||||
zh: 48f5f534812a12b3
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/alternatives-considered:
|
||||
en: e548d12c174bb44e
|
||||
zh: 9f67908a564d6f78
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/consequences:
|
||||
en: d75ef0e16dcdcee2
|
||||
zh: 22ae67a41c1461ca
|
||||
/agent-note-scoped-repl-evaluator-for-retained-ptc/testing:
|
||||
en: 799de02ac67753f3
|
||||
zh: f3ad0647273fc458
|
||||
@@ -0,0 +1,524 @@
|
||||
# Agent Note: Scoped REPL evaluator for retained PTC
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-retained-ptc-scoped-repl.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
`persistent-in-memory` runs every `run_code` call of one Agent in one global scope through node:repl ([best-effort persistent PTC](../../implemented/architecture/2026-09-23-best-effort-persistent-ptc.md)). When a later call declares a `const`, `let`, or `class` name again, V8 rejects the program before it runs with `SyntaxError: Identifier 'x' has already been declared`, and no statement executes. Model guidance can only ask for no redeclarations, and models rarely track every name across many calls.
|
||||
|
||||
Rewriting declarations as `var` removes the error, but every call then shares one binding, so a later declaration changes the value that earlier functions, closures, and background tasks read:
|
||||
|
||||
```js
|
||||
// call 1
|
||||
var value = 1
|
||||
var read = () => value
|
||||
// call 2
|
||||
var value = 2 // no error
|
||||
// call 3
|
||||
read() // 2: call 2 changed the read written by call 1
|
||||
```
|
||||
|
||||
Five requirements must hold together:
|
||||
|
||||
1. A later call may declare an earlier name again with any keyword without an error.
|
||||
2. A redeclaration applies to that call and later calls; earlier functions, closures, and still-running code keep their original values.
|
||||
3. Syntax matches the existing REPL: top-level `await` works, the final expression is the result, and top-level `return` is not supported.
|
||||
4. Errors in asynchronous callbacks are handled as in the existing REPL: the process keeps running and variables are retained.
|
||||
5. No scope analysis and no rewriting of declarations or references in model code; acorn only lists top-level declarations and finds the last statement.
|
||||
|
||||
## Decision
|
||||
|
||||
The scoped REPL evaluator is split into a kernel and an evaluator:
|
||||
|
||||
| File | Contents |
|
||||
|---|---|
|
||||
| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl.ts` | Kernel: the `ScopedReplScopes` scope chain, which owns binding state, copies and fallback values, redeclarations, and Script compilation; plus the acorn scan, top-level declarations and keywords, top-level `return` check, final expression, reserved-name check, syntax-error layout, and source generation |
|
||||
| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl-evaluator.ts` | Evaluator: exports `createScopedReplEvaluator(options)` implementing the existing `ProgramEvaluator` interface and connects the kernel to the existing modes: context and options, dynamic imports and the import handler, starting programs from a microtask and reading completions, the domain, and the injected `reportRedeclarations` |
|
||||
| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl.spec.ts` | Kernel tests only; runs on its own and covers scanning, source generation, and scope layering across consecutive programs in a plain vm context |
|
||||
| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-evaluator.spec.ts` | Integration tests: completions, environment, modules and imports, errors, and asynchronous failures; every option tested on and off |
|
||||
|
||||
The `scoped-repl` format connects the evaluator to the existing execution modes; see Integration.
|
||||
|
||||
### Exact behavior
|
||||
|
||||
#### Syntax and results
|
||||
|
||||
- A program is a list of statements and supports top-level `await`.
|
||||
- When the last non-empty top-level statement is an expression statement, its value is the result. A Promise value is not awaited: the Promise itself is the result, so the host reports `program completion must be lossless JSON`, as with the existing REPL. The `finalExpression` option controls this and defaults to on; when off, the final value is discarded, results come only from printing, and model guidance must change accordingly. `run_code` passes `discardCompletion: true` for TypeScript runtimes, so the host discards completion values and the model displays output with `inspect(...)`; callers that keep completions, such as workflow-ptc, still take the final expression's value as the result.
|
||||
- When the last statement is a declaration, `if`, `for`, block, or another statement, there is no result.
|
||||
- Top-level `return`, including inside top-level `if`, loops, and blocks, reports `SyntaxError: Illegal return statement`, and no statement of that call runs. Through `run_code`, the host's TypeScript erasure rejects it first with `Return statement is not allowed here`, as with the existing REPL.
|
||||
- A static `import` or `export` reports acorn's `SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'`; acorn also rejects top-level `using` and `await using`, which remain available inside blocks and functions.
|
||||
- A program that starts with `#!` reports `SyntaxError: Hashbang lines are not supported` and does not run: a hashbang is valid only at the very start of a Script, and the generated prefix precedes the program.
|
||||
- Output is the printed text, such as `inspect(...)`, plus the final expression's value when the caller keeps completions.
|
||||
|
||||
#### Across calls
|
||||
|
||||
- Each call starts by copying every top-level name left by earlier calls into a same-named declaration; objects are shared by reference, so changes inside an object are visible on both sides.
|
||||
- A call may declare an earlier name again with any keyword, including a `var`→`let`→`const`→`class`→`function` sequence. A name the call declares with `let`, `const`, `class`, or `function` is not copied, and the call's declaration wins; a name it declares again only with `var` is still copied, so that `var` starts from the earlier value.
|
||||
- Assigning to an earlier name without declaring it changes this call's copy: later calls see the new value, and earlier functions keep the old one. This includes names declared with `const`, which are read-only only in the call that declares them.
|
||||
- After a function is redefined, earlier callers still call the old function.
|
||||
- Assignments that earlier code, such as timers and callbacks, makes to top-level variables after a call starts are not visible to later calls; keep shared mutable state in objects.
|
||||
- Earlier functions cannot see names declared later; referencing them reports `ReferenceError`.
|
||||
- When a call declares a name again with `let`, `const`, or `class`, every reference in that call resolves to the new declaration, including references written before it, and the old value is unreachable: reading the name before its declaration runs reports the native `ReferenceError: Cannot access 'x' before initialization`. Such code is a program error and is not handled. A `var` redeclaration starts from the earlier value until it assigns a new one, so `var count = count + 1` adds to the earlier value; a `function` name holds the new function from the start of the call.
|
||||
- When a call fails partway: declarations completed before the throw are kept; an existing name redeclared but not yet initialized falls back to its earlier value in later calls; an uninitialized new name is dropped.
|
||||
- A `var` declared inside a block, including `try`/`catch`/`finally`, `if`/`else`, loop bodies, `switch`, and labeled statements, hoists to the top level of the call and counts as the call's declaration like a top-level `var`: it carries to later calls and may reuse a name that an earlier call declared with any keyword. A `var` inside a nested function or class does not count.
|
||||
- A `var` redeclaration that does not run, after a throw or in a branch that is not taken, keeps the earlier value, and so does `var x;` without an initializer.
|
||||
|
||||
#### Environment
|
||||
|
||||
These are the defaults; one option controls each of the first two items, see Context and options.
|
||||
|
||||
- Strict mode: assigning an undeclared name reports `ReferenceError`; intentional globals use `globalThis.x`. With the option off, strict mode is not forced: a program that starts with `"use strict"` runs strict, and other programs run sloppy.
|
||||
- No code generation from strings: the context's own `eval` and `new Function` report `EvalError`, and compiling WebAssembly from bytes reports `CompileError`. This is no isolation: main-realm functions copied into the context, such as `setTimeout.constructor`, still generate code in the main realm.
|
||||
- Modules load only through dynamic `import()`, whose relative specifiers resolve from the working directory of the environment's first call and keep doing so after later calls change directory; there is no `require`, `module`, or built-in module global such as `fs` and `path`. Relative file access still follows the current directory.
|
||||
- Top-level `this` is `undefined`, or `globalThis` when a program runs sloppy; top-level `arguments` is an empty arguments object with length 0.
|
||||
- Top-level `var` and `function` declarations do not become `globalThis` properties.
|
||||
- Node globals such as `setTimeout`, `Buffer`, `fetch`, `URL`, and `structuredClone` are available.
|
||||
|
||||
#### Errors
|
||||
|
||||
- Runtime error lines and columns are native positions in the model's code, and functions defined in an earlier call show that call's filename, for example `<directory>/.ptc-repl-1.js:2:9`. On the line of the final expression, columns after the insertion point shift right by 17, which is left as is.
|
||||
- Syntax errors that acorn finds are reported with acorn's message and position, laid out like V8's: filename and line, source line, and caret. Two messages use V8's wording: top-level `return` reports `Illegal return statement`, and an error positioned at the end of the code reports `Unexpected end of input`.
|
||||
- Errors that acorn accepts and V8 rejects during compilation report V8's native message; with the `strict` option on, strict-mode syntax violations such as `with` are reported this way.
|
||||
- These are the evaluator's own reports. Through `run_code`, the host's TypeScript erasure parses the whole program first and reports most syntax errors itself, as with the existing REPL; only code that the erasure accepts and the scan rejects, such as reserved names, static `import`, or top-level `using`, shows the layout above.
|
||||
- Runtime errors report the error name and stack, without an `Uncaught ` prefix and without evaluator frames.
|
||||
|
||||
#### Asynchronous failures and lifecycle
|
||||
|
||||
- Errors thrown by timers, callbacks, Promise continuations, and EventEmitters that a program starts, and unhandled rejections, do not end the process, and variables are retained. Exception: when a callback throws a frozen or non-extensible object, Node's domain fails to add its properties before notifying the listener, and the process ends, as with node:repl; rejecting with such an object is unaffected.
|
||||
- If an evaluation is active, it fails with `Uncaught ` followed by the error text; otherwise the error is discarded. The error text is the error's `stack`, or `name: message` when the stack is not a string; a value that is not an error is formatted with `util.inspect` after removing the `domain` and `domainThrown` properties the domain added; a failure while formatting reports `program threw an unrenderable value`. An error belongs to the evaluation that created its callback, so a timer from an earlier call failing during a later call is not charged to the later call.
|
||||
- Output printed after an evaluation ends is discarded; timeout, cancellation, and reset keep the existing host behavior ([retained PTC interruption](../../implemented/architecture/2026-10-29-retained-ptc-interruption.md)).
|
||||
|
||||
### Comparison with node:repl and vm-script
|
||||
|
||||
✓ means supported, ✗ means not supported, and "—" means not applicable: `vm-script` without persistence starts a new process for every call and has no cross-call state. "Persistent vm-script" is vm-script with `scriptPersistence: true` (#7992), and "both vm-script columns" means it and vm-script without persistence. The "ours" column is the default behavior, and its parenthesis names the columns it matches; the Environment table splits it into strict mode on, the default, and off. The Across calls table adds an implementation expected to support cross-call behavior, called the "expected implementation" in parentheses and notes.
|
||||
|
||||
**Syntax and results**
|
||||
|
||||
| Capability | node:repl (existing REPL evaluator) | Ours | vm-script (no persistence) | vm-script (persistent, #7992) | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| Top-level `return`, including inside `if` blocks | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | All report `Illegal return statement` |
|
||||
| Final expression as the result | ✓ | ✓ (default; matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours can turn it off with `finalExpression` |
|
||||
| Awaiting a final Promise | ✗ | ✗ (matches node:repl) | ✓ | ✓ | Without awaiting, the host reports a non-JSON completion |
|
||||
| A result when ending with `if`, `for`, or a block | ✓ | ✗ (matches node:repl, vm-script, and persistent vm-script when the code contains `await`) | ✓ | ✓ | node:repl and both vm-script columns have a result only without `await` |
|
||||
| Top-level `await` | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | node:repl and both vm-script columns rewrite the whole program; ours rewrites only the final expression |
|
||||
| Static `import` | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | Ours reports acorn's message |
|
||||
| Top-level `using` | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | Available inside blocks and functions |
|
||||
| A program that starts with `#!` | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours reports `Hashbang lines are not supported` |
|
||||
| Two `function` declarations of one name, or a `var` and a `function` of one name, in one call | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | |
|
||||
| Dynamic `import()` | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | |
|
||||
|
||||
**Across calls**
|
||||
|
||||
| Capability | node:repl | An implementation expected to support cross-call behavior | Ours | vm-script | Persistent vm-script | Notes |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Variables retained across calls | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | ✗ | ✓ | node:repl and persistent vm-script share one scope; ours copies; the expected implementation copies as well |
|
||||
| Redeclaration with any keyword | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | In node:repl and persistent vm-script, 21 of the 25 keyword pairs report `already declared`, and only `var` and `function` may replace each other; ours reserves a redeclaration notice that prints nothing; the expected implementation prints an extra warning when a `const` is declared again as `const` |
|
||||
| Earlier functions unaffected by a later assignment without declaration | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | |
|
||||
| Assigning to an earlier `const` without declaring it again | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | node:repl and persistent vm-script report `TypeError`; ours prints nothing; the expected implementation prints a warning first |
|
||||
| A `var` redeclaration reads the earlier value of its name (`var n = n + 1`) | ✓ | ✗ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | node:repl and persistent vm-script only when the earlier declaration is also `var`, and report `already declared` after `let`; ours also after `let` or `const`; the expected implementation yields `NaN` |
|
||||
| Earlier callers keep calling the old function after a redefinition | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | |
|
||||
| Later calls see values earlier code assigns afterwards | ✓ | ✗ | ✗ (matches the expected implementation) | — | ✓ | A timer-incremented variable read twice 30 ms apart: node:repl 23, 50; persistent vm-script 22, 44; ours 0, 0; the expected implementation 15, 15 |
|
||||
| Earlier functions see names declared later | ✓ | ✗ | ✗ (matches the expected implementation) | — | ✓ | Ours reports `ReferenceError` |
|
||||
| Changes inside an object visible on both sides | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | — | ✓ | |
|
||||
| A name stays usable after its initializer throws | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | In node:repl and persistent vm-script a new name stays unusable, and declaring it again reports `already declared`; ours falls back to the earlier value for existing names and drops new names |
|
||||
| Declarations completed before a throw are kept | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | — | ✓ | |
|
||||
| A `var` redeclaration not reached before a throw keeps the old value | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | — | ✓ | Ours copies the earlier value into the call's `var`, which also keeps it through an untaken branch; the expected implementation inserts marker code to achieve this |
|
||||
| A new `var` declared in a block is carried to later calls | ✓ | ✗ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | Ours collects block-level `var` declarations |
|
||||
| A block-level `var` with the same name as an earlier `let` is accepted | ✗ | ✗ | ✓ (matches none of node:repl, the expected implementation, persistent vm-script) | — | ✗ | node:repl and persistent vm-script report `already declared`; ours treats it as the call's new declaration; the expected implementation reports `already declared` as well |
|
||||
|
||||
**Environment**
|
||||
|
||||
| Capability | node:repl | Ours (strict, default) | Ours (non-strict) | vm-script | Persistent vm-script | Notes |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Strict mode | ✗ | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | With the option off, a program's own leading `"use strict"` still applies |
|
||||
| Assigning an undeclared name creates a global | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Without strict mode the global is shared by every call and earlier function and is not copied |
|
||||
| Top-level `var` and `function` become `globalThis` properties | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | |
|
||||
| Top-level `this` is `globalThis` | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours is `undefined` in strict mode |
|
||||
| Top-level `arguments` | ✗ | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✗ | ✗ | Ours is an empty arguments object |
|
||||
| `eval` and `new Function` | ✓ | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Can be turned on; limits only the context's own functions, while copied main-realm functions still generate code |
|
||||
| WebAssembly compilation | ✓ | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Same option as `eval` |
|
||||
| Node globals (`setTimeout`, `Buffer`, `fetch`, `URL`, `structuredClone`) | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | |
|
||||
| `require`, `module`, and built-in module globals such as `fs` | ✓ | ✗ (matches vm-script, persistent vm-script) | ✗ (matches vm-script, persistent vm-script) | ✗ | ✗ | Only `import()` |
|
||||
| Relative `import()` follows later directory changes | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours keeps the directory of the environment's first call |
|
||||
| `_` and `_error` | ✓ | ✗ (matches vm-script, persistent vm-script) | ✗ (matches vm-script, persistent vm-script) | ✗ | ✗ | |
|
||||
| Code starting with `{ a: 1 }` is an object literal | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | node:repl treats it as an object; the existing REPL evaluator forces a block |
|
||||
|
||||
**Errors**
|
||||
|
||||
| Capability | node:repl | Ours | vm-script | Persistent vm-script | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| Accurate error positions (code without `await`) | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours excepts the final expression's line |
|
||||
| Accurate first-line positions in code with `await` | ✗ | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✗ | ✗ | node:repl and both vm-script columns report column 22 as column 54 |
|
||||
| Syntax errors show the source line and caret | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours lays out acorn's position; this is evaluator behavior, and through `run_code` the host's TypeScript erasure reports most syntax errors first, matching the node:repl column |
|
||||
| Syntax error messages are V8's wording | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours uses acorn's message, and V8's wording for errors acorn accepts and V8 rejects |
|
||||
| Incomplete code gets a clear message | ✗ | ✓ (matches vm-script, persistent vm-script) | ✓ | ✓ | node:repl reports an empty message; through `run_code` the host's erasure reports it first as well |
|
||||
| Errors carry the error name and stack | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | |
|
||||
| `Uncaught ` prefix on synchronous and awaited failures | ✓ | ✗ (matches vm-script, persistent vm-script) | ✗ | ✗ | |
|
||||
| `Uncaught ` prefix on asynchronous callback failures | ✓ | ✓ (matches node:repl) | — | — | Both vm-script columns end the process instead of reporting |
|
||||
|
||||
**Asynchronous failures and lifecycle**
|
||||
|
||||
| Capability | node:repl | Ours | vm-script | Persistent vm-script | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| A callback failure after an evaluation keeps the process and variables | ✓ | ✓ (matches node:repl) | — | ✗ | Persistent vm-script exits, the next call reports `worker-exit`, and every variable is lost; without persistence the process has already closed; a callback throwing a frozen object ends the process in node:repl and ours |
|
||||
| A callback failure during an evaluation fails only that evaluation and keeps variables | ✓ | ✓ (matches node:repl) | ✗ | ✗ | Both vm-script columns exit with `worker-exit`, and persistent vm-script loses its variables |
|
||||
| Output printed after an evaluation ends is discarded | ✓ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | |
|
||||
| Variables can survive a timeout or cancellation | ✓ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | Requires the program to acknowledge the stop |
|
||||
Sources: the node:repl, vm-script, and persistent vm-script columns come from running master's evaluators directly (Node v24.18.0). Persistent vm-script reuses one evaluator; its single-call rows equal vm-script's, and its cross-call rows and the two asynchronous rows were measured separately, the asynchronous ones through a real child process. `scoped-repl.spec.ts` tests the cross-call items of the "ours" column and `scoped-repl-evaluator.spec.ts` the rest. The two asynchronous rows of vm-script without persistence are inferred from the current implementation; node:repl, persistent vm-script, and ours share the host's timeout, cancellation, and reset behavior. The expected-implementation column was measured on that implementation with a fresh environment per case.
|
||||
|
||||
### Context and options
|
||||
|
||||
One evaluator owns one context. With the `codeGeneration` option off, the default, it is created as:
|
||||
|
||||
```ts ignore-check
|
||||
const runtimeContext = vm.createContext(Object.create(null), { codeGeneration: { strings: false, wasm: false } })
|
||||
```
|
||||
|
||||
- Node globals are copied by the same rule as `createScriptContext` in `vm-script`: every own property of the main `globalThis` that the new context lacks, with `global` pointing at the new context. The evaluator file contains its own copy of these lines and leaves [vm-script.ts](../../../../packages/ptc-runtime/ptc-runtime-node/src/evaluators/vm-script.ts) unchanged.
|
||||
- The child still writes `tools`, binding error classes, `console`, and `process` to `evaluator.globals`, which is `runtimeContext`, before each evaluation.
|
||||
- The sandbox object has no prototype, as in the vm-script and AsyncFunction evaluators, so global lookups do not reach the main realm's `Function` through a prototype chain, as `constructor.constructor("…")()` would. Main-realm values copied into the context, such as `setTimeout`, `console`, `process`, and tool namespaces, still have the main realm's `Function` as their `constructor`, and the main realm has no `codeGeneration` limits, so the option restricts only the context's own `eval`, `Function`, and WebAssembly and is no isolation; the process sandbox provides isolation.
|
||||
- Only dynamic `import()` loads modules, with no option: each Script gets `importModuleDynamically`. There is no `require`, `module`, or built-in module global; host bindings under those names stay available unchanged. Static `import` is unsupported.
|
||||
- The generated filename is `<directory>/.ptc-repl-<number>.js`; no file exists at that path, and the name starts with a dot as a hidden file. The directory is the working directory when the evaluator is created, which is the directory of the environment's first call, and never changes. Node's default loader uses the filename as the `import()` referrer, so relative imports always resolve from that directory, and the directory cannot be left out. Following later directory changes would need an explicit operation, such as `js_switch_cwd`.
|
||||
- Values from bindings and imports belong to the main realm, so cross-realm checks such as `instanceof Array` can be false, as with the REPL and `vm-script`.
|
||||
|
||||
The three options are evaluator creation parameters, not Config fields:
|
||||
|
||||
```ts ignore-check
|
||||
interface ScopedReplEvaluatorOptions extends ProgramEvaluatorOptions {
|
||||
/** Force strict mode for every program; when off, a program's own leading "use strict" decides. Defaults to true. */
|
||||
strict?: boolean
|
||||
/** Allow eval, new Function and WebAssembly compilation inside the program context; defaults to false. */
|
||||
codeGeneration?: boolean
|
||||
/** Use the last top-level expression statement as the completion value; defaults to true. */
|
||||
finalExpression?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
| Option | On | Off | Notes |
|
||||
|---|---|---|---|
|
||||
| `strict` (default on) | The whole Script starts with `"use strict";`, so every call runs strict | Not forced: when a program starts with a `"use strict"` directive, the inner function body starts with `"use strict";`, so the copy declarations cannot void it; other programs run sloppy | acorn scans with script rules in both states, and V8 reports strict-mode syntax violations at compilation. When off, in calls that run sloppy, assigning an undeclared name creates a global that every call shares without copies, top-level `this` is `globalThis`, and a name declared with a strict-mode reserved word such as `package` makes later strict calls fail to compile; see Risks |
|
||||
| `codeGeneration` (default off) | The context is created without the `codeGeneration` limits | The context is created as above | When on, a `var` declared inside `eval` is not in the scanned list and is not carried; when off, it still restricts only the context's own code generation and is no isolation |
|
||||
| `finalExpression` (default on) | The final expression becomes `return { value: (…) }` | No rewrite; the final value is discarded and the result is empty | When off, output comes only from printing; model guidance and consumers of the completion value, such as workflow-ptc, must change; top-level `return` fails in both states |
|
||||
|
||||
The integration uses the default of every option; the other values are intended uses kept by design, and each has tests.
|
||||
|
||||
### Wrapper
|
||||
|
||||
Each call compiles to its own `vm.Script`. For example, after earlier calls left `a` (`const`), `b` (`let`), and `v` (`var`), the model writes:
|
||||
|
||||
```js
|
||||
let c = a + b
|
||||
c * 2
|
||||
```
|
||||
|
||||
The compiled source is:
|
||||
|
||||
```js
|
||||
"use strict";(function (__$binding_vals, __$binding_getters) { return async function () { let a = __$binding_vals[0]; let b = __$binding_vals[1]; var v = __$binding_vals[2]; __$binding_getters.push(() => a, () => b, () => v, () => c);
|
||||
let c = a + b
|
||||
return { value: (c * 2) }
|
||||
} })
|
||||
```
|
||||
|
||||
| Part | Contents | Reason |
|
||||
|---|---|---|
|
||||
| `"use strict";` | With the `strict` option on, the whole Script is strict; when off, it is omitted, and a program that starts with `"use strict"` gets one at the start of the inner function body instead | On forces strict mode; off keeps the copy declarations from voiding the model's directive |
|
||||
| Outer `function (__$binding_vals, __$binding_getters)` | Receives the copied values and an empty array and returns the inner function; the evaluator calls it synchronously | The internal values reach the program through a closure and stay out of its `arguments`; the outer function returns before the program runs, so its frame never appears in program stacks |
|
||||
| Inner `async function ()` | The model's program is its body | Supports top-level `await`; top-level declarations are function locals, so calls never conflict; it is called without a receiver and without arguments, so `this` is `undefined` (`globalThis` when the program runs sloppy) and `arguments` is an empty arguments object |
|
||||
| Copy declarations | Generated only for names that earlier calls left and this call does not declare or declares again only with `var`; values come from `__$binding_vals` by index | Index access is unaffected by names such as `__proto__` |
|
||||
| `__$binding_getters.push(...)` | Before the model's code, pushes one read function per name, copied or declared, in the order the evaluator generated | The evaluator maps the i-th read function to the i-th name, so the prefix needs no name strings; a read function can be created early and read later, and it throws while its declaration is uninitialized |
|
||||
| Final expression | Inserts `return ` before the statement, `{ value: (` before the expression, and `) }` after it | The same handling of the last statement as Node's `processTopLevelAwait`; the box keeps the async function from awaiting a returned Promise |
|
||||
| Prefix on line 0 | Compiled with `lineOffset: -1` | Line N of the model's code reports as line N |
|
||||
| Closing on its own line | `} })` | The model's last line can end with a `//` comment |
|
||||
|
||||
A copy declaration exists when the call does not declare the name or declares it again only with `var`; when the call declares it with `let`, `const`, `class`, or `function`, there is no copy and the call's declaration wins. Copy keywords:
|
||||
|
||||
| Case | Generated copy |
|
||||
|---|---|
|
||||
| Not declared by this call; earlier `let`, `const`, `function`, or `class` | `let` |
|
||||
| Not declared by this call; earlier `var` | `var` |
|
||||
| Declared again by this call only with `var` | `var` |
|
||||
|
||||
A copy only carries the earlier value in, and writing it as `const` would only forbid later calls from assigning to it, so an earlier `const` is copied as `let` too: later calls can assign to it, changing only the copy, while it stays `const` in the call that declares it. The kernel does not check whether a call assigns the name, so it needs no syntax-tree walk and prints no warning.
|
||||
|
||||
A call that declares a name again only with `var` gets a copy too: repeated `var` declarations in one function are one variable, so that `var` starts from the earlier value and a declaration that does not run never replaces it with `undefined`, as a global `var` behaves in node:repl. A `function` of the same name in the same call initializes at the start of the function and takes precedence over the `var`, so it gets no copy.
|
||||
|
||||
Compilation and execution:
|
||||
|
||||
```ts ignore-check
|
||||
// Kernel: ScopedReplScopes.compile
|
||||
const factory = new Script(source, { filename, lineOffset: -1, ...importOption }).runInContext(context) as ScopedReplFactory
|
||||
const getters: (() => unknown)[] = []
|
||||
const program = factory(values, getters)
|
||||
this.compiled = { bindings, getters, replaced }
|
||||
return program
|
||||
|
||||
// Evaluator: evaluate
|
||||
const filename = resolve(baseDirectory, `.ptc-repl-${++submissions}.js`) // baseDirectory: process.cwd() at creation
|
||||
const program = scopes.compile(code, { filename, context, finalExpression, ...importOption })
|
||||
const start = Reflect.apply.bind(undefined, program, undefined, []) as ScopedReplProgram
|
||||
void programDomain.run(() => Promise.resolve().then(start)).then(
|
||||
(completion) => { finish({ ok: true, value: completion?.value }) },
|
||||
(error: unknown) => { finish({ ok: false, error }) },
|
||||
)
|
||||
```
|
||||
|
||||
- The kernel always compiles with `filename` and `lineOffset: -1`, and the evaluator always passes `importModuleDynamically`: `VmModuleImportLoader.forFile(filename)` with an import handler, otherwise `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`.
|
||||
- A microtask calls the program directly, so synchronous throws carry no evaluator frames. The host receives the result with `.then` rather than `await`, which would append a host async frame.
|
||||
- Measured: `this` is `undefined`, `arguments.length` is 0, and a synchronous throw's stack holds only the program's frame; the domain catches timer errors from programs started this way; a boxed Promise is returned without being awaited.
|
||||
- Any occurrence of `__$binding_` in the code, including strings and comments, reports `SyntaxError: Names starting with '__$binding_' are reserved` at the first occurrence, and nothing runs.
|
||||
|
||||
### Kernel: scope chain, acorn scan, and compilation
|
||||
|
||||
The kernel depends only on acorn and `node:vm`, not on the child process or the evaluator, so its tests compile and run consecutive programs in a plain vm context to check scope layering on their own. Its interface:
|
||||
|
||||
```ts ignore-check
|
||||
class ScopedReplScopes {
|
||||
constructor(options: { strict: boolean; onRedeclaration?: (redeclarations: readonly ScopedReplRedeclaration[]) => void })
|
||||
/** Scan and compile one program against the current bindings; throws SyntaxError and leaves the chain unchanged. */
|
||||
compile(code: string, options: { filename: string; context: Context; finalExpression: boolean; importModuleDynamically?: ScriptOptions['importModuleDynamically'] }): ScopedReplProgram
|
||||
}
|
||||
type ScopedReplProgram = () => Promise<{ value: unknown } | undefined>
|
||||
interface ScopedReplRedeclaration { name: string; previous: ScopedReplBindingKind; current: ScopedReplBindingKind }
|
||||
type ScopedReplBindingKind = 'var' | 'let' | 'const' | 'function' | 'class'
|
||||
interface ScopedReplBinding { name: string; kind: ScopedReplBindingKind }
|
||||
interface ScopedReplScan {
|
||||
/** Top-level bindings declared by the program, in source order. */
|
||||
declarations: ReadonlyMap<string, ScopedReplBindingKind>
|
||||
/** Whether the program starts with a "use strict" directive. */
|
||||
useStrict: boolean
|
||||
/** Last top-level statement when it is an expression statement. */
|
||||
finalExpression?: { statementStart: number; expressionStart: number; expressionEnd: number }
|
||||
}
|
||||
/** Parse once; throws a SyntaxError laid out like V8's for every error acorn reports. */
|
||||
function scanProgram(code: string, options: { filename: string }): ScopedReplScan
|
||||
/** Build the Script source and every binding in the order of the read functions it pushes. */
|
||||
function buildProgramSource(
|
||||
code: string, scan: ScopedReplScan, carried: readonly ScopedReplBinding[], options: { strict: boolean; finalExpression: boolean },
|
||||
): { source: string; bindings: ScopedReplBinding[] }
|
||||
```
|
||||
|
||||
**Parsing**: regardless of the `strict` option, the kernel calls `parse(code, { ecmaVersion: 'latest', sourceType: 'script', allowAwaitOutsideFunction: true })`. These rules mostly match an async function body: top-level `await` is valid, top-level `return` is a syntax error, and two `function` declarations of one name, or a `var` and a `function` of one name, are valid. They differ in rejecting top-level `using`, `await using`, and static `import` and `export`. The scan does not decide strictness: with the option on, the Script's leading `"use strict";` does, and V8 reports strict-mode syntax violations at compilation.
|
||||
|
||||
Before parsing, the kernel checks two things: a program that starts with `#!`, or any occurrence of `__$binding_`, reports an error, and the code is not parsed.
|
||||
|
||||
**One parse yields four things**:
|
||||
|
||||
1. The call's own top-level declarations, from top-level statements only:
|
||||
|
||||
| Top-level statement | Collected names | Recorded keyword |
|
||||
|---|---|---|
|
||||
| `const`, `let`, and `var` declarations, including destructuring (objects, arrays, defaults, rest elements) | Every bound name | The original keyword |
|
||||
| `function` declarations, including async and generator functions | The function name | `function`; a `var` of the same name in the same call is recorded as `function` too |
|
||||
| `class` declarations | The class name | `class` |
|
||||
| `var` in the head of `for (var …; …; …)` and `for (var … in/of …)` | Every bound name | `var` |
|
||||
| `var` inside blocks, `try`/`catch`/`finally`, `if`/`else`, loop bodies, `switch`, labeled statements, and `with`, including `for` heads there; nested functions and classes are skipped | Every bound name | `var` |
|
||||
|
||||
2. Whether a top-level `return` exists: acorn reports `'return' outside of function` with its position.
|
||||
3. The last statement: skipping empty statements from the end, the first statement found, if it is an expression statement, records the statement's and expression's offsets.
|
||||
4. Whether the leading directives include `"use strict"`: acorn marks directive statements with `directive`, and the kernel records `useStrict`.
|
||||
|
||||
Out of scope: no search inside nested functions and classes; inside blocks only `var` is collected, while `let`, `const`, `class`, and `function` stay in their blocks; no reference analysis and no assignment search; no rewriting besides the three insertions around the final expression.
|
||||
|
||||
**Syntax errors**: when acorn fails, the kernel throws a `SyntaxError` directly without a V8 compilation. Its `stack` follows V8's layout:
|
||||
|
||||
```text
|
||||
/work/.ptc-repl-3.js:1
|
||||
const x = ;
|
||||
^
|
||||
|
||||
SyntaxError: Unexpected token
|
||||
```
|
||||
|
||||
- The message is acorn's text without its trailing `(line:column)`.
|
||||
- Two messages use V8's wording: `'return' outside of function` reports `Illegal return statement`, and an error positioned at the end of the code reports `Unexpected end of input`.
|
||||
- An occurrence of `__$binding_` reports an error with the same layout at its first position.
|
||||
|
||||
### Scope chain state and the steps of a call
|
||||
|
||||
`ScopedReplScopes` holds:
|
||||
|
||||
- `bindings: Map<string, { kind: ScopedReplBindingKind; read(): unknown }>`: the names available for copying and their read functions. `kind` is the keyword of the name's most recent declaration; a name that is only copied keeps its recorded keyword, so a `function` copied as `let` stays `function`.
|
||||
- `replaced: ReadonlyMap<string, { kind: ScopedReplBindingKind; value: unknown }>`: the values that names redeclared by the most recently adopted program had when it was compiled.
|
||||
- `compiled`: the binding order, read-function array, and `replaced` values of the most recently compiled program.
|
||||
|
||||
Each `compile(code, options)`:
|
||||
|
||||
1. Adopts `compiled`: when the read-function array holds at least one function per name, that program's prefix has run, so `bindings` maps the i-th name to the i-th read function and `replaced` takes its values. The child rejects overlapping evaluations (`overlapping PTC evaluation`), so the previous prefix always runs in a microtask before the next compilation; only two compilations in one synchronous run leave the first program unadopted.
|
||||
2. Scans the program for its declarations and final expression; a syntax error is thrown and the state stays unchanged.
|
||||
3. Calls every read function in `bindings` for its current value. When a read throws because its declaration never finished, the value from `replaced` is used; without either, the name is dropped.
|
||||
4. Copies names the call does not declare or declares again only with `var`, and collects their values in `values`; for existing names the call declares, records the value in the new `replaced` and a redeclaration `{ name, previous, current }`.
|
||||
5. Generates and compiles the source. With the `strict` option off and `useStrict` true, the inner function body starts with `"use strict";`. A V8 compile failure throws the native `SyntaxError` without the compiler frames after the error heading (the same handling as `vm-script`, in a separate copy) and leaves the state unchanged.
|
||||
6. Calls `onRedeclaration(redeclarations)` when there are redeclarations.
|
||||
7. Calls the outer function for the program, records `compiled`, and returns the program.
|
||||
|
||||
Each evaluator `evaluate(code, finish)`:
|
||||
|
||||
1. Increments the submission number, including for submissions with syntax errors; the filename is `<directory at creation>/.ptc-repl-<number>.js`.
|
||||
2. Calls `scopes.compile`; a thrown error ends the evaluation.
|
||||
3. Starts the program from a microtask inside the domain and calls `finish` when its Promise settles, taking `completion?.value` without further awaiting.
|
||||
|
||||
Reads happen in kernel step 3, when a new program is compiled. Later assignments by earlier code change only that code's own variables.
|
||||
|
||||
### Failed calls
|
||||
|
||||
| Call | Code | Result |
|
||||
|---|---|---|
|
||||
| 1 | `const data = 1` | `data` is 1 |
|
||||
| 2 | `const data = await tools.fetch()`, where `fetch` throws | Fails; call 2 declared `data` but never initialized it |
|
||||
| 3 | `data` | 1: reading call 2's `data` in kernel step 3 throws, so the value recorded when call 2 was compiled is used |
|
||||
| 4 | `let fresh = await tools.fetch()`, which throws | Fails; `fresh` is a new name |
|
||||
| 5 | `typeof fresh` | `"undefined"`: there is no earlier value, so the name is dropped |
|
||||
|
||||
- Declarations completed before a throw are kept. For example, after `let y = 5` runs and the call then throws, `y` is still 5 in later calls.
|
||||
- A `var` redeclaration starts from the copied earlier value, so reading it never throws and needs no fallback: an unreached `var` keeps the earlier value. For example, when call 2 throws before `var v = 6`, or the tool call in `var config = await tools.loadConfig({})` fails, later calls still read the earlier value. A `function` name holds the new function from the start of the call.
|
||||
|
||||
### Asynchronous failures: aligned with the REPL
|
||||
|
||||
The REPL catches errors from the asynchronous work a program starts with Node's `domain`. The evaluator does the same:
|
||||
|
||||
- On creation, the evaluator calls `domain.create()` for `programDomain` and starts every program inside `programDomain.run(...)`. Timers, callbacks, Promise continuations, and EventEmitters that the program creates belong to that domain.
|
||||
- `programDomain.on('error', ...)` passes `Uncaught ` followed by the error text to `options.reportError`. The text is the error's `stack`, or `name: message` when the stack is not a string; errors are not formatted with `util.inspect` because the domain adds `domain` and `domainThrown`, which inspect would print. A value that is not an error is formatted with `util.inspect` after deleting those two properties, as node:repl does.
|
||||
- Programs can make this formatting throw through a `stack` accessor, `toString`, or custom inspection. A throw from the listener would end the process, so the formatting runs in `try`/`catch` and a failure reports `program threw an unrenderable value`, the same fallback text as `prepareException` for synchronous failures. The `reportError` call stays outside the `try` because it is the child's own code, whose failures must surface.
|
||||
- When a callback throws a frozen or non-extensible object, Node's domain fails to add its properties before calling the listener, and the process ends, as with node:repl.
|
||||
- The child handles `reportError` unchanged: an active evaluation fails with the error; otherwise the error is discarded. Errors belong to the evaluation that created their callback (AsyncLocalStorage).
|
||||
- No process-wide `uncaughtException` or `unhandledRejection` handler is registered, so errors in the child's own code still surface.
|
||||
- When a program calls a tool, the asynchronous callbacks that the child creates for the call, such as RPC callbacks, also belong to the program's domain: an asynchronous error in the child's own code inside those callbacks is reported as the program's `Uncaught …` failure, and the child keeps running. The existing REPL evaluator behaves the same.
|
||||
|
||||
Verified cases:
|
||||
|
||||
- REPL: timer throws and unhandled Promise rejections are caught both after and during an evaluation; an EventEmitter `error` event is caught after an evaluation.
|
||||
- A standalone domain: in the main realm it catches timer throws, rejections created in timers, failures of unawaited async functions, and EventEmitter `error` events; in a context with the default `codeGeneration` limits it catches timer throws and rejections created in timers; timer throws from programs started by a microtask are caught too.
|
||||
|
||||
### Dynamic import
|
||||
|
||||
- A program's `import()` goes through its Script's `importModuleDynamically`: `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER` without an import handler, and the existing `VmModuleImportLoader.forFile(filename)` with one, as in `vm-script`.
|
||||
- Relative specifiers resolve from the directory where the evaluator was created, which is the working directory of the environment's first call; later directory changes do not move it. node:repl and `vm-script` follow each call's directory; after the Agent changes directory with `working_directory`, import with an absolute path to use the new directory.
|
||||
- There is no `require`: node:repl's `require` resolves inconsistently (relative paths follow the current directory but are cached after their first resolution; packages resolve from the startup directory), so dynamic `import()` is the only way to load modules.
|
||||
|
||||
### Redeclaration notice (reserved)
|
||||
|
||||
The kernel calls `onRedeclaration` in step 6; the evaluator injects its `reportRedeclarations(redeclarations: readonly ScopedReplRedeclaration[])`, whose body stays empty with one `TODO` comment and prints nothing. A future notice writes to the program's `console` here, which makes it model-visible output.
|
||||
|
||||
### Out of scope
|
||||
|
||||
- Memory reclamation: not handled; every call copies every name. Earlier calls without surviving closures are collected; when a call leaves a surviving function, that function keeps every value copied into that call.
|
||||
- Resolving `import()` from the working directory as it changes: an explicit operation such as `js_switch_cwd` can be added when needed.
|
||||
- Reading the earlier value of a name in its own `let`, `const`, or `class` redeclaration, such as `let count = count + 1`: a program error.
|
||||
- Problems from mixing strict and sloppy calls with the `strict` option off, listed under Risks: left to a future reset tool.
|
||||
- The column shift on the final expression's line.
|
||||
|
||||
### Integration
|
||||
|
||||
The `scoped-repl` format connects the evaluator with only the changes the connection requires, without refactoring or reusing existing code, so rebases and merges with other ongoing PTC work stay simple. The program format is `scoped-repl` and the Config field is `replScoped`.
|
||||
|
||||
| Location | Change |
|
||||
|---|---|
|
||||
| `PtcProgramFormat` in `ptc-runtime` | Includes `'scoped-repl'` |
|
||||
| `config.ts` in `ptc-runtime-node` | The boolean field `replScoped`, accepted only with `persistent-in-memory` and rejected at load otherwise; when omitted, `resolveReplScoped` takes the value that `resolvePersistentExecution` writes for function bodies with `persistent-in-memory`, currently true, and false in other modes |
|
||||
| `execution.ts` in `ptc-runtime-node` | In the `persistent-in-memory` branch with `replScoped`, format `scoped-repl`, `retainsState` true, REPL-statement TypeScript erasure, and new model guidance |
|
||||
| `evaluators/index.ts` in `ptc-runtime-node` | The evaluator table maps `scoped-repl` to this evaluator with the default of all three options |
|
||||
| `protocol.ts` in `ptc-runtime-node` | The protocol version is 3, so older bootstraps fail at readiness; the upgrade guide `docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/` also covers the new `PtcProgramFormat` member |
|
||||
| `host.ts` in workflow-ptc | `scoped-repl` uses the same wrapper as `repl`, `await (async () => {…})()` |
|
||||
| `configuration.ts` in `ptc-runtime-node` (used by CUA to merge settings) | `resolvePersistentExecution` returns `executionMode`, `scriptPersistence`, and `replScoped` to merge together: `script` keeps retained VM Scripts with `replScoped: false`, `scoped-repl` yields `replScoped: true`, and function bodies and REPL statements yield `persistent-in-memory` with the constant `SCOPED_REPL_BY_DEFAULT`, currently true, replacing a stale profile value. That constant also sets the omitted default in `config.ts`, so changing it changes one line; `config.ts` imports this function from `configuration.ts`, which is itself a published package entry, and `configuration.ts` imports only the `Config` type, so the build emits no shared chunk |
|
||||
| Documentation, snapshots, and tests | Package README configuration, behavior, and known limitations; the config catalog; the snapshot scenario `ptc-scoped-repl`; a built-artifact e2e case with `replScoped: true` |
|
||||
|
||||
tool-executor-ptc is unchanged: for every format other than `function-body` it uses its printing guidance. The model guidance states the exact behavior above, especially: output uses `inspect(...)`, in a sentence shared with the other modes; top-level `return` is unsupported; copies happen when a call starts and earlier code is unaffected; shared mutable state belongs in objects; an assignment without declaration changes only the copy, including for earlier `const` names; a `let`, `const`, or `class` redeclaration cannot read the earlier value of its name, so assign to the name or use a new one to compute from it; a `var` redeclaration starts from the earlier value; when a call fails, an unfinished `let`, `const`, `class`, or `var` redeclaration keeps the earlier value; a `var` inside a block is also a top-level name of the call, while other block declarations stay in their block; modules load only with `import()`, whose relative specifiers resolve from the directory of the environment's first call. Tests pin the model guidance verbatim.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Nesting each call in the previous call's scope with direct eval.** Calls can share live bindings, but earlier scopes are never reclaimed, positions require a source map or stack rewriting, and direct eval is unavailable in a context that forbids code generation from strings.
|
||||
|
||||
**Rewriting declarations as `var` or global assignments.** Every call shares one binding, which violates requirement 2, and model code must be rewritten.
|
||||
|
||||
**Compiling each call as an ES module.** Each module receives values through a synthetic module for the previous call and an appended `export`. Modules allow neither `return` nor a final value, and the prelude shifts every reported line; function parameters already pass values without modules.
|
||||
|
||||
**Scope analysis with rewritten references.** Allows finer memory reclamation, but needs scope analysis and code rewriting, which violates requirement 5.
|
||||
|
||||
**Printing only, without a final expression.** workflow-ptc and the `repl` format contract depend on completion values, and it departs from the existing REPL syntax.
|
||||
|
||||
**Results from top-level `return`.** Conflicts with requirement 3, requires the function-body format, and changes the run_code guidance.
|
||||
|
||||
**Awaiting a final Promise.** Matches `vm-script` but not the existing REPL; boxing as Node does keeps the REPL behavior.
|
||||
|
||||
**Results for programs ending with `if`, `for`, or a block.** Only Script top-level code has V8 completion values, which a function body lacks; supporting them requires rewriting more statements. node:repl has no result there either when the code contains `await`.
|
||||
|
||||
**Writing the wrapper as `async function (__$binding_vals, __$binding_getters)`.** `this` is also `undefined`, but the program's `arguments` exposes both internal values and has length 3.
|
||||
|
||||
**An async arrow wrapper.** `this` is `globalThis` and `arguments` does not exist, as in the REPL; ours uses `undefined`, as a strict function call without a receiver does.
|
||||
|
||||
**Returning read functions through a callback.** The prefix would need name strings and protection against repeated calls; pushing into an array that the evaluator maps by index is simpler.
|
||||
|
||||
**Recompiling with V8 for syntax errors.** Yields V8's wording at the cost of another compilation; acorn already provides the position and message.
|
||||
|
||||
**Module rules for strict programs.** Module rules are stricter than an async function body: two `function` declarations of one name, a `var` and a `function` of one name, and `await` as a variable name in a nested ordinary function are rejected, and HTML-like comments are handled differently from V8's Script compilation. They are unusable with strict mode off, because module code is always strict.
|
||||
|
||||
**Scanning inside the same function wrapper as the runtime.** Matches the runtime grammar exactly and accepts top-level `using`, as Node's `processTopLevelAwait` does. It requires a statement walk to find top-level `return`, position mapping for the wrapper, and a guard against an extra `}` in the code closing the wrapper early; top-level `using` is not needed, so script rules are simpler.
|
||||
|
||||
**Copying only assigned `const` names as `let`, with a warning.** This walks the new call's syntax tree and tracks shadowing, which is scope analysis and violates requirement 5. Ours copies every `const` as `let` without a notice.
|
||||
|
||||
**Starting a `var` redeclaration from `undefined` without a copy.** `var count = count + 1` then yields `NaN`, but a `var` not reached before a throw or in a branch that is not taken replaces the earlier value with `undefined`; for example, a failed tool call in `var config = await tools.loadConfig({})` leaves later calls without the earlier `config`. With the copy, `var count = count + 1` adds to the earlier value, as in node:repl, which is accepted for now.
|
||||
|
||||
**Falling back only when a call failed and the value reads `undefined`.** It needs no copy, but cannot tell an unreached declaration from one that ran and assigned `undefined`: a call that assigns `undefined` and then fails falls back by mistake, and an untaken branch or `var x;` without an initializer in a successful call is not covered.
|
||||
|
||||
**Marking in the code whether each `var` ran.** It distinguishes the cases exactly but rewrites model code at declarations, earlier assignments, and loop heads, which violates requirement 5.
|
||||
|
||||
**Skipping copies of strict-mode reserved words in strict calls.** It would keep names such as `package`, declared in a sloppy call, from breaking later strict calls; the problem comes from the model mixing both modes, so it is left to a future reset tool.
|
||||
|
||||
**A process-wide handler for uncaught errors.** It would also swallow errors from the child's own code; the REPL's domain covers only the asynchronous work programs start.
|
||||
|
||||
**Not collecting `var` declarations inside blocks.** A block-level `var` then collides with the copy declarations, so the whole program reports `already declared`, and the name is not carried to later calls; collecting it takes about 15 lines of statement traversal without reference analysis, so the scanner collects it.
|
||||
|
||||
**Showing only `.ptc-repl-<number>.js` in stacks, without the directory.** Without the directory, Node's default loader resolves relative `import()` specifiers from the current directory at import time, unlike calls with an import handler; a `//# sourceURL` comment that shows only the name makes V8 ignore `lineOffset`, so every line number grows by 1; handing imports to a callback would work, because both child launches pass `--experimental-vm-modules` and the callback can start `import()` from the first call's directory, but it requires scoped REPL imports to always go through a callback, which the default path does not do yet. The filename therefore keeps the directory of the first call for now.
|
||||
|
||||
**Providing `require`, `module`, and built-in module globals, as node:repl does.** node:repl's `require` resolves inconsistently, and following directory changes needs a rule for when the base moves; only `import()` remains.
|
||||
|
||||
## Consequences
|
||||
|
||||
Gains:
|
||||
|
||||
- Later calls may declare an earlier name again with any keyword, while earlier functions, closures, and still-running code keep their values.
|
||||
- Syntax, results, errors, and asynchronous failure handling match the existing REPL, and asynchronous program failures do not end the process.
|
||||
- There is no scope analysis, and model code is rewritten only at the three insertion points of the final expression.
|
||||
|
||||
Costs:
|
||||
|
||||
- Copying at call start differs from the REPL: assignments that earlier code, such as timers and callbacks, makes to top-level variables afterwards are invisible to later calls; the model guidance states this.
|
||||
- An assignment without declaration affects only later calls and is invisible to earlier functions; in the REPL both sides change.
|
||||
- Strict mode differs from the REPL: assigning an undeclared name creates a global in the REPL and throws here.
|
||||
- For callers that keep completions, a final Promise without `await` makes the host report a non-JSON completion, as in the existing REPL; `run_code` discards completions and is unaffected.
|
||||
- Programs ending with `if`, `for`, or a block have no result, while node:repl has one when the code contains no `await`.
|
||||
- On the final expression's line, columns after the insertion point shift right by 17.
|
||||
- Syntax error messages use acorn's text, which differs from V8's, for example `Unexpected token` instead of `Unexpected token ';'`.
|
||||
- Scanning always uses script rules, so top-level `using` and `await using` are rejected; node:repl does not support them either.
|
||||
- Top-level `arguments` is an empty arguments object, while it does not exist in node:repl.
|
||||
- The context forbids code generation from strings by default: code relying on `eval` or `new Function` fails, including libraries loaded into this context through an import handler. The limit is no isolation, because copied main-realm functions such as `setTimeout.constructor` still generate code.
|
||||
- There is no `require`: code that relies on it must use `await import()` instead.
|
||||
- Relative `import()` keeps resolving from the directory of the environment's first call, also after the Agent changes directory.
|
||||
- Node documents `domain` as deprecated; node:repl still builds on it, so a removal would change the REPL as well.
|
||||
- An error in the child's own code inside a tool call's asynchronous callbacks is reported as the program's `Uncaught …` failure, and the child keeps running, as with the existing REPL.
|
||||
- Programs that start with `#!` are rejected.
|
||||
- Any occurrence of `__$binding_`, including in strings and comments, is rejected; internal names written with escapes such as `\u005f` are not checked.
|
||||
- acorn must keep pace with V8's syntax, or newer syntax is rejected before it runs.
|
||||
- A `var` redeclaration starts from the earlier value: `var count = count + 1` adds to it, as in node:repl, also when the earlier declaration was `let` or `const`, where node:repl reports `already declared`.
|
||||
- A `let`, `const`, or `class` redeclaration cannot read the earlier value of its name and throws, as in `let count = count + 1`. This is a program error and is not handled.
|
||||
- Every earlier `const` is copied as `let` into later calls, which can assign to it without any notice.
|
||||
- With the `strict` option off, strict and sloppy calls can mix: a sloppy call that assigns an undeclared name creates a global shared by every call and earlier function, and a name declared in a sloppy call with a strict-mode reserved word (`package`, `public`, `private`, `protected`, `interface`, `implements`, `static`, `let`, `yield`, `eval`, `arguments`) makes later strict calls fail to compile. This is not handled and is left to a future reset tool.
|
||||
- When a callback throws a frozen or non-extensible object, Node's domain handling fails and the process ends, losing retained variables, as with node:repl.
|
||||
- Every call generates a copy declaration and a read function for every earlier name: the prototype measured about 10 ms per call with 1000 names.
|
||||
- When a call leaves a surviving function, every value copied into that call stays in memory.
|
||||
|
||||
## Testing
|
||||
|
||||
- The kernel tests pass on their own and cover script-rule parsing and detection of a leading `"use strict"`, every statement in the declaration table, top-level `return` including inside blocks, locating and boxing the final expression, programs that start with `#!`, occurrences of `__$binding_`, the syntax-error layout with both message substitutions, and the generated source; with the `strict` option off, a leading `"use strict"` takes effect both with and without copies; running consecutive programs in a plain vm context, they cover every item under Across calls, including keyword combinations, failed calls, timers, function redefinition, and redeclaration notices.
|
||||
- The evaluator tests use the evaluator and a real vm context and cover every item under Syntax and results, Environment, Errors, and Asynchronous failures and lifecycle, plus cross-call behavior through the evaluator, including that the global object's prototype chain does not reach the main realm's `Function` while copied main-realm functions such as `setTimeout.constructor` still generate code, and that host bindings named `module` or `require` stay untouched.
|
||||
- Every option is tested on and off.
|
||||
- Top-level `this` is `undefined`, `arguments.length` is 0, and a synchronous throw's stack holds only the program's frames.
|
||||
- Asynchronous failures: each listed case is tested after and during an evaluation; the text passed to `reportError` starts with `Uncaught `; the process keeps running and variables are retained. A missing `stack`, a throwing `stack` accessor, and throwing custom inspection report `name: message` or the fixed text without ending the process; a thrown plain object is reported without `domainThrown`.
|
||||
- Imports: both the default loader and an import handler; relative specifiers resolve from the directory at creation, also after the working directory changes.
|
||||
- The built-artifact e2e covers `replScoped: true`.
|
||||
- Tests that mount `persistent-in-memory` set `replScoped` explicitly, and retained-execution tests run both values; one test checks the default when it is omitted.
|
||||
- New files have 100% coverage; existing evaluators and their tests are unchanged.
|
||||
@@ -0,0 +1,524 @@
|
||||
# Agent Note: 保留状态 PTC 的 scoped REPL 求值器
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-retained-ptc-scoped-repl.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
`persistent-in-memory` 用 node:repl 在同一个全局作用域里执行同一个 Agent 的每次 `run_code`([尽力保留 PTC 状态](../../implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md))。模型在后面的调用里再次声明前面用过的 `const`、`let`、`class` 名字时,V8 在执行前就报 `SyntaxError: Identifier 'x' has already been declared`,整段代码一行都不执行。模型说明只能要求"不要重复声明",但模型在多轮调用里很难记住每个名字。
|
||||
|
||||
把声明改成 `var` 能消除报错,但所有调用共用同一个绑定,后面的声明会改掉前面的函数、闭包和后台任务读到的值:
|
||||
|
||||
```js
|
||||
// call 1
|
||||
var value = 1
|
||||
var read = () => value
|
||||
// call 2
|
||||
var value = 2 // no error
|
||||
// call 3
|
||||
read() // 2: call 2 changed the read written by call 1
|
||||
```
|
||||
|
||||
需要同时满足五条要求:
|
||||
|
||||
1. 后面的调用可以用任意关键字再次声明前面的名字,不报错。
|
||||
2. 再次声明只对这次和之后的调用生效;前面的函数、闭包和仍在运行的代码继续使用它们原来的值。
|
||||
3. 写法与现有 REPL 一致:支持顶层 `await`,最后一个表达式的值是结果,不支持顶层 `return`。
|
||||
4. 异步回调里的错误与现有 REPL 一样处理:进程不退出,变量保留。
|
||||
5. 不做作用域分析,不改写模型代码里的声明和引用;acorn 只用来列出顶层声明、找到最后一条语句。
|
||||
|
||||
## 决策
|
||||
|
||||
scoped REPL 求值器分成内核和求值器两个文件:
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl.ts` | 内核:作用域链 `ScopedReplScopes`,负责状态表、拷贝与退回旧值、重复声明、编译成 Script;以及 acorn 扫描、顶层声明与关键字、顶层 `return` 检查、最后一条表达式、保留名检查、语法错误格式化、拼源码 |
|
||||
| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl-evaluator.ts` | 求值器:导出 `createScopedReplEvaluator(options)`,实现现有的 `ProgramEvaluator` 接口,把内核接入现有模式:执行环境和开关、动态 import 与 import 处理器、由微任务启动程序并取完成值、domain、注入 `reportRedeclarations` |
|
||||
| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl.spec.ts` | 只测内核,可以单独运行:扫描、拼源码,以及在普通 vm context 里连续执行多段程序的作用域分层 |
|
||||
| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-evaluator.spec.ts` | 测接入层:完成值、执行环境、模块与 import、报错、异步错误;三个开关打开、关闭两种状态都测 |
|
||||
|
||||
求值器以 `scoped-repl` 格式接入现有执行模式,见"接入"。
|
||||
|
||||
### 精确行为
|
||||
|
||||
#### 写法与结果
|
||||
|
||||
- 程序是一组语句,支持顶层 `await`。
|
||||
- 最后一条非空的顶层语句是表达式语句时,它的值就是结果。值是 Promise 时不等待,Promise 本身就是结果,宿主会报 `program completion must be lossless JSON`,和现有 REPL 一样。这一项由 `finalExpression` 开关控制,默认开;关闭后末尾表达式的值被丢弃,结果只能靠打印,模型说明要随之调整。`run_code` 对 TypeScript 运行时传 `discardCompletion: true`,宿主丢弃完成值,模型用 `inspect(...)` 输出;不丢弃完成值的调用方(例如 workflow-ptc)仍以末尾表达式的值为结果。
|
||||
- 最后一条是声明、`if`、`for`、块等其他语句时,没有结果。
|
||||
- 顶层 `return`,包括写在顶层 `if`、循环和块里的,报 `SyntaxError: Illegal return statement`,这次一行都不执行。经 `run_code` 执行时,宿主的 TypeScript 擦除会先拒绝它,报 `Return statement is not allowed here`,和现有 REPL 相同。
|
||||
- 静态 `import`、`export` 报 acorn 的 `SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'`;顶层 `using`、`await using` 同样被 acorn 拒绝,块里和函数里可以用。
|
||||
- 以 `#!` 开头的程序报 `SyntaxError: Hashbang lines are not supported`,这次不执行:`#!` 只能出现在 Script 的最开头,而生成的前缀排在程序前面。
|
||||
- 输出是 `inspect(...)` 等打印的内容;调用方不丢弃完成值时,再加上末尾表达式的值。
|
||||
|
||||
#### 跨次调用
|
||||
|
||||
- 每次调用开始时,把前面留下的每个顶层名字拷贝成本次的同名声明;对象按引用共享,修改对象内部两边都看得到。
|
||||
- 可以用任意关键字再次声明前面的名字,包括 `var`→`let`→`const`→`class`→`function` 依次换。本次用 `let`、`const`、`class`、`function` 声明的名字不再拷贝,以本次为准;只用 `var` 重新声明的名字照样拷贝,这次的 `var` 从旧值开始。
|
||||
- 不声明、直接给前面的名字赋值,改的是本次的拷贝:之后的调用看到新值,前面定义的函数仍看到旧值。前面用 `const` 声明的名字也一样,它只在声明它的那次调用里不能赋值。
|
||||
- 重定义函数后,前面定义的调用方仍然调用旧函数。
|
||||
- 本次开始以后,前面的代码(定时器、回调)再给顶层变量赋值,之后的调用看不到;需要共享的可变状态放进对象。
|
||||
- 前面定义的函数看不到后面才声明的名字,引用时报 `ReferenceError`。
|
||||
- 一次调用用 `let`、`const`、`class` 重新声明了某个名字,这次调用里的所有引用都指向新声明,包括写在声明之前的,拿不到旧值:在声明执行前读取报原生的 `ReferenceError: Cannot access 'x' before initialization`。这类写法是代码本身的问题,不做处理。用 `var` 重新声明时,这次的 `var` 从旧值开始,直到被赋上新值,例如 `var count = count + 1` 在旧值上加 1;`function` 从调用开始就是新函数。
|
||||
- 一次调用中途出错时:抛错前已经执行完的声明保留;重新声明了已有名字、但没来得及赋值的,之后的调用退回旧值;没来得及赋值的新名字直接丢掉。
|
||||
- 块里(包括 `try`/`catch`/`finally`、`if`/`else`、循环体、`switch`、标签语句)声明的 `var` 会提升到这次调用的顶层,和顶层 `var` 一样算这次的声明:带到之后的调用,也可以和前面任何关键字声明的名字同名。嵌套的函数和类里的 `var` 不算。
|
||||
- 没执行到的 `var` 再次声明,不论在抛错之后还是在没走到的分支里,都保留旧值;不带初始值的 `var x;` 也保留旧值。
|
||||
|
||||
#### 执行环境
|
||||
|
||||
下面是默认行为,前两项各由一个开关控制,见"执行环境与开关"。
|
||||
|
||||
- strict 模式:给未声明的名字赋值报 `ReferenceError`;有意的全局变量写 `globalThis.x`。开关关闭时不强制:程序以 `"use strict"` 开头,这次就按严格执行,否则按宽松执行。
|
||||
- 禁止从字符串生成代码:执行环境自己的 `eval`、`new Function` 报 `EvalError`,从字节编译 WebAssembly 报 `CompileError`。这不构成隔离:从主环境复制进来的函数(例如 `setTimeout.constructor`)仍能在主环境里生成代码。
|
||||
- 只能用动态 `import()` 加载模块,相对路径按这个环境第一次调用时的 working directory 解析,之后的调用换了目录也不变;不提供 `require`、`module` 和 `fs`、`path` 这类内置模块全局。读写文件的相对路径仍跟随当前目录。
|
||||
- 顶层 `this` 是 `undefined`,按宽松执行时是 `globalThis`;顶层 `arguments` 是一个空的 arguments 对象,长度为 0。
|
||||
- 顶层 `var` 和 `function` 不会成为 `globalThis` 的属性。
|
||||
- `setTimeout`、`Buffer`、`fetch`、`URL`、`structuredClone` 等 Node 全局对象可用。
|
||||
|
||||
#### 报错
|
||||
|
||||
- 运行时报错的行号、列号是模型代码里的原生位置,跨次调用定义的函数显示它自己那次的文件名,例如 `<目录>/.ptc-repl-1.js:2:9`。最后一条表达式所在的那一行,插入点之后的列号右移 17,这次不处理。
|
||||
- acorn 发现的语法错误直接报 acorn 的消息和位置,按 V8 的样式排版:文件名加行号、源码行、箭头。有两处消息改用 V8 的说法:顶层 `return` 报 `Illegal return statement`;报错位置在代码末尾时报 `Unexpected end of input`。
|
||||
- acorn 放行、V8 编译时才发现的错误,报 V8 原生的消息;strict 开关打开时,严格模式的语法违规(例如 `with`)也在这一步报出。
|
||||
- 以上是求值器自己的行为。经 `run_code` 执行时,宿主的 TypeScript 擦除先解析整段代码,多数语法错误由它报告,和现有 REPL 相同;只有擦除接受、扫描拒绝的代码(例如保留名、静态 `import`、顶层 `using`)才会看到上面的版式。
|
||||
- 运行时错误报错误名加堆栈,没有 `Uncaught ` 前缀,堆栈里没有求值器自己的帧。
|
||||
|
||||
#### 异步错误与生命周期
|
||||
|
||||
- 程序启动的定时器、回调、Promise 后续步骤和 EventEmitter 抛出的错误,以及未处理的 rejection,不让进程退出,变量保留。例外:回调里 `throw` 的是冻结或不可扩展的对象时,Node 的 domain 在通知监听器之前给它加属性失败,进程结束,和 node:repl 相同;以这样的对象 reject 不受影响。
|
||||
- 当时有执行在运行,就让那次执行以 `Uncaught ` 加错误文本失败;否则丢弃。错误文本取错误的 `stack`,`stack` 不是字符串时用"名字: 消息";不是 Error 的值,先去掉 domain 加上的 `domain`、`domainThrown` 再用 `util.inspect`;转换出错时报 `program threw an unrenderable value`。错误按创建回调时所属的执行归属,前一次留下的定时器在后一次运行时抛错,不会算到后一次头上。
|
||||
- 执行结束后才打印的输出被丢弃;超时、取消和重置沿用现有的宿主逻辑([保留状态的 PTC 中断](../../implemented/architecture/2026-10-29-retained-ptc-interruption.zh.md))。
|
||||
|
||||
### 与 node:repl、vm-script 的对比
|
||||
|
||||
✓ 表示支持,✗ 表示不支持,"—" 表示不适用:不开持久化的 `vm-script` 每次调用都是新进程,没有跨次状态。"持久化 vm-script"指设置 `scriptPersistence: true` 的 vm-script(#7992),"两种 vm-script"指它和不开持久化的 vm-script。"我们"一列是默认行为,括号里写和哪几列一致;执行环境一组把"我们"分成 strict 开启(默认)和关闭两列。跨次调用一组多列一项"预期支持跨次调用能力的一种实现",括号和备注里简称"预期实现"。
|
||||
|
||||
**写法与结果**
|
||||
|
||||
| 能力 | node:repl(现有 REPL 求值器) | 我们 | vm-script(不开持久化) | vm-script(开持久化,#7992) | 备注 |
|
||||
|---|---|---|---|---|---|
|
||||
| 顶层 `return`,包括写在 `if` 块里的 | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | 都报 `Illegal return statement` |
|
||||
| 末尾表达式作为结果 | ✓ | ✓(默认;与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 可以用 `finalExpression` 开关关闭 |
|
||||
| 末尾是 Promise 时等它完成 | ✗ | ✗(与 node:repl 一致) | ✓ | ✓ | 不等时宿主报"不是 JSON" |
|
||||
| 以 `if`、`for`、块结尾时有结果 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 含 `await` 时一致) | ✓ | ✓ | node:repl 和两种 vm-script 只在代码不含 `await` 时有结果 |
|
||||
| 顶层 `await` | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | node:repl 和两种 vm-script 靠改写整段代码;我们只改写最后一条表达式 |
|
||||
| 静态 `import` | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | 我们报 acorn 的消息 |
|
||||
| 顶层 `using` | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | 块里和函数里可以用 |
|
||||
| 以 `#!` 开头的程序 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 我们报 `Hashbang lines are not supported` |
|
||||
| 同一次里两个同名 `function`,或同名的 `var` 和 `function` | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | |
|
||||
| 动态 `import()` | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | |
|
||||
|
||||
**跨次调用**
|
||||
|
||||
| 能力 | node:repl | 预期支持跨次调用能力的一种实现 | 我们 | vm-script | 持久化 vm-script | 备注 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 跨次保留变量 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | ✗ | ✓ | node:repl 和持久化 vm-script 共用一个作用域;我们靠拷贝;预期实现也靠拷贝 |
|
||||
| 用任意关键字再次声明 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | node:repl 和持久化 vm-script 的 25 种关键字组合里 21 种报 `already declared`,只有 `var`、`function` 之间可以;我们预留重复声明提示,暂不输出;预期实现对 `const` 再次声明为 `const` 多输出一行警告 |
|
||||
| 后面不声明直接赋值,前面定义的函数不受影响 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | |
|
||||
| 不重新声明,直接给前面的 `const` 赋值 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | node:repl 和持久化 vm-script 报 `TypeError`;我们不提示;预期实现先打印警告 |
|
||||
| 用 `var` 重新声明时读到同名旧值(`var n = n + 1`) | ✓ | ✗ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | node:repl 和持久化 vm-script 只在前面也是 `var` 时成立,前面是 `let` 时报 `already declared`;我们前面是 `let`、`const` 时也成立;预期实现得到 `NaN` |
|
||||
| 重定义函数后,旧的调用方仍调旧函数 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | |
|
||||
| 前面的代码之后改的值,后面的调用能看到 | ✓ | ✗ | ✗(与预期实现一致) | — | ✓ | 定时器自增的变量,间隔 30 ms 读两次:node:repl 23、50;持久化 vm-script 22、44;我们 0、0;预期实现 15、15 |
|
||||
| 前面定义的函数能看到后面才声明的名字 | ✓ | ✗ | ✗(与预期实现一致) | — | ✓ | 我们报 `ReferenceError` |
|
||||
| 修改对象内部,两边都看得到 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | — | ✓ | |
|
||||
| 初始化抛错后,这个名字还能继续用 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | node:repl 和持久化 vm-script 里新名字永久不可用,再次声明报 `already declared`;我们已有名字退回旧值,新名字丢掉 |
|
||||
| 抛错前已经执行完的声明会保留 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | — | ✓ | |
|
||||
| 抛错前没执行到的 `var` 再次声明,保留旧值 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | — | ✓ | 我们把旧值拷进这次的 `var`,没走到的分支里的 `var` 也保留旧值;预期实现靠插入标记代码做到 |
|
||||
| 块里新声明的 `var` 带到下一次 | ✓ | ✗ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | 我们收集块里的 `var` |
|
||||
| 块里的 `var` 和已有的 `let` 同名时不报错 | ✗ | ✗ | ✓(与 node:repl、预期实现、持久化 vm-script 都不一致) | — | ✗ | node:repl 和持久化 vm-script 报 `already declared`;我们把它算作这次的新声明;预期实现也报 `already declared` |
|
||||
|
||||
**执行环境**
|
||||
|
||||
| 能力 | node:repl | 我们(strict,默认) | 我们(非 strict) | vm-script | 持久化 vm-script | 备注 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| strict 模式 | ✗ | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | strict 关闭时,程序自己开头的 `"use strict"` 仍然生效 |
|
||||
| 给未声明的名字赋值会创建全局变量 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 非 strict 时创建的全局变量由所有调用和前面的函数共用,不走拷贝 |
|
||||
| 顶层 `var`、`function` 挂到 `globalThis` | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | |
|
||||
| 顶层 `this` 是 `globalThis` | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 我们 strict 时是 `undefined` |
|
||||
| 顶层 `arguments` | ✗ | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗ | ✗ | 我们的是空的 arguments 对象 |
|
||||
| `eval`、`new Function` | ✓ | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 可打开;只限执行环境自己的,复制进来的主环境函数仍能生成代码 |
|
||||
| 编译 WebAssembly | ✓ | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 与 `eval` 同一个开关 |
|
||||
| Node 全局对象(`setTimeout`、`Buffer`、`fetch`、`URL`、`structuredClone`) | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | |
|
||||
| `require`、`module`、`fs` 等内置模块全局 | ✓ | ✗(与 vm-script、持久化 vm-script 一致) | ✗(与 vm-script、持久化 vm-script 一致) | ✗ | ✗ | 只能用 `import()` |
|
||||
| 相对路径的 `import()` 跟随之后的目录变化 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 我们固定用这个环境第一次调用时的目录 |
|
||||
| `_`、`_error` | ✓ | ✗(与 vm-script、持久化 vm-script 一致) | ✗(与 vm-script、持久化 vm-script 一致) | ✗ | ✗ | |
|
||||
| 以 `{ a: 1 }` 开头的代码当对象字面量 | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | node:repl 原本当对象,现有 REPL 求值器强制改成语句块 |
|
||||
|
||||
**报错**
|
||||
|
||||
| 能力 | node:repl | 我们 | vm-script | 持久化 vm-script | 备注 |
|
||||
|---|---|---|---|---|---|
|
||||
| 报错行列号准确(代码不含 `await`) | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 我们的例外是最后一条表达式所在行 |
|
||||
| 报错行列号准确(代码含 `await` 时的第 1 行) | ✗ | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗ | ✗ | node:repl 和两种 vm-script 把第 22 列报成第 54 列 |
|
||||
| 语法错误带源码行和箭头 | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 我们按 acorn 给出的位置自己排版;这是求值器层的行为,经 `run_code` 时多数语法错误先由宿主的 TypeScript 擦除报告,与 node:repl 列相同 |
|
||||
| 语法错误消息是 V8 的原文 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 我们用 acorn 的消息,acorn 放行、V8 拒绝的错误用 V8 原文 |
|
||||
| 代码不完整时有明确提示 | ✗ | ✓(与 vm-script、持久化 vm-script 一致) | ✓ | ✓ | node:repl 的报错消息为空;经 `run_code` 时同样先由宿主擦除报告 |
|
||||
| 报错带错误名和堆栈 | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | |
|
||||
| 同步错误和 `await` 失败带 `Uncaught ` 前缀 | ✓ | ✗(与 vm-script、持久化 vm-script 一致) | ✗ | ✗ | |
|
||||
| 异步回调错误带 `Uncaught ` 前缀 | ✓ | ✓(与 node:repl 一致) | — | — | 两种 vm-script 的进程直接退出,没有这类报告 |
|
||||
|
||||
**异步错误与生命周期**
|
||||
|
||||
| 能力 | node:repl | 我们 | vm-script | 持久化 vm-script | 备注 |
|
||||
|---|---|---|---|---|---|
|
||||
| 执行结束后回调里出错,进程不崩、变量保留 | ✓ | ✓(与 node:repl 一致) | — | ✗ | 持久化 vm-script 的进程退出,下一次调用报 `worker-exit`,变量全部丢失;不开持久化时执行结束后进程已关闭;回调里 `throw` 冻结的对象时,node:repl 和我们的进程都会结束 |
|
||||
| 执行中回调里出错,只让这次失败、变量保留 | ✓ | ✓(与 node:repl 一致) | ✗ | ✗ | 两种 vm-script 的进程都退出,报 `worker-exit`,持久化 vm-script 的变量丢失 |
|
||||
| 执行结束后才打印的输出被丢弃 | ✓ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | |
|
||||
| 超时或取消后变量可以保留 | ✓ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | 前提是程序确认已经停住 |
|
||||
数据来源:node:repl、vm-script 和持久化 vm-script 三列直接调用 master 的求值器实测(Node v24.18.0)。持久化 vm-script 用同一个求值器连续执行;一次调用内的各行与 vm-script 相同,跨次调用各行和两行异步错误单独实测,异步错误经真实子进程。"我们"一列的跨次调用各项由 `scoped-repl.spec.ts` 测试,其余各项由 `scoped-repl-evaluator.spec.ts` 测试。不开持久化的 vm-script 两行异步错误按现有实现推断;node:repl、持久化 vm-script 和我们的超时、取消、重置沿用同一套宿主逻辑。预期实现一列在该实现上实测,每个用例新开一个环境。
|
||||
|
||||
### 执行环境与开关
|
||||
|
||||
一个求值器只有一个执行环境。`codeGeneration` 开关关闭(默认)时这样创建:
|
||||
|
||||
```ts ignore-check
|
||||
const runtimeContext = vm.createContext(Object.create(null), { codeGeneration: { strings: false, wasm: false } })
|
||||
```
|
||||
|
||||
- Node 全局对象按 `vm-script` 的 `createScriptContext` 同样的规则复制进来:主环境 `globalThis` 上、新环境没有的自有属性逐个复制,`global` 指向新环境自身。这几行在求值器文件里单独写一份,不改 [vm-script.ts](../../../../packages/ptc-runtime/ptc-runtime-node/src/evaluators/vm-script.ts)。
|
||||
- `tools`、绑定错误类、`console`、`process` 仍由子进程在每次执行前写到 `evaluator.globals`,也就是 `runtimeContext`。
|
||||
- 沙箱对象没有原型,和 vm-script、AsyncFunction 两个求值器一样,全局查找因此不会经原型链走到主环境的 `Function`,例如 `constructor.constructor("…")()`。但复制进来的主环境值(`setTimeout`、`console`、`process`、工具命名空间等)的 `constructor` 仍是主环境的 `Function`,主环境没有 `codeGeneration` 限制,所以这个开关只限制执行环境自己的 `eval`、`Function` 和 WebAssembly,不构成隔离;隔离靠进程级沙箱。
|
||||
- 只提供动态 `import()`,没有开关:每个 Script 都配 `importModuleDynamically`。不提供 `require`、`module` 和内置模块全局;宿主以这些名字注入的绑定原样可用。静态 `import` 不支持。
|
||||
- 生成的文件名是 `<目录>/.ptc-repl-<序号>.js`,这个路径上没有真实文件,文件名用点开头的隐藏名。目录是求值器创建时的 working directory,也就是这个环境第一次调用时的目录,之后不再改变;默认加载器把文件名当作 `import()` 的引用方,所以相对路径的 import 固定按这个目录解析,目录部分不能省。以后需要跟随目录变化时,另加显式操作(例如 `js_switch_cwd`)。
|
||||
- 绑定和 import 返回的值属于主环境,`instanceof Array` 这类跨环境判断可能为 false,和 REPL、`vm-script` 相同。
|
||||
|
||||
三个开关是求值器的创建参数,不是 Config 字段:
|
||||
|
||||
```ts ignore-check
|
||||
interface ScopedReplEvaluatorOptions extends ProgramEvaluatorOptions {
|
||||
/** Force strict mode for every program; when off, a program's own leading "use strict" decides. Defaults to true. */
|
||||
strict?: boolean
|
||||
/** Allow eval, new Function and WebAssembly compilation inside the program context; defaults to false. */
|
||||
codeGeneration?: boolean
|
||||
/** Use the last top-level expression statement as the completion value; defaults to true. */
|
||||
finalExpression?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
| 开关 | 打开时 | 关闭时 | 需要注意 |
|
||||
|---|---|---|---|
|
||||
| `strict`(默认开) | 整个 Script 以 `"use strict";` 开头,每次调用都按严格执行 | 不强制:程序以 `"use strict"` 指令开头时,在内层函数体最前面补一个 `"use strict";`,拷贝语句不会让它失效;否则按宽松执行 | 两种状态下 acorn 都按 script 规则扫描,严格模式的语法违规由 V8 编译时报出。关闭后,按宽松执行的调用里:给未声明的名字赋值会创建所有调用共用的全局变量,不走拷贝;顶层 `this` 是 `globalThis`;用严格模式保留字(如 `package`)声明的名字会让之后严格的调用编译失败,见"风险" |
|
||||
| `codeGeneration`(默认关) | 创建执行环境时不加 `codeGeneration` 限制 | 按上面的代码创建 | 打开后,`eval` 里新声明的 `var` 不在扫描出的名单里,不会带到下一次;关闭时也只限制执行环境自己的代码生成,不构成隔离 |
|
||||
| `finalExpression`(默认开) | 最后一条表达式改写成 `return { value: (…) }` | 不改写,末尾表达式的值被丢弃,结果为空 | 关闭后输出只能靠打印,模型说明和使用完成值的地方(例如 workflow-ptc)都要相应调整;顶层 `return` 在两种状态下都报错 |
|
||||
|
||||
接入时三个开关都取默认值;非默认值是设计上预留的用法,各自都有测试。
|
||||
|
||||
### 包装
|
||||
|
||||
每次调用编译成一个独立的 `vm.Script`。例如前面留下了 `a`(`const`)、`b`(`let`)、`v`(`var`),这次模型写了:
|
||||
|
||||
```js
|
||||
let c = a + b
|
||||
c * 2
|
||||
```
|
||||
|
||||
实际编译的源码是:
|
||||
|
||||
```js
|
||||
"use strict";(function (__$binding_vals, __$binding_getters) { return async function () { let a = __$binding_vals[0]; let b = __$binding_vals[1]; var v = __$binding_vals[2]; __$binding_getters.push(() => a, () => b, () => v, () => c);
|
||||
let c = a + b
|
||||
return { value: (c * 2) }
|
||||
} })
|
||||
```
|
||||
|
||||
| 部分 | 内容 | 原因 |
|
||||
|---|---|---|
|
||||
| `"use strict";` | `strict` 开关打开时,整个 Script 是 strict 模式;关闭时省略,程序以 `"use strict"` 开头时改为在内层函数体最前面补一个 | 打开时强制严格;关闭时保证前缀里的拷贝语句不会让模型写的指令失效 |
|
||||
| 外层 `function (__$binding_vals, __$binding_getters)` | 接收拷贝进来的值和一个空数组,返回内层函数;由求值器同步调用 | 内部值通过闭包交给程序,不出现在程序的 `arguments` 里;外层在程序运行前就已返回,它的帧不会出现在程序的堆栈里 |
|
||||
| 内层 `async function ()` | 模型程序就是它的函数体 | 支持顶层 `await`;顶层声明是函数的局部变量,每次调用互不冲突;不带接收者、零参数调用,所以 `this` 是 `undefined`(按宽松执行时是 `globalThis`),`arguments` 是一个空的 arguments 对象 |
|
||||
| 拷贝声明 | 只给"前面有、本次没声明或只用 `var` 重新声明"的名字生成,值按下标从 `__$binding_vals` 取 | 下标访问不受 `__proto__` 这类名字影响 |
|
||||
| `__$binding_getters.push(...)` | 在模型代码之前,按求值器生成前缀时的名字顺序,给每个名字(拷贝来的和本次声明的)推入一个读取函数 | 求值器知道第 i 个读取函数对应第 i 个名字,前缀里不用写名字字符串;读取函数可以先建好、以后再读,声明还没初始化完时读取会抛错 |
|
||||
| 最后一条表达式 | 语句前插入 `return `,表达式前插入 `{ value: (`,表达式后插入 `) }` | 和 Node 的 `processTopLevelAwait` 处理最后一条语句的方式相同;外包一层对象,返回的 Promise 不会被 async 函数自动等待 |
|
||||
| 前缀单独占第 0 行 | 编译时 `lineOffset: -1` | 模型代码第 N 行就报告为第 N 行 |
|
||||
| 收尾另起一行 | `} })` | 模型代码最后一行可能以 `//` 注释结尾 |
|
||||
|
||||
拷贝语句在本次没有声明这个名字、或者只用 `var` 重新声明它时生成;本次用 `let`、`const`、`class`、`function`(包括 `const`)声明了它,就没有这行,以本次的声明为准。生成时的关键字:
|
||||
|
||||
| 情况 | 前缀里生成 |
|
||||
|---|---|
|
||||
| 本次没有声明,前面是 `let`、`const`、`function`、`class` | `let` |
|
||||
| 本次没有声明,前面是 `var` | `var` |
|
||||
| 本次只用 `var` 重新声明 | `var` |
|
||||
|
||||
拷贝语句只负责把旧值带进来,写成 `const` 唯一的效果是禁止之后的调用赋值,所以前面的 `const` 也拷成 `let`:之后的调用可以直接给它赋值,改的只是拷贝;声明它的那次调用里它仍是 `const`。不判断这次调用是否真的赋值,所以不需要遍历语法树,也不打印警告。
|
||||
|
||||
只用 `var` 重新声明时也生成拷贝:同一个函数里重复的 `var` 声明是同一个变量,所以这次的 `var` 从旧值开始,没执行到的声明不会把旧值换成 `undefined`,和 node:repl 里全局 `var` 的行为一致。同一次里同名的 `function` 在函数开头就初始化,优先于 `var`,这时不生成拷贝。
|
||||
|
||||
编译与运行:
|
||||
|
||||
```ts ignore-check
|
||||
// Kernel: ScopedReplScopes.compile
|
||||
const factory = new Script(source, { filename, lineOffset: -1, ...importOption }).runInContext(context) as ScopedReplFactory
|
||||
const getters: (() => unknown)[] = []
|
||||
const program = factory(values, getters)
|
||||
this.compiled = { bindings, getters, replaced }
|
||||
return program
|
||||
|
||||
// Evaluator: evaluate
|
||||
const filename = resolve(baseDirectory, `.ptc-repl-${++submissions}.js`) // baseDirectory: process.cwd() at creation
|
||||
const program = scopes.compile(code, { filename, context, finalExpression, ...importOption })
|
||||
const start = Reflect.apply.bind(undefined, program, undefined, []) as ScopedReplProgram
|
||||
void programDomain.run(() => Promise.resolve().then(start)).then(
|
||||
(completion) => { finish({ ok: true, value: completion?.value }) },
|
||||
(error: unknown) => { finish({ ok: false, error }) },
|
||||
)
|
||||
```
|
||||
|
||||
- 内核编译时固定给出 `filename` 和 `lineOffset: -1`;求值器总是传 `importModuleDynamically`:有 import 处理器时用 `VmModuleImportLoader.forFile(filename)`,没有时用 `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`。
|
||||
- 程序由微任务直接调用,同步抛错时堆栈里没有求值器的帧。宿主用 `.then` 接结果、不用 `await`,否则 V8 会在堆栈末尾补一帧宿主的 async 帧。
|
||||
- 已实测:`this` 是 `undefined`,`arguments.length` 是 0,同步抛错的堆栈只有程序自己的帧;domain 能接住这样启动的程序里定时器抛出的错误;外包对象里的 Promise 原样返回,不被等待。
|
||||
- 代码里任何位置出现 `__$binding_`(包括字符串和注释),都报 `SyntaxError: Names starting with '__$binding_' are reserved`,位置指向第一次出现的地方,这次不执行。
|
||||
|
||||
### 内核:作用域链、acorn 扫描与编译
|
||||
|
||||
内核文件只依赖 acorn 和 `node:vm`,不依赖子进程和求值器,可以在普通 vm context 里连续编译、执行多段程序,单独测试作用域分层。接口:
|
||||
|
||||
```ts ignore-check
|
||||
class ScopedReplScopes {
|
||||
constructor(options: { strict: boolean; onRedeclaration?: (redeclarations: readonly ScopedReplRedeclaration[]) => void })
|
||||
/** Scan and compile one program against the current bindings; throws SyntaxError and leaves the chain unchanged. */
|
||||
compile(code: string, options: { filename: string; context: Context; finalExpression: boolean; importModuleDynamically?: ScriptOptions['importModuleDynamically'] }): ScopedReplProgram
|
||||
}
|
||||
type ScopedReplProgram = () => Promise<{ value: unknown } | undefined>
|
||||
interface ScopedReplRedeclaration { name: string; previous: ScopedReplBindingKind; current: ScopedReplBindingKind }
|
||||
type ScopedReplBindingKind = 'var' | 'let' | 'const' | 'function' | 'class'
|
||||
interface ScopedReplBinding { name: string; kind: ScopedReplBindingKind }
|
||||
interface ScopedReplScan {
|
||||
/** Top-level bindings declared by the program, in source order. */
|
||||
declarations: ReadonlyMap<string, ScopedReplBindingKind>
|
||||
/** Whether the program starts with a "use strict" directive. */
|
||||
useStrict: boolean
|
||||
/** Last top-level statement when it is an expression statement. */
|
||||
finalExpression?: { statementStart: number; expressionStart: number; expressionEnd: number }
|
||||
}
|
||||
/** Parse once; throws a SyntaxError laid out like V8's for every error acorn reports. */
|
||||
function scanProgram(code: string, options: { filename: string }): ScopedReplScan
|
||||
/** Build the Script source and every binding in the order of the read functions it pushes. */
|
||||
function buildProgramSource(
|
||||
code: string, scan: ScopedReplScan, carried: readonly ScopedReplBinding[], options: { strict: boolean; finalExpression: boolean },
|
||||
): { source: string; bindings: ScopedReplBinding[] }
|
||||
```
|
||||
|
||||
**解析方式**:不论 `strict` 开关,都调用 `parse(code, { ecmaVersion: 'latest', sourceType: 'script', allowAwaitOutsideFunction: true })`。这和 async 函数体的规则基本一致:顶层 `await` 合法,顶层 `return` 是语法错误,同一次里两个同名 `function`、同名的 `var` 和 `function` 都合法。不同的是顶层 `using`、`await using` 和静态 `import`、`export` 会被拒绝。扫描时不判断严格与否:开关打开时由 Script 开头的 `"use strict";` 决定,严格模式的语法违规由 V8 编译时报出。
|
||||
|
||||
解析之前先查两件事:程序以 `#!` 开头,或者代码里任何位置出现 `__$binding_`,就报错,不再解析。
|
||||
|
||||
**一次解析得到四样东西**:
|
||||
|
||||
1. 本次的顶层声明,只看顶层语句:
|
||||
|
||||
| 顶层语句 | 收集的名字 | 记录的关键字 |
|
||||
|---|---|---|
|
||||
| `const`、`let`、`var` 声明,含解构(对象、数组、默认值、剩余元素) | 每个绑定名 | 原关键字 |
|
||||
| `function` 声明,含 async 和 generator | 函数名 | `function`;同一次里同名的 `var` 也记为 `function` |
|
||||
| `class` 声明 | 类名 | `class` |
|
||||
| `for (var …; …; …)`、`for (var … in/of …)` 括号里的 `var` | 每个绑定名 | `var` |
|
||||
| 块、`try`/`catch`/`finally`、`if`/`else`、循环体、`switch`、标签语句、`with` 里的 `var`,包括其中 `for` 括号里的 `var`;不进入函数和类 | 每个绑定名 | `var` |
|
||||
|
||||
2. 有没有顶层 `return`:acorn 直接报 `'return' outside of function`,并给出位置。
|
||||
3. 最后一条语句:从后往前跳过空语句 `;`,找到的第一条如果是表达式语句,记下语句和表达式的起止位置。
|
||||
4. 开头的指令里有没有 `"use strict"`:acorn 在指令语句上标出 `directive`,有就记下 `useStrict`。
|
||||
|
||||
不做的事:不进入嵌套的函数和类;块里只找 `var`,`let`、`const`、`class`、`function` 留在块里;不分析引用,不找赋值;除了最后一条表达式的三处插入,不改写代码。
|
||||
|
||||
**语法错误**:acorn 报错时直接抛 `SyntaxError`,不再交给 V8 编译。`stack` 按 V8 的样式排版:
|
||||
|
||||
```text
|
||||
/work/.ptc-repl-3.js:1
|
||||
const x = ;
|
||||
^
|
||||
|
||||
SyntaxError: Unexpected token
|
||||
```
|
||||
|
||||
- 消息取 acorn 的原文,去掉末尾的 `(行:列)`。
|
||||
- 两处改用 V8 的说法:`'return' outside of function` 报 `Illegal return statement`;报错位置在代码末尾时报 `Unexpected end of input`。
|
||||
- 代码里出现 `__$binding_` 时,按同样的样式报错,位置指向第一次出现的地方。
|
||||
|
||||
### 作用域链状态与每次调用的步骤
|
||||
|
||||
`ScopedReplScopes` 持有:
|
||||
|
||||
- `bindings: Map<string, { kind: ScopedReplBindingKind; read(): unknown }>`:当前可拷贝的名字和它们的读取函数。`kind` 是名字最近一次声明用的关键字;只是被拷贝的名字沿用之前记下的关键字,例如 `function` 拷贝成 `let` 后仍记为 `function`。
|
||||
- `replaced: ReadonlyMap<string, { kind: ScopedReplBindingKind; value: unknown }>`:最近采用的那次程序重新声明的名字,在它编译时的旧值。
|
||||
- `compiled`:最近一次编译的程序的绑定顺序、读取函数数组和它的 `replaced`。
|
||||
|
||||
每次 `compile(code, options)`:
|
||||
|
||||
1. 采用 `compiled`:读取函数数组的长度不少于名字个数,说明那次的前缀已经执行过,`bindings` 换成"第 i 个名字对应第 i 个读取函数",`replaced` 换成它的值。子进程不允许两次执行重叠(`overlapping PTC evaluation`),上一次的前缀总在下一次编译之前的微任务里执行完;只有在一段同步代码里连续编译两次时,前一次才会因前缀还没执行而不被采用。
|
||||
2. 扫描,得到本次声明和最后一条表达式的位置;语法错误直接抛出,状态不再变化。
|
||||
3. 逐个调用 `bindings` 里的读取函数取当前值。读取抛错(声明没初始化完)就用 `replaced` 里的值;两边都没有,就丢掉这个名字。
|
||||
4. 本次没声明、或只用 `var` 重新声明的名字作为拷贝,值放进 `values`;本次声明了的已有名字,把值记进新的 `replaced`,同时记一条重复声明 `{ name, previous, current }`。
|
||||
5. 拼源码,然后编译。`strict` 关闭且 `useStrict` 为 true 时,内层函数体最前面加 `"use strict";`。V8 编译失败时抛出原生的 `SyntaxError`,裁掉错误标题之后的编译器内部帧(和 `vm-script` 做法相同,代码单独写一份),状态不再变化。
|
||||
6. 有重复声明时调用 `onRedeclaration(redeclarations)`。
|
||||
7. 调用外层函数拿到程序,记下 `compiled`,返回程序。
|
||||
|
||||
求值器每次 `evaluate(code, finish)`:
|
||||
|
||||
1. 提交序号加 1(包括有语法错误的提交),文件名是 `<创建时的目录>/.ptc-repl-<序号>.js`。
|
||||
2. 调用 `scopes.compile`;抛错就用这个错误结束本次执行。
|
||||
3. 在 domain 里由微任务启动程序;Promise 完成后调用 `finish`,结果取 `completion?.value`,不再等待。
|
||||
|
||||
读取发生在内核第 3 步,也就是新一次编译的时刻。之后前面的代码再给顶层变量赋值,改的只是它自己那次的变量。
|
||||
|
||||
### 失败的调用
|
||||
|
||||
| 第几次 | 代码 | 结果 |
|
||||
|---|---|---|
|
||||
| 1 | `const data = 1` | `data` 是 1 |
|
||||
| 2 | `const data = await tools.fetch()`,`fetch` 抛错 | 失败;第 2 次的 `data` 声明了,但没赋上值 |
|
||||
| 3 | `data` | 1:内核第 3 步读第 2 次的 `data` 时抛错,改用第 2 次编译时记下的旧值 |
|
||||
| 4 | `let fresh = await tools.fetch()`,抛错 | 失败;`fresh` 是新名字 |
|
||||
| 5 | `typeof fresh` | `"undefined"`:没有旧值,名字被丢掉 |
|
||||
|
||||
- 抛错之前已经执行完的声明保留。例如先执行了 `let y = 5` 再抛错,之后的调用里 `y` 仍是 5。
|
||||
- `var` 重新声明从拷贝进来的旧值开始,读取不会抛错,也不需要退回:没执行到的 `var` 保留旧值。例如第 2 次在 `var v = 6` 之前就抛错,或者 `var config = await tools.loadConfig({})` 的工具调用失败,之后的调用读到的仍是之前的值。`function` 在函数开头就是新函数。
|
||||
|
||||
### 异步错误:对齐 REPL
|
||||
|
||||
REPL 用 Node 的 `domain` 接住程序启动的异步工作里抛出的错误。求值器照同样的做法:
|
||||
|
||||
- 创建求值器时调用 `domain.create()` 得到 `programDomain`,每个程序都在 `programDomain.run(...)` 里启动。程序创建的定时器、回调、Promise 后续步骤和 EventEmitter 都归属这个 domain。
|
||||
- `programDomain.on('error', ...)` 把错误写成 `Uncaught ` 加错误文本,交给 `options.reportError`。错误文本取错误的 `stack`,`stack` 不是字符串时用"名字: 消息";不用 `util.inspect` 格式化 Error,是因为 domain 会往错误对象上加 `domain`、`domainThrown`,inspect 会把它们一起打印出来。不是 Error 的值,先删掉这两个属性再用 `util.inspect`,和 node:repl 一样。
|
||||
- 程序能让转换文字这一步抛错(`stack` 访问器、`toString`、自定义 inspect)。监听器里抛错会让 Node 结束进程,所以这一步包在 `try`/`catch` 里,出错时报 `program threw an unrenderable value`,和同步失败时 `prepareException` 的兜底文字相同。`reportError` 放在 `try` 外面,它是子进程自己的代码,出错应该照常暴露。
|
||||
- 回调里 `throw` 冻结或不可扩展的对象时,Node 的 domain 在调用监听器之前给它加属性就失败了,进程结束,和 node:repl 相同。
|
||||
- 子进程处理 `reportError` 的方式不变:当时有执行在运行,就让那次执行以这个错误失败;否则丢弃。错误按创建回调时所属的执行归属(AsyncLocalStorage)。
|
||||
- 不在整个进程上注册 `uncaughtException` 或 `unhandledRejection`,子进程自身代码的错误仍然暴露。
|
||||
- 程序调用工具时,子进程为这次调用创建的异步回调(例如 RPC 回调)也在程序的 domain 里:子进程自身代码在这些回调里的异步错误会被当成程序的 `Uncaught …` 报告,子进程继续运行、不退出。现有 REPL 求值器也是这样。
|
||||
|
||||
已验证的情况:
|
||||
|
||||
- REPL:定时器里抛错、未处理的 Promise rejection,在执行结束后和执行中都被接住;EventEmitter 的 `error` 事件在执行结束后被接住。
|
||||
- 单独的 domain:在主环境里接住了定时器抛错、定时器里产生的 rejection、未被等待的 async 函数失败和 EventEmitter 的 `error` 事件;在带默认 `codeGeneration` 限制的执行环境里,接住了定时器抛错和定时器里产生的 rejection;由微任务启动的程序里,定时器抛错同样被接住。
|
||||
|
||||
### 动态 import
|
||||
|
||||
- 程序里的 `import()` 经过每个 Script 的 `importModuleDynamically`:没有 import 处理器时用 `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`,有处理器时用现有的 `VmModuleImportLoader.forFile(filename)`,和 `vm-script` 相同。
|
||||
- 相对路径按求值器创建时的目录解析,也就是这个环境第一次调用时的 working directory;之后的调用换了目录也不变。node:repl 和 `vm-script` 跟随每次调用的目录;Agent 用 `working_directory` 换目录后,需要按新目录 import 时用绝对路径。
|
||||
- 不提供 `require`:node:repl 的 `require` 解析规则不一致(相对路径跟随当前目录,但第一次解析后被缓存;包名固定按启动目录),只保留动态 `import()` 这一种加载方式。
|
||||
|
||||
### 重复声明提示(预留)
|
||||
|
||||
内核在第 6 步调用 `onRedeclaration`;求值器把自己的 `reportRedeclarations(redeclarations: readonly ScopedReplRedeclaration[])` 注入进去,函数体先留空,只加一行 `TODO` 注释,不输出任何内容。以后要提示时,在这里写入程序的 `console`,内容会进入模型可见的输出。
|
||||
|
||||
### 范围外
|
||||
|
||||
- 内存回收:不处理,每次拷贝全部名字。没有闭包存活的旧调用会被回收;某次调用留下了存活的函数时,这个函数会留住这次开始时拷贝进来的所有值。
|
||||
- 跟随 working directory 变化解析 `import()`:以后需要时另加显式操作,例如 `js_switch_cwd`。
|
||||
- `let`、`const`、`class` 重新声明的初始化表达式里读同名旧值(例如 `let count = count + 1`):属于代码问题。
|
||||
- `strict` 关闭时严格和宽松调用混用造成的问题,见"风险":交给以后的重置工具。
|
||||
- 最后一条表达式所在行的列号偏移。
|
||||
|
||||
### 接入
|
||||
|
||||
以 `scoped-repl` 格式接入时只做必需的改动,不顺手重构或复用现有代码,方便和其他进行中的 PTC 改动 rebase、合并。程序格式名是 `scoped-repl`,配置字段名是 `replScoped`。
|
||||
|
||||
| 位置 | 改动 |
|
||||
|---|---|
|
||||
| `ptc-runtime` 的 `PtcProgramFormat` | 包含 `'scoped-repl'` |
|
||||
| `ptc-runtime-node` 的 `config.ts` | 布尔字段 `replScoped`,只能和 `persistent-in-memory` 一起用,否则加载时报错;省略时由 `resolveReplScoped` 取 `resolvePersistentExecution` 对函数体写入的 `persistent-in-memory` 取值(目前为 true),其他模式下为 false |
|
||||
| `ptc-runtime-node` 的 `execution.ts` | `persistent-in-memory` 分支里 `replScoped` 为 true 时:格式 `scoped-repl`,`retainsState` 为 true,TypeScript 按 REPL 语句擦除,配一段新的模型说明 |
|
||||
| `ptc-runtime-node` 的 `evaluators/index.ts` | 求值器表含 `scoped-repl`,三个开关取默认值 |
|
||||
| `ptc-runtime-node` 的 `protocol.ts` | 协议版本是 3,旧 bootstrap 在就绪阶段报错;升级指南 `docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/` 同时说明 `PtcProgramFormat` 新增的成员 |
|
||||
| workflow-ptc 的 `host.ts` | `scoped-repl` 用和 `repl` 一样的包装 `await (async () => {…})()` |
|
||||
| `ptc-runtime-node` 的 `configuration.ts`(CUA 用它合并配置) | `resolvePersistentExecution` 返回 `executionMode`、`scriptPersistence`、`replScoped` 三个字段,一起合并:`script` 保持持久化的 VM Script,`replScoped: false`;`scoped-repl` 为 `replScoped: true`;函数体和 REPL 语句为 `persistent-in-memory` 加常量 `SCOPED_REPL_BY_DEFAULT`(目前为 true),覆盖 profile 里残留的值。这个常量同时决定 `config.ts` 里省略时的默认值,改它只改一行;`config.ts` 从 `configuration.ts` 导入这个函数,而 `configuration.ts` 本身也是包的发布入口;`configuration.ts` 只导入 `Config` 类型,所以打包不会生成共用的 chunk |
|
||||
| 文档、快照和测试 | 包 README 的配置项、行为说明和"已知限制"、config catalog、快照场景 `ptc-scoped-repl`;构建产物的 e2e 含 `replScoped: true` 用例 |
|
||||
|
||||
tool-executor-ptc 没有改动:格式不是 `function-body` 时,它自动使用"打印输出"那套说明。模型说明写明上面的精确行为,尤其是:输出用 `inspect(...)`,这句和其他模式共用;不支持顶层 `return`;每次调用开始时拷贝、旧代码不受影响;需要共享的可变状态放进对象;不声明直接赋值只改拷贝,前面的 `const` 也可以这样赋值;`let`、`const`、`class` 重新声明的初始化表达式读不到同名旧值,要在旧值上计算就直接赋值或换个名字;`var` 重新声明从旧值开始;调用中途失败时,没执行完的 `let`、`const`、`class`、`var` 重新声明保留旧值;块里的 `var` 也算这次调用的顶层名字,其他块里的声明只属于它的块;只能用 `import()`,相对路径按这个环境第一次调用的目录解析。测试整段逐字比对模型说明。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**用直接 eval 把每次调用嵌进上一次的作用域。** 前后调用能共享活的绑定,但旧作用域永远无法回收,行列号要靠 source map 或改写堆栈才能对上;在禁止从字符串生成代码的执行环境里,直接 eval 也不可用。
|
||||
|
||||
**把声明改写成 `var` 或全局赋值。** 所有调用共用同一个绑定,违反要求 2,而且要改写模型代码。
|
||||
|
||||
**每次调用编译成一个 ES 模块。** 靠合成一个代表上一次调用的模块和追加的 `export` 传值。模块里既不能 `return`,也没有末尾表达式的值,前置代码还会让报错行号整体偏移;函数参数已经能传值,不需要模块。
|
||||
|
||||
**作用域分析加改写引用。** 能做更精细的内存回收,但需要作用域分析并改写代码,违反要求 5。
|
||||
|
||||
**只用打印输出、不支持末尾表达式。** workflow-ptc 和 `repl` 格式的约定都依赖完成值,也偏离现有 REPL 的写法。
|
||||
|
||||
**用顶层 `return` 给出结果。** 与要求 3 冲突,需要换成函数体格式,run_code 的说明也会随之变化。
|
||||
|
||||
**末尾的 Promise 等它完成。** 和 `vm-script` 一致,但和现有 REPL 不一致;按 Node 的写法外包一层对象,保持 REPL 的行为。
|
||||
|
||||
**以 `if`、`for`、块结尾时也给出结果。** 只有在 Script 顶层执行时才有 V8 的完成值,函数体里拿不到;要支持就得改写更多语句。node:repl 在代码含 `await` 时同样没有结果。
|
||||
|
||||
**包装直接写成 `async function (__$binding_vals, __$binding_getters)`。** `this` 同样是 `undefined`,但程序的 `arguments` 里能看到这两个内部值,长度是 3。
|
||||
|
||||
**包装用 async 箭头函数。** `this` 是 `globalThis`、没有 `arguments`,和 REPL 一致;我们选择 strict 模式下不带接收者调用函数时的 `undefined`。
|
||||
|
||||
**用回调交出读取函数。** 前缀里要写名字字符串,还要防止程序重复调用;推入数组、由求值器按下标对应名字更简单。
|
||||
|
||||
**语法错误交给 V8 再编译一次。** 能拿到 V8 原文的消息,但要多编译一次;acorn 已经给出位置和消息,直接报。
|
||||
|
||||
**strict 开启时按 module 规则扫描。** module 规则比 async 函数体严:同一次里两个同名 `function`、同名的 `var` 和 `function`、嵌套的普通函数里把 `await` 当变量名都会被拒绝,HTML 注释的处理也和 V8 编译 Script 时不一致。strict 关闭时也用不了,因为 module 规则一律是 strict 的。
|
||||
|
||||
**套上和运行时一样的函数外壳再扫描。** 和运行时的语法完全一致,顶层 `using` 也能用,Node 的 `processTopLevelAwait` 就是这样做的。但要自己遍历语句查找顶层 `return`,换算外壳带来的位置偏移,还要防止代码里多出的 `}` 提前关闭外壳;我们不需要顶层 `using`,script 规则更简单。
|
||||
|
||||
**只把被赋值的 `const` 拷成 `let`,并打印警告。** 要遍历新调用的语法树并判断遮蔽,属于作用域分析,违反要求 5。我们一律拷成 `let`,不提示。
|
||||
|
||||
**`var` 重新声明不拷贝旧值,从 `undefined` 开始。** `var count = count + 1` 得到 `NaN`;但抛错前没执行到、或在没走到的分支里的 `var` 会把旧值换成 `undefined`,例如工具调用失败的 `var config = await tools.loadConfig({})` 让之后的调用拿不到原来的 `config`。拷贝旧值后,`var count = count + 1` 在旧值上加 1,和 node:repl 一致,暂时接受。
|
||||
|
||||
**只在调用失败、且读到 `undefined` 时退回旧值。** 不用拷贝,但分不出"没执行到"和"执行了、值就是 `undefined`":赋上 `undefined` 之后同一次又失败时,会误退回旧值;成功调用里没走到的分支和不带初始值的 `var x;` 也覆盖不到。
|
||||
|
||||
**在代码里插标记,记录 `var` 是否执行到。** 能准确区分,但要在声明处、声明前的赋值和循环头改写模型代码,违反要求 5。
|
||||
|
||||
**严格的调用里跳过严格模式保留字的拷贝。** 能避免宽松调用里声明的 `package` 这类名字让之后严格的调用编译失败;但这是模型混用两种模式造成的,不处理,交给以后的重置工具。
|
||||
|
||||
**在整个进程上监听未捕获的错误。** 会把子进程自身代码的错误一起吞掉;REPL 用 domain,只接程序启动的异步工作。
|
||||
|
||||
**不收集块里的 `var`。** 块里的 `var` 会和拷贝语句撞名,整段程序报 `already declared`,这个名字也带不到之后的调用;收集它只需约 15 行语句遍历,不分析引用,所以采用收集。
|
||||
|
||||
**堆栈里只显示 `.ptc-repl-<序号>.js`,不带目录。** 文件名去掉目录后,默认加载器按导入那一刻的 cwd 解析相对 `import()`,和有 import 处理器时不一致;用 `//# sourceURL` 只显示短名时,V8 不再应用 `lineOffset`,每个行号多 1;把 import 交给回调函数可以解决:子进程两种启动方式都带 `--experimental-vm-modules`,回调可以在第一次调用的目录下发起 `import()`;但这要求 scoped-repl 总是走回调形式的 import,默认路径现在没有走,所以文件名暂时保留第一次调用的目录。
|
||||
|
||||
**提供 `require`、`module` 和内置模块全局(node:repl 做法)。** node:repl 的 `require` 解析规则不一致,跟随目录又要定义何时换基准;只保留 `import()`。
|
||||
|
||||
## 影响
|
||||
|
||||
得到的:
|
||||
|
||||
- 后面的调用可以用任意关键字再次声明前面的名字,前面的函数、闭包和仍在运行的代码继续使用原来的值。
|
||||
- 写法、结果、报错和异步错误处理与现有 REPL 一致,程序的异步错误不让进程退出。
|
||||
- 不做作用域分析;除了最后一条表达式的三处插入,不改写模型代码。
|
||||
|
||||
付出的:
|
||||
|
||||
- "开始时拷贝"和 REPL 不同:前面的代码(定时器、回调)之后再给顶层变量赋值,后面的调用看不到;模型说明写明了这一点。
|
||||
- 不声明直接赋值只影响之后的调用,前面定义的函数看不到;REPL 里两边会一起变。
|
||||
- strict 模式和 REPL 不同:REPL 里给未声明的名字赋值会创建全局变量,这里会报错。
|
||||
- 调用方不丢弃完成值时,末尾是没写 `await` 的 Promise,宿主报"不是 JSON",和现有 REPL 一样;`run_code` 丢弃完成值,不受影响。
|
||||
- 以 `if`、`for`、块结尾的程序没有结果,node:repl 在代码不含 `await` 时有。
|
||||
- 最后一条表达式所在行,插入点之后的列号右移 17。
|
||||
- 语法错误消息是 acorn 的文字,和 V8 原文不同,例如 `Unexpected token` 而不是 `Unexpected token ';'`。
|
||||
- 扫描统一按 script 规则:顶层 `using`、`await using` 会被拒绝,node:repl 也不支持。
|
||||
- 顶层 `arguments` 是一个空的 arguments 对象,node:repl 里它不存在。
|
||||
- 执行环境默认禁止从字符串生成代码:依赖 `eval` 或 `new Function` 的代码会失败,包括经 import 处理器加载到这个执行环境的库。这个限制不构成隔离,复制进来的主环境函数(例如 `setTimeout.constructor`)仍能生成代码。
|
||||
- 不提供 `require`:依赖 `require` 的代码要改用 `await import()`。
|
||||
- 相对路径的 `import()` 固定按这个环境第一次调用时的目录解析,Agent 换目录后仍按旧目录。
|
||||
- Node 文档把 `domain` 标为已弃用;node:repl 仍建立在它上面,如果 Node 移除它,REPL 也会一起变。
|
||||
- 子进程自身代码在工具调用的异步回调里出错时,会被当成程序的 `Uncaught …` 报告,子进程继续运行,和现有 REPL 相同。
|
||||
- 以 `#!` 开头的程序被拒绝。
|
||||
- 代码里任何位置出现 `__$binding_`(包括字符串、注释)都会被拒绝;用 `\u005f` 这类转义写出的内部名不在检查范围内。
|
||||
- acorn 必须跟上 V8 支持的语法,否则较新的语法会被拒绝执行。
|
||||
- `var` 重新声明从旧值开始:`var count = count + 1` 在旧值上加 1,和 node:repl 一致;即使前面是 `let`、`const` 也是这样,node:repl 在这种情况下报 `already declared`。
|
||||
- `let`、`const`、`class` 重新声明的初始化表达式读不到同名旧值,会报错,例如 `let count = count + 1`。属于代码问题,不处理。
|
||||
- 前面的 `const` 在之后的调用里一律拷成 `let`,可以被赋值,而且没有提示。
|
||||
- `strict` 关闭时,严格和宽松的调用可以混用:宽松调用里给未声明的名字赋值,会创建所有调用和旧函数共用的全局变量;宽松调用里用严格模式保留字(`package`、`public`、`private`、`protected`、`interface`、`implements`、`static`、`let`、`yield`、`eval`、`arguments`)声明的名字,会让之后严格的调用编译失败。不处理,交给以后的重置工具。
|
||||
- 回调里 `throw` 冻结或不可扩展的对象时,Node 的 domain 处理本身出错,进程结束,保留的变量丢失,和 node:repl 相同。
|
||||
- 每次调用都要为前面所有名字生成拷贝声明和读取函数:原型实测 1000 个名字时约 10 ms/次。
|
||||
- 某次调用留下存活的函数时,这次拷贝进来的所有值都会一直留在内存里。
|
||||
|
||||
## 测试
|
||||
|
||||
- 内核测试单独运行即可通过,覆盖:script 规则解析和开头 `"use strict"` 的检测、声明表里的每种语句、顶层 `return`(包括块里的)、最后一条表达式的定位与插入、以 `#!` 开头的程序、代码里出现 `__$binding_`、语法错误的排版和两处消息替换、拼出的源码;`strict` 关闭时,程序开头的 `"use strict"` 在有拷贝和没有拷贝时都生效;并在普通 vm context 里连续执行多段程序,覆盖"跨次调用"里的每一条,包括各种关键字组合、失败的调用、定时器、函数重定义和重复声明通知。
|
||||
- 求值器测试直接使用求值器和真实的 vm 执行环境,覆盖"写法与结果""执行环境""报错""异步错误与生命周期"里的每一条,以及经求值器的跨次调用;包括经全局对象的原型链拿不到主环境的 `Function`、复制进来的主环境函数(例如 `setTimeout.constructor`)仍能生成代码,以及宿主以 `module`、`require` 为名的绑定原样保留。
|
||||
- 三个开关各自在打开和关闭时都有测试。
|
||||
- 顶层 `this` 是 `undefined`、`arguments.length` 是 0,同步抛错的堆栈只有程序自己的帧。
|
||||
- 异步错误:上面列出的每种情况在执行结束后和执行中各测一次,交给 `reportError` 的文本以 `Uncaught ` 开头;进程不退出,变量保留。`stack` 为空、读取 `stack` 抛错、自定义 inspect 抛错时,分别报"名字: 消息"和固定文本,进程不退出;抛出普通对象时报错里没有 `domainThrown`。
|
||||
- import:默认加载器和 import 处理器两条路径,相对路径按创建时的目录解析,之后换了目录也不变。
|
||||
- 构建产物的 e2e 覆盖 `replScoped: true`。
|
||||
- 挂载 `persistent-in-memory` 的测试都显式写 `replScoped`,保留执行的测试两种取值都跑;只有一个测试检查省略时的默认值。
|
||||
- 新文件覆盖率 100%;现有求值器及其测试不变。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-07-forge-changes-view-responsiveness.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.md
|
||||
/agent-note-forge-changes-view-responsiveness:
|
||||
en: e809ffea0d880a4b
|
||||
zh: 6725e6a9bd1c3bd1
|
||||
/agent-note-forge-changes-view-responsiveness/problem:
|
||||
en: 77fab27f3d4a4a59
|
||||
zh: 46e0fa8b9ef978a7
|
||||
/agent-note-forge-changes-view-responsiveness/decision:
|
||||
en: 40550cf129ab4c0c
|
||||
zh: 2e9a3597d03ce185
|
||||
/agent-note-forge-changes-view-responsiveness/alternatives-considered:
|
||||
en: c9833999164e8b67
|
||||
zh: 9459a95f307db854
|
||||
/agent-note-forge-changes-view-responsiveness/consequences:
|
||||
en: 2d74147e306ed174
|
||||
zh: f1369020f27f92c0
|
||||
@@ -0,0 +1,41 @@
|
||||
# Agent Note: Forge changes view responsiveness
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-07-forge-changes-view-responsiveness.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The forge changes view of a large change request froze the browser. Opening #7985 (366 files, 37,563 drawn lines) kept the main thread busy for about five seconds, "expand all" for fifteen, and every later state change, such as a poll result, a tool result, a file jump, or a keystroke in the file filter, re-rendered every file section. While the view was visible, the whole app slowed down: two subject-less `:has()` rules in `ui-sidebar-files` made each DOM change restyle the entire document, and the view's hundred thousand nodes made each restyle cost 170–260 ms, so a streaming Agent turn kept the main thread saturated.
|
||||
|
||||
## Decision
|
||||
|
||||
**Scoped `:has()` rules.** The navigator's covering rules name their row through `data-files-navigator-row`, which both hosts of `sidebar.files.navigator` set, so a DOM change outside such a row schedules no document-wide invalidation.
|
||||
|
||||
**Sections draw what changed and what the reader reaches.** `ChangesTab` passes each memoized `DiffFile` values whose identity survives its renders: one handler object, one comment-actions object, and per-file strings and booleans. Tab visibility is a prop of every section, so a visibility change redraws them all; leaving the view measured +57 ms against reading it from a React context, which the client packages forbid business components to do. The scrollport's reach tracker travels in the handler object. An expanded file holds a 22 px row per drawn line until its section first comes within 1200 px of the scrollport, then draws its lines and keeps them. After a jump, the browser's scroll anchoring keeps the target in place while the sections above it draw.
|
||||
|
||||
**Highlighting in the drawing render.** A section highlights its lines in the same render that draws them, as before, so the drawn text is always the file's current text and a native selection keeps its text nodes.
|
||||
|
||||
**Fewer serial reads.** A panel state equal to the published one reaches no follower. `changeRequestDiff` reads the patch and `.gitattributes` together. Snapshots carry the base commit as `baseSha`; `ForgeService.diff` passes it to the provider, and forge-github starts the compare read while its GraphQL read confirms the head.
|
||||
|
||||
**Pixel measurement.** Whether a section is near the scrollport decides whether React renders its lines at all, which CSS cannot express: `content-visibility` only skips layout and paint of nodes that already exist. The client packages offer no injected measurement hook, so one `IntersectionObserver` on the scrollport measures it off the main thread.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**`content-visibility: auto` alone** cut style work as much as scoping the rules did, but kept the React render and Shiki tokenization of every expanded file at open, about 3 s of script, and its placeholder sizes would need estimates for every collapsed and expanded section.
|
||||
|
||||
**Full virtualization that also unmounts far sections** would bound the DOM after long scrolls, but a section holds a comment draft and a text selection, which unmounting loses.
|
||||
|
||||
**Deferred idle-time highlighting** drew plain text and applied tokens once the page was idle and the scrollport still. It kept fast scrolling smooth, but tokens carry their own text, so a file whose content changed at the same path showed its previous text until the next pass, and replacing the plain text nodes collapsed a selection made in the meantime. Against it, highlighting while drawing raised the blocking time of scrolling all of #7985 from 22 ms to 1,634 ms and its longest frame gap from 34 ms to 817 ms; other operations stayed within 0.1 s.
|
||||
|
||||
**The CSS Custom Highlight API** would paint token colors over unchanged text nodes and keep deferral without either defect, but it cannot apply the themes' bold and italic, and its cost over tens of thousands of ranges is unmeasured.
|
||||
|
||||
**Re-aligning a jumped-to section every frame for a second** kept the last file flush with the end of the list, but it also pulled back any scroll it did not start, such as one from find in page; scroll anchoring already holds every other target at the top.
|
||||
|
||||
**Highlighting in a Web Worker** removes tokenization from the main thread entirely, including a heavy grammar's first use, but the shared highlighter in `ui-primitives` owns Shiki; moving it is a separate change for every consumer.
|
||||
|
||||
**A provider-private cache of base commits** would avoid the optional `baseSha` field, but it adds retained state without an owner that knows when a change request stops being watched.
|
||||
|
||||
## Consequences
|
||||
|
||||
Opening #7985 now takes 0.5 s of main-thread work instead of 5.2 s, and file jumps, filtering, polling, and Agent turns no longer produce long tasks. In exchange, the browser's find in page does not see lines of files the reader has not approached, and scrolling onto files in a slow grammar's language, such as C++, highlights them during the scroll, up to about 0.8 s of main-thread work when that grammar is first used. A diff read costs a second compare request when the base commit changed after the latest status.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Agent Note: Forge 变更视图的响应速度
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-07-forge-changes-view-responsiveness.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
大型变更请求的 forge 变更视图会让浏览器卡住。打开 #7985(366 个文件、37,563 个绘制行)时主线程忙约 5 秒,“全部展开”约 15 秒;之后的每次状态变化,例如轮询结果、工具结果、跳转文件或在文件筛选框中按键,都会重渲染所有文件段。视图可见时整个应用都变慢:`ui-sidebar-files` 中两条没有主体的 `:has()` 规则让每次 DOM 变化都重算整个文档的样式,而视图的十万个节点让每次重算耗时 170–260 ms,所以 Agent 流式输出的回合会让主线程一直饱和。
|
||||
|
||||
## Decision
|
||||
|
||||
**限定 `:has()` 规则。** 导航器的遮盖规则通过 `data-files-navigator-row` 指定所在行,`sidebar.files.navigator` 的两个宿主都会设置它,因此这类行之外的 DOM 变化不再触发全文档失效。
|
||||
|
||||
**文件段只绘制变化的部分和读者接近的部分。** `ChangesTab` 传给每个 memo 化的 `DiffFile` 的值在多次渲染之间保持同一标识:一个处理函数对象、一个评论操作对象,以及每个文件的字符串和布尔值。标签页可见性作为每个文件段的参数传入,可见性变化时全部文件段都会重绘;离开视图实测比从 React context 读取多 57 ms,而客户端包禁止业务组件读取 context。滚动区域的接近跟踪对象放在处理函数对象中传递。展开的文件在它的段第一次进入滚动区域 1200 px 范围之前,按每个绘制行 22 px 占位,之后绘制各行并一直保留。跳转后,上方文件段绘制时,浏览器的滚动锚定让目标保持原位。
|
||||
|
||||
**在绘制的渲染中高亮。** 文件段与修复前一样,在绘制各行的同一次渲染中完成高亮,所以画出的始终是文件当前的文本,原生选区所在的文本节点也不会被替换。
|
||||
|
||||
**减少串行读取。** 与已发布状态相同的面板状态不会通知任何关注方。`changeRequestDiff` 同时读取补丁和 `.gitattributes`。快照把基准提交作为 `baseSha` 携带;`ForgeService.diff` 把它传给提供方,forge-github 在 GraphQL 读取确认 head 的同时就开始 compare 读取。
|
||||
|
||||
**像素测量。** 文件段是否接近滚动区域,决定 React 是否渲染它的各行,这一点 CSS 无法表达:`content-visibility` 只能跳过已有节点的布局与绘制。客户端包没有可注入的测量 hook,所以在滚动区域上用一个 `IntersectionObserver`,在主线程之外测量。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只用 `content-visibility: auto`** 减少的样式工作与限定规则相当,但打开时仍要对每个展开文件做 React 渲染和 Shiki 分词,约 3 秒脚本时间,而且每个折叠和展开的段都需要估计占位尺寸。
|
||||
|
||||
**同时卸载远处文件段的完整虚拟化** 可以在长距离滚动后限制 DOM 规模,但文件段持有评论草稿和文本选区,卸载会丢失它们。
|
||||
|
||||
**空闲时延迟高亮** 先画纯文本,等页面空闲且滚动区域静止后再应用 token。它让快速滚动保持流畅,但 token 自带文本,同一路径内容变化后会显示旧文本直到下一轮高亮完成;替换纯文本节点还会清掉期间做出的选区。与它相比,绘制时高亮让滚动整个 #7985 的阻塞时间从 22 ms 增到 1,634 ms,最长帧间隔从 34 ms 增到 817 ms;其他操作的差异在 0.1 秒以内。
|
||||
|
||||
**CSS Custom Highlight API** 可以在不变的文本节点上绘制 token 颜色,保留延迟高亮又没有上述两个问题,但它无法应用主题中的粗体和斜体,几万个范围的绘制成本也没有测过。
|
||||
|
||||
**跳转后一秒内每帧重新对齐** 能让最后一个文件贴紧列表末端,但它也会把不是它发起的滚动拉回去,例如页内查找引起的滚动;而对其他目标,滚动锚定已经能让它们保持在顶部。
|
||||
|
||||
**在 Web Worker 中高亮** 能把分词完全移出主线程,包括重型语法的首次使用,但 Shiki 由 `ui-primitives` 中的共享高亮器持有;迁移它是影响所有使用方的另一项改动。
|
||||
|
||||
**由提供方私有缓存基准提交** 可以省去可选的 `baseSha` 字段,但会引入保留状态,而且没有一个知道变更请求何时不再被 watch 的所有者。
|
||||
|
||||
## Consequences
|
||||
|
||||
打开 #7985 的主线程工作从 5.2 秒降到 0.5 秒,跳转文件、筛选、轮询和 Agent 回合不再产生长任务。代价是:浏览器的页内查找看不到读者尚未接近的文件中的行;滚动到慢语法(例如 C++)的文件时会在滚动中完成高亮,该语法首次使用时最多约 0.8 秒的主线程工作。最新状态之后基准提交有变化时,一次 diff 读取会多一次 compare 请求。
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 4b312be894531bee
|
||||
zh: d655648ea5843ef5
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision:
|
||||
en: a1732e2b1b46cb39
|
||||
zh: ddfc2bdcffa099a5
|
||||
en: 109e418dd92ead24
|
||||
zh: e2564f0f98cc4641
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/per-program-execution-controls:
|
||||
en: da694641e1d009de
|
||||
zh: 9d7492d39039af66
|
||||
@@ -18,23 +18,23 @@
|
||||
en: 4cd76a34f4712e1a
|
||||
zh: 303ef72a18644d7c
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-run-code-tool-and-the-dispatch-bridge:
|
||||
en: c3d079330748cd24
|
||||
zh: 4e2cc41d00227780
|
||||
en: 69e4683ac3150bdf
|
||||
zh: d8eaa12eaba6d67e
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/observability-tool-ptc-dispatch:
|
||||
en: 5423da23d4e8d1d9
|
||||
zh: f1198d4f224f3fe6
|
||||
en: 951fb03a27841eea
|
||||
zh: 38928d1ca859eced
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-ptc-runtime-seam:
|
||||
en: 4c423f4e9cef6055
|
||||
zh: 5c23a3637eb420c0
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-node-process-runtime:
|
||||
en: 0b846ed33977e383
|
||||
zh: e45158758d657f9a
|
||||
en: b2a8d7d654d1832b
|
||||
zh: 5852a2a3660e5a2e
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/trust-posture:
|
||||
en: d62b41a6a5c58e5f
|
||||
zh: ef72c5a9b32b370e
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/what-the-model-sees:
|
||||
en: 81c12f19f7a967c1
|
||||
zh: 29734ca964acdec2
|
||||
en: 109d4c326bfcf572
|
||||
zh: 9f6be5afc281054d
|
||||
/agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/consequences:
|
||||
en: 761eb6c1aeb7af18
|
||||
zh: 5434456a3d0a1b65
|
||||
|
||||
@@ -22,7 +22,7 @@ Three decisions, each elaborated in its own section below:
|
||||
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-ptc-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, ordinary canonical binding values, `ToolCallError` and lossless runtime output. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript completion suppression and text/image selection. 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
|
||||
|
||||
@@ -48,9 +48,9 @@ The [Node execution decision](../architecture/2026-09-11-sandboxed-node-ptc-runt
|
||||
|
||||
Under `'ptc'` 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 reference](../../../../packages/core/tools/README.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.
|
||||
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 reference](../../../../packages/core/tools/README.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 consumer-facing value, including program Images for the selected TypeScript bindings; 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.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.
|
||||
3. **Settle after quiescence.** When the runtime settles, the bridge aborts outstanding work and drains the dispatch queue before returning. TypeScript success returns captured logs as canonical output and projects inspected images into durable `tool/result.content`; other language consumers also render their completion value. The result card reads that content 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.
|
||||
|
||||
@@ -58,13 +58,13 @@ Under `'ptc'` the registry owns `run_code` as a reserved presentation transport
|
||||
|
||||
**Tool-call allowance.** Counting attempts before validation and queuing bounds loops that repeatedly fail or enqueue work. The allowance scales with the resolved timeout and permits bursts; it does not enforce a rolling window. Exhaustion uses the run-scoped abort path so a program cannot catch a binding failure and keep running. Active calls are canceled, queued calls are abandoned, and settlement waits for cleanup. Completed effects remain; a new run receives a fresh allowance. The [executor README](../../../../packages/core/tool-executor-ptc/README.md#use-this-package) owns configuration and failure reporting.
|
||||
|
||||
**Presentation.** `run_code`'s render intent is decided here per the [render-intent Agent Note](../architecture/2026-07-02-tool-render-intent-union.md): `presentCall` creates a `generic` card with `kind: 'execute'`, the program text as its title, and the same program text as `rawInput`; `run_code` intentionally declares no `presentResult`, so the TUI and host/client runtime (Web) complete that card through their generic raw-content fallback using the final durable `tool/result.content`, including captured logs plus the returned value, failure, or post-policy spill preview. This is not a `terminal` card: that card's semantics are "a shell command in a working directory", which a program is not. See the [result-card completeness note](../../archived/bug-fix/2026-07-20-code-mode-result-card-completeness.md).
|
||||
**Presentation.** `run_code` uses a `generic` card with `kind: 'execute'`, the model-authored description as its title and the submitted program as `rawInput`. UI adapters read durable `tool/result.content` for captured text, selected images, failure or the post-policy spill preview. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns selection of that content.
|
||||
|
||||
### Observability: `tool/ptc-dispatch`
|
||||
|
||||
Each sub-dispatch appends a log-only `tool/ptc-dispatch-start` event at pool entry and a `tool/ptc-dispatch` settle event containing parent and child call ids, tool identity, normalized arguments, and the complete rendered `content`/`isError` outcome. It remains outside model history but available to persistence and UIs. Appends occur inside the open `run_code` turn. Direct executions without an agent still run but cannot log the event.
|
||||
|
||||
New sub-calls use `<parent>:ptc:<n>` ids, numbered by tool-call attempt. Invalid arguments consume a number without a dispatch event, so logged ids may have gaps. All call ids are opaque to consumers: migration preserves every historical id byte-for-byte, including `:code:` substrings, so dispatch pairs, spill references, and other correlations remain intact. The bridge attributes forwarded image context to `{ kind: 'plugin', plugin: 'tools-ptc' }`.
|
||||
New sub-calls use `<parent>:ptc:<n>` ids, numbered by tool-call attempt. Invalid arguments consume a number without a dispatch event, so logged ids may have gaps. All call ids are opaque to consumers: migration preserves every historical id byte-for-byte, including `:code:` substrings, so dispatch pairs, spill references, and other correlations remain intact. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript image presentation; other language consumers attribute forwarded image contexts to `{ kind: 'ptc-mode' }`.
|
||||
|
||||
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.
|
||||
|
||||
@@ -78,7 +78,7 @@ Program outcomes resolve as result fields; caller misuse may reject. Lossless bi
|
||||
|
||||
### The Node process runtime
|
||||
|
||||
The Node provider strips erasable TypeScript, resolves its executable/bootstrap in the configured filesystem/subprocess world, and launches through the shared sandbox and managed process owners. Each child has an empty model environment and fresh program globals. Typed rejection constructors and the capturing console remain program-visible.
|
||||
The Node provider strips erasable TypeScript, resolves its executable/bootstrap in the configured filesystem/subprocess world, and launches through the shared sandbox and managed process owners. Each child has an empty model environment and fresh program globals. Typed rejection constructors and `inspect` are program-visible; optional console support shares the inspection function.
|
||||
|
||||
Binding traffic uses a dedicated control channel separate from stdout/stderr. The host validates frames, call identities and allowed bindings before dispatch. Output, pending calls and channel buffers have configured limits; completion, deadline, cancellation and protocol failure terminate and await the managed range. The provider README and sandboxed Node decision own exact bounds and platform limits.
|
||||
|
||||
@@ -88,7 +88,7 @@ The selected OS backend constrains direct Node effects under the same policy use
|
||||
|
||||
### What the model sees
|
||||
|
||||
The SDK instructs the model to write an async body in the loaded runtime's language (an erasable-TypeScript body by default; a Python `async` body under a Python runtime — see the [language-dispatch note](../../archived/feature/2026-07-31-ptc-language-dispatch.md)), call tools through `await tools.name(args)`, catch rejected tool calls when needed, and return or log only the output that should re-enter context. Both flavors state the same contract in their own primitive: independent read-only calls MAY overlap under `Promise.all` (TypeScript) or `asyncio.gather` (Python), mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, but remains stable for provider caching.
|
||||
The SDK declares the loaded runtime's source format and visible tool bindings, instructs the model to call tools through `await tools.name(args)` and catch rejected tool calls when needed, and presents language-specific output instructions. TypeScript selects output through `inspect`; the Python flavor retains return and print output. Independent read-only calls may overlap under `Promise.all` or `asyncio.gather`, mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, but remains stable for provider caching.
|
||||
|
||||
The transport's own `description` and both SDK instruction flavors open by naming `code` and `description` as the call's two required arguments. Prose that describes the call as passing a program leaves the second argument discoverable only through the parameter schema, and a model that emits `{code}` alone loses the whole written program to an `INVALID_ARGS` rejection.
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
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-ptc-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。
|
||||
本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、普通规范绑定值、`ToolCallError` 与无损运行时输出。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript 完成值抑制及文本/图片选择。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。
|
||||
|
||||
### 每段程序的执行控制
|
||||
|
||||
@@ -48,9 +48,9 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
在 `'ptc'` 下,注册表拥有 `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 参数创建快照,进入原生约定的分发池(调度设计由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责),以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/ptc-dispatch-start`/`tool/ptc-dispatch` 事件对,其中结算侧携带完整渲染后的结果内容。成功时返回工具最终的规范 JSON 值;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。
|
||||
1. **构建绑定。** 一个 run 级别的 signal 跟随外层取消,并在 run 结算时被 abort。每个可见工具绑定都会对无损 JSON 参数创建快照,进入原生约定的分发池(调度设计由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责),以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/ptc-dispatch-start`/`tool/ptc-dispatch` 事件对,其中结算侧携带完整渲染后的结果内容。成功时返回面向消费方的值,包括指定 TypeScript 绑定的程序 Image;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。
|
||||
2. **运行已解析输入:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`。请求携带程序、绑定、运行级信号、调用 Session 的 cwd 与适用的已解析文件策略。运行级信号将外层结算与执行取消关联。
|
||||
3. **完全停稳后结算。** 运行时结算后,桥 abort 未完成的工作并排空分发队列后再返回。成功时返回捕获的日志和完成值,将其作为规范输出;注册表再把该值渲染为持久化的 `tool/result.content`,供结果卡片直接读取。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。
|
||||
3. **完全停稳后结算。** 运行时结算后,桥接层 abort 未完成的工作并排空分发队列后再返回。TypeScript 成功结果将捕获日志作为规范输出,并将显式展示的图片投影到持久化的 `tool/result.content`;其他语言消费方还会渲染完成值。结果卡片直接读取该内容。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。
|
||||
|
||||
**子调用上下文通过父调用延后。** 在 `run_code` 内部注入会破坏父调用/结果的相邻性,因此 `ToolRunContext.deferContext()` 按分发顺序收集每个子结果的 `additionalContexts` 条目。即使程序后来抛出异常,注册表仍携带该数组;循环只在外层结果与步骤中所有兄弟结果之后追加每个条目。外层 post-execute 阻止会丢弃工具延后的条目,只暴露阻止 decision 显式附加的上下文。
|
||||
|
||||
@@ -58,13 +58,13 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
**工具调用额度。** 在验证和排队之前对尝试计数,可以限制重复失败或持续入队的循环。额度随最终超时时间缩放,允许集中调用,不实施滑动窗口限制。额度耗尽时使用运行级取消路径,使程序无法捕获绑定错误后继续运行。活动调用被取消,排队调用被放弃,结算会等待清理完成。已完成的操作仍然生效;新运行获得完整额度。[执行器 README](../../../../packages/core/tool-executor-ptc/README.zh.md#use-this-package) 负责配置与失败报告。
|
||||
|
||||
**呈现。** `run_code` 的 render intent 按[呈现意图 Agent Note](../architecture/2026-07-02-tool-render-intent-union.zh.md)在此决定:`presentCall` 创建一个 `generic` 卡片,`kind: 'execute'`,以程序文本作为标题,并将同一程序文本作为 `rawInput`;`run_code` 有意不声明 `presentResult`,因此 TUI 和宿主/客户端运行时(Web)会通过通用原始内容回退机制,使用最终持久化的 `tool/result.content` 补全该卡片,其中包括捕获的日志,以及返回值、失败信息或 post-policy spill 预览。这不是 `terminal` 卡片:该卡片的语义是「工作目录中的 shell 命令」,程序不是。参见[结果卡片完整性说明](../../archived/bug-fix/2026-07-20-code-mode-result-card-completeness.md)。
|
||||
**呈现。** `run_code` 使用 `kind: 'execute'` 的 `generic` 卡片,标题为模型填写的描述,`rawInput` 为提交的程序。UI 适配器读取持久化的 `tool/result.content`,展示捕获文本、所选图片、失败或 post-policy spill 预览。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责这些内容的选择。
|
||||
|
||||
### 可观测性:`tool/ptc-dispatch`
|
||||
|
||||
每次子分发在进入分发池时追加一个仅日志的 `tool/ptc-dispatch-start` 事件,并以一个 `tool/ptc-dispatch` 结算事件收尾,后者包含父子 call id、工具标识、规范化参数以及完整渲染后的 `content`/`isError` 结果。它不进入模型历史,但可供持久化和 UI 使用。追加发生在开放的 `run_code` 轮次内。没有 agent 的直接执行仍然运行,但无法记录该事件。
|
||||
|
||||
新子调用使用 `<parent>:ptc:<n>` 标识,按工具调用尝试编号。无效参数会占用编号而不产生分发事件,因此日志中的编号可能有空缺。消费者将所有 call id 视为不透明值:迁移逐字节保留每个历史标识,包括 `:code:` 子串,因此分发事件对、spill 引用及其他关联保持完整。桥接层将转发图片上下文的来源标记为 `{ kind: 'plugin', plugin: 'tools-ptc' }`。
|
||||
新子调用使用 `<parent>:ptc:<n>` id,按工具调用尝试编号。无效参数在没有分发事件时仍消耗编号,因此日志中的 id 可能有空缺。所有调用 id 对消费方均不透明:迁移逐字节保留每个历史 id,包括 `:code:` 子串,使分发事件对、spill 引用和其他关联保持完整。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript 图片呈现;其他语言消费方将转发的图片上下文归属为 `{ kind: 'ptc-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 生命周期含义。
|
||||
|
||||
@@ -78,7 +78,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一
|
||||
|
||||
### Node 进程运行时
|
||||
|
||||
Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程世界中解析可执行文件与 bootstrap,并通过共享沙箱与受管进程所有者启动。每个子进程都有空模型环境和全新程序全局对象。类型化拒绝构造器与捕获 console 仍对程序可见。
|
||||
Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程世界中解析可执行文件与 bootstrap,并通过共享沙箱与受管进程所有者启动。每个子进程都有空模型环境和全新程序全局对象。类型化拒绝构造器与 `inspect` 对程序可见;可选 console 支持复用展示函数。
|
||||
|
||||
绑定通信使用与 stdout/stderr 分开的专用控制通道。Host 在分派前验证帧、调用身份与允许的绑定。输出、待处理调用与通道缓冲有配置上限;完成、截止、取消和协议失败会终止并等待受管范围。提供方 README 与沙箱 Node 决策负责确切上限和平台限制。
|
||||
|
||||
@@ -88,7 +88,7 @@ Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程
|
||||
|
||||
### 模型看到的内容
|
||||
|
||||
SDK 指示模型编写一个所加载运行时语言的异步函数体(默认可擦除 TypeScript;Python 运行时下为 Python `async` 函数体——见[语言分发 note](../../archived/feature/2026-07-31-ptc-language-dispatch.md)),通过 `await tools.name(args)` 调用工具,在需要时捕获被拒绝的工具调用,并仅 return 或 log 应重新进入上下文的输出。两种 flavor 用各自的原语陈述同一约定:相互独立的只读调用可以(MAY)在 `Promise.all`(TypeScript)或 `asyncio.gather`(Python)下重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,但对提供方缓存保持稳定。
|
||||
SDK 声明所加载运行时的源码格式和可见工具绑定,指示模型通过 `await tools.name(args)` 调用工具、在需要时捕获被拒绝的工具调用,并提供各语言的输出说明。TypeScript 通过 `inspect` 选择输出;Python flavor 保留 return 和 print 输出。相互独立的只读调用可通过 `Promise.all` 或 `asyncio.gather` 重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,但对提供方缓存保持稳定。
|
||||
|
||||
传输自身的 `description` 与两种 flavor 的 SDK 说明都以点名 `code` 和 `description` 这两个必填参数开头。把该调用描述成「传入一个程序」的散文会让第二个参数只能从参数 schema 中发现,而只发出 `{code}` 的模型会因 `INVALID_ARGS` 被拒,连同已写好的整个程序一起丢失。
|
||||
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
en: 16c4ee08b65ead23
|
||||
zh: df80d6e49982615b
|
||||
/agent-note-parallel-tool-call-execution-by-per-call-safety/configuration-and-declarations:
|
||||
en: e112957ed8a48039
|
||||
zh: 37d63f9ea4968fb2
|
||||
en: 082e5a02b092b656
|
||||
zh: ca674a08323d8cc1
|
||||
/agent-note-parallel-tool-call-execution-by-per-call-safety/verification:
|
||||
en: 224b6838130c113f
|
||||
zh: f3d7eb68ab5932fb
|
||||
en: 20d0e1724ebc1247
|
||||
zh: baa89694cea135c8
|
||||
/agent-note-parallel-tool-call-execution-by-per-call-safety/alternatives-considered:
|
||||
en: 17becc038bb7df7c
|
||||
zh: 673d9a9bdfa39edf
|
||||
|
||||
@@ -60,13 +60,13 @@ Any shared state touched during execution must be concurrency-safe. This include
|
||||
|
||||
`maxParallelToolCalls` is a positive AgentLoop deployment cap shared by every agent the factory creates. It defaults to `10`; `1` preserves serial execution. Exact fields and defaults live in the generated [configuration catalog](../../../../docs/config-catalog.md).
|
||||
|
||||
The shipped declarations are conservative. Web search, web fetch, filesystem read, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Filesystem writes and edits, bash tools, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive.
|
||||
The shipped declarations are conservative. Web search, web fetch, filesystem read, glob, grep, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Read-only queries also opt in: the background job list, the subagent tree and model listings, scheduled task and Team task reads, Cordis Inspect queries, and MCP resource reads. Filesystem writes and edits, bash tools, `job_output` because it consumes a read cursor, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. Read-only `lsp` stays exclusive because its language-server pool already serializes queries per workspace, so overlap would gain nothing, and the goal tools stay exclusive under the [goal tools Agent Note](2026-07-19-model-facing-goal-tools.md).
|
||||
|
||||
Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`.
|
||||
Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `working-directory/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration.
|
||||
Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration, and the working-directory service tests pin per-Session serialization of concurrent directory changes.
|
||||
|
||||
Snapshot coverage pins the visible multi-call transcript: pending calls may overlap while completed results remain model-ordered. PTC mode coverage pins its serial boundary. No provider-backed e2e is required because scheduling is deterministic loop behavior.
|
||||
|
||||
|
||||
@@ -60,13 +60,13 @@ Status: implemented
|
||||
|
||||
`maxParallelToolCalls` 是 AgentLoop 的正整数部署上限,由工厂创建的所有 agent(智能体)共享。默认值为 `10`;`1` 保持串行执行。字段和默认值的精确定义见生成的[配置目录](../../../../docs/config-catalog.zh.md)。
|
||||
|
||||
当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。文件系统写入与编辑、bash 工具、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。
|
||||
当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、glob、grep、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。只读查询也选择并行:后台任务列表、subagent 树与模型列表、定时任务与 Team 任务读取、Cordis Inspect 查询以及 MCP 资源读取。文件系统写入与编辑、bash 工具、`job_output`(因为它会消费读取游标)、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。只读的 `lsp` 仍按独占方式执行,因为其语言服务器池已按工作区串行化查询,重叠执行不会带来收益;goal 工具依照 [goal 工具 Agent Note](2026-07-19-model-facing-goal-tools.zh.md) 仍按独占方式执行。
|
||||
|
||||
文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。
|
||||
文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `working-directory/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。
|
||||
|
||||
## 验证
|
||||
|
||||
单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明。
|
||||
单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明,工作目录服务测试固定了按会话串行化并发目录变更。
|
||||
|
||||
快照测试固定了可见的多调用 transcript(文本记录):待处理调用可以重叠执行,已完成结果仍按模型顺序排列。PTC mode 测试固定了其串行边界。此调度属于确定性循环行为,因此无需依赖提供方的 e2e 测试。
|
||||
|
||||
|
||||
@@ -9,32 +9,32 @@
|
||||
en: e2403bc358c4e14b
|
||||
zh: dd37923097a3b24c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision:
|
||||
en: 2218fac13ef57c77
|
||||
zh: d4a18daa9debc77c
|
||||
en: 6dd62ee16c69536c
|
||||
zh: aec9fa1c74be28e5
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/generated-sdk:
|
||||
en: 30583e9ac6715952
|
||||
zh: 3a85c9482abf574c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/binding-values-and-failures:
|
||||
en: ecb95cafa2dc1297
|
||||
zh: ccdf300ca936ca12
|
||||
en: 8b10f08e67ca9323
|
||||
zh: e57adb520049f407
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/outer-result-and-output-ledger:
|
||||
en: d907d0a8205157e1
|
||||
zh: 1ed99168266a7ca4
|
||||
en: d57456d76fed9c6d
|
||||
zh: 453775faad48588c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/typed-handles-and-lifetime:
|
||||
en: b2b9318c2812e3a4
|
||||
zh: 73cf34bfd487e2f1
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/persistence-metadata-and-spill:
|
||||
en: c388619f862a92ba
|
||||
zh: d557eae40c7b6b7a
|
||||
en: 2c3ad4ec376ed2d5
|
||||
zh: 49e8206a4c17b1b3
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/testing:
|
||||
en: 728513c779f031f8
|
||||
zh: f6d869f18add7242
|
||||
en: 81a4355914c918cf
|
||||
zh: 36aa414cd382ff9c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/alternatives-considered:
|
||||
en: dedd87b9b35d8fab
|
||||
zh: 78db4c7e8c4e5f61
|
||||
en: 069a1e170c7d1dfb
|
||||
zh: 14ce5a56e602595c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/consequences:
|
||||
en: f5726b5e7a2fc73f
|
||||
zh: 0b9aa884db5d920f
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/known-limitations-and-deferred-work:
|
||||
en: a42af629ad6872cc
|
||||
zh: 41e5c0bb3de0ae4d
|
||||
en: 19828c2e5796df2d
|
||||
zh: 2ef63df81fca7a72
|
||||
@@ -14,7 +14,7 @@ The [canonical tool-output contract](../../../../packages/core/tools/README.md)
|
||||
|
||||
## Decision
|
||||
|
||||
PTC mode is a typed projection of the visible tool registry. Each successful binding resolves to the final canonical `JsonValue` after post-execute policy, while a failed binding rejects with a real `ToolCallError`. Intermediate values remain inside the run and cross the worker boundary whole. The outer `run_code` logs, completion value, or failure diagnostic enter the configurable output ledger and model-facing spill pipeline; a successfully settled sub-call whose final Native content contains an image additionally defers that complete ordered content through the parent result as logged, source-attributed context.
|
||||
PTC mode is a typed projection of the visible tool registry. Ordinary successful bindings resolve to the final canonical `JsonValue` after post-execute policy, while failed bindings reject with a real `ToolCallError`. Intermediate values remain inside the run and cross the process boundary whole. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript Image bindings, completion suppression and selection of visible text and images. Other language consumers retain completion rendering and deferred image-bearing content.
|
||||
|
||||
This note owns the return and failure contract layered on the original [PTC mode foundation](2026-06-15-ptc.md). The unified schema vocabulary is owned by the [JSON-value schema DSL reference](../../../../packages/core/tools/README.md), and Native rendering and policy projection remain owned by the canonical-output note.
|
||||
|
||||
@@ -49,15 +49,15 @@ declare const tools: {
|
||||
|
||||
### Binding values and failures
|
||||
|
||||
Before dispatch the bridge snapshots binding arguments as lossless JSON and snapshots the detached value again for an independent durable summary event. Host-side detachment, immutable execution, and output-schema projection all use iterative traversals rather than nested structured clone or recursive freezing. `undefined`, non-finite numbers, `-0`, sparse arrays, cycles, functions, and exotic objects reject that call before the tool runs. Successful dispatch returns `ToolExecutionResult.value`; Native `content`, metadata, and internal error information do not cross to the program. Image-bearing final content is not a second binding value: the bridge ferries it after the outer result so the next model request can see the durable image, while post-execute block/content replacement remains authoritative and text-only results are not duplicated.
|
||||
Before dispatch the bridge snapshots binding arguments as lossless JSON and snapshots the detached value again for an independent durable summary event. Host-side detachment, immutable execution, and output-schema projection all use iterative traversals rather than nested structured clone or recursive freezing. `undefined`, non-finite numbers, `-0`, sparse arrays, cycles, functions, and exotic objects reject that call before the tool runs. Ordinary successful dispatch returns `ToolExecutionResult.value`; the selected TypeScript image bindings use the final image attachment to construct a program Image. Post-execute blocking and result projection remain authoritative. Native content envelopes, metadata and internal error information stay outside ordinary binding values.
|
||||
|
||||
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 `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.
|
||||
Ordinary binding arguments and JSON 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.
|
||||
Runtime consumers that retain completions receive exact lossless JSON: `undefined` omits the completion and `null` is an explicit result. TypeScript `run_code` requests completion discard and returns captured logs plus optional sandbox facts as its canonical value; selected images enter its rendered content separately. Other language consumers also expose `result?: JsonValue`. Their 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, keeping traversal stack-safe and formatted size linear in the canonical JSON size.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -73,13 +73,13 @@ Temporary Cordis Plugins follow the same rule: `cordis_mount` returns `{ id, plu
|
||||
|
||||
### Persistence, metadata, and spill
|
||||
|
||||
Nested dispatch logs the sub-call's full rendered `content`/`isError` on `tool/ptc-dispatch` but does not persist canonical values. `tool/result` continues to persist only rendered content, error, and optional metadata. A successful final content sequence containing an image is also wrapped in a source-attributed user message and deferred through the outer result; the normal session event makes that model-visible input reconstructable. The [PTC mode note](2026-06-15-ptc.md) owns durable event names and historical identity preservation; replay cannot recreate intermediate canonical program values.
|
||||
Nested dispatch logs the sub-call's full rendered `content`/`isError` on `tool/ptc-dispatch` but does not persist canonical values. TypeScript programs select images for the outer `tool/result.content` through explicit inspection. Other language consumers defer successful image-bearing content as source-attributed user messages after the outer result. The normal Session events make these model-visible inputs reconstructable. The [PTC mode note](2026-06-15-ptc.md) owns durable event names and historical identity preservation; replay cannot recreate intermediate canonical program values.
|
||||
|
||||
The opaque `exec.parent` token marks nested calls. Presentation metadata and generic or tool-owned spill projections skip those calls; their canonical values never enter context. The Client can derive [nested terminal cards](../../../../packages/client/ui-tool/README.md) from raw dispatch events without metadata. The outer `run_code` call produces the model-facing result and may spill its final post-policy presentation; `run_code` intentionally declares neither a result presenter nor presentation metadata, so UI adapters complete the card through their generic raw-content fallback using durable `tool/result.content`.
|
||||
|
||||
## Testing
|
||||
|
||||
Compile-time and snapshot tests pin exact `ToolArgsMap`, `ToolOutputMap`, `ToolName`, schema-to-TypeScript coverage, exotic names, and assembled PTC mode image forwarding. Registry and real-worker tests cover scalar, array, object, and null values; raw string rendering; absent `undefined`; consumer-declared real rejection classes, including `ToolCallError`; invalid arguments and completions, including intrinsic-looking forged prototypes; model-mutated JSON-boundary globals, prototype methods, constructor slots, and inherited descriptor fields; typed binding failures after those mutations; large uncapped intermediate bindings; nested spill suppression; generic image-bearing context deferral plus post-execute replacement/block precedence; exact and over-limit 64 MiB accounting; combined logs/value/diagnostic accounting; giant thrown stacks; bounded failure spill; hostile forged traffic; and built-package execution.
|
||||
Compile-time and snapshot tests pin exact `ToolArgsMap`, `ToolOutputMap`, `ToolName`, schema-to-TypeScript coverage, exotic names, and assembled PTC mode image projection. Registry and real-worker tests cover scalar, array, object, and null values; raw string rendering; absent `undefined`; consumer-declared real rejection classes, including `ToolCallError`; invalid arguments and completions, including intrinsic-looking forged prototypes; model-mutated JSON-boundary globals, prototype methods, constructor slots, and inherited descriptor fields; typed binding failures after those mutations; large uncapped intermediate bindings; nested spill suppression; consumer-specific image projection plus post-execute replacement/block precedence; exact and over-limit 64 MiB accounting; combined logs/value/diagnostic accounting; giant thrown stacks; bounded failure spill; hostile forged traffic; and built-package execution.
|
||||
|
||||
Keyless real-worker integration tests pin the two handle workflows that prose results could not safely support. A background bash call returns its job id, the outer run settles, and a later run polls that id to completion; separate cases prove pre-abort creates no task, post-publication call abort preserves the task, foreground execution stays signal-coupled, and `job_kill` owns cancellation. A Cordis program reads an active or pending mount's id and `waitingFor` fields directly, unmounts by that id, and confirms removal without parsing rendered text.
|
||||
|
||||
@@ -93,9 +93,9 @@ Keyless real-worker integration tests pin the two handle workflows that prose re
|
||||
|
||||
**Silently inspect or truncate an oversized completion.** Rejected because changing a JSON value into a string is lossy and type-incorrect. The explicit `output-limit` failure lets the model choose a smaller result, while the retained logs and diagnostic can still use normal outer spill.
|
||||
|
||||
**Require each rich leaf tool to inspect `exec.parent` and defer itself.** Rejected because it couples leaf tools to PTC mode internals, duplicates policy handling, and misses future rich tools. The dispatch bridge owns generic forwarding from the already settled final result.
|
||||
**Require each rich leaf tool to inspect `exec.parent` and defer itself.** Rejected because it couples leaf tools to PTC mode internals and duplicates policy handling. The dispatch bridge owns consumer-specific image projection from the already settled final result.
|
||||
|
||||
**Expose Native rich content as part of every binding's canonical value.** Rejected because a canonical value is lossless JSON and tool-specific; attachment blocks are a model projection with durable lifecycle semantics. Keeping the value and projection separate preserves typed programs without dropping images from later model context.
|
||||
**Expose Native rich content as part of every binding's canonical value.** Rejected because a canonical value is lossless JSON and tool-specific; attachment blocks are a model projection with durable lifecycle semantics. Consumer-owned program Image bindings preserve typed tool values while leaving image selection to the program.
|
||||
|
||||
## Consequences
|
||||
|
||||
@@ -111,6 +111,6 @@ The worker performs bounded-depth flat-wire transport and lossless validation bu
|
||||
- Intermediate values have no byte cap and can exhaust process or worker memory through retention, flat-wire copies, or structured-clone cost.
|
||||
- The 64 MiB hard cap applies only to the outer variable payloads, excluding fixed result-envelope syntax and presentation whitespace; spill cannot recover bytes rejected beyond that cap.
|
||||
- Provider or executor acquisition limits may already have discarded source data before a canonical value reaches PTC mode.
|
||||
- Unsupported MCP output schemas fall back to `JsonValue`; admitted MCP images use the generic deferred projection, while audio and embedded-resource payloads remain diagnostic-only.
|
||||
- Unsupported MCP output schemas fall back to `JsonValue`; image projection follows the consumer-specific rules above, while audio and embedded-resource payloads remain diagnostic-only.
|
||||
- Nested calls have no separate model-facing result; Client child cards do not add model context.
|
||||
- Code failures expose `ToolCallError` message and tool name only, without a programmatic error-code union.
|
||||
@@ -14,7 +14,7 @@ PTC mode 过去会把每个嵌套工具的结果从 `ContentBlock[]` 重新投
|
||||
|
||||
## 决策
|
||||
|
||||
PTC mode 是可见工具注册表的类型化投影。每个成功的绑定调用都会解析为 post-execute 策略处理后的最终规范 `JsonValue`,失败的绑定调用则会以真正的 `ToolCallError` 拒绝 Promise。中间值只存在于本次运行中,并完整跨越 worker 边界。外层 `run_code` 的日志、完成值或失败诊断会进入可配置的输出账本以及面向模型的输出落盘流水线;如果成功结算的子调用最终 Native 内容包含图片,其完整有序内容还会经父结果延后为写入日志且带来源归属的上下文。
|
||||
PTC mode 是可见工具注册表的类型化投影。普通成功绑定调用解析为 post-execute 策略处理后的最终规范 `JsonValue`,失败的绑定调用则以真正的 `ToolCallError` 拒绝 Promise。中间值保留在运行中,并完整跨越进程边界。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript Image 绑定、完成值抑制及可见文本和图片的选择。其他语言消费方保留完成值渲染和含图片内容的延后转发。
|
||||
|
||||
本文档定义叠加在原始 [PTC mode 基础](2026-06-15-ptc.zh.md)之上的返回值与失败约定。统一 schema 词汇由 [JSON 值 schema DSL reference](../../../../packages/core/tools/README.zh.md)负责定义;Native 渲染与策略投影仍由规范输出 Agent Note 负责定义。
|
||||
|
||||
@@ -49,15 +49,15 @@ declare const tools: {
|
||||
|
||||
### 绑定值与失败
|
||||
|
||||
分发前,桥接层会把绑定参数快照为无损 JSON,再对分离后的值生成一次快照,供独立的持久摘要事件使用。宿主侧的值分离、执行数据的不可变处理与输出 schema 投影均采用迭代遍历,而不使用嵌套结构化克隆或递归冻结。`undefined`、非有限数、`-0`、稀疏数组、循环引用、函数和非普通对象都会使该调用在工具运行前被拒绝。成功分发会返回 `ToolExecutionResult.value`;Native `content`、元数据和内部错误信息不会传入程序。含图片的最终内容不是第二份绑定值:桥接层会在外层结果之后转运它,使下一次模型请求可以看到持久图片;post-execute 阻止/内容替换仍具有权威性,纯文本结果不会重复。
|
||||
分发前,桥接层会把绑定参数快照为无损 JSON,再对分离后的值生成一次快照,供独立的持久摘要事件使用。宿主侧的值分离、执行数据的不可变处理与输出 schema 投影均采用迭代遍历,而不使用嵌套结构化克隆或递归冻结。`undefined`、非有限数、`-0`、稀疏数组、循环引用、函数和非普通对象都会使该调用在工具运行前被拒绝。普通成功分发返回 `ToolExecutionResult.value`;指定的 TypeScript 图片绑定使用最终图片附件构造程序 Image。Post-execute 阻止和结果投影仍具有最终决定权。普通绑定值不包含 Native 内容信封、元数据和内部错误信息。
|
||||
|
||||
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 将结构等价类型命名为 `PtcJsonValue`,从而无需依赖会话侧拥有的规范类型;生成的 SDK 和工具 API 则使用 `JsonValue`。这些值不会经过提示词截断、上下文 spill 或持久化。因此,程序可以完整筛选已经采集的搜索、工作流、任务、文件系统与 MCP 值,同时提供方和执行器的采集上限仍会实际生效。
|
||||
普通绑定参数与 JSON 返回值会在不可信 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 大小呈线性关系。
|
||||
保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。其他语言消费方还提供 `result?: JsonValue`。其渲染器先输出日志,字符串结果保持原文,其他 JSON 根值使用迭代式美化渲染器。总缩进长度上限为十个字符,更深子树保持紧凑格式,使遍历不受调用栈深度限制,且格式化大小与规范 JSON 大小呈线性关系。
|
||||
|
||||
`NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。
|
||||
|
||||
@@ -73,13 +73,13 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
### 持久化、元数据与 spill
|
||||
|
||||
嵌套分发在 `tool/ptc-dispatch` 上记录子调用完整渲染后的 `content`/`isError`,但不会持久化规范值。`tool/result` 继续只持久化渲染后的内容、错误和可选元数据。包含图片的成功最终内容序列还会包装成带来源归属的用户消息,并经外层结果延后;普通会话事件使该模型可见输入可以重建。[PTC mode note](2026-06-15-ptc.zh.md) 负责持久事件名称与历史标识保留规则;回放无法重建程序的规范中间值。
|
||||
嵌套分发在 `tool/ptc-dispatch` 上记录子调用完整渲染后的 `content`/`isError`,但不会持久化规范值。TypeScript 程序通过显式展示为外层 `tool/result.content` 选择图片。其他语言消费方将成功的含图片内容作为带来源归属的用户消息,延后到外层结果之后。普通 Session 事件使这些模型可见输入可以重建。[PTC mode note](2026-06-15-ptc.zh.md)负责持久事件名称与历史标识保留规则;回放无法重建程序的规范中间值。
|
||||
|
||||
不透明的 `exec.parent` token 用于标识嵌套调用。展示元数据以及通用或工具自有的 spill 投影都会跳过这些调用;它们的规范值永远不会进入上下文。Client 可以从原始分发事件派生[嵌套 terminal 卡片](../../../../packages/client/ui-tool/README.zh.md),无需元数据。外层 `run_code` 调用产生面向模型的结果,并且可能对 post-policy 处理后的最终展示执行 spill;`run_code` 有意既不声明结果展示器,也不声明展示元数据,因此 UI 适配器会通过通用的原始内容回退机制,使用持久化的 `tool/result.content` 补全该卡片。
|
||||
|
||||
## 测试
|
||||
|
||||
编译期测试与快照测试锁定了精确的 `ToolArgsMap`、`ToolOutputMap`、`ToolName`、schema 到 TypeScript 的覆盖范围、特殊名称,以及组装后的 PTC mode 图片转发。注册表与真实 worker 测试覆盖标量、数组、对象和 null 值;字符串原文渲染;缺席的 `undefined`;消费方声明、实际用于拒绝 Promise 的异常类,包括 `ToolCallError`;无效参数与完成值,包括伪装为内建原型的伪造原型;模型代码修改过的 JSON 边界全局对象、原型方法、构造函数槽位,以及继承而来的属性描述符字段;上述修改后的类型化绑定失败;不设上限的大型中间绑定值;嵌套输出落盘抑制;通用含图片上下文延后以及 post-execute 替换/阻止优先级;64 MiB 上限内外的精确计量;日志、值与诊断的组合计量;抛出的超大堆栈;有界失败的输出落盘;不可信对端伪造的流量;以及构建后包的执行。
|
||||
编译期测试与快照测试锁定了精确的 `ToolArgsMap`、`ToolOutputMap`、`ToolName`、schema 到 TypeScript 的覆盖范围、特殊名称,以及组装后的 PTC mode 图片投影。注册表与真实 worker 测试覆盖标量、数组、对象和 null 值;字符串原文渲染;缺席的 `undefined`;消费方声明、实际用于拒绝 Promise 的异常类,包括 `ToolCallError`;无效参数与完成值,包括伪装为内建原型的伪造原型;模型代码修改过的 JSON 边界全局对象、原型方法、构造函数槽位,以及继承而来的属性描述符字段;上述修改后的类型化绑定失败;不设上限的大型中间绑定值;嵌套输出落盘抑制;按消费方规则投影图片以及 post-execute 替换/阻止优先级;64 MiB 上限内外的精确计量;日志、值与诊断的组合计量;抛出的超大堆栈;有界失败的输出落盘;不可信对端伪造的流量;以及构建后包的执行。
|
||||
|
||||
无密钥的真实 worker 集成测试锁定了自然语言结果无法安全支持的两种句柄工作流。后台 bash 调用返回 job id,外层运行结束,之后的运行再根据该 id 轮询直至任务完成;其他用例分别证明,预先中止不会创建任务、发布后的调用取消会保留任务、前台执行仍与信号耦合,并且由 `job_kill` 负责取消。Cordis 程序会直接读取 active 或 pending 挂载的 id 和 `waitingFor` 字段,按该 id 卸载,并在不解析渲染文本的情况下确认挂载已移除。
|
||||
|
||||
@@ -93,9 +93,9 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
**静默检查格式化或截断过大的完成值:**不予采纳。把 JSON 值改成字符串既有损又违反类型。显式的 `output-limit` 失败让模型可以选择返回更小的结果,而保留的日志和诊断仍可使用普通的外层 spill 机制。
|
||||
|
||||
**要求每个丰富叶子工具检查 `exec.parent` 并自行延后。** 不予采用,因为这会把叶子工具与 PTC mode 内部机制耦合、重复策略处理,并遗漏未来丰富工具。分发桥接层负责从已经结算的最终结果通用转发。
|
||||
**要求每个丰富叶子工具检查 `exec.parent` 并自行延后。** 不予采用,因为这会把叶子工具与 PTC mode 内部机制耦合,并重复策略处理。分发桥接层负责按消费方规则,从已经结算的最终结果投影图片。
|
||||
|
||||
**把 Native 丰富内容暴露为每个绑定规范值的一部分。** 不予采用,因为规范值是无损 JSON 且由工具定义;附件块是具有持久生命周期语义的模型投影。保持值与投影分离,既能保留类型化程序,也不会从后续模型上下文中丢弃图片。
|
||||
**把 Native 丰富内容暴露为每个绑定规范值的一部分。** 不予采用,因为规范值是无损 JSON 且由工具定义;附件块是具有持久生命周期语义的模型投影。消费方拥有的程序 Image 绑定保留类型化工具值,并将图片选择交给程序。
|
||||
|
||||
## 后果
|
||||
|
||||
@@ -111,6 +111,6 @@ worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损
|
||||
- 中间值没有字节上限,可能因值的保留、扁平协议格式副本或结构化克隆开销而耗尽进程或 worker 内存。
|
||||
- 64 MiB 硬上限只适用于外层可变负载,不计固定的结果封装语法与展示空白;spill 无法恢复超出该上限后被拒绝的字节。
|
||||
- 提供方或执行器的采集上限可能在规范值到达 PTC mode 前就已丢弃部分源数据。
|
||||
- 不支持的 MCP 输出 schema 会回退为 `JsonValue`;已准入的 MCP 图片使用通用延后投影,而音频和嵌入资源载荷仍只提供诊断。
|
||||
- 不支持的 MCP 输出 schema 回退为 `JsonValue`;图片投影遵循上述消费方规则,音频和嵌入资源负载仍仅用于诊断。
|
||||
- 嵌套调用没有独立的面向模型的结果;Client 子调用卡片不会增加模型上下文。
|
||||
- PTC mode 失败只暴露 `ToolCallError` 的消息与工具名,不提供程序可用的错误代码联合。
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 12ab239ab0c58e31
|
||||
zh: c32874442ce66041
|
||||
/agent-note-explicit-worktree-creation/decision:
|
||||
en: 92782d5964d1a021
|
||||
zh: 37b385836e9ae2b9
|
||||
en: 571a2d4c5352170b
|
||||
zh: aeb12b849c5f8d31
|
||||
/agent-note-explicit-worktree-creation/alternatives-considered:
|
||||
en: 72d42e892a37b94c
|
||||
zh: 92a14a51c6a89c53
|
||||
|
||||
@@ -18,7 +18,7 @@ Git and directory creation use the mounted subprocess and sandbox providers with
|
||||
|
||||
Leaving uses the shared working-directory operation and retains the checkout and branch. Failed setup can retain partial artifacts and reports their location. The service does not own a branch merge policy or a task association database.
|
||||
|
||||
The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
|
||||
The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Inspection trusts `git status` alone, as peer agent products do: edits to skip-worktree or assume-unchanged files are discarded with the checkout, because sparse checkout sets skip-worktree on every file outside its cone and inspecting those bits would retain every sparse checkout. A checkout whose administrative directory holds submodule repositories is retained; a committed embedded repository is not inspected, and Git's refusal of that removal settles the attempt as failed. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Git 与目录创建使用挂载的子进程及沙箱提供方,不扩大调用
|
||||
|
||||
离开使用共享工作目录操作,保留检出目录与分支。初始化失败可能留下部分产物,并报告其位置。该服务不拥有分支合并策略或任务关联数据库。
|
||||
|
||||
服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
|
||||
服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。检查与同类 Agent 产品一样只依据 `git status`:skip-worktree 或 assume-unchanged 文件的改动随检出目录一起丢弃,因为 sparse checkout 会给稀疏范围之外的每个文件设置 skip-worktree,检查这些标记会保留每个稀疏检出目录。管理目录中含子模块仓库的检出目录会保留;已提交的内嵌仓库不在检查范围内,Git 拒绝这类删除,本次尝试以失败结束。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 344bcc7e9825bbc8
|
||||
zh: c1d0f4b54f5b3786
|
||||
/agent-note-change-request-panel-and-worktree-sessions/decision:
|
||||
en: 66bde24e7c601eb6
|
||||
zh: 5091591f3dc1ac85
|
||||
en: 4695a1e4f8aa7a25
|
||||
zh: e17be0e36ea3eaa3
|
||||
/agent-note-change-request-panel-and-worktree-sessions/deferred:
|
||||
en: 32ef8af85f4d2f66
|
||||
zh: b82b67f94346399e
|
||||
|
||||
@@ -28,7 +28,7 @@ The panel does not move a Session between existing worktrees. Removing a change
|
||||
|
||||
The panel also shows the changes behind a Session's work in a changes view, a resource tab type of this package. The Remote parses every diff on the Host into files and hunks, so the browser draws them without a patch parser, and bounds each read with `maxDiffBytes` and `maxUntrackedFiles`. Local changes come from `git diff` using the Session's permissions and execution world, in a scope the user picks: the branch against its fork point by default, or the uncommitted, unstaged, or staged changes; untracked files are read through the Session's filesystem and shown as new files. A change request's changes come from its code host at the head of the binding's latest status, through two provider reads the forge seam gained, `diff` and `fileText`. The Host keeps the patch it read last for each change request, keyed by the head commit and base branch and bounded by `maxCachedDiffBytes`, so reopening, refreshing, and navigating at the same head download nothing again; a host or provider that refuses an answer over its size limit reports the forge failure `too-large`, and the view then offers the change request's web page instead of a retry. Unchanged lines between hunks expand from the file's new side, which is the working tree, the index, or the head commit, and only while that text still matches the hunks. Each inspection also sizes the branch's changes for a local changes card, shown while no open change request carries the checked-out branch; its Create change request sends the Session a user message, so the Agent creates the change request with its own tools and the binding follows from `gh pr create` as for any other.
|
||||
|
||||
Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Review drafts and inline records belong to a browser tab occurrence, not to the Session log or a GitHub pending review. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records.
|
||||
Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Inline records of Agent references and published comments, and the review summary, belong to a browser tab occurrence, not to the Session log; a pull request comment kept for a later review goes to the code host's pending review, as [the pending review decision](2026-11-05-forge-pending-review-drafts.md) records. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records.
|
||||
|
||||
## Deferred
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都
|
||||
|
||||
面板还通过变更视图展示 Session 工作背后的变更;变更视图是本包的一个资源标签页类型。Remote 在宿主上把每个 diff 解析成文件与 hunk,因此浏览器无需补丁解析器即可绘制,每次读取都受 `maxDiffBytes` 与 `maxUntrackedFiles` 约束。本地变更来自使用 Session 权限与执行环境的 `git diff`,范围由用户选择:默认是分支相对于分叉点的变更,也可以是未提交、未暂存或已暂存的变更;未跟踪文件经 Session 的文件系统读取,显示为新文件。变更请求的变更来自代码托管平台,取自绑定最新状态中的 head,经 forge seam 新增的两个提供方读取操作 `diff` 与 `fileText` 获得。Host 为每个变更请求保留最近读到的补丁,按 head 提交与目标分支区分,总量受 `maxCachedDiffBytes` 约束,因此在同一 head 下重新打开、刷新与导航都不会再次下载;托管平台或提供方因结果超过其大小上限而拒绝时报告 forge 失败 `too-large`,视图随之提供变更请求的网页而不是重试。hunk 之间未变更的行从文件的新版本展开,即工作树、暂存区或 head 提交,并且只在该文本仍与 hunk 吻合时展开。每次检查还会为变更卡片统计分支的变更规模;没有打开中的变更请求以当前检出分支为源分支时才显示该卡片。卡片上的“创建变更请求”向 Session 发送一条用户消息,由 Agent 用自己的工具创建变更请求,绑定像其他变更请求一样来自 `gh pr create`。
|
||||
|
||||
评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。评审草稿与行内记录归浏览器页签实例所有,不进入 Session 日志,也不创建 GitHub 待提交评审。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。
|
||||
评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。Agent 引用与已发布评论的行内记录以及评审总结归浏览器页签实例所有,不进入 Session 日志;留待之后一起提交的 PR 评论写入代码托管平台的待提交评审,见[待提交评审决策](2026-11-05-forge-pending-review-drafts.zh.md)。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。
|
||||
|
||||
## Deferred
|
||||
|
||||
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: e736740546fb8219
|
||||
zh: 46a16a7a633716ec
|
||||
/agent-note-session-change-request-bindings/decision:
|
||||
en: 2bbd058f4edc8bb5
|
||||
zh: 5cc12bb0aa0864e2
|
||||
en: 9aa6d0c9c1177aeb
|
||||
zh: 0f0604176b02e82c
|
||||
/agent-note-session-change-request-bindings/alternatives-considered:
|
||||
en: 15fdaef4e432fc72
|
||||
zh: 8d36c859bd89f403
|
||||
en: 1e2239783738cec2
|
||||
zh: 5f248eee47de376e
|
||||
/agent-note-session-change-request-bindings/consequences:
|
||||
en: a2960e50ec52c9b6
|
||||
zh: fd23f4fe1137787d
|
||||
@@ -12,7 +12,7 @@ A Session that opens or updates pull requests leaves them only in its shell outp
|
||||
|
||||
The experimental forge capability seam has three roles. [`dsh-experimental-forge`](../../../../packages/experimental/forge/README.md) defines provider-neutral repository and change request references, a provider registry, and shared polling: watchers of one change request share one loop, each forge has one batched fetch in flight, and the cadence follows check, mergeability, and lifecycle state. [`dsh-experimental-forge-github`](../../../../packages/experimental/forge-github/README.md) is the first provider; it reads GitHub through the GitHub CLI on the host, so credentials stay in that tool's own store and never enter Session execution worlds. [`dsh-experimental-forge-session`](../../../../packages/experimental/forge-session/README.md) binds change requests to Sessions.
|
||||
|
||||
Bindings derive from the Session log instead of a separate store. A Session projection reads `bash` and `pwsh` calls: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results record the branches they updated. Those three commands act on one change request, so only the URL given as their first argument and the URL their output prints for that change request count; links in a description name other change requests. Caller actions and discovery results are `plugin:forge-session/binding` records. Because every input is a log event, fork and resume carry bindings without new persistence, and the projection rebuilds them from any checkpoint. The printed URL or ref line is the evidence, not the exit status: an existing pull request reported by a failing `gh pr create` still binds, and a partially rejected push still records the branches it updated.
|
||||
Bindings derive from the Session log instead of a separate store. A Session projection reads `bash` and `pwsh` calls, including calls a PTC program dispatches, whose `tool/ptc-dispatch` events log the arguments with the settled outcome: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results record the branches they updated. Those three commands act on one change request, so only the URL given as their first argument and the URL their output prints for that change request count; links in a description name other change requests. Caller actions and discovery results are `plugin:forge-session/binding` records. Because every input is a log event, fork and resume carry bindings without new persistence, and the projection rebuilds them from any checkpoint. The printed URL or ref line is the evidence, not the exit status: an existing pull request reported by a failing `gh pr create` still binds, and a partially rejected push still records the branches it updated.
|
||||
|
||||
After each push result, and when a caller such as the forge panel reports the branch a Session's checkout tracks, the service looks up open change requests for that branch through the provider and records the unbound ones. A dismissed binding stays hidden from discovery and returns only through `track`. Polled status is not logged; it is process-local state that exists while a watcher displays the Session. The projection's client view therefore carries bindings without status.
|
||||
|
||||
@@ -24,6 +24,8 @@ After each push result, and when a caller such as the forge panel reports the br
|
||||
|
||||
**Logging polled status in the Session.** Status changes independently of the conversation. Logging it would grow the log with every poll and expose stale snapshots to later readers.
|
||||
|
||||
**Recording PTC shell calls as `tool/call` and `tool/result` events, or observing the shell service.** Those events feed model history, so program sub-calls would re-enter model context; a shell-service hook would also see host lookups that no tool call made and would leave earlier PTC Sessions without bindings on replay. The dispatch events already log every sub-call outside model history.
|
||||
|
||||
**Running `gh` through the Session's subprocess provider.** Remote and sandboxed execution worlds would need GitHub credentials, and status would depend on the world a Session uses. The host CLI keeps one credential owner.
|
||||
|
||||
## Consequences
|
||||
|
||||
@@ -12,7 +12,7 @@ Status: implemented
|
||||
|
||||
实验性的 forge 能力 seam 由三个角色组成。[`dsh-experimental-forge`](../../../../packages/experimental/forge/README.zh.md) 定义提供方无关的仓库与变更请求引用、提供方注册表与共享轮询:同一变更请求的监听方共享一个循环,每个 forge 同时只有一次批量读取,轮询节奏随检查、可合并性与生命周期状态变化。[`dsh-experimental-forge-github`](../../../../packages/experimental/forge-github/README.zh.md) 是第一个提供方;它通过宿主上的 GitHub CLI 读取 GitHub,因此凭据保留在该工具自己的存储中,从不进入 Session 的执行环境。[`dsh-experimental-forge-session`](../../../../packages/experimental/forge-session/README.zh.md) 把变更请求绑定到 Session。
|
||||
|
||||
绑定从 Session 日志派生,而不是存放在单独的存储中。一个 Session 投影读取 `bash` 与 `pwsh` 调用:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果记录其更新的分支。这三个命令只操作一个变更请求,因此只计入作为第一个参数给出的 URL 和输出为该变更请求打印的 URL;描述正文里的链接指向的是其他变更请求。调用方操作与发现结果是 `plugin:forge-session/binding` 插件记录。由于所有输入都是日志事件,fork 与恢复无需新的持久化即可带上绑定,投影也能从任意检查点重建它们。证据是输出中的 URL 或 ref 行,而不是退出状态:失败的 `gh pr create` 报告的已有 pull request 仍会绑定,部分被拒绝的推送仍会记录它已更新的分支。
|
||||
绑定从 Session 日志派生,而不是存放在单独的存储中。一个 Session 投影读取 `bash` 与 `pwsh` 调用,包括 PTC 程序分派的调用,其 `tool/ptc-dispatch` 事件记录参数与结算结果:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果记录其更新的分支。这三个命令只操作一个变更请求,因此只计入作为第一个参数给出的 URL 和输出为该变更请求打印的 URL;描述正文里的链接指向的是其他变更请求。调用方操作与发现结果是 `plugin:forge-session/binding` 插件记录。由于所有输入都是日志事件,fork 与恢复无需新的持久化即可带上绑定,投影也能从任意检查点重建它们。证据是输出中的 URL 或 ref 行,而不是退出状态:失败的 `gh pr create` 报告的已有 pull request 仍会绑定,部分被拒绝的推送仍会记录它已更新的分支。
|
||||
|
||||
每次推送结果之后,以及 forge 面板等调用方报告 Session 检出所跟踪的分支时,服务通过提供方为该分支查找打开状态的变更请求,并记录尚未绑定的那些。被隐藏的绑定不会被发现逻辑恢复,只能通过 `track` 恢复。轮询到的状态不写入日志;它是进程内状态,仅在有监听方展示该 Session 时存在。因此投影的客户端视图只带绑定,不带状态。
|
||||
|
||||
@@ -24,6 +24,8 @@ Status: implemented
|
||||
|
||||
**把轮询状态写入 Session 日志。** 状态的变化独立于对话。写入日志会让日志随每次轮询增长,并把过期快照暴露给后续读取方。
|
||||
|
||||
**把 PTC 内的 shell 调用记录为 `tool/call` 与 `tool/result` 事件,或观察 shell 服务。** 这两种事件会进入模型历史,程序的子调用将重新进入模型上下文;shell 服务钩子还会看到并非由工具调用发起的宿主查询,而且重放早先的 PTC Session 时仍没有绑定。分派事件已经在模型历史之外记录了每个子调用。
|
||||
|
||||
**通过 Session 的子进程提供方运行 `gh`。** 远端与沙箱执行环境将需要 GitHub 凭据,状态也会取决于 Session 使用的执行环境。宿主 CLI 让凭据只有一个所有者。
|
||||
|
||||
## Consequences
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-05-forge-pending-review-drafts.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md
|
||||
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review:
|
||||
en: 25b4da2d12f15b82
|
||||
zh: 6d9fec68e8bb0baa
|
||||
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/problem:
|
||||
en: 2674866671bd0d4b
|
||||
zh: e60d41a24d20d7bf
|
||||
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/decision:
|
||||
en: 3df55965423b6d33
|
||||
zh: 2e8f0fbb4f7a311f
|
||||
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/alternatives-considered:
|
||||
en: ef67e05cb9442f05
|
||||
zh: d4433ddd090a9cec
|
||||
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/consequences:
|
||||
en: 198f6cf5a2bc2230
|
||||
zh: 92eb0a349356f100
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: Pull request comment drafts in the code host's pending review
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-05-forge-pending-review-drafts.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The [forge panel](2026-10-09-forge-panel.md) kept a pull request's comment drafts in a browser tab occurrence, published them as one review, and recorded what it published. Once the changes view shows the code host's review threads and lets the user reply to them, browser drafts leave four gaps. A reply cannot join a later review, because the drafts and the threads live in different places. A review the user started on the GitHub page, or in another browser, does not appear, and GitHub refuses a review submitted while the user has one. Drafts are lost with the tab and invisible on another device. And GitHub keeps one pending review per user and pull request, so two stores of one review would disagree.
|
||||
|
||||
## Decision
|
||||
|
||||
A pull request comment that the user keeps for a later review goes to the user's pending review on the code host through the provider's optional `writeReview`. The first such comment or reply starts the pending review at the head the user saw; later ones join it. The changes view reads the pending review with the threads, shows its comments as threads tagged Pending, and Submit review submits or discards that review with the summary and decision. Replies, resolving and unresolving, and editing and deleting the user's own comments use the same write, which re-checks the head and is never retried.
|
||||
|
||||
The browser keeps what the code host does not hold: the review summary and decision until submission, the records of Agent references and published comments, and the outgoing direct write whose outcome needs confirmation. Comments on local changes never had a host destination; they go to the main input as before. Comment drafts an earlier panel kept in the browser stay readable: they show beside their code as browser drafts, can move into the pending review, and keep Submit review disabled while a pending review exists; without one, Submit review publishes them as one review as before.
|
||||
|
||||
GitHub measurements on a private test repository decided three rules. While the user has a pending review, GitHub refuses a directly created review and a single comment (HTTP 422, "can only have one pending review per pull request"), so the view offers neither; a reply sent without the review's id still joins the review, so the view offers no reply at once and the provider refuses one. GitHub refuses Approve and Request changes on the user's own pull request, so the dialog offers only Comment there.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keeping drafts in the browser tab.** It needs no host write until submission, but replies cannot join the same review, a review started elsewhere blocks submission without explanation, and the drafts do not follow the user to another device.
|
||||
|
||||
**Keeping both stores.** Mirroring browser drafts into the pending review or the reverse gives one review two owners whose contents can diverge, and every edit would need reconciliation of two writes.
|
||||
|
||||
**Recording drafts in the Session log.** The log records what reaches the model; review drafts are host state the model never sees, and other Sessions on the same pull request would not see them.
|
||||
|
||||
**Retrying a write after an unknown outcome.** A lost response does not show whether GitHub applied the mutation. A submission of the pending review is kept as the write to reconcile, as a direct submission is, and blocks another submission until the user checks GitHub; a reply, resolution, or comment change reads the threads again and asks the user to check them before trying again.
|
||||
|
||||
## Consequences
|
||||
|
||||
A comment kept for later is visible on the GitHub page to its author before submission, and is lost only when the user discards the review. Each comment, reply, or thread change costs one GraphQL query for the head check and one mutation. Resolving a thread does not change the pull request's update time, so every write from the panel drops the panel's kept threads; another view of the same pull request shows the change at its next status or after `reviewRefreshMs`. A provider without `writeReview` reports no write permissions, so its threads stay read-only and its pull request comments are published at once or added to the input. Comment drafts from an earlier panel remain until the user moves, publishes, or deletes them, or closes their tab.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: PR 评论草稿保存在代码托管平台的待提交评审中
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-05-forge-pending-review-drafts.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
[forge 面板](2026-10-09-forge-panel.zh.md)原先把 PR 的评论草稿保存在浏览器页签实例中,作为一次评审发布,并记录已发布的内容。变更视图显示代码托管平台的评审讨论并允许用户回复之后,浏览器草稿留下四个缺口。回复无法加入之后的评审,因为草稿与讨论保存在不同的地方。用户在 GitHub 页面或另一个浏览器中开始的评审不会显示,而用户已有待提交评审时,GitHub 会拒绝直接提交的评审。草稿随页签丢失,在其他设备上也看不到。GitHub 每个用户在每个 PR 上只保留一个待提交评审,两处保存同一个评审会出现不一致。
|
||||
|
||||
## Decision
|
||||
|
||||
用户留待之后一起提交的 PR 评论,通过提供方的可选能力 `writeReview` 写入代码托管平台上该用户的待提交评审。第一条这样的评论或回复在用户看到的 head 上开始待提交评审,之后的评论或回复加入其中。变更视图随讨论一起读取待提交评审,把其中的评论显示为带“待提交”标签的讨论;“提交评审”带着总结和评审决定提交或丢弃这个评审。回复、解决与取消解决、编辑与删除用户自己的评论也使用同一写操作;写操作会重新检查 head,且从不重试。
|
||||
|
||||
浏览器只保存代码托管平台不保存的内容:提交前的评审总结与评审决定、Agent 引用与已发布评论的记录,以及结果有待确认的直接写入。本地变更上的评论本来就没有托管平台上的去处,仍像以前一样进入主输入框。早期面板保存在浏览器中的评论草稿仍可读取:它们作为浏览器草稿显示在对应代码旁,可以加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”像以前一样把它们作为一次评审发布。
|
||||
|
||||
在一个私有测试仓库上对 GitHub 的实测确定了三条规则。用户已有待提交评审时,GitHub 拒绝直接创建的评审和单条评论(HTTP 422,“每个 PR 只能有一个待提交评审”),因此视图两者都不提供;不带评审 id 发送的回复仍会加入该评审,因此视图不提供立即回复,提供方也拒绝这种回复。GitHub 拒绝用户批准或请求更改自己的 PR,因此在这种 PR 上,弹窗只提供“评论”。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**把草稿保存在浏览器页签中。** 提交之前不需要写入托管平台,但回复无法加入同一个评审,在别处开始的评审会无说明地阻止提交,草稿也无法随用户换到另一台设备。
|
||||
|
||||
**两处同时保存。** 把浏览器草稿同步到待提交评审,或反过来同步,会让一个评审有两个所有者,内容可能分歧,每次编辑都要核对两次写入。
|
||||
|
||||
**把草稿记录在 Session 日志中。** 日志记录的是到达模型的内容;评审草稿是模型永远看不到的托管平台状态,同一 PR 上的其他 Session 也看不到它们。
|
||||
|
||||
**结果不明时自动重试写操作。** 响应丢失并不能说明 GitHub 是否执行了 mutation。提交待提交评审时,与直接提交一样,这次提交会作为待核对的写入保留下来,在用户到 GitHub 核对之前阻止再次提交;回复、解决讨论或修改评论时,视图重新读取讨论,并请用户核对后再重试。
|
||||
|
||||
## Consequences
|
||||
|
||||
留待之后提交的评论,在提交前其作者就能在 GitHub 页面上看到,只有用户丢弃评审时才会丢失。每条评论、回复或讨论状态的修改,都消耗一次用于检查 head 的 GraphQL 查询和一个 mutation。解决讨论不会改变 PR 的更新时间,因此面板发出的每个写操作都会丢弃面板保留的讨论;同一 PR 的其他视图在收到下一次状态时,或在 `reviewRefreshMs` 之后显示这一变化。未实现 `writeReview` 的提供方不报告任何写入权限,因此它的讨论保持只读,它的 PR 评论只能立即发布或添加到输入框。早期面板留下的评论草稿会一直保留,直到用户把它们加入评审、发布、删除,或关闭所在页签。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-09-21-reject-silent-empty-catch.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md
|
||||
/agent-note-reject-silent-empty-catch-clauses:
|
||||
en: b058c52537202c50
|
||||
zh: f48d8847967a31a8
|
||||
/agent-note-reject-silent-empty-catch-clauses/problem:
|
||||
en: a89b84c7052329b4
|
||||
zh: 9c511a0b4ee3f1ef
|
||||
/agent-note-reject-silent-empty-catch-clauses/decision:
|
||||
en: 0392fb5d5cc3b387
|
||||
zh: c4219e43bded8ce6
|
||||
/agent-note-reject-silent-empty-catch-clauses/alternatives-considered:
|
||||
en: 65d05680072f8797
|
||||
zh: e160d37d8ece30ad
|
||||
/agent-note-reject-silent-empty-catch-clauses/consequences:
|
||||
en: 88a4796188c31922
|
||||
zh: bfa8efc7944ea12a
|
||||
@@ -0,0 +1,33 @@
|
||||
# Agent Note: Reject silent empty catch clauses
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-09-21-reject-silent-empty-catch.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
An empty `catch` discards every failure of its `try`, including defects the author did not expect. The root rule requires such a clause to name the error, state why discarding it is safe, and keep its `try` to one statement, so that the clause discards only the failure its author considered. Without a check, new clauses drifted from the rule, and existing clauses broke it across many unrelated package and test owners.
|
||||
|
||||
## Decision
|
||||
|
||||
The [checker](../../../../scripts/verify-empty-catch.ts), exposed as `pnpm run verify-empty-catch`, parses first-party JavaScript and TypeScript with the TypeScript syntax tree and reports an empty clause, one whose body holds no statement other than `;`, that is unnamed, unexplained, or wraps a multi-statement `try`. A bare `_` counts as unnamed; lint requires an unused binding to start with `_`, so a conforming name such as `_alreadyGone` states the expected failure. A clause body with any other statement is out of scope because syntax cannot show whether it handles the error. The checker establishes the form; review establishes that the name and the reason are true, using the guidance in [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#empty-catch-clauses).
|
||||
|
||||
Existing clauses have an exact baseline keyed by repository-relative path, a SHA-256 digest of the clause's syntax tokens together with its broken conditions, and occurrence count. Including the broken conditions makes turning a recorded one-statement `try` into a wider one, or deleting a recorded reason, a new finding, while edits inside the `try` that keep its conditions keep the clause's identity. The baseline follows the [unknown-cast inventory](2026-09-19-no-unknown-casts.md), and both checkers share [the inventory module](../../../../scripts/baseline-inventory.ts): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new findings exist, and no command adds an allowance. Unlike the unknown-cast inventory, which requires resolving an assertion before moving it to an unlisted file, moving a file that holds recorded clauses renames its baseline key in the same change, because narrowing a recorded `try` belongs to its owner rather than to the change that moves the file.
|
||||
|
||||
The checker runs in the `hygiene` and `check-all` profiles and the CI static and primary modes of [the gate runner](../../../../scripts/run-gates.ts). Empty Promise rejection handlers such as `.catch(() => {})` are outside this rule and tracked separately in issue #8033.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Fix every existing clause before enforcing the rule.** Rejected because narrowing a multi-statement `try` changes which failures the clause discards, which only each owner can judge. The baseline lets enforcement start while the existing clauses remain recorded findings for their owners to fix.
|
||||
|
||||
**Fingerprint the whole `try` statement.** Rejected because every edit inside a recorded `try` would become a new finding and force its owner to fix the clause during unrelated work. Fingerprinting the clause with its broken conditions rejects a new broken condition on a recorded clause without tying its identity to the statements inside the `try`; a `try` that is already wide can gain statements without a new finding.
|
||||
|
||||
**A command that records clauses from a named revision.** Rejected because a local command cannot prove that the revision is the target branch: naming the current branch would record the branch's own clauses. Once the target branch carries the checker, merging it brings that branch's baseline along, so no command is needed.
|
||||
|
||||
**Search text for `catch {}`.** Rejected because comments, strings, whitespace, and binding patterns defeat a text pattern, and the rule's conditions depend on the syntax tree.
|
||||
|
||||
## Consequences
|
||||
|
||||
New and changed empty clauses must conform, and fixing a recorded clause requires pruning its baseline entry. A partial fix, such as adding a name while the `try` stays wide, changes the clause's identity and therefore fails; the owner fixes the clause completely before pruning. The baseline key carries no line number, so a recorded clause can move within its file; identical clauses in one file share one fingerprint whose count covers each of them.
|
||||
|
||||
Passing the checker establishes the form of every unrecorded empty clause. It does not establish that a reason is true, that a non-empty handler handles its error, or that a `try` holding one block or compound statement discards only one operation's failures.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Agent Note: 拒绝静默的空 catch 子句
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-09-21-reject-silent-empty-catch.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
空 `catch` 会丢弃其 `try` 的所有失败,包括作者未预料到的缺陷。根规则要求此类子句命名错误、说明丢弃该错误为何安全,并将其 `try` 限制为一条语句,使子句只丢弃作者考虑过的失败。没有检查时,新增子句逐渐偏离该规则,而违反规则的现有子句分布在许多互不相关的包和测试所属模块中。
|
||||
|
||||
## 决策
|
||||
|
||||
[检查器](../../../../scripts/verify-empty-catch.ts)通过 `pnpm run verify-empty-catch` 运行,使用 TypeScript 语法树解析第一方 JavaScript 和 TypeScript,并报告未命名、未说明原因或包裹多语句 `try` 的空子句;空子句指主体中除 `;` 外不含任何语句的子句。单独的 `_` 视为未命名;lint 要求未使用的绑定以 `_` 开头,因此 `_alreadyGone` 这类符合要求的名称可以说明预期的失败。主体含有其他语句的子句不属于此规则的范围,因为语法无法表明它是否处理了错误。检查器确认形式;审查依据 [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#empty-catch-clauses) 中的指引确认名称和原因属实。
|
||||
|
||||
现有子句使用精确基线记录,键由仓库相对路径、子句语法 token 连同其违反条件的 SHA-256 摘要及出现次数组成。摘要包含违反条件,因此把已记录的单语句 `try` 扩大为多语句 `try`,或删除已记录的原因,都会产生新的检查发现;而在 `try` 内部进行不改变其违反条件的修改,不改变子句的标识。基线沿用 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的做法,两个检查器共用[清单模块](../../../../scripts/baseline-inventory.ts):基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新发现时拒绝写入,且没有任何命令可以添加放行。unknown 类型断言清单要求先解决断言,才能将其移至未登记的文件;与之不同,移动包含已记录子句的文件时,须在同一变更中重命名其基线键,因为收窄已记录的 `try` 由其所属模块负责,而不属于移动文件的变更。
|
||||
|
||||
检查器在[门禁运行器](../../../../scripts/run-gates.ts)的 `hygiene` 和 `check-all` 配置以及 CI 静态模式和主模式中运行。`.catch(() => {})` 等空的 Promise 拒绝处理函数不属于此规则,另由 issue #8033 跟踪。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**先修复所有现有子句,再执行规则。** 不采用,因为收窄多语句 `try` 会改变子句丢弃哪些失败,只有各所属模块才能判断。基线使规则可以立即开始执行,同时现有子句仍作为已记录的检查发现,由其所属模块修复。
|
||||
|
||||
**对整个 `try` 语句计算指纹。** 不采用,因为已记录 `try` 内部的每次修改都会产生新的检查发现,迫使所属模块在无关工作中修复该子句。对子句连同其违反条件计算指纹,可以拒绝已记录子句上新增的违反条件,同时不让子句的标识依赖 `try` 内部的语句;已经过宽的 `try` 可以增加语句而不产生新的检查发现。
|
||||
|
||||
**提供从指定修订版本记录子句的命令。** 不采用,因为本地命令无法证明该修订版本就是目标分支:指定当前分支会记录该分支自身的子句。目标分支包含检查器后,合并目标分支会一并带入其基线,因此不需要这样的命令。
|
||||
|
||||
**在文本中搜索 `catch {}`。** 不采用,因为注释、字符串、空白和绑定模式都会使文本模式失效,而且规则的条件依赖语法树。
|
||||
|
||||
## 影响
|
||||
|
||||
新增和修改的空子句必须符合规则,修复已记录的子句时须清理其基线条目。部分修复,例如添加名称但 `try` 仍然过宽,会改变子句的标识,因此检查失败;所属模块须先完整修复子句,再清理基线条目。基线键不含行号,因此已记录的子句可以在所在文件内移动;同一文件中相同的子句共用一个指纹,其计数涵盖其中每一个子句。
|
||||
|
||||
通过检查器说明每个未记录的空子句都符合规定形式。它不证明原因属实,不证明非空处理代码处理了其错误,也不证明包含一个代码块或复合语句的 `try` 只丢弃一个操作的失败。
|
||||
+22
-22
@@ -6,38 +6,38 @@
|
||||
en: fe57a78907eab083
|
||||
zh: 4ac96eeb365ac012
|
||||
/agent-note-event-triggered-automation-tasks/problem:
|
||||
en: 491a791a201d0b2c
|
||||
zh: 5a98f693ac4b5e77
|
||||
en: d447fec320c63e96
|
||||
zh: 01e026939933c10a
|
||||
/agent-note-event-triggered-automation-tasks/proposal:
|
||||
en: 7906d9f791e0ba02
|
||||
zh: 3a083d451344f072
|
||||
en: 4cf9612456ff71c8
|
||||
zh: 4e5c1113e034425b
|
||||
/agent-note-event-triggered-automation-tasks/proposal/layers:
|
||||
en: 8bf2fc8ccb162c59
|
||||
zh: e993b9ae72f8d9a2
|
||||
en: 9782ed5704aaf99a
|
||||
zh: b0759dac7c55afde
|
||||
/agent-note-event-triggered-automation-tasks/proposal/sessions:
|
||||
en: 7ec83684c8c19e31
|
||||
zh: 27df2725836e5f7b
|
||||
en: 6854e9fce47f0f90
|
||||
zh: f81ed1dff88902df
|
||||
/agent-note-event-triggered-automation-tasks/proposal/configuration:
|
||||
en: 21be7e27081aff54
|
||||
zh: 7973f7f0d064db35
|
||||
/agent-note-event-triggered-automation-tasks/proposal/mechanisms:
|
||||
en: 2403ec84b12279ec
|
||||
zh: 7e245af54dcf4a1a
|
||||
en: e5cc1e6c1065e33d
|
||||
zh: e1c1e20ee0873ad3
|
||||
/agent-note-event-triggered-automation-tasks/proposal/product-scope:
|
||||
en: c003c908f407ccb2
|
||||
zh: 6113569a44d52202
|
||||
en: 66a513c9dd8ec459
|
||||
zh: 25be2ee31dc7ba2a
|
||||
/agent-note-event-triggered-automation-tasks/proposal/event-triggers-as-infrastructure:
|
||||
en: 4c62e16718896e9b
|
||||
zh: 9c61ea9b6e1f4f22
|
||||
en: b4d70a3dd67ac4f8
|
||||
zh: ff3c85caf63930f5
|
||||
/agent-note-event-triggered-automation-tasks/proposal/delivery-order:
|
||||
en: 79cf498bf3566051
|
||||
zh: 4537f1bd3df527b4
|
||||
en: 8b181877cc83a7c2
|
||||
zh: e8e7695c832a2bc5
|
||||
/agent-note-event-triggered-automation-tasks/alternatives-considered:
|
||||
en: 21df079f7d7c3f4d
|
||||
zh: 67f4ab221aacf2cf
|
||||
en: c8deb1f69853f19b
|
||||
zh: 0ac27b2d59398d53
|
||||
/agent-note-event-triggered-automation-tasks/acceptance-criteria:
|
||||
en: 504feb2cc59f4457
|
||||
zh: c78cd50f2f336562
|
||||
en: 175b07c090098482
|
||||
zh: f17779e363f8b899
|
||||
/agent-note-event-triggered-automation-tasks/risks:
|
||||
en: 35edb8d5b6a1cfa4
|
||||
zh: cb8dbc339c6055be
|
||||
en: 8e1baba10ef46925
|
||||
zh: b38ab076fa053de4
|
||||
@@ -11,11 +11,11 @@ Automation tasks run only on time rules today. The Host stores each rule, and ev
|
||||
Reacting to changes brings two problems that time rules do not have.
|
||||
|
||||
- **Cost and noise.** Most observations of a source contain nothing worth a model turn. If every observation reaches the model and silence depends on the model replying with a marker, each poll costs a full turn, and a model that holds a messaging tool reports "nothing new" anyway.
|
||||
- **Untrusted input.** Event content is written by other people: comments, reviews, messages. A turn started by that content must not edit, push, or send anything before the user has seen it.
|
||||
- **Untrusted input.** Event content is written by other people: comments, reviews, messages. A turn started by that content runs with the permissions of the Session it reaches, so the content must reach the model apart from the user's instruction, and the Session's sandbox and approval settings must still apply.
|
||||
|
||||
## Proposal
|
||||
|
||||
An automation task becomes an instruction, a source with parameters, and a Session mode. Time is one source among several, so a scheduled task is an automation task whose source is time. Each observation passes three layers, and only the last one calls a model: a source event passes the trigger's filter and becomes a candidate, the candidate is delivered to a Session where the model judges it, and only a notify call produces a notice for the user. This partially supersedes the two notes linked above: tasks stop being bound to their original Session, and task records stop meaning inbox delivery only.
|
||||
An automation task becomes an instruction, a source with parameters, and a Session mode. Time is one source among several, so a scheduled task is an automation task whose source is time. Each observation passes three layers, and only the last one calls a model: a source event passes the trigger's filter and becomes a candidate, and the candidate is delivered to the task's target Session, where the model runs the instruction against it. Every source takes the same path after the trigger. This partially supersedes the two notes linked above: tasks stop being bound to their original Session, and task records stop meaning inbox delivery only.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -23,28 +23,18 @@ flowchart TD
|
||||
Prov["Source providers: plugins, code<br/>time, GitHub; later mail, IM, memory"]
|
||||
Trig["Event trigger: shared code, state per task<br/>compare with stored state, match parameters, merge"]
|
||||
Rec[("Run records")]
|
||||
Src{"Source"}
|
||||
Exec["Run the instruction in the target Session<br/>with its permissions"]
|
||||
RO["Read-only turn in the task's own Session<br/>the model judges the candidate"]
|
||||
Note["Notice: action card, unread mark,<br/>system notification"]
|
||||
Quiet["No notice"]
|
||||
Acc["User accepts: the action runs in the Session<br/>that created the task, with its permissions"]
|
||||
Task --> Trig
|
||||
Prov -- "source events" --> Trig
|
||||
Trig -- "each change or failure" --> Rec
|
||||
Trig -- candidate --> Src
|
||||
Src -- time --> Exec
|
||||
Src -- "other sources" --> RO
|
||||
RO -- notify --> Note
|
||||
RO -- "no notify call" --> Quiet
|
||||
Note --> Acc
|
||||
Trig -- candidate --> Exec
|
||||
```
|
||||
|
||||
| Layer | Decides | Model call | Output |
|
||||
|---|---|---|---|
|
||||
| Source provider | What changed in the source | No | Events |
|
||||
| Event trigger | Whether the change matters to this task | No | A run record; a candidate or nothing |
|
||||
| Agent | Whether the user needs to act, and what to propose | Only for delivered candidates | A notice through notify, or nothing |
|
||||
| Agent | What the instruction requires for this candidate | Only for delivered candidates | The turn's work and reply in the target Session |
|
||||
|
||||
### Layers
|
||||
|
||||
@@ -52,14 +42,11 @@ flowchart TD
|
||||
|
||||
**The event trigger** is shared code, registered per source kind and version; each task holds only its parameters and the source state it last observed. For each observation it compares the new state with the stored one, and an observation without a change only updates the last-checked time. A check that turns from passing to failing is a change, a check that stays failing is not, and a pass followed by a new failure is a change again. For a change, the trigger matches the task's conditions, which are parameter fields such as conclusion is failure, author is the user, or commenter is not a bot; merges changes to the same subject inside the provider's merge window, so one push that fails three checks becomes one event; stores the new state with the task; and either delivers a candidate to the Session or drops the change. Each change and each failure writes a run record, listed in the task's Records tab next to today's delivery records: candidate delivered, filtered with its reason, or failed. Consecutive failures with the same cause share one record with a count. Delivery ends the trigger's work: it does not wait for the turn or read a receipt. One queue per task orders its evaluations.
|
||||
|
||||
**The agent** receives the candidate as a message in the target Session, together with the task's instruction in the user's words. What the turn may do depends on the source.
|
||||
|
||||
- **Time**: the turn runs the instruction with the Session's permissions, and its reply is the result, as scheduled tasks behave today.
|
||||
- **Other sources**: the turn gets the read-only tool set described under Mechanisms. It can read files and the source's state, such as check logs and pull request diffs, but has no tool that edits, pushes, or sends. One new tool, **notify** (`automation_notify`), takes a title, a summary, and a proposed action and produces a notice: an [action card](../../../../packages/experimental/action-cards/README.md) with the proposed action in the Session, the Session's unread mark, and a desktop system notification. The model decides whether to call it. A turn without notify produces no notice; there is no end tool, and nothing checks how the turn ended. When the user accepts the card, the Host sends a follow-up to the Session that handles the task, as described under Sessions; the follow-up names the task and the event and quotes the proposed action as the automation's proposal, not as the user's words, and that turn runs with that Session's permissions.
|
||||
**The agent** receives the candidate as a message in the target Session, together with the task's instruction in the user's words. The turn runs the instruction with that Session's tools and permissions, and its reply is the result, as scheduled tasks behave today. The source decides only what the candidate contains, not how the turn runs. The message quotes the event's subject, summary, detail, and links as event data from the source, not as the user's words. No step waits for the user to confirm before the turn acts; an approval the turn itself requests waits for the user as in any turn. The turn needs no automation-specific tool.
|
||||
|
||||
### Sessions
|
||||
|
||||
A task delivers to its target Session in one of three modes: a specified Session, a new Session per trigger, or a new Session on the first trigger that later triggers reuse. Time tasks keep today's target, the Session they were created in. Event tasks separate judging from handling. The read-only turn runs in the task's own Session, created on the first trigger and reused afterwards, because it needs the instruction, the event, and the task's earlier decisions rather than the long history of the conversation the task came from. When the model creates a task in a conversation, it writes the facts the judgment needs into the instruction, such as which check is known to be flaky. When the user accepts a card, the proposed action goes to the Session the task was created in, where the code and its history are. The automation page's New action already creates tasks in a new Session, which then handles them; a task enabled from an official template, which a later step adds, continues in its own Session. The user can change the mode on the task.
|
||||
A task delivers to its target Session in one of three modes: a specified Session, a new Session per trigger, or a new Session on the first trigger that later triggers reuse. A task created in a conversation defaults to a specified Session, the one it was created in, whatever its source; this keeps today's target for scheduled tasks, and the code and its history are there. The model, when the user asks for it, or the user on the task can choose a new-Session mode for a task whose candidates need no history, so its turns do not add to a long conversation; the model then writes the facts the work needs into the instruction, such as which check is known to be flaky. The automation page's New action already creates tasks in a new Session, which then handles them; a task enabled from an official template, which a later step adds, continues in its own Session. The user can change the mode on the task.
|
||||
|
||||
No task runs while the Host is stopped. On restart, each task compares the current source state with its stored state once and does not replay intermediate changes. Time keeps today's rule: a recurring task runs its latest missed occurrence once.
|
||||
|
||||
@@ -69,10 +56,8 @@ Configuration has two layers. Provider code decides what can be observed and how
|
||||
|
||||
### Mechanisms
|
||||
|
||||
- **Event-turn tool set.** Sandbox read-only mode limits only the filesystem, so it cannot stop a push or an outbound request. An event turn is offered a fixed tool set instead of the Session's: file reads and searches, the source provider's read operations, and `automation_notify`. Shell, file writes, web fetch, and MCP tools are absent. The tool set is recorded in the Session log, and a user message queued during the turn starts a normal turn after it ends.
|
||||
- **Notify card.** The automation package registers an action-card kind, and `automation_notify` creates its card through the action-card service; the tool exists only in event turns, so no skill load precedes it. Accepting runs the kind's handler, which queues the follow-up through the Host, so the handling Session need not be open. A newer card replaces an unanswered older one in the same Session, as the service does today; the older card is in that Session's history, so the newer turn sees it and carries over what is still open. A refused card returns an error to the turn.
|
||||
- **Unread mark.** The client derives the unread mark from turn completion. A task's own Session is marked as an automation Session, and for such a Session the client shows the mark only for notices, so a turn without notify leaves no mark.
|
||||
- **Logging.** The delivered candidate, the turn's tool set, and the notify call are Session events, so replay rebuilds the turn; the TypeScript and Python SDK expected outputs and a recorded-session snapshot cover them.
|
||||
- **Delivery.** The Host queues the candidate as a follow-up message through the same path scheduled tasks use today, so the target Session need not be open, and a turn already running there finishes first.
|
||||
- **Logging.** The delivered candidate is a Session event that keeps the event data apart from the instruction, so replay rebuilds the turn's input; the TypeScript and Python SDK expected outputs and a recorded-session snapshot cover it.
|
||||
- **Storage.** Source, parameters, Session mode, trigger state, and run records extend the Host task domain in a new record version with an adjacent migration. A version-1 task reads as a time task, is not rewritten until it changes, and gets no invented records. Run records have their own count and age bounds, separate from delivery records.
|
||||
- **Provider configuration.** Polling intervals and request budgets are validated Config fields of each provider in cordis.yml.
|
||||
|
||||
@@ -82,47 +67,39 @@ Configuration has two layers. Provider code decides what can be observed and how
|
||||
- The task list adds a source-type filter next to the status filter.
|
||||
- Task details add the source with its parameters, read-only, and the Session mode, editable.
|
||||
- A task's Records tab also lists filtered and failed evaluations.
|
||||
- Notifications reuse the Session unread mark and action cards; the desktop app adds a system notification.
|
||||
- A turn started by an event shows up like any other turn in its Session; no new notification surface is added.
|
||||
|
||||
### Event triggers as infrastructure
|
||||
|
||||
The trigger layer is shared infrastructure for DSH, not a feature of the automation page. A feature that watches something and hands changes to an agent becomes a task on this layer instead of building its own polling, state, records, and notifications.
|
||||
The trigger layer is shared infrastructure for DSH, not a feature of the automation page. A feature that watches something and hands changes to an agent becomes a task on this layer instead of building its own polling, state, and records.
|
||||
|
||||
- **DSH's own state as sources**: a Session turn ending in an error, a background job settling, and, once memory lands, a memory consolidation pass finishing or memory entries changing.
|
||||
- **Features on those sources**: plugin recommendations, where a workflow the user repeats by hand shows up after consolidation and the agent proposes a plugin on an action card, and task recommendations, where a review of the day's Sessions proposes follow-up work. Each is a template task with a DSH source, an instruction, and the same notify step. The plugin recommendations package, which proposes cards from conversation turns today, can move onto such a source once consolidation lands.
|
||||
- **What every consumer keeps**: change detection and condition matching in code, run records, Session modes, read-only event turns, and notify as the only way a task reaches the user.
|
||||
- **Features on those sources**: plugin recommendations, where a workflow the user repeats by hand shows up after consolidation and the agent proposes a plugin, and task recommendations, where a review of the day's Sessions proposes follow-up work. Each is a template task with a DSH source and an instruction. The plugin recommendations package, which proposes cards from conversation turns today, can move onto such a source once consolidation lands.
|
||||
- **What every consumer keeps**: change detection and condition matching in code, run records, Session modes, and one delivery path for every source.
|
||||
|
||||
### Delivery order
|
||||
|
||||
1. Task–Session decoupling with the three Session modes.
|
||||
2. The trigger layer with time as its first provider and the task-domain migration; existing scheduled tasks behave as before.
|
||||
3. The GitHub provider for pull request checks, reviews, and comments; the event-turn tool set and `automation_notify`; action cards leave experimental status or ship with the automation bundle.
|
||||
3. The GitHub provider for pull request checks, reviews, and comments.
|
||||
4. Mail and IM providers and official templates, then DSH's own sources.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Judge every observation in a resident Session.** The model reads each poll and replies with a silence marker when nothing changed. It lost because each observation costs a full turn over the Session's context, polls spaced beyond the prefix cache lifetime read that context uncached, and silence depends on the model following an instruction while it holds a messaging tool. Here code drops unchanged and unmatched observations, and only a notify call reaches the user.
|
||||
**Judge every observation in a resident Session.** The model reads each poll and replies with a silence marker when nothing changed. It lost because each observation costs a full turn over the Session's context, polls spaced beyond the prefix cache lifetime read that context uncached, and silence depends on the model following an instruction while it holds a messaging tool. Here code drops unchanged and unmatched observations, so only matched changes start a turn.
|
||||
|
||||
**Judge in the Session that created the task.** That conversation already holds the code and its history, so the instruction would need no extra facts. It lost because most candidates produce no notice, and each of them would add a turn over the conversation's whole context, read uncached once the prefix cache has expired, and queue behind or interrupt the user's own work there. Only accepted work goes to that Session.
|
||||
|
||||
**Let the agent choose the Session for each event.** The choice could differ from one event to the next, so the user could not predict where a notification appears, and deciding whether the history is needed requires reading it first.
|
||||
**Let the agent choose the Session for each event.** The choice could differ from one event to the next, so the user could not predict where the work appears, and deciding whether the history is needed requires reading it first.
|
||||
|
||||
**Condition scripts per task.** A task would carry a script that fetches and decides. It lost because the script runs with the user's credentials without the review a plugin installation gets, and each task would carry its own fetch logic instead of sharing a provider.
|
||||
|
||||
**Notify from code when code can decide.** A failed check could notify without a model. It lost because the notification would carry only the raw status. With one path, the agent reads the logs first and the notification states the cause; change-only delivery keeps these turns rare.
|
||||
|
||||
**One model call outside any Session.** A single call per event costs less and leaves no Session record. It lost because the call cannot read files or logs before deciding, and acting on its result needs a Session anyway.
|
||||
|
||||
**Event turns with the Session's permissions.** Acting directly would save one click. It lost because event content comes from other people, and a read-only turn keeps that text from driving edits, pushes, or messages before the user accepts.
|
||||
**Read-only judging turns with a notify tool and user acceptance.** Non-time sources would get a read-only turn in the task's own Session; an `automation_notify` tool would raise an action card, an unread mark, and a system notification; and the proposed action would run only after the user accepted the card. It lost because work that waits for the user to confirm each event does not fit how automations are used, such as fixing a failed check without anyone watching, and a dedicated notify tool with its card kind and unread rules would be one more model-facing interface that every later source and delivery change must keep compatible.
|
||||
|
||||
**A read-only sandbox for event turns.** It lost because sandbox read-only mode limits only the filesystem, and a turn in it can still push or send requests.
|
||||
|
||||
**An end tool and a check on how the turn ended.** A second tool would record why a turn produced no notice, and the trigger would wait for that outcome. It lost because nothing acts on that reason: delivery ends the trigger's work, and a turn without notify is already silent.
|
||||
**Branch delivery by source.** Time would run the instruction with the Session's permissions while other sources take a separate path. It lost because the source says what changed, not what work the instruction asks for, and two paths would double the turn setup, logging, and tests that every source shares.
|
||||
|
||||
**Parameter forms on the automation page.** Each provider would need its own form, validation, and display. Parameters written by the model and shown read-only cover creation and change through conversation, and the provider schema keeps a generated form possible later.
|
||||
|
||||
**A separate notification entry.** An inbox page or tab would separate the notification from the Session that holds its context. The unread mark and the system notification lead to that Session, and the automation page keeps the records.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Existing scheduled tasks behave the same after time becomes a provider: the same due times, the same catch-up rule, and the same delivery into the Session.
|
||||
@@ -131,23 +108,19 @@ The trigger layer is shared infrastructure for DSH, not a feature of the automat
|
||||
- One push that fails three checks produces one candidate.
|
||||
- An observation without a change writes no record and starts no turn; a change that fails the conditions writes a filtered record and starts no turn; consecutive failures with the same cause write one record with a count.
|
||||
- A run record ends at delivery: it records the candidate, not what the turn did.
|
||||
- An event turn is offered no shell, file-write, web-fetch, or MCP tool, and its tool set appears in the Session log; after the user accepts its card, the next turn runs with the Session's permissions.
|
||||
- A notify call produces the card, the unread mark, and the desktop system notification together.
|
||||
- An event turn without a notify call leaves no unread mark and sends no system notification.
|
||||
- An event task's read-only turns run in the task's own Session, and accepting its card sends the proposed action to the Session the task was created in.
|
||||
- A delivered candidate starts a turn in the target Session with that Session's tools and permissions, whatever the source, without waiting for user confirmation.
|
||||
- The candidate message presents the event content as event data, separate from the instruction.
|
||||
- A task created in a conversation delivers to that Session by default, whatever its source.
|
||||
- Each Session mode delivers as defined: a specified Session receives every trigger, a new Session opens per trigger, or one Session opens on the first trigger and is reused.
|
||||
- Replaying the Session log rebuilds an event turn's candidate, tool set, and notify call.
|
||||
- Replaying the Session log rebuilds an event turn's candidate and instruction.
|
||||
- After a restart, a task compares the current source state with its stored state once and does not replay intermediate changes.
|
||||
- The task list filters by source type, task details show source parameters read-only, and the Session mode can be changed.
|
||||
|
||||
## Risks
|
||||
|
||||
- The read-only turn sees the instruction, the event, and the task's earlier decisions, not the conversation the task came from. Facts the judgment needs from that conversation must be written into the instruction when the task is created; a user who switches the task to its original Session gets the history back at the cost of reading the long context on each delivery.
|
||||
- A notification appears in the task's own Session, not in the conversation that created the task; accepting its card moves the work to that conversation.
|
||||
- The agent may notify too often or stay silent when it should not. Accepted and dismissed cards show over-notification, but a missed notice leaves no trace in the run records, which end at delivery.
|
||||
- Event content written by other people reaches a turn that runs with the Session's permissions. Marking it as event data does not stop a model from following text inside it; the Session's sandbox and approval settings and the task's conditions, such as commenter is not a bot, bound what such a turn can do.
|
||||
- A task delivered to the Session it was created in adds a turn over that conversation's whole context on each candidate, read uncached once the prefix cache has expired, and queues behind the user's own work there; a new-Session mode avoids this but loses the history unless the instruction carries the needed facts.
|
||||
- The run records end at delivery, so what a turn did is visible only in its Session. A task delivered to a new Session reports only there, and the user sees its result only after opening that Session.
|
||||
- Source parameters cannot be edited by hand; every change goes through the model.
|
||||
- A fix on an event waits for the user to accept the card instead of running unattended.
|
||||
- A source without a provider plugin cannot be watched.
|
||||
- Tasks run only while the Host runs: nothing runs while the app is closed or the machine sleeps.
|
||||
- Event tasks depend on action cards, which are experimental and mounted only by the Personalized recommendations bundle today.
|
||||
- The read-only tool set limits judgment to what files and the provider's read operations show; for a source whose provider offers no read operations, the agent judges from the event alone.
|
||||
@@ -11,11 +11,11 @@ Status: proposed
|
||||
响应变化会带来两个时间规则没有的问题。
|
||||
|
||||
- **成本和噪音。** 对来源的大多数观察里,没有值得花一个模型轮次处理的内容。如果每次观察都交给模型,并依靠模型回复一个标记来保持安静,每次轮询都要花一个完整轮次;手里有发消息工具的模型仍然会报告“没有新情况”。
|
||||
- **不可信的输入。** 事件内容由其他人写成:评论、评审、消息。由这类内容启动的轮次,在用户看到之前不能修改、推送或发送任何东西。
|
||||
- **不可信的输入。** 事件内容由其他人写成:评论、评审、消息。由这类内容启动的轮次按其所在会话的权限运行,因此这类内容必须与用户的指令分开交给模型,会话的沙箱和审批设置也必须照常生效。
|
||||
|
||||
## 提案
|
||||
|
||||
自动化任务改为由指令、带参数的来源和会话模式组成。时间是多种来源中的一种,因此定时任务就是来源为时间的自动化任务。每次观察依次经过三层,只有最后一层调用模型:来源事件经过触发器过滤成为候选事件(candidate),候选事件投递到会话,由模型在会话中判断,只有调用通知工具才会为用户产生一条通知(notice)。本提案部分取代上面链接的两篇笔记:任务不再绑定原会话,任务记录也不再只表示收件箱投递。
|
||||
自动化任务改为由指令、带参数的来源和会话模式组成。时间是多种来源中的一种,因此定时任务就是来源为时间的自动化任务。每次观察依次经过三层,只有最后一层调用模型:来源事件经过触发器过滤成为候选事件(candidate),候选事件投递到任务的目标会话,由模型在该会话中针对它执行指令。所有来源在触发器之后走同一条路径。本提案部分取代上面链接的两篇笔记:任务不再绑定原会话,任务记录也不再只表示收件箱投递。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -23,28 +23,18 @@ flowchart TD
|
||||
Prov["Source providers: plugins, code<br/>time, GitHub; later mail, IM, memory"]
|
||||
Trig["Event trigger: shared code, state per task<br/>compare with stored state, match parameters, merge"]
|
||||
Rec[("Run records")]
|
||||
Src{"Source"}
|
||||
Exec["Run the instruction in the target Session<br/>with its permissions"]
|
||||
RO["Read-only turn in the task's own Session<br/>the model judges the candidate"]
|
||||
Note["Notice: action card, unread mark,<br/>system notification"]
|
||||
Quiet["No notice"]
|
||||
Acc["User accepts: the action runs in the Session<br/>that created the task, with its permissions"]
|
||||
Task --> Trig
|
||||
Prov -- "source events" --> Trig
|
||||
Trig -- "each change or failure" --> Rec
|
||||
Trig -- candidate --> Src
|
||||
Src -- time --> Exec
|
||||
Src -- "other sources" --> RO
|
||||
RO -- notify --> Note
|
||||
RO -- "no notify call" --> Quiet
|
||||
Note --> Acc
|
||||
Trig -- candidate --> Exec
|
||||
```
|
||||
|
||||
| 层 | 判断什么 | 是否调用模型 | 输出 |
|
||||
|---|---|---|---|
|
||||
| 来源提供方(source provider) | 来源里发生了什么变化 | 否 | 事件 |
|
||||
| 事件触发器(event trigger) | 这个变化与本任务是否相关 | 否 | 一条运行记录;一个候选事件,或者没有 |
|
||||
| agent(智能体) | 用户是否需要处理,以及建议怎么处理 | 只对已投递的候选事件 | 通过通知工具产生通知,或者没有 |
|
||||
| agent(智能体) | 对这个候选事件,指令要求做什么 | 只对已投递的候选事件 | 该轮次在目标会话中完成的工作和回复 |
|
||||
|
||||
### 分层
|
||||
|
||||
@@ -52,14 +42,11 @@ flowchart TD
|
||||
|
||||
**事件触发器**是共享的代码,按来源类型和版本注册;每个任务只保存自己的参数和上次观察到的来源状态。每次观察时,它把新状态与保存的状态比较;没有变化的观察只更新最近检查时间。检查从通过变为失败算一次变化,持续失败不算,通过之后再次失败又算一次变化。对一次变化,触发器先匹配任务的条件(参数中的字段,例如结论为失败、作者是用户本人、评论者不是 bot),再在来源提供方的合并窗口内合并同一对象的多次变化(一次推送导致三项检查失败,只算一个事件),然后把新状态和任务一起保存,向会话投递一个候选事件,或者丢弃这次变化。每次变化和每次失败都写一条运行记录,列在任务的运行记录页签中,与现有的投递记录并列:已投递候选事件、已过滤(附原因)或失败。同一原因的连续失败共用一条记录并计数。投递之后触发器的工作就结束了,不等待该轮次,也不读取回执。每个任务用一个队列排定自己的判定顺序。
|
||||
|
||||
**agent** 在目标会话中以一条消息收到候选事件,消息附带以用户原话写成的任务指令。轮次能做什么取决于来源。
|
||||
|
||||
- **时间**:轮次按会话的权限执行指令,回复就是结果,与现在的定时任务一致。
|
||||
- **其他来源**:轮次使用“机制”一节所述的只读工具集。它可以读文件和来源的状态,例如检查日志和 PR diff,但没有修改、推送或发送的工具。新增一个工具 **通知**(`automation_notify`),接收标题、摘要和建议的操作,产生一条通知:会话中出现带有建议操作的[操作卡片](../../../../packages/experimental/action-cards/README.zh.md)、会话显示未读标记、桌面端发送系统通知。是否调用由模型决定。没有调用通知的轮次不产生通知;没有结束工具,也不检查轮次如何结束。用户接受卡片后,Host 向处理该任务的会话(见“会话”一节)发送一条后续消息:消息写明任务和事件,并把建议的操作作为自动化提出的建议引用,而不是作为用户的话;该轮次按该会话的权限执行。
|
||||
**agent** 在目标会话中以一条消息收到候选事件,消息附带以用户原话写成的任务指令。轮次使用该会话的工具和权限执行指令,回复就是结果,与现在的定时任务一致。来源只决定候选事件包含什么,不决定轮次如何运行。消息把事件的对象、摘要、详细内容和链接作为来自来源的事件数据引用,而不是作为用户的话。轮次行动前没有任何步骤等待用户确认;轮次自己发起的审批请求与任何轮次一样等待用户处理。轮次不需要自动化专用的工具。
|
||||
|
||||
### 会话
|
||||
|
||||
任务按三种模式之一投递到目标会话:指定的会话、每次触发新建会话、首次触发时新建会话并在之后的触发中复用。定时任务沿用现在的目标,即创建它的会话。事件任务把判断和处理分开。只读轮次在任务自己的会话中运行,首次触发时新建,之后复用,因为它需要的是指令、本次事件和该任务之前的判断,而不是任务来源会话的长历史。模型在会话中创建任务时,把判断需要的事实写进指令,例如哪项检查已知不稳定。用户接受卡片后,建议的操作发往创建任务的会话,代码和相关历史都在那里。自动化页的“新建”本来就在一个新会话中创建任务,之后由该会话处理;从官方模板启用的任务(后续步骤加入)在自己的会话中继续执行。用户可以在任务上修改模式。
|
||||
任务按三种模式之一投递到目标会话:指定的会话、每次触发新建会话、首次触发时新建会话并在之后的触发中复用。在会话中创建的任务,无论来源是什么,默认投递到指定的会话,即创建它的会话;这样定时任务沿用现在的目标,代码和相关历史也都在那里。对候选事件不需要历史的任务,模型可以按用户的要求、用户也可以在任务上改用一种新建会话的模式,这样它的轮次不会继续加长一个很长的会话;这时模型把工作需要的事实写进指令,例如哪项检查已知不稳定。自动化页的“新建”本来就在一个新会话中创建任务,之后由该会话处理;从官方模板启用的任务(后续步骤加入)在自己的会话中继续执行。用户可以在任务上修改模式。
|
||||
|
||||
Host 停止期间不运行任何任务。重启后,每个任务把当前来源状态与保存的状态比较一次,不重放中间的变化。时间沿用现有规则:周期任务只补跑最近一次错过的时间点。
|
||||
|
||||
@@ -69,10 +56,8 @@ Host 停止期间不运行任何任务。重启后,每个任务把当前来源
|
||||
|
||||
### 机制
|
||||
|
||||
- **事件轮次的工具集。** 沙箱的只读模式只限制文件系统,挡不住推送或外发请求。因此事件轮次使用固定的工具集,而不是会话的工具集:读文件和搜索、来源提供方的读取操作,以及 `automation_notify`。没有 shell、写文件、网页抓取和 MCP 工具。工具集记录在会话日志中;轮次进行中排队的用户消息,在该轮次结束后作为普通轮次执行。
|
||||
- **通知卡片。** 自动化包注册一种操作卡片类型,`automation_notify` 通过操作卡片服务创建这类卡片;该工具只在事件轮次中提供,因此调用前不需要加载 Skill。接受卡片时执行该类型的处理器,由处理器通过 Host 排入后续消息,所以处理任务的会话不必处于打开状态。同一会话中,新卡片会替换尚未处理的旧卡片,与操作卡片服务现在的行为一致;旧卡片在该会话的历史中,新的轮次能看到它,并把仍未处理的内容带到新卡片里。被拒绝的卡片会把错误返回给该轮次。
|
||||
- **未读标记。** 客户端根据轮次完成推导未读标记。任务自己的会话标记为自动化会话,对这类会话,客户端只为通知显示未读标记,因此没有调用通知的轮次不留下标记。
|
||||
- **日志。** 已投递的候选事件、轮次的工具集和通知调用都是会话事件,回放可以重建该轮次;TypeScript 和 Python SDK 的期望输出以及一个录制会话快照覆盖这些内容。
|
||||
- **投递。** Host 通过现在定时任务使用的同一条路径,把候选事件作为一条后续消息排入队列,所以目标会话不必处于打开状态;该会话中正在运行的轮次会先结束。
|
||||
- **日志。** 已投递的候选事件是一个会话事件,其中事件数据与指令分开,回放可以重建该轮次的输入;TypeScript 和 Python SDK 的期望输出以及一个录制会话快照覆盖该事件。
|
||||
- **存储。** 来源、参数、会话模式、触发器状态和运行记录以新的记录版本扩展 Host 任务域,并提供相邻迁移。版本 1 的任务按时间任务读取,在发生修改前不重写,也不补造记录。运行记录有自己的数量和时长上限,与投递记录分开。
|
||||
- **来源提供方配置。** 轮询间隔和请求额度是每个来源提供方在 cordis.yml 中经过校验的 Config 字段。
|
||||
|
||||
@@ -82,47 +67,39 @@ Host 停止期间不运行任何任务。重启后,每个任务把当前来源
|
||||
- 任务列表在状态筛选旁增加来源类型筛选。
|
||||
- 任务详情增加来源及其参数(只读)和会话模式(可修改)。
|
||||
- 任务运行记录同时列出已过滤和失败的判定。
|
||||
- 通知复用会话的未读标记和操作卡片;桌面端新增系统通知。
|
||||
- 由事件启动的轮次在所在会话中与其他轮次一样显示;不新增通知界面。
|
||||
|
||||
### 事件触发作为基础设施
|
||||
|
||||
触发层是 DSH 共用的基础设施,而不是自动化页的一项功能。需要观察某样东西并把变化交给 agent 的功能,都作为这一层上的任务实现,不再各自实现轮询、状态、记录和通知。
|
||||
触发层是 DSH 共用的基础设施,而不是自动化页的一项功能。需要观察某样东西并把变化交给 agent 的功能,都作为这一层上的任务实现,不再各自实现轮询、状态和记录。
|
||||
|
||||
- **DSH 自身状态作为来源**:会话轮次以错误结束、后台作业结束;memory 落地后,还包括一次 memory 整理完成,或 memory 条目发生变化。
|
||||
- **基于这些来源的功能**:插件推荐,即 memory 整理后发现用户反复手动执行的流程,由 agent 在操作卡片上推荐插件;任务推荐,即回顾当天的会话,提出后续要做的事。每一项都是一个模板任务,由一个 DSH 来源、一条指令和同样的通知步骤组成。插件推荐包现在从对话轮次中提出卡片,memory 整理落地后可以改为基于这类来源。
|
||||
- **每个使用方都保留的规则**:变化检测和条件匹配由代码完成、运行记录、会话模式、只读的事件轮次,以及只有通知能让任务触达用户。
|
||||
- **基于这些来源的功能**:插件推荐,即 memory 整理后发现用户反复手动执行的流程,由 agent 推荐插件;任务推荐,即回顾当天的会话,提出后续要做的事。每一项都是一个模板任务,由一个 DSH 来源和一条指令组成。插件推荐包现在从对话轮次中提出卡片,memory 整理落地后可以改为基于这类来源。
|
||||
- **每个使用方都保留的规则**:变化检测和条件匹配由代码完成、运行记录、会话模式,以及所有来源共用的一条投递路径。
|
||||
|
||||
### 交付顺序
|
||||
|
||||
1. 任务与会话解耦,支持三种会话模式。
|
||||
2. 上线触发层和任务域迁移,以时间作为第一个来源提供方;现有定时任务行为不变。
|
||||
3. GitHub 来源提供方,覆盖 PR 的检查、评审和评论;事件轮次工具集和 `automation_notify`;操作卡片结束实验状态,或随自动化 bundle 一起提供。
|
||||
3. GitHub 来源提供方,覆盖 PR 的检查、评审和评论。
|
||||
4. 邮件和 IM 来源提供方以及官方模板,然后是 DSH 自身的来源。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**在常驻会话中判断每次观察。** 模型读取每次轮询的结果,没有变化时回复一个静默标记。没有采用,原因是:每次观察都要在会话的完整上下文上花一个轮次;轮询间隔超过前缀缓存的有效期时,每次都要在没有缓存的情况下读取整个上下文;而且模型手里有发消息工具时,能否保持安静取决于它是否遵守指令。本方案由代码丢弃没有变化和不匹配的观察,只有调用通知才会触达用户。
|
||||
**在常驻会话中判断每次观察。** 模型读取每次轮询的结果,没有变化时回复一个静默标记。没有采用,原因是:每次观察都要在会话的完整上下文上花一个轮次;轮询间隔超过前缀缓存的有效期时,每次都要在没有缓存的情况下读取整个上下文;而且模型手里有发消息工具时,能否保持安静取决于它是否遵守指令。本方案由代码丢弃没有变化和不匹配的观察,因此只有匹配的变化才会启动轮次。
|
||||
|
||||
**在创建任务的会话中判断。** 该会话已经有代码和相关历史,指令里不需要额外写事实。没有采用,原因是大多数候选事件不产生通知,每一次都会在该会话的完整上下文上增加一个轮次,前缀缓存过期后要在没有缓存的情况下读取整个上下文,用户正在那里工作时还要排队或打断。只有被接受的工作才会进入该会话。
|
||||
|
||||
**由 agent 为每个事件选择会话。** 每次的选择可能不同,用户无法预料通知出现在哪里;而且要判断是否需要历史,得先读取历史。
|
||||
**由 agent 为每个事件选择会话。** 每次的选择可能不同,用户无法预料工作出现在哪里;而且要判断是否需要历史,得先读取历史。
|
||||
|
||||
**每个任务自带条件脚本。** 任务携带一个脚本,由脚本获取数据并作出判断。没有采用,原因是脚本以用户的凭据运行,却没有经过安装插件时的审查;而且每个任务都要自带获取逻辑,无法共用来源提供方。
|
||||
|
||||
**代码能判断时由代码直接通知。** 检查失败可以不经模型直接通知。没有采用,原因是这样的通知只包含原始状态。只保留一条路径时,agent 会先读日志,通知中写明失败原因;只在变化时投递,这类轮次很少。
|
||||
|
||||
**在会话之外调用一次模型。** 每个事件调用一次模型,成本更低,也不留下会话记录。没有采用,原因是这次调用在判断前无法读取文件或日志,而且要根据结果采取行动仍然需要会话。
|
||||
|
||||
**事件轮次沿用会话的权限。** 直接行动可以省去一次点击。没有采用,原因是事件内容来自其他人,只读轮次能防止这些文字在用户接受之前驱动修改、推送或发消息。
|
||||
**只读判断轮次加通知工具和用户接受。** 非时间来源在任务自己的会话中运行只读轮次;`automation_notify` 工具产生操作卡片、未读标记和系统通知;建议的操作只在用户接受卡片后执行。没有采用,原因是每个事件都要等用户确认的工作不符合自动化的使用方式,例如在无人值守时修复失败的检查;而且专用的通知工具及其卡片类型和未读规则,会多出一个面向模型的接口,之后每次增加来源或修改投递都必须与它保持兼容。
|
||||
|
||||
**事件轮次使用只读沙箱。** 没有采用,原因是沙箱的只读模式只限制文件系统,处于该模式的轮次仍然可以推送或发出请求。
|
||||
|
||||
**结束工具和对轮次结束方式的检查。** 第二个工具可以记录某一轮为什么没有产生通知,触发器则要等待这个结果。没有采用,原因是没有任何环节会使用这个原因:投递之后触发器的工作就结束了,而没有调用通知的轮次本来就是静默的。
|
||||
**按来源分支投递。** 时间按会话的权限执行指令,其他来源走另一条路径。没有采用,原因是来源说明的是发生了什么变化,而不是指令要求做什么工作;两条路径会让所有来源共用的轮次准备、日志和测试都变成两份。
|
||||
|
||||
**在自动化页提供参数表单。** 每个来源提供方都需要各自的表单、校验和展示。由模型写入参数并以只读方式展示,已经覆盖通过对话创建和修改;来源提供方的 schema 让以后生成表单仍然可行。
|
||||
|
||||
**单独的通知入口。** 收件箱页面或标签页会把通知与持有其上下文的会话分开。未读标记和系统通知都指向该会话,自动化页保留记录。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 时间改为来源提供方后,现有定时任务行为不变:到期时间相同、补跑规则相同、投递到会话的方式相同。
|
||||
@@ -131,23 +108,19 @@ Host 停止期间不运行任何任务。重启后,每个任务把当前来源
|
||||
- 一次推送导致三项检查失败,只产生一个候选事件。
|
||||
- 没有变化的观察不写记录,也不启动轮次;不满足条件的变化写一条已过滤记录,不启动轮次;同一原因的连续失败只写一条带计数的记录。
|
||||
- 运行记录到投递为止:记录候选事件,不记录该轮次做了什么。
|
||||
- 事件轮次不提供 shell、写文件、网页抓取或 MCP 工具,其工具集出现在会话日志中;用户接受卡片后,下一轮次按会话的权限执行。
|
||||
- 一次通知调用同时产生卡片、未读标记和桌面端系统通知。
|
||||
- 没有调用通知的事件轮次不留下未读标记,也不发送系统通知。
|
||||
- 事件任务的只读轮次在任务自己的会话中运行;接受卡片后,建议的操作发往创建任务的会话。
|
||||
- 已投递的候选事件在目标会话中启动一个轮次,使用该会话的工具和权限,与来源无关,也不等待用户确认。
|
||||
- 候选事件消息把事件内容作为事件数据呈现,与指令分开。
|
||||
- 在会话中创建的任务默认投递到该会话,与来源无关。
|
||||
- 每种会话模式按定义投递:指定的会话接收每次触发,或每次触发新建一个会话,或首次触发时新建一个会话并在之后复用。
|
||||
- 回放会话日志可以重建事件轮次的候选事件、工具集和通知调用。
|
||||
- 回放会话日志可以重建事件轮次的候选事件和指令。
|
||||
- 重启后,任务把当前来源状态与保存的状态比较一次,不重放中间的变化。
|
||||
- 任务列表可以按来源类型筛选,任务详情以只读方式显示来源参数,会话模式可以修改。
|
||||
|
||||
## 风险
|
||||
|
||||
- 只读轮次看到的是指令、本次事件和该任务之前的判断,看不到任务来源的会话。判断需要的、来自那个会话的事实,必须在创建任务时写进指令;用户把任务改成投回原会话,就能拿回历史,代价是每次投递都要读取很长的上下文。
|
||||
- 通知出现在任务自己的会话里,而不是创建任务的对话里;接受卡片后,工作转到那个对话。
|
||||
- agent 可能通知过于频繁,或者在应该提醒时保持静默。被接受和被忽略的卡片能看出通知过多,但漏掉的通知不会在运行记录中留下痕迹,因为运行记录到投递为止。
|
||||
- 由其他人写成的事件内容会进入按会话权限运行的轮次。把它标为事件数据,并不能阻止模型照着其中的文字去做;这类轮次能做什么,由会话的沙箱和审批设置以及任务的条件(例如评论者不是 bot)限定。
|
||||
- 投递到创建它的会话的任务,每个候选事件都会在该会话的完整上下文上增加一个轮次,前缀缓存过期后要在没有缓存的情况下读取整个上下文,并且要排在用户在那里的工作之后;新建会话的模式可以避免这一点,但除非指令带上所需的事实,否则会失去历史。
|
||||
- 运行记录到投递为止,因此轮次做了什么只能在它所在的会话中看到。投递到新建会话的任务只在那里报告结果,用户打开该会话后才能看到。
|
||||
- 来源参数不能手动编辑,每次修改都要经过模型。
|
||||
- 针对事件的修复要等用户接受卡片,不会在无人值守时执行。
|
||||
- 没有来源提供方插件的来源无法观察。
|
||||
- 任务只在 Host 运行时执行:应用关闭或机器休眠期间不运行任何任务。
|
||||
- 事件任务依赖操作卡片,而它目前是实验包,只由个性化推荐 Bundle 装入。
|
||||
- 只读工具集把判断限制在文件和来源提供方读取操作能看到的内容;来源提供方不提供读取操作时,agent 只能根据事件本身判断。
|
||||
@@ -21,5 +21,5 @@
|
||||
en: 21838e31d29b87fb
|
||||
zh: c72c81ef53b090e0
|
||||
/agent-note-api-extractor-reports/why-deferred:
|
||||
en: e2a8a7c13f4db704
|
||||
zh: aeae101a9a77d677
|
||||
en: 7e8a1bd17832ec5c
|
||||
zh: 3ea8dea04965f676
|
||||
@@ -30,3 +30,5 @@ The dependency is heavy and finicky — the reason this was deferred — and the
|
||||
## Why deferred
|
||||
|
||||
Deferred when doc-sync landed: low value for an internal monorepo where reviewers already see the source diff, and a heavy, finicky dependency. Revisit if the packages are ever published externally — at that point a stable, diffable public API earns its keep.
|
||||
|
||||
The packages are now published to npm, so the revisit condition holds. The [stable API policy](2026-11-05-stable-api-policy.md) proposal replaces the per-package reports with one report covering exports, services, and events, and adds stability levels and per-seam versions; its acceptance criteria apply if it is accepted.
|
||||
@@ -30,3 +30,5 @@ Status: proposed
|
||||
## 推迟原因
|
||||
|
||||
在 doc-sync 落地时被推迟:对于一个内部 monorepo,评审者已经能看到源码 diff,价值不高;且依赖笨重、难以调教。如果各包将来对外发布,再重新评估——届时一份稳定、可 diff 的公开接口报告才值得其维护成本。
|
||||
|
||||
各包现已发布到 npm,重新评估的条件已经满足。[稳定 API 规范](2026-11-05-stable-api-policy.zh.md)提案用一份覆盖导出、服务和事件的报告取代每个包一份的报告,并加入稳定级别和按 seam 划分的版本;该提案被接受后,以其验收标准为准。
|
||||
@@ -0,0 +1,49 @@
|
||||
# Bilingual-pair consistency record for 2026-11-05-stable-api-policy.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/proposed/process/2026-11-05-stable-api-policy.md
|
||||
/agent-note-stable-api-policy:
|
||||
en: efcff6bc65d1ae54
|
||||
zh: 2b32885373cb788d
|
||||
/agent-note-stable-api-policy/problem:
|
||||
en: b6492a320d28ff1c
|
||||
zh: 0105277d71fe43ab
|
||||
/agent-note-stable-api-policy/proposal:
|
||||
en: 88384462c8232e93
|
||||
zh: 355ad48f96efc95e
|
||||
/agent-note-stable-api-policy/proposal/stability-levels:
|
||||
en: ad9ea5e151e05ac2
|
||||
zh: baa08299dac43ee4
|
||||
/agent-note-stable-api-policy/proposal/unit-one-capability-seam:
|
||||
en: 2d33b23a61c8dae4
|
||||
zh: 4d781899433069d5
|
||||
/agent-note-stable-api-policy/proposal/what-stable-covers:
|
||||
en: 0a637e21cfbabeb3
|
||||
zh: 76078282bf686e17
|
||||
/agent-note-stable-api-policy/proposal/api-report-and-ci:
|
||||
en: 772026ec3f2512b0
|
||||
zh: d6cf271248e85a0e
|
||||
/agent-note-stable-api-policy/proposal/plugin-author-warnings:
|
||||
en: e9bdb925a73e14e4
|
||||
zh: e04aa39a43407070
|
||||
/agent-note-stable-api-policy/proposal/plugin-requirements:
|
||||
en: cce626a0c5dff76f
|
||||
zh: d85d04d33ddcff48
|
||||
/agent-note-stable-api-policy/proposal/compatibility-layer:
|
||||
en: 40445e93d1bb8561
|
||||
zh: 05a845c5093f4abd
|
||||
/agent-note-stable-api-policy/proposal/rollout:
|
||||
en: 16e88b03b3f1bc38
|
||||
zh: 5628adf979269b92
|
||||
/agent-note-stable-api-policy/proposal/open-questions:
|
||||
en: b33cf00ac8a10a94
|
||||
zh: e0a041a07879d2d5
|
||||
/agent-note-stable-api-policy/alternatives-considered:
|
||||
en: 4154f0aadc2f0017
|
||||
zh: cc1e120f80e7fbb8
|
||||
/agent-note-stable-api-policy/acceptance-criteria:
|
||||
en: a858ac77edabe3d3
|
||||
zh: 63f0872b73eef7f3
|
||||
/agent-note-stable-api-policy/risks:
|
||||
en: 16693acc4f57df3a
|
||||
zh: 96b056ba83bf3c38
|
||||
@@ -0,0 +1,121 @@
|
||||
# Agent Note: Stable API policy
|
||||
|
||||
Status: proposed
|
||||
|
||||
English | [中文](2026-11-05-stable-api-policy.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Every public DSH API is pre-stable: root `AGENTS.md` tells contributors to update every consumer when an API changes. That rule works inside the repository, but external plugins now install from npm and the plugin market, and their authors cannot tell which APIs they can rely on. All released packages share one lockstep version, so a package version says nothing about which API changed. The only compatibility check, `evaluatePluginCompatibility` in [plugin-compatibility.ts](../../../../packages/boot/app-boot/src/plugin-compatibility.ts), compares a plugin's `engines.dsh` range, or else its `@deepseek-ai/dsh` and `@deepseek-ai/dsh-*` peer ranges, with the whole runtime version; `workspace:` peer ranges count as the running version.
|
||||
|
||||
No source marker distinguishes stable from unstable APIs. Exports carry no `@public`, `@beta`, `@stable`, or `@since` tags; `@internal` appears about ten times with differing meanings, and undated `@deprecated` about a dozen times. The only rigorous compatibility rules cover data formats ([Session format status](../../../../docs/session-format-status.md), SQLite schema versions, persistence type acknowledgements) and [upgrade guides](../../../skills/dsh-create-upgrade-guide/SKILL.md).
|
||||
|
||||
The policy must start from this state. Contributors must not have to classify every API before the policy takes effect, and code that nobody marks must keep today's workflow.
|
||||
|
||||
## Proposal
|
||||
|
||||
Stability markers in source are the only input. A generated API report turns them into a versioned list of stable APIs for each release. The unit of versioning is the [capability seam](../../../../docs/glossary.md#capability-seam). Anything not marked stays unstable, so adoption proceeds one member at a time.
|
||||
|
||||
### Stability levels
|
||||
|
||||
| Level | Marker | Change rule |
|
||||
|---|---|---|
|
||||
| unstable (default) | None | Change freely, update every consumer, and record externally perceptible breaks in an upgrade guide |
|
||||
| stable | `@stable <seam>@<version>`, the seam version that added the member | Backward-compatible additions only; a removal or incompatible change requires a completed deprecation period and a major seam version |
|
||||
| internal | `@internal` | Used only inside this repository; omitted from the API report; change freely |
|
||||
|
||||
Deprecation is a state of a stable member, not a fourth level: a member tagged `@deprecated <replacement or "no replacement">` stays stable until its deprecation period ends. `@internal` and `@deprecated` tags on unstable members keep their current meaning; the policy assigns no new meaning to existing tags.
|
||||
|
||||
Packages under [`packages/experimental/`](../../../../packages/experimental/README.md#status) cannot contain stable members; a package is promoted out of the experimental group before any of its members are promoted.
|
||||
|
||||
### Unit: one capability seam
|
||||
|
||||
Each capability seam has its own API version, independent of the lockstep package version. A stable member belongs to the seam of the Service Definition package that declares it; a member of a declaration-merged interface such as `Context` or `SessionEventMap` belongs to the seam of the package that adds it. Exports that belong to no seam, such as utilities, CLI options, and the SDK wire protocol, stay unstable until a later proposal assigns them. Members reachable only through `./src/*` export subpaths are unstable.
|
||||
|
||||
The package that declares a Service Definition records its seam version in the existing `package.json` `dsh` declaration, owned by the [public package manifest](../../implemented/architecture/2026-09-10-public-package-manifest.md) decision. One package can declare several seams, so the member is a list:
|
||||
|
||||
```json
|
||||
{ "dsh": { "apis": [{ "name": "agent", "version": "1.0.0" }] } }
|
||||
```
|
||||
|
||||
The new members are optional and do not change `manifestVersion`; their names are not settled. As that decision requires, the report generator and the compatibility check each validate the members they read.
|
||||
|
||||
### What stable covers
|
||||
|
||||
Stable covers type signatures, event order, and waterfall calling conventions, including whether a listener must call `next()`. Default config values and config fields are not covered in this proposal. CI detects signature changes from the generated report. Behavior changes cannot be detected reliably; the author declares them in the PR description, and ordinary review checks the declaration. Tests that pin stable event order and waterfall conventions belong to the Service Definition package and run against the shipped Service Provider.
|
||||
|
||||
A stable signature can reference types from other seams, such as `SessionId` or `Scoped`. Those referenced types become part of the referencing seam's promise: the report lists them under that seam, and an incompatible change to them fails the same checks as a change to the seam's own members.
|
||||
|
||||
### API report and CI
|
||||
|
||||
A script generates one checked-in API report covering exports, Cordis services, and events, with each entry's seam, level, and version; it replaces the per-package reports of the deferred [API extractor reports](2026-06-11-api-extractor-reports.md) proposal. Each release archives its report. CI compares stable entries, including referenced types, with the latest released report and fails when:
|
||||
|
||||
- a stable entry is removed or changed incompatibly without a major seam version bump and an upgrade guide;
|
||||
- a removed entry was not deprecated in a released report, or its deprecation period has not elapsed since the first release whose report recorded the deprecation;
|
||||
- a stable entry is added without a minor seam version bump;
|
||||
- a stable signature references a member marked `@internal` or an unstable member of its own seam.
|
||||
|
||||
Measuring the period from the first release that recorded the deprecation keeps it independent of dates authors write. Changes to unstable entries appear in the report diff without failing CI. CI also posts a summary of stable API changes to the PR. Promotion and breaking changes are approved in ordinary PR review; no dedicated API owner or committee is named.
|
||||
|
||||
### Plugin author warnings
|
||||
|
||||
A type-aware lint rule reports uses of unstable members by resolving each used symbol and reading its level from the published declarations. Event and waterfall names are string literals passed to `ctx.on()` and similar calls, so the rule resolves them against the event map; `typescript/no-deprecated` in [.oxlintrc.json](../../../../.oxlintrc.json) does not cover this case. Oxlint offers no custom type-aware rules, so the rule ships as a published tool that plugin authors run in their own builds; the repository runs it on stable Service Definition packages. Subpath export isolation (`…/unstable` entry points) was rejected; see [Alternatives considered](#alternatives-considered).
|
||||
|
||||
### Plugin requirements
|
||||
|
||||
A plugin may declare the seam versions it needs, for example `"dsh": { "requires": { "agent": "^1.0.0" } }`. The seam check is additive: `evaluatePluginCompatibility` still evaluates `engines.dsh` or the DSH peer ranges, and also compares each listed seam range with the seam versions recorded in the running Host's API report. A plugin that declares seam ranges can widen its `engines.dsh` range to every runtime it supports. Plugin market index entries and registry update checks read the same declaration, so discovery, installation, and update reach the same result. By convention the plugin also lists the unstable seams it uses; the Host cannot verify that list, and the plugin manager shows it as a risk. The declaration does not restrict what a plugin can import or access: Cordis plugins run in the Host process and can import any package or reach any service on `ctx`.
|
||||
|
||||
### Compatibility layer
|
||||
|
||||
Serving an old major seam version to old plugins is deferred. It becomes worthwhile once a stable seam takes a major version bump while external plugins still require the previous major. The Host then keeps one current implementation, and an adapter plugin provides the old Service Definition on top of it for a fixed support period.
|
||||
|
||||
### Rollout
|
||||
|
||||
1. Policy only: land this note and define the deprecation period. Replace the pre-stable statement with "unmarked APIs are unstable" in root `AGENTS.md`, [packages/README.md](../../../../packages/README.md), [packages/experimental/README.md](../../../../packages/experimental/README.md), [apps/cli/reference/README.md](../../../../apps/cli/reference/README.md), and the generated package reference from [gen-plugin-packages.ts](../../../../scripts/gen-plugin-packages.ts). No code changes.
|
||||
2. Baseline report: generate and check in the first API report; CI only checks that it is current.
|
||||
3. Pilot: promote members of the agent seam declared by `dsh-agent`: `ctx.agents`, `AgentHandle`, `Agent`, the `agent/*` events other than the deprecated `agent/request`, and the `agent/pre-step` waterfall. Types they reference from session, scope, and llm packages join the promise as described above. The `dsh-agent-loop` Service Provider and its config stay unstable, so the pilot stabilizes no configuration. The lint tool and the `requires` check ship in this phase; [package-manifest README](../../../../packages/util/package-manifest/README.md) and the public package manifest note are updated to describe the enforced check.
|
||||
4. Promote further members and seams when the maintainers of a seam choose to; publish the stable API list on the documentation website.
|
||||
5. Add compatibility adapters for specific seams when the condition above holds.
|
||||
|
||||
### Open questions
|
||||
|
||||
- Names of the `dsh.apis` and `dsh.requires` members.
|
||||
- Length of the time-based deprecation period before DSH 1.0.
|
||||
- Whether the Python SDK methods, the SDK JSON-RPC protocol, and `cordis.yml` config fields join the same levels, and whether the protocol needs its own version.
|
||||
- Report generator: API Extractor or a dump built on the export walker in [scripts/verify-export-jsdoc.ts](../../../../scripts/verify-export-jsdoc.ts) and the tag parser in [scripts/jsdoc.ts](../../../../scripts/jsdoc.ts).
|
||||
- Lint tool form: a standalone published checker built on the same export walker, a non-type-aware approximation, or an upstream oxlint rule.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**`@stable` markers without versions.** Cheapest and incremental, but a plugin cannot state which stable API it was built against, the Host cannot check it, and the report cannot tell additions from existing members. Kept as the input format with the adding seam version attached; the generated report supplies the list.
|
||||
|
||||
**A hand-maintained versioned list per release.** Gives plugin authors a clear reference, but maintaining it by hand for over a thousand export subpaths and more than a hundred services is not practical, and one version for the whole list forces every plugin to react to any seam's break. Kept as the generated report rather than a maintained artifact.
|
||||
|
||||
**One API version for the whole platform** (Android API level, VS Code `engines`). Simplest for plugin authors, but DSH releases often and its seams evolve independently; a single number would either grow with every break or discourage necessary breaks.
|
||||
|
||||
**Independent semver per npm package, dropping the lockstep version.** The [npm release sequences](../../implemented/process/2026-08-10-npm-release-sequences.md) decision keeps all DSH packages on one version so releases and peer ranges stay consistent. Package versions would also change for internal refactors that do not touch any API a plugin uses. Seam versions describe API compatibility without changing how packages are released.
|
||||
|
||||
**Grouping by package directory instead of seam.** Groups such as `fs/` mix Service Definitions, providers, and tools that evolve separately. The seam is already the unit the architecture uses, so it costs the least to maintain.
|
||||
|
||||
**Subpath export isolation for unstable APIs.** Making the import path the opt-in is more explicit than a lint warning, but it restructures the exports of every package and breaks every current consumer at once, which contradicts incremental adoption.
|
||||
|
||||
**Shipping a compatibility layer from the start.** Each retained old version needs its own conversion code and tests. Before any seam is stable and before external plugins depend on an old major, that cost buys nothing.
|
||||
|
||||
**Counting the deprecation period in releases.** DSH release frequency varies, so a release count gives plugin authors an unpredictable amount of time. Measuring time from the first release that recorded the deprecation is predictable and can be computed from archived reports.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Root `AGENTS.md` and the package documentation listed in rollout step 1 state that unmarked APIs are unstable, and the deprecation period is defined.
|
||||
- A checked-in API report covers exports, services, and events; CI fails when it is stale.
|
||||
- The pilot members of the agent seam carry `@stable [email protected]`; CI rejects an incompatible change to them or to a type they reference, and posts a stable API change summary on PRs that touch them.
|
||||
- The lint tool reports a plugin's use of an unstable member, including an unstable event name passed to `ctx.on()`.
|
||||
- A plugin that declares `requires` is accepted or rejected per seam range in installation, update, and market discovery; a plugin without it behaves as it does today.
|
||||
|
||||
## Risks
|
||||
|
||||
- Referenced types from other seams join the promise of the referencing seam; promoting the agent seam therefore freezes parts of the session, scope, and llm types before those seams are promoted.
|
||||
- Behavior changes rely on author declarations, which review can miss.
|
||||
- Seam versions and the lockstep package version are two numbering systems, which plugin authors may confuse.
|
||||
- Promoting the agent seam constrains a core part of the loop that still changes often; promotion trades that flexibility for plugin stability.
|
||||
- The lint tool is new published tooling that the project must maintain alongside the oxlint configuration.
|
||||
- The manifest declaration cannot stop a plugin from using undeclared APIs; it informs checks and users, not enforcement.
|
||||
@@ -0,0 +1,121 @@
|
||||
# Agent Note: 稳定 API 规范
|
||||
|
||||
Status: proposed
|
||||
|
||||
[English](2026-11-05-stable-api-policy.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
DSH 的所有公开 API 都处于预稳定(pre-stable)阶段:根目录 `AGENTS.md` 要求 API 变化时同步更新每个消费方。这条规则在仓库内部可行,但外部插件现在从 npm 和插件市场安装,作者无法判断哪些 API 可以依赖。所有发布的包共用一个锁步版本,包版本无法说明哪个 API 变了。唯一的兼容检查是 [plugin-compatibility.ts](../../../../packages/boot/app-boot/src/plugin-compatibility.ts) 中的 `evaluatePluginCompatibility`,它把插件的 `engines.dsh` 范围(没有时改用 `@deepseek-ai/dsh` 和 `@deepseek-ai/dsh-*` peer 范围)与整个运行时版本比较;`workspace:` peer 范围视为当前运行版本。
|
||||
|
||||
源码中没有区分 stable 与 unstable API 的标记。导出不带 `@public`、`@beta`、`@stable` 或 `@since` 标签;`@internal` 出现约十次且含义不一,不带日期的 `@deprecated` 出现约十几次。唯一严格的兼容规则针对数据格式([Session 格式状态](../../../../docs/session-format-status.zh.md)、SQLite schema 版本、持久化类型变更确认)和 [upgrade guide](../../../skills/dsh-create-upgrade-guide/SKILL.md)。
|
||||
|
||||
规范必须从这一现状起步。贡献者不需要先给所有 API 定级,规范才能生效;没有人标记的代码保持现有工作方式。
|
||||
|
||||
## Proposal
|
||||
|
||||
源码中的稳定性标记是唯一输入。生成的 API 报告把标记转换为每次发布的带版本稳定 API 列表。版本单位是[能力 seam](../../../../docs/glossary.zh.md#capability-seam)。未标记的内容一律保持 unstable,因此可以逐个成员推进。
|
||||
|
||||
### 稳定级别
|
||||
|
||||
| 级别 | 标记 | 变更规则 |
|
||||
|---|---|---|
|
||||
| unstable(默认) | 无 | 随时修改,更新每个消费方,外部可感知的破坏性变更写入 upgrade guide |
|
||||
| stable | `@stable <seam>@<version>`,即加入该成员的 seam 版本 | 只允许向后兼容的新增;删除或不兼容修改需要弃用期已满,并升级 seam 主版本 |
|
||||
| internal | `@internal` | 仅在本仓库内部使用;不进入 API 报告;随时修改 |
|
||||
|
||||
弃用是 stable 成员的一种状态,不是第四个级别:带 `@deprecated <替代项或“无替代”>` 的成员在弃用期结束前仍是 stable。unstable 成员上的 `@internal` 和 `@deprecated` 标签保持现有含义;本规范不给现有标签赋予新含义。
|
||||
|
||||
[`packages/experimental/`](../../../../packages/experimental/README.zh.md#status) 下的包不能包含 stable 成员;包须先移出 experimental 分组,其中的成员才能晋升。
|
||||
|
||||
### 单位:一个能力 seam
|
||||
|
||||
每个能力 seam 有自己的 API 版本,与锁步的包版本无关。stable 成员属于声明它的 Service Definition 包所在的 seam;`Context`、`SessionEventMap` 等声明合并接口的成员属于添加该成员的包所在的 seam。不属于任何 seam 的导出(如工具函数、CLI 选项、SDK wire 协议)保持 unstable,留待后续提案归属。只能通过 `./src/*` 导出子路径访问的成员是 unstable。
|
||||
|
||||
声明 Service Definition 的包在现有的 `package.json` `dsh` 声明中登记 seam 版本,该声明由[公开包 manifest](../../implemented/architecture/2026-09-10-public-package-manifest.zh.md) 决策负责。一个包可以声明多个 seam,因此该成员是列表:
|
||||
|
||||
```json
|
||||
{ "dsh": { "apis": [{ "name": "agent", "version": "1.0.0" }] } }
|
||||
```
|
||||
|
||||
新成员是可选的,不改变 `manifestVersion`;成员名称尚未确定。按该决策的要求,报告生成器和兼容检查各自校验自己读取的成员。
|
||||
|
||||
### stable 覆盖的范围
|
||||
|
||||
stable 覆盖类型签名、事件顺序和 waterfall 调用约定(包括 listener 是否必须调用 `next()`)。本提案不覆盖默认配置值和配置字段。CI 根据生成的报告检测签名变化。行为变化无法可靠地自动检测;作者在 PR 描述中声明,由正常评审核对。锁定 stable 事件顺序和 waterfall 约定的测试属于 Service Definition 包,针对随产品发布的 Service Provider 运行。
|
||||
|
||||
stable 签名可以引用其他 seam 的类型,例如 `SessionId` 或 `Scoped`。这些被引用的类型成为引用方 seam 承诺的一部分:报告把它们列在该 seam 下,对它们的不兼容修改与修改该 seam 自身成员一样触发检查失败。
|
||||
|
||||
### API 报告与 CI
|
||||
|
||||
一个脚本生成并提交一份 API 报告,覆盖导出、Cordis 服务和事件,每个条目带有所属 seam、级别和版本;它取代已推迟的 [API extractor 报告](2026-06-11-api-extractor-reports.zh.md)提案中每个包一份的报告。每次发布归档当次报告。CI 把 stable 条目(包括被引用的类型)与最近一次发布的报告比较,以下情况失败:
|
||||
|
||||
- stable 条目被删除或不兼容修改,但没有升级 seam 主版本并写 upgrade guide;
|
||||
- 被删除的条目没有在已发布的报告中标为弃用,或自首次记录该弃用的发布起弃用期未满;
|
||||
- 新增 stable 条目,但没有升级 seam 次版本;
|
||||
- stable 签名引用了标为 `@internal` 的成员,或本 seam 的 unstable 成员。
|
||||
|
||||
从首次记录弃用的发布开始计算弃用期,使其不依赖作者填写的日期。unstable 条目的变化只出现在报告 diff 中,不会让 CI 失败。CI 还会在 PR 中发布 stable API 变更摘要。晋升和破坏性变更在正常 PR 评审中批准,不指定专门的 API owner 或委员会。
|
||||
|
||||
### 插件作者告警
|
||||
|
||||
一条类型感知的 lint 规则报告对 unstable 成员的使用:解析每个被使用的符号,并从发布的类型声明中读取其级别。事件和 waterfall 名称是传给 `ctx.on()` 等调用的字符串字面量,因此规则要把它们与事件映射对应起来;[.oxlintrc.json](../../../../.oxlintrc.json) 中的 `typescript/no-deprecated` 不覆盖这种情况。oxlint 不支持自定义的类型感知规则,因此该规则以发布的工具形式提供,插件作者在自己的构建中运行;仓库对 stable 的 Service Definition 包运行该规则。子路径导出隔离(`…/unstable` 入口)已否决,见 [Alternatives considered](#alternatives-considered)。
|
||||
|
||||
### 插件依赖声明
|
||||
|
||||
插件可以声明所需的 seam 版本,例如 `"dsh": { "requires": { "agent": "^1.0.0" } }`。seam 检查是附加的:`evaluatePluginCompatibility` 仍然检查 `engines.dsh` 或 DSH peer 范围,同时把列出的每个 seam 范围与当前 Host 的 API 报告中记录的 seam 版本比较。声明了 seam 范围的插件可以把 `engines.dsh` 放宽到它支持的所有运行时。插件市场索引条目和 registry 更新检查读取同一声明,使发现、安装和更新得出相同结论。按约定,插件还列出它使用的 unstable seam;Host 无法验证这份列表,插件管理页把它显示为风险。该声明不限制插件能导入或访问什么:Cordis 插件在 Host 进程内运行,可以导入任意包或访问 `ctx` 上的任意服务。
|
||||
|
||||
### 兼容层
|
||||
|
||||
为旧插件提供旧的 seam 主版本暂缓实现。当某个 stable seam 升级主版本、而外部插件仍依赖上一个主版本时,兼容层才有价值。届时 Host 只保留一份当前实现,由适配插件在其上提供旧的 Service Definition,并设定固定支持期限。
|
||||
|
||||
### 落地步骤
|
||||
|
||||
1. 仅规范:合入本 Agent Note 并确定弃用期。把根目录 `AGENTS.md`、[packages/README.md](../../../../packages/README.zh.md)、[packages/experimental/README.md](../../../../packages/experimental/README.zh.md)、[apps/cli/reference/README.md](../../../../apps/cli/reference/README.zh.md) 以及由 [gen-plugin-packages.ts](../../../../scripts/gen-plugin-packages.ts) 生成的包参考中的预稳定表述改为“未标记的 API 为 unstable”。不改代码。
|
||||
2. 基线报告:生成并提交第一份 API 报告;CI 只检查报告是否最新。
|
||||
3. 试点:晋升 `dsh-agent` 声明的 agent seam 成员:`ctx.agents`、`AgentHandle`、`Agent`、除已弃用的 `agent/request` 之外的 `agent/*` 事件,以及 `agent/pre-step` waterfall。它们引用的 session、scope 和 llm 包类型按上文加入承诺。Service Provider `dsh-agent-loop` 及其配置保持 unstable,因此试点不稳定任何配置。lint 工具和 `requires` 检查在这一阶段交付;同时更新 [package-manifest README](../../../../packages/util/package-manifest/README.zh.md) 和公开包 manifest 决策记录,说明已强制执行的检查。
|
||||
4. 由各 seam 的维护者按需晋升更多成员和 seam;在文档站发布稳定 API 列表。
|
||||
5. 满足上述条件时,为特定 seam 增加兼容适配插件。
|
||||
|
||||
### 待决问题
|
||||
|
||||
- `dsh.apis` 和 `dsh.requires` 成员的名称。
|
||||
- DSH 1.0 之前按时间计算的弃用期长度。
|
||||
- Python SDK 方法、SDK JSON-RPC 协议和 `cordis.yml` 配置字段是否纳入同一套级别,以及协议是否需要独立版本。
|
||||
- 报告生成方式:API Extractor,还是基于 [scripts/verify-export-jsdoc.ts](../../../../scripts/verify-export-jsdoc.ts) 的导出遍历和 [scripts/jsdoc.ts](../../../../scripts/jsdoc.ts) 的标签解析生成的转储。
|
||||
- lint 工具形式:基于同一导出遍历的独立发布检查器、非类型感知的近似实现,或上游 oxlint 规则。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**不带版本的 `@stable` 标记。** 成本最低且可渐进,但插件无法说明自己基于哪个稳定 API 构建,Host 也无法检查,报告也无法区分新增成员和已有成员。保留为输入格式,并附上加入该成员的 seam 版本;列表由生成的报告提供。
|
||||
|
||||
**每次发布手工维护带版本的列表。** 插件作者有明确的参考,但为一千多个导出子路径和一百多个服务手工维护不现实,而且整个列表只有一个版本,任何 seam 的破坏性变更都会波及所有插件。保留为生成的报告,而不是手工维护的产物。
|
||||
|
||||
**整个平台一个 API 版本**(Android API level、VS Code `engines`)。对插件作者最简单,但 DSH 发布频繁,各 seam 独立演进;单一版本号要么随每次破坏性变更增长,要么抑制必要的破坏性变更。
|
||||
|
||||
**每个 npm 包独立 semver,取消锁步版本。** [npm 发布序列](../../implemented/process/2026-08-10-npm-release-sequences.zh.md)决策让所有 DSH 包使用同一版本,以保持发布和 peer 范围一致。包版本还会因不涉及任何插件所用 API 的内部重构而变化。seam 版本描述 API 兼容性,不改变包的发布方式。
|
||||
|
||||
**按包目录而不是 seam 分组。** `fs/` 等分组混合了独立演进的 Service Definition、provider 和工具。seam 本来就是架构使用的单位,维护成本最低。
|
||||
|
||||
**用子路径导出隔离 unstable API。** 让导入路径本身成为 opt-in,比 lint 告警更明确,但需要重组每个包的导出,并一次性破坏所有现有消费方,与渐进推进相矛盾。
|
||||
|
||||
**一开始就提供兼容层。** 每保留一个旧版本,都需要单独的转换代码和测试。在任何 seam 稳定、且外部插件依赖旧主版本之前,这项成本没有收益。
|
||||
|
||||
**按发布次数计算弃用期。** DSH 发布频率不固定,按次数计算给插件作者的时间不可预测。从首次记录弃用的发布开始按时间计算,结果可预测,并且可以从归档的报告中算出。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- 根目录 `AGENTS.md` 和落地步骤 1 列出的包文档写明未标记的 API 为 unstable,且弃用期已确定。
|
||||
- 已提交的 API 报告覆盖导出、服务和事件;报告过期时 CI 失败。
|
||||
- agent seam 的试点成员带有 `@stable [email protected]`;CI 拒绝对它们或它们引用的类型的不兼容修改,并在涉及它们的 PR 中发布 stable API 变更摘要。
|
||||
- lint 工具报告插件对 unstable 成员的使用,包括传给 `ctx.on()` 的 unstable 事件名。
|
||||
- 声明了 `requires` 的插件在安装、更新和市场发现中按 seam 范围被接受或拒绝;未声明的插件行为与现在相同。
|
||||
|
||||
## Risks
|
||||
|
||||
- 其他 seam 中被引用的类型会加入引用方 seam 的承诺;晋升 agent seam 因而会在 session、scope 和 llm 等 seam 晋升之前冻结其部分类型。
|
||||
- 行为变化依赖作者声明,评审可能遗漏。
|
||||
- seam 版本与锁步包版本是两套编号,插件作者可能混淆。
|
||||
- 晋升 agent seam 会约束仍在频繁变化的 loop 核心部分;晋升以这部分灵活性换取插件稳定性。
|
||||
- lint 工具是新的发布工具,项目需要与 oxlint 配置一起维护。
|
||||
- manifest 声明无法阻止插件使用未声明的 API;它只为检查和用户提供信息,不是强制手段。
|
||||
@@ -39,10 +39,10 @@ If an existing record is damaged or its keychain/certificate is missing, setup s
|
||||
|
||||
## Configure the source build
|
||||
|
||||
Resolve the DSH home used by the developer (`DSH_HOME`, otherwise `~/.dsh`). Merge the two printed values into its `cordis.patch.yml`, targeting the entry that loads `@deepseek-ai/dsh-experimental-cua-macos`. The shipped entry ID is `cua`:
|
||||
Resolve the DSH home used by the developer (`DSH_HOME`, otherwise `~/.dsh`). Merge the two printed values into its `cordis.patch.yml`, targeting the entry that loads `@deepseek-ai/dsh-cua-macos`. The shipped entry ID is `cua-macos`:
|
||||
|
||||
```yaml
|
||||
- id: cua
|
||||
- id: cua-macos
|
||||
config:
|
||||
sourceSigning:
|
||||
identity: "<fingerprint printed by setup>"
|
||||
|
||||
@@ -34,6 +34,48 @@ For each failure, define handling and reporting owners, containment, and guarant
|
||||
|
||||
Catching limits exception propagation, not mutations. Only the affected state's owner can establish safe continuation. Otherwise stop dependent work, discard invalid state or instances, or escalate. Logging alone is not recovery. Retries require safe repetition, cancellation, and an explicit owner; finite operations need budgets, while continuing supervision needs lifecycle ownership and observable degradation.
|
||||
|
||||
### Empty catch clauses
|
||||
|
||||
An empty `catch` has no statement other than `;` in its block, and it discards every failure its `try` raises. Use one only when every such failure leaves the owner's state valid and no caller could act on it, such as failing to remove a temporary file that nothing reads. A `catch` that logs, reports, rethrows, or returns a fallback is not empty, and the rules below do not apply to it. [`verify-empty-catch`](../../../scripts/verify-empty-catch.ts) checks every `try`/`catch` statement in first-party JavaScript and TypeScript, including tests; it does not check `promise.catch()` callbacks. The checker checks the form; review checks that the name and the reason are true.
|
||||
|
||||
**The `try` holds one statement.** One statement means one syntactic statement, such as one call or one assignment, however many lines it spans; it does not mean one line. With several statements, the reason covers one expected failure while the clause also discards the others, including defects such as a `TypeError`, and a failure in an early statement skips the later ones while the caller sees success:
|
||||
|
||||
```ts
|
||||
// Rejected: three statements in one try.
|
||||
try {
|
||||
await unlink(tempFile)
|
||||
registry.delete(id)
|
||||
emit('removed', id)
|
||||
} catch (_cleanupFailed) {
|
||||
// A leftover temporary file holds no state anything reads.
|
||||
}
|
||||
|
||||
// Accepted: only the unlink failure is discarded.
|
||||
try {
|
||||
await unlink(tempFile)
|
||||
} catch (_cleanupFailed) {
|
||||
// A leftover temporary file holds no state anything reads.
|
||||
}
|
||||
registry.delete(id)
|
||||
emit('removed', id)
|
||||
```
|
||||
|
||||
When several statements each tolerate a failure, give each its own `try` and reason. The checker counts one block or one compound statement, such as one `if`, as one statement; review rejects such a `try` when it contains several operations.
|
||||
|
||||
**The binding names the expected failure.** Write `catch (_cleanupFailed)`, not `catch {}` or `catch (_)`. Lint requires an unused binding to start with `_`, and a bare `_` names nothing.
|
||||
|
||||
**A comment states why discarding the failure is safe.** Put it in the `catch` block or after the clause's closing `}` on the same line. A comment inside the `try` block or above `try` does not count. `// ignore` and `// expected` restate the empty block; say which failure is expected and why the state stays valid.
|
||||
|
||||
**Accept only some failures by testing them.** When only some failures are safe, such as a missing file while a permission error must still surface, write a non-empty `catch` that tests `code` or `name` and rethrows the rest; the checker does not check such a clause.
|
||||
|
||||
```ts
|
||||
try {
|
||||
await unlink(tempFile)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
}
|
||||
```
|
||||
|
||||
## Localized, actionable, visible reports
|
||||
|
||||
Every final report needs a readable summary, affected operation, and safe next action. Localize through the receiving application's locale mechanism where one exists; other diagnostics use their existing output language. Keep sensitive internal details out of user-facing text.
|
||||
|
||||
@@ -16,3 +16,12 @@ docs/persistence-changes/historical-formats/*.schema.json linguist-generated=tru
|
||||
|
||||
# Unified patch blank context lines require their leading space.
|
||||
patches/*.patch whitespace=-blank-at-eol
|
||||
|
||||
# Review layers of the forge changes view (dsh-review-layer), for this repository's own conventions:
|
||||
# plugin locale dictionaries and the session snapshot tree hide with test files, generated bilingual
|
||||
# pairing records join them, and a package's types-only module is part of its interface.
|
||||
packages/*/*/locale/*.json dsh-review-layer=test
|
||||
locales.ts dsh-review-layer=test
|
||||
snapshots/** dsh-review-layer=test
|
||||
*.i18n.yaml dsh-review-layer=test
|
||||
packages/*/*/src/types.ts dsh-review-layer=interface
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 2374f332d040ece2
|
||||
zh: 7f914fb83cfb5caa
|
||||
/pr-preview-runner-sizing/publication-semantics:
|
||||
en: 25ee2f4b26ef7770
|
||||
zh: 788b7fb4bee6e159
|
||||
en: 0d86702bcbbe23f4
|
||||
zh: cd0041c917ac8c55
|
||||
/pr-preview-runner-sizing/dev-note:
|
||||
en: c3e8959997c4d5d0
|
||||
zh: 109a391915c2bdfb
|
||||
@@ -26,7 +26,7 @@ A build-only benchmark does not deploy, access Cloudflare credentials, or post p
|
||||
|
||||
## Publication semantics
|
||||
|
||||
Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines.
|
||||
Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site and the snapshot diff page to the PR branch alias; that page embeds committed `snapshots/` diff text, never package sources. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
## 发布语义
|
||||
|
||||
运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。
|
||||
运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点和 snapshot diff 页面上传至 PR 分支别名;该页面嵌入已提交的 `snapshots/` diff 文本,不含包源码。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ name: Build PR preview
|
||||
|
||||
# Every push to a pull request publishes that pull request's preview to
|
||||
# Cloudflare Pages under its own branch alias, behind Cloudflare Access. The
|
||||
# upload carries build products only: the workflow never grants the deployment
|
||||
# upload carries build products plus the snapshot diff page, which embeds
|
||||
# committed `snapshots/` diff text: the workflow never grants the deployment
|
||||
# platform access to this repository's sources. This lane also owns the
|
||||
# aggregate test and script type checks that the required Linux consumers no
|
||||
# longer repeat on every pull request.
|
||||
@@ -43,9 +44,12 @@ jobs:
|
||||
|| 'ubuntu-24.04' }}
|
||||
name: cloudflare pages preview
|
||||
steps:
|
||||
# The pull_request checkout is the merge commit; depth 2 brings its first
|
||||
# parent, the base branch tip, for the snapshot diff page.
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 2
|
||||
|
||||
- uses: pnpm/[email protected]
|
||||
with:
|
||||
@@ -98,6 +102,18 @@ jobs:
|
||||
find apps/web/dist -name '*.map' -delete
|
||||
cp apps/web/dist/preview.html apps/web/dist/index.html
|
||||
|
||||
# Reviewers read snapshot changes at /snapshot-diff/, which opens on the
|
||||
# SDK blank-Session catalog (system prompt and tool schemas); the source
|
||||
# chooser links to it. The page serves review only, so a failure warns
|
||||
# like publication instead of failing the build.
|
||||
- name: Render the snapshot diff page
|
||||
id: snapshot-diff
|
||||
continue-on-error: true
|
||||
run: >-
|
||||
pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD
|
||||
--out apps/web/dist/snapshot-diff
|
||||
--preview-manifest apps/web/dist/preview/fixtures.json
|
||||
|
||||
- name: Upload to Cloudflare Pages
|
||||
id: upload
|
||||
continue-on-error: true
|
||||
@@ -164,33 +180,41 @@ jobs:
|
||||
# The alias URL follows from the pull request number, so it is stable
|
||||
# across redeploys and worth stating once. The marker makes the comment
|
||||
# idempotent: a pull request opened before this workflow existed never
|
||||
# sees an `opened` event, and every later push must not restate the URL.
|
||||
# sees an `opened` event, and every later push must not restate the URL;
|
||||
# an existing comment with older text is edited in place.
|
||||
- name: Comment the preview URL
|
||||
id: comment
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
SNAPSHOT_DIFF: ${{ steps.snapshot-diff.outcome }}
|
||||
run: |
|
||||
marker='<!-- dsh-preview-url -->'
|
||||
existing=$(gh pr view "$PR" --json comments \
|
||||
--jq "[.comments[] | select(.body | contains(\"$marker\")) | .url] | first // empty")
|
||||
if [ -n "$existing" ]; then
|
||||
echo "preview URL already commented: $existing"
|
||||
exit 0
|
||||
fi
|
||||
url="https://pr-$PR.${CF_PROJECT}.pages.dev"
|
||||
links="[Preview for #$PR]($url)"
|
||||
if [ "$SNAPSHOT_DIFF" = success ]; then links="$links · [snapshot changes]($url/snapshot-diff/)"; fi
|
||||
# The marker sits on its own line: markdown renders no link on a
|
||||
# line that opens with a raw HTML comment.
|
||||
printf '%s\n\n%s\n' \
|
||||
"$marker" \
|
||||
"[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \
|
||||
| gh pr comment "$PR" --body-file -
|
||||
body=$(printf '%s\n\n%s\n' "$marker" "$links (requires Cloudflare Access sign-in)")
|
||||
existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \
|
||||
--jq "[.[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\")))] | first // empty | [.id, .body] | @json")
|
||||
if [ -z "$existing" ]; then
|
||||
printf '%s' "$body" | gh pr comment "$PR" --body-file -
|
||||
elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then
|
||||
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null
|
||||
else
|
||||
echo "preview URL already commented"
|
||||
fi
|
||||
|
||||
# Publishing stays outside the required verdict: a Cloudflare, Access, or
|
||||
# comment failure warns, while a build failure still fails this check.
|
||||
# Publishing stays outside the required verdict: a snapshot diff page,
|
||||
# Cloudflare, Access, or comment failure warns, while a build failure
|
||||
# still fails this check.
|
||||
- name: Report preview publication failures
|
||||
if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'
|
||||
if: >-
|
||||
steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'
|
||||
|| steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'
|
||||
run: |
|
||||
message='preview publication failed; the build passed, see the upload, verify, and comment steps'
|
||||
message='preview publication failed; the build passed, see the snapshot diff, upload, verify, and comment steps'
|
||||
echo "::warning::$message"
|
||||
echo "$message" >> "$GITHUB_STEP_SUMMARY"
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
name: Package CUA helper · macOS
|
||||
name: Package CUA helper · macOS · arm64 + x64
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -14,7 +14,7 @@ on:
|
||||
reuse:
|
||||
type: boolean
|
||||
default: false
|
||||
cua_run_id:
|
||||
cua_macos_run_id:
|
||||
type: string
|
||||
default: ''
|
||||
preset:
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
id: retained
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
CUA_RUN_ID: ${{ inputs.cua_run_id }}
|
||||
CUA_MACOS_RUN_ID: ${{ inputs.cua_macos_run_id }}
|
||||
CUA_BUILD_KEY: ${{ steps.build-inputs.outputs.build-key }}
|
||||
run: node scripts/cua-helper/select-artifact.ts
|
||||
- uses: pnpm/[email protected]
|
||||
@@ -96,7 +96,7 @@ jobs:
|
||||
if: steps.retained.outputs.artifact-id == ''
|
||||
id: upload
|
||||
with:
|
||||
name: cua-helper-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.build-inputs.outputs.build-key }}
|
||||
name: cua-helper-macos-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.build-inputs.outputs.build-key }}
|
||||
path: dist/cua-helper/*
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
Loaded 100 of 2968 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user