@xiangyixie/dsh-superagent 0.14.2 → 0.14.3

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
@@ -15,7 +15,9 @@
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'
@@ -40,6 +42,8 @@ import { createUsageReader } from './usage.js'
40
42
  import { describeWorkspace } from './workspace.js'
41
43
  import { createRunChangeTracker, createWorkbench } from './workbench.js'
42
44
  import { createConsole } from './console.js'
45
+ import { createWizard } from './wizard.js'
46
+ import { createBoard } from './board.js'
43
47
 
44
48
  export const name = 'dsh-superagent'
45
49
  // The host menu and sessions are required. `subagents` is read through
@@ -103,7 +107,7 @@ const DEFAULTS = {
103
107
  */
104
108
  plannerMaxModelCalls: 20,
105
109
  /** Upper bound on subtasks executing at once. */
106
- maxParallel: 3,
110
+ maxParallel: 4,
107
111
  /** Runs allowed to be active at the same time; a start over this waits instead of failing. */
108
112
  maxActiveRuns: 2,
109
113
  /** Runs allowed to wait for a free slot when queueing is on; 0 disables queueing. */
@@ -245,6 +249,14 @@ const DEFAULTS = {
245
249
  workspaceIsolation: false,
246
250
  /** Repository whose worktrees isolate the workers; defaults to the host's cwd. */
247
251
  workspaceRoot: null,
252
+ /**
253
+ * Which directory isolation is based on. `session` (default) uses the calling
254
+ * session's cwd — or the repository root git resolves from it — because that
255
+ * is the directory the sandbox boundary and the merge target already agree
256
+ * on. `config` keeps the older behaviour and always uses `workspaceRoot`,
257
+ * which is only correct when it names the same repository as the session.
258
+ */
259
+ workspaceBase: 'session',
248
260
  /**
249
261
  * Loopback HTTP port for the local workspace panel. `null` (default) keeps it
250
262
  * off; `0` asks the OS for a free port. The bound address and its one-time
@@ -262,6 +274,18 @@ const DEFAULTS = {
262
274
  * token are written to `<stateDir>/console.json`.
263
275
  */
264
276
  consolePort: null,
277
+ /**
278
+ * Loopback HTTP port for the task board — one page showing every run as
279
+ * subtask cards, everything waiting for a person, and the built-in templates.
280
+ * `null` (default) keeps it off; `0` asks the OS for a free port. The bound
281
+ * address and its one-time token are written to `<stateDir>/board.json`.
282
+ */
283
+ boardPort: null,
284
+ /**
285
+ * Directory the board conversation joins, and where a template-started run
286
+ * works. Defaults to `consoleRoot`, then `workbenchRoot`, then the host cwd.
287
+ */
288
+ boardRoot: null,
265
289
  /**
266
290
  * Directory the console conversation joins. Defaults to `workbenchRoot`, then
267
291
  * the host process's working directory.
@@ -306,6 +330,34 @@ const DEFAULTS = {
306
330
 
307
331
  const REPORT_PREVIEW_CHARS = 8000
308
332
 
333
+ /**
334
+ * Read the arguments of the tool call an approval is blocking, so the page can
335
+ * name the exact path instead of paraphrasing the asker. Sessions keep the
336
+ * append-only event log; the call preceding the ask is the last matching
337
+ * `tool/call` record. Anything unreadable stays null — the card then falls back
338
+ * to the host's own reason, never to a guess.
339
+ *
340
+ * @param {object|undefined} session - the asking agent's session.
341
+ * @param {string|undefined} callId - the blocked tool call.
342
+ * @returns {string|null} the raw JSON arguments, or null when unavailable.
343
+ */
344
+ function blockedCallArguments(session, callId) {
345
+ if (!session || typeof callId !== 'string' || !callId) return null
346
+ try {
347
+ const events = typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : null
348
+ if (!Array.isArray(events)) return null
349
+ for (let index = events.length - 1; index >= 0; index -= 1) {
350
+ const event = events[index]
351
+ if (event?.type !== 'tool/call' || event.data?.callId !== callId) continue
352
+ const raw = event.data?.arguments
353
+ return typeof raw === 'string' ? raw : null
354
+ }
355
+ } catch {
356
+ return null
357
+ }
358
+ return null
359
+ }
360
+
309
361
  /**
310
362
  * Coerce one numeric setting into its documented range. A value like "abc"
311
363
  * would otherwise become NaN and silently remove a limit (NaN comparisons are
@@ -381,6 +433,10 @@ function resolveConfig(config) {
381
433
  merged.consoleRoot = typeof merged.consoleRoot === 'string' && merged.consoleRoot.trim()
382
434
  ? merged.consoleRoot.trim()
383
435
  : null
436
+ merged.boardPort = controlPortOf(merged.boardPort)
437
+ merged.boardRoot = typeof merged.boardRoot === 'string' && merged.boardRoot.trim()
438
+ ? merged.boardRoot.trim()
439
+ : null
384
440
  merged.consolePreset = typeof merged.consolePreset === 'string' && merged.consolePreset.trim()
385
441
  ? merged.consolePreset.trim()
386
442
  : null
@@ -433,6 +489,9 @@ function resolveConfig(config) {
433
489
  merged.workspaceRoot = typeof merged.workspaceRoot === 'string' && merged.workspaceRoot.trim()
434
490
  ? merged.workspaceRoot.trim()
435
491
  : null
492
+ // Anything but an explicit `config` keeps the session-following default, so a
493
+ // typo cannot silently point isolation back at a stale profile directory.
494
+ merged.workspaceBase = merged.workspaceBase === 'config' ? 'config' : 'session'
436
495
  // The guard block merges so a user can set only `allowCommands` without
437
496
  // restating the rest of the defaults.
438
497
  merged.guard = {
@@ -764,6 +823,11 @@ function formatRun(run, { includeReport = true } = {}) {
764
823
  }
765
824
  if (run.resumedAt) lines.push(`resumed at: ${run.resumedAt}`)
766
825
  if (run.reclaimed) lines.push(`reclaimed: ${run.reclaimed.basis}`)
826
+ if (run.budgetStop?.detail) {
827
+ // A budget stop explains why no further worker started; it is not a
828
+ // failure, so it never sits in the error line of a finished run.
829
+ lines.push(`note: stopped starting new workers — ${run.budgetStop.detail}; finished work was kept`)
830
+ }
767
831
  if (run.status === 'interrupted' && run.error) {
768
832
  // Not a failure: the host went away and the run is waiting to be resumed.
769
833
  lines.push(`note: ${run.error}`)
@@ -1029,6 +1093,7 @@ export function apply(ctx, config) {
1029
1093
  const configuredPort = config?.controlPort
1030
1094
  const configuredWorkbenchPort = config?.workbenchPort
1031
1095
  const configuredConsolePort = config?.consolePort
1096
+ const configuredBoardPort = config?.boardPort
1032
1097
  const cfg = resolveConfig(config)
1033
1098
  if (configuredPort !== undefined && configuredPort !== null && cfg.controlPort === null) {
1034
1099
  log(`controlPort ${JSON.stringify(configuredPort)} is not a whole number in 0–65535; the local HTTP control plane stays off`)
@@ -1039,6 +1104,9 @@ export function apply(ctx, config) {
1039
1104
  if (configuredConsolePort !== undefined && configuredConsolePort !== null && cfg.consolePort === null) {
1040
1105
  log(`consolePort ${JSON.stringify(configuredConsolePort)} is not a whole number in 0–65535; the conversation console stays off`)
1041
1106
  }
1107
+ if (configuredBoardPort !== undefined && configuredBoardPort !== null && cfg.boardPort === null) {
1108
+ log(`boardPort ${JSON.stringify(configuredBoardPort)} is not a whole number in 0–65535; the task board stays off`)
1109
+ }
1042
1110
  if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
1043
1111
  console.error('[dsh-superagent] host exposes no tools service; plugin disabled')
1044
1112
  return
@@ -1076,6 +1144,32 @@ export function apply(ctx, config) {
1076
1144
  // directory that is meant to be shipped byte-for-byte from git. Refuse rather
1077
1145
  // than rely on the `.gitignore` the notebook writes for itself.
1078
1146
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
1147
+ // The browser half joins a shared combo script served to every page load, so
1148
+ // one syntax error in it can take the whole host UI down with it. Compile it
1149
+ // here, before the client-modules service reads it, and fall back to a no-op
1150
+ // entry when it does not parse: the worst case is a missing sidebar row.
1151
+ try {
1152
+ const clientEntry = path.join(packageRoot, 'lib', 'client.js')
1153
+ if (existsSync(clientEntry)) {
1154
+ const source = readFileSync(clientEntry, 'utf8')
1155
+ try {
1156
+ new Script(source, { filename: clientEntry })
1157
+ } catch (error) {
1158
+ writeFileSync(`${clientEntry}.broken`, source, 'utf8')
1159
+ writeFileSync(
1160
+ clientEntry,
1161
+ `window.__ModuleLoader__.load({ id: ${JSON.stringify(pkg.name)}, factory: () => ({ apply() {} }) })\n`,
1162
+ 'utf8',
1163
+ )
1164
+ log(
1165
+ `the browser half did not compile (${error?.message ?? error}); `
1166
+ + `kept it as ${clientEntry}.broken and served a no-op so the host still boots`,
1167
+ )
1168
+ }
1169
+ }
1170
+ } catch (error) {
1171
+ log(`cannot verify the browser half: ${error?.message ?? error}`)
1172
+ }
1079
1173
  const memoryBlocked = isInside(store.root, packageRoot)
1080
1174
  const memory = cfg.memory && !memoryBlocked ? createMemory(store.root, { warn: log }) : null
1081
1175
  // The user-level profile is a deliberate opt-in: it outlives tasks and records
@@ -1156,6 +1250,38 @@ export function apply(ctx, config) {
1156
1250
  }
1157
1251
  }
1158
1252
 
1253
+ // Tools alone do not tell a model when to use them. A session that mounts
1254
+ // `superagent_start` next to the host's `subagent` tool can hand-orchestrate
1255
+ // the work with the latter — three children, three report fragments, and no
1256
+ // run, no plan, no merged report, and nothing in the run list to look at.
1257
+ // This nudge is the only thing that states the policy, so it is injected
1258
+ // once per turn, at the first step of a top-level session.
1259
+ const GUIDANCE_SOURCE = { kind: 'superagent-guidance', form: 'notice', summary: '多步目标先起 run' }
1260
+ const GUIDANCE_TEXT = [
1261
+ '多步目标必须先用 superagent_start(mode="planned") 起一个 run:目标含两个及以上可独立交付物,',
1262
+ '或含“先做 A 才能做 B”的前置依赖时都算多步。之后用 superagent_followup 续,用 superagent_status 读报告。',
1263
+ '不要用宿主内置的 subagent 工具自己编排这些子任务——那样没有 run 记录、没有计划、没有合并报告。',
1264
+ '直接调用 superagent_start,不要先判断“当前有没有这个工具”;只有调用返回工具不存在时,才退回 subagent 并说明原因。',
1265
+ '只有单一动作(一次查找、一次编辑、一条命令、一段短文本)才直接做,不必起 run。',
1266
+ ].join('')
1267
+ if (typeof ctx.on === 'function') {
1268
+ ctx.on('agent/pre-step', async ({ agent, step }, next) => {
1269
+ const decision = await next()
1270
+ if (decision.kind === 'reject' || step !== 1) return decision
1271
+ const header = agent?.session?.header
1272
+ if (!header) return decision
1273
+ if ((header.delegationDepth ?? 0) > 0 || header.origin === 'subagent') return decision
1274
+ if (decision.messages.some(message => message?.source?.kind === GUIDANCE_SOURCE.kind)) return decision
1275
+ const guidance = {
1276
+ id: randomUUID(),
1277
+ role: 'user',
1278
+ content: [{ type: 'text', text: GUIDANCE_TEXT }],
1279
+ source: GUIDANCE_SOURCE,
1280
+ }
1281
+ return { ...decision, messages: [guidance, ...decision.messages] }
1282
+ })
1283
+ }
1284
+
1159
1285
  // Runtime control is opt-in. With `runtime.enabled` false nothing below is
1160
1286
  // registered, which is why a profile that never asked for browser or desktop
1161
1287
  // access sees exactly the same tool list as before this layer existed.
@@ -1541,10 +1667,17 @@ export function apply(ctx, config) {
1541
1667
  : null
1542
1668
  let pending
1543
1669
  try {
1670
+ // dsh 0.2.2-rc.1 reads the delegation fields from `request`; 0.2.2-rc.3
1671
+ // (the desktop host) reads them from the spec itself. Sending only
1672
+ // `request` leaves the newer host's `spec.parent` undefined, and it
1673
+ // throws "Cannot read properties of undefined (reading 'id')" before
1674
+ // any child exists. Mirror both shapes; each host ignores the keys it
1675
+ // does not read.
1544
1676
  pending = subagents.startActivation({
1545
1677
  provider: cfg.provider,
1546
1678
  label,
1547
1679
  request,
1680
+ ...request,
1548
1681
  signal,
1549
1682
  delivery: 'caller',
1550
1683
  })
@@ -1802,6 +1935,8 @@ export function apply(ctx, config) {
1802
1935
  + 'Pass mode "direct" for a single self-contained task instead: one worker does it, there is no planner '
1803
1936
  + 'or aggregator, and its reply is the report verbatim — use it for one lookup, one edit, one query, or '
1804
1937
  + 'one short piece of writing, not for a goal with parts that can be worked in parallel. '
1938
+ + 'Prefer this over the built-in subagent tool whenever the goal has several deliverables or a '
1939
+ + 'declared prerequisite step: only a run keeps the plan, the parallel timing, and one merged report. '
1805
1940
  + 'The call returns immediately with a run id; poll it with superagent_status. Runs are persisted, '
1806
1941
  + 'so they survive a host restart and can be resumed or cancelled.',
1807
1942
  properties: {
@@ -1941,6 +2076,22 @@ export function apply(ctx, config) {
1941
2076
  },
1942
2077
  }))
1943
2078
 
2079
+ // Files on disk can be newer than the code this host loaded: a package update
2080
+ // only takes effect after DSH restarts. Surface the mismatch instead of
2081
+ // letting the user wonder why the new version behaves like the old one.
2082
+ async function restartNotice() {
2083
+ try {
2084
+ const onDisk = JSON.parse(await fsp.readFile(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'))
2085
+ if (onDisk.version && onDisk.version !== pkg.version) {
2086
+ return `\n\nnote: package files on disk are ${onDisk.version} but this host is still running `
2087
+ + `${pkg.version} — restart DSH to load the new version.`
2088
+ }
2089
+ } catch {
2090
+ // Best effort: a status read must not fail because of this check.
2091
+ }
2092
+ return ''
2093
+ }
2094
+
1944
2095
  ctx.tools.register(defineTool({
1945
2096
  name: 'superagent_status',
1946
2097
  description:
@@ -1957,7 +2108,7 @@ export function apply(ctx, config) {
1957
2108
  if (stateError) return describeError(stateError)
1958
2109
  const run = await orchestrator.status(String(args.run_id ?? '').trim(), Number(args.wait_seconds) || 0)
1959
2110
  await recordSpend([run])
1960
- return formatRun(run)
2111
+ return `${formatRun(run)}${await restartNotice()}`
1961
2112
  } catch (error) {
1962
2113
  return describeError(error)
1963
2114
  }
@@ -2981,6 +3132,7 @@ export function apply(ctx, config) {
2981
3132
  // host has no session service the page is told so; it is never a mock chat.
2982
3133
  if (cfg.consolePort !== null) {
2983
3134
  const consoleRoot = cfg.consoleRoot ? path.resolve(cfg.consoleRoot) : workbenchRoot
3135
+ const CONSOLE_SPACE_ID = 'superagent-console-space'
2984
3136
 
2985
3137
  function consoleCapabilities() {
2986
3138
  const session = getSessionController()
@@ -3000,6 +3152,38 @@ export function apply(ctx, config) {
3000
3152
  return { chat: true, reason: null }
3001
3153
  }
3002
3154
 
3155
+ function consoleService(name) {
3156
+ if (typeof ctx.get === 'function') {
3157
+ const service = ctx.get(name)
3158
+ if (service) return service
3159
+ }
3160
+ try {
3161
+ return ctx[name]
3162
+ } catch {
3163
+ return undefined
3164
+ }
3165
+ }
3166
+
3167
+ // The wizard edits the profile's own patch layer and hands the key to the
3168
+ // host credential store. It never writes a secret into the profile file.
3169
+ const wizard = createWizard({
3170
+ stateRoot: store.root,
3171
+ version: pkg.version,
3172
+ log,
3173
+ pricing: cfg.pricing,
3174
+ getProfile: () => consoleService('profileContext') ?? null,
3175
+ getCredentials: () => consoleService('credentials'),
3176
+ getDefaultModel: () => {
3177
+ const service = consoleService('agentDefaultModel')
3178
+ if (!service) return null
3179
+ if (typeof service.currentSelection === 'function') return service.currentSelection()
3180
+ return service.selection ?? null
3181
+ },
3182
+ getSessionController,
3183
+ listTools: sessionId => consoleHost.listTools(sessionId),
3184
+ fetchImpl: typeof fetch === 'function' ? fetch : undefined,
3185
+ })
3186
+
3003
3187
  /** The conversation agent is the owner of every run it starts. */
3004
3188
  function conversationAgent(sessionId) {
3005
3189
  const agents = getAgents()
@@ -3068,14 +3252,43 @@ export function apply(ctx, config) {
3068
3252
  const consoleHost = {
3069
3253
  capabilities: consoleCapabilities,
3070
3254
 
3255
+ async wizardStatus(options = {}) {
3256
+ return wizard.status(options)
3257
+ },
3258
+
3259
+ async wizardPreview(body = {}) {
3260
+ return wizard.preview(body)
3261
+ },
3262
+
3263
+ async wizardSave(body = {}) {
3264
+ return wizard.save(body)
3265
+ },
3266
+
3267
+ async wizardRollback(id) {
3268
+ return wizard.rollback(id)
3269
+ },
3270
+
3271
+ async wizardTrial() {
3272
+ return wizard.trial()
3273
+ },
3274
+
3071
3275
  async createSession() {
3072
3276
  const caps = consoleCapabilities()
3073
3277
  if (!caps.chat) throw new Error(caps.reason)
3074
3278
  const session = getSessionController()
3075
- const created = await session.create({
3279
+ const base = {
3076
3280
  cwd: consoleRoot,
3077
3281
  ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3078
- })
3282
+ }
3283
+ // A fixed identity makes the console its own space: the same
3284
+ // conversation is reused on the next host start instead of a new chat,
3285
+ // and it stays separate from the sessions the user starts themselves.
3286
+ let created
3287
+ try {
3288
+ created = await session.create({ ...base, sessionId: CONSOLE_SPACE_ID })
3289
+ } catch {
3290
+ created = await session.create(base)
3291
+ }
3079
3292
  if (!created || typeof created.sessionId !== 'string' || !created.sessionId) {
3080
3293
  throw new Error('sessionController.create returned no sessionId')
3081
3294
  }
@@ -3260,6 +3473,483 @@ export function apply(ctx, config) {
3260
3473
  + 'is writable, or remove consolePort to keep the console off',
3261
3474
  )
3262
3475
  })
3476
+
3477
+ // Approvals asked inside this console's own conversation tree are put to the
3478
+ // person in the page; everything else keeps the host's normal answerer chain.
3479
+ // The bridge only relays the question — it never decides, and it fails closed
3480
+ // when no page is open, so nothing here widens what a tool may do.
3481
+ //
3482
+ // Registration is prepended and lives on the root event bus: the Web
3483
+ // assembly forwards `approval/request` to connected clients through its own
3484
+ // waterfall listener, and a listener that never calls `next()` would win by
3485
+ // order alone. Answering our own sessions first is what routes this tree's
3486
+ // ask to this page; every other session still falls through untouched.
3487
+ const approvalCtx = (ctx.root && typeof ctx.root.on === 'function') ? ctx.root : ctx
3488
+ const bridgeApproval = (request, next) => {
3489
+ try {
3490
+ const session = request?.agent?.session
3491
+ // The console owns whichever session it created this run (the fixed space
3492
+ // id, or a fresh id when the host refuses that one), so the live id is read
3493
+ // back from the console instead of assumed.
3494
+ const consoleSessionId = conversationConsole.sessionId
3495
+ const belongs = id => typeof id === 'string'
3496
+ && (id === CONSOLE_SPACE_ID || (typeof consoleSessionId === 'string' && id === consoleSessionId))
3497
+ const parent = (() => {
3498
+ const raw = session?.parentSession
3499
+ return typeof raw === 'string' ? raw : raw?.id
3500
+ })()
3501
+ if (!belongs(session?.id) && !belongs(parent)) return next()
3502
+ if (typeof conversationConsole.askApproval !== 'function') return next()
3503
+ return conversationConsole.askApproval({
3504
+ toolName: request?.toolName,
3505
+ callId: request?.callId ?? null,
3506
+ reason: request?.reason ?? null,
3507
+ displayReason: request?.displayReason ?? null,
3508
+ agentId: request?.agent?.id ?? null,
3509
+ callArguments: blockedCallArguments(session, request?.callId),
3510
+ source: belongs(session?.id) ? '主对话' : '子任务线',
3511
+ })
3512
+ } catch (error) {
3513
+ // A bridge that cannot even read the ask must not decide it: falling
3514
+ // through leaves the host's own answerers in charge (fail closed).
3515
+ log(`approval bridge skipped one ask: ${error?.message ?? error}`)
3516
+ return next()
3517
+ }
3518
+ }
3519
+ if (typeof approvalCtx.on === 'function') {
3520
+ try {
3521
+ if (typeof ctx.effect === 'function') {
3522
+ ctx.effect(() => approvalCtx.on('approval/request', bridgeApproval, { prepend: true }), 'dsh-superagent approval bridge')
3523
+ } else {
3524
+ const off = approvalCtx.on('approval/request', bridgeApproval, { prepend: true })
3525
+ if (typeof off === 'function' && typeof ctx.on === 'function') {
3526
+ ctx.on('dispose', () => {
3527
+ try {
3528
+ off()
3529
+ } catch {
3530
+ // the bus is already gone; nothing left to release
3531
+ }
3532
+ })
3533
+ }
3534
+ }
3535
+ } catch (error) {
3536
+ log(`cannot listen for approvals: ${error?.message ?? error}`)
3537
+ }
3538
+ }
3539
+
3540
+ // The browser half seats this console in the host's main panel. That frame
3541
+ // cannot read the discovery file, so one loopback route on the host's own
3542
+ // origin hands out the address and the one-time token. The path stays
3543
+ // outside `/api`: that prefix belongs to the connection gate, which answers
3544
+ // every unrouted request before plugin routes can see it. Registering this
3545
+ // is best-effort — a profile without a web server keeps every tool working
3546
+ // and the panel simply reports the console as unavailable.
3547
+ // `webServer` may mount after this plugin, so the route waits for it
3548
+ // through the loader's inject rather than reading it once at apply time.
3549
+ if (typeof ctx.inject === 'function') {
3550
+ ctx.inject(['webServer'], webCtx => {
3551
+ try {
3552
+ webCtx.effect(() => webCtx.webServer.register({
3553
+ kind: 'exact',
3554
+ path: '/superagent/console-address',
3555
+ handler: (req, res) => {
3556
+ if ((req.method ?? 'GET') !== 'GET') {
3557
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
3558
+ res.end(JSON.stringify({ ok: false, message: 'only GET is allowed here' }))
3559
+ return
3560
+ }
3561
+ const address = conversationConsole.url
3562
+ res.writeHead(200, {
3563
+ 'content-type': 'application/json; charset=utf-8',
3564
+ 'cache-control': 'no-store',
3565
+ })
3566
+ res.end(JSON.stringify({
3567
+ ok: true,
3568
+ data: {
3569
+ ready: Boolean(address),
3570
+ url: address,
3571
+ token: conversationConsole.token,
3572
+ reason: address ? null : 'the console is not listening yet; check consolePort and the state directory',
3573
+ },
3574
+ }))
3575
+ },
3576
+ }), 'dsh-superagent console address')
3577
+ } catch (error) {
3578
+ log(`cannot publish the console address route: ${error?.message ?? error}`)
3579
+ }
3580
+ })
3581
+ } else {
3582
+ log('this host has no inject(); the sidebar entry reports the console as unavailable')
3583
+ }
3584
+ }
3585
+
3586
+ // The task board is the third loopback surface, and the first one written for
3587
+ // a person who does not read JSON. It never owns a run: every action resolves
3588
+ // the run's owning session and calls the same orchestrator method a tool call
3589
+ // would. On a host without a session service it still shows every run and
3590
+ // says, in Chinese, why its buttons are unavailable.
3591
+ if (cfg.boardPort !== null) {
3592
+ const boardRoot = cfg.boardRoot
3593
+ ? path.resolve(cfg.boardRoot)
3594
+ : cfg.consoleRoot
3595
+ ? path.resolve(cfg.consoleRoot)
3596
+ : workbenchRoot
3597
+ const boardSessionFile = path.join(store.root, 'board-session.json')
3598
+
3599
+ const timeZoneOf = () => {
3600
+ try {
3601
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
3602
+ } catch {
3603
+ return undefined
3604
+ }
3605
+ }
3606
+
3607
+ function boardCapabilities() {
3608
+ const session = getSessionController()
3609
+ if (!session) {
3610
+ return {
3611
+ start: false,
3612
+ answer: false,
3613
+ reason: '宿主没有挂载 sessionController,看板只能查看运行,不能替你回答或继续。',
3614
+ }
3615
+ }
3616
+ const missing = ['create', 'resolveAgent'].filter(name => typeof session[name] !== 'function')
3617
+ if (missing.length > 0) {
3618
+ return {
3619
+ start: false,
3620
+ answer: false,
3621
+ reason: `sessionController 缺少 ${missing.join(' / ')},看板只能查看运行。`,
3622
+ }
3623
+ }
3624
+ if (!hasSubagents()) {
3625
+ return {
3626
+ start: false,
3627
+ answer: false,
3628
+ reason: '宿主没有 subagents 服务,无法从看板发起运行;查看和取消仍然可用。',
3629
+ }
3630
+ }
3631
+ return { start: true, answer: true, reason: null }
3632
+ }
3633
+
3634
+ /** Prefer the live agent; reopen the session only when it is not loaded. */
3635
+ async function resolveAgentById(sessionId) {
3636
+ if (!sessionId) return null
3637
+ const live = getAgents()?.get?.(sessionId)
3638
+ if (live) return live
3639
+ const session = getSessionController()
3640
+ if (!session || typeof session.resolveAgent !== 'function') return null
3641
+ try {
3642
+ return (await session.resolveAgent(sessionId))?.agent ?? null
3643
+ } catch {
3644
+ return null
3645
+ }
3646
+ }
3647
+
3648
+ /**
3649
+ * The board's own session, persisted so a host restart does not orphan
3650
+ * runs it started. A run's owner must stay the same session; that is why
3651
+ * this is a real session and not a synthetic agent.
3652
+ */
3653
+ async function boardSessionAgent() {
3654
+ const caps = boardCapabilities()
3655
+ if (!caps.start) throw new Error(caps.reason)
3656
+ let saved = null
3657
+ try {
3658
+ saved = JSON.parse(await fsp.readFile(boardSessionFile, 'utf8'))?.sessionId ?? null
3659
+ } catch {
3660
+ // First use, or a state directory that was cleaned.
3661
+ }
3662
+ let agent = await resolveAgentById(saved)
3663
+ if (agent) return agent
3664
+ const created = await getSessionController().create({
3665
+ cwd: boardRoot,
3666
+ ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3667
+ })
3668
+ const sessionId = typeof created?.sessionId === 'string' ? created.sessionId : ''
3669
+ if (!sessionId) throw new Error('sessionController.create 没有返回 sessionId,无法从看板发起运行')
3670
+ await fsp.mkdir(path.dirname(boardSessionFile), { recursive: true })
3671
+ await fsp.writeFile(
3672
+ boardSessionFile,
3673
+ `${JSON.stringify({ sessionId, createdAt: new Date().toISOString() }, null, 2)}\n`,
3674
+ 'utf8',
3675
+ )
3676
+ agent = await resolveAgentById(sessionId)
3677
+ if (!agent) {
3678
+ throw new Error('看板会话已经创建,但宿主没有把它变成可用 agent;请先在宿主里打开一次这个会话,再回来启动')
3679
+ }
3680
+ return agent
3681
+ }
3682
+
3683
+ async function runOwnerAgent(run) {
3684
+ const agent = await resolveAgentById(run?.parentSessionId)
3685
+ if (!agent) {
3686
+ throw new Error(
3687
+ '这次运行的发起会话已经关闭,看板不能替你继续;请在宿主里重新打开那个会话,'
3688
+ + '或用 superagent_resume 从新会话恢复。',
3689
+ )
3690
+ }
3691
+ return agent
3692
+ }
3693
+
3694
+ /**
3695
+ * Items that are not on a run record: a policy that held an operation for
3696
+ * confirmation, and a browser that stopped on a check only a person can do.
3697
+ */
3698
+ async function boardExtraInbox() {
3699
+ if (!auditor) return []
3700
+ let events = []
3701
+ try {
3702
+ events = (await auditor.query({ limit: 600, order: 'desc' })).events ?? []
3703
+ } catch (error) {
3704
+ log(`board: cannot read the audit trail: ${error?.message ?? error}`)
3705
+ return []
3706
+ }
3707
+ let runs = []
3708
+ try {
3709
+ runs = await store.list()
3710
+ } catch {
3711
+ // The run cards already cover this; the extras can stand without a goal.
3712
+ }
3713
+ const byId = new Map(runs.map(run => [run.id, run]))
3714
+ const approved = new Set(events
3715
+ .filter(event => event.kind === 'approved')
3716
+ .map(event => event.meta?.approves)
3717
+ .filter(Boolean))
3718
+ const items = []
3719
+ const seen = new Set()
3720
+ for (const event of events) {
3721
+ if (items.length >= 8) break
3722
+ if (event.decision === 'confirm' && event.result === 'pending' && !approved.has(event.id)) {
3723
+ const id = `permission:${event.id}`
3724
+ if (seen.has(id)) continue
3725
+ seen.add(id)
3726
+ items.push({
3727
+ id,
3728
+ kind: 'permission',
3729
+ kindLabel: '需要你授权',
3730
+ runId: event.runId ?? null,
3731
+ runGoal: event.runId ? byId.get(event.runId)?.goal ?? null : null,
3732
+ title: '有一个操作被权限策略拦下,等你点头',
3733
+ what: `被拦下的操作:${event.kind ?? '操作'} / ${event.action ?? ''}`
3734
+ + `${event.target ? ` → ${String(event.target).slice(0, 200)}` : ''}`,
3735
+ why: '策略要求人来确认这一次。它不是故障;拒绝也不会影响其他运行。',
3736
+ options: ['允许这次操作', '不允许'],
3737
+ impact: '允许后这一次操作会被放行,并记录是谁在什么时候批准的;不允许则保持拦截。',
3738
+ input: 'choice',
3739
+ canAnswer: true,
3740
+ })
3741
+ continue
3742
+ }
3743
+ if (event.kind !== 'attention' || event.result !== 'needs-human') continue
3744
+ const cleared = events.some(other => other.runId === event.runId
3745
+ && String(other.at ?? '') > String(event.at ?? '')
3746
+ && /await_human/i.test(String(other.action ?? '')))
3747
+ if (cleared) continue
3748
+ const id = `human:${event.runId}:${event.id}`
3749
+ if (seen.has(id) || !event.runId) continue
3750
+ seen.add(id)
3751
+ const goal = byId.get(event.runId)?.goal ?? null
3752
+ items.push({
3753
+ id,
3754
+ kind: 'human',
3755
+ kindLabel: '需要你亲自操作',
3756
+ runId: event.runId,
3757
+ runGoal: goal,
3758
+ title: '浏览器停在一个需要人完成的检查上',
3759
+ what: `运行${goal ? `「${String(goal).slice(0, 100)}」` : ''}停住了:${String(event.target ?? '页面检查').slice(0, 200)}。`
3760
+ + '验证码、扫码或登录只能由人完成,自动化到这一步就停下,不会替你点。',
3761
+ why: '让自动化硬闯检查既不可靠也不安全;停在这里是设计好的行为,不算失败。',
3762
+ options: ['我已经处理完成,继续'],
3763
+ impact: '告诉运行继续;它会重新检查页面,检查通过后接着做未完成的部分。',
3764
+ input: 'choice',
3765
+ canAnswer: true,
3766
+ })
3767
+ }
3768
+ return items
3769
+ }
3770
+
3771
+ async function boardAnswerInbox({ id, answer }) {
3772
+ const [kind, runId, rest] = String(id ?? '').split(':')
3773
+ if (kind === 'permission') {
3774
+ if (!auditor) throw new Error('审计没有启用,无法记录这次授权')
3775
+ if (/不允许|拒绝|deny|reject/i.test(answer)) {
3776
+ return { message: '已记录你的拒绝,这次操作不会执行。' }
3777
+ }
3778
+ await auditor.approve(rest, {
3779
+ actor: 'board',
3780
+ note: 'approved from the task board',
3781
+ runId: runId || null,
3782
+ kind: 'board',
3783
+ })
3784
+ return { message: '已批准这次操作,回到刚才的步骤重试即可。' }
3785
+ }
3786
+ if (kind === 'human') {
3787
+ const run = await store.read(runId)
3788
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
3789
+ const agent = await runOwnerAgent(run)
3790
+ await orchestrator.followup(runId, '人工检查已完成,请继续。', agent)
3791
+ return { runId, message: '已通知运行继续,它会重新检查页面。' }
3792
+ }
3793
+ throw new Error('这条待办已经失效,请刷新页面')
3794
+ }
3795
+
3796
+ const boardHost = {
3797
+ capabilities: boardCapabilities,
3798
+
3799
+ async listRuns() {
3800
+ await ready
3801
+ if (stateError) throw stateError
3802
+ return (await store.list()).filter(run => run && typeof run === 'object' && run.id)
3803
+ },
3804
+
3805
+ async readRun(runId) {
3806
+ await ready
3807
+ if (stateError) throw stateError
3808
+ return store.read(runId)
3809
+ },
3810
+
3811
+ async answer({ runId, attentionId, answer }) {
3812
+ await ready
3813
+ if (stateError) throw stateError
3814
+ const run = await store.read(runId)
3815
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
3816
+ const agent = await runOwnerAgent(run)
3817
+ const result = await answerAttention({ runId, attentionId, answer }, agent, timeZoneOf())
3818
+ // A question answered from the board must leave the same evidence a
3819
+ // tool answer would: who answered, when, and the words they used.
3820
+ if (auditor && typeof auditor.record === 'function') {
3821
+ const text = String(answer ?? '').trim().slice(0, 1000)
3822
+ await auditor.record({
3823
+ runId: result?.run?.id ?? runId,
3824
+ subtaskId: attentionId ? String(attentionId) : 'planner',
3825
+ actor: agent?.id ? `session:${agent.id}` : 'board',
3826
+ kind: 'attention',
3827
+ action: 'attention.answer',
3828
+ target: text,
3829
+ result: result?.resumed === true ? 'resumed' : 'recorded',
3830
+ source: 'board',
3831
+ meta: {
3832
+ attentionId: attentionId ?? null,
3833
+ answer: text,
3834
+ effect: result?.effect?.detail ?? null,
3835
+ },
3836
+ }).catch(error => log(`audit: cannot record the board answer: ${error?.message ?? error}`))
3837
+ }
3838
+ return {
3839
+ runId: result?.run?.id ?? runId,
3840
+ attentionId: result?.attentionId ?? attentionId,
3841
+ status: result?.run?.status ?? null,
3842
+ resumed: result?.resumed === true,
3843
+ effect: result?.effect?.detail ?? null,
3844
+ }
3845
+ },
3846
+
3847
+ async cancelSubtask({ runId, subtask }) {
3848
+ await ready
3849
+ if (stateError) throw stateError
3850
+ return orchestrator.cancelSubtask(runId, subtask)
3851
+ },
3852
+
3853
+ async rerunSubtask({ runId, subtask }) {
3854
+ await ready
3855
+ if (stateError) throw stateError
3856
+ const run = await store.read(runId)
3857
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
3858
+ const agent = await runOwnerAgent(run)
3859
+ return orchestrator.rerunSubtask(runId, subtask, agent, timeZoneOf())
3860
+ },
3861
+
3862
+ async reviewSubtask({ runId, subtask, verdict, note }) {
3863
+ await ready
3864
+ if (stateError) throw stateError
3865
+ const run = await store.read(runId)
3866
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
3867
+ const agent = await runOwnerAgent(run)
3868
+ return orchestrator.reviewSubtask(runId, subtask, verdict, agent, timeZoneOf(), note)
3869
+ },
3870
+
3871
+ async resumeRun({ runId }) {
3872
+ await ready
3873
+ if (stateError) throw stateError
3874
+ const run = await store.read(runId)
3875
+ if (!run) throw new Error('找不到这次运行,可能已经被清理')
3876
+ const agent = await runOwnerAgent(run)
3877
+ return orchestrator.resume(runId, agent, timeZoneOf(), { reopen: true })
3878
+ },
3879
+
3880
+ async startTemplate({ templateId, values }) {
3881
+ await ready
3882
+ if (stateError) throw stateError
3883
+ const caps = boardCapabilities()
3884
+ if (!caps.start) throw new Error(caps.reason)
3885
+ const template = await templates.get(templateId)
3886
+ if (!template) throw new Error(`没有 id 为「${templateId}」的模板,请刷新页面`)
3887
+ let expanded
3888
+ try {
3889
+ expanded = expandTemplate(template, values)
3890
+ } catch (error) {
3891
+ throw new Error(`模板参数不完整:${error?.message ?? error}`)
3892
+ }
3893
+ const agent = await boardSessionAgent()
3894
+ return orchestrator.start({
3895
+ goal: expanded.goal,
3896
+ parentSessionId: agent.id,
3897
+ parent: agent,
3898
+ clientTimeZone: timeZoneOf(),
3899
+ })
3900
+ },
3901
+
3902
+ async templates() {
3903
+ const result = await templates.list()
3904
+ return result.templates ?? []
3905
+ },
3906
+
3907
+ async auditFor({ runId, limit }) {
3908
+ if (!auditor) return []
3909
+ const result = await auditor.query({ runId, limit: limit ?? 200, order: 'asc' })
3910
+ return result.events ?? []
3911
+ },
3912
+
3913
+ extraInbox: boardExtraInbox,
3914
+ answerInbox: boardAnswerInbox,
3915
+ }
3916
+
3917
+ const taskBoard = createBoard({
3918
+ port: cfg.boardPort,
3919
+ stateRoot: store.root,
3920
+ host: boardHost,
3921
+ version: pkg.version,
3922
+ log,
3923
+ })
3924
+ let boardDisposed = false
3925
+ const stopBoard = () => {
3926
+ boardDisposed = true
3927
+ return taskBoard.stop().catch(error => log(`cannot stop the board: ${error?.message ?? error}`))
3928
+ }
3929
+ if (typeof ctx.effect === 'function') {
3930
+ ctx.effect(() => stopBoard, 'dsh-superagent board')
3931
+ } else if (typeof ctx.on === 'function') {
3932
+ ctx.on('dispose', stopBoard)
3933
+ }
3934
+ ready
3935
+ .then(() => {
3936
+ if (boardDisposed || stateError) return null
3937
+ return taskBoard.start()
3938
+ })
3939
+ .then(result => {
3940
+ if (!result) return
3941
+ log(
3942
+ `task board is listening on ${result.url}; open ${result.url}/?token=`
3943
+ + `${taskBoard.token} (the same token is in ${taskBoard.discoveryPath})`,
3944
+ )
3945
+ })
3946
+ .catch(error => {
3947
+ log(
3948
+ `task board is not listening: ${error?.message ?? error}; `
3949
+ + `check that boardRoot (${boardRoot}) exists, that boardPort is free, and that the state directory `
3950
+ + 'is writable, or remove boardPort to keep the board off',
3951
+ )
3952
+ })
3263
3953
  }
3264
3954
 
3265
3955
  // A mounted plugin owns one timer; unmounting must not leave it firing into
@@ -3280,6 +3970,7 @@ export function apply(ctx, config) {
3280
3970
  `registered ${auditor ? 12 : 11} tools; state ${store.root}`
3281
3971
  + `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
3282
3972
  + `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`
3283
- + `${cfg.consolePort === null ? '' : `; console on port ${cfg.consolePort}`}`,
3973
+ + `${cfg.consolePort === null ? '' : `; console on port ${cfg.consolePort}`}`
3974
+ + `${cfg.boardPort === null ? '' : `; task board on port ${cfg.boardPort}`}`,
3284
3975
  )
3285
3976
  }