Merge remote-tracking branch 'origin/master' into feat/cua-mcp
Conflicts: both sides added one adjacent entry (cua-mcp here, cua-windows on master) to scripts/experimental-package-policy.ts, scripts/release/families.spec.ts, and tsconfig.host.json; both entries are kept. Generated and recorded files take master's side and are regenerated: the config catalog, the module graph, the package list, two pairing records, pnpm-lock.yaml, and the creation-recommendations fixture. Adaptations to master: - @deepseek-ai/dsh-cua-mcp follows its release family to 0.2.2-rc.2. - Window ids are strings: this branch's fixture programs and assertions pass "7". - The retained program environment is a scoped REPL, in which a later call may declare an earlier name again: cua_reset no longer names declaration conflicts as its use, and the cua-mcp README and Agent Note state the registration's current description length. - The cua-mcp README names the Windows provider, which this profile does not mount. - The profile's expected reference and tool list are re-recorded.
This commit is contained in:
commit
b2e064fecb
774 files changed
+20420
-1747
No files matched your search
@@ -12,8 +12,8 @@
|
||||
en: c02307553b723361
|
||||
zh: ac5557c85a0c1b24
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/alternatives-considered:
|
||||
en: 1cb5819091df8907
|
||||
zh: ce9e60339bf159e3
|
||||
en: e9d7e085b38020ec
|
||||
zh: 4771a40ee0aa2972
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/consequences:
|
||||
en: ff77201d75fe884c
|
||||
zh: 6982dbfad834849f
|
||||
@@ -40,7 +40,7 @@ The composition lists its dependency closure, twenty-five rows, instead of layer
|
||||
|
||||
**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 2,000-character description stays within the budget.
|
||||
**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.
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会
|
||||
|
||||
**为 `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 个字符,因此作为工具结果传递,注册项 2,000 个字符的描述留在预算之内。
|
||||
**把 `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 都在首个程序之前调用了它。
|
||||
|
||||
|
||||
@@ -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%;现有求值器及其测试不变。
|
||||
@@ -0,0 +1,107 @@
|
||||
name: Package CUA helper · Windows · x64
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
outputs:
|
||||
artifact-id:
|
||||
description: '包含 win-x64 helper ZIP 的产物编号'
|
||||
value: ${{ jobs.package.outputs.artifact-id }}
|
||||
run-id:
|
||||
description: '产物所属的构建运行编号'
|
||||
value: ${{ jobs.package.outputs.run-id }}
|
||||
build-key:
|
||||
description: '提交 SHA、.NET SDK 版本和 win-x64 RID 的 SHA-256 摘要'
|
||||
value: ${{ jobs.package.outputs.build-key }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
package:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 30
|
||||
defaults:
|
||||
run:
|
||||
shell: pwsh
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
run-id: ${{ github.run_id }}
|
||||
build-key: ${{ steps.metadata.outputs.build-key }}
|
||||
steps:
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
- name: Restore locked Windows helper and run protocol checks
|
||||
run: |
|
||||
dotnet restore packages/experimental/cua-windows/native/cua-windows.slnx --locked-mode
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
dotnet run --project packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj --configuration Release --no-restore
|
||||
- name: Publish Windows CUA helper
|
||||
run: >-
|
||||
dotnet publish packages/experimental/cua-windows/native/entry/CuaWindows.csproj
|
||||
--configuration Release
|
||||
--runtime win-x64
|
||||
--self-contained true
|
||||
--no-restore
|
||||
--output dist/cua-helper-win-x64
|
||||
# Standalone helper zip contract: flat root with cua-helper.json,
|
||||
# dsh-cua-windows.exe, and its runtime files. Installed providers place
|
||||
# the same payload under native/bin/win-x64.
|
||||
- name: Add helper metadata
|
||||
id: metadata
|
||||
env:
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$directory = 'dist/cua-helper-win-x64'
|
||||
$exe = Join-Path $directory 'dsh-cua-windows.exe'
|
||||
if (-not (Test-Path $exe -PathType Leaf)) { throw "helper executable is missing: $exe" }
|
||||
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
||||
$commit = $env:GITHUB_SHA
|
||||
$sdk = (& dotnet --version).Trim()
|
||||
$keyBytes = [Text.Encoding]::UTF8.GetBytes("$commit`n$sdk`nwin-x64")
|
||||
$buildKey = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($keyBytes)).ToLowerInvariant()
|
||||
$files = [ordered]@{}
|
||||
Get-ChildItem $directory -Recurse -File | Sort-Object FullName | ForEach-Object {
|
||||
$relative = [IO.Path]::GetRelativePath($directory, $_.FullName) -replace '\\', '/'
|
||||
$files[$relative] = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
}
|
||||
# sha256 is the executable alias of files[dsh-cua-windows.exe].
|
||||
# signing is an enum: unsigned or authenticode.
|
||||
$metadata = [ordered]@{
|
||||
schemaVersion = 1
|
||||
platform = 'windows'
|
||||
buildKey = $buildKey
|
||||
version = $version
|
||||
commit = $commit
|
||||
architecture = 'x64'
|
||||
executable = 'dsh-cua-windows.exe'
|
||||
sha256 = $files['dsh-cua-windows.exe']
|
||||
signing = 'unsigned'
|
||||
files = $files
|
||||
}
|
||||
$json = $metadata | ConvertTo-Json -Depth 5
|
||||
Set-Content -Path (Join-Path $directory 'cua-helper.json') -Value "$json`n" -NoNewline -Encoding utf8NoBOM
|
||||
Add-Content -Path $env:GITHUB_OUTPUT -Value "build-key=$buildKey`n" -NoNewline -Encoding utf8
|
||||
- name: Archive publish output
|
||||
run: |
|
||||
$zipPath = 'dist/cua-helper-win-x64.zip'
|
||||
Compress-Archive -Path dist/cua-helper-win-x64/* -DestinationPath $zipPath
|
||||
$zip = [IO.Compression.ZipFile]::OpenRead((Resolve-Path $zipPath).Path)
|
||||
try {
|
||||
foreach ($name in 'dsh-cua-windows.exe', 'cua-helper.json') {
|
||||
if (-not $zip.GetEntry($name)) { throw "Missing root entry in helper ZIP: $name" }
|
||||
}
|
||||
} finally { $zip.Dispose() }
|
||||
- uses: actions/[email protected]
|
||||
id: upload
|
||||
with:
|
||||
name: cua-helper-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.metadata.outputs.build-key }}
|
||||
path: dist/cua-helper-win-x64.zip
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
retention-days: 14
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh",
|
||||
"description": "dsh CLI: profile launch, plugin management, and configuration inspection",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -261,6 +261,17 @@ export interface RunProfileOptions {
|
||||
packageManager?: ProfileContext['packageManager']
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a profile name as an RFC 9110 `User-Agent` product version: bytes outside `tchar`, and `%`, are percent-encoded,
|
||||
* so spaces, `/`, and non-ASCII names stay readable and reversible.
|
||||
* @param name - the booted profile name.
|
||||
* @returns the encoded name.
|
||||
*/
|
||||
export function userAgentProfile(name: string): string {
|
||||
// encodeURIComponent leaves only `(` and `)` outside tchar.
|
||||
return encodeURIComponent(name).replace(/[()]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Boot one profile invocation end to end and leave process lifetime to the
|
||||
* mounted plugins (or to a one-shot runner the composition mounts).
|
||||
@@ -269,6 +280,8 @@ export interface RunProfileOptions {
|
||||
* @throws after disposing startup resources; cleanup failures retain the original error.
|
||||
*/
|
||||
export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> {
|
||||
// Model providers see which profile sent a request.
|
||||
process.env.DSH_USER_AGENT_SUFFIX = `dsh-profile/${userAgentProfile(options.profile)}`
|
||||
// Before the first plugin mounts and before anything can issue a request: Node's fetch ignores the
|
||||
// proxy environment on its own, so every profile would otherwise connect directly. Resolving from
|
||||
// the launcher's snapshot — not `process.env` — is what lets a proxy declared in a `.env` layer
|
||||
|
||||
@@ -66,7 +66,7 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => {
|
||||
await expect(`${textOf(reference.content[0])}\n`).toMatchFileSnapshot('./expected/reference.md')
|
||||
|
||||
const first = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
|
||||
code: 'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); '
|
||||
code: 'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); '
|
||||
+ 'await win.getAccessibilityTree(); await win.click("0"); '
|
||||
+ 'inspect(JSON.stringify({ visits, window: win.windowId, pid: process.pid, cwd: process.cwd() }), await win.getScreenshot())',
|
||||
description: 'Open the fixture window',
|
||||
@@ -74,7 +74,7 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => {
|
||||
expect(first.isError).toBeUndefined()
|
||||
expect(first.content.map(block => block.type)).toEqual(['text', 'image'])
|
||||
const state = JSON.parse(textOf(first.content[0])) as { visits: number; window: number; pid: number; cwd: string }
|
||||
expect(state).toMatchObject({ visits: 1, window: 7 })
|
||||
expect(state).toMatchObject({ visits: 1, window: '7' })
|
||||
// Without DSH_CUA_WORKSPACE the profile creates its workspace inside the Harness home and starts programs there.
|
||||
expect(state.cwd).toBe(await realpath(join(home, 'cua-mcp', 'workspace')))
|
||||
expect(state.cwd).not.toBe(await realpath(launch))
|
||||
@@ -84,7 +84,7 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => {
|
||||
expect(Buffer.from(image.data, 'base64').length).toBeGreaterThan(0)
|
||||
|
||||
const second = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
|
||||
code: 'globalThis.visits++; inspect(JSON.stringify({ visits, sameWindow: win.windowId === 7, pid: process.pid }))', description: 'Count another visit',
|
||||
code: 'globalThis.visits++; inspect(JSON.stringify({ visits, sameWindow: win.windowId === "7", pid: process.pid }))', description: 'Count another visit',
|
||||
} }) as CallResult
|
||||
expect(second.content).toHaveLength(1)
|
||||
expect(JSON.parse(textOf(second.content[0]))).toEqual({ visits: 2, sameWindow: true, pid: state.pid })
|
||||
|
||||
@@ -4,19 +4,19 @@ Use cua to observe and operate native applications. Always use cua.getCapabiliti
|
||||
|
||||
Call inspect(...values) to display selected observation results.
|
||||
|
||||
Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid.
|
||||
Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: string and the methods listed below for window level. Window IDs are opaque provider-issued strings; preserve them verbatim.
|
||||
|
||||
Setup and discovery:
|
||||
- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions.
|
||||
- cua.listApps() -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications.
|
||||
- cua.findApps(query: string) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid.
|
||||
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation.
|
||||
- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app.
|
||||
- app.getWindows() -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
|
||||
- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
|
||||
- cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp.
|
||||
- cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches.
|
||||
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation.
|
||||
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading AX or activating the app.
|
||||
- app.getWindows() -> { windowId: string, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
|
||||
- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
|
||||
- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required.
|
||||
- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
|
||||
- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
|
||||
- app.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
|
||||
- window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
|
||||
|
||||
## Accessibility tree
|
||||
Available at app or window level depending on the platform.
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
{
|
||||
"name": "cua_run_code",
|
||||
"title": "Computer use program",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. Await tools and cleanup before returning; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before returning; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call starts with copies of the top-level bindings left by earlier calls and may declare any of those names again with any keyword. A new declaration applies to this and later calls; functions and still-running code from earlier calls keep the values they captured. Assigning to an earlier name without declaring it, even one declared with const, changes only the copy seen by this and later calls. A let, const, or class declaration cannot read the earlier value of its own name, so let total = total + 1 throws; assign to the name or use a new name instead. A var declaration of an earlier name starts from the earlier value. var declarations become top-level names of the call even inside blocks; other declarations inside blocks stay in their block. Assignments that earlier code makes later, such as from timers, are not visible to later calls; keep shared mutable state in objects. If a call fails before a let, const, class, or var declaration of an existing name finishes, later calls keep that name's earlier value. Use await import(...) for modules; require is unavailable, and relative specifiers resolve from the working directory of this environment's first call. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before returning; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before returning; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -49,7 +49,7 @@
|
||||
{
|
||||
"name": "cua_reset",
|
||||
"title": "Reset computer use program state",
|
||||
"description": "Discard the program environment of this connection: every variable, import, and application or window object held by earlier cua_run_code calls. A running cua_run_code program is cancelled. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment. Use it when a declaration conflicts with an earlier call or the environment has become unusable.",
|
||||
"description": "Discard the program environment of this connection: every variable, import, and application or window object held by earlier cua_run_code calls. A running cua_run_code program is cancelled. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment. Use it when the environment has become unusable or its retained state must not carry into the next task.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
PluginPackages, type Profile,
|
||||
} from '@deepseek-ai/dsh-app-boot'
|
||||
import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { runProfile } from '../src/profile-boot.ts'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { runProfile, userAgentProfile } from '../src/profile-boot.ts'
|
||||
|
||||
vi.mock('@deepseek-ai/dsh-app-boot', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@deepseek-ai/dsh-app-boot')>()
|
||||
@@ -25,6 +25,8 @@ vi.mock('@deepseek-ai/dsh-app-boot', async (importOriginal) => {
|
||||
vi.mock('@deepseek-ai/dsh-http-proxy', () => ({ installProxyFromEnvironment: vi.fn() }))
|
||||
|
||||
const homes: string[] = []
|
||||
// runProfile writes the suffix into process.env; stubbing first lets afterEach restore it.
|
||||
beforeEach(() => { vi.stubEnv('DSH_USER_AGENT_SUFFIX', undefined) })
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
@@ -173,3 +175,40 @@ describe('runProfile with an application-owned profile', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('profile User-Agent suffix', () => {
|
||||
it.each([
|
||||
['web', 'web'],
|
||||
['sdk-minimal', 'sdk-minimal'],
|
||||
['my web/v2', 'my%20web%2Fv2'],
|
||||
['工作', '%E5%B7%A5%E4%BD%9C'],
|
||||
['a(b)%', 'a%28b%29%25'],
|
||||
])('encodes %j as %j', (name, encoded) => {
|
||||
expect(userAgentProfile(name)).toBe(encoded)
|
||||
})
|
||||
|
||||
it('names the profile before any plugin loads', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'dsh-profile-user-agent-'))
|
||||
homes.push(home)
|
||||
mkdirSync(join(home, 'runtime'))
|
||||
writeFileSync(join(home, 'runtime/package.json'), '{"name":"test-runtime","version":"1.0.0"}')
|
||||
writeFileSync(join(home, 'package.json'), '{"name":"test-bundle","version":"1.0.0"}')
|
||||
vi.stubEnv('DSH_HOME', home)
|
||||
vi.spyOn(process, 'on').mockReturnValue(process)
|
||||
vi.mocked(installProxyFromEnvironment).mockResolvedValue(async () => {})
|
||||
const failure = new Error('stop after observing the environment')
|
||||
let seen: string | undefined
|
||||
vi.mocked(boot).mockImplementation(() => {
|
||||
seen = process.env.DSH_USER_AGENT_SUFFIX
|
||||
return Promise.reject(failure)
|
||||
})
|
||||
const profile: Profile = { skippedBundles: [],
|
||||
name: 'my web', dir: home, patchPath: join(home, 'cordis.patch.yml'), patches: [], layers: [],
|
||||
}
|
||||
await expect(runProfile({
|
||||
environment: createLaunchEnvironmentSnapshot([]), profile: 'my web', patchFiles: [], args: [],
|
||||
resolvedProfile: { profile, installAnchor: join(home, 'runtime/package.json') },
|
||||
})).rejects.toBe(failure)
|
||||
expect(seen).toBe('dsh-profile/my%20web')
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-desktop-host",
|
||||
"description": "Private Node-mode host process for the Electron desktop application",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-desktop",
|
||||
"description": "Electron desktop shell for a bundled dsh runtime and external plugins",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
|
||||
@@ -10,11 +10,12 @@ import { pnpmCommand } from '../../../scripts/release/process.ts'
|
||||
|
||||
const repository = resolve(import.meta.dirname, '../../..')
|
||||
const providerName = '@deepseek-ai/dsh-experimental-cua-macos'
|
||||
const windowsProvider = '@deepseek-ai/dsh-cua-windows'
|
||||
const bundleName = '@deepseek-ai/dsh-cua-bundle'
|
||||
const readManifest = async (path: string): Promise<Record<string, unknown>> =>
|
||||
JSON.parse(await readFile(join(repository, path, 'package.json'), 'utf8')) as Record<string, unknown>
|
||||
|
||||
it('fetches the macOS optional tarball only for Darwin, with an empty cache for every target', async () => {
|
||||
it('fetches the platform-declared CUA provider tarballs with an empty cache for every target', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'cua-cold-install-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const userconfig = join(root, 'npmrc')
|
||||
@@ -37,17 +38,22 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for
|
||||
const cli = await readManifest('apps/cli')
|
||||
const bundle = await readManifest('packages/experimental/cua-bundle')
|
||||
const native = await readManifest('packages/experimental/cua-macos')
|
||||
const windows = await readManifest('packages/experimental/cua-windows')
|
||||
expect(cli.dependencies).toHaveProperty(bundleName)
|
||||
expect(bundle.dependencies).not.toHaveProperty(providerName)
|
||||
expect(bundle.optionalDependencies).toEqual({ [providerName]: 'workspace:*' })
|
||||
expect(bundle.dependencies).not.toHaveProperty(windowsProvider)
|
||||
expect(bundle.optionalDependencies).toEqual({ [providerName]: 'workspace:*', [windowsProvider]: 'workspace:*' })
|
||||
expect(windows.os).toEqual(['win32', 'linux'])
|
||||
expect(native.os).toEqual(['darwin'])
|
||||
const version = '1.0.0'
|
||||
const bundleDependencies = Object.fromEntries(Object.keys(bundle.dependencies as Record<string, string>).map(name => [name, version]))
|
||||
const manifests = [
|
||||
{ name: cli.name, version, dependencies: { [bundleName]: version } },
|
||||
{ name: bundleName, version, dependencies: bundleDependencies, optionalDependencies: { [providerName]: version } },
|
||||
{ name: bundleName, version, dependencies: bundleDependencies,
|
||||
optionalDependencies: { [providerName]: version, [windowsProvider]: version } },
|
||||
...Object.keys(bundleDependencies).map(name => ({ name, version })),
|
||||
{ name: providerName, version, os: native.os, files: native.files },
|
||||
{ name: windowsProvider, version, os: windows.os, files: windows.files },
|
||||
]
|
||||
const generation = 'a'.repeat(64)
|
||||
const nativePayload = `native/bin/darwin-arm64/${generation}/DSH Computer Use.app/Contents/MacOS/dsh-cua-native`
|
||||
@@ -121,5 +127,7 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for
|
||||
expect(requests).toContain('/@deepseek-ai/dsh-cua.tgz')
|
||||
expect(requests.includes(`/${providerName}.tgz`), `${target}: ${JSON.stringify(requests)}\n${output}`)
|
||||
.toBe(target === 'darwin' || unrestricted)
|
||||
expect(requests.includes(`/${windowsProvider}.tgz`), `${target}: ${JSON.stringify(requests)}\n${output}`)
|
||||
.toBe(target !== 'darwin')
|
||||
}
|
||||
}, 120_000)
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-plugin-market-generator",
|
||||
"description": "Reference generator of plugin market index files from a list of npm packages and Git repositories",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-web-frontend",
|
||||
"description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -21,7 +21,7 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
|
||||
await writeFile(join(root, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: {
|
||||
patch: './cordis.patch.yml', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'],
|
||||
} } }))
|
||||
await writeFile(join(root, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: persistent-in-memory\n')
|
||||
await writeFile(join(root, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: persistent-in-memory\n replScoped: false\n')
|
||||
const scaffold = owned.scaffold = await launchWebScaffold({ profile: { packages: [{ dir: root }] } })
|
||||
const browser = owned.browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
|
||||
@@ -44,8 +44,9 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
|
||||
const names = [name]
|
||||
await page.locator('[data-plugin-panel]').getByRole('button', { name: '更多', exact: true }).click()
|
||||
const cua = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]')
|
||||
expect(await cua.count()).toBe(process.platform === 'darwin' ? 1 : 0)
|
||||
if (process.platform !== 'darwin') {
|
||||
const cuaSupported = process.platform === 'darwin' || process.platform === 'win32'
|
||||
expect(await cua.count()).toBe(cuaSupported ? 1 : 0)
|
||||
if (!cuaSupported) {
|
||||
expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
|
||||
.toMatchObject({ listedByDefault: false, enabled: false, error: { code: 'unsupported-platform' } })
|
||||
names.push('@deepseek-ai/dsh-cua-bundle')
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
webSnapshotMode,
|
||||
type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { conversationContextKey, expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
import { conversationContextKey, expandOwningTurnProcess, loadEarlierChatPage, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
|
||||
const MODE = webSnapshotMode()
|
||||
const SESSION_ID = 'chat-long-interactions-e2e'
|
||||
@@ -219,10 +219,9 @@ describe('web e2e: long Chat interaction contract', () => {
|
||||
))
|
||||
expect(await markPitch()).toBe(10)
|
||||
|
||||
const loadEarlier = page.getByRole('button', { name: 'Load earlier', exact: true })
|
||||
const loadedRows = page.locator('[data-chat-flow-key]')
|
||||
const loadedBefore = await loadedRows.count()
|
||||
await loadEarlier.click()
|
||||
await loadEarlierChatPage(page)
|
||||
await expect.poll(() => loadedRows.count(), { timeout: 15_000 }).toBeGreaterThan(loadedBefore)
|
||||
await railScroller.hover()
|
||||
await page.mouse.wheel(0, -FIXTURE_TURNS * 10)
|
||||
|
||||
@@ -13,7 +13,7 @@ import { expect, it, vi } from 'vitest'
|
||||
import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode, type WebScaffold } from './scaffold.ts'
|
||||
import { connectFreshWorkspaceZh, ZH_BROWSER_LOCALE } from './support.ts'
|
||||
|
||||
// The shipped bundle admits only macOS Hosts; unsupported Hosts are exercised in bundle-platform.e2e.ts.
|
||||
// This fixture exercises the macOS provider’s permission setup.
|
||||
it.skipIf(process.platform !== 'darwin').each([
|
||||
{ selectedDefault: undefined, codingTools: false, script: false },
|
||||
{ selectedDefault: undefined, codingTools: true, script: false },
|
||||
@@ -111,7 +111,7 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
expect(await card.getByText('实验性', { exact: true }).count()).toBe(1)
|
||||
expect(await card.textContent()).not.toContain('将 PTC 模式改为可持久化')
|
||||
expect(await card.textContent()).not.toContain('请切换到 PTC 模式')
|
||||
expect(await card.textContent()).toContain('Windows 支持正在开发中')
|
||||
expect(await card.textContent()).toContain('通过 npm 安装 DSH 的 Windows 用户需要单独配置 helper')
|
||||
expect(await card.textContent()).not.toContain('Swift')
|
||||
const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => {
|
||||
const element = document.getElementById(button.getAttribute('aria-describedby')!)!
|
||||
@@ -174,6 +174,7 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
expect(scaffold.ctx.agentPresets.composedPreset(fresh.ctx)).toBe('ptc')
|
||||
expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true)
|
||||
await card.getByRole('button', { name: '查看 Computer Use', exact: true }).click()
|
||||
await plugins.locator('[data-detail-document]').getByText('helperPath', { exact: true }).waitFor()
|
||||
toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true })
|
||||
const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true })
|
||||
if (!codingTools) {
|
||||
@@ -200,12 +201,13 @@ it.skipIf(process.platform !== 'darwin').each([
|
||||
const beforePersistent = scaffold.ctx.ptcRuntime
|
||||
await persistent.getByRole('button', { name: '设为持久化', exact: true }).click()
|
||||
await persistent.getByRole('button', { name: '已设为持久化', exact: true }).waitFor()
|
||||
expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'repl')
|
||||
expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'scoped-repl')
|
||||
expect(scaffold.ctx.ptcRuntime.retainsState).toBe(true)
|
||||
expect(scaffold.ctx.ptcRuntime === beforePersistent).toBe(false)
|
||||
saved = await readFile(settingsPath, 'utf8')
|
||||
expect(saved).toContain(`executionMode: ${script ? 'vm-script' : 'persistent-in-memory'}`)
|
||||
expect(saved).toContain(`scriptPersistence: ${script}`)
|
||||
expect(saved).toContain(`replScoped: ${!script}`)
|
||||
const runtime = scaffold.ctx.ptcRuntime
|
||||
const persistentRuntimeFiber = runtimeFiber()
|
||||
const owner = {}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 6" [checked]
|
||||
- radio "接口 1"
|
||||
- radio "实现 2"
|
||||
- radio "测试 3"
|
||||
- button "全部 6 个文件"
|
||||
- switch "隐藏测试文件"
|
||||
- button "筛选透镜": 透镜
|
||||
- button "笔记 2" [pressed]
|
||||
- progressbar "已审阅的文件": 已审阅 0 / 6
|
||||
- text: +8 −2
|
||||
- button "刷新变更"
|
||||
- button "全部折叠"
|
||||
- button "左右对比" [pressed]
|
||||
- button "自动换行" [pressed]
|
||||
- button "将文件树移到右侧" [expanded]
|
||||
- region "全部 6 个文件":
|
||||
- button "收起 panel.md" [expanded]
|
||||
- text: docs/panel.md 新文件 +2 −0
|
||||
- checkbox "将 panel.md 标记为已审阅"
|
||||
- button "panel.md 的更多操作"
|
||||
- strong: 笔记
|
||||
- text: 已看过此文件
|
||||
- button "移除"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ # Panel"
|
||||
- button "选择第 R2 行": "2"
|
||||
- text: + Shows the change requests of a Session.
|
||||
- button "收起 schema.json" [expanded]
|
||||
- text: docs/schema.json 新文件 +1 −0
|
||||
- checkbox "将 schema.json 标记为已审阅"
|
||||
- button "schema.json 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ { \"type\": \"object\" }"
|
||||
- button "收起 zh.json" [expanded]
|
||||
- text: locale/zh.json 新文件 +1 −0
|
||||
- checkbox "将 zh.json 标记为已审阅"
|
||||
- button "zh.json 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ { \"title\": \"面板\" }"
|
||||
- button "收起 panel.spec.ts" [expanded]
|
||||
- text: src/panel.spec.ts 新文件 +1 −0
|
||||
- checkbox "将 panel.spec.ts 标记为已审阅"
|
||||
- button "panel.spec.ts 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ it('shows the panel', () => {})"
|
||||
- button "收起 panel.ts" [expanded]
|
||||
- text: src/panel.ts +2 −2
|
||||
- checkbox "将 panel.ts 标记为已审阅"
|
||||
- button "panel.ts 的更多操作"
|
||||
- button "选择第 L1 行": "1"
|
||||
- text: export const n1 = 1
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: export const n1 = 1
|
||||
- button "选择第 L2 行": "2"
|
||||
- text: export const n2 = 2
|
||||
- button "选择第 R2 行": "2"
|
||||
- text: export const n2 = 'two'
|
||||
- strong: 笔记
|
||||
- text: Check the quoted value
|
||||
- button "移除"
|
||||
- button "选择第 L3 行": "3"
|
||||
- text: export const n3 = 3
|
||||
- button "选择第 R3 行": "3"
|
||||
- text: export const n3 = 3
|
||||
- button "选择第 L4 行": "4"
|
||||
- text: export const n4 = 4
|
||||
- button "选择第 R4 行": "4"
|
||||
- text: export const n4 = 4
|
||||
- button "选择第 L5 行": "5"
|
||||
- text: export const n5 = 5
|
||||
- button "选择第 R5 行": "5"
|
||||
- text: export const n5 = 5
|
||||
- button "6 行未变更"
|
||||
- button "选择第 L12 行": "12"
|
||||
- text: export const n12 = 12
|
||||
- button "选择第 R12 行": "12"
|
||||
- text: export const n12 = 12
|
||||
- button "选择第 L13 行": "13"
|
||||
- text: export const n13 = 13
|
||||
- button "选择第 R13 行": "13"
|
||||
- text: export const n13 = 13
|
||||
- button "选择第 L14 行": "14"
|
||||
- text: export const n14 = 14
|
||||
- button "选择第 R14 行": "14"
|
||||
- text: export const n14 = 14
|
||||
- button "选择第 L15 行": "15"
|
||||
- text: export const n15 = 15
|
||||
- button "选择第 R15 行": "15"
|
||||
- text: export const n15 = 'fifteen'
|
||||
- button "选择第 L16 行": "16"
|
||||
- text: export const n16 = 16
|
||||
- button "选择第 R16 行": "16"
|
||||
- text: export const n16 = 16
|
||||
- button "选择第 L17 行": "17"
|
||||
- text: export const n17 = 17
|
||||
- button "选择第 R17 行": "17"
|
||||
- text: export const n17 = 17
|
||||
- button "选择第 L18 行": "18"
|
||||
- text: export const n18 = 18
|
||||
- button "选择第 R18 行": "18"
|
||||
- text: export const n18 = 18
|
||||
- button "其余未变更的行"
|
||||
- button "收起 package.json" [expanded]
|
||||
- text: package.json 新文件 +1 −0
|
||||
- checkbox "将 package.json 标记为已审阅"
|
||||
- button "package.json 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ { \"name\": \"demo\" }"
|
||||
- separator "调整文件树宽度"
|
||||
- navigation "全部 6 个文件":
|
||||
- textbox "筛选文件…"
|
||||
- button "docs" [expanded]
|
||||
- button "docs/panel.md": panel.md +2 −0
|
||||
- button "docs/schema.json": schema.json +1 −0
|
||||
- button "locale" [expanded]
|
||||
- button "locale/zh.json": zh.json +1 −0
|
||||
- button "src" [expanded]
|
||||
- button "src/panel.spec.ts": panel.spec.ts +1 −0
|
||||
- button "src/panel.ts": panel.ts +2 −2
|
||||
- button "package.json": package.json +1 −0
|
||||
@@ -0,0 +1,81 @@
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 1" [checked]
|
||||
- radio "接口 0"
|
||||
- radio "实现 1"
|
||||
- radio "测试 0"
|
||||
- button "全部 1 个文件"
|
||||
- switch "隐藏测试文件"
|
||||
- button "筛选透镜:导出": 导出 1
|
||||
- button "笔记 0" [pressed]
|
||||
- progressbar "已审阅的文件": 已审阅 0 / 1
|
||||
- text: +2 −2
|
||||
- button "刷新变更"
|
||||
- button "全部折叠"
|
||||
- button "左右对比" [pressed]
|
||||
- button "自动换行" [pressed]
|
||||
- button "将文件树移到右侧" [expanded]
|
||||
- region "全部 1 个文件":
|
||||
- button "收起 panel.ts" [expanded]
|
||||
- text: src/panel.ts +2 −2
|
||||
- checkbox "将 panel.ts 标记为已审阅"
|
||||
- button "panel.ts 的更多操作"
|
||||
- button "选择第 L1 行": "1"
|
||||
- text: export const n1 = 1
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: export const n1 = 1
|
||||
- button "选择第 L2 行": "2"
|
||||
- text: export const n2 = 2
|
||||
- button "选择第 R2 行": "2"
|
||||
- text: export const n2 = 'two'
|
||||
- button "选择第 L3 行": "3"
|
||||
- text: export const n3 = 3
|
||||
- button "选择第 R3 行": "3"
|
||||
- text: export const n3 = 3
|
||||
- button "选择第 L4 行": "4"
|
||||
- text: export const n4 = 4
|
||||
- button "选择第 R4 行": "4"
|
||||
- text: export const n4 = 4
|
||||
- button "选择第 L5 行": "5"
|
||||
- text: export const n5 = 5
|
||||
- button "选择第 R5 行": "5"
|
||||
- text: export const n5 = 5
|
||||
- button "6 行未变更"
|
||||
- button "选择第 L12 行": "12"
|
||||
- text: export const n12 = 12
|
||||
- button "选择第 R12 行": "12"
|
||||
- text: export const n12 = 12
|
||||
- button "选择第 L13 行": "13"
|
||||
- text: export const n13 = 13
|
||||
- button "选择第 R13 行": "13"
|
||||
- text: export const n13 = 13
|
||||
- button "选择第 L14 行": "14"
|
||||
- text: export const n14 = 14
|
||||
- button "选择第 R14 行": "14"
|
||||
- text: export const n14 = 14
|
||||
- button "选择第 L15 行": "15"
|
||||
- text: export const n15 = 15
|
||||
- button "选择第 R15 行": "15"
|
||||
- text: export const n15 = 'fifteen'
|
||||
- button "选择第 L16 行": "16"
|
||||
- text: export const n16 = 16
|
||||
- button "选择第 R16 行": "16"
|
||||
- text: export const n16 = 16
|
||||
- button "选择第 L17 行": "17"
|
||||
- text: export const n17 = 17
|
||||
- button "选择第 R17 行": "17"
|
||||
- text: export const n17 = 17
|
||||
- button "选择第 L18 行": "18"
|
||||
- text: export const n18 = 18
|
||||
- button "选择第 R18 行": "18"
|
||||
- text: export const n18 = 18
|
||||
- button "其余未变更的行"
|
||||
- separator "调整文件树宽度"
|
||||
- navigation "全部 1 个文件":
|
||||
- textbox "筛选文件…"
|
||||
- button "src" [expanded]
|
||||
- button "src/panel.ts": panel.ts +2 −2
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Client half of the forge extension fixture: the title of the Host lens, and notes pinned through every forge slot —
|
||||
* a comment form action pins a line note, a file menu row pins a file note, each note shows as a line annotation, a
|
||||
* toolbar toggle hides them, and a card button opens the change request's changes view with the lens chosen.
|
||||
*/
|
||||
window.__ModuleLoader__.load({
|
||||
id: '@fixture/forge-extension',
|
||||
factory(require) {
|
||||
const React = require('react')
|
||||
const { Button, MenuItemButton, Tooltip } = require('@deepseek-ai/dsh-client-ui-primitives')
|
||||
const h = React.createElement
|
||||
const NS = 'fixtureForge'
|
||||
return {
|
||||
inject: ['slots', 'locale', 'forgeChanges'],
|
||||
apply(ctx) {
|
||||
ctx.effect(() => ctx.locale.register(NS, {
|
||||
zh: {
|
||||
lens: '导出', pin: '钉为笔记', pinFile: '钉上文件笔记', fileNote: '已看过此文件', notes: '笔记 {count}', toggle: '显示或隐藏笔记',
|
||||
note: '笔记', remove: '移除', open: '打开导出视图',
|
||||
},
|
||||
en: {
|
||||
lens: 'Exports', pin: 'Pin as note', pinFile: 'Pin a file note', fileNote: 'Looked at this file', notes: 'Notes {count}',
|
||||
toggle: 'Show or hide notes', note: 'Note', remove: 'Remove', open: 'Open the exports view',
|
||||
},
|
||||
}))
|
||||
const t = ctx.locale.bind(NS)
|
||||
ctx.effect(() => ctx.forgeChanges.describeLens({ id: 'fixture/exports', title: () => t('lens') }))
|
||||
|
||||
// Notes of each changes view by address; the observable a view reads publishes nothing while its notes hide.
|
||||
const views = new Map()
|
||||
let sequence = 0
|
||||
const viewOf = (target) => {
|
||||
const address = ctx.forgeChanges.address(target)
|
||||
let view = views.get(address)
|
||||
if (view === undefined) {
|
||||
const listeners = new Set()
|
||||
const state = { notes: [], shown: true, snapshot: new Map() }
|
||||
const publish = () => {
|
||||
const byPath = new Map()
|
||||
if (state.shown) {
|
||||
for (const note of state.notes) byPath.set(note.path, [...(byPath.get(note.path) ?? []), note.annotation])
|
||||
}
|
||||
state.snapshot = byPath
|
||||
for (const listener of [...listeners]) listener()
|
||||
}
|
||||
view = {
|
||||
state,
|
||||
observable: {
|
||||
getSnapshot: () => state.snapshot,
|
||||
subscribe: (listener) => { listeners.add(listener); return () => { listeners.delete(listener) } },
|
||||
},
|
||||
add(path, place, text) {
|
||||
sequence += 1
|
||||
state.notes = [...state.notes, { path, text, annotation: { key: `note-${sequence}`, place, version: 1 } }]
|
||||
publish()
|
||||
},
|
||||
remove(key) {
|
||||
state.notes = state.notes.filter(note => note.annotation.key !== key)
|
||||
publish()
|
||||
},
|
||||
toggle() {
|
||||
state.shown = !state.shown
|
||||
publish()
|
||||
},
|
||||
textOf: key => state.notes.find(note => note.annotation.key === key)?.text ?? '',
|
||||
listeners,
|
||||
}
|
||||
views.set(address, view)
|
||||
}
|
||||
return view
|
||||
}
|
||||
ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'fixture-notes', observe: target => viewOf(target).observable }))
|
||||
|
||||
function useNotes(target) {
|
||||
const view = viewOf(target)
|
||||
React.useSyncExternalStore(view.observable.subscribe, view.observable.getSnapshot)
|
||||
return view
|
||||
}
|
||||
function NotesToggle({ target, form, close }) {
|
||||
const view = useNotes(target)
|
||||
const label = t('notes', { count: view.state.notes.length })
|
||||
if (form === 'menu') return h(MenuItemButton, { onSelect: () => { view.toggle(); close() } }, label)
|
||||
return h(Tooltip, { label: t('toggle'), side: 'bottom' },
|
||||
h('button', { type: 'button', 'data-fixture-notes-toggle': '', 'aria-pressed': view.state.shown, onClick: () => { view.toggle() },
|
||||
style: { height: 28, padding: '0 8px', border: 0, borderRadius: 8, background: 'transparent', color: 'inherit', font: 'inherit', cursor: 'pointer' } }, label))
|
||||
}
|
||||
function PinNote({ target, selection, empty, busy, send }) {
|
||||
return h(Button, { size: 'sm', variant: 'outline', disabled: empty || busy, 'data-fixture-pin': '',
|
||||
onClick: () => { send(async (body) => { viewOf(target).add(selection.path, { side: selection.side, startLine: selection.startLine, endLine: selection.endLine }, body); return undefined }) } },
|
||||
t('pin'))
|
||||
}
|
||||
function NoteBody({ target, annotation }) {
|
||||
const view = useNotes(target)
|
||||
return h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px' }, 'data-fixture-note': annotation.key },
|
||||
h('strong', { style: { fontWeight: 500 } }, t('note')),
|
||||
h('span', { style: { flex: 1, minWidth: 0 } }, view.textOf(annotation.key)),
|
||||
h(Button, { size: 'sm', variant: 'outline', onClick: () => { view.remove(annotation.key) } }, t('remove')))
|
||||
}
|
||||
function PinFileNote({ target, file, dismiss }) {
|
||||
return h(MenuItemButton, { onSelect: () => { viewOf(target).add(file.path, 'file', t('fileNote')); dismiss() } }, t('pinFile'))
|
||||
}
|
||||
function OpenExports({ url, ref, sessionId }) {
|
||||
if (ref === null) return null
|
||||
return h(Tooltip, { label: t('open'), side: 'top' },
|
||||
h('button', { type: 'button', 'aria-label': t('open'), 'data-fixture-open-exports': '',
|
||||
onClick: () => { ctx.forgeChanges.open({ sessionId, source: { kind: 'change', url } }, { lens: 'fixture/exports' }) },
|
||||
style: { width: 24, height: 24, border: 0, borderRadius: 6, background: 'transparent', color: 'inherit', cursor: 'pointer' } }, '⎇'))
|
||||
}
|
||||
ctx.slots.inject('forge.changes.toolbar', () => ctx.slots.register({ name: 'forge.changes.toolbar', id: 'fixture-notes', locale: NS }, NotesToggle))
|
||||
ctx.slots.inject('forge.diff.comment.actions', () => ctx.slots.register({ name: 'forge.diff.comment.actions', id: 'fixture-notes', locale: NS }, PinNote))
|
||||
ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register({ name: 'forge.diff.line.annotation', key: 'fixture-notes', locale: NS }, NoteBody))
|
||||
ctx.slots.inject('forge.changes.file.menu', () => ctx.slots.register({ name: 'forge.changes.file.menu', id: 'fixture-notes', locale: NS }, PinFileNote))
|
||||
ctx.slots.inject('forge.change-request.card.actions', () => ctx.slots.register({ name: 'forge.change-request.card.actions', id: 'fixture-notes', locale: NS }, OpenExports))
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
- insert:
|
||||
- id: fixture-forge-extension
|
||||
name: '@fixture/forge-extension'
|
||||
@@ -0,0 +1,27 @@
|
||||
/** Host half of the forge extension fixture: a filter lens that keeps the files whose new side has `export` lines, about those lines. */
|
||||
export const name = '@fixture/forge-extension'
|
||||
export const inject = ['forgePanel']
|
||||
|
||||
/** @param {import('@deepseek-ai/cordis').Context} ctx */
|
||||
export function apply(ctx) {
|
||||
ctx.forgePanel.registerLens({
|
||||
id: 'fixture/exports',
|
||||
version: '1',
|
||||
async classify(input, signal) {
|
||||
const files = {}
|
||||
let done = 0
|
||||
for (const file of input.files) {
|
||||
const text = await input.text('new', file.path, signal)
|
||||
done += 1
|
||||
input.progress(done, input.files.length)
|
||||
if (text === null) continue
|
||||
const ranges = []
|
||||
text.split('\n').forEach((line, index) => {
|
||||
if (/^export\b/.test(line)) ranges.push({ start: index + 1, end: index + 1 })
|
||||
})
|
||||
if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } }
|
||||
}
|
||||
return { files }
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@fixture/forge-extension",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./client": "./client.js"
|
||||
},
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-experimental-client-ui-forge"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ declare global {
|
||||
}
|
||||
|
||||
const BUNDLE = fileURLToPath(new URL('../../../packages/experimental/forge-bundle', import.meta.url))
|
||||
/** A plugin that uses the forge extension API: a Host lens, line annotations, and every forge slot. */
|
||||
const EXTENSION = fileURLToPath(new URL('./fixtures/plugins/fixture-forge-extension', import.meta.url))
|
||||
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome/session.v4.jsonl', import.meta.url))
|
||||
const EXPECTED = fileURLToPath(new URL('./expected/forge-panel', import.meta.url))
|
||||
const MODE = webSnapshotMode()
|
||||
@@ -471,11 +473,19 @@ interface PanelLaunch {
|
||||
* Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace.
|
||||
* @param failureShot - name of the screenshot saved when the test fails.
|
||||
* @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup.
|
||||
* @param options - desktop transport, checkout branch, browser input, sandbox runner availability, and diff output limit.
|
||||
* @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit, and
|
||||
* whether the extension fixture plugin loads.
|
||||
* @returns the scaffold, page, and checkout.
|
||||
*/
|
||||
async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' = 'normal',
|
||||
options: { desktop?: 'darwin' | 'win32'; branch?: string; hasTouch?: boolean; missingSandbox?: boolean; maxDiffBytes?: number } = {}): Promise<PanelLaunch> {
|
||||
options: {
|
||||
desktop?: 'darwin' | 'win32'
|
||||
branch?: string
|
||||
hasTouch?: boolean
|
||||
missingSandbox?: boolean
|
||||
maxDiffBytes?: number
|
||||
extension?: boolean
|
||||
} = {}): Promise<PanelLaunch> {
|
||||
const { desktop } = options
|
||||
const resources: { scaffold?: WebScaffold; browser?: Browser } = {}
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-forge-panel-'))
|
||||
@@ -513,7 +523,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
|
||||
] }))
|
||||
}
|
||||
const scaffold = await launchWebScaffold({
|
||||
profile: { packages: [{ dir: BUNDLE, enabled: true }] },
|
||||
profile: { packages: [{ dir: BUNDLE, enabled: true }, ...options.extension === true ? [{ dir: EXTENSION, enabled: true }] : []] },
|
||||
extraOverlayPath: overlay,
|
||||
replayFixture: FIXTURE,
|
||||
...scenario !== 'normal' ? { replayOverride: override } : {},
|
||||
@@ -1915,6 +1925,65 @@ async function shownPaths(view: ReturnType<Page['locator']>): Promise<(string |
|
||||
return await view.locator('[data-forge-diff-file]').evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file')))
|
||||
}
|
||||
|
||||
it.skipIf(MODE === 'record')('lets a plugin filter the changes by its lens, annotate lines and files, and act from the toolbar, comment form, and card', async () => {
|
||||
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-extension', 'normal', { extension: true })
|
||||
await writeReviewFixture(root)
|
||||
// The plugin's lens keeps the export lines; past line 9 the head's src/panel.ts has none, so its second hunk folds.
|
||||
const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record<string, string>
|
||||
contents[`src/panel.ts@${HEAD7}`] = `${Array.from({ length: 20 }, (_, index) => index < 9 ? panelLine(index + 1, 'new')
|
||||
: panelLine(index + 1, 'new').replace(/^export /, '')).join('\n')}\n`
|
||||
await writeFile(join(root, 'contents.json'), JSON.stringify(contents))
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
const session = scaffold.ctx.sessions.get(await settled)
|
||||
if (session === undefined) throw new Error('Session must stay loaded')
|
||||
scaffold.ctx.forgeSession.track(session, PULL)
|
||||
await page.locator('[data-forge-header]').click()
|
||||
|
||||
// The card button the plugin adds opens the changes view with its lens chosen.
|
||||
await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '打开导出视图', exact: true }).click()
|
||||
await page.getByRole('button', { name: '全屏', exact: true }).click()
|
||||
const view = page.locator('[data-forge-changes="change"]')
|
||||
const lens = view.locator('[data-forge-filter-lens]')
|
||||
await expect.poll(() => lens.getAttribute('data-forge-filter-lens'), { timeout: 20_000 }).toBe('fixture/exports')
|
||||
await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['src/panel.ts'])
|
||||
await expect.poll(() => lens.textContent()).toBe('导出1')
|
||||
const panel = view.locator('[data-forge-diff-file="src/panel.ts"]')
|
||||
const fold = panel.locator('[data-forge-lens-fold]')
|
||||
await expect.poll(() => fold.textContent()).toBe('另有 1 处与「导出」无关的改动已折叠展开')
|
||||
await fold.click()
|
||||
await expect.poll(() => fold.count()).toBe(0)
|
||||
await panel.locator('[data-review-code][data-new-line="15"]').waitFor()
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'extension-lens.expected.md'),
|
||||
await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE)
|
||||
|
||||
await lens.click()
|
||||
await page.getByRole('menuitem', { name: '不使用透镜', exact: true }).click()
|
||||
await expect.poll(() => shownPaths(view)).toHaveLength(6)
|
||||
|
||||
// The comment form's plugin button pins the comment as a line note; the toolbar toggle hides and shows the notes.
|
||||
await panel.getByRole('button', { name: '选择第 R2 行', exact: true }).click()
|
||||
await panel.getByRole('button', { name: '添加评论', exact: true }).click()
|
||||
await panel.getByRole('textbox', { name: '留下评论…', exact: true }).fill('Check the quoted value')
|
||||
await panel.getByRole('button', { name: '钉为笔记', exact: true }).click()
|
||||
const note = panel.locator('[data-forge-annotation^="fixture-notes/"]')
|
||||
await expect.poll(() => note.textContent()).toBe('笔记Check the quoted value移除')
|
||||
const toggle = view.locator('[data-fixture-notes-toggle]')
|
||||
await expect.poll(() => toggle.textContent()).toBe('笔记 1')
|
||||
await toggle.click()
|
||||
await expect.poll(() => note.count()).toBe(0)
|
||||
await toggle.click()
|
||||
await expect.poll(() => note.count()).toBe(1)
|
||||
|
||||
// The file menu's plugin row pins a note on the whole file.
|
||||
const docs = view.locator('[data-forge-diff-file="docs/panel.md"]')
|
||||
await docs.getByRole('button', { name: 'panel.md 的更多操作', exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: '钉上文件笔记', exact: true }).click()
|
||||
await expect.poll(() => docs.locator('[data-forge-annotation^="fixture-notes/"]').textContent()).toBe('笔记已看过此文件移除')
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'extension-annotations.expected.md'),
|
||||
await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('reviews a change request by layer, hides test files, marks files viewed, and views chosen commits', async () => {
|
||||
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-layers')
|
||||
await writeReviewFixture(root)
|
||||
|
||||
@@ -125,6 +125,36 @@ describe('web e2e: CJK-adjacent Markdown strong emphasis', () => {
|
||||
expect(await page.getByText(paragraph, { exact: true }).count()).toBe(1)
|
||||
}
|
||||
|
||||
const viewport = page.viewportSize()!
|
||||
try {
|
||||
for (const size of [{ width: 390, height: 844 }, { width: 951, height: 669 }, { width: 669, height: 951 }]) {
|
||||
await page.setViewportSize(size)
|
||||
expect(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('-webkit-text-size-adjust')))
|
||||
.toBe('100%')
|
||||
expect(await strong.evaluateAll(elements => elements.map(element => getComputedStyle(element).fontSize)))
|
||||
.toEqual(CASES.map(() => '14px'))
|
||||
}
|
||||
const restoreFont = await page.evaluateHandle(() => {
|
||||
const style = document.body.style
|
||||
const before = style.getPropertyValue('--dsh-content-font-size')
|
||||
const priority = style.getPropertyPriority('--dsh-content-font-size')
|
||||
style.setProperty('--dsh-content-font-size', '18px')
|
||||
return () => {
|
||||
if (before) style.setProperty('--dsh-content-font-size', before, priority)
|
||||
else style.removeProperty('--dsh-content-font-size')
|
||||
}
|
||||
})
|
||||
try {
|
||||
expect(await strong.evaluateAll(elements => elements.map(element => getComputedStyle(element).fontSize)))
|
||||
.toEqual(CASES.map(() => '18px'))
|
||||
} finally {
|
||||
await restoreFont.evaluate((restore) => { restore() })
|
||||
await restoreFont.dispose()
|
||||
}
|
||||
} finally {
|
||||
await page.setViewportSize(viewport)
|
||||
}
|
||||
|
||||
const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
|
||||
.split(SEED_ID).join('{{seededId}}')
|
||||
await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
webSnapshotMode,
|
||||
type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
import { expandOwningTurnProcess, loadEarlierChatPage, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
|
||||
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/minimal-preset', import.meta.url))
|
||||
const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl')
|
||||
@@ -485,7 +485,7 @@ describe('minimal image reading', () => {
|
||||
page = await openSession(pagedId)
|
||||
await page.getByText('Later image-history message 53', { exact: true }).waitFor()
|
||||
expect(await page.locator('[data-tool="read_image"]').count()).toBe(0)
|
||||
await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
|
||||
await loadEarlierChatPage(page)
|
||||
card = await imageCard(page)
|
||||
await expect.poll(() => card.locator('img').first().evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1)
|
||||
|
||||
|
||||
@@ -857,7 +857,7 @@ describe('web e2e: plugin manager', () => {
|
||||
&& bundle.name !== '@deepseek-ai/dsh-experimental-liveshare'
|
||||
&& bundle.official && (bundle.listedByDefault !== false || bundle.enabled || bundle.installed)).length)
|
||||
// Computer Use ships with the installation and is listed only on the macOS Hosts it supports.
|
||||
const cuaSupported = process.platform === 'darwin'
|
||||
const cuaSupported = process.platform === 'darwin' || process.platform === 'win32'
|
||||
expect(bundles.find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
|
||||
.toMatchObject({ enabled: false, optional: true, availability: 'installation', ...cuaSupported ? {} : { listedByDefault: false } })
|
||||
expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count())
|
||||
|
||||
@@ -233,6 +233,17 @@ export async function scrollIntoView(target: Locator): Promise<void> {
|
||||
}), { timeout: 10_000 }).toBe(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request one earlier page without scrolling the transcript to its automatic pagination threshold.
|
||||
* @param page - Page showing the English Chat history control.
|
||||
*/
|
||||
export async function loadEarlierChatPage(page: Page): Promise<void> {
|
||||
await page.getByRole('button', { name: 'Load earlier', exact: true }).evaluate((button) => {
|
||||
button.focus({ preventScroll: true })
|
||||
})
|
||||
await page.keyboard.press('Enter')
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand every eligible Turn process and secondary group so a Tool-focused
|
||||
* scenario can exercise the original row contract beneath product-default
|
||||
|
||||
+38
-5
@@ -915,6 +915,26 @@ export type ConsentMode = 'allow' | 'elicit'
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-mcp -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-cua-windows -->
|
||||
<a id="deepseek-aidsh-cua-windows"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-cua-windows`
|
||||
|
||||
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
|
||||
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
|
||||
- `source`: [`packages/experimental/cua-windows/src/index.ts:32`](../packages/experimental/cua-windows/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Windows native waiting policy, alongside shared CUA resource limits. */
|
||||
export interface Config extends CuaConfig {
|
||||
/** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */
|
||||
windowsPowerShellPath: string
|
||||
/** Milliseconds between application-readiness and clipboard-release observations. */
|
||||
pollIntervalMs: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-windows -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
|
||||
<a id="deepseek-aidsh-deepseek-account"></a>
|
||||
|
||||
@@ -1110,7 +1130,7 @@ export interface CotTranslationPreferences {
|
||||
## `@deepseek-ai/dsh-experimental-client-ui-forge`
|
||||
|
||||
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:483`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
@@ -1157,6 +1177,14 @@ export interface Config {
|
||||
* request's update time does not change when a thread is resolved.
|
||||
*/
|
||||
reviewRefreshMs?: number
|
||||
/** Deadline in milliseconds for one lens `classify` call. */
|
||||
lensTimeoutMs?: number
|
||||
/** Most UTF-8 bytes of file text one lens `classify` call may read. */
|
||||
maxLensReadBytes?: number
|
||||
/** Most UTF-8 bytes, as JSON, of lens results kept in memory for later requests with the same files, lens, and lens version. */
|
||||
maxCachedLensBytes?: number
|
||||
/** Most line annotations a changes view shows in one file, across every annotation source. */
|
||||
maxAnnotationsPerFile?: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
|
||||
@@ -1222,7 +1250,7 @@ export type SourceSigning = 'ad-hoc' | {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
@@ -1635,7 +1663,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-file-reference-local`
|
||||
|
||||
- `inject`: `agents` · `workingDirectory`
|
||||
- `source`: [`packages/context/file-reference-local/src/index.ts:35`](../packages/context/file-reference-local/src/index.ts)
|
||||
- `source`: [`packages/context/file-reference-local/src/index.ts:27`](../packages/context/file-reference-local/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Local file-reference discovery configuration. */
|
||||
@@ -2434,7 +2462,7 @@ export type Config = Readonly<Record<string, never>>
|
||||
## `@deepseek-ai/dsh-lsp-stdio`
|
||||
|
||||
- `inject`: `fs` · `lsp` · `subprocess`
|
||||
- `source`: [`packages/lsp/lsp-stdio/src/index.ts:83`](../packages/lsp/lsp-stdio/src/index.ts)
|
||||
- `source`: [`packages/lsp/lsp-stdio/src/index.ts:70`](../packages/lsp/lsp-stdio/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Plugin configuration: provider id → local language-server configuration. */
|
||||
@@ -2887,7 +2915,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-ptc-runtime-node`
|
||||
|
||||
- `inject`: `fs` · `subprocess` · `sandbox` · `sandboxPolicy`
|
||||
- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:7`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts)
|
||||
- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:8`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment-varying runtime bounds and launch choices. */
|
||||
@@ -2898,6 +2926,11 @@ export interface Config {
|
||||
executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script'
|
||||
/** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */
|
||||
scriptPersistence?: boolean
|
||||
/**
|
||||
* Run persistent-in-memory programs as scoped REPL statements whose later calls receive copies of earlier top-level bindings;
|
||||
* omitted, it is `SCOPED_REPL_BY_DEFAULT` from configuration.ts, currently true, with persistent-in-memory and false otherwise.
|
||||
*/
|
||||
replScoped?: boolean
|
||||
/** Default elapsed deadline, including nested tool and approval waits. */
|
||||
timeoutMs?: number
|
||||
/** Maximum numeric elapsed budget accepted by resolve. */
|
||||
|
||||
@@ -917,6 +917,26 @@ export type ConsentMode = 'allow' | 'elicit'
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-mcp -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-cua-windows -->
|
||||
<a id="deepseek-aidsh-cua-windows"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-cua-windows`
|
||||
|
||||
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
|
||||
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
|
||||
- `source`: [`packages/experimental/cua-windows/src/index.ts:32`](../packages/experimental/cua-windows/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Windows native waiting policy, alongside shared CUA resource limits. */
|
||||
export interface Config extends CuaConfig {
|
||||
/** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */
|
||||
windowsPowerShellPath: string
|
||||
/** Milliseconds between application-readiness and clipboard-release observations. */
|
||||
pollIntervalMs: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-windows -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
|
||||
<a id="deepseek-aidsh-deepseek-account"></a>
|
||||
|
||||
@@ -1112,7 +1132,7 @@ export interface CotTranslationPreferences {
|
||||
## `@deepseek-ai/dsh-experimental-client-ui-forge`
|
||||
|
||||
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:483`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
@@ -1159,6 +1179,14 @@ export interface Config {
|
||||
* request's update time does not change when a thread is resolved.
|
||||
*/
|
||||
reviewRefreshMs?: number
|
||||
/** Deadline in milliseconds for one lens `classify` call. */
|
||||
lensTimeoutMs?: number
|
||||
/** Most UTF-8 bytes of file text one lens `classify` call may read. */
|
||||
maxLensReadBytes?: number
|
||||
/** Most UTF-8 bytes, as JSON, of lens results kept in memory for later requests with the same files, lens, and lens version. */
|
||||
maxCachedLensBytes?: number
|
||||
/** Most line annotations a changes view shows in one file, across every annotation source. */
|
||||
maxAnnotationsPerFile?: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
|
||||
@@ -1224,7 +1252,7 @@ export type SourceSigning = 'ad-hoc' | {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
@@ -1637,7 +1665,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-file-reference-local`
|
||||
|
||||
- `inject`: `agents` · `workingDirectory`
|
||||
- `source`: [`packages/context/file-reference-local/src/index.ts:35`](../packages/context/file-reference-local/src/index.ts)
|
||||
- `source`: [`packages/context/file-reference-local/src/index.ts:27`](../packages/context/file-reference-local/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Local file-reference discovery configuration. */
|
||||
@@ -2436,7 +2464,7 @@ export type Config = Readonly<Record<string, never>>
|
||||
## `@deepseek-ai/dsh-lsp-stdio`
|
||||
|
||||
- `inject`: `fs` · `lsp` · `subprocess`
|
||||
- `source`: [`packages/lsp/lsp-stdio/src/index.ts:83`](../packages/lsp/lsp-stdio/src/index.ts)
|
||||
- `source`: [`packages/lsp/lsp-stdio/src/index.ts:70`](../packages/lsp/lsp-stdio/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Plugin configuration: provider id → local language-server configuration. */
|
||||
@@ -2889,7 +2917,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-ptc-runtime-node`
|
||||
|
||||
- `inject`: `fs` · `subprocess` · `sandbox` · `sandboxPolicy`
|
||||
- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:7`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts)
|
||||
- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:8`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment-varying runtime bounds and launch choices. */
|
||||
@@ -2900,6 +2928,11 @@ export interface Config {
|
||||
executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script'
|
||||
/** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */
|
||||
scriptPersistence?: boolean
|
||||
/**
|
||||
* Run persistent-in-memory programs as scoped REPL statements whose later calls receive copies of earlier top-level bindings;
|
||||
* omitted, it is `SCOPED_REPL_BY_DEFAULT` from configuration.ts, currently true, with persistent-in-memory and false otherwise.
|
||||
*/
|
||||
replScoped?: boolean
|
||||
/** Default elapsed deadline, including nested tool and approval waits. */
|
||||
timeoutMs?: number
|
||||
/** Maximum numeric elapsed budget accepted by resolve. */
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
/cookbook-extension-plugin-shapes/an-external-protocol-driver:
|
||||
en: fc5e0d074214eaaf
|
||||
zh: aac2bf67d6e7b30a
|
||||
/cookbook-extension-plugin-shapes/a-forge-review-extension:
|
||||
en: 63267f9317969d16
|
||||
zh: 9a0ce54da348509a
|
||||
/cookbook-extension-plugin-shapes/runnable-wirings:
|
||||
en: f0a28d07c0bb4d1b
|
||||
zh: 840962f512cb4031
|
||||
|
||||
@@ -91,6 +91,49 @@ export function apply(ctx: Context) {
|
||||
}
|
||||
```
|
||||
|
||||
## A forge review extension
|
||||
|
||||
Change request review opens to plugins through the [forge extension API](../subsystems/forge.md#extension-api). A Host plugin registers a filter lens, which keeps some of the files a changes view shows and names the lines it is about:
|
||||
|
||||
```ts
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { ForgeLensId } from '@deepseek-ai/dsh-experimental-client-ui-forge'
|
||||
|
||||
export const name = 'exports-lens'
|
||||
export const inject = ['forgePanel']
|
||||
|
||||
export function apply(ctx: Context) {
|
||||
// An effect of this plugin's fiber: unloading the plugin withdraws the lens and aborts its runs.
|
||||
ctx.forgePanel.registerLens({
|
||||
id: brandString<ForgeLensId>('example/exports'),
|
||||
version: '1',
|
||||
async classify(input, signal) {
|
||||
const files: Record<string, { ranges: { old: []; new: { start: number; end: number }[] } }> = {}
|
||||
for (const file of input.files) {
|
||||
const lines = (await input.text('new', file.path, signal))?.split('\n') ?? []
|
||||
const ranges = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : [])
|
||||
if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } }
|
||||
}
|
||||
return { files }
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
A Client plugin names that lens and adds line annotations; `notesOf` returns one stable observable per view, and `NoteBody` is a module-scope component that draws one annotation inside the frame the view draws. The forge tests' [fixture plugin](../../apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js) also uses the toolbar, file menu, comment form, and card slots.
|
||||
|
||||
```ts ignore-check
|
||||
export const inject = ['forgeChanges', 'slots']
|
||||
|
||||
export function apply(ctx: Context) {
|
||||
ctx.effect(() => ctx.forgeChanges.describeLens({ id: brandString<ForgeLensId>('example/exports'), title: () => 'Exports' }))
|
||||
ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'example-notes', observe: target => notesOf(target) }))
|
||||
ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register(
|
||||
{ name: 'forge.diff.line.annotation', key: 'example-notes' }, NoteBody))
|
||||
}
|
||||
```
|
||||
|
||||
## Runnable wirings
|
||||
|
||||
Shipped applications contribute profile layers through `packages/bundle/*/cordis.patch.yml`, and the product `dsh` launcher owns Web, ACP, SDK, and one-shot headless execution through named profiles. Optional user-facing overlays live under `apps/cli/config/examples/`; profile integration tests live under `apps/cli/tests/profiles/`, while package-specific Loader compositions stay with their package tests.
|
||||
|
||||
@@ -93,6 +93,49 @@ export function apply(ctx: Context) {
|
||||
}
|
||||
```
|
||||
|
||||
## Forge 评审扩展
|
||||
|
||||
变更请求评审经由 [forge 扩展 API](../subsystems/forge.zh.md#extension-api) 向插件开放。Host 插件注册一个筛选透镜,它保留变更视图所显示文件中的一部分,并给出它关心的行:
|
||||
|
||||
```ts
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { ForgeLensId } from '@deepseek-ai/dsh-experimental-client-ui-forge'
|
||||
|
||||
export const name = 'exports-lens'
|
||||
export const inject = ['forgePanel']
|
||||
|
||||
export function apply(ctx: Context) {
|
||||
// An effect of this plugin's fiber: unloading the plugin withdraws the lens and aborts its runs.
|
||||
ctx.forgePanel.registerLens({
|
||||
id: brandString<ForgeLensId>('example/exports'),
|
||||
version: '1',
|
||||
async classify(input, signal) {
|
||||
const files: Record<string, { ranges: { old: []; new: { start: number; end: number }[] } }> = {}
|
||||
for (const file of input.files) {
|
||||
const lines = (await input.text('new', file.path, signal))?.split('\n') ?? []
|
||||
const ranges = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : [])
|
||||
if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } }
|
||||
}
|
||||
return { files }
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Client 插件给这个透镜起名并添加行注解;`notesOf` 为每个视图返回一个稳定的可观察对象,`NoteBody` 是模块级组件,在视图所画的外框中绘制一条注解。forge 测试的[夹具插件](../../apps/web/tests/fixtures/plugins/fixture-forge-extension/client.js)还用到了工具栏、文件菜单、评论框和卡片的 slot。
|
||||
|
||||
```ts ignore-check
|
||||
export const inject = ['forgeChanges', 'slots']
|
||||
|
||||
export function apply(ctx: Context) {
|
||||
ctx.effect(() => ctx.forgeChanges.describeLens({ id: brandString<ForgeLensId>('example/exports'), title: () => 'Exports' }))
|
||||
ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'example-notes', observe: target => notesOf(target) }))
|
||||
ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register(
|
||||
{ name: 'forge.diff.line.annotation', key: 'example-notes' }, NoteBody))
|
||||
}
|
||||
```
|
||||
|
||||
## 可运行的组装示例
|
||||
|
||||
交付应用通过 `packages/bundle/*/cordis.patch.yml` 提供 profile 层,产品 `dsh` 启动器通过具名 profile 负责 Web、ACP、SDK 与一次性 headless 执行。可选的用户 overlay 位于 `apps/cli/config/examples/`;profile 集成测试位于 `apps/cli/tests/profiles/`,包专属 Loader 组合则留在对应包的测试目录中。
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 1da81051addc4b47
|
||||
zh: 3e8d7cd3f8c1cdba
|
||||
/official-deepseek-llm-api-wire-extensions/request-headers:
|
||||
en: d3d6a2c8240b80e9
|
||||
zh: debf42ed01233728
|
||||
en: a55fbcd176b7a7a7
|
||||
zh: ed8b10f6e840cc44
|
||||
/official-deepseek-llm-api-wire-extensions/body-extension-transaction:
|
||||
en: 48001cfd1281a23b
|
||||
zh: d410530ae8aa2823
|
||||
|
||||
@@ -23,7 +23,7 @@ The [`DeepSeekLlmApiExtensionRegistry`](../packages/llm/deepseek-llm-api-extensi
|
||||
|
||||
| Header | Presence | Value |
|
||||
|---|---|---|
|
||||
| `user-agent` | Every provider HTTP request, including Files API operations | Application identity in `product/version (+url)` form; the default product is `deepseek-harness` |
|
||||
| `user-agent` | Every provider HTTP request, including Files API operations | Application identity in `product/version (+url)` form, followed by `dsh-profile/<profile>` naming the booted profile, percent-encoded outside `tchar` and for `%` (for example `dsh-profile/desktop`, `dsh-profile/web`, `dsh-profile/sdk`); the default product is `deepseek-harness` |
|
||||
| `x-deepseek-harness-user-id` | Every authorized model request | The stable anonymous UUID for the resolved Harness home |
|
||||
| `x-deepseek-harness-session-id` | Model requests carrying a Session id | The exact request `sessionId` string |
|
||||
| `x-deepseek-harness-compact` | Model requests whose purpose is `compaction` | The literal string `1` |
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
|
||||
| 标头 | 出现条件 | 值 |
|
||||
|---|---|---|
|
||||
| `user-agent` | 每个提供方 HTTP 请求,包括 Files API 操作 | 采用 `product/version (+url)` 形式的应用身份;默认产品为 `deepseek-harness` |
|
||||
| `user-agent` | 每个提供方 HTTP 请求,包括 Files API 操作 | 采用 `product/version (+url)` 形式的应用身份,其后追加命名所启动 profile 的 `dsh-profile/<profile>`,`tchar` 以外的字节及 `%` 做百分号编码(例如 `dsh-profile/desktop`、`dsh-profile/web`、`dsh-profile/sdk`);默认产品为 `deepseek-harness` |
|
||||
| `x-deepseek-harness-user-id` | 每个已授权的模型请求 | 已解析 Harness home 的稳定匿名 UUID |
|
||||
| `x-deepseek-harness-session-id` | 携带会话 id 的模型请求 | 确切的请求 `sessionId` 字符串 |
|
||||
| `x-deepseek-harness-compact` | 用途为 `compaction` 的模型请求 | 字面字符串 `1` |
|
||||
|
||||
@@ -47,7 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
|
||||
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
|
||||
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:30`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:39`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
|
||||
@@ -56,7 +57,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
|
||||
| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
|
||||
| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
|
||||
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
|
||||
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
|
||||
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
|
||||
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
|
||||
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) |
|
||||
|
||||
@@ -49,7 +49,8 @@
|
||||
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
|
||||
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
|
||||
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:30`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:39`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
|
||||
@@ -58,7 +59,7 @@
|
||||
| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
|
||||
| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
|
||||
| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
|
||||
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
|
||||
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
|
||||
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
|
||||
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
|
||||
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) |
|
||||
|
||||
+10
-1
@@ -265,6 +265,7 @@ flowchart TD
|
||||
pkg_cua["cua"]
|
||||
pkg_cua_bundle["cua-bundle"]
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_cua_windows["cua-windows"]
|
||||
pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"]
|
||||
pkg_experimental_auto_review["experimental-auto-review"]
|
||||
pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"]
|
||||
@@ -962,6 +963,12 @@ flowchart TD
|
||||
pkg_creation_recommendations --> pkg_session
|
||||
pkg_creation_recommendations --> pkg_skill
|
||||
pkg_creation_recommendations --> pkg_tools
|
||||
pkg_cua_windows --> pkg_agent
|
||||
pkg_cua_windows --> pkg_computer_use
|
||||
pkg_cua_windows --> pkg_subprocess
|
||||
pkg_cua_windows --> pkg_system_prompt
|
||||
pkg_cua_windows --> pkg_tools
|
||||
pkg_cua_windows --> pkg_user_questions
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt
|
||||
@@ -1130,6 +1137,7 @@ flowchart TD
|
||||
pkg_api_settings_controller --> pkg_typert_protocol
|
||||
pkg_web_app --> pkg_shell_env
|
||||
pkg_cua --> pkg_attachment
|
||||
pkg_cua --> pkg_error
|
||||
pkg_cua --> pkg_ptc_runtime_node
|
||||
pkg_cua --> pkg_scope
|
||||
pkg_cua --> pkg_tool_executor_ptc
|
||||
@@ -1837,6 +1845,7 @@ flowchart TD
|
||||
| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) |
|
||||
| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) |
|
||||
| [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
|
||||
@@ -1870,7 +1879,7 @@ flowchart TD
|
||||
| [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) |
|
||||
| [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) |
|
||||
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) |
|
||||
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
|
||||
|
||||
+10
-1
@@ -267,6 +267,7 @@ flowchart TD
|
||||
pkg_cua["cua"]
|
||||
pkg_cua_bundle["cua-bundle"]
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_cua_windows["cua-windows"]
|
||||
pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"]
|
||||
pkg_experimental_auto_review["experimental-auto-review"]
|
||||
pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"]
|
||||
@@ -964,6 +965,12 @@ flowchart TD
|
||||
pkg_creation_recommendations --> pkg_session
|
||||
pkg_creation_recommendations --> pkg_skill
|
||||
pkg_creation_recommendations --> pkg_tools
|
||||
pkg_cua_windows --> pkg_agent
|
||||
pkg_cua_windows --> pkg_computer_use
|
||||
pkg_cua_windows --> pkg_subprocess
|
||||
pkg_cua_windows --> pkg_system_prompt
|
||||
pkg_cua_windows --> pkg_tools
|
||||
pkg_cua_windows --> pkg_user_questions
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use
|
||||
pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt
|
||||
@@ -1132,6 +1139,7 @@ flowchart TD
|
||||
pkg_api_settings_controller --> pkg_typert_protocol
|
||||
pkg_web_app --> pkg_shell_env
|
||||
pkg_cua --> pkg_attachment
|
||||
pkg_cua --> pkg_error
|
||||
pkg_cua --> pkg_ptc_runtime_node
|
||||
pkg_cua --> pkg_scope
|
||||
pkg_cua --> pkg_tool_executor_ptc
|
||||
@@ -1839,6 +1847,7 @@ flowchart TD
|
||||
| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) |
|
||||
| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) |
|
||||
| [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
|
||||
@@ -1872,7 +1881,7 @@ flowchart TD
|
||||
| [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) |
|
||||
| [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) |
|
||||
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) |
|
||||
| [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) |
|
||||
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/subsystems/computer-use.md
|
||||
/computer-use:
|
||||
en: e02a2e4cc9970cba
|
||||
zh: 29aac6c0530a582f
|
||||
en: bf7dcc9124e8bce2
|
||||
zh: 4199c51e21dc9b0a
|
||||
/computer-use/serve-computer-use-to-another-harness:
|
||||
en: 6424dd8388f342fb
|
||||
zh: c5ecebb60ab1f50f
|
||||
|
||||
@@ -14,7 +14,7 @@ The CUA provider owns `ctx.cuaAccess` for system-permission status, explicit sys
|
||||
|---|---|
|
||||
| `CuaApplicationId`, `CuaApplicationGrant` | A platform-provided application identity and its displayed saved decision. |
|
||||
| `CuaSystemPermission` | Accessibility or Screen Recording, selected by the human. |
|
||||
| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native access observations tagged `darwin` or `win32`, with helper process identity. macOS includes permission checks, parent identity and responsible-application metadata when available (falling back to the helper’s own bundle); Windows includes desktop lock, capture availability and elevation status. |
|
||||
| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native access observations tagged `darwin` or `windows`, with the helper’s name and path when available. macOS includes permission checks, numeric helper and parent PIDs, and responsible-application metadata when available (falling back to the helper’s own bundle); Windows includes desktop lock, capture availability and elevation status, and omits the helper PID. |
|
||||
| `CuaApplicationState` | Saved grants, refused applications, and whether persistence is available. Session-only grants remain internal to the provider. System observations and application icons are queried separately so the page can display each result as it arrives. |
|
||||
|
||||
The [shared object API](../../packages/experimental/cua/README.md) uses `connectCua` to select an application, then `app.getWindows()` and `app.getWindow(windowId)` to select a window for screenshots and pointer input. Accessibility operations use element IDs from the latest tree for that application handle. Providers declare keyboard scopes and application-level accessibility in `getCapabilities()`.
|
||||
|
||||
@@ -14,7 +14,7 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申
|
||||
|---|---|
|
||||
| `CuaApplicationId`、`CuaApplicationGrant` | 平台提供的应用身份,以及显示给用户的已保存决定。 |
|
||||
| `CuaSystemPermission` | 用户选择申请的辅助功能或屏幕录制权限。 |
|
||||
| `CuaPermissionProcess`、`CuaSystemPermissionState` | 以 `darwin` 或 `win32` 标记的原生访问状态和 helper 进程身份。macOS 包含权限检查、父进程身份和责任应用信息(系统无法识别时使用 helper 自身的应用包);Windows 包含桌面锁定、截图可用性和提权状态。 |
|
||||
| `CuaPermissionProcess`、`CuaSystemPermissionState` | 以 `darwin` 或 `windows` 标记的原生访问状态,包含可获取的 helper 名称和路径。macOS 包含权限检查、helper 和父进程的数字 PID,以及责任应用信息(系统无法识别时使用 helper 自身的应用包);Windows 包含桌面锁定、截图可用性和提权状态,省略 helper 的 PID。 |
|
||||
| `CuaApplicationState` | 持久授权、拒绝记录,以及能否持久保存。会话授权只保留在 provider 内部。系统权限和应用图标分别查询,页面在各项结果返回后分别显示。 |
|
||||
|
||||
调用[共享对象 API](../../packages/experimental/cua/README.zh.md) 时,通过 `connectCua` 连接,选择应用后用 `app.getWindows()` 和 `app.getWindow(windowId)` 选择要截图或进行鼠标操作的窗口。辅助功能操作使用该应用句柄最近一次读取的树中的元素 ID。提供方通过 `getCapabilities()` 声明键盘输入支持的范围,以及是否支持应用级辅助功能。
|
||||
|
||||
@@ -24,5 +24,8 @@
|
||||
en: 13dfd36f2166bba0
|
||||
zh: a369434f52f04d57
|
||||
/forges/panel:
|
||||
en: 0e0348e9a38215ed
|
||||
zh: affcc0231e15d682
|
||||
en: 7dcefe2825490257
|
||||
zh: 38cec4d1ae3b0d6e
|
||||
/forges/extension-api:
|
||||
en: f35345e482e84f4f
|
||||
zh: 2ecb7d9498decb31
|
||||
+197
-3
@@ -101,6 +101,12 @@ interface ForgeProvider {
|
||||
* with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`.
|
||||
*/
|
||||
compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
/**
|
||||
* Find the merge base of commits `base` and `head` in the change request's repository, as a full object name: the
|
||||
* commit whose files the old side of a change request's diff shows. Omission declares that the provider cannot name
|
||||
* it, so readers of the old side get `unsupported`.
|
||||
*/
|
||||
mergeBase?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are
|
||||
* returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a
|
||||
@@ -928,6 +934,11 @@ interface ForgePanelWorktree {
|
||||
interface ForgePanelChangeRequest extends SessionChangeRequest {
|
||||
/** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */
|
||||
readonly snapshot: ChangeRequestSnapshot | null
|
||||
/**
|
||||
* Number of review changes `forge/review-changed` announced for the change request since the panel host started; it
|
||||
* grows when any plugin's write is accepted, so a reader shows threads and viewed marks read after it.
|
||||
*/
|
||||
readonly reviewRevision: number
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1187,6 +1198,120 @@ interface ForgeLocalChanges {
|
||||
}
|
||||
```
|
||||
|
||||
<a id="extension-api"></a>
|
||||
|
||||
## Extension API
|
||||
|
||||
Other plugins extend change request review through the services above and five more extension points; each registration returns its disposer and ends with the plugin that made it. The surface is experimental and pre-stable like the rest of this capability. Adding an optional field, method, slot, event, error code, or defaulted Config key is compatible; removing or renaming a type, method, slot, owner prop, event, Config key, or the `dsh-resource://forge-changes/` address, or narrowing what one means, needs an [upgrade guide](../../.agents/skills/dsh-create-upgrade-guide/SKILL.md). None of these extension points sends anything to a model: a plugin that shows forge data, lens results, or annotations to a model does so through its own tool results or `agent.inject()`, which the Session log records.
|
||||
|
||||
| Extension point | Service Definition | Service Provider | Consumer |
|
||||
|---|---|---|---|
|
||||
| Review data | `ctx.forge` and the `forge/review-changed` event | The forge providers | The panel host and other Host plugins |
|
||||
| Filter lenses | `ctx.forgePanel.registerLens` | Host plugins | The changes view through `changesLens` |
|
||||
| Changes view face | `ctx.forgeChanges` | The forge panel's Client plugin | Client plugins that open views, name lenses, and add annotations |
|
||||
| Slots | `forge.changes.toolbar`, `forge.changes.file.menu`, `forge.diff.line.annotation`, `forge.diff.comment.actions`, `forge.change-request.card.actions` | Client plugins | The changes view and the change request card |
|
||||
| Session data | The `forgeChangeRequests` and `forgeWorktree` projections | forge-session and the forge panel | Client plugins through `useProjection`, Host plugins through `ctx.forgeSession.changeRequests` or `ctx.sessionProjections.snapshot` |
|
||||
|
||||
`ctx.forge` announces `forge/review-changed` after a review write, a submitted review, or a viewed mark the host accepted, whichever plugin made it; an outcome that is unknown, refused, stale, or unsupported is not announced. The panel host then drops the threads it keeps for the change request and raises `reviewRevision` on its entries, so an open changes view reads the threads and the viewed marks again without a refresh.
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* One review change the host accepted, which `forge/review-changed` announces: a write to the threads or the pending
|
||||
* review, a submitted review, or a viewed mark. Each names the head commit the change was made against.
|
||||
*/
|
||||
type ForgeReviewChange =
|
||||
| { readonly kind: 'write'; readonly write: ForgeReviewWrite['kind']; readonly headSha: string }
|
||||
| { readonly kind: 'submit'; readonly headSha: string }
|
||||
| { readonly kind: 'viewed'; readonly path: string; readonly viewed: boolean; readonly headSha: string }
|
||||
```
|
||||
|
||||
A Host plugin registers a filter lens with `ctx.forgePanel.registerLens(lens)`, and a Client plugin names it with `ctx.forgeChanges.describeLens({ id, title })`; a lens without a description shows its identity. A lens filters the shown files and does not place them in layers: the changes view shows the files that both the chosen layer and the chosen lens keep, the test switch still hides test files, and a lens cannot move a file to another layer. Hunks that meet none of a kept file's `ranges` fold into one row the reader can expand. The view asks for the chosen lens only, through the streaming Remote `changesLens`, which reads the same files as the view, refuses other files with `forgePanel/lens-stale`, and runs `classify` within `lensTimeoutMs` and `maxLensReadBytes`; results are kept up to `maxCachedLensBytes`. `text` reads a local old side at the fork point, HEAD, the index, or the parent of the first chosen commit, and a change request's old side at the chosen commits' parent or at the merge base its provider names through the optional `mergeBase`.
|
||||
|
||||
```ts type-equiv
|
||||
/** A filter over the files of a changes view, which a plugin registers with `ctx.forgePanel.registerLens()`. */
|
||||
interface ForgeLens {
|
||||
/** Identity the plugin chooses; one registration holds an id at a time. */
|
||||
readonly id: ForgeLensId
|
||||
/** Changes whenever `classify` may answer differently for the same input, which drops results kept under another version. */
|
||||
readonly version: string
|
||||
/**
|
||||
* Decide which files the lens keeps and which lines it is about. The signal aborts when the reader stops waiting, the
|
||||
* registration ends, or `lensTimeoutMs` passes; a rejection fails the request without a partial result.
|
||||
*/
|
||||
classify(input: ForgeLensInput, signal: AbortSignal): Promise<ForgeLensResult>
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** What one `classify` call receives. */
|
||||
interface ForgeLensInput {
|
||||
/** What the view shows. */
|
||||
readonly source: ForgeLensSource
|
||||
/** Every file of the diff in display order, with the layer the panel gave it. */
|
||||
readonly files: readonly ForgeLensFile[]
|
||||
/**
|
||||
* Read one side of a file of `files`, by its `path`: the old side reads `previousPath` for a renamed file. Resolves to
|
||||
* null when the side does not exist, as the old side of an added file, or holds binary content. Rejects for a path not
|
||||
* in `files`, once the reads of one call exceed the panel's `maxLensReadBytes`, for an old side the provider cannot
|
||||
* locate, and when the read fails.
|
||||
*/
|
||||
text(side: 'old' | 'new', path: string, signal: AbortSignal): Promise<string | null>
|
||||
/** Report how many of `total` units the lens finished; the changes view shows it while the lens runs. */
|
||||
progress(done: number, total: number): void
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The files a lens keeps, by path; a file the result does not name is filtered out. */
|
||||
interface ForgeLensResult {
|
||||
readonly files: Readonly<Record<string, ForgeLensKeep>>
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** What a lens keeps of one file. */
|
||||
interface ForgeLensKeep {
|
||||
/**
|
||||
* Lines the lens is about on each side; hunks that touch none of them fold into one row the reader can expand.
|
||||
* Omitted: every hunk of the file shows.
|
||||
*/
|
||||
readonly ranges?: { readonly old: readonly ForgeLineRange[]; readonly new: readonly ForgeLineRange[] }
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forgeChanges` also mints and reads changes addresses, names the tab `kinds`, and opens a view with `open(target, { path, lens })` in the Session the sidebar shows. `registerAnnotations(source)` adds line annotations: the source observes each view's annotations by path, and its `forge.diff.line.annotation` entry, keyed by the source's identity, draws each one inside a frame the view draws. Annotations stack on the row of their last line after the comment form, the browser drafts, and the host threads, in the column of their side; whole-file annotations come first, and those written on another `digest` follow the file in their own section. A file shows at most `maxAnnotationsPerFile`, and a file that draws its lines draws no annotation before its section comes within reach of the scrollport. The owner props of every slot live in [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts).
|
||||
|
||||
```ts type-equiv
|
||||
/** Where one line annotation sits in a file of a changes view. */
|
||||
interface ForgeLineAnnotation {
|
||||
/** Identity within its source, stable across updates; it keys the drawn entry. */
|
||||
readonly key: string
|
||||
/** Inclusive 1-based lines on the old (`L`) or new (`R`) side, or `file` for the whole file. */
|
||||
readonly place: { readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } | 'file'
|
||||
/** Digest of the file change it was written on; a file whose `digest` differs shows it in its outdated section. */
|
||||
readonly digest?: string
|
||||
/** Changes whenever the entry should draw again; equal keys and versions keep the drawn entry's props. */
|
||||
readonly version: string | number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** A Client plugin's line annotations, drawn through its `forge.diff.line.annotation` entry. */
|
||||
interface ForgeAnnotationSource {
|
||||
/** Unique source identity, also the key of its `forge.diff.line.annotation` entry. */
|
||||
readonly id: string
|
||||
/** Position among sources in one stack, lower first; equal positions keep registration order. Default 0. */
|
||||
readonly order?: number
|
||||
/**
|
||||
* Observe the annotations of one view, by path. The changes view calls it once per view and source registration;
|
||||
* the source republishes through the same observable whenever the annotations change.
|
||||
* @param target - the view's Session and source.
|
||||
* @returns annotations by repository-relative path.
|
||||
*/
|
||||
observe(target: ChangesTarget): HostObservable<ReadonlyMap<string, readonly ForgeLineAnnotation[]>>
|
||||
}
|
||||
```
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
<a id="cordis-surface"></a>
|
||||
@@ -1355,7 +1480,7 @@ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): P
|
||||
/**
|
||||
* Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then
|
||||
* poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls
|
||||
* it as a stale read does.
|
||||
* it as a stale read does; a write the host took is announced with `forge/review-changed`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param write - the write and the head commit the user saw.
|
||||
* @param signal - cancellation of the write.
|
||||
@@ -1379,7 +1504,8 @@ async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal):
|
||||
|
||||
/**
|
||||
* Set or clear the signed-in user's viewed mark on one file of a change request while its head is still
|
||||
* `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does.
|
||||
* `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does; a saved
|
||||
* mark is announced with `forge/review-changed`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param request - the file, its mark, and the head commit the user saw.
|
||||
* @param signal - cancellation of the request.
|
||||
@@ -1410,7 +1536,21 @@ async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitLi
|
||||
async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status.
|
||||
* Find the merge base of two commits of a change request's repository: the commit whose files the old side of the
|
||||
* change request's diff shows when `base` is the snapshot's `baseSha` and `head` its `headSha`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param base - full object name of the base commit.
|
||||
* @param head - full object name of the head commit.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the merge base's full object name, or why the host did not provide it; `unsupported` when the provider
|
||||
* cannot name merge bases.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param request - explicitly selected commit, comments, and review decision.
|
||||
* @param signal - request cancellation.
|
||||
@@ -1658,6 +1798,40 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise<string>
|
||||
|
||||
/**
|
||||
* Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending
|
||||
* the registration aborts its running classifications and waits for them.
|
||||
* @param lens - the lens.
|
||||
* @returns the disposer that unregisters the lens and waits for its classifications to stop.
|
||||
* @throws when another registration holds `lens.id`.
|
||||
*/
|
||||
registerLens(lens: ForgeLens): () => Promise<void>
|
||||
|
||||
/**
|
||||
* Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts
|
||||
* after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param signal - ends the stream.
|
||||
* @returns the registered lenses and the annotation limit, in publication order.
|
||||
*/
|
||||
@Remote({ mode: 'stream' }) async *extensions(signal: AbortSignal): AsyncIterable<ForgeExtensionState>
|
||||
|
||||
/**
|
||||
* Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens
|
||||
* runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until
|
||||
* `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files
|
||||
* are those `changeRequestDiff` reads.
|
||||
* @param session - Session whose checkout or binding the view shows.
|
||||
* @param request - the view's source, the version of the files it shows, and the lens.
|
||||
* @param signal - ends the classification.
|
||||
* @returns progress frames, then one result frame.
|
||||
* @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends;
|
||||
* `forgePanel/lens-stale` before a change request's status was read, when the files differ from `request.version`, and
|
||||
* when local files changed while the lens ran;
|
||||
* `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers
|
||||
* over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files.
|
||||
*/
|
||||
@Remote({ mode: 'stream' }) async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable<ForgeLensFrame>
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the
|
||||
* whole change request.
|
||||
@@ -1971,5 +2145,25 @@ Announces a provider registration or withdrawal after the registry changes. List
|
||||
'forge/providers-changed'(forge: string): void | Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts)
|
||||
|
||||
<a id="forgereview-changed--parallel"></a>
|
||||
|
||||
#### `forge/review-changed` — parallel
|
||||
|
||||
Announces a review change the host accepted through this service: a thread or pending-review write, a submitted review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. Listener failures are logged without preventing other listeners from running.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Announces a review change the host accepted through this service: a thread or pending-review write, a submitted
|
||||
* review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced.
|
||||
* Listener failures are logged without preventing other listeners from running.
|
||||
* @param ref - change request the change went to.
|
||||
* @param change - what changed and the head commit it was made against.
|
||||
* @mode parallel
|
||||
*/
|
||||
'forge/review-changed'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
+197
-3
@@ -101,6 +101,12 @@ interface ForgeProvider {
|
||||
* with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`.
|
||||
*/
|
||||
compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
/**
|
||||
* Find the merge base of commits `base` and `head` in the change request's repository, as a full object name: the
|
||||
* commit whose files the old side of a change request's diff shows. Omission declares that the provider cannot name
|
||||
* it, so readers of the old side get `unsupported`.
|
||||
*/
|
||||
mergeBase?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are
|
||||
* returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a
|
||||
@@ -930,6 +936,11 @@ interface ForgePanelWorktree {
|
||||
interface ForgePanelChangeRequest extends SessionChangeRequest {
|
||||
/** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */
|
||||
readonly snapshot: ChangeRequestSnapshot | null
|
||||
/**
|
||||
* Number of review changes `forge/review-changed` announced for the change request since the panel host started; it
|
||||
* grows when any plugin's write is accepted, so a reader shows threads and viewed marks read after it.
|
||||
*/
|
||||
readonly reviewRevision: number
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1189,6 +1200,120 @@ interface ForgeLocalChanges {
|
||||
}
|
||||
```
|
||||
|
||||
<a id="extension-api"></a>
|
||||
|
||||
## 扩展 API
|
||||
|
||||
其他插件通过上面的服务和另外五个扩展点扩展变更请求评审;每次注册都返回 disposer,并随做出注册的插件一起结束。与这一能力的其余部分一样,这些接口处于实验阶段,尚未稳定。新增可选字段、方法、slot、事件、错误码或带默认值的 Config 键是兼容的;删除或改名类型、方法、slot、owner props、事件、Config 键或 `dsh-resource://forge-changes/` 地址,或收窄其含义,需要写[升级指南](../../.agents/skills/dsh-create-upgrade-guide/SKILL.md)。这些扩展点都不向模型发送任何内容:插件要让模型看到 forge 数据、透镜结果或注解,须经由它自己的工具结果或 `agent.inject()`,Session log 会记录它们。
|
||||
|
||||
| 扩展点 | Service Definition | Service Provider | Consumer |
|
||||
|---|---|---|---|
|
||||
| 评审数据 | `ctx.forge` 与 `forge/review-changed` 事件 | 各 forge 提供方 | 面板 Host 与其他 Host 插件 |
|
||||
| 筛选透镜 | `ctx.forgePanel.registerLens` | Host 插件 | 经 `changesLens` 使用它的变更视图 |
|
||||
| 变更视图接口 | `ctx.forgeChanges` | forge 面板的 Client 插件 | 打开视图、给透镜起名、添加注解的 Client 插件 |
|
||||
| Slot | `forge.changes.toolbar`、`forge.changes.file.menu`、`forge.diff.line.annotation`、`forge.diff.comment.actions`、`forge.change-request.card.actions` | Client 插件 | 变更视图与变更请求卡片 |
|
||||
| Session 数据 | `forgeChangeRequests` 与 `forgeWorktree` 投影 | forge-session 与 forge 面板 | Client 插件经 `useProjection` 读取,Host 插件经 `ctx.forgeSession.changeRequests` 或 `ctx.sessionProjections.snapshot` 读取 |
|
||||
|
||||
托管平台接受一次评审写入、一次评审提交或一个已审阅标记后,`ctx.forge` 发出 `forge/review-changed`,无论是哪个插件做的;结果未知、被拒绝、已过时或不支持时不发出。面板 Host 随后丢弃为该变更请求保留的讨论,并让对应条目的 `reviewRevision` 加一,因此已打开的变更视图无需刷新就会重新读取讨论和已审阅标记。
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* One review change the host accepted, which `forge/review-changed` announces: a write to the threads or the pending
|
||||
* review, a submitted review, or a viewed mark. Each names the head commit the change was made against.
|
||||
*/
|
||||
type ForgeReviewChange =
|
||||
| { readonly kind: 'write'; readonly write: ForgeReviewWrite['kind']; readonly headSha: string }
|
||||
| { readonly kind: 'submit'; readonly headSha: string }
|
||||
| { readonly kind: 'viewed'; readonly path: string; readonly viewed: boolean; readonly headSha: string }
|
||||
```
|
||||
|
||||
Host 插件用 `ctx.forgePanel.registerLens(lens)` 注册筛选透镜,Client 插件用 `ctx.forgeChanges.describeLens({ id, title })` 给它起名;没有名字的透镜显示其身份。透镜筛选显示的文件,不给文件分层:变更视图显示所选分层与所选透镜都保留的文件,测试文件开关仍然隐藏测试文件,透镜也不能把文件移到另一层。被保留文件中与 `ranges` 都不相交的 hunk 折叠成一行,读者可以展开。视图只请求所选的透镜,经流式 Remote `changesLens` 进行:它读取与视图相同的文件,文件不同时以 `forgePanel/lens-stale` 拒绝,并在 `lensTimeoutMs` 与 `maxLensReadBytes` 之内运行 `classify`;结果最多保留 `maxCachedLensBytes`。`text` 在分叉点、HEAD、暂存区或第一个所选提交的父提交上读取本地变更的旧侧,在所选提交的父提交上,或在提供方经可选的 `mergeBase` 给出的合并基准上读取变更请求的旧侧。
|
||||
|
||||
```ts type-equiv
|
||||
/** A filter over the files of a changes view, which a plugin registers with `ctx.forgePanel.registerLens()`. */
|
||||
interface ForgeLens {
|
||||
/** Identity the plugin chooses; one registration holds an id at a time. */
|
||||
readonly id: ForgeLensId
|
||||
/** Changes whenever `classify` may answer differently for the same input, which drops results kept under another version. */
|
||||
readonly version: string
|
||||
/**
|
||||
* Decide which files the lens keeps and which lines it is about. The signal aborts when the reader stops waiting, the
|
||||
* registration ends, or `lensTimeoutMs` passes; a rejection fails the request without a partial result.
|
||||
*/
|
||||
classify(input: ForgeLensInput, signal: AbortSignal): Promise<ForgeLensResult>
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** What one `classify` call receives. */
|
||||
interface ForgeLensInput {
|
||||
/** What the view shows. */
|
||||
readonly source: ForgeLensSource
|
||||
/** Every file of the diff in display order, with the layer the panel gave it. */
|
||||
readonly files: readonly ForgeLensFile[]
|
||||
/**
|
||||
* Read one side of a file of `files`, by its `path`: the old side reads `previousPath` for a renamed file. Resolves to
|
||||
* null when the side does not exist, as the old side of an added file, or holds binary content. Rejects for a path not
|
||||
* in `files`, once the reads of one call exceed the panel's `maxLensReadBytes`, for an old side the provider cannot
|
||||
* locate, and when the read fails.
|
||||
*/
|
||||
text(side: 'old' | 'new', path: string, signal: AbortSignal): Promise<string | null>
|
||||
/** Report how many of `total` units the lens finished; the changes view shows it while the lens runs. */
|
||||
progress(done: number, total: number): void
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The files a lens keeps, by path; a file the result does not name is filtered out. */
|
||||
interface ForgeLensResult {
|
||||
readonly files: Readonly<Record<string, ForgeLensKeep>>
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** What a lens keeps of one file. */
|
||||
interface ForgeLensKeep {
|
||||
/**
|
||||
* Lines the lens is about on each side; hunks that touch none of them fold into one row the reader can expand.
|
||||
* Omitted: every hunk of the file shows.
|
||||
*/
|
||||
readonly ranges?: { readonly old: readonly ForgeLineRange[]; readonly new: readonly ForgeLineRange[] }
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forgeChanges` 还可以生成和解析变更视图地址,给出标签的 `kinds`,并用 `open(target, { path, lens })` 在侧栏所显示的 Session 中打开视图。`registerAnnotations(source)` 添加行注解:数据源按路径观察每个视图的注解,它在 `forge.diff.line.annotation` 中按数据源身份登记的条目,负责绘制视图所画外框里的内容。注解放在其最后一行之后,位于评论框、浏览器草稿和托管平台讨论之后,落在所在一侧的那一栏;整个文件的注解排在最前,写在另一个 `digest` 上的注解在文件之后单独成段。每个文件最多显示 `maxAnnotationsPerFile` 条;逐行绘制的文件在文件段进入可视区附近之前不绘制注解。所有 slot 的 owner props 见 [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts)。
|
||||
|
||||
```ts type-equiv
|
||||
/** Where one line annotation sits in a file of a changes view. */
|
||||
interface ForgeLineAnnotation {
|
||||
/** Identity within its source, stable across updates; it keys the drawn entry. */
|
||||
readonly key: string
|
||||
/** Inclusive 1-based lines on the old (`L`) or new (`R`) side, or `file` for the whole file. */
|
||||
readonly place: { readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number } | 'file'
|
||||
/** Digest of the file change it was written on; a file whose `digest` differs shows it in its outdated section. */
|
||||
readonly digest?: string
|
||||
/** Changes whenever the entry should draw again; equal keys and versions keep the drawn entry's props. */
|
||||
readonly version: string | number
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** A Client plugin's line annotations, drawn through its `forge.diff.line.annotation` entry. */
|
||||
interface ForgeAnnotationSource {
|
||||
/** Unique source identity, also the key of its `forge.diff.line.annotation` entry. */
|
||||
readonly id: string
|
||||
/** Position among sources in one stack, lower first; equal positions keep registration order. Default 0. */
|
||||
readonly order?: number
|
||||
/**
|
||||
* Observe the annotations of one view, by path. The changes view calls it once per view and source registration;
|
||||
* the source republishes through the same observable whenever the annotations change.
|
||||
* @param target - the view's Session and source.
|
||||
* @returns annotations by repository-relative path.
|
||||
*/
|
||||
observe(target: ChangesTarget): HostObservable<ReadonlyMap<string, readonly ForgeLineAnnotation[]>>
|
||||
}
|
||||
```
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
<a id="cordis-surface"></a>
|
||||
@@ -1357,7 +1482,7 @@ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): P
|
||||
/**
|
||||
* Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then
|
||||
* poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls
|
||||
* it as a stale read does.
|
||||
* it as a stale read does; a write the host took is announced with `forge/review-changed`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param write - the write and the head commit the user saw.
|
||||
* @param signal - cancellation of the write.
|
||||
@@ -1381,7 +1506,8 @@ async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal):
|
||||
|
||||
/**
|
||||
* Set or clear the signed-in user's viewed mark on one file of a change request while its head is still
|
||||
* `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does.
|
||||
* `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does; a saved
|
||||
* mark is announced with `forge/review-changed`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param request - the file, its mark, and the head commit the user saw.
|
||||
* @param signal - cancellation of the request.
|
||||
@@ -1412,7 +1538,21 @@ async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitLi
|
||||
async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status.
|
||||
* Find the merge base of two commits of a change request's repository: the commit whose files the old side of the
|
||||
* change request's diff shows when `base` is the snapshot's `baseSha` and `head` its `headSha`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param base - full object name of the base commit.
|
||||
* @param head - full object name of the head commit.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the merge base's full object name, or why the host did not provide it; `unsupported` when the provider
|
||||
* cannot name merge bases.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param request - explicitly selected commit, comments, and review decision.
|
||||
* @param signal - request cancellation.
|
||||
@@ -1660,6 +1800,40 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise<string>
|
||||
|
||||
/**
|
||||
* Register a filter lens as an effect on the calling fiber. The changes views list it while it is registered; ending
|
||||
* the registration aborts its running classifications and waits for them.
|
||||
* @param lens - the lens.
|
||||
* @returns the disposer that unregisters the lens and waits for its classifications to stop.
|
||||
* @throws when another registration holds `lens.id`.
|
||||
*/
|
||||
registerLens(lens: ForgeLens): () => Promise<void>
|
||||
|
||||
/**
|
||||
* Stream the facts every changes view reads about the panel's extensions: the current facts first, then the facts
|
||||
* after each lens registration or withdrawal. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param signal - ends the stream.
|
||||
* @returns the registered lenses and the annotation limit, in publication order.
|
||||
*/
|
||||
@Remote({ mode: 'stream' }) async *extensions(signal: AbortSignal): AsyncIterable<ForgeExtensionState>
|
||||
|
||||
/**
|
||||
* Classify the files a changes view of a Session shows with one registered lens: progress frames while the lens
|
||||
* runs, then the files it keeps. Results for the same files, lens, and lens version are reused from memory until
|
||||
* `maxCachedLensBytes` evicts them. Local changes are read with the Session's permissions; a change request's files
|
||||
* are those `changeRequestDiff` reads.
|
||||
* @param session - Session whose checkout or binding the view shows.
|
||||
* @param request - the view's source, the version of the files it shows, and the lens.
|
||||
* @param signal - ends the classification.
|
||||
* @returns progress frames, then one result frame.
|
||||
* @throws `forgePanel/lens-missing` while no lens holds the identity or once its registration ends;
|
||||
* `forgePanel/lens-stale` before a change request's status was read, when the files differ from `request.version`, and
|
||||
* when local files changed while the lens ran;
|
||||
* `forgePanel/lens-failed` when the lens fails, runs past `lensTimeoutMs`, reads past `maxLensReadBytes`, or answers
|
||||
* over `maxCachedLensBytes`; the errors of `localDiff` and `changeRequestDiff` for the files.
|
||||
*/
|
||||
@Remote({ mode: 'stream' }) async *changesLens(session: Session, request: ForgeLensRequest, signal: AbortSignal): AsyncIterable<ForgeLensFrame>
|
||||
|
||||
/**
|
||||
* Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the
|
||||
* whole change request.
|
||||
@@ -1973,5 +2147,25 @@ Announces a provider registration or withdrawal after the registry changes. List
|
||||
'forge/providers-changed'(forge: string): void | Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts)
|
||||
|
||||
<a id="forgereview-changed--parallel"></a>
|
||||
|
||||
#### `forge/review-changed` — parallel
|
||||
|
||||
Announces a review change the host accepted through this service: a thread or pending-review write, a submitted review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced. Listener failures are logged without preventing other listeners from running.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Announces a review change the host accepted through this service: a thread or pending-review write, a submitted
|
||||
* review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced.
|
||||
* Listener failures are logged without preventing other listeners from running.
|
||||
* @param ref - change request the change went to.
|
||||
* @param change - what changed and the head commit it was made against.
|
||||
* @mode parallel
|
||||
*/
|
||||
'forge/review-changed'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental/forge/src/index.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -27,8 +27,8 @@
|
||||
en: cbab49d689311d4d
|
||||
zh: 76246140eabaa55e
|
||||
/llm-streaming/appidentity-app-attribution:
|
||||
en: e053f18c7dc070a8
|
||||
zh: 90ded9a892ed2fd5
|
||||
en: 2da6911c03ea8195
|
||||
zh: ae55da1a7e22be3a
|
||||
/llm-streaming/tokenusage:
|
||||
en: 33830f78fdb845fa
|
||||
zh: f43a4502c4c3bfff
|
||||
|
||||
@@ -311,7 +311,7 @@ Retry configuration resolves before route registration into an immutable discrim
|
||||
|
||||
## `AppIdentity` — app attribution
|
||||
|
||||
The static public application identity every adapter sends to providers ([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts)). `attributionHeaders(identity?)` maps it to the standard `User-Agent` header only; OpenRouter-specific app attribution headers are intentionally not supported by this contract. The default `APP_IDENTITY` sources its version from the package manifest; every field is a public product fact - no secrets, paths, session ids, or per-user identifiers, and nothing per-request may influence the values.
|
||||
The static public application identity every adapter sends to providers ([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts)). `attributionHeaders(identity?)` maps it to the standard `User-Agent` header only; OpenRouter-specific app attribution headers are intentionally not supported by this contract. The default `APP_IDENTITY` sources its version from the package manifest; every field is a public product fact - no secrets, paths, session ids, or per-user identifiers, and nothing per-request may influence the values. `APP_IDENTITY.suffix` reads `DSH_USER_AGENT_SUFFIX` on each use, and `userAgent()` appends it after the comment; a value that is not an RFC 9110 product token fails the request. The `dsh` launcher sets it to `dsh-profile/<profile>` before any plugin loads, percent-encoding profile-name bytes outside `tchar` and `%` itself, so Desktop sends `deepseek-harness/<version> (+<url>) dsh-profile/desktop` and a profile named `my web` sends `dsh-profile/my%20web`. A dsh subagent child reports its own profile, because child processes do not inherit `DSH_*` variables.
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
@@ -328,6 +328,8 @@ interface AppIdentity {
|
||||
version: string
|
||||
/** Repository home URL of the app, used as the `User-Agent` comment. */
|
||||
url: string
|
||||
/** RFC 9110 product token appended after the comment, such as `dsh-profile/web`. */
|
||||
suffix?: string | undefined
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -313,7 +313,7 @@ interface LlmImageRequestPricing {
|
||||
|
||||
## `AppIdentity`:应用归属
|
||||
|
||||
每个适配器都会向提供方发送的静态公开应用标识([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts))。`attributionHeaders(identity?)` 只把它映射到标准 `User-Agent` header;该约定有意不支持 OpenRouter 特有的应用归属 header。默认 `APP_IDENTITY` 从包 manifest(元数据清单)获取版本;每个字段都是公开产品事实——不含 secret、路径、会话 id 或逐用户标识,且任何逐请求信息都不得影响这些值。
|
||||
每个适配器都会向提供方发送的静态公开应用标识([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts))。`attributionHeaders(identity?)` 只把它映射到标准 `User-Agent` header;该约定有意不支持 OpenRouter 特有的应用归属 header。默认 `APP_IDENTITY` 从包 manifest(元数据清单)获取版本;每个字段都是公开产品事实——不含 secret、路径、会话 id 或逐用户标识,且任何逐请求信息都不得影响这些值。`APP_IDENTITY.suffix` 在每次使用时读取 `DSH_USER_AGENT_SUFFIX`,`userAgent()` 将其追加在注释之后;不是 RFC 9110 product token 的值使请求失败。`dsh` 启动器在任何插件加载前将其设为 `dsh-profile/<profile>`,并对 profile 名中 `tchar` 以外的字节及 `%` 本身做百分号编码,因此 Desktop 发送 `deepseek-harness/<version> (+<url>) dsh-profile/desktop`,名为 `my web` 的 profile 发送 `dsh-profile/my%20web`。dsh 子代理子进程报告自己的 profile,因为子进程不继承 `DSH_*` 变量。
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
@@ -330,6 +330,8 @@ interface AppIdentity {
|
||||
version: string
|
||||
/** Repository home URL of the app, used as the `User-Agent` comment. */
|
||||
url: string
|
||||
/** RFC 9110 product token appended after the comment, such as `dsh-profile/web`. */
|
||||
suffix?: string | undefined
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
en: 337a6580d7571274
|
||||
zh: f4ae98899120d122
|
||||
/ptc-runtime/the-run-request-in-result-out:
|
||||
en: 6dfa7da8b13a4f17
|
||||
zh: 09a3c8c4922239ef
|
||||
en: 94ba725bef6684b7
|
||||
zh: f113745a4a07952a
|
||||
/ptc-runtime/bindings-host-functions-as-program-globals:
|
||||
en: 182147ddf388c600
|
||||
zh: c0a7d77602c78bcd
|
||||
|
||||
@@ -19,7 +19,7 @@ interface PtcRunRequest {
|
||||
/**
|
||||
* The program source, in the runtime's {@link ../index.ts | language}. It
|
||||
* follows the provider's programFormat: an async function body supports
|
||||
* top-level `await` and `return`; REPL and Script programs support top-level
|
||||
* top-level `await` and `return`; REPL (`repl`, `scoped-repl`) and Script programs support top-level
|
||||
* declarations, `await`, and a final expression, but not top-level `return`.
|
||||
* The Script provider lowers top-level await; its executionInstructions and
|
||||
* documentation define retained-binding semantics. The completion value
|
||||
@@ -108,10 +108,10 @@ interface PtcRunResult {
|
||||
|
||||
```ts type-equiv
|
||||
/** Source evaluation form, independent of retained program state. */
|
||||
type PtcProgramFormat = 'function-body' | 'repl' | 'script'
|
||||
type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl'
|
||||
```
|
||||
|
||||
`programFormat` distinguishes async function bodies, REPL statements, and scripts. REPL and Script programs accept top-level `await`, declarations, and a final expression; top-level `return` is not supported. The Node Script provider lowers top-level await and awaits the completion value; its [declaration limitations](../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) apply to transformed programs. `retainsState` reports memory retention independently of source syntax. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format.
|
||||
`programFormat` distinguishes async function bodies, REPL statements, scoped REPL statements, and scripts. REPL, scoped REPL, and Script programs accept top-level `await`, declarations, and a final expression; top-level `return` is not supported. Retained REPL calls share one scope, while each scoped REPL call starts with copies of the top-level bindings that earlier calls left, so it can declare those names again without changing earlier code. The Node Script provider lowers top-level await and awaits the completion value; its [declaration limitations](../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) apply to transformed programs. `retainsState` reports memory retention independently of source syntax. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format.
|
||||
|
||||
## Bindings: host functions as program globals
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ interface PtcRunRequest {
|
||||
/**
|
||||
* The program source, in the runtime's {@link ../index.ts | language}. It
|
||||
* follows the provider's programFormat: an async function body supports
|
||||
* top-level `await` and `return`; REPL and Script programs support top-level
|
||||
* top-level `await` and `return`; REPL (`repl`, `scoped-repl`) and Script programs support top-level
|
||||
* declarations, `await`, and a final expression, but not top-level `return`.
|
||||
* The Script provider lowers top-level await; its executionInstructions and
|
||||
* documentation define retained-binding semantics. The completion value
|
||||
@@ -108,10 +108,10 @@ interface PtcRunResult {
|
||||
|
||||
```ts type-equiv
|
||||
/** Source evaluation form, independent of retained program state. */
|
||||
type PtcProgramFormat = 'function-body' | 'repl' | 'script'
|
||||
type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl'
|
||||
```
|
||||
|
||||
`programFormat` 区分异步函数体、REPL 语句与脚本。REPL 与 Script 程序接受顶层 `await`、声明和末尾表达式,不支持顶层 `return`。Node Script 提供方转换顶层 await 并等待完成值;其[声明限制](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)适用于转换后的程序。`retainsState` 独立于源码语法报告是否保留内存。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。
|
||||
`programFormat` 区分异步函数体、REPL 语句、scoped REPL 语句与脚本。REPL、scoped REPL 与 Script 程序接受顶层 `await`、声明和末尾表达式,不支持顶层 `return`。保留状态的 REPL 各次调用共用一个作用域;scoped REPL 每次调用开始时拿到之前调用留下的顶层绑定的拷贝,因此可以再次声明这些名字,而不改变之前的代码。Node Script 提供方转换顶层 await 并等待完成值;其[声明限制](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)适用于转换后的程序。`retainsState` 独立于源码语法报告是否保留内存。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。
|
||||
|
||||
## 绑定:宿主函数作为程序全局变量
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 207c515390c5e529
|
||||
zh: bd4d90881efb011d
|
||||
/native-cua-application-and-window-api/change:
|
||||
en: d3b7e02c362b0049
|
||||
zh: 49f1a190495e813d
|
||||
en: 43ace3409e7976b8
|
||||
zh: da185b705dfe600a
|
||||
/native-cua-application-and-window-api/migration:
|
||||
en: fe1cd8e7812f6fb2
|
||||
zh: 449cca5b18275ebd
|
||||
en: 33bdef11cad75c53
|
||||
zh: 0d576c6160278b7b
|
||||
@@ -9,15 +9,15 @@ English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
Screenshots and pointer input require explicit windows. App (`appHandle`) and Window (`windowId`) objects share their application handle's latest accessibility snapshot. Discovery reports running matches' PIDs.
|
||||
Screenshots and pointer input require explicit windows. App (`appHandle`) and Window (`windowId`) objects share their application handle's latest accessibility snapshot. Window IDs are opaque strings. macOS retains running application PIDs and permission `helper.pid` and `parent.pid`. Windows permission metadata omits PIDs.
|
||||
|
||||
Providers supply startup capabilities and implement `getGuidance(kind)` instead of supplying a `guidance` string. `raw` selects instructions for the raw `cua` tool; `standalone` selects instructions for `cua_run_code`. The native helper reports runtime permissions and session lock state; the Host combines these with startup capabilities in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `win32` platform tag.
|
||||
Providers supply startup capabilities and implement `getGuidance(kind)` instead of supplying a `guidance` string. `raw` selects instructions for the raw `cua` tool; `standalone` selects instructions for `cua_run_code`. The native helper reports runtime permissions and session lock state; the Host combines these with startup capabilities in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `windows` platform tag.
|
||||
|
||||
## Migration
|
||||
|
||||
1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action.
|
||||
1. Pass a current `app.getWindows()` ID unchanged to `app.getWindow(windowId)`. Rediscover saved numeric IDs. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action.
|
||||
2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Application and window selection does not read AX. Before using element IDs, call `getAccessibilityTree()` explicitly. To display the tree in TypeScript PTC, pass its return value to `inspect`. A screenshot does not require a successful AX read. Before coordinate input, including relative coordinates, obtain a successful AX observation covering the window or a screenshot; absolute coordinates require a screenshot. See [macOS AX read limits](../cua-ax-read-limits/guide.md) for changes to traversal defaults and configuration.
|
||||
3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active.
|
||||
4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` or `cua_run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying.
|
||||
5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID.
|
||||
6. Custom providers replace `CuaBackend.description` with `capabilities` and `guidance` with `getGuidance(kind)`, and supply `permissionParameters` to `installCua`. Both kinds may return identical text. Rebuild custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart and verify both tool forms' guidance, advertised methods, keyboard scopes, and platform controls on the Computer Use permission page.
|
||||
4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` or `cua_run_code` to hold a key across tool calls. Repeat a held non-modifier with another down. Returning, throwing or pausing releases any remaining keys. Replace `NATIVE_ERROR` with `INVALID_ARGUMENT` for unknown macOS keys and correct the key before retrying.
|
||||
5. Read `dispatched`, then observe the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Pass a Windows application ID unchanged. For a specific macOS instance, use `getApp(String(row.pid))`. Update permission readers that test for `win32` to use `windows`.
|
||||
6. Custom providers replace `CuaBackend.description` with `capabilities` and `guidance` with `getGuidance(kind)`. Supply `permissionParameters`. Set `acceptsPidSelector: true` if `getApp` accepts process IDs. Rebuild custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart. Verify both tool forms’ guidance, advertised methods, keyboard scopes and permission controls.
|
||||
@@ -9,15 +9,15 @@ description: "迁移 CUA 脚本和自定义原生提供方,使用显式窗口
|
||||
|
||||
## 变更
|
||||
|
||||
截图和指针输入要求显式选择窗口。App(`appHandle`)和 Window(`windowId`)对象共享所属应用句柄的最新辅助功能快照。应用发现返回运行中匹配项的 PID。
|
||||
截图和指针输入要求显式选择窗口。App(`appHandle`)和 Window(`windowId`)对象共享所属应用句柄的最新辅助功能快照。窗口 ID 是不透明字符串,macOS 应用发现保留运行进程的 PID,权限诊断保留 `helper.pid` 和 `parent.pid`。Windows 权限诊断不提供 PID。
|
||||
|
||||
提供方声明启动能力,并实现 `getGuidance(kind)`,不再传入 `guidance` 字符串。`raw` 选择原始 `cua` 工具的指引,`standalone` 选择 `cua_run_code` 的指引。原生 helper 返回运行时权限和会话锁定状态,Host 将其与启动能力合并到 `getCapabilities()` 中。供权限页面使用的响应带有 `darwin` 或 `win32` 平台标记。
|
||||
提供方声明启动能力,并实现 `getGuidance(kind)`,不再传入 `guidance` 字符串。`raw` 选择原始 `cua` 工具的指引,`standalone` 选择 `cua_run_code` 的指引。原生 helper 返回运行时权限和会话锁定状态,Host 将其与启动能力合并到 `getCapabilities()` 中。供权限页面使用的响应带有 `darwin` 或 `windows` 平台标记。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。
|
||||
1. 从 `app.getWindows()` 返回的列表选定目标,把原始字符串传给 `app.getWindow(windowId)`。曾以数字保存的窗口 ID 需要重新获取。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。
|
||||
2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择应用或窗口不读取 AX。使用元素 ID 前须显式调用 `getAccessibilityTree()`。在 TypeScript PTC 中,将返回值传给 `inspect` 即可展示这棵树。截图不要求 AX 读取成功。所有坐标输入(包括相对坐标)之前都须成功读取覆盖该窗口的 AX 或取得截图;绝对坐标要求截图。[读取上限的迁移说明](../cua-ax-read-limits/guide.zh.md)列出了 macOS 默认值和配置含义的变化。
|
||||
3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。
|
||||
4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 或 `cua_run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。
|
||||
5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。
|
||||
6. 自定义提供方将 `CuaBackend.description` 改为 `capabilities`,将 `guidance` 改为 `getGuidance(kind)`,并向 `installCua` 传入 `permissionParameters`。两种形态可以返回相同文本。按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建自定义 `helperPath` 对应的 helper。重启后验证两种工具形态的指引、声明的方法、键盘输入范围及 Computer Use 权限页的平台控件。
|
||||
5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。Windows 应用 ID 原样传递。需要选择某个 macOS 进程时,使用 `getApp(String(row.pid))`。读取权限状态时,将原先判断 `win32` 的代码改为判断 `windows`。
|
||||
6. 自定义提供方将 `CuaBackend.description` 改为 `capabilities`,将 `guidance` 改为 `getGuidance(kind)`,并向 `installCua` 传入 `permissionParameters`。若 `getApp` 接受进程 ID,设置 `acceptsPidSelector: true`。按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建自定义 `helperPath` 对应的 helper。重启后验证两种工具形态的指引、声明的方法、键盘输入范围及 Computer Use 权限页的平台控件。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.md
|
||||
/:
|
||||
en: 5048dc7fc046e7ab
|
||||
zh: 7845cb3ba5a543d4
|
||||
/replace-internal-plugin-root-imports:
|
||||
en: 65af277d1f4ed1a0
|
||||
zh: 9d2b980fb6fabe89
|
||||
/replace-internal-plugin-root-imports/change:
|
||||
en: fcb1af4db4d0edd5
|
||||
zh: 6cc6ed79d0100eac
|
||||
/replace-internal-plugin-root-imports/migration:
|
||||
en: 01c24ef3fa9273f6
|
||||
zh: cd5ae3b6f0218aba
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: Internal helper values are removed from three published plugin-root entries.
|
||||
---
|
||||
|
||||
# Replace internal plugin-root imports
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
After upgrading from v0.2.2-rc.1, the following plugin-root values are no longer exported. Their implementations remain inside the packages. Consumers importing these values from a package root must change their imports or use the owning service.
|
||||
|
||||
| Package suffix (`@deepseek-ai/dsh-`) | Removed root helpers |
|
||||
|---|---|
|
||||
| `file-reference-local` | `DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES`, `DEFAULT_FILE_SEARCH_MAX_ENTRIES`, `DEFAULT_FILE_SEARCH_MAX_RESULTS`, `WorkspaceFileSearch`, `FILE_REFERENCE_PROMPT`, `activeAtToken`, `formatFileMention` |
|
||||
| `llm-pi-ai` | `recordKeyFor` |
|
||||
| `lsp-stdio` | `LspConnection`, `LspInstance`, `MessageDecoder`, `canonicalizeWorkspace`, `encodeMessage`, `negotiatePositionEncoding`, `normalizeHover`, `normalizeLocations`, `readHostSource`, `requestMethod`, `supportsOperation`, `supportsTransientOpen` |
|
||||
|
||||
Brand constructors, package subpaths, persisted values and Session formats are unchanged.
|
||||
|
||||
## Migration
|
||||
|
||||
1. Stop importing the listed helper values from plugin roots. Package-owned tests can use relative imports from the corresponding internal modules.
|
||||
2. Application code should use the injected `fileReferences` or `lsp` service instead of provider implementation classes or protocol helpers. File-reference grammar remains at `@deepseek-ai/dsh-file-reference/grammar`; `FILE_REFERENCE_PROMPT` remains at `@deepseek-ai/dsh-file-reference`. `recordKeyFor` has no replacement public entry.
|
||||
3. Compile the application and run its tests. Load any plain-JavaScript consumers under Node as well: TypeScript checking alone does not cover missing ESM named exports in `.mjs` files.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: 三个已发布插件的根入口移除内部辅助实体的值导出。
|
||||
---
|
||||
|
||||
# 替换内部插件根导入
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
从 v0.2.2-rc.1 升级后,以下插件根入口不再导出这些值。对应实现在包内保留。从包根入口导入这些值的消费方需要更改导入或改用所属服务。
|
||||
|
||||
| 包名后缀(`@deepseek-ai/dsh-`) | 移除的根辅助实体 |
|
||||
|---|---|
|
||||
| `file-reference-local` | `DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES`、`DEFAULT_FILE_SEARCH_MAX_ENTRIES`、`DEFAULT_FILE_SEARCH_MAX_RESULTS`、`WorkspaceFileSearch`、`FILE_REFERENCE_PROMPT`、`activeAtToken`、`formatFileMention` |
|
||||
| `llm-pi-ai` | `recordKeyFor` |
|
||||
| `lsp-stdio` | `LspConnection`、`LspInstance`、`MessageDecoder`、`canonicalizeWorkspace`、`encodeMessage`、`negotiatePositionEncoding`、`normalizeHover`、`normalizeLocations`、`readHostSource`、`requestMethod`、`supportsOperation`、`supportsTransientOpen` |
|
||||
|
||||
品牌构造器、包子路径、持久化值和 Session 格式不变。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 停止从插件根入口导入上表的辅助实体值。包内测试可以相对导入对应内部模块。
|
||||
2. 应用代码应使用注入的 `fileReferences` 或 `lsp` 服务,而不是提供方的实现类或协议辅助函数。文件引用语法仍在 `@deepseek-ai/dsh-file-reference/grammar`;`FILE_REFERENCE_PROMPT` 仍在 `@deepseek-ai/dsh-file-reference`。`recordKeyFor` 没有替代的公开入口。
|
||||
3. 编译应用并运行其测试,同时用 Node 加载纯 JavaScript 消费方:仅检查 TypeScript 无法覆盖 `.mjs` 文件中缺少 ESM 命名导出的错误。
|
||||
@@ -3,14 +3,14 @@
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md
|
||||
/:
|
||||
en: 200e3531fb831ad1
|
||||
zh: b529f83a2f83ef6d
|
||||
/node-ptc-bootstrap-protocol-version-3:
|
||||
en: 5c10a48d83f56e19
|
||||
zh: 1c8d8832764d558f
|
||||
/node-ptc-bootstrap-protocol-version-3/change:
|
||||
en: 6d4af1d37654f401
|
||||
zh: a06ee0ee8a9326ee
|
||||
/node-ptc-bootstrap-protocol-version-3/migration:
|
||||
en: 4c25b296ed471589
|
||||
zh: 46071ce14e092f48
|
||||
en: cee454924a9ab1f8
|
||||
zh: 2d7cbdcc398fa914
|
||||
/node-ptc-bootstrap-protocol-version-3-and-the-scoped-repl-format:
|
||||
en: 541c4f16c0107c90
|
||||
zh: edda22e2ebf01992
|
||||
/node-ptc-bootstrap-protocol-version-3-and-the-scoped-repl-format/change:
|
||||
en: f9b071385a270a1e
|
||||
zh: e664c70b769579e9
|
||||
/node-ptc-bootstrap-protocol-version-3-and-the-scoped-repl-format/migration:
|
||||
en: 350de9ad88b43420
|
||||
zh: 8b8bfe380cbf6fe8
|
||||
@@ -1,22 +1,25 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Update custom Node PTC bootstraps to protocol version 3 before running them with the upgraded Host."
|
||||
description: "Update custom Node PTC bootstraps to protocol version 3 before running them with the upgraded Host, and handle the new scoped-repl program format."
|
||||
---
|
||||
|
||||
# Node PTC bootstrap protocol version 3
|
||||
# Node PTC bootstrap protocol version 3 and the scoped-repl format
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
The Node PTC Host requires bootstrap protocol version 3 instead of version 2. It rejects an older bootstrap before dispatching a program, with `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`. This affects custom `launch.bootstrapPath` deployments in every execution mode. The bootstrap bundled with DSH updates with the Host and needs no configuration change.
|
||||
The Node PTC Host requires bootstrap protocol version 3 instead of version 2. It rejects an older bootstrap before dispatching a program, with `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`. This affects custom `launch.bootstrapPath` deployments in every execution mode, including `@deepseek-ai/dsh-ssh` hosts with a `node-script` launch that set `launch.bootstrapPath` and `launch.bootstrapHash`. The bootstrap bundled with DSH updates with the Host and needs no configuration change.
|
||||
|
||||
Version 3 carries optional `ProgramBootData.initialization` source for each new environment. The bootstrap evaluates it separately after installing current bindings, then awaits the Host's `initialized()` RPC acceptance and rechecks cancellation before running the model program. Initialization failure discards the environment and prevents model execution. The Node provider supports initializer registration only in `persistent-in-memory` mode.
|
||||
|
||||
Version 3 also carries `ProgramBootData.discardCompletion` to discard completion values before JSON validation and serialization. The bootstrap provides `inspect` and sends selected images through `HostMethods.image(id)` in output order. Custom bootstraps must support these fields and methods alongside environment initialization.
|
||||
|
||||
Version 3 also adds the `scoped-repl` program format. `PtcProgramFormat` in `@deepseek-ai/dsh-ptc-runtime` now includes `'scoped-repl'`, which `@deepseek-ai/dsh-ptc-runtime-node` reports as `PtcRuntime.programFormat` when `replScoped: true` is set with `executionMode: persistent-in-memory`. Code that matches the union exhaustively stops compiling until it handles the new value.
|
||||
|
||||
## Migration
|
||||
|
||||
1. If your Node PTC configuration sets `launch.bootstrapPath`, deploy the matching version of `@deepseek-ai/dsh-ptc-runtime-node` in its execution environment. Use the package's built `lib/process.js` or REPL-default `lib/persistent-process.js` with its dependencies. Keep the Host and bootstrap versions aligned; changing only the advertised version is insufficient.
|
||||
2. Update `launch.bootstrapPath` to the matching entry and restart the provider. For local deployments that need no custom bootstrap, remove that override to use the installed default. The [Node runtime documentation](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) describes retained execution and remote launch.
|
||||
3. Run a program in each configured execution mode and confirm that it completes without the protocol error. Consumers using `registerEnvironmentInitializer(program)` must also verify that initialization runs once per new environment and that an initialization error prevents the model program's effects.
|
||||
2. Update `launch.bootstrapPath` to the matching entry and restart the provider. For `@deepseek-ai/dsh-ssh` with a `node-script` launch, copy the new bootstrap to the remote `launch.bootstrapPath` and set `launch.bootstrapHash` to its lowercase SHA-256, for example from `sha256sum`. For local deployments that need no custom bootstrap, remove that override to use the installed default. The [Node runtime documentation](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) describes retained execution and remote launch.
|
||||
3. Handle `'scoped-repl'` wherever code switches over `PtcProgramFormat` or keys a record by it. A `scoped-repl` program is REPL statements whose final expression is the result; top-level `return` is not supported, and a final Promise is not awaited.
|
||||
4. Run a program in each configured execution mode and confirm that it completes without the protocol error. Consumers using `registerEnvironmentInitializer(program)` must also verify that initialization runs once per new environment and that an initialization error prevents the model program's effects. Typecheck the code that uses `PtcProgramFormat`.
|
||||
@@ -1,22 +1,25 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "自定义 Node PTC bootstrap 必须升级到协议版本 3,才能与新版 Host 一起运行。"
|
||||
description: "自定义 Node PTC bootstrap 必须升级到协议版本 3,才能与新版 Host 一起运行;还要处理新增的 scoped-repl 程序格式。"
|
||||
---
|
||||
|
||||
# Node PTC bootstrap 协议版本 3
|
||||
# Node PTC bootstrap 协议版本 3 与 scoped-repl 格式
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
Node PTC Host 要求 bootstrap 协议版本从 2 升至 3。它会在派发程序前拒绝旧 bootstrap,并报告 `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`。这影响所有执行模式下自定义 `launch.bootstrapPath` 的部署。DSH 内置 bootstrap 随 Host 更新,无需修改配置。
|
||||
Node PTC Host 要求 bootstrap 协议版本从 2 升至 3。它会在派发程序前拒绝旧 bootstrap,并报告 `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`。这影响所有执行模式下自定义 `launch.bootstrapPath` 的部署,包括使用 `node-script` 启动、设置了 `launch.bootstrapPath` 和 `launch.bootstrapHash` 的 `@deepseek-ai/dsh-ssh` 宿主。DSH 内置 bootstrap 随 Host 更新,无需修改配置。
|
||||
|
||||
版本 3 为每个新环境携带可选的 `ProgramBootData.initialization` 源码。bootstrap 安装本次绑定后独立执行初始化,随后等待 Host 对 `initialized()` RPC 的确认,再次检查取消状态后才执行模型程序。初始化失败会丢弃环境并阻止模型代码执行。Node 提供方仅在 `persistent-in-memory` 模式下支持注册初始化程序。
|
||||
|
||||
版本 3 还携带 `ProgramBootData.discardCompletion`,用于在 JSON 校验和序列化前丢弃完成值。bootstrap 提供 `inspect`,并通过 `HostMethods.image(id)` 按输出顺序发送选中的图片。自定义 bootstrap 必须同时支持这些字段、方法和环境初始化。
|
||||
|
||||
版本 3 还新增了 `scoped-repl` 程序格式。`@deepseek-ai/dsh-ptc-runtime` 的 `PtcProgramFormat` 新增 `'scoped-repl'`;`@deepseek-ai/dsh-ptc-runtime-node` 在 `executionMode: persistent-in-memory` 下设置 `replScoped: true` 时,`PtcRuntime.programFormat` 报告这个值。对这个联合类型做穷尽匹配的代码,处理新值之前无法通过编译。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 如果 Node PTC 配置设置了 `launch.bootstrapPath`,请在其执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node`。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`,并保留其依赖。Host 与 bootstrap 版本必须匹配;只修改声明的版本号并不够。
|
||||
2. 将 `launch.bootstrapPath` 指向匹配的入口并重启提供方。本地部署若不需要自定义 bootstrap,可以移除此覆盖项以使用安装默认值。[Node 运行时文档](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)说明状态保留和远程启动方式。
|
||||
3. 在每种已配置的执行模式中运行一个程序,确认正常完成且没有协议错误。使用 `registerEnvironmentInitializer(program)` 的消费方还须验证:初始化在每个新环境中只执行一次,且初始化出错时模型程序不会产生效果。
|
||||
2. 将 `launch.bootstrapPath` 指向匹配的入口并重启提供方。使用 `node-script` 启动的 `@deepseek-ai/dsh-ssh`:把新的 bootstrap 复制到远端的 `launch.bootstrapPath`,并把 `launch.bootstrapHash` 设为它的小写 SHA-256,例如用 `sha256sum` 计算。本地部署若不需要自定义 bootstrap,可以移除此覆盖项以使用安装默认值。[Node 运行时文档](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)说明状态保留和远程启动方式。
|
||||
3. 在按 `PtcProgramFormat` 分支或以它为键的地方处理 `'scoped-repl'`。`scoped-repl` 程序是 REPL 语句,最后一条表达式就是结果;不支持顶层 `return`,末尾的 Promise 不会被等待。
|
||||
4. 在每种已配置的执行模式中运行一个程序,确认正常完成且没有协议错误。使用 `registerEnvironmentInitializer(program)` 的消费方还须验证:初始化在每个新环境中只执行一次,且初始化出错时模型程序不会产生效果。再对使用 `PtcProgramFormat` 的代码做类型检查。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.md
|
||||
/:
|
||||
en: cff145a993d30f0a
|
||||
zh: 784a2ce78146a563
|
||||
/retained-node-ptc-runs-the-scoped-repl-by-default:
|
||||
en: 60119ea304ce7bad
|
||||
zh: c0724f1da0e4590c
|
||||
/retained-node-ptc-runs-the-scoped-repl-by-default/change:
|
||||
en: 1ca349eed9a54b9b
|
||||
zh: 5dc5ba17ec953f0e
|
||||
/retained-node-ptc-runs-the-scoped-repl-by-default/migration:
|
||||
en: 5d1e1f1bf7ce7821
|
||||
zh: aafa439b6080acb4
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Node PTC persistent-in-memory execution runs the scoped REPL unless replScoped is false."
|
||||
---
|
||||
|
||||
# Retained Node PTC runs the scoped REPL by default
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
`@deepseek-ai/dsh-ptc-runtime-node` previously ran `executionMode: persistent-in-memory` programs in Node's REPL evaluator when `replScoped` was omitted. It now runs them as scoped REPL statements and reports program format `scoped-repl`. Each call is a separate strict-mode script that starts with copies of the top-level bindings left by earlier calls, so a later call may declare a `let`, `const`, or `class` name again. `require`, `_`, `_error`, and globals created by assigning an undeclared name are unavailable. The model guidance describes this behavior; the package README lists its [known limitations](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work).
|
||||
|
||||
This affects:
|
||||
|
||||
- profiles whose `ptc-runtime` entry sets `executionMode: persistent-in-memory` without `replScoped`, including workflow-ptc scripts that run on that runtime;
|
||||
- persistent PTC enabled from the Computer Use detail page, which now writes `replScoped: true`;
|
||||
- the Computer Use `cua_run_code` tool, whose dedicated runtime omits `replScoped` unless `standaloneRunCode.runtime.replScoped` is set;
|
||||
- profile editors that merge `resolvePersistentExecution` from `@deepseek-ai/dsh-ptc-runtime-node/configuration`, which now returns `replScoped: true` for function bodies and REPL statements.
|
||||
|
||||
`per-call` and `vm-script` execution, including the default profile, are unchanged, and entries that set `replScoped: false` keep Node's REPL evaluator.
|
||||
|
||||
## Migration
|
||||
|
||||
1. To keep the scoped REPL, replace REPL-only code: use `await import(...)` instead of `require`, assign `globalThis.name` for an intentional global, and use a new name instead of reading a name's earlier value in its own `let` or `const` initializer.
|
||||
2. To restore Node's REPL evaluator, set `replScoped: false` in `$DSH_HOME/profiles/<profile>/cordis.patch.yml`; to move an entry that sets `false` to the scoped REPL, delete the key or set `true`. Each patch below replaces that entry's whole `config`, so copy the entry's existing fields into it, for the `cua` entry including `agentPreset`, `allowedApps`, and the other `standaloneRunCode` fields:
|
||||
|
||||
```yaml
|
||||
- id: ptc-runtime
|
||||
config:
|
||||
executionMode: persistent-in-memory
|
||||
replScoped: false
|
||||
```
|
||||
|
||||
For `cua_run_code`, set it on the Computer Use provider entry:
|
||||
|
||||
```yaml
|
||||
- id: cua
|
||||
config:
|
||||
standaloneRunCode:
|
||||
runtime:
|
||||
replScoped: false
|
||||
```
|
||||
|
||||
3. Restart the profile and run `const probe = 1` in two consecutive calls. The scoped REPL accepts both calls; Node's REPL evaluator reports that `probe` has already been declared in the second.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Node PTC 的 persistent-in-memory 执行默认使用 scoped REPL,replScoped 为 false 时除外。"
|
||||
---
|
||||
|
||||
# 保留状态的 Node PTC 默认使用 scoped REPL
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
`@deepseek-ai/dsh-ptc-runtime-node` 在 `executionMode: persistent-in-memory` 下省略 `replScoped` 时,原先用 Node 的 REPL 求值器运行程序;现在按 scoped REPL 语句运行,并报告程序格式 `scoped-repl`。每次调用是独立的严格模式脚本,开始时拿到之前调用留下的顶层绑定的拷贝,因此之后的调用可以再次声明同名的 `let`、`const` 或 `class`。`require`、`_`、`_error`,以及给未声明的名字赋值而产生的全局变量都不可用。模型说明描述了这些行为;包 README 列出了它的[已知限制](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)。
|
||||
|
||||
受影响的有:
|
||||
|
||||
- `ptc-runtime` 条目设置了 `executionMode: persistent-in-memory` 但没写 `replScoped` 的 profile,包括在该运行时上运行的 workflow-ptc 脚本;
|
||||
- 在 Computer Use 详情页打开的持久化 PTC,现在会写入 `replScoped: true`;
|
||||
- Computer Use 的 `cua_run_code` 工具,其专用运行时在没有设置 `standaloneRunCode.runtime.replScoped` 时省略 `replScoped`;
|
||||
- 合并 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 中 `resolvePersistentExecution` 结果的 profile 编辑器,该函数现在对函数体和 REPL 语句返回 `replScoped: true`。
|
||||
|
||||
`per-call` 和 `vm-script` 执行(包括默认 profile)不变,设置了 `replScoped: false` 的条目继续使用 Node 的 REPL 求值器。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 如果保留 scoped REPL,替换只在 REPL 下可用的代码:用 `await import(...)` 代替 `require`,有意的全局变量赋给 `globalThis.name`,不要在 `let` 或 `const` 的初始化表达式里读取同名的旧值,改用新名字。
|
||||
2. 如果要恢复 Node 的 REPL 求值器,在 `$DSH_HOME/profiles/<profile>/cordis.patch.yml` 里设置 `replScoped: false`;要让设为 `false` 的条目改用 scoped REPL,删除这个键或改为 `true`。下面每个 patch 都会替换该条目的整个 `config`,所以要把条目已有的字段一并写进去,`cua` 条目还包括 `agentPreset`、`allowedApps` 和 `standaloneRunCode` 的其他字段:
|
||||
|
||||
```yaml
|
||||
- id: ptc-runtime
|
||||
config:
|
||||
executionMode: persistent-in-memory
|
||||
replScoped: false
|
||||
```
|
||||
|
||||
对 `cua_run_code`,在 Computer Use 提供方条目上设置:
|
||||
|
||||
```yaml
|
||||
- id: cua
|
||||
config:
|
||||
standaloneRunCode:
|
||||
runtime:
|
||||
replScoped: false
|
||||
```
|
||||
|
||||
3. 重启 profile,在连续两次调用里运行 `const probe = 1`。scoped REPL 两次都接受;Node 的 REPL 求值器在第二次报告 `probe` 已经声明过。
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-root",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -301,6 +301,7 @@
|
||||
"@deepseek-ai/dsh-experimental-worktree": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*",
|
||||
"@deepseek-ai/dsh-cua-bundle": "workspace:*",
|
||||
"@deepseek-ai/dsh-cua-windows": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-subagent-oar": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-cua-macos": "workspace:*",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-acp",
|
||||
"description": "Automation-only Agent Client Protocol server for driving DeepSeek Harness agents over JSON-RPC stdio",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -32,7 +32,7 @@ function llmRuntime(overrides: Partial<LlmRuntime> = {}): LlmRuntime {
|
||||
},
|
||||
}),
|
||||
...overrides,
|
||||
} as unknown as LlmRuntime
|
||||
} as LlmRuntime
|
||||
}
|
||||
|
||||
async function createControl(runtime: LlmRuntime, initial?: ModelSelection) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-gateway",
|
||||
"description": "Typert Remote Host dispatcher and Client API endpoint",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-job-controller",
|
||||
"description": "Job Remote observation stream and the reference-counted client job-output service",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-remote-access",
|
||||
"description": "Method-level Remote access control for non-owner Peers and the per-Peer access snapshot",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-remotes",
|
||||
"description": "Remote BFF assembly for application-selected Host capabilities",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-session-controller",
|
||||
"description": "Session Remote commands, cold reads, and live control transport",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-settings-controller",
|
||||
"description": "Remote owner for the configuration surfaces over the settings-domain seams",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-terminal-controller",
|
||||
"description": "Session-owned interactive terminals with shell discovery, screen recovery and typed Remote control",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-workspace-controller",
|
||||
"description": "Workspace Remote commands and reconnect-safe state transport",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-api-workspace-files",
|
||||
"description": "Workspace file service and Client resource provider: bounded reads, directory listing, and live metadata over the workspaceFiles Remote namespace",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-attachment-local",
|
||||
"description": "Private content-addressed DSH_HOME attachment storage",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-attachment",
|
||||
"description": "Durable immutable attachment storage seam for the DeepSeek Harness",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-app-boot",
|
||||
"description": "Shared boot glue for the app bins: .env loading, fail-loud Loader guards, snapshot-aware config resolution, and the Loader boot sequence",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -80,7 +80,7 @@ it('skips an unsupported saved bundle before composing any runtime overrides and
|
||||
const unsupported = process.platform === 'darwin' ? 'win32' : 'darwin'
|
||||
const anchor = stageInstallation({
|
||||
base: { patch: '- insert:\n - id: ptc-runtime\n name: runtime\n config: { executionMode: isolated }\n' },
|
||||
restricted: { platforms: [unsupported], patch: '- id: ptc-runtime\n config: { executionMode: persistent-in-memory }\n' },
|
||||
restricted: { platforms: [unsupported], patch: '- id: ptc-runtime\n config: { executionMode: persistent-in-memory, replScoped: false }\n' },
|
||||
})
|
||||
const dir = join(tmp(), 'profile')
|
||||
initProfile(dir, ['base', 'restricted'])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-cmdline",
|
||||
"description": "Immutable command-line handoff from a dsh launcher to any app plugin that injects cmdlineArgs",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-config-editor",
|
||||
"description": "Persist plugin configuration through profile patches and Loader reconciliation",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-hmr",
|
||||
"description": "Coordinated module and profile configuration hot reload",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-plugin-manager",
|
||||
"description": "Current-profile plugin and bundle management shared by dsh CLI, Web and agent tools",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-plugin-market",
|
||||
"description": "Configured plugin market indexes for the Web Discover page and the plugin_market agent tool",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-browser-use",
|
||||
"description": "Exclusive named browser-use provider registration",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-acp-app",
|
||||
"description": "The dsh ACP profile bundle: automation-only JSON-RPC stdio and process lifecycle over dsh-base",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-base",
|
||||
"description": "The shared dsh core as a profile bundle: the first patch layer of base-backed profiles, inserting core rows over the empty profile root",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-headless",
|
||||
"description": "The dsh one-shot bundle: a direct core Agent/Session runner over dsh-base with no Host, HTTP, or browser layer",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-sdk-app",
|
||||
"description": "The dsh SDK profile bundle: stdio JSON-RPC serving and process lifecycle over dsh-base",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-sdk-minimal",
|
||||
"description": "The standalone minimal SDK profile bundle: JSON-RPC, one DeepSeek adapter, persistent shell, and JSONL sessions",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-web-app",
|
||||
"description": "The dsh browser-surface bundle: the web patch layer over dsh-base plus the runtime glue plugin (frontend dist serving, bash runtime variables, URL line)",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-connection",
|
||||
"description": "Authenticated RPC transport and generation lifecycle",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-file-upload",
|
||||
"description": "Agent-scoped browser file upload, streaming intake, and staged receipt service",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-hmr",
|
||||
"description": "Web client graph synchronization and rebuilt-bundle reload transport",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-locale",
|
||||
"description": "Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries",
|
||||
"version": "0.2.2-rc.1",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
Loaded 100 of 774 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user