@xiangyixie/dsh-superagent 0.9.3 → 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,29 +1,38 @@
1
1
  /**
2
2
  * dsh-superagent — long-horizon autonomous runs for DeepSeek Harness.
3
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.
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.
8
9
  *
9
10
  * Registered tools: superagent_start, superagent_status, superagent_list,
10
- * superagent_cancel, superagent_resume.
11
+ * superagent_cancel, superagent_resume, superagent_followup,
12
+ * superagent_answer, superagent_memory, superagent_template.
11
13
  *
12
14
  * @module dsh-superagent
13
15
  */
14
16
  import { randomUUID } from 'node:crypto'
15
17
  import os from 'node:os'
16
18
  import path from 'node:path'
19
+ import { fileURLToPath } from 'node:url'
17
20
  import pkg from '../package.json' with { type: 'json' }
18
- import { createOrchestrator } from './orchestrator.js'
21
+ import { createOrchestrator, followupEffect } from './orchestrator.js'
19
22
  import { createControlPlane } from './control.js'
23
+ import { formatMoney } from './cost.js'
20
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'
21
28
  import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
29
+ import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
22
30
  import { createUsageReader } from './usage.js'
31
+ import { describeWorkspace } from './workspace.js'
23
32
 
24
33
  export const name = 'dsh-superagent'
25
34
  // The host menu and sessions are required. `subagents` is read through
26
- // `ctx.get('subagents')`, so a profile without it still mounts the five tools;
35
+ // `ctx.get('subagents')`, so a profile without it still mounts the eight tools;
27
36
  // they then report what is missing instead of the plugin silently vanishing.
28
37
  export const inject = ['tools', 'agents']
29
38
 
@@ -50,8 +59,17 @@ const DEFAULTS = {
50
59
  maxSubtasks: 8,
51
60
  /** Upper bound on subtasks executing at once. */
52
61
  maxParallel: 3,
53
- /** Runs allowed to be active at the same time; further starts are rejected. */
62
+ /** Runs allowed to be active at the same time; a start over this waits instead of failing. */
54
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,
55
73
  /** Attempts per subtask before it is marked failed. */
56
74
  attempts: 2,
57
75
  /** Wall-clock budget for a whole run, in minutes. */
@@ -70,6 +88,44 @@ const DEFAULTS = {
70
88
  resultCapBytes: 32 * 1024,
71
89
  /** Write one message back to the owning session when a run finishes unattended. */
72
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,
73
129
  /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
74
130
  keepRuns: 0,
75
131
  /**
@@ -78,6 +134,15 @@ const DEFAULTS = {
78
134
  * bearer token are written to `<stateDir>/control.json`.
79
135
  */
80
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,
81
146
  }
82
147
 
83
148
  const REPORT_PREVIEW_CHARS = 8000
@@ -111,6 +176,13 @@ function controlPortOf(value) {
111
176
  return null
112
177
  }
113
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
+
114
186
  function resolveConfig(config) {
115
187
  const merged = { ...DEFAULTS }
116
188
  if (config && typeof config === 'object') {
@@ -121,6 +193,9 @@ function resolveConfig(config) {
121
193
  merged.maxSubtasks = bounded(merged.maxSubtasks, DEFAULTS.maxSubtasks, 1, 16)
122
194
  merged.maxParallel = bounded(merged.maxParallel, DEFAULTS.maxParallel, 1, 8)
123
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)
124
199
  merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
125
200
  merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
126
201
  merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
@@ -134,6 +209,25 @@ function resolveConfig(config) {
134
209
  // Per-model prices merge, so a user can add one route without restating the
135
210
  // built-in table.
136
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
137
231
  return merged
138
232
  }
139
233
 
@@ -181,13 +275,6 @@ function usageLine(usage, status) {
181
275
  + (models ? ` (${models})` : '')
182
276
  }
183
277
 
184
- function currencySymbol(code) {
185
- if (code === 'CNY') return '¥'
186
- if (code === 'USD') return '$'
187
- if (code === 'EUR') return '€'
188
- return `${code} `
189
- }
190
-
191
278
  /**
192
279
  * Cost line for one run. The number is an estimate from the configured list
193
280
  * prices; models without a price are named instead of guessed so a user can
@@ -197,15 +284,30 @@ function costLine(run) {
197
284
  if (!run.usage || !run.usage.modelCalls) return null
198
285
  const models = Object.keys(run.usage.models ?? {})
199
286
  const cost = run.cost
200
- if (!cost || Object.keys(cost.byModel).length === 0) {
201
- return `cost: not computed — no price configured for ${models.join(', ') || 'this model'}; `
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}; `
202
293
  + 'add a pricing entry in cordis.patch.yml to get an estimate'
203
294
  }
204
- const money = `${currencySymbol(cost.currency)}${cost.total.toFixed(4)}`
295
+ const money = formatMoney(cost)
205
296
  if (cost.complete) return `cost: ${money} (estimate; all models priced)`
206
297
  return `cost: at least ${money} (estimate; no price for ${cost.unpriced.join(', ')})`
207
298
  }
208
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
+
209
311
  /** Render one run as text for a tool result. */
210
312
  function formatRun(run, { includeReport = true } = {}) {
211
313
  const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
@@ -217,6 +319,17 @@ function formatRun(run, { includeReport = true } = {}) {
217
319
  `elapsed: ${elapsed(run)}`,
218
320
  usageLine(run.usage, run.status),
219
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
+ }
220
333
  const unreadable = Object.keys(run.counters?.unreadable ?? {}).length
221
334
  if (unreadable > 0) {
222
335
  lines.push(
@@ -226,6 +339,80 @@ function formatRun(run, { includeReport = true } = {}) {
226
339
  }
227
340
  const cost = costLine(run)
228
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
+ }
229
416
  if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
230
417
  if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
231
418
  if (run.status === 'interrupted' && run.error) {
@@ -242,14 +429,24 @@ function formatRun(run, { includeReport = true } = {}) {
242
429
  lines.push('cancel: requested, but the process running this run has not confirmed yet; check superagent_status again in a few seconds')
243
430
  }
244
431
  for (const subtask of run.subtasks) {
245
- const tokens = subtask.usage ? ` ${subtask.usage.inputTokens} in / ${subtask.usage.outputTokens} out` : ''
246
- const detail = subtask.error ? ` — ${summarizeError(subtask.error)}` : ''
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)}` : '')
247
444
  // A cancelled run never judged its unfinished subtasks, so calling them
248
445
  // "pending" or "failed (attempts 0)" would misreport what happened.
249
446
  const status = run.status === 'cancelled' && subtask.status !== 'completed'
250
447
  ? (subtask.attempts > 0 ? 'cancelled' : 'skipped')
251
448
  : subtask.status
252
- lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${detail}`)
449
+ lines.push(` [${subtask.index}] ${status} (attempts ${subtask.attempts}) ${subtask.title}${tokens}${waiting}${detail}`)
253
450
  }
254
451
  const failed = run.subtasks.find(subtask => subtask.error)
255
452
  if (failed) {
@@ -259,6 +456,12 @@ function formatRun(run, { includeReport = true } = {}) {
259
456
  if (includeReport && run.report) {
260
457
  lines.push('', 'report:', '', preview(run.report))
261
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
+ }
262
465
  if (!TERMINAL_STATUSES.has(run.status)) {
263
466
  lines.push('', `next: superagent_status run_id="${run.id}" wait_seconds=120`)
264
467
  } else if (run.status === 'interrupted') {
@@ -279,6 +482,17 @@ function notifyFailed(run) {
279
482
  return !/^(skipped|disabled):/.test(String(run.notify.reason ?? ''))
280
483
  }
281
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
+
282
496
  function formatList(runs, limit, stats = null) {
283
497
  if (runs.length === 0) return 'no superagent runs recorded'
284
498
  const rows = runs.slice(0, limit).map(run => {
@@ -290,6 +504,29 @@ function formatList(runs, limit, stats = null) {
290
504
  if (stats) {
291
505
  lines.push('', `state: ${stats.files} file(s), ${formatBytes(stats.bytes)} in ${stats.root}`
292
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
+ }
293
530
  }
294
531
  return lines.join('\n')
295
532
  }
@@ -328,6 +565,44 @@ export function apply(ctx, config) {
328
565
  const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
329
566
  const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
330
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 })
331
606
 
332
607
  /** Child sessions spawned by this process; a run may not be started from one. */
333
608
  const childIds = new Set()
@@ -335,7 +610,7 @@ export function apply(ctx, config) {
335
610
  /**
336
611
  * The subagent service is optional, so it is read from the service store at
337
612
  * call time rather than declared as an injection: a profile without it must
338
- * still mount the five tools (they then explain what is missing), and reading
613
+ * still mount the eight tools (they then explain what is missing), and reading
339
614
  * it lazily also sees a service that registers after this plugin.
340
615
  */
341
616
  function getSubagents() {
@@ -362,8 +637,11 @@ export function apply(ctx, config) {
362
637
  /**
363
638
  * Map a run outcome to one message for the owning session.
364
639
  *
365
- * The followup is awaited: an unhandled rejection from it would otherwise
366
- * escape as a host-level error while the run already claims it was delivered.
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.
367
645
  */
368
646
  async function notifyParent(run) {
369
647
  if (run.notified) return { delivered: false, reason: 'skipped: the owning session was already notified' }
@@ -377,22 +655,61 @@ export function apply(ctx, config) {
377
655
  reason: `the owning session ${run.parentSessionId} is no longer live; read the report with superagent_status`,
378
656
  }
379
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
+
380
663
  const completed = run.subtasks.filter(subtask => subtask.status === 'completed').length
381
- const text = [
382
- `[superagent] run ${run.id} finished: ${run.status} (${completed}/${run.subtasks.length} subtasks).`,
383
- `Call superagent_status with run_id="${run.id}" to read the report.`,
384
- ].join(' ')
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.`)
385
697
  try {
386
- await agent.followup({
698
+ await outbox.enqueue(run.parentSessionId, () => agent.followup({
387
699
  id: randomUUID(),
388
700
  role: 'user',
389
- content: [{ type: 'text', text }],
701
+ content: [{ type: 'text', text: lines.join(' ') }],
390
702
  source: { kind: 'user' },
391
- })
703
+ }))
392
704
  run.notified = true
393
705
  return { delivered: true }
394
706
  } catch (error) {
395
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
+ })
396
713
  return { delivered: false, reason: `waking the session failed: ${error?.message ?? error}` }
397
714
  }
398
715
  }
@@ -402,8 +719,9 @@ export function apply(ctx, config) {
402
719
  config: cfg,
403
720
  log,
404
721
  readUsage,
722
+ memory,
405
723
  notify: notifyParent,
406
- async spawnChild({ label, prompt, parent, signal }) {
724
+ async spawnChild({ label, prompt, parent, signal, model }) {
407
725
  const subagents = getSubagents()
408
726
  if (!subagents || typeof subagents.startActivation !== 'function') {
409
727
  const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
@@ -416,8 +734,11 @@ export function apply(ctx, config) {
416
734
  const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(cfg.provider) : undefined
417
735
  const capabilities = provider?.capabilities ?? null
418
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
419
740
  if (cfg.childProvider) agentOptions.provider = cfg.childProvider
420
- if (cfg.childModel) agentOptions.model = cfg.childModel
741
+ if (childModel) agentOptions.model = childModel
421
742
  const request = {
422
743
  parent,
423
744
  prompt: [{ type: 'text', text: prompt }],
@@ -483,6 +804,23 @@ export function apply(ctx, config) {
483
804
  log(`state directory is not usable: ${stateError.message}`)
484
805
  return
485
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
+ }
486
824
  if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
487
825
  try {
488
826
  const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
@@ -541,15 +879,38 @@ export function apply(ctx, config) {
541
879
  ctx.tools.register(defineTool({
542
880
  name: 'superagent_start',
543
881
  description:
544
- 'Start a long-horizon autonomous run: a planner decomposes the goal into independent subtasks, '
545
- + 'the subtasks run in parallel child agents, and their reports are merged into one final report. '
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. '
546
888
  + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
547
889
  + 'so they survive a host restart and can be resumed or cancelled.',
548
890
  properties: {
549
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
+ },
550
906
  max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
551
907
  max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
552
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
+ },
553
914
  wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
554
915
  },
555
916
  required: ['goal'],
@@ -570,6 +931,9 @@ export function apply(ctx, config) {
570
931
  parentSessionId: check.agent.id,
571
932
  parent: check.agent,
572
933
  clientTimeZone: exec.clientTimeZone,
934
+ allowDuplicate: args.allow_duplicate === true,
935
+ mode: args.mode,
936
+ queue: args.queue === true,
573
937
  overrides: {
574
938
  maxSubtasks: args.max_subtasks,
575
939
  maxParallel: args.max_parallel,
@@ -579,7 +943,14 @@ export function apply(ctx, config) {
579
943
  const waitSeconds = Number(args.wait_seconds) || 0
580
944
  if (waitSeconds > 0) {
581
945
  const finished = await orchestrator.status(run.id, waitSeconds)
582
- return formatRun(finished)
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.'
583
954
  }
584
955
  return `${formatRun(run, { includeReport: false })}\n\nStarted in the background. Poll with superagent_status; `
585
956
  + 'the run keeps going after this tool call returns.'
@@ -604,6 +975,7 @@ export function apply(ctx, config) {
604
975
  await ready
605
976
  if (stateError) return describeError(stateError)
606
977
  const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
978
+ await recordSpend([run])
607
979
  return formatRun(run)
608
980
  } catch (error) {
609
981
  return describeError(error)
@@ -622,8 +994,26 @@ export function apply(ctx, config) {
622
994
  await ready
623
995
  if (stateError) return describeError(stateError)
624
996
  const runs = await orchestrator.list()
997
+ await recordSpend(runs)
625
998
  const stats = typeof store.stats === 'function' ? await store.stats() : null
626
- return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), stats ? { ...stats, root: store.root } : null)
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)
627
1017
  } catch (error) {
628
1018
  return describeError(error)
629
1019
  }
@@ -646,6 +1036,7 @@ export function apply(ctx, config) {
646
1036
  await ready
647
1037
  if (stateError) return describeError(stateError)
648
1038
  const run = await orchestrator.cancel(String(args.run_id ?? '').trim())
1039
+ await recordSpend([run])
649
1040
  const head = run.status === 'cancelled'
650
1041
  ? `cancelled ${run.id}`
651
1042
  : run.cancelPending
@@ -662,10 +1053,15 @@ export function apply(ctx, config) {
662
1053
  name: 'superagent_resume',
663
1054
  description:
664
1055
  'Resume a run that was interrupted by a host restart, ran out of time, or failed part way. '
665
- + 'Completed subtasks are kept; pending and failed ones run again.',
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.',
666
1058
  properties: {
667
1059
  run_id: { type: 'string', description: 'Run id to resume.' },
668
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
+ },
669
1065
  },
670
1066
  required: ['run_id'],
671
1067
  async execute(args = {}, exec) {
@@ -679,9 +1075,15 @@ export function apply(ctx, config) {
679
1075
  'subagent service is unavailable; resuming a run needs the host subagents service to create child agents.',
680
1076
  )
681
1077
  }
682
- const run = await orchestrator.resume(String(args.run_id ?? '').trim(), check.agent, exec.clientTimeZone)
1078
+ const run = await orchestrator.resume(
1079
+ String(args.run_id ?? '').trim(),
1080
+ check.agent,
1081
+ exec.clientTimeZone,
1082
+ { force: args.force === true },
1083
+ )
683
1084
  const waitSeconds = Number(args.wait_seconds) || 0
684
1085
  const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
1086
+ await recordSpend([current])
685
1087
  return formatRun(current)
686
1088
  } catch (error) {
687
1089
  return describeError(error)
@@ -689,6 +1091,313 @@ export function apply(ctx, config) {
689
1091
  },
690
1092
  }))
691
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
+
692
1401
  // The embedding surface is opt-in: mounting the plugin must not open a port
693
1402
  // unasked. When it is on, every request goes through the same orchestrator as
694
1403
  // the tools, so quota, budgets, ownership, and cancel behave identically.
@@ -749,6 +1458,9 @@ export function apply(ctx, config) {
749
1458
  parentSessionId: agent.id,
750
1459
  parent: agent,
751
1460
  clientTimeZone: body.time_zone,
1461
+ allowDuplicate: body.allow_duplicate === true,
1462
+ mode: body.mode,
1463
+ queue: body.queue === true,
752
1464
  overrides: {
753
1465
  maxSubtasks: body.max_subtasks,
754
1466
  maxParallel: body.max_parallel,
@@ -758,7 +1470,15 @@ export function apply(ctx, config) {
758
1470
  const waitSeconds = clampControlWait(body.wait_seconds)
759
1471
  if (waitSeconds > 0) {
760
1472
  const finished = await orchestrator.status(run.id, waitSeconds)
761
- return { data: { run: finished }, text: formatRun(finished) }
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
+ }
762
1482
  }
763
1483
  return {
764
1484
  data: { run },
@@ -784,7 +1504,12 @@ export function apply(ctx, config) {
784
1504
  throw new Error('subagent service is unavailable; resuming a run needs the host subagents service to create child agents.')
785
1505
  }
786
1506
  const agent = resolveSession(body.session_id)
787
- const run = await orchestrator.resume(String(runId ?? '').trim(), agent, body.time_zone)
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
+ )
788
1513
  const waitSeconds = clampControlWait(body.wait_seconds)
789
1514
  const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
790
1515
  return { data: { run: current }, text: formatRun(current) }
@@ -818,5 +1543,5 @@ export function apply(ctx, config) {
818
1543
  })
819
1544
  }
820
1545
 
821
- log(`registered 5 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
1546
+ log(`registered 9 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
822
1547
  }