@xiangyixie/dsh-superagent 0.14.2 → 0.14.4

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
@@ -10,12 +10,14 @@
10
10
  * Registered tools: superagent_start, superagent_status, superagent_list,
11
11
  * superagent_cancel, superagent_resume, superagent_followup, superagent_inject,
12
12
  * superagent_answer, superagent_memory, superagent_template, superagent_audit,
13
- * superagent_schedule.
13
+ * superagent_schedule, superagent_goal.
14
14
  *
15
15
  * @module dsh-superagent
16
16
  */
17
17
  import { randomUUID } from 'node:crypto'
18
- import { existsSync } from 'node:fs'
18
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
19
+ import fsp from 'node:fs/promises'
20
+ import { Script } from 'node:vm'
19
21
  import os from 'node:os'
20
22
  import path from 'node:path'
21
23
  import { fileURLToPath } from 'node:url'
@@ -34,16 +36,19 @@ import { createUserMemory, USER_MEMORY_CATEGORIES } from './user-memory.js'
34
36
  import { createNotifyPolicy, createOutbox } from './notify.js'
35
37
  import { createRuntimeControl } from './runtime-control.js'
36
38
  import { createScheduler, formatSchedule, formatScheduleList } from './schedule.js'
39
+ import { createLongGoalManager, formatStatus as formatLongGoal } from './long-goal.js'
37
40
  import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
38
41
  import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
39
42
  import { createUsageReader } from './usage.js'
40
43
  import { describeWorkspace } from './workspace.js'
41
44
  import { createRunChangeTracker, createWorkbench } from './workbench.js'
42
45
  import { createConsole } from './console.js'
46
+ import { createWizard } from './wizard.js'
47
+ import { createBoard } from './board.js'
43
48
 
44
49
  export const name = 'dsh-superagent'
45
50
  // The host menu and sessions are required. `subagents` is read through
46
- // `ctx.get('subagents')`, so a profile without it still mounts the twelve tools;
51
+ // `ctx.get('subagents')`, so a profile without it still mounts the thirteen tools;
47
52
  // they then report what is missing instead of the plugin silently vanishing.
48
53
  export const inject = ['tools', 'agents']
49
54
 
@@ -103,7 +108,7 @@ const DEFAULTS = {
103
108
  */
104
109
  plannerMaxModelCalls: 20,
105
110
  /** Upper bound on subtasks executing at once. */
106
- maxParallel: 3,
111
+ maxParallel: 4,
107
112
  /** Runs allowed to be active at the same time; a start over this waits instead of failing. */
108
113
  maxActiveRuns: 2,
109
114
  /** Runs allowed to wait for a free slot when queueing is on; 0 disables queueing. */
@@ -245,6 +250,14 @@ const DEFAULTS = {
245
250
  workspaceIsolation: false,
246
251
  /** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
247
252
  workspaceRoot: null,
253
+ /**
254
+ * Which directory isolation is based on. `session` (default) uses the calling
255
+ * session's cwd — or the repository root git resolves from it — because that
256
+ * is the directory the sandbox boundary and the merge target already agree
257
+ * on. `config` keeps the older behaviour and always uses `workspaceRoot`,
258
+ * which is only correct when it names the same repository as the session.
259
+ */
260
+ workspaceBase: 'session',
248
261
  /**
249
262
  * Loopback HTTP port for the local workspace panel. `null` (default) keeps it
250
263
  * off; `0` asks the OS for a free port. The bound address and its one-time
@@ -262,6 +275,18 @@ const DEFAULTS = {
262
275
  * token are written to `<stateDir>/console.json`.
263
276
  */
264
277
  consolePort: null,
278
+ /**
279
+ * Loopback HTTP port for the task board — one page showing every run as
280
+ * subtask cards, everything waiting for a person, and the built-in templates.
281
+ * `null` (default) keeps it off; `0` asks the OS for a free port. The bound
282
+ * address and its one-time token are written to `<stateDir>/board.json`.
283
+ */
284
+ boardPort: null,
285
+ /**
286
+ * Directory the board conversation joins, and where a template-started run
287
+ * works. Defaults to `consoleRoot`, then `workbenchRoot`, then the host cwd.
288
+ */
289
+ boardRoot: null,
265
290
  /**
266
291
  * Directory the console conversation joins. Defaults to `workbenchRoot`, then
267
292
  * the host process's working directory.
@@ -306,6 +331,34 @@ const DEFAULTS = {
306
331
 
307
332
  const REPORT_PREVIEW_CHARS = 8000
308
333
 
334
+ /**
335
+ * Read the arguments of the tool call an approval is blocking, so the page can
336
+ * name the exact path instead of paraphrasing the asker. Sessions keep the
337
+ * append-only event log; the call preceding the ask is the last matching
338
+ * `tool/call` record. Anything unreadable stays null — the card then falls back
339
+ * to the host's own reason, never to a guess.
340
+ *
341
+ * @param {object|undefined} session - the asking agent's session.
342
+ * @param {string|undefined} callId - the blocked tool call.
343
+ * @returns {string|null} the raw JSON arguments, or null when unavailable.
344
+ */
345
+ function blockedCallArguments(session, callId) {
346
+ if (!session || typeof callId !== 'string' || !callId) return null
347
+ try {
348
+ const events = typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : null
349
+ if (!Array.isArray(events)) return null
350
+ for (let index = events.length - 1; index >= 0; index -= 1) {
351
+ const event = events[index]
352
+ if (event?.type !== 'tool/call' || event.data?.callId !== callId) continue
353
+ const raw = event.data?.arguments
354
+ return typeof raw === 'string' ? raw : null
355
+ }
356
+ } catch {
357
+ return null
358
+ }
359
+ return null
360
+ }
361
+
309
362
  /**
310
363
  * Coerce one numeric setting into its documented range. A value like "abc"
311
364
  * would otherwise become NaN and silently remove a limit (NaN comparisons are
@@ -381,6 +434,10 @@ function resolveConfig(config) {
381
434
  merged.consoleRoot = typeof merged.consoleRoot === 'string' && merged.consoleRoot.trim()
382
435
  ? merged.consoleRoot.trim()
383
436
  : null
437
+ merged.boardPort = controlPortOf(merged.boardPort)
438
+ merged.boardRoot = typeof merged.boardRoot === 'string' && merged.boardRoot.trim()
439
+ ? merged.boardRoot.trim()
440
+ : null
384
441
  merged.consolePreset = typeof merged.consolePreset === 'string' && merged.consolePreset.trim()
385
442
  ? merged.consolePreset.trim()
386
443
  : null
@@ -433,6 +490,9 @@ function resolveConfig(config) {
433
490
  merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
434
491
  ? merged.workspaceRoot.trim()
435
492
  : null
493
+ // Anything but an explicit `config` keeps the session-following default, so a
494
+ // typo cannot silently point isolation back at a stale profile directory.
495
+ merged.workspaceBase = merged.workspaceBase === 'config' ? 'config' : 'session'
436
496
  // The guard block merges so a user can set only `allowCommands` without
437
497
  // restating the rest of the defaults.
438
498
  merged.guard = {
@@ -764,6 +824,11 @@ function formatRun(run, { includeReport = true } = {}) {
764
824
  }
765
825
  if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
766
826
  if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
827
+ if (run.budgetStop?.detail) {
828
+ // A budget stop explains why no further worker started; it is not a
829
+ // failure, so it never sits in the error line of a finished run.
830
+ lines.push(`note: stopped starting new workers — ${run.budgetStop.detail}; finished work was kept`)
831
+ }
767
832
  if (run.status === 'interrupted' && run.error) {
768
833
  // Not a failure: the host went away and the run is waiting to be resumed.
769
834
  lines.push(`note: ${run.error}`)
@@ -1029,6 +1094,7 @@ export function apply(ctx, config) {
1029
1094
  const configuredPort = config?.controlPort
1030
1095
  const configuredWorkbenchPort = config?.workbenchPort
1031
1096
  const configuredConsolePort = config?.consolePort
1097
+ const configuredBoardPort = config?.boardPort
1032
1098
  const cfg = resolveConfig(config)
1033
1099
  if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
1034
1100
  log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
@@ -1039,6 +1105,9 @@ export function apply(ctx, config) {
1039
1105
  if (configuredConsolePort !== undefined && configuredConsolePort !== null && cfg.consolePort === null) {
1040
1106
  log(`consolePort ${JSON.stringify(configuredConsolePort)} is not a whole number in 0–65535; the conversation console stays off`)
1041
1107
  }
1108
+ if (configuredBoardPort !== undefined && configuredBoardPort !== null && cfg.boardPort === null) {
1109
+ log(`boardPort ${JSON.stringify(configuredBoardPort)} is not a whole number in 0–65535; the task board stays off`)
1110
+ }
1042
1111
  if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
1043
1112
  console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
1044
1113
  return
@@ -1076,6 +1145,32 @@ export function apply(ctx, config) {
1076
1145
  // directory that is meant to be shipped byte-for-byte from git. Refuse rather
1077
1146
  // than rely on the `.gitignore` the notebook writes for itself.
1078
1147
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
1148
+ // The browser half joins a shared combo script served to every page load, so
1149
+ // one syntax error in it can take the whole host UI down with it. Compile it
1150
+ // here, before the client-modules service reads it, and fall back to a no-op
1151
+ // entry when it does not parse: the worst case is a missing sidebar row.
1152
+ try {
1153
+ const clientEntry = path.join(packageRoot, 'lib', 'client.js')
1154
+ if (existsSync(clientEntry)) {
1155
+ const source = readFileSync(clientEntry, 'utf8')
1156
+ try {
1157
+ new Script(source, { filename: clientEntry })
1158
+ } catch (error) {
1159
+ writeFileSync(`${clientEntry}.broken`, source, 'utf8')
1160
+ writeFileSync(
1161
+ clientEntry,
1162
+ `window.__ModuleLoader__.load({ id: ${JSON.stringify(pkg.name)}, factory: () => ({ apply() {} }) })\n`,
1163
+ 'utf8',
1164
+ )
1165
+ log(
1166
+ `the browser half did not compile (${error?.message ?? error}); `
1167
+ + `kept it as ${clientEntry}.broken and served a no-op so the host still boots`,
1168
+ )
1169
+ }
1170
+ }
1171
+ } catch (error) {
1172
+ log(`cannot verify the browser half: ${error?.message ?? error}`)
1173
+ }
1079
1174
  const memoryBlocked = isInside(store.root, packageRoot)
1080
1175
  const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
1081
1176
  // The user-level profile is a deliberate opt-in: it outlives tasks and records
@@ -1156,6 +1251,38 @@ export function apply(ctx, config) {
1156
1251
  }
1157
1252
  }
1158
1253
 
1254
+ // Tools alone do not tell a model when to use them. A session that mounts
1255
+ // `superagent_start` next to the host's `subagent` tool can hand-orchestrate
1256
+ // the work with the latter — three children, three report fragments, and no
1257
+ // run, no plan, no merged report, and nothing in the run list to look at.
1258
+ // This nudge is the only thing that states the policy, so it is injected
1259
+ // once per turn, at the first step of a top-level session.
1260
+ const GUIDANCE_SOURCE = { kind: 'superagent-guidance', form: 'notice', summary: '多步目标先起 run' }
1261
+ const GUIDANCE_TEXT = [
1262
+ '多步目标必须先用 superagent_start(mode="planned") 起一个 run:目标含两个及以上可独立交付物,',
1263
+ '或含“先做 A 才能做 B”的前置依赖时都算多步。之后用 superagent_followup 续,用 superagent_status 读报告。',
1264
+ '不要用宿主内置的 subagent 工具自己编排这些子任务——那样没有 run 记录、没有计划、没有合并报告。',
1265
+ '直接调用 superagent_start,不要先判断“当前有没有这个工具”;只有调用返回工具不存在时,才退回 subagent 并说明原因。',
1266
+ '只有单一动作(一次查找、一次编辑、一条命令、一段短文本)才直接做,不必起 run。',
1267
+ ].join('')
1268
+ if (typeof ctx.on === 'function') {
1269
+ ctx.on('agent/pre-step', async ({ agent, step }, next) => {
1270
+ const decision = await next()
1271
+ if (decision.kind === 'reject' || step !== 1) return decision
1272
+ const header = agent?.session?.header
1273
+ if (!header) return decision
1274
+ if ((header.delegationDepth ?? 0) > 0 || header.origin === 'subagent') return decision
1275
+ if (decision.messages.some(message => message?.source?.kind === GUIDANCE_SOURCE.kind)) return decision
1276
+ const guidance = {
1277
+ id: randomUUID(),
1278
+ role: 'user',
1279
+ content: [{ type: 'text', text: GUIDANCE_TEXT }],
1280
+ source: GUIDANCE_SOURCE,
1281
+ }
1282
+ return { ...decision, messages: [guidance, ...decision.messages] }
1283
+ })
1284
+ }
1285
+
1159
1286
  // Runtime control is opt-in. With `runtime.enabled` false nothing below is
1160
1287
  // registered, which is why a profile that never asked for browser or desktop
1161
1288
  // access sees exactly the same tool list as before this layer existed.
@@ -1190,7 +1317,7 @@ export function apply(ctx, config) {
1190
1317
  /**
1191
1318
  * The subagent service is optional, so it is read from the service store at
1192
1319
  * call time rather than declared as an injection: a profile without it must
1193
- * still mount the twelve tools (they then explain what is missing), and reading
1320
+ * still mount the thirteen tools (they then explain what is missing), and reading
1194
1321
  * it lazily also sees a service that registers after this plugin.
1195
1322
  */
1196
1323
  function getSubagents() {
@@ -1541,10 +1668,17 @@ export function apply(ctx, config) {
1541
1668
  : null
1542
1669
  let pending
1543
1670
  try {
1671
+ // dsh 0.2.2-rc.1 reads the delegation fields from `request`; 0.2.2-rc.3
1672
+ // (the desktop host) reads them from the spec itself. Sending only
1673
+ // `request` leaves the newer host's `spec.parent` undefined, and it
1674
+ // throws "Cannot read properties of undefined (reading 'id')" before
1675
+ // any child exists. Mirror both shapes; each host ignores the keys it
1676
+ // does not read.
1544
1677
  pending = subagents.startActivation({
1545
1678
  provider: cfg.provider,
1546
1679
  label,
1547
1680
  request,
1681
+ ...request,
1548
1682
  signal,
1549
1683
  delivery: 'caller',
1550
1684
  })
@@ -1589,8 +1723,27 @@ export function apply(ctx, config) {
1589
1723
  * @param {object} plan - plan whose window is firing.
1590
1724
  * @returns {Promise<object | {agent: object, sessionId: string} | null>} agent or agent+id.
1591
1725
  */
1592
- async function recoverScheduleOwner(plan) {
1726
+ async function recoverScheduleOwner(plan, label = 'schedule', options = {}) {
1593
1727
  const agents = getAgents()
1728
+ const session = getSessionController()
1729
+ // `agents.resume` reopens the transcript without the Session's agent
1730
+ // preset, so the agent it returns runs without the file and shell tools the
1731
+ // Session was created with. A long-goal phase hands its owner to child
1732
+ // agents, so it needs a fully composed owner: the session controller mounts
1733
+ // the recorded preset, which is why the goal path asks it first. Scheduled
1734
+ // runs keep the old order so their behaviour does not change.
1735
+ if (options.preferResolve && session && typeof session.resolveAgent === 'function') {
1736
+ try {
1737
+ const resolved = await session.resolveAgent(plan.ownerSessionId)
1738
+ if (resolved?.agent) {
1739
+ const registered = getAgents()?.get?.(plan.ownerSessionId)
1740
+ return registered ?? resolved.agent
1741
+ }
1742
+ if (resolved?.error) log(`${label} ${plan.id}: cannot open session ${plan.ownerSessionId}: ${resolved.error}`)
1743
+ } catch (error) {
1744
+ log(`${label} ${plan.id}: cannot open session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1745
+ }
1746
+ }
1594
1747
  if (agents && typeof agents.resume === 'function') {
1595
1748
  try {
1596
1749
  const handle = await agents.resume({ resumeSessionId: plan.ownerSessionId })
@@ -1599,17 +1752,16 @@ export function apply(ctx, config) {
1599
1752
  return handle.agent
1600
1753
  }
1601
1754
  } catch (error) {
1602
- log(`schedule ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1755
+ log(`${label} ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1603
1756
  }
1604
1757
  }
1605
- const session = getSessionController()
1606
1758
  if (session && typeof session.resolveAgent === 'function') {
1607
1759
  const resolved = await session.resolveAgent(plan.ownerSessionId)
1608
1760
  if (resolved?.agent) {
1609
1761
  const registered = getAgents()?.get?.(plan.ownerSessionId)
1610
1762
  return registered ?? resolved.agent
1611
1763
  }
1612
- if (resolved?.error) log(`schedule ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${resolved.error}`)
1764
+ if (resolved?.error) log(`${label} ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${resolved.error}`)
1613
1765
  }
1614
1766
  if (agents && typeof agents.create === 'function') {
1615
1767
  const sessionId = randomUUID()
@@ -1623,7 +1775,7 @@ export function apply(ctx, config) {
1623
1775
  return { agent: handle.agent, sessionId }
1624
1776
  }
1625
1777
  } catch (error) {
1626
- log(`schedule ${plan.id}: cannot create a replacement session: ${error?.message ?? error}`)
1778
+ log(`${label} ${plan.id}: cannot create a replacement session: ${error?.message ?? error}`)
1627
1779
  }
1628
1780
  }
1629
1781
  if (session && typeof session.create === 'function') {
@@ -1637,7 +1789,7 @@ export function apply(ctx, config) {
1637
1789
  if (resolved?.agent) return { agent: resolved.agent, sessionId }
1638
1790
  }
1639
1791
  }
1640
- log(`schedule ${plan.id}: the host could not create a replacement session`)
1792
+ log(`${label} ${plan.id}: the host could not create a replacement session`)
1641
1793
  }
1642
1794
  return null
1643
1795
  }
@@ -1684,6 +1836,54 @@ export function apply(ctx, config) {
1684
1836
  warn: log,
1685
1837
  })
1686
1838
 
1839
+ // A long-term goal is a thin layer above runs: each phase is a normal run.
1840
+ // The manager only owns the phase graph, the goal budget, and the decisions
1841
+ // that a phase cannot make by itself. Keeping it behind the orchestrator API
1842
+ // means it inherits every run-side guarantee (locks, persistence, resume).
1843
+ const longGoal = createLongGoalManager({
1844
+ root: store.root,
1845
+ orchestrator: {
1846
+ start: args => orchestrator.start(args),
1847
+ status: runId => orchestrator.status(runId),
1848
+ resume: (runId, parent, clientTimeZone) => orchestrator.resume(runId, parent, clientTimeZone),
1849
+ cancel: runId => orchestrator.cancel(runId),
1850
+ answer: (runId, attentionId, answer, agent, clientTimeZone) =>
1851
+ orchestrator.answer(runId, attentionId, answer, agent, clientTimeZone),
1852
+ },
1853
+ async resolveOwner(goal) {
1854
+ const live = getAgents()?.get?.(goal.ownerSessionId)
1855
+ if (live && typeof live === 'object') return live
1856
+ return recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
1857
+ },
1858
+ async notify({ goal, message }) {
1859
+ let agent = getAgents()?.get?.(goal.ownerSessionId)
1860
+ if (!agent) {
1861
+ const recovered = await recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
1862
+ agent = recovered?.agent ?? recovered ?? null
1863
+ }
1864
+ if (!agent || typeof agent.followup !== 'function') {
1865
+ log(`long-goal ${goal.id} has no live session ${goal.ownerSessionId} to notify`)
1866
+ return { delivered: false }
1867
+ }
1868
+ await outbox.enqueue(goal.ownerSessionId, () => agent.followup({
1869
+ id: randomUUID(),
1870
+ role: 'user',
1871
+ content: [{ type: 'text', text: message }],
1872
+ source: { kind: 'user' },
1873
+ }))
1874
+ return { delivered: true }
1875
+ },
1876
+ config: {
1877
+ phaseBudget: {
1878
+ maxModelCalls: cfg.maxModelCallsPerRun,
1879
+ maxTokens: cfg.maxTokensPerRun,
1880
+ },
1881
+ },
1882
+ log,
1883
+ now: () => Date.now(),
1884
+ tickSeconds: 5,
1885
+ })
1886
+
1687
1887
  // Recovery runs once at mount; tools wait for it so a run left active by a
1688
1888
  // dead host reads as interrupted before the first tool call sees it. A
1689
1889
  // failure to initialize the state directory is kept and reported by every
@@ -1726,6 +1926,15 @@ export function apply(ctx, config) {
1726
1926
  } catch (error) {
1727
1927
  log(`cannot load scheduled runs from ${scheduler.stateFile}: ${error?.message ?? error}`)
1728
1928
  }
1929
+ // Long goals survive the host on their own: init marks the phases that were
1930
+ // mid-run as resumable and the manager continues them on its next tick.
1931
+ try {
1932
+ const goals = await longGoal.init()
1933
+ const active = goals.filter(item => ['planning', 'running', 'paused'].includes(item.status)).length
1934
+ if (goals.length > 0) log(`long goals: ${goals.length} loaded, ${active} to continue`)
1935
+ } catch (error) {
1936
+ log(`cannot load long goals: ${error?.message ?? error}`)
1937
+ }
1729
1938
  if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
1730
1939
  try {
1731
1940
  const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
@@ -1802,6 +2011,8 @@ export function apply(ctx, config) {
1802
2011
  + 'Pass mode "direct" for a single self-contained task instead: one worker does it, there is no planner '
1803
2012
  + 'or aggregator, and its reply is the report verbatim — use it for one lookup, one edit, one query, or '
1804
2013
  + 'one short piece of writing, not for a goal with parts that can be worked in parallel. '
2014
+ + 'Prefer this over the built-in subagent tool whenever the goal has several deliverables or a '
2015
+ + 'declared prerequisite step: only a run keeps the plan, the parallel timing, and one merged report. '
1805
2016
  + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
1806
2017
  + 'so they survive a host restart and can be resumed or cancelled.',
1807
2018
  properties: {
@@ -1941,6 +2152,228 @@ export function apply(ctx, config) {
1941
2152
  },
1942
2153
  }))
1943
2154
 
2155
+ ctx.tools.register(defineTool({
2156
+ name: 'superagent_goal',
2157
+ description:
2158
+ 'Run a long-term goal as several phases. A natural-language goal is split into 2–8 phases by a phase planner, '
2159
+ + 'or you can pass the phases explicitly. Each phase is a normal run with its own planner and parallel workers; '
2160
+ + 'independent phases run at the same time; later phases receive the earlier phases\' reports. The goal record is '
2161
+ + 'persisted, so after a host restart it resumes the interrupted phase instead of starting over. A phase that '
2162
+ + 'keeps failing, or a goal that stops making progress, opens a decision that a person answers with action '
2163
+ + '"answer" — no goal-level question is guessed by the model. Per-phase and whole-goal model budgets are hard '
2164
+ + 'stops. Use superagent_status/superagent_cancel on the phase run ids it reports. Prefer this over '
2165
+ + 'superagent_start when the work has milestones that must happen in order over a long horizon.',
2166
+ properties: {
2167
+ action: {
2168
+ type: 'string',
2169
+ enum: ['create', 'status', 'list', 'answer', 'resume', 'pause', 'cancel'],
2170
+ description: 'create a goal, read one, list them, answer an open decision, resume/pause/cancel the goal.',
2171
+ },
2172
+ goal_id: { type: 'string', description: 'Goal id returned by action=create; required except for create/list.' },
2173
+ goal: {
2174
+ type: 'string',
2175
+ description: 'create: the complete long-term outcome. Be concrete about the finished state and where the work lives.',
2176
+ },
2177
+ phases: {
2178
+ type: 'array',
2179
+ description: 'create: optional explicit phases. Omit to let the phase planner split the goal. Each item is '
2180
+ + '{id?, title, objective, depends_on?, acceptance?, max_rounds?, max_wall_clock_minutes?, deliverables?}. '
2181
+ + 'acceptance uses the same {text, check?} shape as superagent_start; at least one condition per phase.',
2182
+ items: {
2183
+ type: 'object',
2184
+ properties: {
2185
+ id: { type: 'string', description: 'Short id, e.g. "p1"; unique and referenced by depends_on.' },
2186
+ title: { type: 'string', description: 'Short name shown in the phase table.' },
2187
+ objective: { type: 'string', description: 'What this phase must produce; later phases read its report.' },
2188
+ depends_on: {
2189
+ type: 'array',
2190
+ items: { type: 'string' },
2191
+ description: 'Phase ids that must complete before this one starts. Omit for independent phases.',
2192
+ },
2193
+ acceptance: {
2194
+ type: 'array',
2195
+ items: {
2196
+ type: 'object',
2197
+ properties: {
2198
+ id: { type: 'string' },
2199
+ text: { type: 'string' },
2200
+ check: {
2201
+ type: 'object',
2202
+ properties: {
2203
+ type: { type: 'string', enum: ['command', 'file'] },
2204
+ command: { type: 'string' },
2205
+ cwd: { type: 'string' },
2206
+ timeout_seconds: { type: 'number' },
2207
+ path: { type: 'string' },
2208
+ must_exist: { type: 'boolean' },
2209
+ },
2210
+ required: ['type'],
2211
+ },
2212
+ },
2213
+ required: ['text'],
2214
+ },
2215
+ },
2216
+ max_rounds: { type: 'number', description: 'Rounds this phase may retry before it stops (default 3).' },
2217
+ max_wall_clock_minutes: { type: 'number', description: 'Wall-clock cap for this phase (default 120).' },
2218
+ deliverables: { type: 'array', items: { type: 'string' }, description: 'Optional paths to report.' },
2219
+ },
2220
+ required: ['objective'],
2221
+ },
2222
+ },
2223
+ cwd: { type: 'string', description: 'Workspace every phase and every machine check runs in (default: current cwd).' },
2224
+ max_parallel_phases: { type: 'number', description: 'Phases allowed in flight at once (default 2, max 8).' },
2225
+ max_attempts_per_phase: {
2226
+ type: 'number',
2227
+ description: 'Attempts per phase before it asks a person (default 2). Attempts also require a different '
2228
+ + 'failure signature; an identical no-change failure stops earlier.',
2229
+ },
2230
+ max_rounds_per_phase: { type: 'number', description: 'Default goal-mode rounds inside one phase run (default 3).' },
2231
+ no_progress_rounds: { type: 'number', description: 'Goal mode: identical failing rounds before a phase stops (default 2).' },
2232
+ phase_budget: {
2233
+ type: 'object',
2234
+ description: 'Per-phase-run hard cap. Narrows to what remains of the goal budget.',
2235
+ properties: {
2236
+ max_model_calls: { type: 'number' },
2237
+ max_tokens: { type: 'number' },
2238
+ },
2239
+ },
2240
+ budget: {
2241
+ type: 'object',
2242
+ description: 'Whole-goal hard cap across every phase and retry; reaching it stops the goal.',
2243
+ properties: {
2244
+ max_model_calls: { type: 'number' },
2245
+ max_tokens: { type: 'number' },
2246
+ },
2247
+ },
2248
+ max_wall_clock_minutes: { type: 'number', description: 'Whole-goal wall-clock cap before it stalls (default 1440).' },
2249
+ stall_after_minutes: {
2250
+ type: 'number',
2251
+ description: 'No completed phase for this long opens a stall decision (default 180).',
2252
+ },
2253
+ auto_resume: {
2254
+ type: 'boolean',
2255
+ description: 'Continue automatically after a host restart (default true). false leaves it paused for a person.',
2256
+ },
2257
+ decision_id: { type: 'string', description: 'answer: the id shown in action=status.' },
2258
+ answer: {
2259
+ type: 'string',
2260
+ description: 'answer: one of the decision options. retry starts a fresh attempt for the phase; skip cascades '
2261
+ + 'to dependents; stop ends the goal; continue resets a stall; answer (worker question) needs note.',
2262
+ },
2263
+ note: {
2264
+ type: 'string',
2265
+ description: 'answer: a new instruction for retry, or the actual answer text for a worker question.',
2266
+ },
2267
+ limit: { type: 'number', description: 'list: maximum rows (default 20).' },
2268
+ },
2269
+ required: ['action'],
2270
+ async execute(args = {}, exec) {
2271
+ const check = requireAgent(exec)
2272
+ if (check.error) return check.error
2273
+ try {
2274
+ await ready
2275
+ if (stateError) return describeError(stateError)
2276
+ const action = String(args.action ?? '').trim().toLowerCase()
2277
+ if (action === 'create') {
2278
+ const phases = Array.isArray(args.phases)
2279
+ ? args.phases.map(entry => ({
2280
+ id: entry?.id,
2281
+ title: entry?.title,
2282
+ objective: entry?.objective,
2283
+ dependsOn: entry?.depends_on ?? entry?.dependsOn,
2284
+ acceptance: Array.isArray(entry?.acceptance)
2285
+ ? entry.acceptance.map(acceptanceFromToolArgs)
2286
+ : entry?.acceptance,
2287
+ maxRounds: entry?.max_rounds ?? entry?.maxRounds,
2288
+ maxWallClockMinutes: entry?.max_wall_clock_minutes ?? entry?.maxWallClockMinutes,
2289
+ deliverables: entry?.deliverables,
2290
+ }))
2291
+ : undefined
2292
+ const created = await longGoal.create({
2293
+ goal: args.goal,
2294
+ phases,
2295
+ cwd: args.cwd,
2296
+ maxParallelPhases: args.max_parallel_phases,
2297
+ maxAttemptsPerPhase: args.max_attempts_per_phase,
2298
+ maxRoundsPerPhase: args.max_rounds_per_phase,
2299
+ noProgressRounds: args.no_progress_rounds,
2300
+ phaseBudget: args.phase_budget
2301
+ ? {
2302
+ maxModelCalls: args.phase_budget.max_model_calls,
2303
+ maxTokens: args.phase_budget.max_tokens,
2304
+ }
2305
+ : undefined,
2306
+ budget: args.budget
2307
+ ? { maxModelCalls: args.budget.max_model_calls, maxTokens: args.budget.max_tokens }
2308
+ : undefined,
2309
+ maxWallClockMinutes: args.max_wall_clock_minutes,
2310
+ stallAfterMinutes: args.stall_after_minutes,
2311
+ autoResume: args.auto_resume,
2312
+ parentSessionId: check.agent.id,
2313
+ })
2314
+ const { goal, runs } = await longGoal.status(created.id)
2315
+ return `${formatLongGoal(goal, runs)}\n\nCreated in the background. Poll with `
2316
+ + `superagent_goal action=status goal_id=${goal.id}; phase runs continue after this call.`
2317
+ }
2318
+ if (action === 'list') {
2319
+ const limit = Math.max(1, Math.min(100, Number(args.limit) || 20))
2320
+ const goals = (await longGoal.list()).slice(0, limit)
2321
+ if (goals.length === 0) return 'No long-term goals recorded.'
2322
+ return goals.map(goal => {
2323
+ const phases = goal.phases ?? []
2324
+ const done = phases.filter(phase => phase.status === 'completed').length
2325
+ return `- ${goal.id} [${goal.status}] ${done}/${phases.length} phases — ${String(goal.goal).slice(0, 120)}`
2326
+ }).join('\n')
2327
+ }
2328
+ const goalId = String(args.goal_id ?? '').trim()
2329
+ if (!goalId) return describeError(`action=${action} requires goal_id`)
2330
+ if (action === 'status') {
2331
+ const { goal, runs } = await longGoal.status(goalId)
2332
+ return formatLongGoal(goal, runs)
2333
+ }
2334
+ if (action === 'answer') {
2335
+ const goal = await longGoal.answer(
2336
+ goalId,
2337
+ String(args.decision_id ?? '').trim(),
2338
+ args.answer,
2339
+ { note: args.note, parent: check.agent, clientTimeZone: exec.clientTimeZone },
2340
+ )
2341
+ const { goal: fresh, runs } = await longGoal.status(goal.id)
2342
+ return formatLongGoal(fresh, runs)
2343
+ }
2344
+ if (action === 'resume') {
2345
+ await longGoal.resume(goalId)
2346
+ } else if (action === 'pause') {
2347
+ await longGoal.pause(goalId)
2348
+ } else if (action === 'cancel') {
2349
+ await longGoal.cancel(goalId)
2350
+ } else {
2351
+ return describeError(`unknown action ${JSON.stringify(action)}`)
2352
+ }
2353
+ const { goal, runs } = await longGoal.status(goalId)
2354
+ return formatLongGoal(goal, runs)
2355
+ } catch (error) {
2356
+ return describeError(error)
2357
+ }
2358
+ },
2359
+ }))
2360
+
2361
+ // Files on disk can be newer than the code this host loaded: a package update
2362
+ // only takes effect after DSH restarts. Surface the mismatch instead of
2363
+ // letting the user wonder why the new version behaves like the old one.
2364
+ async function restartNotice() {
2365
+ try {
2366
+ const onDisk = JSON.parse(await fsp.readFile(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'))
2367
+ if (onDisk.version && onDisk.version !== pkg.version) {
2368
+ return `\n\nnote: package files on disk are ${onDisk.version} but this host is still running `
2369
+ + `${pkg.version} — restart DSH to load the new version.`
2370
+ }
2371
+ } catch {
2372
+ // Best effort: a status read must not fail because of this check.
2373
+ }
2374
+ return ''
2375
+ }
2376
+
1944
2377
  ctx.tools.register(defineTool({
1945
2378
  name: 'superagent_status',
1946
2379
  description:
@@ -1957,7 +2390,7 @@ export function apply(ctx, config) {
1957
2390
  if (stateError) return describeError(stateError)
1958
2391
  const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
1959
2392
  await recordSpend([run])
1960
- return formatRun(run)
2393
+ return `${formatRun(run)}${await restartNotice()}`
1961
2394
  } catch (error) {
1962
2395
  return describeError(error)
1963
2396
  }
@@ -2981,6 +3414,7 @@ export function apply(ctx, config) {
2981
3414
  // host has no session service the page is told so; it is never a mock chat.
2982
3415
  if (cfg.consolePort !== null) {
2983
3416
  const consoleRoot = cfg.consoleRoot ? path.resolve(cfg.consoleRoot) : workbenchRoot
3417
+ const CONSOLE_SPACE_ID = 'superagent-console-space'
2984
3418
 
2985
3419
  function consoleCapabilities() {
2986
3420
  const session = getSessionController()
@@ -3000,6 +3434,38 @@ export function apply(ctx, config) {
3000
3434
  return { chat: true, reason: null }
3001
3435
  }
3002
3436
 
3437
+ function consoleService(name) {
3438
+ if (typeof ctx.get === 'function') {
3439
+ const service = ctx.get(name)
3440
+ if (service) return service
3441
+ }
3442
+ try {
3443
+ return ctx[name]
3444
+ } catch {
3445
+ return undefined
3446
+ }
3447
+ }
3448
+
3449
+ // The wizard edits the profile's own patch layer and hands the key to the
3450
+ // host credential store. It never writes a secret into the profile file.
3451
+ const wizard = createWizard({
3452
+ stateRoot: store.root,
3453
+ version: pkg.version,
3454
+ log,
3455
+ pricing: cfg.pricing,
3456
+ getProfile: () => consoleService('profileContext') ?? null,
3457
+ getCredentials: () => consoleService('credentials'),
3458
+ getDefaultModel: () => {
3459
+ const service = consoleService('agentDefaultModel')
3460
+ if (!service) return null
3461
+ if (typeof service.currentSelection === 'function') return service.currentSelection()
3462
+ return service.selection ?? null
3463
+ },
3464
+ getSessionController,
3465
+ listTools: sessionId => consoleHost.listTools(sessionId),
3466
+ fetchImpl: typeof fetch === 'function' ? fetch : undefined,
3467
+ })
3468
+
3003
3469
  /** The conversation agent is the owner of every run it starts. */
3004
3470
  function conversationAgent(sessionId) {
3005
3471
  const agents = getAgents()
@@ -3068,14 +3534,43 @@ export function apply(ctx, config) {
3068
3534
  const consoleHost = {
3069
3535
  capabilities: consoleCapabilities,
3070
3536
 
3537
+ async wizardStatus(options = {}) {
3538
+ return wizard.status(options)
3539
+ },
3540
+
3541
+ async wizardPreview(body = {}) {
3542
+ return wizard.preview(body)
3543
+ },
3544
+
3545
+ async wizardSave(body = {}) {
3546
+ return wizard.save(body)
3547
+ },
3548
+
3549
+ async wizardRollback(id) {
3550
+ return wizard.rollback(id)
3551
+ },
3552
+
3553
+ async wizardTrial() {
3554
+ return wizard.trial()
3555
+ },
3556
+
3071
3557
  async createSession() {
3072
3558
  const caps = consoleCapabilities()
3073
3559
  if (!caps.chat) throw new Error(caps.reason)
3074
3560
  const session = getSessionController()
3075
- const created = await session.create({
3561
+ const base = {
3076
3562
  cwd: consoleRoot,
3077
3563
  ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3078
- })
3564
+ }
3565
+ // A fixed identity makes the console its own space: the same
3566
+ // conversation is reused on the next host start instead of a new chat,
3567
+ // and it stays separate from the sessions the user starts themselves.
3568
+ let created
3569
+ try {
3570
+ created = await session.create({ ...base, sessionId: CONSOLE_SPACE_ID })
3571
+ } catch {
3572
+ created = await session.create(base)
3573
+ }
3079
3574
  if (!created || typeof created.sessionId !== 'string' || !created.sessionId) {
3080
3575
  throw new Error('sessionController.create returned no sessionId')
3081
3576
  }
@@ -3260,6 +3755,483 @@ export function apply(ctx, config) {
3260
3755
  + 'is writable, or remove consolePort to keep the console off',
3261
3756
  )
3262
3757
  })
3758
+
3759
+ // Approvals asked inside this console's own conversation tree are put to the
3760
+ // person in the page; everything else keeps the host's normal answerer chain.
3761
+ // The bridge only relays the question — it never decides, and it fails closed
3762
+ // when no page is open, so nothing here widens what a tool may do.
3763
+ //
3764
+ // Registration is prepended and lives on the root event bus: the Web
3765
+ // assembly forwards `approval/request` to connected clients through its own
3766
+ // waterfall listener, and a listener that never calls `next()` would win by
3767
+ // order alone. Answering our own sessions first is what routes this tree's
3768
+ // ask to this page; every other session still falls through untouched.
3769
+ const approvalCtx = (ctx.root && typeof ctx.root.on === 'function') ? ctx.root : ctx
3770
+ const bridgeApproval = (request, next) => {
3771
+ try {
3772
+ const session = request?.agent?.session
3773
+ // The console owns whichever session it created this run (the fixed space
3774
+ // id, or a fresh id when the host refuses that one), so the live id is read
3775
+ // back from the console instead of assumed.
3776
+ const consoleSessionId = conversationConsole.sessionId
3777
+ const belongs = id => typeof id === 'string'
3778
+ && (id === CONSOLE_SPACE_ID || (typeof consoleSessionId === 'string' && id === consoleSessionId))
3779
+ const parent = (() => {
3780
+ const raw = session?.parentSession
3781
+ return typeof raw === 'string' ? raw : raw?.id
3782
+ })()
3783
+ if (!belongs(session?.id) && !belongs(parent)) return next()
3784
+ if (typeof conversationConsole.askApproval !== 'function') return next()
3785
+ return conversationConsole.askApproval({
3786
+ toolName: request?.toolName,
3787
+ callId: request?.callId ?? null,
3788
+ reason: request?.reason ?? null,
3789
+ displayReason: request?.displayReason ?? null,
3790
+ agentId: request?.agent?.id ?? null,
3791
+ callArguments: blockedCallArguments(session, request?.callId),
3792
+ source: belongs(session?.id) ? '主对话' : '子任务线',
3793
+ })
3794
+ } catch (error) {
3795
+ // A bridge that cannot even read the ask must not decide it: falling
3796
+ // through leaves the host's own answerers in charge (fail closed).
3797
+ log(`approval bridge skipped one ask: ${error?.message ?? error}`)
3798
+ return next()
3799
+ }
3800
+ }
3801
+ if (typeof approvalCtx.on === 'function') {
3802
+ try {
3803
+ if (typeof ctx.effect === 'function') {
3804
+ ctx.effect(() => approvalCtx.on('approval/request', bridgeApproval, { prepend: true }), 'dsh-superagent approval bridge')
3805
+ } else {
3806
+ const off = approvalCtx.on('approval/request', bridgeApproval, { prepend: true })
3807
+ if (typeof off === 'function' && typeof ctx.on === 'function') {
3808
+ ctx.on('dispose', () => {
3809
+ try {
3810
+ off()
3811
+ } catch {
3812
+ // the bus is already gone; nothing left to release
3813
+ }
3814
+ })
3815
+ }
3816
+ }
3817
+ } catch (error) {
3818
+ log(`cannot listen for approvals: ${error?.message ?? error}`)
3819
+ }
3820
+ }
3821
+
3822
+ // The browser half seats this console in the host's main panel. That frame
3823
+ // cannot read the discovery file, so one loopback route on the host's own
3824
+ // origin hands out the address and the one-time token. The path stays
3825
+ // outside `/api`: that prefix belongs to the connection gate, which answers
3826
+ // every unrouted request before plugin routes can see it. Registering this
3827
+ // is best-effort — a profile without a web server keeps every tool working
3828
+ // and the panel simply reports the console as unavailable.
3829
+ // `webServer` may mount after this plugin, so the route waits for it
3830
+ // through the loader's inject rather than reading it once at apply time.
3831
+ if (typeof ctx.inject === 'function') {
3832
+ ctx.inject(['webServer'], webCtx => {
3833
+ try {
3834
+ webCtx.effect(() => webCtx.webServer.register({
3835
+ kind: 'exact',
3836
+ path: '/superagent/console-address',
3837
+ handler: (req, res) => {
3838
+ if ((req.method ?? 'GET') !== 'GET') {
3839
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
3840
+ res.end(JSON.stringify({ ok: false, message: 'only GET is allowed here' }))
3841
+ return
3842
+ }
3843
+ const address = conversationConsole.url
3844
+ res.writeHead(200, {
3845
+ 'content-type': 'application/json; charset=utf-8',
3846
+ 'cache-control': 'no-store',
3847
+ })
3848
+ res.end(JSON.stringify({
3849
+ ok: true,
3850
+ data: {
3851
+ ready: Boolean(address),
3852
+ url: address,
3853
+ token: conversationConsole.token,
3854
+ reason: address ? null : 'the console is not listening yet; check consolePort and the state directory',
3855
+ },
3856
+ }))
3857
+ },
3858
+ }), 'dsh-superagent console address')
3859
+ } catch (error) {
3860
+ log(`cannot publish the console address route: ${error?.message ?? error}`)
3861
+ }
3862
+ })
3863
+ } else {
3864
+ log('this host has no inject(); the sidebar entry reports the console as unavailable')
3865
+ }
3866
+ }
3867
+
3868
+ // The task board is the third loopback surface, and the first one written for
3869
+ // a person who does not read JSON. It never owns a run: every action resolves
3870
+ // the run's owning session and calls the same orchestrator method a tool call
3871
+ // would. On a host without a session service it still shows every run and
3872
+ // says, in Chinese, why its buttons are unavailable.
3873
+ if (cfg.boardPort !== null) {
3874
+ const boardRoot = cfg.boardRoot
3875
+ ? path.resolve(cfg.boardRoot)
3876
+ : cfg.consoleRoot
3877
+ ? path.resolve(cfg.consoleRoot)
3878
+ : workbenchRoot
3879
+ const boardSessionFile = path.join(store.root, 'board-session.json')
3880
+
3881
+ const timeZoneOf = () => {
3882
+ try {
3883
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
3884
+ } catch {
3885
+ return undefined
3886
+ }
3887
+ }
3888
+
3889
+ function boardCapabilities() {
3890
+ const session = getSessionController()
3891
+ if (!session) {
3892
+ return {
3893
+ start: false,
3894
+ answer: false,
3895
+ reason: '宿主没有挂载 sessionController,看板只能查看运行,不能替你回答或继续。',
3896
+ }
3897
+ }
3898
+ const missing = ['create', 'resolveAgent'].filter(name => typeof session[name] !== 'function')
3899
+ if (missing.length > 0) {
3900
+ return {
3901
+ start: false,
3902
+ answer: false,
3903
+ reason: `sessionController 缺少 ${missing.join(' / ')},看板只能查看运行。`,
3904
+ }
3905
+ }
3906
+ if (!hasSubagents()) {
3907
+ return {
3908
+ start: false,
3909
+ answer: false,
3910
+ reason: '宿主没有 subagents 服务,无法从看板发起运行;查看和取消仍然可用。',
3911
+ }
3912
+ }
3913
+ return { start: true, answer: true, reason: null }
3914
+ }
3915
+
3916
+ /** Prefer the live agent; reopen the session only when it is not loaded. */
3917
+ async function resolveAgentById(sessionId) {
3918
+ if (!sessionId) return null
3919
+ const live = getAgents()?.get?.(sessionId)
3920
+ if (live) return live
3921
+ const session = getSessionController()
3922
+ if (!session || typeof session.resolveAgent !== 'function') return null
3923
+ try {
3924
+ return (await session.resolveAgent(sessionId))?.agent ?? null
3925
+ } catch {
3926
+ return null
3927
+ }
3928
+ }
3929
+
3930
+ /**
3931
+ * The board's own session, persisted so a host restart does not orphan
3932
+ * runs it started. A run's owner must stay the same session; that is why
3933
+ * this is a real session and not a synthetic agent.
3934
+ */
3935
+ async function boardSessionAgent() {
3936
+ const caps = boardCapabilities()
3937
+ if (!caps.start) throw new Error(caps.reason)
3938
+ let saved = null
3939
+ try {
3940
+ saved = JSON.parse(await fsp.readFile(boardSessionFile, 'utf8'))?.sessionId ?? null
3941
+ } catch {
3942
+ // First use, or a state directory that was cleaned.
3943
+ }
3944
+ let agent = await resolveAgentById(saved)
3945
+ if (agent) return agent
3946
+ const created = await getSessionController().create({
3947
+ cwd: boardRoot,
3948
+ ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3949
+ })
3950
+ const sessionId = typeof created?.sessionId === 'string' ? created.sessionId : ''
3951
+ if (!sessionId) throw new Error('sessionController.create 没有返回 sessionId,无法从看板发起运行')
3952
+ await fsp.mkdir(path.dirname(boardSessionFile), { recursive: true })
3953
+ await fsp.writeFile(
3954
+ boardSessionFile,
3955
+ `${JSON.stringify({ sessionId, createdAt: new Date().toISOString() }, null, 2)}\n`,
3956
+ 'utf8',
3957
+ )
3958
+ agent = await resolveAgentById(sessionId)
3959
+ if (!agent) {
3960
+ throw new Error('看板会话已经创建,但宿主没有把它变成可用 agent;请先在宿主里打开一次这个会话,再回来启动')
3961
+ }
3962
+ return agent
3963
+ }
3964
+
3965
+ async function runOwnerAgent(run) {
3966
+ const agent = await resolveAgentById(run?.parentSessionId)
3967
+ if (!agent) {
3968
+ throw new Error(
3969
+ '这次运行的发起会话已经关闭,看板不能替你继续;请在宿主里重新打开那个会话,'
3970
+ + '或用 superagent_resume 从新会话恢复。',
3971
+ )
3972
+ }
3973
+ return agent
3974
+ }
3975
+
3976
+ /**
3977
+ * Items that are not on a run record: a policy that held an operation for
3978
+ * confirmation, and a browser that stopped on a check only a person can do.
3979
+ */
3980
+ async function boardExtraInbox() {
3981
+ if (!auditor) return []
3982
+ let events = []
3983
+ try {
3984
+ events = (await auditor.query({ limit: 600, order: 'desc' })).events ?? []
3985
+ } catch (error) {
3986
+ log(`board: cannot read the audit trail: ${error?.message ?? error}`)
3987
+ return []
3988
+ }
3989
+ let runs = []
3990
+ try {
3991
+ runs = await store.list()
3992
+ } catch {
3993
+ // The run cards already cover this; the extras can stand without a goal.
3994
+ }
3995
+ const byId = new Map(runs.map(run => [run.id, run]))
3996
+ const approved = new Set(events
3997
+ .filter(event => event.kind === 'approved')
3998
+ .map(event => event.meta?.approves)
3999
+ .filter(Boolean))
4000
+ const items = []
4001
+ const seen = new Set()
4002
+ for (const event of events) {
4003
+ if (items.length >= 8) break
4004
+ if (event.decision === 'confirm' && event.result === 'pending' && !approved.has(event.id)) {
4005
+ const id = `permission:${event.id}`
4006
+ if (seen.has(id)) continue
4007
+ seen.add(id)
4008
+ items.push({
4009
+ id,
4010
+ kind: 'permission',
4011
+ kindLabel: '需要你授权',
4012
+ runId: event.runId ?? null,
4013
+ runGoal: event.runId ? byId.get(event.runId)?.goal ?? null : null,
4014
+ title: '有一个操作被权限策略拦下,等你点头',
4015
+ what: `被拦下的操作:${event.kind ?? '操作'} / ${event.action ?? ''}`
4016
+ + `${event.target ? ` → ${String(event.target).slice(0, 200)}` : ''}`,
4017
+ why: '策略要求人来确认这一次。它不是故障;拒绝也不会影响其他运行。',
4018
+ options: ['允许这次操作', '不允许'],
4019
+ impact: '允许后这一次操作会被放行,并记录是谁在什么时候批准的;不允许则保持拦截。',
4020
+ input: 'choice',
4021
+ canAnswer: true,
4022
+ })
4023
+ continue
4024
+ }
4025
+ if (event.kind !== 'attention' || event.result !== 'needs-human') continue
4026
+ const cleared = events.some(other => other.runId === event.runId
4027
+ && String(other.at ?? '') > String(event.at ?? '')
4028
+ && /await_human/i.test(String(other.action ?? '')))
4029
+ if (cleared) continue
4030
+ const id = `human:${event.runId}:${event.id}`
4031
+ if (seen.has(id) || !event.runId) continue
4032
+ seen.add(id)
4033
+ const goal = byId.get(event.runId)?.goal ?? null
4034
+ items.push({
4035
+ id,
4036
+ kind: 'human',
4037
+ kindLabel: '需要你亲自操作',
4038
+ runId: event.runId,
4039
+ runGoal: goal,
4040
+ title: '浏览器停在一个需要人完成的检查上',
4041
+ what: `运行${goal ? `「${String(goal).slice(0, 100)}」` : ''}停住了:${String(event.target ?? '页面检查').slice(0, 200)}。`
4042
+ + '验证码、扫码或登录只能由人完成,自动化到这一步就停下,不会替你点。',
4043
+ why: '让自动化硬闯检查既不可靠也不安全;停在这里是设计好的行为,不算失败。',
4044
+ options: ['我已经处理完成,继续'],
4045
+ impact: '告诉运行继续;它会重新检查页面,检查通过后接着做未完成的部分。',
4046
+ input: 'choice',
4047
+ canAnswer: true,
4048
+ })
4049
+ }
4050
+ return items
4051
+ }
4052
+
4053
+ async function boardAnswerInbox({ id, answer }) {
4054
+ const [kind, runId, rest] = String(id ?? '').split(':')
4055
+ if (kind === 'permission') {
4056
+ if (!auditor) throw new Error('审计没有启用,无法记录这次授权')
4057
+ if (/不允许|拒绝|deny|reject/i.test(answer)) {
4058
+ return { message: '已记录你的拒绝,这次操作不会执行。' }
4059
+ }
4060
+ await auditor.approve(rest, {
4061
+ actor: 'board',
4062
+ note: 'approved from the task board',
4063
+ runId: runId || null,
4064
+ kind: 'board',
4065
+ })
4066
+ return { message: '已批准这次操作,回到刚才的步骤重试即可。' }
4067
+ }
4068
+ if (kind === 'human') {
4069
+ const run = await store.read(runId)
4070
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
4071
+ const agent = await runOwnerAgent(run)
4072
+ await orchestrator.followup(runId, '人工检查已完成,请继续。', agent)
4073
+ return { runId, message: '已通知运行继续,它会重新检查页面。' }
4074
+ }
4075
+ throw new Error('这条待办已经失效,请刷新页面')
4076
+ }
4077
+
4078
+ const boardHost = {
4079
+ capabilities: boardCapabilities,
4080
+
4081
+ async listRuns() {
4082
+ await ready
4083
+ if (stateError) throw stateError
4084
+ return (await store.list()).filter(run => run && typeof run === 'object' && run.id)
4085
+ },
4086
+
4087
+ async readRun(runId) {
4088
+ await ready
4089
+ if (stateError) throw stateError
4090
+ return store.read(runId)
4091
+ },
4092
+
4093
+ async answer({ runId, attentionId, answer }) {
4094
+ await ready
4095
+ if (stateError) throw stateError
4096
+ const run = await store.read(runId)
4097
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
4098
+ const agent = await runOwnerAgent(run)
4099
+ const result = await answerAttention({ runId, attentionId, answer }, agent, timeZoneOf())
4100
+ // A question answered from the board must leave the same evidence a
4101
+ // tool answer would: who answered, when, and the words they used.
4102
+ if (auditor && typeof auditor.record === 'function') {
4103
+ const text = String(answer ?? '').trim().slice(0, 1000)
4104
+ await auditor.record({
4105
+ runId: result?.run?.id ?? runId,
4106
+ subtaskId: attentionId ? String(attentionId) : 'planner',
4107
+ actor: agent?.id ? `session:${agent.id}` : 'board',
4108
+ kind: 'attention',
4109
+ action: 'attention.answer',
4110
+ target: text,
4111
+ result: result?.resumed === true ? 'resumed' : 'recorded',
4112
+ source: 'board',
4113
+ meta: {
4114
+ attentionId: attentionId ?? null,
4115
+ answer: text,
4116
+ effect: result?.effect?.detail ?? null,
4117
+ },
4118
+ }).catch(error => log(`audit: cannot record the board answer: ${error?.message ?? error}`))
4119
+ }
4120
+ return {
4121
+ runId: result?.run?.id ?? runId,
4122
+ attentionId: result?.attentionId ?? attentionId,
4123
+ status: result?.run?.status ?? null,
4124
+ resumed: result?.resumed === true,
4125
+ effect: result?.effect?.detail ?? null,
4126
+ }
4127
+ },
4128
+
4129
+ async cancelSubtask({ runId, subtask }) {
4130
+ await ready
4131
+ if (stateError) throw stateError
4132
+ return orchestrator.cancelSubtask(runId, subtask)
4133
+ },
4134
+
4135
+ async rerunSubtask({ runId, subtask }) {
4136
+ await ready
4137
+ if (stateError) throw stateError
4138
+ const run = await store.read(runId)
4139
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
4140
+ const agent = await runOwnerAgent(run)
4141
+ return orchestrator.rerunSubtask(runId, subtask, agent, timeZoneOf())
4142
+ },
4143
+
4144
+ async reviewSubtask({ runId, subtask, verdict, note }) {
4145
+ await ready
4146
+ if (stateError) throw stateError
4147
+ const run = await store.read(runId)
4148
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
4149
+ const agent = await runOwnerAgent(run)
4150
+ return orchestrator.reviewSubtask(runId, subtask, verdict, agent, timeZoneOf(), note)
4151
+ },
4152
+
4153
+ async resumeRun({ runId }) {
4154
+ await ready
4155
+ if (stateError) throw stateError
4156
+ const run = await store.read(runId)
4157
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
4158
+ const agent = await runOwnerAgent(run)
4159
+ return orchestrator.resume(runId, agent, timeZoneOf(), { reopen: true })
4160
+ },
4161
+
4162
+ async startTemplate({ templateId, values }) {
4163
+ await ready
4164
+ if (stateError) throw stateError
4165
+ const caps = boardCapabilities()
4166
+ if (!caps.start) throw new Error(caps.reason)
4167
+ const template = await templates.get(templateId)
4168
+ if (!template) throw new Error(`没有 id 为「${templateId}」的模板,请刷新页面`)
4169
+ let expanded
4170
+ try {
4171
+ expanded = expandTemplate(template, values)
4172
+ } catch (error) {
4173
+ throw new Error(`模板参数不完整:${error?.message ?? error}`)
4174
+ }
4175
+ const agent = await boardSessionAgent()
4176
+ return orchestrator.start({
4177
+ goal: expanded.goal,
4178
+ parentSessionId: agent.id,
4179
+ parent: agent,
4180
+ clientTimeZone: timeZoneOf(),
4181
+ })
4182
+ },
4183
+
4184
+ async templates() {
4185
+ const result = await templates.list()
4186
+ return result.templates ?? []
4187
+ },
4188
+
4189
+ async auditFor({ runId, limit }) {
4190
+ if (!auditor) return []
4191
+ const result = await auditor.query({ runId, limit: limit ?? 200, order: 'asc' })
4192
+ return result.events ?? []
4193
+ },
4194
+
4195
+ extraInbox: boardExtraInbox,
4196
+ answerInbox: boardAnswerInbox,
4197
+ }
4198
+
4199
+ const taskBoard = createBoard({
4200
+ port: cfg.boardPort,
4201
+ stateRoot: store.root,
4202
+ host: boardHost,
4203
+ version: pkg.version,
4204
+ log,
4205
+ })
4206
+ let boardDisposed = false
4207
+ const stopBoard = () => {
4208
+ boardDisposed = true
4209
+ return taskBoard.stop().catch(error => log(`cannot stop the board: ${error?.message ?? error}`))
4210
+ }
4211
+ if (typeof ctx.effect === 'function') {
4212
+ ctx.effect(() => stopBoard, 'dsh-superagent board')
4213
+ } else if (typeof ctx.on === 'function') {
4214
+ ctx.on('dispose', stopBoard)
4215
+ }
4216
+ ready
4217
+ .then(() => {
4218
+ if (boardDisposed || stateError) return null
4219
+ return taskBoard.start()
4220
+ })
4221
+ .then(result => {
4222
+ if (!result) return
4223
+ log(
4224
+ `task board is listening on ${result.url}; open ${result.url}/?token=`
4225
+ + `${taskBoard.token} (the same token is in ${taskBoard.discoveryPath})`,
4226
+ )
4227
+ })
4228
+ .catch(error => {
4229
+ log(
4230
+ `task board is not listening: ${error?.message ?? error}; `
4231
+ + `check that boardRoot (${boardRoot}) exists, that boardPort is free, and that the state directory `
4232
+ + 'is writable, or remove boardPort to keep the board off',
4233
+ )
4234
+ })
3263
4235
  }
3264
4236
 
3265
4237
  // A mounted plugin owns one timer; unmounting must not leave it firing into
@@ -3275,11 +4247,13 @@ export function apply(ctx, config) {
3275
4247
  scheduleOwners.clear()
3276
4248
  }
3277
4249
  if (typeof ctx.on === 'function') ctx.on('dispose', stopScheduler)
4250
+ if (typeof ctx.on === 'function') ctx.on('dispose', () => longGoal.close())
3278
4251
 
3279
4252
  log(
3280
- `registered ${auditor ? 12 : 11} tools; state ${store.root}`
4253
+ `registered ${auditor ? 13 : 12} tools; state ${store.root}`
3281
4254
  + `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
3282
4255
  + `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`
3283
- + `${cfg.consolePort === null ? '' : `; console on port ${cfg.consolePort}`}`,
4256
+ + `${cfg.consolePort === null ? '' : `; console on port ${cfg.consolePort}`}`
4257
+ + `${cfg.boardPort === null ? '' : `; task board on port ${cfg.boardPort}`}`,
3284
4258
  )
3285
4259
  }