@xiangyixie/dsh-superagent 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,556 +1,589 @@
1
- # dsh-superagent
2
-
3
- Long-horizon autonomous runs for [DeepSeek Harness](https://dshai.org).
4
-
5
- One goal goes in. A planner splits it into independent subtasks, the subtasks
6
- run in parallel child agents, and an aggregator merges their reports into one
7
- answer. Runs are persisted to disk, so a host restart does not lose them:
8
- `superagent_status` reports them and `superagent_resume` continues them.
9
-
10
- Registered tools: `superagent_start`, `superagent_status`, `superagent_list`,
11
- `superagent_cancel`, `superagent_resume`. The plugin adds no in-host UI and
12
- patches no host code. Two optional operator utilities ship beside it — a
13
- terminal panel and an HTML report — and both are ordinary files rather than
14
- hooks into the host. No runtime dependencies.
15
-
16
- ### Naming
17
-
18
- The package is published as `@xiangyixie/dsh-superagent` — npm already has a
19
- `dsh-super-agent` that is too close to the unscoped name, so the scope keeps
20
- the name instead of renaming the project. The five tools are unchanged:
21
- `superagent_*`. The earlier working name was `dsh-longhaul` with `longhaul_*`
22
- tools; nothing was ever published, so the old names do not exist anywhere and
23
- there is no alias layer. If you find an old snippet that calls `longhaul_start`,
24
- replace the prefix — the arguments are unchanged.
25
-
26
- ## Requirements
27
-
28
- - Node `>= 24.9.0`. DeepSeek Harness refuses to start below that, so this
29
- plugin does too.
30
- - DeepSeek Harness `>= 0.2.2-rc.1 < 0.3.0` with the base bundle (the `tools`,
31
- `agents`, and `subagents` services).
32
- - A model route that can call tools, and that route's API key in the
33
- environment. The default profile uses `deepseek-official` / `deepseek-flash`
34
- and reads `DEEPSEEK_API_KEY`.
35
-
36
- ## Quickstart
37
-
38
- Five minutes, from nothing to a finished run. Every command below runs on a
39
- clean machine.
40
-
41
- ### 0. Do not install `dsh` from npm by name
42
-
43
- ```bash
44
- # WRONG: npm's `dsh` is unrelated ("a shell written in JavaScript")
45
- npm i -g dsh
46
-
47
- # RIGHT: run the DeepSeek Harness by its scoped package, pinned
48
- npx @deepseek-ai/dsh@0.2.2-rc.1 --version
49
- ```
50
-
51
- The rest of this page writes `dsh` for that command; if the binary is not on
52
- your `PATH`, use `npx @deepseek-ai/dsh@0.2.2-rc.1` instead.
53
-
54
- ```bash
55
- # 1. install the plugin into a profile (web, headless, ... whatever you run)
56
- dsh plugin --profile web add @xiangyixie/dsh-superagent
57
-
58
- # 2. confirm the bundle row exists in the merged config
59
- dsh --profile web --dump-config
60
- ```
61
-
62
- `add @xiangyixie/dsh-superagent` resolves the published package. For an offline
63
- machine or a pinned artifact, install a packed tarball instead — it is
64
- byte-identical to what the registry serves:
65
-
66
- ```bash
67
- npm pack # writes xiangyixie-dsh-superagent-<version>.tgz
68
- dsh plugin --profile web add ./xiangyixie-dsh-superagent-<version>.tgz
69
- ```
70
-
71
- If you are working on the plugin itself, install the checkout instead:
72
-
73
- ```bash
74
- dsh plugin --profile web add file:/absolute/path/to/dsh-superagent
75
- ```
76
-
77
- `file:` installs copy the package; re-run the `add` after changing the source,
78
- or the profile keeps running the old copy.
79
-
80
- Look for this block in the dump. If it is missing, the plugin is installed but
81
- not mounted, and no `superagent_*` tool will exist:
82
-
83
- ```yaml
84
- # == @xiangyixie/dsh-superagent
85
- - id: superagent
86
- name: @xiangyixie/dsh-superagent
87
- ```
88
-
89
- ```bash
90
- # 3. start the host with the key in the environment that starts it
91
- export DEEPSEEK_API_KEY=sk-... # PowerShell: $env:DEEPSEEK_API_KEY="sk-..."
92
- dsh --profile web
93
- ```
94
-
95
- The key must be the one for the route the profile actually uses. A profile
96
- pointing at DashScope uses `DASHSCOPE_API_KEY`; a profile pointing at a
97
- self-hosted gateway uses whatever that route names. See
98
- [Other routes](#other-routes) if you want to add one.
99
-
100
- In the session, ask for a run:
101
-
102
- > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
103
-
104
- Shape of the reply (numbers illustrative — a full transcript of a real run is
105
- in [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md)):
106
-
107
- ```
108
- run 20261114T051233-a1b2 — completed
109
- goal: Explain the difference between process and thread in 300 words, with one concrete example
110
- plan: planned; subtasks 2/2 completed; max 3 in parallel; 2 attempt(s) each
111
- elapsed: 18.4s
112
- usage: input 4120 (+980 prompt tokens served from cache), output 455, calls 4 (deepseek-official/deepseek-flash: 4 call(s) 4120 in / 455 out)
113
- cost: not computed — no price configured for deepseek-official/deepseek-flash; add a pricing entry in cordis.patch.yml to get an estimate
114
- [1] completed (attempts 1) Processes vs threads
115
- [2] completed (attempts 1) Concrete example
116
-
117
- report:
118
- ...
119
- ```
120
-
121
- There is no built-in price for the default DeepSeek route; see
122
- [Spending limits and prices](#spending-limits-and-prices) to add one, after
123
- which the next run (or a resume of this one) prints `cost: ...`. `cost` is
124
- computed when a run settles, so an already-finished run keeps the "not
125
- computed" line. `usage: not recorded` only appears on a finished run whose
126
- child logs cannot be read at all — see [Troubleshooting](#troubleshooting).
127
-
128
- If `wait_seconds` runs out before the run finishes, the reply ends with
129
- `next: superagent_status run_id="..." wait_seconds=120`. Call it again; the run
130
- keeps going either way.
131
-
132
- To check recovery without a real crash: kill the host while a run is active,
133
- start it again, then `superagent_status` shows `interrupted` and
134
- `superagent_resume` finishes it. A run is only `interrupted` when no live
135
- process owns it: while the original host is still running, its run is left
136
- alone and the next mount reports it as active, not as interrupted.
137
-
138
- Two shutdown paths behave differently, and both are covered by the E2E record:
139
-
140
- - **Hard kill (or crash).** The heartbeat is a few seconds old, but on the
141
- machine that wrote the run the dead pid is checked first, so the next mount
142
- reclaims it immediately and prints
143
- `reclaimed: owner pid … is not running and this state directory is local`.
144
- A shared state directory written by another machine trusts the heartbeat
145
- instead, so reclamation there waits up to 90 s.
146
- - **Graceful shutdown.** If the host disappears while a run is in flight (for
147
- example a one-shot headless turn that ends after `wait_seconds: 0`), the
148
- plugin notices that the `subagents` service is gone, leaves the unfinished
149
- subtasks `pending`, and settles the run as `interrupted` with
150
- `note: the host shut down while this run was active`. No attempts are burned
151
- on a service that cannot answer. In that case the host process itself may
152
- linger until a child that ignores abort exits; that wait is the host's, not
153
- the plugin's.
154
-
155
- ## Configuration
156
-
157
- Row config in `<profile>/cordis.patch.yml`:
158
-
159
- ```yaml
160
- - id: superagent
161
- config:
162
- maxSubtasks: 8
163
- maxParallel: 3
164
- maxActiveRuns: 2
165
- ```
166
-
167
- | Key | Default | Meaning |
168
- | --- | --- | --- |
169
- | `stateDir` | `$DSH_HOME/state/superagent` | Run state root. |
170
- | `provider` | `spawn` | Subagent backend used for planner, workers, aggregator. |
171
- | `childProvider` | parent's | Optional provider route override for child agents. |
172
- | `childModel` | parent's | Optional model override for child agents. |
173
- | `childPreset` | none | Agent preset for child agents. A preset owns the child's tool set; this host has no per-run tool filter. |
174
- | `maxSubagentDepth` | `1` | How deep children may delegate. `1` forbids grandchildren; `provider-managed` leaves it to the backend. |
175
- | `maxSubtasks` | `8` | Cap on planned subtasks. A tool argument can only lower it, never raise it; hard max 16. |
176
- | `maxParallel` | `3` | Subtasks executing at once. A tool argument can only lower it; hard max 8. |
177
- | `maxActiveRuns` | `2` | Active runs per state directory, across profiles and hosts that share it; further `superagent_start` and `superagent_resume` calls are rejected. |
178
- | `attempts` | `2` | Attempts per subtask before it is marked failed. |
179
- | `deadlineMinutes` | `120` | Wall-clock budget; on expiry the run ends `partial` or `failed`. |
180
- | `maxModelCallsPerRun` | `80` | Hard cap on child model calls per run; `0` disables. |
181
- | `maxTokensPerRun` | `2000000` | Hard cap on prompt + completion tokens per run; `0` disables. |
182
- | `pricing` | empty | Per-1M-token prices, keyed exactly as the usage log names the model (`provider/model`). Nothing is priced out of the box. |
183
- | `resultCapBytes` | `32768` | Bytes kept per subtask report. |
184
- | `notifyOnComplete` | `true` | Wake the owning session once when a run finishes while nobody is polling. |
185
- | `keepRuns` | `0` | Delete terminal runs older than this many days at mount; `0` keeps everything. |
186
- | `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). |
187
-
188
- ### Switching models
189
-
190
- Model choice is configuration, not code. By default child agents inherit the
191
- session's model from the profile's `agent-default-model`. To pin children to a
192
- specific route, set both keys and restart the host:
193
-
194
- ```yaml
195
- - id: superagent
196
- config:
197
- childProvider: dashscope
198
- childModel: qwen-flash
199
- ```
200
-
201
- Nothing about a model id is compiled into the plugin. API keys are read from
202
- the environment variable named by the route; the plugin never stores a key. The
203
- default profile's route is `deepseek-official` and reads `DEEPSEEK_API_KEY`.
204
-
205
- ### Other routes
206
-
207
- The example above assumes a DashScope route is installed in the profile. It is
208
- not part of the base bundle: the default profile has no `dashscope` provider and
209
- `DASHSCOPE_API_KEY` alone will not create one. Add the route first (see the
210
- harness docs for LLM plugins), then name it in `childProvider`.
211
-
212
- ### Child tools and recursion
213
-
214
- `maxSubagentDepth: 1` is passed to the host as `maxDepth`, so a worker cannot
215
- create its own children. This is enforced by the host, not by prompting, and a
216
- provider that cannot enforce it makes `superagent_start` fail with an explicit
217
- error instead of silently running unbounded.
218
-
219
- There is **no** enforced tool allowlist on `dsh@0.2.2-rc.1`. The host's
220
- subagent start request has no tool filter, and its own `subagent` tool rejects a
221
- `toolFilter` config and points at agent presets. `childPreset` is therefore the
222
- supported way to narrow a child's tools; without a dedicated preset, workers
223
- inherit the session's tools. The `superagent_*` tools still exist in their tool
224
- list, but `superagent_start`, `superagent_resume`, and `superagent_cancel`
225
- refuse to run from a worker session; only the top-level agent manages runs.
226
-
227
- ### Spending limits and prices
228
-
229
- Two hard budgets stop a pathological goal before it can spend quietly. Both are
230
- checked before every child is spawned, so a retry loop cannot walk past them:
231
-
232
- ```yaml
233
- - id: superagent
234
- config:
235
- maxModelCallsPerRun: 40
236
- maxTokensPerRun: 500000
237
- pricing:
238
- deepseek-official/deepseek-flash:
239
- input: 0.28 # price per 1M uncached prompt tokens (example)
240
- output: 0.42 # price per 1M completion tokens (example)
241
- cacheRead: 0.028 # optional; defaults to the input price
242
- currency: CNY
243
- ```
244
-
245
- The pricing key is matched against the model id in the usage log, which is
246
- `provider/model` — `superagent_status` prints it on the `usage:` line, so copy
247
- the key from there. A key is matched exactly first, then by its bare model name,
248
- so `qwen-flash` also prices `dashscope/qwen-flash` when there is no exact entry.
249
- The plugin ships no price for any route, because a stale price is worse than a
250
- missing one.
251
-
252
- When a budget is hit, no new child starts and the abort controller stops the
253
- child that is still running, so spend stops at the cap instead of draining one
254
- more worker. Reports that already finished are still merged. The run ends
255
- `partial` when at least one subtask completed and `failed` when none did (the
256
- unfinished subtasks stay `pending`). `superagent_resume` rebuilds the limits
257
- from the current config, keeps everything already spent, and continues from
258
- there — that is how you raise a cap. On the real host, raising
259
- `maxModelCallsPerRun` from 2 to 80 and resuming a run that stopped at 2/2
260
- completed it without dropping the earlier spend.
261
-
262
- A spawn counts as one model call even when the child's session log cannot be
263
- read, so the call budget keeps working on a host whose log layout changed.
264
- Token accounting still needs the log; when it is unavailable, the run prints a
265
- `usage note:` saying the figures are a lower bound.
266
-
267
- Costs are estimates from the table above, never from a built-in guess. A model
268
- that is not listed is reported as `unpriced` and excluded from the total, so the
269
- number you see is always a lower bound:
270
-
271
- ```
272
- cost: at least ¥0.0041 (estimate; no price for haoduo/gpt-6.1-sol)
273
- ```
274
-
275
- ## Tools
276
-
277
- - `superagent_start(goal, max_subtasks?, max_parallel?, deadline_minutes?, wait_seconds?)`
278
- starts a run and returns immediately with a run id. `wait_seconds` blocks for
279
- a terminal state instead.
280
- - `superagent_status(run_id, wait_seconds?)` returns status, per-subtask outcome,
281
- measured token usage, estimated cost, and the final report.
282
- - `superagent_list(limit?)` lists runs, newest first, plus the state directory's
283
- file count and size.
284
- - `superagent_cancel(run_id)` stops the run, from any process; see below.
285
- - `superagent_resume(run_id, wait_seconds?)` continues an `interrupted`, `failed`,
286
- `partial`, or `cancelled` run; completed subtasks are kept.
287
-
288
- ## Watch and report
289
-
290
- ![Run report preview](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-preview.jpg?raw=true)
291
-
292
- _Top of a report rendered from 40 real host runs. The full page — timeline,
293
- swimlanes, call and cost curves, failure annotations, run table — is
294
- [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)._
295
-
296
- Two operator utilities ship with the package. They read the same durable run
297
- files as the tools, need no session, and add no runtime dependency.
298
-
299
- Run them from the installed copy inside the profile:
300
-
301
- ```bash
302
- PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
303
- node "$PKG/bin/watch.js" # live panel, Ctrl-C to stop
304
- node "$PKG/bin/report.js" --out report.html # self-contained HTML page
305
- ```
306
-
307
- If the profile's linker created bin links (npm does), the same commands are
308
- `node_modules/.bin/dsh-superagent-watch` and `node_modules/.bin/dsh-superagent-report`.
309
-
310
- Both accept `--state-dir <path>`; it defaults to `$DSH_HOME/state/superagent`.
311
- Pass it when the plugin config sets a custom `stateDir`.
312
-
313
- **`watch`** draws one line per run — id, status, calls used against the cap,
314
- elapsed time, what it is doing right now, and the parent session — in the
315
- alternate screen, and restores the cursor on Ctrl-C, SIGTERM, or a closed pipe.
316
- A status change repaints immediately; an idle panel reads one small file per
317
- second. `--once` prints a single plain frame, which is what
318
- [docs/e2e/transcripts/watch-panel.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/watch-panel.log)
319
- captures from 40 real runs.
320
-
321
- **`report`** renders recorded runs into one HTML file: inline CSS, inline SVG,
322
- no script, no font, no image, no network. It has a timeline with each run's
323
- start, end, and derived planning/work/merge phases; a swimlane chart whose lane
324
- count is the peak concurrency; cumulative model-call and cost curves; explicit
325
- failure, cancellation, and interruption annotations; and a run table.
326
- [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)
327
- is the 40-run report from the host e2e — open it directly, nothing is fetched —
328
- and
329
- [docs/e2e/transcripts/report-cli.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/report-cli.log)
330
- records the command plus a zero-external-reference audit.
331
-
332
- Neither utility is the install path: the plugin is installed with
333
- `dsh plugin add`, never with `npm i -g`.
334
-
335
- ## Embedding over local HTTP
336
-
337
- The tools require a session. If another UI or script must start and watch runs
338
- without importing this package, set `controlPort`:
339
-
340
- ```yaml
341
- - id: superagent
342
- config:
343
- controlPort: 0 # off by default; 0 = OS picks a free loopback port
344
- ```
345
-
346
- The plugin then writes `<stateDir>/control.json` with the bound URL and a
347
- per-process bearer token (mode `0600`) and serves `GET /`, `GET /health`,
348
- `GET /runs`, `GET /runs/:id`, `POST /runs`, `POST /runs/:id/cancel`, and
349
- `POST /runs/:id/resume` on `127.0.0.1` only. Every reply carries the same text
350
- the tool would print (the route index and `/health` are the two exceptions:
351
- they describe the socket, not a run). Every run goes through the same quota,
352
- budgets, locks, and recovery as a tool-started run. `POST /runs` requires
353
- `session_id` of a session that is live in that host — a run needs a real parent
354
- agent for its children.
355
-
356
- ```bash
357
- STATE="${DSH_HOME:-$HOME/.dsh}/state/superagent"
358
- URL=$(node -e "console.log(require('$STATE/control.json').url)")
359
- TOKEN=$(node -e "console.log(require('$STATE/control.json').token)")
360
- curl -s -H "Authorization: Bearer $TOKEN" "$URL/runs"
361
- ```
362
-
363
- The full contract — routes, error ids, security model, lifecycle, client
364
- examples — is [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md). It is opt-in, loopback
365
- only, and there is no remote or unauthenticated mode.
366
-
367
- ## State and recovery
368
-
369
- One file per run: `$DSH_HOME/state/superagent/runs/<runId>.json`, written with a
370
- temp file plus rename, so a kill during a save cannot leave a half-written run.
371
- Statuses: `queued`, `planning`, `running`, `aggregating`, `completed`,
372
- `partial`, `failed`, `cancelled`, `interrupted`.
373
-
374
- At mount the plugin marks a run as `interrupted` **only when it has no live
375
- owner** (see below) and resets its in-flight subtasks to `pending`.
376
- `superagent_resume` then re-runs only what did not finish. The planner's plan is
377
- reused, so a resumed run does not pay for planning twice.
378
-
379
- A state directory can be shared by two profiles or two machines. Recovery
380
- therefore never decides from this process's memory alone: a run whose owner is
381
- still alive — fresh heartbeat, live local pid, or a live process holding its
382
- lock — is left untouched, cancel marker included. Two processes rewriting one
383
- run would make the surviving child keep spending while the file says
384
- `interrupted`, and a resume would then run the same subtasks twice.
385
-
386
- Resuming is exclusive for the same reason. `superagent_resume` takes the same
387
- serial gate as `superagent_start`, claims `<runId>.lock` (created atomically),
388
- and refuses a run that still has a live owner or that would exceed
389
- `maxActiveRuns`.
390
-
391
- Three side files live next to the run:
392
-
393
- | File | Meaning |
394
- | --- | --- |
395
- | `<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. |
396
- | `<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. |
397
- | `<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. |
398
-
399
- If a run's file is damaged, nothing else breaks: other runs list normally, and
400
- starting a new run works. Inspect the `.corrupt-` file, then delete it. A file
401
- that cannot be read at all (permission, too many open files, disk full) is
402
- reported as such instead of being shown as an unknown run.
403
-
404
- ### Orphaned runs and the active-run quota
405
-
406
- A run counts against `maxActiveRuns` while its status is active. If the process
407
- owning it disappears without a restart, the run would otherwise hold that slot
408
- forever. Before every quota check the plugin looks for such runs and reclaims
409
- them, with two different rules:
410
-
411
- - **The state directory belongs to this machine** (`.owner` holds our hostname):
412
- a dead local pid is enough on its own — that is direct evidence the process is
413
- gone, so the next mount reclaims immediately regardless of the heartbeat. A
414
- live pid vetoes reclamation even with a stale heartbeat, because a wedged
415
- process may still resume.
416
- - **The directory is shared, or its owner is unknown**: the pid may belong to
417
- another machine, so it is ignored and only the heartbeat decides; a run is
418
- reclaimed once its heartbeat is older than 90 seconds. This is the case for a
419
- state directory on a network share or a synced folder.
420
-
421
- In both cases a lock held by a live local process also vetoes reclamation, and
422
- mount-time recovery uses exactly the same rules — a run is never rewritten
423
- while anybody can still be working on it.
424
-
425
- Reclamation is never silent: the run becomes `interrupted`, its `reclaimed`
426
- field records the exact basis (`pid 1234 is not running and its heartbeat
427
- stopped at ...`, or `the state directory is shared with <host> ...`), the reason
428
- is printed by `superagent_status`, and one line goes to the host log. The subtasks
429
- that were mid-flight become `pending`, so `superagent_resume` continues the run.
430
-
431
- The heartbeat is refreshed every 30 seconds by the owning process, so a healthy
432
- run is never mistaken for an orphan.
433
-
434
- ### Notification boundaries
435
-
436
- `notifyOnComplete` writes one message back into the owning session when a run
437
- finishes. Two cases report instead of notifying:
438
-
439
- - a caller in the same host process was inside `superagent_status` and receives
440
- the terminal report itself (no message, to avoid duplicate noise). A poller in
441
- a *different* process does not suppress the message: it can time out just
442
- before the run ends, and then the only notification would be lost;
443
- - the owning session is gone (headless users who closed it): the run records
444
- `notify.delivered = false` with the reason, `superagent_status` prints
445
- `notify: not delivered — ...`, and `superagent_list` marks the row
446
- `(result not delivered to the session)`. The report is always readable with
447
- `superagent_status`.
448
-
449
- Waking the session is bounded (15 s), and the heartbeat keeps running until the
450
- terminal state is written, so a slow wake-up cannot make another process treat a
451
- live run as orphaned.
452
-
453
- ### Retention
454
-
455
- Nothing is deleted by default. Set `keepRuns` to a number of days to delete
456
- terminal runs older than that at mount; active runs are never touched, and the
457
- removed ids are logged. `superagent_list` prints the current file count and size,
458
- so growth is visible before it becomes a problem.
459
-
460
- ## Cancelling from another process
461
-
462
- `superagent_cancel` works even when the run was started by a different host
463
- process (web and headless running side by side, or a second terminal). The
464
- crossing point is the `.cancel` marker file, not shared memory:
465
-
466
- 1. the caller writes `<runId>.cancel`;
467
- 2. the owning process notices within a second, aborts its children' signal,
468
- disposes their activations, and writes `cancelled`;
469
- 3. the caller waits up to 5 seconds for that, then reports what happened.
470
-
471
- If the owner does not answer in time, the reply says
472
- `cancel requested ... not confirmed` instead of `cancelled`. That means the
473
- owning process is gone or wedged; the marker stays on disk, and the next mount
474
- converts the run to `cancelled` during recovery. No socket, pipe, or Windows
475
- named pipe is involved, so this works the same on every platform and across a
476
- shared state directory.
477
-
478
- Measured on the real host: with two workers sleeping inside a model call that
479
- ignores abort, `superagent_cancel` returned `cancelled` in **1.99 s** and the
480
- state file stopped accepting new spawns at that instant. The *host process*
481
- still took 22.8 s to exit, because it waits for its own child sessions; that
482
- wait is the host's teardown, outside the plugin's control. In an interactive
483
- session you never notice it; in a one-shot headless turn it is why cancel
484
- appears to "hang" until the ignored-abort child returns.
485
-
486
- ## Troubleshooting
487
-
488
- | What you see | What it means | What to do |
489
- | --- | --- | --- |
490
- | `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` and read the host log for `[dsh-superagent]` lines. |
491
- | `[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`. |
492
- | `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. |
493
- | `[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. |
494
- | `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. |
495
- | `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. |
496
- | `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. | Wait, cancel one, or raise `maxActiveRuns`. |
497
- | `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. |
498
- | `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. |
499
- | `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. |
500
- | `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. |
501
- | `cost: at least ... (no price for X)` | Some children used an unpriced model. | Same as above; the figure covers only the priced part. |
502
- | `[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. |
503
- | `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. |
504
- | `[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. |
505
- | `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. |
506
- | `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. |
507
- | `[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. |
508
-
509
- A tool call that fails itself returns three lines: `[error]` a sentence, `hint:`
510
- one next step, and `detail:` the untouched host message, so nothing is hidden.
511
- A run that fails *after* it was accepted keeps its report and shows `error:`
512
- (plus a `hint:` line when it is `failed`) in the run block instead.
513
-
514
- ## Known limits
515
-
516
- - A run lives inside the host process. Killing the process stops its children;
517
- the run becomes `interrupted` on the next mount.
518
- - Cancelling from another process is cooperative: it relies on the owning
519
- process still running. A wedged process is only cleaned up at the next mount
520
- or when its heartbeat goes stale and the quota is reclaimed.
521
- - Planning is one model call. If the reply has no parsable
522
- `{"subtasks":[...]}` object, the run degrades to a single subtask and is
523
- marked `plan.mode = "degraded"`.
524
- - Aggregation is skipped for a single successful subtask (the report is that
525
- subtask's text under the goal heading) and falls back to a deterministic merge
526
- when the aggregator fails or the budget is exhausted.
527
- - Retention is opt-in (`keepRuns`); by default state accumulates, at up to
528
- 32 KB per subtask plus the report per run.
529
- - The HTTP embedding surface is loopback-only, opt-in, and token-authenticated;
530
- it cannot be exposed remotely, and there is no MCP server. A local process
531
- running as the same user can read the token, which is the same trust boundary
532
- as writing run files.
533
-
534
- ## Development
535
-
536
- ```bash
537
- npm test # node:test, fake store and fake child spawner, no network
538
- npm pack # inspect what would ship
539
- ```
540
-
541
- What "ready to publish" means is written down as checkable rows in
542
- [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
543
- [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md).
544
-
545
- Layout: `lib/index.js` (plugin, tool schemas, run formatting),
546
- `lib/orchestrator.js` (ordering, retries, budgets, cancel, resume),
547
- `lib/store.js` (atomic run files, cancel markers, quarantine),
548
- `lib/errors.js` (readable error text), `lib/usage.js` (session log parsing),
549
- `lib/control.js` (optional loopback HTTP surface).
550
-
551
- ## License
552
-
553
- MIT. Copyright (c) 2026 Admire (LittleChenLiya); see [LICENSE](LICENSE).
554
-
555
- The npm scope `@xiangyixie` and the GitHub account `LittleChenLiya` are the same
556
- author.
1
+ # dsh-superagent
2
+
3
+ Long-horizon runs for [DeepSeek Harness](https://dshai.org): one goal in,
4
+ model-planned parallel subtasks, one merged report — and the run survives a host
5
+ restart.
6
+
7
+ A single agent loop is one context and one sequence. Goals that need several
8
+ independent lines of work stall in it, and a crash ends the turn with nothing to
9
+ resume. This plugin takes one goal, asks the model to split it into subtasks, runs
10
+ up to three child agents at a time, and merges their reports into one answer. Run
11
+ state and spend are written to disk, so after a host restart `superagent_status`
12
+ still finds the run and `superagent_resume` finishes only the unfinished part.
13
+ Every run has a hard call and token budget, prints the usage it measured, and
14
+ prints the cost once you give it a price for the route.
15
+
16
+ **Don't use it when** one model call can answer: you would only be paying for a
17
+ planner and an aggregator on top. It is also the wrong tool for work that must
18
+ finish inside a single turn, for a step that needs human approval in the middle,
19
+ for anything that needs nested delegation (child depth is capped at 1), and for
20
+ anyone who wants an in-host panel — this adds no UI, only five tools. Children run
21
+ with the host's credentials and filesystem; this is not a sandbox.
22
+
23
+ **Install and run.** Node `>= 24.9.0`, a tool-calling route, and that route's key
24
+ in the environment:
25
+
26
+ ```bash
27
+ dsh plugin --profile web add @xiangyixie/dsh-superagent
28
+ ```
29
+
30
+ Then ask the session for a run — a real call, not a sketch:
31
+
32
+ > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
33
+
34
+ The reply ends `completed` with the merged report, or with
35
+ `next: superagent_status run_id="..."` if the wait ran out. [Quickstart](#quickstart)
36
+ covers the path from an empty machine, including the reason not to install npm's
37
+ unrelated `dsh` package by name.
38
+
39
+ It adds no in-host UI and patches no host code: the five `superagent_*` tools are
40
+ the surface, plus two optional operator utilities (a terminal panel and an HTML
41
+ report) that read the same run files.
42
+
43
+ Personal project, not affiliated with DeepSeek or the harness maintainers. MIT
44
+ licensed, © 2026 Admire (LittleChenLiya); details in [License](#license).
45
+
46
+ ## Requirements
47
+
48
+ - Node `>= 24.9.0`. DeepSeek Harness refuses to start below that, so this
49
+ plugin does too.
50
+ - DeepSeek Harness `>= 0.2.2-rc.1 < 0.3.0` with the base bundle (the `tools`,
51
+ `agents`, and `subagents` services).
52
+ - A model route that can call tools, and that route's API key in the
53
+ environment. The default profile uses `deepseek-official` / `deepseek-flash`
54
+ and reads `DEEPSEEK_API_KEY`.
55
+
56
+ ## Quickstart
57
+
58
+ Five minutes, from nothing to a finished run. Every command below runs on a
59
+ clean machine.
60
+
61
+ ### 0. Do not install `dsh` from npm by name
62
+
63
+ ```bash
64
+ # WRONG: npm's `dsh` is unrelated ("a shell written in JavaScript")
65
+ npm i -g dsh
66
+
67
+ # RIGHT: run the DeepSeek Harness by its scoped package, pinned
68
+ npx @deepseek-ai/dsh@0.2.2-rc.1 --version
69
+ ```
70
+
71
+ The rest of this page writes `dsh` for that command; if the binary is not on
72
+ your `PATH`, use `npx @deepseek-ai/dsh@0.2.2-rc.1` instead.
73
+
74
+ ```bash
75
+ # 1. install the plugin into a profile (web, headless, ... whatever you run)
76
+ dsh plugin --profile web add @xiangyixie/dsh-superagent
77
+
78
+ # 2. confirm the bundle row exists in the merged config
79
+ dsh --profile web --dump-config
80
+ ```
81
+
82
+ `add @xiangyixie/dsh-superagent` resolves the published package. For an offline
83
+ machine or a pinned artifact, install a packed tarball instead — it is
84
+ byte-identical to what the registry serves:
85
+
86
+ ```bash
87
+ npm pack # writes xiangyixie-dsh-superagent-<version>.tgz
88
+ dsh plugin --profile web add ./xiangyixie-dsh-superagent-<version>.tgz
89
+ ```
90
+
91
+ If you are working on the plugin itself, install the checkout instead:
92
+
93
+ ```bash
94
+ dsh plugin --profile web add file:/absolute/path/to/dsh-superagent
95
+ ```
96
+
97
+ `file:` installs copy the package; re-run the `add` after changing the source,
98
+ or the profile keeps running the old copy.
99
+
100
+ Look for this block in the dump. If it is missing, the plugin is installed but
101
+ not mounted, and no `superagent_*` tool will exist:
102
+
103
+ ```yaml
104
+ # == @xiangyixie/dsh-superagent
105
+ - id: superagent
106
+ name: @xiangyixie/dsh-superagent
107
+ ```
108
+
109
+ ```bash
110
+ # 3. start the host with the key in the environment that starts it
111
+ export DEEPSEEK_API_KEY=sk-... # PowerShell: $env:DEEPSEEK_API_KEY="sk-..."
112
+ dsh --profile web
113
+ ```
114
+
115
+ The key must be the one for the route the profile actually uses. A profile
116
+ pointing at DashScope uses `DASHSCOPE_API_KEY`; a profile pointing at a
117
+ self-hosted gateway uses whatever that route names. See
118
+ [Other routes](#other-routes) if you want to add one.
119
+
120
+ In the session, ask for a run:
121
+
122
+ > Use superagent_start with goal "Explain the difference between process and thread in 300 words, with one concrete example" and wait_seconds 120.
123
+
124
+ Shape of the reply (numbers illustrative — a full transcript of a real run is
125
+ in [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md)):
126
+
127
+ ```
128
+ run 20261114T051233-a1b2 — completed
129
+ goal: Explain the difference between process and thread in 300 words, with one concrete example
130
+ plan: planned; subtasks 2/2 completed; max 3 in parallel; 2 attempt(s) each
131
+ elapsed: 18.4s
132
+ usage: input 4120 (+980 prompt tokens served from cache), output 455, calls 4 (deepseek-official/deepseek-flash: 4 call(s) 4120 in / 455 out)
133
+ cost: not computed — no price configured for deepseek-official/deepseek-flash; add a pricing entry in cordis.patch.yml to get an estimate
134
+ [1] completed (attempts 1) Processes vs threads
135
+ [2] completed (attempts 1) Concrete example
136
+
137
+ report:
138
+ ...
139
+ ```
140
+
141
+ There is no built-in price for the default DeepSeek route; see
142
+ [Spending limits and prices](#spending-limits-and-prices) to add one, after
143
+ which the next run (or a resume of this one) prints `cost: ...`. `cost` is
144
+ computed when a run settles, so an already-finished run keeps the "not
145
+ computed" line. `usage: not recorded` only appears on a finished run whose
146
+ child logs cannot be read at all — see [Troubleshooting](#troubleshooting).
147
+
148
+ If `wait_seconds` runs out before the run finishes, the reply ends with
149
+ `next: superagent_status run_id="..." wait_seconds=120`. Call it again; the run
150
+ keeps going either way.
151
+
152
+ To check recovery without a real crash: kill the host while a run is active,
153
+ start it again, then `superagent_status` shows `interrupted` and
154
+ `superagent_resume` finishes it. A run is only `interrupted` when no live
155
+ process owns it: while the original host is still running, its run is left
156
+ alone and the next mount reports it as active, not as interrupted.
157
+
158
+ Two shutdown paths behave differently, and both are covered by the E2E record:
159
+
160
+ - **Hard kill (or crash).** The heartbeat is a few seconds old, but on the
161
+ machine that wrote the run the dead pid is checked first, so the next mount
162
+ reclaims it immediately and prints
163
+ `reclaimed: owner pid … is not running and this state directory is local`.
164
+ A shared state directory written by another machine trusts the heartbeat
165
+ instead, so reclamation there waits up to 90 s.
166
+ - **Graceful shutdown.** If the host disappears while a run is in flight (for
167
+ example a one-shot headless turn that ends after `wait_seconds: 0`), the
168
+ plugin notices that the `subagents` service is gone, leaves the unfinished
169
+ subtasks `pending`, and settles the run as `interrupted` with
170
+ `note: the host shut down while this run was active`. No attempts are burned
171
+ on a service that cannot answer. In that case the host process itself may
172
+ linger until a child that ignores abort exits; that wait is the host's, not
173
+ the plugin's.
174
+
175
+ ## Configuration
176
+
177
+ Row config in `<profile>/cordis.patch.yml`:
178
+
179
+ ```yaml
180
+ - id: superagent
181
+ config:
182
+ maxSubtasks: 8
183
+ maxParallel: 3
184
+ maxActiveRuns: 2
185
+ ```
186
+
187
+ | Key | Default | Meaning |
188
+ | --- | --- | --- |
189
+ | `stateDir` | `$DSH_HOME/state/superagent` | Run state root. |
190
+ | `provider` | `spawn` | Subagent backend used for planner, workers, aggregator. |
191
+ | `childProvider` | parent's | Optional provider route override for child agents. |
192
+ | `childModel` | parent's | Optional model override for child agents. |
193
+ | `childPreset` | none | Agent preset for child agents. A preset owns the child's tool set; this host has no per-run tool filter. |
194
+ | `maxSubagentDepth` | `1` | How deep children may delegate. `1` forbids grandchildren; `provider-managed` leaves it to the backend. |
195
+ | `maxSubtasks` | `8` | Cap on planned subtasks. A tool argument can only lower it, never raise it; hard max 16. |
196
+ | `maxParallel` | `3` | Subtasks executing at once. A tool argument can only lower it; hard max 8. |
197
+ | `maxActiveRuns` | `2` | Active runs per state directory, across profiles and hosts that share it; further `superagent_start` and `superagent_resume` calls are rejected. |
198
+ | `attempts` | `2` | Attempts per subtask before it is marked failed. |
199
+ | `deadlineMinutes` | `120` | Wall-clock budget; on expiry the run ends `partial` or `failed`. |
200
+ | `maxModelCallsPerRun` | `80` | Hard cap on child model calls per run; `0` disables. |
201
+ | `maxTokensPerRun` | `2000000` | Hard cap on prompt + completion tokens per run; `0` disables. |
202
+ | `pricing` | empty | Per-1M-token prices, keyed exactly as the usage log names the model (`provider/model`). Nothing is priced out of the box. |
203
+ | `resultCapBytes` | `32768` | Bytes kept per subtask report. |
204
+ | `notifyOnComplete` | `true` | Wake the owning session once when a run finishes while nobody is polling. |
205
+ | `keepRuns` | `0` | Delete terminal runs older than this many days at mount; `0` keeps everything. |
206
+ | `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). |
207
+
208
+ ### Switching models
209
+
210
+ Model choice is configuration, not code. By default child agents inherit the
211
+ session's model from the profile's `agent-default-model`. To pin children to a
212
+ specific route, set both keys and restart the host:
213
+
214
+ ```yaml
215
+ - id: superagent
216
+ config:
217
+ childProvider: dashscope
218
+ childModel: qwen-flash
219
+ ```
220
+
221
+ Nothing about a model id is compiled into the plugin. API keys are read from
222
+ the environment variable named by the route; the plugin never stores a key. The
223
+ default profile's route is `deepseek-official` and reads `DEEPSEEK_API_KEY`.
224
+
225
+ ### Other routes
226
+
227
+ The example above assumes a DashScope route is installed in the profile. It is
228
+ not part of the base bundle: the default profile has no `dashscope` provider and
229
+ `DASHSCOPE_API_KEY` alone will not create one. Add the route first (see the
230
+ harness docs for LLM plugins), then name it in `childProvider`.
231
+
232
+ ### Child tools and recursion
233
+
234
+ `maxSubagentDepth: 1` is passed to the host as `maxDepth`, so a worker cannot
235
+ create its own children. This is enforced by the host, not by prompting, and a
236
+ provider that cannot enforce it makes `superagent_start` fail with an explicit
237
+ error instead of silently running unbounded.
238
+
239
+ There is **no** enforced tool allowlist on `dsh@0.2.2-rc.1`. The host's
240
+ subagent start request has no tool filter, and its own `subagent` tool rejects a
241
+ `toolFilter` config and points at agent presets. `childPreset` is therefore the
242
+ supported way to narrow a child's tools; without a dedicated preset, workers
243
+ inherit the session's tools. The `superagent_*` tools still exist in their tool
244
+ list, but `superagent_start`, `superagent_resume`, and `superagent_cancel`
245
+ refuse to run from a worker session; only the top-level agent manages runs.
246
+
247
+ ### Spending limits and prices
248
+
249
+ Two hard budgets stop a pathological goal before it can spend quietly. Both are
250
+ checked before every child is spawned, so a retry loop cannot walk past them:
251
+
252
+ ```yaml
253
+ - id: superagent
254
+ config:
255
+ maxModelCallsPerRun: 40
256
+ maxTokensPerRun: 500000
257
+ pricing:
258
+ deepseek-official/deepseek-flash:
259
+ input: 0.28 # price per 1M uncached prompt tokens (example)
260
+ output: 0.42 # price per 1M completion tokens (example)
261
+ cacheRead: 0.028 # optional; defaults to the input price
262
+ currency: CNY
263
+ ```
264
+
265
+ The pricing key is matched against the model id in the usage log, which is
266
+ `provider/model` — `superagent_status` prints it on the `usage:` line, so copy
267
+ the key from there. A key is matched exactly first, then by its bare model name,
268
+ so `qwen-flash` also prices `dashscope/qwen-flash` when there is no exact entry.
269
+ The plugin ships no price for any route, because a stale price is worse than a
270
+ missing one.
271
+
272
+ When a budget is hit, no new child starts and the abort controller stops the
273
+ child that is still running, so spend stops at the cap instead of draining one
274
+ more worker. Reports that already finished are still merged. The run ends
275
+ `partial` when at least one subtask completed and `failed` when none did (the
276
+ unfinished subtasks stay `pending`). `superagent_resume` rebuilds the limits
277
+ from the current config, keeps everything already spent, and continues from
278
+ there — that is how you raise a cap. On the real host, raising
279
+ `maxModelCallsPerRun` from 2 to 80 and resuming a run that stopped at 2/2
280
+ completed it without dropping the earlier spend.
281
+
282
+ A spawn counts as one model call even when the child's session log cannot be
283
+ read, so the call budget keeps working on a host whose log layout changed.
284
+ Token accounting still needs the log; when it is unavailable, the run prints a
285
+ `usage note:` saying the figures are a lower bound.
286
+
287
+ Costs are estimates from the table above, never from a built-in guess. A model
288
+ that is not listed is reported as `unpriced` and excluded from the total, so the
289
+ number you see is always a lower bound:
290
+
291
+ ```
292
+ cost: at least ¥0.0041 (estimate; no price for haoduo/gpt-6.1-sol)
293
+ ```
294
+
295
+ ## Tools
296
+
297
+ - `superagent_start(goal, max_subtasks?, max_parallel?, deadline_minutes?, wait_seconds?)`
298
+ starts a run and returns immediately with a run id. `wait_seconds` blocks for
299
+ a terminal state instead.
300
+ - `superagent_status(run_id, wait_seconds?)` returns status, per-subtask outcome,
301
+ measured token usage, estimated cost, and the final report.
302
+ - `superagent_list(limit?)` lists runs, newest first, plus the state directory's
303
+ file count and size.
304
+ - `superagent_cancel(run_id)` stops the run, from any process; see below.
305
+ - `superagent_resume(run_id, wait_seconds?)` continues an `interrupted`, `failed`,
306
+ `partial`, or `cancelled` run; completed subtasks are kept.
307
+
308
+ ## Watch and report
309
+
310
+ ![Run report preview](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-preview.jpg?raw=true)
311
+
312
+ _Top of a report rendered from 40 real host runs. The full page — timeline,
313
+ swimlanes, call and cost curves, failure annotations, run table — is
314
+ [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)._
315
+
316
+ Two operator utilities ship with the package. They read the same durable run
317
+ files as the tools, need no session, and add no runtime dependency.
318
+
319
+ Run them from the installed copy inside the profile:
320
+
321
+ ```bash
322
+ PKG="${DSH_HOME:-$HOME/.dsh}/profiles/web/node_modules/@xiangyixie/dsh-superagent"
323
+ node "$PKG/bin/watch.js" # live panel, Ctrl-C to stop
324
+ node "$PKG/bin/report.js" --out report.html # self-contained HTML page
325
+ ```
326
+
327
+ If the profile's linker created bin links (npm does), the same commands are
328
+ `node_modules/.bin/dsh-superagent-watch` and `node_modules/.bin/dsh-superagent-report`.
329
+
330
+ Both accept `--state-dir <path>`; it defaults to `$DSH_HOME/state/superagent`.
331
+ Pass it when the plugin config sets a custom `stateDir`.
332
+
333
+ **`watch`** draws one line per run — id, status, calls used against the cap,
334
+ elapsed time, what it is doing right now, and the parent session — in the
335
+ alternate screen, and restores the cursor on Ctrl-C, SIGTERM, or a closed pipe.
336
+ A status change repaints immediately; an idle panel reads one small file per
337
+ second. `--once` prints a single plain frame, which is what
338
+ [docs/e2e/transcripts/watch-panel.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/watch-panel.log)
339
+ captures from 40 real runs.
340
+
341
+ **`report`** renders recorded runs into one HTML file: inline CSS, inline SVG,
342
+ no script, no font, no image, no network. It has a timeline with each run's
343
+ start, end, and derived planning/work/merge phases; a swimlane chart whose lane
344
+ count is the peak concurrency; cumulative model-call and cost curves; explicit
345
+ failure, cancellation, and interruption annotations; and a run table.
346
+ [docs/report-sample.html](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/report-sample.html)
347
+ is the 40-run report from the host e2e — open it directly, nothing is fetched —
348
+ and
349
+ [docs/e2e/transcripts/report-cli.log](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e/transcripts/report-cli.log)
350
+ records the command plus a zero-external-reference audit.
351
+
352
+ Neither utility is the install path: the plugin is installed with
353
+ `dsh plugin add`, never with `npm i -g`.
354
+
355
+ ## Embedding over local HTTP
356
+
357
+ The tools require a session. If another UI or script must start and watch runs
358
+ without importing this package, set `controlPort`:
359
+
360
+ ```yaml
361
+ - id: superagent
362
+ config:
363
+ controlPort: 0 # off by default; 0 = OS picks a free loopback port
364
+ ```
365
+
366
+ The plugin then writes `<stateDir>/control.json` with the bound URL and a
367
+ per-process bearer token (mode `0600`) and serves `GET /`, `GET /health`,
368
+ `GET /runs`, `GET /runs/:id`, `POST /runs`, `POST /runs/:id/cancel`, and
369
+ `POST /runs/:id/resume` on `127.0.0.1` only. Every reply carries the same text
370
+ the tool would print (the route index and `/health` are the two exceptions:
371
+ they describe the socket, not a run). Every run goes through the same quota,
372
+ budgets, locks, and recovery as a tool-started run. `POST /runs` requires
373
+ `session_id` of a session that is live in that host — a run needs a real parent
374
+ agent for its children.
375
+
376
+ ```bash
377
+ STATE="${DSH_HOME:-$HOME/.dsh}/state/superagent"
378
+ URL=$(node -e "console.log(require('$STATE/control.json').url)")
379
+ TOKEN=$(node -e "console.log(require('$STATE/control.json').token)")
380
+ curl -s -H "Authorization: Bearer $TOKEN" "$URL/runs"
381
+ ```
382
+
383
+ The full contract — routes, error ids, security model, lifecycle, client
384
+ examples — is [docs/embedding.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/embedding.md). It is opt-in, loopback
385
+ only, and there is no remote or unauthenticated mode.
386
+
387
+ ## State and recovery
388
+
389
+ One file per run: `$DSH_HOME/state/superagent/runs/<runId>.json`, written with a
390
+ temp file plus rename, so a kill during a save cannot leave a half-written run.
391
+ Statuses: `queued`, `planning`, `running`, `aggregating`, `completed`,
392
+ `partial`, `failed`, `cancelled`, `interrupted`.
393
+
394
+ At mount the plugin marks a run as `interrupted` **only when it has no live
395
+ owner** (see below) and resets its in-flight subtasks to `pending`.
396
+ `superagent_resume` then re-runs only what did not finish. The planner's plan is
397
+ reused, so a resumed run does not pay for planning twice.
398
+
399
+ A state directory can be shared by two profiles or two machines. Recovery
400
+ therefore never decides from this process's memory alone: a run whose owner is
401
+ still alive — fresh heartbeat, live local pid, or a live process holding its
402
+ lock — is left untouched, cancel marker included. Two processes rewriting one
403
+ run would make the surviving child keep spending while the file says
404
+ `interrupted`, and a resume would then run the same subtasks twice.
405
+
406
+ Resuming is exclusive for the same reason. `superagent_resume` takes the same
407
+ serial gate as `superagent_start`, claims `<runId>.lock` (created atomically),
408
+ and refuses a run that still has a live owner or that would exceed
409
+ `maxActiveRuns`.
410
+
411
+ Three side files live next to the run:
412
+
413
+ | File | Meaning |
414
+ | --- | --- |
415
+ | `<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. |
416
+ | `<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. |
417
+ | `<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. |
418
+
419
+ If a run's file is damaged, nothing else breaks: other runs list normally, and
420
+ starting a new run works. Inspect the `.corrupt-` file, then delete it. A file
421
+ that cannot be read at all (permission, too many open files, disk full) is
422
+ reported as such instead of being shown as an unknown run.
423
+
424
+ ### Orphaned runs and the active-run quota
425
+
426
+ A run counts against `maxActiveRuns` while its status is active. If the process
427
+ owning it disappears without a restart, the run would otherwise hold that slot
428
+ forever. Before every quota check the plugin looks for such runs and reclaims
429
+ them, with two different rules:
430
+
431
+ - **The state directory belongs to this machine** (`.owner` holds our hostname):
432
+ a dead local pid is enough on its own — that is direct evidence the process is
433
+ gone, so the next mount reclaims immediately regardless of the heartbeat. A
434
+ live pid vetoes reclamation even with a stale heartbeat, because a wedged
435
+ process may still resume.
436
+ - **The directory is shared, or its owner is unknown**: the pid may belong to
437
+ another machine, so it is ignored and only the heartbeat decides; a run is
438
+ reclaimed once its heartbeat is older than 90 seconds. This is the case for a
439
+ state directory on a network share or a synced folder.
440
+
441
+ In both cases a lock held by a live local process also vetoes reclamation, and
442
+ mount-time recovery uses exactly the same rules — a run is never rewritten
443
+ while anybody can still be working on it.
444
+
445
+ Reclamation is never silent: the run becomes `interrupted`, its `reclaimed`
446
+ field records the exact basis (`pid 1234 is not running and its heartbeat
447
+ stopped at ...`, or `the state directory is shared with <host> ...`), the reason
448
+ is printed by `superagent_status`, and one line goes to the host log. The subtasks
449
+ that were mid-flight become `pending`, so `superagent_resume` continues the run.
450
+
451
+ The heartbeat is refreshed every 30 seconds by the owning process, so a healthy
452
+ run is never mistaken for an orphan.
453
+
454
+ ### Notification boundaries
455
+
456
+ `notifyOnComplete` writes one message back into the owning session when a run
457
+ finishes. Two cases report instead of notifying:
458
+
459
+ - a caller in the same host process was inside `superagent_status` and receives
460
+ the terminal report itself (no message, to avoid duplicate noise). A poller in
461
+ a *different* process does not suppress the message: it can time out just
462
+ before the run ends, and then the only notification would be lost;
463
+ - the owning session is gone (headless users who closed it): the run records
464
+ `notify.delivered = false` with the reason, `superagent_status` prints
465
+ `notify: not delivered — ...`, and `superagent_list` marks the row
466
+ `(result not delivered to the session)`. The report is always readable with
467
+ `superagent_status`.
468
+
469
+ Waking the session is bounded (15 s), and the heartbeat keeps running until the
470
+ terminal state is written, so a slow wake-up cannot make another process treat a
471
+ live run as orphaned.
472
+
473
+ ### Retention
474
+
475
+ Nothing is deleted by default. Set `keepRuns` to a number of days to delete
476
+ terminal runs older than that at mount; active runs are never touched, and the
477
+ removed ids are logged. `superagent_list` prints the current file count and size,
478
+ so growth is visible before it becomes a problem.
479
+
480
+ ## Cancelling from another process
481
+
482
+ `superagent_cancel` works even when the run was started by a different host
483
+ process (web and headless running side by side, or a second terminal). The
484
+ crossing point is the `.cancel` marker file, not shared memory:
485
+
486
+ 1. the caller writes `<runId>.cancel`;
487
+ 2. the owning process notices within a second, aborts its children' signal,
488
+ disposes their activations, and writes `cancelled`;
489
+ 3. the caller waits up to 5 seconds for that, then reports what happened.
490
+
491
+ If the owner does not answer in time, the reply says
492
+ `cancel requested ... not confirmed` instead of `cancelled`. That means the
493
+ owning process is gone or wedged; the marker stays on disk, and the next mount
494
+ converts the run to `cancelled` during recovery. No socket, pipe, or Windows
495
+ named pipe is involved, so this works the same on every platform and across a
496
+ shared state directory.
497
+
498
+ Measured on the real host: with two workers sleeping inside a model call that
499
+ ignores abort, `superagent_cancel` returned `cancelled` in **1.99 s** and the
500
+ state file stopped accepting new spawns at that instant. The *host process*
501
+ still took 22.8 s to exit, because it waits for its own child sessions; that
502
+ wait is the host's teardown, outside the plugin's control. In an interactive
503
+ session you never notice it; in a one-shot headless turn it is why cancel
504
+ appears to "hang" until the ignored-abort child returns.
505
+
506
+ ## Troubleshooting
507
+
508
+ | What you see | What it means | What to do |
509
+ | --- | --- | --- |
510
+ | `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` and read the host log for `[dsh-superagent]` lines. |
511
+ | `[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`. |
512
+ | `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. |
513
+ | `[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. |
514
+ | `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. |
515
+ | `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. |
516
+ | `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. | Wait, cancel one, or raise `maxActiveRuns`. |
517
+ | `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. |
518
+ | `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. |
519
+ | `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. |
520
+ | `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. |
521
+ | `cost: at least ... (no price for X)` | Some children used an unpriced model. | Same as above; the figure covers only the priced part. |
522
+ | `[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. |
523
+ | `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. |
524
+ | `[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. |
525
+ | `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. |
526
+ | `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. |
527
+ | `[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. |
528
+
529
+ A tool call that fails itself returns three lines: `[error]` a sentence, `hint:`
530
+ one next step, and `detail:` the untouched host message, so nothing is hidden.
531
+ A run that fails *after* it was accepted keeps its report and shows `error:`
532
+ (plus a `hint:` line when it is `failed`) in the run block instead.
533
+
534
+ ## Known limits
535
+
536
+ - Children are not isolated by this plugin: they run with the host's
537
+ credentials and filesystem, under whatever sandbox policy the host itself
538
+ applies.
539
+ - A run lives inside the host process. Killing the process stops its children;
540
+ the run becomes `interrupted` on the next mount.
541
+ - Cancelling from another process is cooperative: it relies on the owning
542
+ process still running. A wedged process is only cleaned up at the next mount
543
+ or when its heartbeat goes stale and the quota is reclaimed.
544
+ - Planning is one model call. If the reply has no parsable
545
+ `{"subtasks":[...]}` object, the run degrades to a single subtask and is
546
+ marked `plan.mode = "degraded"`.
547
+ - Aggregation is skipped for a single successful subtask (the report is that
548
+ subtask's text under the goal heading) and falls back to a deterministic merge
549
+ when the aggregator fails or the budget is exhausted.
550
+ - Retention is opt-in (`keepRuns`); by default state accumulates, at up to
551
+ 32 KB per subtask plus the report per run.
552
+ - The HTTP embedding surface is loopback-only, opt-in, and token-authenticated;
553
+ it cannot be exposed remotely, and there is no MCP server. A local process
554
+ running as the same user can read the token, which is the same trust boundary
555
+ as writing run files.
556
+
557
+ ## Naming
558
+
559
+ The package is published as `@xiangyixie/dsh-superagent` — npm already has a
560
+ `dsh-super-agent` that is too close to the unscoped name, so the scope keeps
561
+ the name instead of renaming the project. The five tools are unchanged:
562
+ `superagent_*`. The earlier working name was `dsh-longhaul` with `longhaul_*`
563
+ tools; nothing was ever published, so the old names do not exist anywhere and
564
+ there is no alias layer. If you find an old snippet that calls `longhaul_start`,
565
+ replace the prefix — the arguments are unchanged.
566
+
567
+ ## Development
568
+
569
+ ```bash
570
+ npm test # node:test, fake store and fake child spawner, no network
571
+ npm pack # inspect what would ship
572
+ ```
573
+
574
+ What "ready to publish" means is written down as checkable rows in
575
+ [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
576
+ [docs/e2e-2026-11-14.md](https://github.com/LittleChenLiya/dsh-superagent/blob/main/docs/e2e-2026-11-14.md).
577
+
578
+ Layout: `lib/index.js` (plugin, tool schemas, run formatting),
579
+ `lib/orchestrator.js` (ordering, retries, budgets, cancel, resume),
580
+ `lib/store.js` (atomic run files, cancel markers, quarantine),
581
+ `lib/errors.js` (readable error text), `lib/usage.js` (session log parsing),
582
+ `lib/control.js` (optional loopback HTTP surface).
583
+
584
+ ## License
585
+
586
+ MIT. Copyright (c) 2026 Admire (LittleChenLiya); see [LICENSE](LICENSE).
587
+
588
+ The npm scope `@xiangyixie` and the GitHub account `LittleChenLiya` are the same
589
+ author.