@kolisachint/hoocode-agent 0.4.78 → 0.4.79

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.
Files changed (79) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/core/agent-frontmatter.d.ts +5 -7
  3. package/dist/core/agent-frontmatter.d.ts.map +1 -1
  4. package/dist/core/agent-frontmatter.js +2 -4
  5. package/dist/core/agent-frontmatter.js.map +1 -1
  6. package/dist/core/agent-registry.d.ts +12 -1
  7. package/dist/core/agent-registry.d.ts.map +1 -1
  8. package/dist/core/agent-registry.js +38 -3
  9. package/dist/core/agent-registry.js.map +1 -1
  10. package/dist/core/agent-session.d.ts.map +1 -1
  11. package/dist/core/agent-session.js +3 -3
  12. package/dist/core/agent-session.js.map +1 -1
  13. package/dist/core/dispatch-evaluator.d.ts +1 -1
  14. package/dist/core/dispatch-evaluator.d.ts.map +1 -1
  15. package/dist/core/dispatch-evaluator.js +1 -1
  16. package/dist/core/dispatch-evaluator.js.map +1 -1
  17. package/dist/core/messages.d.ts.map +1 -1
  18. package/dist/core/messages.js +24 -6
  19. package/dist/core/messages.js.map +1 -1
  20. package/dist/core/model-categories.d.ts +14 -8
  21. package/dist/core/model-categories.d.ts.map +1 -1
  22. package/dist/core/model-categories.js +13 -24
  23. package/dist/core/model-categories.js.map +1 -1
  24. package/dist/core/provider-health.d.ts +1 -1
  25. package/dist/core/provider-health.d.ts.map +1 -1
  26. package/dist/core/provider-health.js +1 -1
  27. package/dist/core/provider-health.js.map +1 -1
  28. package/dist/core/settings-manager.d.ts +3 -2
  29. package/dist/core/settings-manager.d.ts.map +1 -1
  30. package/dist/core/settings-manager.js.map +1 -1
  31. package/dist/core/subagent-inbox.d.ts +92 -0
  32. package/dist/core/subagent-inbox.d.ts.map +1 -0
  33. package/dist/core/subagent-inbox.js +245 -0
  34. package/dist/core/subagent-inbox.js.map +1 -0
  35. package/dist/core/subagent-pool.d.ts +3 -7
  36. package/dist/core/subagent-pool.d.ts.map +1 -1
  37. package/dist/core/subagent-pool.js +9 -62
  38. package/dist/core/subagent-pool.js.map +1 -1
  39. package/dist/core/system-prompt.d.ts +1 -1
  40. package/dist/core/system-prompt.d.ts.map +1 -1
  41. package/dist/core/system-prompt.js +8 -8
  42. package/dist/core/system-prompt.js.map +1 -1
  43. package/dist/core/task-store.d.ts +6 -5
  44. package/dist/core/task-store.d.ts.map +1 -1
  45. package/dist/core/task-store.js +4 -3
  46. package/dist/core/task-store.js.map +1 -1
  47. package/dist/core/tools/index.d.ts +1 -1
  48. package/dist/core/tools/index.d.ts.map +1 -1
  49. package/dist/core/tools/index.js +1 -1
  50. package/dist/core/tools/index.js.map +1 -1
  51. package/dist/core/tools/subagent.d.ts +23 -20
  52. package/dist/core/tools/subagent.d.ts.map +1 -1
  53. package/dist/core/tools/subagent.js +267 -163
  54. package/dist/core/tools/subagent.js.map +1 -1
  55. package/dist/core/tools/todo.d.ts.map +1 -1
  56. package/dist/core/tools/todo.js +10 -6
  57. package/dist/core/tools/todo.js.map +1 -1
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +1 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/init-templates.generated.d.ts.map +1 -1
  63. package/dist/init-templates.generated.js +1 -1
  64. package/dist/init-templates.generated.js.map +1 -1
  65. package/dist/main.d.ts.map +1 -1
  66. package/dist/main.js +5 -5
  67. package/dist/main.js.map +1 -1
  68. package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
  69. package/dist/modes/interactive/components/task-panel.js +11 -1
  70. package/dist/modes/interactive/components/task-panel.js.map +1 -1
  71. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  72. package/dist/modes/interactive/interactive-mode.js +1 -1
  73. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  74. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  75. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  76. package/examples/extensions/sandbox/package.json +1 -1
  77. package/examples/extensions/with-deps/package.json +1 -1
  78. package/package.json +4 -4
  79. package/templates/agents/general-purpose.md +1 -1
@@ -12,62 +12,27 @@
12
12
  */
13
13
  import { Text } from "@kolisachint/hoocode-tui";
14
14
  import { Type } from "typebox";
15
- import { getAgentDir } from "../../config.js";
16
- import { EXECUTE_TASK_TOOL_NAME, MODEL_INHERIT } from "../agent-frontmatter.js";
15
+ import { TASK_TOOL_NAME } from "../agent-frontmatter.js";
17
16
  import { loadAgentRegistry } from "../agent-registry.js";
18
17
  import { defineTool } from "../extensions/types.js";
19
- import { resolveModelReference } from "../model-categories.js";
20
18
  import { getProviderExhaustion } from "../provider-health.js";
21
19
  import { SessionManager } from "../session-manager.js";
22
- import { SettingsManager } from "../settings-manager.js";
23
20
  import { delegateAllowList, isDelegateAllowed } from "../subagent-depth.js";
21
+ import { subagentInbox } from "../subagent-inbox.js";
24
22
  import { getSubagentPool } from "../subagent-pool-instance.js";
25
23
  import { taskStore } from "../task-store.js";
26
- /**
27
- * Condense a (possibly multi-line, bulleted) agent description into a single
28
- * useful one-liner for the agent picker list.
29
- *
30
- * Built-in agent descriptions open with a boilerplate header ("Use this
31
- * subagent ONLY when:") followed by "when to use" bullets and a "DO NOT use"
32
- * section. Taking the first line alone yields that identical header for every
33
- * agent, so instead surface the first meaningful bullets (or the first prose
34
- * line) from the positive "when to use" region.
35
- */
36
- export function summarizeAgentDescription(description) {
37
- const lines = description
38
- .split("\n")
39
- .map((line) => line.trim())
40
- .filter((line) => line.length > 0);
41
- if (lines.length === 0)
42
- return "";
43
- // Keep only the positive region: everything before a "DO NOT use" section.
44
- const stop = lines.findIndex((line) => /^(do\s*not|don'?t|avoid)\b/i.test(line));
45
- const region = stop === -1 ? lines : lines.slice(0, stop);
46
- // Drop a leading header line (e.g. "Use this subagent ONLY when:").
47
- const body = region.length > 1 && region[0].endsWith(":") ? region.slice(1) : region;
48
- const stripBullet = (line) => line.replace(/^[-*\u2022]\s+/, "").trim();
49
- const bullets = body
50
- .filter((line) => /^[-*\u2022]\s+/.test(line))
51
- .map(stripBullet)
52
- .filter((line) => line.length > 0);
53
- const summary = bullets.length > 0 ? bullets.slice(0, 3).join("; ") : (body[0] ?? lines[0] ?? "").replace(/:$/, "");
54
- const MAX = 200;
55
- return summary.length > MAX ? `${summary.slice(0, MAX - 1).trimEnd()}\u2026` : summary;
56
- }
57
- /** Render the available agents as a "- name: description" list for prompts. */
58
- function describeAvailableAgents(cwd) {
59
- const agents = loadAgentRegistry({ cwd }).list();
60
- if (agents.length === 0)
61
- return "(no agents available)";
62
- return agents.map((a) => `- ${a.name}: ${summarizeAgentDescription(a.description)}`).join("\n");
63
- }
64
- /** System prompt appendix for the main session when the ExecuteTask tool is enabled.
65
- * Instructs the parent agent on when and how to delegate effectively. */
66
- export function buildTaskMainPrompt(cwd = process.cwd()) {
67
- return `You have access to the **ExecuteTask** tool. Use it to delegate self-contained tasks to specialized subagents that run in their own isolated context and return only their final answer.
68
-
69
- Available agents (choose one via \`subagent_type\`):
70
- ${describeAvailableAgents(cwd)}
24
+ // Re-exported from its home in agent-registry (where formatAgentsForPrompt uses
25
+ // it to render the roster) so existing importers keep working without creating a
26
+ // tools -> registry -> tools cycle.
27
+ export { summarizeAgentDescription } from "../agent-registry.js";
28
+ /** System prompt appendix for the main session when the Task tool is enabled.
29
+ * Instructs the parent agent on when and how to delegate effectively. The
30
+ * available agents themselves are listed once, authoritatively, in the
31
+ * `<available_agents>` block the system prompt emits whenever the Task tool is
32
+ * active (see agent-session `_rebuildSystemPrompt`); this appendix references
33
+ * that list rather than re-rendering the roster and paying for it twice. */
34
+ export function buildTaskMainPrompt() {
35
+ return `You have access to the **Task** tool. Use it to delegate self-contained tasks to specialized subagents that run in their own isolated context and return only their final answer. Pick an agent by name from the <available_agents> list in this prompt and pass it as \`subagent_type\`.
71
36
 
72
37
  When to delegate:
73
38
  1. The work is self-contained and you only need the final result, not intermediate steps.
@@ -75,11 +40,7 @@ When to delegate:
75
40
  3. The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug).
76
41
  4. You need to run a long command or test suite and wait for its output without blocking your own reasoning.
77
42
 
78
- Model categories:
79
- - \`complexity: "fast\`\` — quick reads, simple lookups, grep/find operations
80
- - \`complexity: "standard\`\` — multi-file edits, moderate reasoning, test runs
81
- - \`complexity: "capable\`\` — deep architecture changes, complex refactors, full PRs
82
- If omitted, the agent's default model is used.
43
+ Model tier (optional \`complexity\`): set \`fast\` for quick reads/lookups, \`standard\` for multi-file edits, \`capable\` for deep architecture work. It maps to a model from \`settings.modelCategories\`. Omit it to use the agent's default; an agent that pins its own model ignores \`complexity\`.
83
44
 
84
45
  Guidelines:
85
46
  - Choose the agent whose description best matches the task.
@@ -87,8 +48,9 @@ Guidelines:
87
48
  - Do NOT delegate tasks that require tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.
88
49
  - The subagent returns ONLY its final answer. Its intermediate reasoning, tool calls, and output are hidden from you.
89
50
  - Delegate proactively when work is self-contained or parallelizable: multi-step investigation, read-only exploration (use \`explore\`), research before changes (use \`plan\`), drafting a standalone file/section, or running a long command/test suite. Dispatch independent subtasks in the same turn. Handle only trivial single-step edits or tightly interactive back-and-forth inline.
90
- - All ExecuteTask calls run as background tasks (non-blocking). The agent loop continues while the subagent runs. Results arrive as follow-up messages automatically. Use TaskOutput to poll for results while a subagent is running.
91
- - To continue a previous subagent (for example one that returned partial results), call ExecuteTask again with \`resume_task_id\` set to its task_id; it resumes with its full prior transcript and \`prompt\` is your follow-up.`;
51
+ - Some agents run in the background (non-blocking); force it per call with \`background: true\` (or \`background: false\` to wait inline). A background Task does not block your turn and does not return its answer inline: you get a short notification ("explore#1 finished") and the full result is held for you to pull with \`TaskOutput\`. Keep working in the meantime.
52
+ - Use **TaskOutput** to manage background subagents: \`TaskOutput(list: true)\` shows every running/finished subagent and what each is doing; \`TaskOutput("explore#1")\` reads a finished subagent's full result (or reports its status if still running); \`TaskOutput(wait: true)\` blocks until a named task — or, with no task_id, ALL outstanding subagents — finish. Dispatch a batch in one turn, then barrier on them with \`TaskOutput(wait: true)\`.
53
+ - To continue a previous subagent (for example one that returned partial results), call Task again with \`resume_task_id\` set to its task_id; it resumes with its full prior transcript and \`prompt\` is your follow-up.`;
92
54
  }
93
55
  const taskParams = Type.Object({
94
56
  description: Type.String({
@@ -100,14 +62,14 @@ const taskParams = Type.Object({
100
62
  subagent_type: Type.String({
101
63
  description: "The name of the specialized agent to delegate to. Must be one of the available agents.",
102
64
  }),
103
- item_id: Type.Optional(Type.Number({
104
- description: "Optional. References a TodoWrite item id to link this dispatch to a plan item. The task panel shows the linkage.",
105
- })),
106
65
  complexity: Type.Optional(Type.Union([Type.Literal("fast"), Type.Literal("standard"), Type.Literal("capable")], {
107
- description: "Model category: fast (quick reads/lookups), standard (multi-file edits), capable (deep architecture). Omit to use the agent's default model.",
66
+ description: "Model tier for this dispatch: fast (quick reads/lookups), standard (multi-file edits), capable (deep architecture). Maps to settings.modelCategories. Ignored if the chosen agent pins its own model; omit to use the agent's default.",
67
+ })),
68
+ background: Type.Optional(Type.Boolean({
69
+ description: "Set true to run non-blocking: you get a short notification when it finishes and pull the full result with TaskOutput; set false to wait and get the answer inline. Defaults to the agent's own background setting.",
108
70
  })),
109
71
  resume_task_id: Type.Optional(Type.String({
110
- description: "Optional. To continue a previous subagent run, pass its task_id (returned by an earlier ExecuteTask or TaskOutput call). The subagent resumes with its full prior transcript and `prompt` is your follow-up instruction.",
72
+ description: "Optional. To continue a previous subagent run, pass its task_id (returned by an earlier Task or TaskOutput call). The subagent resumes with its full prior transcript and `prompt` is your follow-up instruction.",
111
73
  })),
112
74
  });
113
75
  /**
@@ -124,31 +86,30 @@ function summarize(task) {
124
86
  name = `${name.slice(0, 59)}…`;
125
87
  return name;
126
88
  }
127
- /** Create the ExecuteTask tool definition. Registered as a customTool when enabled. */
128
- export function createExecuteTaskToolDefinition(cwd = process.cwd()) {
129
- const agentList = describeAvailableAgents(cwd);
130
- // All ExecuteTask calls run as background tools. The agent loop runs the
131
- // dispatch detached: the parent keeps reasoning and the subagent's answer is
132
- // injected as a follow-up message when it finishes. TaskOutput can poll for
133
- // results while the subagent runs.
89
+ /** Create the Task tool definition. Registered as a customTool when enabled. */
90
+ export function createTaskToolDefinition(cwd = process.cwd()) {
91
+ // Agents whose definitions opt into background execution. The agent loop reads
92
+ // the tool's `background` flag per call and, for these, runs the dispatch
93
+ // detached: the parent keeps reasoning and the subagent's answer is injected as
94
+ // a follow-up message when it finishes (no polling needed). A per-call
95
+ // `background` argument overrides the agent's default in either direction.
96
+ const backgroundAgents = collectBackgroundAgentNames(cwd);
134
97
  return defineTool({
135
- name: EXECUTE_TASK_TOOL_NAME,
136
- label: EXECUTE_TASK_TOOL_NAME,
137
- background: () => true,
98
+ name: TASK_TOOL_NAME,
99
+ label: TASK_TOOL_NAME,
100
+ background: (toolCall) => {
101
+ const override = toolCall.arguments?.background;
102
+ if (typeof override === "boolean")
103
+ return override;
104
+ return backgroundAgents.has(String(toolCall.arguments?.subagent_type ?? ""));
105
+ },
106
+ // Kept lean: the available agents are listed in the system prompt, and the
107
+ // `complexity`/`background` semantics live in their parameter descriptions —
108
+ // repeating them here would re-spend those tokens on every turn.
138
109
  description: [
139
- "Delegate a focused task to a specialized subagent that runs in a fresh, isolated context (it cannot see this conversation).",
140
- "Select the agent via `subagent_type`; pass everything it needs via `prompt`. The subagent returns only its final answer.",
141
- "Available agents:",
142
- agentList,
143
- "Model categories: fast (quick reads/lookups), standard (multi-file edits), capable (deep architecture). Omit to use agent default.",
144
- "All ExecuteTask calls run as background tasks. The agent loop continues while the subagent runs. Results arrive as follow-up messages.",
145
- "Use TaskOutput to poll for results while a subagent is running.",
146
- "WHEN TO USE: (1) self-contained work where you only need the final result;",
147
- "(2) parallel investigation/edits without losing your reasoning chain;",
148
- "(3) a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs);",
149
- "(4) a long command or test suite you want to run without blocking your reasoning.",
150
- "Do NOT use for tasks needing tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.",
151
- "Delegate proactively for self-contained or parallelizable work; handle only trivial single-step or tightly interactive work inline.",
110
+ "Delegate a focused task to a specialized subagent that runs in a fresh, isolated context (it cannot see this conversation). Choose one of the available agents (listed in the system prompt) via `subagent_type` and pass everything it needs via `prompt`; the subagent returns only its final answer.",
111
+ "WHEN TO USE: (1) self-contained work where you only need the final result; (2) parallel investigation/edits without losing your reasoning chain; (3) a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs); (4) a long command or test suite you want to run without blocking your reasoning.",
112
+ "Do NOT use for tasks needing tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about. Delegate proactively for self-contained or parallelizable work; handle only trivial single-step or tightly interactive work inline.",
152
113
  ].join("\n"),
153
114
  promptSnippet: "delegate a self-contained task to a specialized subagent (choose via subagent_type)",
154
115
  parameters: taskParams,
@@ -230,37 +191,69 @@ export function createExecuteTaskToolDefinition(cwd = process.cwd()) {
230
191
  agent: params.subagent_type,
231
192
  });
232
193
  registerSubagentDispatch(params.subagent_type);
233
- // Always dispatch and await the subagent's full result here. Background
234
- // agents (def.background) are made non-blocking by the agent loop via this
235
- // tool's `background` flag: the loop runs this execute() detached, answers
236
- // the call with a placeholder, and injects the answer below as a follow-up
237
- // message when it resolves. Foreground agents block the turn as usual.
238
194
  taskStore.update(task.id, { status: "in_progress" });
239
- // Resolve model: complexity category > agent definition default > parent model
240
- let resolvedModel = ctx.model?.id;
241
- if (params.complexity) {
242
- // Model category from ExecuteTask's complexity parameter
243
- const settingsManager = SettingsManager.create(ctx.cwd, getAgentDir());
244
- const globalSettings = settingsManager.getGlobalSettings();
245
- const projectSettings = settingsManager.getProjectSettings();
246
- const settings = { ...globalSettings, ...projectSettings };
247
- const categoryModel = resolveModelReference(params.complexity, settings);
248
- if (categoryModel)
249
- resolvedModel = categoryModel;
250
- }
251
- else if (def.model && def.model !== MODEL_INHERIT) {
252
- // Agent definition's default model (fallback)
253
- resolvedModel = def.model;
254
- }
255
195
  // Fork agents inherit the parent's conversation via a forked session.
256
196
  const forkSessionFile = def.fork
257
197
  ? resolveForkSessionFile(def, ctx.sessionManager?.getSessionFile(), ctx.cwd)
258
198
  : undefined;
199
+ // `complexity` is passed as the model: the pool's spawn() already lets a
200
+ // non-`inherit` agent model win, then resolves a category string (fast/
201
+ // standard/capable) via settings.modelCategories. So a pinned-model agent
202
+ // ignores complexity, and an `inherit` agent picks up the requested tier —
203
+ // no settings lookup needed here.
204
+ const dispatchModel = params.complexity ?? ctx.model?.id;
205
+ // Whether this call runs detached. The agent loop reads the tool's
206
+ // `background` flag (the same predicate) to run execute() detached; we
207
+ // recompute it here to choose the notify-and-pull return shape.
208
+ const isBackground = params.background ?? backgroundAgents.has(params.subagent_type);
209
+ if (isBackground) {
210
+ // Notify-and-pull: register the dispatch in the inbox under a pre-allocated
211
+ // id, await it, retain the body in the inbox, and return a compact
212
+ // notification (not the body). The model pulls the body with TaskOutput.
213
+ const poolTaskId = `dispatch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
214
+ const label = subagentInbox.nextLabel(params.subagent_type);
215
+ subagentInbox.observe(pool);
216
+ subagentInbox.start(poolTaskId, label, params.subagent_type);
217
+ try {
218
+ const dispatchResult = await pool.dispatch(params.prompt, {
219
+ forceAgent: params.subagent_type,
220
+ context: "",
221
+ model: dispatchModel,
222
+ provider: ctx.model?.provider,
223
+ sessionFile: forkSessionFile,
224
+ taskId: poolTaskId,
225
+ });
226
+ subagentInbox.finish(poolTaskId, dispatchResult);
227
+ return finalizeDispatchResult(dispatchResult, params.subagent_type, task.id, poolTaskId, {
228
+ taskId: poolTaskId,
229
+ label,
230
+ });
231
+ }
232
+ catch (error) {
233
+ const reason = error instanceof Error ? error.message : String(error);
234
+ taskStore.update(task.id, { status: "failed" });
235
+ subagentInbox.fail(poolTaskId, reason);
236
+ // A background dispatch reports failure as a compact notification, not a
237
+ // thrown tool error — the call was already answered by a placeholder.
238
+ return {
239
+ content: [{ type: "text", text: `${label} failed ✗ — ${reason}` }],
240
+ details: {
241
+ subagent_type: params.subagent_type,
242
+ ok: false,
243
+ error: reason,
244
+ taskId: task.id,
245
+ poolTaskId,
246
+ background: true,
247
+ },
248
+ };
249
+ }
250
+ }
251
+ // Foreground: block the turn and return the subagent's full answer inline.
259
252
  try {
260
253
  const dispatchResult = await pool.dispatch(params.prompt, {
261
254
  forceAgent: params.subagent_type,
262
255
  context: "",
263
- model: resolvedModel,
256
+ model: dispatchModel,
264
257
  provider: ctx.model?.provider,
265
258
  sessionFile: forkSessionFile,
266
259
  });
@@ -306,6 +299,15 @@ export function resolveForkSessionFile(def, parentSessionPath, cwd) {
306
299
  function registerSubagentDispatch(type) {
307
300
  taskStore.upsertAgent({ id: type, name: type, role: "subagent", kind: "subagent", state: "running" });
308
301
  }
302
+ /** Names of agents configured to run in the background (non-blocking). */
303
+ function collectBackgroundAgentNames(cwd) {
304
+ const names = new Set();
305
+ for (const agent of loadAgentRegistry({ cwd }).list()) {
306
+ if (agent.background)
307
+ names.add(agent.name);
308
+ }
309
+ return names;
310
+ }
309
311
  /**
310
312
  * Merge a child subagent's task subtree into the parent's task store, rooting
311
313
  * each top-level node under the dispatching task (`parentTaskId`). Recurses so a
@@ -328,8 +330,16 @@ function mergeChildTaskTree(nodes, parentTaskId) {
328
330
  }
329
331
  });
330
332
  }
331
- /** Extract the final answer from a finished dispatch, updating the task panel. */
332
- function finalizeDispatchResult(dispatchResult, subagentType, taskStoreId, resumeHandle) {
333
+ /**
334
+ * Update the task panel from a finished dispatch and shape the tool result.
335
+ *
336
+ * Foreground calls return the subagent's full answer inline and signal a hard
337
+ * failure by throwing (the agent loop derives a tool's error state from a thrown
338
+ * error). A background call passes `background`: the body already lives in the
339
+ * inbox, so it returns a compact, self-contained notification (success or
340
+ * failure) and never throws — the call was already answered by a placeholder.
341
+ */
342
+ function finalizeDispatchResult(dispatchResult, subagentType, taskStoreId, resumeHandle, background) {
333
343
  const result = dispatchResult.result;
334
344
  const resultData = result?.result_data;
335
345
  const usage = resultData?.usage;
@@ -342,12 +352,23 @@ function finalizeDispatchResult(dispatchResult, subagentType, taskStoreId, resum
342
352
  taskStore.addAgentStats(subagentType, { input: usage.input, output: usage.output, cost: usage.cost });
343
353
  }
344
354
  if (!result || !result.ok) {
345
- // Signal failure by throwing: the agent loop derives a tool's error state
346
- // from a thrown error, not from a returned flag.
347
355
  const failNote = result?.usedInheritedModelFallback ? "inherited-model retry failed" : undefined;
348
356
  taskStore.update(taskStoreId, { status: "failed", usage, note: failNote });
349
357
  taskStore.patchAgent(subagentType, { state: "failed" });
350
358
  const reason = result?.error ?? (result?.status ? `subagent ${result.status}` : "unknown error");
359
+ if (background) {
360
+ return {
361
+ content: [{ type: "text", text: `${background.label} failed ✗ — ${reason}` }],
362
+ details: {
363
+ subagent_type: subagentType,
364
+ ok: false,
365
+ error: reason,
366
+ taskId: taskStoreId,
367
+ poolTaskId: background.taskId,
368
+ background: true,
369
+ },
370
+ };
371
+ }
351
372
  const stderr = result?.stderr?.trim();
352
373
  throw new Error(`Subagent (${subagentType}) failed: ${reason}${stderr ? `\nstderr: ${stderr.slice(-500)}` : ""}`);
353
374
  }
@@ -367,90 +388,173 @@ function finalizeDispatchResult(dispatchResult, subagentType, taskStoreId, resum
367
388
  if (result.status === "partial" && resumeHandle) {
368
389
  answer += `\n\n[Partial result. To continue this subagent, call Task again with resume_task_id="${resumeHandle}".]`;
369
390
  }
391
+ if (background) {
392
+ // Compact notification: the body is retained in the inbox; the model pulls it
393
+ // with TaskOutput. Keeps a wide swarm from flooding the parent's context.
394
+ const partial = result.status === "partial" ? " (partial — resume to continue)" : "";
395
+ const outstanding = subagentInbox.outstanding().length;
396
+ const tail = outstanding > 0 ? ` ${outstanding} still running.` : "";
397
+ const text = `${background.label} finished ✓${partial} — ${summarize(answer)}.${tail}\n` +
398
+ `Read the full result with TaskOutput("${background.label}").`;
399
+ return {
400
+ content: [{ type: "text", text }],
401
+ details: {
402
+ subagent_type: subagentType,
403
+ ok: true,
404
+ taskId: taskStoreId,
405
+ poolTaskId: background.taskId,
406
+ background: true,
407
+ },
408
+ };
409
+ }
370
410
  return {
371
411
  content: [{ type: "text", text: answer }],
372
412
  details: { subagent_type: subagentType, ok: true, taskId: taskStoreId, poolTaskId: resumeHandle },
373
413
  };
374
414
  }
375
415
  const taskOutputParams = Type.Object({
376
- task_id: Type.String({
377
- description: "The task_id of a background (or previously dispatched) subagent, as returned by the Task tool.",
378
- }),
416
+ task_id: Type.Optional(Type.String({
417
+ description: 'Handle of a background subagent — its task_id or friendly label (e.g. "explore#1") from a Task notification. Omit (or set list:true) to see every background task.',
418
+ })),
419
+ list: Type.Optional(Type.Boolean({
420
+ description: "List all background subagents with their status (running/done/failed) and current activity. No result bodies are returned.",
421
+ })),
422
+ wait: Type.Optional(Type.Boolean({
423
+ description: "Block until the named task finishes — or, with no task_id, until all outstanding subagents finish (a swarm barrier) — before returning. Bounded by timeout_ms.",
424
+ })),
425
+ timeout_ms: Type.Optional(Type.Number({ description: "Maximum time to block in wait mode, in milliseconds (default 120000)." })),
379
426
  });
427
+ const TASK_OUTPUT_DEFAULT_TIMEOUT_MS = 120_000;
428
+ /** Whole seconds a record has run (so far, or until it settled). */
429
+ function recordElapsed(rec) {
430
+ const end = rec.endedAt ?? Date.now();
431
+ return `${Math.max(0, Math.round((end - rec.startedAt) / 1000))}s`;
432
+ }
433
+ /** A compact roster of every known background subagent — status + activity, no bodies. */
434
+ function formatTaskRoster() {
435
+ const all = subagentInbox.list();
436
+ const outstanding = subagentInbox.outstanding().length;
437
+ if (all.length === 0) {
438
+ return {
439
+ content: [{ type: "text", text: "No background subagents have been dispatched." }],
440
+ details: { status: "empty", ok: true, outstanding: 0 },
441
+ };
442
+ }
443
+ const lines = all.map((r) => {
444
+ const when = recordElapsed(r);
445
+ switch (r.lifecycle) {
446
+ case "running":
447
+ return `- ${r.label} running ${when}${r.lastActivity ? ` · ${r.lastActivity}` : ""}`;
448
+ case "done":
449
+ return `- ${r.label} done (uncollected) ${when} — ${r.summaryLine ?? ""}`;
450
+ case "collected":
451
+ return `- ${r.label} collected ${when} — ${r.summaryLine ?? ""}`;
452
+ default:
453
+ return `- ${r.label} ${r.lifecycle} ✗ — ${r.error ?? "unknown error"}`;
454
+ }
455
+ });
456
+ const header = `${all.length} background subagent${all.length === 1 ? "" : "s"} (${outstanding} running):`;
457
+ const hint = all.some((r) => r.lifecycle === "done") ? '\nRead a finished one with TaskOutput("<label>").' : "";
458
+ return {
459
+ content: [{ type: "text", text: `${header}\n${lines.join("\n")}${hint}` }],
460
+ details: { status: "list", ok: true, outstanding },
461
+ };
462
+ }
380
463
  /**
381
- * TaskOutput tool: poll a background subagent and collect its final answer.
382
- * Returns the current status while running, or the subagent's final answer once
383
- * complete. Registered alongside the Task tool when subagents are enabled.
464
+ * TaskOutput tool: check on background subagents and pull their results.
465
+ *
466
+ * Background `Task` calls don't push their body into the conversation — they
467
+ * leave it in the inbox and post a compact notification. TaskOutput is how the
468
+ * model pulls a body, checks liveness, or waits. It never throws on a valid
469
+ * handle (an error tool result would only confuse the loop): it reports status
470
+ * instead. Modes: `list` (roster), a `task_id` to read/check one, and `wait` to
471
+ * block until one task — or all outstanding tasks — finish.
384
472
  */
385
473
  export function createTaskOutputToolDefinition() {
386
474
  return defineTool({
387
475
  name: "TaskOutput",
388
476
  label: "TaskOutput",
389
477
  description: [
390
- "Check the status of a background subagent and collect its final answer once it finishes.",
391
- "Pass the task_id returned by a background ExecuteTask call. While the subagent runs this reports its status; once complete it returns only the subagent's final answer.",
478
+ "Check on background subagents dispatched via Task, and pull their results.",
479
+ 'Pass a task_id/label (e.g. "explore#1") to read a finished subagent\'s full result, or to see its status while it runs.',
480
+ "Set list:true (or omit task_id) to list every background subagent with its status and current activity.",
481
+ "Set wait:true to block until that task finishes — or, with no task_id, until all outstanding subagents finish (a swarm barrier).",
482
+ "It never errors on a valid handle: a running task reports status, a finished one returns its result, an already-read one says so.",
392
483
  ].join("\n"),
393
- promptSnippet: "check status / collect the result of a background subagent",
484
+ promptSnippet: "check status / list / collect the results of background subagents",
394
485
  parameters: taskOutputParams,
395
486
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
396
- const pool = getSubagentPool(ctx.cwd);
397
- const status = pool.get_status(params.task_id);
398
- // If the task is still running, wait for it to finish (with a timeout)
399
- // instead of asking the model to poll. This eliminates the extra LLM
400
- // round-trip that polling would require.
401
- if (status === "running" || status === "queued") {
402
- const TASK_OUTPUT_TIMEOUT_MS = 120_000;
403
- const result = await Promise.race([
404
- pool.wait_for_completion(params.task_id),
405
- new Promise((resolve) => setTimeout(() => resolve(undefined), TASK_OUTPUT_TIMEOUT_MS)),
406
- ]);
407
- if (!result) {
408
- return {
409
- content: [
410
- {
411
- type: "text",
412
- text: `Subagent task "${params.task_id}" is still ${pool.get_status(params.task_id)}. Timed out after ${TASK_OUTPUT_TIMEOUT_MS / 1000}s.`,
413
- },
414
- ],
415
- details: { task_id: params.task_id, status: pool.get_status(params.task_id), ok: true },
416
- };
417
- }
418
- return formatTaskOutputResult(result, params.task_id);
487
+ // Touch the pool so the inbox is wired to its progress stream for activity.
488
+ subagentInbox.observe(getSubagentPool(ctx.cwd));
489
+ const handle = params.task_id?.trim();
490
+ // Barrier: wait for the target (or all outstanding) to settle first.
491
+ if (params.wait) {
492
+ const timeout = params.timeout_ms ?? TASK_OUTPUT_DEFAULT_TIMEOUT_MS;
493
+ if (handle)
494
+ await subagentInbox.waitFor(handle, timeout);
495
+ else
496
+ await subagentInbox.waitForAll(timeout);
497
+ }
498
+ // Roster when asked, or when no specific task was named.
499
+ if (params.list || !handle) {
500
+ return formatTaskRoster();
419
501
  }
420
- if (status === "unknown") {
502
+ const rec = subagentInbox.get(handle);
503
+ if (!rec) {
421
504
  return {
422
505
  content: [
423
506
  {
424
507
  type: "text",
425
- text: `No result available for task "${params.task_id}" (status: unknown). It may not exist or its result was already collected.`,
508
+ text: `No background task "${handle}". Call TaskOutput with list:true to see active tasks.`,
426
509
  },
427
510
  ],
428
- details: { task_id: params.task_id, status, ok: false },
511
+ details: { task_id: handle, status: "unknown", ok: false },
429
512
  };
430
513
  }
431
- const result = pool.collect(params.task_id);
432
- if (!result) {
433
- throw new Error(`No result available for task "${params.task_id}" (status: ${status}). It may not exist or its result was already collected.`);
514
+ if (rec.lifecycle === "running") {
515
+ const activity = rec.lastActivity ? ` (currently: ${rec.lastActivity})` : "";
516
+ return {
517
+ content: [
518
+ {
519
+ type: "text",
520
+ text: `${rec.label} is still running — ${recordElapsed(rec)} elapsed${activity}. Call TaskOutput again, or with wait:true to block until it finishes.`,
521
+ },
522
+ ],
523
+ details: { task_id: handle, status: "running", ok: true },
524
+ };
434
525
  }
435
- return formatTaskOutputResult(result, params.task_id);
526
+ if (rec.lifecycle === "done") {
527
+ const collected = subagentInbox.collect(handle);
528
+ const body = collected?.body ?? rec.summaryLine ?? "(subagent returned no output)";
529
+ return {
530
+ content: [{ type: "text", text: body }],
531
+ details: { task_id: handle, status: "done", ok: true },
532
+ };
533
+ }
534
+ if (rec.lifecycle === "collected") {
535
+ return {
536
+ content: [
537
+ {
538
+ type: "text",
539
+ text: `${rec.label} was already delivered — ${rec.summaryLine ?? "(no summary kept)"}.`,
540
+ },
541
+ ],
542
+ details: { task_id: handle, status: "collected", ok: true },
543
+ };
544
+ }
545
+ // failed / stalled / timeout
546
+ return {
547
+ content: [
548
+ { type: "text", text: `${rec.label} ${rec.lifecycle} ✗ — ${rec.error ?? "unknown error"}.` },
549
+ ],
550
+ details: { task_id: handle, status: rec.lifecycle, ok: false },
551
+ };
436
552
  },
437
553
  renderCall(args, theme) {
438
- const text = theme.fg("toolTitle", theme.bold("TaskOutput ")) + theme.fg("dim", String(args.task_id ?? ""));
554
+ const target = args.list ? "list" : String(args.task_id ?? "");
555
+ const text = theme.fg("toolTitle", theme.bold("TaskOutput ")) + theme.fg("dim", args.wait ? `${target} (wait)` : target);
439
556
  return new Text(text, 0, 0);
440
557
  },
441
558
  });
442
559
  }
443
- /** Format a completed subagent result for TaskOutput. */
444
- function formatTaskOutputResult(result, taskId) {
445
- if (!result.ok) {
446
- const reason = result.error ?? (result.status ? `subagent ${result.status}` : "unknown error");
447
- throw new Error(`Background subagent "${taskId}" failed: ${reason}`);
448
- }
449
- const resultData = result.result_data;
450
- const answer = resultData?.summary || "(subagent returned no output)";
451
- return {
452
- content: [{ type: "text", text: answer }],
453
- details: { task_id: taskId, status: result.status ?? "complete", ok: true },
454
- };
455
- }
456
560
  //# sourceMappingURL=subagent.js.map