@xiangyixie/dsh-superagent 0.12.1 → 0.14.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
@@ -9,7 +9,8 @@
9
9
  *
10
10
  * Registered tools: superagent_start, superagent_status, superagent_list,
11
11
  * superagent_cancel, superagent_resume, superagent_followup, superagent_inject,
12
- * superagent_answer, superagent_memory, superagent_template, superagent_audit.
12
+ * superagent_answer, superagent_memory, superagent_template, superagent_audit,
13
+ * superagent_schedule.
13
14
  *
14
15
  * @module dsh-superagent
15
16
  */
@@ -23,21 +24,26 @@ import { createAuditor } from './audit.js'
23
24
  import { createOrchestrator, followupEffect } from './orchestrator.js'
24
25
  import { createChildSteerer, createChildWatcher, INJECT_POLL_MS, pendingIds } from './inject.js'
25
26
  import { createControlPlane } from './control.js'
26
- import { formatMoney } from './cost.js'
27
+ import { computeCost, formatCurrencyTally, formatMoney } from './cost.js'
27
28
  import { createGuard } from './guard.js'
29
+ import { describeGoal } from './goal.js'
28
30
  import { classifyError, describeError, summarizeError } from './errors.js'
29
31
  import { createLedger } from './ledger.js'
30
32
  import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.js'
33
+ import { createUserMemory, USER_MEMORY_CATEGORIES } from './user-memory.js'
31
34
  import { createNotifyPolicy, createOutbox } from './notify.js'
35
+ import { createRuntimeControl } from './runtime-control.js'
36
+ import { createScheduler, formatSchedule, formatScheduleList } from './schedule.js'
32
37
  import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
33
38
  import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
34
39
  import { createUsageReader } from './usage.js'
35
40
  import { describeWorkspace } from './workspace.js'
36
41
  import { createRunChangeTracker, createWorkbench } from './workbench.js'
42
+ import { createConsole } from './console.js'
37
43
 
38
44
  export const name = 'dsh-superagent'
39
45
  // The host menu and sessions are required. `subagents` is read through
40
- // `ctx.get('subagents')`, so a profile without it still mounts the eleven tools;
46
+ // `ctx.get('subagents')`, so a profile without it still mounts the twelve tools;
41
47
  // they then report what is missing instead of the plugin silently vanishing.
42
48
  export const inject = ['tools', 'agents']
43
49
 
@@ -55,13 +61,47 @@ const DEFAULTS = {
55
61
  * composition, which is the only way this host version can restrict it.
56
62
  */
57
63
  childPreset: null,
64
+ /**
65
+ * Agent preset used for the planner child only. A planner needs no tools, but
66
+ * children otherwise inherit the session's full tool set; under a weak model
67
+ * that turns into a tool loop that never returns a plan. Leave null to keep
68
+ * inheriting. Hosts must compose an `agentPresets` registry and declare the
69
+ * preset for this to apply.
70
+ */
71
+ plannerPreset: null,
72
+ /**
73
+ * Optional model route for the planner child only. Planning is one JSON turn,
74
+ * so a stronger model there is cheap relative to the workers it coordinates;
75
+ * leaving these null keeps the session's route.
76
+ */
77
+ plannerModel: null,
78
+ plannerProvider: null,
58
79
  /**
59
80
  * Delegation depth granted to child agents. 1 means a worker may not create
60
81
  * children of its own; `provider-managed` leaves the cap to the backend.
61
82
  */
62
83
  maxSubagentDepth: 1,
84
+ /**
85
+ * Sandbox mode granted to a worker whose plan entry declares a shell
86
+ * capability. `inherit` keeps the host's delegation inheritance for every
87
+ * child, which is the pre-existing behaviour.
88
+ */
89
+ commandWorkerPermission: 'inherit',
63
90
  /** Upper bound on planned subtasks per run. */
64
91
  maxSubtasks: 8,
92
+ /**
93
+ * How long one planner attempt may run before its child is stopped and the
94
+ * next attempt (or the invalid-plan path) takes over. A planner that starts
95
+ * calling tools can otherwise spend the whole run budget before returning.
96
+ */
97
+ plannerTimeoutSeconds: 120,
98
+ /**
99
+ * Model calls the planning phase may spend in total, across attempts. 0
100
+ * disables the cap. A planner that calls tools instead of replying can loop
101
+ * for dozens of calls; once the budget is gone the run is reported as
102
+ * unplannable instead of draining the run budget.
103
+ */
104
+ plannerMaxModelCalls: 20,
65
105
  /** Upper bound on subtasks executing at once. */
66
106
  maxParallel: 3,
67
107
  /** Runs allowed to be active at the same time; a start over this waits instead of failing. */
@@ -111,6 +151,19 @@ const DEFAULTS = {
111
151
  notifyRetries: 2,
112
152
  /** First delay between delivery attempts; it doubles per attempt. */
113
153
  notifyRetryDelayMs: 2000,
154
+ /**
155
+ * How often a scheduled plan is checked, in seconds. Plans are the only
156
+ * thing that arms the timer, so an install with no plan pays nothing.
157
+ */
158
+ schedulerTickSeconds: 30,
159
+ /**
160
+ * Keep one concurrency slot free for manual starts when a scheduled plan is
161
+ * due. The reservation happens inside the start gate, so a person's start
162
+ * cannot lose a race with the timer.
163
+ */
164
+ schedulerHumanPriority: true,
165
+ /** Consecutive failed runs before a plan pauses and says so once. */
166
+ schedulerMaxConsecutiveFailures: 3,
114
167
  /**
115
168
  * Poll period, in milliseconds, used to observe when a running child claims
116
169
  * an injected message. It is the resolution of every reported latency, so it
@@ -137,6 +190,12 @@ const DEFAULTS = {
137
190
  memoryDigestEntries: 12,
138
191
  /** Character budget for the note part of that prompt context. */
139
192
  memoryDigestChars: 1600,
193
+ /**
194
+ * User-level profile: facts, preferences and decisions kept across unrelated
195
+ * tasks under `<stateDir>/user-memory`. Off by default because it is a
196
+ * durable record about a person, not just about a task.
197
+ */
198
+ memoryUserProfile: false,
140
199
  /** Delete terminal runs older than this many days on mount; 0 keeps everything. */
141
200
  keepRuns: 0,
142
201
  /**
@@ -178,9 +237,10 @@ const DEFAULTS = {
178
237
  controlPort: null,
179
238
  /**
180
239
  * Run every worker in its own git worktree of `workspaceRoot`, so parallel
181
- * workers cannot overwrite each other's files. Off by default: it needs a
182
- * git repository and it moves files, which is not something a plugin should
183
- * start doing unasked.
240
+ * workers cannot overwrite each other's files. Checkouts live under
241
+ * `<repository>/.superagent/worktrees/`, inside the checkout the host sandbox
242
+ * restricts writes to. Off by default: it needs a git repository and it moves
243
+ * files, which is not something a plugin should start doing unasked.
184
244
  */
185
245
  workspaceIsolation: false,
186
246
  /** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
@@ -196,6 +256,52 @@ const DEFAULTS = {
196
256
  * Defaults to the host process's working directory.
197
257
  */
198
258
  workbenchRoot: null,
259
+ /**
260
+ * Loopback HTTP port for the conversation console. `null` (default) keeps it
261
+ * off; `0` asks the OS for a free port. The bound address and its one-time
262
+ * token are written to `<stateDir>/console.json`.
263
+ */
264
+ consolePort: null,
265
+ /**
266
+ * Directory the console conversation joins. Defaults to `workbenchRoot`, then
267
+ * the host process's working directory.
268
+ */
269
+ consoleRoot: null,
270
+ /**
271
+ * Agent preset the console conversation mounts. Null keeps the profile
272
+ * default, which is what the Web app's own sessions use. Tools come from the
273
+ * preset, not from this plugin: pass a preset id (for example one that
274
+ * includes runtime-control) to change the console's tool set.
275
+ */
276
+ consolePreset: null,
277
+ /**
278
+ * Browser and desktop control. Off by default: with `enabled: false` not one
279
+ * of these tools is registered, so an existing profile behaves exactly as
280
+ * before. See "Runtime control" in the README for the gates that apply once
281
+ * it is on.
282
+ */
283
+ runtime: {
284
+ enabled: false,
285
+ /**
286
+ * Chromium driven over CDP. A fresh temporary profile is the default, so the
287
+ * user's daily logins stay out of reach; `attachPort` borrows a browser the
288
+ * user started, and `userDataDir` keeps one dedicated profile across runs.
289
+ */
290
+ browser: {
291
+ enabled: true,
292
+ headless: true,
293
+ executablePath: null,
294
+ attachPort: null,
295
+ userDataDir: null,
296
+ allowedHosts: [],
297
+ },
298
+ /** Windows input and capture. Background delivery is the default. */
299
+ desktop: { enabled: false, allowActivation: false },
300
+ /** Emergency stop file; a present file refuses every runtime action. */
301
+ stopFile: null,
302
+ /** Where screenshots are written; defaults to `<stateDir>/runtime/shots`. */
303
+ shotDir: null,
304
+ },
199
305
  }
200
306
 
201
307
  const REPORT_PREVIEW_CHARS = 8000
@@ -252,6 +358,17 @@ function resolveConfig(config) {
252
358
  merged.attempts = bounded(merged.attempts, DEFAULTS.attempts, 1, 5)
253
359
  merged.deadlineMinutes = bounded(merged.deadlineMinutes, DEFAULTS.deadlineMinutes, 1, 720)
254
360
  merged.maxModelCallsPerRun = bounded(merged.maxModelCallsPerRun, DEFAULTS.maxModelCallsPerRun, 0, 10000)
361
+ merged.plannerTimeoutSeconds = bounded(merged.plannerTimeoutSeconds, DEFAULTS.plannerTimeoutSeconds, 0, 3600)
362
+ merged.plannerMaxModelCalls = bounded(merged.plannerMaxModelCalls, DEFAULTS.plannerMaxModelCalls, 0, 1000)
363
+ merged.plannerPreset = typeof merged.plannerPreset === 'string' && merged.plannerPreset.trim()
364
+ ? merged.plannerPreset.trim()
365
+ : null
366
+ merged.plannerModel = typeof merged.plannerModel === 'string' && merged.plannerModel.trim()
367
+ ? merged.plannerModel.trim()
368
+ : null
369
+ merged.plannerProvider = typeof merged.plannerProvider === 'string' && merged.plannerProvider.trim()
370
+ ? merged.plannerProvider.trim()
371
+ : null
255
372
  merged.maxTokensPerRun = bounded(merged.maxTokensPerRun, DEFAULTS.maxTokensPerRun, 0, 1e12)
256
373
  merged.resultCapBytes = bounded(merged.resultCapBytes, DEFAULTS.resultCapBytes, 1024, 1024 * 1024)
257
374
  merged.keepRuns = bounded(merged.keepRuns, DEFAULTS.keepRuns, 0, 3650)
@@ -260,13 +377,26 @@ function resolveConfig(config) {
260
377
  merged.workbenchRoot = typeof merged.workbenchRoot === 'string' && merged.workbenchRoot.trim()
261
378
  ? merged.workbenchRoot.trim()
262
379
  : null
380
+ merged.consolePort = controlPortOf(merged.consolePort)
381
+ merged.consoleRoot = typeof merged.consoleRoot === 'string' && merged.consoleRoot.trim()
382
+ ? merged.consoleRoot.trim()
383
+ : null
384
+ merged.consolePreset = typeof merged.consolePreset === 'string' && merged.consolePreset.trim()
385
+ ? merged.consolePreset.trim()
386
+ : null
263
387
  merged.maxSubagentDepth = merged.maxSubagentDepth === 'provider-managed'
264
388
  ? 'provider-managed'
265
389
  : bounded(merged.maxSubagentDepth, DEFAULTS.maxSubagentDepth, 0, 4)
390
+ // Only the two documented values are meaningful; anything else keeps
391
+ // inheritance, because a typo must not silently hand out full access.
392
+ merged.commandWorkerPermission = merged.commandWorkerPermission === 'danger-full-access'
393
+ ? 'danger-full-access'
394
+ : 'inherit'
266
395
  // Per-model prices merge, so a user can add one route without restating the
267
396
  // built-in table.
268
397
  merged.pricing = { ...DEFAULTS.pricing, ...(config?.pricing ?? {}) }
269
398
  merged.memory = flag(merged.memory, DEFAULTS.memory)
399
+ merged.memoryUserProfile = flag(merged.memoryUserProfile, DEFAULTS.memoryUserProfile)
270
400
  merged.audit = flag(merged.audit, DEFAULTS.audit)
271
401
  merged.policyFile = typeof merged.policyFile === 'string' && merged.policyFile.trim()
272
402
  ? merged.policyFile.trim()
@@ -282,6 +412,16 @@ function resolveConfig(config) {
282
412
  merged.autoResumeRounds = bounded(merged.autoResumeRounds, DEFAULTS.autoResumeRounds, 0, 3)
283
413
  merged.notifyRetries = bounded(merged.notifyRetries, DEFAULTS.notifyRetries, 0, 5)
284
414
  merged.notifyRetryDelayMs = bounded(merged.notifyRetryDelayMs, DEFAULTS.notifyRetryDelayMs, 0, 60000)
415
+ // A one-second floor keeps the timer responsive in a demo without allowing a
416
+ // busy loop; an hour ceiling means a typo cannot stop plans from running.
417
+ merged.schedulerTickSeconds = bounded(merged.schedulerTickSeconds, DEFAULTS.schedulerTickSeconds, 1, 3600)
418
+ merged.schedulerHumanPriority = flag(merged.schedulerHumanPriority, DEFAULTS.schedulerHumanPriority)
419
+ merged.schedulerMaxConsecutiveFailures = bounded(
420
+ merged.schedulerMaxConsecutiveFailures,
421
+ DEFAULTS.schedulerMaxConsecutiveFailures,
422
+ 1,
423
+ 20,
424
+ )
285
425
  merged.injectPollMs = bounded(merged.injectPollMs, DEFAULTS.injectPollMs, 10, 1000)
286
426
  merged.maxNotificationsPerHour = bounded(merged.maxNotificationsPerHour, DEFAULTS.maxNotificationsPerHour, 0, 1000)
287
427
  merged.childModelFallback = typeof merged.childModelFallback === 'string' && merged.childModelFallback.trim()
@@ -299,9 +439,56 @@ function resolveConfig(config) {
299
439
  ...DEFAULTS.guard,
300
440
  ...(config?.guard && typeof config.guard === 'object' ? config.guard : {}),
301
441
  }
442
+ // Runtime control merges one level deeper: a profile that only sets
443
+ // `browser.allowedHosts` keeps the desktop defaults and vice versa.
444
+ merged.runtime = {
445
+ ...DEFAULTS.runtime,
446
+ ...(config?.runtime && typeof config.runtime === 'object' ? config.runtime : {}),
447
+ browser: {
448
+ ...DEFAULTS.runtime.browser,
449
+ ...(config?.runtime?.browser && typeof config.runtime.browser === 'object' ? config.runtime.browser : {}),
450
+ },
451
+ desktop: {
452
+ ...DEFAULTS.runtime.desktop,
453
+ ...(config?.runtime?.desktop && typeof config.runtime.desktop === 'object' ? config.runtime.desktop : {}),
454
+ },
455
+ }
456
+ merged.runtime.enabled = flag(merged.runtime.enabled, DEFAULTS.runtime.enabled)
457
+ merged.runtime.browser.enabled = flag(merged.runtime.browser.enabled, DEFAULTS.runtime.browser.enabled)
458
+ merged.runtime.browser.headless = flag(merged.runtime.browser.headless, DEFAULTS.runtime.browser.headless)
459
+ merged.runtime.desktop.enabled = flag(merged.runtime.desktop.enabled, DEFAULTS.runtime.desktop.enabled)
460
+ merged.runtime.desktop.allowActivation = flag(merged.runtime.desktop.allowActivation, DEFAULTS.runtime.desktop.allowActivation)
461
+ merged.runtime.browser.allowedHosts = (Array.isArray(merged.runtime.browser.allowedHosts) ? merged.runtime.browser.allowedHosts : [])
462
+ .map(entry => String(entry ?? '').trim())
463
+ .filter(Boolean)
464
+ merged.runtime.browser.attachPort = controlPortOf(merged.runtime.browser.attachPort)
465
+ merged.runtime.browser.userDataDir = typeof merged.runtime.browser.userDataDir === 'string'
466
+ && merged.runtime.browser.userDataDir.trim()
467
+ ? merged.runtime.browser.userDataDir.trim()
468
+ : null
469
+ for (const key of ['stopFile', 'shotDir']) {
470
+ merged.runtime[key] = typeof merged.runtime[key] === 'string' && merged.runtime[key].trim()
471
+ ? merged.runtime[key].trim()
472
+ : null
473
+ }
302
474
  return merged
303
475
  }
304
476
 
477
+ /**
478
+ * One user-level record as a tool row. A decision always shows its rationale:
479
+ * a bare "chose X" is exactly what the profile exists to avoid.
480
+ */
481
+ function userRecordLine(entry) {
482
+ const when = String(entry.source?.ts ?? entry.ts ?? '').slice(0, 10)
483
+ const run = entry.source?.runId ?? entry.runId ?? 'manual'
484
+ const score = Number.isFinite(entry.score) ? ` score ${entry.score.toFixed(2)}` : ''
485
+ const body = entry.category === 'decision'
486
+ ? `chose ${entry.choice}; rejected ${entry.rejected || 'nothing recorded'}; `
487
+ + `why ${entry.reason}; rollback ${entry.rollback || 'not recorded'}`
488
+ : entry.text
489
+ return `- ${entry.key} [${entry.category}]${score} (run ${run}, ${when}): ${body}`
490
+ }
491
+
305
492
  function preview(text, limit = REPORT_PREVIEW_CHARS) {
306
493
  if (typeof text !== 'string') return ''
307
494
  if (text.length <= limit) return text
@@ -315,8 +502,7 @@ function durationText(ms) {
315
502
  return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
316
503
  }
317
504
 
318
- function elapsed(run) {
319
- const start = Date.parse(run.startedAt)
505
+ function elapsed(run) { const start = Date.parse(run.startedAt)
320
506
  const end = run.finishedAt ? Date.parse(run.finishedAt) : Date.now()
321
507
  if (!Number.isFinite(start) || !Number.isFinite(end)) return 'unknown'
322
508
  const wall = Math.max(0, end - start)
@@ -329,6 +515,46 @@ function elapsed(run) {
329
515
  return durationText(wall)
330
516
  }
331
517
 
518
+ /** Tool arguments are snake_case; a goal spec is camelCase. */
519
+ function acceptanceFromToolArgs(entry) {
520
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return entry
521
+ if (!entry.check || typeof entry.check !== 'object') return entry
522
+ const { must_exist: mustExist, timeout_seconds: timeoutSeconds, ...check } = entry.check
523
+ return {
524
+ ...entry,
525
+ check: {
526
+ ...check,
527
+ ...(mustExist === undefined ? {} : { mustExist }),
528
+ ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
529
+ },
530
+ }
531
+ }
532
+
533
+ /**
534
+ * Build the goal spec from the flat tool arguments.
535
+ *
536
+ * `budget` is read only for `superagent_start`; on a schedule, `budget` is the
537
+ * plan's own spending ceiling and is not a goal-mode field.
538
+ */
539
+ function goalModeFromToolArgs(args, { budget = true } = {}) {
540
+ if (args.goal_mode !== true) {
541
+ if (args.acceptance !== undefined) {
542
+ throw new Error('acceptance is only read in goal mode; pass goal_mode: true to enable it (goal mode is off by default)')
543
+ }
544
+ return null
545
+ }
546
+ const budgetArg = budget ? args.budget : null
547
+ return {
548
+ acceptance: Array.isArray(args.acceptance) ? args.acceptance.map(acceptanceFromToolArgs) : args.acceptance,
549
+ maxRounds: args.max_rounds,
550
+ maxWallClockMinutes: args.max_wall_clock_minutes,
551
+ noProgressRounds: args.no_progress_rounds,
552
+ budget: budgetArg && typeof budgetArg === 'object'
553
+ ? { maxModelCalls: budgetArg.max_model_calls, maxTokens: budgetArg.max_tokens }
554
+ : null,
555
+ }
556
+ }
557
+
332
558
  function usageLine(usage, status) {
333
559
  if (!usage || !usage.modelCalls) {
334
560
  if (ACTIVE_STATUSES.has(status)) {
@@ -410,9 +636,11 @@ function formatRun(run, { includeReport = true } = {}) {
410
636
  }
411
637
  const cost = costLine(run)
412
638
  if (cost) lines.push(cost)
639
+ lines.push(...describeGoal(run.goalMode))
413
640
  if (run.memory?.digest) {
641
+ const profile = run.memory.userNotes > 0 ? `, ${run.memory.userNotes} user-level record(s)` : ''
414
642
  lines.push(
415
- `memory: ${run.memory.notes} note(s) and ${run.memory.runs} earlier run(s) carried into this run `
643
+ `memory: ${run.memory.notes} note(s)${profile} and ${run.memory.runs} earlier run(s) carried into this run `
416
644
  + `(${run.memory.digestChars} chars)`,
417
645
  )
418
646
  }
@@ -526,6 +754,14 @@ function formatRun(run, { includeReport = true } = {}) {
526
754
  } else if (run.memoryWrite?.reason && /^(the memory block|write failed)/.test(run.memoryWrite.reason)) {
527
755
  lines.push(`memory note not written: ${run.memoryWrite.reason}`)
528
756
  }
757
+ if (run.preflight?.status === 'checked' && run.preflight.blocked > 0) {
758
+ lines.push(
759
+ `capability preflight: ${run.preflight.blocked} subtask(s) blocked before start `
760
+ + `(${run.preflight.toolCount} tool(s) available)`,
761
+ )
762
+ } else if (run.preflight?.status === 'unavailable') {
763
+ lines.push(`capability preflight: skipped — ${run.preflight.reason}`)
764
+ }
529
765
  if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
530
766
  if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
531
767
  if (run.status === 'interrupted' && run.error) {
@@ -553,7 +789,18 @@ function formatRun(run, { includeReport = true } = {}) {
553
789
  const skipped = subtask.status === 'skipped' && subtask.skippedReason
554
790
  ? ` — skipped: ${subtask.skippedReason}`
555
791
  : ''
556
- const detail = skipped || (subtask.error ? ` — ${summarizeError(subtask.error)}` : '')
792
+ // Blocked is not skipped: nothing upstream failed, the session lacks a tool
793
+ // this subtask declared it needs, so no worker was ever started.
794
+ const blocked = subtask.status === 'blocked' && subtask.blockedReason
795
+ ? ` — blocked: ${subtask.blockedReason}`
796
+ : ''
797
+ // Unverified is not completed: the worker declared an artifact this
798
+ // session could not check, so the reason must be visible.
799
+ const unverified = subtask.status === 'unverified' && subtask.unverifiedReason
800
+ ? ` — unverified: ${subtask.unverifiedReason}`
801
+ : ''
802
+ const detail = blocked || skipped || unverified
803
+ || (subtask.error ? ` — ${summarizeError(subtask.error)}` : '')
557
804
  // A cancelled run never judged its unfinished subtasks, so calling them
558
805
  // "pending" or "failed (attempts 0)" would misreport what happened.
559
806
  const status = run.status === 'cancelled' && subtask.status !== 'completed'
@@ -706,12 +953,12 @@ function formatList(runs, limit, stats = null) {
706
953
  lines.push(`ledger: ${ledger.runs} run(s) in the last ${stats.ledgerDays} days are unpriced — `
707
954
  + 'no configured price matches their models, so no total is claimed')
708
955
  } else {
709
- const total = ledger.mixedCurrency
710
- ? `${formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency ?? 'USD' })}`
711
- : formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency })
956
+ const total = ledger.byCurrency && Object.keys(ledger.byCurrency).length > 0
957
+ ? formatCurrencyTally(ledger.byCurrency)
958
+ : formatMoney({ totalMicros: ledger.totalMicros, currency: ledger.currency ?? 'USD' })
712
959
  lines.push(`ledger: ${total} across ${ledger.priced} priced run(s) in the last ${stats.ledgerDays} days`
713
960
  + (ledger.unpricedRuns > 0 ? ` (${ledger.unpricedRuns} run(s) partially unpriced)` : '')
714
- + (ledger.mixedCurrency ? ' (mixed currencies; figure uses the first)' : ''))
961
+ + (ledger.mixedCurrency ? ' (mixed currencies kept separate)' : ''))
715
962
  }
716
963
  }
717
964
  }
@@ -781,6 +1028,7 @@ export function apply(ctx, config) {
781
1028
  const log = message => console.error(`[dsh-superagent] ${message}`)
782
1029
  const configuredPort = config?.controlPort
783
1030
  const configuredWorkbenchPort = config?.workbenchPort
1031
+ const configuredConsolePort = config?.consolePort
784
1032
  const cfg = resolveConfig(config)
785
1033
  if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
786
1034
  log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
@@ -788,6 +1036,9 @@ export function apply(ctx, config) {
788
1036
  if (configuredWorkbenchPort !== undefined && configuredWorkbenchPort !== null && cfg.workbenchPort === null) {
789
1037
  log(`workbenchPort ${JSON.stringify(configuredWorkbenchPort)} is not a whole number in 0–65535; the workspace panel stays off`)
790
1038
  }
1039
+ if (configuredConsolePort !== undefined && configuredConsolePort !== null && cfg.consolePort === null) {
1040
+ log(`consolePort ${JSON.stringify(configuredConsolePort)} is not a whole number in 0–65535; the conversation console stays off`)
1041
+ }
791
1042
  if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
792
1043
  console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
793
1044
  return
@@ -827,6 +1078,11 @@ export function apply(ctx, config) {
827
1078
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
828
1079
  const memoryBlocked = isInside(store.root, packageRoot)
829
1080
  const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
1081
+ // The user-level profile is a deliberate opt-in: it outlives tasks and records
1082
+ // things about a person, so it is never created from a default config.
1083
+ const userMemory = cfg.memory && cfg.memoryUserProfile && !memoryBlocked
1084
+ ? createUserMemory(store.root, { warn: log })
1085
+ : null
830
1086
  if (cfg.memory && memoryBlocked) {
831
1087
  log(`cross-run memory stays off: stateDir ${store.root} is inside the installed package; point stateDir elsewhere`)
832
1088
  }
@@ -900,6 +1156,24 @@ export function apply(ctx, config) {
900
1156
  }
901
1157
  }
902
1158
 
1159
+ // Runtime control is opt-in. With `runtime.enabled` false nothing below is
1160
+ // registered, which is why a profile that never asked for browser or desktop
1161
+ // access sees exactly the same tool list as before this layer existed.
1162
+ const runtime = createRuntimeControl({
1163
+ config: cfg.runtime,
1164
+ stateRoot: store.root,
1165
+ auditor,
1166
+ warn: log,
1167
+ })
1168
+ if (runtime.tools.length > 0) {
1169
+ for (const spec of runtime.tools) ctx.tools.register(defineTool(spec))
1170
+ log(
1171
+ `runtime control: ${runtime.tools.length} tool(s) registered; stop switch ${runtime.stopFile}; `
1172
+ + `screenshots ${runtime.shotDir}`,
1173
+ )
1174
+ if (typeof ctx.effect === 'function') ctx.effect(() => () => runtime.dispose())
1175
+ }
1176
+
903
1177
  const notifyPolicy = createNotifyPolicy({
904
1178
  stateFile: path.join(store.root, 'notifications.json'),
905
1179
  maxPerHour: cfg.maxNotificationsPerHour,
@@ -916,7 +1190,7 @@ export function apply(ctx, config) {
916
1190
  /**
917
1191
  * The subagent service is optional, so it is read from the service store at
918
1192
  * call time rather than declared as an injection: a profile without it must
919
- * still mount the eleven tools (they then explain what is missing), and reading
1193
+ * still mount the twelve tools (they then explain what is missing), and reading
920
1194
  * it lazily also sees a service that registers after this plugin.
921
1195
  */
922
1196
  function getSubagents() {
@@ -942,6 +1216,42 @@ export function apply(ctx, config) {
942
1216
  return undefined
943
1217
  }
944
1218
 
1219
+ /**
1220
+ * The Host Session API, when the host provides one. The console uses it for
1221
+ * conversation; the scheduler uses it to bring back the session that owns a
1222
+ * plan after a restart, so a scheduled run does not depend on the original
1223
+ * process still being alive.
1224
+ */
1225
+ function getSessionController() {
1226
+ if (typeof ctx.get === 'function') {
1227
+ const service = ctx.get('sessionController')
1228
+ if (service) return service
1229
+ }
1230
+ // Direct property is topology-sensitive; this is a fallback for hosts
1231
+ // that expose the service without the registry.
1232
+ try {
1233
+ return ctx.sessionController
1234
+ } catch {
1235
+ return undefined
1236
+ }
1237
+ }
1238
+
1239
+ /**
1240
+ * What this host can do about a plan's owner when its session is not live.
1241
+ * `resume` reopens a persisted session, `create` can at least start a fresh
1242
+ * one, and `none` means a plan is only as durable as the session that made
1243
+ * it — a limit recorded on the plan instead of discovered as a pause.
1244
+ */
1245
+ function scheduleOwnerRecovery() {
1246
+ const agents = getAgents()
1247
+ if (agents && typeof agents.resume === 'function') return 'resume'
1248
+ if (agents && typeof agents.create === 'function') return 'create'
1249
+ const session = getSessionController()
1250
+ if (session && typeof session.resolveAgent === 'function') return 'resume'
1251
+ if (session && typeof session.create === 'function') return 'create'
1252
+ return 'none'
1253
+ }
1254
+
945
1255
  /** Remember a child id for the recursion guard without growing forever. */
946
1256
  function rememberChild(childId) {
947
1257
  if (!childId) return
@@ -1029,12 +1339,102 @@ export function apply(ctx, config) {
1029
1339
  }
1030
1340
  }
1031
1341
 
1342
+ /**
1343
+ * Capability tags that mean "this worker will run commands". The planner emits
1344
+ * lowercase tags (`capabilityList`), and `shell` is the canonical name; the
1345
+ * aliases are here because a plan may spell the tool family instead.
1346
+ */
1347
+ const COMMAND_CAPABILITIES = new Set([
1348
+ 'shell', 'bash', 'sh', 'zsh', 'fish', 'terminal', 'pwsh', 'powershell', 'cmd',
1349
+ 'run.command', 'run_command', 'exec.command', 'exec_command',
1350
+ ])
1351
+
1352
+ /** True when one plan entry says its worker needs a command tool. */
1353
+ function wantsCommandSandbox(requires) {
1354
+ return Array.isArray(requires) && requires.some(tag => COMMAND_CAPABILITIES.has(String(tag).toLowerCase()))
1355
+ }
1356
+
1357
+ /** Record one escalation step; callers never await it, so the window stays synchronous. */
1358
+ function recordSandboxEscalation(kind, { runId, subtaskId, reason, from, to }) {
1359
+ if (!auditor || typeof auditor.record !== 'function') return
1360
+ auditor.record({
1361
+ kind,
1362
+ runId,
1363
+ subtaskId,
1364
+ actor: 'superagent',
1365
+ action: 'sandbox',
1366
+ target: to,
1367
+ decision: 'allow',
1368
+ result: 'allowed',
1369
+ source: 'permission',
1370
+ meta: { reason, from: from ?? null, to },
1371
+ }).catch(error => log(`audit: cannot record ${kind}: ${error?.message ?? error}`))
1372
+ }
1373
+
1374
+ /**
1375
+ * Raise the parent session's sandbox override for exactly one synchronous
1376
+ * call, without awaiting inside that call.
1377
+ *
1378
+ * The host has no per-subagent permission field. Its one seam is delegation
1379
+ * inheritance: `startActivation` reads the parent session's last
1380
+ * `sandbox/mode` event synchronously, before its first await, and seeds that
1381
+ * mode into the child. So the override is appended, `startActivation` is
1382
+ * invoked in the same tick, and the previous mode is appended again in a
1383
+ * `finally` before control returns to the event loop. Nothing between those
1384
+ * three steps may await, or a concurrent call would observe full access.
1385
+ *
1386
+ * @param {object} parent - the live parent agent the child is delegated from.
1387
+ * @param {{ runId?: string, subtaskId?: string, reason: string }} meta - audit context.
1388
+ * @returns {{ restore: () => void } | null} the rollback, or null when this host cannot be used.
1389
+ */
1390
+ function beginCommandEscalation(parent, { runId, subtaskId, reason }) {
1391
+ const session = parent?.session
1392
+ const sandboxPolicy = typeof parent?.ctx?.get === 'function' ? parent.ctx.get('sandboxPolicy') : undefined
1393
+ if (!session || typeof session.append !== 'function'
1394
+ || !sandboxPolicy || typeof sandboxPolicy.overrideOf !== 'function') {
1395
+ log(`commandWorkerPermission: the parent session exposes no sandbox override, so this worker inherits (${reason})`)
1396
+ return null
1397
+ }
1398
+ const previous = sandboxPolicy.overrideOf(session) ?? sandboxPolicy.defaultMode
1399
+ // Without a readable previous mode the window could not be closed again.
1400
+ if (previous === undefined) {
1401
+ log(`commandWorkerPermission: the deployment default sandbox mode is unknown, so this worker inherits (${reason})`)
1402
+ return null
1403
+ }
1404
+ // Already unconfined: the child inherits it, so no event is needed.
1405
+ if (previous === 'danger-full-access') return null
1406
+ recordSandboxEscalation('worker.escalate', {
1407
+ runId,
1408
+ subtaskId,
1409
+ reason,
1410
+ from: previous,
1411
+ to: 'danger-full-access',
1412
+ })
1413
+ session.append('sandbox/mode', { mode: 'danger-full-access' })
1414
+ return {
1415
+ restore() {
1416
+ session.append('sandbox/mode', { mode: previous })
1417
+ recordSandboxEscalation('worker.restore', {
1418
+ runId,
1419
+ subtaskId,
1420
+ reason: `restore the parent sandbox mode after the child captured the delegation (${reason})`,
1421
+ from: 'danger-full-access',
1422
+ to: previous,
1423
+ })
1424
+ },
1425
+ }
1426
+ }
1427
+
1032
1428
  const orchestrator = createOrchestrator({
1033
1429
  store,
1034
1430
  config: cfg,
1035
1431
  log,
1432
+ // Declared deliverables are resolved against the same directory workers
1433
+ // see: an isolated checkout per subtask, or the host project otherwise.
1434
+ cwd: cfg.workspaceRoot ? path.resolve(cfg.workspaceRoot) : process.cwd(),
1036
1435
  readUsage,
1037
1436
  memory,
1437
+ userMemory,
1038
1438
  guard,
1039
1439
  audit: auditor,
1040
1440
  notify: notifyParent,
@@ -1050,7 +1450,24 @@ export function apply(ctx, config) {
1050
1450
  resolveChild: childId => getAgents()?.get?.(childId),
1051
1451
  intervalMs: cfg.injectPollMs,
1052
1452
  }),
1053
- async spawnChild({ label, prompt, parent, signal, model, runId }) {
1453
+ // Capability preflight reads the host's own tool list for the calling
1454
+ // session, so it blocks exactly what this session cannot do. The orchestrator
1455
+ // tools are excluded: a worker is forbidden to call them and they are not a
1456
+ // capability the plan can use.
1457
+ toolInventory(parent) {
1458
+ if (typeof ctx.tools?.definitions !== 'function') return null
1459
+ try {
1460
+ const definitions = ctx.tools.definitions(parent)
1461
+ if (!Array.isArray(definitions)) return null
1462
+ return definitions
1463
+ .map(definition => definition?.name)
1464
+ .filter(name => typeof name === 'string' && name.length > 0 && !name.startsWith('superagent_'))
1465
+ } catch (error) {
1466
+ log(`cannot read the host tool inventory: ${error?.message ?? error}`)
1467
+ return null
1468
+ }
1469
+ },
1470
+ async spawnChild({ label, prompt, parent, signal, model, runId, subtaskId, requires, preset, provider: providerOverride, cwd: childCwd }) {
1054
1471
  const subagents = getSubagents()
1055
1472
  if (!subagents || typeof subagents.startActivation !== 'function') {
1056
1473
  const error = new Error('subagent service is unavailable; dsh-superagent needs the host subagents service')
@@ -1066,23 +1483,37 @@ export function apply(ctx, config) {
1066
1483
  // Only the self-heal round passes a model override; everything else keeps
1067
1484
  // the configured route.
1068
1485
  const childModel = model ?? cfg.childModel
1069
- if (cfg.childProvider) agentOptions.provider = cfg.childProvider
1486
+ const childProvider = providerOverride ?? cfg.childProvider
1487
+ if (childProvider) agentOptions.provider = childProvider
1070
1488
  if (childModel) agentOptions.model = childModel
1071
1489
  const request = {
1072
1490
  parent,
1073
1491
  prompt: [{ type: 'text', text: prompt }],
1492
+ // The host resolves relative paths (and shell commands) against this
1493
+ // directory. Isolation is only real when the child starts in its own
1494
+ // checkout; otherwise `notes/report.md` lands in the parent's checkout
1495
+ // while verification looks inside the worktree.
1496
+ ...(childCwd ? { cwd: path.resolve(childCwd) } : {}),
1074
1497
  ...(Object.keys(agentOptions).length > 0 ? { agentOptions } : {}),
1075
1498
  }
1076
1499
  // A preset is the host's only way to give a child a narrower tool set:
1077
- // the start request has no tool filter in dsh 0.2.2-rc.1.
1078
- if (cfg.childPreset) {
1500
+ // the start request has no tool filter. The planner passes its own
1501
+ // preset (usually one with no tools); workers fall back to childPreset.
1502
+ const requestedPreset = preset ?? cfg.childPreset
1503
+ if (requestedPreset) {
1504
+ if (typeof ctx.get === 'function' && !ctx.get('agentPresets')) {
1505
+ throw new Error(
1506
+ `agent preset "${requestedPreset}" cannot be applied: this profile does not compose an agentPresets `
1507
+ + 'registry, so the child would run with this session\'s tools',
1508
+ )
1509
+ }
1079
1510
  if (capabilities && !capabilities.agentPreset) {
1080
1511
  throw new Error(
1081
- `childPreset "${cfg.childPreset}" cannot be applied: subagent provider "${cfg.provider}" does not support `
1082
- + 'independent agent presets, so this child would run with this session\'s tools',
1512
+ `agent preset "${requestedPreset}" cannot be applied: subagent provider "${cfg.provider}" does not `
1513
+ + 'support independent agent presets, so this child would run with this session\'s tools',
1083
1514
  )
1084
1515
  }
1085
- request.agentPreset = cfg.childPreset
1516
+ request.agentPreset = requestedPreset
1086
1517
  }
1087
1518
  // Recursion is bounded unless the operator explicitly left it to the
1088
1519
  // backend. Silently dropping the cap would hand 8 parallel workers the
@@ -1097,13 +1528,30 @@ export function apply(ctx, config) {
1097
1528
  }
1098
1529
  request.maxDepth = cfg.maxSubagentDepth
1099
1530
  }
1100
- const activation = await subagents.startActivation({
1101
- provider: cfg.provider,
1102
- label,
1103
- request,
1104
- signal,
1105
- delivery: 'caller',
1106
- })
1531
+ // Escalation and rollback are one synchronous tick: the host captures the
1532
+ // parent override inside `startActivation` before its first await, so an
1533
+ // await anywhere between append, call, and restore would leak full access
1534
+ // to a concurrent child of this session.
1535
+ const escalation = cfg.commandWorkerPermission === 'danger-full-access' && wantsCommandSandbox(requires)
1536
+ ? beginCommandEscalation(parent, {
1537
+ runId,
1538
+ subtaskId,
1539
+ reason: `the plan declared command capability: ${requires.join(', ')}`,
1540
+ })
1541
+ : null
1542
+ let pending
1543
+ try {
1544
+ pending = subagents.startActivation({
1545
+ provider: cfg.provider,
1546
+ label,
1547
+ request,
1548
+ signal,
1549
+ delivery: 'caller',
1550
+ })
1551
+ } finally {
1552
+ escalation?.restore()
1553
+ }
1554
+ const activation = await pending
1107
1555
  rememberChild(activation.childId)
1108
1556
  guard.bindChild(activation.childId, { runId, label })
1109
1557
  return {
@@ -1121,6 +1569,121 @@ export function apply(ctx, config) {
1121
1569
  },
1122
1570
  })
1123
1571
 
1572
+ /**
1573
+ * The scheduler is a caller of the orchestrator, not a second run engine.
1574
+ * Its timer starts a run only if the plan is due, the previous run of that
1575
+ * plan is over, the plan's budget still has room, and the quota has a slot
1576
+ * for it. A plan's failure backoff decides whether the user is woken.
1577
+ */
1578
+ // A session brought back for scheduled runs is owned by this plugin, so it
1579
+ // is disposed with the plugin instead of outliving the host that made it.
1580
+ const scheduleOwners = new Set()
1581
+
1582
+ /**
1583
+ * Bring back the session that owns a plan, using the narrowest host API that
1584
+ * can do it. `agents.resume` is the durable one: it reopens the persisted
1585
+ * session in this process, which is exactly the "usable execution context"
1586
+ * a scheduled run needs after a restart. The console's Host Session API is a
1587
+ * fallback; a fresh session is the last resort.
1588
+ *
1589
+ * @param {object} plan - plan whose window is firing.
1590
+ * @returns {Promise<object | {agent: object, sessionId: string} | null>} agent or agent+id.
1591
+ */
1592
+ async function recoverScheduleOwner(plan) {
1593
+ const agents = getAgents()
1594
+ if (agents && typeof agents.resume === 'function') {
1595
+ try {
1596
+ const handle = await agents.resume({ resumeSessionId: plan.ownerSessionId })
1597
+ if (handle?.agent) {
1598
+ scheduleOwners.add(handle)
1599
+ return handle.agent
1600
+ }
1601
+ } catch (error) {
1602
+ log(`schedule ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1603
+ }
1604
+ }
1605
+ const session = getSessionController()
1606
+ if (session && typeof session.resolveAgent === 'function') {
1607
+ const resolved = await session.resolveAgent(plan.ownerSessionId)
1608
+ if (resolved?.agent) {
1609
+ const registered = getAgents()?.get?.(plan.ownerSessionId)
1610
+ return registered ?? resolved.agent
1611
+ }
1612
+ if (resolved?.error) log(`schedule ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${resolved.error}`)
1613
+ }
1614
+ if (agents && typeof agents.create === 'function') {
1615
+ const sessionId = randomUUID()
1616
+ try {
1617
+ const handle = await agents.create({
1618
+ sessionId,
1619
+ ...(plan.cwd ? { meta: { cwd: plan.cwd } } : {}),
1620
+ })
1621
+ if (handle?.agent) {
1622
+ scheduleOwners.add(handle)
1623
+ return { agent: handle.agent, sessionId }
1624
+ }
1625
+ } catch (error) {
1626
+ log(`schedule ${plan.id}: cannot create a replacement session: ${error?.message ?? error}`)
1627
+ }
1628
+ }
1629
+ if (session && typeof session.create === 'function') {
1630
+ const created = await session.create({ cwd: plan.cwd || workbenchRoot })
1631
+ const sessionId = typeof created?.sessionId === 'string' ? created.sessionId : ''
1632
+ if (sessionId) {
1633
+ const registered = getAgents()?.get?.(sessionId)
1634
+ if (registered && typeof registered === 'object') return { agent: registered, sessionId }
1635
+ if (typeof session.resolveAgent === 'function') {
1636
+ const resolved = await session.resolveAgent(sessionId)
1637
+ if (resolved?.agent) return { agent: resolved.agent, sessionId }
1638
+ }
1639
+ }
1640
+ log(`schedule ${plan.id}: the host could not create a replacement session`)
1641
+ }
1642
+ return null
1643
+ }
1644
+
1645
+ const scheduler = createScheduler({
1646
+ stateFile: path.join(store.root, 'schedules.json'),
1647
+ orchestrator: {
1648
+ start: args => orchestrator.start(args),
1649
+ status: runId => orchestrator.status(runId),
1650
+ activeSnapshot: () => orchestrator.activeSnapshot(),
1651
+ list: () => orchestrator.list(),
1652
+ },
1653
+ async resolveOwner(plan) {
1654
+ const live = getAgents()?.get?.(plan.ownerSessionId)
1655
+ if (live && typeof live === 'object') return live
1656
+ return recoverScheduleOwner(plan)
1657
+ },
1658
+ async notify({ plan, event, message }) {
1659
+ let agent = getAgents()?.get?.(plan.ownerSessionId)
1660
+ if (!agent) {
1661
+ const recovered = await recoverScheduleOwner(plan)
1662
+ agent = recovered?.agent ?? recovered ?? null
1663
+ }
1664
+ if (!agent || typeof agent.followup !== 'function') {
1665
+ log(`schedule ${plan.id} (${event}) has no live session ${plan.ownerSessionId} to notify`)
1666
+ return { delivered: false }
1667
+ }
1668
+ // The scheduler owns this message, so it does not go through the run
1669
+ // notification policy: a budget or decision stop must not be folded away
1670
+ // by the hourly cap. Duplicate suppression is per plan and per outcome.
1671
+ await outbox.enqueue(plan.ownerSessionId, () => agent.followup({
1672
+ id: randomUUID(),
1673
+ role: 'user',
1674
+ content: [{ type: 'text', text: message }],
1675
+ source: { kind: 'user' },
1676
+ }))
1677
+ return { delivered: true }
1678
+ },
1679
+ now: () => Date.now(),
1680
+ tickSeconds: cfg.schedulerTickSeconds,
1681
+ humanPriority: cfg.schedulerHumanPriority,
1682
+ maxConsecutiveFailures: cfg.schedulerMaxConsecutiveFailures,
1683
+ maxActiveRuns: cfg.maxActiveRuns,
1684
+ warn: log,
1685
+ })
1686
+
1124
1687
  // Recovery runs once at mount; tools wait for it so a run left active by a
1125
1688
  // dead host reads as interrupted before the first tool call sees it. A
1126
1689
  // failure to initialize the state directory is kept and reported by every
@@ -1152,6 +1715,17 @@ export function apply(ctx, config) {
1152
1715
  log(`cannot create the template directory ${templates.dir}: ${error?.message ?? error}`)
1153
1716
  }
1154
1717
  }
1718
+ // Schedules are off unless a plan file exists. Loading it here means a
1719
+ // restart does not wait for the first tool call, and the timer is armed
1720
+ // before the host reports itself ready.
1721
+ try {
1722
+ const loaded = await scheduler.init()
1723
+ if (loaded.plans > 0) {
1724
+ log(`scheduled runs: ${loaded.plans} plan(s) loaded; checking every ${cfg.schedulerTickSeconds}s`)
1725
+ }
1726
+ } catch (error) {
1727
+ log(`cannot load scheduled runs from ${scheduler.stateFile}: ${error?.message ?? error}`)
1728
+ }
1155
1729
  if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
1156
1730
  try {
1157
1731
  const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
@@ -1163,6 +1737,18 @@ export function apply(ctx, config) {
1163
1737
  }
1164
1738
  })()
1165
1739
 
1740
+ /**
1741
+ * One answer path for both `superagent_answer` and the console's attention
1742
+ * card. The page must not grow a second, subtly different way to decide a
1743
+ * question; it calls the same orchestrator method with the conversation agent
1744
+ * as the owner.
1745
+ */
1746
+ async function answerAttention({ runId, attentionId, answer }, agent, clientTimeZone) {
1747
+ await ready
1748
+ if (stateError) throw stateError
1749
+ return orchestrator.answer(runId, attentionId, answer, agent, clientTimeZone)
1750
+ }
1751
+
1166
1752
  /** True when the host actually provides a subagent service. */
1167
1753
  function hasSubagents() {
1168
1754
  const subagents = getSubagents()
@@ -1234,6 +1820,60 @@ export function apply(ctx, config) {
1234
1820
  + `queueTimeoutMinutes (default ${DEFAULTS.queueTimeoutMinutes}). Off by default; at most maxQueuedRuns `
1235
1821
  + `(default ${DEFAULTS.maxQueuedRuns}) may wait.`,
1236
1822
  },
1823
+ goal_mode: {
1824
+ type: 'boolean',
1825
+ description: 'Opt in to goal mode (default false). The run does not finish when its subtasks do: an independent '
1826
+ + 'acceptance step checks the acceptance conditions, and a failed round starts another one with what is '
1827
+ + 'missing instead of repeating the same work. It stops when the goal is met, when max_rounds, '
1828
+ + 'max_wall_clock_minutes or the budget is reached, or when consecutive rounds stop making progress. Off by '
1829
+ + 'default, so a start without this flag behaves exactly as before.',
1830
+ },
1831
+ acceptance: {
1832
+ type: 'array',
1833
+ description: 'Acceptance conditions, required when goal_mode is true. Each item is {id?, text, check?}. A '
1834
+ + 'check is {"type":"command","command":"npm test"} (real exit code) or {"type":"file","path":"dist/app.js"} '
1835
+ + '(existence); the plugin runs it, so the verdict is not the model\'s opinion. A condition without a check '
1836
+ + 'is judged by an independent acceptance model, and status names the source of every verdict.',
1837
+ items: {
1838
+ type: 'object',
1839
+ properties: {
1840
+ id: { type: 'string', description: 'Short id used in reports and feedback, e.g. "tests".' },
1841
+ text: { type: 'string', description: 'What must hold, in one sentence.' },
1842
+ check: {
1843
+ type: 'object',
1844
+ description: 'Machine-checkable part; omit to have the acceptance model judge the condition.',
1845
+ properties: {
1846
+ type: { type: 'string', enum: ['command', 'file'] },
1847
+ command: { type: 'string', description: 'Shell command for type "command"; its exit code is the verdict.' },
1848
+ cwd: { type: 'string', description: 'Optional working directory, relative to the goal workspace.' },
1849
+ timeout_seconds: { type: 'number', description: 'Command timeout (default 120, max 900).' },
1850
+ path: { type: 'string', description: 'File path for type "file", relative to the goal workspace.' },
1851
+ must_exist: { type: 'boolean', description: 'For type "file": true (default) requires it, false requires absence.' },
1852
+ },
1853
+ required: ['type'],
1854
+ },
1855
+ },
1856
+ required: ['text'],
1857
+ },
1858
+ },
1859
+ max_rounds: { type: 'number', description: 'Goal mode: rounds allowed before it stops (default 5, max 20).' },
1860
+ max_wall_clock_minutes: {
1861
+ type: 'number',
1862
+ description: 'Goal mode: wall-clock budget for the rounds (default 60; a resume restarts it).',
1863
+ },
1864
+ no_progress_rounds: {
1865
+ type: 'number',
1866
+ description: 'Goal mode: consecutive rounds with the same failing condition before it stops (default 2). When '
1867
+ + 'the acceptance has a machine check, a round that changed no file stops immediately instead.',
1868
+ },
1869
+ budget: {
1870
+ type: 'object',
1871
+ description: 'Goal mode budget, narrowing the operator cap: {max_model_calls, max_tokens}.',
1872
+ properties: {
1873
+ max_model_calls: { type: 'number' },
1874
+ max_tokens: { type: 'number' },
1875
+ },
1876
+ },
1237
1877
  max_subtasks: { type: 'number', description: `Cap on planned subtasks (default ${DEFAULTS.maxSubtasks}, max 16).` },
1238
1878
  max_parallel: { type: 'number', description: `Subtasks allowed to run at once (default ${DEFAULTS.maxParallel}, max 8).` },
1239
1879
  deadline_minutes: { type: 'number', description: `Wall-clock budget in minutes (default ${DEFAULTS.deadlineMinutes}).` },
@@ -1262,6 +1902,9 @@ export function apply(ctx, config) {
1262
1902
  + 'worker, and aggregator agents. Enable it in this profile (the base bundle provides it) and restart.',
1263
1903
  )
1264
1904
  }
1905
+ // The tool surface is snake_case; the orchestrator and the goal module
1906
+ // use camelCase, so the conversion happens once, in goalModeFromToolArgs.
1907
+ const goalMode = goalModeFromToolArgs(args)
1265
1908
  const run = await orchestrator.start({
1266
1909
  goal: args.goal,
1267
1910
  parentSessionId: check.agent.id,
@@ -1269,6 +1912,7 @@ export function apply(ctx, config) {
1269
1912
  clientTimeZone: exec.clientTimeZone,
1270
1913
  allowDuplicate: args.allow_duplicate === true,
1271
1914
  mode: args.mode,
1915
+ goalMode,
1272
1916
  queue: args.queue === true,
1273
1917
  approvePolicy: args.approve_policy === true,
1274
1918
  overrides: {
@@ -1535,15 +2179,11 @@ export function apply(ctx, config) {
1535
2179
  const check = requireAgent(exec)
1536
2180
  if (check.error) return check.error
1537
2181
  try {
1538
- await ready
1539
- if (stateError) return describeError(stateError)
1540
- const result = await orchestrator.answer(
1541
- String(args.run_id ?? '').trim(),
1542
- args.attention_id,
1543
- args.answer,
1544
- check.agent,
1545
- exec.clientTimeZone,
1546
- )
2182
+ const result = await answerAttention({
2183
+ runId: String(args.run_id ?? '').trim(),
2184
+ attentionId: args.attention_id,
2185
+ answer: args.answer,
2186
+ }, check.agent, exec.clientTimeZone)
1547
2187
  let head
1548
2188
  if (result.resumed) {
1549
2189
  head = `answered ${result.attentionId} on run ${result.run.id}; the run was reopened and is ${result.run.status} `
@@ -1569,16 +2209,32 @@ export function apply(ctx, config) {
1569
2209
  name: 'superagent_memory',
1570
2210
  description:
1571
2211
  'Read or correct the cross-run notebook: short notes that earlier runs left for the next one. '
1572
- + 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it.',
2212
+ + 'A note is advisory and can be stale; a new note with the same key supersedes it, and forget retracts it. '
2213
+ + 'With layer="user" (when the user-level profile is enabled) the same actions address durable facts, '
2214
+ + 'preferences, and decisions with their rationale; forgetting there deletes instead of retracting.',
1573
2215
  properties: {
1574
2216
  action: {
1575
2217
  type: 'string',
1576
2218
  enum: ['list', 'search', 'set', 'forget'],
1577
2219
  description: 'List notes, search them by keyword or tag, set (add or correct) one, or forget one.',
1578
2220
  },
2221
+ layer: {
2222
+ type: 'string',
2223
+ enum: ['run', 'user'],
2224
+ description: 'run (default) reads the task notebook; user reads the cross-task profile.',
2225
+ },
2226
+ category: {
2227
+ type: 'string',
2228
+ enum: [...USER_MEMORY_CATEGORIES],
2229
+ description: 'User layer only: fact, preference, or decision.',
2230
+ },
1579
2231
  key: { type: 'string', description: 'Short topic key. A new note with the same key replaces the older one.' },
1580
2232
  kind: { type: 'string', enum: [...MEMORY_KINDS], description: 'decision, pitfall, next, dispatch, or note.' },
1581
- text: { type: 'string', description: 'The durable fact to record (set only).' },
2233
+ text: { type: 'string', description: 'The durable fact to record (run, or user fact/preference).' },
2234
+ choice: { type: 'string', description: 'User decision only: what was chosen.' },
2235
+ rejected: { type: 'string', description: 'User decision only: the alternative that was given up.' },
2236
+ reason: { type: 'string', description: 'User decision only: why the choice was made.' },
2237
+ rollback: { type: 'string', description: 'User decision only: how to undo the choice later.' },
1582
2238
  query: {
1583
2239
  type: 'string',
1584
2240
  description: 'Keywords to rank notes by (search only). The goal of the current task works well.',
@@ -1593,6 +2249,18 @@ export function apply(ctx, config) {
1593
2249
  description: 'Notebook scope: "rules" for project rules, "profile" for user preferences, '
1594
2250
  + 'or the run scope (default) that earlier runs write to.',
1595
2251
  },
2252
+ run_id: {
2253
+ type: 'string',
2254
+ description: 'User layer forget only: delete every record written by this run.',
2255
+ },
2256
+ before: {
2257
+ type: 'string',
2258
+ description: 'User layer forget only: delete records at or before this date.',
2259
+ },
2260
+ after: {
2261
+ type: 'string',
2262
+ description: 'User layer forget only: delete records at or after this date.',
2263
+ },
1596
2264
  limit: { type: 'number', description: 'Maximum notes to print (default 20).' },
1597
2265
  },
1598
2266
  required: ['action'],
@@ -1614,6 +2282,83 @@ export function apply(ctx, config) {
1614
2282
  const scope = args.scope === undefined || args.scope === null
1615
2283
  ? cfg.memoryScope
1616
2284
  : normalizeScope(args.scope)
2285
+ const layer = String(args.layer ?? 'run').trim().toLowerCase()
2286
+ if (layer !== 'run' && layer !== 'user') {
2287
+ return describeError(`unknown layer "${args.layer}"; use "run" or "user"`)
2288
+ }
2289
+ if (layer === 'user') {
2290
+ if (!userMemory) {
2291
+ return describeError(
2292
+ 'user-level memory is off; set memoryUserProfile: true in the plugin config and restart',
2293
+ )
2294
+ }
2295
+ const category = args.category === undefined || args.category === null || args.category === ''
2296
+ ? null
2297
+ : String(args.category).trim().toLowerCase()
2298
+ if (category && !USER_MEMORY_CATEGORIES.includes(category)) {
2299
+ return describeError(`category must be one of ${USER_MEMORY_CATEGORIES.join(', ')}`)
2300
+ }
2301
+ const limit = Math.max(1, Math.min(30, Number(args.limit) || 20))
2302
+ const tags = Array.isArray(args.tags) ? args.tags : []
2303
+ if (action === 'list') {
2304
+ const rows = []
2305
+ let total = 0
2306
+ for (const name of category ? [category] : USER_MEMORY_CATEGORIES) {
2307
+ const result = await userMemory.list({ category: name, limit })
2308
+ total += result.total
2309
+ rows.push(...result.entries.map(userRecordLine))
2310
+ }
2311
+ if (total === 0) return `no user-level record recorded yet (${path.join(store.root, 'user-memory')})`
2312
+ return `${total} user-level record(s)\n\n${rows.join('\n')}`
2313
+ }
2314
+ if (action === 'search') {
2315
+ const query = String(args.query ?? '').trim()
2316
+ if (!query && tags.length === 0) {
2317
+ return describeError('search needs a query, tags, or both; call action="list" to read everything')
2318
+ }
2319
+ const rows = []
2320
+ let matched = 0
2321
+ let total = 0
2322
+ for (const name of category ? [category] : USER_MEMORY_CATEGORIES) {
2323
+ const result = await userMemory.recall({ category: name, query, tags, maxEntries: limit })
2324
+ total += result.total
2325
+ matched += result.matched
2326
+ rows.push(...result.entries.map(userRecordLine))
2327
+ }
2328
+ if (matched === 0) return `no user-level record matches ${query ? `“${query}”` : 'those tags'} (${total} recorded)`
2329
+ return `${matched} of ${total} user-level record(s) match, best first\n\n${rows.join('\n')}`
2330
+ }
2331
+ if (action === 'forget') {
2332
+ const result = await userMemory.forget({
2333
+ key: args.key,
2334
+ runId: args.run_id,
2335
+ before: args.before,
2336
+ after: args.after,
2337
+ category,
2338
+ })
2339
+ if (result.reason) return describeError(result.reason)
2340
+ if (result.deleted === 0) return 'no user-level record matched those filters'
2341
+ return `deleted ${result.deleted} user-level record(s) from ${result.categories.join(', ')}; `
2342
+ + 'they are gone from the files, not retracted'
2343
+ }
2344
+ if (action === 'set') {
2345
+ if (!category) return describeError('user set needs category: fact, preference, or decision')
2346
+ if (category === 'decision' && (!String(args.choice ?? '').trim() || !String(args.reason ?? '').trim())) {
2347
+ return describeError('a user decision needs both choice and reason')
2348
+ }
2349
+ if (category !== 'decision' && !String(args.text ?? '').trim()) {
2350
+ return describeError(`set needs text for a user ${category}`)
2351
+ }
2352
+ const entry = category === 'decision'
2353
+ ? { key: args.key, choice: args.choice, rejected: args.rejected, reason: args.reason, rollback: args.rollback, tags }
2354
+ : { key: args.key, text: args.text, tags }
2355
+ const result = await userMemory.record({ category, entry })
2356
+ return result.written > 0
2357
+ ? `recorded user ${category}; later unrelated tasks will see it`
2358
+ : describeError(result.reason ?? 'cannot record that user-level entry')
2359
+ }
2360
+ return describeError(`unknown action "${args.action}"; use list, search, set, or forget`)
2361
+ }
1617
2362
  if (action === 'list') {
1618
2363
  // Capped at 30: this output goes straight into the model context, and a
1619
2364
  // 200-row dump would cost more than the notes are worth.
@@ -1783,6 +2528,213 @@ export function apply(ctx, config) {
1783
2528
  },
1784
2529
  }))
1785
2530
 
2531
+ ctx.tools.register(defineTool({
2532
+ name: 'superagent_schedule',
2533
+ description:
2534
+ 'Create and manage scheduled runs: a plan that starts a run on a cron expression or a fixed interval, without '
2535
+ + 'anyone calling superagent_start. Actions: create, list, pause, resume, delete, run-now. A plan stores its '
2536
+ + 'cron or interval, time zone, goal (or template), optional goal mode and acceptance, its own budget, and its '
2537
+ + 'concurrency policy. Plans survive a host restart under the state directory. '
2538
+ + 'Missed windows are not replayed: the default miss policy "latest" runs only the newest due window and marks '
2539
+ + 'the rest missed with a reason; "none" skips due windows while the host is down. '
2540
+ + 'A plan never overlaps itself: if its previous run is still active, that window is recorded as '
2541
+ + '"skipped: previous run still active". Scheduled runs share the concurrency quota with manual runs, and by '
2542
+ + 'default one slot stays reserved for manual starts. Notifications are limited to achieved, first failure, '
2543
+ + 'budget stop, and a needed decision; a plan that fails 3 times in a row pauses and says so once. '
2544
+ + 'Cron support is zero-dependency: 5 fields, *, */n, ranges, lists, month/weekday names, 0 or 7 for Sunday. '
2545
+ + 'Seconds, @macros, L, W, # and ? are refused when the plan is created, with the field number. '
2546
+ + 'Nothing runs until a plan is created; an install with no plans behaves exactly as before.',
2547
+ properties: {
2548
+ action: {
2549
+ type: 'string',
2550
+ enum: ['create', 'list', 'pause', 'resume', 'delete', 'run-now'],
2551
+ description: 'create a plan, list plans, pause/resume one, delete one, or start one run now without moving its '
2552
+ + 'next planned window.',
2553
+ },
2554
+ id: { type: 'string', description: 'Schedule id (sch-...), required for pause, resume, delete, and run-now.' },
2555
+ name: { type: 'string', description: 'Create: a short name used in list and in notifications.' },
2556
+ goal: {
2557
+ type: 'string',
2558
+ description: 'Create: the complete goal the scheduled run starts. Give goal or template_id, not both.',
2559
+ },
2560
+ template_id: {
2561
+ type: 'string',
2562
+ description: 'Create: expand this workflow template into the goal at create time, using params. The stored '
2563
+ + 'goal is the expanded text, so a later template edit does not change the plan.',
2564
+ },
2565
+ params: {
2566
+ type: 'object',
2567
+ description: 'Create with template_id: values for the template placeholders.',
2568
+ additionalProperties: { type: 'string' },
2569
+ },
2570
+ cron: {
2571
+ type: 'string',
2572
+ description: 'Create: a 5-field cron expression (minute hour day-of-month month day-of-week) evaluated in '
2573
+ + 'timezone, e.g. "0 9 * * MON-FRI". Give cron or every_minutes, not both.',
2574
+ },
2575
+ every_minutes: {
2576
+ type: 'number',
2577
+ description: 'Create: a fixed interval in minutes instead of cron. The first run is one interval from now; '
2578
+ + 'later runs are one interval after the previous planned window.',
2579
+ },
2580
+ timezone: {
2581
+ type: 'string',
2582
+ description: 'Create: IANA time zone the cron is written in (default UTC), e.g. "Asia/Shanghai". The host '
2583
+ + 'clock is not used as an implicit zone.',
2584
+ },
2585
+ miss_policy: {
2586
+ type: 'string',
2587
+ enum: ['latest', 'none'],
2588
+ description: 'Create: what to do after downtime. latest (default) runs only the newest missed window and marks '
2589
+ + 'the others missed; none skips all due windows and advances to the next one.',
2590
+ },
2591
+ mode: {
2592
+ type: 'string',
2593
+ enum: ['planned', 'direct'],
2594
+ description: 'Create: run mode for each execution, same meaning as superagent_start.',
2595
+ },
2596
+ goal_mode: {
2597
+ type: 'boolean',
2598
+ description: 'Create: run each execution in goal mode with acceptance checking and self-continuation.',
2599
+ },
2600
+ acceptance: {
2601
+ type: 'array',
2602
+ description: 'Create with goal_mode: acceptance conditions, same shape as superagent_start.',
2603
+ items: {
2604
+ type: 'object',
2605
+ properties: {
2606
+ id: { type: 'string' },
2607
+ text: { type: 'string' },
2608
+ check: {
2609
+ type: 'object',
2610
+ properties: {
2611
+ type: { type: 'string', enum: ['command', 'file'] },
2612
+ command: { type: 'string' },
2613
+ cwd: { type: 'string' },
2614
+ timeout_seconds: { type: 'number' },
2615
+ path: { type: 'string' },
2616
+ must_exist: { type: 'boolean' },
2617
+ },
2618
+ required: ['type'],
2619
+ },
2620
+ },
2621
+ required: ['text'],
2622
+ },
2623
+ },
2624
+ max_rounds: { type: 'number', description: 'Create with goal_mode: rounds per execution (default 5, max 20).' },
2625
+ max_wall_clock_minutes: { type: 'number', description: 'Create with goal_mode: wall-clock budget per execution.' },
2626
+ no_progress_rounds: { type: 'number', description: 'Create with goal_mode: no-progress rounds before stopping.' },
2627
+ budget: {
2628
+ type: 'object',
2629
+ description: 'Create: spending ceiling. max_model_calls and max_tokens cap one execution; '
2630
+ + 'max_total_model_calls, max_total_tokens and max_total_runs cap the plan across executions. A reached '
2631
+ + 'total pauses the plan and records the reason.',
2632
+ properties: {
2633
+ max_model_calls: { type: 'number' },
2634
+ max_tokens: { type: 'number' },
2635
+ max_total_model_calls: { type: 'number' },
2636
+ max_total_tokens: { type: 'number' },
2637
+ max_total_runs: { type: 'number' },
2638
+ },
2639
+ },
2640
+ human_priority: {
2641
+ type: 'boolean',
2642
+ description: 'Create: when true (default), a scheduled run may not take the last concurrency slot, so a '
2643
+ + 'manual superagent_start at the same moment still finds room.',
2644
+ },
2645
+ session_id: {
2646
+ type: 'string',
2647
+ description: 'Create: the session that owns the scheduled runs and receives their notifications. Defaults to '
2648
+ + 'the calling session. After a host restart the plugin asks the Host Session API to reopen that session, '
2649
+ + 'and creates a replacement if it was deleted, so a plan does not depend on the original process staying '
2650
+ + 'alive. On a host without that API the plan is marked at create time as requiring a resident session.',
2651
+ },
2652
+ },
2653
+ required: ['action'],
2654
+ async execute(args = {}, exec) {
2655
+ const check = requireAgent(exec)
2656
+ if (check.error) return check.error
2657
+ try {
2658
+ await ready
2659
+ if (stateError) return describeError(stateError)
2660
+ const action = String(args.action ?? '').trim().toLowerCase()
2661
+ if (action === 'create') {
2662
+ let goal = typeof args.goal === 'string' ? args.goal.trim() : ''
2663
+ const templateId = String(args.template_id ?? '').trim()
2664
+ if (templateId) {
2665
+ if (goal) return describeError('create takes goal or template_id, not both; remove one')
2666
+ const template = await templates.get(templateId)
2667
+ if (!template) {
2668
+ return describeError(`no workflow template with id "${templateId}"; call superagent_template action="list"`)
2669
+ }
2670
+ goal = expandTemplate(template, args.params).goal
2671
+ }
2672
+ const budget = args.budget && typeof args.budget === 'object'
2673
+ ? {
2674
+ maxModelCalls: args.budget.max_model_calls,
2675
+ maxTokens: args.budget.max_tokens,
2676
+ maxTotalModelCalls: args.budget.max_total_model_calls,
2677
+ maxTotalTokens: args.budget.max_total_tokens,
2678
+ maxTotalRuns: args.budget.max_total_runs,
2679
+ }
2680
+ : null
2681
+ const recovery = scheduleOwnerRecovery()
2682
+ const plan = await scheduler.create({
2683
+ name: args.name,
2684
+ goal,
2685
+ mode: args.mode,
2686
+ cron: args.cron,
2687
+ everyMinutes: args.every_minutes,
2688
+ timeZone: args.timezone,
2689
+ missPolicy: args.miss_policy,
2690
+ goalMode: goalModeFromToolArgs(args, { budget: false }),
2691
+ budget,
2692
+ humanPriority: args.human_priority,
2693
+ ownerSessionId: String(args.session_id ?? check.agent.id).trim(),
2694
+ ownerRecovery: recovery,
2695
+ cwd: check.agent.session?.cwd ?? workbenchRoot,
2696
+ })
2697
+ const warning = recovery === 'none'
2698
+ ? '\n\nwarning: this host has no Host Session API, so it cannot reopen the owning session after a '
2699
+ + 'restart. The plan is marked as requiring a resident session; it will not silently pause, but it '
2700
+ + 'will not run while that session is closed.'
2701
+ : ''
2702
+ return `created schedule ${plan.id}. The timer is armed from now on; no further tool call is needed.\n\n`
2703
+ + formatSchedule(plan) + warning
2704
+ }
2705
+ if (action === 'list') {
2706
+ const plans = await scheduler.list()
2707
+ const snapshot = await orchestrator.activeSnapshot()
2708
+ const quota = `quota: ${snapshot.active}/${snapshot.maxActiveRuns} active `
2709
+ + `(${snapshot.manualActive} manual, ${snapshot.scheduledActive} scheduled); `
2710
+ + `${snapshot.waiting} waiting (${snapshot.manualWaiting} manual)`
2711
+ return `${formatScheduleList(plans)}\n${quota}`
2712
+ }
2713
+ if (action === 'pause') {
2714
+ const plan = await scheduler.pause(String(args.id ?? ''), 'paused by superagent_schedule')
2715
+ return `paused ${plan.id} ("${plan.name}"). It will not start again until action="resume".`
2716
+ }
2717
+ if (action === 'resume') {
2718
+ const plan = await scheduler.resume(String(args.id ?? ''))
2719
+ return `resumed ${plan.id} ("${plan.name}"); next run ${plan.nextRunAt}. Past windows are not replayed.`
2720
+ }
2721
+ if (action === 'delete') {
2722
+ const removed = await scheduler.remove(String(args.id ?? ''))
2723
+ return `deleted ${removed.id} ("${removed.name}"). Runs it already started keep their records.`
2724
+ }
2725
+ if (action === 'run-now') {
2726
+ const { plan, run } = await scheduler.runNow(String(args.id ?? ''))
2727
+ return `started ${run.id} now for schedule ${plan.id} ("${plan.name}"); its next planned window is `
2728
+ + `${plan.nextRunAt}. Poll the run with superagent_status.`
2729
+ }
2730
+ return describeError(`unknown action "${args.action}"; use create, list, pause, resume, delete, or run-now`)
2731
+ } catch (error) {
2732
+ if (error instanceof TemplateError) return templateProblem(error)
2733
+ return describeError(error)
2734
+ }
2735
+ },
2736
+ }))
2737
+
1786
2738
  // The embedding surface is opt-in: mounting the plugin must not open a port
1787
2739
  // unasked. When it is on, every request goes through the same orchestrator as
1788
2740
  // the tools, so quota, budgets, ownership, and cancel behave identically.
@@ -2023,9 +2975,311 @@ export function apply(ctx, config) {
2023
2975
  })
2024
2976
  }
2025
2977
 
2978
+ // The conversation console is opt-in as well. Unlike the workbench it does
2979
+ // not read files: it creates a real Host Session through `sessionController`,
2980
+ // sends prompts, and fans the session's own follow stream to the page. If the
2981
+ // host has no session service the page is told so; it is never a mock chat.
2982
+ if (cfg.consolePort !== null) {
2983
+ const consoleRoot = cfg.consoleRoot ? path.resolve(cfg.consoleRoot) : workbenchRoot
2984
+
2985
+ function consoleCapabilities() {
2986
+ const session = getSessionController()
2987
+ if (!session) {
2988
+ return {
2989
+ chat: false,
2990
+ reason: '宿主没有挂载 sessionController(Host Session API),因此没有可对话的 session;控制台不会伪造聊天。',
2991
+ }
2992
+ }
2993
+ const missing = ['create', 'prompt', 'follow'].filter(name => typeof session[name] !== 'function')
2994
+ if (missing.length > 0) {
2995
+ return {
2996
+ chat: false,
2997
+ reason: `sessionController 已挂载,但缺少 ${missing.join(' / ')},无法建立可流式回复的对话。`,
2998
+ }
2999
+ }
3000
+ return { chat: true, reason: null }
3001
+ }
3002
+
3003
+ /** The conversation agent is the owner of every run it starts. */
3004
+ function conversationAgent(sessionId) {
3005
+ const agents = getAgents()
3006
+ if (agents && typeof agents.get === 'function') {
3007
+ const agent = agents.get(sessionId)
3008
+ if (agent) return agent
3009
+ }
3010
+ return null
3011
+ }
3012
+
3013
+ function runView(run, { detail = false } = {}) {
3014
+ const usage = run.usage && typeof run.usage === 'object' ? run.usage : null
3015
+ const cost = usage ? computeCost(usage, cfg.pricing) : null
3016
+ const openAttention = Array.isArray(run.attention?.items)
3017
+ ? run.attention.items.filter(item => item && !item.answer).map(item => ({
3018
+ id: item.id,
3019
+ source: item.source ?? null,
3020
+ question: item.question,
3021
+ options: Array.isArray(item.options) ? item.options : [],
3022
+ reason: item.reason ?? null,
3023
+ askedAt: run.attention?.at ?? null,
3024
+ }))
3025
+ : []
3026
+ const subtasks = Array.isArray(run.subtasks)
3027
+ ? run.subtasks.map(subtask => ({
3028
+ index: subtask.index ?? null,
3029
+ title: subtask.title ?? null,
3030
+ status: subtask.status ?? null,
3031
+ childId: subtask.childId ?? null,
3032
+ }))
3033
+ : []
3034
+ const report = typeof run.report === 'string' ? run.report : null
3035
+ return {
3036
+ id: run.id,
3037
+ goal: run.goal,
3038
+ status: run.status,
3039
+ createdAt: run.createdAt ?? null,
3040
+ finishedAt: run.finishedAt ?? null,
3041
+ parentSessionId: run.parentSessionId ?? null,
3042
+ cost: cost
3043
+ ? {
3044
+ totalMicros: cost.totalMicros,
3045
+ currency: cost.currency,
3046
+ mixedCurrency: cost.mixedCurrency === true,
3047
+ byCurrency: cost.byCurrency,
3048
+ text: formatMoney(cost),
3049
+ complete: cost.complete === true,
3050
+ unpriced: Array.isArray(cost.unpriced) ? cost.unpriced : [],
3051
+ }
3052
+ : null,
3053
+ usage: usage
3054
+ ? {
3055
+ inputTokens: usage.inputTokens ?? null,
3056
+ outputTokens: usage.outputTokens ?? null,
3057
+ totalTokens: usage.totalTokens ?? null,
3058
+ modelCalls: usage.modelCalls ?? null,
3059
+ }
3060
+ : null,
3061
+ subtasks,
3062
+ attention: openAttention,
3063
+ report: report ? report.slice(0, detail ? 40_000 : 4_000) : null,
3064
+ reportTruncated: Boolean(report && report.length > (detail ? 40_000 : 4_000)),
3065
+ }
3066
+ }
3067
+
3068
+ const consoleHost = {
3069
+ capabilities: consoleCapabilities,
3070
+
3071
+ async createSession() {
3072
+ const caps = consoleCapabilities()
3073
+ if (!caps.chat) throw new Error(caps.reason)
3074
+ const session = getSessionController()
3075
+ const created = await session.create({
3076
+ cwd: consoleRoot,
3077
+ ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3078
+ })
3079
+ if (!created || typeof created.sessionId !== 'string' || !created.sessionId) {
3080
+ throw new Error('sessionController.create returned no sessionId')
3081
+ }
3082
+ return { sessionId: created.sessionId, preset: created.preset ?? cfg.consolePreset ?? null }
3083
+ },
3084
+
3085
+ /**
3086
+ * The tools this conversation actually has, read from the live agent's
3087
+ * scope rather than a list kept here. Resolving a blank session starts
3088
+ * its agent, which is the same work the first prompt would do.
3089
+ */
3090
+ async listTools(sessionId) {
3091
+ const session = getSessionController()
3092
+ let agent = conversationAgent(sessionId)
3093
+ if (!agent && session && typeof session.resolveAgent === 'function') {
3094
+ const resolved = await session.resolveAgent(sessionId)
3095
+ agent = resolved?.agent ?? null
3096
+ }
3097
+ if (!agent) return null
3098
+ if (typeof ctx.tools?.definitions !== 'function') return null
3099
+ return ctx.tools.definitions(agent)
3100
+ .map(definition => ({
3101
+ name: definition.name,
3102
+ description: typeof definition.description === 'string'
3103
+ ? definition.description.slice(0, 240)
3104
+ : null,
3105
+ }))
3106
+ .sort((left, right) => left.name.localeCompare(right.name))
3107
+ },
3108
+
3109
+ async prompt({ sessionId, text, mode }) {
3110
+ const session = getSessionController()
3111
+ if (!session) throw new Error('sessionController is not mounted')
3112
+ const timeZone = (() => {
3113
+ try {
3114
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
3115
+ } catch {
3116
+ return undefined
3117
+ }
3118
+ })()
3119
+ await session.prompt({
3120
+ requestId: randomUUID(),
3121
+ sessionId,
3122
+ mode: mode === 'steer' ? 'steer' : 'queue',
3123
+ content: [{ type: 'text', text }],
3124
+ ...(timeZone ? { clientTimeZone: timeZone } : {}),
3125
+ }, new AbortController().signal)
3126
+ return { accepted: true }
3127
+ },
3128
+
3129
+ async listRuns(sessionId) {
3130
+ await ready
3131
+ if (stateError) throw stateError
3132
+ const runs = await store.list()
3133
+ return runs
3134
+ .filter(run => run && run.parentSessionId === sessionId)
3135
+ .slice(0, 20)
3136
+ .map(run => runView(run))
3137
+ },
3138
+
3139
+ async readRun(sessionId, runId) {
3140
+ await ready
3141
+ if (stateError) throw stateError
3142
+ const run = await store.read(runId)
3143
+ if (!run || run.parentSessionId !== sessionId) return null
3144
+ return runView(run, { detail: true })
3145
+ },
3146
+
3147
+ async answer({ sessionId, runId, attentionId, answer }) {
3148
+ let agent = conversationAgent(sessionId)
3149
+ if (!agent) {
3150
+ const session = getSessionController()
3151
+ if (session && typeof session.resolveAgent === 'function') {
3152
+ const resolved = await session.resolveAgent(sessionId)
3153
+ agent = resolved?.agent ?? null
3154
+ }
3155
+ }
3156
+ if (!agent) {
3157
+ throw new Error('the conversation agent is no longer live; reopen the conversation before answering')
3158
+ }
3159
+ const timeZone = (() => {
3160
+ try {
3161
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
3162
+ } catch {
3163
+ return undefined
3164
+ }
3165
+ })()
3166
+ const result = await answerAttention({ runId, attentionId, answer }, agent, timeZone)
3167
+ return {
3168
+ runId: result?.run?.id ?? runId,
3169
+ attentionId: result?.attentionId ?? attentionId,
3170
+ status: result?.run?.status ?? null,
3171
+ resumed: result?.resumed === true,
3172
+ effect: result?.effect?.detail ?? null,
3173
+ }
3174
+ },
3175
+
3176
+ subscribe(sessionId, listener) {
3177
+ const session = getSessionController()
3178
+ if (!session || typeof session.follow !== 'function') {
3179
+ throw new Error('sessionController.follow is not available')
3180
+ }
3181
+ const controller = new AbortController()
3182
+ let closed = false
3183
+ const emit = frame => {
3184
+ if (!closed) listener(frame)
3185
+ }
3186
+ ;(async () => {
3187
+ for await (const frame of session.follow({
3188
+ address: { kind: 'session', sessionId },
3189
+ assistantStream: true,
3190
+ }, controller.signal)) {
3191
+ if (closed) break
3192
+ if (frame?.type === 'snapshot') {
3193
+ emit({
3194
+ type: 'stream.snapshot',
3195
+ header: frame.header,
3196
+ cursor: frame.cursor,
3197
+ records: Array.isArray(frame.records) ? frame.records.slice(-200) : [],
3198
+ hasMore: frame.hasMore === true,
3199
+ })
3200
+ } else if (frame?.type === 'event') {
3201
+ emit({ type: 'session.event', event: frame.event })
3202
+ } else if (frame?.type === 'assistant-stream') {
3203
+ emit({ type: 'assistant.frame', frame: frame.frame })
3204
+ }
3205
+ }
3206
+ })().catch(error => {
3207
+ if (!closed) {
3208
+ emit({ type: 'error', code: 'follow-failed', message: error?.message ?? String(error) })
3209
+ }
3210
+ })
3211
+ if (typeof session.observeState === 'function') {
3212
+ ;(async () => {
3213
+ for await (const state of session.observeState({ sessionId }, controller.signal)) {
3214
+ if (closed) break
3215
+ emit({ type: 'session.state', state })
3216
+ }
3217
+ })().catch(error => {
3218
+ if (!closed) {
3219
+ emit({ type: 'error', code: 'state-failed', message: error?.message ?? String(error) })
3220
+ }
3221
+ })
3222
+ }
3223
+ return () => {
3224
+ closed = true
3225
+ controller.abort()
3226
+ }
3227
+ },
3228
+ }
3229
+
3230
+ const conversationConsole = createConsole({
3231
+ port: cfg.consolePort,
3232
+ stateRoot: store.root,
3233
+ host: consoleHost,
3234
+ version: pkg.version,
3235
+ log,
3236
+ })
3237
+ let consoleDisposed = false
3238
+ const stopConsole = () => {
3239
+ consoleDisposed = true
3240
+ return conversationConsole.stop().catch(error => log(`cannot stop the console: ${error?.message ?? error}`))
3241
+ }
3242
+ if (typeof ctx.effect === 'function') {
3243
+ ctx.effect(() => stopConsole, 'dsh-superagent console')
3244
+ } else if (typeof ctx.on === 'function') {
3245
+ ctx.on('dispose', stopConsole)
3246
+ }
3247
+ ready
3248
+ .then(() => {
3249
+ if (consoleDisposed || stateError) return null
3250
+ return conversationConsole.start()
3251
+ })
3252
+ .then(result => {
3253
+ if (!result) return
3254
+ log(`console is listening on ${result.url}; the one-time token is in ${conversationConsole.discoveryPath}`)
3255
+ })
3256
+ .catch(error => {
3257
+ log(
3258
+ `console is not listening: ${error?.message ?? error}; `
3259
+ + `check that consoleRoot (${consoleRoot}) exists, that consolePort is free, and that the state directory `
3260
+ + 'is writable, or remove consolePort to keep the console off',
3261
+ )
3262
+ })
3263
+ }
3264
+
3265
+ // A mounted plugin owns one timer; unmounting must not leave it firing into
3266
+ // a disposed orchestrator. The timer is unref'd, so it never keeps the host
3267
+ // alive on its own. Cleanup uses the dispose event rather than a second
3268
+ // effect: a host that exposes a single effect slot (as the plugin tests do)
3269
+ // must keep that slot for the control plane.
3270
+ const stopScheduler = () => {
3271
+ scheduler.stop()
3272
+ for (const handle of scheduleOwners) {
3273
+ handle.dispose().catch(error => log(`cannot dispose a scheduled-run session: ${error?.message ?? error}`))
3274
+ }
3275
+ scheduleOwners.clear()
3276
+ }
3277
+ if (typeof ctx.on === 'function') ctx.on('dispose', stopScheduler)
3278
+
2026
3279
  log(
2027
- `registered ${auditor ? 11 : 10} tools; state ${store.root}`
3280
+ `registered ${auditor ? 12 : 11} tools; state ${store.root}`
2028
3281
  + `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
2029
- + `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`,
3282
+ + `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`
3283
+ + `${cfg.consolePort === null ? '' : `; console on port ${cfg.consolePort}`}`,
2030
3284
  )
2031
3285
  }