@xiangyixie/dsh-superagent 0.10.0 → 0.11.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,1104 +1,1547 @@
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
- }
1
+ /**
2
+ * dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
3
+ *
4
+ * One goal enters; a planner decomposes it into subtasks; independent subtasks
5
+ * run in parallel child agents while a declared dependency holds the rest back;
6
+ * an aggregator merges their reports. Runs survive a host restart, can be
7
+ * cancelled, and have their token usage read back from the child sessions'
8
+ * durable logs.
9
+ *
10
+ * Registered tools: superagent_start, superagent_status, superagent_list,
11
+ * superagent_cancel, superagent_resume, superagent_followup,
12
+ * superagent_answer, superagent_memory, superagent_template.
13
+ *
14
+ * @module dsh-superagent
15
+ */
16
+ import { randomUUID } from 'node:crypto'
17
+ import os from 'node:os'
18
+ import path from 'node:path'
19
+ import { fileURLToPath } from 'node:url'
20
+ import pkg from '../package.json' with { type: 'json' }
21
+ import { createOrchestrator, followupEffect } from './orchestrator.js'
22
+ import { createControlPlane } from './control.js'
23
+ import { formatMoney } from './cost.js'
24
+ import { classifyError, describeError, summarizeError } from './errors.js'
25
+ import { createLedger } from './ledger.js'
26
+ import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
27
+ import { createNotifyPolicy, createOutbox } from './notify.js'
28
+ import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
29
+ import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
30
+ import { createUsageReader } from './usage.js'
31
+ import { describeWorkspace } from './workspace.js'
32
+
33
+ export const name = 'dsh-superagent'
34
+ // The host menu and sessions are required. `subagents` is read through
35
+ // `ctx.get('subagents')`, so a profile without it still mounts the eight tools;
36
+ // they then report what is missing instead of the plugin silently vanishing.
37
+ export const inject = ['tools', 'agents']
38
+
39
+ const DEFAULTS = {
40
+ /** Directory for run state; defaults to `$DSH_HOME/state/superagent`. */
41
+ stateDir: null,
42
+ /** Child backend registered on `ctx.subagents`. */
43
+ provider: 'spawn',
44
+ /** Optional provider override for every child agent; unset inherits the parent's model route. */
45
+ childProvider: null,
46
+ /** Optional model override for every child agent; unset inherits the parent's model. */
47
+ childModel: null,
48
+ /**
49
+ * Optional agent preset for child agents. A preset owns the child's tool
50
+ * composition, which is the only way this host version can restrict it.
51
+ */
52
+ childPreset: null,
53
+ /**
54
+ * Delegation depth granted to child agents. 1 means a worker may not create
55
+ * children of its own; `provider-managed` leaves the cap to the backend.
56
+ */
57
+ maxSubagentDepth: 1,
58
+ /** Upper bound on planned subtasks per run. */
59
+ maxSubtasks: 8,
60
+ /** Upper bound on subtasks executing at once. */
61
+ maxParallel: 3,
62
+ /** Runs allowed to be active at the same time; a start over this waits instead of failing. */
63
+ maxActiveRuns: 2,
64
+ /** Runs allowed to wait for a free slot when queueing is on; 0 disables queueing. */
65
+ maxQueuedRuns: 5,
66
+ /** How long a queued run waits before it fails, in minutes. */
67
+ queueTimeoutMinutes: 30,
68
+ /**
69
+ * Queue starts that did not ask for it with `queue: true`. Off by default: a
70
+ * caller opts in, so a script that relied on the quota error keeps seeing it.
71
+ */
72
+ queueOnFull: false,
73
+ /** Attempts per subtask before it is marked failed. */
74
+ attempts: 2,
75
+ /** Wall-clock budget for a whole run, in minutes. */
76
+ deadlineMinutes: 120,
77
+ /** Hard cap on child model calls per run; 0 disables the cap. */
78
+ maxModelCallsPerRun: 80,
79
+ /** Hard cap on prompt + completion tokens per run; 0 disables the cap. */
80
+ maxTokensPerRun: 2_000_000,
81
+ /**
82
+ * List prices per 1M tokens, keyed by model id as it appears in usage logs.
83
+ * Only models listed here are priced; everything else is reported as unpriced
84
+ * rather than guessed. Nothing is shipped: a stale price is worse than none.
85
+ */
86
+ pricing: {},
87
+ /** Bytes kept from one subtask report. */
88
+ resultCapBytes: 32 * 1024,
89
+ /** Write one message back to the owning session when a run finishes unattended. */
90
+ notifyOnComplete: true,
91
+ /**
92
+ * Proactive messages allowed per rolling hour. Runs that finish after the cap
93
+ * are folded into one summary instead of waking the session again.
94
+ */
95
+ maxNotificationsPerHour: 3,
96
+ /**
97
+ * Extra rounds that retry failed subtasks before the failure is reported, so
98
+ * a transient error is healed automatically instead of asking the user.
99
+ */
100
+ autoResumeRounds: 1,
101
+ /**
102
+ * Delivery attempts for one wake-up. A followup can fail while the session
103
+ * loop is busy; retrying it is the difference between a lost result and a
104
+ * late one. 0 means one attempt.
105
+ */
106
+ notifyRetries: 2,
107
+ /** First delay between delivery attempts; it doubles per attempt. */
108
+ notifyRetryDelayMs: 2000,
109
+ /**
110
+ * Child model used on a self-heal round when the failure looks transient
111
+ * (quota, rate limit, timeout). `null` keeps the configured route.
112
+ */
113
+ childModelFallback: null,
114
+ /**
115
+ * Cross-run notebook. Notes live under `stateDir` and never enter the package
116
+ * or a default commit; see the privacy section of the README.
117
+ */
118
+ memory: true,
119
+ /** Notebook scope; each scope is one file, so unrelated projects stay apart. */
120
+ memoryScope: 'default',
121
+ /** Notes kept before the notebook is compacted. */
122
+ memoryMaxEntries: 60,
123
+ /** Notes older than this are ignored, then compacted away. */
124
+ memoryMaxAgeDays: 30,
125
+ /** Notes injected into the planner and aggregator prompts. */
126
+ memoryDigestEntries: 12,
127
+ /** Character budget for the note part of that prompt context. */
128
+ memoryDigestChars: 1600,
129
+ /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
130
+ keepRuns: 0,
131
+ /**
132
+ * Loopback HTTP port for the embedding surface. `null` (default) keeps the
133
+ * socket closed; `0` asks the OS for a free port. The bound address and its
134
+ * bearer token are written to `<stateDir>/control.json`.
135
+ */
136
+ controlPort: null,
137
+ /**
138
+ * Run every worker in its own git worktree of `workspaceRoot`, so parallel
139
+ * workers cannot overwrite each other's files. Off by default: it needs a
140
+ * git repository and it moves files, which is not something a plugin should
141
+ * start doing unasked.
142
+ */
143
+ workspaceIsolation: false,
144
+ /** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
145
+ workspaceRoot: null,
146
+ }
147
+
148
+ const REPORT_PREVIEW_CHARS = 8000
149
+
150
+ /**
151
+ * Coerce one numeric setting into its documented range. A value like "abc"
152
+ * would otherwise become NaN and silently remove a limit (NaN comparisons are
153
+ * always false), which is how a quota disappears without any error.
154
+ */
155
+ function bounded(value, fallback, min, max) {
156
+ const number = Number(value)
157
+ if (!Number.isFinite(number)) return fallback
158
+ return Math.min(max, Math.max(min, Math.trunc(number)))
159
+ }
160
+
161
+ /**
162
+ * A port is a whole number in 0–65535, or nothing. A malformed value must not
163
+ * silently open a socket somewhere unexpected, so anything else stays off.
164
+ */
165
+ function controlPortOf(value) {
166
+ if (value === null || value === undefined || value === false) return null
167
+ // Coercion would turn "" and " " into 0, i.e. an accidental listener; only a
168
+ // real number or a plain digit string may enable the surface.
169
+ if (typeof value === 'number') {
170
+ return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : null
171
+ }
172
+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
173
+ const number = Number(value.trim())
174
+ return number <= 65535 ? number : null
175
+ }
176
+ return null
177
+ }
178
+
179
+ /** Read a YAML/JSON boolean without letting the string "false" mean true. */
180
+ function flag(value, fallback) {
181
+ if (value === undefined) return fallback
182
+ if (typeof value === 'string') return !/^(false|0|off|no)$/i.test(value.trim())
183
+ return Boolean(value)
184
+ }
185
+
186
+ function resolveConfig(config) {
187
+ const merged = { ...DEFAULTS }
188
+ if (config && typeof config === 'object') {
189
+ for (const [key, value] of Object.entries(config)) {
190
+ if (value !== undefined) merged[key] = value
191
+ }
192
+ }
193
+ merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
194
+ merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
195
+ merged.maxActiveRuns = bounded(merged.maxActiveRuns, DEFAULTS.maxActiveRuns, 1, 8)
196
+ merged.maxQueuedRuns = bounded(merged.maxQueuedRuns, DEFAULTS.maxQueuedRuns, 0, 32)
197
+ merged.queueTimeoutMinutes = bounded(merged.queueTimeoutMinutes, DEFAULTS.queueTimeoutMinutes, 1, 720)
198
+ merged.queueOnFull = flag(merged.queueOnFull, DEFAULTS.queueOnFull)
199
+ merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
200
+ merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
201
+ merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
202
+ merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
203
+ merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
204
+ merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
205
+ merged.controlPort = controlPortOf(merged.controlPort)
206
+ merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
207
+ ? 'provider-managed'
208
+ : bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
209
+ // Per-model prices merge, so a user can add one route without restating the
210
+ // built-in table.
211
+ merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
212
+ merged.memory = flag(merged.memory, DEFAULTS.memory)
213
+ merged.memoryScope = normalizeScope(merged.memoryScope)
214
+ merged.memoryMaxEntries = bounded(merged.memoryMaxEntries, DEFAULTS.memoryMaxEntries, 1, 500)
215
+ merged.memoryMaxAgeDays = bounded(merged.memoryMaxAgeDays, DEFAULTS.memoryMaxAgeDays, 1, 3650)
216
+ merged.memoryDigestEntries = bounded(merged.memoryDigestEntries, DEFAULTS.memoryDigestEntries, 1, 50)
217
+ merged.memoryDigestChars = bounded(merged.memoryDigestChars, DEFAULTS.memoryDigestChars, 200, 8000)
218
+ merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
219
+ merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
220
+ merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
221
+ merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
222
+ merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
223
+ ? merged.childModelFallback.trim()
224
+ : null
225
+ merged.workspaceIsolation = flag(merged.workspaceIsolation, DEFAULTS.workspaceIsolation)
226
+ // A blank path would resolve to the cwd, which is how isolation would silently
227
+ // point at the wrong repository; blank therefore means "use the default".
228
+ merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
229
+ ? merged.workspaceRoot.trim()
230
+ : null
231
+ return merged
232
+ }
233
+
234
+ function preview(text, limit = REPORT_PREVIEW_CHARS) {
235
+ if (typeof text !== 'string') return ''
236
+ if (text.length <= limit) return text
237
+ return `${text.slice(0, limit)}\n\n[report truncated to ${limit} characters; full text is in the run state file]`
238
+ }
239
+
240
+ function durationText(ms) {
241
+ const seconds = Math.max(0, ms / 1000)
242
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
243
+ const minutes = Math.floor(seconds / 60)
244
+ return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
245
+ }
246
+
247
+ function elapsed(run) {
248
+ const start = Date.parse(run.startedAt)
249
+ const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
250
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
251
+ const wall = Math.max(0, end - start)
252
+ const active = Number.isFinite(run.activeMs) ? run.activeMs : wall
253
+ // A resumed run can span hours of downtime. Reporting one number would make
254
+ // it look like the model worked all that time.
255
+ if (run.resumedAt && wall - active > 5000) {
256
+ return `${durationText(active)} running, ${durationText(wall)} since it was started (includes time stopped)`
257
+ }
258
+ return durationText(wall)
259
+ }
260
+
261
+ function usageLine(usage, status) {
262
+ if (!usage || !usage.modelCalls) {
263
+ if (ACTIVE_STATUSES.has(status)) {
264
+ return 'usage: accounting pending — token usage is read from child session logs while the run is in progress'
265
+ }
266
+ return 'usage: not recorded — no child session log was readable for this run '
267
+ + '(usually a run created before usage tracking, or a sessions directory that moved); '
268
+ + 'token and cost figures are unavailable'
269
+ }
270
+ const models = Object.entries(usage.models ?? {})
271
+ .map(([model, entry]) => `${model}: ${entry.calls} call(s) ${entry.inputTokens} in / ${entry.outputTokens} out`)
272
+ .join('; ')
273
+ const cached = usage.cacheReadTokens ? ` (+${usage.cacheReadTokens} prompt tokens served from cache)` : ''
274
+ return `usage: input ${usage.inputTokens}${cached}, output ${usage.outputTokens}, calls ${usage.modelCalls}`
275
+ + (models ? ` (${models})` : '')
276
+ }
277
+
278
+ /**
279
+ * Cost line for one run. The number is an estimate from the configured list
280
+ * prices; models without a price are named instead of guessed so a user can
281
+ * always tell how much of the spend the figure covers.
282
+ */
283
+ function costLine(run) {
284
+ if (!run.usage || !run.usage.modelCalls) return null
285
+ const models = Object.keys(run.usage.models ?? {})
286
+ const cost = run.cost
287
+ // An all-unpriced run has no priced line at all. Printing 0.0000 there would
288
+ // claim the run was free, which is the one thing an estimate must not do.
289
+ const priced = Boolean(cost) && Object.keys(cost.byModel ?? {}).length > 0
290
+ if (!priced) {
291
+ const named = cost?.unpriced?.length ? cost.unpriced.join(', ') : (models.join(', ') || 'this model')
292
+ return `cost: not computed — no price configured for ${named}; `
293
+ + 'add a pricing entry in cordis.patch.yml to get an estimate'
294
+ }
295
+ const money = formatMoney(cost)
296
+ if (cost.complete) return `cost: ${money} (estimate; all models priced)`
297
+ return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
298
+ }
299
+
300
+ /** Spend for one subtask: measured when priced, explicit when not. */
301
+ function subtaskCostText(subtask) {
302
+ if (!subtask?.usage || !subtask.usage.modelCalls) return ''
303
+ const cost = subtask.cost
304
+ if (!cost || Object.keys(cost.byModel ?? {}).length === 0) {
305
+ const named = cost?.unpriced?.length ? ` (${cost.unpriced.join(', ')})` : ''
306
+ return `, cost unpriced${named}`
307
+ }
308
+ return `, ${formatMoney(cost)}${cost.complete ? '' : '+'}`
309
+ }
310
+
311
+ /** Render one run as text for a tool result. */
312
+ function formatRun(run, { includeReport = true } = {}) {
313
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
314
+ const lines = [
315
+ `run ${run.id} — ${run.status}`,
316
+ `goal: ${run.goal}`,
317
+ `plan: ${run.plan?.mode ?? 'pending'}; subtasks ${completed}/${run.subtasks.length} completed; `
318
+ + `max ${run.limits.maxParallel} in parallel; ${run.limits.attempts} attempt(s) each`,
319
+ `elapsed: ${elapsed(run)}`,
320
+ usageLine(run.usage, run.status),
321
+ ]
322
+ if (run.queue?.waiting) {
323
+ lines.push(
324
+ `queue: waiting for a free slot — position ${run.queue.position} of ${run.queue.of}; `
325
+ + 'it starts automatically when an active run finishes, does not count against maxActiveRuns while it waits, '
326
+ + `and fails if no slot frees by ${run.queue.timeoutAt}`,
327
+ )
328
+ } else if (run.queue?.expired) {
329
+ lines.push(`queue: timed out after waiting ${run.queue.of > 0 ? `behind ${run.queue.of} run(s)` : 'for a slot'}; it never started`)
330
+ } else if (run.queue?.cancelled) {
331
+ lines.push('queue: cancelled while waiting for a slot; it never started')
332
+ }
333
+ const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
334
+ if (unreadable > 0) {
335
+ lines.push(
336
+ `usage note: ${unreadable} child session log(s) could not be read, so the token figures above cover only `
337
+ + 'the readable ones; the model-call budget counted those children as one call each instead of ignoring them',
338
+ )
339
+ }
340
+ const cost = costLine(run)
341
+ if (cost) lines.push(cost)
342
+ if (run.memory?.digest) {
343
+ lines.push(
344
+ `memory: ${run.memory.notes} note(s) and ${run.memory.runs} earlier run(s) carried into this run `
345
+ + `(${run.memory.digestChars} chars)`,
346
+ )
347
+ }
348
+ if (run.attention?.issue) {
349
+ lines.push(`attention: ${run.attention.issue}`)
350
+ }
351
+ if (run.attention?.items?.length > 0) {
352
+ const items = run.attention.items
353
+ const idOf = item => item.id ?? `q${items.indexOf(item) + 1}`
354
+ const open = items.filter(item => !item.answer)
355
+ const first = open[0] ?? items[0]
356
+ if (open.length > 0) {
357
+ lines.push(`needs your decision: ${first.question}${first.source ? ` (from ${first.source})` : ''}`)
358
+ if (first.options?.length) lines.push(`options: ${first.options.join(' | ')}`)
359
+ if (first.reason) lines.push(`why: ${first.reason}`)
360
+ lines.push(`attention id: ${idOf(first)}`)
361
+ } else {
362
+ // Answering does not hide the question: the record shows what was decided.
363
+ lines.push(`answered [${idOf(first)}]: ${first.question} — ${first.answer}`)
364
+ }
365
+ if (open.length > 1) {
366
+ lines.push(`and ${open.length - 1} more open question(s): ${open.slice(1).map(idOf).join(', ')}`)
367
+ }
368
+ }
369
+ if (Array.isArray(run.followups) && run.followups.length > 0) {
370
+ const pending = run.followups.filter(entry => !entry.appliedAt)
371
+ const missed = pending.filter(entry => entry.missedAt)
372
+ const applied = run.followups.length - pending.length
373
+ if (applied > 0) {
374
+ const stages = [...new Set(run.followups.filter(entry => entry.appliedAt).map(entry => entry.appliedAtStage))]
375
+ lines.push(`instructions: ${applied} added during the run, applied at ${stages.join(' / ')}`)
376
+ }
377
+ if (pending.length > missed.length) {
378
+ lines.push(
379
+ `instructions: ${pending.length - missed.length} waiting; they take effect at ${followupEffect(run).detail}`,
380
+ )
381
+ }
382
+ if (missed.length > 0) {
383
+ lines.push(
384
+ `instructions: ${missed.length} never took effect — ${missed[0].missedReason ?? 'the run settled first'}`,
385
+ )
386
+ }
387
+ }
388
+ if (Array.isArray(run.milestones) && run.milestones.length > 0) {
389
+ // Times are UTC because the record is ISO; a status line is not a place to
390
+ // start guessing the reader's timezone.
391
+ lines.push(`milestones: ${run.milestones
392
+ .map(milestone => `${milestone.name}@${String(milestone.at ?? '').slice(11, 19)}`)
393
+ .join(' → ')}`)
394
+ }
395
+ lines.push(...describeWorkspace(run.workspace))
396
+ const reportArtifact = (run.artifacts ?? []).find(artifact => artifact?.kind === 'report')
397
+ if (reportArtifact?.path) lines.push(`report file: ${reportArtifact.path} (${reportArtifact.bytes} bytes)`)
398
+ else if (run.artifactError) lines.push(`report file: not written — ${run.artifactError}`)
399
+ if (run.deduped) {
400
+ lines.push(
401
+ 'deduped: true — an active run with the same goal already exists, so this call joined it instead of starting '
402
+ + 'a second one (pass allow_duplicate: true to start another)',
403
+ )
404
+ }
405
+ if (run.selfHeal?.retried) {
406
+ lines.push(
407
+ `self-heal: retried ${run.selfHeal.retried} failed subtask(s) in ${run.selfHeal.rounds} extra round(s); `
408
+ + `${run.selfHeal.recovered} recovered` + (run.selfHeal.model ? ` (on ${run.selfHeal.model})` : ''),
409
+ )
410
+ }
411
+ if (run.memoryWrite?.written > 0) {
412
+ lines.push(`memory: wrote ${run.memoryWrite.written} note(s) for the next run`)
413
+ } else if (run.memoryWrite?.reason && /^(the memory block|write failed)/.test(run.memoryWrite.reason)) {
414
+ lines.push(`memory note not written: ${run.memoryWrite.reason}`)
415
+ }
416
+ if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
417
+ if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
418
+ if (run.status === 'interrupted' && run.error) {
419
+ // Not a failure: the host went away and the run is waiting to be resumed.
420
+ lines.push(`note: ${run.error}`)
421
+ } else if (run.status !== 'cancelled' && run.error) {
422
+ lines.push(`error: ${summarizeError(run.error)}`)
423
+ if (run.status === 'failed') lines.push(`hint: ${classifyError(run.error).hint}`)
424
+ }
425
+ if (notifyFailed(run)) {
426
+ lines.push(`notify: not delivered — ${run.notify.reason}`)
427
+ }
428
+ if (run.cancelPending) {
429
+ lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
430
+ }
431
+ for (const subtask of run.subtasks) {
432
+ const tokens = subtask.usage
433
+ ? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out${subtaskCostText(subtask)}`
434
+ : ''
435
+ // A subtask waiting on a dependency is not running and not failed; saying
436
+ // which tasks it waits for is the difference between "stuck" and "queued".
437
+ const waiting = subtask.status === 'waiting' && subtask.waitingOn?.length > 0
438
+ ? ` — waiting on ${subtask.waitingOn.join(', ')}`
439
+ : ''
440
+ const skipped = subtask.status === 'skipped' && subtask.skippedReason
441
+ ? ` — skipped: ${subtask.skippedReason}`
442
+ : ''
443
+ const detail = skipped || (subtask.error ? ` — ${summarizeError(subtask.error)}` : '')
444
+ // A cancelled run never judged its unfinished subtasks, so calling them
445
+ // "pending" or "failed (attempts 0)" would misreport what happened.
446
+ const status = run.status === 'cancelled' && subtask.status !== 'completed'
447
+ ? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
448
+ : subtask.status
449
+ lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${waiting}${detail}`)
450
+ }
451
+ const failed = run.subtasks.find(subtask => subtask.error)
452
+ if (failed) {
453
+ const hint = classifyError(failed.error).hint
454
+ if (classifyError(failed.error).id !== 'unclassified') lines.push('', `hint: ${hint}`)
455
+ }
456
+ if (includeReport && run.report) {
457
+ lines.push('', 'report:', '', preview(run.report))
458
+ }
459
+ const openQuestion = (run.attention?.items ?? []).find(item => !item.answer)
460
+ if (openQuestion) {
461
+ // The user can act on this line directly; the id is what makes the answer
462
+ // land on the question it belongs to.
463
+ lines.push('', `next: superagent_answer run_id="${run.id}" attention_id="${openQuestion.id ?? 'q1'}" answer="..."`)
464
+ }
465
+ if (!TERMINAL_STATUSES.has(run.status)) {
466
+ lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
467
+ } else if (run.status === 'interrupted') {
468
+ lines.push('', `next: superagent_resume run_id="${run.id}"`)
469
+ }
470
+ return lines.join('\n')
471
+ }
472
+
473
+ function formatBytes(bytes) {
474
+ if (bytes < 1024) return `${bytes} B`
475
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
476
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`
477
+ }
478
+
479
+ /** True when a run finished but its owner was never told, and that is a problem. */
480
+ function notifyFailed(run) {
481
+ if (!run.notify || run.notify.delivered) return false
482
+ return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
483
+ }
484
+
485
+ /** What a failed run already tried, so the message is not just "it broke". */
486
+ function triedLine(run) {
487
+ const attempts = run.limits?.attempts ?? 1
488
+ const parts = [`tried: ${attempts} attempt(s) per subtask`]
489
+ if (run.selfHeal?.rounds > 0) {
490
+ parts.push(`${run.selfHeal.rounds} self-heal round(s), ${run.selfHeal.recovered ?? 0} recovered`)
491
+ }
492
+ if (run.selfHeal?.model) parts.push(`switched to ${run.selfHeal.model} for the retry`)
493
+ return `${parts.join('; ')}.`
494
+ }
495
+
496
+ function formatList(runs, limit, stats = null) {
497
+ if (runs.length === 0) return 'no superagent runs recorded'
498
+ const rows = runs.slice(0, limit).map(run => {
499
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
500
+ return `${run.id} ${run.status.padEnd(11)} ${completed}/${run.subtasks.length} done `
501
+ + `${run.goal.slice(0, 70)}${notifyFailed(run) ? ' (result not delivered to the session)' : ''}`
502
+ })
503
+ const lines = [`${runs.length} run(s):`, ...rows]
504
+ if (stats) {
505
+ lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
506
+ + (stats.corrupt ? ` (${stats.corrupt} quarantined file(s))` : ''))
507
+ if (stats.memory) {
508
+ lines.push(`memory: ${stats.memory.entries} note(s), ${formatBytes(stats.memory.bytes)} in ${path.dirname(stats.memory.path)}`)
509
+ }
510
+ if (stats.pendingNotifications > 0) {
511
+ lines.push(`notifications: ${stats.pendingNotifications} run(s) held back by the hourly limit; `
512
+ + 'they are folded into the next message')
513
+ }
514
+ if (stats.ledger) {
515
+ const ledger = stats.ledger
516
+ if (ledger.runs === 0) {
517
+ lines.push(`ledger: no spend recorded in the last ${stats.ledgerDays} days`)
518
+ } else if (ledger.priced === 0) {
519
+ lines.push(`ledger: ${ledger.runs} run(s) in the last ${stats.ledgerDays} days are unpriced — `
520
+ + 'no configured price matches their models, so no total is claimed')
521
+ } else {
522
+ const total = ledger.mixedCurrency
523
+ ? `${formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency ?? 'USD' })}`
524
+ : formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency })
525
+ lines.push(`ledger: ${total} across ${ledger.priced} priced run(s) in the last ${stats.ledgerDays} days`
526
+ + (ledger.unpricedRuns > 0 ? ` (${ledger.unpricedRuns} run(s) partially unpriced)` : '')
527
+ + (ledger.mixedCurrency ? ' (mixed currencies; figure uses the first)' : ''))
528
+ }
529
+ }
530
+ }
531
+ return lines.join('\n')
532
+ }
533
+
534
+ function toolText(text) {
535
+ return [{ type: 'text', text }]
536
+ }
537
+
538
+ function defineTool(spec) {
539
+ return {
540
+ name: spec.name,
541
+ description: spec.description,
542
+ parameters: { type: 'object', properties: spec.properties, ...(spec.required?.length ? { required: spec.required } : {}) },
543
+ output: { schema: { type: 'string' }, render: (_args, value) => toolText(value) },
544
+ execute: spec.execute,
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Mount the plugin.
550
+ * @param {object} ctx - Cordis context.
551
+ * @param {object} [config] - row config from `cordis.patch.yml`.
552
+ */
553
+ export function apply(ctx, config) {
554
+ const log = message => console.error(`[dsh-superagent] ${message}`)
555
+ const configuredPort = config?.controlPort
556
+ const cfg = resolveConfig(config)
557
+ if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
558
+ log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
559
+ }
560
+ if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
561
+ console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
562
+ return
563
+ }
564
+
565
+ const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
566
+ const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
567
+ const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
568
+ // The ledger is an append-only history of priced runs. Writing it here, from
569
+ // the read paths, keeps it out of the scheduling loop: a status or list call
570
+ // is already a snapshot of finished work, and a run is recorded exactly once.
571
+ const ledger = createLedger(store.root, { warn: log })
572
+ const LEDGER_WINDOW_DAYS = 30
573
+
574
+ /** Append finished runs to the spend ledger; a ledger fault never blocks a tool. */
575
+ async function recordSpend(runs) {
576
+ for (const run of runs) {
577
+ try {
578
+ await ledger.record(run)
579
+ } catch (error) {
580
+ log(`ledger: cannot record run ${run?.id}: ${error?.message ?? error}`)
581
+ }
582
+ }
583
+ }
584
+
585
+ // A state directory inside the installed package would put the notebook in a
586
+ // directory that is meant to be shipped byte-for-byte from git. Refuse rather
587
+ // than rely on the `.gitignore` the notebook writes for itself.
588
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
589
+ const memoryBlocked = isInside(store.root, packageRoot)
590
+ const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
591
+ if (cfg.memory && memoryBlocked) {
592
+ log(`cross-run memory stays off: stateDir ${store.root} is inside the installed package; point stateDir elsewhere`)
593
+ }
594
+ // Built-ins need no storage; only custom templates touch the state directory,
595
+ // and a state directory inside the package must not receive new files.
596
+ const templates = createTemplateStore(store.root, { warn: log })
597
+ const notifyPolicy = createNotifyPolicy({
598
+ stateFile: path.join(store.root, 'notifications.json'),
599
+ maxPerHour: cfg.maxNotificationsPerHour,
600
+ warn: log,
601
+ })
602
+ // One wake-up per run, delivered in order per session. A busy session loop
603
+ // can reject a followup, so the same message is retried with backoff instead
604
+ // of being reported as lost on the first refusal.
605
+ const outbox = createOutbox({ retries: cfg.notifyRetries, delayMs: cfg.notifyRetryDelayMs })
606
+
607
+ /** Child sessions spawned by this process; a run may not be started from one. */
608
+ const childIds = new Set()
609
+
610
+ /**
611
+ * The subagent service is optional, so it is read from the service store at
612
+ * call time rather than declared as an injection: a profile without it must
613
+ * still mount the eight tools (they then explain what is missing), and reading
614
+ * it lazily also sees a service that registers after this plugin.
615
+ */
616
+ function getSubagents() {
617
+ if (typeof ctx.get === 'function') {
618
+ const service = ctx.get('subagents')
619
+ if (service) return service
620
+ }
621
+ // The direct property is topology-sensitive on a real host; it is only a
622
+ // fallback for test contexts that provide the service without a registry.
623
+ try {
624
+ return ctx.subagents
625
+ } catch {
626
+ return undefined
627
+ }
628
+ }
629
+
630
+ /** Remember a child id for the recursion guard without growing forever. */
631
+ function rememberChild(childId) {
632
+ if (!childId) return
633
+ childIds.add(childId)
634
+ if (childIds.size > 512) childIds.delete(childIds.values().next().value)
635
+ }
636
+
637
+ /**
638
+ * Map a run outcome to one message for the owning session.
639
+ *
640
+ * The notification policy decides first: a cancelled run is never announced,
641
+ * and a burst above the hourly cap is buffered instead of waking the session
642
+ * once per run. The followup is awaited: an unhandled rejection from it would
643
+ * otherwise escape as a host-level error while the run already claims it was
644
+ * delivered.
645
+ */
646
+ async function notifyParent(run) {
647
+ if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
648
+ if (!cfg.notifyOnComplete) return { delivered: false, reason: 'disabled: notifyOnComplete is false' }
649
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
650
+ const agent = agents && typeof agents.get === 'function' ? agents.get(run.parentSessionId) : undefined
651
+ if (!agent || typeof agent.followup !== 'function') {
652
+ log(`run ${run.id} finished but its session ${run.parentSessionId} is no longer live`)
653
+ return {
654
+ delivered: false,
655
+ reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
656
+ }
657
+ }
658
+ // Reserve only once the session is known to exist: a missing session is not
659
+ // an interruption and must not consume the hourly budget.
660
+ const verdict = await notifyPolicy.reserve(run)
661
+ if (!verdict.allowed) return { delivered: false, reason: verdict.reason }
662
+
663
+ const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
664
+ const decision = (run.attention?.items ?? []).find(item => !item.answer) ?? null
665
+ const questionId = decision?.id ?? (decision ? 'q1' : null)
666
+ const lines = decision
667
+ ? [`[superagent] needs your decision on run ${run.id} (question ${questionId}): ${decision.question}`]
668
+ : [`[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`]
669
+ if (decision) {
670
+ if (decision.options?.length) lines.push(`Options: ${decision.options.join(' / ')}.`)
671
+ lines.push(`The run itself ended as ${run.status} (${completed}/${run.subtasks.length} subtasks).`)
672
+ lines.push(`Answer with superagent_answer attention_id="${questionId}".`)
673
+ } else if (run.attention?.issue) {
674
+ // A malformed block asked for a decision too; keeping it quiet would look
675
+ // like an ordinary finished run.
676
+ lines.push(`Attention: ${run.attention.issue}.`)
677
+ }
678
+ if (!decision && run.status !== 'completed') lines.push(triedLine(run))
679
+ if (run.workspace?.conflicts > 0) {
680
+ // A conflict is the one outcome the user must act on even when the run
681
+ // "completed": saying only "finished: completed" would bury it.
682
+ lines.push(
683
+ `${run.workspace.conflicts} worker branch(es) could not be merged into ${run.workspace.base}; `
684
+ + 'both sides were kept, so nothing was lost — superagent_status lists the conflicting files and the branch '
685
+ + 'to merge by hand.',
686
+ )
687
+ } else if (run.workspace?.mode === 'unavailable') {
688
+ lines.push(`Workspace isolation was unavailable (${run.workspace.reason}), so the workers shared one directory.`)
689
+ }
690
+ if (verdict.batch.length > 0) {
691
+ lines.push(
692
+ 'Also finished since the last update: '
693
+ + `${verdict.batch.map(item => `${item.id} ${item.status}`).join('; ')}.`,
694
+ )
695
+ }
696
+ lines.push(`Call superagent_status with run_id="${run.id}" to read the report.`)
697
+ try {
698
+ await outbox.enqueue(run.parentSessionId, () => agent.followup({
699
+ id: randomUUID(),
700
+ role: 'user',
701
+ content: [{ type: 'text', text: lines.join(' ') }],
702
+ source: { kind: 'user' },
703
+ }))
704
+ run.notified = true
705
+ return { delivered: true }
706
+ } catch (error) {
707
+ log(`cannot notify session ${run.parentSessionId}: ${error?.message ?? error}`)
708
+ // The folded runs were reserved but never delivered. Put them back so the
709
+ // next allowed message still carries them, up to the policy's retry cap.
710
+ await notifyPolicy.restore(verdict.batch).catch(restoreError => {
711
+ log(`cannot restore ${verdict.batch.length} batched notification(s): ${restoreError?.message ?? restoreError}`)
712
+ })
713
+ return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
714
+ }
715
+ }
716
+
717
+ const orchestrator = createOrchestrator({
718
+ store,
719
+ config: cfg,
720
+ log,
721
+ readUsage,
722
+ memory,
723
+ notify: notifyParent,
724
+ async spawnChild({ label, prompt, parent, signal, model }) {
725
+ const subagents = getSubagents()
726
+ if (!subagents || typeof subagents.startActivation !== 'function') {
727
+ const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
728
+ // The service can also disappear in the middle of a run, when the host
729
+ // is shutting down. The orchestrator turns this code into `interrupted`
730
+ // instead of a failed subtask, so the run stays resumable.
731
+ error.code = 'subagent-unavailable'
732
+ throw error
733
+ }
734
+ const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
735
+ const capabilities = provider?.capabilities ?? null
736
+ const agentOptions = {}
737
+ // Only the self-heal round passes a model override; everything else keeps
738
+ // the configured route.
739
+ const childModel = model ?? cfg.childModel
740
+ if (cfg.childProvider) agentOptions.provider = cfg.childProvider
741
+ if (childModel) agentOptions.model = childModel
742
+ const request = {
743
+ parent,
744
+ prompt: [{ type: 'text', text: prompt }],
745
+ ...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
746
+ }
747
+ // A preset is the host's only way to give a child a narrower tool set:
748
+ // the start request has no tool filter in dsh 0.2.2-rc.1.
749
+ if (cfg.childPreset) {
750
+ if (capabilities && !capabilities.agentPreset) {
751
+ throw new Error(
752
+ `childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
753
+ + 'independent agent presets, so this child would run with this session\'s tools',
754
+ )
755
+ }
756
+ request.agentPreset = cfg.childPreset
757
+ }
758
+ // Recursion is bounded unless the operator explicitly left it to the
759
+ // backend. Silently dropping the cap would hand 8 parallel workers the
760
+ // right to spawn their own armies.
761
+ if (cfg.maxSubagentDepth !== 'provider-managed') {
762
+ if (capabilities && !capabilities.depthLimit) {
763
+ throw new Error(
764
+ `subagent provider "${cfg.provider}" cannot enforce maxSubagentDepth (${cfg.maxSubagentDepth}), so child `
765
+ + 'agents could spawn their own children without limit; set maxSubagentDepth: provider-managed to accept '
766
+ + 'the backend\'s own cap',
767
+ )
768
+ }
769
+ request.maxDepth = cfg.maxSubagentDepth
770
+ }
771
+ const activation = await subagents.startActivation({
772
+ provider: cfg.provider,
773
+ label,
774
+ request,
775
+ signal,
776
+ delivery: 'caller',
777
+ })
778
+ rememberChild(activation.childId)
779
+ return {
780
+ childId: activation.childId,
781
+ result: activation.result,
782
+ dispose: async () => {
783
+ try {
784
+ await activation.dispose()
785
+ } catch (error) {
786
+ log(`dispose failed for ${activation.childId}: ${error?.message ?? error}`)
787
+ }
788
+ },
789
+ }
790
+ },
791
+ })
792
+
793
+ // Recovery runs once at mount; tools wait for it so a run left active by a
794
+ // dead host reads as interrupted before the first tool call sees it. A
795
+ // failure to initialize the state directory is kept and reported by every
796
+ // tool: hiding it behind "no runs recorded" is how a broken stateDir looks
797
+ // like an empty one.
798
+ let stateError = null
799
+ const ready = (async () => {
800
+ try {
801
+ await orchestrator.recover()
802
+ } catch (error) {
803
+ stateError = error instanceof Error ? error : new Error(String(error))
804
+ log(`state directory is not usable: ${stateError.message}`)
805
+ return
806
+ }
807
+ // Backfill runs that settled while no tool was watching, so the ledger is
808
+ // complete after a restart. Recording is idempotent: a normal mount adds
809
+ // nothing for runs already written.
810
+ try {
811
+ await recordSpend(await orchestrator.list())
812
+ } catch (error) {
813
+ log(`ledger: cannot backfill from runs: ${error?.message ?? error}`)
814
+ }
815
+ // Templates are optional: a failure here must not make every run tool
816
+ // answer with a state error, and the built-ins still work without a file.
817
+ if (!memoryBlocked) {
818
+ try {
819
+ await templates.init()
820
+ } catch (error) {
821
+ log(`cannot create the template directory ${templates.dir}: ${error?.message ?? error}`)
822
+ }
823
+ }
824
+ if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
825
+ try {
826
+ const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
827
+ if (removed.length > 0) {
828
+ log(`pruned ${removed.length} terminal run(s) older than ${cfg.keepRuns} day(s): ${removed.join(', ')}`)
829
+ }
830
+ } catch (error) {
831
+ log(`cannot prune old runs: ${error?.message ?? error}`)
832
+ }
833
+ })()
834
+
835
+ /** True when the host actually provides a subagent service. */
836
+ function hasSubagents() {
837
+ const subagents = getSubagents()
838
+ return Boolean(subagents && typeof subagents.startActivation === 'function')
839
+ }
840
+
841
+ function requireAgent(exec) {
842
+ const agent = exec?.agent
843
+ if (!agent || typeof agent !== 'object' || !agent.id) return { error: describeError('no live agent in this tool call context') }
844
+ if (childIds.has(agent.id)) {
845
+ return { error: describeError('refused: a superagent worker may not start, resume, or cancel runs; finish your subtask instead') }
846
+ }
847
+ return { agent }
848
+ }
849
+
850
+ /**
851
+ * Resolve the session named by an HTTP caller. An embedded start is a normal
852
+ * run: it needs a live agent to own the children, and the same recursion
853
+ * guard as a tool call. A synthetic parent would spawn children no session
854
+ * owns, so a missing session is an error, never a fallback.
855
+ * @param {unknown} sessionId - `session_id` from the request body.
856
+ * @returns {object} live agent.
857
+ */
858
+ function resolveSession(sessionId) {
859
+ const id = typeof sessionId === 'string' ? sessionId.trim() : ''
860
+ if (!id) {
861
+ throw new Error(
862
+ 'no live agent: session_id is required; an HTTP-started run needs an open session to own its child agents',
863
+ )
864
+ }
865
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
866
+ const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
867
+ if (!agent || typeof agent !== 'object' || !agent.id) {
868
+ throw new Error(
869
+ `no live agent: session ${id} is not open in this host process; open that session, or start the run from a `
870
+ + 'tool call inside it',
871
+ )
872
+ }
873
+ if (childIds.has(agent.id)) {
874
+ throw new Error('refused: a superagent worker may not start or resume runs; finish your subtask instead')
875
+ }
876
+ return agent
877
+ }
878
+
879
+ ctx.tools.register(defineTool({
880
+ name: 'superagent_start',
881
+ description:
882
+ 'Start a long-horizon autonomous run: a planner decomposes the goal into subtasks, '
883
+ + 'independent subtasks run in parallel child agents while ones with a declared dependency wait for it, '
884
+ + 'and their reports are merged into one final report. '
885
+ + 'Pass mode "direct" for a single self-contained task instead: one worker does it, there is no planner '
886
+ + 'or aggregator, and its reply is the report verbatim — use it for one lookup, one edit, one query, or '
887
+ + 'one short piece of writing, not for a goal with parts that can be worked in parallel. '
888
+ + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
889
+ + 'so they survive a host restart and can be resumed or cancelled.',
890
+ properties: {
891
+ goal: { type: 'string', description: 'The complete goal for the run. Be specific about the expected outcome.' },
892
+ mode: {
893
+ type: 'string',
894
+ enum: ['planned', 'direct'],
895
+ description: 'planned (default): planner, parallel workers, merged report. direct: one worker runs the whole '
896
+ + 'goal, with no planning or aggregation, and its reply is returned unchanged. Choose direct only when the '
897
+ + 'task is one self-contained pass that gains nothing from splitting.',
898
+ },
899
+ queue: {
900
+ type: 'boolean',
901
+ description: 'When maxActiveRuns is already in use, wait for a free slot instead of failing. The run returns '
902
+ + `status "queued" with its position, starts automatically when another run finishes, and gives up after `
903
+ + `queueTimeoutMinutes (default ${DEFAULTS.queueTimeoutMinutes}). Off by default; at most maxQueuedRuns `
904
+ + `(default ${DEFAULTS.maxQueuedRuns}) may wait.`,
905
+ },
906
+ max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
907
+ max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
908
+ deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
909
+ allow_duplicate: {
910
+ type: 'boolean',
911
+ description: 'Start a second run for the same goal even when an active run already has it. '
912
+ + 'By default the active run id is returned instead, so a retry cannot double the spend.',
913
+ },
914
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
915
+ },
916
+ required: ['goal'],
917
+ async execute(args = {}, exec) {
918
+ const check = requireAgent(exec)
919
+ if (check.error) return check.error
920
+ try {
921
+ await ready
922
+ if (stateError) return describeError(stateError)
923
+ if (!hasSubagents()) {
924
+ return describeError(
925
+ 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
926
+ + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
927
+ )
928
+ }
929
+ const run = await orchestrator.start({
930
+ goal: args.goal,
931
+ parentSessionId: check.agent.id,
932
+ parent: check.agent,
933
+ clientTimeZone: exec.clientTimeZone,
934
+ allowDuplicate: args.allow_duplicate === true,
935
+ mode: args.mode,
936
+ queue: args.queue === true,
937
+ overrides: {
938
+ maxSubtasks: args.max_subtasks,
939
+ maxParallel: args.max_parallel,
940
+ deadlineMinutes: args.deadline_minutes,
941
+ },
942
+ })
943
+ const waitSeconds = Number(args.wait_seconds) || 0
944
+ if (waitSeconds > 0) {
945
+ const finished = await orchestrator.status(run.id, waitSeconds)
946
+ await recordSpend([finished])
947
+ // `status` reads the stored run, which never has the transient join
948
+ // marker; carry it over so the caller can still see it joined.
949
+ return formatRun(run.deduped ? { ...finished, deduped: true } : finished)
950
+ }
951
+ if (run.queue?.waiting) {
952
+ return `${formatRun(run, { includeReport: false })}\n\nQueued, not started: the run begins automatically when `
953
+ + 'an active run finishes. Poll with superagent_status or cancel it with superagent_cancel.'
954
+ }
955
+ return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
956
+ + 'the run keeps going after this tool call returns.'
957
+ } catch (error) {
958
+ return describeError(error)
959
+ }
960
+ },
961
+ }))
962
+
963
+ ctx.tools.register(defineTool({
964
+ name: 'superagent_status',
965
+ description:
966
+ 'Read one superagent run: status, subtask outcomes, measured token usage, and the final report. '
967
+ + 'With wait_seconds it blocks until the run reaches a terminal state or the wait expires.',
968
+ properties: {
969
+ run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
970
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
971
+ },
972
+ required: ['run_id'],
973
+ async execute(args = {}) {
974
+ try {
975
+ await ready
976
+ if (stateError) return describeError(stateError)
977
+ const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
978
+ await recordSpend([run])
979
+ return formatRun(run)
980
+ } catch (error) {
981
+ return describeError(error)
982
+ }
983
+ },
984
+ }))
985
+
986
+ ctx.tools.register(defineTool({
987
+ name: 'superagent_list',
988
+ description: 'List recorded superagent runs, newest first, with status and progress.',
989
+ properties: {
990
+ limit: { type: 'number', description: 'Maximum rows to print (default 20).' },
991
+ },
992
+ async execute(args = {}) {
993
+ try {
994
+ await ready
995
+ if (stateError) return describeError(stateError)
996
+ const runs = await orchestrator.list()
997
+ await recordSpend(runs)
998
+ const stats = typeof store.stats === 'function' ? await store.stats() : null
999
+ const memoryStats = memory
1000
+ ? await memory.stats({ scope: cfg.memoryScope, maxAgeDays: cfg.memoryMaxAgeDays }).catch(() => null)
1001
+ : null
1002
+ const notifyState = await notifyPolicy.summary().catch(() => null)
1003
+ const ledgerStats = await ledger
1004
+ .summarize({ since: Date.now() - LEDGER_WINDOW_DAYS * 86400000 })
1005
+ .catch(() => null)
1006
+ const extra = stats
1007
+ ? {
1008
+ ...stats,
1009
+ root: store.root,
1010
+ memory: memoryStats,
1011
+ pendingNotifications: notifyState?.pending?.length ?? 0,
1012
+ ledger: ledgerStats,
1013
+ ledgerDays: LEDGER_WINDOW_DAYS,
1014
+ }
1015
+ : null
1016
+ return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
1017
+ } catch (error) {
1018
+ return describeError(error)
1019
+ }
1020
+ },
1021
+ }))
1022
+
1023
+ ctx.tools.register(defineTool({
1024
+ name: 'superagent_cancel',
1025
+ description:
1026
+ 'Cancel a superagent run: stops running subtasks, marks the run cancelled, and keeps the state file '
1027
+ + 'so the partial work stays inspectable.',
1028
+ properties: {
1029
+ run_id: { type: 'string', description: 'Run id to cancel.' },
1030
+ },
1031
+ required: ['run_id'],
1032
+ async execute(args = {}, exec) {
1033
+ const check = requireAgent(exec)
1034
+ if (check.error) return check.error
1035
+ try {
1036
+ await ready
1037
+ if (stateError) return describeError(stateError)
1038
+ const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
1039
+ await recordSpend([run])
1040
+ const head = run.status === 'cancelled'
1041
+ ? `cancelled ${run.id}`
1042
+ : run.cancelPending
1043
+ ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
1044
+ : `${run.id} is ${run.status}; nothing to cancel`
1045
+ return `${head}\n\n${formatRun(run, { includeReport: false })}`
1046
+ } catch (error) {
1047
+ return describeError(error)
1048
+ }
1049
+ },
1050
+ }))
1051
+
1052
+ ctx.tools.register(defineTool({
1053
+ name: 'superagent_resume',
1054
+ description:
1055
+ 'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
1056
+ + 'Completed subtasks are kept; pending and failed ones run again. A completed run is reopened only when it '
1057
+ + 'holds an answer that never reached a prompt, so its aggregation can apply the decision.',
1058
+ properties: {
1059
+ run_id: { type: 'string', description: 'Run id to resume.' },
1060
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal state (default 0).' },
1061
+ force: {
1062
+ type: 'boolean',
1063
+ description: 'Accepted for backward compatibility and ignored: a resume is never refused by maxActiveRuns.',
1064
+ },
1065
+ },
1066
+ required: ['run_id'],
1067
+ async execute(args = {}, exec) {
1068
+ const check = requireAgent(exec)
1069
+ if (check.error) return check.error
1070
+ try {
1071
+ await ready
1072
+ if (stateError) return describeError(stateError)
1073
+ if (!hasSubagents()) {
1074
+ return describeError(
1075
+ 'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
1076
+ )
1077
+ }
1078
+ const run = await orchestrator.resume(
1079
+ String(args.run_id ?? '').trim(),
1080
+ check.agent,
1081
+ exec.clientTimeZone,
1082
+ { force: args.force === true },
1083
+ )
1084
+ const waitSeconds = Number(args.wait_seconds) || 0
1085
+ const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
1086
+ await recordSpend([current])
1087
+ return formatRun(current)
1088
+ } catch (error) {
1089
+ return describeError(error)
1090
+ }
1091
+ },
1092
+ }))
1093
+
1094
+ ctx.tools.register(defineTool({
1095
+ name: 'superagent_followup',
1096
+ description:
1097
+ 'Add an instruction to a run that is already executing, instead of starting a second run. This is not a live '
1098
+ + 'channel to the running children: the host has no way to append a message to a child activation, so the '
1099
+ + 'instruction is queued on the run and carried by the next prompt built for it — the next worker spawn or the '
1100
+ + 'aggregation, whichever comes first. Subtasks that are already running or finished keep their results. The '
1101
+ + 'reply states exactly which boundary it will reach.',
1102
+ properties: {
1103
+ run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
1104
+ message: { type: 'string', description: 'The instruction or constraint to add.' },
1105
+ },
1106
+ required: ['run_id', 'message'],
1107
+ async execute(args = {}, exec) {
1108
+ const check = requireAgent(exec)
1109
+ if (check.error) return check.error
1110
+ try {
1111
+ await ready
1112
+ if (stateError) return describeError(stateError)
1113
+ const result = await orchestrator.followup(
1114
+ String(args.run_id ?? '').trim(),
1115
+ args.message,
1116
+ check.agent,
1117
+ )
1118
+ return [
1119
+ `instruction ${result.followup.id} added to run ${result.run.id} — ${result.run.status}`,
1120
+ `when it takes effect: ${result.effect.detail} (boundary: ${result.effect.boundary}).`,
1121
+ 'A child that is already running is not interrupted and does not see it.',
1122
+ '',
1123
+ formatRun(result.run, { includeReport: false }),
1124
+ ].join('\n')
1125
+ } catch (error) {
1126
+ return describeError(error)
1127
+ }
1128
+ },
1129
+ }))
1130
+
1131
+ ctx.tools.register(defineTool({
1132
+ name: 'superagent_answer',
1133
+ description:
1134
+ 'Answer a question a run asked — the "needs your decision" item with a qN id — so that run continues with the '
1135
+ + 'decision instead of a new run being started. An active run applies it at its next boundary; a finished run '
1136
+ + 'is reopened and only its aggregation runs again, now with the answer. The answer is matched to one specific '
1137
+ + 'question: an unknown, already answered, or expired question is refused instead of being attached to whatever '
1138
+ + 'is open.',
1139
+ properties: {
1140
+ run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
1141
+ attention_id: {
1142
+ type: 'string',
1143
+ description: 'Question id from superagent_status, e.g. q1. Required when the run has more than one open question.',
1144
+ },
1145
+ answer: { type: 'string', description: 'The decision itself; one of the listed options is enough, free text is allowed.' },
1146
+ wait_seconds: { type: 'number', description: 'Block up to this many seconds for the run to settle again (default 0).' },
1147
+ },
1148
+ required: ['run_id', 'answer'],
1149
+ async execute(args = {}, exec) {
1150
+ const check = requireAgent(exec)
1151
+ if (check.error) return check.error
1152
+ try {
1153
+ await ready
1154
+ if (stateError) return describeError(stateError)
1155
+ const result = await orchestrator.answer(
1156
+ String(args.run_id ?? '').trim(),
1157
+ args.attention_id,
1158
+ args.answer,
1159
+ check.agent,
1160
+ exec.clientTimeZone,
1161
+ )
1162
+ let head
1163
+ if (result.resumed) {
1164
+ head = `answered ${result.attentionId} on run ${result.run.id}; the run was reopened and is ${result.run.status} `
1165
+ + `again — it applies the answer at ${result.effect.detail}`
1166
+ } else if (result.reason) {
1167
+ head = `answered ${result.attentionId} on run ${result.run.id}, but the run was not restarted: ${result.reason}. `
1168
+ + 'The answer is saved; call superagent_resume when you want it applied.'
1169
+ } else {
1170
+ head = `answered ${result.attentionId} on run ${result.run.id}; it takes effect at ${result.effect.detail}`
1171
+ }
1172
+ const waitSeconds = Number(args.wait_seconds) || 0
1173
+ const current = result.resumed && waitSeconds > 0
1174
+ ? await orchestrator.status(result.run.id, waitSeconds)
1175
+ : result.run
1176
+ return `${head}.\n\n${formatRun(current)}`
1177
+ } catch (error) {
1178
+ return describeError(error)
1179
+ }
1180
+ },
1181
+ }))
1182
+
1183
+ ctx.tools.register(defineTool({
1184
+ name: 'superagent_memory',
1185
+ description:
1186
+ 'Read or correct the cross-run notebook: short notes that earlier runs left for the next one. '
1187
+ + 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it.',
1188
+ properties: {
1189
+ action: {
1190
+ type: 'string',
1191
+ enum: ['list', 'search', 'set', 'forget'],
1192
+ description: 'List notes, search them by keyword or tag, set (add or correct) one, or forget one.',
1193
+ },
1194
+ key: { type: 'string', description: 'Short topic key. A new note with the same key replaces the older one.' },
1195
+ kind: { type: 'string', enum: [...MEMORY_KINDS], description: 'decision, pitfall, next, dispatch, or note.' },
1196
+ text: { type: 'string', description: 'The durable fact to record (set only).' },
1197
+ query: {
1198
+ type: 'string',
1199
+ description: 'Keywords to rank notes by (search only). The goal of the current task works well.',
1200
+ },
1201
+ tags: {
1202
+ type: 'array',
1203
+ items: { type: 'string' },
1204
+ description: 'Topic labels to match exactly (search) or to attach to a note (set).',
1205
+ },
1206
+ scope: {
1207
+ type: 'string',
1208
+ description: 'Notebook scope: "rules" for project rules, "profile" for user preferences, '
1209
+ + 'or the run scope (default) that earlier runs write to.',
1210
+ },
1211
+ limit: { type: 'number', description: 'Maximum notes to print (default 20).' },
1212
+ },
1213
+ required: ['action'],
1214
+ async execute(args = {}, exec) {
1215
+ const check = requireAgent(exec)
1216
+ if (check.error) return check.error
1217
+ if (!memory) {
1218
+ return describeError(
1219
+ 'cross-run memory is disabled (memory: false, or stateDir points inside the installed package)',
1220
+ )
1221
+ }
1222
+ try {
1223
+ await ready
1224
+ if (stateError) return describeError(stateError)
1225
+ const action = String(args.action ?? '').trim().toLowerCase()
1226
+ // A run writes to the configured scope; `rules` and `profile` are
1227
+ // curated by hand and read into every run, so the tool can address
1228
+ // them explicitly.
1229
+ const scope = args.scope === undefined || args.scope === null
1230
+ ? cfg.memoryScope
1231
+ : normalizeScope(args.scope)
1232
+ if (action === 'list') {
1233
+ // Capped at 30: this output goes straight into the model context, and a
1234
+ // 200-row dump would cost more than the notes are worth.
1235
+ const limit = Math.max(1, Math.min(30, Number(args.limit) || 20))
1236
+ const result = await memory.list({ scope, limit, maxAgeDays: cfg.memoryMaxAgeDays })
1237
+ if (result.total === 0) return `no notes recorded in scope "${scope}" (${result.path})`
1238
+ const rows = result.entries.map(entry => `- ${entry.key} [${entry.kind}] ${entry.text}`)
1239
+ const notes = result.bad ? `\n\n${result.bad} unreadable line(s) skipped` : ''
1240
+ return `${result.total} note(s) in scope "${scope}" (${result.path})\n\n${rows.join('\n')}${notes}`
1241
+ }
1242
+ if (action === 'search') {
1243
+ const query = String(args.query ?? '').trim()
1244
+ const tags = Array.isArray(args.tags) ? args.tags : []
1245
+ if (!query && tags.length === 0) {
1246
+ return describeError('search needs a query, tags, or both; call action="list" to read everything')
1247
+ }
1248
+ const limit = Math.max(1, Math.min(20, Number(args.limit) || 10))
1249
+ const result = await memory.recall({
1250
+ scope,
1251
+ query,
1252
+ tags,
1253
+ maxEntries: limit,
1254
+ maxAgeDays: cfg.memoryMaxAgeDays,
1255
+ })
1256
+ if (result.matched === 0) {
1257
+ return `no note in scope "${scope}" matches ${query ? `“${query}”` : 'those tags'} `
1258
+ + `(${result.total} note(s) recorded; action="list" shows them all)`
1259
+ }
1260
+ // The score and its parts are printed so a ranking can be argued with
1261
+ // instead of taken on faith.
1262
+ const rows = result.entries.map(entry => {
1263
+ const run = entry.source.runId ?? 'manual'
1264
+ return `- ${entry.key} [${entry.kind}] score ${entry.score.toFixed(2)} `
1265
+ + `(keyword ${entry.keyword.toFixed(2)}, tag ${entry.tag.toFixed(2)}) `
1266
+ + `from run ${run}, ${String(entry.source.ts ?? '').slice(0, 10)}: ${entry.text}`
1267
+ })
1268
+ return `${result.matched} of ${result.total} note(s) in scope "${scope}" match, best first\n\n${rows.join('\n')}`
1269
+ }
1270
+ if (action === 'forget') {
1271
+ const key = String(args.key ?? '').trim()
1272
+ if (!key) return describeError('forget needs the key of the note to retract; call action="list" first')
1273
+ const result = await memory.forget({ scope, key })
1274
+ return result.forgotten
1275
+ ? `retracted "${key}" in scope "${scope}"; later runs will not see it`
1276
+ : describeError(result.reason ?? 'cannot retract that note')
1277
+ }
1278
+ if (action === 'set') {
1279
+ const key = String(args.key ?? '').trim()
1280
+ const text = String(args.text ?? '').trim()
1281
+ if (!key || !text) return describeError('set needs both key and text')
1282
+ const result = await memory.set({ scope, key, kind: args.kind, text, tags: args.tags })
1283
+ return result.written > 0
1284
+ ? `recorded "${key}" in scope "${scope}"; later runs will see it`
1285
+ : describeError(result.reason ?? 'cannot record that note')
1286
+ }
1287
+ return describeError(`unknown action "${args.action}"; use list, search, set, or forget`)
1288
+ } catch (error) {
1289
+ return describeError(error)
1290
+ }
1291
+ },
1292
+ }))
1293
+
1294
+ /**
1295
+ * A template failure already names the concrete problem (which parameters
1296
+ * are missing, which field is not allowed), so it gets its own hint instead
1297
+ * of the generic "this came from the host" text.
1298
+ */
1299
+ function templateProblem(error) {
1300
+ const hints = {
1301
+ 'missing-parameters': 'pass every declared parameter in params={...}; a template never guesses a default, '
1302
+ + 'and action="show" lists each parameter with what it should contain',
1303
+ 'unknown-parameters': 'remove the parameters the template does not declare, or declare them in a custom '
1304
+ + 'template saved with action="save"',
1305
+ 'builtin-template': 'built-in templates are read-only; save your version under a new id',
1306
+ 'unknown-template': 'call action="list" to see the available template ids',
1307
+ }
1308
+ const hint = hints[error.code]
1309
+ ?? 'call action="show" on a built-in template to see the accepted fields, then save the corrected definition'
1310
+ return [`[error] ${error.message}`, `hint: ${hint}`].join('\n')
1311
+ }
1312
+
1313
+ ctx.tools.register(defineTool({
1314
+ name: 'superagent_template',
1315
+ description:
1316
+ 'List, show, expand, save, or delete a workflow template: a fixed goal skeleton with required parameters, '
1317
+ + 'the situations it fits, and when it is the wrong tool. Expanding returns one normal goal string, which '
1318
+ + 'superagent_start plans exactly like a goal typed by the user. A template cannot set limits, budgets, a '
1319
+ + 'mode, or an override, so using one never widens what a run may do.',
1320
+ properties: {
1321
+ action: {
1322
+ type: 'string',
1323
+ enum: ['list', 'show', 'expand', 'save', 'delete'],
1324
+ description: 'List templates, show one in full, expand one into a goal, save a custom one, or delete a custom one.',
1325
+ },
1326
+ id: { type: 'string', description: 'Template id from action="list". Built-in ids are read-only.' },
1327
+ params: {
1328
+ type: 'object',
1329
+ description: 'Values for the placeholders (expand only). Every declared parameter is required; a missing or '
1330
+ + 'empty value is refused with its name instead of being given a default.',
1331
+ additionalProperties: { type: 'string' },
1332
+ },
1333
+ template: {
1334
+ type: 'object',
1335
+ description: 'Complete definition (save only): id, title, whenToUse, whenNotToUse (list of strings), '
1336
+ + 'variables (list of {name, description}), and skeleton with {{name}} placeholders. Unknown fields are '
1337
+ + 'refused so a template cannot carry limits or overrides.',
1338
+ },
1339
+ limit: { type: 'number', description: 'Maximum templates to list (default 50).' },
1340
+ },
1341
+ required: ['action'],
1342
+ async execute(args = {}, exec) {
1343
+ const check = requireAgent(exec)
1344
+ if (check.error) return check.error
1345
+ try {
1346
+ await ready
1347
+ if (stateError) return describeError(stateError)
1348
+ const action = String(args.action ?? '').trim().toLowerCase()
1349
+ if (action === 'list') {
1350
+ const result = await templates.list()
1351
+ return formatTemplateList(result, Math.max(1, Math.min(100, Number(args.limit) || 50)))
1352
+ }
1353
+ if ((action === 'save' || action === 'delete') && memoryBlocked) {
1354
+ return describeError(
1355
+ `cannot ${action} a template: stateDir ${store.root} is inside the installed package, so writing there `
1356
+ + 'would modify the shipped files; point stateDir elsewhere',
1357
+ )
1358
+ }
1359
+ if (action === 'show' || action === 'expand') {
1360
+ const id = String(args.id ?? '').trim()
1361
+ if (!id) return describeError(`${action} needs the id of a template; call action="list" first`)
1362
+ const template = await templates.get(id)
1363
+ if (!template) {
1364
+ return describeError(`no workflow template with id "${id}"; call action="list" to see the ids`)
1365
+ }
1366
+ if (action === 'show') return formatTemplateDetail(template)
1367
+ const expanded = expandTemplate(template, args.params)
1368
+ return [
1369
+ `expanded template "${expanded.templateId}" into one goal of ${expanded.goal.length} characters. `
1370
+ + 'Start it with superagent_start goal=<the text below>; the planner sees the same goal it would '
1371
+ + 'have seen if you had typed it.',
1372
+ '',
1373
+ expanded.goal,
1374
+ ].join('\n')
1375
+ }
1376
+ if (action === 'save') {
1377
+ if (!args.template || typeof args.template !== 'object') {
1378
+ return describeError(
1379
+ 'save needs template: the full definition (id, title, whenToUse, whenNotToUse, variables, skeleton)',
1380
+ )
1381
+ }
1382
+ const saved = await templates.save(args.template)
1383
+ return `saved template "${saved.id}"${saved.replaced ? ' (replaced the earlier version)' : ''} at ${saved.path}`
1384
+ }
1385
+ if (action === 'delete') {
1386
+ const id = String(args.id ?? '').trim()
1387
+ if (!id) return describeError('delete needs the id of a custom template; call action="list" first')
1388
+ const result = await templates.remove(id)
1389
+ return result.removed
1390
+ ? `deleted custom template "${result.id}"; built-in templates are unaffected`
1391
+ : describeError(`no custom template with id "${result.id}" to delete; built-in templates cannot be deleted`)
1392
+ }
1393
+ return describeError(`unknown action "${args.action}"; use list, show, expand, save, or delete`)
1394
+ } catch (error) {
1395
+ if (error instanceof TemplateError) return templateProblem(error)
1396
+ return describeError(error)
1397
+ }
1398
+ },
1399
+ }))
1400
+
1401
+ // The embedding surface is opt-in: mounting the plugin must not open a port
1402
+ // unasked. When it is on, every request goes through the same orchestrator as
1403
+ // the tools, so quota, budgets, ownership, and cancel behave identically.
1404
+ if (cfg.controlPort !== null) {
1405
+ const clampControlWait = value => {
1406
+ const seconds = Number(value)
1407
+ if (!Number.isFinite(seconds) || seconds <= 0) return 0
1408
+ return Math.min(300, Math.trunc(seconds))
1409
+ }
1410
+ const control = createControlPlane({
1411
+ port: cfg.controlPort,
1412
+ stateRoot: store.root,
1413
+ version: pkg.version,
1414
+ log,
1415
+ actions: {
1416
+ // Liveness only: a probe must not sweep or reclaim runs, so this
1417
+ // deliberately does no state-directory work. Use GET /runs to ask what
1418
+ // is running.
1419
+ async health() {
1420
+ return { runs: 'GET /runs' }
1421
+ },
1422
+ async list({ limit } = {}) {
1423
+ await ready
1424
+ if (stateError) throw stateError
1425
+ const runs = await orchestrator.list()
1426
+ const stats = typeof store.stats === 'function' ? await store.stats() : null
1427
+ const rows = Math.max(1, Math.min(100, Number(limit) || 20))
1428
+ const visible = runs.slice(0, rows)
1429
+ return {
1430
+ data: { runs: visible, stats: stats ? { ...stats, root: store.root } : null },
1431
+ text: formatList(runs, rows, stats ? { ...stats, root: store.root } : null),
1432
+ }
1433
+ },
1434
+ async status(runId, waitSeconds) {
1435
+ await ready
1436
+ if (stateError) throw stateError
1437
+ const run = await orchestrator.status(String(runId ?? '').trim(), clampControlWait(waitSeconds))
1438
+ return { data: { run }, text: formatRun(run) }
1439
+ },
1440
+ async start(body = {}) {
1441
+ await ready
1442
+ if (stateError) throw stateError
1443
+ if (!hasSubagents()) {
1444
+ throw new Error(
1445
+ 'subagent service is unavailable; dsh-superagent needs the host subagents service to create planner, '
1446
+ + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
1447
+ )
1448
+ }
1449
+ const goal = typeof body.goal === 'string' ? body.goal.trim() : ''
1450
+ if (!goal) {
1451
+ // Report the caller's mistake as written in the docs: a missing goal
1452
+ // is 400, not "you also did not name a session".
1453
+ throw new Error('goal is required; pass a concrete goal string')
1454
+ }
1455
+ const agent = resolveSession(body.session_id)
1456
+ const run = await orchestrator.start({
1457
+ goal,
1458
+ parentSessionId: agent.id,
1459
+ parent: agent,
1460
+ clientTimeZone: body.time_zone,
1461
+ allowDuplicate: body.allow_duplicate === true,
1462
+ mode: body.mode,
1463
+ queue: body.queue === true,
1464
+ overrides: {
1465
+ maxSubtasks: body.max_subtasks,
1466
+ maxParallel: body.max_parallel,
1467
+ deadlineMinutes: body.deadline_minutes,
1468
+ },
1469
+ })
1470
+ const waitSeconds = clampControlWait(body.wait_seconds)
1471
+ if (waitSeconds > 0) {
1472
+ const finished = await orchestrator.status(run.id, waitSeconds)
1473
+ const current = run.deduped ? { ...finished, deduped: true } : finished
1474
+ return { data: { run: current }, text: formatRun(current) }
1475
+ }
1476
+ if (run.queue?.waiting) {
1477
+ return {
1478
+ data: { run },
1479
+ text: `${formatRun(run, { includeReport: false })}\n\nQueued, not started: it begins automatically when `
1480
+ + `an active run finishes. Poll GET /runs/${run.id} or cancel it.`,
1481
+ }
1482
+ }
1483
+ return {
1484
+ data: { run },
1485
+ text: `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll `
1486
+ + `GET /runs/${run.id} or call superagent_status.`,
1487
+ }
1488
+ },
1489
+ async cancel(runId) {
1490
+ await ready
1491
+ if (stateError) throw stateError
1492
+ const run = await orchestrator.cancel(String(runId ?? '').trim())
1493
+ const head = run.status === 'cancelled'
1494
+ ? `cancelled ${run.id}`
1495
+ : run.cancelPending
1496
+ ? `cancel requested for ${run.id}, not confirmed by the owning process yet`
1497
+ : `${run.id} is ${run.status}; nothing to cancel`
1498
+ return { data: { run }, text: `${head}\n\n${formatRun(run, { includeReport: false })}` }
1499
+ },
1500
+ async resume(runId, body = {}) {
1501
+ await ready
1502
+ if (stateError) throw stateError
1503
+ if (!hasSubagents()) {
1504
+ throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
1505
+ }
1506
+ const agent = resolveSession(body.session_id)
1507
+ const run = await orchestrator.resume(
1508
+ String(runId ?? '').trim(),
1509
+ agent,
1510
+ body.time_zone,
1511
+ { force: body.force === true || body.override_quota === true },
1512
+ )
1513
+ const waitSeconds = clampControlWait(body.wait_seconds)
1514
+ const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
1515
+ return { data: { run: current }, text: formatRun(current) }
1516
+ },
1517
+ },
1518
+ })
1519
+ let disposed = false
1520
+ const stopControl = () => {
1521
+ disposed = true
1522
+ return control.stop().catch(error => log(`cannot stop the control plane: ${error?.message ?? error}`))
1523
+ }
1524
+ if (typeof ctx.effect === 'function') {
1525
+ ctx.effect(() => stopControl, 'dsh-superagent control plane')
1526
+ } else if (typeof ctx.on === 'function') {
1527
+ ctx.on('dispose', stopControl)
1528
+ }
1529
+ // The state directory is created by `orchestrator.recover()`, which `ready`
1530
+ // awaits. Starting before it exists makes the discovery write fail with
1531
+ // ENOENT and would leave the plane off for the whole host lifetime.
1532
+ ready
1533
+ .then(() => {
1534
+ if (disposed || stateError) return null
1535
+ return control.start()
1536
+ })
1537
+ .catch(error => {
1538
+ log(
1539
+ `control plane is not listening: ${error?.message ?? error}; `
1540
+ + 'check that controlPort is free and the state directory is writable, '
1541
+ + 'or remove controlPort to keep the socket closed',
1542
+ )
1543
+ })
1544
+ }
1545
+
1546
+ log(`registered 9 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
1547
+ }