@xiangyixie/dsh-superagent 0.14.6 → 0.14.8

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
@@ -2156,12 +2156,14 @@ export function apply(ctx, config) {
2156
2156
  description:
2157
2157
  'Run a long-term goal as ordered phases: each phase is its own run with planner and parallel workers, and later '
2158
2158
  + 'phases receive earlier reports. A phase that keeps failing opens a decision a person answers with action '
2159
- + '"answer". Use it over superagent_start when milestones must happen in order over a long horizon.',
2159
+ + '"answer"; a phase nothing later depends on is skipped instead, the goal ends partial, and '
2160
+ + 'action="retry_phase" redoes just that phase. Use it over superagent_start when milestones must happen in order '
2161
+ + 'over a long horizon.',
2160
2162
  properties: {
2161
2163
  action: {
2162
2164
  type: 'string',
2163
- enum: ['create', 'status', 'list', 'answer', 'resume', 'pause', 'cancel'],
2164
- description: 'create, read one, list, answer an open decision, resume/pause/cancel.',
2165
+ enum: ['create', 'status', 'list', 'answer', 'resume', 'pause', 'cancel', 'retry_phase'],
2166
+ description: 'create, read one, list, answer an open decision, retry one skipped/failed phase, resume/pause/cancel.',
2165
2167
  },
2166
2168
  goal_id: { type: 'string', description: 'From action=create; required except for create/list.' },
2167
2169
  goal: {
@@ -2246,6 +2248,7 @@ export function apply(ctx, config) {
2246
2248
  description: 'Continue after a host restart (default true); false leaves it paused.',
2247
2249
  },
2248
2250
  decision_id: { type: 'string', description: 'answer: id shown in action=status.' },
2251
+ phase_id: { type: 'string', description: 'retry_phase: phase id shown in action=status.' },
2249
2252
  answer: {
2250
2253
  type: 'string',
2251
2254
  description: 'answer: retry, skip, stop, continue, or answer (worker question, needs note).',
@@ -2331,7 +2334,11 @@ export function apply(ctx, config) {
2331
2334
  const { goal: fresh, runs } = await longGoal.status(goal.id)
2332
2335
  return formatLongGoal(fresh, runs)
2333
2336
  }
2334
- if (action === 'resume') {
2337
+ if (action === 'retry_phase') {
2338
+ const phaseId = String(args.phase_id ?? '').trim()
2339
+ if (!phaseId) return describeError('action=retry_phase requires phase_id')
2340
+ await longGoal.retryPhase(goalId, phaseId)
2341
+ } else if (action === 'resume') {
2335
2342
  await longGoal.resume(goalId)
2336
2343
  } else if (action === 'pause') {
2337
2344
  await longGoal.pause(goalId)
@@ -2443,7 +2450,7 @@ export function apply(ctx, config) {
2443
2450
  }
2444
2451
  return [
2445
2452
  '已展开,下一步起可用(参数见各自 schema):',
2446
- '- superagent_goal: 长期目标按阶段推进,多里程碑或必须按序时用;action=create/status/list/answer/resume/pause/cancel',
2453
+ '- superagent_goal: 长期目标按阶段推进,多里程碑或必须按序时用;action=create/status/list/answer/retry_phase/resume/pause/cancel',
2447
2454
  '- superagent_schedule: 定时或按间隔自动起 run;action=create/list/pause/resume/delete/run-now',
2448
2455
  '- superagent_inject: 给正在跑的 worker 立刻发指令;不着急就用 superagent_followup',
2449
2456
  '- superagent_memory: 跨 run 笔记;action=list/search/set/forget,layer="user" 读写用户级事实',
@@ -3395,6 +3402,20 @@ export function apply(ctx, config) {
3395
3402
  const consoleRoot = cfg.consoleRoot ? path.resolve(cfg.consoleRoot) : workbenchRoot
3396
3403
  const CONSOLE_SPACE_ID = 'superagent-console-space'
3397
3404
 
3405
+ function getSessionController() {
3406
+ if (typeof ctx.get === 'function') {
3407
+ const service = ctx.get('sessionController')
3408
+ if (service) return service
3409
+ }
3410
+ // Direct property is topology-sensitive; this is a fallback for hosts
3411
+ // that expose the service without the registry.
3412
+ try {
3413
+ return ctx.sessionController
3414
+ } catch {
3415
+ return undefined
3416
+ }
3417
+ }
3418
+
3398
3419
  function consoleCapabilities() {
3399
3420
  const session = getSessionController()
3400
3421
  if (!session) {
@@ -3455,6 +3476,60 @@ export function apply(ctx, config) {
3455
3476
  return null
3456
3477
  }
3457
3478
 
3479
+ /**
3480
+ * The tool a running worker is spending its time on, read from that worker's
3481
+ * own event log: the last unanswered `tool/call`, or the most recent one
3482
+ * when every call already came back (a worker between calls). Null when the
3483
+ * log cannot be read; the page then shows no tool rather than a guess.
3484
+ */
3485
+ function runningToolName(childId) {
3486
+ if (typeof childId !== 'string' || !childId) return null
3487
+ const holder = (() => {
3488
+ const sessions = consoleService('sessions')
3489
+ if (sessions && typeof sessions.get === 'function') {
3490
+ const session = sessions.get(childId)
3491
+ if (session) return session
3492
+ }
3493
+ const agents = getAgents()
3494
+ if (agents && typeof agents.get === 'function') {
3495
+ const agent = agents.get(childId)
3496
+ return agent?.session ?? agent ?? null
3497
+ }
3498
+ return null
3499
+ })()
3500
+ if (!holder || typeof holder.snapshotEvents !== 'function') return null
3501
+ let events
3502
+ try {
3503
+ events = holder.snapshotEvents()
3504
+ } catch {
3505
+ return null
3506
+ }
3507
+ if (!Array.isArray(events)) return null
3508
+ const answered = new Set()
3509
+ // The newest unanswered call is what the lane is running now. When every
3510
+ // call already came back, the most recent one still tells the user what
3511
+ // that lane is spending its time on.
3512
+ let latest = null
3513
+ for (let index = events.length - 1, scanned = 0; index >= 0 && scanned < 80; index -= 1, scanned += 1) {
3514
+ const event = events[index]
3515
+ const data = event?.data
3516
+ if (!data || typeof data !== 'object') continue
3517
+ const callId = data.callId || data.message?.toolCallId || data.message?.source?.callId
3518
+ if (event.type === 'tool/result') {
3519
+ if (callId) answered.add(callId)
3520
+ continue
3521
+ }
3522
+ if (event.type !== 'tool/call' || !callId) continue
3523
+ const name = typeof data.name === 'string' && data.name ? data.name : null
3524
+ if (answered.has(callId)) {
3525
+ if (!latest) latest = name
3526
+ continue
3527
+ }
3528
+ return name
3529
+ }
3530
+ return latest
3531
+ }
3532
+
3458
3533
  function runView(run, { detail = false } = {}) {
3459
3534
  const usage = run.usage && typeof run.usage === 'object' ? run.usage : null
3460
3535
  const cost = usage ? computeCost(usage, cfg.pricing) : null
@@ -3474,6 +3549,11 @@ export function apply(ctx, config) {
3474
3549
  title: subtask.title ?? null,
3475
3550
  status: subtask.status ?? null,
3476
3551
  childId: subtask.childId ?? null,
3552
+ // Timing is what lets the page show which line is slow; without it
3553
+ // every lane looks equally busy.
3554
+ startedAt: subtask.startedAt ?? null,
3555
+ finishedAt: subtask.finishedAt ?? null,
3556
+ tool: subtask.status === 'running' ? runningToolName(subtask.childId) : null,
3477
3557
  }))
3478
3558
  : []
3479
3559
  const report = typeof run.report === 'string' ? run.report : null
@@ -3510,6 +3590,91 @@ export function apply(ctx, config) {
3510
3590
  }
3511
3591
  }
3512
3592
 
3593
+ /**
3594
+ * Count the files and pages a run report names, using the same rule the page
3595
+ * uses for artifact chips. The history row only needs the number.
3596
+ */
3597
+ function countReportArtifacts(report) {
3598
+ const text = typeof report === 'string' ? report : ''
3599
+ if (!text) return 0
3600
+ const seen = new Set()
3601
+ const push = value => {
3602
+ const href = value.replace(/[.,;:,。;:]+$/, '')
3603
+ if (href) seen.add(href)
3604
+ }
3605
+ for (const match of text.matchAll(/https?:\/\/[^\s"'`<>)\]}|]+/g)) push(match[0])
3606
+ for (const match of text.matchAll(/(?:[A-Za-z]:[\\/]|\.{1,2}[\\/]|~[\\/])[^\s"'`<>|]+?\.(?:html?|md|pdf|docx?|xlsx?|csv|tsv|json|ya?ml|txt|log|png|jpe?g|gif|webp|svg|zip|pptx?|py|js|mjs|css)\b/gi)) {
3607
+ push(match[0])
3608
+ }
3609
+ return Math.min(seen.size, 12)
3610
+ }
3611
+
3612
+ const firstTextCache = new Map()
3613
+
3614
+ /**
3615
+ * Session records as the page consumes them (`{type:'event', event}`).
3616
+ * Pages back from the newest until the first turn is reached, bounded so a
3617
+ * very long conversation cannot stall the drawer. Null when unreadable.
3618
+ */
3619
+ async function readSessionRecords(sessionId) {
3620
+ const controller = getSessionController()
3621
+ if (!controller || typeof controller.events !== 'function') return null
3622
+ const address = { kind: 'session', sessionId }
3623
+ const { signal } = new AbortController()
3624
+ try {
3625
+ const newest = await controller.events({ address, maxMessages: 200 }, signal)
3626
+ if (!newest || !Array.isArray(newest.records)) return null
3627
+ let records = newest.records.slice()
3628
+ let page = newest
3629
+ for (let guard = 0; page.hasMore === true && guard < 8; guard += 1) {
3630
+ const oldest = records[0]?.event?.seq
3631
+ if (!Number.isSafeInteger(oldest) || oldest <= 0) break
3632
+ const older = await controller.events({ address, maxMessages: 200, beforeSeq: oldest }, signal)
3633
+ const batch = Array.isArray(older?.records) ? older.records : []
3634
+ if (batch.length === 0) break
3635
+ records = [...batch, ...records]
3636
+ page = older
3637
+ }
3638
+ return records
3639
+ } catch (error) {
3640
+ const message = error instanceof Error ? error.message : String(error)
3641
+ const frame = error instanceof Error && error.stack ? String(error.stack).split('\n')[1]?.trim() ?? '' : ''
3642
+ log(`session read error: ${message}`)
3643
+ log(`session read at: ${frame.slice(0, 100)}`)
3644
+ return null
3645
+ }
3646
+ }
3647
+
3648
+ /**
3649
+ * The first thing the user said in a conversation, read from that session's
3650
+ * own log. Cached per `updatedAt` so opening the drawer does not re-read
3651
+ * every transcript, and null when the log cannot be read.
3652
+ */
3653
+ async function firstUserText(sessionId, marker) {
3654
+ const key = `${sessionId}:${marker ?? ''}`
3655
+ if (firstTextCache.has(key)) return firstTextCache.get(key)
3656
+ const records = await readSessionRecords(sessionId)
3657
+ let text = null
3658
+ for (const record of records ?? []) {
3659
+ const event = record?.event
3660
+ if (event?.type !== 'user/message') continue
3661
+ if (event.data?.source?.kind !== 'user') continue
3662
+ const parts = Array.isArray(event.data?.content) ? event.data.content : []
3663
+ const joined = parts
3664
+ .filter(part => part?.type === 'text' && typeof part.text === 'string')
3665
+ .map(part => part.text)
3666
+ .join(' ')
3667
+ .trim()
3668
+ if (joined) {
3669
+ text = joined.slice(0, 140)
3670
+ break
3671
+ }
3672
+ }
3673
+ if (text === null && records === null) log(`[superagent-console] first text unavailable for ${sessionId}`)
3674
+ firstTextCache.set(key, text)
3675
+ return text
3676
+ }
3677
+
3513
3678
  const consoleHost = {
3514
3679
  capabilities: consoleCapabilities,
3515
3680
 
@@ -3618,6 +3783,92 @@ export function apply(ctx, config) {
3618
3783
  return runView(run, { detail: true })
3619
3784
  },
3620
3785
 
3786
+ /**
3787
+ * Stop one run through the same cancel path the `superagent_cancel` tool
3788
+ * uses. Ownership is checked against the conversation first, so a page
3789
+ * can only stop runs it is showing.
3790
+ */
3791
+ async cancelRun(sessionId, runId) {
3792
+ await ready
3793
+ if (stateError) throw stateError
3794
+ const id = typeof runId === 'string' ? runId.trim() : ''
3795
+ if (!id) return null
3796
+ const run = await store.read(id)
3797
+ if (!run || run.parentSessionId !== sessionId) return null
3798
+ const cancelled = await orchestrator.cancel(id)
3799
+ return {
3800
+ runId: id,
3801
+ status: cancelled?.status ?? null,
3802
+ cancelPending: cancelled?.cancelPending === true,
3803
+ }
3804
+ },
3805
+
3806
+ /** The console's own conversations, newest first, with what they produced. */
3807
+ async listSessions() {
3808
+ const controller = getSessionController()
3809
+ if (!controller || typeof controller.list !== 'function') return []
3810
+ await ready
3811
+ if (stateError) throw stateError
3812
+ // The registered controller answers `{ items }`; older shapes are a bare array.
3813
+ const listed = await controller.list()
3814
+ const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
3815
+ const runs = await store.list().catch(() => [])
3816
+ const counts = new Map()
3817
+ for (const run of runs) {
3818
+ if (!run || typeof run.parentSessionId !== 'string') continue
3819
+ const entry = counts.get(run.parentSessionId) ?? { runs: 0, artifacts: 0 }
3820
+ entry.runs += 1
3821
+ entry.artifacts += countReportArtifacts(run.report)
3822
+ counts.set(run.parentSessionId, entry)
3823
+ }
3824
+ const own = items
3825
+ .filter(item => item && typeof item.sessionId === 'string')
3826
+ .filter(item => item.parentSessionId === undefined)
3827
+ .filter(item => typeof item.cwd === 'string' && path.resolve(item.cwd) === consoleRoot)
3828
+ .sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
3829
+ .slice(0, 12)
3830
+ return Promise.all(own.map(async item => ({
3831
+ sessionId: item.sessionId,
3832
+ updatedAt: item.updatedAt ?? null,
3833
+ running: item.running === true,
3834
+ blank: item.blank === true,
3835
+ runs: counts.get(item.sessionId)?.runs ?? 0,
3836
+ artifacts: counts.get(item.sessionId)?.artifacts ?? 0,
3837
+ first: item.blank ? null : await firstUserText(item.sessionId, item.updatedAt),
3838
+ title: item.projections?.values?.sessionTitle ?? item.projections?.values?.title ?? null,
3839
+ })))
3840
+ },
3841
+
3842
+ /**
3843
+ * One conversation's log, newest page first and then walked back to the
3844
+ * first turn. The controller reads cold sessions too, so a conversation
3845
+ * the console has never shown can still be reopened.
3846
+ */
3847
+ async readSessionEvents(sessionId) {
3848
+ const records = await readSessionRecords(sessionId)
3849
+ return records === null ? null : records.slice(-600)
3850
+ },
3851
+
3852
+ /**
3853
+ * Resolve a conversation this console may show. Only sessions created in
3854
+ * the console space qualify, so the page cannot wander into the user's own
3855
+ * sessions by guessing an id.
3856
+ */
3857
+ async openSession(sessionId) {
3858
+ const id = typeof sessionId === 'string' ? sessionId.trim() : ''
3859
+ if (!id) return null
3860
+ const controller = getSessionController()
3861
+ if (!controller || typeof controller.list !== 'function') return null
3862
+ const listed = await controller.list()
3863
+ const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
3864
+ const hit = items.find(item => item
3865
+ && item.sessionId === id
3866
+ && item.parentSessionId === undefined
3867
+ && typeof item.cwd === 'string'
3868
+ && path.resolve(item.cwd) === consoleRoot)
3869
+ return hit ? { sessionId: id, updatedAt: hit.updatedAt ?? null } : null
3870
+ },
3871
+
3621
3872
  async answer({ sessionId, runId, attentionId, answer }) {
3622
3873
  let agent = conversationAgent(sessionId)
3623
3874
  if (!agent) {