@xiangyixie/dsh-superagent 0.14.3 → 0.14.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * Registered tools: superagent_start, superagent_status, superagent_list,
11
11
  * superagent_cancel, superagent_resume, superagent_followup, superagent_inject,
12
12
  * superagent_answer, superagent_memory, superagent_template, superagent_audit,
13
- * superagent_schedule.
13
+ * superagent_schedule, superagent_goal.
14
14
  *
15
15
  * @module dsh-superagent
16
16
  */
@@ -36,6 +36,7 @@ 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
38
  import { createScheduler, formatSchedule, formatScheduleList } from './schedule.js'
39
+ import { createLongGoalManager, formatStatus as formatLongGoal } from './long-goal.js'
39
40
  import { ACTIVE_STATUSES, createStore, resolveStateRoot, TERMINAL_STATUSES } from './store.js'
40
41
  import { createTemplateStore, expandTemplate, formatTemplateDetail, formatTemplateList, TemplateError } from './templates.js'
41
42
  import { createUsageReader } from './usage.js'
@@ -47,7 +48,7 @@ import { createBoard } from './board.js'
47
48
 
48
49
  export const name = 'dsh-superagent'
49
50
  // The host menu and sessions are required. `subagents` is read through
50
- // `ctx.get('subagents')`, so a profile without it still mounts the twelve tools;
51
+ // `ctx.get('subagents')`, so a profile without it still mounts the thirteen tools;
51
52
  // they then report what is missing instead of the plugin silently vanishing.
52
53
  export const inject = ['tools', 'agents']
53
54
 
@@ -1316,7 +1317,7 @@ export function apply(ctx, config) {
1316
1317
  /**
1317
1318
  * The subagent service is optional, so it is read from the service store at
1318
1319
  * call time rather than declared as an injection: a profile without it must
1319
- * still mount the twelve tools (they then explain what is missing), and reading
1320
+ * still mount the thirteen tools (they then explain what is missing), and reading
1320
1321
  * it lazily also sees a service that registers after this plugin.
1321
1322
  */
1322
1323
  function getSubagents() {
@@ -1722,8 +1723,27 @@ export function apply(ctx, config) {
1722
1723
  * @param {object} plan - plan whose window is firing.
1723
1724
  * @returns {Promise<object | {agent: object, sessionId: string} | null>} agent or agent+id.
1724
1725
  */
1725
- async function recoverScheduleOwner(plan) {
1726
+ async function recoverScheduleOwner(plan, label = 'schedule', options = {}) {
1726
1727
  const agents = getAgents()
1728
+ const session = getSessionController()
1729
+ // `agents.resume` reopens the transcript without the Session's agent
1730
+ // preset, so the agent it returns runs without the file and shell tools the
1731
+ // Session was created with. A long-goal phase hands its owner to child
1732
+ // agents, so it needs a fully composed owner: the session controller mounts
1733
+ // the recorded preset, which is why the goal path asks it first. Scheduled
1734
+ // runs keep the old order so their behaviour does not change.
1735
+ if (options.preferResolve && session && typeof session.resolveAgent === 'function') {
1736
+ try {
1737
+ const resolved = await session.resolveAgent(plan.ownerSessionId)
1738
+ if (resolved?.agent) {
1739
+ const registered = getAgents()?.get?.(plan.ownerSessionId)
1740
+ return registered ?? resolved.agent
1741
+ }
1742
+ if (resolved?.error) log(`${label} ${plan.id}: cannot open session ${plan.ownerSessionId}: ${resolved.error}`)
1743
+ } catch (error) {
1744
+ log(`${label} ${plan.id}: cannot open session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1745
+ }
1746
+ }
1727
1747
  if (agents && typeof agents.resume === 'function') {
1728
1748
  try {
1729
1749
  const handle = await agents.resume({ resumeSessionId: plan.ownerSessionId })
@@ -1732,17 +1752,16 @@ export function apply(ctx, config) {
1732
1752
  return handle.agent
1733
1753
  }
1734
1754
  } catch (error) {
1735
- log(`schedule ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1755
+ log(`${label} ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${error?.message ?? error}`)
1736
1756
  }
1737
1757
  }
1738
- const session = getSessionController()
1739
1758
  if (session && typeof session.resolveAgent === 'function') {
1740
1759
  const resolved = await session.resolveAgent(plan.ownerSessionId)
1741
1760
  if (resolved?.agent) {
1742
1761
  const registered = getAgents()?.get?.(plan.ownerSessionId)
1743
1762
  return registered ?? resolved.agent
1744
1763
  }
1745
- if (resolved?.error) log(`schedule ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${resolved.error}`)
1764
+ if (resolved?.error) log(`${label} ${plan.id}: cannot resume session ${plan.ownerSessionId}: ${resolved.error}`)
1746
1765
  }
1747
1766
  if (agents && typeof agents.create === 'function') {
1748
1767
  const sessionId = randomUUID()
@@ -1756,7 +1775,7 @@ export function apply(ctx, config) {
1756
1775
  return { agent: handle.agent, sessionId }
1757
1776
  }
1758
1777
  } catch (error) {
1759
- log(`schedule ${plan.id}: cannot create a replacement session: ${error?.message ?? error}`)
1778
+ log(`${label} ${plan.id}: cannot create a replacement session: ${error?.message ?? error}`)
1760
1779
  }
1761
1780
  }
1762
1781
  if (session && typeof session.create === 'function') {
@@ -1770,7 +1789,7 @@ export function apply(ctx, config) {
1770
1789
  if (resolved?.agent) return { agent: resolved.agent, sessionId }
1771
1790
  }
1772
1791
  }
1773
- log(`schedule ${plan.id}: the host could not create a replacement session`)
1792
+ log(`${label} ${plan.id}: the host could not create a replacement session`)
1774
1793
  }
1775
1794
  return null
1776
1795
  }
@@ -1817,6 +1836,54 @@ export function apply(ctx, config) {
1817
1836
  warn: log,
1818
1837
  })
1819
1838
 
1839
+ // A long-term goal is a thin layer above runs: each phase is a normal run.
1840
+ // The manager only owns the phase graph, the goal budget, and the decisions
1841
+ // that a phase cannot make by itself. Keeping it behind the orchestrator API
1842
+ // means it inherits every run-side guarantee (locks, persistence, resume).
1843
+ const longGoal = createLongGoalManager({
1844
+ root: store.root,
1845
+ orchestrator: {
1846
+ start: args => orchestrator.start(args),
1847
+ status: runId => orchestrator.status(runId),
1848
+ resume: (runId, parent, clientTimeZone) => orchestrator.resume(runId, parent, clientTimeZone),
1849
+ cancel: runId => orchestrator.cancel(runId),
1850
+ answer: (runId, attentionId, answer, agent, clientTimeZone) =>
1851
+ orchestrator.answer(runId, attentionId, answer, agent, clientTimeZone),
1852
+ },
1853
+ async resolveOwner(goal) {
1854
+ const live = getAgents()?.get?.(goal.ownerSessionId)
1855
+ if (live && typeof live === 'object') return live
1856
+ return recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
1857
+ },
1858
+ async notify({ goal, message }) {
1859
+ let agent = getAgents()?.get?.(goal.ownerSessionId)
1860
+ if (!agent) {
1861
+ const recovered = await recoverScheduleOwner(goal, 'long-goal', { preferResolve: true })
1862
+ agent = recovered?.agent ?? recovered ?? null
1863
+ }
1864
+ if (!agent || typeof agent.followup !== 'function') {
1865
+ log(`long-goal ${goal.id} has no live session ${goal.ownerSessionId} to notify`)
1866
+ return { delivered: false }
1867
+ }
1868
+ await outbox.enqueue(goal.ownerSessionId, () => agent.followup({
1869
+ id: randomUUID(),
1870
+ role: 'user',
1871
+ content: [{ type: 'text', text: message }],
1872
+ source: { kind: 'user' },
1873
+ }))
1874
+ return { delivered: true }
1875
+ },
1876
+ config: {
1877
+ phaseBudget: {
1878
+ maxModelCalls: cfg.maxModelCallsPerRun,
1879
+ maxTokens: cfg.maxTokensPerRun,
1880
+ },
1881
+ },
1882
+ log,
1883
+ now: () => Date.now(),
1884
+ tickSeconds: 5,
1885
+ })
1886
+
1820
1887
  // Recovery runs once at mount; tools wait for it so a run left active by a
1821
1888
  // dead host reads as interrupted before the first tool call sees it. A
1822
1889
  // failure to initialize the state directory is kept and reported by every
@@ -1859,6 +1926,15 @@ export function apply(ctx, config) {
1859
1926
  } catch (error) {
1860
1927
  log(`cannot load scheduled runs from ${scheduler.stateFile}: ${error?.message ?? error}`)
1861
1928
  }
1929
+ // Long goals survive the host on their own: init marks the phases that were
1930
+ // mid-run as resumable and the manager continues them on its next tick.
1931
+ try {
1932
+ const goals = await longGoal.init()
1933
+ const active = goals.filter(item => ['planning', 'running', 'paused'].includes(item.status)).length
1934
+ if (goals.length > 0) log(`long goals: ${goals.length} loaded, ${active} to continue`)
1935
+ } catch (error) {
1936
+ log(`cannot load long goals: ${error?.message ?? error}`)
1937
+ }
1862
1938
  if (!(cfg.keepRuns > 0) || typeof store.prune !== 'function') return
1863
1939
  try {
1864
1940
  const { removed } = await store.prune({ olderThanDays: cfg.keepRuns })
@@ -2076,6 +2152,212 @@ export function apply(ctx, config) {
2076
2152
  },
2077
2153
  }))
2078
2154
 
2155
+ ctx.tools.register(defineTool({
2156
+ name: 'superagent_goal',
2157
+ description:
2158
+ 'Run a long-term goal as several phases. A natural-language goal is split into 2–8 phases by a phase planner, '
2159
+ + 'or you can pass the phases explicitly. Each phase is a normal run with its own planner and parallel workers; '
2160
+ + 'independent phases run at the same time; later phases receive the earlier phases\' reports. The goal record is '
2161
+ + 'persisted, so after a host restart it resumes the interrupted phase instead of starting over. A phase that '
2162
+ + 'keeps failing, or a goal that stops making progress, opens a decision that a person answers with action '
2163
+ + '"answer" — no goal-level question is guessed by the model. Per-phase and whole-goal model budgets are hard '
2164
+ + 'stops. Use superagent_status/superagent_cancel on the phase run ids it reports. Prefer this over '
2165
+ + 'superagent_start when the work has milestones that must happen in order over a long horizon.',
2166
+ properties: {
2167
+ action: {
2168
+ type: 'string',
2169
+ enum: ['create', 'status', 'list', 'answer', 'resume', 'pause', 'cancel'],
2170
+ description: 'create a goal, read one, list them, answer an open decision, resume/pause/cancel the goal.',
2171
+ },
2172
+ goal_id: { type: 'string', description: 'Goal id returned by action=create; required except for create/list.' },
2173
+ goal: {
2174
+ type: 'string',
2175
+ description: 'create: the complete long-term outcome. Be concrete about the finished state and where the work lives.',
2176
+ },
2177
+ phases: {
2178
+ type: 'array',
2179
+ description: 'create: optional explicit phases. Omit to let the phase planner split the goal. Each item is '
2180
+ + '{id?, title, objective, depends_on?, acceptance?, max_rounds?, max_wall_clock_minutes?, deliverables?}. '
2181
+ + 'acceptance uses the same {text, check?} shape as superagent_start; at least one condition per phase.',
2182
+ items: {
2183
+ type: 'object',
2184
+ properties: {
2185
+ id: { type: 'string', description: 'Short id, e.g. "p1"; unique and referenced by depends_on.' },
2186
+ title: { type: 'string', description: 'Short name shown in the phase table.' },
2187
+ objective: { type: 'string', description: 'What this phase must produce; later phases read its report.' },
2188
+ depends_on: {
2189
+ type: 'array',
2190
+ items: { type: 'string' },
2191
+ description: 'Phase ids that must complete before this one starts. Omit for independent phases.',
2192
+ },
2193
+ acceptance: {
2194
+ type: 'array',
2195
+ items: {
2196
+ type: 'object',
2197
+ properties: {
2198
+ id: { type: 'string' },
2199
+ text: { type: 'string' },
2200
+ check: {
2201
+ type: 'object',
2202
+ properties: {
2203
+ type: { type: 'string', enum: ['command', 'file'] },
2204
+ command: { type: 'string' },
2205
+ cwd: { type: 'string' },
2206
+ timeout_seconds: { type: 'number' },
2207
+ path: { type: 'string' },
2208
+ must_exist: { type: 'boolean' },
2209
+ },
2210
+ required: ['type'],
2211
+ },
2212
+ },
2213
+ required: ['text'],
2214
+ },
2215
+ },
2216
+ max_rounds: { type: 'number', description: 'Rounds this phase may retry before it stops (default 3).' },
2217
+ max_wall_clock_minutes: { type: 'number', description: 'Wall-clock cap for this phase (default 120).' },
2218
+ deliverables: { type: 'array', items: { type: 'string' }, description: 'Optional paths to report.' },
2219
+ },
2220
+ required: ['objective'],
2221
+ },
2222
+ },
2223
+ cwd: { type: 'string', description: 'Workspace every phase and every machine check runs in (default: current cwd).' },
2224
+ max_parallel_phases: { type: 'number', description: 'Phases allowed in flight at once (default 2, max 8).' },
2225
+ max_attempts_per_phase: {
2226
+ type: 'number',
2227
+ description: 'Attempts per phase before it asks a person (default 2). Attempts also require a different '
2228
+ + 'failure signature; an identical no-change failure stops earlier.',
2229
+ },
2230
+ max_rounds_per_phase: { type: 'number', description: 'Default goal-mode rounds inside one phase run (default 3).' },
2231
+ no_progress_rounds: { type: 'number', description: 'Goal mode: identical failing rounds before a phase stops (default 2).' },
2232
+ phase_budget: {
2233
+ type: 'object',
2234
+ description: 'Per-phase-run hard cap. Narrows to what remains of the goal budget.',
2235
+ properties: {
2236
+ max_model_calls: { type: 'number' },
2237
+ max_tokens: { type: 'number' },
2238
+ },
2239
+ },
2240
+ budget: {
2241
+ type: 'object',
2242
+ description: 'Whole-goal hard cap across every phase and retry; reaching it stops the goal.',
2243
+ properties: {
2244
+ max_model_calls: { type: 'number' },
2245
+ max_tokens: { type: 'number' },
2246
+ },
2247
+ },
2248
+ max_wall_clock_minutes: { type: 'number', description: 'Whole-goal wall-clock cap before it stalls (default 1440).' },
2249
+ stall_after_minutes: {
2250
+ type: 'number',
2251
+ description: 'No completed phase for this long opens a stall decision (default 180).',
2252
+ },
2253
+ auto_resume: {
2254
+ type: 'boolean',
2255
+ description: 'Continue automatically after a host restart (default true). false leaves it paused for a person.',
2256
+ },
2257
+ decision_id: { type: 'string', description: 'answer: the id shown in action=status.' },
2258
+ answer: {
2259
+ type: 'string',
2260
+ description: 'answer: one of the decision options. retry starts a fresh attempt for the phase; skip cascades '
2261
+ + 'to dependents; stop ends the goal; continue resets a stall; answer (worker question) needs note.',
2262
+ },
2263
+ note: {
2264
+ type: 'string',
2265
+ description: 'answer: a new instruction for retry, or the actual answer text for a worker question.',
2266
+ },
2267
+ limit: { type: 'number', description: 'list: maximum rows (default 20).' },
2268
+ },
2269
+ required: ['action'],
2270
+ async execute(args = {}, exec) {
2271
+ const check = requireAgent(exec)
2272
+ if (check.error) return check.error
2273
+ try {
2274
+ await ready
2275
+ if (stateError) return describeError(stateError)
2276
+ const action = String(args.action ?? '').trim().toLowerCase()
2277
+ if (action === 'create') {
2278
+ const phases = Array.isArray(args.phases)
2279
+ ? args.phases.map(entry => ({
2280
+ id: entry?.id,
2281
+ title: entry?.title,
2282
+ objective: entry?.objective,
2283
+ dependsOn: entry?.depends_on ?? entry?.dependsOn,
2284
+ acceptance: Array.isArray(entry?.acceptance)
2285
+ ? entry.acceptance.map(acceptanceFromToolArgs)
2286
+ : entry?.acceptance,
2287
+ maxRounds: entry?.max_rounds ?? entry?.maxRounds,
2288
+ maxWallClockMinutes: entry?.max_wall_clock_minutes ?? entry?.maxWallClockMinutes,
2289
+ deliverables: entry?.deliverables,
2290
+ }))
2291
+ : undefined
2292
+ const created = await longGoal.create({
2293
+ goal: args.goal,
2294
+ phases,
2295
+ cwd: args.cwd,
2296
+ maxParallelPhases: args.max_parallel_phases,
2297
+ maxAttemptsPerPhase: args.max_attempts_per_phase,
2298
+ maxRoundsPerPhase: args.max_rounds_per_phase,
2299
+ noProgressRounds: args.no_progress_rounds,
2300
+ phaseBudget: args.phase_budget
2301
+ ? {
2302
+ maxModelCalls: args.phase_budget.max_model_calls,
2303
+ maxTokens: args.phase_budget.max_tokens,
2304
+ }
2305
+ : undefined,
2306
+ budget: args.budget
2307
+ ? { maxModelCalls: args.budget.max_model_calls, maxTokens: args.budget.max_tokens }
2308
+ : undefined,
2309
+ maxWallClockMinutes: args.max_wall_clock_minutes,
2310
+ stallAfterMinutes: args.stall_after_minutes,
2311
+ autoResume: args.auto_resume,
2312
+ parentSessionId: check.agent.id,
2313
+ })
2314
+ const { goal, runs } = await longGoal.status(created.id)
2315
+ return `${formatLongGoal(goal, runs)}\n\nCreated in the background. Poll with `
2316
+ + `superagent_goal action=status goal_id=${goal.id}; phase runs continue after this call.`
2317
+ }
2318
+ if (action === 'list') {
2319
+ const limit = Math.max(1, Math.min(100, Number(args.limit) || 20))
2320
+ const goals = (await longGoal.list()).slice(0, limit)
2321
+ if (goals.length === 0) return 'No long-term goals recorded.'
2322
+ return goals.map(goal => {
2323
+ const phases = goal.phases ?? []
2324
+ const done = phases.filter(phase => phase.status === 'completed').length
2325
+ return `- ${goal.id} [${goal.status}] ${done}/${phases.length} phases — ${String(goal.goal).slice(0, 120)}`
2326
+ }).join('\n')
2327
+ }
2328
+ const goalId = String(args.goal_id ?? '').trim()
2329
+ if (!goalId) return describeError(`action=${action} requires goal_id`)
2330
+ if (action === 'status') {
2331
+ const { goal, runs } = await longGoal.status(goalId)
2332
+ return formatLongGoal(goal, runs)
2333
+ }
2334
+ if (action === 'answer') {
2335
+ const goal = await longGoal.answer(
2336
+ goalId,
2337
+ String(args.decision_id ?? '').trim(),
2338
+ args.answer,
2339
+ { note: args.note, parent: check.agent, clientTimeZone: exec.clientTimeZone },
2340
+ )
2341
+ const { goal: fresh, runs } = await longGoal.status(goal.id)
2342
+ return formatLongGoal(fresh, runs)
2343
+ }
2344
+ if (action === 'resume') {
2345
+ await longGoal.resume(goalId)
2346
+ } else if (action === 'pause') {
2347
+ await longGoal.pause(goalId)
2348
+ } else if (action === 'cancel') {
2349
+ await longGoal.cancel(goalId)
2350
+ } else {
2351
+ return describeError(`unknown action ${JSON.stringify(action)}`)
2352
+ }
2353
+ const { goal, runs } = await longGoal.status(goalId)
2354
+ return formatLongGoal(goal, runs)
2355
+ } catch (error) {
2356
+ return describeError(error)
2357
+ }
2358
+ },
2359
+ }))
2360
+
2079
2361
  // Files on disk can be newer than the code this host loaded: a package update
2080
2362
  // only takes effect after DSH restarts. Surface the mismatch instead of
2081
2363
  // letting the user wonder why the new version behaves like the old one.
@@ -3965,9 +4247,10 @@ export function apply(ctx, config) {
3965
4247
  scheduleOwners.clear()
3966
4248
  }
3967
4249
  if (typeof ctx.on === 'function') ctx.on('dispose', stopScheduler)
4250
+ if (typeof ctx.on === 'function') ctx.on('dispose', () => longGoal.close())
3968
4251
 
3969
4252
  log(
3970
- `registered ${auditor ? 12 : 11} tools; state ${store.root}`
4253
+ `registered ${auditor ? 13 : 12} tools; state ${store.root}`
3971
4254
  + `${cfg.controlPort === null ? '' : `; control port ${cfg.controlPort}`}`
3972
4255
  + `${cfg.workbenchPort === null ? '' : `; workbench ${workbenchRoot} on port ${cfg.workbenchPort}`}`
3973
4256
  + `${cfg.consolePort === null ? '' : `; console on port ${cfg.consolePort}`}`