@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.en.md ADDED
@@ -0,0 +1,1771 @@
1
+ [中文](README.md) | English
2
+
3
+ # dsh-superagent
4
+
5
+ Long-horizon runs for [DeepSeek Harness](https://dshai.org): one goal in,
6
+ model-planned parallel subtasks, one merged report — and the run survives a host
7
+ restart.
8
+
9
+ A single agent loop is one context and one sequence. Goals that need several
10
+ independent lines of work stall in it, and a crash ends the turn with nothing to
11
+ resume. This plugin takes one goal, asks the model to split it into subtasks, runs
12
+ up to three child agents at a time, and merges their reports into one answer. Run
13
+ state and spend are written to disk, so after a host restart `superagent_status`
14
+ still finds the run and `superagent_resume` finishes only the unfinished part.
15
+ Every run has a hard call and token budget, prints the usage it measured, and
16
+ prints the cost once you give it a price for the route.
17
+
18
+ **Don't use it when** one model call can answer: you would only be paying for a
19
+ planner and an aggregator on top. It is also the wrong tool for work that must
20
+ finish inside a single turn, for a step that needs human approval in the middle,
21
+ for anything that needs nested delegation (child depth is capped at 1), and for
22
+ anyone who wants an in-host panel — the optional workspace panel below is a
23
+ loopback page, not host UI. Children run with the host's credentials and
24
+ filesystem; this is not a sandbox.
25
+
26
+ **Install and run.** Node `>= 24.9.0`, a tool-calling route, and that route's key
27
+ in the environment:
28
+
29
+ ```bash
30
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.2
31
+ ```
32
+
33
+ Then ask the session for a run — a real call, not a sketch:
34
+
35
+ > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
36
+
37
+ The reply ends `completed` with the merged report, or with
38
+ `next: superagent_status run_id="..."` if the wait ran out. [Quickstart](#quickstart)
39
+ covers the path from an empty machine, including the reason not to install npm's
40
+ unrelated `dsh` package by name.
41
+
42
+ It adds no in-host UI (the workspace panel and the conversation console are
43
+ loopback pages) and patches no host code: the twelve `superagent_*` tools are the
44
+ surface, plus six optional operator utilities (a terminal panel, an HTML report,
45
+ an install doctor, a run archive, git sync, and the workspace panel) that read the
46
+ same run files. Browser and desktop control is a separate layer: with
47
+ `runtime.enabled` set, fourteen more tools are registered, and with the default
48
+ `false` none of them exist.
49
+
50
+ Personal project, not affiliated with DeepSeek or the harness maintainers. MIT
51
+ licensed, © 2026 Admire (LittleChenLiya); details in [License](#license).
52
+
53
+ ## Requirements
54
+
55
+ - Node `>= 24.9.0`. DeepSeek Harness refuses to start below that, so this
56
+ plugin does too.
57
+ - DeepSeek Harness `>= 0.2.2-rc.1 < 0.3.0` with the base bundle (the `tools`,
58
+ `agents`, and `subagents` services).
59
+ - A model route that can call tools, and that route's API key in the
60
+ environment. The default profile uses `deepseek-official` / `deepseek-flash`
61
+ and reads `DEEPSEEK_API_KEY`.
62
+
63
+ ## Quickstart
64
+
65
+ Five minutes, from nothing to a finished run. Every command below runs on a
66
+ clean machine.
67
+
68
+ ### 0. Do not install `dsh` from npm by name
69
+
70
+ ```bash
71
+ # WRONG: npm's `dsh` is unrelated ("a shell written in JavaScript")
72
+ npm i -g dsh
73
+
74
+ # RIGHT: run the DeepSeek Harness by its scoped package, pinned
75
+ npx @deepseek-ai/dsh@0.2.2-rc.1 --version
76
+ ```
77
+
78
+ The rest of this page writes `dsh` for that command; if the binary is not on
79
+ your `PATH`, use `npx @deepseek-ai/dsh@0.2.2-rc.1` instead.
80
+
81
+ ```bash
82
+ # 1. install the plugin into a profile (web, headless, ... whatever you run)
83
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.2
84
+
85
+ # 2. confirm the bundle row exists in the merged config
86
+ dsh --profile web --dump-config
87
+ ```
88
+
89
+ ### Install from the plugin index (optional)
90
+
91
+ The plugin index pins the package name, the release version, and the exact commit
92
+ in one JSON file, which the desktop app's **Discover** page can read directly:
93
+
94
+ 1. Open **Discover**, choose **Add index**, and enter `https://raw.githubusercontent.com/LittleChenLiya/dsh-superagent/main/plugin-index.json`.
95
+ 2. Find "Superagent" in the list and install it; later releases update from the same entry.
96
+
97
+ Every version entry points at a full 40-hex commit, so a one-click update lands on
98
+ a known revision instead of a moving branch head.
99
+
100
+ The desktop app's **Add plugin** dialog accepts the same three forms:
101
+
102
+ | Dialog input | Value | What it does |
103
+ | --- | --- | --- |
104
+ | Package name | `@xiangyixie/dsh-superagent@0.14.2` | Installs from npm. Name the version (see below). |
105
+ | GitHub repository | `https://github.com/LittleChenLiya/dsh-superagent` | Installs from the repository. Add `#v0.14.2` if you need a fixed release. |
106
+ | Local directory | `file:/absolute/path/to/dsh-superagent` | Copies the checkout. Re-add after changing the source. |
107
+
108
+ Upgrading is remove-then-add, not in-place: remove the old copy
109
+ (`dsh plugin --profile web remove @xiangyixie/dsh-superagent`) before adding
110
+ the new version. The same applies to any other plugin already in that profile —
111
+ remove and re-add it rather than expecting the dialog or `add` to replace it.
112
+
113
+ Name the version. Without one, pnpm's minimum release age policy skips releases
114
+ published in the last few hours and installs the newest older one, so a bare
115
+ `add` succeeds while giving you a version that is not current. If you would
116
+ rather track the newest release, add it to `minimumReleaseAgeExclude` in the
117
+ profile's `pnpm-workspace.yaml`; otherwise bump the number above. Check what
118
+ actually landed with:
119
+
120
+ ```bash
121
+ npm ls --prefix <DSH_HOME>/profiles/web @xiangyixie/dsh-superagent
122
+ ```
123
+
124
+ For an offline machine or a pinned artifact, install a packed tarball instead —
125
+ it is byte-identical to what the registry serves:
126
+
127
+ ```bash
128
+ npm pack # writes xiangyixie-dsh-superagent-<version>.tgz
129
+ dsh plugin --profile web add ./xiangyixie-dsh-superagent-<version>.tgz
130
+ ```
131
+
132
+ Look for this block in the dump. If it is missing, the plugin is installed but
133
+ not mounted, and no `superagent_*` tool will exist:
134
+
135
+ ```yaml
136
+ # == @xiangyixie/dsh-superagent
137
+ - id: superagent
138
+ name: @xiangyixie/dsh-superagent
139
+ ```
140
+
141
+ ```bash
142
+ # 3. start the host with the key in the environment that starts it
143
+ export DEEPSEEK_API_KEY=sk-... # PowerShell: $env:DEEPSEEK_API_KEY="sk-..."
144
+ dsh --profile web
145
+ ```
146
+
147
+ The key must be the one for the route the profile actually uses. A profile
148
+ pointing at DashScope uses `DASHSCOPE_API_KEY`; a profile pointing at a
149
+ self-hosted gateway uses whatever that route names. See
150
+ [Other routes](#other-routes) if you want to add one.
151
+
152
+ In the session, ask for a run:
153
+
154
+ > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
155
+
156
+ Shape of the reply (numbers illustrative — a full transcript of a real run is
157
+ in [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md)):
158
+
159
+ ```
160
+ run 20261114T051233-a1b2 — completed
161
+ goal: Explain the difference between process and thread in 300 words, with one concrete example
162
+ plan: planned; subtasks 2/2 completed; max 3 in parallel; 2 attempt(s) each
163
+ elapsed: 18.4s
164
+ usage: input 4120 (+980 prompt tokens served from cache), output 455, calls 4 (deepseek-official/deepseek-flash: 4 call(s) 4120 in / 455 out)
165
+ cost: not computed — no price configured for deepseek-official/deepseek-flash; add a pricing entry in cordis.patch.yml to get an estimate
166
+ [1] completed (attempts 1) Processes vs threads
167
+ [2] completed (attempts 1) Concrete example
168
+
169
+ report:
170
+ ...
171
+ ```
172
+
173
+ There is no built-in price for the default DeepSeek route; see
174
+ [Spending limits and prices](#spending-limits-and-prices) to add one, after
175
+ which the next run (or a resume of this one) prints `cost: ...`. `cost` is
176
+ computed when a run settles, so an already-finished run keeps the "not
177
+ computed" line. `usage: not recorded` only appears on a finished run whose
178
+ child logs cannot be read at all — see [Troubleshooting](#troubleshooting).
179
+
180
+ If `wait_seconds` runs out before the run finishes, the reply ends with
181
+ `next: superagent_status run_id="..." wait_seconds=120`. Call it again; the run
182
+ keeps going either way.
183
+
184
+ To check recovery without a real crash: kill the host while a run is active,
185
+ start it again, then `superagent_status` shows `interrupted` and
186
+ `superagent_resume` finishes it. A run is only `interrupted` when no live
187
+ process owns it: while the original host is still running, its run is left
188
+ alone and the next mount reports it as active, not as interrupted.
189
+
190
+ Two shutdown paths behave differently, and both are covered by the E2E record:
191
+
192
+ - **Hard kill (or crash).** The heartbeat is a few seconds old, but on the
193
+ machine that wrote the run the dead pid is checked first, so the next mount
194
+ reclaims it immediately and prints
195
+ `reclaimed: owner pid … is not running and this state directory is local`.
196
+ A shared state directory written by another machine trusts the heartbeat
197
+ instead, so reclamation there waits up to 90 s.
198
+ - **Graceful shutdown.** If the host disappears while a run is in flight (for
199
+ example a one-shot headless turn that ends after `wait_seconds: 0`), the
200
+ plugin notices that the `subagents` service is gone, leaves the unfinished
201
+ subtasks `pending`, and settles the run as `interrupted` with
202
+ `note: the host shut down while this run was active`. No attempts are burned
203
+ on a service that cannot answer. In that case the host process itself may
204
+ linger until a child that ignores abort exits; that wait is the host's, not
205
+ the plugin's.
206
+
207
+ ## Configuration
208
+
209
+ Row config in `<profile>/cordis.patch.yml`:
210
+
211
+ ```yaml
212
+ - id: superagent
213
+ config:
214
+ maxSubtasks: 8
215
+ maxParallel: 3
216
+ maxActiveRuns: 2
217
+ ```
218
+
219
+ | Key | Default | Meaning |
220
+ | --- | --- | --- |
221
+ | `stateDir` | `$DSH_HOME/state/superagent` | Run state root. |
222
+ | `provider` | `spawn` | Subagent backend used for planner, workers, aggregator. |
223
+ | `childProvider` | parent's | Optional provider route override for child agents. |
224
+ | `childModel` | parent's | Optional model override for child agents. |
225
+ | `childPreset` | none | Agent preset for child agents. A preset owns the child's tool set; this host has no per-run tool filter. |
226
+ | `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. |
227
+ | `plannerProvider` | parent's | Optional provider route override for the planner child. |
228
+ | `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. |
229
+ | `plannerTimeoutSeconds` | `120` | Wall-clock bound per planner attempt. On expiry the attempt is stopped and recorded; no fallback worker is started. |
230
+ | `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. |
231
+ | `maxSubagentDepth` | `1` | How deep children may delegate. `1` forbids grandchildren; `provider-managed` leaves it to the backend. |
232
+ | `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). |
233
+ | `maxSubtasks` | `8` | Cap on planned subtasks. A tool argument can only lower it, never raise it; hard max 16. |
234
+ | `maxParallel` | `3` | Subtasks executing at once. A tool argument can only lower it; hard max 8. |
235
+ | `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. |
236
+ | `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. |
237
+ | `queueTimeoutMinutes` | `30` | How long a queued run waits before it fails without ever starting; nothing is spent. |
238
+ | `queueOnFull` | `false` | Queue every start that exceeds `maxActiveRuns`, not only the ones that pass `queue: true`. |
239
+ | `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. |
240
+ | `deadlineMinutes` | `120` | Wall-clock budget; on expiry the run ends `partial` or `failed`. |
241
+ | `maxModelCallsPerRun` | `80` | Hard cap on child model calls per run; `0` disables. |
242
+ | `maxTokensPerRun` | `2000000` | Hard cap on prompt + completion tokens per run; `0` disables. |
243
+ | `pricing` | empty | Per-1M-token prices, keyed exactly as the usage log names the model (`provider/model`). Nothing is priced out of the box. |
244
+ | `resultCapBytes` | `32768` | Bytes kept per subtask report. |
245
+ | `notifyOnComplete` | `true` | Master switch for proactive messages. Off means the plugin never wakes the session. |
246
+ | `maxNotificationsPerHour` | `3` | Proactive messages allowed per hour. Runs above the cap are folded into one summary; `0` disables the cap. |
247
+ | `notifyRetries` | `2` | Extra delivery attempts when the host refuses a wake-up; messages for one session are delivered in order. |
248
+ | `notifyRetryDelayMs` | `2000` | First delay between those attempts; it doubles per attempt, capped at 60s. |
249
+ | `autoResumeRounds` | `1` | Extra rounds that retry subtasks which failed in a way that looks transient, before the failure is reported; `0` disables. |
250
+ | `childModelFallback` | none | Model used on such a retry (quota, rate limit, timeout). Unset keeps the configured route. |
251
+ | `memory` | `true` | Cross-run notebook. See [Cross-run memory](#cross-run-memory). |
252
+ | `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. |
253
+ | `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). |
254
+ | `memoryMaxAgeDays` | `30` | Notes older than this are ignored, then compacted away. |
255
+ | `memoryDigestEntries` | `12` | Notes injected into a prompt. |
256
+ | `memoryDigestChars` | `1600` | Character budget for the note part of that prompt. |
257
+ | `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). |
258
+ | `keepRuns` | `0` | Delete terminal runs older than this many days at mount; `0` keeps everything. |
259
+ | `guard` | on | Worker path and command policy. See [Worker safety guard](#worker-safety-guard) for every default and the reason behind it. |
260
+ | `audit` | `true` | Append-only audit trail. It only observes; turning it off removes the trail, never the run behaviour. |
261
+ | `policyFile` | `<stateDir>/policy.json` when it exists | Permission policy. Unset and absent means no policy, i.e. the old behaviour. |
262
+ | `auditDir` | `<stateDir>/audit` | Where `audit.jsonl` and its exports live. |
263
+ | `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). |
264
+ | `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). |
265
+ | `workspaceRoot` | host cwd | Repository the workers are isolated in when `workspaceIsolation` is on. Must be a git working tree with at least one commit. |
266
+ | `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. |
267
+ | `workbenchRoot` | `process.cwd()` | Directory the panel may browse and edit. Every path outside it is refused. |
268
+ | `consolePort` | off | Loopback port for the conversation console; `0` picks a free one. Requires the host `sessionController` service. |
269
+ | `consoleRoot` | `workbenchRoot`, then host cwd | Directory the console's conversation session joins. |
270
+ | `consolePreset` | host default | Agent preset id the console session mounts. Tools follow this preset, not this plugin. |
271
+ | `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. |
272
+ | `schedulerHumanPriority` | `true` | Default for a plan's `human_priority`: a scheduled run may not take the last free concurrency slot. |
273
+ | `schedulerMaxConsecutiveFailures` | `3` | Consecutive failed executions before a plan pauses itself and says so once (1–20). |
274
+
275
+ ### Switching models
276
+
277
+ Model choice is configuration, not code. By default child agents inherit the
278
+ session's model from the profile's `agent-default-model`. To pin children to a
279
+ specific route, set both keys and restart the host:
280
+
281
+ ```yaml
282
+ - id: superagent
283
+ config:
284
+ childProvider: dashscope
285
+ childModel: qwen-flash
286
+ ```
287
+
288
+ Nothing about a model id is compiled into the plugin. API keys are read from
289
+ the environment variable named by the route; the plugin never stores a key. The
290
+ default profile's route is `deepseek-official` and reads `DEEPSEEK_API_KEY`.
291
+
292
+ ### Other routes
293
+
294
+ The example above assumes a DashScope route is installed in the profile. It is
295
+ not part of the base bundle: the default profile has no `dashscope` provider and
296
+ `DASHSCOPE_API_KEY` alone will not create one. Add the route first (see the
297
+ harness docs for LLM plugins), then name it in `childProvider`.
298
+
299
+ ### Child tools and recursion
300
+
301
+ `maxSubagentDepth: 1` is passed to the host as `maxDepth`, so a worker cannot
302
+ create its own children. This is enforced by the host, not by prompting, and a
303
+ provider that cannot enforce it makes `superagent_start` fail with an explicit
304
+ error instead of silently running unbounded.
305
+
306
+ There is **no** enforced tool allowlist on `dsh@0.2.2-rc.1`. The host's
307
+ subagent start request has no tool filter, and its own `subagent` tool rejects a
308
+ `toolFilter` config and points at agent presets. `childPreset` is therefore the
309
+ supported way to narrow a child's tools; without a dedicated preset, workers
310
+ inherit the session's tools. The `superagent_*` tools still exist in their tool
311
+ list, but the run tools (`superagent_start`, `superagent_resume`, `superagent_cancel`,
312
+ `superagent_followup`, `superagent_inject`, `superagent_answer`) refuse to run from a worker session;
313
+ only the top-level agent manages runs.
314
+
315
+ ### Per-worker command permissions
316
+
317
+ A `workspace-write` host sandbox refuses a child process spawned with piped
318
+ stdio (`EPERM`). A worker that needs to run `npm test` therefore cannot do so
319
+ under the inherited policy, and this plugin will not turn the sandbox off for
320
+ the whole machine. `commandWorkerPermission` raises it only for the workers that
321
+ declare it:
322
+
323
+ ```yaml
324
+ - id: superagent
325
+ config:
326
+ commandWorkerPermission: danger-full-access
327
+ ```
328
+
329
+ With that setting, a worker whose plan entry has `requires` containing a command
330
+ capability (`shell`, `bash`, `sh`, `zsh`, `fish`, `terminal`, `pwsh`,
331
+ `powershell`, `cmd`, `run_command`, `exec_command`) gets full access. Planner,
332
+ aggregator, acceptance judges, and workers without such a capability keep the
333
+ inherited mode.
334
+
335
+ How it works, and why it is a delegation trick rather than a host feature:
336
+
337
+ - The host has no per-subagent permission field. What it does have is
338
+ inheritance: `subagents.startActivation` captures the parent session's last
339
+ `sandbox/mode` event **synchronously, before its first `await`**, and seeds
340
+ that mode into the child.
341
+ - For one qualifying worker, the plugin appends `sandbox/mode:
342
+ danger-full-access` to the parent session, calls `startActivation`, and
343
+ appends the previous mode back in a `finally` — all in the same synchronous
344
+ tick, with no `await` between those steps. A concurrent call can therefore
345
+ never observe the temporary override, and the child still captures it.
346
+ - Both steps append one `sandbox/mode` event; the plugin never uses
347
+ `permissionPresets.set()`, whose `custom` state cannot be restored by name.
348
+ - The approval policy is pinned to `never` for that child by the host's own
349
+ delegation capture, not by this plugin.
350
+ - Each step is written to the audit trail as `worker.escalate` and
351
+ `worker.restore` with `runId`, `subtaskId`, and the reason (the declared
352
+ capability). When `audit` is off, no audit line is written; the escalation
353
+ still behaves the same.
354
+
355
+ Limits: this only applies to in-process providers whose child is created from
356
+ the parent session in the same host process (`provider: spawn`). An upstream
357
+ change to when the override is captured — or to delegation inheritance itself —
358
+ makes this silently fall back to inheritance rather than fail the run. The
359
+ temporary event also pins the previous mode in the parent log when the parent
360
+ had no explicit override: it records the deployment default, which is
361
+ behaviourally identical until that default changes.
362
+
363
+ ### Per-worker workspace isolation
364
+
365
+ Parallel workers are independent agents, but by default they share one working
366
+ directory: two subtasks that edit the same file overwrite each other, and the
367
+ last writer wins. `workspaceIsolation` fixes that by giving each worker its own
368
+ checkout.
369
+
370
+ ```yaml
371
+ - id: superagent
372
+ config:
373
+ workspaceIsolation: true
374
+ workspaceRoot: /home/me/projects/api # or C:\work\api on Windows
375
+ ```
376
+
377
+ **Why git worktrees rather than a directory copy.** The hard half of isolation
378
+ is merging the results back. A worktree gives that for free: a real three-way
379
+ merge with conflict detection, both sides preserved as refs, and one command the
380
+ user can run to finish by hand. A recursive copy would either need a diff3
381
+ engine (a dependency this package does not have) or overwrite the main checkout,
382
+ which is the bug the feature exists to prevent. A worktree also shares the object
383
+ database and ignore rules, so a worker sees the real repository without a full
384
+ copy of it. Worktrees live under `.superagent/worktrees/<runId>/w<n>` inside the
385
+ directory the host was started in — the repository itself when that is the
386
+ starting directory. The host's `workspace-write` sandbox takes its writable
387
+ boundary from the session cwd, so a checkout under the state directory, or
388
+ inside a repository the host was not started in, would be denied every write.
389
+ The pool carries its own `.gitignore`, so worker checkouts never leak into the
390
+ user's next commit or make the main checkout look dirty.
391
+
392
+ **What happens during a run.** Each worker is given
393
+ `superagent/<runId>-w<n>`, a branch created from the main checkout's `HEAD`. Its
394
+ prompt names the absolute path and forbids touching anything else, switching
395
+ branches, committing, merging, or pushing. When the worker finishes, the run
396
+ commits whatever it left in the checkout (so a model that forgot to commit still
397
+ loses nothing; git hooks are skipped so a pre-commit hook cannot block the merge)
398
+ and then merges the branches into the main checkout **one at a time**, after all
399
+ subtasks are done.
400
+
401
+ **What you see when a merge conflicts.** The merge is aborted, so the main
402
+ checkout is restored exactly as it was and no conflict markers are left in it.
403
+ The outcome is recorded on the run and printed by `superagent_status`:
404
+
405
+ ```
406
+ workspace conflict: [2] src/routes.js, src/index.js — branch superagent/20261115T101500-ab12-w2
407
+ kept at <repository>/.superagent/worktrees/20261115T101500-ab12/w2; the main checkout was restored, so nothing
408
+ was lost. Resolve with: git -C "/home/me/projects/api" merge superagent/20261115T101500-ab12-w2
409
+ ```
410
+
411
+ The wake-up message for the run says the same in one line, because a conflict is
412
+ the one outcome that needs the user even when the run itself "completed". Nothing
413
+ is discarded: the branch and its checkout are kept until you merge or delete
414
+ them. Two more cases are reported the same way rather than silently dropped:
415
+
416
+ - the main checkout has uncommitted changes when the merge is due — every
417
+ branch is left unmerged, since merging into a dirty tree would mix your edits
418
+ with the workers' and make an abort restore the wrong state;
419
+ - the run was cancelled or hit its deadline before merging — the branches are
420
+ kept and a resume reuses the same worktrees.
421
+
422
+ **When isolation is not possible.** If `workspaceRoot` is not a git working tree,
423
+ git is not on `PATH`, or the repository has no commit yet, the run does not fail.
424
+ It falls back to the shared directory (the previous behaviour) and both
425
+ `superagent_status` and the notification say so:
426
+
427
+ ```
428
+ workspace: isolation was requested but is unavailable — /tmp/notes is not a git working tree,
429
+ so a per-worker worktree cannot be created; workers shared /tmp/notes, so their edits can
430
+ overwrite each other
431
+ ```
432
+
433
+ **Limits, stated plainly.** `dsh@0.2.2-rc.1` gives a child agent no `cwd` field,
434
+ so the plugin cannot hand a worker a directory at spawn time. Isolation is a
435
+ prompt contract plus a real branch: a worker that ignores the prompt can still
436
+ edit the main checkout, but that shows up in `git status` before any merge and
437
+ cannot damage a sibling's branch. With isolation off, behaviour is exactly what
438
+ it was before this option existed.
439
+
440
+ ### Worker safety guard
441
+
442
+ Workers inherit the session's filesystem and credentials, so every tool call a
443
+ superagent child makes passes through a guard mounted on the host's
444
+ `tools/pre-execute` path (`ctx.tools.guard` when available). The guard only
445
+ policies children this plugin spawned; the parent session is untouched.
446
+
447
+ ```yaml
448
+ - id: superagent
449
+ config:
450
+ guard:
451
+ enabled: true
452
+ allowWriteRoots: [] # extra writable roots, absolute or ~-relative
453
+ denyPaths: [] # extra read+write denials
454
+ denyCommands: [] # [{ id, pattern, reason }] extra regex denials
455
+ allowCommands: # explicit overrides; every use is recorded
456
+ - id: clean-build
457
+ pattern: '^rm -rf build$'
458
+ reason: clean build output
459
+ maxEvents: 50
460
+ ```
461
+
462
+ Defaults, and why they are set that way:
463
+
464
+ | Rule | Default | Why |
465
+ | --- | --- | --- |
466
+ | 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. |
467
+ | 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. |
468
+ | 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. |
469
+ | `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. |
470
+ | `cmd/disk-format` | `mkfs`, `diskpart`, `wipefs`, `format X:`, `dd of=/dev/sd*` | Never a development action. |
471
+ | `cmd/system-scheduler` | `schtasks /create`, `Register-ScheduledTask`, `crontab -r`, `systemctl enable\|disable\|mask`, `launchctl load` | Persistence outside the workspace. |
472
+ | `cmd/system-registry` | `reg add/delete` on `HKLM`/`HKCR`, and any `\Run` key | Machine-wide or auto-start changes. |
473
+ | `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. |
474
+ | `cmd/permission-nuke` | `chmod -R 777 /`, recursive `chown` of `/`, `icacls … /grant Everyone /t` | Destroys the access model of the machine. |
475
+ | `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. |
476
+
477
+ A denial is a real tool error, not a silent failure: the worker receives
478
+ `[guard] blocked <tool>: rule <id> — <reason>. The call did not run.`, and the
479
+ event is added to the run. `superagent_status` prints
480
+ `guard: N tool call(s) blocked; M explicit allow(s) recorded (rule ×count)`
481
+ plus up to three blocked commands, and the finished report gains a
482
+ `## Safety guard` section listing every kept event. Counters cover all events
483
+ even when `maxEvents` stops the list.
484
+
485
+ `allowCommands` is the only override. It wins over a denial, but every match is
486
+ recorded as `decision: allowed` with the rule it overrode, so an override is
487
+ never invisible. Credential, `.git` control, and system-directory denials are
488
+ not overridable; to permit a legitimate build directory outside the workspace,
489
+ add it to `allowWriteRoots`. The guard is lexical and realpath based, so a
490
+ symlink inside the workspace that points at a denied path is still caught.
491
+
492
+ The guard is a policy layer over tool arguments, not an OS sandbox. A command
493
+ that delegates the write to a program (`node build.js`, a compiler) can still
494
+ write wherever that program runs; blocking that requires a host-level sandbox,
495
+ which `dsh@0.2.2-rc.1` does not expose. The guard stops direct `write`/`edit`/
496
+ `apply_patch` targets, shell redirections, and the destructive command classes
497
+ above, which covers the accidental `rm` and "write into `C:\Windows`" cases a
498
+ wandering worker actually produces.
499
+
500
+ ### Spending limits and prices
501
+
502
+ Two hard budgets stop a pathological goal before it can spend quietly. Both are
503
+ checked before every child is spawned, so a retry loop cannot walk past them:
504
+
505
+ ```yaml
506
+ - id: superagent
507
+ config:
508
+ maxModelCallsPerRun: 40
509
+ maxTokensPerRun: 500000
510
+ pricing:
511
+ deepseek-official/deepseek-flash:
512
+ input: 0.28 # price per 1M uncached prompt tokens (example)
513
+ output: 0.42 # price per 1M completion tokens (example)
514
+ cacheRead: 0.028 # optional; defaults to the input price
515
+ currency: CNY
516
+ ```
517
+
518
+ The pricing key is matched against the model id in the usage log, which is
519
+ `provider/model` — `superagent_status` prints it on the `usage:` line, so copy
520
+ the key from there. A key is matched exactly first, then by its bare model name,
521
+ so `qwen-flash` also prices `dashscope/qwen-flash` when there is no exact entry.
522
+ The plugin ships no price for any route, because a stale price is worse than a
523
+ missing one.
524
+
525
+ When a budget is hit, no new child starts and the abort controller stops the
526
+ child that is still running, so spend stops at the cap instead of draining one
527
+ more worker. Reports that already finished are still merged. The run ends
528
+ `partial` when at least one subtask completed and `failed` when none did (the
529
+ unfinished subtasks stay `pending`). `superagent_resume` rebuilds the limits
530
+ from the current config, keeps everything already spent, and continues from
531
+ there — that is how you raise a cap. On the real host, raising
532
+ `maxModelCallsPerRun` from 2 to 80 and resuming a run that stopped at 2/2
533
+ completed it without dropping the earlier spend.
534
+
535
+ A spawn counts as one model call even when the child's session log cannot be
536
+ read, so the call budget keeps working on a host whose log layout changed.
537
+ Token accounting still needs the log; when it is unavailable, the run prints a
538
+ `usage note:` saying the figures are a lower bound.
539
+
540
+ Costs are estimates from the table above, never from a built-in guess. A model
541
+ that is not listed is reported as `unpriced` and excluded from the total, so the
542
+ number you see is always a lower bound:
543
+
544
+ ```
545
+ cost: at least ¥0.0041 (estimate; no price for haoduo/gpt-6.1-sol)
546
+ ```
547
+
548
+ Amounts are kept per currency and never added across currencies. A run that
549
+ used both a CNY route and a USD route prints one subtotal per currency:
550
+
551
+ ```
552
+ cost: ¥0.0952 + $0.0248 (estimate; all models priced)
553
+ ```
554
+
555
+ The same rule holds for `superagent_list`'s ledger line, the live `watch`
556
+ footer, the exported `README.md`, and the HTML report — a mixed window gets one
557
+ figure per currency instead of a single number whose unit would be undefined.
558
+
559
+ ## Runtime control
560
+
561
+ The plugin can drive a browser and, on Windows, the desktop. Both halves are
562
+ **off by default**: with `runtime.enabled` false not one of these tools is
563
+ registered, so an existing profile sees exactly the same tool list as before.
564
+ Nothing here needs an npm dependency — the browser is spoken to over the
565
+ DevTools protocol with Node's own `WebSocket`, and the desktop is reached
566
+ through `powershell.exe` and `user32.dll`.
567
+
568
+ ```json
569
+ {
570
+ "@xiangyixie/dsh-superagent": {
571
+ "runtime": {
572
+ "enabled": true,
573
+ "browser": {
574
+ "headless": true,
575
+ "allowedHosts": ["localhost", "127.0.0.1"],
576
+ "executablePath": null,
577
+ "attachPort": null,
578
+ "userDataDir": null
579
+ },
580
+ "desktop": { "enabled": false, "allowActivation": false }
581
+ }
582
+ }
583
+ }
584
+ ```
585
+
586
+ `enabled` turns the layer on. `browser.enabled` and `desktop.enabled` decide
587
+ which halves register; desktop is separately gated because it can touch any
588
+ application on the machine. `allowedHosts` replaces the loopback default — a
589
+ leading `*.` matches any subdomain. `stopFile` and `shotDir` default to
590
+ `<stateDir>/runtime/STOP` and `<stateDir>/runtime/shots`.
591
+
592
+ `attachPort` and `userDataDir` are the two ways to reach a page that needs a
593
+ sign-in, and they trade differently:
594
+
595
+ - **`attachPort`** (for example `9222`) borrows the browser you started
596
+ yourself with `--remote-debugging-port`. Element listing, clicks, typing, and
597
+ screenshots all run on that connection, the tab keeps its own window size, and
598
+ `browser_close` only detaches — it never terminates your browser. If the port
599
+ is not listening the call fails with the port and a start command; it never
600
+ falls back to a fresh profile behind your back. Because that profile is
601
+ already signed in to whatever you use, every action inherits that access.
602
+ - **`userDataDir`** keeps one dedicated profile for a browser this plugin
603
+ launches: sign in once (QR code, SMS, whatever the site asks), and later runs
604
+ reuse the same cookie jar. The directory is a real credential store on disk —
605
+ keep it somewhere you would keep a password file, and do not point it at your
606
+ daily browser's profile. It is ignored while `attachPort` is set.
607
+
608
+ The default remains a fresh temporary profile under
609
+ `%TEMP%/dsh-runtime-profile-*`, so an ordinary run cannot see your daily
610
+ browser's cookies.
611
+
612
+ ### What it registers
613
+
614
+ | Tool | What it does |
615
+ | --- | --- |
616
+ | `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]`. |
617
+ | `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. |
618
+ | `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. |
619
+ | `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). |
620
+ | `browser_screenshot(path?, full_page?)` | PNG of the page, with path, pixel size, and byte size. |
621
+ | `browser_script(expression, await_promise?)` | Evaluates one expression and returns its JSON value; for reads, not for clicking. |
622
+ | `browser_wait(text?, css?, url_contains?, milliseconds?, timeout_ms?)` | Waits for a condition or a fixed delay. |
623
+ | `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. |
624
+ | `browser_close()` | Closes a browser this plugin launched. On an attach connection it only detaches and leaves your browser running. |
625
+ | `desktop_screenshot(window?, path?)` | Whole desktop, or one window by title captured with `PrintWindow` (a covered window still yields its own pixels). |
626
+ | `desktop_windows(filter?, limit?)` | Visible top-level windows: handle, title, pid, screen rectangle. |
627
+ | `desktop_click(x, y, window?, activate?, right?, confirm?)` | Click at screen coordinates. Background by default; `activate` is required for a foreground click. |
628
+ | `desktop_type(text, window?, activate?)` | Types into a window, background `WM_CHAR` by default. |
629
+ | `desktop_keys(keys, window?, activate?)` | Presses named keys (`enter`, `tab`, `f5`, `a`, `1` …) in order. |
630
+ | `runtime_status()` | Stop state, registered halves, allowed hosts, browser executable, attach/launch mode, session. |
631
+
632
+ Every browser and desktop call writes one line to the existing audit trail
633
+ (`lib/audit.js`) with `source: "runtime"`, the action, the target, the decision,
634
+ the result, and the duration. A gate that refuses an action writes
635
+ `decision: "deny"` or `"confirm"` and `result: "blocked"`, so the log can never
636
+ claim that a refused click succeeded. Browser lines also carry `meta.session` —
637
+ `"attach"` when the action ran on the browser you started (with `meta.port` and
638
+ the tab it reused), `"launch"` when it ran on one this plugin started (with
639
+ `meta.profile` and `meta.persistentProfile`) — so the trail can never confuse
640
+ your session with a throwaway profile. A page that asks for a person writes
641
+ `kind: "attention"`, `decision: "attention"`, and `result: "needs-human"`.
642
+
643
+ ### Gates
644
+
645
+ - **Emergency stop.** While the stop file exists — or `DSH_RUNTIME_STOP=1` is
646
+ set — every action is refused and the refusal is audited. Create the file and
647
+ the layer stops at the next call; delete it to re-enable.
648
+ - **Navigation.** Only `http:` and `https:` on the allowed hosts. `file://` is
649
+ refused because a page that could read local files would walk around the
650
+ workspace guard; `javascript:`, `data:`, and `chrome:` are refused too.
651
+ - **Uploads.** `browser_click` refuses an `<input type="file">`, because the
652
+ native file picker that follows cannot be driven and would fall through to the
653
+ user's own file system.
654
+ - **Irreversible actions.** A target whose label reads submit, delete, pay,
655
+ publish, transfer, 提交, 删除, 支付 … needs `confirm: true`. Without it the
656
+ click does not happen and the audit line records `decision: "confirm"`.
657
+ - **Human checks.** A page asking for a sign-in, CAPTCHA, SMS code, two-factor
658
+ confirmation, or QR scan stops the action at that point and returns
659
+ `[attention]` with what the page wants and how to hand over. The check is read
660
+ from the page text, so an ordinary settings page with a password field but no
661
+ sign-in wording is not flagged; nothing here solves or types the check. In a
662
+ launched window or an attached tab the person finishes it in the browser, then
663
+ `browser_await_human` polls until it is gone and the run continues. A pending
664
+ check is a hand-off, not a failed run.
665
+ - **Focus.** A background click or keystroke never brings a window forward. A
666
+ foreground action requires `activate: true` **and**
667
+ `runtime.desktop.allowActivation: true`, and each activation is recorded in
668
+ `meta.activated`.
669
+ - **Worker agents.** `browser_*` and `desktop_*` belong to the session that
670
+ mounted the plugin. The guard blocks them for bound child agents with rule
671
+ `guard/runtime-tool` unless `guard.allowRuntimeTools` is true.
672
+
673
+ ### What it deliberately cannot do
674
+
675
+ - **Borrow your logins by accident.** A launched browser gets a fresh profile
676
+ under `%TEMP%/dsh-runtime-profile-*`, so your cookies, saved passwords, and
677
+ signed-in sessions are simply not there. Reaching an authenticated page is an
678
+ explicit choice: attach to a browser you started with
679
+ `--remote-debugging-port` and set `browser.attachPort`, or point
680
+ `browser.userDataDir` at one dedicated profile and sign in there once. Both
681
+ make that access available to every later action, and both are visible in
682
+ `meta.session` in the audit log; a wrong attach port fails with instructions
683
+ instead of silently starting a profile.
684
+ - **Solve human verification for you.** CAPTCHAs, SMS codes, "confirm you are
685
+ human" interstitials, and QR logins stop the action and hand it back. It never
686
+ types a code or scans a code for you; it waits for you to do it and then
687
+ reports that the run may continue.
688
+ - **Evade bot detection.** A launched Chromium is detectable through CDP
689
+ artefacts, and sites that block automation will block this. Nothing here
690
+ patches `navigator.webdriver` or spoofs fingerprints.
691
+ - **Type into every application.** Background `WM_CHAR` reaches classic Win32
692
+ controls; Chromium, Electron, Qt, and most games ignore posted messages. For
693
+ those, either `activate: true` and accept the focus change, or drive the page
694
+ through `browser_*` instead.
695
+ - **Guess coordinates.** `desktop_*` takes physical screen pixels. With mixed
696
+ DPI scaling, take a `desktop_screenshot` first and read the rectangle from
697
+ `desktop_windows` rather than computing it.
698
+ - **Control macOS or Linux desktops.** The desktop half is Windows-only. The
699
+ browser half works anywhere a Chromium-family binary exists.
700
+
701
+ Two runnable proofs ship with the repository. `node scripts/runtime-demo.mjs`
702
+ starts a local page, clicks a button, reads the counter back out of the DOM,
703
+ types into a field, is refused on an irreversible button and on a file input,
704
+ flips the stop switch, and prints the audit lines and screenshot paths.
705
+ `node scripts/runtime-desktop-demo.mjs` opens a no-activate test window, posts a
706
+ click and text into it, verifies both from the target process's own state file,
707
+ and captures the window.
708
+
709
+ ## Tools
710
+
711
+ - `superagent_start(goal, mode?, queue?, max_subtasks?, max_parallel?, deadline_minutes?, allow_duplicate?, wait_seconds?)`
712
+ starts a run and returns immediately with a run id. `mode: "direct"` runs the
713
+ goal on one worker with no planner and no aggregator, and returns that worker's
714
+ reply as the report unchanged — right for one self-contained lookup, edit,
715
+ query, or short piece of writing, wrong for a goal with parts that can run in
716
+ parallel. The default, `mode: "planned"`, does the full planner → workers →
717
+ merged report pipeline. A planned subtask may declare `dependsOn` another
718
+ subtask: the dependent waits for it and gets its report in its prompt, while
719
+ independent subtasks still run in parallel. A dependency cycle rejects the
720
+ plan before any work starts, and a dependency on a task the plan never
721
+ declared is skipped with the reason. Both modes produce the same run record,
722
+ quota, deadline, cancel, and usage accounting. `goal_mode: true` adds an
723
+ acceptance step and re-plans a failed round; see [Goal mode](#goal-mode).
724
+ `queue: true` makes a start wait for a free slot when `maxActiveRuns` is in use
725
+ instead of failing: it returns `status: "queued"` with `queue.position` /
726
+ `queue.of`, starts automatically when an active run finishes, and fails after
727
+ `queueTimeoutMinutes` if no slot frees. At most `maxQueuedRuns` waits; a queued
728
+ run does not count against `maxActiveRuns` while it waits, and cancelling it
729
+ removes it from the line cleanly. Starting a goal that an
730
+ active run in the same session already covers returns that run id marked
731
+ `deduped: true` instead of paying for a second plan: the goal is compared after
732
+ trimming, collapsing runs of whitespace, and ignoring case, and the check runs
733
+ under a per-goal claim keyed in the state directory, so two processes that share
734
+ it still start one run. The match is per session, because two sessions may
735
+ legitimately ask for the same generic goal at once.
736
+ `allow_duplicate: true` starts another one. A finished run never blocks the same
737
+ goal from being started again. `wait_seconds` blocks for a terminal state and
738
+ keeps the `deduped` marker in its result.
739
+ - `superagent_status(run_id, wait_seconds?)` returns status, milestones,
740
+ per-subtask outcome, measured token usage, estimated cost, the report file
741
+ path, and the final report.
742
+ - `superagent_list(limit?)` lists runs, newest first, plus the state directory's
743
+ file count and size.
744
+ - `superagent_cancel(run_id)` stops the run, from any process; see below.
745
+ - `superagent_resume(run_id, wait_seconds?, force?)` continues an `interrupted`,
746
+ `failed`, `partial`, or `cancelled` run; completed subtasks are kept. Workers
747
+ are told what failed and to check what the earlier attempt already did. Only
748
+ the session that started the run may resume it. A resume is not counted
749
+ against `maxActiveRuns`, so it works when the cap is full; `force` is still
750
+ accepted but no longer needed. A `completed` run stays completed unless it
751
+ holds an answer that never reached a prompt — then resume reopens it, because
752
+ otherwise that decision would be stranded.
753
+ - `superagent_followup(run_id, message)` adds an instruction to a run that is
754
+ already executing, instead of starting a second run. This tool is explicitly
755
+ next-prompt: the instruction is queued on the run and the next prompt built for
756
+ it carries it — the next worker spawn or the aggregation, whichever comes
757
+ first. Subtasks that are already running or finished keep their results and
758
+ never see it. The reply names that boundary, and status shows the same thing;
759
+ an instruction that arrives after the last boundary is recorded as
760
+ `never took effect` rather than looking delivered. A paused run
761
+ (`interrupted`, `failed`, `partial`, `cancelled`) keeps the instruction for
762
+ the next round, which starts when it is resumed; a `completed` run refuses it.
763
+ A run owned by another process is refused, because that owner's next save
764
+ would overwrite it. Only the session that started the run may add to it. Use
765
+ `superagent_inject` when the running workers must read the instruction now.
766
+ - `superagent_inject(run_id, message, subtask_index?, wait_seconds?)` delivers
767
+ one instruction into the workers that are running right now. It uses the
768
+ host's live steering channel (`subagents.sendMessage`, the same inbox the
769
+ agent loop drains at its next pre-step), so the message is part of the child's
770
+ next model request. It does not interrupt a model call already in flight: the
771
+ delay is the remainder of the step that is running (that model response plus
772
+ its tool batch). A live child that had already decided to stop runs one more
773
+ turn to read it, so an uncancelled child consumes it. The reply reports the
774
+ measured delay from acceptance to the child's next request, and marks a
775
+ message as `missed` — never as delivered — when the child is cancelled,
776
+ disposed, or finishes before another boundary. Worst case measured on a real
777
+ `dsh@0.2.2-rc.1` host: **6978 ms** with an 8 s child step and **2986 ms** with
778
+ a 4 s step, i.e. the bound tracks the step, not the plugin. With a host that
779
+ exposes no live channel, the tool degrades to the followup queue and says so
780
+ in the reply; it never calls that live.
781
+ - `superagent_answer(run_id, attention_id?, answer, wait_seconds?)` answers one
782
+ structured attention item so that run continues with the decision. An active
783
+ run applies the answer at its next boundary; a finished run is reopened and
784
+ only its aggregation runs again, now with the answer in the prompt, so the
785
+ report reflects the decision instead of the user starting a new run.
786
+ `attention_id` is required when more than one question is open. An answer is
787
+ matched to the id, not to the array position: an id that was never asked, a
788
+ question already answered, and a question retired by a later resume are all
789
+ refused, and an answer whose text is another question's option names that
790
+ other id instead of guessing.
791
+ - `superagent_memory(action, key?, kind?, text?, scope?, query?, tags?, limit?)`
792
+ lists, searches, adds, corrects, or forgets notebook notes. `set` with an
793
+ existing key supersedes it; `forget` retracts it. `scope` addresses `rules`
794
+ (project rules), `profile` (user preferences), or the run scope. `search`
795
+ ranks notes against `query` (the current goal works well) and/or exact `tags`,
796
+ so a relevant old note is found instead of only the newest ones; notes can
797
+ carry `tags` when set. The tool is additive: the eleven other tools keep their
798
+ arguments and output.
799
+ - `superagent_template(action, id?, params?, template?, limit?)` lists, shows,
800
+ expands, saves, or deletes a workflow template: a fixed goal skeleton with
801
+ required parameters, when it fits, and when it does not. `expand` returns one
802
+ ordinary goal string, which `superagent_start` plans exactly like a typed goal;
803
+ a missing or empty parameter is refused by name instead of defaulted. A
804
+ template cannot set limits, budgets, a mode, or an override, so using one never
805
+ widens what a run may do. Built-in ids are read-only; custom ones live under
806
+ the template directory in the state directory, and a failure there is logged
807
+ without disabling the run tools.
808
+ - `superagent_schedule(action, id?, name?, goal?, template_id?, params?, cron?,
809
+ every_minutes?, timezone?, miss_policy?, goal_mode?, acceptance?, max_rounds?,
810
+ max_wall_clock_minutes?, no_progress_rounds?, budget?, human_priority?)` creates,
811
+ lists, pauses, resumes, deletes, or runs a scheduled plan now. A plan stores a
812
+ goal (or an expanded template), a clock, and its own limits; it survives a host
813
+ restart and starts runs nobody asked for. Nothing is armed until a plan exists.
814
+ See [Scheduled runs](#scheduled-runs).
815
+ - `superagent_audit(run_id?, subtask_id?, kind?, decision?, result?, target?,
816
+ since?, until?, limit?, order?, format?, out_path?)` reads the audit trail, or
817
+ exports the matching events as one JSONL or CSV file. See
818
+ [Permissions and audit](#permissions-and-audit).
819
+
820
+
821
+ ## Goal mode
822
+
823
+ A normal run finishes when its subtasks finish. That is not the same as the goal
824
+ being met, and a plan can report success over a broken build. Goal mode is an
825
+ opt-in (`goal_mode: true` on `superagent_start` or `superagent_schedule`) that
826
+ adds an independent acceptance step and keeps the run going until every
827
+ condition passes or a hard stop says a person has to decide.
828
+
829
+ - **Acceptance conditions.** `acceptance` is required and is a list of
830
+ `{id?, text, check?}`. A `check` of `{"type":"command","command":"npm test"}`
831
+ or `{"type":"file","path":"dist/app.js"}` is run by the plugin itself, so that
832
+ verdict rests on a real exit code or a real file, never on a model's claim. A
833
+ condition without a check is judged by a separate acceptance model, and
834
+ `superagent_status` names the source of every verdict. At most 12 conditions
835
+ are accepted; a longer list is a badly framed goal, not a checklist.
836
+ - **Rounds.** A failed round does not repeat the same work: the next round's
837
+ plan receives what failed and why. `max_rounds` (default 5, max 20),
838
+ `max_wall_clock_minutes` (default 60), and `no_progress_rounds` (default 2)
839
+ bound it. When the acceptance has a machine check, a round that changed no
840
+ file stops immediately instead of paying for another one.
841
+ - **Hard stops.** The loop stops with a reason instead of looping forever: the
842
+ round cap, the wall clock, the run deadline, a budget stop, an open attention
843
+ item, two identical failing rounds, or a round that cannot make progress.
844
+ The stop report lists every condition with its last result and what was tried.
845
+ - **Notifications.** One notification when the goal is met or the loop stops —
846
+ none between rounds. The run record, status line, and report all carry the
847
+ round count and each condition's verdict.
848
+
849
+ Goal mode is off by default, adds no tool of its own, and changes nothing about
850
+ a run that does not pass `goal_mode: true`.
851
+
852
+ ## Scheduled runs
853
+
854
+ `superagent_schedule` stores a plan — a goal plus a clock — and starts it
855
+ without anyone calling `superagent_start`. A scheduled run is an ordinary run:
856
+ same planner, same quota, same budgets, cancel, usage accounting, report, and
857
+ status. The scheduler is only a timer-shaped caller of the orchestrator, not a
858
+ second run engine.
859
+
860
+ ```text
861
+ superagent_schedule(action: "create", name: "nightly audit",
862
+ goal: "Audit yesterday's error logs and list anything new",
863
+ cron: "0 3 * * *", timezone: "Asia/Shanghai",
864
+ budget: { max_total_runs: 30, max_total_tokens: 5000000 })
865
+ ```
866
+
867
+ Actions are `create`, `list`, `pause`, `resume`, `delete`, and `run-now`.
868
+ `run-now` starts one execution immediately without moving the next planned
869
+ window. A plan may name a `template_id` and `params` instead of a literal
870
+ `goal`; the template is expanded at create time, so editing the template later
871
+ does not silently change an existing plan.
872
+
873
+ A plan stores its clock (`cron` or `every_minutes`, plus `timezone`), the goal,
874
+ an optional `mode` / `goal_mode` with acceptance, its own `budget`, and its
875
+ `human_priority`. Plans persist to `schedules.json` in the state directory and
876
+ are reloaded at mount, so a host restart keeps them. The timer starts only when
877
+ at least one plan exists; the state file is not created by `init()` on an empty
878
+ state directory.
879
+
880
+ ### Missed windows
881
+
882
+ A window that comes due while the host is down is **not** replayed in full. The
883
+ default policy, `miss_policy: "latest"`, runs only the newest missed window and
884
+ records every other due window as `missed` with its scheduled time and the
885
+ reason (the host was not running at that time); the plan then advances to its
886
+ next window on the normal grid. The run that executes that newest window is a
887
+ catch-up, and the plan says so: `totalRuns` counts it, `catchUpRuns` counts how
888
+ many runs were catch-ups, and the `started` history entry names the window and
889
+ the number of missed windows it stands in for. `miss_policy: "none"` skips all
890
+ due windows while the host was down, records the count, and resumes at the next
891
+ scheduled window. Catch-up work is bounded, so a laptop that was off for a month
892
+ does not queue thousands of runs.
893
+
894
+ The counters are separate on purpose: `missedRuns` is how many windows never
895
+ ran, `catchUpRuns` is how many ran late, and `skippedRuns` is how many were
896
+ passed over because the previous run was still active. `list` prints all three.
897
+
898
+ A plan also never overlaps itself: if the previous execution is still active
899
+ when a new window comes due, that window is not started and is recorded as
900
+ `skipped: previous run still active`. The next window is evaluated normally.
901
+
902
+ ### Completion requires an artifact
903
+
904
+ A worker ending its turn with `completed` is not, by itself, a completed
905
+ subtask. When a subtask declares `deliverables` (file paths, relative to its
906
+ working directory), every listed file must exist, be a file, and be non-empty
907
+ before the subtask counts. With no file declared, the reply text is the
908
+ artifact, so an empty or whitespace-only reply is rejected with
909
+ `empty deliverable: ...` and the subtask is retried or failed like any other
910
+ incomplete attempt. A run whose report strips down to nothing is recorded as
911
+ `partial`, never `completed`, so a schedule cannot report success for an empty
912
+ result.
913
+
914
+ ### Quota and manual priority
915
+
916
+ Scheduled runs share `maxActiveRuns` with manual runs. With
917
+ `human_priority: true` (the default, also configurable with
918
+ `schedulerHumanPriority`), a scheduled run may not occupy the last free slot:
919
+ when only one slot is free it waits for the next tick instead of blocking a
920
+ `superagent_start`. A scheduled run also never enters the queue, so a person's
921
+ `superagent_start(..., queue: true)` is never pushed back by a timer. When the
922
+ cap is reached, the due window stays due and is retried on a later tick,
923
+ without spending anything.
924
+
925
+ ### Budget and failures
926
+
927
+ `budget.max_model_calls` / `max_tokens` cap one execution;
928
+ `budget.max_total_model_calls` / `max_total_tokens` / `max_total_runs` cap the
929
+ plan across executions. Reaching a plan total pauses the plan and records the
930
+ reason on the plan and in its run report; reaching a per-run cap ends that
931
+ execution the same way a manual run ends.
932
+
933
+ A failed execution does not notify on every retry. The first failure is
934
+ reported once, and `schedulerMaxConsecutiveFailures` (default 3) consecutive
935
+ failures pause the plan and report that once. A success resets the counter.
936
+ Notifications are otherwise limited to: the goal was achieved, the budget was
937
+ reached, or a run needs a decision. Milestones and ordinary progress stay in
938
+ `list` / `status` and never wake the session.
939
+
940
+ ### Cron support
941
+
942
+ Cron parsing is built in and has no dependency. Supported: the standard five
943
+ fields (minute hour day-of-month month day-of-week), `*`, `*/n`, ranges
944
+ (`1-5`), lists (`1,15,30`), month and weekday names (`JAN`, `MON-FRI`), and `0`
945
+ or `7` for Sunday. Day-of-month and day-of-week together are OR-ed, as in
946
+ classic cron.
947
+
948
+ Not supported, and refused at create time with the offending field number:
949
+ seconds, a year field, `@daily`-style macros, and the `L`, `W`, `#`, and `?`
950
+ extensions. An expression with six fields is rejected as “field 1 is not a
951
+ minute” rather than being reinterpreted. Time zones use IANA names and are
952
+ evaluated in the zone the expression was written in, never the host's zone; a
953
+ time that does not exist at the spring DST jump is skipped, and an ambiguous
954
+ autumn time uses the earlier offset.
955
+
956
+ ### What a plan needs from the host
957
+
958
+ Each plan is owned by the session that created it (or an explicit
959
+ `session_id`), and that owner is resolved **on every window**, not captured once.
960
+ If the session is live, it is used as is. After a host restart the plugin asks
961
+ the host to resume the persisted session (`agents.resume`, or the Host Session
962
+ API where that is the available surface); if the session was deleted, it creates
963
+ a replacement and the plan adopts the new id (recorded as `owner-recovered`). A
964
+ plan therefore survives a restart without depending on the original process or
965
+ conversation staying open.
966
+
967
+ When the host exposes no way to resume or create a session at all, that limit is
968
+ recorded at `create` time instead of being discovered as a pause. The response
969
+ carries a warning and the plan is marked `requires a resident session`; when a
970
+ window finds no live owner it is recorded as `blocked`, announced once, and the
971
+ plan stays enabled. It is not silently paused after three windows.
972
+
973
+ Nothing runs and nothing is written until the first `create`. An installation
974
+ with no plans behaves exactly as it did before this tool existed.
975
+
976
+ ## Progress, decisions, and artifacts
977
+
978
+ - **Plan honesty.** Before a worker starts, the planner names what it cannot map
979
+ to a concrete object: an ambiguous phrase goes into `ambiguities`, and a
980
+ question only the user can answer goes into `needsInput`, so the run stops and
981
+ asks instead of inventing a name that looks plausible. Each assumption the
982
+ planner does make is recorded on that subtask (`assumptions`) and printed in
983
+ status and in the report, so a guess is visible instead of silent. A plan
984
+ whose questions arrive together is one decision point, not a drip of prompts.
985
+ - **Capability preflight.** A subtask may declare `requires` (`shell`,
986
+ `net.http`, `browser`, `gui`, `desktop`, `git`, `gh`). The host compares that
987
+ list with the tools this session actually has before any worker is spawned.
988
+ A subtask whose capability is missing is `blocked`, with the capability and
989
+ what would enable it named; it never starts and is never counted as success,
990
+ and everything downstream of it is skipped for that reason. When the host
991
+ cannot list its tools, preflight records `unavailable` and blocks nothing
992
+ rather than guessing an inventory.
993
+ - **Milestones.** Every run records `plan_ready`, `running`, `aggregating`, and
994
+ `settled` with a timestamp, shown in `superagent_status`. They never produce a
995
+ proactive message; progress stays visible without becoming noisy.
996
+ - **Attention.** A worker or the aggregator may append one fenced `attention`
997
+ block with a question that only the user can answer. It is stripped from the
998
+ report, stored on the run as `attention.items`, shown as `needs your decision:`
999
+ in status, and leads the notification when the run finishes. Every item gets a
1000
+ stable id (`q1`, `q2`, …) from a counter on the run, so a question means the
1001
+ same thing across saves and resumes. The question, options, and reason are
1002
+ collapsed to one line and capped at 500 / 200 / 300 characters, so the block
1003
+ cannot inject a forged status or notification line. A block that is not valid
1004
+ JSON or has no question is kept in the report, and status prints
1005
+ `attention: <reason>` instead of hiding the request.
1006
+ - **Answering.** `superagent_answer` records the decision on that item and lets
1007
+ the run continue: an active run carries it into its next prompt, a terminal
1008
+ run is reopened so the aggregation runs again with the answer. The question is
1009
+ archived (not deleted) when a resume retires it, which is what lets a late
1010
+ answer be refused with `expired at <time>` instead of being attached to
1011
+ whatever is open now.
1012
+ - **Instructions during a run.** Two boundaries, kept distinct.
1013
+ `superagent_followup` appends to the dialog log and is carried by the next
1014
+ prompt built for the run: each instruction records `appliedAt` /
1015
+ `appliedAtStage` when a prompt first carries it, or `missedAt` when the run
1016
+ settled first. `superagent_inject` instead steers a live child's inbox and is
1017
+ claimed at its next pre-step; its receipt records `latencyMs` measured from
1018
+ acceptance to that claim, or `missedReason` when the child left first. Status
1019
+ prints both, so a queued instruction and a live one are never confused.
1020
+ - **Report file.** A terminal run writes its report to
1021
+ `<stateDir>/reports/<runId>.md` with an atomic rename, so the outcome has a
1022
+ path that can be opened or attached. The directory carries a `.gitignore` with
1023
+ `*`, and the path is recorded in `run.artifacts` and shown in status.
1024
+ - **Dependencies between subtasks.** The planner may give a subtask an id and a
1025
+ `dependsOn` list; the dependent then waits (`waiting`) instead of starting,
1026
+ and its prompt carries the finished dependency's report. Independent subtasks
1027
+ still run in parallel. An unknown reference is `skipped` with the reason, a
1028
+ failure skips everything downstream rather than reporting it as done, and a
1029
+ cycle rejects the plan before any subtask starts. Status and the report show
1030
+ waiting separately from running.
1031
+
1032
+ ## Permissions and audit
1033
+
1034
+ Two independent layers sit around a run. A **policy** decides whether an action
1035
+ may happen; an **audit trail** records what was decided and what followed. The
1036
+ trail is on by default because it only observes. A policy changes nothing until
1037
+ one exists, and it can only tighten what the plugin does on its own.
1038
+
1039
+ ### Policy
1040
+
1041
+ Copy [docs/policy.example.json](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/policy.example.json) to
1042
+ `<stateDir>/policy.json`, or name another file with `policyFile`. Rules are
1043
+ matched in this order:
1044
+
1045
+ 1. a `paths.deny` / `commands.deny` pattern -> `deny` (deny always wins);
1046
+ 2. an explicit `paths.allow` / `commands.allow` entry -> `allow`;
1047
+ 3. the action kind listed under `confirm.actions` -> `confirm`;
1048
+ 4. the run's `runs.<id>.level`, else `defaultLevel`.
1049
+
1050
+ An allow entry that beats a `confirm` or a per-run `deny` is recorded with
1051
+ `meta.relaxedFrom`, so a person can always see where the policy was opened up.
1052
+ Relative path patterns match at any directory boundary (`src/**` covers
1053
+ `/anywhere/repo/src/a.js`) but not a sibling that merely ends the same way
1054
+ (`xsrc/a.js`). A command entry without `*` is a prefix on whole tokens
1055
+ (`git status` permits `git status --short`, not `git statusx`); a composite line
1056
+ (`git status && curl ...`) can never be lifted above `confirm` by a prefix.
1057
+
1058
+ `policy.json` may contain `//`, `#`, and `/* */` comments. A schema problem is
1059
+ reported with the file, line, and column:
1060
+
1061
+ ```
1062
+ policy.json: 1 problem in the permission policy
1063
+ policy.json:3:19 [defaultLevel] must be one of allow | confirm | deny
1064
+ "defaultLevel": "maybe",
1065
+ ^
1066
+ ```
1067
+
1068
+ An unreadable or invalid policy **fails closed**: governed actions are denied and
1069
+ `superagent_audit` prints the problem. A start or resume that is denied is
1070
+ refused before any state changes; one held for `confirm` needs
1071
+ `approve_policy: true` on the next call, and that approval is written as an
1072
+ `approved` event naming the held event. An approval cannot release a `deny`.
1073
+
1074
+ ### Audit
1075
+
1076
+ `<stateDir>/audit/audit.jsonl`, one JSON object per event:
1077
+
1078
+ ```json
1079
+ {"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":"..."}}
1080
+ ```
1081
+
1082
+ Every event carries the run, the subtask, the actor, a timestamp, the decision,
1083
+ the result, and how long the check took. Higher layers may add `tool.call` and
1084
+ `command.exec` events. Triggered by the plugin itself: `run.start`, `run.resume`,
1085
+ `run.cancel`, `run.finish`, `attention`, plus `blocked` when a policy denies and
1086
+ `approved` when a person releases a held action.
1087
+
1088
+ Appends are serialized inside the process and guarded by a `wx` lock file across
1089
+ processes, and each event is written with one append, so two workers finishing at
1090
+ the same moment cannot splice a line. A trailing fragment left by a crash is
1091
+ reported as `torn` and skipped; a damaged line is counted as `invalid` and does
1092
+ not hide the rest.
1093
+
1094
+ `superagent_audit` reads by run, subtask, kind, decision, result, target text, and
1095
+ time window. With `format: "jsonl"` or `format: "csv"` it writes one deliverable
1096
+ file (default `<stateDir>/audit/audit-export-<time>.<ext>`) and returns its path.
1097
+
1098
+ A path/command guard can be attached without the audit layer knowing its rules:
1099
+ `createAuditor({ dir, policyFile }).attachGuard(request => ({ decision, reason }))`.
1100
+ The guard may only tighten the decision the policy produced; a guard that throws
1101
+ is treated as a block. A guard that answers `{ blocked, rule, reason }` — the
1102
+ shape a tool-call guard already produces — is understood as well.
1103
+
1104
+ ## Cross-run memory
1105
+
1106
+ A run is isolated on purpose: planner and workers start empty. Without a
1107
+ notebook, every run repeats work the last one already finished and rediscovers
1108
+ the same traps. The plugin keeps two different things, and only one of them is
1109
+ stored:
1110
+
1111
+ 1. **What happened** is derived from the run store at planning time. The six
1112
+ most recent runs are rendered as one line each (date, status, completed
1113
+ subtasks, goal, run id). Nothing is copied, so it cannot drift from the run
1114
+ records.
1115
+ 2. **What was learned** is a small curated notebook: decisions, pitfalls, next
1116
+ steps, and which work was delegated. The aggregator returns it inside a
1117
+ fenced `memory` block that is removed from the report before the user sees it.
1118
+ A run that produces no block writes nothing; the plugin never invents a note.
1119
+
1120
+ **Storage.** `<stateDir>/memory/<scope>.jsonl`, one JSON object per line. A line
1121
+ is `{v,id,ts,key,kind,text,runId,status}`; `key` is a short slug (`deploy-target`)
1122
+ and `kind` is `decision`, `pitfall`, `next`, `dispatch`, or `note`. The directory
1123
+ contains a `.gitignore` with `*`, so even a `stateDir` that points inside a
1124
+ repository cannot commit the notebook. It is never listed in the package `files`
1125
+ whitelist, so it never ships to npm.
1126
+
1127
+ **When it is written.** Once per run, at settle, only for a terminal run whose
1128
+ report carried a block. A resume that settles the same run again is a no-op
1129
+ because the store records the writing run id. A write failure is recorded on the
1130
+ run (`memoryWrite.reason`) and never fails the run.
1131
+
1132
+ **When it is read.** Once at `superagent_start` (and again at `superagent_resume`,
1133
+ since the aggregator will run again), before planning. The composed context is
1134
+ stored on the run as `memory.digest`, injected into the planner and aggregator
1135
+ prompts, and summarised in `superagent_status`.
1136
+
1137
+ **Layers.** Three scopes are read, in order: `rules` (project rules), `profile`
1138
+ (user preferences), then `memoryScope` (what earlier runs learned). The first
1139
+ two are curated with `superagent_memory` and are never written by a run, so a
1140
+ rule cannot be overwritten by a model's observation. Each layer is labelled in
1141
+ the prompt and bounded on its own; `memory.scopes` on the run lists what was
1142
+ read.
1143
+
1144
+ **Size.** Each note is capped at 400 characters after redaction. A prompt sees at
1145
+ most `memoryDigestEntries` notes inside `memoryDigestChars` characters, plus six
1146
+ one-line run summaries, hard-capped at 2600 characters in total. The file is
1147
+ compacted when a write would push it past `memoryMaxEntries` notes, 400 lines,
1148
+ or 128 KB; compaction keeps the newest `memoryMaxEntries` notes.
1149
+ Context cannot grow with the number of runs.
1150
+
1151
+ **Concurrency.** Within a process, writes to one scope are serialised. Across
1152
+ processes, each batch is appended as one small `write` (no read-modify-write of
1153
+ the whole file), compaction takes a lock file and replaces the file from a temp
1154
+ file, and a truncated last line from a killed process is skipped. Two runs
1155
+ finishing at once cannot overwrite each other's notes; a line may land in a
1156
+ different order, and resolution is by timestamp, never by position.
1157
+
1158
+ **Search.** `superagent_memory` with `action: "search"` ranks notes by `query`
1159
+ keywords and exact `tags` instead of returning the newest ones, and the planner
1160
+ digest uses the same ranking against the run's goal. A relevant note from weeks
1161
+ ago therefore still reaches the prompt when it matches, while unrelated notes do
1162
+ not crowd out the budget. Notes can carry `tags` when set.
1163
+
1164
+ **Correction.** A newer note with the same key supersedes the old one. An
1165
+ explicit `forget` writes a tombstone. Notes older than `memoryMaxAgeDays` stop
1166
+ being injected and are dropped at the next compaction. Every note is shown with
1167
+ its age and the digest tells the model the notes may be stale and must be
1168
+ verified, so a wrong conclusion can be refuted by a later run instead of
1169
+ becoming a permanent bias.
1170
+
1171
+ **Privacy.** Notes are written outside the repository by default
1172
+ (`$DSH_HOME/state/superagent/memory`). Before storage, the plugin redacts API-key
1173
+ shapes (`sk-…`, `Bearer …`, `ghp_…`, `AKIA…`), long hex/base64 blobs, email
1174
+ addresses, and absolute home paths; it collapses a note to one line and caps it.
1175
+ The aggregator is instructed not to record secrets, customer data, or the report
1176
+ itself. A `stateDir` inside the installed package disables memory rather than
1177
+ risk shipping it. If you point `stateDir` at a repository, the nested
1178
+ `.gitignore` still keeps the files out of a default `git add`.
1179
+
1180
+ ### User profile
1181
+
1182
+ The notebook above answers "what did the last run learn about this task". A
1183
+ second, optional store answers a different question — "who is this person, what
1184
+ do they want, and why did we choose that before" — and it has to outlive
1185
+ unrelated tasks, so it is kept apart and read apart. It is off by default
1186
+ (`memoryUserProfile: false`): nothing is constructed, no directory is created,
1187
+ and the run notebook behaves exactly as before.
1188
+
1189
+ - **Three categories, three files.** `fact` (durable technical context such as
1190
+ the stack or the environment), `preference` (how the user wants work done),
1191
+ and `decision` (the choice, what was rejected, why, and how to undo it).
1192
+ A search opens one category file, so a fact can never come back as a
1193
+ preference just because the words match.
1194
+ - **A decision needs its reason.** A decision without a rationale teaches the
1195
+ next run nothing, so the reason is part of the record and part of every digest
1196
+ line; a bare "chose X" is refused.
1197
+ - **Reading and writing.** `superagent_memory` with `layer: "user"` and a
1198
+ `category` lists, searches, adds, corrects, or forgets profile records. The
1199
+ planner prompt gets a short digest of the matching records, labelled by
1200
+ category, under the same character budget as the notebook.
1201
+ - **Forgetting is deletion.** The matching lines are removed under a lock and the
1202
+ file is replaced, with no tombstone that a later search could leak the value
1203
+ back through. A forget must name a key, a run id, or a time range, so a bare
1204
+ "forget everything" cannot wipe the profile by accident.
1205
+ - **Privacy.** Every record is redacted before it is written: credentials,
1206
+ emails, phone numbers, and usernames inside home paths. The profile lives
1207
+ under `<stateDir>/user-memory` with the same nested `.gitignore` as the
1208
+ notebook, and is never in the package `files` whitelist.
1209
+
1210
+ ## Watch and report
1211
+
1212
+ ![Run report preview](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-preview.jpg?raw=true)
1213
+
1214
+ _Top of a report rendered from 40 real host runs. The full page — timeline,
1215
+ swimlanes, call and cost curves, failure annotations, run table — is
1216
+ [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)._
1217
+
1218
+ Five operator utilities ship with the package, need no session, and add no
1219
+ runtime dependency. `watch`, `report`, `archive`, and `sync` read the same
1220
+ durable run files as the tools; `doctor` inspects the install itself.
1221
+
1222
+ Run them from the installed copy inside the profile:
1223
+
1224
+ ```bash
1225
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
1226
+ node "$PKG/bin/watch.js" # live panel, Ctrl-C to stop
1227
+ node "$PKG/bin/report.js" --out report.html # self-contained HTML page
1228
+ ```
1229
+
1230
+ If the profile's linker created bin links (npm does), the same commands are
1231
+ `node_modules/.bin/dsh-superagent-watch`, `node_modules/.bin/dsh-superagent-report`,
1232
+ and `node_modules/.bin/dsh-superagent-doctor`.
1233
+
1234
+ `watch`, `report`, and `archive` all accept `--state-dir <path>`; it defaults to
1235
+ `$DSH_HOME/state/superagent`. Pass it when the plugin config sets a custom
1236
+ `stateDir`.
1237
+
1238
+ **`watch`** draws one line per run — id, status, calls used against the cap,
1239
+ elapsed time, what it is doing right now, and the parent session — in the
1240
+ alternate screen, and restores the cursor on Ctrl-C, SIGTERM, or a closed pipe.
1241
+ A status change repaints immediately; an idle panel reads one small file per
1242
+ second. Runs alive at the same moment share a numbered gutter, so parallel work
1243
+ is visible as a group instead of unrelated rows. A waiting row leads with the
1244
+ run holding its slot, then the queue position, because a narrow cell clips from
1245
+ the right and the holder is the actionable part. `--once` prints a single plain
1246
+ frame, which is what
1247
+ [docs/e2e/transcripts/watch-panel.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/watch-panel.log)
1248
+ captures from 40 real runs.
1249
+
1250
+ **`report`** renders recorded runs into one HTML file: inline CSS, inline SVG,
1251
+ no script, no font, no image, no network. It has a timeline with each run's
1252
+ start, end, and derived planning/work/merge phases; a swimlane chart whose lane
1253
+ count is the peak concurrency; cumulative model-call and cost curves; explicit
1254
+ failure, cancellation, and interruption annotations; and a run table. Each
1255
+ worker's retry chain and its share of the run's wall clock are listed next to
1256
+ its outcome, so an expensive flaky subtask is visible instead of only its final
1257
+ failure.
1258
+ [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)
1259
+ is the 40-run report from the host e2e — open it directly, nothing is fetched —
1260
+ and
1261
+ [docs/e2e/transcripts/report-cli.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/report-cli.log)
1262
+ records the command plus a zero-external-reference audit.
1263
+
1264
+ **`doctor`** answers "it installed, why does nothing work?" before the host
1265
+ does. It reads only: no install, no mount, no edit to the profile. One block per
1266
+ check — imported files against the `files` whitelist, declared files against
1267
+ what is on disk, the installed copy against the published tarball for its
1268
+ version, the profile's bundle registration, and the twelve registered tools — each
1269
+ failure followed by the command that fixes it.
1270
+
1271
+ ```bash
1272
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
1273
+ node "$PKG/bin/doctor.js" --profile web
1274
+ node "$PKG/bin/doctor.js" --profile web --offline # skip the registry hash check
1275
+ ```
1276
+
1277
+ Exit code is `0` when no check fails, `1` when one does, so it can gate a
1278
+ deploy. `npm test` runs the same pack guard as
1279
+ [`scripts/check-pack.mjs`](scripts/check-pack.mjs): every file reachable from
1280
+ the entry points must appear in `npm pack --dry-run`, which is the check the
1281
+ 0.9.x release lacked.
1282
+
1283
+ None of these utilities is the install path: the plugin is installed with
1284
+ `dsh plugin add`, never with `npm i -g`.
1285
+
1286
+ **`archive`** is the fourth utility. It prunes terminal runs and exports or
1287
+ imports one run as a self-contained archive; see [Retention](#retention) and
1288
+ [Archives](#archives).
1289
+ ## Syncing one state directory across machines
1290
+
1291
+ There is no server and no account. The state directory is a directory of files,
1292
+ so a git remote can carry it: `dsh-superagent-sync` makes that directory a
1293
+ repository, keeps the machine-local files out, and gives you `pull`, `push`, and
1294
+ `status`. `git` is the only requirement — the command has no dependency of its
1295
+ own.
1296
+
1297
+ ```bash
1298
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
1299
+ node "$PKG/bin/sync.js" init git@github.com:me/superagent-state.git # once per machine
1300
+ node "$PKG/bin/sync.js" push # after runs finish
1301
+ node "$PKG/bin/sync.js" pull # before starting work
1302
+ node "$PKG/bin/sync.js" status
1303
+ ```
1304
+
1305
+ Or `node_modules/.bin/dsh-superagent-sync`. All four accept `--state-dir
1306
+ <path>` (default `$DSH_HOME/state/superagent`), and `--json` prints the raw
1307
+ result.
1308
+
1309
+ **`init <remote>`** creates the repository, writes a managed block into
1310
+ `.gitignore`, sets `origin`, and makes the first commit. Re-running it refreshes
1311
+ the remote URL and that block without touching entries you added yourself. A
1312
+ machine with no `~/.gitconfig` gets a repository-local commit identity, so the
1313
+ first commit cannot fail on that alone.
1314
+
1315
+ **`pull`** fetches `origin`, then merges. Uncommitted local changes are stashed
1316
+ first (`stash@{0}`, subject `dsh-sync auto-stash …`) and reapplied after the
1317
+ merge, so a pull never silently overwrites an edit. A conflict stops the merge
1318
+ with both sides still in the files: the paths are printed, nothing is chosen,
1319
+ and the stash is left unapplied with a line saying so.
1320
+
1321
+ **`push`** commits everything and pushes the current branch, setting its
1322
+ upstream on the first push. A rejected push is reported, not forced and not
1323
+ auto-merged: run `pull`, resolve what it reports, then push again.
1324
+
1325
+ **`status`** prints ahead/behind counts, uncommitted files, stashes, and the
1326
+ conflicted paths waiting for a decision.
1327
+
1328
+ ### What never leaves the machine
1329
+
1330
+ `.owner`, `control.json` (a bearer token), `notifications.json`, `*.lock`,
1331
+ `*.cancel`, `*.corrupt-*`, `*.tmp`, `*.log`, and `.env` / key material. The
1332
+ notebook is the one exception worth knowing: `memory/.gitignore` normally holds
1333
+ a bare `*`, which would keep every note local, so `init` rewrites that one
1334
+ default to allow `<scope>.jsonl`. A file you customized is left alone.
1335
+
1336
+ ### When it conflicts
1337
+
1338
+ Run records are one file per run (`runs/<runId>.json`), so ordinary concurrent
1339
+ work on two machines — different runs — never touches the same path. A conflict
1340
+ needs one of these:
1341
+
1342
+ - the same run id written on both machines: a resume or cancel on the second
1343
+ machine before pulling the first machine's state;
1344
+ - the same memory scope appended to on both machines (`memory/<scope>.jsonl` is
1345
+ append-only, and two different tails collide);
1346
+ - the same `reports/<runId>.md` regenerated with different content;
1347
+ - `.gitignore` edited by hand on both machines.
1348
+
1349
+ While a run file still contains conflict markers it is not valid JSON, and the
1350
+ plugin quarantines it at mount as `<runId>.json.corrupt-<ts>`. Resolve it before
1351
+ starting the host: keep the side you want, `git add` it, `git commit`.
1352
+
1353
+ ### Why this is approximate
1354
+
1355
+ - Two machines writing at the same moment can conflict. The merge stops and you
1356
+ decide; nothing is merged behind your back.
1357
+ - There is no live sync and no cross-machine lock. A machine sees another
1358
+ machine's run only after `pull`, and `push` does not know what the other
1359
+ machine is doing right now. Run one host per state directory at a time.
1360
+ - Keys are not distributed: each machine still needs its own model credential.
1361
+ - `keepRuns` pruning deletes files, and a deletion reaches the other machine
1362
+ only on the next `pull`.
1363
+
1364
+ ## Embedding over local HTTP
1365
+
1366
+ The tools require a session. If another UI or script must start and watch runs
1367
+ without importing this package, set `controlPort`:
1368
+
1369
+ ```yaml
1370
+ - id: superagent
1371
+ config:
1372
+ controlPort: 0 # off by default; 0 = OS picks a free loopback port
1373
+ ```
1374
+
1375
+ The plugin then writes `<stateDir>/control.json` with the bound URL and a
1376
+ per-process bearer token (mode `0600`) and serves `GET /`, `GET /health`,
1377
+ `GET /runs`, `GET /runs/:id`, `POST /runs`, `POST /runs/:id/cancel`, and
1378
+ `POST /runs/:id/resume` on `127.0.0.1` only. Every reply carries the same text
1379
+ the tool would print (the route index and `/health` are the two exceptions:
1380
+ they describe the socket, not a run). Every run goes through the same quota,
1381
+ budgets, locks, and recovery as a tool-started run. `POST /runs` requires
1382
+ `session_id` of a session that is live in that host — a run needs a real parent
1383
+ agent for its children.
1384
+
1385
+ ```bash
1386
+ STATE="${DSH_HOME:-$HOME/.dsh}/state/superagent"
1387
+ URL=$(node -e "console.log(require('$STATE/control.json').url)")
1388
+ TOKEN=$(node -e "console.log(require('$STATE/control.json').token)")
1389
+ curl -s -H "Authorization: Bearer $TOKEN" "$URL/runs"
1390
+ ```
1391
+
1392
+ The full contract — routes, error ids, security model, lifecycle, client
1393
+ examples — is [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md). It is opt-in, loopback
1394
+ only, and there is no remote or unauthenticated mode.
1395
+
1396
+ ## Conversation console
1397
+
1398
+ `consolePort` adds a local page where you talk to a **real Host Session**, not a
1399
+ mock chat and not a re-skinned `superagent_start(goal)` form:
1400
+
1401
+ ```yaml
1402
+ - id: superagent
1403
+ config:
1404
+ consolePort: 0 # off by default; 0 = OS picks a free loopback port
1405
+ consoleRoot: /path/to/project
1406
+ ```
1407
+
1408
+ The plugin creates the session with the host's `sessionController.create()`,
1409
+ sends each message with `prompt({ mode: 'queue' | 'steer' })`, and forwards
1410
+ `follow({ assistantStream: true })` plus `observeState()` to the page. Follow-up
1411
+ messages therefore continue the same conversation; they are not a new session.
1412
+ The right-hand column lists the runs whose `parentSessionId` is that session, so
1413
+ the page shows exactly the subtasks the conversation derived. An attention card
1414
+ answers through `orchestrator.answer`, the same path as the
1415
+ `superagent_answer` tool, with the conversation agent as the run owner.
1416
+
1417
+ The bound URL and a fresh per-process token are written to
1418
+ `<stateDir>/console.json` (mode `0600`). Open
1419
+ `http://127.0.0.1:<port>/?token=<token>` once; the page stores the token in
1420
+ `sessionStorage` and removes it from the address bar. Every route, including
1421
+ the event stream, answers `401` without it, and every request with a non-loopback
1422
+ `Host` header answers `403`.
1423
+
1424
+ If the host does not mount `sessionController` (for example a headless profile
1425
+ without the web session API), the page says so and refuses to create a session.
1426
+ It does **not** pretend to be a chat. The console also keeps one active
1427
+ conversation per process; "新对话" creates a new Host Session and leaves the old
1428
+ one intact. Approval prompts that appear as host `pendingInput` are surfaced in
1429
+ the status line but are not answered by this page; only run attention questions
1430
+ are.
1431
+
1432
+ ### Tools the conversation gets
1433
+
1434
+ The console session is created with no tool list of its own: it mounts whatever
1435
+ the host's agent preset mounts, which is the same set the Web app's own
1436
+ sessions get. The plugin registers no conversation tools and filters none; the
1437
+ only filter it can apply is the opt-in `guard` for child agent calls. To see the
1438
+ real list, the page asks the host for `ctx.tools.definitions(agent)` and shows
1439
+ it under "这个会话挂载的工具"; when the host cannot enumerate, the page says so
1440
+ instead of printing a fixed list. `consolePreset` passes `agentPreset` to
1441
+ `sessionController.create()` when you want a preset other than the profile
1442
+ default.
1443
+
1444
+ Browser and desktop control are not implemented here. They come from
1445
+ `feat/runtime-control`, which registers host-scope `browser_*` and `desktop_*`
1446
+ tools; those are visible to the console session like any other host tool. On a
1447
+ build without that branch the page reports them as "未挂载". Neither branch ships a 3D tool; when
1448
+ the preset includes `bash` or `pwsh`, a headless Blender can be driven through
1449
+ it (`blender --background --python`), which is the scriptable path the console
1450
+ can already reach.
1451
+
1452
+ ## Workspace panel
1453
+
1454
+ `workbenchPort` adds a local, IDE-shaped panel over one directory. It has its
1455
+ own file tree, editor, diff preview, and run change view; nothing is proxied
1456
+ through the host.
1457
+
1458
+ ```bash
1459
+ npx dsh-superagent-workbench --root /path/to/project --port 8787
1460
+ ```
1461
+
1462
+ The same server can run inside the host, with its Runs view wired to the plugin
1463
+ state directory:
1464
+
1465
+ ```yaml
1466
+ - id: superagent
1467
+ config:
1468
+ workbenchPort: 0 # off by default; 0 = OS picks a free loopback port
1469
+ workbenchRoot: /path/to/project
1470
+ ```
1471
+
1472
+ The standalone command serves the same page and defaults its run state to
1473
+ `<root>/.dsh-workbench`; pass `--state-dir <plugin state directory>` to read
1474
+ existing runs. Neither form opens a socket unless you ask for it.
1475
+
1476
+ The bound URL and a fresh per-process token are written to
1477
+ `<stateDir>/workbench.json` (mode `0600`). Open `http://127.0.0.1:<port>/?token=<token>`
1478
+ once; the page keeps the token in `sessionStorage` and strips it from the
1479
+ address bar. Without the token every route answers `401`.
1480
+
1481
+ The panel can list, read, and edit regular text files under `workbenchRoot`. It
1482
+ refuses absolute paths, `..` traversal, symlinks that leave the root, the plugin
1483
+ state directory, binary files, and files above 512 KB. Saving sends the hash and
1484
+ mtime the editor read; if either changed on disk, the save is refused with
1485
+ `external-change` instead of overwriting another process's work. Before a save
1486
+ is confirmed the page shows a unified diff.
1487
+
1488
+ When `workbenchPort` is on, the plugin records the files each run changed into
1489
+ that run's JSON record (`run.changes`), so the Runs view can show those files and
1490
+ their diff against `git HEAD` later.
1491
+
1492
+ ## State and recovery
1493
+
1494
+ One file per run: `$DSH_HOME/state/superagent/runs/<runId>.json`, written with a
1495
+ temp file plus rename, so a kill during a save cannot leave a half-written run.
1496
+ Statuses: `queued`, `planning`, `running`, `aggregating`, `completed`,
1497
+ `partial`, `failed`, `cancelled`, `interrupted`. A run that is waiting for a free
1498
+ slot also has `queued` as its status but carries `queue.waiting: true` with its
1499
+ position in line; it is not active and does not count against `maxActiveRuns`.
1500
+
1501
+ At mount the plugin marks a run as `interrupted` **only when it has no live
1502
+ owner** (see below) and resets its in-flight subtasks to `pending`.
1503
+ `superagent_resume` then re-runs only what did not finish. The planner's plan is
1504
+ reused, so a resumed run does not pay for planning twice.
1505
+
1506
+ A state directory can be shared by two profiles or two machines. Recovery
1507
+ therefore never decides from this process's memory alone: a run whose owner is
1508
+ still alive — fresh heartbeat, live local pid, or a live process holding its
1509
+ lock — is left untouched, cancel marker included. Two processes rewriting one
1510
+ run would make the surviving child keep spending while the file says
1511
+ `interrupted`, and a resume would then run the same subtasks twice.
1512
+
1513
+ Resuming is exclusive for the same reason. `superagent_resume` takes the same
1514
+ serial gate as `superagent_start`, claims `<runId>.lock` (created atomically),
1515
+ refuses a run that still has a live owner, and refuses a caller that is not the
1516
+ session in `parentSessionId`. It does not count against `maxActiveRuns`: a
1517
+ resume finishes work that already exists, so a full cap never blocks it. `force`
1518
+ (tool) or `force` / `override_quota` (HTTP) is still accepted for compatibility
1519
+ and changes nothing.
1520
+
1521
+ Three side files live next to the run:
1522
+
1523
+ | File | Meaning |
1524
+ | --- | --- |
1525
+ | `<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. |
1526
+ | `<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. |
1527
+ | `<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. |
1528
+ | `<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. |
1529
+
1530
+ If a run's file is damaged, nothing else breaks: other runs list normally, and
1531
+ starting a new run works. Inspect the `.corrupt-` file, then delete it. A file
1532
+ that cannot be read at all (permission, too many open files, disk full) is
1533
+ reported as such instead of being shown as an unknown run.
1534
+
1535
+ ### Orphaned runs and the active-run quota
1536
+
1537
+ A run counts against `maxActiveRuns` while its status is active. If the process
1538
+ owning it disappears without a restart, the run would otherwise hold that slot
1539
+ forever. Before every quota check the plugin looks for such runs and reclaims
1540
+ them, with two different rules:
1541
+
1542
+ - **The state directory belongs to this machine** (`.owner` holds our hostname):
1543
+ a dead local pid is enough on its own — that is direct evidence the process is
1544
+ gone, so the next mount reclaims immediately regardless of the heartbeat. A
1545
+ live pid vetoes reclamation even with a stale heartbeat, because a wedged
1546
+ process may still resume.
1547
+ - **The directory is shared, or its owner is unknown**: the pid may belong to
1548
+ another machine, so it is ignored and only the heartbeat decides; a run is
1549
+ reclaimed once its heartbeat is older than 90 seconds. This is the case for a
1550
+ state directory on a network share or a synced folder.
1551
+
1552
+ In both cases a lock held by a live local process also vetoes reclamation, and
1553
+ mount-time recovery uses exactly the same rules — a run is never rewritten
1554
+ while anybody can still be working on it.
1555
+
1556
+ Reclamation is never silent: the run becomes `interrupted`, its `reclaimed`
1557
+ field records the exact basis (`pid 1234 is not running and its heartbeat
1558
+ stopped at ...`, or `the state directory is shared with <host> ...`), the reason
1559
+ is printed by `superagent_status`, and one line goes to the host log. The subtasks
1560
+ that were mid-flight become `pending`, so `superagent_resume` continues the run.
1561
+
1562
+ The heartbeat is refreshed every 30 seconds by the owning process, so a healthy
1563
+ run is never mistaken for an orphan.
1564
+
1565
+ ### Talking to the user
1566
+
1567
+ The plugin is quiet unless the user must hear something. This is a rule in code,
1568
+ not only in this document:
1569
+
1570
+ - **Allowed to interrupt:** a run finished and delivered a result, a run failed,
1571
+ or a run stopped half-way (`partial`, `interrupted`). A run the user cancelled
1572
+ is never announced — the caller already knows.
1573
+ - **Never pushed:** progress, subtask start/finish, retries, and memory writes.
1574
+ They live in the run record, `superagent_status`, the watch panel, and the
1575
+ report page; the user can look, but nothing pops up.
1576
+ - **Self-heal first:** each subtask gets `attempts` tries, and a failure that
1577
+ looks transient (quota, rate limit, timeout, 5xx) gets `autoResumeRounds`
1578
+ more rounds, optionally on `childModelFallback`. Only what still fails is
1579
+ reported, and the message says what was tried.
1580
+ - **Bounded noise:** at most `maxNotificationsPerHour` proactive messages per
1581
+ hour. Runs above the cap are buffered and folded into the next message as one
1582
+ summary; `superagent_list` shows how many are waiting. If the message carrying
1583
+ a folded batch cannot be delivered, the batch stays buffered and rides the
1584
+ next one; it is dropped only after three failed deliveries.
1585
+ - **Do not ask what is known:** the planner and aggregator receive the notebook
1586
+ and are told to use it instead of asking the user for facts it already holds.
1587
+
1588
+ `notifyOnComplete` is the master switch. Two cases already report instead of
1589
+ notifying:
1590
+
1591
+ - a caller in the same host process was inside `superagent_status` and receives
1592
+ the terminal report itself (no message, to avoid duplicate noise). A poller in
1593
+ a *different* process does not suppress the message: it can time out just
1594
+ before the run ends, and then the only notification would be lost;
1595
+ - the owning session is gone (headless users who closed it): the run records
1596
+ `notify.delivered = false` with the reason, `superagent_status` prints
1597
+ `notify: not delivered — ...`, and `superagent_list` marks the row
1598
+ `(result not delivered to the session)`. The report is always readable with
1599
+ `superagent_status`.
1600
+
1601
+ Waking the session is bounded (15 s), and the heartbeat keeps running until the
1602
+ terminal state is written, so a slow wake-up cannot make another process treat a
1603
+ live run as orphaned.
1604
+
1605
+ ### Retention
1606
+
1607
+ Nothing is deleted by default. Set `keepRuns` to a number of days to delete
1608
+ terminal runs older than that at mount; active runs are never touched, the
1609
+ removed ids are logged, and the matching `reports/<runId>.md` artifact is
1610
+ removed with its run. `superagent_list` prints the current file count and size,
1611
+ so growth is visible before it becomes a problem.
1612
+
1613
+ To clean up on demand, `dsh-superagent-archive prune` plans first and deletes
1614
+ second:
1615
+
1616
+ ```bash
1617
+ node "$PKG/bin/archive.js" prune --older-than 30 # dry run
1618
+ node "$PKG/bin/archive.js" prune --older-than 30 --status failed # dry run, one status
1619
+ node "$PKG/bin/archive.js" prune --older-than 30 --confirm # delete
1620
+ ```
1621
+
1622
+ The plan prints each run id, status, finish time, and the bytes it holds; the
1623
+ summary gives the run, file, and byte totals. Without `--confirm` nothing is
1624
+ deleted. Only terminal runs (`completed`, `partial`, `failed`, `cancelled`,
1625
+ `interrupted`) are ever candidates: a run that is still active, or whose
1626
+ `.lock` is held by another process, is listed as skipped and left alone. A run
1627
+ inside the window, a run with no parsable timestamp, and a quarantined
1628
+ `*.corrupt-*` file are kept as well.
1629
+
1630
+ ## Archives
1631
+
1632
+ `archive export` turns one run into evidence another person can open offline —
1633
+ no host, no plugin, no network:
1634
+
1635
+ ```bash
1636
+ node "$PKG/bin/archive.js" export <run-id> --out ./run-archive # directory
1637
+ node "$PKG/bin/archive.js" export <run-id> --out ./run.html --format html # one page
1638
+ node "$PKG/bin/archive.js" export <run-id> --out ./run.json --format bundle
1639
+ ```
1640
+
1641
+ The directory contains `README.md` (summary, the merged report, a subtask
1642
+ table, and a file index), `report.md` (the report as markdown), `run.json` (the
1643
+ full durable record), `subtasks/` (one markdown page and one JSON file per
1644
+ subtask), `guards.json` / `guards.md` (every decision a worker or the
1645
+ aggregator stopped on), `usage.json` (token totals per child plus the cost the
1646
+ operator prices produce), and `manifest.json` (archive metadata, sizes, and a
1647
+ SHA-256 per file). `--format html` writes the same content as one self-contained
1648
+ page with the bundle embedded; `--format bundle` writes only that JSON.
1649
+
1650
+ `archive import <path>` reads any of the three back into the local store for
1651
+ review, restoring the run record and its report artifact. It never overwrites:
1652
+ when a local run has the same id, the command fails before writing anything and
1653
+ says so. An imported run is terminal, so it is listed and readable but never
1654
+ resumed.
1655
+
1656
+ ## Cancelling from another process
1657
+
1658
+ `superagent_cancel` works even when the run was started by a different host
1659
+ process (web and headless running side by side, or a second terminal). The
1660
+ crossing point is the `.cancel` marker file, not shared memory:
1661
+
1662
+ 1. the caller writes `<runId>.cancel`;
1663
+ 2. the owning process notices within a second, aborts its children' signal,
1664
+ disposes their activations, and writes `cancelled`;
1665
+ 3. the caller waits up to 5 seconds for that, then reports what happened.
1666
+
1667
+ If the owner does not answer in time, the reply says
1668
+ `cancel requested ... not confirmed` instead of `cancelled`. That means the
1669
+ owning process is gone or wedged; the marker stays on disk, and the next mount
1670
+ converts the run to `cancelled` during recovery. No socket, pipe, or Windows
1671
+ named pipe is involved, so this works the same on every platform and across a
1672
+ shared state directory.
1673
+
1674
+ Measured on the real host: with two workers sleeping inside a model call that
1675
+ ignores abort, `superagent_cancel` returned `cancelled` in **1.99 s** and the
1676
+ state file stopped accepting new spawns at that instant. The *host process*
1677
+ still took 22.8 s to exit, because it waits for its own child sessions; that
1678
+ wait is the host's teardown, outside the plugin's control. In an interactive
1679
+ session you never notice it; in a one-shot headless turn it is why cancel
1680
+ appears to "hang" until the ignored-abort child returns.
1681
+
1682
+ ## Troubleshooting
1683
+
1684
+ | What you see | What it means | What to do |
1685
+ | --- | --- | --- |
1686
+ | `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.2` and read the host log for `[dsh-superagent]` lines. |
1687
+ | `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. |
1688
+ | `[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`. |
1689
+ | `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. |
1690
+ | `[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. |
1691
+ | `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. |
1692
+ | `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. |
1693
+ | `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`. |
1694
+ | `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. |
1695
+ | `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. |
1696
+ | `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. |
1697
+ | `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. |
1698
+ | `cost: at least ... (no price for X)` | Some children used an unpriced model. | Same as above; the figure covers only the priced part. |
1699
+ | `[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. |
1700
+ | `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. |
1701
+ | `[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. |
1702
+ | `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. |
1703
+ | `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. |
1704
+ | `[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. |
1705
+
1706
+ A tool call that fails itself returns three lines: `[error]` a sentence, `hint:`
1707
+ one next step, and `detail:` the untouched host message, so nothing is hidden.
1708
+ A run that fails *after* it was accepted keeps its report and shows `error:`
1709
+ (plus a `hint:` line when it is `failed`) in the run block instead.
1710
+
1711
+ ## Known limits
1712
+
1713
+ - Children are not isolated by this plugin: they run with the host's
1714
+ credentials and filesystem, under whatever sandbox policy the host itself
1715
+ applies.
1716
+ - A run lives inside the host process. Killing the process stops its children;
1717
+ the run becomes `interrupted` on the next mount.
1718
+ - Cancelling from another process is cooperative: it relies on the owning
1719
+ process still running. A wedged process is only cleaned up at the next mount
1720
+ or when its heartbeat goes stale and the quota is reclaimed.
1721
+ - Planning is one model call. If the reply has no parsable
1722
+ `{"subtasks":[...]}` object, the run degrades to a single subtask and is
1723
+ marked `plan.mode = "degraded"`.
1724
+ - Aggregation is skipped for a single successful subtask (the report is that
1725
+ subtask's text under the goal heading) and falls back to a deterministic merge
1726
+ when the aggregator fails or the budget is exhausted.
1727
+ - Retention is opt-in (`keepRuns`); by default state accumulates, at up to
1728
+ 32 KB per subtask plus the report per run. `archive prune` removes terminal
1729
+ runs on demand, as a dry run unless `--confirm` is given.
1730
+ - The HTTP embedding surface is loopback-only, opt-in, and token-authenticated;
1731
+ it cannot be exposed remotely, and there is no MCP server. A local process
1732
+ running as the same user can read the token, which is the same trust boundary
1733
+ as writing run files.
1734
+ - Cross-machine sync is a git repository, not a service: it is offline-first,
1735
+ conflict-stop rather than conflict-free, has no realtime channel, and does
1736
+ not move credentials between machines. Two hosts actively writing one state
1737
+ directory on two machines still need a `pull` between them.
1738
+
1739
+ ## Naming
1740
+
1741
+ The package is published as `@xiangyixie/dsh-superagent` — npm already has a
1742
+ `dsh-super-agent` that is too close to the unscoped name, so the scope keeps
1743
+ the name instead of renaming the project. The tools are unchanged:
1744
+ `superagent_*` (with `superagent_memory` added in 0.10, additively). The earlier working name was `dsh-longhaul` with `longhaul_*`
1745
+ tools; nothing was ever published, so the old names do not exist anywhere and
1746
+ there is no alias layer. If you find an old snippet that calls `longhaul_start`,
1747
+ replace the prefix — the arguments are unchanged.
1748
+
1749
+ ## Development
1750
+
1751
+ ```bash
1752
+ npm test # node:test, fake store and fake child spawner, no network
1753
+ npm pack # inspect what would ship
1754
+ ```
1755
+
1756
+ What "ready to publish" means is written down as checkable rows in
1757
+ [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
1758
+ [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md).
1759
+
1760
+ Layout: `lib/index.js` (plugin, tool schemas, run formatting),
1761
+ `lib/orchestrator.js` (ordering, retries, budgets, cancel, resume),
1762
+ `lib/store.js` (atomic run files, cancel markers, quarantine),
1763
+ `lib/errors.js` (readable error text), `lib/usage.js` (session log parsing),
1764
+ `lib/control.js` (optional loopback HTTP surface).
1765
+
1766
+ ## License
1767
+
1768
+ MIT. Copyright (c) 2026 Admire (LittleChenLiya); see [LICENSE](LICENSE).
1769
+
1770
+ The npm scope `@xiangyixie` and the GitHub account `LittleChenLiya` are the same
1771
+ author.