@xiangyixie/dsh-superagent 0.9.0 → 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/lib/index.js CHANGED
@@ -1,822 +1,822 @@
1
- /**
2
- * dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
3
- *
4
- * One goal enters; a planner decomposes it into independent subtasks; those
5
- * subtasks run in parallel child agents; an aggregator merges their reports.
6
- * Runs survive a host restart, can be cancelled, and have their token usage
7
- * read back from the child sessions' durable logs.
8
- *
9
- * Registered tools: superagent_start, superagent_status, superagent_list,
10
- * superagent_cancel, superagent_resume.
11
- *
12
- * @module dsh-superagent
13
- */
14
- import { randomUUID } from 'node:crypto'
15
- import os from 'node:os'
16
- import path from 'node:path'
17
- import pkg from '../package.json' with { type: 'json' }
18
- import { createOrchestrator } from './orchestrator.js'
19
- import { createControlPlane } from './control.js'
20
- import { classifyError, describeError, summarizeError } from './errors.js'
21
- import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
22
- import { createUsageReader } from './usage.js'
23
-
24
- export const name = 'dsh-superagent'
25
- // The host menu and sessions are required. `subagents` is read through
26
- // `ctx.get('subagents')`, so a profile without it still mounts the five tools;
27
- // they then report what is missing instead of the plugin silently vanishing.
28
- export const inject = ['tools', 'agents']
29
-
30
- const DEFAULTS = {
31
- /** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
32
- stateDir: null,
33
- /** Child backend registered on `ctx.subagents`. */
34
- provider: 'spawn',
35
- /** Optional provider override for every child agent; unset inherits the parent's model route. */
36
- childProvider: null,
37
- /** Optional model override for every child agent; unset inherits the parent's model. */
38
- childModel: null,
39
- /**
40
- * Optional agent preset for child agents. A preset owns the child's tool
41
- * composition, which is the only way this host version can restrict it.
42
- */
43
- childPreset: null,
44
- /**
45
- * Delegation depth granted to child agents. 1 means a worker may not create
46
- * children of its own; `provider-managed` leaves the cap to the backend.
47
- */
48
- maxSubagentDepth: 1,
49
- /** Upper bound on planned subtasks per run. */
50
- maxSubtasks: 8,
51
- /** Upper bound on subtasks executing at once. */
52
- maxParallel: 3,
53
- /** Runs allowed to be active at the same time; further starts are rejected. */
54
- maxActiveRuns: 2,
55
- /** Attempts per subtask before it is marked failed. */
56
- attempts: 2,
57
- /** Wall-clock budget for a whole run, in minutes. */
58
- deadlineMinutes: 120,
59
- /** Hard cap on child model calls per run; 0 disables the cap. */
60
- maxModelCallsPerRun: 80,
61
- /** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
62
- maxTokensPerRun: 2_000_000,
63
- /**
64
- * List prices per 1M tokens, keyed by model id as it appears in usage logs.
65
- * Only models listed here are priced; everything else is reported as unpriced
66
- * rather than guessed. Nothing is shipped: a stale price is worse than none.
67
- */
68
- pricing: {},
69
- /** Bytes kept from one subtask report. */
70
- resultCapBytes: 32 * 1024,
71
- /** Write one message back to the owning session when a run finishes unattended. */
72
- notifyOnComplete: true,
73
- /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
74
- keepRuns: 0,
75
- /**
76
- * Loopback HTTP port for the embedding surface. `null` (default) keeps the
77
- * socket closed; `0` asks the OS for a free port. The bound address and its
78
- * bearer token are written to `<stateDir>/control.json`.
79
- */
80
- controlPort: null,
81
- }
82
-
83
- const REPORT_PREVIEW_CHARS = 8000
84
-
85
- /**
86
- * Coerce one numeric setting into its documented range. A value like "abc"
87
- * would otherwise become NaN and silently remove a limit (NaN comparisons are
88
- * always false), which is how a quota disappears without any error.
89
- */
90
- function bounded(value, fallback, min, max) {
91
- const number = Number(value)
92
- if (!Number.isFinite(number)) return fallback
93
- return Math.min(max, Math.max(min, Math.trunc(number)))
94
- }
95
-
96
- /**
97
- * A port is a whole number in 0–65535, or nothing. A malformed value must not
98
- * silently open a socket somewhere unexpected, so anything else stays off.
99
- */
100
- function controlPortOf(value) {
101
- if (value === null || value === undefined || value === false) return null
102
- // Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
103
- // real number or a plain digit string may enable the surface.
104
- if (typeof value === 'number') {
105
- return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
106
- }
107
- if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
108
- const number = Number(value.trim())
109
- return number <= 65535 ? number : null
110
- }
111
- return null
112
- }
113
-
114
- function resolveConfig(config) {
115
- const merged = { ...DEFAULTS }
116
- if (config && typeof config === 'object') {
117
- for (const [key, value] of Object.entries(config)) {
118
- if (value !== undefined) merged[key] = value
119
- }
120
- }
121
- merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
122
- merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
123
- merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
124
- merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
125
- merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
126
- merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
127
- merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
128
- merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
129
- merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
130
- merged.controlPort = controlPortOf(merged.controlPort)
131
- merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
132
- ? 'provider-managed'
133
- : bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
134
- // Per-model prices merge, so a user can add one route without restating the
135
- // built-in table.
136
- merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
137
- return merged
138
- }
139
-
140
- function preview(text, limit = REPORT_PREVIEW_CHARS) {
141
- if (typeof text !== 'string') return ''
142
- if (text.length <= limit) return text
143
- return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
144
- }
145
-
146
- function durationText(ms) {
147
- const seconds = Math.max(0, ms / 1000)
148
- if (seconds < 60) return `${seconds.toFixed(1)}s`
149
- const minutes = Math.floor(seconds / 60)
150
- return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
151
- }
152
-
153
- function elapsed(run) {
154
- const start = Date.parse(run.startedAt)
155
- const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
156
- if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
157
- const wall = Math.max(0, end - start)
158
- const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
159
- // A resumed run can span hours of downtime. Reporting one number would make
160
- // it look like the model worked all that time.
161
- if (run.resumedAt && wall - active > 5000) {
162
- return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
163
- }
164
- return durationText(wall)
165
- }
166
-
167
- function usageLine(usage, status) {
168
- if (!usage || !usage.modelCalls) {
169
- if (ACTIVE_STATUSES.has(status)) {
170
- return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
171
- }
172
- return 'usage: not recorded — no child session log was readable for this run '
173
- + '(usually a run created before usage tracking, or a sessions directory that moved); '
174
- + 'token and cost figures are unavailable'
175
- }
176
- const models = Object.entries(usage.models ?? {})
177
- .map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
178
- .join('; ')
179
- const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
180
- return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
181
- + (models ? ` (${models})` : '')
182
- }
183
-
184
- function currencySymbol(code) {
185
- if (code === 'CNY') return '¥'
186
- if (code === 'USD') return '$'
187
- if (code === 'EUR') return '€'
188
- return `${code} `
189
- }
190
-
191
- /**
192
- * Cost line for one run. The number is an estimate from the configured list
193
- * prices; models without a price are named instead of guessed so a user can
194
- * always tell how much of the spend the figure covers.
195
- */
196
- function costLine(run) {
197
- if (!run.usage || !run.usage.modelCalls) return null
198
- const models = Object.keys(run.usage.models ?? {})
199
- const cost = run.cost
200
- if (!cost || Object.keys(cost.byModel).length === 0) {
201
- return `cost: not computed — no price configured for ${models.join(', ') || 'this model'}; `
202
- + 'add a pricing entry in cordis.patch.yml to get an estimate'
203
- }
204
- const money = `${currencySymbol(cost.currency)}${cost.total.toFixed(4)}`
205
- if (cost.complete) return `cost: ${money} (estimate; all models priced)`
206
- return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
207
- }
208
-
209
- /** Render one run as text for a tool result. */
210
- function formatRun(run, { includeReport = true } = {}) {
211
- const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
212
- const lines = [
213
- `run ${run.id} — ${run.status}`,
214
- `goal: ${run.goal}`,
215
- `plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
216
- + `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
217
- `elapsed: ${elapsed(run)}`,
218
- usageLine(run.usage, run.status),
219
- ]
220
- const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
221
- if (unreadable > 0) {
222
- lines.push(
223
- `usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
224
- + 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
225
- )
226
- }
227
- const cost = costLine(run)
228
- if (cost) lines.push(cost)
229
- if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
230
- if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
231
- if (run.status === 'interrupted' && run.error) {
232
- // Not a failure: the host went away and the run is waiting to be resumed.
233
- lines.push(`note: ${run.error}`)
234
- } else if (run.status !== 'cancelled' && run.error) {
235
- lines.push(`error: ${summarizeError(run.error)}`)
236
- if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
237
- }
238
- if (notifyFailed(run)) {
239
- lines.push(`notify: not delivered — ${run.notify.reason}`)
240
- }
241
- if (run.cancelPending) {
242
- lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
243
- }
244
- for (const subtask of run.subtasks) {
245
- const tokens = subtask.usage ? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out` : ''
246
- const detail = subtask.error ? ` — ${summarizeError(subtask.error)}` : ''
247
- // A cancelled run never judged its unfinished subtasks, so calling them
248
- // "pending" or "failed (attempts 0)" would misreport what happened.
249
- const status = run.status === 'cancelled' && subtask.status !== 'completed'
250
- ? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
251
- : subtask.status
252
- lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${detail}`)
253
- }
254
- const failed = run.subtasks.find(subtask => subtask.error)
255
- if (failed) {
256
- const hint = classifyError(failed.error).hint
257
- if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
258
- }
259
- if (includeReport && run.report) {
260
- lines.push('', 'report:', '', preview(run.report))
261
- }
262
- if (!TERMINAL_STATUSES.has(run.status)) {
263
- lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
264
- } else if (run.status === 'interrupted') {
265
- lines.push('', `next: superagent_resume run_id="${run.id}"`)
266
- }
267
- return lines.join('\n')
268
- }
269
-
270
- function formatBytes(bytes) {
271
- if (bytes < 1024) return `${bytes} B`
272
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
273
- return `${(bytes / 1024 / 1024).toFixed(1)} MB`
274
- }
275
-
276
- /** True when a run finished but its owner was never told, and that is a problem. */
277
- function notifyFailed(run) {
278
- if (!run.notify || run.notify.delivered) return false
279
- return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
280
- }
281
-
282
- function formatList(runs, limit, stats = null) {
283
- if (runs.length === 0) return 'no superagent runs recorded'
284
- const rows = runs.slice(0, limit).map(run => {
285
- const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
286
- return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
287
- + `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
288
- })
289
- const lines = [`${runs.length} run(s):`, ...rows]
290
- if (stats) {
291
- lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
292
- + (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
293
- }
294
- return lines.join('\n')
295
- }
296
-
297
- function toolText(text) {
298
- return [{ type: 'text', text }]
299
- }
300
-
301
- function defineTool(spec) {
302
- return {
303
- name: spec.name,
304
- description: spec.description,
305
- parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
306
- output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
307
- execute: spec.execute,
308
- }
309
- }
310
-
311
- /**
312
- * Mount the plugin.
313
- * @param {object} ctx - Cordis context.
314
- * @param {object} [config] - row config from `cordis.patch.yml`.
315
- */
316
- export function apply(ctx, config) {
317
- const log = message => console.error(`[dsh-superagent] ${message}`)
318
- const configuredPort = config?.controlPort
319
- const cfg = resolveConfig(config)
320
- if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
321
- log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
322
- }
323
- if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
324
- console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
325
- return
326
- }
327
-
328
- const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
329
- const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
330
- const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
331
-
332
- /** Child sessions spawned by this process; a run may not be started from one. */
333
- const childIds = new Set()
334
-
335
- /**
336
- * The subagent service is optional, so it is read from the service store at
337
- * call time rather than declared as an injection: a profile without it must
338
- * still mount the five tools (they then explain what is missing), and reading
339
- * it lazily also sees a service that registers after this plugin.
340
- */
341
- function getSubagents() {
342
- if (typeof ctx.get === 'function') {
343
- const service = ctx.get('subagents')
344
- if (service) return service
345
- }
346
- // The direct property is topology-sensitive on a real host; it is only a
347
- // fallback for test contexts that provide the service without a registry.
348
- try {
349
- return ctx.subagents
350
- } catch {
351
- return undefined
352
- }
353
- }
354
-
355
- /** Remember a child id for the recursion guard without growing forever. */
356
- function rememberChild(childId) {
357
- if (!childId) return
358
- childIds.add(childId)
359
- if (childIds.size > 512) childIds.delete(childIds.values().next().value)
360
- }
361
-
362
- /**
363
- * Map a run outcome to one message for the owning session.
364
- *
365
- * The followup is awaited: an unhandled rejection from it would otherwise
366
- * escape as a host-level error while the run already claims it was delivered.
367
- */
368
- async function notifyParent(run) {
369
- if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
370
- if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
371
- const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
372
- const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
373
- if (!agent || typeof agent.followup !== 'function') {
374
- log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
375
- return {
376
- delivered: false,
377
- reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
378
- }
379
- }
380
- const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
381
- const text = [
382
- `[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`,
383
- `Call superagent_status with run_id="${run.id}" to read the report.`,
384
- ].join(' ')
385
- try {
386
- await agent.followup({
387
- id: randomUUID(),
388
- role: 'user',
389
- content: [{ type: 'text', text }],
390
- source: { kind: 'user' },
391
- })
392
- run.notified = true
393
- return { delivered: true }
394
- } catch (error) {
395
- log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
396
- return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
397
- }
398
- }
399
-
400
- const orchestrator = createOrchestrator({
401
- store,
402
- config: cfg,
403
- log,
404
- readUsage,
405
- notify: notifyParent,
406
- async spawnChild({ label, prompt, parent, signal }) {
407
- const subagents = getSubagents()
408
- if (!subagents || typeof subagents.startActivation !== 'function') {
409
- const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
410
- // The service can also disappear in the middle of a run, when the host
411
- // is shutting down. The orchestrator turns this code into `interrupted`
412
- // instead of a failed subtask, so the run stays resumable.
413
- error.code = 'subagent-unavailable'
414
- throw error
415
- }
416
- const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
417
- const capabilities = provider?.capabilities ?? null
418
- const agentOptions = {}
419
- if (cfg.childProvider) agentOptions.provider = cfg.childProvider
420
- if (cfg.childModel) agentOptions.model = cfg.childModel
421
- const request = {
422
- parent,
423
- prompt: [{ type: 'text', text: prompt }],
424
- ...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
425
- }
426
- // A preset is the host's only way to give a child a narrower tool set:
427
- // the start request has no tool filter in dsh 0.2.2-rc.1.
428
- if (cfg.childPreset) {
429
- if (capabilities && !capabilities.agentPreset) {
430
- throw new Error(
431
- `childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
432
- + 'independent agent presets, so this child would run with this session\'s tools',
433
- )
434
- }
435
- request.agentPreset = cfg.childPreset
436
- }
437
- // Recursion is bounded unless the operator explicitly left it to the
438
- // backend. Silently dropping the cap would hand 8 parallel workers the
439
- // right to spawn their own armies.
440
- if (cfg.maxSubagentDepth !== 'provider-managed') {
441
- if (capabilities && !capabilities.depthLimit) {
442
- throw new Error(
443
- `subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
444
- + 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
445
- + 'the backend\'s own cap',
446
- )
447
- }
448
- request.maxDepth = cfg.maxSubagentDepth
449
- }
450
- const activation = await subagents.startActivation({
451
- provider: cfg.provider,
452
- label,
453
- request,
454
- signal,
455
- delivery: 'caller',
456
- })
457
- rememberChild(activation.childId)
458
- return {
459
- childId: activation.childId,
460
- result: activation.result,
461
- dispose: async () => {
462
- try {
463
- await activation.dispose()
464
- } catch (error) {
465
- log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
466
- }
467
- },
468
- }
469
- },
470
- })
471
-
472
- // Recovery runs once at mount; tools wait for it so a run left active by a
473
- // dead host reads as interrupted before the first tool call sees it. A
474
- // failure to initialize the state directory is kept and reported by every
475
- // tool: hiding it behind "no runs recorded" is how a broken stateDir looks
476
- // like an empty one.
477
- let stateError = null
478
- const ready = (async () => {
479
- try {
480
- await orchestrator.recover()
481
- } catch (error) {
482
- stateError = error instanceof Error ? error : new Error(String(error))
483
- log(`state directory is not usable: ${stateError.message}`)
484
- return
485
- }
486
- if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
487
- try {
488
- const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
489
- if (removed.length > 0) {
490
- log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
491
- }
492
- } catch (error) {
493
- log(`cannot prune old runs: ${error?.message ?? error}`)
494
- }
495
- })()
496
-
497
- /** True when the host actually provides a subagent service. */
498
- function hasSubagents() {
499
- const subagents = getSubagents()
500
- return Boolean(subagents && typeof subagents.startActivation === 'function')
501
- }
502
-
503
- function requireAgent(exec) {
504
- const agent = exec?.agent
505
- if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
506
- if (childIds.has(agent.id)) {
507
- return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
508
- }
509
- return { agent }
510
- }
511
-
512
- /**
513
- * Resolve the session named by an HTTP caller. An embedded start is a normal
514
- * run: it needs a live agent to own the children, and the same recursion
515
- * guard as a tool call. A synthetic parent would spawn children no session
516
- * owns, so a missing session is an error, never a fallback.
517
- * @param {unknown} sessionId - `session_id` from the request body.
518
- * @returns {object} live agent.
519
- */
520
- function resolveSession(sessionId) {
521
- const id = typeof sessionId === 'string' ? sessionId.trim() : ''
522
- if (!id) {
523
- throw new Error(
524
- 'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
525
- )
526
- }
527
- const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
528
- const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
529
- if (!agent || typeof agent !== 'object' || !agent.id) {
530
- throw new Error(
531
- `no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
532
- + 'tool call inside it',
533
- )
534
- }
535
- if (childIds.has(agent.id)) {
536
- throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
537
- }
538
- return agent
539
- }
540
-
541
- ctx.tools.register(defineTool({
542
- name: 'superagent_start',
543
- description:
544
- 'Start a long-horizon autonomous run: a planner decomposes the goal into independent subtasks, '
545
- + 'the subtasks run in parallel child agents, and their reports are merged into one final report. '
546
- + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
547
- + 'so they survive a host restart and can be resumed or cancelled.',
548
- properties: {
549
- goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
550
- max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
551
- max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
552
- deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
553
- wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
554
- },
555
- required: ['goal'],
556
- async execute(args = {}, exec) {
557
- const check = requireAgent(exec)
558
- if (check.error) return check.error
559
- try {
560
- await ready
561
- if (stateError) return describeError(stateError)
562
- if (!hasSubagents()) {
563
- return describeError(
564
- 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
565
- + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
566
- )
567
- }
568
- const run = await orchestrator.start({
569
- goal: args.goal,
570
- parentSessionId: check.agent.id,
571
- parent: check.agent,
572
- clientTimeZone: exec.clientTimeZone,
573
- overrides: {
574
- maxSubtasks: args.max_subtasks,
575
- maxParallel: args.max_parallel,
576
- deadlineMinutes: args.deadline_minutes,
577
- },
578
- })
579
- const waitSeconds = Number(args.wait_seconds) || 0
580
- if (waitSeconds > 0) {
581
- const finished = await orchestrator.status(run.id, waitSeconds)
582
- return formatRun(finished)
583
- }
584
- return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
585
- + 'the run keeps going after this tool call returns.'
586
- } catch (error) {
587
- return describeError(error)
588
- }
589
- },
590
- }))
591
-
592
- ctx.tools.register(defineTool({
593
- name: 'superagent_status',
594
- description:
595
- 'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
596
- + 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
597
- properties: {
598
- run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
599
- wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
600
- },
601
- required: ['run_id'],
602
- async execute(args = {}) {
603
- try {
604
- await ready
605
- if (stateError) return describeError(stateError)
606
- const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
607
- return formatRun(run)
608
- } catch (error) {
609
- return describeError(error)
610
- }
611
- },
612
- }))
613
-
614
- ctx.tools.register(defineTool({
615
- name: 'superagent_list',
616
- description: 'List recorded superagent runs, newest first, with status and progress.',
617
- properties: {
618
- limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
619
- },
620
- async execute(args = {}) {
621
- try {
622
- await ready
623
- if (stateError) return describeError(stateError)
624
- const runs = await orchestrator.list()
625
- const stats = typeof store.stats === 'function' ? await store.stats() : null
626
- return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), stats ? { ...stats, root: store.root } : null)
627
- } catch (error) {
628
- return describeError(error)
629
- }
630
- },
631
- }))
632
-
633
- ctx.tools.register(defineTool({
634
- name: 'superagent_cancel',
635
- description:
636
- 'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
637
- + 'so the partial work stays inspectable.',
638
- properties: {
639
- run_id: { type: 'string', description: 'Run id to cancel.' },
640
- },
641
- required: ['run_id'],
642
- async execute(args = {}, exec) {
643
- const check = requireAgent(exec)
644
- if (check.error) return check.error
645
- try {
646
- await ready
647
- if (stateError) return describeError(stateError)
648
- const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
649
- const head = run.status === 'cancelled'
650
- ? `cancelled ${run.id}`
651
- : run.cancelPending
652
- ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
653
- : `${run.id} is ${run.status}; nothing to cancel`
654
- return `${head}\n\n${formatRun(run, { includeReport: false })}`
655
- } catch (error) {
656
- return describeError(error)
657
- }
658
- },
659
- }))
660
-
661
- ctx.tools.register(defineTool({
662
- name: 'superagent_resume',
663
- description:
664
- 'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
665
- + 'Completed subtasks are kept; pending and failed ones run again.',
666
- properties: {
667
- run_id: { type: 'string', description: 'Run id to resume.' },
668
- wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
669
- },
670
- required: ['run_id'],
671
- async execute(args = {}, exec) {
672
- const check = requireAgent(exec)
673
- if (check.error) return check.error
674
- try {
675
- await ready
676
- if (stateError) return describeError(stateError)
677
- if (!hasSubagents()) {
678
- return describeError(
679
- 'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
680
- )
681
- }
682
- const run = await orchestrator.resume(String(args.run_id ?? '').trim(), check.agent, exec.clientTimeZone)
683
- const waitSeconds = Number(args.wait_seconds) || 0
684
- const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
685
- return formatRun(current)
686
- } catch (error) {
687
- return describeError(error)
688
- }
689
- },
690
- }))
691
-
692
- // The embedding surface is opt-in: mounting the plugin must not open a port
693
- // unasked. When it is on, every request goes through the same orchestrator as
694
- // the tools, so quota, budgets, ownership, and cancel behave identically.
695
- if (cfg.controlPort !== null) {
696
- const clampControlWait = value => {
697
- const seconds = Number(value)
698
- if (!Number.isFinite(seconds) || seconds <= 0) return 0
699
- return Math.min(300, Math.trunc(seconds))
700
- }
701
- const control = createControlPlane({
702
- port: cfg.controlPort,
703
- stateRoot: store.root,
704
- version: pkg.version,
705
- log,
706
- actions: {
707
- // Liveness only: a probe must not sweep or reclaim runs, so this
708
- // deliberately does no state-directory work. Use GET /runs to ask what
709
- // is running.
710
- async health() {
711
- return { runs: 'GET /runs' }
712
- },
713
- async list({ limit } = {}) {
714
- await ready
715
- if (stateError) throw stateError
716
- const runs = await orchestrator.list()
717
- const stats = typeof store.stats === 'function' ? await store.stats() : null
718
- const rows = Math.max(1, Math.min(100, Number(limit) || 20))
719
- const visible = runs.slice(0, rows)
720
- return {
721
- data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
722
- text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
723
- }
724
- },
725
- async status(runId, waitSeconds) {
726
- await ready
727
- if (stateError) throw stateError
728
- const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
729
- return { data: { run }, text: formatRun(run) }
730
- },
731
- async start(body = {}) {
732
- await ready
733
- if (stateError) throw stateError
734
- if (!hasSubagents()) {
735
- throw new Error(
736
- 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
737
- + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
738
- )
739
- }
740
- const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
741
- if (!goal) {
742
- // Report the caller's mistake as written in the docs: a missing goal
743
- // is 400, not "you also did not name a session".
744
- throw new Error('goal is required; pass a concrete goal string')
745
- }
746
- const agent = resolveSession(body.session_id)
747
- const run = await orchestrator.start({
748
- goal,
749
- parentSessionId: agent.id,
750
- parent: agent,
751
- clientTimeZone: body.time_zone,
752
- overrides: {
753
- maxSubtasks: body.max_subtasks,
754
- maxParallel: body.max_parallel,
755
- deadlineMinutes: body.deadline_minutes,
756
- },
757
- })
758
- const waitSeconds = clampControlWait(body.wait_seconds)
759
- if (waitSeconds > 0) {
760
- const finished = await orchestrator.status(run.id, waitSeconds)
761
- return { data: { run: finished }, text: formatRun(finished) }
762
- }
763
- return {
764
- data: { run },
765
- text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
766
- + `GET /runs/${run.id} or call superagent_status.`,
767
- }
768
- },
769
- async cancel(runId) {
770
- await ready
771
- if (stateError) throw stateError
772
- const run = await orchestrator.cancel(String(runId ?? '').trim())
773
- const head = run.status === 'cancelled'
774
- ? `cancelled ${run.id}`
775
- : run.cancelPending
776
- ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
777
- : `${run.id} is ${run.status}; nothing to cancel`
778
- return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
779
- },
780
- async resume(runId, body = {}) {
781
- await ready
782
- if (stateError) throw stateError
783
- if (!hasSubagents()) {
784
- throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
785
- }
786
- const agent = resolveSession(body.session_id)
787
- const run = await orchestrator.resume(String(runId ?? '').trim(), agent, body.time_zone)
788
- const waitSeconds = clampControlWait(body.wait_seconds)
789
- const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
790
- return { data: { run: current }, text: formatRun(current) }
791
- },
792
- },
793
- })
794
- let disposed = false
795
- const stopControl = () => {
796
- disposed = true
797
- return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
798
- }
799
- if (typeof ctx.effect === 'function') {
800
- ctx.effect(() => stopControl, 'dsh-superagent control plane')
801
- } else if (typeof ctx.on === 'function') {
802
- ctx.on('dispose', stopControl)
803
- }
804
- // The state directory is created by `orchestrator.recover()`, which `ready`
805
- // awaits. Starting before it exists makes the discovery write fail with
806
- // ENOENT and would leave the plane off for the whole host lifetime.
807
- ready
808
- .then(() => {
809
- if (disposed || stateError) return null
810
- return control.start()
811
- })
812
- .catch(error => {
813
- log(
814
- `control plane is not listening: ${error?.message ?? error}; `
815
- + 'check that controlPort is free and the state directory is writable, '
816
- + 'or remove controlPort to keep the socket closed',
817
- )
818
- })
819
- }
820
-
821
- log(`registered 5 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
822
- }
1
+ /**
2
+ * dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
3
+ *
4
+ * One goal enters; a planner decomposes it into independent subtasks; those
5
+ * subtasks run in parallel child agents; an aggregator merges their reports.
6
+ * Runs survive a host restart, can be cancelled, and have their token usage
7
+ * read back from the child sessions' durable logs.
8
+ *
9
+ * Registered tools: superagent_start, superagent_status, superagent_list,
10
+ * superagent_cancel, superagent_resume.
11
+ *
12
+ * @module dsh-superagent
13
+ */
14
+ import { randomUUID } from 'node:crypto'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import pkg from '../package.json' with { type: 'json' }
18
+ import { createOrchestrator } from './orchestrator.js'
19
+ import { createControlPlane } from './control.js'
20
+ import { classifyError, describeError, summarizeError } from './errors.js'
21
+ import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
22
+ import { createUsageReader } from './usage.js'
23
+
24
+ export const name = 'dsh-superagent'
25
+ // The host menu and sessions are required. `subagents` is read through
26
+ // `ctx.get('subagents')`, so a profile without it still mounts the five tools;
27
+ // they then report what is missing instead of the plugin silently vanishing.
28
+ export const inject = ['tools', 'agents']
29
+
30
+ const DEFAULTS = {
31
+ /** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
32
+ stateDir: null,
33
+ /** Child backend registered on `ctx.subagents`. */
34
+ provider: 'spawn',
35
+ /** Optional provider override for every child agent; unset inherits the parent's model route. */
36
+ childProvider: null,
37
+ /** Optional model override for every child agent; unset inherits the parent's model. */
38
+ childModel: null,
39
+ /**
40
+ * Optional agent preset for child agents. A preset owns the child's tool
41
+ * composition, which is the only way this host version can restrict it.
42
+ */
43
+ childPreset: null,
44
+ /**
45
+ * Delegation depth granted to child agents. 1 means a worker may not create
46
+ * children of its own; `provider-managed` leaves the cap to the backend.
47
+ */
48
+ maxSubagentDepth: 1,
49
+ /** Upper bound on planned subtasks per run. */
50
+ maxSubtasks: 8,
51
+ /** Upper bound on subtasks executing at once. */
52
+ maxParallel: 3,
53
+ /** Runs allowed to be active at the same time; further starts are rejected. */
54
+ maxActiveRuns: 2,
55
+ /** Attempts per subtask before it is marked failed. */
56
+ attempts: 2,
57
+ /** Wall-clock budget for a whole run, in minutes. */
58
+ deadlineMinutes: 120,
59
+ /** Hard cap on child model calls per run; 0 disables the cap. */
60
+ maxModelCallsPerRun: 80,
61
+ /** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
62
+ maxTokensPerRun: 2_000_000,
63
+ /**
64
+ * List prices per 1M tokens, keyed by model id as it appears in usage logs.
65
+ * Only models listed here are priced; everything else is reported as unpriced
66
+ * rather than guessed. Nothing is shipped: a stale price is worse than none.
67
+ */
68
+ pricing: {},
69
+ /** Bytes kept from one subtask report. */
70
+ resultCapBytes: 32 * 1024,
71
+ /** Write one message back to the owning session when a run finishes unattended. */
72
+ notifyOnComplete: true,
73
+ /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
74
+ keepRuns: 0,
75
+ /**
76
+ * Loopback HTTP port for the embedding surface. `null` (default) keeps the
77
+ * socket closed; `0` asks the OS for a free port. The bound address and its
78
+ * bearer token are written to `<stateDir>/control.json`.
79
+ */
80
+ controlPort: null,
81
+ }
82
+
83
+ const REPORT_PREVIEW_CHARS = 8000
84
+
85
+ /**
86
+ * Coerce one numeric setting into its documented range. A value like "abc"
87
+ * would otherwise become NaN and silently remove a limit (NaN comparisons are
88
+ * always false), which is how a quota disappears without any error.
89
+ */
90
+ function bounded(value, fallback, min, max) {
91
+ const number = Number(value)
92
+ if (!Number.isFinite(number)) return fallback
93
+ return Math.min(max, Math.max(min, Math.trunc(number)))
94
+ }
95
+
96
+ /**
97
+ * A port is a whole number in 0–65535, or nothing. A malformed value must not
98
+ * silently open a socket somewhere unexpected, so anything else stays off.
99
+ */
100
+ function controlPortOf(value) {
101
+ if (value === null || value === undefined || value === false) return null
102
+ // Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
103
+ // real number or a plain digit string may enable the surface.
104
+ if (typeof value === 'number') {
105
+ return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
106
+ }
107
+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
108
+ const number = Number(value.trim())
109
+ return number <= 65535 ? number : null
110
+ }
111
+ return null
112
+ }
113
+
114
+ function resolveConfig(config) {
115
+ const merged = { ...DEFAULTS }
116
+ if (config && typeof config === 'object') {
117
+ for (const [key, value] of Object.entries(config)) {
118
+ if (value !== undefined) merged[key] = value
119
+ }
120
+ }
121
+ merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
122
+ merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
123
+ merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
124
+ merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
125
+ merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
126
+ merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
127
+ merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
128
+ merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
129
+ merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
130
+ merged.controlPort = controlPortOf(merged.controlPort)
131
+ merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
132
+ ? 'provider-managed'
133
+ : bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
134
+ // Per-model prices merge, so a user can add one route without restating the
135
+ // built-in table.
136
+ merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
137
+ return merged
138
+ }
139
+
140
+ function preview(text, limit = REPORT_PREVIEW_CHARS) {
141
+ if (typeof text !== 'string') return ''
142
+ if (text.length <= limit) return text
143
+ return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
144
+ }
145
+
146
+ function durationText(ms) {
147
+ const seconds = Math.max(0, ms / 1000)
148
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
149
+ const minutes = Math.floor(seconds / 60)
150
+ return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
151
+ }
152
+
153
+ function elapsed(run) {
154
+ const start = Date.parse(run.startedAt)
155
+ const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
156
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
157
+ const wall = Math.max(0, end - start)
158
+ const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
159
+ // A resumed run can span hours of downtime. Reporting one number would make
160
+ // it look like the model worked all that time.
161
+ if (run.resumedAt && wall - active > 5000) {
162
+ return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
163
+ }
164
+ return durationText(wall)
165
+ }
166
+
167
+ function usageLine(usage, status) {
168
+ if (!usage || !usage.modelCalls) {
169
+ if (ACTIVE_STATUSES.has(status)) {
170
+ return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
171
+ }
172
+ return 'usage: not recorded — no child session log was readable for this run '
173
+ + '(usually a run created before usage tracking, or a sessions directory that moved); '
174
+ + 'token and cost figures are unavailable'
175
+ }
176
+ const models = Object.entries(usage.models ?? {})
177
+ .map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
178
+ .join('; ')
179
+ const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
180
+ return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
181
+ + (models ? ` (${models})` : '')
182
+ }
183
+
184
+ function currencySymbol(code) {
185
+ if (code === 'CNY') return '¥'
186
+ if (code === 'USD') return '$'
187
+ if (code === 'EUR') return '€'
188
+ return `${code} `
189
+ }
190
+
191
+ /**
192
+ * Cost line for one run. The number is an estimate from the configured list
193
+ * prices; models without a price are named instead of guessed so a user can
194
+ * always tell how much of the spend the figure covers.
195
+ */
196
+ function costLine(run) {
197
+ if (!run.usage || !run.usage.modelCalls) return null
198
+ const models = Object.keys(run.usage.models ?? {})
199
+ const cost = run.cost
200
+ if (!cost || Object.keys(cost.byModel).length === 0) {
201
+ return `cost: not computed — no price configured for ${models.join(', ') || 'this model'}; `
202
+ + 'add a pricing entry in cordis.patch.yml to get an estimate'
203
+ }
204
+ const money = `${currencySymbol(cost.currency)}${cost.total.toFixed(4)}`
205
+ if (cost.complete) return `cost: ${money} (estimate; all models priced)`
206
+ return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
207
+ }
208
+
209
+ /** Render one run as text for a tool result. */
210
+ function formatRun(run, { includeReport = true } = {}) {
211
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
212
+ const lines = [
213
+ `run ${run.id} — ${run.status}`,
214
+ `goal: ${run.goal}`,
215
+ `plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
216
+ + `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
217
+ `elapsed: ${elapsed(run)}`,
218
+ usageLine(run.usage, run.status),
219
+ ]
220
+ const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
221
+ if (unreadable > 0) {
222
+ lines.push(
223
+ `usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
224
+ + 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
225
+ )
226
+ }
227
+ const cost = costLine(run)
228
+ if (cost) lines.push(cost)
229
+ if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
230
+ if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
231
+ if (run.status === 'interrupted' && run.error) {
232
+ // Not a failure: the host went away and the run is waiting to be resumed.
233
+ lines.push(`note: ${run.error}`)
234
+ } else if (run.status !== 'cancelled' && run.error) {
235
+ lines.push(`error: ${summarizeError(run.error)}`)
236
+ if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
237
+ }
238
+ if (notifyFailed(run)) {
239
+ lines.push(`notify: not delivered — ${run.notify.reason}`)
240
+ }
241
+ if (run.cancelPending) {
242
+ lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
243
+ }
244
+ for (const subtask of run.subtasks) {
245
+ const tokens = subtask.usage ? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out` : ''
246
+ const detail = subtask.error ? ` — ${summarizeError(subtask.error)}` : ''
247
+ // A cancelled run never judged its unfinished subtasks, so calling them
248
+ // "pending" or "failed (attempts 0)" would misreport what happened.
249
+ const status = run.status === 'cancelled' && subtask.status !== 'completed'
250
+ ? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
251
+ : subtask.status
252
+ lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${detail}`)
253
+ }
254
+ const failed = run.subtasks.find(subtask => subtask.error)
255
+ if (failed) {
256
+ const hint = classifyError(failed.error).hint
257
+ if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
258
+ }
259
+ if (includeReport && run.report) {
260
+ lines.push('', 'report:', '', preview(run.report))
261
+ }
262
+ if (!TERMINAL_STATUSES.has(run.status)) {
263
+ lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
264
+ } else if (run.status === 'interrupted') {
265
+ lines.push('', `next: superagent_resume run_id="${run.id}"`)
266
+ }
267
+ return lines.join('\n')
268
+ }
269
+
270
+ function formatBytes(bytes) {
271
+ if (bytes < 1024) return `${bytes} B`
272
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
273
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`
274
+ }
275
+
276
+ /** True when a run finished but its owner was never told, and that is a problem. */
277
+ function notifyFailed(run) {
278
+ if (!run.notify || run.notify.delivered) return false
279
+ return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
280
+ }
281
+
282
+ function formatList(runs, limit, stats = null) {
283
+ if (runs.length === 0) return 'no superagent runs recorded'
284
+ const rows = runs.slice(0, limit).map(run => {
285
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
286
+ return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
287
+ + `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
288
+ })
289
+ const lines = [`${runs.length} run(s):`, ...rows]
290
+ if (stats) {
291
+ lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
292
+ + (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
293
+ }
294
+ return lines.join('\n')
295
+ }
296
+
297
+ function toolText(text) {
298
+ return [{ type: 'text', text }]
299
+ }
300
+
301
+ function defineTool(spec) {
302
+ return {
303
+ name: spec.name,
304
+ description: spec.description,
305
+ parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
306
+ output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
307
+ execute: spec.execute,
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Mount the plugin.
313
+ * @param {object} ctx - Cordis context.
314
+ * @param {object} [config] - row config from `cordis.patch.yml`.
315
+ */
316
+ export function apply(ctx, config) {
317
+ const log = message => console.error(`[dsh-superagent] ${message}`)
318
+ const configuredPort = config?.controlPort
319
+ const cfg = resolveConfig(config)
320
+ if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
321
+ log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
322
+ }
323
+ if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
324
+ console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
325
+ return
326
+ }
327
+
328
+ const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
329
+ const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
330
+ const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
331
+
332
+ /** Child sessions spawned by this process; a run may not be started from one. */
333
+ const childIds = new Set()
334
+
335
+ /**
336
+ * The subagent service is optional, so it is read from the service store at
337
+ * call time rather than declared as an injection: a profile without it must
338
+ * still mount the five tools (they then explain what is missing), and reading
339
+ * it lazily also sees a service that registers after this plugin.
340
+ */
341
+ function getSubagents() {
342
+ if (typeof ctx.get === 'function') {
343
+ const service = ctx.get('subagents')
344
+ if (service) return service
345
+ }
346
+ // The direct property is topology-sensitive on a real host; it is only a
347
+ // fallback for test contexts that provide the service without a registry.
348
+ try {
349
+ return ctx.subagents
350
+ } catch {
351
+ return undefined
352
+ }
353
+ }
354
+
355
+ /** Remember a child id for the recursion guard without growing forever. */
356
+ function rememberChild(childId) {
357
+ if (!childId) return
358
+ childIds.add(childId)
359
+ if (childIds.size > 512) childIds.delete(childIds.values().next().value)
360
+ }
361
+
362
+ /**
363
+ * Map a run outcome to one message for the owning session.
364
+ *
365
+ * The followup is awaited: an unhandled rejection from it would otherwise
366
+ * escape as a host-level error while the run already claims it was delivered.
367
+ */
368
+ async function notifyParent(run) {
369
+ if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
370
+ if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
371
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
372
+ const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
373
+ if (!agent || typeof agent.followup !== 'function') {
374
+ log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
375
+ return {
376
+ delivered: false,
377
+ reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
378
+ }
379
+ }
380
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
381
+ const text = [
382
+ `[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`,
383
+ `Call superagent_status with run_id="${run.id}" to read the report.`,
384
+ ].join(' ')
385
+ try {
386
+ await agent.followup({
387
+ id: randomUUID(),
388
+ role: 'user',
389
+ content: [{ type: 'text', text }],
390
+ source: { kind: 'user' },
391
+ })
392
+ run.notified = true
393
+ return { delivered: true }
394
+ } catch (error) {
395
+ log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
396
+ return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
397
+ }
398
+ }
399
+
400
+ const orchestrator = createOrchestrator({
401
+ store,
402
+ config: cfg,
403
+ log,
404
+ readUsage,
405
+ notify: notifyParent,
406
+ async spawnChild({ label, prompt, parent, signal }) {
407
+ const subagents = getSubagents()
408
+ if (!subagents || typeof subagents.startActivation !== 'function') {
409
+ const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
410
+ // The service can also disappear in the middle of a run, when the host
411
+ // is shutting down. The orchestrator turns this code into `interrupted`
412
+ // instead of a failed subtask, so the run stays resumable.
413
+ error.code = 'subagent-unavailable'
414
+ throw error
415
+ }
416
+ const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
417
+ const capabilities = provider?.capabilities ?? null
418
+ const agentOptions = {}
419
+ if (cfg.childProvider) agentOptions.provider = cfg.childProvider
420
+ if (cfg.childModel) agentOptions.model = cfg.childModel
421
+ const request = {
422
+ parent,
423
+ prompt: [{ type: 'text', text: prompt }],
424
+ ...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
425
+ }
426
+ // A preset is the host's only way to give a child a narrower tool set:
427
+ // the start request has no tool filter in dsh 0.2.2-rc.1.
428
+ if (cfg.childPreset) {
429
+ if (capabilities && !capabilities.agentPreset) {
430
+ throw new Error(
431
+ `childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
432
+ + 'independent agent presets, so this child would run with this session\'s tools',
433
+ )
434
+ }
435
+ request.agentPreset = cfg.childPreset
436
+ }
437
+ // Recursion is bounded unless the operator explicitly left it to the
438
+ // backend. Silently dropping the cap would hand 8 parallel workers the
439
+ // right to spawn their own armies.
440
+ if (cfg.maxSubagentDepth !== 'provider-managed') {
441
+ if (capabilities && !capabilities.depthLimit) {
442
+ throw new Error(
443
+ `subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
444
+ + 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
445
+ + 'the backend\'s own cap',
446
+ )
447
+ }
448
+ request.maxDepth = cfg.maxSubagentDepth
449
+ }
450
+ const activation = await subagents.startActivation({
451
+ provider: cfg.provider,
452
+ label,
453
+ request,
454
+ signal,
455
+ delivery: 'caller',
456
+ })
457
+ rememberChild(activation.childId)
458
+ return {
459
+ childId: activation.childId,
460
+ result: activation.result,
461
+ dispose: async () => {
462
+ try {
463
+ await activation.dispose()
464
+ } catch (error) {
465
+ log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
466
+ }
467
+ },
468
+ }
469
+ },
470
+ })
471
+
472
+ // Recovery runs once at mount; tools wait for it so a run left active by a
473
+ // dead host reads as interrupted before the first tool call sees it. A
474
+ // failure to initialize the state directory is kept and reported by every
475
+ // tool: hiding it behind "no runs recorded" is how a broken stateDir looks
476
+ // like an empty one.
477
+ let stateError = null
478
+ const ready = (async () => {
479
+ try {
480
+ await orchestrator.recover()
481
+ } catch (error) {
482
+ stateError = error instanceof Error ? error : new Error(String(error))
483
+ log(`state directory is not usable: ${stateError.message}`)
484
+ return
485
+ }
486
+ if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
487
+ try {
488
+ const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
489
+ if (removed.length > 0) {
490
+ log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
491
+ }
492
+ } catch (error) {
493
+ log(`cannot prune old runs: ${error?.message ?? error}`)
494
+ }
495
+ })()
496
+
497
+ /** True when the host actually provides a subagent service. */
498
+ function hasSubagents() {
499
+ const subagents = getSubagents()
500
+ return Boolean(subagents && typeof subagents.startActivation === 'function')
501
+ }
502
+
503
+ function requireAgent(exec) {
504
+ const agent = exec?.agent
505
+ if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
506
+ if (childIds.has(agent.id)) {
507
+ return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
508
+ }
509
+ return { agent }
510
+ }
511
+
512
+ /**
513
+ * Resolve the session named by an HTTP caller. An embedded start is a normal
514
+ * run: it needs a live agent to own the children, and the same recursion
515
+ * guard as a tool call. A synthetic parent would spawn children no session
516
+ * owns, so a missing session is an error, never a fallback.
517
+ * @param {unknown} sessionId - `session_id` from the request body.
518
+ * @returns {object} live agent.
519
+ */
520
+ function resolveSession(sessionId) {
521
+ const id = typeof sessionId === 'string' ? sessionId.trim() : ''
522
+ if (!id) {
523
+ throw new Error(
524
+ 'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
525
+ )
526
+ }
527
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
528
+ const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
529
+ if (!agent || typeof agent !== 'object' || !agent.id) {
530
+ throw new Error(
531
+ `no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
532
+ + 'tool call inside it',
533
+ )
534
+ }
535
+ if (childIds.has(agent.id)) {
536
+ throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
537
+ }
538
+ return agent
539
+ }
540
+
541
+ ctx.tools.register(defineTool({
542
+ name: 'superagent_start',
543
+ description:
544
+ 'Start a long-horizon autonomous run: a planner decomposes the goal into independent subtasks, '
545
+ + 'the subtasks run in parallel child agents, and their reports are merged into one final report. '
546
+ + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
547
+ + 'so they survive a host restart and can be resumed or cancelled.',
548
+ properties: {
549
+ goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
550
+ max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
551
+ max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
552
+ deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
553
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
554
+ },
555
+ required: ['goal'],
556
+ async execute(args = {}, exec) {
557
+ const check = requireAgent(exec)
558
+ if (check.error) return check.error
559
+ try {
560
+ await ready
561
+ if (stateError) return describeError(stateError)
562
+ if (!hasSubagents()) {
563
+ return describeError(
564
+ 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
565
+ + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
566
+ )
567
+ }
568
+ const run = await orchestrator.start({
569
+ goal: args.goal,
570
+ parentSessionId: check.agent.id,
571
+ parent: check.agent,
572
+ clientTimeZone: exec.clientTimeZone,
573
+ overrides: {
574
+ maxSubtasks: args.max_subtasks,
575
+ maxParallel: args.max_parallel,
576
+ deadlineMinutes: args.deadline_minutes,
577
+ },
578
+ })
579
+ const waitSeconds = Number(args.wait_seconds) || 0
580
+ if (waitSeconds > 0) {
581
+ const finished = await orchestrator.status(run.id, waitSeconds)
582
+ return formatRun(finished)
583
+ }
584
+ return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
585
+ + 'the run keeps going after this tool call returns.'
586
+ } catch (error) {
587
+ return describeError(error)
588
+ }
589
+ },
590
+ }))
591
+
592
+ ctx.tools.register(defineTool({
593
+ name: 'superagent_status',
594
+ description:
595
+ 'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
596
+ + 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
597
+ properties: {
598
+ run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
599
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
600
+ },
601
+ required: ['run_id'],
602
+ async execute(args = {}) {
603
+ try {
604
+ await ready
605
+ if (stateError) return describeError(stateError)
606
+ const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
607
+ return formatRun(run)
608
+ } catch (error) {
609
+ return describeError(error)
610
+ }
611
+ },
612
+ }))
613
+
614
+ ctx.tools.register(defineTool({
615
+ name: 'superagent_list',
616
+ description: 'List recorded superagent runs, newest first, with status and progress.',
617
+ properties: {
618
+ limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
619
+ },
620
+ async execute(args = {}) {
621
+ try {
622
+ await ready
623
+ if (stateError) return describeError(stateError)
624
+ const runs = await orchestrator.list()
625
+ const stats = typeof store.stats === 'function' ? await store.stats() : null
626
+ return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), stats ? { ...stats, root: store.root } : null)
627
+ } catch (error) {
628
+ return describeError(error)
629
+ }
630
+ },
631
+ }))
632
+
633
+ ctx.tools.register(defineTool({
634
+ name: 'superagent_cancel',
635
+ description:
636
+ 'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
637
+ + 'so the partial work stays inspectable.',
638
+ properties: {
639
+ run_id: { type: 'string', description: 'Run id to cancel.' },
640
+ },
641
+ required: ['run_id'],
642
+ async execute(args = {}, exec) {
643
+ const check = requireAgent(exec)
644
+ if (check.error) return check.error
645
+ try {
646
+ await ready
647
+ if (stateError) return describeError(stateError)
648
+ const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
649
+ const head = run.status === 'cancelled'
650
+ ? `cancelled ${run.id}`
651
+ : run.cancelPending
652
+ ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
653
+ : `${run.id} is ${run.status}; nothing to cancel`
654
+ return `${head}\n\n${formatRun(run, { includeReport: false })}`
655
+ } catch (error) {
656
+ return describeError(error)
657
+ }
658
+ },
659
+ }))
660
+
661
+ ctx.tools.register(defineTool({
662
+ name: 'superagent_resume',
663
+ description:
664
+ 'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
665
+ + 'Completed subtasks are kept; pending and failed ones run again.',
666
+ properties: {
667
+ run_id: { type: 'string', description: 'Run id to resume.' },
668
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
669
+ },
670
+ required: ['run_id'],
671
+ async execute(args = {}, exec) {
672
+ const check = requireAgent(exec)
673
+ if (check.error) return check.error
674
+ try {
675
+ await ready
676
+ if (stateError) return describeError(stateError)
677
+ if (!hasSubagents()) {
678
+ return describeError(
679
+ 'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
680
+ )
681
+ }
682
+ const run = await orchestrator.resume(String(args.run_id ?? '').trim(), check.agent, exec.clientTimeZone)
683
+ const waitSeconds = Number(args.wait_seconds) || 0
684
+ const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
685
+ return formatRun(current)
686
+ } catch (error) {
687
+ return describeError(error)
688
+ }
689
+ },
690
+ }))
691
+
692
+ // The embedding surface is opt-in: mounting the plugin must not open a port
693
+ // unasked. When it is on, every request goes through the same orchestrator as
694
+ // the tools, so quota, budgets, ownership, and cancel behave identically.
695
+ if (cfg.controlPort !== null) {
696
+ const clampControlWait = value => {
697
+ const seconds = Number(value)
698
+ if (!Number.isFinite(seconds) || seconds <= 0) return 0
699
+ return Math.min(300, Math.trunc(seconds))
700
+ }
701
+ const control = createControlPlane({
702
+ port: cfg.controlPort,
703
+ stateRoot: store.root,
704
+ version: pkg.version,
705
+ log,
706
+ actions: {
707
+ // Liveness only: a probe must not sweep or reclaim runs, so this
708
+ // deliberately does no state-directory work. Use GET /runs to ask what
709
+ // is running.
710
+ async health() {
711
+ return { runs: 'GET /runs' }
712
+ },
713
+ async list({ limit } = {}) {
714
+ await ready
715
+ if (stateError) throw stateError
716
+ const runs = await orchestrator.list()
717
+ const stats = typeof store.stats === 'function' ? await store.stats() : null
718
+ const rows = Math.max(1, Math.min(100, Number(limit) || 20))
719
+ const visible = runs.slice(0, rows)
720
+ return {
721
+ data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
722
+ text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
723
+ }
724
+ },
725
+ async status(runId, waitSeconds) {
726
+ await ready
727
+ if (stateError) throw stateError
728
+ const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
729
+ return { data: { run }, text: formatRun(run) }
730
+ },
731
+ async start(body = {}) {
732
+ await ready
733
+ if (stateError) throw stateError
734
+ if (!hasSubagents()) {
735
+ throw new Error(
736
+ 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
737
+ + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
738
+ )
739
+ }
740
+ const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
741
+ if (!goal) {
742
+ // Report the caller's mistake as written in the docs: a missing goal
743
+ // is 400, not "you also did not name a session".
744
+ throw new Error('goal is required; pass a concrete goal string')
745
+ }
746
+ const agent = resolveSession(body.session_id)
747
+ const run = await orchestrator.start({
748
+ goal,
749
+ parentSessionId: agent.id,
750
+ parent: agent,
751
+ clientTimeZone: body.time_zone,
752
+ overrides: {
753
+ maxSubtasks: body.max_subtasks,
754
+ maxParallel: body.max_parallel,
755
+ deadlineMinutes: body.deadline_minutes,
756
+ },
757
+ })
758
+ const waitSeconds = clampControlWait(body.wait_seconds)
759
+ if (waitSeconds > 0) {
760
+ const finished = await orchestrator.status(run.id, waitSeconds)
761
+ return { data: { run: finished }, text: formatRun(finished) }
762
+ }
763
+ return {
764
+ data: { run },
765
+ text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
766
+ + `GET /runs/${run.id} or call superagent_status.`,
767
+ }
768
+ },
769
+ async cancel(runId) {
770
+ await ready
771
+ if (stateError) throw stateError
772
+ const run = await orchestrator.cancel(String(runId ?? '').trim())
773
+ const head = run.status === 'cancelled'
774
+ ? `cancelled ${run.id}`
775
+ : run.cancelPending
776
+ ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
777
+ : `${run.id} is ${run.status}; nothing to cancel`
778
+ return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
779
+ },
780
+ async resume(runId, body = {}) {
781
+ await ready
782
+ if (stateError) throw stateError
783
+ if (!hasSubagents()) {
784
+ throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
785
+ }
786
+ const agent = resolveSession(body.session_id)
787
+ const run = await orchestrator.resume(String(runId ?? '').trim(), agent, body.time_zone)
788
+ const waitSeconds = clampControlWait(body.wait_seconds)
789
+ const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
790
+ return { data: { run: current }, text: formatRun(current) }
791
+ },
792
+ },
793
+ })
794
+ let disposed = false
795
+ const stopControl = () => {
796
+ disposed = true
797
+ return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
798
+ }
799
+ if (typeof ctx.effect === 'function') {
800
+ ctx.effect(() => stopControl, 'dsh-superagent control plane')
801
+ } else if (typeof ctx.on === 'function') {
802
+ ctx.on('dispose', stopControl)
803
+ }
804
+ // The state directory is created by `orchestrator.recover()`, which `ready`
805
+ // awaits. Starting before it exists makes the discovery write fail with
806
+ // ENOENT and would leave the plane off for the whole host lifetime.
807
+ ready
808
+ .then(() => {
809
+ if (disposed || stateError) return null
810
+ return control.start()
811
+ })
812
+ .catch(error => {
813
+ log(
814
+ `control plane is not listening: ${error?.message ?? error}; `
815
+ + 'check that controlPort is free and the state directory is writable, '
816
+ + 'or remove controlPort to keep the socket closed',
817
+ )
818
+ })
819
+ }
820
+
821
+ log(`registered 5 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
822
+ }