@xiangyixie/dsh-superagent 0.18.4 → 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
@@ -35,7 +35,15 @@ import { createMemory, isInside, MEMORY_KINDS, normalizeScope } from './memory.j
35
35
  import { createUserMemory, USER_MEMORY_CATEGORIES } from './user-memory.js'
36
36
  import { createNotifyPolicy, createOutbox } from './notify.js'
37
37
  import { createRuntimeControl } from './runtime-control.js'
38
- import { createScheduler, formatSchedule, formatScheduleList } from './schedule.js'
38
+ import {
39
+ createScheduler,
40
+ formatSchedule,
41
+ formatScheduleList,
42
+ normalizeScheduleInput,
43
+ rruleForInterval,
44
+ rruleFromCron,
45
+ rruleWithStart,
46
+ } from './schedule.js'
39
47
  import { createLongGoalManager, formatStatus as formatLongGoal } from './long-goal.js'
40
48
  import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
41
49
  import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
@@ -596,8 +604,7 @@ function acceptanceFromToolArgs(entry) {
596
604
  * `budget` is read only for `superagent_start`; on a schedule, `budget` is the
597
605
  * plan's own spending ceiling and is not a goal-mode field.
598
606
  */
599
- function goalModeFromToolArgs(args, { budget = true } = {}) {
600
- if (args.goal_mode !== true) {
607
+ function goalModeFromToolArgs(args, { budget = true } = {}) { if (args.goal_mode !== true) {
601
608
  if (args.acceptance !== undefined) {
602
609
  throw new Error('acceptance is only read in goal mode; pass goal_mode: true to enable it (goal mode is off by default)')
603
610
  }
@@ -615,6 +622,85 @@ function goalModeFromToolArgs(args, { budget = true } = {}) {
615
622
  }
616
623
  }
617
624
 
625
+ /** The Host Schedule tool a root Agent can call itself, when the host exposes it. */
626
+ const HOST_SCHEDULE_TOOL = 'schedule_create'
627
+
628
+ /**
629
+ * Resolve whether this caller may create a Host scheduled task.
630
+ *
631
+ * The host tool refuses delegated subagents, so they stay on the local timer
632
+ * instead of asking for a handoff that would fail. A missing tools service or
633
+ * a preset without `dsh-tool-schedule` reads as unavailable, never as "try it".
634
+ *
635
+ * @param {object} agent - calling Agent.
636
+ * @returns {string | null} tool name, or null when the plugin must keep the timer.
637
+ */
638
+ function hostScheduleToolFor(agent) {
639
+ const header = agent?.session?.header
640
+ if ((header?.delegationDepth ?? 0) > 0) return null
641
+ try {
642
+ const tools = agent?.ctx?.tools
643
+ if (typeof tools?.get !== 'function') return null
644
+ return tools.get(HOST_SCHEDULE_TOOL, agent.ctx) ? HOST_SCHEDULE_TOOL : null
645
+ } catch {
646
+ return null
647
+ }
648
+ }
649
+
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' }
656
+ }
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 = {
665
+ goal: plan.goal,
666
+ mode: plan.mode,
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
+ }),
675
+ }
676
+ return {
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
+ },
686
+ }
687
+ }
688
+
689
+ /**
690
+ * Tell the model to create the plan through the host instead of returning a
691
+ * plugin timer. The tool result carries the exact arguments so the follow-up
692
+ * call needs no translation.
693
+ */
694
+ function scheduleHandoffText({ payload, toolName }) {
695
+ return `handoff: this host exposes ${toolName}, so this plan belongs to the Host Scheduler, not to the plugin.\n\n`
696
+ + 'Call it now with exactly these arguments:\n'
697
+ + `${JSON.stringify(payload, null, 2)}\n\n`
698
+ + 'Do not tell the user the schedule exists until that call succeeds. It will then appear in the host\'s '
699
+ + 'scheduled tasks and deliver the prompt above to this session at each occurrence.\n'
700
+ + 'No timer is armed in this plugin for a host-backed plan. If the call fails, report its error verbatim; '
701
+ + 'do not fall back to a local timer silently.'
702
+ }
703
+
618
704
  function usageLine(usage, status) {
619
705
  if (!usage || !usage.modelCalls) {
620
706
  if (ACTIVE_STATUSES.has(status)) {
@@ -1285,7 +1371,15 @@ export function apply(ctx, config) {
1285
1371
  const guidance = {
1286
1372
  id: randomUUID(),
1287
1373
  role: 'user',
1288
- 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 }],
1289
1383
  source: GUIDANCE_SOURCE,
1290
1384
  }
1291
1385
  return { ...decision, messages: [guidance, ...decision.messages] }
@@ -1316,6 +1410,7 @@ export function apply(ctx, config) {
1316
1410
  // core tools stay visible there. A plain host conversation sees only
1317
1411
  // `superagent_help`, which expands the rest on demand.
1318
1412
  const panelSessions = new Set()
1413
+ let searchWorkbenchHistory = null
1319
1414
  const isPanelSession = agent => {
1320
1415
  const header = agent?.session?.header
1321
1416
  return panelSessions.has(agent?.id)
@@ -1847,11 +1942,6 @@ export function apply(ctx, config) {
1847
1942
  return null
1848
1943
  }
1849
1944
 
1850
- // This host build does not expose a scheduling API on the plugin context,
1851
- // so plans stay in the plugin store. The tool reports that instead of
1852
- // letting the user look for them in the host's automation list.
1853
- const hostScheduleVisible = typeof ctx.schedule === 'function'
1854
-
1855
1945
  const scheduler = createScheduler({
1856
1946
  stateFile: path.join(store.root, 'schedules.json'),
1857
1947
  orchestrator: {
@@ -1911,9 +2001,14 @@ export function apply(ctx, config) {
1911
2001
  async resolveOwner(goal) {
1912
2002
  const live = getAgents()?.get?.(goal.ownerSessionId)
1913
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
+ }
1914
2008
  return recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
1915
2009
  },
1916
2010
  async notify({ goal, message }) {
2011
+ if (goal.consoleOwned) return { delivered: false, reason: 'the console displays this goal' }
1917
2012
  let agent = getAgents()?.get?.(goal.ownerSessionId)
1918
2013
  if (!agent) {
1919
2014
  const recovered = await recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
@@ -2320,7 +2415,7 @@ export function apply(ctx, config) {
2320
2415
  const created = await longGoal.create({
2321
2416
  goal: args.goal,
2322
2417
  phases,
2323
- cwd: args.cwd,
2418
+ cwd: args.cwd ?? check.agent.session?.cwd,
2324
2419
  maxParallelPhases: args.max_parallel_phases,
2325
2420
  maxAttemptsPerPhase: args.max_attempts_per_phase,
2326
2421
  maxRoundsPerPhase: args.max_rounds_per_phase,
@@ -2431,15 +2526,22 @@ export function apply(ctx, config) {
2431
2526
 
2432
2527
  registerTool(defineTool({
2433
2528
  name: 'superagent_list',
2434
- description: 'List recorded runs, newest first, with status and progress.',
2529
+ description: 'List runs and progress, newest first.',
2435
2530
  properties: {
2436
2531
  limit: { type: 'number', description: 'Maximum rows (default 20).' },
2532
+ query: { type: 'string', description: 'Search visible tasks and deliverables.' },
2437
2533
  },
2438
- async execute(args = {}) {
2534
+ async execute(args = {}, exec) {
2439
2535
  try {
2440
2536
  await ready
2441
2537
  if (stateError) return describeError(stateError)
2442
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
+ }
2443
2545
  await recordSpend(runs)
2444
2546
  const stats = typeof store.stats === 'function' ? await store.stats() : null
2445
2547
  const memoryStats = memory
@@ -2459,7 +2561,7 @@ export function apply(ctx, config) {
2459
2561
  ledgerDays: LEDGER_WINDOW_DAYS,
2460
2562
  }
2461
2563
  : null
2462
- return formatList(runs, Math.max(1, Math.min(100, Number(args.limit) || 20)), extra)
2564
+ return formatList(runs, limit, extra)
2463
2565
  } catch (error) {
2464
2566
  return describeError(error)
2465
2567
  }
@@ -2486,7 +2588,9 @@ export function apply(ctx, config) {
2486
2588
  return [
2487
2589
  '已展开,下一步起可用(参数见各自 schema):',
2488
2590
  '- superagent_goal: 长期目标按阶段推进,多里程碑或必须按序时用;action=create/status/list/answer/retry_phase/resume/pause/cancel',
2489
- '- superagent_schedule: 定时或按间隔自动起 run;action=create/list/pause/resume/delete/run-now',
2591
+ '- superagent_schedule: 定时或按间隔自动起 run;action=create/list/migrate/pause/resume/delete/run-now。'
2592
+ + '宿主会话能调 schedule_create 时,create 只返回要转交的参数,必须自己调 schedule_create 建到宿主定时任务里;'
2593
+ + '插件本地定时只作兜底',
2490
2594
  '- superagent_inject: 给正在跑的 worker 立刻发指令;不着急就用 superagent_followup',
2491
2595
  '- superagent_memory: 跨 run 笔记;action=list/search/set/forget,layer="user" 读写用户级事实',
2492
2596
  '- superagent_template: 工作流模板;action=list/show/expand/save/delete,expand 出 goal 再 start',
@@ -2639,7 +2743,7 @@ export function apply(ctx, config) {
2639
2743
  return describeError(error)
2640
2744
  }
2641
2745
  },
2642
- }), EXTRA_TOOLS)
2746
+ }))
2643
2747
 
2644
2748
  registerTool(defineTool({
2645
2749
  name: 'superagent_answer',
@@ -3005,15 +3109,16 @@ export function apply(ctx, config) {
3005
3109
  registerTool(defineTool({
3006
3110
  name: 'superagent_schedule',
3007
3111
  description:
3008
- 'Create and manage scheduled runs that start on a cron expression or fixed interval without anyone calling '
3009
- + 'superagent_start. Actions: create, list, pause, resume, delete, run-now. Plans survive restarts, never overlap '
3010
- + 'themselves, and pause after 3 consecutive failures. Cron is 5 fields (*, */n, ranges, lists, names, 0/7 '
3011
- + 'Sunday); seconds and macros are refused.',
3112
+ 'Create and manage scheduled runs that start on cron or a fixed interval without anyone calling '
3113
+ + 'superagent_start. Actions: create, list, migrate, pause, resume, delete, run-now. When this session has '
3114
+ + 'schedule_create, create returns a handoff payload: call schedule_create with it so the plan lands in the '
3115
+ + 'host\'s scheduled tasks. The plugin timer is only a fallback for subagents, presets without '
3116
+ + 'dsh-tool-schedule, and cron with no lossless RRULE mapping. Cron is 5 fields; seconds and macros are refused.',
3012
3117
  properties: {
3013
3118
  action: {
3014
3119
  type: 'string',
3015
- enum: ['create', 'list', 'pause', 'resume', 'delete', 'run-now'],
3016
- description: 'create, list, pause/resume, delete, or start one run now without moving the next window.',
3120
+ enum: ['create', 'list', 'migrate', 'pause', 'resume', 'delete', 'run-now'],
3121
+ description: 'create, list, migrate local plans to the Host Scheduler, pause/resume, delete, or start one run now.',
3017
3122
  },
3018
3123
  id: { type: 'string', description: 'Schedule id (sch-...); required for pause, resume, delete, run-now.' },
3019
3124
  name: { type: 'string', description: 'create: short name used in list and notifications.' },
@@ -3134,6 +3239,38 @@ export function apply(ctx, config) {
3134
3239
  }
3135
3240
  : null
3136
3241
  const recovery = scheduleOwnerRecovery()
3242
+ // Validate the timing before choosing an owner for the timer: a bad
3243
+ // cron must fail the same way whether the host or the plugin runs it.
3244
+ let draft
3245
+ try {
3246
+ draft = normalizeScheduleInput({
3247
+ name: args.name,
3248
+ goal,
3249
+ mode: args.mode,
3250
+ cron: args.cron,
3251
+ everyMinutes: args.every_minutes,
3252
+ timeZone: args.timezone,
3253
+ missPolicy: args.miss_policy,
3254
+ goalMode: goalModeFromToolArgs(args, { budget: false }),
3255
+ budget,
3256
+ humanPriority: args.human_priority,
3257
+ ownerSessionId: String(args.session_id ?? check.agent.id).trim(),
3258
+ ownerRecovery: recovery,
3259
+ cwd: check.agent.session?.cwd ?? workbenchRoot,
3260
+ }, { now: () => Date.now() })
3261
+ } catch (error) {
3262
+ return describeError(error)
3263
+ }
3264
+ const hostTool = hostScheduleToolFor(check.agent)
3265
+ const handoff = hostTool ? schedulePayloadFor(draft, check.agent.id) : null
3266
+ if (handoff?.payload) {
3267
+ return scheduleHandoffText({ payload: handoff.payload, toolName: hostTool })
3268
+ }
3269
+ const fallbackReason = handoff
3270
+ ? `${handoff.reason}, so the plan stays local`
3271
+ : (check.agent.session?.header?.delegationDepth ?? 0) > 0
3272
+ ? `a delegated subagent cannot call ${HOST_SCHEDULE_TOOL}, so the plan stays local`
3273
+ : `this session cannot call ${HOST_SCHEDULE_TOOL} (the host preset does not mount dsh-tool-schedule), so the plan stays local`
3137
3274
  const plan = await scheduler.create({
3138
3275
  name: args.name,
3139
3276
  goal,
@@ -3148,19 +3285,15 @@ export function apply(ctx, config) {
3148
3285
  ownerSessionId: String(args.session_id ?? check.agent.id).trim(),
3149
3286
  ownerRecovery: recovery,
3150
3287
  cwd: check.agent.session?.cwd ?? workbenchRoot,
3288
+ fallbackReason,
3151
3289
  })
3152
3290
  const warning = recovery === 'none'
3153
3291
  ? '\n\nwarning: this host has no Host Session API, so it cannot reopen the owning session after a '
3154
3292
  + 'restart. The plan is marked as requiring a resident session; it will not silently pause, but it '
3155
3293
  + 'will not run while that session is closed.'
3156
3294
  : ''
3157
- const hostNotice = hostScheduleVisible
3158
- ? ''
3159
- : '\n\nnote: this host build exposes no scheduling API to plugins, so the plan lives in this '
3160
- + "plugin's own store and will not appear under the host's automation list. It still fires "
3161
- + `every ${cfg.schedulerTickSeconds}s while the app is running.`
3162
- return `created schedule ${plan.id}. The timer is armed from now on; no further tool call is needed.\n\n`
3163
- + formatSchedule(plan) + warning + hostNotice
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 + `\n\nThe timer checks every ${cfg.schedulerTickSeconds}s while the host is running.`
3164
3297
  }
3165
3298
  if (action === 'list') {
3166
3299
  const plans = await scheduler.list()
@@ -3170,6 +3303,36 @@ export function apply(ctx, config) {
3170
3303
  + `${snapshot.waiting} waiting (${snapshot.manualWaiting} manual)`
3171
3304
  return `${formatScheduleList(plans)}\n${quota}`
3172
3305
  }
3306
+ if (action === 'migrate') {
3307
+ if (!hostScheduleToolFor(check.agent)) return 'this session cannot call schedule_create; all plans stay local'
3308
+ const plans = await scheduler.list()
3309
+ if (plans.length === 0) {
3310
+ return 'no plugin-local plans to migrate; every new plan on this host is created through schedule_create already'
3311
+ }
3312
+ const migrated = []
3313
+ const skipped = []
3314
+ for (const plan of plans) {
3315
+ const { payload, reason } = schedulePayloadFor(plan, check.agent.id)
3316
+ if (!payload) {
3317
+ skipped.push(`${plan.id} ("${plan.name}"): ${reason}`)
3318
+ continue
3319
+ }
3320
+ if (plan.enabled) await scheduler.pause(plan.id, 'migrating to a Host scheduled task')
3321
+ migrated.push({ pluginId: plan.id, arguments: payload })
3322
+ }
3323
+ const lines = [
3324
+ `migration: ${migrated.length} plan(s) are paused and ready to move to the Host Scheduler.`,
3325
+ 'For each one, call schedule_create with the arguments below, then call superagent_schedule '
3326
+ + 'action="delete" with the pluginId once the host task exists. A paused local plan cannot double-fire '
3327
+ + 'while the host task is being created; action="resume" undoes the pause if the migration is abandoned.',
3328
+ JSON.stringify(migrated, null, 2),
3329
+ ]
3330
+ if (skipped.length > 0) {
3331
+ lines.push('these plans stay local because the Host Scheduler cannot preserve their settings:')
3332
+ lines.push(...skipped.map(line => `- ${line}`))
3333
+ }
3334
+ return lines.join('\n')
3335
+ }
3173
3336
  if (action === 'pause') {
3174
3337
  const plan = await scheduler.pause(String(args.id ?? ''), 'paused by superagent_schedule')
3175
3338
  return `paused ${plan.id} ("${plan.name}"). It will not start again until action="resume".`
@@ -3187,7 +3350,7 @@ export function apply(ctx, config) {
3187
3350
  return `started ${run.id} now for schedule ${plan.id} ("${plan.name}"); its next planned window is `
3188
3351
  + `${plan.nextRunAt}. Poll the run with superagent_status.`
3189
3352
  }
3190
- return describeError(`unknown action "${args.action}"; use create, list, pause, resume, delete, or run-now`)
3353
+ return describeError(`unknown action "${args.action}"; use create, list, migrate, pause, resume, delete, or run-now`)
3191
3354
  } catch (error) {
3192
3355
  if (error instanceof TemplateError) return templateProblem(error)
3193
3356
  return describeError(error)
@@ -3440,6 +3603,53 @@ export function apply(ctx, config) {
3440
3603
  // host has no session service the page is told so; it is never a mock chat.
3441
3604
  if (cfg.consolePort !== null) {
3442
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
+ }
3443
3653
  const CONSOLE_SPACE_ID = 'superagent-console-space'
3444
3654
 
3445
3655
  function getSessionController() {
@@ -3516,6 +3726,29 @@ export function apply(ctx, config) {
3516
3726
  return null
3517
3727
  }
3518
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
+
3519
3752
  /**
3520
3753
  * The tool a running worker is spending its time on, read from that worker's
3521
3754
  * own event log: the last unanswered `tool/call`, or the most recent one
@@ -3611,6 +3844,17 @@ export function apply(ctx, config) {
3611
3844
  startedAt: run.startedAt ?? null,
3612
3845
  finishedAt: run.finishedAt ?? null,
3613
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
+ })),
3614
3858
  // The cap the scheduler really used, and the line it is holding in the
3615
3859
  // queue, are read from the run record rather than re-derived here.
3616
3860
  limits: run.limits
@@ -3644,7 +3888,13 @@ export function apply(ctx, config) {
3644
3888
  }
3645
3889
  : null,
3646
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),
3647
3896
  attention: openAttention,
3897
+ output: run.goalMode?.achieved ? run.goalMode.rounds?.at(-1)?.report ?? null : null,
3648
3898
  report: report ? report.slice(0, detail ? 40_000 : 4_000) : null,
3649
3899
  reportTruncated: Boolean(report && report.length > (detail ? 40_000 : 4_000)),
3650
3900
  }
@@ -3767,26 +4017,35 @@ export function apply(ctx, config) {
3767
4017
  if (typeof sessionId === 'string' && sessionId) panelSessions.add(sessionId)
3768
4018
  },
3769
4019
 
3770
- async createSession() {
4020
+ async createSession({ cwd } = {}) {
3771
4021
  const caps = consoleCapabilities()
3772
4022
  if (!caps.chat) throw new Error(caps.reason)
3773
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
+ }
3774
4030
  const base = {
3775
- cwd: consoleRoot,
4031
+ cwd: directory,
3776
4032
  ...(cfg.consolePreset ? { agentPreset: cfg.consolePreset } : {}),
3777
4033
  }
3778
4034
  // A fixed identity makes the console its own space: the same
3779
4035
  // conversation is reused on the next host start instead of a new chat,
3780
4036
  // and it stays separate from the sessions the user starts themselves.
3781
4037
  let created
3782
- try {
3783
- created = await session.create({ ...base, sessionId: CONSOLE_SPACE_ID })
3784
- } catch {
3785
- created = await session.create(base)
3786
- }
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)
3787
4045
  if (!created || typeof created.sessionId !== 'string' || !created.sessionId) {
3788
4046
  throw new Error('sessionController.create returned no sessionId')
3789
4047
  }
4048
+ if (directory !== consoleRoot) await saveWorkbench(data => { data.sessions[created.sessionId] = directory })
3790
4049
  panelSessions.add(created.sessionId)
3791
4050
  return { sessionId: created.sessionId, preset: created.preset ?? cfg.consolePreset ?? null }
3792
4051
  },
@@ -3876,11 +4135,61 @@ export function apply(ctx, config) {
3876
4135
  if (stateError) throw stateError
3877
4136
  const runs = await store.list()
3878
4137
  return runs
3879
- .filter(run => run && run.parentSessionId === sessionId)
4138
+ .filter(run => run && run.parentSessionId === sessionId && run.origin?.role !== 'decompose')
3880
4139
  .slice(0, 20)
3881
4140
  .map(run => runView(run))
3882
4141
  },
3883
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
+
3884
4193
  async readRun(sessionId, runId) {
3885
4194
  await ready
3886
4195
  if (stateError) throw stateError
@@ -3889,6 +4198,14 @@ export function apply(ctx, config) {
3889
4198
  return runView(run, { detail: true })
3890
4199
  },
3891
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
+
3892
4209
  /**
3893
4210
  * Stop one run through the same cancel path the `superagent_cancel` tool
3894
4211
  * uses. Ownership is checked against the conversation first, so a page
@@ -3910,7 +4227,7 @@ export function apply(ctx, config) {
3910
4227
  },
3911
4228
 
3912
4229
  /** The console's own conversations, newest first, with what they produced. */
3913
- async listSessions() {
4230
+ async listSessions({ limit = 12 } = {}) {
3914
4231
  const controller = getSessionController()
3915
4232
  if (!controller || typeof controller.list !== 'function') return []
3916
4233
  await ready
@@ -3918,6 +4235,7 @@ export function apply(ctx, config) {
3918
4235
  // The registered controller answers `{ items }`; older shapes are a bare array.
3919
4236
  const listed = await controller.list()
3920
4237
  const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
4238
+ const workbench = await workbenchData
3921
4239
  const runs = await store.list().catch(() => [])
3922
4240
  const counts = new Map()
3923
4241
  for (const run of runs) {
@@ -3928,16 +4246,15 @@ export function apply(ctx, config) {
3928
4246
  counts.set(run.parentSessionId, entry)
3929
4247
  }
3930
4248
  const own = items
3931
- .filter(item => item && typeof item.sessionId === 'string')
3932
- .filter(item => item.parentSessionId === undefined)
3933
- .filter(item => typeof item.cwd === 'string' && path.resolve(item.cwd) === consoleRoot)
4249
+ .filter(item => consoleOwns(item, workbench))
3934
4250
  .sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
3935
- .slice(0, 12)
4251
+ .slice(0, limit)
3936
4252
  return Promise.all(own.map(async item => ({
3937
4253
  sessionId: item.sessionId,
3938
4254
  updatedAt: item.updatedAt ?? null,
3939
4255
  running: item.running === true,
3940
4256
  blank: item.blank === true,
4257
+ cwd: path.resolve(item.cwd),
3941
4258
  runs: counts.get(item.sessionId)?.runs ?? 0,
3942
4259
  artifacts: counts.get(item.sessionId)?.artifacts ?? 0,
3943
4260
  first: item.blank ? null : await firstUserText(item.sessionId, item.updatedAt),
@@ -3945,6 +4262,37 @@ export function apply(ctx, config) {
3945
4262
  })))
3946
4263
  },
3947
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
+
3948
4296
  /**
3949
4297
  * Session list plus the run rows the sidebar needs. The rows are the same
3950
4298
  * runView the message stream uses; the sidebar only groups them per
@@ -3988,11 +4336,8 @@ export function apply(ctx, config) {
3988
4336
  if (!controller || typeof controller.list !== 'function') return null
3989
4337
  const listed = await controller.list()
3990
4338
  const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
3991
- const hit = items.find(item => item
3992
- && item.sessionId === id
3993
- && item.parentSessionId === undefined
3994
- && typeof item.cwd === 'string'
3995
- && path.resolve(item.cwd) === consoleRoot)
4339
+ const workbench = await workbenchData
4340
+ const hit = items.find(item => item?.sessionId === id && consoleOwns(item, workbench))
3996
4341
  return hit ? { sessionId: id, updatedAt: hit.updatedAt ?? null } : null
3997
4342
  },
3998
4343
 
@@ -4079,6 +4424,12 @@ export function apply(ctx, config) {
4079
4424
  },
4080
4425
  }
4081
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
+
4082
4433
  const conversationConsole = createConsole({
4083
4434
  port: cfg.consolePort,
4084
4435
  stateRoot: store.root,