@xiangyixie/dsh-superagent 0.19.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -647,44 +647,42 @@ function hostScheduleToolFor(agent) {
647
647
  }
648
648
  }
649
649
 
650
- /** `superagent_start` arguments one host-delivered message should repeat. */
651
- function startArgsForDraft(draft, args = {}) {
652
- return {
653
- goal: draft.goal,
654
- mode: draft.mode,
655
- session_id: draft.ownerSessionId,
656
- ...(args.goal_mode === undefined ? {} : { goal_mode: args.goal_mode }),
657
- ...(args.acceptance === undefined ? {} : { acceptance: args.acceptance }),
658
- ...(args.max_rounds === undefined ? {} : { max_rounds: args.max_rounds }),
659
- ...(args.max_wall_clock_minutes === undefined ? {} : { max_wall_clock_minutes: args.max_wall_clock_minutes }),
660
- ...(args.no_progress_rounds === undefined ? {} : { no_progress_rounds: args.no_progress_rounds }),
661
- ...(args.budget === undefined ? {} : { budget: args.budget }),
662
- ...(args.human_priority === undefined ? {} : { human_priority: args.human_priority }),
650
+ function schedulePayloadFor(plan, sessionId) {
651
+ if (plan.ownerSessionId !== sessionId) return { reason: 'the plan belongs to a different session' }
652
+ const rule = plan.schedule.cron ? rruleFromCron(plan.schedule.cron) : rruleForInterval(plan.schedule.everyMinutes)
653
+ if (!rule) return { reason: 'the recurrence has no lossless RRULE equivalent' }
654
+ if (Object.values(plan.budget ?? {}).some(value => value != null)) {
655
+ return { reason: 'the Host Scheduler cannot enforce the plugin plan budget' }
663
656
  }
664
- }
665
-
666
- /** `superagent_start` arguments a stored plugin-local plan should repeat. */
667
- function startArgsForPlan(plan) {
668
- return {
657
+ if (plan.schedule.missPolicy === 'none' || plan.concurrency?.humanPriority === false) {
658
+ return { reason: 'the Host Scheduler cannot preserve the selected missed-run or priority policy' }
659
+ }
660
+ const mode = plan.goalMode
661
+ if (mode?.budget && Object.values(mode.budget).some(value => value != null)) {
662
+ return { reason: 'the Host Scheduler cannot enforce the plugin plan budget' }
663
+ }
664
+ const args = {
669
665
  goal: plan.goal,
670
666
  mode: plan.mode,
671
- session_id: plan.ownerSessionId,
672
- ...(plan.goalMode ? { goal_mode: true } : {}),
673
- ...(plan.concurrency?.humanPriority === false ? { human_priority: false } : {}),
667
+ allow_duplicate: true,
668
+ ...(mode && {
669
+ goal_mode: true,
670
+ acceptance: mode.acceptance,
671
+ max_rounds: mode.maxRounds,
672
+ max_wall_clock_minutes: mode.maxWallClockMinutes,
673
+ no_progress_rounds: mode.noProgressRounds,
674
+ }),
674
675
  }
675
- }
676
-
677
- /** The exact `schedule_create` payload for one stored plan, or null when cron cannot be mapped. */
678
- function schedulePayloadFor(plan) {
679
- const rule = plan.schedule.cron ? rruleFromCron(plan.schedule.cron) : rruleForInterval(plan.schedule.everyMinutes)
680
- if (!rule) return null
681
676
  return {
682
- title: plan.name,
683
- prompt: `[scheduled task ${plan.name}] Start the scheduled run now by calling superagent_start with these arguments:\n`
684
- + `${JSON.stringify(startArgsForPlan(plan), null, 2)}\n`
685
- + 'This message is the recurring trigger; do not create or edit the schedule.',
686
- rrule: rruleWithStart(rule, plan.schedule.timeZone),
687
- target: 'this_session',
677
+ payload: {
678
+ title: plan.name,
679
+ prompt: `[scheduled task ${plan.name}] If superagent_start is not visible, call superagent_help first. `
680
+ + 'Start the scheduled run now by calling superagent_start with these arguments:\n'
681
+ + `${JSON.stringify(args, null, 2)}\n`
682
+ + 'This message is the recurring trigger; do not create or edit the schedule.',
683
+ rrule: rruleWithStart(rule, plan.schedule.timeZone),
684
+ target: 'this_session',
685
+ },
688
686
  }
689
687
  }
690
688
 
@@ -693,15 +691,7 @@ function schedulePayloadFor(plan) {
693
691
  * plugin timer. The tool result carries the exact arguments so the follow-up
694
692
  * call needs no translation.
695
693
  */
696
- function scheduleHandoffText({ draft, rrule, toolName, args }) {
697
- const payload = {
698
- title: draft.name,
699
- prompt: `[scheduled task ${draft.name}] Start the scheduled run now by calling superagent_start with these arguments:\n`
700
- + `${JSON.stringify(startArgsForDraft(draft, args), null, 2)}\n`
701
- + 'This message is the recurring trigger; do not create or edit the schedule.',
702
- rrule: rruleWithStart(rrule, draft.schedule.timeZone),
703
- target: 'this_session',
704
- }
694
+ function scheduleHandoffText({ payload, toolName }) {
705
695
  return `handoff: this host exposes ${toolName}, so this plan belongs to the Host Scheduler, not to the plugin.\n\n`
706
696
  + 'Call it now with exactly these arguments:\n'
707
697
  + `${JSON.stringify(payload, null, 2)}\n\n`
@@ -1381,7 +1371,15 @@ export function apply(ctx, config) {
1381
1371
  const guidance = {
1382
1372
  id: randomUUID(),
1383
1373
  role: 'user',
1384
- content: [{ type: 'text', text: GUIDANCE_TEXT }],
1374
+ content: [{ type: 'text', text: isPanelSession(agent)
1375
+ ? '先区分新委托和对已有任务的补充。用户补充正在进行的任务时,先用 superagent_list 找到本会话的任务,'
1376
+ + '再用 superagent_status 核对具体工作线。只有目标明确才用 superagent_inject 给指定工作线发送,'
1377
+ + '或在暂无运行中的工作线时用 superagent_followup 给该任务留下一次执行的要求。'
1378
+ + '有多个可能的任务时只问一句要改哪一项。不要重开任务,也不要把修改发到无关任务。'
1379
+ + '引用旧方案或产物时,用 superagent_list 的 query 搜索工作台历史。'
1380
+ + '新委托需要交付时调用 superagent_start,单项用 direct,多项用 planned。可验收时设置 goal_mode 和验收条件。'
1381
+ + '多阶段长期目标先用 superagent_help 展开 superagent_goal。单纯问答直接回复。'
1382
+ : GUIDANCE_TEXT }],
1385
1383
  source: GUIDANCE_SOURCE,
1386
1384
  }
1387
1385
  return { ...decision, messages: [guidance, ...decision.messages] }
@@ -1412,6 +1410,7 @@ export function apply(ctx, config) {
1412
1410
  // core tools stay visible there. A plain host conversation sees only
1413
1411
  // `superagent_help`, which expands the rest on demand.
1414
1412
  const panelSessions = new Set()
1413
+ let searchWorkbenchHistory = null
1415
1414
  const isPanelSession = agent => {
1416
1415
  const header = agent?.session?.header
1417
1416
  return panelSessions.has(agent?.id)
@@ -1943,11 +1942,6 @@ export function apply(ctx, config) {
1943
1942
  return null
1944
1943
  }
1945
1944
 
1946
- // This host build does not expose a scheduling API on the plugin context,
1947
- // so plans stay in the plugin store. The tool reports that instead of
1948
- // letting the user look for them in the host's automation list.
1949
- const hostScheduleVisible = typeof ctx.schedule === 'function'
1950
-
1951
1945
  const scheduler = createScheduler({
1952
1946
  stateFile: path.join(store.root, 'schedules.json'),
1953
1947
  orchestrator: {
@@ -2007,9 +2001,14 @@ export function apply(ctx, config) {
2007
2001
  async resolveOwner(goal) {
2008
2002
  const live = getAgents()?.get?.(goal.ownerSessionId)
2009
2003
  if (live && typeof live === 'object') return live
2004
+ if (goal.consoleOwned) {
2005
+ const resolved = await getSessionController()?.resolveAgent?.(goal.ownerSessionId)
2006
+ return resolved?.agent ?? null
2007
+ }
2010
2008
  return recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
2011
2009
  },
2012
2010
  async notify({ goal, message }) {
2011
+ if (goal.consoleOwned) return { delivered: false, reason: 'the console displays this goal' }
2013
2012
  let agent = getAgents()?.get?.(goal.ownerSessionId)
2014
2013
  if (!agent) {
2015
2014
  const recovered = await recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
@@ -2416,7 +2415,7 @@ export function apply(ctx, config) {
2416
2415
  const created = await longGoal.create({
2417
2416
  goal: args.goal,
2418
2417
  phases,
2419
- cwd: args.cwd,
2418
+ cwd: args.cwd ?? check.agent.session?.cwd,
2420
2419
  maxParallelPhases: args.max_parallel_phases,
2421
2420
  maxAttemptsPerPhase: args.max_attempts_per_phase,
2422
2421
  maxRoundsPerPhase: args.max_rounds_per_phase,
@@ -2527,15 +2526,22 @@ export function apply(ctx, config) {
2527
2526
 
2528
2527
  registerTool(defineTool({
2529
2528
  name: 'superagent_list',
2530
- description: 'List recorded runs, newest first, with status and progress.',
2529
+ description: 'List runs and progress, newest first.',
2531
2530
  properties: {
2532
2531
  limit: { type: 'number', description: 'Maximum rows (default 20).' },
2532
+ query: { type: 'string', description: 'Search visible tasks and deliverables.' },
2533
2533
  },
2534
- async execute(args = {}) {
2534
+ async execute(args = {}, exec) {
2535
2535
  try {
2536
2536
  await ready
2537
2537
  if (stateError) return describeError(stateError)
2538
2538
  const runs = await orchestrator.list()
2539
+ const limit = Math.max(1, Math.min(100, Number(args.limit) || 20))
2540
+ if (isPanelSession(exec?.agent)) {
2541
+ const query = typeof args.query === 'string' ? args.query.trim().slice(0, 160) : ''
2542
+ if (query && searchWorkbenchHistory) return await searchWorkbenchHistory(exec.agent.id, query, Math.min(limit, 8))
2543
+ return formatList(runs.filter(run => run.parentSessionId === exec.agent.id && run.origin?.role !== 'decompose'), limit)
2544
+ }
2539
2545
  await recordSpend(runs)
2540
2546
  const stats = typeof store.stats === 'function' ? await store.stats() : null
2541
2547
  const memoryStats = memory
@@ -2555,7 +2561,7 @@ export function apply(ctx, config) {
2555
2561
  ledgerDays: LEDGER_WINDOW_DAYS,
2556
2562
  }
2557
2563
  : null
2558
- return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
2564
+ return formatList(runs, limit, extra)
2559
2565
  } catch (error) {
2560
2566
  return describeError(error)
2561
2567
  }
@@ -2737,7 +2743,7 @@ export function apply(ctx, config) {
2737
2743
  return describeError(error)
2738
2744
  }
2739
2745
  },
2740
- }), EXTRA_TOOLS)
2746
+ }))
2741
2747
 
2742
2748
  registerTool(defineTool({
2743
2749
  name: 'superagent_answer',
@@ -3256,14 +3262,12 @@ export function apply(ctx, config) {
3256
3262
  return describeError(error)
3257
3263
  }
3258
3264
  const hostTool = hostScheduleToolFor(check.agent)
3259
- const hostRule = hostTool
3260
- ? (draft.schedule.cron ? rruleFromCron(draft.schedule.cron) : rruleForInterval(draft.schedule.everyMinutes))
3261
- : null
3262
- if (hostTool && hostRule) {
3263
- return scheduleHandoffText({ draft, rrule: hostRule, toolName: hostTool, args })
3265
+ const handoff = hostTool ? schedulePayloadFor(draft, check.agent.id) : null
3266
+ if (handoff?.payload) {
3267
+ return scheduleHandoffText({ payload: handoff.payload, toolName: hostTool })
3264
3268
  }
3265
- const fallbackReason = hostTool
3266
- ? `cron "${draft.schedule.cron}" has no lossless RRULE equivalent in ${hostTool}, so the plan stays local`
3269
+ const fallbackReason = handoff
3270
+ ? `${handoff.reason}, so the plan stays local`
3267
3271
  : (check.agent.session?.header?.delegationDepth ?? 0) > 0
3268
3272
  ? `a delegated subagent cannot call ${HOST_SCHEDULE_TOOL}, so the plan stays local`
3269
3273
  : `this session cannot call ${HOST_SCHEDULE_TOOL} (the host preset does not mount dsh-tool-schedule), so the plan stays local`
@@ -3288,12 +3292,8 @@ export function apply(ctx, config) {
3288
3292
  + 'restart. The plan is marked as requiring a resident session; it will not silently pause, but it '
3289
3293
  + 'will not run while that session is closed.'
3290
3294
  : ''
3291
- const hostNotice = hostScheduleVisible
3292
- ? ''
3293
- : '\n\nnote: the plugin context itself has no ctx.schedule; the local timer is the only engine here. '
3294
- + `It checks every ${cfg.schedulerTickSeconds}s while the app is running.`
3295
3295
  return `created schedule ${plan.id}. The plugin-local timer is armed from now on; no further tool call is needed.\n\n`
3296
- + formatSchedule(plan) + warning + hostNotice
3296
+ + formatSchedule(plan) + warning + `\n\nThe timer checks every ${cfg.schedulerTickSeconds}s while the host is running.`
3297
3297
  }
3298
3298
  if (action === 'list') {
3299
3299
  const plans = await scheduler.list()
@@ -3304,6 +3304,7 @@ export function apply(ctx, config) {
3304
3304
  return `${formatScheduleList(plans)}\n${quota}`
3305
3305
  }
3306
3306
  if (action === 'migrate') {
3307
+ if (!hostScheduleToolFor(check.agent)) return 'this session cannot call schedule_create; all plans stay local'
3307
3308
  const plans = await scheduler.list()
3308
3309
  if (plans.length === 0) {
3309
3310
  return 'no plugin-local plans to migrate; every new plan on this host is created through schedule_create already'
@@ -3311,9 +3312,9 @@ export function apply(ctx, config) {
3311
3312
  const migrated = []
3312
3313
  const skipped = []
3313
3314
  for (const plan of plans) {
3314
- const payload = schedulePayloadFor(plan)
3315
+ const { payload, reason } = schedulePayloadFor(plan, check.agent.id)
3315
3316
  if (!payload) {
3316
- skipped.push(`${plan.id} ("${plan.name}"): cron "${plan.schedule.cron}" has no lossless RRULE equivalent`)
3317
+ skipped.push(`${plan.id} ("${plan.name}"): ${reason}`)
3317
3318
  continue
3318
3319
  }
3319
3320
  if (plan.enabled) await scheduler.pause(plan.id, 'migrating to a Host scheduled task')
@@ -3327,7 +3328,7 @@ export function apply(ctx, config) {
3327
3328
  JSON.stringify(migrated, null, 2),
3328
3329
  ]
3329
3330
  if (skipped.length > 0) {
3330
- lines.push('these plans stay local because their cron cannot be mapped without changing the schedule:')
3331
+ lines.push('these plans stay local because the Host Scheduler cannot preserve their settings:')
3331
3332
  lines.push(...skipped.map(line => `- ${line}`))
3332
3333
  }
3333
3334
  return lines.join('\n')
@@ -3602,6 +3603,53 @@ export function apply(ctx, config) {
3602
3603
  // host has no session service the page is told so; it is never a mock chat.
3603
3604
  if (cfg.consolePort !== null) {
3604
3605
  const consoleRoot = cfg.consoleRoot ? path.resolve(cfg.consoleRoot) : workbenchRoot
3606
+ const workbenchFile = path.join(store.root, 'console-workbench.json')
3607
+ const workbenchData = ready.then(async () => {
3608
+ try {
3609
+ const saved = JSON.parse(await fsp.readFile(workbenchFile, 'utf8'))
3610
+ return { name: typeof saved.name === 'string' ? saved.name : '', sessions: saved.sessions ?? {} }
3611
+ } catch (error) {
3612
+ if (error.code !== 'ENOENT') log(`cannot read console workbench: ${error.message}`)
3613
+ return { name: '', sessions: {} }
3614
+ }
3615
+ })
3616
+ let workbenchWrites = Promise.resolve()
3617
+
3618
+ function saveWorkbench(update) {
3619
+ const writing = workbenchWrites.then(async () => {
3620
+ const data = await workbenchData
3621
+ const next = { name: data.name, sessions: { ...data.sessions } }
3622
+ update(next)
3623
+ const temporary = `${workbenchFile}.${randomUUID()}.tmp`
3624
+ await fsp.writeFile(temporary, JSON.stringify(next), { encoding: 'utf8', mode: 0o600 })
3625
+ try {
3626
+ await fsp.rename(temporary, workbenchFile)
3627
+ } catch (error) {
3628
+ await fsp.unlink(temporary).catch(() => {})
3629
+ throw error
3630
+ }
3631
+ Object.assign(data, next)
3632
+ return next
3633
+ })
3634
+ workbenchWrites = writing.catch(() => {})
3635
+ return writing
3636
+ }
3637
+
3638
+ function consoleOwns(item, workbench) {
3639
+ if (!item || item.parentSessionId != null || typeof item.sessionId !== 'string' || typeof item.cwd !== 'string') return false
3640
+ const cwd = path.resolve(item.cwd)
3641
+ return cwd === consoleRoot || (Object.hasOwn(workbench.sessions, item.sessionId) && workbench.sessions[item.sessionId] === cwd)
3642
+ }
3643
+
3644
+ let directoryPicker = null
3645
+ if (typeof ctx.inject === 'function') {
3646
+ ctx.inject(['directoryPicker'], scoped => {
3647
+ const capability = scoped.directoryPicker.capability()
3648
+ if (capability?.kind !== 'native') return
3649
+ directoryPicker = capability
3650
+ scoped.on?.('dispose', () => { if (directoryPicker === capability) directoryPicker = null })
3651
+ })
3652
+ }
3605
3653
  const CONSOLE_SPACE_ID = 'superagent-console-space'
3606
3654
 
3607
3655
  function getSessionController() {
@@ -3678,6 +3726,29 @@ export function apply(ctx, config) {
3678
3726
  return null
3679
3727
  }
3680
3728
 
3729
+ async function resolveConversationAgent(sessionId) {
3730
+ const live = conversationAgent(sessionId)
3731
+ if (live) return live
3732
+ const resolved = await getSessionController()?.resolveAgent?.(sessionId)
3733
+ return resolved?.agent ?? null
3734
+ }
3735
+
3736
+ function goalView(goal) {
3737
+ return {
3738
+ id: goal.id,
3739
+ goal: goal.goal,
3740
+ status: goal.status,
3741
+ reason: goal.pausedReason ?? goal.stoppedReason?.detail ?? null,
3742
+ decisions: goal.status === 'needs-decision' ? (goal.decisions ?? []).filter(decision => !decision.answer) : [],
3743
+ phases: (goal.phases ?? []).map(phase => ({
3744
+ id: phase.id,
3745
+ title: phase.title,
3746
+ status: phase.status,
3747
+ runId: phase.currentRunId ?? phase.runIds?.at(-1) ?? null,
3748
+ })),
3749
+ }
3750
+ }
3751
+
3681
3752
  /**
3682
3753
  * The tool a running worker is spending its time on, read from that worker's
3683
3754
  * own event log: the last unanswered `tool/call`, or the most recent one
@@ -3773,6 +3844,17 @@ export function apply(ctx, config) {
3773
3844
  startedAt: run.startedAt ?? null,
3774
3845
  finishedAt: run.finishedAt ?? null,
3775
3846
  parentSessionId: run.parentSessionId ?? null,
3847
+ goalId: run.origin?.kind === 'long-goal' ? run.origin.goalId : null,
3848
+ instructions: (run.injections ?? []).slice(-5).map(entry => ({
3849
+ id: entry.id,
3850
+ text: entry.text,
3851
+ targets: (entry.targets ?? []).map(({ subtaskIndex, status }) => ({ subtaskIndex, status })),
3852
+ })),
3853
+ followups: (run.followups ?? []).filter(entry => entry.kind === 'followup').slice(-5).map(entry => ({
3854
+ id: entry.id,
3855
+ text: entry.text,
3856
+ status: entry.appliedAt ? 'applied' : entry.missedAt ? 'missed' : 'pending',
3857
+ })),
3776
3858
  // The cap the scheduler really used, and the line it is holding in the
3777
3859
  // queue, are read from the run record rather than re-derived here.
3778
3860
  limits: run.limits
@@ -3806,7 +3888,13 @@ export function apply(ctx, config) {
3806
3888
  }
3807
3889
  : null,
3808
3890
  subtasks,
3891
+ artifacts: (run.subtasks ?? []).flatMap(task => task.status === 'completed'
3892
+ ? (task.deliverables ?? []).filter(item => item.status === 'verified').map(item => {
3893
+ const root = task.workspace?.dir ?? run.workspace?.base ?? run.goalMode?.cwd
3894
+ return { name: path.basename(item.path), href: root ? path.resolve(root, item.path) : item.path }
3895
+ }) : []).slice(0, 30),
3809
3896
  attention: openAttention,
3897
+ output: run.goalMode?.achieved ? run.goalMode.rounds?.at(-1)?.report ?? null : null,
3810
3898
  report: report ? report.slice(0, detail ? 40_000 : 4_000) : null,
3811
3899
  reportTruncated: Boolean(report && report.length > (detail ? 40_000 : 4_000)),
3812
3900
  }
@@ -3929,26 +4017,35 @@ export function apply(ctx, config) {
3929
4017
  if (typeof sessionId === 'string' && sessionId) panelSessions.add(sessionId)
3930
4018
  },
3931
4019
 
3932
- async createSession() {
4020
+ async createSession({ cwd } = {}) {
3933
4021
  const caps = consoleCapabilities()
3934
4022
  if (!caps.chat) throw new Error(caps.reason)
3935
4023
  const session = getSessionController()
4024
+ let directory = consoleRoot
4025
+ if (cwd) {
4026
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) throw new Error('请输入本地项目的绝对路径')
4027
+ directory = await fsp.realpath(cwd)
4028
+ if (!(await fsp.stat(directory)).isDirectory()) throw new Error('项目路径须指向一个文件夹')
4029
+ }
3936
4030
  const base = {
3937
- cwd: consoleRoot,
4031
+ cwd: directory,
3938
4032
  ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3939
4033
  }
3940
4034
  // A fixed identity makes the console its own space: the same
3941
4035
  // conversation is reused on the next host start instead of a new chat,
3942
4036
  // and it stays separate from the sessions the user starts themselves.
3943
4037
  let created
3944
- try {
3945
- created = await session.create({ ...base, sessionId: CONSOLE_SPACE_ID })
3946
- } catch {
3947
- created = await session.create(base)
3948
- }
4038
+ if (directory === consoleRoot) {
4039
+ try {
4040
+ created = await session.create({ ...base, sessionId: CONSOLE_SPACE_ID })
4041
+ } catch {
4042
+ created = await session.create(base)
4043
+ }
4044
+ } else created = await session.create(base)
3949
4045
  if (!created || typeof created.sessionId !== 'string' || !created.sessionId) {
3950
4046
  throw new Error('sessionController.create returned no sessionId')
3951
4047
  }
4048
+ if (directory !== consoleRoot) await saveWorkbench(data => { data.sessions[created.sessionId] = directory })
3952
4049
  panelSessions.add(created.sessionId)
3953
4050
  return { sessionId: created.sessionId, preset: created.preset ?? cfg.consolePreset ?? null }
3954
4051
  },
@@ -4038,11 +4135,61 @@ export function apply(ctx, config) {
4038
4135
  if (stateError) throw stateError
4039
4136
  const runs = await store.list()
4040
4137
  return runs
4041
- .filter(run => run && run.parentSessionId === sessionId)
4138
+ .filter(run => run && run.parentSessionId === sessionId && run.origin?.role !== 'decompose')
4042
4139
  .slice(0, 20)
4043
4140
  .map(run => runView(run))
4044
4141
  },
4045
4142
 
4143
+ async listGoals(sessionId) {
4144
+ await ready
4145
+ if (stateError) throw stateError
4146
+ return (await longGoal.list()).filter(goal => goal.ownerSessionId === sessionId).slice(0, 20).map(goalView)
4147
+ },
4148
+
4149
+ async createGoal(sessionId, text) {
4150
+ await ready
4151
+ if (stateError) throw stateError
4152
+ const agent = await resolveConversationAgent(sessionId)
4153
+ if (!agent) throw new Error('cannot start a goal without its conversation agent')
4154
+ if (!hasSubagents()) throw new Error('cannot start a goal without the host subagents service')
4155
+ const goal = await longGoal.create({
4156
+ goal: text,
4157
+ parentSessionId: sessionId,
4158
+ cwd: agent.session?.cwd ?? await consoleHost.sessionWorkspace(sessionId),
4159
+ consoleOwned: true,
4160
+ })
4161
+ return goalView(goal)
4162
+ },
4163
+
4164
+ async actOnGoal(sessionId, id, action, body) {
4165
+ await ready
4166
+ if (stateError) throw stateError
4167
+ const goal = await longGoal.store.read(id)
4168
+ if (!goal || goal.ownerSessionId !== sessionId) return null
4169
+ if (action === 'answer') {
4170
+ const parent = await resolveConversationAgent(sessionId)
4171
+ return goalView(await longGoal.answer(id, body.decisionId, body.answer, { parent, note: body.note }))
4172
+ }
4173
+ if (action === 'retry_phase') await longGoal.retryPhase(id, body.phaseId)
4174
+ else await longGoal[action](id)
4175
+ return goalView(await longGoal.get(id))
4176
+ },
4177
+
4178
+ async instructRun(sessionId, id, { text, subtaskIndex, mode }) {
4179
+ await ready
4180
+ if (stateError) throw stateError
4181
+ const run = await store.read(id)
4182
+ if (!run || run.parentSessionId !== sessionId) return null
4183
+ const agent = await resolveConversationAgent(sessionId)
4184
+ if (!agent) throw new Error('cannot send an instruction without its conversation agent')
4185
+ if (mode === 'followup') {
4186
+ const result = await orchestrator.followup(id, text, agent)
4187
+ return { id: result.followup.id, detail: result.effect.detail }
4188
+ }
4189
+ const result = await orchestrator.inject(id, text, agent, { subtaskIndex, fallbackToFollowup: false })
4190
+ return { id: result.injection.id, targets: result.injection.targets.map(({ subtaskIndex, status }) => ({ subtaskIndex, status })) }
4191
+ },
4192
+
4046
4193
  async readRun(sessionId, runId) {
4047
4194
  await ready
4048
4195
  if (stateError) throw stateError
@@ -4051,6 +4198,14 @@ export function apply(ctx, config) {
4051
4198
  return runView(run, { detail: true })
4052
4199
  },
4053
4200
 
4201
+ async readWorkerSession(sessionId, runId, childId) {
4202
+ const run = await this.readRun(sessionId, runId)
4203
+ const subtask = run?.subtasks.find(item => item.childId === childId)
4204
+ if (!subtask) return null
4205
+ const records = await this.readSessionEvents(childId)
4206
+ return { title: subtask.title, records: (records ?? []).slice(-150) }
4207
+ },
4208
+
4054
4209
  /**
4055
4210
  * Stop one run through the same cancel path the `superagent_cancel` tool
4056
4211
  * uses. Ownership is checked against the conversation first, so a page
@@ -4072,7 +4227,7 @@ export function apply(ctx, config) {
4072
4227
  },
4073
4228
 
4074
4229
  /** The console's own conversations, newest first, with what they produced. */
4075
- async listSessions() {
4230
+ async listSessions({ limit = 12 } = {}) {
4076
4231
  const controller = getSessionController()
4077
4232
  if (!controller || typeof controller.list !== 'function') return []
4078
4233
  await ready
@@ -4080,6 +4235,7 @@ export function apply(ctx, config) {
4080
4235
  // The registered controller answers `{ items }`; older shapes are a bare array.
4081
4236
  const listed = await controller.list()
4082
4237
  const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
4238
+ const workbench = await workbenchData
4083
4239
  const runs = await store.list().catch(() => [])
4084
4240
  const counts = new Map()
4085
4241
  for (const run of runs) {
@@ -4090,16 +4246,15 @@ export function apply(ctx, config) {
4090
4246
  counts.set(run.parentSessionId, entry)
4091
4247
  }
4092
4248
  const own = items
4093
- .filter(item => item && typeof item.sessionId === 'string')
4094
- .filter(item => item.parentSessionId === undefined)
4095
- .filter(item => typeof item.cwd === 'string' && path.resolve(item.cwd) === consoleRoot)
4249
+ .filter(item => consoleOwns(item, workbench))
4096
4250
  .sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
4097
- .slice(0, 12)
4251
+ .slice(0, limit)
4098
4252
  return Promise.all(own.map(async item => ({
4099
4253
  sessionId: item.sessionId,
4100
4254
  updatedAt: item.updatedAt ?? null,
4101
4255
  running: item.running === true,
4102
4256
  blank: item.blank === true,
4257
+ cwd: path.resolve(item.cwd),
4103
4258
  runs: counts.get(item.sessionId)?.runs ?? 0,
4104
4259
  artifacts: counts.get(item.sessionId)?.artifacts ?? 0,
4105
4260
  first: item.blank ? null : await firstUserText(item.sessionId, item.updatedAt),
@@ -4107,6 +4262,37 @@ export function apply(ctx, config) {
4107
4262
  })))
4108
4263
  },
4109
4264
 
4265
+ async workbench(sessionId, { query = '', limit = 20 } = {}) {
4266
+ await ready
4267
+ if (stateError) throw stateError
4268
+ const { name, sessions: tracked } = await workbenchData
4269
+ const sessions = await this.listSessions({ limit: 80 })
4270
+ const bySession = new Map(sessions.map(session => [session.sessionId, session]))
4271
+ const projects = [...new Set(Object.values(tracked))].map(cwd => ({
4272
+ cwd, name: path.basename(cwd) || cwd,
4273
+ sessionId: sessions.find(session => session.cwd === cwd)?.sessionId ?? null,
4274
+ }))
4275
+ const cwd = bySession.get(sessionId)?.cwd ?? consoleRoot
4276
+ const project = projects.find(entry => entry.cwd === cwd) ?? null
4277
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean)
4278
+ const runs = (await store.list())
4279
+ .filter(run => bySession.has(run.parentSessionId) && run.origin?.role !== 'decompose')
4280
+ .filter(run => !project || bySession.get(run.parentSessionId).cwd === project.cwd)
4281
+ .filter(run => terms.every(term => `${run.goal} ${run.report ?? ''}`.toLowerCase().includes(term)))
4282
+ .slice(0, limit).map(run => runView(run))
4283
+ return { name, project, projects, runs, canPickProject: Boolean(directoryPicker), globalSessionId: sessions.find(session => session.cwd === consoleRoot)?.sessionId ?? null }
4284
+ },
4285
+
4286
+ async pickProject(signal) {
4287
+ if (!directoryPicker) throw new Error('此宿主未挂载本地文件夹选择器')
4288
+ return directoryPicker.pick(signal)
4289
+ },
4290
+
4291
+ async nameWorkbench(name) {
4292
+ const next = await saveWorkbench(data => { data.name = name })
4293
+ return { name: next.name }
4294
+ },
4295
+
4110
4296
  /**
4111
4297
  * Session list plus the run rows the sidebar needs. The rows are the same
4112
4298
  * runView the message stream uses; the sidebar only groups them per
@@ -4150,11 +4336,8 @@ export function apply(ctx, config) {
4150
4336
  if (!controller || typeof controller.list !== 'function') return null
4151
4337
  const listed = await controller.list()
4152
4338
  const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
4153
- const hit = items.find(item => item
4154
- && item.sessionId === id
4155
- && item.parentSessionId === undefined
4156
- && typeof item.cwd === 'string'
4157
- && path.resolve(item.cwd) === consoleRoot)
4339
+ const workbench = await workbenchData
4340
+ const hit = items.find(item => item?.sessionId === id && consoleOwns(item, workbench))
4158
4341
  return hit ? { sessionId: id, updatedAt: hit.updatedAt ?? null } : null
4159
4342
  },
4160
4343
 
@@ -4241,6 +4424,12 @@ export function apply(ctx, config) {
4241
4424
  },
4242
4425
  }
4243
4426
 
4427
+ searchWorkbenchHistory = async (sessionId, query, limit) => {
4428
+ const { runs } = await consoleHost.workbench(sessionId, { query, limit })
4429
+ return runs.length ? runs.map(run => `- ${run.id} [${run.status}] ${run.goal.slice(0, 180)}\n ${(run.output ?? run.report ?? '').slice(0, 500)}`).join('\n')
4430
+ : 'No matching tasks or deliverables in the visible workbench history.'
4431
+ }
4432
+
4244
4433
  const conversationConsole = createConsole({
4245
4434
  port: cfg.consolePort,
4246
4435
  stateRoot: store.root,