@xiangyixie/dsh-superagent 0.11.0 → 0.12.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
@@ -8,19 +8,23 @@
8
8
  * durable logs.
9
9
  *
10
10
  * Registered tools: superagent_start, superagent_status, superagent_list,
11
- * superagent_cancel, superagent_resume, superagent_followup,
12
- * superagent_answer, superagent_memory, superagent_template.
11
+ * superagent_cancel, superagent_resume, superagent_followup, superagent_inject,
12
+ * superagent_answer, superagent_memory, superagent_template, superagent_audit.
13
13
  *
14
14
  * @module dsh-superagent
15
15
  */
16
16
  import { randomUUID } from 'node:crypto'
17
+ import { existsSync } from 'node:fs'
17
18
  import os from 'node:os'
18
19
  import path from 'node:path'
19
20
  import { fileURLToPath } from 'node:url'
20
21
  import pkg from '../package.json' with { type: 'json' }
22
+ import { createAuditor } from './audit.js'
21
23
  import { createOrchestrator, followupEffect } from './orchestrator.js'
24
+ import { createChildSteerer, createChildWatcher, INJECT_POLL_MS, pendingIds } from './inject.js'
22
25
  import { createControlPlane } from './control.js'
23
26
  import { formatMoney } from './cost.js'
27
+ import { createGuard } from './guard.js'
24
28
  import { classifyError, describeError, summarizeError } from './errors.js'
25
29
  import { createLedger } from './ledger.js'
26
30
  import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
@@ -29,10 +33,11 @@ import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } fro
29
33
  import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
30
34
  import { createUsageReader } from './usage.js'
31
35
  import { describeWorkspace } from './workspace.js'
36
+ import { createRunChangeTracker, createWorkbench } from './workbench.js'
32
37
 
33
38
  export const name = 'dsh-superagent'
34
39
  // 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;
40
+ // `ctx.get('subagents')`, so a profile without it still mounts the eleven tools;
36
41
  // they then report what is missing instead of the plugin silently vanishing.
37
42
  export const inject = ['tools', 'agents']
38
43
 
@@ -106,6 +111,12 @@ const DEFAULTS = {
106
111
  notifyRetries: 2,
107
112
  /** First delay between delivery attempts; it doubles per attempt. */
108
113
  notifyRetryDelayMs: 2000,
114
+ /**
115
+ * Poll period, in milliseconds, used to observe when a running child claims
116
+ * an injected message. It is the resolution of every reported latency, so it
117
+ * is deliberately visible instead of rounded away.
118
+ */
119
+ injectPollMs: INJECT_POLL_MS,
109
120
  /**
110
121
  * Child model used on a self-heal round when the failure looks transient
111
122
  * (quota, rate limit, timeout). `null` keeps the configured route.
@@ -128,6 +139,37 @@ const DEFAULTS = {
128
139
  memoryDigestChars: 1600,
129
140
  /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
130
141
  keepRuns: 0,
142
+ /**
143
+ * Safety guard for child tool calls. Workers inherit the session's filesystem
144
+ * and credentials, so this policy is enforced on the host's tool pipeline.
145
+ * Defaults stand in `lib/guard.js`; see “Safety guard” in the README.
146
+ */
147
+ guard: {
148
+ enabled: true,
149
+ /** Extra writable roots; the child session workspace and OS temp dir are implicit. */
150
+ allowWriteRoots: [],
151
+ /** Extra paths denied for both reading and writing. */
152
+ denyPaths: [],
153
+ /** Extra `{ id, pattern, reason }` command denials. */
154
+ denyCommands: [],
155
+ /** `{ id, pattern, reason }` entries that override a denial; every use is recorded. */
156
+ allowCommands: [],
157
+ /** Events kept per run; the counters still include events beyond the cap. */
158
+ maxEvents: 50,
159
+ },
160
+ /**
161
+ * Append-only audit trail under `<stateDir>/audit/audit.jsonl`. It is an
162
+ * observer layer: turning it off removes the trail, never the run behaviour.
163
+ */
164
+ audit: true,
165
+ /**
166
+ * Permission policy for runs. Unset means `<stateDir>/policy.json` when that
167
+ * file exists, so dropping a policy next to the state is enough to enable it.
168
+ * An empty state means "no policy", which is exactly the old behaviour.
169
+ */
170
+ policyFile: null,
171
+ /** Where the audit JSONL lives; defaults to `<stateDir>/audit`. */
172
+ auditDir: null,
131
173
  /**
132
174
  * Loopback HTTP port for the embedding surface. `null` (default) keeps the
133
175
  * socket closed; `0` asks the OS for a free port. The bound address and its
@@ -143,6 +185,17 @@ const DEFAULTS = {
143
185
  workspaceIsolation: false,
144
186
  /** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
145
187
  workspaceRoot: null,
188
+ /**
189
+ * Loopback HTTP port for the local workspace panel. `null` (default) keeps it
190
+ * off; `0` asks the OS for a free port. The bound address and its one-time
191
+ * token are written to `<stateDir>/workbench.json`.
192
+ */
193
+ workbenchPort: null,
194
+ /**
195
+ * Directory the panel may read and edit. Everything outside it is refused.
196
+ * Defaults to the host process's working directory.
197
+ */
198
+ workbenchRoot: null,
146
199
  }
147
200
 
148
201
  const REPORT_PREVIEW_CHARS = 8000
@@ -203,6 +256,10 @@ function resolveConfig(config) {
203
256
  merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
204
257
  merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
205
258
  merged.controlPort = controlPortOf(merged.controlPort)
259
+ merged.workbenchPort = controlPortOf(merged.workbenchPort)
260
+ merged.workbenchRoot = typeof merged.workbenchRoot === 'string' && merged.workbenchRoot.trim()
261
+ ? merged.workbenchRoot.trim()
262
+ : null
206
263
  merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
207
264
  ? 'provider-managed'
208
265
  : bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
@@ -210,6 +267,13 @@ function resolveConfig(config) {
210
267
  // built-in table.
211
268
  merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
212
269
  merged.memory = flag(merged.memory, DEFAULTS.memory)
270
+ merged.audit = flag(merged.audit, DEFAULTS.audit)
271
+ merged.policyFile = typeof merged.policyFile === 'string' && merged.policyFile.trim()
272
+ ? merged.policyFile.trim()
273
+ : null
274
+ merged.auditDir = typeof merged.auditDir === 'string' && merged.auditDir.trim()
275
+ ? merged.auditDir.trim()
276
+ : null
213
277
  merged.memoryScope = normalizeScope(merged.memoryScope)
214
278
  merged.memoryMaxEntries = bounded(merged.memoryMaxEntries, DEFAULTS.memoryMaxEntries, 1, 500)
215
279
  merged.memoryMaxAgeDays = bounded(merged.memoryMaxAgeDays, DEFAULTS.memoryMaxAgeDays, 1, 3650)
@@ -218,6 +282,7 @@ function resolveConfig(config) {
218
282
  merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
219
283
  merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
220
284
  merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
285
+ merged.injectPollMs = bounded(merged.injectPollMs, DEFAULTS.injectPollMs, 10, 1000)
221
286
  merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
222
287
  merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
223
288
  ? merged.childModelFallback.trim()
@@ -228,6 +293,12 @@ function resolveConfig(config) {
228
293
  merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
229
294
  ? merged.workspaceRoot.trim()
230
295
  : null
296
+ // The guard block merges so a user can set only `allowCommands` without
297
+ // restating the rest of the defaults.
298
+ merged.guard = {
299
+ ...DEFAULTS.guard,
300
+ ...(config?.guard && typeof config.guard === 'object' ? config.guard : {}),
301
+ }
231
302
  return merged
232
303
  }
233
304
 
@@ -345,6 +416,19 @@ function formatRun(run, { includeReport = true } = {}) {
345
416
  + `(${run.memory.digestChars} chars)`,
346
417
  )
347
418
  }
419
+ if (run.guard && (run.guard.blocked > 0 || run.guard.allowed > 0)) {
420
+ const rules = Object.entries(run.guard.byRule ?? {})
421
+ .map(([rule, count]) => `${rule} ×${count}`)
422
+ .join(', ')
423
+ lines.push(
424
+ `guard: ${run.guard.blocked} tool call(s) blocked; ${run.guard.allowed} explicit allow(s) recorded`
425
+ + (rules ? ` (${rules})` : ''),
426
+ )
427
+ for (const event of (run.guard.events ?? []).filter(item => item.decision === 'blocked').slice(0, 3)) {
428
+ const detail = String(event.detail ?? '').replace(/\s+/g, ' ').slice(0, 120)
429
+ lines.push(` blocked ${event.tool}${event.label ? ` (${event.label})` : ''}: ${detail} — ${event.rule}`)
430
+ }
431
+ }
348
432
  if (run.attention?.issue) {
349
433
  lines.push(`attention: ${run.attention.issue}`)
350
434
  }
@@ -385,6 +469,35 @@ function formatRun(run, { includeReport = true } = {}) {
385
469
  )
386
470
  }
387
471
  }
472
+ if (Array.isArray(run.injections) && run.injections.length > 0) {
473
+ const degraded = run.injections.filter(entry => entry.status === 'degraded')
474
+ const targets = run.injections.flatMap(entry => entry.targets ?? [])
475
+ const applied = targets.filter(target => target.status === 'applied')
476
+ const pending = targets.filter(target => target.status === 'pending')
477
+ const missed = targets.filter(target => target.status === 'missed' || target.status === 'failed')
478
+ const worst = run.injectionStats?.worstLatencyMs
479
+ if (applied.length > 0) {
480
+ lines.push(
481
+ `live injections: ${applied.length} reached a child's next step`
482
+ + (Number.isFinite(worst) ? ` (worst measured ${worst} ms)` : ''),
483
+ )
484
+ }
485
+ if (pending.length > 0) {
486
+ lines.push(`live injections: ${pending.length} accepted and waiting for a child's next step boundary`)
487
+ }
488
+ if (missed.length > 0) {
489
+ lines.push(
490
+ `live injections: ${missed.length} never entered a prompt — `
491
+ + `${missed[0].missedReason ?? missed[0].error ?? 'the child left first'}`,
492
+ )
493
+ }
494
+ if (degraded.length > 0) {
495
+ lines.push(
496
+ `live injections: ${degraded.length} could not be delivered live and were queued; they take effect at `
497
+ + followupEffect(run).detail,
498
+ )
499
+ }
500
+ }
388
501
  if (Array.isArray(run.milestones) && run.milestones.length > 0) {
389
502
  // Times are UTC because the record is ISO; a status line is not a place to
390
503
  // start guessing the reader's timezone.
@@ -476,6 +589,80 @@ function formatBytes(bytes) {
476
589
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`
477
590
  }
478
591
 
592
+ /**
593
+ * The reply for one live injection.
594
+ *
595
+ * The wording separates four states instead of collapsing them into "sent":
596
+ * accepted (the child's inbox holds the message), applied (a step boundary
597
+ * claimed it, with the measured delay), pending (still waiting for that
598
+ * boundary), and missed (the child left before it could read the message).
599
+ *
600
+ * @param {object} run - live run record.
601
+ * @param {object} entry - injection receipt.
602
+ * @param {object | null} degraded - queued-as-followup fallback, when the host has no live channel.
603
+ * @param {{ pollMs: number }} options - poll resolution used for the measurement.
604
+ * @returns {string} the tool reply.
605
+ */
606
+ function formatInjectionReply(run, entry, degraded, { pollMs }) {
607
+ const targets = entry?.targets ?? []
608
+ const accepted = targets.filter(target => target.messageId)
609
+ const applied = targets.filter(target => target.status === 'applied')
610
+ const missed = targets.filter(target => target.status === 'missed')
611
+ const failed = targets.filter(target => target.status === 'failed')
612
+ const pending = targets.filter(target => target.status === 'pending')
613
+ const lines = []
614
+
615
+ if (degraded) {
616
+ lines.push(
617
+ `instruction ${entry.id} could not be delivered live on run ${run.id}: ${degraded.reason}`,
618
+ `it was queued as instruction ${degraded.followup.id} instead, and takes effect at ${degraded.effect.detail} `
619
+ + `(boundary: ${degraded.effect.boundary}).`,
620
+ 'a worker that is already running is not interrupted and does not see it.',
621
+ )
622
+ return lines.join('\n')
623
+ }
624
+
625
+ lines.push(
626
+ `instruction ${entry.id} accepted by ${accepted.length}/${targets.length} running worker(s) on run ${run.id} — `
627
+ + `${run.status}`,
628
+ )
629
+ for (const target of targets) {
630
+ const who = `subtask ${target.subtaskIndex} (child ${target.childId})`
631
+ if (target.status === 'applied') {
632
+ lines.push(` ${who}: seen at the child's next step after ${target.latencyMs ?? '?'} ms${target.via ? ` via ${target.via}` : ''}`)
633
+ } else if (target.status === 'pending') {
634
+ lines.push(` ${who}: accepted (message ${target.messageId}); it has not reached a step boundary yet`)
635
+ } else if (target.status === 'missed') {
636
+ lines.push(` ${who}: missed — ${target.missedReason}`)
637
+ } else {
638
+ lines.push(` ${who}: not delivered — ${target.error ?? 'unknown error'}`)
639
+ }
640
+ }
641
+ const stats = run.injectionStats
642
+ const worst = Number.isFinite(stats?.worstLatencyMs) ? `${stats.worstLatencyMs} ms` : 'not measured yet'
643
+ lines.push(
644
+ 'delivery: steering is read at the child\'s next step boundary, just before its next model request. It does not '
645
+ + 'interrupt a model call already in flight, so the worst case is the remainder of that step (its model response '
646
+ + 'plus tool batch).',
647
+ `measured on this run: worst ${worst} over ${stats?.samples ?? 0} claimed message(s); the poll resolution is `
648
+ + `${pollMs} ms.`,
649
+ )
650
+ if (pending.length > 0) {
651
+ lines.push(
652
+ `not seen yet: ${pending.length} message(s) are still waiting at a live child's boundary; this reply does not `
653
+ + 'claim they were read. superagent_status shows the receipt once the boundary claims it.',
654
+ )
655
+ }
656
+ if (missed.length + failed.length > 0) {
657
+ lines.push(
658
+ `${missed.length + failed.length} message(s) never entered a prompt. If the work must still change, send the `
659
+ + 'instruction again to a running worker, or use superagent_followup for the next prompt.',
660
+ )
661
+ }
662
+ lines.push('', formatRun(run, { includeReport: false }))
663
+ return lines.join('\n')
664
+ }
665
+
479
666
  /** True when a run finished but its owner was never told, and that is a problem. */
480
667
  function notifyFailed(run) {
481
668
  if (!run.notify || run.notify.delivered) return false
@@ -535,6 +722,46 @@ function toolText(text) {
535
722
  return [{ type: 'text', text }]
536
723
  }
537
724
 
725
+ /**
726
+ * Render one audit query as a short report: the window, how the events break
727
+ * down, and the latest rows. The full detail stays one export away, so this
728
+ * never floods the session with a thousand lines it cannot use.
729
+ */
730
+ function formatAudit(result, { limit = 8 } = {}) {
731
+ const { events, scanned, invalid, torn, file } = result
732
+ const notes = []
733
+ if (invalid) notes.push(`${invalid} unreadable line(s) skipped`)
734
+ if (torn) notes.push('1 torn trailing line ignored')
735
+ const tail = notes.length > 0 ? `; ${notes.join('; ')}` : ''
736
+ if (events.length === 0) return `audit: no matching events (${scanned} scanned in ${file}${tail})`
737
+ const tally = field => {
738
+ const counts = new Map()
739
+ for (const event of events) {
740
+ const key = event[field] ?? 'none'
741
+ counts.set(key, (counts.get(key) ?? 0) + 1)
742
+ }
743
+ return [...counts.entries()]
744
+ .sort((a, b) => b[1] - a[1])
745
+ .map(([key, count]) => `${key} ${count}`)
746
+ .join(', ')
747
+ }
748
+ const lines = [
749
+ `audit: ${events.length} event(s) match (${scanned} scanned in ${file}${tail})`,
750
+ `window: ${events[0].at} .. ${events.at(-1).at}`,
751
+ `decision: ${tally('decision')}`,
752
+ `kind: ${tally('kind')}`,
753
+ `result: ${tally('result')}`,
754
+ 'latest:',
755
+ ]
756
+ for (const event of events.slice(-Math.max(1, limit))) {
757
+ lines.push(
758
+ ` ${event.at} ${String(event.decision ?? '-').padEnd(7)} ${String(event.kind).padEnd(12)} `
759
+ + `${String(event.runId ?? '-').padEnd(14)} ${event.rule ?? '-'} ${event.target ?? ''}`.trimEnd(),
760
+ )
761
+ }
762
+ return lines.join('\n')
763
+ }
764
+
538
765
  function defineTool(spec) {
539
766
  return {
540
767
  name: spec.name,
@@ -553,16 +780,28 @@ function defineTool(spec) {
553
780
  export function apply(ctx, config) {
554
781
  const log = message => console.error(`[dsh-superagent] ${message}`)
555
782
  const configuredPort = config?.controlPort
783
+ const configuredWorkbenchPort = config?.workbenchPort
556
784
  const cfg = resolveConfig(config)
557
785
  if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
558
786
  log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
559
787
  }
788
+ if (configuredWorkbenchPort !== undefined && configuredWorkbenchPort !== null && cfg.workbenchPort === null) {
789
+ log(`workbenchPort ${JSON.stringify(configuredWorkbenchPort)} is not a whole number in 0–65535; the workspace panel stays off`)
790
+ }
560
791
  if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
561
792
  console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
562
793
  return
563
794
  }
564
795
 
565
- const store = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
796
+ const baseStore = createStore(resolveStateRoot(cfg.stateDir), { warn: log })
797
+ const workbenchRoot = cfg.workbenchRoot ? path.resolve(cfg.workbenchRoot) : process.cwd()
798
+ // The panel reads `run.changes` from the durable record. The tracker writes
799
+ // that field through the same store the orchestrator already uses, so the
800
+ // orchestrator itself needs no edit and the panel can stay opt-in.
801
+ const changeTracker = cfg.workbenchPort === null
802
+ ? null
803
+ : createRunChangeTracker({ store: baseStore, root: workbenchRoot, stateRoot: baseStore.root, warn: log })
804
+ const store = changeTracker?.store ?? baseStore
566
805
  const home = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
567
806
  const readUsage = createUsageReader({ sessionsRoot: path.join(home, 'sessions'), warn: log })
568
807
  // The ledger is an append-only history of priced runs. Writing it here, from
@@ -594,6 +833,73 @@ export function apply(ctx, config) {
594
833
  // Built-ins need no storage; only custom templates touch the state directory,
595
834
  // and a state directory inside the package must not receive new files.
596
835
  const templates = createTemplateStore(store.root, { warn: log })
836
+ // The trail and its policy live beside the run state, so one directory holds
837
+ // everything a reviewer needs. A policy the user did not name is picked up
838
+ // only when it already exists; without one, runs behave exactly as before.
839
+ const auditDir = cfg.auditDir ? path.resolve(cfg.auditDir) : path.join(store.root, 'audit')
840
+ const implicitPolicy = path.join(store.root, 'policy.json')
841
+ const policyFile = cfg.policyFile
842
+ ? path.resolve(cfg.policyFile)
843
+ : (existsSync(implicitPolicy) ? implicitPolicy : null)
844
+ const auditBlocked = isInside(auditDir, packageRoot)
845
+ const auditor = cfg.audit && !auditBlocked ? createAuditor({ dir: auditDir, policyFile, warn: log }) : null
846
+ if (cfg.audit && auditBlocked) {
847
+ log(`audit trail stays off: ${auditDir} is inside the installed package; point stateDir or auditDir elsewhere`)
848
+ }
849
+ if (auditor) {
850
+ auditor.policyError()
851
+ .then(error => {
852
+ if (error) log(error.message ?? String(error))
853
+ })
854
+ .catch(() => {})
855
+ log(`audit trail ${auditor.file}; policy ${policyFile ?? 'none (permissive)'}`)
856
+ }
857
+
858
+ // The guard is mounted on the host's tool pipeline, scoped to children this
859
+ // plugin spawns. `process.cwd()` is only a fallback: every call uses the
860
+ // child session's own workspace when the host exposes one.
861
+ const guard = createGuard({ config: cfg.guard, cwd: process.cwd(), warn: log })
862
+ if (guard.enabled) {
863
+ const enforce = exec => {
864
+ const verdict = guard.checkToolCall(exec)
865
+ if (!verdict.blocked) return undefined
866
+ log(`guard blocked ${exec?.name ?? 'tool'} for ${verdict.label ?? 'a worker'}: ${verdict.rule} — ${verdict.reason}`)
867
+ // A block is evidence, so it belongs in the same trail as every other
868
+ // decision. The guard owns the verdict; the trail only records it.
869
+ if (auditor && typeof auditor.record === 'function') {
870
+ auditor.record({
871
+ kind: 'blocked',
872
+ action: exec?.name ?? 'tool',
873
+ target: verdict.detail ?? null,
874
+ actor: verdict.label ?? null,
875
+ decision: 'deny',
876
+ result: 'blocked',
877
+ rule: verdict.rule ?? null,
878
+ source: 'guard',
879
+ meta: { reason: verdict.reason ?? null },
880
+ }).catch(error => log(`audit: cannot record guard block: ${error?.message ?? error}`))
881
+ }
882
+ return verdict.reasonText
883
+ }
884
+ let hooked = false
885
+ if (typeof ctx.tools.guard === 'function') {
886
+ const release = ctx.tools.guard(enforce)
887
+ hooked = true
888
+ if (typeof release === 'function' && typeof ctx.effect === 'function') {
889
+ ctx.effect(() => () => release())
890
+ }
891
+ } else if (typeof ctx.on === 'function') {
892
+ ctx.on('tools/pre-execute', async (exec, next) => {
893
+ const reason = enforce(exec)
894
+ return reason ? { kind: 'deny', reason } : next()
895
+ })
896
+ hooked = true
897
+ }
898
+ if (!hooked) {
899
+ log('guard is enabled but this host exposes neither tools.guard nor tools/pre-execute; child calls are not gated')
900
+ }
901
+ }
902
+
597
903
  const notifyPolicy = createNotifyPolicy({
598
904
  stateFile: path.join(store.root, 'notifications.json'),
599
905
  maxPerHour: cfg.maxNotificationsPerHour,
@@ -610,7 +916,7 @@ export function apply(ctx, config) {
610
916
  /**
611
917
  * The subagent service is optional, so it is read from the service store at
612
918
  * 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
919
+ * still mount the eleven tools (they then explain what is missing), and reading
614
920
  * it lazily also sees a service that registers after this plugin.
615
921
  */
616
922
  function getSubagents() {
@@ -627,6 +933,15 @@ export function apply(ctx, config) {
627
933
  }
628
934
  }
629
935
 
936
+ /** The agent registry, read lazily for the same reason as `subagents`. */
937
+ function getAgents() {
938
+ if (typeof ctx.get === 'function') {
939
+ const service = ctx.get('agents')
940
+ if (service) return service
941
+ }
942
+ return undefined
943
+ }
944
+
630
945
  /** Remember a child id for the recursion guard without growing forever. */
631
946
  function rememberChild(childId) {
632
947
  if (!childId) return
@@ -720,8 +1035,22 @@ export function apply(ctx, config) {
720
1035
  log,
721
1036
  readUsage,
722
1037
  memory,
1038
+ guard,
1039
+ audit: auditor,
723
1040
  notify: notifyParent,
724
- async spawnChild({ label, prompt, parent, signal, model }) {
1041
+ // Live delivery into a running child. The steerer reads both services at
1042
+ // call time; the inspector gives the orchestrator the child's inbox state
1043
+ // at the moment its attempt ends, before disposal.
1044
+ steerChild: createChildSteerer({ getSubagents, getAgents, log }),
1045
+ inspectChild(childId) {
1046
+ const agent = getAgents()?.get?.(childId)
1047
+ return { live: Boolean(agent), pending: pendingIds(agent) }
1048
+ },
1049
+ watchChild: createChildWatcher({
1050
+ resolveChild: childId => getAgents()?.get?.(childId),
1051
+ intervalMs: cfg.injectPollMs,
1052
+ }),
1053
+ async spawnChild({ label, prompt, parent, signal, model, runId }) {
725
1054
  const subagents = getSubagents()
726
1055
  if (!subagents || typeof subagents.startActivation !== 'function') {
727
1056
  const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
@@ -776,10 +1105,12 @@ export function apply(ctx, config) {
776
1105
  delivery: 'caller',
777
1106
  })
778
1107
  rememberChild(activation.childId)
1108
+ guard.bindChild(activation.childId, { runId, label })
779
1109
  return {
780
1110
  childId: activation.childId,
781
1111
  result: activation.result,
782
1112
  dispose: async () => {
1113
+ guard.unbindChild(activation.childId)
783
1114
  try {
784
1115
  await activation.dispose()
785
1116
  } catch (error) {
@@ -911,6 +1242,11 @@ export function apply(ctx, config) {
911
1242
  description: 'Start a second run for the same goal even when an active run already has it. '
912
1243
  + 'By default the active run id is returned instead, so a retry cannot double the spend.',
913
1244
  },
1245
+ approve_policy: {
1246
+ type: 'boolean',
1247
+ description: 'Release a start that the permission policy holds for confirmation. The approval is '
1248
+ + 'recorded in the audit trail. It cannot override a policy that denies the start.',
1249
+ },
914
1250
  wait_seconds: { type: 'number', description: 'Block up to this many seconds for a terminal status before returning (0 returns immediately).' },
915
1251
  },
916
1252
  required: ['goal'],
@@ -934,6 +1270,7 @@ export function apply(ctx, config) {
934
1270
  allowDuplicate: args.allow_duplicate === true,
935
1271
  mode: args.mode,
936
1272
  queue: args.queue === true,
1273
+ approvePolicy: args.approve_policy === true,
937
1274
  overrides: {
938
1275
  maxSubtasks: args.max_subtasks,
939
1276
  maxParallel: args.max_parallel,
@@ -1062,6 +1399,11 @@ export function apply(ctx, config) {
1062
1399
  type: 'boolean',
1063
1400
  description: 'Accepted for backward compatibility and ignored: a resume is never refused by maxActiveRuns.',
1064
1401
  },
1402
+ approve_policy: {
1403
+ type: 'boolean',
1404
+ description: 'Release a resume that the permission policy holds for confirmation. The approval is '
1405
+ + 'recorded in the audit trail. It cannot override a policy that denies the resume.',
1406
+ },
1065
1407
  },
1066
1408
  required: ['run_id'],
1067
1409
  async execute(args = {}, exec) {
@@ -1079,7 +1421,7 @@ export function apply(ctx, config) {
1079
1421
  String(args.run_id ?? '').trim(),
1080
1422
  check.agent,
1081
1423
  exec.clientTimeZone,
1082
- { force: args.force === true },
1424
+ { force: args.force === true, approvePolicy: args.approve_policy === true },
1083
1425
  )
1084
1426
  const waitSeconds = Number(args.wait_seconds) || 0
1085
1427
  const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
@@ -1128,6 +1470,49 @@ export function apply(ctx, config) {
1128
1470
  },
1129
1471
  }))
1130
1472
 
1473
+ ctx.tools.register(defineTool({
1474
+ name: 'superagent_inject',
1475
+ description:
1476
+ 'Deliver an instruction into the workers that are running right now, instead of waiting for the next prompt. '
1477
+ + 'The host reads steering at a child\'s next step boundary, so the message becomes part of that child\'s next '
1478
+ + 'model request: it never interrupts a model call already in flight, and it arrives only after the current step '
1479
+ + '(the model response plus its tool batch) finishes. A live child that had already decided to stop runs one more '
1480
+ + 'turn to read it. The reply reports the measured delay from acceptance to the child\'s next request; a message '
1481
+ + 'the child never claimed is reported as missed, never as delivered. Use superagent_followup when no worker is '
1482
+ + 'running or the instruction can wait for the next prompt.',
1483
+ properties: {
1484
+ run_id: { type: 'string', description: 'Run id returned by superagent_start.' },
1485
+ message: { type: 'string', description: 'The instruction or constraint the running workers should read next.' },
1486
+ subtask_index: {
1487
+ type: 'number',
1488
+ description: 'Narrow delivery to one running worker, using its index from superagent_status. Omit to reach every running worker.',
1489
+ },
1490
+ wait_seconds: {
1491
+ type: 'number',
1492
+ description: 'Block up to this many seconds for the children to claim the message, so the reply can report the measured delay (default 0).',
1493
+ },
1494
+ },
1495
+ required: ['run_id', 'message'],
1496
+ async execute(args = {}, exec) {
1497
+ const check = requireAgent(exec)
1498
+ if (check.error) return check.error
1499
+ try {
1500
+ await ready
1501
+ if (stateError) return describeError(stateError)
1502
+ const result = await orchestrator.inject(
1503
+ String(args.run_id ?? '').trim(),
1504
+ args.message,
1505
+ check.agent,
1506
+ { subtaskIndex: args.subtask_index },
1507
+ )
1508
+ const entry = await orchestrator.waitForInjection(result.run, result.injection, args.wait_seconds)
1509
+ return formatInjectionReply(result.run, entry, result.degraded, { pollMs: cfg.injectPollMs })
1510
+ } catch (error) {
1511
+ return describeError(error)
1512
+ }
1513
+ },
1514
+ }))
1515
+
1131
1516
  ctx.tools.register(defineTool({
1132
1517
  name: 'superagent_answer',
1133
1518
  description:
@@ -1401,6 +1786,64 @@ export function apply(ctx, config) {
1401
1786
  // The embedding surface is opt-in: mounting the plugin must not open a port
1402
1787
  // unasked. When it is on, every request goes through the same orchestrator as
1403
1788
  // the tools, so quota, budgets, ownership, and cancel behave identically.
1789
+ if (auditor) {
1790
+ ctx.tools.register(defineTool({
1791
+ name: 'superagent_audit',
1792
+ description:
1793
+ 'Query the append-only audit trail (tool calls, path writes, commands, blocks, approvals, attention '
1794
+ + 'decisions, run lifecycle) for one run or a time window, or export the matching events as a single '
1795
+ + 'JSONL or CSV file.',
1796
+ properties: {
1797
+ run_id: { type: 'string', description: 'Only events for this run id.' },
1798
+ subtask_id: { type: 'string', description: 'Only events for one subtask, e.g. "subtask-2" or "aggregator".' },
1799
+ kind: { type: 'string', description: 'Event kind, e.g. tool.call, path.write, command.exec, blocked, approved, attention.' },
1800
+ decision: { type: 'string', description: 'Only events with this decision: allow, confirm, or deny.' },
1801
+ result: { type: 'string', description: 'Only events with this result, e.g. ok, blocked, pending, approved, failed.' },
1802
+ target: { type: 'string', description: 'Substring of the path, command, or question the event is about.' },
1803
+ since: { type: 'string', description: 'ISO timestamp; events before it are skipped.' },
1804
+ until: { type: 'string', description: 'ISO timestamp; events after it are skipped.' },
1805
+ limit: { type: 'number', description: 'Maximum events to read or rows to print (default 8 for the summary, all for an export).' },
1806
+ order: { type: 'string', description: 'asc (oldest first, default) or desc.' },
1807
+ format: { type: 'string', description: 'summary (default), jsonl, or csv. jsonl and csv write a file and return its path.' },
1808
+ out_path: { type: 'string', description: 'File to write for jsonl/csv. Defaults to <stateDir>/audit/audit-export-<time>.<ext>.' },
1809
+ },
1810
+ async execute(args = {}) {
1811
+ try {
1812
+ await ready
1813
+ if (stateError) return describeError(stateError)
1814
+ const filter = {
1815
+ runId: args.run_id,
1816
+ subtaskId: args.subtask_id,
1817
+ kind: args.kind,
1818
+ decision: args.decision,
1819
+ result: args.result,
1820
+ target: args.target,
1821
+ since: args.since,
1822
+ until: args.until,
1823
+ limit: args.limit,
1824
+ order: String(args.order ?? '').toLowerCase() === 'desc' ? 'desc' : 'asc',
1825
+ }
1826
+ const format = String(args.format ?? 'summary').toLowerCase()
1827
+ if (format === 'jsonl' || format === 'csv') {
1828
+ const written = await auditor.export({ ...filter, format, outFile: args.out_path })
1829
+ return `exported ${written.count} event(s) to ${written.path} (${written.format}, ${formatBytes(written.bytes)})`
1830
+ + (written.invalid ? `; ${written.invalid} unreadable line(s) were skipped` : '')
1831
+ }
1832
+ if (format !== 'summary') return `unknown format ${JSON.stringify(args.format)}; use summary, jsonl, or csv`
1833
+ const result = await auditor.query(filter)
1834
+ const policyError = await auditor.policyError().catch(() => null)
1835
+ const head = policyError
1836
+ ? `policy: ${auditor.policyFile} is invalid, so actions are denied — `
1837
+ + `${String(policyError.message ?? policyError).split('\n')[0]}\n`
1838
+ : ''
1839
+ return `${head}${formatAudit(result, { limit: Math.min(50, Math.max(1, Number(args.limit) || 8)) })}`
1840
+ } catch (error) {
1841
+ return describeError(error)
1842
+ }
1843
+ },
1844
+ }))
1845
+ }
1846
+
1404
1847
  if (cfg.controlPort !== null) {
1405
1848
  const clampControlWait = value => {
1406
1849
  const seconds = Number(value)
@@ -1461,6 +1904,7 @@ export function apply(ctx, config) {
1461
1904
  allowDuplicate: body.allow_duplicate === true,
1462
1905
  mode: body.mode,
1463
1906
  queue: body.queue === true,
1907
+ approvePolicy: body.approve_policy === true,
1464
1908
  overrides: {
1465
1909
  maxSubtasks: body.max_subtasks,
1466
1910
  maxParallel: body.max_parallel,
@@ -1508,7 +1952,7 @@ export function apply(ctx, config) {
1508
1952
  String(runId ?? '').trim(),
1509
1953
  agent,
1510
1954
  body.time_zone,
1511
- { force: body.force === true || body.override_quota === true },
1955
+ { force: body.force === true || body.override_quota === true, approvePolicy: body.approve_policy === true },
1512
1956
  )
1513
1957
  const waitSeconds = clampControlWait(body.wait_seconds)
1514
1958
  const current = waitSeconds > 0 ? await orchestrator.status(run.id, waitSeconds) : run
@@ -1543,5 +1987,45 @@ export function apply(ctx, config) {
1543
1987
  })
1544
1988
  }
1545
1989
 
1546
- log(`registered 9 tools; state ${store.root}${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`)
1990
+ // The workspace panel is opt-in for the same reason: mounting the plugin
1991
+ // must not open a socket. It reads and writes files itself, so the only
1992
+ // boundary that matters is the configured root, enforced in workbench.js.
1993
+ if (cfg.workbenchPort !== null) {
1994
+ const workbench = createWorkbench({
1995
+ port: cfg.workbenchPort,
1996
+ root: workbenchRoot,
1997
+ stateRoot: store.root,
1998
+ store,
1999
+ version: pkg.version,
2000
+ log,
2001
+ })
2002
+ let panelDisposed = false
2003
+ const stopWorkbench = () => {
2004
+ panelDisposed = true
2005
+ return workbench.stop().catch(error => log(`cannot stop the workbench: ${error?.message ?? error}`))
2006
+ }
2007
+ if (typeof ctx.effect === 'function') {
2008
+ ctx.effect(() => stopWorkbench, 'dsh-superagent workbench')
2009
+ } else if (typeof ctx.on === 'function') {
2010
+ ctx.on('dispose', stopWorkbench)
2011
+ }
2012
+ ready
2013
+ .then(() => {
2014
+ if (panelDisposed || stateError) return null
2015
+ return workbench.start()
2016
+ })
2017
+ .catch(error => {
2018
+ log(
2019
+ `workbench is not listening: ${error?.message ?? error}; `
2020
+ + `check that workbenchRoot (${workbenchRoot}) exists, that workbenchPort is free, and that the state `
2021
+ + 'directory is writable, or remove workbenchPort to keep the panel off',
2022
+ )
2023
+ })
2024
+ }
2025
+
2026
+ log(
2027
+ `registered ${auditor ? 11 : 10} tools; state ${store.root}`
2028
+ + `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
2029
+ + `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`,
2030
+ )
1547
2031
  }