@xiangyixie/dsh-superagent 0.14.5 → 0.14.6

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