@kolisachint/hoocode-agent 0.4.10 → 0.4.12

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 (60) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/cli/args.d.ts +2 -0
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +3 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/config.d.ts +16 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +22 -0
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/lifeguard.d.ts +1 -0
  11. package/dist/core/lifeguard.d.ts.map +1 -1
  12. package/dist/core/lifeguard.js +6 -0
  13. package/dist/core/lifeguard.js.map +1 -1
  14. package/dist/core/subagent-pool-instance.d.ts +19 -0
  15. package/dist/core/subagent-pool-instance.d.ts.map +1 -0
  16. package/dist/core/subagent-pool-instance.js +40 -0
  17. package/dist/core/subagent-pool-instance.js.map +1 -0
  18. package/dist/core/subagent-pool.d.ts +18 -6
  19. package/dist/core/subagent-pool.d.ts.map +1 -1
  20. package/dist/core/subagent-pool.js +33 -14
  21. package/dist/core/subagent-pool.js.map +1 -1
  22. package/dist/core/subagent-result.d.ts +34 -0
  23. package/dist/core/subagent-result.d.ts.map +1 -0
  24. package/dist/core/subagent-result.js +89 -0
  25. package/dist/core/subagent-result.js.map +1 -0
  26. package/dist/core/subagent.d.ts +6 -46
  27. package/dist/core/subagent.d.ts.map +1 -1
  28. package/dist/core/subagent.js +5 -141
  29. package/dist/core/subagent.js.map +1 -1
  30. package/dist/core/task-store.d.ts +3 -2
  31. package/dist/core/task-store.d.ts.map +1 -1
  32. package/dist/core/task-store.js +3 -2
  33. package/dist/core/task-store.js.map +1 -1
  34. package/dist/core/tools/subagent.d.ts +1 -1
  35. package/dist/core/tools/subagent.d.ts.map +1 -1
  36. package/dist/core/tools/subagent.js +46 -41
  37. package/dist/core/tools/subagent.js.map +1 -1
  38. package/dist/main.d.ts.map +1 -1
  39. package/dist/main.js +1 -0
  40. package/dist/main.js.map +1 -1
  41. package/dist/modes/interactive/components/task-panel.d.ts +4 -3
  42. package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
  43. package/dist/modes/interactive/components/task-panel.js +52 -21
  44. package/dist/modes/interactive/components/task-panel.js.map +1 -1
  45. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  46. package/dist/modes/interactive/components/tool-execution.js +38 -6
  47. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  48. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  49. package/dist/modes/interactive/interactive-mode.js +16 -15
  50. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  51. package/dist/modes/print-mode.d.ts +2 -0
  52. package/dist/modes/print-mode.d.ts.map +1 -1
  53. package/dist/modes/print-mode.js +30 -1
  54. package/dist/modes/print-mode.js.map +1 -1
  55. package/docs/routing.md +13 -2
  56. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  57. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  58. package/examples/extensions/sandbox/package.json +1 -1
  59. package/examples/extensions/with-deps/package.json +1 -1
  60. package/package.json +4 -4
@@ -1,21 +1,14 @@
1
1
  /**
2
- * Subagent core: spawn a fresh, isolated agent loop for one delegated task.
2
+ * Subagent definitions: modes, per-mode tool allowlists, and system prompts.
3
3
  *
4
- * Each invocation creates a brand-new in-process AgentSession with:
5
- * - a clean, minimal system prompt (the mode template, no parent history),
6
- * - an in-memory session (nothing persisted to disk),
7
- * - a tool allowlist scoped to the mode.
8
- *
9
- * The subagent runs to completion and returns ONLY its final answer string;
10
- * intermediate reasoning, tool calls, and tool output are discarded.
4
+ * Subagents run as isolated `hoocode` child processes managed by SubagentPool.
5
+ * This module is the single source of truth for what each mode is allowed to do
6
+ * (tool allowlist) and the clean system prompt it runs with.
11
7
  */
12
8
  import { EMBEDDED_SUBAGENT_PROMPTS } from "../init-templates.generated.js";
13
- import { createExtensionRuntime } from "./extensions/index.js";
14
- import { createAgentSession } from "./sdk.js";
15
- import { SessionManager } from "./session-manager.js";
16
9
  export const SUBAGENT_MODES = ["explore", "edit", "test", "fix", "review", "doc"];
17
10
  /** Tool allowlist per mode. Read-only modes deliberately omit edit/write. */
18
- const MODE_TOOLS = {
11
+ export const MODE_TOOLS = {
19
12
  explore: ["read", "grep", "find", "ls", "bash"],
20
13
  edit: ["read", "edit", "write", "grep", "find", "ls", "bash"],
21
14
  test: ["read", "bash", "grep", "find", "ls"],
@@ -31,133 +24,4 @@ export function getSubagentSystemPrompt(mode) {
31
24
  }
32
25
  return prompt;
33
26
  }
34
- /**
35
- * Resource loader that gives the subagent a clean context: just the mode's
36
- * system prompt, with no project context files, skills, prompts, or extensions.
37
- */
38
- class MinimalResourceLoader {
39
- systemPrompt;
40
- extensionsResult;
41
- constructor(systemPrompt) {
42
- this.systemPrompt = systemPrompt;
43
- this.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() };
44
- }
45
- getExtensions() {
46
- return this.extensionsResult;
47
- }
48
- getSkills() {
49
- return { skills: [], diagnostics: [] };
50
- }
51
- getPrompts() {
52
- return { prompts: [], diagnostics: [] };
53
- }
54
- getThemes() {
55
- return { themes: [], diagnostics: [] };
56
- }
57
- getAgentsFiles() {
58
- return { agentsFiles: [], warnings: [] };
59
- }
60
- getSystemPrompt() {
61
- return this.systemPrompt;
62
- }
63
- getAppendSystemPrompt() {
64
- return [];
65
- }
66
- addAppendSystemPrompt(_text) {
67
- // Subagents do not accept dynamic prompt appendages.
68
- }
69
- extendResources(_paths) {
70
- // Subagents do not accept additional resource paths.
71
- }
72
- async reload() {
73
- // Nothing to reload: the context is fixed at construction.
74
- }
75
- }
76
- function composePrompt(task, context) {
77
- const trimmedContext = context?.trim();
78
- const trimmedTask = task.trim();
79
- if (trimmedContext) {
80
- return `Context from the calling agent:\n\n${trimmedContext}\n\nTask: ${trimmedTask}`;
81
- }
82
- return `Task: ${trimmedTask}`;
83
- }
84
- /**
85
- * Run one subagent task to completion and return only its final answer.
86
- */
87
- export async function runSubagent(options) {
88
- const { task, context, mode, cwd, model, modelRegistry, signal } = options;
89
- if (signal?.aborted) {
90
- return { mode, answer: "", ok: false, error: "Subagent aborted before starting." };
91
- }
92
- const systemPrompt = getSubagentSystemPrompt(mode);
93
- const { session } = await createAgentSession({
94
- cwd,
95
- model,
96
- modelRegistry,
97
- tools: MODE_TOOLS[mode],
98
- resourceLoader: new MinimalResourceLoader(systemPrompt),
99
- sessionManager: SessionManager.inMemory(cwd),
100
- });
101
- const onAbort = () => {
102
- void session.abort();
103
- };
104
- signal?.addEventListener("abort", onAbort, { once: true });
105
- try {
106
- if (!session.model) {
107
- return { mode, answer: "", ok: false, error: "No model available for the subagent." };
108
- }
109
- await session.bindExtensions({ onError: () => { } });
110
- await session.prompt(composePrompt(task, context), {
111
- expandPromptTemplates: false,
112
- source: "extension",
113
- });
114
- const messages = session.messages;
115
- const last = messages[messages.length - 1];
116
- if (last?.role === "assistant") {
117
- const assistant = last;
118
- if (assistant.stopReason === "error" || assistant.stopReason === "aborted") {
119
- return {
120
- mode,
121
- answer: "",
122
- ok: false,
123
- error: assistant.errorMessage || `Subagent ${assistant.stopReason}.`,
124
- };
125
- }
126
- }
127
- const answer = session.getLastAssistantText() ?? "";
128
- const stats = session.getSessionStats();
129
- return {
130
- mode,
131
- answer,
132
- ok: true,
133
- usage: {
134
- input: stats.tokens.input,
135
- output: stats.tokens.output,
136
- cacheRead: stats.tokens.cacheRead,
137
- cacheWrite: stats.tokens.cacheWrite,
138
- cost: stats.cost,
139
- },
140
- };
141
- }
142
- catch (error) {
143
- const stats = session.getSessionStats();
144
- return {
145
- mode,
146
- answer: "",
147
- ok: false,
148
- error: error instanceof Error ? error.message : String(error),
149
- usage: {
150
- input: stats.tokens.input,
151
- output: stats.tokens.output,
152
- cacheRead: stats.tokens.cacheRead,
153
- cacheWrite: stats.tokens.cacheWrite,
154
- cost: stats.cost,
155
- },
156
- };
157
- }
158
- finally {
159
- signal?.removeEventListener("abort", onAbort);
160
- session.dispose();
161
- }
162
- }
163
27
  //# sourceMappingURL=subagent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../src/core/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAA6B,MAAM,uBAAuB,CAAC;AAG1F,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAItD,MAAM,CAAC,MAAM,cAAc,GAA4B,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;AAE3G,6EAA6E;AAC7E,MAAM,UAAU,GAAmC;IAClD,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;IAC/C,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;IAC7D,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;IAC5C,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;IAC5D,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;IAC9C,GAAG,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;CAC5D,CAAC;AAoCF,mEAAmE;AACnE,MAAM,UAAU,uBAAuB,CAAC,IAAkB,E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AK,CAAC,MAAM,CAAC,UAAU;gBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;aAChB;SACD,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,KAAK,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;QACxC,OAAO;YACN,IAAI;YACJ,MAAM,EAAE,EAAE;YACV,EAAE,EAAE,KAAK;YACT,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;YAC7D,KAAK,EAAE;gBACN,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK;gBACzB,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM;gBAC3B,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;gBACjC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;gBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;aAChB;SACD,CAAC;IACH,CAAC;YAAS,CAAC;QACV,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC;AAAA,CACD","sourcesContent":["/**\n * Subagent core: spawn a fresh, isolated agent loop for one delegated task.\n *\n * Each invocation creates a brand-new in-process AgentSession with:\n * - a clean, minimal system prompt (the mode template, no parent history),\n * - an in-memory session (nothing persisted to disk),\n * - a tool allowlist scoped to the mode.\n *\n * The subagent runs to completion and returns ONLY its final answer string;\n * intermediate reasoning, tool calls, and tool output are discarded.\n */\n\nimport type { AssistantMessage, Model } from \"@kolisachint/hoocode-ai\";\nimport { EMBEDDED_SUBAGENT_PROMPTS } from \"../init-templates.generated.js\";\nimport { createExtensionRuntime, type LoadExtensionsResult } from \"./extensions/index.js\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport type { ResourceExtensionPaths, ResourceLoader } from \"./resource-loader.js\";\nimport { createAgentSession } from \"./sdk.js\";\nimport { SessionManager } from \"./session-manager.js\";\n\nexport type SubagentMode = \"explore\" | \"edit\" | \"test\" | \"fix\" | \"review\" | \"doc\";\n\nexport const SUBAGENT_MODES: readonly SubagentMode[] = [\"explore\", \"edit\", \"test\", \"fix\", \"review\", \"doc\"];\n\n/** Tool allowlist per mode. Read-only modes deliberately omit edit/write. */\nconst MODE_TOOLS: Record<SubagentMode, string[]> = {\n\texplore: [\"read\", \"grep\", \"find\", \"ls\", \"bash\"],\n\tedit: [\"read\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"bash\"],\n\ttest: [\"read\", \"bash\", \"grep\", \"find\", \"ls\"],\n\tfix: [\"read\", \"edit\", \"write\", \"bash\", \"grep\", \"find\", \"ls\"],\n\treview: [\"read\", \"grep\", \"find\", \"ls\", \"bash\"],\n\tdoc: [\"read\", \"write\", \"edit\", \"grep\", \"find\", \"ls\", \"bash\"],\n};\n\nexport interface RunSubagentOptions {\n\t/** The task to delegate. */\n\ttask: string;\n\t/** Optional context distilled from the parent conversation. */\n\tcontext?: string;\n\t/** Which subagent mode to run. */\n\tmode: SubagentMode;\n\t/** Working directory for the subagent. */\n\tcwd: string;\n\t/** Model to use. When omitted the subagent picks the configured default. */\n\tmodel?: Model<any>;\n\t/** Model registry to reuse (shares the parent's auth). */\n\tmodelRegistry?: ModelRegistry;\n\t/** Abort signal from the parent; aborts the subagent loop. */\n\tsignal?: AbortSignal;\n}\n\nexport interface SubagentResult {\n\tmode: SubagentMode;\n\t/** The subagent's final answer (its last assistant text), or \"\" on failure. */\n\tanswer: string;\n\tok: boolean;\n\t/** Populated when ok is false. */\n\terror?: string;\n\t/** Token and cost usage from the subagent session, if available. */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\n/** Return the clean, minimal system prompt for a subagent mode. */\nexport function getSubagentSystemPrompt(mode: SubagentMode): string {\n\tconst prompt = EMBEDDED_SUBAGENT_PROMPTS[mode];\n\tif (!prompt) {\n\t\tthrow new Error(`No system prompt template for subagent mode \"${mode}\"`);\n\t}\n\treturn prompt;\n}\n\n/**\n * Resource loader that gives the subagent a clean context: just the mode's\n * system prompt, with no project context files, skills, prompts, or extensions.\n */\nclass MinimalResourceLoader implements ResourceLoader {\n\tprivate readonly extensionsResult: LoadExtensionsResult;\n\n\tconstructor(private readonly systemPrompt: string) {\n\t\tthis.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() };\n\t}\n\n\tgetExtensions(): LoadExtensionsResult {\n\t\treturn this.extensionsResult;\n\t}\n\n\tgetSkills() {\n\t\treturn { skills: [], diagnostics: [] };\n\t}\n\n\tgetPrompts() {\n\t\treturn { prompts: [], diagnostics: [] };\n\t}\n\n\tgetThemes() {\n\t\treturn { themes: [], diagnostics: [] };\n\t}\n\n\tgetAgentsFiles() {\n\t\treturn { agentsFiles: [], warnings: [] };\n\t}\n\n\tgetSystemPrompt(): string | undefined {\n\t\treturn this.systemPrompt;\n\t}\n\n\tgetAppendSystemPrompt(): string[] {\n\t\treturn [];\n\t}\n\n\taddAppendSystemPrompt(_text: string): void {\n\t\t// Subagents do not accept dynamic prompt appendages.\n\t}\n\n\textendResources(_paths: ResourceExtensionPaths): void {\n\t\t// Subagents do not accept additional resource paths.\n\t}\n\n\tasync reload(): Promise<void> {\n\t\t// Nothing to reload: the context is fixed at construction.\n\t}\n}\n\nfunction composePrompt(task: string, context: string | undefined): string {\n\tconst trimmedContext = context?.trim();\n\tconst trimmedTask = task.trim();\n\tif (trimmedContext) {\n\t\treturn `Context from the calling agent:\\n\\n${trimmedContext}\\n\\nTask: ${trimmedTask}`;\n\t}\n\treturn `Task: ${trimmedTask}`;\n}\n\n/**\n * Run one subagent task to completion and return only its final answer.\n */\nexport async function runSubagent(options: RunSubagentOptions): Promise<SubagentResult> {\n\tconst { task, context, mode, cwd, model, modelRegistry, signal } = options;\n\n\tif (signal?.aborted) {\n\t\treturn { mode, answer: \"\", ok: false, error: \"Subagent aborted before starting.\" };\n\t}\n\n\tconst systemPrompt = getSubagentSystemPrompt(mode);\n\tconst { session } = await createAgentSession({\n\t\tcwd,\n\t\tmodel,\n\t\tmodelRegistry,\n\t\ttools: MODE_TOOLS[mode],\n\t\tresourceLoader: new MinimalResourceLoader(systemPrompt),\n\t\tsessionManager: SessionManager.inMemory(cwd),\n\t});\n\n\tconst onAbort = () => {\n\t\tvoid session.abort();\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\tif (!session.model) {\n\t\t\treturn { mode, answer: \"\", ok: false, error: \"No model available for the subagent.\" };\n\t\t}\n\n\t\tawait session.bindExtensions({ onError: () => {} });\n\t\tawait session.prompt(composePrompt(task, context), {\n\t\t\texpandPromptTemplates: false,\n\t\t\tsource: \"extension\",\n\t\t});\n\n\t\tconst messages = session.messages;\n\t\tconst last = messages[messages.length - 1];\n\t\tif (last?.role === \"assistant\") {\n\t\t\tconst assistant = last as AssistantMessage;\n\t\t\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\t\t\treturn {\n\t\t\t\t\tmode,\n\t\t\t\t\tanswer: \"\",\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: assistant.errorMessage || `Subagent ${assistant.stopReason}.`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst answer = session.getLastAssistantText() ?? \"\";\n\t\tconst stats = session.getSessionStats();\n\t\treturn {\n\t\t\tmode,\n\t\t\tanswer,\n\t\t\tok: true,\n\t\t\tusage: {\n\t\t\t\tinput: stats.tokens.input,\n\t\t\t\toutput: stats.tokens.output,\n\t\t\t\tcacheRead: stats.tokens.cacheRead,\n\t\t\t\tcacheWrite: stats.tokens.cacheWrite,\n\t\t\t\tcost: stats.cost,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconst stats = session.getSessionStats();\n\t\treturn {\n\t\t\tmode,\n\t\t\tanswer: \"\",\n\t\t\tok: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tusage: {\n\t\t\t\tinput: stats.tokens.input,\n\t\t\t\toutput: stats.tokens.output,\n\t\t\t\tcacheRead: stats.tokens.cacheRead,\n\t\t\t\tcacheWrite: stats.tokens.cacheWrite,\n\t\t\t\tcost: stats.cost,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\tsession.dispose();\n\t}\n}\n"]}
1
+ {"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../src/core/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAI3E,MAAM,CAAC,MAAM,cAAc,GAA4B,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;AAE3G,6EAA6E;AAC7E,MAAM,CAAC,MAAM,UAAU,GAAmC;IACzD,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;IAC/C,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;IAC7D,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;IAC5C,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;IAC5D,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;IAC9C,GAAG,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC;CAC5D,CAAC;AAEF,mEAAmE;AACnE,MAAM,UAAU,uBAAuB,CAAC,IAAkB,EAAU;IACnE,MAAM,MAAM,GAAG,yBAAyB,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,gDAAgD,IAAI,GAAG,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * Subagent definitions: modes, per-mode tool allowlists, and system prompts.\n *\n * Subagents run as isolated `hoocode` child processes managed by SubagentPool.\n * This module is the single source of truth for what each mode is allowed to do\n * (tool allowlist) and the clean system prompt it runs with.\n */\n\nimport { EMBEDDED_SUBAGENT_PROMPTS } from \"../init-templates.generated.js\";\n\nexport type SubagentMode = \"explore\" | \"edit\" | \"test\" | \"fix\" | \"review\" | \"doc\";\n\nexport const SUBAGENT_MODES: readonly SubagentMode[] = [\"explore\", \"edit\", \"test\", \"fix\", \"review\", \"doc\"];\n\n/** Tool allowlist per mode. Read-only modes deliberately omit edit/write. */\nexport const MODE_TOOLS: Record<SubagentMode, string[]> = {\n\texplore: [\"read\", \"grep\", \"find\", \"ls\", \"bash\"],\n\tedit: [\"read\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"bash\"],\n\ttest: [\"read\", \"bash\", \"grep\", \"find\", \"ls\"],\n\tfix: [\"read\", \"edit\", \"write\", \"bash\", \"grep\", \"find\", \"ls\"],\n\treview: [\"read\", \"grep\", \"find\", \"ls\", \"bash\"],\n\tdoc: [\"read\", \"write\", \"edit\", \"grep\", \"find\", \"ls\", \"bash\"],\n};\n\n/** Return the clean, minimal system prompt for a subagent mode. */\nexport function getSubagentSystemPrompt(mode: SubagentMode): string {\n\tconst prompt = EMBEDDED_SUBAGENT_PROMPTS[mode];\n\tif (!prompt) {\n\t\tthrow new Error(`No system prompt template for subagent mode \"${mode}\"`);\n\t}\n\treturn prompt;\n}\n"]}
@@ -39,8 +39,9 @@ declare class TaskStore {
39
39
  /**
40
40
  * Remove all finished tasks (done or failed), keeping pending/in_progress ones.
41
41
  *
42
- * Called when the main agent moves on after a parallel subagent spawn: finished
43
- * tasks stay visible (with their final status) until that point, then retire.
42
+ * Called when a new user message arrives: finished subagent tasks stay visible
43
+ * (with their final status) for the whole turn and only retire when the user
44
+ * starts the next turn, so their outcome remains glanceable until then.
44
45
  */
45
46
  retireFinished(): void;
46
47
  list(): readonly Task[];
@@ -1 +1 @@
1
- {"version":3,"file":"task-store.d.ts","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,aAAa,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEvE,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,UAAU,CAAC;IACnB,4EAA4E;IAC5E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,mFAAmF;IACnF,KAAK,CAAC,EAAE;QACP,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;QACnB,IAAI,EAAE,MAAM,CAAC;KACb,CAAC;CACF;AAED,MAAM,WAAW,iBAAiB;IACjC,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC;AAE3F,KAAK,QAAQ,GAAG,MAAM,IAAI,CAAC;AAE3B,cAAM,SAAS;IACd,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAuB;IAEjD,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,IAAI,CAa3D;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CASzC;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAKvB;IAED;;;;;OAKG;IACH,cAAc,IAAI,IAAI,CAIrB;IAED,IAAI,IAAI,SAAS,IAAI,EAAE,CAEtB;IAED,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAKxC;IAED,yDAAyD;IACzD,KAAK,IAAI,IAAI,CAIZ;IAED,OAAO,CAAC,IAAI;CAKZ;AAED,uCAAuC;AACvC,eAAO,MAAM,SAAS,WAAkB,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\";\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Subagent mode when this task is owned by a subagent (e.g. \"explore\"). */\n\tsubagentMode?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsubagentMode?: string;\n}\n\nexport type TaskPatch = Partial<Pick<Task, \"title\" | \"status\" | \"subagentMode\" | \"usage\">>;\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) return;\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Remove all finished tasks (done or failed), keeping pending/in_progress ones.\n\t *\n\t * Called when the main agent moves on after a parallel subagent spawn: finished\n\t * tasks stay visible (with their final status) until that point, then retire.\n\t */\n\tretireFinished(): void {\n\t\tconst before = this.tasks.length;\n\t\tthis.tasks = this.tasks.filter((t) => t.status !== \"done\" && t.status !== \"failed\");\n\t\tif (this.tasks.length !== before) this.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/** Clear all tasks. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tprivate emit(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
1
+ {"version":3,"file":"task-store.d.ts","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,aAAa,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEvE,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,UAAU,CAAC;IACnB,4EAA4E;IAC5E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,mFAAmF;IACnF,KAAK,CAAC,EAAE;QACP,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;QACnB,IAAI,EAAE,MAAM,CAAC;KACb,CAAC;CACF;AAED,MAAM,WAAW,iBAAiB;IACjC,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC;AAE3F,KAAK,QAAQ,GAAG,MAAM,IAAI,CAAC;AAE3B,cAAM,SAAS;IACd,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAuB;IAEjD,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,IAAI,CAa3D;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CASzC;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAKvB;IAED;;;;;;OAMG;IACH,cAAc,IAAI,IAAI,CAIrB;IAED,IAAI,IAAI,SAAS,IAAI,EAAE,CAEtB;IAED,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAKxC;IAED,yDAAyD;IACzD,KAAK,IAAI,IAAI,CAIZ;IAED,OAAO,CAAC,IAAI;CAKZ;AAED,uCAAuC;AACvC,eAAO,MAAM,SAAS,WAAkB,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\";\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Subagent mode when this task is owned by a subagent (e.g. \"explore\"). */\n\tsubagentMode?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsubagentMode?: string;\n}\n\nexport type TaskPatch = Partial<Pick<Task, \"title\" | \"status\" | \"subagentMode\" | \"usage\">>;\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) return;\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Remove all finished tasks (done or failed), keeping pending/in_progress ones.\n\t *\n\t * Called when a new user message arrives: finished subagent tasks stay visible\n\t * (with their final status) for the whole turn and only retire when the user\n\t * starts the next turn, so their outcome remains glanceable until then.\n\t */\n\tretireFinished(): void {\n\t\tconst before = this.tasks.length;\n\t\tthis.tasks = this.tasks.filter((t) => t.status !== \"done\" && t.status !== \"failed\");\n\t\tif (this.tasks.length !== before) this.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/** Clear all tasks. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tprivate emit(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
@@ -49,8 +49,9 @@ class TaskStore {
49
49
  /**
50
50
  * Remove all finished tasks (done or failed), keeping pending/in_progress ones.
51
51
  *
52
- * Called when the main agent moves on after a parallel subagent spawn: finished
53
- * tasks stay visible (with their final status) until that point, then retire.
52
+ * Called when a new user message arrives: finished subagent tasks stay visible
53
+ * (with their final status) for the whole turn and only retire when the user
54
+ * starts the next turn, so their outcome remains glanceable until then.
54
55
  */
55
56
  retireFinished() {
56
57
  const before = this.tasks.length;
@@ -1 +1 @@
1
- {"version":3,"file":"task-store.js","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AA8BH,MAAM,SAAS;IACN,KAAK,GAAW,EAAE,CAAC;IACnB,MAAM,GAAG,CAAC,CAAC;IACF,SAAS,GAAG,IAAI,GAAG,EAAY,CAAC;IAEjD,MAAM,CAAC,KAAa,EAAE,OAAO,GAAsB,EAAE,EAAQ;QAC5D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,MAAM,IAAI,GAAS;YAClB,EAAE,EAAE,IAAI,CAAC,MAAM,EAAE;YACjB,KAAK,EAAE,KAAK,CAAC,IAAI,EAAE,IAAI,iBAAiB;YACxC,MAAM,EAAE,SAAS;YACjB,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,SAAS,EAAE,GAAG;YACd,SAAS,EAAE,GAAG;SACd,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,MAAM,CAAC,EAAU,EAAE,KAAgB,EAAQ;QAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QACjD,IAAI,CAAC,IAAI;YAAE,OAAO;QAClB,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS;YAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACxD,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS;YAAE,IAAI,CAAC,MAAM,GAAG,K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CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAAA,CAChC,CAAC;IAAA,CACF;IAED,yDAAyD;IACzD,KAAK,GAAS;QACb,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;QAChB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAChB,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;IAEO,IAAI,GAAS;QACpB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,QAAQ,EAAE,CAAC;QACZ,CAAC;IAAA,CACD;CACD;AAED,uCAAuC;AACvC,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\";\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Subagent mode when this task is owned by a subagent (e.g. \"explore\"). */\n\tsubagentMode?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsubagentMode?: string;\n}\n\nexport type TaskPatch = Partial<Pick<Task, \"title\" | \"status\" | \"subagentMode\" | \"usage\">>;\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) return;\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Remove all finished tasks (done or failed), keeping pending/in_progress ones.\n\t *\n\t * Called when the main agent moves on after a parallel subagent spawn: finished\n\t * tasks stay visible (with their final status) until that point, then retire.\n\t */\n\tretireFinished(): void {\n\t\tconst before = this.tasks.length;\n\t\tthis.tasks = this.tasks.filter((t) => t.status !== \"done\" && t.status !== \"failed\");\n\t\tif (this.tasks.length !== before) this.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/** Clear all tasks. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tprivate emit(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
1
+ {"version":3,"file":"task-store.js","source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AC,CAAC;QAChB,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;IAEO,IAAI,GAAS;QACpB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,QAAQ,EAAE,CAAC;QACZ,CAAC;IAAA,CACD;CACD;AAED,uCAAuC;AACvC,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\";\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Subagent mode when this task is owned by a subagent (e.g. \"explore\"). */\n\tsubagentMode?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsubagentMode?: string;\n}\n\nexport type TaskPatch = Partial<Pick<Task, \"title\" | \"status\" | \"subagentMode\" | \"usage\">>;\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) return;\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Remove all finished tasks (done or failed), keeping pending/in_progress ones.\n\t *\n\t * Called when a new user message arrives: finished subagent tasks stay visible\n\t * (with their final status) for the whole turn and only retire when the user\n\t * starts the next turn, so their outcome remains glanceable until then.\n\t */\n\tretireFinished(): void {\n\t\tconst before = this.tasks.length;\n\t\tthis.tasks = this.tasks.filter((t) => t.status !== \"done\" && t.status !== \"failed\");\n\t\tif (this.tasks.length !== before) this.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/** Clear all tasks. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tprivate emit(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
@@ -10,7 +10,7 @@
10
10
  * Instructs the parent agent on when and how to delegate effectively. */
11
11
  export declare const SUBAGENT_MAIN_PROMPT = "You have access to the **subagent** tool. Use it to delegate self-contained tasks to isolated subagent loops that run with their own context and return only their final answer.\n\nAvailable subagent modes:\n- explore: read-only investigation (read, grep, find, ls, bash).\n- edit: make a focused code change (read, edit, write, grep, find, ls, bash).\n- test: run tests and report (read, bash, grep, find, ls).\n- fix: diagnose and fix a failure (read, edit, write, bash, grep, find, ls).\n- review: read-only code review (read, grep, find, ls, bash).\n- doc: write documentation, README, or comments (read, write, edit, grep, find, ls, bash).\n\nWhen to delegate:\n1. The work is self-contained and you only need the final result, not intermediate steps.\n2. You want to investigate or edit something in parallel without losing your current context or reasoning chain.\n3. The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug).\n4. You need to run a long command or test suite and wait for its output without blocking your own reasoning.\n\nGuidelines:\n- Make every task specific and self-contained. The subagent cannot see this conversation.\n- Pass all necessary context (files, constraints, prior findings) via the `context` parameter.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning.\n- Do NOT delegate edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Intermediate reasoning, tool calls, and output are hidden from you.\n\nDispatch evaluator:\n- The dispatch evaluator determines if a subagent is needed. Do not spawn subagents directly unless the user explicitly requests it.\n- For simple single-file changes (<50 lines, read-only or trivial edit), handle them inline.\n- Use force=true to bypass evaluation when you are certain a subagent is required.";
12
12
  import type { ToolDefinition } from "../extensions/types.js";
13
- import { type SubagentMode } from "../subagent.js";
13
+ import type { SubagentMode } from "../subagent.js";
14
14
  export interface SubagentToolDetails {
15
15
  mode: SubagentMode;
16
16
  ok: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;0EAC0E;AAC1E,eAAO,MAAM,oBAAoB,82DA0BkD,CAAC;AAKpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE7D,OAAO,EAAe,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAmChE,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,YAAY,CAAC;IACnB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,6EAA6E;IAC7E,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAQD,sDAAsD;AACtD,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAG3D;AAOD,oFAAoF;AACpF,wBAAgB,4BAA4B,IAAI,cAAc,CAuF7D","sourcesContent":["/**\n * Subagent tool: delegate a focused task to a fresh, isolated agent loop.\n *\n * The tool registers a task in the shared task store (visible in the task panel),\n * runs the subagent to completion, and returns ONLY the subagent's final\n * answer. It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\n/** System prompt appendix for the main session when subagent tooling is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport const SUBAGENT_MAIN_PROMPT = `You have access to the **subagent** tool. Use it to delegate self-contained tasks to isolated subagent loops that run with their own context and return only their final answer.\n\nAvailable subagent modes:\n- explore: read-only investigation (read, grep, find, ls, bash).\n- edit: make a focused code change (read, edit, write, grep, find, ls, bash).\n- test: run tests and report (read, bash, grep, find, ls).\n- fix: diagnose and fix a failure (read, edit, write, bash, grep, find, ls).\n- review: read-only code review (read, grep, find, ls, bash).\n- doc: write documentation, README, or comments (read, write, edit, grep, find, ls, bash).\n\nWhen to delegate:\n1. The work is self-contained and you only need the final result, not intermediate steps.\n2. You want to investigate or edit something in parallel without losing your current context or reasoning chain.\n3. The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug).\n4. You need to run a long command or test suite and wait for its output without blocking your own reasoning.\n\nGuidelines:\n- Make every task specific and self-contained. The subagent cannot see this conversation.\n- Pass all necessary context (files, constraints, prior findings) via the \\`context\\` parameter.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning.\n- Do NOT delegate edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Intermediate reasoning, tool calls, and output are hidden from you.\n\nDispatch evaluator:\n- The dispatch evaluator determines if a subagent is needed. Do not spawn subagents directly unless the user explicitly requests it.\n- For simple single-file changes (<50 lines, read-only or trivial edit), handle them inline.\n- Use force=true to bypass evaluation when you are certain a subagent is required.`;\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { type AgentType, DispatchEvaluator } from \"../dispatch-evaluator.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport { runSubagent, type SubagentMode } from \"../subagent.js\";\nimport { taskStore } from \"../task-store.js\";\n\nconst subagentParams = Type.Object({\n\ttask: Type.String({\n\t\tdescription:\n\t\t\t\"The task to delegate. Make it specific and self-contained; the subagent cannot see this conversation.\",\n\t}),\n\tcontext: Type.String({\n\t\tdescription:\n\t\t\t'Context distilled from the conversation the subagent needs (files, constraints, prior findings). Pass \"\" if none.',\n\t}),\n\tmode: Type.Union(\n\t\t[\n\t\t\tType.Literal(\"explore\"),\n\t\t\tType.Literal(\"edit\"),\n\t\t\tType.Literal(\"test\"),\n\t\t\tType.Literal(\"fix\"),\n\t\t\tType.Literal(\"review\"),\n\t\t\tType.Literal(\"doc\"),\n\t\t],\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"explore: read-only investigation. edit: make a focused code change. test: run tests and report. fix: diagnose and fix a failure. review: read-only code review. doc: write documentation.\",\n\t\t},\n\t),\n\tforce: Type.Boolean({\n\t\tdescription:\n\t\t\t\"Bypass dispatch evaluation and spawn the subagent directly. Use when you are certain a subagent is required.\",\n\t\tdefault: false,\n\t}),\n});\n\ntype SubagentParams = Static<typeof subagentParams>;\n\nexport interface SubagentToolDetails {\n\tmode: SubagentMode;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** True when the evaluator handled the task inline instead of delegating. */\n\tinline?: boolean;\n}\n\n/** First line of the task, trimmed to a short summary for the task list/footer. */\nfunction summarize(task: string): string {\n\tconst firstLine = task.trim().split(\"\\n\")[0] ?? \"\";\n\treturn firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || \"(task)\";\n}\n\n/** Quick check: should this task go to a subagent? */\nexport function isSubagentRecommended(task: string): boolean {\n\tconst evaluator = new DispatchEvaluator();\n\treturn evaluator.evaluate(task).should_delegate;\n}\n\n/** Map evaluator AgentType to SubagentMode (they are compatible strings). */\nfunction toSubagentMode(agentType: AgentType | null): SubagentMode {\n\treturn (agentType as SubagentMode) ?? \"explore\";\n}\n\n/** Create the subagent tool definition. Registered as a customTool when enabled. */\nexport function createSubagentToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof subagentParams, SubagentToolDetails>({\n\t\tname: \"subagent\",\n\t\tlabel: \"Subagent\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Pass everything it needs via `context`. The subagent returns only its final answer.\",\n\t\t\t\"Modes: explore, edit, test, fix, review, doc.\",\n\t\t\t\"WHEN TO USE: (1) The work is self-contained and you do not need to see intermediate steps — only the final result.\",\n\t\t\t\"(2) You want to investigate or edit something in parallel without losing your current context or reasoning chain.\",\n\t\t\t\"(3) The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs).\",\n\t\t\t\"(4) You need to run a long command or test suite and wait for its output without blocking your own reasoning.\",\n\t\t\t\"Do NOT use for tasks that require tight back-and-forth with your current reasoning or that change files you are actively reasoning about.\",\n\t\t\t\"Use force=true to bypass dispatch evaluation when you are certain a subagent is required.\",\n\t\t].join(\" \"),\n\t\tpromptSnippet: \"delegate a self-contained task to an isolated subagent (modes: explore/edit/test/fix/review/doc)\",\n\t\tparameters: subagentParams,\n\n\t\tasync execute(_toolCallId, params: SubagentParams, signal, _onUpdate, ctx) {\n\t\t\tconst forcedMode = params.mode as SubagentMode;\n\n\t\t\t// Dispatch evaluation\n\t\t\tif (!params.force) {\n\t\t\t\tconst evaluator = new DispatchEvaluator();\n\t\t\t\tconst analysis = evaluator.evaluate(params.task);\n\t\t\t\tif (!analysis.should_delegate) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Task is simple enough for inline handling. Reason: ${analysis.reason}. Use force=true for subagent override.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: forcedMode, ok: true, taskId: 0, inline: true },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst mode = params.force\n\t\t\t\t? forcedMode\n\t\t\t\t: toSubagentMode(new DispatchEvaluator().evaluate(params.task).agent_type);\n\t\t\tconst summary = summarize(params.task);\n\n\t\t\tconst task = taskStore.create(summary, { subagentMode: mode });\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst result = await runSubagent({\n\t\t\t\t\ttask: params.task,\n\t\t\t\t\tcontext: params.context,\n\t\t\t\t\tmode,\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tmodel: ctx.model,\n\t\t\t\t\tmodelRegistry: ctx.modelRegistry,\n\t\t\t\t\tsignal: signal ?? ctx.signal,\n\t\t\t\t});\n\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\t// Signal failure by throwing: the agent loop derives a tool's error\n\t\t\t\t\t// state from a thrown error, not from a returned flag.\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\", usage: result.usage });\n\t\t\t\t\tthrow new Error(`Subagent (${mode}) failed: ${result.error ?? \"unknown error\"}`);\n\t\t\t\t}\n\n\t\t\t\t// Leave the task in the store with its final status. It stays visible in\n\t\t\t\t// the task panel until the main agent moves on (retireFinished is called\n\t\t\t\t// when the main agent starts its next turn).\n\t\t\t\ttaskStore.update(task.id, { status: \"done\", usage: result.usage });\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: result.answer || \"(subagent returned no output)\" }],\n\t\t\t\t\tdetails: { mode, ok: true, taskId: task.id },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst mode = args.mode ?? \"explore\";\n\t\t\tconst preview = summarize(args.task ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${mode}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;0EAC0E;AAC1E,eAAO,MAAM,oBAAoB,82DA0BkD,CAAC;AAKpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE7D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAqCnD,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,YAAY,CAAC;IACnB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,6EAA6E;IAC7E,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAgBD,sDAAsD;AACtD,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAG3D;AAED,oFAAoF;AACpF,wBAAgB,4BAA4B,IAAI,cAAc,CAuF7D","sourcesContent":["/**\n * Subagent tool: delegate a focused task to a fresh, isolated agent loop.\n *\n * The tool registers a task in the shared task store (visible in the task panel),\n * runs the subagent to completion, and returns ONLY the subagent's final\n * answer. It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\n/** System prompt appendix for the main session when subagent tooling is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport const SUBAGENT_MAIN_PROMPT = `You have access to the **subagent** tool. Use it to delegate self-contained tasks to isolated subagent loops that run with their own context and return only their final answer.\n\nAvailable subagent modes:\n- explore: read-only investigation (read, grep, find, ls, bash).\n- edit: make a focused code change (read, edit, write, grep, find, ls, bash).\n- test: run tests and report (read, bash, grep, find, ls).\n- fix: diagnose and fix a failure (read, edit, write, bash, grep, find, ls).\n- review: read-only code review (read, grep, find, ls, bash).\n- doc: write documentation, README, or comments (read, write, edit, grep, find, ls, bash).\n\nWhen to delegate:\n1. The work is self-contained and you only need the final result, not intermediate steps.\n2. You want to investigate or edit something in parallel without losing your current context or reasoning chain.\n3. The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug).\n4. You need to run a long command or test suite and wait for its output without blocking your own reasoning.\n\nGuidelines:\n- Make every task specific and self-contained. The subagent cannot see this conversation.\n- Pass all necessary context (files, constraints, prior findings) via the \\`context\\` parameter.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning.\n- Do NOT delegate edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Intermediate reasoning, tool calls, and output are hidden from you.\n\nDispatch evaluator:\n- The dispatch evaluator determines if a subagent is needed. Do not spawn subagents directly unless the user explicitly requests it.\n- For simple single-file changes (<50 lines, read-only or trivial edit), handle them inline.\n- Use force=true to bypass evaluation when you are certain a subagent is required.`;\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { DispatchEvaluator } from \"../dispatch-evaluator.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport type { SubagentMode } from \"../subagent.js\";\nimport { getSubagentPool } from \"../subagent-pool-instance.js\";\nimport type { SubagentResultFile } from \"../subagent-result.js\";\nimport { taskStore } from \"../task-store.js\";\n\nconst subagentParams = Type.Object({\n\ttask: Type.String({\n\t\tdescription:\n\t\t\t\"The task to delegate. Make it specific and self-contained; the subagent cannot see this conversation.\",\n\t}),\n\tcontext: Type.String({\n\t\tdescription:\n\t\t\t'Context distilled from the conversation the subagent needs (files, constraints, prior findings). Pass \"\" if none.',\n\t}),\n\tmode: Type.Union(\n\t\t[\n\t\t\tType.Literal(\"explore\"),\n\t\t\tType.Literal(\"edit\"),\n\t\t\tType.Literal(\"test\"),\n\t\t\tType.Literal(\"fix\"),\n\t\t\tType.Literal(\"review\"),\n\t\t\tType.Literal(\"doc\"),\n\t\t],\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"explore: read-only investigation. edit: make a focused code change. test: run tests and report. fix: diagnose and fix a failure. review: read-only code review. doc: write documentation.\",\n\t\t},\n\t),\n\tforce: Type.Boolean({\n\t\tdescription:\n\t\t\t\"Bypass dispatch evaluation and spawn the subagent directly. Use when you are certain a subagent is required.\",\n\t\tdefault: false,\n\t}),\n});\n\ntype SubagentParams = Static<typeof subagentParams>;\n\nexport interface SubagentToolDetails {\n\tmode: SubagentMode;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** True when the evaluator handled the task inline instead of delegating. */\n\tinline?: boolean;\n}\n\n/**\n * A short, human-readable task name for the task panel: the first line of the\n * task limited to ~4–8 words so it stays glanceable in the pane. A character cap\n * guards against a single very long word.\n */\nfunction summarize(task: string): string {\n\tconst firstLine = (task.trim().split(\"\\n\")[0] ?? \"\").trim();\n\tif (!firstLine) return \"(task)\";\n\tconst words = firstLine.split(/\\s+/);\n\tlet name = words.length > 8 ? `${words.slice(0, 8).join(\" \")}…` : firstLine;\n\tif (name.length > 60) name = `${name.slice(0, 59)}…`;\n\treturn name;\n}\n\n/** Quick check: should this task go to a subagent? */\nexport function isSubagentRecommended(task: string): boolean {\n\tconst evaluator = new DispatchEvaluator();\n\treturn evaluator.evaluate(task).should_delegate;\n}\n\n/** Create the subagent tool definition. Registered as a customTool when enabled. */\nexport function createSubagentToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof subagentParams, SubagentToolDetails>({\n\t\tname: \"subagent\",\n\t\tlabel: \"Subagent\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Pass everything it needs via `context`. The subagent returns only its final answer.\",\n\t\t\t\"Modes: explore, edit, test, fix, review, doc.\",\n\t\t\t\"WHEN TO USE: (1) The work is self-contained and you do not need to see intermediate steps — only the final result.\",\n\t\t\t\"(2) You want to investigate or edit something in parallel without losing your current context or reasoning chain.\",\n\t\t\t\"(3) The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs).\",\n\t\t\t\"(4) You need to run a long command or test suite and wait for its output without blocking your own reasoning.\",\n\t\t\t\"Do NOT use for tasks that require tight back-and-forth with your current reasoning or that change files you are actively reasoning about.\",\n\t\t\t\"Use force=true to bypass dispatch evaluation when you are certain a subagent is required.\",\n\t\t].join(\" \"),\n\t\tpromptSnippet: \"delegate a self-contained task to an isolated subagent (modes: explore/edit/test/fix/review/doc)\",\n\t\tparameters: subagentParams,\n\n\t\tasync execute(_toolCallId, params: SubagentParams, _signal, _onUpdate, ctx) {\n\t\t\tconst forcedMode = params.mode as SubagentMode;\n\n\t\t\t// Dispatch evaluation: a single evaluator/analysis decides inline vs delegate\n\t\t\t// and (when not forced) which mode to use.\n\t\t\tconst evaluator = new DispatchEvaluator();\n\t\t\tconst analysis = evaluator.evaluate(params.task);\n\t\t\tif (!params.force && !analysis.should_delegate) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Task is simple enough for inline handling. Reason: ${analysis.reason}. Use force=true for subagent override.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { mode: forcedMode, ok: true, taskId: 0, inline: true },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst mode: SubagentMode = params.force ? forcedMode : ((analysis.agent_type as SubagentMode) ?? \"explore\");\n\t\t\tconst summary = summarize(params.task);\n\n\t\t\tconst task = taskStore.create(summary, { subagentMode: mode });\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\t\t\t\tconst dispatchResult = await pool.dispatch(params.task, {\n\t\t\t\t\tforceAgent: mode,\n\t\t\t\t\tcontext: params.context,\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\n\t\t\t\tconst result = dispatchResult.result;\n\t\t\t\tconst resultData = result?.result_data as SubagentResultFile | undefined;\n\t\t\t\tconst usage = resultData?.usage;\n\n\t\t\t\tif (!result || !result.ok) {\n\t\t\t\t\t// Signal failure by throwing: the agent loop derives a tool's error\n\t\t\t\t\t// state from a thrown error, not from a returned flag.\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\", usage });\n\t\t\t\t\tthrow new Error(`Subagent (${mode}) failed: ${result?.error ?? \"unknown error\"}`);\n\t\t\t\t}\n\n\t\t\t\t// Leave the task in the store with its final status. It stays visible in\n\t\t\t\t// the task panel until the next user message arrives (retireFinished is\n\t\t\t\t// called when the user starts the next turn).\n\t\t\t\ttaskStore.update(task.id, { status: \"done\", usage });\n\t\t\t\tconst answer = resultData?.summary || \"(subagent returned no output)\";\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: answer }],\n\t\t\t\t\tdetails: { mode, ok: true, taskId: task.id },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst mode = args.mode ?? \"explore\";\n\t\t\tconst preview = summarize(args.task ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${mode}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n"]}
@@ -39,7 +39,7 @@ import { Text } from "@kolisachint/hoocode-tui";
39
39
  import { Type } from "typebox";
40
40
  import { DispatchEvaluator } from "../dispatch-evaluator.js";
41
41
  import { defineTool } from "../extensions/types.js";
42
- import { runSubagent } from "../subagent.js";
42
+ import { getSubagentPool } from "../subagent-pool-instance.js";
43
43
  import { taskStore } from "../task-store.js";
44
44
  const subagentParams = Type.Object({
45
45
  task: Type.String({
@@ -63,20 +63,26 @@ const subagentParams = Type.Object({
63
63
  default: false,
64
64
  }),
65
65
  });
66
- /** First line of the task, trimmed to a short summary for the task list/footer. */
66
+ /**
67
+ * A short, human-readable task name for the task panel: the first line of the
68
+ * task limited to ~4–8 words so it stays glanceable in the pane. A character cap
69
+ * guards against a single very long word.
70
+ */
67
71
  function summarize(task) {
68
- const firstLine = task.trim().split("\n")[0] ?? "";
69
- return firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || "(task)";
72
+ const firstLine = (task.trim().split("\n")[0] ?? "").trim();
73
+ if (!firstLine)
74
+ return "(task)";
75
+ const words = firstLine.split(/\s+/);
76
+ let name = words.length > 8 ? `${words.slice(0, 8).join(" ")}…` : firstLine;
77
+ if (name.length > 60)
78
+ name = `${name.slice(0, 59)}…`;
79
+ return name;
70
80
  }
71
81
  /** Quick check: should this task go to a subagent? */
72
82
  export function isSubagentRecommended(task) {
73
83
  const evaluator = new DispatchEvaluator();
74
84
  return evaluator.evaluate(task).should_delegate;
75
85
  }
76
- /** Map evaluator AgentType to SubagentMode (they are compatible strings). */
77
- function toSubagentMode(agentType) {
78
- return agentType ?? "explore";
79
- }
80
86
  /** Create the subagent tool definition. Registered as a customTool when enabled. */
81
87
  export function createSubagentToolDefinition() {
82
88
  return defineTool({
@@ -95,52 +101,51 @@ export function createSubagentToolDefinition() {
95
101
  ].join(" "),
96
102
  promptSnippet: "delegate a self-contained task to an isolated subagent (modes: explore/edit/test/fix/review/doc)",
97
103
  parameters: subagentParams,
98
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
104
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
99
105
  const forcedMode = params.mode;
100
- // Dispatch evaluation
101
- if (!params.force) {
102
- const evaluator = new DispatchEvaluator();
103
- const analysis = evaluator.evaluate(params.task);
104
- if (!analysis.should_delegate) {
105
- return {
106
- content: [
107
- {
108
- type: "text",
109
- text: `Task is simple enough for inline handling. Reason: ${analysis.reason}. Use force=true for subagent override.`,
110
- },
111
- ],
112
- details: { mode: forcedMode, ok: true, taskId: 0, inline: true },
113
- };
114
- }
106
+ // Dispatch evaluation: a single evaluator/analysis decides inline vs delegate
107
+ // and (when not forced) which mode to use.
108
+ const evaluator = new DispatchEvaluator();
109
+ const analysis = evaluator.evaluate(params.task);
110
+ if (!params.force && !analysis.should_delegate) {
111
+ return {
112
+ content: [
113
+ {
114
+ type: "text",
115
+ text: `Task is simple enough for inline handling. Reason: ${analysis.reason}. Use force=true for subagent override.`,
116
+ },
117
+ ],
118
+ details: { mode: forcedMode, ok: true, taskId: 0, inline: true },
119
+ };
115
120
  }
116
- const mode = params.force
117
- ? forcedMode
118
- : toSubagentMode(new DispatchEvaluator().evaluate(params.task).agent_type);
121
+ const mode = params.force ? forcedMode : (analysis.agent_type ?? "explore");
119
122
  const summary = summarize(params.task);
120
123
  const task = taskStore.create(summary, { subagentMode: mode });
121
124
  taskStore.update(task.id, { status: "in_progress" });
122
125
  try {
123
- const result = await runSubagent({
124
- task: params.task,
126
+ const pool = getSubagentPool(ctx.cwd);
127
+ const dispatchResult = await pool.dispatch(params.task, {
128
+ forceAgent: mode,
125
129
  context: params.context,
126
- mode,
127
- cwd: ctx.cwd,
128
- model: ctx.model,
129
- modelRegistry: ctx.modelRegistry,
130
- signal: signal ?? ctx.signal,
130
+ model: ctx.model?.id,
131
+ provider: ctx.model?.provider,
131
132
  });
132
- if (!result.ok) {
133
+ const result = dispatchResult.result;
134
+ const resultData = result?.result_data;
135
+ const usage = resultData?.usage;
136
+ if (!result || !result.ok) {
133
137
  // Signal failure by throwing: the agent loop derives a tool's error
134
138
  // state from a thrown error, not from a returned flag.
135
- taskStore.update(task.id, { status: "failed", usage: result.usage });
136
- throw new Error(`Subagent (${mode}) failed: ${result.error ?? "unknown error"}`);
139
+ taskStore.update(task.id, { status: "failed", usage });
140
+ throw new Error(`Subagent (${mode}) failed: ${result?.error ?? "unknown error"}`);
137
141
  }
138
142
  // Leave the task in the store with its final status. It stays visible in
139
- // the task panel until the main agent moves on (retireFinished is called
140
- // when the main agent starts its next turn).
141
- taskStore.update(task.id, { status: "done", usage: result.usage });
143
+ // the task panel until the next user message arrives (retireFinished is
144
+ // called when the user starts the next turn).
145
+ taskStore.update(task.id, { status: "done", usage });
146
+ const answer = resultData?.summary || "(subagent returned no output)";
142
147
  return {
143
- content: [{ type: "text", text: result.answer || "(subagent returned no output)" }],
148
+ content: [{ type: "text", text: answer }],
144
149
  details: { mode, ok: true, taskId: task.id },
145
150
  };
146
151
  }
@@ -1 +1 @@
1
- {"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;0EAC0E;AAC1E,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;mFA0B+C,CAAC;AAEpF,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAkB,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7E,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAqB,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,cAAc,GAAG,IAAI,CA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IAAI,+BAA+B,EAAE,CAAC;oBACnF,OAAO,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE;iBAC5C,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;gBAChD,MAAM,KAAK,CAAC;YACb,CAAC;QAAA,CACD;QAED,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE;YACvB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,SAAS,CAAC;YACpC,MAAM,OAAO,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;YAC3C,MAAM,IAAI,GACT,KAAK,CAAC,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;gBAC9C,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,IAAI,GAAG,CAAC;gBAC/B,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,OAAO,EAAE,CAAC,CAAC;YAChC,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAAA,CAC5B;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Subagent tool: delegate a focused task to a fresh, isolated agent loop.\n *\n * The tool registers a task in the shared task store (visible in the task panel),\n * runs the subagent to completion, and returns ONLY the subagent's final\n * answer. It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\n/** System prompt appendix for the main session when subagent tooling is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport const SUBAGENT_MAIN_PROMPT = `You have access to the **subagent** tool. Use it to delegate self-contained tasks to isolated subagent loops that run with their own context and return only their final answer.\n\nAvailable subagent modes:\n- explore: read-only investigation (read, grep, find, ls, bash).\n- edit: make a focused code change (read, edit, write, grep, find, ls, bash).\n- test: run tests and report (read, bash, grep, find, ls).\n- fix: diagnose and fix a failure (read, edit, write, bash, grep, find, ls).\n- review: read-only code review (read, grep, find, ls, bash).\n- doc: write documentation, README, or comments (read, write, edit, grep, find, ls, bash).\n\nWhen to delegate:\n1. The work is self-contained and you only need the final result, not intermediate steps.\n2. You want to investigate or edit something in parallel without losing your current context or reasoning chain.\n3. The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug).\n4. You need to run a long command or test suite and wait for its output without blocking your own reasoning.\n\nGuidelines:\n- Make every task specific and self-contained. The subagent cannot see this conversation.\n- Pass all necessary context (files, constraints, prior findings) via the \\`context\\` parameter.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning.\n- Do NOT delegate edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Intermediate reasoning, tool calls, and output are hidden from you.\n\nDispatch evaluator:\n- The dispatch evaluator determines if a subagent is needed. Do not spawn subagents directly unless the user explicitly requests it.\n- For simple single-file changes (<50 lines, read-only or trivial edit), handle them inline.\n- Use force=true to bypass evaluation when you are certain a subagent is required.`;\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { type AgentType, DispatchEvaluator } from \"../dispatch-evaluator.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport { runSubagent, type SubagentMode } from \"../subagent.js\";\nimport { taskStore } from \"../task-store.js\";\n\nconst subagentParams = Type.Object({\n\ttask: Type.String({\n\t\tdescription:\n\t\t\t\"The task to delegate. Make it specific and self-contained; the subagent cannot see this conversation.\",\n\t}),\n\tcontext: Type.String({\n\t\tdescription:\n\t\t\t'Context distilled from the conversation the subagent needs (files, constraints, prior findings). Pass \"\" if none.',\n\t}),\n\tmode: Type.Union(\n\t\t[\n\t\t\tType.Literal(\"explore\"),\n\t\t\tType.Literal(\"edit\"),\n\t\t\tType.Literal(\"test\"),\n\t\t\tType.Literal(\"fix\"),\n\t\t\tType.Literal(\"review\"),\n\t\t\tType.Literal(\"doc\"),\n\t\t],\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"explore: read-only investigation. edit: make a focused code change. test: run tests and report. fix: diagnose and fix a failure. review: read-only code review. doc: write documentation.\",\n\t\t},\n\t),\n\tforce: Type.Boolean({\n\t\tdescription:\n\t\t\t\"Bypass dispatch evaluation and spawn the subagent directly. Use when you are certain a subagent is required.\",\n\t\tdefault: false,\n\t}),\n});\n\ntype SubagentParams = Static<typeof subagentParams>;\n\nexport interface SubagentToolDetails {\n\tmode: SubagentMode;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** True when the evaluator handled the task inline instead of delegating. */\n\tinline?: boolean;\n}\n\n/** First line of the task, trimmed to a short summary for the task list/footer. */\nfunction summarize(task: string): string {\n\tconst firstLine = task.trim().split(\"\\n\")[0] ?? \"\";\n\treturn firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || \"(task)\";\n}\n\n/** Quick check: should this task go to a subagent? */\nexport function isSubagentRecommended(task: string): boolean {\n\tconst evaluator = new DispatchEvaluator();\n\treturn evaluator.evaluate(task).should_delegate;\n}\n\n/** Map evaluator AgentType to SubagentMode (they are compatible strings). */\nfunction toSubagentMode(agentType: AgentType | null): SubagentMode {\n\treturn (agentType as SubagentMode) ?? \"explore\";\n}\n\n/** Create the subagent tool definition. Registered as a customTool when enabled. */\nexport function createSubagentToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof subagentParams, SubagentToolDetails>({\n\t\tname: \"subagent\",\n\t\tlabel: \"Subagent\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Pass everything it needs via `context`. The subagent returns only its final answer.\",\n\t\t\t\"Modes: explore, edit, test, fix, review, doc.\",\n\t\t\t\"WHEN TO USE: (1) The work is self-contained and you do not need to see intermediate steps — only the final result.\",\n\t\t\t\"(2) You want to investigate or edit something in parallel without losing your current context or reasoning chain.\",\n\t\t\t\"(3) The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs).\",\n\t\t\t\"(4) You need to run a long command or test suite and wait for its output without blocking your own reasoning.\",\n\t\t\t\"Do NOT use for tasks that require tight back-and-forth with your current reasoning or that change files you are actively reasoning about.\",\n\t\t\t\"Use force=true to bypass dispatch evaluation when you are certain a subagent is required.\",\n\t\t].join(\" \"),\n\t\tpromptSnippet: \"delegate a self-contained task to an isolated subagent (modes: explore/edit/test/fix/review/doc)\",\n\t\tparameters: subagentParams,\n\n\t\tasync execute(_toolCallId, params: SubagentParams, signal, _onUpdate, ctx) {\n\t\t\tconst forcedMode = params.mode as SubagentMode;\n\n\t\t\t// Dispatch evaluation\n\t\t\tif (!params.force) {\n\t\t\t\tconst evaluator = new DispatchEvaluator();\n\t\t\t\tconst analysis = evaluator.evaluate(params.task);\n\t\t\t\tif (!analysis.should_delegate) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Task is simple enough for inline handling. Reason: ${analysis.reason}. Use force=true for subagent override.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: forcedMode, ok: true, taskId: 0, inline: true },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst mode = params.force\n\t\t\t\t? forcedMode\n\t\t\t\t: toSubagentMode(new DispatchEvaluator().evaluate(params.task).agent_type);\n\t\t\tconst summary = summarize(params.task);\n\n\t\t\tconst task = taskStore.create(summary, { subagentMode: mode });\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst result = await runSubagent({\n\t\t\t\t\ttask: params.task,\n\t\t\t\t\tcontext: params.context,\n\t\t\t\t\tmode,\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tmodel: ctx.model,\n\t\t\t\t\tmodelRegistry: ctx.modelRegistry,\n\t\t\t\t\tsignal: signal ?? ctx.signal,\n\t\t\t\t});\n\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\t// Signal failure by throwing: the agent loop derives a tool's error\n\t\t\t\t\t// state from a thrown error, not from a returned flag.\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\", usage: result.usage });\n\t\t\t\t\tthrow new Error(`Subagent (${mode}) failed: ${result.error ?? \"unknown error\"}`);\n\t\t\t\t}\n\n\t\t\t\t// Leave the task in the store with its final status. It stays visible in\n\t\t\t\t// the task panel until the main agent moves on (retireFinished is called\n\t\t\t\t// when the main agent starts its next turn).\n\t\t\t\ttaskStore.update(task.id, { status: \"done\", usage: result.usage });\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: result.answer || \"(subagent returned no output)\" }],\n\t\t\t\t\tdetails: { mode, ok: true, taskId: task.id },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst mode = args.mode ?? \"explore\";\n\t\t\tconst preview = summarize(args.task ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${mode}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;0EAC0E;AAC1E,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;mFA0B+C,CAAC;AAEpF,OAAO,EAAE,IAAI,EAA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AC,WAAW,CAAC,CAAC;gBAC9C,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,IAAI,GAAG,CAAC;gBAC/B,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,OAAO,EAAE,CAAC,CAAC;YAChC,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAAA,CAC5B;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Subagent tool: delegate a focused task to a fresh, isolated agent loop.\n *\n * The tool registers a task in the shared task store (visible in the task panel),\n * runs the subagent to completion, and returns ONLY the subagent's final\n * answer. It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\n/** System prompt appendix for the main session when subagent tooling is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport const SUBAGENT_MAIN_PROMPT = `You have access to the **subagent** tool. Use it to delegate self-contained tasks to isolated subagent loops that run with their own context and return only their final answer.\n\nAvailable subagent modes:\n- explore: read-only investigation (read, grep, find, ls, bash).\n- edit: make a focused code change (read, edit, write, grep, find, ls, bash).\n- test: run tests and report (read, bash, grep, find, ls).\n- fix: diagnose and fix a failure (read, edit, write, bash, grep, find, ls).\n- review: read-only code review (read, grep, find, ls, bash).\n- doc: write documentation, README, or comments (read, write, edit, grep, find, ls, bash).\n\nWhen to delegate:\n1. The work is self-contained and you only need the final result, not intermediate steps.\n2. You want to investigate or edit something in parallel without losing your current context or reasoning chain.\n3. The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug).\n4. You need to run a long command or test suite and wait for its output without blocking your own reasoning.\n\nGuidelines:\n- Make every task specific and self-contained. The subagent cannot see this conversation.\n- Pass all necessary context (files, constraints, prior findings) via the \\`context\\` parameter.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning.\n- Do NOT delegate edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Intermediate reasoning, tool calls, and output are hidden from you.\n\nDispatch evaluator:\n- The dispatch evaluator determines if a subagent is needed. Do not spawn subagents directly unless the user explicitly requests it.\n- For simple single-file changes (<50 lines, read-only or trivial edit), handle them inline.\n- Use force=true to bypass evaluation when you are certain a subagent is required.`;\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { DispatchEvaluator } from \"../dispatch-evaluator.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport type { SubagentMode } from \"../subagent.js\";\nimport { getSubagentPool } from \"../subagent-pool-instance.js\";\nimport type { SubagentResultFile } from \"../subagent-result.js\";\nimport { taskStore } from \"../task-store.js\";\n\nconst subagentParams = Type.Object({\n\ttask: Type.String({\n\t\tdescription:\n\t\t\t\"The task to delegate. Make it specific and self-contained; the subagent cannot see this conversation.\",\n\t}),\n\tcontext: Type.String({\n\t\tdescription:\n\t\t\t'Context distilled from the conversation the subagent needs (files, constraints, prior findings). Pass \"\" if none.',\n\t}),\n\tmode: Type.Union(\n\t\t[\n\t\t\tType.Literal(\"explore\"),\n\t\t\tType.Literal(\"edit\"),\n\t\t\tType.Literal(\"test\"),\n\t\t\tType.Literal(\"fix\"),\n\t\t\tType.Literal(\"review\"),\n\t\t\tType.Literal(\"doc\"),\n\t\t],\n\t\t{\n\t\t\tdescription:\n\t\t\t\t\"explore: read-only investigation. edit: make a focused code change. test: run tests and report. fix: diagnose and fix a failure. review: read-only code review. doc: write documentation.\",\n\t\t},\n\t),\n\tforce: Type.Boolean({\n\t\tdescription:\n\t\t\t\"Bypass dispatch evaluation and spawn the subagent directly. Use when you are certain a subagent is required.\",\n\t\tdefault: false,\n\t}),\n});\n\ntype SubagentParams = Static<typeof subagentParams>;\n\nexport interface SubagentToolDetails {\n\tmode: SubagentMode;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** True when the evaluator handled the task inline instead of delegating. */\n\tinline?: boolean;\n}\n\n/**\n * A short, human-readable task name for the task panel: the first line of the\n * task limited to ~4–8 words so it stays glanceable in the pane. A character cap\n * guards against a single very long word.\n */\nfunction summarize(task: string): string {\n\tconst firstLine = (task.trim().split(\"\\n\")[0] ?? \"\").trim();\n\tif (!firstLine) return \"(task)\";\n\tconst words = firstLine.split(/\\s+/);\n\tlet name = words.length > 8 ? `${words.slice(0, 8).join(\" \")}…` : firstLine;\n\tif (name.length > 60) name = `${name.slice(0, 59)}…`;\n\treturn name;\n}\n\n/** Quick check: should this task go to a subagent? */\nexport function isSubagentRecommended(task: string): boolean {\n\tconst evaluator = new DispatchEvaluator();\n\treturn evaluator.evaluate(task).should_delegate;\n}\n\n/** Create the subagent tool definition. Registered as a customTool when enabled. */\nexport function createSubagentToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof subagentParams, SubagentToolDetails>({\n\t\tname: \"subagent\",\n\t\tlabel: \"Subagent\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Pass everything it needs via `context`. The subagent returns only its final answer.\",\n\t\t\t\"Modes: explore, edit, test, fix, review, doc.\",\n\t\t\t\"WHEN TO USE: (1) The work is self-contained and you do not need to see intermediate steps — only the final result.\",\n\t\t\t\"(2) You want to investigate or edit something in parallel without losing your current context or reasoning chain.\",\n\t\t\t\"(3) The task is a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs).\",\n\t\t\t\"(4) You need to run a long command or test suite and wait for its output without blocking your own reasoning.\",\n\t\t\t\"Do NOT use for tasks that require tight back-and-forth with your current reasoning or that change files you are actively reasoning about.\",\n\t\t\t\"Use force=true to bypass dispatch evaluation when you are certain a subagent is required.\",\n\t\t].join(\" \"),\n\t\tpromptSnippet: \"delegate a self-contained task to an isolated subagent (modes: explore/edit/test/fix/review/doc)\",\n\t\tparameters: subagentParams,\n\n\t\tasync execute(_toolCallId, params: SubagentParams, _signal, _onUpdate, ctx) {\n\t\t\tconst forcedMode = params.mode as SubagentMode;\n\n\t\t\t// Dispatch evaluation: a single evaluator/analysis decides inline vs delegate\n\t\t\t// and (when not forced) which mode to use.\n\t\t\tconst evaluator = new DispatchEvaluator();\n\t\t\tconst analysis = evaluator.evaluate(params.task);\n\t\t\tif (!params.force && !analysis.should_delegate) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Task is simple enough for inline handling. Reason: ${analysis.reason}. Use force=true for subagent override.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { mode: forcedMode, ok: true, taskId: 0, inline: true },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst mode: SubagentMode = params.force ? forcedMode : ((analysis.agent_type as SubagentMode) ?? \"explore\");\n\t\t\tconst summary = summarize(params.task);\n\n\t\t\tconst task = taskStore.create(summary, { subagentMode: mode });\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\t\t\t\tconst dispatchResult = await pool.dispatch(params.task, {\n\t\t\t\t\tforceAgent: mode,\n\t\t\t\t\tcontext: params.context,\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\n\t\t\t\tconst result = dispatchResult.result;\n\t\t\t\tconst resultData = result?.result_data as SubagentResultFile | undefined;\n\t\t\t\tconst usage = resultData?.usage;\n\n\t\t\t\tif (!result || !result.ok) {\n\t\t\t\t\t// Signal failure by throwing: the agent loop derives a tool's error\n\t\t\t\t\t// state from a thrown error, not from a returned flag.\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\", usage });\n\t\t\t\t\tthrow new Error(`Subagent (${mode}) failed: ${result?.error ?? \"unknown error\"}`);\n\t\t\t\t}\n\n\t\t\t\t// Leave the task in the store with its final status. It stays visible in\n\t\t\t\t// the task panel until the next user message arrives (retireFinished is\n\t\t\t\t// called when the user starts the next turn).\n\t\t\t\ttaskStore.update(task.id, { status: \"done\", usage });\n\t\t\t\tconst answer = resultData?.summary || \"(subagent returned no output)\";\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: answer }],\n\t\t\t\t\tdetails: { mode, ok: true, taskId: task.id },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst mode = args.mode ?? \"explore\";\n\t\t\tconst preview = summarize(args.task ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${mode}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n"]}