@xiangyixie/dsh-superagent 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1756 +1,1167 @@
1
- # dsh-superagent
2
-
3
- Long-horizon runs for [DeepSeek Harness](https://dshai.org): one goal in,
4
- model-planned parallel subtasks, one merged report — and the run survives a host
5
- restart.
6
-
7
- A single agent loop is one context and one sequence. Goals that need several
8
- independent lines of work stall in it, and a crash ends the turn with nothing to
9
- resume. This plugin takes one goal, asks the model to split it into subtasks, runs
10
- up to three child agents at a time, and merges their reports into one answer. Run
11
- state and spend are written to disk, so after a host restart `superagent_status`
12
- still finds the run and `superagent_resume` finishes only the unfinished part.
13
- Every run has a hard call and token budget, prints the usage it measured, and
14
- prints the cost once you give it a price for the route.
15
-
16
- **Don't use it when** one model call can answer: you would only be paying for a
17
- planner and an aggregator on top. It is also the wrong tool for work that must
18
- finish inside a single turn, for a step that needs human approval in the middle,
19
- for anything that needs nested delegation (child depth is capped at 1), and for
20
- anyone who wants an in-host panel — the optional workspace panel below is a
21
- loopback page, not host UI. Children run with the host's credentials and
22
- filesystem; this is not a sandbox.
23
-
24
- **Install and run.** Node `>= 24.9.0`, a tool-calling route, and that route's key
25
- in the environment:
26
-
27
- ```bash
28
- dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.0
29
- ```
30
-
31
- Then ask the session for a run — a real call, not a sketch:
32
-
33
- > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
34
-
35
- The reply ends `completed` with the merged report, or with
36
- `next: superagent_status run_id="..."` if the wait ran out. [Quickstart](#quickstart)
37
- covers the path from an empty machine, including the reason not to install npm's
38
- unrelated `dsh` package by name.
39
-
40
- It adds no in-host UI (the workspace panel and the conversation console are
41
- loopback pages) and patches no host code: the twelve `superagent_*` tools are the
42
- surface, plus six optional operator utilities (a terminal panel, an HTML report,
43
- an install doctor, a run archive, git sync, and the workspace panel) that read the
44
- same run files. Browser and desktop control is a separate layer: with
45
- `runtime.enabled` set, fourteen more tools are registered, and with the default
46
- `false` none of them exist.
47
-
48
- Personal project, not affiliated with DeepSeek or the harness maintainers. MIT
49
- licensed, © 2026 Admire (LittleChenLiya); details in [License](#license).
50
-
51
- ## Requirements
52
-
53
- - Node `>= 24.9.0`. DeepSeek Harness refuses to start below that, so this
54
- plugin does too.
55
- - DeepSeek Harness `>= 0.2.2-rc.1 < 0.3.0` with the base bundle (the `tools`,
56
- `agents`, and `subagents` services).
57
- - A model route that can call tools, and that route's API key in the
58
- environment. The default profile uses `deepseek-official` / `deepseek-flash`
59
- and reads `DEEPSEEK_API_KEY`.
60
-
61
- ## Quickstart
62
-
63
- Five minutes, from nothing to a finished run. Every command below runs on a
64
- clean machine.
65
-
66
- ### 0. Do not install `dsh` from npm by name
67
-
68
- ```bash
69
- # WRONG: npm's `dsh` is unrelated ("a shell written in JavaScript")
70
- npm i -g dsh
71
-
72
- # RIGHT: run the DeepSeek Harness by its scoped package, pinned
73
- npx @deepseek-ai/dsh@0.2.2-rc.1 --version
74
- ```
75
-
76
- The rest of this page writes `dsh` for that command; if the binary is not on
77
- your `PATH`, use `npx @deepseek-ai/dsh@0.2.2-rc.1` instead.
78
-
79
- ```bash
80
- # 1. install the plugin into a profile (web, headless, ... whatever you run)
81
- dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.0
82
-
83
- # 2. confirm the bundle row exists in the merged config
84
- dsh --profile web --dump-config
85
- ```
86
-
87
- The desktop app's **Add plugin** dialog accepts the same three forms:
88
-
89
- | Dialog input | Value | What it does |
90
- | --- | --- | --- |
91
- | Package name | `@xiangyixie/dsh-superagent@0.14.0` | Installs from npm. Name the version (see below). |
92
- | GitHub repository | `https://github.com/LittleChenLiya/dsh-superagent` | Installs from the repository. Add `#v0.14.0` if you need a fixed release. |
93
- | Local directory | `file:/absolute/path/to/dsh-superagent` | Copies the checkout. Re-add after changing the source. |
94
-
95
- Upgrading is remove-then-add, not in-place: remove the old copy
96
- (`dsh plugin --profile web remove @xiangyixie/dsh-superagent`) before adding
97
- the new version. The same applies to any other plugin already in that profile —
98
- remove and re-add it rather than expecting the dialog or `add` to replace it.
99
-
100
- Name the version. Without one, pnpm's minimum release age policy skips releases
101
- published in the last few hours and installs the newest older one, so a bare
102
- `add` succeeds while giving you a version that is not current. If you would
103
- rather track the newest release, add it to `minimumReleaseAgeExclude` in the
104
- profile's `pnpm-workspace.yaml`; otherwise bump the number above. Check what
105
- actually landed with:
106
-
107
- ```bash
108
- npm ls --prefix <DSH_HOME>/profiles/web @xiangyixie/dsh-superagent
109
- ```
110
-
111
- For an offline machine or a pinned artifact, install a packed tarball instead —
112
- it is byte-identical to what the registry serves:
113
-
114
- ```bash
115
- npm pack # writes xiangyixie-dsh-superagent-<version>.tgz
116
- dsh plugin --profile web add ./xiangyixie-dsh-superagent-<version>.tgz
117
- ```
118
-
119
- Look for this block in the dump. If it is missing, the plugin is installed but
120
- not mounted, and no `superagent_*` tool will exist:
121
-
122
- ```yaml
123
- # == @xiangyixie/dsh-superagent
124
- - id: superagent
125
- name: @xiangyixie/dsh-superagent
126
- ```
127
-
128
- ```bash
129
- # 3. start the host with the key in the environment that starts it
130
- export DEEPSEEK_API_KEY=sk-... # PowerShell: $env:DEEPSEEK_API_KEY="sk-..."
131
- dsh --profile web
132
- ```
133
-
134
- The key must be the one for the route the profile actually uses. A profile
135
- pointing at DashScope uses `DASHSCOPE_API_KEY`; a profile pointing at a
136
- self-hosted gateway uses whatever that route names. See
137
- [Other routes](#other-routes) if you want to add one.
138
-
139
- In the session, ask for a run:
140
-
141
- > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
142
-
143
- Shape of the reply (numbers illustrative — a full transcript of a real run is
144
- in [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md)):
145
-
146
- ```
147
- run 20261114T051233-a1b2 — completed
148
- goal: Explain the difference between process and thread in 300 words, with one concrete example
149
- plan: planned; subtasks 2/2 completed; max 3 in parallel; 2 attempt(s) each
150
- elapsed: 18.4s
151
- usage: input 4120 (+980 prompt tokens served from cache), output 455, calls 4 (deepseek-official/deepseek-flash: 4 call(s) 4120 in / 455 out)
152
- cost: not computed — no price configured for deepseek-official/deepseek-flash; add a pricing entry in cordis.patch.yml to get an estimate
153
- [1] completed (attempts 1) Processes vs threads
154
- [2] completed (attempts 1) Concrete example
155
-
156
- report:
157
- ...
158
- ```
159
-
160
- There is no built-in price for the default DeepSeek route; see
161
- [Spending limits and prices](#spending-limits-and-prices) to add one, after
162
- which the next run (or a resume of this one) prints `cost: ...`. `cost` is
163
- computed when a run settles, so an already-finished run keeps the "not
164
- computed" line. `usage: not recorded` only appears on a finished run whose
165
- child logs cannot be read at all — see [Troubleshooting](#troubleshooting).
166
-
167
- If `wait_seconds` runs out before the run finishes, the reply ends with
168
- `next: superagent_status run_id="..." wait_seconds=120`. Call it again; the run
169
- keeps going either way.
170
-
171
- To check recovery without a real crash: kill the host while a run is active,
172
- start it again, then `superagent_status` shows `interrupted` and
173
- `superagent_resume` finishes it. A run is only `interrupted` when no live
174
- process owns it: while the original host is still running, its run is left
175
- alone and the next mount reports it as active, not as interrupted.
176
-
177
- Two shutdown paths behave differently, and both are covered by the E2E record:
178
-
179
- - **Hard kill (or crash).** The heartbeat is a few seconds old, but on the
180
- machine that wrote the run the dead pid is checked first, so the next mount
181
- reclaims it immediately and prints
182
- `reclaimed: owner pid … is not running and this state directory is local`.
183
- A shared state directory written by another machine trusts the heartbeat
184
- instead, so reclamation there waits up to 90 s.
185
- - **Graceful shutdown.** If the host disappears while a run is in flight (for
186
- example a one-shot headless turn that ends after `wait_seconds: 0`), the
187
- plugin notices that the `subagents` service is gone, leaves the unfinished
188
- subtasks `pending`, and settles the run as `interrupted` with
189
- `note: the host shut down while this run was active`. No attempts are burned
190
- on a service that cannot answer. In that case the host process itself may
191
- linger until a child that ignores abort exits; that wait is the host's, not
192
- the plugin's.
193
-
194
- ## Configuration
195
-
196
- Row config in `<profile>/cordis.patch.yml`:
197
-
198
- ```yaml
199
- - id: superagent
200
- config:
201
- maxSubtasks: 8
202
- maxParallel: 3
203
- maxActiveRuns: 2
204
- ```
205
-
206
- | Key | Default | Meaning |
207
- | --- | --- | --- |
208
- | `stateDir` | `$DSH_HOME/state/superagent` | Run state root. |
209
- | `provider` | `spawn` | Subagent backend used for planner, workers, aggregator. |
210
- | `childProvider` | parent's | Optional provider route override for child agents. |
211
- | `childModel` | parent's | Optional model override for child agents. |
212
- | `childPreset` | none | Agent preset for child agents. A preset owns the child's tool set; this host has no per-run tool filter. |
213
- | `plannerPreset` | none | Agent preset for the planner child only. Use a tool-less preset: a planner only reads its prompt and returns JSON, and inherited tools invite a tool loop instead of a plan. Requires the host to compose an `agentPresets` registry. |
214
- | `plannerProvider` | parent's | Optional provider route override for the planner child. |
215
- | `plannerModel` | parent's | Optional model override for the planner child. Planning is a single JSON turn, so a stronger model here is usually cheaper than fixing plans after workers ran. |
216
- | `plannerTimeoutSeconds` | `120` | Wall-clock bound per planner attempt. On expiry the attempt is stopped and recorded; no fallback worker is started. |
217
- | `plannerMaxModelCalls` | `20` | Model calls the planning phase may spend across attempts; `0` disables. Once spent, the run fails as unplannable instead of draining the run budget. |
218
- | `maxSubagentDepth` | `1` | How deep children may delegate. `1` forbids grandchildren; `provider-managed` leaves it to the backend. |
219
- | `commandWorkerPermission` | `inherit` | Sandbox mode for workers whose plan entry declares a command capability (`shell`, `bash`, `pwsh`, …). `danger-full-access` lets those workers actually run commands on a `workspace-write` host; every other child keeps inheritance. See [Per-worker command permissions](#per-worker-command-permissions). |
220
- | `maxSubtasks` | `8` | Cap on planned subtasks. A tool argument can only lower it, never raise it; hard max 16. |
221
- | `maxParallel` | `3` | Subtasks executing at once. A tool argument can only lower it; hard max 8. |
222
- | `maxActiveRuns` | `2` | Active runs per state directory, across profiles and hosts that share it. A further `superagent_start` is rejected unless it passes `queue: true`, in which case it waits for a slot instead. `superagent_resume` is not counted and works when the cap is full, because it only finishes work that already exists. |
223
- | `maxQueuedRuns` | `5` | Runs allowed to wait for a free slot at once; hard max 32. `0` turns queueing off, so every start over `maxActiveRuns` is rejected again. |
224
- | `queueTimeoutMinutes` | `30` | How long a queued run waits before it fails without ever starting; nothing is spent. |
225
- | `queueOnFull` | `false` | Queue every start that exceeds `maxActiveRuns`, not only the ones that pass `queue: true`. |
226
- | `attempts` | `2` | Attempts per subtask before it is marked failed. A failure that looks transient (quota, rate limit, timeout, 5xx) waits 2s, then 4s, then 8s before the next attempt. |
227
- | `deadlineMinutes` | `120` | Wall-clock budget; on expiry the run ends `partial` or `failed`. |
228
- | `maxModelCallsPerRun` | `80` | Hard cap on child model calls per run; `0` disables. |
229
- | `maxTokensPerRun` | `2000000` | Hard cap on prompt + completion tokens per run; `0` disables. |
230
- | `pricing` | empty | Per-1M-token prices, keyed exactly as the usage log names the model (`provider/model`). Nothing is priced out of the box. |
231
- | `resultCapBytes` | `32768` | Bytes kept per subtask report. |
232
- | `notifyOnComplete` | `true` | Master switch for proactive messages. Off means the plugin never wakes the session. |
233
- | `maxNotificationsPerHour` | `3` | Proactive messages allowed per hour. Runs above the cap are folded into one summary; `0` disables the cap. |
234
- | `notifyRetries` | `2` | Extra delivery attempts when the host refuses a wake-up; messages for one session are delivered in order. |
235
- | `notifyRetryDelayMs` | `2000` | First delay between those attempts; it doubles per attempt, capped at 60s. |
236
- | `autoResumeRounds` | `1` | Extra rounds that retry subtasks which failed in a way that looks transient, before the failure is reported; `0` disables. |
237
- | `childModelFallback` | none | Model used on such a retry (quota, rate limit, timeout). Unset keeps the configured route. |
238
- | `memory` | `true` | Cross-run notebook. See [Cross-run memory](#cross-run-memory). |
239
- | `memoryScope` | `default` | Notebook file per scope, so unrelated projects can stay apart. Run notes are written here; `rules` and `profile` are read into every run. |
240
- | `memoryMaxEntries` | `60` | Compaction threshold: a write that would exceed it compacts the notebook down to this many notes (400 lines / 128 KB are hard caps too). |
241
- | `memoryMaxAgeDays` | `30` | Notes older than this are ignored, then compacted away. |
242
- | `memoryDigestEntries` | `12` | Notes injected into a prompt. |
243
- | `memoryDigestChars` | `1600` | Character budget for the note part of that prompt. |
244
- | `memoryUserProfile` | `false` | Cross-task user profile (facts, preferences, decisions) under `<stateDir>/user-memory`. Off means nothing is constructed and no directory is created. See [User profile](#user-profile). |
245
- | `keepRuns` | `0` | Delete terminal runs older than this many days at mount; `0` keeps everything. |
246
- | `guard` | on | Worker path and command policy. See [Worker safety guard](#worker-safety-guard) for every default and the reason behind it. |
247
- | `audit` | `true` | Append-only audit trail. It only observes; turning it off removes the trail, never the run behaviour. |
248
- | `policyFile` | `<stateDir>/policy.json` when it exists | Permission policy. Unset and absent means no policy, i.e. the old behaviour. |
249
- | `auditDir` | `<stateDir>/audit` | Where `audit.jsonl` and its exports live. |
250
- | `controlPort` | off | Loopback port for the embedding surface; `0` picks a free one. See [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md). |
251
- | `workspaceIsolation` | `false` | Give every worker its own git worktree so parallel workers cannot overwrite each other. See [Per-worker workspace isolation](#per-worker-workspace-isolation). |
252
- | `workspaceRoot` | host cwd | Repository the workers are isolated in when `workspaceIsolation` is on. Must be a git working tree with at least one commit. |
253
- | `workbenchPort` | off | Loopback port for the local workspace panel; `0` picks a free one. The panel reads and edits files itself, without a host API. |
254
- | `workbenchRoot` | `process.cwd()` | Directory the panel may browse and edit. Every path outside it is refused. |
255
- | `consolePort` | off | Loopback port for the conversation console; `0` picks a free one. Requires the host `sessionController` service. |
256
- | `consoleRoot` | `workbenchRoot`, then host cwd | Directory the console's conversation session joins. |
257
- | `consolePreset` | host default | Agent preset id the console session mounts. Tools follow this preset, not this plugin. |
258
- | `schedulerTickSeconds` | `30` | How often a live plan is checked for a due window, in seconds (1–3600). Nothing is armed until a plan exists, so this has no effect on an install with no schedules. |
259
- | `schedulerHumanPriority` | `true` | Default for a plan's `human_priority`: a scheduled run may not take the last free concurrency slot. |
260
- | `schedulerMaxConsecutiveFailures` | `3` | Consecutive failed executions before a plan pauses itself and says so once (1–20). |
261
-
262
- ### Switching models
263
-
264
- Model choice is configuration, not code. By default child agents inherit the
265
- session's model from the profile's `agent-default-model`. To pin children to a
266
- specific route, set both keys and restart the host:
267
-
268
- ```yaml
269
- - id: superagent
270
- config:
271
- childProvider: dashscope
272
- childModel: qwen-flash
273
- ```
274
-
275
- Nothing about a model id is compiled into the plugin. API keys are read from
276
- the environment variable named by the route; the plugin never stores a key. The
277
- default profile's route is `deepseek-official` and reads `DEEPSEEK_API_KEY`.
278
-
279
- ### Other routes
280
-
281
- The example above assumes a DashScope route is installed in the profile. It is
282
- not part of the base bundle: the default profile has no `dashscope` provider and
283
- `DASHSCOPE_API_KEY` alone will not create one. Add the route first (see the
284
- harness docs for LLM plugins), then name it in `childProvider`.
285
-
286
- ### Child tools and recursion
287
-
288
- `maxSubagentDepth: 1` is passed to the host as `maxDepth`, so a worker cannot
289
- create its own children. This is enforced by the host, not by prompting, and a
290
- provider that cannot enforce it makes `superagent_start` fail with an explicit
291
- error instead of silently running unbounded.
292
-
293
- There is **no** enforced tool allowlist on `dsh@0.2.2-rc.1`. The host's
294
- subagent start request has no tool filter, and its own `subagent` tool rejects a
295
- `toolFilter` config and points at agent presets. `childPreset` is therefore the
296
- supported way to narrow a child's tools; without a dedicated preset, workers
297
- inherit the session's tools. The `superagent_*` tools still exist in their tool
298
- list, but the run tools (`superagent_start`, `superagent_resume`, `superagent_cancel`,
299
- `superagent_followup`, `superagent_inject`, `superagent_answer`) refuse to run from a worker session;
300
- only the top-level agent manages runs.
301
-
302
- ### Per-worker command permissions
303
-
304
- A `workspace-write` host sandbox refuses a child process spawned with piped
305
- stdio (`EPERM`). A worker that needs to run `npm test` therefore cannot do so
306
- under the inherited policy, and this plugin will not turn the sandbox off for
307
- the whole machine. `commandWorkerPermission` raises it only for the workers that
308
- declare it:
309
-
310
- ```yaml
311
- - id: superagent
312
- config:
313
- commandWorkerPermission: danger-full-access
314
- ```
315
-
316
- With that setting, a worker whose plan entry has `requires` containing a command
317
- capability (`shell`, `bash`, `sh`, `zsh`, `fish`, `terminal`, `pwsh`,
318
- `powershell`, `cmd`, `run_command`, `exec_command`) gets full access. Planner,
319
- aggregator, acceptance judges, and workers without such a capability keep the
320
- inherited mode.
321
-
322
- How it works, and why it is a delegation trick rather than a host feature:
323
-
324
- - The host has no per-subagent permission field. What it does have is
325
- inheritance: `subagents.startActivation` captures the parent session's last
326
- `sandbox/mode` event **synchronously, before its first `await`**, and seeds
327
- that mode into the child.
328
- - For one qualifying worker, the plugin appends `sandbox/mode:
329
- danger-full-access` to the parent session, calls `startActivation`, and
330
- appends the previous mode back in a `finally` — all in the same synchronous
331
- tick, with no `await` between those steps. A concurrent call can therefore
332
- never observe the temporary override, and the child still captures it.
333
- - Both steps append one `sandbox/mode` event; the plugin never uses
334
- `permissionPresets.set()`, whose `custom` state cannot be restored by name.
335
- - The approval policy is pinned to `never` for that child by the host's own
336
- delegation capture, not by this plugin.
337
- - Each step is written to the audit trail as `worker.escalate` and
338
- `worker.restore` with `runId`, `subtaskId`, and the reason (the declared
339
- capability). When `audit` is off, no audit line is written; the escalation
340
- still behaves the same.
341
-
342
- Limits: this only applies to in-process providers whose child is created from
343
- the parent session in the same host process (`provider: spawn`). An upstream
344
- change to when the override is captured — or to delegation inheritance itself —
345
- makes this silently fall back to inheritance rather than fail the run. The
346
- temporary event also pins the previous mode in the parent log when the parent
347
- had no explicit override: it records the deployment default, which is
348
- behaviourally identical until that default changes.
349
-
350
- ### Per-worker workspace isolation
351
-
352
- Parallel workers are independent agents, but by default they share one working
353
- directory: two subtasks that edit the same file overwrite each other, and the
354
- last writer wins. `workspaceIsolation` fixes that by giving each worker its own
355
- checkout.
356
-
357
- ```yaml
358
- - id: superagent
359
- config:
360
- workspaceIsolation: true
361
- workspaceRoot: /home/me/projects/api # or C:\work\api on Windows
362
- ```
363
-
364
- **Why git worktrees rather than a directory copy.** The hard half of isolation
365
- is merging the results back. A worktree gives that for free: a real three-way
366
- merge with conflict detection, both sides preserved as refs, and one command the
367
- user can run to finish by hand. A recursive copy would either need a diff3
368
- engine (a dependency this package does not have) or overwrite the main checkout,
369
- which is the bug the feature exists to prevent. A worktree also shares the object
370
- database and ignore rules, so a worker sees the real repository without a full
371
- copy of it. Worktrees live under `.superagent/worktrees/<runId>/w<n>` inside the
372
- directory the host was started in — the repository itself when that is the
373
- starting directory. The host's `workspace-write` sandbox takes its writable
374
- boundary from the session cwd, so a checkout under the state directory, or
375
- inside a repository the host was not started in, would be denied every write.
376
- The pool carries its own `.gitignore`, so worker checkouts never leak into the
377
- user's next commit or make the main checkout look dirty.
378
-
379
- **What happens during a run.** Each worker is given
380
- `superagent/<runId>-w<n>`, a branch created from the main checkout's `HEAD`. Its
381
- prompt names the absolute path and forbids touching anything else, switching
382
- branches, committing, merging, or pushing. When the worker finishes, the run
383
- commits whatever it left in the checkout (so a model that forgot to commit still
384
- loses nothing; git hooks are skipped so a pre-commit hook cannot block the merge)
385
- and then merges the branches into the main checkout **one at a time**, after all
386
- subtasks are done.
387
-
388
- **What you see when a merge conflicts.** The merge is aborted, so the main
389
- checkout is restored exactly as it was and no conflict markers are left in it.
390
- The outcome is recorded on the run and printed by `superagent_status`:
391
-
392
- ```
393
- workspace conflict: [2] src/routes.js, src/index.js — branch superagent/20261115T101500-ab12-w2
394
- kept at <repository>/.superagent/worktrees/20261115T101500-ab12/w2; the main checkout was restored, so nothing
395
- was lost. Resolve with: git -C "/home/me/projects/api" merge superagent/20261115T101500-ab12-w2
396
- ```
397
-
398
- The wake-up message for the run says the same in one line, because a conflict is
399
- the one outcome that needs the user even when the run itself "completed". Nothing
400
- is discarded: the branch and its checkout are kept until you merge or delete
401
- them. Two more cases are reported the same way rather than silently dropped:
402
-
403
- - the main checkout has uncommitted changes when the merge is due — every
404
- branch is left unmerged, since merging into a dirty tree would mix your edits
405
- with the workers' and make an abort restore the wrong state;
406
- - the run was cancelled or hit its deadline before merging — the branches are
407
- kept and a resume reuses the same worktrees.
408
-
409
- **When isolation is not possible.** If `workspaceRoot` is not a git working tree,
410
- git is not on `PATH`, or the repository has no commit yet, the run does not fail.
411
- It falls back to the shared directory (the previous behaviour) and both
412
- `superagent_status` and the notification say so:
413
-
414
- ```
415
- workspace: isolation was requested but is unavailable — /tmp/notes is not a git working tree,
416
- so a per-worker worktree cannot be created; workers shared /tmp/notes, so their edits can
417
- overwrite each other
418
- ```
419
-
420
- **Limits, stated plainly.** `dsh@0.2.2-rc.1` gives a child agent no `cwd` field,
421
- so the plugin cannot hand a worker a directory at spawn time. Isolation is a
422
- prompt contract plus a real branch: a worker that ignores the prompt can still
423
- edit the main checkout, but that shows up in `git status` before any merge and
424
- cannot damage a sibling's branch. With isolation off, behaviour is exactly what
425
- it was before this option existed.
426
-
427
- ### Worker safety guard
428
-
429
- Workers inherit the session's filesystem and credentials, so every tool call a
430
- superagent child makes passes through a guard mounted on the host's
431
- `tools/pre-execute` path (`ctx.tools.guard` when available). The guard only
432
- policies children this plugin spawned; the parent session is untouched.
433
-
434
- ```yaml
435
- - id: superagent
436
- config:
437
- guard:
438
- enabled: true
439
- allowWriteRoots: [] # extra writable roots, absolute or ~-relative
440
- denyPaths: [] # extra read+write denials
441
- denyCommands: [] # [{ id, pattern, reason }] extra regex denials
442
- allowCommands: # explicit overrides; every use is recorded
443
- - id: clean-build
444
- pattern: '^rm -rf build$'
445
- reason: clean build output
446
- maxEvents: 50
447
- ```
448
-
449
- Defaults, and why they are set that way:
450
-
451
- | Rule | Default | Why |
452
- | --- | --- | --- |
453
- | Write roots | The child session's working directory plus the OS temp directory | A worker needs its own workspace and a scratch area. Everything else is outside the job, so it is refused. The state directory is deliberately **not** writable: a worker must not rewrite run records or reports. |
454
- | Always denied (read and write) | `~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.netrc`, `~/.npmrc`, `~/.yarnrc`, `~/.pypirc`, `~/.git-credentials`, `~/.docker/config.json`, `~/.kube/config`, `~/.config/gcloud`, `~/.config/gh/hosts.yml`, `~/.azure`, any `.git/config` and `.git/hooks` | These are credentials or code-execution vectors. A broader workspace never opens them. |
455
- | System directories | Writable by nobody (`C:\Windows`, `C:\Program Files`, `C:\ProgramData`, `/etc`, `/usr`, `/bin`, `/boot`, `/dev`, `/System`, `/Library`, …), except the OS temp directory | Reading them is normal (`win.ini`, `/etc/hosts`); writing them is not a development task. The temp exception exists because `%TEMP%` can live under `C:\Windows\TEMP` for service accounts, and workers must still be able to write scratch files there. |
456
- | `cmd/recursive-force-delete` | Denied when the target is `/`, a drive root, `~`, `.`, `..`, `*`, outside the write roots, or contains one | `rm -rf build` and `rm -rf node_modules` are normal; `rm -rf /` and `rm -rf .` are not. Blanket-blocking every `rm -rf` would make ordinary cleanup impossible, so the target decides. |
457
- | `cmd/disk-format` | `mkfs`, `diskpart`, `wipefs`, `format X:`, `dd of=/dev/sd*` | Never a development action. |
458
- | `cmd/system-scheduler` | `schtasks /create`, `Register-ScheduledTask`, `crontab -r`, `systemctl enable\|disable\|mask`, `launchctl load` | Persistence outside the workspace. |
459
- | `cmd/system-registry` | `reg add/delete` on `HKLM`/`HKCR`, and any `\Run` key | Machine-wide or auto-start changes. |
460
- | `cmd/system-write` | A redirection or write cmdlet whose target is a system directory, including `%SystemRoot%`/`$env:SystemRoot` | Catches writes that hide behind a variable. |
461
- | `cmd/permission-nuke` | `chmod -R 777 /`, recursive `chown` of `/`, `icacls … /grant Everyone /t` | Destroys the access model of the machine. |
462
- | `cmd/credential-access` | A shell command that names one of the credential locations above, `id_rsa`, `id_ed25519`, … | A worker reading a key is as harmful as writing one. |
463
-
464
- A denial is a real tool error, not a silent failure: the worker receives
465
- `[guard] blocked <tool>: rule <id> — <reason>. The call did not run.`, and the
466
- event is added to the run. `superagent_status` prints
467
- `guard: N tool call(s) blocked; M explicit allow(s) recorded (rule ×count)`
468
- plus up to three blocked commands, and the finished report gains a
469
- `## Safety guard` section listing every kept event. Counters cover all events
470
- even when `maxEvents` stops the list.
471
-
472
- `allowCommands` is the only override. It wins over a denial, but every match is
473
- recorded as `decision: allowed` with the rule it overrode, so an override is
474
- never invisible. Credential, `.git` control, and system-directory denials are
475
- not overridable; to permit a legitimate build directory outside the workspace,
476
- add it to `allowWriteRoots`. The guard is lexical and realpath based, so a
477
- symlink inside the workspace that points at a denied path is still caught.
478
-
479
- The guard is a policy layer over tool arguments, not an OS sandbox. A command
480
- that delegates the write to a program (`node build.js`, a compiler) can still
481
- write wherever that program runs; blocking that requires a host-level sandbox,
482
- which `dsh@0.2.2-rc.1` does not expose. The guard stops direct `write`/`edit`/
483
- `apply_patch` targets, shell redirections, and the destructive command classes
484
- above, which covers the accidental `rm` and "write into `C:\Windows`" cases a
485
- wandering worker actually produces.
486
-
487
- ### Spending limits and prices
488
-
489
- Two hard budgets stop a pathological goal before it can spend quietly. Both are
490
- checked before every child is spawned, so a retry loop cannot walk past them:
491
-
492
- ```yaml
493
- - id: superagent
494
- config:
495
- maxModelCallsPerRun: 40
496
- maxTokensPerRun: 500000
497
- pricing:
498
- deepseek-official/deepseek-flash:
499
- input: 0.28 # price per 1M uncached prompt tokens (example)
500
- output: 0.42 # price per 1M completion tokens (example)
501
- cacheRead: 0.028 # optional; defaults to the input price
502
- currency: CNY
503
- ```
504
-
505
- The pricing key is matched against the model id in the usage log, which is
506
- `provider/model` — `superagent_status` prints it on the `usage:` line, so copy
507
- the key from there. A key is matched exactly first, then by its bare model name,
508
- so `qwen-flash` also prices `dashscope/qwen-flash` when there is no exact entry.
509
- The plugin ships no price for any route, because a stale price is worse than a
510
- missing one.
511
-
512
- When a budget is hit, no new child starts and the abort controller stops the
513
- child that is still running, so spend stops at the cap instead of draining one
514
- more worker. Reports that already finished are still merged. The run ends
515
- `partial` when at least one subtask completed and `failed` when none did (the
516
- unfinished subtasks stay `pending`). `superagent_resume` rebuilds the limits
517
- from the current config, keeps everything already spent, and continues from
518
- there — that is how you raise a cap. On the real host, raising
519
- `maxModelCallsPerRun` from 2 to 80 and resuming a run that stopped at 2/2
520
- completed it without dropping the earlier spend.
521
-
522
- A spawn counts as one model call even when the child's session log cannot be
523
- read, so the call budget keeps working on a host whose log layout changed.
524
- Token accounting still needs the log; when it is unavailable, the run prints a
525
- `usage note:` saying the figures are a lower bound.
526
-
527
- Costs are estimates from the table above, never from a built-in guess. A model
528
- that is not listed is reported as `unpriced` and excluded from the total, so the
529
- number you see is always a lower bound:
530
-
531
- ```
532
- cost: at least ¥0.0041 (estimate; no price for haoduo/gpt-6.1-sol)
533
- ```
534
-
535
- Amounts are kept per currency and never added across currencies. A run that
536
- used both a CNY route and a USD route prints one subtotal per currency:
537
-
538
- ```
539
- cost: ¥0.0952 + $0.0248 (estimate; all models priced)
540
- ```
541
-
542
- The same rule holds for `superagent_list`'s ledger line, the live `watch`
543
- footer, the exported `README.md`, and the HTML report — a mixed window gets one
544
- figure per currency instead of a single number whose unit would be undefined.
545
-
546
- ## Runtime control
547
-
548
- The plugin can drive a browser and, on Windows, the desktop. Both halves are
549
- **off by default**: with `runtime.enabled` false not one of these tools is
550
- registered, so an existing profile sees exactly the same tool list as before.
551
- Nothing here needs an npm dependency — the browser is spoken to over the
552
- DevTools protocol with Node's own `WebSocket`, and the desktop is reached
553
- through `powershell.exe` and `user32.dll`.
554
-
555
- ```json
556
- {
557
- "@xiangyixie/dsh-superagent": {
558
- "runtime": {
559
- "enabled": true,
560
- "browser": {
561
- "headless": true,
562
- "allowedHosts": ["localhost", "127.0.0.1"],
563
- "executablePath": null,
564
- "attachPort": null,
565
- "userDataDir": null
566
- },
567
- "desktop": { "enabled": false, "allowActivation": false }
568
- }
569
- }
570
- }
571
- ```
572
-
573
- `enabled` turns the layer on. `browser.enabled` and `desktop.enabled` decide
574
- which halves register; desktop is separately gated because it can touch any
575
- application on the machine. `allowedHosts` replaces the loopback default — a
576
- leading `*.` matches any subdomain. `stopFile` and `shotDir` default to
577
- `<stateDir>/runtime/STOP` and `<stateDir>/runtime/shots`.
578
-
579
- `attachPort` and `userDataDir` are the two ways to reach a page that needs a
580
- sign-in, and they trade differently:
581
-
582
- - **`attachPort`** (for example `9222`) borrows the browser you started
583
- yourself with `--remote-debugging-port`. Element listing, clicks, typing, and
584
- screenshots all run on that connection, the tab keeps its own window size, and
585
- `browser_close` only detaches — it never terminates your browser. If the port
586
- is not listening the call fails with the port and a start command; it never
587
- falls back to a fresh profile behind your back. Because that profile is
588
- already signed in to whatever you use, every action inherits that access.
589
- - **`userDataDir`** keeps one dedicated profile for a browser this plugin
590
- launches: sign in once (QR code, SMS, whatever the site asks), and later runs
591
- reuse the same cookie jar. The directory is a real credential store on disk —
592
- keep it somewhere you would keep a password file, and do not point it at your
593
- daily browser's profile. It is ignored while `attachPort` is set.
594
-
595
- The default remains a fresh temporary profile under
596
- `%TEMP%/dsh-runtime-profile-*`, so an ordinary run cannot see your daily
597
- browser's cookies.
598
-
599
- ### What it registers
600
-
601
- | Tool | What it does |
602
- | --- | --- |
603
- | `browser_open(url, headless?, width?, height?)` | Launches a browser with its own fresh or persistent profile, or attaches to yours when `attachPort` is set; opens the URL, returns URL, title, viewport, and a screenshot path. A sign-in, CAPTCHA, SMS, or QR page comes back as `[attention]`. |
604
- | `browser_elements(text?, role?, limit?)` | Lists actionable elements with a stable index, accessible name, role, bounding box, and whether it is in the viewport. Matching is by visible text, ARIA name, or role — not only CSS. |
605
- | `browser_click(index?, css?, text?, role?, confirm?, screenshot?)` | Scrolls the element into view, dispatches a real mouse press/release at its centre, and screenshots afterwards. |
606
- | `browser_type(index?, css?, text?, value, submit?, screenshot?)` | Focuses the field, inserts text through the browser input pipeline, optionally presses Enter, and reports the value the page now holds (a password field is masked). |
607
- | `browser_screenshot(path?, full_page?)` | PNG of the page, with path, pixel size, and byte size. |
608
- | `browser_script(expression, await_promise?)` | Evaluates one expression and returns its JSON value; for reads, not for clicking. |
609
- | `browser_wait(text?, css?, url_contains?, milliseconds?, timeout_ms?)` | Waits for a condition or a fixed delay. |
610
- | `browser_await_human(timeout_ms?, poll_ms?, screenshot?)` | Waits for the person to clear a sign-in, CAPTCHA, SMS, two-factor, or QR check; returns ok when automation may continue, or `[attention]` if it is still pending. It never solves the check itself. |
611
- | `browser_close()` | Closes a browser this plugin launched. On an attach connection it only detaches and leaves your browser running. |
612
- | `desktop_screenshot(window?, path?)` | Whole desktop, or one window by title captured with `PrintWindow` (a covered window still yields its own pixels). |
613
- | `desktop_windows(filter?, limit?)` | Visible top-level windows: handle, title, pid, screen rectangle. |
614
- | `desktop_click(x, y, window?, activate?, right?, confirm?)` | Click at screen coordinates. Background by default; `activate` is required for a foreground click. |
615
- | `desktop_type(text, window?, activate?)` | Types into a window, background `WM_CHAR` by default. |
616
- | `desktop_keys(keys, window?, activate?)` | Presses named keys (`enter`, `tab`, `f5`, `a`, `1` …) in order. |
617
- | `runtime_status()` | Stop state, registered halves, allowed hosts, browser executable, attach/launch mode, session. |
618
-
619
- Every browser and desktop call writes one line to the existing audit trail
620
- (`lib/audit.js`) with `source: "runtime"`, the action, the target, the decision,
621
- the result, and the duration. A gate that refuses an action writes
622
- `decision: "deny"` or `"confirm"` and `result: "blocked"`, so the log can never
623
- claim that a refused click succeeded. Browser lines also carry `meta.session` —
624
- `"attach"` when the action ran on the browser you started (with `meta.port` and
625
- the tab it reused), `"launch"` when it ran on one this plugin started (with
626
- `meta.profile` and `meta.persistentProfile`) — so the trail can never confuse
627
- your session with a throwaway profile. A page that asks for a person writes
628
- `kind: "attention"`, `decision: "attention"`, and `result: "needs-human"`.
629
-
630
- ### Gates
631
-
632
- - **Emergency stop.** While the stop file exists — or `DSH_RUNTIME_STOP=1` is
633
- set — every action is refused and the refusal is audited. Create the file and
634
- the layer stops at the next call; delete it to re-enable.
635
- - **Navigation.** Only `http:` and `https:` on the allowed hosts. `file://` is
636
- refused because a page that could read local files would walk around the
637
- workspace guard; `javascript:`, `data:`, and `chrome:` are refused too.
638
- - **Uploads.** `browser_click` refuses an `<input type="file">`, because the
639
- native file picker that follows cannot be driven and would fall through to the
640
- user's own file system.
641
- - **Irreversible actions.** A target whose label reads submit, delete, pay,
642
- publish, transfer, 提交, 删除, 支付 … needs `confirm: true`. Without it the
643
- click does not happen and the audit line records `decision: "confirm"`.
644
- - **Human checks.** A page asking for a sign-in, CAPTCHA, SMS code, two-factor
645
- confirmation, or QR scan stops the action at that point and returns
646
- `[attention]` with what the page wants and how to hand over. The check is read
647
- from the page text, so an ordinary settings page with a password field but no
648
- sign-in wording is not flagged; nothing here solves or types the check. In a
649
- launched window or an attached tab the person finishes it in the browser, then
650
- `browser_await_human` polls until it is gone and the run continues. A pending
651
- check is a hand-off, not a failed run.
652
- - **Focus.** A background click or keystroke never brings a window forward. A
653
- foreground action requires `activate: true` **and**
654
- `runtime.desktop.allowActivation: true`, and each activation is recorded in
655
- `meta.activated`.
656
- - **Worker agents.** `browser_*` and `desktop_*` belong to the session that
657
- mounted the plugin. The guard blocks them for bound child agents with rule
658
- `guard/runtime-tool` unless `guard.allowRuntimeTools` is true.
659
-
660
- ### What it deliberately cannot do
661
-
662
- - **Borrow your logins by accident.** A launched browser gets a fresh profile
663
- under `%TEMP%/dsh-runtime-profile-*`, so your cookies, saved passwords, and
664
- signed-in sessions are simply not there. Reaching an authenticated page is an
665
- explicit choice: attach to a browser you started with
666
- `--remote-debugging-port` and set `browser.attachPort`, or point
667
- `browser.userDataDir` at one dedicated profile and sign in there once. Both
668
- make that access available to every later action, and both are visible in
669
- `meta.session` in the audit log; a wrong attach port fails with instructions
670
- instead of silently starting a profile.
671
- - **Solve human verification for you.** CAPTCHAs, SMS codes, "confirm you are
672
- human" interstitials, and QR logins stop the action and hand it back. It never
673
- types a code or scans a code for you; it waits for you to do it and then
674
- reports that the run may continue.
675
- - **Evade bot detection.** A launched Chromium is detectable through CDP
676
- artefacts, and sites that block automation will block this. Nothing here
677
- patches `navigator.webdriver` or spoofs fingerprints.
678
- - **Type into every application.** Background `WM_CHAR` reaches classic Win32
679
- controls; Chromium, Electron, Qt, and most games ignore posted messages. For
680
- those, either `activate: true` and accept the focus change, or drive the page
681
- through `browser_*` instead.
682
- - **Guess coordinates.** `desktop_*` takes physical screen pixels. With mixed
683
- DPI scaling, take a `desktop_screenshot` first and read the rectangle from
684
- `desktop_windows` rather than computing it.
685
- - **Control macOS or Linux desktops.** The desktop half is Windows-only. The
686
- browser half works anywhere a Chromium-family binary exists.
687
-
688
- Two runnable proofs ship with the repository. `node scripts/runtime-demo.mjs`
689
- starts a local page, clicks a button, reads the counter back out of the DOM,
690
- types into a field, is refused on an irreversible button and on a file input,
691
- flips the stop switch, and prints the audit lines and screenshot paths.
692
- `node scripts/runtime-desktop-demo.mjs` opens a no-activate test window, posts a
693
- click and text into it, verifies both from the target process's own state file,
694
- and captures the window.
695
-
696
- ## Tools
697
-
698
- - `superagent_start(goal, mode?, queue?, max_subtasks?, max_parallel?, deadline_minutes?, allow_duplicate?, wait_seconds?)`
699
- starts a run and returns immediately with a run id. `mode: "direct"` runs the
700
- goal on one worker with no planner and no aggregator, and returns that worker's
701
- reply as the report unchanged — right for one self-contained lookup, edit,
702
- query, or short piece of writing, wrong for a goal with parts that can run in
703
- parallel. The default, `mode: "planned"`, does the full planner → workers →
704
- merged report pipeline. A planned subtask may declare `dependsOn` another
705
- subtask: the dependent waits for it and gets its report in its prompt, while
706
- independent subtasks still run in parallel. A dependency cycle rejects the
707
- plan before any work starts, and a dependency on a task the plan never
708
- declared is skipped with the reason. Both modes produce the same run record,
709
- quota, deadline, cancel, and usage accounting. `goal_mode: true` adds an
710
- acceptance step and re-plans a failed round; see [Goal mode](#goal-mode).
711
- `queue: true` makes a start wait for a free slot when `maxActiveRuns` is in use
712
- instead of failing: it returns `status: "queued"` with `queue.position` /
713
- `queue.of`, starts automatically when an active run finishes, and fails after
714
- `queueTimeoutMinutes` if no slot frees. At most `maxQueuedRuns` waits; a queued
715
- run does not count against `maxActiveRuns` while it waits, and cancelling it
716
- removes it from the line cleanly. Starting a goal that an
717
- active run in the same session already covers returns that run id marked
718
- `deduped: true` instead of paying for a second plan: the goal is compared after
719
- trimming, collapsing runs of whitespace, and ignoring case, and the check runs
720
- under a per-goal claim keyed in the state directory, so two processes that share
721
- it still start one run. The match is per session, because two sessions may
722
- legitimately ask for the same generic goal at once.
723
- `allow_duplicate: true` starts another one. A finished run never blocks the same
724
- goal from being started again. `wait_seconds` blocks for a terminal state and
725
- keeps the `deduped` marker in its result.
726
- - `superagent_status(run_id, wait_seconds?)` returns status, milestones,
727
- per-subtask outcome, measured token usage, estimated cost, the report file
728
- path, and the final report.
729
- - `superagent_list(limit?)` lists runs, newest first, plus the state directory's
730
- file count and size.
731
- - `superagent_cancel(run_id)` stops the run, from any process; see below.
732
- - `superagent_resume(run_id, wait_seconds?, force?)` continues an `interrupted`,
733
- `failed`, `partial`, or `cancelled` run; completed subtasks are kept. Workers
734
- are told what failed and to check what the earlier attempt already did. Only
735
- the session that started the run may resume it. A resume is not counted
736
- against `maxActiveRuns`, so it works when the cap is full; `force` is still
737
- accepted but no longer needed. A `completed` run stays completed unless it
738
- holds an answer that never reached a prompt — then resume reopens it, because
739
- otherwise that decision would be stranded.
740
- - `superagent_followup(run_id, message)` adds an instruction to a run that is
741
- already executing, instead of starting a second run. This tool is explicitly
742
- next-prompt: the instruction is queued on the run and the next prompt built for
743
- it carries it — the next worker spawn or the aggregation, whichever comes
744
- first. Subtasks that are already running or finished keep their results and
745
- never see it. The reply names that boundary, and status shows the same thing;
746
- an instruction that arrives after the last boundary is recorded as
747
- `never took effect` rather than looking delivered. A paused run
748
- (`interrupted`, `failed`, `partial`, `cancelled`) keeps the instruction for
749
- the next round, which starts when it is resumed; a `completed` run refuses it.
750
- A run owned by another process is refused, because that owner's next save
751
- would overwrite it. Only the session that started the run may add to it. Use
752
- `superagent_inject` when the running workers must read the instruction now.
753
- - `superagent_inject(run_id, message, subtask_index?, wait_seconds?)` delivers
754
- one instruction into the workers that are running right now. It uses the
755
- host's live steering channel (`subagents.sendMessage`, the same inbox the
756
- agent loop drains at its next pre-step), so the message is part of the child's
757
- next model request. It does not interrupt a model call already in flight: the
758
- delay is the remainder of the step that is running (that model response plus
759
- its tool batch). A live child that had already decided to stop runs one more
760
- turn to read it, so an uncancelled child consumes it. The reply reports the
761
- measured delay from acceptance to the child's next request, and marks a
762
- message as `missed` — never as delivered — when the child is cancelled,
763
- disposed, or finishes before another boundary. Worst case measured on a real
764
- `dsh@0.2.2-rc.1` host: **6978 ms** with an 8 s child step and **2986 ms** with
765
- a 4 s step, i.e. the bound tracks the step, not the plugin. With a host that
766
- exposes no live channel, the tool degrades to the followup queue and says so
767
- in the reply; it never calls that live.
768
- - `superagent_answer(run_id, attention_id?, answer, wait_seconds?)` answers one
769
- structured attention item so that run continues with the decision. An active
770
- run applies the answer at its next boundary; a finished run is reopened and
771
- only its aggregation runs again, now with the answer in the prompt, so the
772
- report reflects the decision instead of the user starting a new run.
773
- `attention_id` is required when more than one question is open. An answer is
774
- matched to the id, not to the array position: an id that was never asked, a
775
- question already answered, and a question retired by a later resume are all
776
- refused, and an answer whose text is another question's option names that
777
- other id instead of guessing.
778
- - `superagent_memory(action, key?, kind?, text?, scope?, query?, tags?, limit?)`
779
- lists, searches, adds, corrects, or forgets notebook notes. `set` with an
780
- existing key supersedes it; `forget` retracts it. `scope` addresses `rules`
781
- (project rules), `profile` (user preferences), or the run scope. `search`
782
- ranks notes against `query` (the current goal works well) and/or exact `tags`,
783
- so a relevant old note is found instead of only the newest ones; notes can
784
- carry `tags` when set. The tool is additive: the eleven other tools keep their
785
- arguments and output.
786
- - `superagent_template(action, id?, params?, template?, limit?)` lists, shows,
787
- expands, saves, or deletes a workflow template: a fixed goal skeleton with
788
- required parameters, when it fits, and when it does not. `expand` returns one
789
- ordinary goal string, which `superagent_start` plans exactly like a typed goal;
790
- a missing or empty parameter is refused by name instead of defaulted. A
791
- template cannot set limits, budgets, a mode, or an override, so using one never
792
- widens what a run may do. Built-in ids are read-only; custom ones live under
793
- the template directory in the state directory, and a failure there is logged
794
- without disabling the run tools.
795
- - `superagent_schedule(action, id?, name?, goal?, template_id?, params?, cron?,
796
- every_minutes?, timezone?, miss_policy?, goal_mode?, acceptance?, max_rounds?,
797
- max_wall_clock_minutes?, no_progress_rounds?, budget?, human_priority?)` creates,
798
- lists, pauses, resumes, deletes, or runs a scheduled plan now. A plan stores a
799
- goal (or an expanded template), a clock, and its own limits; it survives a host
800
- restart and starts runs nobody asked for. Nothing is armed until a plan exists.
801
- See [Scheduled runs](#scheduled-runs).
802
- - `superagent_audit(run_id?, subtask_id?, kind?, decision?, result?, target?,
803
- since?, until?, limit?, order?, format?, out_path?)` reads the audit trail, or
804
- exports the matching events as one JSONL or CSV file. See
805
- [Permissions and audit](#permissions-and-audit).
806
-
807
-
808
- ## Goal mode
809
-
810
- A normal run finishes when its subtasks finish. That is not the same as the goal
811
- being met, and a plan can report success over a broken build. Goal mode is an
812
- opt-in (`goal_mode: true` on `superagent_start` or `superagent_schedule`) that
813
- adds an independent acceptance step and keeps the run going until every
814
- condition passes or a hard stop says a person has to decide.
815
-
816
- - **Acceptance conditions.** `acceptance` is required and is a list of
817
- `{id?, text, check?}`. A `check` of `{"type":"command","command":"npm test"}`
818
- or `{"type":"file","path":"dist/app.js"}` is run by the plugin itself, so that
819
- verdict rests on a real exit code or a real file, never on a model's claim. A
820
- condition without a check is judged by a separate acceptance model, and
821
- `superagent_status` names the source of every verdict. At most 12 conditions
822
- are accepted; a longer list is a badly framed goal, not a checklist.
823
- - **Rounds.** A failed round does not repeat the same work: the next round's
824
- plan receives what failed and why. `max_rounds` (default 5, max 20),
825
- `max_wall_clock_minutes` (default 60), and `no_progress_rounds` (default 2)
826
- bound it. When the acceptance has a machine check, a round that changed no
827
- file stops immediately instead of paying for another one.
828
- - **Hard stops.** The loop stops with a reason instead of looping forever: the
829
- round cap, the wall clock, the run deadline, a budget stop, an open attention
830
- item, two identical failing rounds, or a round that cannot make progress.
831
- The stop report lists every condition with its last result and what was tried.
832
- - **Notifications.** One notification when the goal is met or the loop stops —
833
- none between rounds. The run record, status line, and report all carry the
834
- round count and each condition's verdict.
835
-
836
- Goal mode is off by default, adds no tool of its own, and changes nothing about
837
- a run that does not pass `goal_mode: true`.
838
-
839
- ## Scheduled runs
840
-
841
- `superagent_schedule` stores a plan — a goal plus a clock — and starts it
842
- without anyone calling `superagent_start`. A scheduled run is an ordinary run:
843
- same planner, same quota, same budgets, cancel, usage accounting, report, and
844
- status. The scheduler is only a timer-shaped caller of the orchestrator, not a
845
- second run engine.
846
-
847
- ```text
848
- superagent_schedule(action: "create", name: "nightly audit",
849
- goal: "Audit yesterday's error logs and list anything new",
850
- cron: "0 3 * * *", timezone: "Asia/Shanghai",
851
- budget: { max_total_runs: 30, max_total_tokens: 5000000 })
852
- ```
853
-
854
- Actions are `create`, `list`, `pause`, `resume`, `delete`, and `run-now`.
855
- `run-now` starts one execution immediately without moving the next planned
856
- window. A plan may name a `template_id` and `params` instead of a literal
857
- `goal`; the template is expanded at create time, so editing the template later
858
- does not silently change an existing plan.
859
-
860
- A plan stores its clock (`cron` or `every_minutes`, plus `timezone`), the goal,
861
- an optional `mode` / `goal_mode` with acceptance, its own `budget`, and its
862
- `human_priority`. Plans persist to `schedules.json` in the state directory and
863
- are reloaded at mount, so a host restart keeps them. The timer starts only when
864
- at least one plan exists; the state file is not created by `init()` on an empty
865
- state directory.
866
-
867
- ### Missed windows
868
-
869
- A window that comes due while the host is down is **not** replayed in full. The
870
- default policy, `miss_policy: "latest"`, runs only the newest missed window and
871
- records every other due window as `missed` with its scheduled time and the
872
- reason (the host was not running at that time); the plan then advances to its
873
- next window on the normal grid. The run that executes that newest window is a
874
- catch-up, and the plan says so: `totalRuns` counts it, `catchUpRuns` counts how
875
- many runs were catch-ups, and the `started` history entry names the window and
876
- the number of missed windows it stands in for. `miss_policy: "none"` skips all
877
- due windows while the host was down, records the count, and resumes at the next
878
- scheduled window. Catch-up work is bounded, so a laptop that was off for a month
879
- does not queue thousands of runs.
880
-
881
- The counters are separate on purpose: `missedRuns` is how many windows never
882
- ran, `catchUpRuns` is how many ran late, and `skippedRuns` is how many were
883
- passed over because the previous run was still active. `list` prints all three.
884
-
885
- A plan also never overlaps itself: if the previous execution is still active
886
- when a new window comes due, that window is not started and is recorded as
887
- `skipped: previous run still active`. The next window is evaluated normally.
888
-
889
- ### Completion requires an artifact
890
-
891
- A worker ending its turn with `completed` is not, by itself, a completed
892
- subtask. When a subtask declares `deliverables` (file paths, relative to its
893
- working directory), every listed file must exist, be a file, and be non-empty
894
- before the subtask counts. With no file declared, the reply text is the
895
- artifact, so an empty or whitespace-only reply is rejected with
896
- `empty deliverable: ...` and the subtask is retried or failed like any other
897
- incomplete attempt. A run whose report strips down to nothing is recorded as
898
- `partial`, never `completed`, so a schedule cannot report success for an empty
899
- result.
900
-
901
- ### Quota and manual priority
902
-
903
- Scheduled runs share `maxActiveRuns` with manual runs. With
904
- `human_priority: true` (the default, also configurable with
905
- `schedulerHumanPriority`), a scheduled run may not occupy the last free slot:
906
- when only one slot is free it waits for the next tick instead of blocking a
907
- `superagent_start`. A scheduled run also never enters the queue, so a person's
908
- `superagent_start(..., queue: true)` is never pushed back by a timer. When the
909
- cap is reached, the due window stays due and is retried on a later tick,
910
- without spending anything.
911
-
912
- ### Budget and failures
913
-
914
- `budget.max_model_calls` / `max_tokens` cap one execution;
915
- `budget.max_total_model_calls` / `max_total_tokens` / `max_total_runs` cap the
916
- plan across executions. Reaching a plan total pauses the plan and records the
917
- reason on the plan and in its run report; reaching a per-run cap ends that
918
- execution the same way a manual run ends.
919
-
920
- A failed execution does not notify on every retry. The first failure is
921
- reported once, and `schedulerMaxConsecutiveFailures` (default 3) consecutive
922
- failures pause the plan and report that once. A success resets the counter.
923
- Notifications are otherwise limited to: the goal was achieved, the budget was
924
- reached, or a run needs a decision. Milestones and ordinary progress stay in
925
- `list` / `status` and never wake the session.
926
-
927
- ### Cron support
928
-
929
- Cron parsing is built in and has no dependency. Supported: the standard five
930
- fields (minute hour day-of-month month day-of-week), `*`, `*/n`, ranges
931
- (`1-5`), lists (`1,15,30`), month and weekday names (`JAN`, `MON-FRI`), and `0`
932
- or `7` for Sunday. Day-of-month and day-of-week together are OR-ed, as in
933
- classic cron.
934
-
935
- Not supported, and refused at create time with the offending field number:
936
- seconds, a year field, `@daily`-style macros, and the `L`, `W`, `#`, and `?`
937
- extensions. An expression with six fields is rejected as “field 1 is not a
938
- minute” rather than being reinterpreted. Time zones use IANA names and are
939
- evaluated in the zone the expression was written in, never the host's zone; a
940
- time that does not exist at the spring DST jump is skipped, and an ambiguous
941
- autumn time uses the earlier offset.
942
-
943
- ### What a plan needs from the host
944
-
945
- Each plan is owned by the session that created it (or an explicit
946
- `session_id`), and that owner is resolved **on every window**, not captured once.
947
- If the session is live, it is used as is. After a host restart the plugin asks
948
- the host to resume the persisted session (`agents.resume`, or the Host Session
949
- API where that is the available surface); if the session was deleted, it creates
950
- a replacement and the plan adopts the new id (recorded as `owner-recovered`). A
951
- plan therefore survives a restart without depending on the original process or
952
- conversation staying open.
953
-
954
- When the host exposes no way to resume or create a session at all, that limit is
955
- recorded at `create` time instead of being discovered as a pause. The response
956
- carries a warning and the plan is marked `requires a resident session`; when a
957
- window finds no live owner it is recorded as `blocked`, announced once, and the
958
- plan stays enabled. It is not silently paused after three windows.
959
-
960
- Nothing runs and nothing is written until the first `create`. An installation
961
- with no plans behaves exactly as it did before this tool existed.
962
-
963
- ## Progress, decisions, and artifacts
964
-
965
- - **Plan honesty.** Before a worker starts, the planner names what it cannot map
966
- to a concrete object: an ambiguous phrase goes into `ambiguities`, and a
967
- question only the user can answer goes into `needsInput`, so the run stops and
968
- asks instead of inventing a name that looks plausible. Each assumption the
969
- planner does make is recorded on that subtask (`assumptions`) and printed in
970
- status and in the report, so a guess is visible instead of silent. A plan
971
- whose questions arrive together is one decision point, not a drip of prompts.
972
- - **Capability preflight.** A subtask may declare `requires` (`shell`,
973
- `net.http`, `browser`, `gui`, `desktop`, `git`, `gh`). The host compares that
974
- list with the tools this session actually has before any worker is spawned.
975
- A subtask whose capability is missing is `blocked`, with the capability and
976
- what would enable it named; it never starts and is never counted as success,
977
- and everything downstream of it is skipped for that reason. When the host
978
- cannot list its tools, preflight records `unavailable` and blocks nothing
979
- rather than guessing an inventory.
980
- - **Milestones.** Every run records `plan_ready`, `running`, `aggregating`, and
981
- `settled` with a timestamp, shown in `superagent_status`. They never produce a
982
- proactive message; progress stays visible without becoming noisy.
983
- - **Attention.** A worker or the aggregator may append one fenced `attention`
984
- block with a question that only the user can answer. It is stripped from the
985
- report, stored on the run as `attention.items`, shown as `needs your decision:`
986
- in status, and leads the notification when the run finishes. Every item gets a
987
- stable id (`q1`, `q2`, …) from a counter on the run, so a question means the
988
- same thing across saves and resumes. The question, options, and reason are
989
- collapsed to one line and capped at 500 / 200 / 300 characters, so the block
990
- cannot inject a forged status or notification line. A block that is not valid
991
- JSON or has no question is kept in the report, and status prints
992
- `attention: <reason>` instead of hiding the request.
993
- - **Answering.** `superagent_answer` records the decision on that item and lets
994
- the run continue: an active run carries it into its next prompt, a terminal
995
- run is reopened so the aggregation runs again with the answer. The question is
996
- archived (not deleted) when a resume retires it, which is what lets a late
997
- answer be refused with `expired at <time>` instead of being attached to
998
- whatever is open now.
999
- - **Instructions during a run.** Two boundaries, kept distinct.
1000
- `superagent_followup` appends to the dialog log and is carried by the next
1001
- prompt built for the run: each instruction records `appliedAt` /
1002
- `appliedAtStage` when a prompt first carries it, or `missedAt` when the run
1003
- settled first. `superagent_inject` instead steers a live child's inbox and is
1004
- claimed at its next pre-step; its receipt records `latencyMs` measured from
1005
- acceptance to that claim, or `missedReason` when the child left first. Status
1006
- prints both, so a queued instruction and a live one are never confused.
1007
- - **Report file.** A terminal run writes its report to
1008
- `<stateDir>/reports/<runId>.md` with an atomic rename, so the outcome has a
1009
- path that can be opened or attached. The directory carries a `.gitignore` with
1010
- `*`, and the path is recorded in `run.artifacts` and shown in status.
1011
- - **Dependencies between subtasks.** The planner may give a subtask an id and a
1012
- `dependsOn` list; the dependent then waits (`waiting`) instead of starting,
1013
- and its prompt carries the finished dependency's report. Independent subtasks
1014
- still run in parallel. An unknown reference is `skipped` with the reason, a
1015
- failure skips everything downstream rather than reporting it as done, and a
1016
- cycle rejects the plan before any subtask starts. Status and the report show
1017
- waiting separately from running.
1018
-
1019
- ## Permissions and audit
1020
-
1021
- Two independent layers sit around a run. A **policy** decides whether an action
1022
- may happen; an **audit trail** records what was decided and what followed. The
1023
- trail is on by default because it only observes. A policy changes nothing until
1024
- one exists, and it can only tighten what the plugin does on its own.
1025
-
1026
- ### Policy
1027
-
1028
- Copy [docs/policy.example.json](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/policy.example.json) to
1029
- `<stateDir>/policy.json`, or name another file with `policyFile`. Rules are
1030
- matched in this order:
1031
-
1032
- 1. a `paths.deny` / `commands.deny` pattern -> `deny` (deny always wins);
1033
- 2. an explicit `paths.allow` / `commands.allow` entry -> `allow`;
1034
- 3. the action kind listed under `confirm.actions` -> `confirm`;
1035
- 4. the run's `runs.<id>.level`, else `defaultLevel`.
1036
-
1037
- An allow entry that beats a `confirm` or a per-run `deny` is recorded with
1038
- `meta.relaxedFrom`, so a person can always see where the policy was opened up.
1039
- Relative path patterns match at any directory boundary (`src/**` covers
1040
- `/anywhere/repo/src/a.js`) but not a sibling that merely ends the same way
1041
- (`xsrc/a.js`). A command entry without `*` is a prefix on whole tokens
1042
- (`git status` permits `git status --short`, not `git statusx`); a composite line
1043
- (`git status && curl ...`) can never be lifted above `confirm` by a prefix.
1044
-
1045
- `policy.json` may contain `//`, `#`, and `/* */` comments. A schema problem is
1046
- reported with the file, line, and column:
1047
-
1048
- ```
1049
- policy.json: 1 problem in the permission policy
1050
- policy.json:3:19 [defaultLevel] must be one of allow | confirm | deny
1051
- "defaultLevel": "maybe",
1052
- ^
1053
- ```
1054
-
1055
- An unreadable or invalid policy **fails closed**: governed actions are denied and
1056
- `superagent_audit` prints the problem. A start or resume that is denied is
1057
- refused before any state changes; one held for `confirm` needs
1058
- `approve_policy: true` on the next call, and that approval is written as an
1059
- `approved` event naming the held event. An approval cannot release a `deny`.
1060
-
1061
- ### Audit
1062
-
1063
- `<stateDir>/audit/audit.jsonl`, one JSON object per event:
1064
-
1065
- ```json
1066
- {"v":1,"id":"evt_...","at":"2026-11-15T10:04:11.238Z","runId":"20261115T100400-ab12cd34","subtaskId":"subtask-2","actor":"session:9f3c","kind":"path.write","action":"path.write","target":"C:/work/app/src/db.js","decision":"allow","result":"ok","durationMs":4,"rule":"paths.allow[0]","source":"policy","meta":{"relaxedFrom":"confirm","reason":"..."}}
1067
- ```
1068
-
1069
- Every event carries the run, the subtask, the actor, a timestamp, the decision,
1070
- the result, and how long the check took. Higher layers may add `tool.call` and
1071
- `command.exec` events. Triggered by the plugin itself: `run.start`, `run.resume`,
1072
- `run.cancel`, `run.finish`, `attention`, plus `blocked` when a policy denies and
1073
- `approved` when a person releases a held action.
1074
-
1075
- Appends are serialized inside the process and guarded by a `wx` lock file across
1076
- processes, and each event is written with one append, so two workers finishing at
1077
- the same moment cannot splice a line. A trailing fragment left by a crash is
1078
- reported as `torn` and skipped; a damaged line is counted as `invalid` and does
1079
- not hide the rest.
1080
-
1081
- `superagent_audit` reads by run, subtask, kind, decision, result, target text, and
1082
- time window. With `format: "jsonl"` or `format: "csv"` it writes one deliverable
1083
- file (default `<stateDir>/audit/audit-export-<time>.<ext>`) and returns its path.
1084
-
1085
- A path/command guard can be attached without the audit layer knowing its rules:
1086
- `createAuditor({ dir, policyFile }).attachGuard(request => ({ decision, reason }))`.
1087
- The guard may only tighten the decision the policy produced; a guard that throws
1088
- is treated as a block. A guard that answers `{ blocked, rule, reason }` — the
1089
- shape a tool-call guard already produces — is understood as well.
1090
-
1091
- ## Cross-run memory
1092
-
1093
- A run is isolated on purpose: planner and workers start empty. Without a
1094
- notebook, every run repeats work the last one already finished and rediscovers
1095
- the same traps. The plugin keeps two different things, and only one of them is
1096
- stored:
1097
-
1098
- 1. **What happened** is derived from the run store at planning time. The six
1099
- most recent runs are rendered as one line each (date, status, completed
1100
- subtasks, goal, run id). Nothing is copied, so it cannot drift from the run
1101
- records.
1102
- 2. **What was learned** is a small curated notebook: decisions, pitfalls, next
1103
- steps, and which work was delegated. The aggregator returns it inside a
1104
- fenced `memory` block that is removed from the report before the user sees it.
1105
- A run that produces no block writes nothing; the plugin never invents a note.
1106
-
1107
- **Storage.** `<stateDir>/memory/<scope>.jsonl`, one JSON object per line. A line
1108
- is `{v,id,ts,key,kind,text,runId,status}`; `key` is a short slug (`deploy-target`)
1109
- and `kind` is `decision`, `pitfall`, `next`, `dispatch`, or `note`. The directory
1110
- contains a `.gitignore` with `*`, so even a `stateDir` that points inside a
1111
- repository cannot commit the notebook. It is never listed in the package `files`
1112
- whitelist, so it never ships to npm.
1113
-
1114
- **When it is written.** Once per run, at settle, only for a terminal run whose
1115
- report carried a block. A resume that settles the same run again is a no-op
1116
- because the store records the writing run id. A write failure is recorded on the
1117
- run (`memoryWrite.reason`) and never fails the run.
1118
-
1119
- **When it is read.** Once at `superagent_start` (and again at `superagent_resume`,
1120
- since the aggregator will run again), before planning. The composed context is
1121
- stored on the run as `memory.digest`, injected into the planner and aggregator
1122
- prompts, and summarised in `superagent_status`.
1123
-
1124
- **Layers.** Three scopes are read, in order: `rules` (project rules), `profile`
1125
- (user preferences), then `memoryScope` (what earlier runs learned). The first
1126
- two are curated with `superagent_memory` and are never written by a run, so a
1127
- rule cannot be overwritten by a model's observation. Each layer is labelled in
1128
- the prompt and bounded on its own; `memory.scopes` on the run lists what was
1129
- read.
1130
-
1131
- **Size.** Each note is capped at 400 characters after redaction. A prompt sees at
1132
- most `memoryDigestEntries` notes inside `memoryDigestChars` characters, plus six
1133
- one-line run summaries, hard-capped at 2600 characters in total. The file is
1134
- compacted when a write would push it past `memoryMaxEntries` notes, 400 lines,
1135
- or 128 KB; compaction keeps the newest `memoryMaxEntries` notes.
1136
- Context cannot grow with the number of runs.
1137
-
1138
- **Concurrency.** Within a process, writes to one scope are serialised. Across
1139
- processes, each batch is appended as one small `write` (no read-modify-write of
1140
- the whole file), compaction takes a lock file and replaces the file from a temp
1141
- file, and a truncated last line from a killed process is skipped. Two runs
1142
- finishing at once cannot overwrite each other's notes; a line may land in a
1143
- different order, and resolution is by timestamp, never by position.
1144
-
1145
- **Search.** `superagent_memory` with `action: "search"` ranks notes by `query`
1146
- keywords and exact `tags` instead of returning the newest ones, and the planner
1147
- digest uses the same ranking against the run's goal. A relevant note from weeks
1148
- ago therefore still reaches the prompt when it matches, while unrelated notes do
1149
- not crowd out the budget. Notes can carry `tags` when set.
1150
-
1151
- **Correction.** A newer note with the same key supersedes the old one. An
1152
- explicit `forget` writes a tombstone. Notes older than `memoryMaxAgeDays` stop
1153
- being injected and are dropped at the next compaction. Every note is shown with
1154
- its age and the digest tells the model the notes may be stale and must be
1155
- verified, so a wrong conclusion can be refuted by a later run instead of
1156
- becoming a permanent bias.
1157
-
1158
- **Privacy.** Notes are written outside the repository by default
1159
- (`$DSH_HOME/state/superagent/memory`). Before storage, the plugin redacts API-key
1160
- shapes (`sk-…`, `Bearer …`, `ghp_…`, `AKIA…`), long hex/base64 blobs, email
1161
- addresses, and absolute home paths; it collapses a note to one line and caps it.
1162
- The aggregator is instructed not to record secrets, customer data, or the report
1163
- itself. A `stateDir` inside the installed package disables memory rather than
1164
- risk shipping it. If you point `stateDir` at a repository, the nested
1165
- `.gitignore` still keeps the files out of a default `git add`.
1166
-
1167
- ### User profile
1168
-
1169
- The notebook above answers "what did the last run learn about this task". A
1170
- second, optional store answers a different question — "who is this person, what
1171
- do they want, and why did we choose that before" — and it has to outlive
1172
- unrelated tasks, so it is kept apart and read apart. It is off by default
1173
- (`memoryUserProfile: false`): nothing is constructed, no directory is created,
1174
- and the run notebook behaves exactly as before.
1175
-
1176
- - **Three categories, three files.** `fact` (durable technical context such as
1177
- the stack or the environment), `preference` (how the user wants work done),
1178
- and `decision` (the choice, what was rejected, why, and how to undo it).
1179
- A search opens one category file, so a fact can never come back as a
1180
- preference just because the words match.
1181
- - **A decision needs its reason.** A decision without a rationale teaches the
1182
- next run nothing, so the reason is part of the record and part of every digest
1183
- line; a bare "chose X" is refused.
1184
- - **Reading and writing.** `superagent_memory` with `layer: "user"` and a
1185
- `category` lists, searches, adds, corrects, or forgets profile records. The
1186
- planner prompt gets a short digest of the matching records, labelled by
1187
- category, under the same character budget as the notebook.
1188
- - **Forgetting is deletion.** The matching lines are removed under a lock and the
1189
- file is replaced, with no tombstone that a later search could leak the value
1190
- back through. A forget must name a key, a run id, or a time range, so a bare
1191
- "forget everything" cannot wipe the profile by accident.
1192
- - **Privacy.** Every record is redacted before it is written: credentials,
1193
- emails, phone numbers, and usernames inside home paths. The profile lives
1194
- under `<stateDir>/user-memory` with the same nested `.gitignore` as the
1195
- notebook, and is never in the package `files` whitelist.
1196
-
1197
- ## Watch and report
1198
-
1199
- ![Run report preview](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-preview.jpg?raw=true)
1200
-
1201
- _Top of a report rendered from 40 real host runs. The full page — timeline,
1202
- swimlanes, call and cost curves, failure annotations, run table — is
1203
- [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)._
1204
-
1205
- Five operator utilities ship with the package, need no session, and add no
1206
- runtime dependency. `watch`, `report`, `archive`, and `sync` read the same
1207
- durable run files as the tools; `doctor` inspects the install itself.
1208
-
1209
- Run them from the installed copy inside the profile:
1210
-
1211
- ```bash
1212
- PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
1213
- node "$PKG/bin/watch.js" # live panel, Ctrl-C to stop
1214
- node "$PKG/bin/report.js" --out report.html # self-contained HTML page
1215
- ```
1216
-
1217
- If the profile's linker created bin links (npm does), the same commands are
1218
- `node_modules/.bin/dsh-superagent-watch`, `node_modules/.bin/dsh-superagent-report`,
1219
- and `node_modules/.bin/dsh-superagent-doctor`.
1220
-
1221
- `watch`, `report`, and `archive` all accept `--state-dir <path>`; it defaults to
1222
- `$DSH_HOME/state/superagent`. Pass it when the plugin config sets a custom
1223
- `stateDir`.
1224
-
1225
- **`watch`** draws one line per run — id, status, calls used against the cap,
1226
- elapsed time, what it is doing right now, and the parent session — in the
1227
- alternate screen, and restores the cursor on Ctrl-C, SIGTERM, or a closed pipe.
1228
- A status change repaints immediately; an idle panel reads one small file per
1229
- second. Runs alive at the same moment share a numbered gutter, so parallel work
1230
- is visible as a group instead of unrelated rows. A waiting row leads with the
1231
- run holding its slot, then the queue position, because a narrow cell clips from
1232
- the right and the holder is the actionable part. `--once` prints a single plain
1233
- frame, which is what
1234
- [docs/e2e/transcripts/watch-panel.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/watch-panel.log)
1235
- captures from 40 real runs.
1236
-
1237
- **`report`** renders recorded runs into one HTML file: inline CSS, inline SVG,
1238
- no script, no font, no image, no network. It has a timeline with each run's
1239
- start, end, and derived planning/work/merge phases; a swimlane chart whose lane
1240
- count is the peak concurrency; cumulative model-call and cost curves; explicit
1241
- failure, cancellation, and interruption annotations; and a run table. Each
1242
- worker's retry chain and its share of the run's wall clock are listed next to
1243
- its outcome, so an expensive flaky subtask is visible instead of only its final
1244
- failure.
1245
- [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)
1246
- is the 40-run report from the host e2e — open it directly, nothing is fetched —
1247
- and
1248
- [docs/e2e/transcripts/report-cli.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/report-cli.log)
1249
- records the command plus a zero-external-reference audit.
1250
-
1251
- **`doctor`** answers "it installed, why does nothing work?" before the host
1252
- does. It reads only: no install, no mount, no edit to the profile. One block per
1253
- check — imported files against the `files` whitelist, declared files against
1254
- what is on disk, the installed copy against the published tarball for its
1255
- version, the profile's bundle registration, and the twelve registered tools — each
1256
- failure followed by the command that fixes it.
1257
-
1258
- ```bash
1259
- PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
1260
- node "$PKG/bin/doctor.js" --profile web
1261
- node "$PKG/bin/doctor.js" --profile web --offline # skip the registry hash check
1262
- ```
1263
-
1264
- Exit code is `0` when no check fails, `1` when one does, so it can gate a
1265
- deploy. `npm test` runs the same pack guard as
1266
- [`scripts/check-pack.mjs`](scripts/check-pack.mjs): every file reachable from
1267
- the entry points must appear in `npm pack --dry-run`, which is the check the
1268
- 0.9.x release lacked.
1269
-
1270
- None of these utilities is the install path: the plugin is installed with
1271
- `dsh plugin add`, never with `npm i -g`.
1272
-
1273
- **`archive`** is the fourth utility. It prunes terminal runs and exports or
1274
- imports one run as a self-contained archive; see [Retention](#retention) and
1275
- [Archives](#archives).
1276
- ## Syncing one state directory across machines
1277
-
1278
- There is no server and no account. The state directory is a directory of files,
1279
- so a git remote can carry it: `dsh-superagent-sync` makes that directory a
1280
- repository, keeps the machine-local files out, and gives you `pull`, `push`, and
1281
- `status`. `git` is the only requirement — the command has no dependency of its
1282
- own.
1283
-
1284
- ```bash
1285
- PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
1286
- node "$PKG/bin/sync.js" init git@github.com:me/superagent-state.git # once per machine
1287
- node "$PKG/bin/sync.js" push # after runs finish
1288
- node "$PKG/bin/sync.js" pull # before starting work
1289
- node "$PKG/bin/sync.js" status
1290
- ```
1291
-
1292
- Or `node_modules/.bin/dsh-superagent-sync`. All four accept `--state-dir
1293
- <path>` (default `$DSH_HOME/state/superagent`), and `--json` prints the raw
1294
- result.
1295
-
1296
- **`init <remote>`** creates the repository, writes a managed block into
1297
- `.gitignore`, sets `origin`, and makes the first commit. Re-running it refreshes
1298
- the remote URL and that block without touching entries you added yourself. A
1299
- machine with no `~/.gitconfig` gets a repository-local commit identity, so the
1300
- first commit cannot fail on that alone.
1301
-
1302
- **`pull`** fetches `origin`, then merges. Uncommitted local changes are stashed
1303
- first (`stash@{0}`, subject `dsh-sync auto-stash …`) and reapplied after the
1304
- merge, so a pull never silently overwrites an edit. A conflict stops the merge
1305
- with both sides still in the files: the paths are printed, nothing is chosen,
1306
- and the stash is left unapplied with a line saying so.
1307
-
1308
- **`push`** commits everything and pushes the current branch, setting its
1309
- upstream on the first push. A rejected push is reported, not forced and not
1310
- auto-merged: run `pull`, resolve what it reports, then push again.
1311
-
1312
- **`status`** prints ahead/behind counts, uncommitted files, stashes, and the
1313
- conflicted paths waiting for a decision.
1314
-
1315
- ### What never leaves the machine
1316
-
1317
- `.owner`, `control.json` (a bearer token), `notifications.json`, `*.lock`,
1318
- `*.cancel`, `*.corrupt-*`, `*.tmp`, `*.log`, and `.env` / key material. The
1319
- notebook is the one exception worth knowing: `memory/.gitignore` normally holds
1320
- a bare `*`, which would keep every note local, so `init` rewrites that one
1321
- default to allow `<scope>.jsonl`. A file you customized is left alone.
1322
-
1323
- ### When it conflicts
1324
-
1325
- Run records are one file per run (`runs/<runId>.json`), so ordinary concurrent
1326
- work on two machines — different runs — never touches the same path. A conflict
1327
- needs one of these:
1328
-
1329
- - the same run id written on both machines: a resume or cancel on the second
1330
- machine before pulling the first machine's state;
1331
- - the same memory scope appended to on both machines (`memory/<scope>.jsonl` is
1332
- append-only, and two different tails collide);
1333
- - the same `reports/<runId>.md` regenerated with different content;
1334
- - `.gitignore` edited by hand on both machines.
1335
-
1336
- While a run file still contains conflict markers it is not valid JSON, and the
1337
- plugin quarantines it at mount as `<runId>.json.corrupt-<ts>`. Resolve it before
1338
- starting the host: keep the side you want, `git add` it, `git commit`.
1339
-
1340
- ### Why this is approximate
1341
-
1342
- - Two machines writing at the same moment can conflict. The merge stops and you
1343
- decide; nothing is merged behind your back.
1344
- - There is no live sync and no cross-machine lock. A machine sees another
1345
- machine's run only after `pull`, and `push` does not know what the other
1346
- machine is doing right now. Run one host per state directory at a time.
1347
- - Keys are not distributed: each machine still needs its own model credential.
1348
- - `keepRuns` pruning deletes files, and a deletion reaches the other machine
1349
- only on the next `pull`.
1350
-
1351
- ## Embedding over local HTTP
1352
-
1353
- The tools require a session. If another UI or script must start and watch runs
1354
- without importing this package, set `controlPort`:
1355
-
1356
- ```yaml
1357
- - id: superagent
1358
- config:
1359
- controlPort: 0 # off by default; 0 = OS picks a free loopback port
1360
- ```
1361
-
1362
- The plugin then writes `<stateDir>/control.json` with the bound URL and a
1363
- per-process bearer token (mode `0600`) and serves `GET /`, `GET /health`,
1364
- `GET /runs`, `GET /runs/:id`, `POST /runs`, `POST /runs/:id/cancel`, and
1365
- `POST /runs/:id/resume` on `127.0.0.1` only. Every reply carries the same text
1366
- the tool would print (the route index and `/health` are the two exceptions:
1367
- they describe the socket, not a run). Every run goes through the same quota,
1368
- budgets, locks, and recovery as a tool-started run. `POST /runs` requires
1369
- `session_id` of a session that is live in that host — a run needs a real parent
1370
- agent for its children.
1371
-
1372
- ```bash
1373
- STATE="${DSH_HOME:-$HOME/.dsh}/state/superagent"
1374
- URL=$(node -e "console.log(require('$STATE/control.json').url)")
1375
- TOKEN=$(node -e "console.log(require('$STATE/control.json').token)")
1376
- curl -s -H "Authorization: Bearer $TOKEN" "$URL/runs"
1377
- ```
1378
-
1379
- The full contract — routes, error ids, security model, lifecycle, client
1380
- examples — is [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md). It is opt-in, loopback
1381
- only, and there is no remote or unauthenticated mode.
1382
-
1383
- ## Conversation console
1384
-
1385
- `consolePort` adds a local page where you talk to a **real Host Session**, not a
1386
- mock chat and not a re-skinned `superagent_start(goal)` form:
1387
-
1388
- ```yaml
1389
- - id: superagent
1390
- config:
1391
- consolePort: 0 # off by default; 0 = OS picks a free loopback port
1392
- consoleRoot: /path/to/project
1393
- ```
1394
-
1395
- The plugin creates the session with the host's `sessionController.create()`,
1396
- sends each message with `prompt({ mode: 'queue' | 'steer' })`, and forwards
1397
- `follow({ assistantStream: true })` plus `observeState()` to the page. Follow-up
1398
- messages therefore continue the same conversation; they are not a new session.
1399
- The right-hand column lists the runs whose `parentSessionId` is that session, so
1400
- the page shows exactly the subtasks the conversation derived. An attention card
1401
- answers through `orchestrator.answer`, the same path as the
1402
- `superagent_answer` tool, with the conversation agent as the run owner.
1403
-
1404
- The bound URL and a fresh per-process token are written to
1405
- `<stateDir>/console.json` (mode `0600`). Open
1406
- `http://127.0.0.1:<port>/?token=<token>` once; the page stores the token in
1407
- `sessionStorage` and removes it from the address bar. Every route, including
1408
- the event stream, answers `401` without it, and every request with a non-loopback
1409
- `Host` header answers `403`.
1410
-
1411
- If the host does not mount `sessionController` (for example a headless profile
1412
- without the web session API), the page says so and refuses to create a session.
1413
- It does **not** pretend to be a chat. The console also keeps one active
1414
- conversation per process; "新对话" creates a new Host Session and leaves the old
1415
- one intact. Approval prompts that appear as host `pendingInput` are surfaced in
1416
- the status line but are not answered by this page; only run attention questions
1417
- are.
1418
-
1419
- ### Tools the conversation gets
1420
-
1421
- The console session is created with no tool list of its own: it mounts whatever
1422
- the host's agent preset mounts, which is the same set the Web app's own
1423
- sessions get. The plugin registers no conversation tools and filters none; the
1424
- only filter it can apply is the opt-in `guard` for child agent calls. To see the
1425
- real list, the page asks the host for `ctx.tools.definitions(agent)` and shows
1426
- it under "这个会话挂载的工具"; when the host cannot enumerate, the page says so
1427
- instead of printing a fixed list. `consolePreset` passes `agentPreset` to
1428
- `sessionController.create()` when you want a preset other than the profile
1429
- default.
1430
-
1431
- Browser and desktop control are not implemented here. They come from
1432
- `feat/runtime-control`, which registers host-scope `browser_*` and `desktop_*`
1433
- tools; those are visible to the console session like any other host tool. On a
1434
- build without that branch the page reports them as "未挂载". Neither branch ships a 3D tool; when
1435
- the preset includes `bash` or `pwsh`, a headless Blender can be driven through
1436
- it (`blender --background --python`), which is the scriptable path the console
1437
- can already reach.
1438
-
1439
- ## Workspace panel
1440
-
1441
- `workbenchPort` adds a local, IDE-shaped panel over one directory. It has its
1442
- own file tree, editor, diff preview, and run change view; nothing is proxied
1443
- through the host.
1444
-
1445
- ```bash
1446
- npx dsh-superagent-workbench --root /path/to/project --port 8787
1447
- ```
1448
-
1449
- The same server can run inside the host, with its Runs view wired to the plugin
1450
- state directory:
1451
- - id: superagent
1452
- config:
1453
- workbenchPort: 0 # off by default; 0 = OS picks a free loopback port
1454
- workbenchRoot: /path/to/project
1455
- ```
1456
-
1457
- The standalone command serves the same page and defaults its run state to
1458
- `<root>/.dsh-workbench`; pass `--state-dir <plugin state directory>` to read
1459
- existing runs. Neither form opens a socket unless you ask for it.
1460
-
1461
- The bound URL and a fresh per-process token are written to
1462
- `<stateDir>/workbench.json` (mode `0600`). Open `http://127.0.0.1:<port>/?token=<token>`
1463
- once; the page keeps the token in `sessionStorage` and strips it from the
1464
- address bar. Without the token every route answers `401`.
1465
-
1466
- The panel can list, read, and edit regular text files under `workbenchRoot`. It
1467
- refuses absolute paths, `..` traversal, symlinks that leave the root, the plugin
1468
- state directory, binary files, and files above 512 KB. Saving sends the hash and
1469
- mtime the editor read; if either changed on disk, the save is refused with
1470
- `external-change` instead of overwriting another process's work. Before a save
1471
- is confirmed the page shows a unified diff.
1472
-
1473
- When `workbenchPort` is on, the plugin records the files each run changed into
1474
- that run's JSON record (`run.changes`), so the Runs view can show those files and
1475
- their diff against `git HEAD` later.
1476
-
1477
- ## State and recovery
1478
-
1479
- One file per run: `$DSH_HOME/state/superagent/runs/<runId>.json`, written with a
1480
- temp file plus rename, so a kill during a save cannot leave a half-written run.
1481
- Statuses: `queued`, `planning`, `running`, `aggregating`, `completed`,
1482
- `partial`, `failed`, `cancelled`, `interrupted`. A run that is waiting for a free
1483
- slot also has `queued` as its status but carries `queue.waiting: true` with its
1484
- position in line; it is not active and does not count against `maxActiveRuns`.
1485
-
1486
- At mount the plugin marks a run as `interrupted` **only when it has no live
1487
- owner** (see below) and resets its in-flight subtasks to `pending`.
1488
- `superagent_resume` then re-runs only what did not finish. The planner's plan is
1489
- reused, so a resumed run does not pay for planning twice.
1490
-
1491
- A state directory can be shared by two profiles or two machines. Recovery
1492
- therefore never decides from this process's memory alone: a run whose owner is
1493
- still alive — fresh heartbeat, live local pid, or a live process holding its
1494
- lock — is left untouched, cancel marker included. Two processes rewriting one
1495
- run would make the surviving child keep spending while the file says
1496
- `interrupted`, and a resume would then run the same subtasks twice.
1497
-
1498
- Resuming is exclusive for the same reason. `superagent_resume` takes the same
1499
- serial gate as `superagent_start`, claims `<runId>.lock` (created atomically),
1500
- refuses a run that still has a live owner, and refuses a caller that is not the
1501
- session in `parentSessionId`. It does not count against `maxActiveRuns`: a
1502
- resume finishes work that already exists, so a full cap never blocks it. `force`
1503
- (tool) or `force` / `override_quota` (HTTP) is still accepted for compatibility
1504
- and changes nothing.
1505
-
1506
- Three side files live next to the run:
1507
-
1508
- | File | Meaning |
1509
- | --- | --- |
1510
- | `<runId>.cancel` | A cancel was requested by some process. The owner polls it once per second and stops its children. Removed when the run ends. |
1511
- | `<runId>.lock` | The process that is allowed to schedule this run. Created with `wx`, so exactly one process wins. A lock left by a dead local pid is broken immediately; a live local pid keeps it however long it has held it; a lock from another machine is broken once it is older than 10 minutes, since its pid cannot be checked. |
1512
- | `<runId>.json.corrupt-<ts>` | The state file was not valid JSON and was moved aside, not deleted. The run is skipped by `superagent_list` and reported by id with this path. |
1513
- | `<anchor>/.superagent/worktrees/<runId>/w<n>/` | A worker's git worktree when `workspaceIsolation` is on. Anchored inside the host's session directory (the repository when that is where the host started) so the sandbox allows writes, and ignored so it never shows up in `git status`. Removed once its branch is merged or it produced no change; kept when a conflict left it for the user to merge. |
1514
-
1515
- If a run's file is damaged, nothing else breaks: other runs list normally, and
1516
- starting a new run works. Inspect the `.corrupt-` file, then delete it. A file
1517
- that cannot be read at all (permission, too many open files, disk full) is
1518
- reported as such instead of being shown as an unknown run.
1519
-
1520
- ### Orphaned runs and the active-run quota
1521
-
1522
- A run counts against `maxActiveRuns` while its status is active. If the process
1523
- owning it disappears without a restart, the run would otherwise hold that slot
1524
- forever. Before every quota check the plugin looks for such runs and reclaims
1525
- them, with two different rules:
1526
-
1527
- - **The state directory belongs to this machine** (`.owner` holds our hostname):
1528
- a dead local pid is enough on its own — that is direct evidence the process is
1529
- gone, so the next mount reclaims immediately regardless of the heartbeat. A
1530
- live pid vetoes reclamation even with a stale heartbeat, because a wedged
1531
- process may still resume.
1532
- - **The directory is shared, or its owner is unknown**: the pid may belong to
1533
- another machine, so it is ignored and only the heartbeat decides; a run is
1534
- reclaimed once its heartbeat is older than 90 seconds. This is the case for a
1535
- state directory on a network share or a synced folder.
1536
-
1537
- In both cases a lock held by a live local process also vetoes reclamation, and
1538
- mount-time recovery uses exactly the same rules — a run is never rewritten
1539
- while anybody can still be working on it.
1540
-
1541
- Reclamation is never silent: the run becomes `interrupted`, its `reclaimed`
1542
- field records the exact basis (`pid 1234 is not running and its heartbeat
1543
- stopped at ...`, or `the state directory is shared with <host> ...`), the reason
1544
- is printed by `superagent_status`, and one line goes to the host log. The subtasks
1545
- that were mid-flight become `pending`, so `superagent_resume` continues the run.
1546
-
1547
- The heartbeat is refreshed every 30 seconds by the owning process, so a healthy
1548
- run is never mistaken for an orphan.
1549
-
1550
- ### Talking to the user
1551
-
1552
- The plugin is quiet unless the user must hear something. This is a rule in code,
1553
- not only in this document:
1554
-
1555
- - **Allowed to interrupt:** a run finished and delivered a result, a run failed,
1556
- or a run stopped half-way (`partial`, `interrupted`). A run the user cancelled
1557
- is never announced — the caller already knows.
1558
- - **Never pushed:** progress, subtask start/finish, retries, and memory writes.
1559
- They live in the run record, `superagent_status`, the watch panel, and the
1560
- report page; the user can look, but nothing pops up.
1561
- - **Self-heal first:** each subtask gets `attempts` tries, and a failure that
1562
- looks transient (quota, rate limit, timeout, 5xx) gets `autoResumeRounds`
1563
- more rounds, optionally on `childModelFallback`. Only what still fails is
1564
- reported, and the message says what was tried.
1565
- - **Bounded noise:** at most `maxNotificationsPerHour` proactive messages per
1566
- hour. Runs above the cap are buffered and folded into the next message as one
1567
- summary; `superagent_list` shows how many are waiting. If the message carrying
1568
- a folded batch cannot be delivered, the batch stays buffered and rides the
1569
- next one; it is dropped only after three failed deliveries.
1570
- - **Do not ask what is known:** the planner and aggregator receive the notebook
1571
- and are told to use it instead of asking the user for facts it already holds.
1572
-
1573
- `notifyOnComplete` is the master switch. Two cases already report instead of
1574
- notifying:
1575
-
1576
- - a caller in the same host process was inside `superagent_status` and receives
1577
- the terminal report itself (no message, to avoid duplicate noise). A poller in
1578
- a *different* process does not suppress the message: it can time out just
1579
- before the run ends, and then the only notification would be lost;
1580
- - the owning session is gone (headless users who closed it): the run records
1581
- `notify.delivered = false` with the reason, `superagent_status` prints
1582
- `notify: not delivered — ...`, and `superagent_list` marks the row
1583
- `(result not delivered to the session)`. The report is always readable with
1584
- `superagent_status`.
1585
-
1586
- Waking the session is bounded (15 s), and the heartbeat keeps running until the
1587
- terminal state is written, so a slow wake-up cannot make another process treat a
1588
- live run as orphaned.
1589
-
1590
- ### Retention
1591
-
1592
- Nothing is deleted by default. Set `keepRuns` to a number of days to delete
1593
- terminal runs older than that at mount; active runs are never touched, the
1594
- removed ids are logged, and the matching `reports/<runId>.md` artifact is
1595
- removed with its run. `superagent_list` prints the current file count and size,
1596
- so growth is visible before it becomes a problem.
1597
-
1598
- To clean up on demand, `dsh-superagent-archive prune` plans first and deletes
1599
- second:
1600
-
1601
- ```bash
1602
- node "$PKG/bin/archive.js" prune --older-than 30 # dry run
1603
- node "$PKG/bin/archive.js" prune --older-than 30 --status failed # dry run, one status
1604
- node "$PKG/bin/archive.js" prune --older-than 30 --confirm # delete
1605
- ```
1606
-
1607
- The plan prints each run id, status, finish time, and the bytes it holds; the
1608
- summary gives the run, file, and byte totals. Without `--confirm` nothing is
1609
- deleted. Only terminal runs (`completed`, `partial`, `failed`, `cancelled`,
1610
- `interrupted`) are ever candidates: a run that is still active, or whose
1611
- `.lock` is held by another process, is listed as skipped and left alone. A run
1612
- inside the window, a run with no parsable timestamp, and a quarantined
1613
- `*.corrupt-*` file are kept as well.
1614
-
1615
- ## Archives
1616
-
1617
- `archive export` turns one run into evidence another person can open offline —
1618
- no host, no plugin, no network:
1619
-
1620
- ```bash
1621
- node "$PKG/bin/archive.js" export <run-id> --out ./run-archive # directory
1622
- node "$PKG/bin/archive.js" export <run-id> --out ./run.html --format html # one page
1623
- node "$PKG/bin/archive.js" export <run-id> --out ./run.json --format bundle
1624
- ```
1625
-
1626
- The directory contains `README.md` (summary, the merged report, a subtask
1627
- table, and a file index), `report.md` (the report as markdown), `run.json` (the
1628
- full durable record), `subtasks/` (one markdown page and one JSON file per
1629
- subtask), `guards.json` / `guards.md` (every decision a worker or the
1630
- aggregator stopped on), `usage.json` (token totals per child plus the cost the
1631
- operator prices produce), and `manifest.json` (archive metadata, sizes, and a
1632
- SHA-256 per file). `--format html` writes the same content as one self-contained
1633
- page with the bundle embedded; `--format bundle` writes only that JSON.
1634
-
1635
- `archive import <path>` reads any of the three back into the local store for
1636
- review, restoring the run record and its report artifact. It never overwrites:
1637
- when a local run has the same id, the command fails before writing anything and
1638
- says so. An imported run is terminal, so it is listed and readable but never
1639
- resumed.
1640
-
1641
- ## Cancelling from another process
1642
-
1643
- `superagent_cancel` works even when the run was started by a different host
1644
- process (web and headless running side by side, or a second terminal). The
1645
- crossing point is the `.cancel` marker file, not shared memory:
1646
-
1647
- 1. the caller writes `<runId>.cancel`;
1648
- 2. the owning process notices within a second, aborts its children' signal,
1649
- disposes their activations, and writes `cancelled`;
1650
- 3. the caller waits up to 5 seconds for that, then reports what happened.
1651
-
1652
- If the owner does not answer in time, the reply says
1653
- `cancel requested ... not confirmed` instead of `cancelled`. That means the
1654
- owning process is gone or wedged; the marker stays on disk, and the next mount
1655
- converts the run to `cancelled` during recovery. No socket, pipe, or Windows
1656
- named pipe is involved, so this works the same on every platform and across a
1657
- shared state directory.
1658
-
1659
- Measured on the real host: with two workers sleeping inside a model call that
1660
- ignores abort, `superagent_cancel` returned `cancelled` in **1.99 s** and the
1661
- state file stopped accepting new spawns at that instant. The *host process*
1662
- still took 22.8 s to exit, because it waits for its own child sessions; that
1663
- wait is the host's teardown, outside the plugin's control. In an interactive
1664
- session you never notice it; in a one-shot headless turn it is why cancel
1665
- appears to "hang" until the ignored-abort child returns.
1666
-
1667
- ## Troubleshooting
1668
-
1669
- | What you see | What it means | What to do |
1670
- | --- | --- | --- |
1671
- | `superagent_*` tools do not exist | The bundle row is not mounted, or the host refused to load the plugin. | Run `--dump-config` and check for the `@xiangyixie/dsh-superagent` block; reinstall with `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.0` and read the host log for `[dsh-superagent]` lines. |
1672
- | `Cannot find module .../lib/control.js` (or `watch.js` / `report.js`) and the plugin never activates | The copy in that profile is incomplete — an `add` that was interrupted leaves a partial extraction. The published package is not the cause: every version ships all thirty `lib/` files. | Delete the plugin's directory under the profile's `node_modules` (scoped `@xiangyixie/dsh-superagent`, or unscoped `dsh-superagent` from an older tarball install) and run the same `add` command again, with the version number. Do not copy files in by hand. |
1673
- | `[error] the model provider rejected the API key` | The key env var is missing in the process that started the host. | Export `DEEPSEEK_API_KEY` (the default route) or the variable your route names, then restart `dsh`. |
1674
- | `MISSING_CREDENTIAL ... no API key for provider route "..."` | The profile's route has no credential in the environment. | Set the env var named for that route and restart. The error line names the route, so use that, not this page. |
1675
- | `[error] the subagent service is unavailable` | The profile has no `subagents` service, so the plugin has nothing to spawn. | Use a profile built on the base bundle (`web` or `headless` from the stock image), or add the subagent plugin to the profile. |
1676
- | `error: subagent provider "..." cannot enforce maxSubagentDepth` | The route's subagent backend cannot cap delegation. | Keep `provider: spawn`, or set `maxSubagentDepth: provider-managed` if you accept the backend's own limit. |
1677
- | `error: the Windows file sandbox could not start a child process` | Host sandbox launcher failure (`windows-acl-run: ...`), not your goal or key. The subtask is retried once. | Retry the run; if it repeats, restart the host, or disable the Windows ACL sandbox in the profile, then run the `diagnose-windows-sandbox-acl` skill. |
1678
- | `error: the run was not started because the active-run limit is already in use` | `maxActiveRuns` is full, including runs from another profile that shares the state directory, and the start did not ask to queue (or the queue itself is full). | Retry with `queue: true`, wait, cancel one, or raise `maxActiveRuns` / `maxQueuedRuns`. |
1679
- | `error: the run stopped because it reached its spending cap` | `maxModelCallsPerRun` or `maxTokensPerRun` was hit. | Read the partial report; raise the cap in the config, then `superagent_resume` continues with the new limits. |
1680
- | `usage: not recorded` | The run finished and no child session log could be read (moved `sessions` directory, or a run created before accounting). | Nothing to fix on old runs; new runs record usage. While a run is still active the line says accounting is pending instead. |
1681
- | `usage note: N child session log(s) could not be read` | Part of the usage was unreadable; the token figures are a lower bound. The call budget still counted those children. | Check that `$DSH_HOME/sessions` exists and is readable by the host process. |
1682
- | `cost: not computed — no price configured for X` | The model is not in the `pricing` table. | Add its per-1M prices under `pricing["provider/model"]`, copying the id from the `usage:` line. |
1683
- | `cost: at least ... (no price for X)` | Some children used an unpriced model. | Same as above; the figure covers only the priced part. |
1684
- | `[error] a saved run file is damaged` | A state file was truncated or invalid JSON. | The bytes were kept at `<runId>.json.corrupt-<ts>`; inspect, then delete. |
1685
- | `cancel requested ... not confirmed` | The owning process did not acknowledge within 5 s. | Check `superagent_status`; if the owner is gone, restart the host so recovery marks the run `cancelled`, then `superagent_resume` if you want it to continue. |
1686
- | `[error] ... still owned by a live process` | Another profile is running this run, so resuming here would duplicate the work. | Let it finish, or `superagent_cancel` it first. |
1687
- | `missing or wrong bearer token` (HTTP 401) | The embedder used a token from an earlier host start, or the wrong state directory's discovery file. | Read `token` from `<stateDir>/control.json` again; it is regenerated on every start. Read the file as UTF-8. |
1688
- | `the request did not name a live session` (HTTP 409) | `POST /runs` or `/resume` was called without a `session_id`, or the session closed. | Pass the id of a session open in that host process; run the start from the session that should own it. |
1689
- | `[dsh-superagent] control plane is not listening` in the host log | `controlPort` is already taken, the value is invalid, or the state directory is not writable. | Use `controlPort: 0`, free the port, fix the state directory, or remove the key; the tools keep working either way. |
1690
-
1691
- A tool call that fails itself returns three lines: `[error]` a sentence, `hint:`
1692
- one next step, and `detail:` the untouched host message, so nothing is hidden.
1693
- A run that fails *after* it was accepted keeps its report and shows `error:`
1694
- (plus a `hint:` line when it is `failed`) in the run block instead.
1695
-
1696
- ## Known limits
1697
-
1698
- - Children are not isolated by this plugin: they run with the host's
1699
- credentials and filesystem, under whatever sandbox policy the host itself
1700
- applies.
1701
- - A run lives inside the host process. Killing the process stops its children;
1702
- the run becomes `interrupted` on the next mount.
1703
- - Cancelling from another process is cooperative: it relies on the owning
1704
- process still running. A wedged process is only cleaned up at the next mount
1705
- or when its heartbeat goes stale and the quota is reclaimed.
1706
- - Planning is one model call. If the reply has no parsable
1707
- `{"subtasks":[...]}` object, the run degrades to a single subtask and is
1708
- marked `plan.mode = "degraded"`.
1709
- - Aggregation is skipped for a single successful subtask (the report is that
1710
- subtask's text under the goal heading) and falls back to a deterministic merge
1711
- when the aggregator fails or the budget is exhausted.
1712
- - Retention is opt-in (`keepRuns`); by default state accumulates, at up to
1713
- 32 KB per subtask plus the report per run. `archive prune` removes terminal
1714
- runs on demand, as a dry run unless `--confirm` is given.
1715
- - The HTTP embedding surface is loopback-only, opt-in, and token-authenticated;
1716
- it cannot be exposed remotely, and there is no MCP server. A local process
1717
- running as the same user can read the token, which is the same trust boundary
1718
- as writing run files.
1719
- - Cross-machine sync is a git repository, not a service: it is offline-first,
1720
- conflict-stop rather than conflict-free, has no realtime channel, and does
1721
- not move credentials between machines. Two hosts actively writing one state
1722
- directory on two machines still need a `pull` between them.
1723
-
1724
- ## Naming
1725
-
1726
- The package is published as `@xiangyixie/dsh-superagent` — npm already has a
1727
- `dsh-super-agent` that is too close to the unscoped name, so the scope keeps
1728
- the name instead of renaming the project. The tools are unchanged:
1729
- `superagent_*` (with `superagent_memory` added in 0.10, additively). The earlier working name was `dsh-longhaul` with `longhaul_*`
1730
- tools; nothing was ever published, so the old names do not exist anywhere and
1731
- there is no alias layer. If you find an old snippet that calls `longhaul_start`,
1732
- replace the prefix — the arguments are unchanged.
1733
-
1734
- ## Development
1735
-
1736
- ```bash
1737
- npm test # node:test, fake store and fake child spawner, no network
1738
- npm pack # inspect what would ship
1739
- ```
1740
-
1741
- What "ready to publish" means is written down as checkable rows in
1742
- [docs/DONE.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/DONE.md); the real-host run that most of them point at is
1743
- [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md).
1744
-
1745
- Layout: `lib/index.js` (plugin, tool schemas, run formatting),
1746
- `lib/orchestrator.js` (ordering, retries, budgets, cancel, resume),
1747
- `lib/store.js` (atomic run files, cancel markers, quarantine),
1748
- `lib/errors.js` (readable error text), `lib/usage.js` (session log parsing),
1749
- `lib/control.js` (optional loopback HTTP surface).
1750
-
1751
- ## License
1752
-
1753
- MIT. Copyright (c) 2026 Admire (LittleChenLiya); see [LICENSE](LICENSE).
1754
-
1755
- The npm scope `@xiangyixie` and the GitHub account `LittleChenLiya` are the same
1756
- author.
1
+ 中文 | [English](README.en.md)
2
+
3
+ # dsh-superagent
4
+
5
+ [DeepSeek Harness](https://dshai.org) 的长程运行插件:输入一个 goal,由模型规划出可并行的 subtask,最后合成一份报告——而且宿主重启之后,这次 run 还能接着跑完。
6
+
7
+ ## 这是什么,解决什么问题
8
+
9
+ 单个 agent 循环只有一个上下文、一条执行序列。需要几条独立工作线的目标会在里面卡住,一次崩溃就会让这一轮什么都留不下、无从续跑。这个插件接收一个 goal,让模型把它拆成若干 subtask,最多同时跑三个子 agent,再把它们的报告合并成一个回答。run 的状态和花费都写到磁盘上,所以宿主重启之后 `superagent_status` 仍然能找到这个 run,`superagent_resume` 只把没做完的部分补完。每个 run 都有硬性的调用次数与 token 预算,会打印实测用量;一旦你为对应路由配好了价格,它还会打印花费。
10
+
11
+ **以下情况不要用它**:一次模型调用就能答完的时候——那样你只是在为 planner 和 aggregator 额外付钱。必须在一轮之内结束的工作、中间需要人工审批的步骤、需要嵌套委派的任务(子 agent 深度上限为 1)、以及想要宿主内嵌面板的人,也不适合;下文那个可选的工作区面板是回环地址上的网页,不是宿主 UI。子 agent 运行时用的是宿主的凭据和文件系统,这里不是沙箱。
12
+
13
+ 它不添加宿主内 UI(工作区面板和对话控制台都是回环页面),也不修改宿主代码:对外的接口就是十二个 `superagent_*` 工具,另外还有六个可选的运维工具(终端面板、HTML 报告、安装自检、run 归档、git 同步、工作区面板),它们读的是同一批 run 文件。浏览器与桌面控制是独立的一层:设置 `runtime.enabled` 后会再注册十四个工具;默认值是 `false`,此时这些工具一个都不存在。
14
+
15
+ 个人项目,与 DeepSeek 及 harness 维护方无关。MIT 许可,© 2026 Admire (LittleChenLiya);详见[许可证](#许可证)。
16
+
17
+ ## 安装
18
+
19
+ 三种安装方式,`dsh plugin add` 和桌面应用的 **Add plugin** 对话框都接受:
20
+
21
+ - **npm 包名**:`@xiangyixie/dsh-superagent@0.14.2`,从 npm 安装。请写明版本号,原因见下文。
22
+ - **GitHub 仓库**:`https://github.com/LittleChenLiya/dsh-superagent`,从仓库安装。需要固定版本时加 `#v0.14.2`。
23
+ - **本地目录**:`file:/absolute/path/to/dsh-superagent`,拷贝本地 checkout。改过源码之后要重新 add 一次。
24
+
25
+ 最常用的一条命令:
26
+
27
+ ```bash
28
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.2
29
+ ```
30
+
31
+ ### 从插件索引安装(可选)
32
+
33
+ 插件索引把包名、版本和固定的 commit 写在一个 JSON 里,桌面应用的「发现」页可以直接读取:
34
+
35
+ 1. 打开「发现」页,点「添加索引」,填入 `https://raw.githubusercontent.com/LittleChenLiya/dsh-superagent/main/plugin-index.json`。
36
+ 2. 在列表里找到「超级智能体」并安装;之后有新版本也在这里一键更新。
37
+
38
+ 索引里的每个版本都绑定完整的 40 位 commit,所以一键更新拿到的是确定的那一份代码,而不是浮动的分支头。
39
+
40
+ ### 升级:先卸载,再装新版
41
+
42
+ 升级是 remove-then-add,不是原地覆盖:先卸掉旧的那份
43
+ (`dsh plugin --profile web remove @xiangyixie/dsh-superagent`),再装新版本。同一个 profile 里已有的其他插件也是同样的规则——要先卸载再重新安装,不要指望对话框或 `add` 会替你替换掉它们。
44
+
45
+ 版本号要写清。不写的话,pnpm 的 minimum release age 策略会跳过最近几小时才发布的版本,装上一个"次新"的版本,结果是 `add` 成功了,但拿到的不是当前版本。如果你更想跟最新发布,就把它加进该 profile 的 `pnpm-workspace.yaml` 里的 `minimumReleaseAgeExclude`;否则请把上面的版本号改掉。用下面这条命令确认实际装上的是哪个版本:
46
+
47
+ ```bash
48
+ npm ls --prefix <DSH_HOME>/profiles/web @xiangyixie/dsh-superagent
49
+ ```
50
+
51
+ 离线机器或需要固定制品时,改装打好的 tarball——它与 registry 提供的内容逐字节一致:
52
+
53
+ ```bash
54
+ npm pack # writes xiangyixie-dsh-superagent-<version>.tgz
55
+ dsh plugin --profile web add ./xiangyixie-dsh-superagent-<version>.tgz
56
+ ```
57
+
58
+ ## 需要执行命令时开启 commandWorkerPermission
59
+
60
+ 在默认的 `inherit` 权限下,worker 跑不了 `npm test` 这类命令:宿主以管道 stdio 启动子进程时会被 `workspace-write` 沙箱拒绝(`EPERM`)。要让计划里声明了命令能力的 worker 真正执行命令,就打开 `commandWorkerPermission`(例如设为 `danger-full-access`)。它只影响声明了该能力的 worker,planner、aggregator、验收判定和其他子 agent 仍然继承原权限。完整的机制、边界和风险见[按 worker 设置命令权限](#按-worker-设置命令权限)。
61
+
62
+ ## 环境要求
63
+
64
+ - Node `>= 24.9.0`。DeepSeek Harness 低于这个版本拒绝启动,所以本插件也一样。
65
+ - DeepSeek Harness `>= 0.2.2-rc.1 < 0.3.0`,并带 base bundle(即 `tools`、`agents`、`subagents` 三个服务)。
66
+ - 一条能调用工具的模型路由,且该路由的 API key 已放进环境。默认 profile 使用 `deepseek-official` / `deepseek-flash`,读取 `DEEPSEEK_API_KEY`。
67
+
68
+ ## 快速开始
69
+
70
+ 五分钟,从空机器做到一次跑完的 run。下面每条命令都能在干净机器上执行——这里也是从零起步的完整路径,包括为什么不要按名字安装 npm 上那个无关的 `dsh` 包。
71
+
72
+ ### 0. 不要按名字从 npm 安装 `dsh`
73
+
74
+ ```bash
75
+ # WRONG: npm's `dsh` is unrelated ("a shell written in JavaScript")
76
+ npm i -g dsh
77
+
78
+ # RIGHT: run the DeepSeek Harness by its scoped package, pinned
79
+ npx @deepseek-ai/dsh@0.2.2-rc.1 --version
80
+ ```
81
+
82
+ 本文其余部分直接用 `dsh` 指代那条命令;如果二进制不在你的 `PATH` 里,就换成 `npx @deepseek-ai/dsh@0.2.2-rc.1`。
83
+
84
+ ```bash
85
+ # 1. install the plugin into a profile (web, headless, ... whatever you run)
86
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.2
87
+
88
+ # 2. confirm the bundle row exists in the merged config
89
+ dsh --profile web --dump-config
90
+ ```
91
+
92
+ 桌面应用的 **Add plugin** 对话框接受同样这三种形式:
93
+
94
+ | 对话框中的栏目 | 填写值 | 作用 |
95
+ | --- | --- | --- |
96
+ | 包名(Package name) | `@xiangyixie/dsh-superagent@0.14.2` | 从 npm 安装。要写明版本号(见上文)。 |
97
+ | GitHub 仓库(GitHub repository) | `https://github.com/LittleChenLiya/dsh-superagent` | 从仓库安装。需要固定版本时加 `#v0.14.2`。 |
98
+ | 本地目录(Local directory) | `file:/absolute/path/to/dsh-superagent` | 拷贝本地 checkout。改过源码后需重新 add 一次。 |
99
+
100
+ 安装的三种形式和升级方式见上文的[安装](#安装)一节。查一下 dump 里有没有下面这一段。如果没有,说明插件装了但没挂载,任何 `superagent_*` 工具都不会存在:
101
+
102
+ ```yaml
103
+ # == @xiangyixie/dsh-superagent
104
+ - id: superagent
105
+ name: @xiangyixie/dsh-superagent
106
+ ```
107
+
108
+ ```bash
109
+ # 3. start the host with the key in the environment that starts it
110
+ export DEEPSEEK_API_KEY=sk-... # PowerShell: $env:DEEPSEEK_API_KEY="sk-..."
111
+ dsh --profile web
112
+ ```
113
+
114
+ 这个 key 必须是该 profile 实际使用的那条路由的 key。指向 DashScope 的 profile 用 `DASHSCOPE_API_KEY`;指向自建网关的 profile 用它自己声明的变量。想新增一条路由,看[其他路由](#其他路由)。
115
+
116
+ 在会话里发起一次 run:
117
+
118
+ > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
119
+
120
+ 回复长这样(数字仅作示意——一次真实 run 的完整记录在 [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md)):
121
+
122
+ ```
123
+ run 20261114T051233-a1b2 — completed
124
+ goal: Explain the difference between process and thread in 300 words, with one concrete example
125
+ plan: planned; subtasks 2/2 completed; max 3 in parallel; 2 attempt(s) each
126
+ elapsed: 18.4s
127
+ usage: input 4120 (+980 prompt tokens served from cache), output 455, calls 4 (deepseek-official/deepseek-flash: 4 call(s) 4120 in / 455 out)
128
+ cost: not computed — no price configured for deepseek-official/deepseek-flash; add a pricing entry in cordis.patch.yml to get an estimate
129
+ [1] completed (attempts 1) Processes vs threads
130
+ [2] completed (attempts 1) Concrete example
131
+
132
+ report:
133
+ ...
134
+ ```
135
+
136
+ 默认的 DeepSeek 路由没有内置价格;想加上就参见[花费上限与价格](#花费上限与价格),之后下一次 run(或者对这次 run 的 resume)就会打印 `cost: ...`。`cost` 是在 run 落定时计算的,所以已经结束的 run 会一直保留 "not computed" 那一行。`usage: not recorded` 只会出现在一种已结束的 run 上:它的子 session 日志完全读不到——见[故障排查](#故障排查)。
137
+
138
+ 如果 `wait_seconds` 用完时 run 还没结束,回复会以
139
+ `next: superagent_status run_id="..." wait_seconds=120` 结尾。再调一次就行;无论哪种情况,run 都在继续跑。
140
+
141
+ 想验证恢复能力又不想真的崩一次:在 run 活跃时杀掉宿主,再启动它,`superagent_status` 会显示 `interrupted`,`superagent_resume` 会把它跑完。只有当没有任何活着的进程拥有这个 run 时,它才会是 `interrupted`:原宿主还在跑的时候,它拥有的 run 不会被动,下一次挂载会把它报成活跃,而不是 interrupted。
142
+
143
+ 两条关闭路径行为不同,E2E 记录里都有:
144
+
145
+ - **硬杀(或崩溃)。** 心跳只有几秒旧,但在写下这个 run 的那台机器上会先检查那个 pid 是否已死,所以下一次挂载会立即回收,并打印
146
+ `reclaimed: owner pid … is not running and this state directory is local`。
147
+ 如果状态目录是另一台机器写的共享目录,就改为信任心跳,那里的回收最多要等 90 秒。
148
+ - **优雅关闭。** 如果 run 还在飞的时候宿主消失(例如一次 `wait_seconds: 0` 之后结束的无头单次运行),插件会发现 `subagents` 服务不在了,把没做完的 subtask 留在 `pending`,并以 `interrupted` 落定这次 run,附上
149
+ `note: the host shut down while this run was active`。不会把 attempt 浪费在一个已经无法应答的服务上。这种情况下宿主进程本身可能还会滞留,直到某个无视 abort 的子进程退出;那段等待属于宿主,不属于插件。
150
+
151
+ ## 配置
152
+
153
+ 在 `<profile>/cordis.patch.yml` 里写行配置:
154
+
155
+ ```yaml
156
+ - id: superagent
157
+ config:
158
+ maxSubtasks: 8
159
+ maxParallel: 3
160
+ maxActiveRuns: 2
161
+ ```
162
+
163
+ | 配置项 | 默认值 | 含义 |
164
+ | --- | --- | --- |
165
+ | `stateDir` | `$DSH_HOME/state/superagent` | run 状态根目录。 |
166
+ | `provider` | `spawn` | planner、worker、aggregator 使用的子 agent 后端。 |
167
+ | `childProvider` | 跟随父级 | 可选的子 agent provider 路由覆盖。 |
168
+ | `childModel` | 跟随父级 | 可选的子 agent 模型覆盖。 |
169
+ | `childPreset` | 无 | 子 agent 使用的 agent preset。preset 决定子 agent 的工具集;这个宿主没有按 run 过滤工具的能力。 |
170
+ | `plannerPreset` | 无 | 只给 planner 子 agent 用的 preset。请用无工具的 preset:planner 只读自己的 prompt 并返回 JSON,继承来的工具反而会引出一整轮工具调用而不是计划。需要宿主组合出 `agentPresets` 注册表。 |
171
+ | `plannerProvider` | 跟随父级 | 可选,planner 子 agent 的 provider 路由覆盖。 |
172
+ | `plannerModel` | 跟随父级 | 可选,planner 子 agent 的模型覆盖。规划只是一次 JSON 回合,所以这里换个更强的模型,通常比 worker 跑完之后再修计划便宜。 |
173
+ | `plannerTimeoutSeconds` | `120` | 单次规划尝试的墙钟上限。超时后这次尝试被停止并记录;不会转而启动一个兜底 worker。 |
174
+ | `plannerMaxModelCalls` | `20` | 规划阶段跨多次尝试可以花的模型调用数;`0` 表示不限制。花完就以"无法规划"失败,而不是把整个 run 的预算抽干。 |
175
+ | `maxSubagentDepth` | `1` | 子 agent 还能往下委派几层。`1` 禁止孙代理;`provider-managed` 交给后端。 |
176
+ | `commandWorkerPermission` | `inherit` | 给"计划条目里声明了命令能力"的 worker(`shell`、`bash`、`pwsh`、…)使用的沙箱模式。`danger-full-access` 让这些 worker 在 `workspace-write` 宿主上真正执行命令;其他子 agent 保持继承。见[按 worker 设置命令权限](#按-worker-设置命令权限)。 |
177
+ | `maxSubtasks` | `8` | 计划中子任务数量的上限。工具参数只能调低,不能调高;硬上限 16。 |
178
+ | `maxParallel` | `3` | 同时执行的子任务数。工具参数只能调低;硬上限 8。 |
179
+ | `maxActiveRuns` | `2` | 每个状态目录的活跃 run 数,跨共享该目录的 profile 和宿主计算。超出后再 `superagent_start` 会被拒,除非带上 `queue: true`,那样会等一个空位。`superagent_resume` 不计入配额,配额满了也能用,因为它只是把已经存在的活儿干完。 |
180
+ | `maxQueuedRuns` | `5` | 同时允许排队等空位的 run 数;硬上限 32。`0` 关闭排队,超过 `maxActiveRuns` 的启动重新一律被拒。 |
181
+ | `queueTimeoutMinutes` | `30` | 排队的 run 等多久还没开始就失败;期间不花任何钱。 |
182
+ | `queueOnFull` | `false` | 让每个超过 `maxActiveRuns` 的启动都排队,而不只是显式传 `queue: true` 的那些。 |
183
+ | `attempts` | `2` | 每个子任务的尝试次数,用完即标记失败。看起来是暂时性的失败(配额、限流、超时、5xx)会依次等 2s、4s、8s 再试。 |
184
+ | `deadlineMinutes` | `120` | 墙钟预算;到期后 run 以 `partial` 或 `failed` 结束。 |
185
+ | `maxModelCallsPerRun` | `80` | 每个 run 子 agent 模型调用次数的硬上限;`0` 关闭。 |
186
+ | `maxTokensPerRun` | `2000000` | 每个 run 的 prompt + completion token 硬上限;`0` 关闭。 |
187
+ | `pricing` | 空 | 每百万 token 的价格,键必须与用量日志里模型的名字完全一致(`provider/model`)。开箱状态下没有任何价格。 |
188
+ | `resultCapBytes` | `32768` | 每个子任务报告保留的字节数。 |
189
+ | `notifyOnComplete` | `true` | 主动消息的总开关。关掉之后插件永远不会叫醒会话。 |
190
+ | `maxNotificationsPerHour` | `3` | 每小时允许的主动消息数。超出上限的 run 会被折叠成一条摘要;`0` 取消上限。 |
191
+ | `notifyRetries` | `2` | 宿主拒绝唤醒时的额外投递次数;同一个会话的消息按顺序投递。 |
192
+ | `notifyRetryDelayMs` | `2000` | 上述重试的首次间隔,每次翻倍,上限 60s。 |
193
+ | `autoResumeRounds` | `1` | 在报告失败之前,针对"看起来是暂时性"的失败再重试子任务的轮数;`0` 关闭。 |
194
+ | `childModelFallback` | 无 | 这类重试(配额、限流、超时)时使用的模型。不设则沿用配置的路由。 |
195
+ | `memory` | `true` | 跨 run 的笔记本。见[跨运行记忆](#跨运行记忆)。 |
196
+ | `memoryScope` | `default` | 按 scope 分文件,让不相关的项目彼此分开。run 的笔记写在这里;`rules` 和 `profile` 会被读进每一个 run。 |
197
+ | `memoryMaxEntries` | `60` | 压缩阈值:一次会超过它的写入会把笔记本压缩到这个条数(400 行 / 128 KB 也是硬上限)。 |
198
+ | `memoryMaxAgeDays` | `30` | 比这更旧的笔记被忽略,并在压缩时清掉。 |
199
+ | `memoryDigestEntries` | `12` | 注入 prompt 的笔记条数。 |
200
+ | `memoryDigestChars` | `1600` | 该 prompt 中笔记部分的字符预算。 |
201
+ | `memoryUserProfile` | `false` | 跨任务的用户画像(事实、偏好、决策),位于 `<stateDir>/user-memory`。关掉时不构建任何东西,也不创建目录。见[用户画像](#用户画像)。 |
202
+ | `keepRuns` | `0` | 挂载时删除早于这么多天的终态 run;`0` 全部保留。 |
203
+ | `guard` | 开 | worker 的路径与命令策略。每一项默认值和背后的理由见[worker 安全护栏](#worker-安全护栏)。 |
204
+ | `audit` | `true` | 只追加的审计轨迹。它只观察;关掉只会去掉轨迹,不会改变 run 的行为。 |
205
+ | `policyFile` | 存在时为 `<stateDir>/policy.json` | 权限策略文件。不设置且文件不存在就表示没有策略,即旧行为。 |
206
+ | `auditDir` | `<stateDir>/audit` | `audit.jsonl` 及其导出文件所在目录。 |
207
+ | `controlPort` | 关 | 嵌入接口的回环端口;`0` 让系统挑一个空闲端口。见 [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md)。 |
208
+ | `workspaceIsolation` | `false` | 给每个 worker 一个自己的 git worktree,避免并行 worker 互相覆盖。见[按 worker 隔离工作区](#按-worker-隔离工作区)。 |
209
+ | `workspaceRoot` | 宿主 cwd | `workspaceIsolation` 打开时,worker 在其中被隔离的仓库。必须是至少有一次提交的 git 工作树。 |
210
+ | `workbenchPort` | 关 | 本地工作区面板的回环端口;`0` 让系统挑一个空闲端口。面板自己读写文件,不经过宿主 API。 |
211
+ | `workbenchRoot` | `process.cwd()` | 面板可以浏览和编辑的目录。它之外的任何路径都会被拒绝。 |
212
+ | `consolePort` | 关 | 对话控制台的回环端口;`0` 让系统挑一个空闲端口。需要宿主的 `sessionController` 服务。 |
213
+ | `consoleRoot` | 先取 `workbenchRoot`,再取宿主 cwd | 控制台的对话会话所加入的目录。 |
214
+ | `consolePreset` | 宿主默认 | 控制台会话挂载的 agent preset id。工具跟着这个 preset 走,不跟本插件走。 |
215
+ | `schedulerTickSeconds` | `30` | 检查活跃计划是否到点的频率,单位秒(1–3600)。没有计划之前不会武装任何东西,所以对没有定时任务的安装没有影响。 |
216
+ | `schedulerHumanPriority` | `true` | 计划 `human_priority` 的默认值:定时 run 不能占掉最后一个空闲并发位。 |
217
+ | `schedulerMaxConsecutiveFailures` | `3` | 连续失败多少次后计划自动暂停并只通知一次(1–20)。 |
218
+
219
+ ### 切换模型
220
+
221
+ 模型选择是配置,不是代码。默认情况下子 agent 继承会话的模型,即 profile 的 `agent-default-model`。要把子 agent 钉在特定路由上,两个键都设,然后重启宿主:
222
+
223
+ ```yaml
224
+ - id: superagent
225
+ config:
226
+ childProvider: dashscope
227
+ childModel: qwen-flash
228
+ ```
229
+
230
+ 插件里没有编译进任何模型 id。API key 只从路由指定的环境变量读取;插件从不保存 key。默认 profile 的路由是 `deepseek-official`,读取 `DEEPSEEK_API_KEY`。
231
+
232
+ ### 其他路由
233
+
234
+ 上面的例子假设 profile 里已经装了 DashScope 路由。它不属于 base bundle:默认 profile 没有 `dashscope` provider,光有 `DASHSCOPE_API_KEY` 也不会变出一个来。先装好那条路由(见 harness 关于 LLM 插件的文档),再在 `childProvider` 里写它的名字。
235
+
236
+ ### 子 agent 的工具与递归
237
+
238
+ `maxSubagentDepth: 1` 会作为 `maxDepth` 传给宿主,所以 worker 无法再创建自己的子 agent。这条限制由宿主强制执行,而不是靠 prompt 劝说;如果某个 provider 做不到,`superagent_start` 会直接报错失败,而不是悄悄无限制地跑下去。
239
+
240
+ 在 `dsh@0.2.2-rc.1` 上**没有**强制的工具白名单。宿主的 subagent 启动请求里没有工具过滤字段,它自己的 `subagent` 工具也拒绝 `toolFilter` 配置,并指向 agent preset。因此 `childPreset` 才是收窄子 agent 工具集的受支持方式;没有专用 preset 时,worker 继承会话的工具。`superagent_*` 工具仍在它们的工具列表里,但管理 run 的那几个(`superagent_start`、`superagent_resume`、`superagent_cancel`、
241
+ `superagent_followup`、`superagent_inject`、`superagent_answer`)会拒绝从 worker 会话中运行;只有顶层 agent 能管理 run。
242
+
243
+ ### 按 worker 设置命令权限
244
+
245
+ `workspace-write` 的宿主沙箱会拒绝以管道 stdio 启动子进程(`EPERM`)。所以需要跑 `npm test` 的 worker 在继承策略下做不到,而这个插件也不会为整台机器关掉沙箱。`commandWorkerPermission` 只对声明了该能力的 worker 抬高权限:
246
+
247
+ ```yaml
248
+ - id: superagent
249
+ config:
250
+ commandWorkerPermission: danger-full-access
251
+ ```
252
+
253
+ 这样设置之后,计划条目中 `requires` 带命令能力(`shell`、`bash`、`sh`、`zsh`、`fish`、`terminal`、`pwsh`、
254
+ `powershell`、`cmd`、`run_command`、`exec_command`)的 worker 获得完全访问权。planner、aggregator、验收判定,以及没有这类能力的 worker,仍然保持继承模式。
255
+
256
+ 它的工作原理,以及为什么这是一种"委派技巧"而不是宿主特性:
257
+
258
+ - 宿主没有按子 agent 设置权限的字段。它有的是继承机制:`subagents.startActivation` 会**在第一次 `await` 之前同步地**捕获父会话最后的
259
+ `sandbox/mode` 事件,并把该模式播种给子会话。
260
+ - 对一个符合条件的 worker,插件先向父会话追加 `sandbox/mode:
261
+ danger-full-access`,调用 `startActivation`,再在 `finally` 里把先前的模式追加回去——整个过程在同一个同步 tick 内完成,中间没有 `await`。因此并发调用永远看不到这个临时覆盖,而子会话仍然捕获到了它。
262
+ - 两个步骤各追加一条 `sandbox/mode` 事件;插件从不用
263
+ `permissionPresets.set()`,因为它的 `custom` 状态无法按名字恢复。
264
+ - 该子会话的审批策略被钉为 `never`,这是宿主自己的委派捕获行为,不是本插件做的。
265
+ - 每一步都会以 `worker.escalate` 和 `worker.restore` 写进审计轨迹,带上 `runId`、`subtaskId` 和原因(所声明的能力)。`audit` 关闭时不写审计行,但升级行为本身不变。
266
+
267
+ 限制:这只适用于进程内、子会话由同一宿主进程中的父会话创建的那种 provider(`provider: spawn`)。如果上游改变了捕获时机,或者改变了委派继承本身,这里会静默退回继承模式,而不是让 run 失败。另外,当父会话没有显式覆盖时,这个临时事件也会把"部署默认模式"钉进父日志:它记录的是部署默认值,在该默认值变化之前行为完全一致。
268
+
269
+ ### 按 worker 隔离工作区
270
+
271
+ 并行 worker 是相互独立的 agent,但默认共用一个工作目录:两个子任务改同一个文件就会互相覆盖,最后写的赢。`workspaceIsolation` 通过给每个 worker 一份自己的 checkout 来解决这个问题。
272
+
273
+ ```yaml
274
+ - id: superagent
275
+ config:
276
+ workspaceIsolation: true
277
+ workspaceRoot: /home/me/projects/api # or C:\work\api on Windows
278
+ ```
279
+
280
+ **为什么用 git worktree 而不是复制目录。** 隔离难的那一半是把结果合回去。worktree 免费提供了这件事:真正的三方合并、带冲突检测、两侧都保留为 ref,还留一条命令让用户手工收尾。递归复制要么需要 diff3 引擎(本包没有这个依赖),要么直接覆盖主 checkout——而那正是这个特性要防的 bug。worktree 还共享对象库和忽略规则,所以 worker 看到的是真实仓库,而不是它的一份完整拷贝。worktree 放在宿主启动目录下的 `.superagent/worktrees/<runId>/w<n>`——如果宿主就是在仓库里启动的,那就是仓库本身。宿主的 `workspace-write` 沙箱以会话 cwd 为可写边界,所以放在状态目录下、或者放在宿主并非在其中启动的仓库里,checkout 的每次写入都会被拒。这个 worktree 池自带 `.gitignore`,因此 worker 的 checkout 不会漏进用户的下一次提交,也不会让主 checkout 看起来是脏的。
281
+
282
+ **run 期间发生什么。** 每个 worker 拿到一个从主 checkout 的 `HEAD` 创建的
283
+ `superagent/<runId>-w<n>` 分支。它的 prompt 里写明绝对路径,并禁止碰其他任何东西、切分支、commit、merge 或 push。worker 结束时,run 会把它在 checkout 里留下的东西提交掉(所以忘了 commit 的模型也不会丢东西;git hook 被跳过,免得 pre-commit 钩子挡住合并),然后在所有子任务结束之后,**逐个**把分支合并回主 checkout。
284
+
285
+ **合并冲突时你会看到什么。** 合并被中止,主 checkout 精确恢复到原样,里面不会留下冲突标记。结果记录在 run 上,并由 `superagent_status` 打印:
286
+
287
+ ```
288
+ workspace conflict: [2] src/routes.js, src/index.js — branch superagent/20261115T101500-ab12-w2
289
+ kept at <repository>/.superagent/worktrees/20261115T101500-ab12/w2; the main checkout was restored, so nothing
290
+ was lost. Resolve with: git -C "/home/me/projects/api" merge superagent/20261115T101500-ab12-w2
291
+ ```
292
+
293
+ 该 run 的唤醒消息会用一行说出同样的事,因为冲突是那种即便 run 本身"completed"也必须让人知道的结局。什么都不会被丢弃:分支和它的 checkout 会一直保留,直到你合并或删除它们。另外两种情况也照样报告,而不是悄悄丢掉:
294
+
295
+ - 该合并时主 checkout 还有未提交的改动——所有分支都不合并,因为往脏树上合并会把你的改动和 worker 的混在一起,中止时还会恢复成错误的状态;
296
+ - 合并之前 run 被取消或撞上了 deadline——分支保留,resume 会复用同一批 worktree。
297
+
298
+ **无法隔离时。** 如果 `workspaceRoot` 不是 git 工作树、`PATH` 里没有 git,或者仓库还没有任何提交,run 不会失败。它退回共享目录(也就是旧行为),并且 `superagent_status` 和通知都会说明:
299
+
300
+ ```
301
+ workspace: isolation was requested but is unavailable — /tmp/notes is not a git working tree,
302
+ so a per-worker worktree cannot be created; workers shared /tmp/notes, so their edits can
303
+ overwrite each other
304
+ ```
305
+
306
+ **直说限制。** `dsh@0.2.2-rc.1` 不给子 agent 提供 `cwd` 字段,所以插件无法在 spawn 时交给 worker 一个目录。隔离是一份 prompt 约定加一个真实分支:无视 prompt 的 worker 仍然能改主 checkout,但这种改动会在任何合并之前出现在 `git status` 里,也破坏不了兄弟分支。关掉隔离时,行为与这个选项存在之前完全一致。
307
+
308
+ ### worker 安全护栏
309
+
310
+ worker 继承会话的文件系统和凭据,所以 superagent 子 agent 的每次工具调用都会经过挂在宿主
311
+ `tools/pre-execute` 路径上的护栏(有 `ctx.tools.guard` 时走它)。护栏只约束本插件 spawn 的子 agent;父会话不受影响。
312
+
313
+ ```yaml
314
+ - id: superagent
315
+ config:
316
+ guard:
317
+ enabled: true
318
+ allowWriteRoots: [] # extra writable roots, absolute or ~-relative
319
+ denyPaths: [] # extra read+write denials
320
+ denyCommands: [] # [{ id, pattern, reason }] extra regex denials
321
+ allowCommands: # explicit overrides; every use is recorded
322
+ - id: clean-build
323
+ pattern: '^rm -rf build$'
324
+ reason: clean build output
325
+ maxEvents: 50
326
+ ```
327
+
328
+ 默认值,以及为什么这么设:
329
+
330
+ | 规则 | 默认值 | 理由 |
331
+ | --- | --- | --- |
332
+ | 可写根目录 | 子会话的工作目录加上操作系统临时目录 | worker 需要自己的工作区和一处草稿区。其他一切都与任务无关,因此拒绝。状态目录**故意**不可写:worker 不能改写 run 记录或报告。 |
333
+ | 始终拒绝(读和写) | `~/.ssh`、`~/.aws`、`~/.gnupg`、`~/.netrc`、`~/.npmrc`、`~/.yarnrc`、`~/.pypirc`、`~/.git-credentials`、`~/.docker/config.json`、`~/.kube/config`、`~/.config/gcloud`、`~/.config/gh/hosts.yml`、`~/.azure`、任何 `.git/config` 与 `.git/hooks` | 这些是凭据或代码执行入口。工作区再大也不会开放它们。 |
334
+ | 系统目录 | 一律不可写(`C:\Windows`、`C:\Program Files`、`C:\ProgramData`、`/etc`、`/usr`、`/bin`、`/boot`、`/dev`、`/System`、`/Library`、…),操作系统临时目录除外 | 读它们是正常的(`win.ini`、`/etc/hosts`);写它们不是开发任务。临时目录之所以例外,是因为服务账号的 `%TEMP%` 可能落在 `C:\Windows\TEMP` 下,而 worker 仍必须能在那里写草稿文件。 |
335
+ | `cmd/recursive-force-delete` | 当目标是 `/`、盘符根、`~`、`.`、`..`、`*`、可写根之外,或包含其中之一时拒绝 | `rm -rf build` 和 `rm -rf node_modules` 是正常的;`rm -rf /` 和 `rm -rf .` 不是。一刀切地封掉所有 `rm -rf` 会让日常清理没法做,所以由目标决定。 |
336
+ | `cmd/disk-format` | `mkfs`、`diskpart`、`wipefs`、`format X:`、`dd of=/dev/sd*` | 从来不是开发动作。 |
337
+ | `cmd/system-scheduler` | `schtasks /create`、`Register-ScheduledTask`、`crontab -r`、`systemctl enable\|disable\|mask`、`launchctl load` | 在工作区之外建立持久化。 |
338
+ | `cmd/system-registry` | 针对 `HKLM`/`HKCR` 的 `reg add/delete`,以及任何 `\Run` 键 | 全机范围或开机自启的改动。 |
339
+ | `cmd/system-write` | 目标为系统目录的重定向或写 cmdlet,包括 `%SystemRoot%`/`$env:SystemRoot` | 抓住藏在变量后面的写入。 |
340
+ | `cmd/permission-nuke` | `chmod -R 777 /`、递归 `chown /`、`icacls … /grant Everyone /t` | 摧毁机器的访问模型。 |
341
+ | `cmd/credential-access` | 点名上述凭据位置、`id_rsa`、`id_ed25519`、… 的 shell 命令 | worker 读 key 和写 key 一样有害。 |
342
+
343
+ 拒绝是真实的工具错误,不是静默失败:worker 会收到
344
+ `[guard] blocked <tool>: rule <id> — <reason>. The call did not run.`,事件也会加到 run 上。`superagent_status` 打印
345
+ `guard: N tool call(s) blocked; M explicit allow(s) recorded (rule ×count)`
346
+ 以及最多三条被拦下的命令,最终报告会多出一节 `## Safety guard`,列出每一个保留的事件。即使 `maxEvents` 截断了列表,计数器也统计全部事件。
347
+
348
+ `allowCommands` 是唯一的越权通道。它胜过拒绝,但每一次命中都会以 `decision: allowed` 记录下来,并注明它覆盖了哪条规则,所以覆盖行为永远不会隐身。凭据、`.git` 控制项和系统目录的拒绝不可覆盖;要放行工作区之外的合法构建目录,请加进 `allowWriteRoots`。护栏基于词法和 realpath,所以工作区内指向被拒路径的符号链接照样会被抓住。
349
+
350
+ 护栏是加在工具参数上的一层策略,不是操作系统沙箱。把写入委托给某个程序的命令(`node build.js`、一个编译器)仍然能写到那个程序能写的任何地方;要挡住它需要宿主级沙箱,而 `dsh@0.2.2-rc.1` 没有暴露。护栏拦住的是直接的 `write`/`edit`/
351
+ `apply_patch` 目标、shell 重定向,以及上面那些破坏性命令类型——这恰好覆盖了一个乱走的 worker 真正会造成的"误删 `rm`"和"写进 `C:\Windows`"。
352
+
353
+ ### 花费上限与价格
354
+
355
+ 两道硬预算,能在病态目标开始悄悄烧钱之前把它停住。两者都在每次 spawn 子 agent 之前检查,所以重试循环也绕不过去:
356
+
357
+ ```yaml
358
+ - id: superagent
359
+ config:
360
+ maxModelCallsPerRun: 40
361
+ maxTokensPerRun: 500000
362
+ pricing:
363
+ deepseek-official/deepseek-flash:
364
+ input: 0.28 # price per 1M uncached prompt tokens (example)
365
+ output: 0.42 # price per 1M completion tokens (example)
366
+ cacheRead: 0.028 # optional; defaults to the input price
367
+ currency: CNY
368
+ ```
369
+
370
+ 价格键会与用量日志里的模型 id 匹配,那个 id 就是
371
+ `provider/model`——`superagent_status` 会在 `usage:` 行打印它,从那里复制键即可。先精确匹配,再不济按裸模型名匹配,所以没有精确条目时 `qwen-flash` 也能给 `dashscope/qwen-flash` 定价。插件不为任何路由内置价格,因为过期价格比没有价格更糟。
372
+
373
+ 预算触顶时不再启动新的子 agent,并让 abort controller 停掉还在跑的那个,于是花费停在帽子上,而不是再抽干一个 worker。已经完成的报告仍然会被合并。至少有一个子任务完成时 run 以 `partial` 结束,一个都没完成时以 `failed` 结束(没做完的子任务留在 `pending`)。`superagent_resume` 会用当前配置重建限额,保留已经花掉的部分。从那里继续——这也是提高上限的方式。在真实宿主上,把
374
+ `maxModelCallsPerRun` 从 2 提到 80 再 resume 一个停在 2/2 的 run,它跑完了,且没有丢掉先前的花费。
375
+
376
+ 即使子会话日志读不到,一次 spawn 也算一次模型调用,所以调用预算在日志布局变了的宿主上仍然有效。token 记账仍然依赖日志;读不到时 run 会打印一行
377
+ `usage note:`,说明这些数字只是下界。
378
+
379
+ 花费是根据上表估算的,绝不来自内置猜测。没列出的模型报为 `unpriced` 并排除在合计之外,所以你看到的数永远是下界:
380
+
381
+ ```
382
+ cost: at least ¥0.0041 (estimate; no price for haoduo/gpt-6.1-sol)
383
+ ```
384
+
385
+ 金额按币种分别记账,绝不跨币种相加。同时用了 CNY 和 USD 路由的 run 会每种币种打一个小计:
386
+
387
+ ```
388
+ cost: ¥0.0952 + $0.0248 (estimate; all models priced)
389
+ ```
390
+
391
+ 同样的规则适用于 `superagent_list` 的账目行、实时 `watch` 的页脚、导出的 `README.md` 以及 HTML 报告——混合窗口会得到每种币种一个数字,而不是一个单位不明的单一数字。
392
+
393
+ ## 运行时控制
394
+
395
+ 插件可以驱动浏览器,在 Windows 上还可以驱动桌面。两部分**默认都关**:`runtime.enabled` 为 false 时,这些工具一个都不注册,已有的 profile 看到的工具列表与之前完全一样。这里不需要任何 npm 依赖——浏览器通过 DevTools 协议、用 Node 自带的 `WebSocket` 对话,桌面则通过 `powershell.exe` 和 `user32.dll` 触达。
396
+
397
+ ```json
398
+ {
399
+ "@xiangyixie/dsh-superagent": {
400
+ "runtime": {
401
+ "enabled": true,
402
+ "browser": {
403
+ "headless": true,
404
+ "allowedHosts": ["localhost", "127.0.0.1"],
405
+ "executablePath": null,
406
+ "attachPort": null,
407
+ "userDataDir": null
408
+ },
409
+ "desktop": { "enabled": false, "allowActivation": false }
410
+ }
411
+ }
412
+ }
413
+ ```
414
+
415
+ `enabled` 打开这一层。`browser.enabled` 和 `desktop.enabled` 决定哪一半注册;桌面单独设闸,因为它能碰机器上的任何应用。`allowedHosts` 替代回环默认值——开头的 `*.` 匹配任意子域。`stopFile` 和 `shotDir` 默认是
416
+ `<stateDir>/runtime/STOP` 和 `<stateDir>/runtime/shots`。
417
+
418
+ `attachPort` 和 `userDataDir` 是两种触达"需要登录的页面"的方式,代价各不相同:
419
+
420
+ - **`attachPort`**(例如 `9222`)借用你自己用 `--remote-debugging-port` 启动的浏览器。元素列举、点击、输入、截图全都走那条连接,标签页保持自己的窗口尺寸,而
421
+ `browser_close` 只是断开——它从不终止你的浏览器。如果端口没在监听,调用会失败并给出端口和启动命令;它绝不会背着你退回一个全新的 profile。因为那个 profile 已经登录了你用的东西,每个动作都会继承那份权限。
422
+ - **`userDataDir`** 为本插件启动的浏览器保留一个专用 profile:登录一次(二维码、短信,站点要什么就什么),之后的 run 复用同一个 cookie jar。这个目录是磁盘上一份真实的凭据存储——请放在你愿意放密码文件的地方,不要指向日常浏览器的 profile。设置 `attachPort` 时它会被忽略。
423
+
424
+ 默认仍然是 `%TEMP%/dsh-runtime-profile-*` 下的临时 profile,所以普通 run 看不到你日常浏览器的 cookie。
425
+
426
+ ### 注册的工具
427
+
428
+ | 工具 | 作用 |
429
+ | --- | --- |
430
+ | `browser_open(url, headless?, width?, height?)` | 用全新的或持久化的 profile 启动浏览器,或者在你设置了 `attachPort` 时附着到你的浏览器;打开 URL,返回 URL、标题、视口和一张截图路径。登录、CAPTCHA、短信或二维码页面会以 `[attention]` 返回。 |
431
+ | `browser_elements(text?, role?, limit?)` | 列出可操作元素,带稳定索引、无障碍名、角色、包围盒以及是否在视口内。匹配依据是可见文本、ARIA 名或角色——不只靠 CSS。 |
432
+ | `browser_click(index?, css?, text?, role?, confirm?, screenshot?)` | 把元素滚进视口,在它的中心派发真实的鼠标按下/抬起,然后截图。 |
433
+ | `browser_type(index?, css?, text?, value, submit?, screenshot?)` | 聚焦输入框,通过浏览器输入管线插入文本,可选按回车,并报告页面现在的值(密码框会被遮蔽)。 |
434
+ | `browser_screenshot(path?, full_page?)` | 页面 PNG,带路径、像素尺寸和字节大小。 |
435
+ | `browser_script(expression, await_promise?)` | 求值一个表达式并返回其 JSON 值;用于读取,不用于点击。 |
436
+ | `browser_wait(text?, css?, url_contains?, milliseconds?, timeout_ms?)` | 等待某个条件或固定时长。 |
437
+ | `browser_await_human(timeout_ms?, poll_ms?, screenshot?)` | 等待人去完成登录、CAPTCHA、短信、双因素或二维码检查;可以继续自动化时返回 ok,仍在等待时返回 `[attention]`。它从不自己解这个检查。 |
438
+ | `browser_close()` | 关闭本插件启动的浏览器。在 attach 连接上它只断开,你的浏览器继续运行。 |
439
+ | `desktop_screenshot(window?, path?)` | 整个桌面,或用 `PrintWindow` 抓取某个标题的窗口(被遮挡的窗口也能拿到自己的像素)。 |
440
+ | `desktop_windows(filter?, limit?)` | 可见的顶层窗口:句柄、标题、pid、屏幕矩形。 |
441
+ | `desktop_click(x, y, window?, activate?, right?, confirm?)` | 按屏幕坐标点击。默认后台;前台点击必须 `activate`。 |
442
+ | `desktop_type(text, window?, activate?)` | 向窗口输入文本,默认后台 `WM_CHAR`。 |
443
+ | `desktop_keys(keys, window?, activate?)` | 按顺序按下具名键(`enter`、`tab`、`f5`、`a`、`1` …)。 |
444
+ | `runtime_status()` | 停止状态、已注册的部分、允许的 host、浏览器可执行文件、attach/启动模式、会话。 |
445
+
446
+ 每次浏览器和桌面调用都会往既有审计轨迹(`lib/audit.js`)写一行,带 `source: "runtime"`、动作、目标、判定、
447
+ 结果和耗时。被闸门拒绝的动作写
448
+ `decision: "deny"` 或 `"confirm"` 以及 `result: "blocked"`,所以日志永远不会声称一次被拒的点击成功了。浏览器那几行还带 `meta.session`——
449
+ 动作跑在你启动的浏览器上时是 `"attach"`(带 `meta.port` 和它复用的标签页),跑在本插件启动的浏览器上时是 `"launch"`(带
450
+ `meta.profile` 和 `meta.persistentProfile`)——因此轨迹永远不会把你的会话和一次性 profile 搞混。需要人介入的页面会写
451
+ `kind: "attention"`、`decision: "attention"` 和 `result: "needs-human"`。
452
+
453
+ ### 闸门
454
+
455
+ - **紧急停止。** 停止文件存在期间——或者设置了 `DSH_RUNTIME_STOP=1`——每个动作都被拒绝,且拒绝行为会被审计。创建该文件,这一层在下次调用时停下;删掉它即恢复。
456
+ - **导航。** 只允许 `http:` 和 `https:`,且 host 在白名单内。`file://` 被拒,因为能读本地文件的页面会绕过工作区护栏;`javascript:`、`data:` 和 `chrome:` 同样被拒。
457
+ - **上传。** `browser_click` 拒绝 `<input type="file">`,因为随之而来的原生文件选择器无法被驱动,会一路落到用户自己的文件系统上。
458
+ - **不可逆动作。** 标签里出现 submit、delete、pay、publish、transfer、提交、删除、支付 … 的目标需要 `confirm: true`。没有它点击不会发生,审计行记录 `decision: "confirm"`。
459
+ - **人工检查。** 要求登录、CAPTCHA、短信验证码、双因素确认或扫码的页面会在那一点停下动作,返回
460
+ `[attention]`,说明页面要什么以及如何交接。检查内容是从页面文本里读的,所以一个带密码框但没有登录字样的普通设置页不会被误判;这里不会去解或去输入那个检查。在启动的窗口或 attach 的标签页里,人就在浏览器里完成,然后
461
+ `browser_await_human` 轮询到它消失,run 继续。等待中的检查是一次交接,不是失败的 run。
462
+ - **焦点。** 后台点击或按键从不把窗口拉到前面。前台动作需要 `activate: true` **并且**
463
+ `runtime.desktop.allowActivation: true`,每次激活都记录在
464
+ `meta.activated` 里。
465
+ - **worker agent。** `browser_*` 和 `desktop_*` 属于挂载插件的那个会话。护栏会以规则
466
+ `guard/runtime-tool` 拦下受绑定的子 agent 的调用,除非 `guard.allowRuntimeTools` 为 true。
467
+
468
+ ### 它刻意做不到的事
469
+
470
+ - **顺手借用你的登录态。** 启动的浏览器拿的是
471
+ `%TEMP%/dsh-runtime-profile-*` 下的全新 profile,所以你的 cookie、保存的密码和已登录会话根本不在那里。触达需要认证的页面是一个明确选择:attach 到你自己用
472
+ `--remote-debugging-port` 启动的浏览器并设置 `browser.attachPort`,或者把
473
+ `browser.userDataDir` 指向一个专用 profile 并在那里登录一次。两者都会让那份权限对之后每个动作可用,也都会出现在审计日志的
474
+ `meta.session` 里;attach 端口写错会失败并给出说明,而不是悄悄启动一个新 profile。
475
+ - **替你通过人机验证。** CAPTCHA、短信验证码、"确认你是真人"的中间页、扫码登录都会停下动作交还给人。它从不替你输码或扫码;它等你做完,然后报告 run 可以继续。
476
+ - **规避 bot 检测。** 启动的 Chromium 能通过 CDP 特征被检测出来,封自动化站点的站会连它一起封。这里没有修补 `navigator.webdriver`,也没有伪装指纹。
477
+ - **往任何应用里输入。** 后台 `WM_CHAR` 能触达经典 Win32 控件;Chromium、Electron、Qt 和大多数游戏会忽略投递的消息。对它们,要么 `activate: true` 并接受焦点变化,要么改用 `browser_*` 驱动页面。
478
+ - **猜坐标。** `desktop_*` 用的是物理屏幕像素。DPI 缩放混杂时,先 `desktop_screenshot`,再从
479
+ `desktop_windows` 读矩形,而不是自己算。
480
+ - **控制 macOS 或 Linux 桌面。** 桌面这一半只支持 Windows。浏览器那一半在任何有 Chromium 系二进制的地方都能用。
481
+
482
+ 仓库里带了两份可直接跑的验证。`node scripts/runtime-demo.mjs`
483
+ 启动一个本地页面,点一个按钮,从 DOM 读回计数器,往输入框里打字,在不可逆按钮和文件输入上被拒,翻转停止开关,并打印审计行和截图路径。
484
+ `node scripts/runtime-desktop-demo.mjs` 打开一个不激活的测试窗口,向它投递点击和文本,用目标进程自己的状态文件验证两者,
485
+ 并抓取该窗口。
486
+
487
+ ## 工具
488
+
489
+ - `superagent_start(goal, mode?, queue?, max_subtasks?, max_parallel?, deadline_minutes?, allow_duplicate?, wait_seconds?)`
490
+ 启动一次 run 并立刻返回 run id。`mode: "direct"` 让一个 worker 直接跑这个 goal,不要 planner 也不要 aggregator,并把该 worker 的回复原样作为报告返回——适合一次自成一体的查询、修改、检索或短写作,不适合可以并行拆开的目标。默认的 `mode: "planned"` 走完整的 planner → worker → 合并报告流程。计划中的子任务可以声明 `dependsOn` 另一个子任务:依赖方会等它,并在自己的 prompt 里拿到它的报告,而彼此独立的子任务仍然并行。依赖成环会在任何工作开始前否掉整个计划,依赖一个计划从未声明的任务则以原因跳过。两种模式产出相同的 run 记录、配额、deadline、取消和用量记账。`goal_mode: true` 增加一步验收,并在失败的轮次重新规划;见 [Goal 模式](#goal-模式)。
491
+ `queue: true` 让 `maxActiveRuns` 占满时的启动改为等空位而不是失败:它返回 `status: "queued"` 以及
492
+ `queue.position` / `queue.of`,某个活跃 run 结束时自动开始,等不到空位则在
493
+ `queueTimeoutMinutes` 之后失败。最多 `maxQueuedRuns` 个在等;排队的 run 在等待期间不计入 `maxActiveRuns`,取消它会干净地把它从队列里移除。启动一个同会话中活跃 run 已经覆盖的 goal,会返回那个 run id 并标上
494
+ `deduped: true`,而不是为第二个计划付钱:比较前会去掉首尾空白、折叠连续空白并忽略大小写,检查在一个按 goal 命名的 claim 锁下进行,并落在状态目录里,所以共享该目录的两个进程也只会启动一个 run。匹配是按会话的,因为两个会话同时要同一个泛化的 goal 是合理的。
495
+ `allow_duplicate: true` 可以再起一个。已结束的 run 从不阻止同一个 goal 再次启动。`wait_seconds` 会阻塞到终态,并在结果里保留 `deduped` 标记。
496
+ - `superagent_status(run_id, wait_seconds?)` 返回状态、里程碑、
497
+ 每个子任务的结果、实测 token 用量、估算花费、报告文件路径,以及最终报告。
498
+ - `superagent_list(limit?)` 列出 run,最新的在前,并给出状态目录的文件数与大小。
499
+ - `superagent_cancel(run_id)` 停止 run,可从任何进程调用;见下文。
500
+ - `superagent_resume(run_id, wait_seconds?, force?)` 继续一个 `interrupted`、
501
+ `failed`、`partial` 或 `cancelled` 的 run;已完成的子任务保留。worker 会被告知什么失败了,并被要求检查之前那次尝试已经做了什么。只有启动该 run 的会话才能 resume 它。resume 不计入
502
+ `maxActiveRuns`,所以配额满了也能用;`force` 仍然被接受,但已不再需要。`completed` 的 run 保持 completed,除非它持有一个从未进入任何 prompt 的答案——那时 resume 会重新打开它,否则那个决定就会被搁浅。
503
+ - `superagent_followup(run_id, message)` 往已经在执行的 run 里加一条指令,而不是另起一个 run。这个工具明确是"下一个 prompt 生效":指令排在 run 上,下一次为它构建的 prompt 会带上它——下一个 worker 的 spawn 或聚合,哪个先到算哪个。已经在跑或已完成的子任务保留自己的结果,永远看不到它。回复会点名这个边界,status 也显示同样的东西;在最后一个边界之后到达的指令记录为
504
+ `never took effect`,而不是看起来已投递。暂停的 run
505
+ (`interrupted`、`failed`、`partial`、`cancelled`)会保留这条指令给下一轮,resume 时开始;`completed` 的 run 会拒绝它。属于另一个进程的 run 会被拒绝,因为那个 owner 的下一次保存会覆盖它。只有启动该 run 的会话才能往里加。如果正在跑的 worker 必须立刻读到指令,用
506
+ `superagent_inject`。
507
+ - `superagent_inject(run_id, message, subtask_index?, wait_seconds?)` 把一条指令送进此刻正在运行的 worker。它使用宿主的实时引导通道(`subagents.sendMessage`,即 agent 循环在下一个 pre-step 排空的同一个收件箱),所以消息会成为子 agent 下一次模型请求的一部分。它不会打断已经在飞的模型调用:延迟就是当前那一步剩下的部分(那次模型响应加上它的工具批次)。一个已经决定收尾的活着的子 agent 会再跑一轮来读它,所以未被取消的子 agent 会消费掉它。回复报告从接受到子 agent 下一次请求的实测延迟,并在子 agent 被取消、
508
+ 释放或在另一边界之前结束时,把消息标成 `missed`——而不是 delivered。在真实
509
+ `dsh@0.2.2-rc.1` 宿主上实测最坏情况:子 agent 步长 8 s 时 **6978 ms**,步长 4 s 时 **2986 ms**,也就是说上界跟着步长走,不是跟着插件走。宿主没有暴露实时通道时,工具退化为 followup 队列并在回复里说明;它从不把那种情况称作实时。
510
+ - `superagent_answer(run_id, attention_id?, answer, wait_seconds?)` 回答一条结构化的 attention 项,让 run 带着这个决定继续。活跃 run 在下一个边界应用答案;已结束的 run 会被重新打开,只重跑它的聚合,这次 prompt 里带着答案,所以报告反映该决定,而不是让用户另起一个 run。
511
+ 同时有多个问题时 `attention_id` 必填。答案按 id 匹配,不按数组位置匹配:从未问过的 id、已经回答过的问题、以及被后续 resume 退役的问题都会被拒绝,而如果答案文本正好是另一个问题的选项,会指出那个 id 而不是猜。
512
+ - `superagent_memory(action, key?, kind?, text?, scope?, query?, tags?, limit?)`
513
+ 列出、搜索、添加、更正或遗忘笔记本里的笔记。`set` 一个已存在的 key 会取代旧的;`forget` 撤回它。`scope` 指向 `rules`
514
+ (项目规则)、`profile`(用户偏好),或 run scope。`search`
515
+ 按 `query`(当前 goal 效果不错)和/或精确 `tags` 给笔记排序,于是相关的老笔记能被找到,而不只是最新的几条;笔记在设置时可以携带 `tags`。这个工具是增量的:另外十一个工具的参数和输出都不变。
516
+ - `superagent_template(action, id?, params?, template?, limit?)` 列出、展示、展开、保存或删除一个工作流模板:一个固定的 goal 骨架,带必需参数、适用场景和不适用场景。`expand` 返回一个普通 goal 字符串,`superagent_start` 会像对待手打的 goal 一样规划它;缺失或为空的参数会按名字被拒绝,而不是取默认值。模板不能设置限额、预算、模式或覆盖项,所以用模板永远不会扩大 run 的权限。内置 id 只读;自定义模板放在状态目录的模板目录下,那里的失败会被记录,但不会让 run 工具失效。
517
+ - `superagent_schedule(action, id?, name?, goal?, template_id?, params?, cron?,
518
+ every_minutes?, timezone?, miss_policy?, goal_mode?, acceptance?, max_rounds?,
519
+ max_wall_clock_minutes?, no_progress_rounds?, budget?, human_priority?)` 创建、列出、暂停、恢复、删除或立即运行一个定时计划。计划保存一个 goal(或展开后的模板)、一个时钟和它自己的限额;它能跨宿主重启存活,并启动没人手动发起的 run。没有计划之前不会武装任何东西。见[定时运行](#定时运行)。
520
+ - `superagent_audit(run_id?, subtask_id?, kind?, decision?, result?, target?,
521
+ since?, until?, limit?, order?, format?, out_path?)` 读审计轨迹,或把匹配的事件导出成一个 JSONL 或 CSV 文件。见
522
+ [权限与审计](#权限与审计)。
523
+
524
+
525
+ ## Goal 模式
526
+
527
+ 普通 run 在子任务结束时结束。这和"目标达成了"不是一回事,一个计划完全可能在构建已经坏掉的情况下报告成功。Goal 模式是可选开启的(在 `superagent_start` 或 `superagent_schedule` 上设 `goal_mode: true`),它增加一步独立的验收,并让 run 一直跑到每个条件都通过、或者某个硬停点说明必须由人来决定为止。
528
+
529
+ - **验收条件。** `acceptance` 必填,是 `{id?, text, check?}` 的列表。
530
+ `{"type":"command","command":"npm test"}` 或 `{"type":"file","path":"dist/app.js"}` 这样的 `check` 由插件自己执行,所以那个判定落在真实的退出码或真实存在的文件上,绝不落在模型的声称上。没有 check 的条件由另一个验收模型判定,`superagent_status` 会注明每个判定的来源。最多接受 12 个条件;更长的列表说明目标本身没框好,那不是清单。
531
+ - **轮次。** 失败的轮次不会重复同样的工作:下一轮的计划会拿到什么失败了、为什么。
532
+ `max_rounds`(默认 5,最大 20)、
533
+ `max_wall_clock_minutes`(默认 60)和 `no_progress_rounds`(默认 2)给它设界。当验收带有机器检查时,一个没有改动任何文件的轮次会立刻停下,而不是再付一轮钱。
534
+ - **硬停。** 循环带着原因停下,而不是永远转下去:轮次上限、墙钟、run 的 deadline、预算停、有一个未决的 attention 项、两轮完全相同的失败,或者某一轮无法取得进展。停止报告列出每个条件及其最后结果,以及试过什么。
535
+ - **通知。** 只有 goal 达成或循环停止时通知一次——轮次之间不通知。run 记录、状态行和报告都带轮次计数和每个条件的判定。
536
+
537
+ Goal 模式默认关闭,不新增自己的工具,也不会改变任何不带 `goal_mode: true` 的 run。
538
+
539
+ ## 定时运行
540
+
541
+ `superagent_schedule` 保存一个计划——一个 goal 加一个时钟——并在没人调用 `superagent_start` 的情况下启动它。定时 run 是普通的 run:同样的 planner、同样的配额、同样的预算、取消、用量记账、报告和状态。调度器只是编排器的一个定时形状的调用方,不是第二套 run 引擎。
542
+
543
+ ```text
544
+ superagent_schedule(action: "create", name: "nightly audit",
545
+ goal: "Audit yesterday's error logs and list anything new",
546
+ cron: "0 3 * * *", timezone: "Asia/Shanghai",
547
+ budget: { max_total_runs: 30, max_total_tokens: 5000000 })
548
+ ```
549
+
550
+ 动作有 `create`、`list`、`pause`、`resume`、`delete` 和 `run-now`。
551
+ `run-now` 立刻开始一次执行,但不移动下一个计划窗口。计划可以用 `template_id` 和 `params` 代替字面 `goal`;模板在创建时展开,所以之后编辑模板不会悄悄改变已有计划。
552
+
553
+ 计划保存它的时钟(`cron` 或 `every_minutes`,外加 `timezone`)、goal、
554
+ 可选的 `mode` / `goal_mode` 与 acceptance、它自己的 `budget`,以及
555
+ `human_priority`。计划持久化到状态目录下的 `schedules.json`,并在挂载时重新加载,所以宿主重启不会丢。只有至少存在一个计划时定时器才启动;空状态目录下 `init()` 不会创建那个状态文件。
556
+
557
+ ### 错过的窗口
558
+
559
+ 宿主停机期间到点的窗口**不会**全部重放。默认策略 `miss_policy: "latest"` 只跑最新一个错过的窗口,把其他每个到点窗口记录为 `missed`,并带上计划时间和原因(那时宿主没在运行);随后计划在正常网格上推进到下一个窗口。执行那个最新窗口的 run 是一次追赶,计划会说明这一点:`totalRuns` 计入它,`catchUpRuns` 记录有多少次是追赶,`started` 历史条目会写明是哪个窗口、它代表了多少个错过的窗口。`miss_policy: "none"` 跳过宿主停机期间所有到点窗口,记录数量,并在下一个计划窗口恢复。追赶工作是有界的,所以一台关了一个月的笔记本不会排出几千个 run。
560
+
561
+ 这些计数器故意分开:`missedRuns` 是从未运行的窗口数,`catchUpRuns` 是晚运行的次数,`skippedRuns` 是因为上一次 run 还活跃而被跳过的次数。`list` 会把三者都打印出来。
562
+
563
+ 计划也永远不会和自己重叠:新窗口到点时如果上一次执行还活跃,该窗口不会启动,并记录为
564
+ `skipped: previous run still active`。下一个窗口正常评估。
565
+
566
+ ### 完成必须有产物
567
+
568
+ worker 以 `completed` 结束自己的回合,本身并不等于子任务完成。当子任务声明了 `deliverables`(文件路径,相对于它的工作目录)时,列出的每个文件都必须存在、是文件、且非空,子任务才算数。没有声明文件时,回复文本就是产物,所以空回复或只有空白的回复会以
569
+ `empty deliverable: ...` 被拒绝,子任务像其他未完成的尝试一样重试或失败。报告被剥到什么都不剩的 run 会记录为
570
+ `partial`,永远不会是 `completed`,所以定时任务无法为空结果报告成功。
571
+
572
+ ### 配额与人工优先
573
+
574
+ 定时 run 与手动 run 共享 `maxActiveRuns`。设了
575
+ `human_priority: true`(默认值,也可用
576
+ `schedulerHumanPriority` 配置)时,定时 run 不能占用最后一个空闲位:只剩一个空位时它会等下一个 tick,而不是堵住一次
577
+ `superagent_start`。定时 run 也永远不进队列,所以人的
578
+ `superagent_start(..., queue: true)` 永远不会被定时器推后。配额满时,到点的窗口保持到点状态,在之后的 tick 重试,
579
+ 期间不花任何东西。
580
+
581
+ ### 预算与失败
582
+
583
+ `budget.max_model_calls` / `max_tokens` 限制单次执行;
584
+ `budget.max_total_model_calls` / `max_total_tokens` / `max_total_runs` 限制计划跨多次执行的总量。达到计划总量会暂停计划,并把原因记在计划和它的 run 报告里;达到单次 run 的上限则以手动 run 相同的方式结束那次执行。
585
+
586
+ 失败的执行不会在每次重试时都通知。第一次失败只报告一次,
587
+ `schedulerMaxConsecutiveFailures`(默认 3)次连续失败会暂停计划并只报告这一次。成功会重置计数。除此之外,通知仅限于:目标达成、预算到顶、或者某个 run 需要决策。里程碑和普通进展留在
588
+ `list` / `status` 里,永远不会叫醒会话。
589
+
590
+ ### Cron 支持
591
+
592
+ Cron 解析是内置的,没有依赖。支持:标准五个字段(分 时 日 月 星期)、`*`、`*/n`、范围
593
+ (`1-5`)、列表(`1,15,30`)、月份与星期名(`JAN`、`MON-FRI`),以及星期日写成 `0`
594
+ 或 `7`。日与星期同时出现时按经典 cron 的方式做 OR。
595
+
596
+ 不支持,并在创建时以出错的字段序号拒绝:秒、年份字段、`@daily` 之类的宏,以及 `L`、`W`、`#`、`?`
597
+ 扩展。六个字段的表达式会以"field 1 is not a minute"被拒,而不是被重新解释。时区用 IANA 名字,始终按表达式书写时所在的时区求值,绝不按宿主时区;春季 DST 跳变时不存在的时间被跳过,秋季二义的时间使用较早的那个偏移。
598
+
599
+ ### 计划对宿主的要求
600
+
601
+ 每个计划都属于创建它的会话(或显式的
602
+ `session_id`),而这个 owner 是**在每个窗口**解析的,不是只捕获一次。会话还活着就直接用。宿主重启后,插件请求宿主恢复持久化的会话(`agents.resume`,或在只有那个接口时用 Host Session API);如果会话被删除,它会创建一个替代者,计划采用新 id(记录为 `owner-recovered`)。因此计划能跨重启存活,而不依赖原进程或原对话保持打开。
603
+
604
+ 当宿主完全没有提供恢复或创建会话的途径时,这个限制在 `create` 时就记录下来,而不是事后以一次暂停的形式被发现。响应里带一条警告,计划标记为
605
+ `requires a resident session`;窗口发现没有活着的 owner 时记为 `blocked`,只通告一次,计划保持启用。它不会在三个窗口之后被悄悄暂停。
606
+
607
+ 在第一次 `create` 之前,不跑任何东西,也不写任何东西。没有任何计划的安装,行为与这个工具存在之前完全一样。
608
+
609
+ ## 进度、决策与产物
610
+
611
+ - **计划的诚实性。** worker 开始之前,planner 会点出它无法映射到具体对象的东西:含糊的措辞进 `ambiguities`,只有用户能回答的问题进 `needsInput`,于是 run 停下来问,而不是编一个看起来合理的名字。planner 确实做出的每个假设都记录在那个子任务上(`assumptions`)并打印在 status 和报告里,所以猜测是可见的而不是静默的。问题一起到达的计划是一个决策点,而不是一连串滴灌式的提示。
612
+ - **能力预检。** 子任务可以声明 `requires`(`shell`、
613
+ `net.http`、`browser`、`gui`、`desktop`、`git`、`gh`)。宿主会在 spawn 任何 worker 之前,把该列表与本会话实际拥有的工具比对。能力缺失的子任务是 `blocked`,会写明缺哪项能力、什么能启用它;它从不开始,也从不被算作成功,它下游的一切都因这个原因跳过。宿主无法列出自己的工具时,预检记录 `unavailable` 并不阻挡任何东西,而不是猜一份清单。
614
+ - **里程碑。** 每个 run 记录 `plan_ready`、`running`、`aggregating` 和
615
+ `settled` 及时间戳,显示在 `superagent_status` 里。它们从不产生主动消息;进展保持可见但不会变成噪音。
616
+ - **Attention。** worker 或 aggregator 可以追加一个围栏 `attention`
617
+ 块,提出一个只有用户能回答的问题。它从报告里剥掉,作为 `attention.items` 存在 run 上,在 status 里显示为 `needs your decision:`,并在 run 结束时领衔通知。每一项都从 run 上的计数器获得稳定 id(`q1`、`q2`、…),所以同一个问题在多次保存和 resume 之间含义不变。问题、选项和原因会折叠成一行,并分别限制在 500 / 200 / 300 字符,所以这个块无法注入伪造的状态行或通知行。不是合法 JSON 或没有问题的块会留在报告里,status 打印
618
+ `attention: <reason>` 而不是把请求藏起来。
619
+ - **回答。** `superagent_answer` 把决定记录在该项上,让 run 继续:活跃 run 把它带进下一个 prompt,终态 run 被重新打开以便带着答案重跑聚合。resume 让问题退役时,它是被归档而不是删除——这正是让迟到的答案能以 `expired at <time>` 被拒、而不是被挂到当前随便哪个问题上。
620
+ - **run 期间的指令。** 两个边界,保持区分。
621
+ `superagent_followup` 追加到对话日志,由下一个为 run 构建的 prompt 携带:每条指令在某个 prompt 第一次携带它时记录 `appliedAt` /
622
+ `appliedAtStage`,run 先落定时记录 `missedAt`。`superagent_inject` 则引导活着的子 agent 的收件箱,并在它的下一个 pre-step 被认领;回执记录从接受到那次认领的 `latencyMs`,或者在子 agent 先离开时记录 `missedReason`。Status 两者都打印,所以排队的指令和实时的指令永远不会混淆。
623
+ - **报告文件。** 终态 run 把报告写到
624
+ `<stateDir>/reports/<runId>.md`,用原子重命名,所以结果有一个可以打开或附加的路径。该目录带一个内容为 `*` 的 `.gitignore`,路径记录在 `run.artifacts` 里并显示在 status 中。
625
+ - **子任务之间的依赖。** planner 可以给子任务一个 id 和
626
+ `dependsOn` 列表;依赖方于是等待(`waiting`)而不是开始,它的 prompt 带上已完成的依赖方的报告。彼此独立的子任务仍然并行。未知引用是 `skipped` 并带原因,失败会跳过下游的一切而不是把它报成完成,成环则在任何子任务开始之前否掉计划。Status 和报告把等待与运行分开显示。
627
+
628
+ ## 权限与审计
629
+
630
+ run 周围有两层互相独立的东西。**策略**决定某个动作能否发生;**审计轨迹**记录决定了什么、随后发生了什么。轨迹默认开启,因为它只观察。策略在存在之前不改变任何东西,而且它只能把插件自发的行为收得更紧。
631
+
632
+ ### 策略
633
+
634
+ 把 [docs/policy.example.json](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/policy.example.json) 复制到
635
+ `<stateDir>/policy.json`,或用 `policyFile` 指定另一个文件。规则按这个顺序匹配:
636
+
637
+ 1. `paths.deny` / `commands.deny` 模式 -> `deny`(deny 永远优先);
638
+ 2. 显式的 `paths.allow` / `commands.allow` 条目 -> `allow`;
639
+ 3. `confirm.actions` 里列出的动作类型 -> `confirm`;
640
+ 4. run 的 `runs.<id>.level`,否则 `defaultLevel`。
641
+
642
+ 压过 `confirm` 或按 run 的 `deny` 的 allow 条目会带
643
+ `meta.relaxedFrom` 记录,所以人总能看出策略在哪里被放宽了。相对路径模式在任意目录边界匹配(`src/**` 覆盖
644
+ `/anywhere/repo/src/a.js`),但不匹配只是结尾相同的兄弟路径(`xsrc/a.js`)。不带 `*` 的命令条目是按整 token 的前缀
645
+ (`git status` 允许 `git status --short`,不允许 `git statusx`);复合行
646
+ (`git status && curl ...`)永远不能被前缀提升到 `confirm` 之上。
647
+
648
+ `policy.json` 可以包含 `//`、`#` 和 `/* */` 注释。模式问题会带着文件、行、列报告:
649
+
650
+ ```
651
+ policy.json: 1 problem in the permission policy
652
+ policy.json:3:19 [defaultLevel] must be one of allow | confirm | deny
653
+ "defaultLevel": "maybe",
654
+ ^
655
+ ```
656
+
657
+ 不可读或无效的策略**失败关闭**:受管辖的动作被拒绝,`superagent_audit` 打印问题。被拒绝的 start 或 resume 在任何状态改变之前就被拒;被 `confirm` 拦下的那个需要在下一次调用时带
658
+ `approve_policy: true`,该批准会写成一条
659
+ `approved` 事件,点名被拦下的事件。批准不能解除 `deny`。
660
+
661
+ ### 审计
662
+
663
+ `<stateDir>/audit/audit.jsonl`,每个事件一个 JSON 对象:
664
+
665
+ ```json
666
+ {"v":1,"id":"evt_...","at":"2026-11-15T10:04:11.238Z","runId":"20261115T100400-ab12cd34","subtaskId":"subtask-2","actor":"session:9f3c","kind":"path.write","action":"path.write","target":"C:/work/app/src/db.js","decision":"allow","result":"ok","durationMs":4,"rule":"paths.allow[0]","source":"policy","meta":{"relaxedFrom":"confirm","reason":"..."}}
667
+ ```
668
+
669
+ 每个事件都带 run、子任务、actor、时间戳、判定、
670
+ 结果,以及检查耗时。更高层可能再加 `tool.call` 和
671
+ `command.exec` 事件。由插件自己触发的是:`run.start`、`run.resume`、
672
+ `run.cancel`、`run.finish`、`attention`,以及策略拒绝时的 `blocked`、人释放被拦动作时的
673
+ `approved`。
674
+
675
+ 进程内的追加是串行的,跨进程由一个 `wx` 锁文件守护,每个事件一次追加写完,所以两个同时结束的 worker 不会把行拼在一起。崩溃留下的尾部碎片会报为
676
+ `torn` 并跳过;损坏的行计为 `invalid`,不会掩盖其余部分。
677
+
678
+ `superagent_audit` 可按 run、子任务、kind、decision、result、目标文本和时间窗读取。用 `format: "jsonl"` 或 `format: "csv"` 时,它写出一个可交付文件(默认
679
+ `<stateDir>/audit/audit-export-<time>.<ext>`)并返回路径。
680
+
681
+ 路径/命令护栏可以挂上去,而不需要审计层知道它的规则:
682
+ `createAuditor({ dir, policyFile }).attachGuard(request => ({ decision, reason }))`。
683
+ 护栏只能把策略产生的判定收得更紧;抛异常的护栏被视为阻断。返回 `{ blocked, rule, reason }`——也就是工具调用护栏本来就产出的形状——的护栏同样能被理解。
684
+
685
+ ## 跨运行记忆
686
+
687
+ run 是故意隔离的:planner 和 worker 都从空白开始。没有笔记本,每个 run 都会重复上一个已经做完的工作,并重新踩一遍同样的坑。插件保存两类不同的东西,而其中只有一类被存下来:
688
+
689
+ 1. **发生过什么** 在规划时从 run 存储推导。最近六次 run 各渲染成一行(日期、状态、完成的
690
+ 子任务数、goal、run id)。没有任何东西被复制,所以它不可能和 run
691
+ 记录漂移。
692
+ 2. **学到了什么** 是一个小的、经过整理的笔记本:决策、坑、下一步,以及哪些工作被委派出去了。aggregator 把它放在一个围栏 `memory` 块里返回,这个块在用户看到之前就从报告里移除。没有产出块的 run 什么都不写;插件从不凭空造笔记。
693
+
694
+ **存储。** `<stateDir>/memory/<scope>.jsonl`,一行一个 JSON 对象。一行的结构是
695
+ `{v,id,ts,key,kind,text,runId,status}`;`key` 是一个短 slug(`deploy-target`),
696
+ `kind` 是 `decision`、`pitfall`、`next`、`dispatch` 或 `note`。该目录包含一个内容为 `*` 的 `.gitignore`,所以即便 `stateDir` 指向仓库内部,笔记本也不会被提交。它也从不进入包的 `files`
697
+ 白名单,所以永远不会发布到 npm。
698
+
699
+ **什么时候写。** 每个 run 一次,在落定时,且只对报告里带块的终态 run。把同一个 run 再次落定的 resume 是一次 no-op,
700
+ 因为存储记录了写入的 run id。写入失败记录在 run 上(`memoryWrite.reason`),从不让 run 失败。
701
+
702
+ **什么时候读。** 在规划之前,`superagent_start` 时读一次(`superagent_resume` 时再读一次,因为 aggregator 会再跑)。组合出的上下文作为 `memory.digest` 存在 run 上,注入 planner 和 aggregator
703
+ 的 prompt,并在 `superagent_status` 里摘要显示。
704
+
705
+ **分层。** 按顺序读三个 scope:`rules`(项目规则)、`profile`
706
+ (用户偏好),然后 `memoryScope`(更早的 run 学到的东西)。前两个用
707
+ `superagent_memory` 整理,永远不由 run 写入,所以一条规则不会被模型的观察覆盖。每一层在 prompt 里都有标注,并各自设界;run 上的 `memory.scopes` 列出读了哪些。
708
+
709
+ **体量。** 每条笔记在脱敏之后上限 400 字符。一个 prompt 最多看到
710
+ `memoryDigestEntries` 条笔记、总计 `memoryDigestChars` 字符以内,再加六条
711
+ 一行的 run 摘要,整体硬上限 2600 字符。当一次写入会把文件推过 `memoryMaxEntries` 条笔记、400 行
712
+ 或 128 KB 时,文件被压缩;压缩保留最新的 `memoryMaxEntries` 条笔记。
713
+ 上下文不会随 run 数量增长。
714
+
715
+ **并发。** 进程内,对同一 scope 的写入是串行的。跨进程,每一批作为一次小 `write` 追加(不对整个文件做读-改-写),压缩拿锁文件并从临时文件替换,被杀死进程留下的截断末行会被跳过。两个同时结束的 run 不会覆盖彼此的笔记;行的顺序可能不同,但合并依据时间戳,绝不依据位置。
716
+
717
+ **搜索。** `superagent_memory` 的 `action: "search"` 按 `query`
718
+ 关键词和精确 `tags` 给笔记排序,而不是只返回最新的那些;planner 的摘要也用同一套排序针对 run 的 goal。所以几周前一条相关的笔记在匹配时仍能进入 prompt,而不相关的笔记不会挤占预算。笔记在设置时可以携带 `tags`。
719
+
720
+ **更正。** 同一 key 的更新笔记取代旧的。显式 `forget` 写一条墓碑。早于 `memoryMaxAgeDays` 的笔记不再被注入,并在下一次压缩时丢弃。每条笔记都显示年龄,摘要也会告诉模型这些笔记可能过期、必须核实,所以一个错误结论可以被后续的 run 推翻,而不是变成永久的偏见。
721
+
722
+ **隐私。** 默认情况下笔记写在仓库之外
723
+ (`$DSH_HOME/state/superagent/memory`)。存储之前,插件会脱敏 API key 形状(`sk-…`、`Bearer …`、`ghp_…`、`AKIA…`)、长的 hex/base64 串、邮箱
724
+ 地址,以及绝对家目录路径;它把笔记压成一行并设上限。
725
+ aggregator 被指示不要记录密钥、客户数据或报告本身。`stateDir` 落在已安装包内时会禁用记忆,而不是冒把它发布出去的风险。如果你把 `stateDir` 指向仓库,嵌套的
726
+ `.gitignore` 仍然会让这些文件躲开默认的 `git add`。
727
+
728
+ ### 用户画像
729
+
730
+ 上面的笔记本回答的是"上一个 run 对这个任务学到了什么"。第二个可选的存储回答另一个问题——"这个人是谁、他想要什么、我们之前为什么那样选"——而且它必须比不相关的任务活得更久,所以它单独存放、单独读取。默认关闭
731
+ (`memoryUserProfile: false`):不构建任何东西、不创建目录,
732
+ run 笔记本的行为与之前完全一致。
733
+
734
+ - **三类,三个文件。** `fact`(持久的技术背景,例如技术栈或环境)、`preference`(用户希望工作怎么做)、
735
+ 以及 `decision`(选了什么、否决了什么、为什么、以及怎么撤销)。
736
+ 一次搜索只打开一个类别的文件,所以一条事实不会仅仅因为词对得上就被当成偏好返回。
737
+ - **决策必须带理由。** 没有理由的决策教不会下一个 run 任何东西,所以理由既是记录的一部分,也是每条摘要
738
+ 行的一部分;光秃秃的"选了 X"会被拒绝。
739
+ - **读写。** 带 `layer: "user"` 和
740
+ `category` 的 `superagent_memory` 可以列出、搜索、添加、更正或遗忘画像记录。planner 的 prompt 会拿到匹配记录的短摘要,按
741
+ 类别标注,字符预算与笔记本相同。
742
+ - **遗忘就是删除。** 匹配的行在锁下被移除,文件被替换,不留墓碑,所以后续搜索不可能把值泄漏回来。遗忘必须点名 key、run id 或时间范围,所以光秃秃的"全部忘掉"不会误清整个画像。
743
+ - **隐私。** 每条记录在写入前都会脱敏:凭据、
744
+ 邮箱、电话号码,以及家目录路径里的用户名。画像位于
745
+ `<stateDir>/user-memory`,带与笔记本相同的嵌套 `.gitignore`,
746
+ 并且永远不在包的 `files` 白名单里。
747
+
748
+ ## 观察与报告
749
+
750
+ ![run 报告预览](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-preview.jpg?raw=true)
751
+
752
+ _一份由 40 次真实宿主 run 渲染出来的报告顶部。完整页面——时间线、
753
+ 泳道图、调用与花费曲线、失败标注、run 表——在
754
+ [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)。_
755
+
756
+ 包里带五个运维工具,不需要会话,也不增加运行时依赖。`watch`、`report`、`archive` 和 `sync`
757
+ 读的是与工具相同的持久 run 文件;`doctor` 检查安装本身。
758
+
759
+ 从 profile 里已安装的那份副本运行:
760
+
761
+ ```bash
762
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
763
+ node "$PKG/bin/watch.js" # live panel, Ctrl-C to stop
764
+ node "$PKG/bin/report.js" --out report.html # self-contained HTML page
765
+ ```
766
+
767
+ 如果 profile 的链接器创建了 bin 链接(npm 会),同样的命令是
768
+ `node_modules/.bin/dsh-superagent-watch`、`node_modules/.bin/dsh-superagent-report`、
769
+ 以及 `node_modules/.bin/dsh-superagent-doctor`。
770
+
771
+ `watch`、`report` 和 `archive` 都接受 `--state-dir <path>`;默认是
772
+ `$DSH_HOME/state/superagent`。当插件配置设置了自定义
773
+ `stateDir` 时要传它。
774
+
775
+ **`watch`** 在备用屏幕上为每个 run 画一行——id、状态、已用调用数对上限、已耗时、此刻在做什么,以及父会话——并在 Ctrl-C、SIGTERM 或管道关闭时恢复光标。状态变化立即重绘;空闲面板每秒只读一个小文件。同一时刻活着的 run 共享编号边栏,所以并行工作看起来是一组,而不是互不相关的行。等待中的行先显示占着空位的那个 run,再显示队列位置,因为窄单元格从右边截断,而占位者才是可操作的信息。`--once` 打印单帧纯文本,
776
+ [docs/e2e/transcripts/watch-panel.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/watch-panel.log) 捕获的就是这个,来自 40 次真实 run。
777
+
778
+ **`report`** 把记录下来的 run 渲染成一个 HTML 文件:内联 CSS、内联 SVG、
779
+ 不含脚本、字体、图片,也不联网。它有时间线(每个 run 的开始、结束,以及推导出的规划/执行/合并阶段);泳道图,泳道数等于峰值并发;累计模型调用与花费曲线;明确的失败、取消、中断标注;以及一张 run 表。每个
780
+ worker 的重试链和它占 run 墙钟的比例列在结果旁边,所以一个昂贵而飘忽的子任务能被看见,而不只是它最终的失败。
781
+ [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)
782
+ 是宿主 e2e 的 40-run 报告——直接打开即可,不请求任何东西——
783
+ 而
784
+ [docs/e2e/transcripts/report-cli.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/report-cli.log)
785
+ 记录了命令本身,以及一次零外部引用的审计。
786
+
787
+ **`doctor`** 在宿主之前回答"装是装上了,为什么什么都不工作?"。它只读:不安装、不挂载、不修改 profile。每项检查一个块——导入的文件对 `files` 白名单、声明的文件对磁盘实况、已安装副本对同版本已发布的 tarball、profile 的 bundle 注册,以及注册的十二个工具——每个失败后面跟着能修好它的命令。
788
+
789
+ ```bash
790
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
791
+ node "$PKG/bin/doctor.js" --profile web
792
+ node "$PKG/bin/doctor.js" --profile web --offline # skip the registry hash check
793
+ ```
794
+
795
+ 没有检查失败时退出码是 `0`,有一项失败是 `1`,所以它能用来给部署设闸。`npm test` 跑的打包防护与
796
+ [`scripts/check-pack.mjs`](scripts/check-pack.mjs) 相同:从入口点可达的每个文件都必须出现在 `npm pack --dry-run` 里,而这正是 0.9.x 版本缺的那项检查。
797
+
798
+ 这些工具都不是安装路径:插件用 `dsh plugin add` 安装,绝不用 `npm i -g`。
799
+
800
+ **`archive`** 是第四个工具。它清理终态 run,并把一个 run 导出或导入成一个自包含的归档;见[保留策略](#保留策略)和
801
+ [归档](#归档)。
802
+ ## 在多台机器间同步同一个状态目录
803
+
804
+ 没有服务器,也没有账号。状态目录就是一堆文件,所以一个 git remote 就能承载它:`dsh-superagent-sync` 把那个目录变成仓库,把机器本地文件排除在外,并提供 `pull`、`push` 和
805
+ `status`。唯一的要求是 `git`——这个命令本身没有依赖。
806
+
807
+ ```bash
808
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
809
+ node "$PKG/bin/sync.js" init git@github.com:me/superagent-state.git # once per machine
810
+ node "$PKG/bin/sync.js" push # after runs finish
811
+ node "$PKG/bin/sync.js" pull # before starting work
812
+ node "$PKG/bin/sync.js" status
813
+ ```
814
+
815
+ 或者用 `node_modules/.bin/dsh-superagent-sync`。四个子命令都接受 `--state-dir
816
+ <path>`(默认 `$DSH_HOME/state/superagent`),`--json` 打印原始结果。
817
+
818
+ **`init <remote>`** 创建仓库,往
819
+ `.gitignore` 写入一个受管块,设置 `origin`,并做第一次提交。重复执行会刷新远端 URL 和那个块,不会碰你自己加的条目。没有 `~/.gitconfig` 的机器会得到一个仓库本地的提交身份,所以第一次提交不会仅因为这个失败。
820
+
821
+ **`pull`** 获取 `origin`,然后合并。未提交的本地改动会先被 stash
822
+ (`stash@{0}`,主题 `dsh-sync auto-stash …`)并在合并后重新应用,所以 pull 绝不会悄悄覆盖一次编辑。冲突会让合并停下,两侧内容都还在文件里:路径被打印出来,不做任何取舍,stash 保持未应用并有一行说明。
823
+
824
+ **`push`** 提交所有东西并推送当前分支,首次推送时设置 upstream。被拒的 push 会被报告,不强制、也不自动合并:先 `pull`,解决它报告的问题,再 push。
825
+
826
+ **`status`** 打印 ahead/behind 计数、未提交文件、stash,以及等待决定的冲突路径。
827
+
828
+ ### 什么东西不会离开本机
829
+
830
+ `.owner`、`control.json`(一个 bearer token)、`notifications.json`、`*.lock`、
831
+ `*.cancel`、`*.corrupt-*`、`*.tmp`、`*.log`,以及 `.env` / key 材料。笔记本是唯一值得知道的例外:`memory/.gitignore` 通常是一个光秃秃的 `*`,那会让每条笔记都留在本地,所以 `init` 会把这一处默认值改写成允许 `<scope>.jsonl`。你自定义过的文件不会被改动。
832
+
833
+ ### 发生冲突时
834
+
835
+ run 记录是一个 run 一个文件(`runs/<runId>.json`),所以两台机器上普通的并发工作——不同的 run——永远不会碰到同一个路径。冲突需要以下之一:
836
+
837
+ - 同一个 run id 在两台机器上都被写:在 pull 第一台机器的状态之前,就在第二台上 resume 或 cancel 了它;
838
+ - 同一个记忆 scope 在两台机器上都被追加(`memory/<scope>.jsonl` 是
839
+ 只追加的,两条不同的尾部会碰撞);
840
+ - 同一个 `reports/<runId>.md` 被用不同内容重新生成;
841
+ - `.gitignore` 在两台机器上都被手工改过。
842
+
843
+ run 文件里只要还有冲突标记就不是合法 JSON,插件会在挂载时把它隔离为 `<runId>.json.corrupt-<ts>`。启动宿主之前先解决它:留下你要的那一侧,`git add`,`git commit`。
844
+
845
+ ### 为什么说这是近似的
846
+
847
+ - 两台机器在同一时刻写入会冲突。合并停下,由你决定;不会有任何东西在你背后被合并。
848
+ - 没有实时同步,也没有跨机器锁。一台机器只有 `pull` 之后才看到另一台机器的 run,而 `push` 不知道另一台此刻在做什么。同一时间只让一个宿主使用一个状态目录。
849
+ - key 不分发:每台机器仍然需要自己的模型凭据。
850
+ - `keepRuns` 清理会删文件,而删除要等到下一次 `pull` 才到达另一台机器。
851
+
852
+ ## 通过本地 HTTP 嵌入
853
+
854
+ 工具需要一个会话。如果另一个 UI 或脚本要在不导入本包的情况下启动并观察 run,就设置 `controlPort`:
855
+
856
+ ```yaml
857
+ - id: superagent
858
+ config:
859
+ controlPort: 0 # off by default; 0 = OS picks a free loopback port
860
+ ```
861
+
862
+ 插件随后写出 `<stateDir>/control.json`,含绑定的 URL 和每进程一个的 bearer token(权限 `0600`),并只在 `127.0.0.1` 上提供 `GET /`、`GET /health`、
863
+ `GET /runs`、`GET /runs/:id`、`POST /runs`、`POST /runs/:id/cancel` 和
864
+ `POST /runs/:id/resume`。每个回复都带与该工具会打印的相同文本
865
+ (路由索引和 `/health` 是两个例外:
866
+ 它们描述的是 socket,不是 run)。每个 run 都走与工具启动的 run 相同的配额、
867
+ 预算、锁和恢复流程。`POST /runs` 要求 `session_id` 是该宿主中活着的会话——run 需要一个真实的父
868
+ agent 来带它的子 agent。
869
+
870
+ ```bash
871
+ STATE="${DSH_HOME:-$HOME/.dsh}/state/superagent"
872
+ URL=$(node -e "console.log(require('$STATE/control.json').url)")
873
+ TOKEN=$(node -e "console.log(require('$STATE/control.json').token)")
874
+ curl -s -H "Authorization: Bearer $TOKEN" "$URL/runs"
875
+ ```
876
+
877
+ 完整契约——路由、错误 id、安全模型、生命周期、客户端
878
+ 示例——在 [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md)。它是可选开启的、只走回环,
879
+ 没有远程模式,也没有免认证模式。
880
+
881
+ ## 对话控制台
882
+
883
+ `consolePort` 增加一个本地页面,让你和**真实的 Host Session** 对话,而不是一个假聊天,也不是一个换了皮的 `superagent_start(goal)` 表单:
884
+
885
+ ```yaml
886
+ - id: superagent
887
+ config:
888
+ consolePort: 0 # off by default; 0 = OS picks a free loopback port
889
+ consoleRoot: /path/to/project
890
+ ```
891
+
892
+ 插件用宿主的 `sessionController.create()` 创建会话,用 `prompt({ mode: 'queue' | 'steer' })` 发送每条消息,并把
893
+ `follow({ assistantStream: true })` 加 `observeState()` 转发给页面。所以后续消息是在继续同一个对话;它们不是新会话。
894
+ 右栏列出 `parentSessionId` 为该会话的 run,所以页面显示的就是这个对话派生出的那些子任务。attention 卡片
895
+ 通过 `orchestrator.answer` 作答,与
896
+ `superagent_answer` 工具走同一条路径,run owner 就是对话 agent。
897
+
898
+ 绑定的 URL 和每进程新生成的 token 写到
899
+ `<stateDir>/console.json`(权限 `0600`)。打开
900
+ `http://127.0.0.1:<port>/?token=<token>` 一次;页面把 token 存进
901
+ `sessionStorage` 并从地址栏移除。没有它,每个路由(包括
902
+ 事件流)都返回 `401`,而每个带非回环
903
+ `Host` 头的请求返回 `403`。
904
+
905
+ 如果宿主没有挂载 `sessionController`(例如没有 web session API 的无头 profile),页面会说明这一点并拒绝创建会话。它**不会**假装成一个聊天。控制台在一个进程里也只保留一个活跃
906
+ 对话;"新对话"会创建一个新的 Host Session,旧的保持原样。以宿主 `pendingInput` 形式出现的审批提示会显示在
907
+ 状态行里,但不会由这个页面回答;只有 run 的 attention 问题会被回答。
908
+
909
+ ### 这个对话能用的工具
910
+
911
+ 控制台会话创建时没有自己的工具列表:它挂载宿主 agent preset 挂载的那些,与 Web 应用自己的
912
+ 会话拿到的是同一组。插件不注册对话工具,也不过滤;它唯一能施加的过滤是给子 agent 调用的可选 `guard`。要看真实的列表,页面向宿主请求 `ctx.tools.definitions(agent)`,并显示在"这个会话挂载的工具"下;宿主无法枚举时,页面会说明,而不是打印一个固定列表。想要 profile
913
+ 默认之外的 preset 时,`consolePreset` 会把 `agentPreset` 传给
914
+ `sessionController.create()`。
915
+
916
+ 浏览器与桌面控制不在这里实现。它们来自
917
+ `feat/runtime-control`,那个分支注册宿主级的 `browser_*` 和 `desktop_*`
918
+ 工具;这些工具像其他宿主工具一样对控制台会话可见。在没有那个分支的构建上,页面把它们报成"未挂载"。两个分支都不带 3D 工具;当
919
+ preset 里有 `bash` 或 `pwsh` 时,无头 Blender 可以通过它驱动
920
+ (`blender --background --python`),这是控制台本来就能触达的脚本化路径。
921
+
922
+ ## 工作区面板
923
+
924
+ `workbenchPort` 在一个目录上增加一个本地的、IDE 形状的面板。它有自己的文件树、编辑器、diff 预览和 run 改动视图;任何东西都不经过宿主代理。
925
+
926
+ ```bash
927
+ npx dsh-superagent-workbench --root /path/to/project --port 8787
928
+ ```
929
+
930
+ 同一个服务器也可以跑在宿主内部,Runs 视图接到插件的
931
+ 状态目录:
932
+
933
+ ```yaml
934
+ - id: superagent
935
+ config:
936
+ workbenchPort: 0 # off by default; 0 = OS picks a free loopback port
937
+ workbenchRoot: /path/to/project
938
+ ```
939
+
940
+ 独立命令提供同一个页面,其 run 状态默认是
941
+ `<root>/.dsh-workbench`;传 `--state-dir <plugin state directory>` 可以读已有的 run。两种形式都不会在你要求之前打开 socket。
942
+
943
+ 绑定的 URL 和每进程新生成的 token 写到
944
+ `<stateDir>/workbench.json`(权限 `0600`)。打开 `http://127.0.0.1:<port>/?token=<token>`
945
+ 一次;页面把 token 存进 `sessionStorage` 并从
946
+ 地址栏去掉。没有 token 时每个路由都返回 `401`。
947
+
948
+ 面板可以列出、读取和编辑 `workbenchRoot` 下的普通文本文件。它
949
+ 拒绝绝对路径、`..` 穿越、指向根之外的符号链接、插件
950
+ 状态目录、二进制文件,以及大于 512 KB 的文件。保存时发送编辑器读到的哈希和
951
+ mtime;如果磁盘上任一已变,保存会以
952
+ `external-change` 被拒,而不是覆盖另一个进程的工作。保存确认之前,页面显示统一 diff。
953
+
954
+ `workbenchPort` 打开时,插件把每次 run 改动的文件记录进
955
+ 该 run 的 JSON 记录(`run.changes`),这样 Runs 视图之后可以显示这些文件及其
956
+ 针对 `git HEAD` 的 diff。
957
+
958
+ ## 状态与恢复
959
+
960
+ 一个 run 一个文件:`$DSH_HOME/state/superagent/runs/<runId>.json`,用
961
+ 临时文件加重命名写出,所以保存过程中被 kill 也不会留下半写的 run。
962
+ 状态有:`queued`、`planning`、`running`、`aggregating`、`completed`、
963
+ `partial`、`failed`、`cancelled`、`interrupted`。正在等空位的 run 状态也是 `queued`,但带 `queue.waiting: true` 和它在队列里的
964
+ 位置;它不是活跃的,不计入 `maxActiveRuns`。
965
+
966
+ 挂载时,插件**只在 run 没有活着的 owner**(见下文)时把它标成 `interrupted`,并把在飞的子任务重置为 `pending`。
967
+ `superagent_resume` 随后只重跑没完成的部分。planner 的计划被复用,所以 resume 的 run 不会为规划付两次钱。
968
+
969
+ 一个状态目录可以被两个 profile 或两台机器共享。因此恢复从不只凭本进程的内存做决定:owner 还活着的 run——心跳新鲜、本地 pid 活着、或有活进程持有它的
970
+ 锁——保持不动,cancel 标记也一样。两个进程重写同一个
971
+ run 会让还活着的子 agent 继续花钱,而文件却说
972
+ `interrupted`,之后一次 resume 会把同样的子任务跑两遍。
973
+
974
+ resume 的独占性也是同一个原因。`superagent_resume` 拿与 `superagent_start` 相同的
975
+ 串行闸,占用 `<runId>.lock`(原子创建),
976
+ 拒绝还有活着 owner 的 run,也拒绝不是
977
+ `parentSessionId` 中那个会话的调用者。它不计入 `maxActiveRuns`:resume 是在把已经存在的活儿干完,所以配额满了也永远不会挡住它。`force`
978
+ (工具)或 `force` / `override_quota`(HTTP)仍然为兼容而接受,
979
+ 但不改变任何东西。
980
+
981
+ run 旁边还有三个附属文件:
982
+
983
+ | 文件 | 含义 |
984
+ | --- | --- |
985
+ | `<runId>.cancel` | 某个进程请求了取消。owner 每秒轮询一次并停掉它的子 agent。run 结束时移除。 |
986
+ | `<runId>.lock` | 允许调度这个 run 的进程。用 `wx` 创建,所以恰好一个进程胜出。本地已死 pid 留下的锁立即破除;活着的本地 pid 无论持有多久都保留;来自另一台机器的锁超过 10 分钟后破除,因为它的 pid 无法检查。 |
987
+ | `<runId>.json.corrupt-<ts>` | 状态文件不是合法 JSON,被移到一边而不是删除。`superagent_list` 跳过该 run,并按 id 连同这个路径报告。 |
988
+ | `<anchor>/.superagent/worktrees/<runId>/w<n>/` | `workspaceIsolation` 打开时某个 worker 的 git worktree。锚定在宿主的会话目录内(宿主就是在仓库里启动时就是仓库),好让沙箱允许写入,并被忽略所以从不出现在 `git status` 里。分支合并完成或没产生改动后移除;冲突留给用户合并时保留。 |
989
+
990
+ run 的文件损坏时,其他东西不会跟着坏:其他 run 正常列出,启动新 run 也照常工作。检查 `.corrupt-` 文件,然后删掉它。完全读不出来的文件(权限、打开文件过多、磁盘满)会如实报告,而不是显示成一个未知的 run。
991
+
992
+ ### 孤儿运行与活跃运行配额
993
+
994
+ 一个 run 在其状态是活跃期间计入 `maxActiveRuns`。如果拥有它的进程没有重启就消失了,这个 run 否则会永远占着那个空位。每次配额检查之前,插件都会寻找这类 run 并回收,规则有两种:
995
+
996
+ - **状态目录属于本机**(`.owner` 里是我们的主机名):
997
+ 本地已死的 pid 本身就够了——那是进程没了的直接证据,所以下一次挂载会立即回收,不管心跳。活着的 pid 能否决回收,即便心跳陈旧,因为一个卡住的进程仍可能恢复。
998
+ - **目录是共享的,或它的 owner 未知**:pid 可能属于另一台机器,所以忽略它,只由心跳决定;心跳超过 90 秒后 run 被回收。网络共享或同步文件夹上的状态目录就属于这种情况。
999
+
1000
+ 两种情况下,活着的本地进程持有的锁也能否否决回收,挂载时恢复用的是完全相同的规则——只要还有任何人可能在干活,run 就绝不会被重写。
1001
+
1002
+ 回收从不静默:run 变成 `interrupted`,它的 `reclaimed`
1003
+ 字段记录确切依据(`pid 1234 is not running and its heartbeat
1004
+ stopped at ...`,或 `the state directory is shared with <host> ...`),原因由 `superagent_status` 打印,另有一行进宿主日志。在飞的子任务变成 `pending`,所以 `superagent_resume` 能继续这个 run。
1005
+
1006
+ 心跳由拥有进程每 30 秒刷新一次,所以健康的
1007
+ run 永远不会被误认成孤儿。
1008
+
1009
+ ### 与用户对话
1010
+
1011
+ 除非用户必须知道什么,插件是安静的。这是代码里的规则,不只是这份文档里的规则:
1012
+
1013
+ - **允许打断:** run 结束并交付了结果、run 失败、或者 run 半途停下(`partial`、`interrupted`)。用户自己取消的 run 从不通告——调用方已经知道了。
1014
+ - **从不推送:** 进展、子任务开始/结束、重试,以及记忆写入。
1015
+ 它们留在 run 记录、`superagent_status`、watch 面板和报告页里;用户可以去看,但不会有东西弹出来。
1016
+ - **先自愈:** 每个子任务有 `attempts` 次尝试,看起来是暂时性的失败(配额、限流、超时、5xx)还会多 `autoResumeRounds` 轮,可选地在
1017
+ `childModelFallback` 上跑。只有仍然失败的东西才被报告,消息里会说明试过什么。
1018
+ - **噪音有界:** 每小时最多 `maxNotificationsPerHour` 条主动消息。超出上限的 run 被缓冲,并折叠进下一条消息作为一个摘要;`superagent_list` 显示有多少在等。如果承载折叠批次的消息投递失败,批次留在缓冲区搭下一条;只有连续三次投递失败后才丢弃。
1019
+ - **不要问已经知道的事:** planner 和 aggregator 拿到笔记本,并被要求用它,而不是拿它已经持有的事实去问用户。
1020
+
1021
+ `notifyOnComplete` 是总开关。有两种情况本来就会报告而不是通知:
1022
+
1023
+ - 同一宿主进程里的调用方正在 `superagent_status` 里,会自己收到终态报告(不发消息,避免重复噪音)。在*另一个*进程里的轮询者不会抑制消息:它可能在 run 结束前一刻超时,那样唯一的通知就丢了;
1024
+ - 拥有该 run 的会话已经没了(关掉了无头用户的会话):run 记录 `notify.delivered = false` 及原因,`superagent_status` 打印
1025
+ `notify: not delivered — ...`,`superagent_list` 把该行标成
1026
+ `(result not delivered to the session)`。报告始终可以用 `superagent_status` 读。
1027
+
1028
+ 唤醒会话是有界的(15 s),并且心跳会一直跑到终态写入为止,所以慢唤醒不会让另一个进程把活着的 run 当成孤儿。
1029
+
1030
+ ### 保留策略
1031
+
1032
+ 默认什么都不删。把 `keepRuns` 设成天数,挂载时删除早于该天数的终态 run;活跃 run 从不动,被删的 id 会记日志,对应的 `reports/<runId>.md` 产物随 run 一起删除。`superagent_list` 打印当前文件数和大小,
1033
+ 所以增长在变成问题之前就能看见。
1034
+
1035
+ 要按需清理,`dsh-superagent-archive prune` 先规划、再删除:
1036
+
1037
+ ```bash
1038
+ node "$PKG/bin/archive.js" prune --older-than 30 # dry run
1039
+ node "$PKG/bin/archive.js" prune --older-than 30 --status failed # dry run, one status
1040
+ node "$PKG/bin/archive.js" prune --older-than 30 --confirm # delete
1041
+ ```
1042
+
1043
+ 规划会打印每个 run 的 id、状态、结束时间和它占的字节数;摘要给出 run、文件、字节的合计。不带 `--confirm` 不删任何东西。只有终态 run(`completed`、`partial`、`failed`、`cancelled`、
1044
+ `interrupted`)才可能成为候选:还在活跃的 run,或 `.lock` 被另一个进程持有的 run,被列为跳过并保持原样。窗口之内的 run、没有可解析时间戳的 run,以及被隔离的
1045
+ `*.corrupt-*` 文件也同样保留。
1046
+
1047
+ ## 归档
1048
+
1049
+ `archive export` 把一个 run 变成别人可以离线打开的凭据——
1050
+ 不需要宿主、插件或网络:
1051
+
1052
+ ```bash
1053
+ node "$PKG/bin/archive.js" export <run-id> --out ./run-archive # directory
1054
+ node "$PKG/bin/archive.js" export <run-id> --out ./run.html --format html # one page
1055
+ node "$PKG/bin/archive.js" export <run-id> --out ./run.json --format bundle
1056
+ ```
1057
+
1058
+ 目录里有 `README.md`(摘要、合并报告、子任务表、文件索引)、`report.md`(markdown 形式的报告)、`run.json`(完整的持久记录)、`subtasks/`(每个子任务一个 markdown 页面和一个 JSON 文件)、`guards.json` / `guards.md`(worker 或 aggregator 停下的每一个决定)、`usage.json`(每个子 agent 的 token 合计,加上运维定价产生的花费)、以及 `manifest.json`(归档元数据、大小,以及每个文件的
1059
+ SHA-256)。`--format html` 把同样的内容写成一个自包含
1060
+ 页面,包体嵌入其中;`--format bundle` 只写那个 JSON。
1061
+
1062
+ `archive import <path>` 把三种形式中的任意一种读回本地存储以便
1063
+ 查看,恢复 run 记录和它的报告产物。它从不覆盖:本地已有同 id 的 run 时,命令在写任何东西之前就失败并
1064
+ 说明。导入的 run 是终态的,所以它可列出、可读,但永远不会被 resume。
1065
+
1066
+ ## 从另一个进程取消
1067
+
1068
+ 即使 run 是由另一个宿主进程启动的(web 与无头并存,或另一个终端),`superagent_cancel` 也能工作。交汇点是 `.cancel` 标记文件,不是共享内存:
1069
+
1070
+ 1. 调用方写 `<runId>.cancel`;
1071
+ 2. 拥有进程在一秒内察觉,abort 子 agent 的 signal,
1072
+ 释放它们的 activation,并写 `cancelled`;
1073
+ 3. 调用方最多等 5 秒,然后报告实际发生了什么。
1074
+
1075
+ 如果 owner 没有及时应答,回复说
1076
+ `cancel requested ... not confirmed`,而不是 `cancelled`。那意味着拥有进程没了或卡住了;标记留在磁盘上,下一次挂载会在恢复时把 run 转成 `cancelled`。整个过程不涉及 socket、管道或 Windows
1077
+ 命名管道,所以在每个平台上、跨共享状态目录,行为都一样。
1078
+
1079
+ 在真实宿主上实测:两个 worker 睡在一个无视 abort 的模型调用里,
1080
+ `superagent_cancel` 在 **1.99 s** 内返回 `cancelled`,状态文件从那一刻起不再接受新的 spawn。*宿主进程*仍然花了 22.8 s 才退出,因为它在等自己的子会话;那段等待是宿主的收尾,不在插件控制之内。在交互式
1081
+ 会话里你根本注意不到;在一次性的无头回合里,这就是为什么 cancel 看起来会"卡住",直到那个无视 abort 的子 agent 返回。
1082
+
1083
+ ## 故障排查
1084
+
1085
+ | 你看到的 | 含义 | 怎么办 |
1086
+ | --- | --- | --- |
1087
+ | `superagent_*` 工具不存在 | bundle 行没挂上,或者宿主拒绝加载插件。 | 跑 `--dump-config` 查 `@xiangyixie/dsh-superagent` 块;用 `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.2` 重装,并在宿主日志里找 `[dsh-superagent]` 行。 |
1088
+ | `Cannot find module .../lib/control.js`(或 `watch.js` / `report.js`)且插件从未激活 | 那个 profile 里的副本不完整——被中断的 `add` 会留下残缺的解包结果。已发布的包不是原因:每个版本都带全部三十个 `lib/` 文件。 | 删掉 profile 的 `node_modules` 下该插件的目录(带 scope 的 `@xiangyixie/dsh-superagent`,或旧 tarball 安装留下的无 scope 的 `dsh-superagent`),再用同一条 `add` 命令重装,并带上版本号。不要手工拷贝文件进去。 |
1089
+ | `[error] the model provider rejected the API key` | 启动宿主的那个进程里缺 key 环境变量。 | 导出 `DEEPSEEK_API_KEY`(默认路由)或你那条路由声明的变量,然后重启 `dsh`。 |
1090
+ | `MISSING_CREDENTIAL ... no API key for provider route "..."` | profile 的路由在环境里没有凭据。 | 设置该路由对应的环境变量并重启。错误行里写了路由名,以它为准,不要照本文。 |
1091
+ | `[error] the subagent service is unavailable` | profile 没有 `subagents` 服务,插件没有东西可 spawn。 | 用基于 base bundle 的 profile(原版镜像的 `web` 或 `headless`),或者给该 profile 加上 subagent 插件。 |
1092
+ | `error: subagent provider "..." cannot enforce maxSubagentDepth` | 该路由的子 agent 后端无法限制委派深度。 | 保持 `provider: spawn`,或者在你接受后端自身限制时设 `maxSubagentDepth: provider-managed`。 |
1093
+ | `error: the Windows file sandbox could not start a child process` | 宿主沙箱启动器失败(`windows-acl-run: ...`),不是你的 goal 或 key 的问题。子任务会重试一次。 | 重试这个 run;如果重复出现,重启宿主,或在 profile 里关掉 Windows ACL 沙箱,然后跑 `diagnose-windows-sandbox-acl` 技能。 |
1094
+ | `error: the run was not started because the active-run limit is already in use` | `maxActiveRuns` 满了,包括共享该状态目录的其他 profile 的 run,而这次启动没要求排队(或者队列本身也满了)。 | 用 `queue: true` 重试、等一等、取消一个,或者调高 `maxActiveRuns` / `maxQueuedRuns`。 |
1095
+ | `error: the run stopped because it reached its spending cap` | 撞上了 `maxModelCallsPerRun` 或 `maxTokensPerRun`。 | 读已有的部分报告;在配置里调高上限,然后 `superagent_resume` 会用新限额继续。 |
1096
+ | `usage: not recorded` | run 已结束,但读不到任何子会话日志(`sessions` 目录被移走,或者这个 run 创建于记账功能之前)。 | 旧 run 没什么可修;新 run 会记录用量。run 还在活跃时,这一行说的是记账尚未完成。 |
1097
+ | `usage note: N child session log(s) could not be read` | 部分用量读不出来;token 数字是下界。调用预算仍然计入了这些子 agent。 | 检查 `$DSH_HOME/sessions` 存在且宿主进程可读。 |
1098
+ | `cost: not computed — no price configured for X` | 该模型不在 `pricing` 表里。 | 在 `pricing["provider/model"]` 下加它的每百万 token 价格,id 从 `usage:` 行复制。 |
1099
+ | `cost: at least ... (no price for X)` | 有些子 agent 用了未定价的模型。 | 同上;那个数字只覆盖已定价的部分。 |
1100
+ | `[error] a saved run file is damaged` | 某个状态文件被截断或是非法 JSON。 | 字节被保存在 `<runId>.json.corrupt-<ts>`;检查后删除。 |
1101
+ | `cancel requested ... not confirmed` | 拥有进程在 5 s 内没有确认。 | 查 `superagent_status`;如果 owner 已经不在,重启宿主让恢复把 run 标成 `cancelled`,想让它继续再 `superagent_resume`。 |
1102
+ | `[error] ... still owned by a live process` | 另一个 profile 正在跑这个 run,在这里 resume 会把工作做两遍。 | 让它跑完,或者先 `superagent_cancel`。 |
1103
+ | `missing or wrong bearer token`(HTTP 401) | 嵌入方用了上一次宿主启动的 token,或者读错了状态目录的发现文件。 | 重新从 `<stateDir>/control.json` 读 `token`;它每次启动都会重新生成。以 UTF-8 读该文件。 |
1104
+ | `the request did not name a live session`(HTTP 409) | `POST /runs` 或 `/resume` 调用时没有 `session_id`,或者会话已经关闭。 | 传一个在该宿主进程中打开的会话 id;从应该拥有它的那个会话里发起。 |
1105
+ | 宿主日志里的 `[dsh-superagent] control plane is not listening` | `controlPort` 已被占用、值非法,或状态目录不可写。 | 用 `controlPort: 0`、释放端口、修好状态目录,或删掉这个键;两种情况下工具都照常工作。 |
1106
+
1107
+ 本身失败的工具调用会返回三行:`[error]` 一句说明、`hint:`
1108
+ 一个下一步、以及 `detail:` 原封不动的宿主消息,什么都不隐藏。
1109
+ *在被接受之后*才失败的 run 保留它的报告,并在 run 块里显示 `error:`
1110
+ (是 `failed` 时再加一行 `hint:`)。
1111
+
1112
+ ## 已知限制
1113
+
1114
+ - 子 agent 不由本插件隔离:它们带着宿主的
1115
+ 凭据和文件系统运行,受宿主自身施加的沙箱策略约束。
1116
+ - run 活在宿主进程里。杀掉进程会停掉它的子 agent;
1117
+ run 在下一次挂载时变成 `interrupted`。
1118
+ - 从另一个进程取消是协作式的:它依赖拥有进程还在运行。卡死的进程只能在下次挂载时清理,
1119
+ 或者在它的心跳过期、配额被回收时清理。
1120
+ - 规划是一次模型调用。如果回复里没有可解析的
1121
+ `{"subtasks":[...]}` 对象,run 退化为一个子任务,并
1122
+ 标记 `plan.mode = "degraded"`。
1123
+ - 只有一个成功子任务时跳过聚合(报告就是该
1124
+ 子任务的文本加上 goal 标题),aggregator 失败或预算耗尽时退回到确定性的合并。
1125
+ - 保留策略是可选开启的(`keepRuns`);默认状态会累积,每个子任务最多
1126
+ 32 KB,外加每个 run 的报告。`archive prune` 按需删除终态
1127
+ run,不给 `--confirm` 时只是演练。
1128
+ - HTTP 嵌入面只走回环、可选开启、需要 token 认证;
1129
+ 它无法暴露到远程,也没有 MCP server。以同一用户身份运行的本地进程可以读 token,这与能写 run 文件是同一条信任边界。
1130
+ - 跨机器同步是一个 git 仓库,不是服务:离线优先、
1131
+ 冲突即停而非无冲突、没有实时通道,也
1132
+ 不在机器之间搬运凭据。两台机器同时写一个状态
1133
+ 目录时,仍然需要在它们之间 `pull`。
1134
+
1135
+ ## 命名
1136
+
1137
+ 包以 `@xiangyixie/dsh-superagent` 发布——npm 上已经有一个
1138
+ `dsh-super-agent`,与无 scope 的名字太接近,所以用 scope 保住
1139
+ 名字,而不是给项目改名。工具名不变:
1140
+ `superagent_*`(`superagent_memory` 在 0.10 中以增量方式加入)。早期的工作名是 `dsh-longhaul`,工具前缀 `longhaul_*`;
1141
+ 从未发布过,所以旧名字在任何地方都不存在,
1142
+ 也没有别名层。如果你找到调用 `longhaul_start` 的旧片段,
1143
+ 把前缀换掉即可——参数没有变。
1144
+
1145
+ ## 开发
1146
+
1147
+ ```bash
1148
+ npm test # node:test, fake store and fake child spawner, no network
1149
+ npm pack # inspect what would ship
1150
+ ```
1151
+
1152
+ "可以发布"意味着什么,写成了可勾选的行,在
1153
+ [docs/DONE.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/DONE.md);其中大部分条目指向的真实宿主运行记录在
1154
+ [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md)。
1155
+
1156
+ 代码布局:`lib/index.js`(插件、工具 schema、run 格式化)、
1157
+ `lib/orchestrator.js`(排序、重试、预算、取消、resume)、
1158
+ `lib/store.js`(原子 run 文件、取消标记、隔离)、
1159
+ `lib/errors.js`(可读的错误文本)、`lib/usage.js`(会话日志解析)、
1160
+ `lib/control.js`(可选的本地 HTTP 接口)。
1161
+
1162
+ ## 许可证
1163
+
1164
+ MIT。Copyright (c) 2026 Admire (LittleChenLiya);见 [LICENSE](LICENSE)。
1165
+
1166
+ npm scope `@xiangyixie` 与 GitHub 账号 `LittleChenLiya` 是同一位
1167
+ 作者。