@xiangyixie/dsh-superagent 0.9.2 → 0.10.0

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,1104 @@
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 { fileURLToPath } from 'node:url'
18
+ import pkg from '../package.json' with { type: 'json' }
19
+ import { createOrchestrator } from './orchestrator.js'
20
+ import { createControlPlane } from './control.js'
21
+ import { classifyError, describeError, summarizeError } from './errors.js'
22
+ import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
23
+ import { createNotifyPolicy, createOutbox } from './notify.js'
24
+ import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
25
+ import { createUsageReader } from './usage.js'
26
+
27
+ export const name = 'dsh-superagent'
28
+ // The host menu and sessions are required. `subagents` is read through
29
+ // `ctx.get('subagents')`, so a profile without it still mounts the six tools;
30
+ // they then report what is missing instead of the plugin silently vanishing.
31
+ export const inject = ['tools', 'agents']
32
+
33
+ const DEFAULTS = {
34
+ /** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
35
+ stateDir: null,
36
+ /** Child backend registered on `ctx.subagents`. */
37
+ provider: 'spawn',
38
+ /** Optional provider override for every child agent; unset inherits the parent's model route. */
39
+ childProvider: null,
40
+ /** Optional model override for every child agent; unset inherits the parent's model. */
41
+ childModel: null,
42
+ /**
43
+ * Optional agent preset for child agents. A preset owns the child's tool
44
+ * composition, which is the only way this host version can restrict it.
45
+ */
46
+ childPreset: null,
47
+ /**
48
+ * Delegation depth granted to child agents. 1 means a worker may not create
49
+ * children of its own; `provider-managed` leaves the cap to the backend.
50
+ */
51
+ maxSubagentDepth: 1,
52
+ /** Upper bound on planned subtasks per run. */
53
+ maxSubtasks: 8,
54
+ /** Upper bound on subtasks executing at once. */
55
+ maxParallel: 3,
56
+ /** Runs allowed to be active at the same time; further starts are rejected. */
57
+ maxActiveRuns: 2,
58
+ /** Attempts per subtask before it is marked failed. */
59
+ attempts: 2,
60
+ /** Wall-clock budget for a whole run, in minutes. */
61
+ deadlineMinutes: 120,
62
+ /** Hard cap on child model calls per run; 0 disables the cap. */
63
+ maxModelCallsPerRun: 80,
64
+ /** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
65
+ maxTokensPerRun: 2_000_000,
66
+ /**
67
+ * List prices per 1M tokens, keyed by model id as it appears in usage logs.
68
+ * Only models listed here are priced; everything else is reported as unpriced
69
+ * rather than guessed. Nothing is shipped: a stale price is worse than none.
70
+ */
71
+ pricing: {},
72
+ /** Bytes kept from one subtask report. */
73
+ resultCapBytes: 32 * 1024,
74
+ /** Write one message back to the owning session when a run finishes unattended. */
75
+ notifyOnComplete: true,
76
+ /**
77
+ * Proactive messages allowed per rolling hour. Runs that finish after the cap
78
+ * are folded into one summary instead of waking the session again.
79
+ */
80
+ maxNotificationsPerHour: 3,
81
+ /**
82
+ * Extra rounds that retry failed subtasks before the failure is reported, so
83
+ * a transient error is healed automatically instead of asking the user.
84
+ */
85
+ autoResumeRounds: 1,
86
+ /**
87
+ * Delivery attempts for one wake-up. A followup can fail while the session
88
+ * loop is busy; retrying it is the difference between a lost result and a
89
+ * late one. 0 means one attempt.
90
+ */
91
+ notifyRetries: 2,
92
+ /** First delay between delivery attempts; it doubles per attempt. */
93
+ notifyRetryDelayMs: 2000,
94
+ /**
95
+ * Child model used on a self-heal round when the failure looks transient
96
+ * (quota, rate limit, timeout). `null` keeps the configured route.
97
+ */
98
+ childModelFallback: null,
99
+ /**
100
+ * Cross-run notebook. Notes live under `stateDir` and never enter the package
101
+ * or a default commit; see the privacy section of the README.
102
+ */
103
+ memory: true,
104
+ /** Notebook scope; each scope is one file, so unrelated projects stay apart. */
105
+ memoryScope: 'default',
106
+ /** Notes kept before the notebook is compacted. */
107
+ memoryMaxEntries: 60,
108
+ /** Notes older than this are ignored, then compacted away. */
109
+ memoryMaxAgeDays: 30,
110
+ /** Notes injected into the planner and aggregator prompts. */
111
+ memoryDigestEntries: 12,
112
+ /** Character budget for the note part of that prompt context. */
113
+ memoryDigestChars: 1600,
114
+ /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
115
+ keepRuns: 0,
116
+ /**
117
+ * Loopback HTTP port for the embedding surface. `null` (default) keeps the
118
+ * socket closed; `0` asks the OS for a free port. The bound address and its
119
+ * bearer token are written to `<stateDir>/control.json`.
120
+ */
121
+ controlPort: null,
122
+ }
123
+
124
+ const REPORT_PREVIEW_CHARS = 8000
125
+
126
+ /**
127
+ * Coerce one numeric setting into its documented range. A value like "abc"
128
+ * would otherwise become NaN and silently remove a limit (NaN comparisons are
129
+ * always false), which is how a quota disappears without any error.
130
+ */
131
+ function bounded(value, fallback, min, max) {
132
+ const number = Number(value)
133
+ if (!Number.isFinite(number)) return fallback
134
+ return Math.min(max, Math.max(min, Math.trunc(number)))
135
+ }
136
+
137
+ /**
138
+ * A port is a whole number in 0–65535, or nothing. A malformed value must not
139
+ * silently open a socket somewhere unexpected, so anything else stays off.
140
+ */
141
+ function controlPortOf(value) {
142
+ if (value === null || value === undefined || value === false) return null
143
+ // Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
144
+ // real number or a plain digit string may enable the surface.
145
+ if (typeof value === 'number') {
146
+ return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
147
+ }
148
+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
149
+ const number = Number(value.trim())
150
+ return number <= 65535 ? number : null
151
+ }
152
+ return null
153
+ }
154
+
155
+ /** Read a YAML/JSON boolean without letting the string "false" mean true. */
156
+ function flag(value, fallback) {
157
+ if (value === undefined) return fallback
158
+ if (typeof value === 'string') return !/^(false|0|off|no)$/i.test(value.trim())
159
+ return Boolean(value)
160
+ }
161
+
162
+ function resolveConfig(config) {
163
+ const merged = { ...DEFAULTS }
164
+ if (config && typeof config === 'object') {
165
+ for (const [key, value] of Object.entries(config)) {
166
+ if (value !== undefined) merged[key] = value
167
+ }
168
+ }
169
+ merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
170
+ merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
171
+ merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
172
+ merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
173
+ merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
174
+ merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
175
+ merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
176
+ merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
177
+ merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
178
+ merged.controlPort = controlPortOf(merged.controlPort)
179
+ merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
180
+ ? 'provider-managed'
181
+ : bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
182
+ // Per-model prices merge, so a user can add one route without restating the
183
+ // built-in table.
184
+ merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
185
+ merged.memory = flag(merged.memory, DEFAULTS.memory)
186
+ merged.memoryScope = normalizeScope(merged.memoryScope)
187
+ merged.memoryMaxEntries = bounded(merged.memoryMaxEntries, DEFAULTS.memoryMaxEntries, 1, 500)
188
+ merged.memoryMaxAgeDays = bounded(merged.memoryMaxAgeDays, DEFAULTS.memoryMaxAgeDays, 1, 3650)
189
+ merged.memoryDigestEntries = bounded(merged.memoryDigestEntries, DEFAULTS.memoryDigestEntries, 1, 50)
190
+ merged.memoryDigestChars = bounded(merged.memoryDigestChars, DEFAULTS.memoryDigestChars, 200, 8000)
191
+ merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
192
+ merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
193
+ merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
194
+ merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
195
+ merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
196
+ ? merged.childModelFallback.trim()
197
+ : null
198
+ return merged
199
+ }
200
+
201
+ function preview(text, limit = REPORT_PREVIEW_CHARS) {
202
+ if (typeof text !== 'string') return ''
203
+ if (text.length <= limit) return text
204
+ return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
205
+ }
206
+
207
+ function durationText(ms) {
208
+ const seconds = Math.max(0, ms / 1000)
209
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
210
+ const minutes = Math.floor(seconds / 60)
211
+ return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
212
+ }
213
+
214
+ function elapsed(run) {
215
+ const start = Date.parse(run.startedAt)
216
+ const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
217
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
218
+ const wall = Math.max(0, end - start)
219
+ const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
220
+ // A resumed run can span hours of downtime. Reporting one number would make
221
+ // it look like the model worked all that time.
222
+ if (run.resumedAt && wall - active > 5000) {
223
+ return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
224
+ }
225
+ return durationText(wall)
226
+ }
227
+
228
+ function usageLine(usage, status) {
229
+ if (!usage || !usage.modelCalls) {
230
+ if (ACTIVE_STATUSES.has(status)) {
231
+ return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
232
+ }
233
+ return 'usage: not recorded — no child session log was readable for this run '
234
+ + '(usually a run created before usage tracking, or a sessions directory that moved); '
235
+ + 'token and cost figures are unavailable'
236
+ }
237
+ const models = Object.entries(usage.models ?? {})
238
+ .map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
239
+ .join('; ')
240
+ const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
241
+ return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
242
+ + (models ? ` (${models})` : '')
243
+ }
244
+
245
+ function currencySymbol(code) {
246
+ if (code === 'CNY') return '¥'
247
+ if (code === 'USD') return '$'
248
+ if (code === 'EUR') return '€'
249
+ return `${code} `
250
+ }
251
+
252
+ /**
253
+ * Cost line for one run. The number is an estimate from the configured list
254
+ * prices; models without a price are named instead of guessed so a user can
255
+ * always tell how much of the spend the figure covers.
256
+ */
257
+ function costLine(run) {
258
+ if (!run.usage || !run.usage.modelCalls) return null
259
+ const models = Object.keys(run.usage.models ?? {})
260
+ const cost = run.cost
261
+ if (!cost || Object.keys(cost.byModel).length === 0) {
262
+ return `cost: not computed — no price configured for ${models.join(', ') || 'this model'}; `
263
+ + 'add a pricing entry in cordis.patch.yml to get an estimate'
264
+ }
265
+ const money = `${currencySymbol(cost.currency)}${cost.total.toFixed(4)}`
266
+ if (cost.complete) return `cost: ${money} (estimate; all models priced)`
267
+ return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
268
+ }
269
+
270
+ /** Render one run as text for a tool result. */
271
+ function formatRun(run, { includeReport = true } = {}) {
272
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
273
+ const lines = [
274
+ `run ${run.id} — ${run.status}`,
275
+ `goal: ${run.goal}`,
276
+ `plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
277
+ + `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
278
+ `elapsed: ${elapsed(run)}`,
279
+ usageLine(run.usage, run.status),
280
+ ]
281
+ const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
282
+ if (unreadable > 0) {
283
+ lines.push(
284
+ `usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
285
+ + 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
286
+ )
287
+ }
288
+ const cost = costLine(run)
289
+ if (cost) lines.push(cost)
290
+ if (run.memory?.digest) {
291
+ lines.push(
292
+ `memory: ${run.memory.notes} note(s) and ${run.memory.runs} earlier run(s) carried into this run `
293
+ + `(${run.memory.digestChars} chars)`,
294
+ )
295
+ }
296
+ if (run.attention?.issue) {
297
+ lines.push(`attention: ${run.attention.issue}`)
298
+ }
299
+ if (run.attention?.items?.length > 0) {
300
+ const first = run.attention.items[0]
301
+ lines.push(`needs your decision: ${first.question}${first.source ? ` (from ${first.source})` : ''}`)
302
+ if (first.options?.length) lines.push(`options: ${first.options.join(' | ')}`)
303
+ if (first.reason) lines.push(`why: ${first.reason}`)
304
+ if (run.attention.items.length > 1) {
305
+ lines.push(`and ${run.attention.items.length - 1} more question(s) recorded on the run`)
306
+ }
307
+ }
308
+ if (Array.isArray(run.milestones) && run.milestones.length > 0) {
309
+ // Times are UTC because the record is ISO; a status line is not a place to
310
+ // start guessing the reader's timezone.
311
+ lines.push(`milestones: ${run.milestones
312
+ .map(milestone => `${milestone.name}@${String(milestone.at ?? '').slice(11, 19)}`)
313
+ .join(' → ')}`)
314
+ }
315
+ const reportArtifact = (run.artifacts ?? []).find(artifact => artifact?.kind === 'report')
316
+ if (reportArtifact?.path) lines.push(`report file: ${reportArtifact.path} (${reportArtifact.bytes} bytes)`)
317
+ else if (run.artifactError) lines.push(`report file: not written — ${run.artifactError}`)
318
+ if (run.deduped) {
319
+ lines.push(
320
+ 'deduped: true — an active run with the same goal already exists, so this call joined it instead of starting '
321
+ + 'a second one (pass allow_duplicate: true to start another)',
322
+ )
323
+ }
324
+ if (run.selfHeal?.retried) {
325
+ lines.push(
326
+ `self-heal: retried ${run.selfHeal.retried} failed subtask(s) in ${run.selfHeal.rounds} extra round(s); `
327
+ + `${run.selfHeal.recovered} recovered` + (run.selfHeal.model ? ` (on ${run.selfHeal.model})` : ''),
328
+ )
329
+ }
330
+ if (run.memoryWrite?.written > 0) {
331
+ lines.push(`memory: wrote ${run.memoryWrite.written} note(s) for the next run`)
332
+ } else if (run.memoryWrite?.reason && /^(the memory block|write failed)/.test(run.memoryWrite.reason)) {
333
+ lines.push(`memory note not written: ${run.memoryWrite.reason}`)
334
+ }
335
+ if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
336
+ if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
337
+ if (run.status === 'interrupted' && run.error) {
338
+ // Not a failure: the host went away and the run is waiting to be resumed.
339
+ lines.push(`note: ${run.error}`)
340
+ } else if (run.status !== 'cancelled' && run.error) {
341
+ lines.push(`error: ${summarizeError(run.error)}`)
342
+ if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
343
+ }
344
+ if (notifyFailed(run)) {
345
+ lines.push(`notify: not delivered — ${run.notify.reason}`)
346
+ }
347
+ if (run.cancelPending) {
348
+ lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
349
+ }
350
+ for (const subtask of run.subtasks) {
351
+ const tokens = subtask.usage ? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out` : ''
352
+ const detail = subtask.error ? ` — ${summarizeError(subtask.error)}` : ''
353
+ // A cancelled run never judged its unfinished subtasks, so calling them
354
+ // "pending" or "failed (attempts 0)" would misreport what happened.
355
+ const status = run.status === 'cancelled' && subtask.status !== 'completed'
356
+ ? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
357
+ : subtask.status
358
+ lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${detail}`)
359
+ }
360
+ const failed = run.subtasks.find(subtask => subtask.error)
361
+ if (failed) {
362
+ const hint = classifyError(failed.error).hint
363
+ if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
364
+ }
365
+ if (includeReport && run.report) {
366
+ lines.push('', 'report:', '', preview(run.report))
367
+ }
368
+ if (!TERMINAL_STATUSES.has(run.status)) {
369
+ lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
370
+ } else if (run.status === 'interrupted') {
371
+ lines.push('', `next: superagent_resume run_id="${run.id}"`)
372
+ }
373
+ return lines.join('\n')
374
+ }
375
+
376
+ function formatBytes(bytes) {
377
+ if (bytes < 1024) return `${bytes} B`
378
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
379
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`
380
+ }
381
+
382
+ /** True when a run finished but its owner was never told, and that is a problem. */
383
+ function notifyFailed(run) {
384
+ if (!run.notify || run.notify.delivered) return false
385
+ return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
386
+ }
387
+
388
+ /** What a failed run already tried, so the message is not just "it broke". */
389
+ function triedLine(run) {
390
+ const attempts = run.limits?.attempts ?? 1
391
+ const parts = [`tried: ${attempts} attempt(s) per subtask`]
392
+ if (run.selfHeal?.rounds > 0) {
393
+ parts.push(`${run.selfHeal.rounds} self-heal round(s), ${run.selfHeal.recovered ?? 0} recovered`)
394
+ }
395
+ if (run.selfHeal?.model) parts.push(`switched to ${run.selfHeal.model} for the retry`)
396
+ return `${parts.join('; ')}.`
397
+ }
398
+
399
+ function formatList(runs, limit, stats = null) {
400
+ if (runs.length === 0) return 'no superagent runs recorded'
401
+ const rows = runs.slice(0, limit).map(run => {
402
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
403
+ return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
404
+ + `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
405
+ })
406
+ const lines = [`${runs.length} run(s):`, ...rows]
407
+ if (stats) {
408
+ lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
409
+ + (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
410
+ if (stats.memory) {
411
+ lines.push(`memory: ${stats.memory.entries} note(s), ${formatBytes(stats.memory.bytes)} in ${path.dirname(stats.memory.path)}`)
412
+ }
413
+ if (stats.pendingNotifications > 0) {
414
+ lines.push(`notifications: ${stats.pendingNotifications} run(s) held back by the hourly limit; `
415
+ + 'they are folded into the next message')
416
+ }
417
+ }
418
+ return lines.join('\n')
419
+ }
420
+
421
+ function toolText(text) {
422
+ return [{ type: 'text', text }]
423
+ }
424
+
425
+ function defineTool(spec) {
426
+ return {
427
+ name: spec.name,
428
+ description: spec.description,
429
+ parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
430
+ output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
431
+ execute: spec.execute,
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Mount the plugin.
437
+ * @param {object} ctx - Cordis context.
438
+ * @param {object} [config] - row config from `cordis.patch.yml`.
439
+ */
440
+ export function apply(ctx, config) {
441
+ const log = message => console.error(`[dsh-superagent] ${message}`)
442
+ const configuredPort = config?.controlPort
443
+ const cfg = resolveConfig(config)
444
+ if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
445
+ log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
446
+ }
447
+ if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
448
+ console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
449
+ return
450
+ }
451
+
452
+ const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
453
+ const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
454
+ const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
455
+
456
+ // A state directory inside the installed package would put the notebook in a
457
+ // directory that is meant to be shipped byte-for-byte from git. Refuse rather
458
+ // than rely on the `.gitignore` the notebook writes for itself.
459
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
460
+ const memoryBlocked = isInside(store.root, packageRoot)
461
+ const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
462
+ if (cfg.memory && memoryBlocked) {
463
+ log(`cross-run memory stays off: stateDir ${store.root} is inside the installed package; point stateDir elsewhere`)
464
+ }
465
+ const notifyPolicy = createNotifyPolicy({
466
+ stateFile: path.join(store.root, 'notifications.json'),
467
+ maxPerHour: cfg.maxNotificationsPerHour,
468
+ warn: log,
469
+ })
470
+ // One wake-up per run, delivered in order per session. A busy session loop
471
+ // can reject a followup, so the same message is retried with backoff instead
472
+ // of being reported as lost on the first refusal.
473
+ const outbox = createOutbox({ retries: cfg.notifyRetries, delayMs: cfg.notifyRetryDelayMs })
474
+
475
+ /** Child sessions spawned by this process; a run may not be started from one. */
476
+ const childIds = new Set()
477
+
478
+ /**
479
+ * The subagent service is optional, so it is read from the service store at
480
+ * call time rather than declared as an injection: a profile without it must
481
+ * still mount the six tools (they then explain what is missing), and reading
482
+ * it lazily also sees a service that registers after this plugin.
483
+ */
484
+ function getSubagents() {
485
+ if (typeof ctx.get === 'function') {
486
+ const service = ctx.get('subagents')
487
+ if (service) return service
488
+ }
489
+ // The direct property is topology-sensitive on a real host; it is only a
490
+ // fallback for test contexts that provide the service without a registry.
491
+ try {
492
+ return ctx.subagents
493
+ } catch {
494
+ return undefined
495
+ }
496
+ }
497
+
498
+ /** Remember a child id for the recursion guard without growing forever. */
499
+ function rememberChild(childId) {
500
+ if (!childId) return
501
+ childIds.add(childId)
502
+ if (childIds.size > 512) childIds.delete(childIds.values().next().value)
503
+ }
504
+
505
+ /**
506
+ * Map a run outcome to one message for the owning session.
507
+ *
508
+ * The notification policy decides first: a cancelled run is never announced,
509
+ * and a burst above the hourly cap is buffered instead of waking the session
510
+ * once per run. The followup is awaited: an unhandled rejection from it would
511
+ * otherwise escape as a host-level error while the run already claims it was
512
+ * delivered.
513
+ */
514
+ async function notifyParent(run) {
515
+ if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
516
+ if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
517
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
518
+ const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
519
+ if (!agent || typeof agent.followup !== 'function') {
520
+ log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
521
+ return {
522
+ delivered: false,
523
+ reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
524
+ }
525
+ }
526
+ // Reserve only once the session is known to exist: a missing session is not
527
+ // an interruption and must not consume the hourly budget.
528
+ const verdict = await notifyPolicy.reserve(run)
529
+ if (!verdict.allowed) return { delivered: false, reason: verdict.reason }
530
+
531
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
532
+ const decision = run.attention?.items?.[0] ?? null
533
+ const lines = decision
534
+ ? [`[superagent] needs your decision on run ${run.id}: ${decision.question}`]
535
+ : [`[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`]
536
+ if (decision) {
537
+ if (decision.options?.length) lines.push(`Options: ${decision.options.join(' / ')}.`)
538
+ lines.push(`The run itself ended as ${run.status} (${completed}/${run.subtasks.length} subtasks).`)
539
+ } else if (run.attention?.issue) {
540
+ // A malformed block asked for a decision too; keeping it quiet would look
541
+ // like an ordinary finished run.
542
+ lines.push(`Attention: ${run.attention.issue}.`)
543
+ }
544
+ if (!decision && run.status !== 'completed') lines.push(triedLine(run))
545
+ if (verdict.batch.length > 0) {
546
+ lines.push(
547
+ 'Also finished since the last update: '
548
+ + `${verdict.batch.map(item => `${item.id} ${item.status}`).join('; ')}.`,
549
+ )
550
+ }
551
+ lines.push(`Call superagent_status with run_id="${run.id}" to read the report.`)
552
+ try {
553
+ await outbox.enqueue(run.parentSessionId, () => agent.followup({
554
+ id: randomUUID(),
555
+ role: 'user',
556
+ content: [{ type: 'text', text: lines.join(' ') }],
557
+ source: { kind: 'user' },
558
+ }))
559
+ run.notified = true
560
+ return { delivered: true }
561
+ } catch (error) {
562
+ log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
563
+ // The folded runs were reserved but never delivered. Put them back so the
564
+ // next allowed message still carries them, up to the policy's retry cap.
565
+ await notifyPolicy.restore(verdict.batch).catch(restoreError => {
566
+ log(`cannot restore ${verdict.batch.length} batched notification(s): ${restoreError?.message ?? restoreError}`)
567
+ })
568
+ return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
569
+ }
570
+ }
571
+
572
+ const orchestrator = createOrchestrator({
573
+ store,
574
+ config: cfg,
575
+ log,
576
+ readUsage,
577
+ memory,
578
+ notify: notifyParent,
579
+ async spawnChild({ label, prompt, parent, signal, model }) {
580
+ const subagents = getSubagents()
581
+ if (!subagents || typeof subagents.startActivation !== 'function') {
582
+ const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
583
+ // The service can also disappear in the middle of a run, when the host
584
+ // is shutting down. The orchestrator turns this code into `interrupted`
585
+ // instead of a failed subtask, so the run stays resumable.
586
+ error.code = 'subagent-unavailable'
587
+ throw error
588
+ }
589
+ const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
590
+ const capabilities = provider?.capabilities ?? null
591
+ const agentOptions = {}
592
+ // Only the self-heal round passes a model override; everything else keeps
593
+ // the configured route.
594
+ const childModel = model ?? cfg.childModel
595
+ if (cfg.childProvider) agentOptions.provider = cfg.childProvider
596
+ if (childModel) agentOptions.model = childModel
597
+ const request = {
598
+ parent,
599
+ prompt: [{ type: 'text', text: prompt }],
600
+ ...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
601
+ }
602
+ // A preset is the host's only way to give a child a narrower tool set:
603
+ // the start request has no tool filter in dsh 0.2.2-rc.1.
604
+ if (cfg.childPreset) {
605
+ if (capabilities && !capabilities.agentPreset) {
606
+ throw new Error(
607
+ `childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
608
+ + 'independent agent presets, so this child would run with this session\'s tools',
609
+ )
610
+ }
611
+ request.agentPreset = cfg.childPreset
612
+ }
613
+ // Recursion is bounded unless the operator explicitly left it to the
614
+ // backend. Silently dropping the cap would hand 8 parallel workers the
615
+ // right to spawn their own armies.
616
+ if (cfg.maxSubagentDepth !== 'provider-managed') {
617
+ if (capabilities && !capabilities.depthLimit) {
618
+ throw new Error(
619
+ `subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
620
+ + 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
621
+ + 'the backend\'s own cap',
622
+ )
623
+ }
624
+ request.maxDepth = cfg.maxSubagentDepth
625
+ }
626
+ const activation = await subagents.startActivation({
627
+ provider: cfg.provider,
628
+ label,
629
+ request,
630
+ signal,
631
+ delivery: 'caller',
632
+ })
633
+ rememberChild(activation.childId)
634
+ return {
635
+ childId: activation.childId,
636
+ result: activation.result,
637
+ dispose: async () => {
638
+ try {
639
+ await activation.dispose()
640
+ } catch (error) {
641
+ log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
642
+ }
643
+ },
644
+ }
645
+ },
646
+ })
647
+
648
+ // Recovery runs once at mount; tools wait for it so a run left active by a
649
+ // dead host reads as interrupted before the first tool call sees it. A
650
+ // failure to initialize the state directory is kept and reported by every
651
+ // tool: hiding it behind "no runs recorded" is how a broken stateDir looks
652
+ // like an empty one.
653
+ let stateError = null
654
+ const ready = (async () => {
655
+ try {
656
+ await orchestrator.recover()
657
+ } catch (error) {
658
+ stateError = error instanceof Error ? error : new Error(String(error))
659
+ log(`state directory is not usable: ${stateError.message}`)
660
+ return
661
+ }
662
+ if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
663
+ try {
664
+ const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
665
+ if (removed.length > 0) {
666
+ log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
667
+ }
668
+ } catch (error) {
669
+ log(`cannot prune old runs: ${error?.message ?? error}`)
670
+ }
671
+ })()
672
+
673
+ /** True when the host actually provides a subagent service. */
674
+ function hasSubagents() {
675
+ const subagents = getSubagents()
676
+ return Boolean(subagents && typeof subagents.startActivation === 'function')
677
+ }
678
+
679
+ function requireAgent(exec) {
680
+ const agent = exec?.agent
681
+ if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
682
+ if (childIds.has(agent.id)) {
683
+ return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
684
+ }
685
+ return { agent }
686
+ }
687
+
688
+ /**
689
+ * Resolve the session named by an HTTP caller. An embedded start is a normal
690
+ * run: it needs a live agent to own the children, and the same recursion
691
+ * guard as a tool call. A synthetic parent would spawn children no session
692
+ * owns, so a missing session is an error, never a fallback.
693
+ * @param {unknown} sessionId - `session_id` from the request body.
694
+ * @returns {object} live agent.
695
+ */
696
+ function resolveSession(sessionId) {
697
+ const id = typeof sessionId === 'string' ? sessionId.trim() : ''
698
+ if (!id) {
699
+ throw new Error(
700
+ 'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
701
+ )
702
+ }
703
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
704
+ const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
705
+ if (!agent || typeof agent !== 'object' || !agent.id) {
706
+ throw new Error(
707
+ `no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
708
+ + 'tool call inside it',
709
+ )
710
+ }
711
+ if (childIds.has(agent.id)) {
712
+ throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
713
+ }
714
+ return agent
715
+ }
716
+
717
+ ctx.tools.register(defineTool({
718
+ name: 'superagent_start',
719
+ description:
720
+ 'Start a long-horizon autonomous run: a planner decomposes the goal into independent subtasks, '
721
+ + 'the subtasks run in parallel child agents, and their reports are merged into one final report. '
722
+ + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
723
+ + 'so they survive a host restart and can be resumed or cancelled.',
724
+ properties: {
725
+ goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
726
+ max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
727
+ max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
728
+ deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
729
+ allow_duplicate: {
730
+ type: 'boolean',
731
+ description: 'Start a second run for the same goal even when an active run already has it. '
732
+ + 'By default the active run id is returned instead, so a retry cannot double the spend.',
733
+ },
734
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
735
+ },
736
+ required: ['goal'],
737
+ async execute(args = {}, exec) {
738
+ const check = requireAgent(exec)
739
+ if (check.error) return check.error
740
+ try {
741
+ await ready
742
+ if (stateError) return describeError(stateError)
743
+ if (!hasSubagents()) {
744
+ return describeError(
745
+ 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
746
+ + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
747
+ )
748
+ }
749
+ const run = await orchestrator.start({
750
+ goal: args.goal,
751
+ parentSessionId: check.agent.id,
752
+ parent: check.agent,
753
+ clientTimeZone: exec.clientTimeZone,
754
+ allowDuplicate: args.allow_duplicate === true,
755
+ overrides: {
756
+ maxSubtasks: args.max_subtasks,
757
+ maxParallel: args.max_parallel,
758
+ deadlineMinutes: args.deadline_minutes,
759
+ },
760
+ })
761
+ const waitSeconds = Number(args.wait_seconds) || 0
762
+ if (waitSeconds > 0) {
763
+ const finished = await orchestrator.status(run.id, waitSeconds)
764
+ // `status` reads the stored run, which never has the transient join
765
+ // marker; carry it over so the caller can still see it joined.
766
+ return formatRun(run.deduped ? { ...finished, deduped: true } : finished)
767
+ }
768
+ return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
769
+ + 'the run keeps going after this tool call returns.'
770
+ } catch (error) {
771
+ return describeError(error)
772
+ }
773
+ },
774
+ }))
775
+
776
+ ctx.tools.register(defineTool({
777
+ name: 'superagent_status',
778
+ description:
779
+ 'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
780
+ + 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
781
+ properties: {
782
+ run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
783
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
784
+ },
785
+ required: ['run_id'],
786
+ async execute(args = {}) {
787
+ try {
788
+ await ready
789
+ if (stateError) return describeError(stateError)
790
+ const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
791
+ return formatRun(run)
792
+ } catch (error) {
793
+ return describeError(error)
794
+ }
795
+ },
796
+ }))
797
+
798
+ ctx.tools.register(defineTool({
799
+ name: 'superagent_list',
800
+ description: 'List recorded superagent runs, newest first, with status and progress.',
801
+ properties: {
802
+ limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
803
+ },
804
+ async execute(args = {}) {
805
+ try {
806
+ await ready
807
+ if (stateError) return describeError(stateError)
808
+ const runs = await orchestrator.list()
809
+ const stats = typeof store.stats === 'function' ? await store.stats() : null
810
+ const memoryStats = memory
811
+ ? await memory.stats({ scope: cfg.memoryScope, maxAgeDays: cfg.memoryMaxAgeDays }).catch(() => null)
812
+ : null
813
+ const notifyState = await notifyPolicy.summary().catch(() => null)
814
+ const extra = stats
815
+ ? {
816
+ ...stats,
817
+ root: store.root,
818
+ memory: memoryStats,
819
+ pendingNotifications: notifyState?.pending?.length ?? 0,
820
+ }
821
+ : null
822
+ return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
823
+ } catch (error) {
824
+ return describeError(error)
825
+ }
826
+ },
827
+ }))
828
+
829
+ ctx.tools.register(defineTool({
830
+ name: 'superagent_cancel',
831
+ description:
832
+ 'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
833
+ + 'so the partial work stays inspectable.',
834
+ properties: {
835
+ run_id: { type: 'string', description: 'Run id to cancel.' },
836
+ },
837
+ required: ['run_id'],
838
+ async execute(args = {}, exec) {
839
+ const check = requireAgent(exec)
840
+ if (check.error) return check.error
841
+ try {
842
+ await ready
843
+ if (stateError) return describeError(stateError)
844
+ const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
845
+ const head = run.status === 'cancelled'
846
+ ? `cancelled ${run.id}`
847
+ : run.cancelPending
848
+ ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
849
+ : `${run.id} is ${run.status}; nothing to cancel`
850
+ return `${head}\n\n${formatRun(run, { includeReport: false })}`
851
+ } catch (error) {
852
+ return describeError(error)
853
+ }
854
+ },
855
+ }))
856
+
857
+ ctx.tools.register(defineTool({
858
+ name: 'superagent_resume',
859
+ description:
860
+ 'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
861
+ + 'Completed subtasks are kept; pending and failed ones run again.',
862
+ properties: {
863
+ run_id: { type: 'string', description: 'Run id to resume.' },
864
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
865
+ force: {
866
+ type: 'boolean',
867
+ description: 'Accepted for backward compatibility and ignored: a resume is never refused by maxActiveRuns.',
868
+ },
869
+ },
870
+ required: ['run_id'],
871
+ async execute(args = {}, exec) {
872
+ const check = requireAgent(exec)
873
+ if (check.error) return check.error
874
+ try {
875
+ await ready
876
+ if (stateError) return describeError(stateError)
877
+ if (!hasSubagents()) {
878
+ return describeError(
879
+ 'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
880
+ )
881
+ }
882
+ const run = await orchestrator.resume(
883
+ String(args.run_id ?? '').trim(),
884
+ check.agent,
885
+ exec.clientTimeZone,
886
+ { force: args.force === true },
887
+ )
888
+ const waitSeconds = Number(args.wait_seconds) || 0
889
+ const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
890
+ return formatRun(current)
891
+ } catch (error) {
892
+ return describeError(error)
893
+ }
894
+ },
895
+ }))
896
+
897
+ ctx.tools.register(defineTool({
898
+ name: 'superagent_memory',
899
+ description:
900
+ 'Read or correct the cross-run notebook: short notes that earlier runs left for the next one. '
901
+ + 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it.',
902
+ properties: {
903
+ action: { type: 'string', enum: ['list', 'set', 'forget'], description: 'List notes, set (add or correct) one, or forget one.' },
904
+ key: { type: 'string', description: 'Short topic key. A new note with the same key replaces the older one.' },
905
+ kind: { type: 'string', enum: [...MEMORY_KINDS], description: 'decision, pitfall, next, dispatch, or note.' },
906
+ text: { type: 'string', description: 'The durable fact to record (set only).' },
907
+ scope: {
908
+ type: 'string',
909
+ description: 'Notebook scope: "rules" for project rules, "profile" for user preferences, '
910
+ + 'or the run scope (default) that earlier runs write to.',
911
+ },
912
+ limit: { type: 'number', description: 'Maximum notes to print (default 20).' },
913
+ },
914
+ required: ['action'],
915
+ async execute(args = {}, exec) {
916
+ const check = requireAgent(exec)
917
+ if (check.error) return check.error
918
+ if (!memory) {
919
+ return describeError(
920
+ 'cross-run memory is disabled (memory: false, or stateDir points inside the installed package)',
921
+ )
922
+ }
923
+ try {
924
+ await ready
925
+ if (stateError) return describeError(stateError)
926
+ const action = String(args.action ?? '').trim().toLowerCase()
927
+ // A run writes to the configured scope; `rules` and `profile` are
928
+ // curated by hand and read into every run, so the tool can address
929
+ // them explicitly.
930
+ const scope = args.scope === undefined || args.scope === null
931
+ ? cfg.memoryScope
932
+ : normalizeScope(args.scope)
933
+ if (action === 'list') {
934
+ // Capped at 30: this output goes straight into the model context, and a
935
+ // 200-row dump would cost more than the notes are worth.
936
+ const limit = Math.max(1, Math.min(30, Number(args.limit) || 20))
937
+ const result = await memory.list({ scope, limit, maxAgeDays: cfg.memoryMaxAgeDays })
938
+ if (result.total === 0) return `no notes recorded in scope "${scope}" (${result.path})`
939
+ const rows = result.entries.map(entry => `- ${entry.key} [${entry.kind}] ${entry.text}`)
940
+ const notes = result.bad ? `\n\n${result.bad} unreadable line(s) skipped` : ''
941
+ return `${result.total} note(s) in scope "${scope}" (${result.path})\n\n${rows.join('\n')}${notes}`
942
+ }
943
+ if (action === 'forget') {
944
+ const key = String(args.key ?? '').trim()
945
+ if (!key) return describeError('forget needs the key of the note to retract; call action="list" first')
946
+ const result = await memory.forget({ scope, key })
947
+ return result.forgotten
948
+ ? `retracted "${key}" in scope "${scope}"; later runs will not see it`
949
+ : describeError(result.reason ?? 'cannot retract that note')
950
+ }
951
+ if (action === 'set') {
952
+ const key = String(args.key ?? '').trim()
953
+ const text = String(args.text ?? '').trim()
954
+ if (!key || !text) return describeError('set needs both key and text')
955
+ const result = await memory.set({ scope, key, kind: args.kind, text })
956
+ return result.written > 0
957
+ ? `recorded "${key}" in scope "${scope}"; later runs will see it`
958
+ : describeError(result.reason ?? 'cannot record that note')
959
+ }
960
+ return describeError(`unknown action "${args.action}"; use list, set, or forget`)
961
+ } catch (error) {
962
+ return describeError(error)
963
+ }
964
+ },
965
+ }))
966
+
967
+ // The embedding surface is opt-in: mounting the plugin must not open a port
968
+ // unasked. When it is on, every request goes through the same orchestrator as
969
+ // the tools, so quota, budgets, ownership, and cancel behave identically.
970
+ if (cfg.controlPort !== null) {
971
+ const clampControlWait = value => {
972
+ const seconds = Number(value)
973
+ if (!Number.isFinite(seconds) || seconds <= 0) return 0
974
+ return Math.min(300, Math.trunc(seconds))
975
+ }
976
+ const control = createControlPlane({
977
+ port: cfg.controlPort,
978
+ stateRoot: store.root,
979
+ version: pkg.version,
980
+ log,
981
+ actions: {
982
+ // Liveness only: a probe must not sweep or reclaim runs, so this
983
+ // deliberately does no state-directory work. Use GET /runs to ask what
984
+ // is running.
985
+ async health() {
986
+ return { runs: 'GET /runs' }
987
+ },
988
+ async list({ limit } = {}) {
989
+ await ready
990
+ if (stateError) throw stateError
991
+ const runs = await orchestrator.list()
992
+ const stats = typeof store.stats === 'function' ? await store.stats() : null
993
+ const rows = Math.max(1, Math.min(100, Number(limit) || 20))
994
+ const visible = runs.slice(0, rows)
995
+ return {
996
+ data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
997
+ text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
998
+ }
999
+ },
1000
+ async status(runId, waitSeconds) {
1001
+ await ready
1002
+ if (stateError) throw stateError
1003
+ const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
1004
+ return { data: { run }, text: formatRun(run) }
1005
+ },
1006
+ async start(body = {}) {
1007
+ await ready
1008
+ if (stateError) throw stateError
1009
+ if (!hasSubagents()) {
1010
+ throw new Error(
1011
+ 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
1012
+ + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
1013
+ )
1014
+ }
1015
+ const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
1016
+ if (!goal) {
1017
+ // Report the caller's mistake as written in the docs: a missing goal
1018
+ // is 400, not "you also did not name a session".
1019
+ throw new Error('goal is required; pass a concrete goal string')
1020
+ }
1021
+ const agent = resolveSession(body.session_id)
1022
+ const run = await orchestrator.start({
1023
+ goal,
1024
+ parentSessionId: agent.id,
1025
+ parent: agent,
1026
+ clientTimeZone: body.time_zone,
1027
+ allowDuplicate: body.allow_duplicate === true,
1028
+ overrides: {
1029
+ maxSubtasks: body.max_subtasks,
1030
+ maxParallel: body.max_parallel,
1031
+ deadlineMinutes: body.deadline_minutes,
1032
+ },
1033
+ })
1034
+ const waitSeconds = clampControlWait(body.wait_seconds)
1035
+ if (waitSeconds > 0) {
1036
+ const finished = await orchestrator.status(run.id, waitSeconds)
1037
+ const current = run.deduped ? { ...finished, deduped: true } : finished
1038
+ return { data: { run: current }, text: formatRun(current) }
1039
+ }
1040
+ return {
1041
+ data: { run },
1042
+ text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
1043
+ + `GET /runs/${run.id} or call superagent_status.`,
1044
+ }
1045
+ },
1046
+ async cancel(runId) {
1047
+ await ready
1048
+ if (stateError) throw stateError
1049
+ const run = await orchestrator.cancel(String(runId ?? '').trim())
1050
+ const head = run.status === 'cancelled'
1051
+ ? `cancelled ${run.id}`
1052
+ : run.cancelPending
1053
+ ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
1054
+ : `${run.id} is ${run.status}; nothing to cancel`
1055
+ return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
1056
+ },
1057
+ async resume(runId, body = {}) {
1058
+ await ready
1059
+ if (stateError) throw stateError
1060
+ if (!hasSubagents()) {
1061
+ throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
1062
+ }
1063
+ const agent = resolveSession(body.session_id)
1064
+ const run = await orchestrator.resume(
1065
+ String(runId ?? '').trim(),
1066
+ agent,
1067
+ body.time_zone,
1068
+ { force: body.force === true || body.override_quota === true },
1069
+ )
1070
+ const waitSeconds = clampControlWait(body.wait_seconds)
1071
+ const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
1072
+ return { data: { run: current }, text: formatRun(current) }
1073
+ },
1074
+ },
1075
+ })
1076
+ let disposed = false
1077
+ const stopControl = () => {
1078
+ disposed = true
1079
+ return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
1080
+ }
1081
+ if (typeof ctx.effect === 'function') {
1082
+ ctx.effect(() => stopControl, 'dsh-superagent control plane')
1083
+ } else if (typeof ctx.on === 'function') {
1084
+ ctx.on('dispose', stopControl)
1085
+ }
1086
+ // The state directory is created by `orchestrator.recover()`, which `ready`
1087
+ // awaits. Starting before it exists makes the discovery write fail with
1088
+ // ENOENT and would leave the plane off for the whole host lifetime.
1089
+ ready
1090
+ .then(() => {
1091
+ if (disposed || stateError) return null
1092
+ return control.start()
1093
+ })
1094
+ .catch(error => {
1095
+ log(
1096
+ `control plane is not listening: ${error?.message ?? error}; `
1097
+ + 'check that controlPort is free and the state directory is writable, '
1098
+ + 'or remove controlPort to keep the socket closed',
1099
+ )
1100
+ })
1101
+ }
1102
+
1103
+ log(`registered 6 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
1104
+ }