@kolisachint/hoocode-agent 0.4.23 → 0.4.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +14 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/provider-health.d.ts +36 -0
- package/dist/core/provider-health.d.ts.map +1 -0
- package/dist/core/provider-health.js +54 -0
- package/dist/core/provider-health.js.map +1 -0
- package/dist/core/subagent-pool.d.ts +6 -0
- package/dist/core/subagent-pool.d.ts.map +1 -1
- package/dist/core/subagent-pool.js +28 -0
- package/dist/core/subagent-pool.js.map +1 -1
- package/dist/core/subagent-result.d.ts.map +1 -1
- package/dist/core/subagent-result.js +32 -2
- package/dist/core/subagent-result.js.map +1 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +26 -0
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/init-templates.generated.d.ts.map +1 -1
- package/dist/init-templates.generated.js +1 -1
- package/dist/init-templates.generated.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
- package/templates/agents/general-purpose.md +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-result.d.ts","sourceRoot":"","sources":["../../src/core/subagent-result.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAIpE,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,UAAU,GAAG,SAAS,GAAG,QAAQ,CAAC;IAC1C,4FAA4F;IAC5F,KAAK,CAAC,EAAE,aAAa,CAAC;CACtB;
|
|
1
|
+
{"version":3,"file":"subagent-result.d.ts","sourceRoot":"","sources":["../../src/core/subagent-result.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAIpE,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,UAAU,GAAG,SAAS,GAAG,QAAQ,CAAC;IAC1C,4FAA4F;IAC5F,KAAK,CAAC,EAAE,aAAa,CAAC;CACtB;AAiED,gFAAgF;AAChF,MAAM,WAAW,0BAA0B;IAC1C,iGAAiG;IACjG,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,KAAK,CAAC,EAAE,aAAa,EACrB,OAAO,CAAC,EAAE,0BAA0B,GAClC,kBAAkB,CAkCpB;AAED,iEAAiE;AACjE,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAQjG","sourcesContent":["/**\n * Writes a subagent's `result.json` audit file.\n *\n * When a subagent runs as a spawned child process (`--task-id <id>`), the parent\n * SubagentPool verifies `.hoocode/dispatch/<task_id>/result.json` against a fixed\n * schema (see OutputVerifier). This module derives that file deterministically\n * from the finished session so subagents never have to write it themselves.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { AgentMessage } from \"@kolisachint/hoocode-agent-core\";\nimport type { AssistantMessage } from \"@kolisachint/hoocode-ai\";\nimport { getDispatchTaskDir } from \"../config.js\";\n\nexport interface SubagentUsage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport interface SubagentResultFile {\n\tsummary: string;\n\tfiles_changed: string[];\n\tconfidence: number;\n\tstatus: \"complete\" | \"partial\" | \"failed\";\n\t/** Token and cost usage for the subagent session (extra field; ignored by the verifier). */\n\tusage?: SubagentUsage;\n}\n\n/** Tool names that mutate files. Their `path`/`file_path` argument is a changed file. */\nconst MUTATING_TOOLS = new Set([\"edit\", \"write\"]);\n\n/** Collect distinct file paths touched by edit/write tool calls across the session. */\nfunction collectChangedFiles(messages: readonly AgentMessage[]): string[] {\n\tconst files = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\") continue;\n\t\tfor (const content of (message as AssistantMessage).content) {\n\t\t\tif (content.type !== \"toolCall\") continue;\n\t\t\tif (!MUTATING_TOOLS.has(content.name)) continue;\n\t\t\tconst args = content.arguments ?? {};\n\t\t\tconst path =\n\t\t\t\ttypeof args.path === \"string\" ? args.path : typeof args.file_path === \"string\" ? args.file_path : null;\n\t\t\tif (path) files.add(path);\n\t\t}\n\t}\n\treturn [...files];\n}\n\n/** Last assistant text, trimmed, as the summary. */\nfunction deriveSummary(messages: readonly AgentMessage[]): string {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role !== \"assistant\") continue;\n\t\tconst assistant = message as AssistantMessage;\n\t\tlet text = \"\";\n\t\tfor (const content of assistant.content) {\n\t\t\tif (content.type === \"text\") text += content.text;\n\t\t}\n\t\tconst trimmed = text.trim();\n\t\tif (trimmed) return trimmed;\n\t}\n\treturn \"\";\n}\n\n/** Derive the terminal status from the final assistant message. */\nfunction deriveStatus(messages: readonly AgentMessage[]): \"complete\" | \"failed\" {\n\tconst last = messages[messages.length - 1];\n\tif (last?.role === \"assistant\") {\n\t\tconst assistant = last as AssistantMessage;\n\t\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") return \"failed\";\n\t}\n\treturn \"complete\";\n}\n\n/**\n * Concrete error text from the final assistant message when the run ended in an\n * error (e.g. a provider usage/quota or rate-limit message). Surfacing this in\n * the summary lets the parent report the real cause instead of \"subagent failed\".\n */\nfunction deriveErrorMessage(messages: readonly AgentMessage[]): string | undefined {\n\tconst last = messages[messages.length - 1];\n\tif (last?.role === \"assistant\") {\n\t\tconst assistant = last as AssistantMessage;\n\t\tif (assistant.stopReason === \"error\" && assistant.errorMessage) {\n\t\t\tconst trimmed = assistant.errorMessage.trim();\n\t\t\tif (trimmed) return trimmed;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Extra build options that override the status derived from the transcript. */\nexport interface BuildSubagentResultOptions {\n\t/** The run was stopped at its turn cap. Report a usable partial result rather than a failure. */\n\treachedMaxTurns?: boolean;\n}\n\n/**\n * Build the `result.json` payload for a finished subagent session.\n *\n * The verifier requires a non-empty summary and confidence >= 0.5, so a\n * successful run with no assistant text still yields a usable summary.\n *\n * When the run was stopped at its turn cap (`reachedMaxTurns`), the result is\n * reported as `partial` with whatever summary the agent managed to produce,\n * instead of the `failed` status an aborted final message would otherwise yield.\n */\nexport function buildSubagentResult(\n\tmessages: readonly AgentMessage[],\n\tusage?: SubagentUsage,\n\toptions?: BuildSubagentResultOptions,\n): SubagentResultFile {\n\tif (options?.reachedMaxTurns) {\n\t\treturn {\n\t\t\tsummary: deriveSummary(messages) || \"Reached the turn limit before completing. Returning partial findings.\",\n\t\t\tfiles_changed: collectChangedFiles(messages),\n\t\t\tconfidence: 0.6,\n\t\t\tstatus: \"partial\",\n\t\t\tusage,\n\t\t};\n\t}\n\n\tconst status = deriveStatus(messages);\n\tif (status === \"failed\") {\n\t\t// Prefer the provider/model error over any partial assistant text so the\n\t\t// caller sees the real cause (e.g. \"usage limit reached\").\n\t\tconst errorMessage = deriveErrorMessage(messages);\n\t\tconst summary = errorMessage ? `Task failed: ${errorMessage}` : deriveSummary(messages) || \"Task failed.\";\n\t\treturn {\n\t\t\tsummary,\n\t\t\tfiles_changed: collectChangedFiles(messages),\n\t\t\tconfidence: 0.5,\n\t\t\tstatus,\n\t\t\tusage,\n\t\t};\n\t}\n\n\tconst summary = deriveSummary(messages) || \"Task completed with no textual summary.\";\n\treturn {\n\t\tsummary,\n\t\tfiles_changed: collectChangedFiles(messages),\n\t\tconfidence: 0.9,\n\t\tstatus,\n\t\tusage,\n\t};\n}\n\n/** Write `result.json` for a task. Best-effort: never throws. */\nexport function writeSubagentResult(cwd: string, taskId: string, result: SubagentResultFile): void {\n\tconst path = join(getDispatchTaskDir(cwd, taskId), \"result.json\");\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(result, null, 2));\n\t} catch {\n\t\t// Audit file is best-effort; the parent treats a missing file as a failure.\n\t}\n}\n"]}
|
|
@@ -58,6 +58,23 @@ function deriveStatus(messages) {
|
|
|
58
58
|
}
|
|
59
59
|
return "complete";
|
|
60
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Concrete error text from the final assistant message when the run ended in an
|
|
63
|
+
* error (e.g. a provider usage/quota or rate-limit message). Surfacing this in
|
|
64
|
+
* the summary lets the parent report the real cause instead of "subagent failed".
|
|
65
|
+
*/
|
|
66
|
+
function deriveErrorMessage(messages) {
|
|
67
|
+
const last = messages[messages.length - 1];
|
|
68
|
+
if (last?.role === "assistant") {
|
|
69
|
+
const assistant = last;
|
|
70
|
+
if (assistant.stopReason === "error" && assistant.errorMessage) {
|
|
71
|
+
const trimmed = assistant.errorMessage.trim();
|
|
72
|
+
if (trimmed)
|
|
73
|
+
return trimmed;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
61
78
|
/**
|
|
62
79
|
* Build the `result.json` payload for a finished subagent session.
|
|
63
80
|
*
|
|
@@ -79,11 +96,24 @@ export function buildSubagentResult(messages, usage, options) {
|
|
|
79
96
|
};
|
|
80
97
|
}
|
|
81
98
|
const status = deriveStatus(messages);
|
|
82
|
-
|
|
99
|
+
if (status === "failed") {
|
|
100
|
+
// Prefer the provider/model error over any partial assistant text so the
|
|
101
|
+
// caller sees the real cause (e.g. "usage limit reached").
|
|
102
|
+
const errorMessage = deriveErrorMessage(messages);
|
|
103
|
+
const summary = errorMessage ? `Task failed: ${errorMessage}` : deriveSummary(messages) || "Task failed.";
|
|
104
|
+
return {
|
|
105
|
+
summary,
|
|
106
|
+
files_changed: collectChangedFiles(messages),
|
|
107
|
+
confidence: 0.5,
|
|
108
|
+
status,
|
|
109
|
+
usage,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const summary = deriveSummary(messages) || "Task completed with no textual summary.";
|
|
83
113
|
return {
|
|
84
114
|
summary,
|
|
85
115
|
files_changed: collectChangedFiles(messages),
|
|
86
|
-
confidence:
|
|
116
|
+
confidence: 0.9,
|
|
87
117
|
status,
|
|
88
118
|
usage,
|
|
89
119
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-result.js","sourceRoot":"","sources":["../../src/core/subagent-result.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAG1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAmBlD,yFAAyF;AACz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AAkB,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,aAAa,CAAC,CAAC;IAClE,IAAI,CAAC;QACJ,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9C,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IACtD,CAAC;IAAC,MAAM,CAAC;QACR,4EAA4E;IAC7E,CAAC;AAAA,CACD","sourcesContent":["/**\n * Writes a subagent's `result.json` audit file.\n *\n * When a subagent runs as a spawned child process (`--task-id <id>`), the parent\n * SubagentPool verifies `.hoocode/dispatch/<task_id>/result.json` against a fixed\n * schema (see OutputVerifier). This module derives that file deterministically\n * from the finished session so subagents never have to write it themselves.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { AgentMessage } from \"@kolisachint/hoocode-agent-core\";\nimport type { AssistantMessage } from \"@kolisachint/hoocode-ai\";\nimport { getDispatchTaskDir } from \"../config.js\";\n\nexport interface SubagentUsage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport interface SubagentResultFile {\n\tsummary: string;\n\tfiles_changed: string[];\n\tconfidence: number;\n\tstatus: \"complete\" | \"partial\" | \"failed\";\n\t/** Token and cost usage for the subagent session (extra field; ignored by the verifier). */\n\tusage?: SubagentUsage;\n}\n\n/** Tool names that mutate files. Their `path`/`file_path` argument is a changed file. */\nconst MUTATING_TOOLS = new Set([\"edit\", \"write\"]);\n\n/** Collect distinct file paths touched by edit/write tool calls across the session. */\nfunction collectChangedFiles(messages: readonly AgentMessage[]): string[] {\n\tconst files = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\") continue;\n\t\tfor (const content of (message as AssistantMessage).content) {\n\t\t\tif (content.type !== \"toolCall\") continue;\n\t\t\tif (!MUTATING_TOOLS.has(content.name)) continue;\n\t\t\tconst args = content.arguments ?? {};\n\t\t\tconst path =\n\t\t\t\ttypeof args.path === \"string\" ? args.path : typeof args.file_path === \"string\" ? args.file_path : null;\n\t\t\tif (path) files.add(path);\n\t\t}\n\t}\n\treturn [...files];\n}\n\n/** Last assistant text, trimmed, as the summary. */\nfunction deriveSummary(messages: readonly AgentMessage[]): string {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role !== \"assistant\") continue;\n\t\tconst assistant = message as AssistantMessage;\n\t\tlet text = \"\";\n\t\tfor (const content of assistant.content) {\n\t\t\tif (content.type === \"text\") text += content.text;\n\t\t}\n\t\tconst trimmed = text.trim();\n\t\tif (trimmed) return trimmed;\n\t}\n\treturn \"\";\n}\n\n/** Derive the terminal status from the final assistant message. */\nfunction deriveStatus(messages: readonly AgentMessage[]): \"complete\" | \"failed\" {\n\tconst last = messages[messages.length - 1];\n\tif (last?.role === \"assistant\") {\n\t\tconst assistant = last as AssistantMessage;\n\t\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") return \"failed\";\n\t}\n\treturn \"complete\";\n}\n\n/**\n * Concrete error text from the final assistant message when the run ended in an\n * error (e.g. a provider usage/quota or rate-limit message). Surfacing this in\n * the summary lets the parent report the real cause instead of \"subagent failed\".\n */\nfunction deriveErrorMessage(messages: readonly AgentMessage[]): string | undefined {\n\tconst last = messages[messages.length - 1];\n\tif (last?.role === \"assistant\") {\n\t\tconst assistant = last as AssistantMessage;\n\t\tif (assistant.stopReason === \"error\" && assistant.errorMessage) {\n\t\t\tconst trimmed = assistant.errorMessage.trim();\n\t\t\tif (trimmed) return trimmed;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Extra build options that override the status derived from the transcript. */\nexport interface BuildSubagentResultOptions {\n\t/** The run was stopped at its turn cap. Report a usable partial result rather than a failure. */\n\treachedMaxTurns?: boolean;\n}\n\n/**\n * Build the `result.json` payload for a finished subagent session.\n *\n * The verifier requires a non-empty summary and confidence >= 0.5, so a\n * successful run with no assistant text still yields a usable summary.\n *\n * When the run was stopped at its turn cap (`reachedMaxTurns`), the result is\n * reported as `partial` with whatever summary the agent managed to produce,\n * instead of the `failed` status an aborted final message would otherwise yield.\n */\nexport function buildSubagentResult(\n\tmessages: readonly AgentMessage[],\n\tusage?: SubagentUsage,\n\toptions?: BuildSubagentResultOptions,\n): SubagentResultFile {\n\tif (options?.reachedMaxTurns) {\n\t\treturn {\n\t\t\tsummary: deriveSummary(messages) || \"Reached the turn limit before completing. Returning partial findings.\",\n\t\t\tfiles_changed: collectChangedFiles(messages),\n\t\t\tconfidence: 0.6,\n\t\t\tstatus: \"partial\",\n\t\t\tusage,\n\t\t};\n\t}\n\n\tconst status = deriveStatus(messages);\n\tif (status === \"failed\") {\n\t\t// Prefer the provider/model error over any partial assistant text so the\n\t\t// caller sees the real cause (e.g. \"usage limit reached\").\n\t\tconst errorMessage = deriveErrorMessage(messages);\n\t\tconst summary = errorMessage ? `Task failed: ${errorMessage}` : deriveSummary(messages) || \"Task failed.\";\n\t\treturn {\n\t\t\tsummary,\n\t\t\tfiles_changed: collectChangedFiles(messages),\n\t\t\tconfidence: 0.5,\n\t\t\tstatus,\n\t\t\tusage,\n\t\t};\n\t}\n\n\tconst summary = deriveSummary(messages) || \"Task completed with no textual summary.\";\n\treturn {\n\t\tsummary,\n\t\tfiles_changed: collectChangedFiles(messages),\n\t\tconfidence: 0.9,\n\t\tstatus,\n\t\tusage,\n\t};\n}\n\n/** Write `result.json` for a task. Best-effort: never throws. */\nexport function writeSubagentResult(cwd: string, taskId: string, result: SubagentResultFile): void {\n\tconst path = join(getDispatchTaskDir(cwd, taskId), \"result.json\");\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(result, null, 2));\n\t} catch {\n\t\t// Audit file is best-effort; the parent treats a missing file as a failure.\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAKH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAO7D;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAwBrE;AASD;0EAC0E;AAC1E,wBAAgB,mBAAmB,CAAC,GAAG,GAAE,MAAsB,GAAG,MAAM,CAoBvE;AAuBD,MAAM,WAAW,eAAe;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,EAAE,OAAO,CAAC;CACZ;AAeD,gFAAgF;AAChF,wBAAgB,wBAAwB,CAAC,GAAG,GAAE,MAAsB,GAAG,cAAc,CAkHpF;AAmED;;;;GAIG;AACH,wBAAgB,8BAA8B,IAAI,cAAc,CAiD/D","sourcesContent":["/**\n * Task tool: delegate a focused task to a specialized subagent.\n *\n * Mirrors the Claude Code `Task` tool. The parent agent decides *when* to\n * delegate based on each agent's `description` (there is no deterministic gate)\n * and selects *which* agent via `subagent_type`. The chosen agent runs in a\n * fresh, isolated child process (SubagentPool) and only its final answer is\n * returned to the parent.\n *\n * It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { loadAgentRegistry } from \"../agent-registry.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport type { SubagentPool, TaskResult } from \"../subagent-pool.js\";\nimport { getSubagentPool } from \"../subagent-pool-instance.js\";\nimport type { SubagentResultFile } from \"../subagent-result.js\";\nimport { taskStore } from \"../task-store.js\";\n\n/**\n * Condense a (possibly multi-line, bulleted) agent description into a single\n * useful one-liner for the agent picker list.\n *\n * Built-in agent descriptions open with a boilerplate header (\"Use this\n * subagent ONLY when:\") followed by \"when to use\" bullets and a \"DO NOT use\"\n * section. Taking the first line alone yields that identical header for every\n * agent, so instead surface the first meaningful bullets (or the first prose\n * line) from the positive \"when to use\" region.\n */\nexport function summarizeAgentDescription(description: string): string {\n\tconst lines = description\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (lines.length === 0) return \"\";\n\n\t// Keep only the positive region: everything before a \"DO NOT use\" section.\n\tconst stop = lines.findIndex((line) => /^(do\\s*not|don'?t|avoid)\\b/i.test(line));\n\tconst region = stop === -1 ? lines : lines.slice(0, stop);\n\n\t// Drop a leading header line (e.g. \"Use this subagent ONLY when:\").\n\tconst body = region.length > 1 && region[0]!.endsWith(\":\") ? region.slice(1) : region;\n\n\tconst stripBullet = (line: string) => line.replace(/^[-*\\u2022]\\s+/, \"\").trim();\n\tconst bullets = body\n\t\t.filter((line) => /^[-*\\u2022]\\s+/.test(line))\n\t\t.map(stripBullet)\n\t\t.filter((line) => line.length > 0);\n\n\tconst summary = bullets.length > 0 ? bullets.slice(0, 3).join(\"; \") : (body[0] ?? lines[0] ?? \"\").replace(/:$/, \"\");\n\n\tconst MAX = 200;\n\treturn summary.length > MAX ? `${summary.slice(0, MAX - 1).trimEnd()}\\u2026` : summary;\n}\n\n/** Render the available agents as a \"- name: description\" list for prompts. */\nfunction describeAvailableAgents(cwd: string): string {\n\tconst agents = loadAgentRegistry({ cwd }).list();\n\tif (agents.length === 0) return \"(no agents available)\";\n\treturn agents.map((a) => `- ${a.name}: ${summarizeAgentDescription(a.description)}`).join(\"\\n\");\n}\n\n/** System prompt appendix for the main session when the Task tool is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport function buildTaskMainPrompt(cwd: string = process.cwd()): string {\n\treturn `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.\n\nAvailable agents (choose one via \\`subagent_type\\`):\n${describeAvailableAgents(cwd)}\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- Choose the agent whose description best matches the task.\n- Make every task specific and self-contained. The subagent cannot see this conversation; pass all necessary context (files, constraints, prior findings) in \\`prompt\\`.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Its intermediate reasoning, tool calls, and output are hidden from you.\n- Default to handling small, quick, or single-file work inline; delegate only self-contained units.\n- Some agents are configured to run in the background (non-blocking). For those, Task returns immediately with a task_id; use the **TaskOutput** tool with that task_id to check status and collect the final answer.\n- 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.`;\n}\n\nconst taskParams = Type.Object({\n\tdescription: Type.String({\n\t\tdescription: \"A short (3-5 word) description of the task, shown in the task panel.\",\n\t}),\n\tprompt: Type.String({\n\t\tdescription:\n\t\t\t\"The full, self-contained task for the subagent. It cannot see this conversation, so include all needed context, files, and constraints.\",\n\t}),\n\tsubagent_type: Type.String({\n\t\tdescription: \"The name of the specialized agent to delegate to. Must be one of the available agents.\",\n\t}),\n\tresume_task_id: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"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.\",\n\t\t}),\n\t),\n});\n\ntype TaskParams = Static<typeof taskParams>;\n\nexport interface TaskToolDetails {\n\tsubagent_type: string;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** Pool-level task id usable for resume/polling. */\n\tpoolTaskId?: string;\n\t/** True when dispatched as a non-blocking background task. */\n\tbackground?: boolean;\n}\n\nexport interface TaskOutputDetails {\n\ttask_id: string;\n\tstatus: string;\n\tok: boolean;\n}\n\n/**\n * A short, human-readable task name for the task panel: the first line limited\n * to ~8 words so it stays glanceable. A character cap guards a single 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/** Create the Task tool definition. Registered as a customTool when enabled. */\nexport function createTaskToolDefinition(cwd: string = process.cwd()): ToolDefinition {\n\tconst agentList = describeAvailableAgents(cwd);\n\treturn defineTool<typeof taskParams, TaskToolDetails>({\n\t\tname: \"Task\",\n\t\tlabel: \"Task\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a specialized subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Select the agent via `subagent_type`; pass everything it needs via `prompt`. The subagent returns only its final answer.\",\n\t\t\t\"Available agents:\",\n\t\t\tagentList,\n\t\t\t\"WHEN TO USE: (1) self-contained work where you only need the final result;\",\n\t\t\t\"(2) parallel investigation/edits without losing your reasoning chain;\",\n\t\t\t\"(3) a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs);\",\n\t\t\t\"(4) a long command or test suite you want to run without blocking your reasoning.\",\n\t\t\t\"Do NOT use for tasks needing tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\",\n\t\t\t\"Prefer handling small, quick, or single-file tasks yourself; delegate only self-contained units of work.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"delegate a self-contained task to a specialized subagent (choose via subagent_type)\",\n\t\tparameters: taskParams,\n\n\t\tasync execute(_toolCallId, params: TaskParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\n\t\t\t// Resume path: continue a previously dispatched subagent with a follow-up\n\t\t\t// prompt, reusing its persisted session (full prior transcript).\n\t\t\tconst resumeId = params.resume_task_id?.trim();\n\t\t\tif (resumeId) {\n\t\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\ttry {\n\t\t\t\t\tconst dispatchResult = await pool.resume(resumeId, params.prompt, {\n\t\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t\t});\n\t\t\t\t\t// The session lives under the original task id; keep it as the resume handle.\n\t\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, resumeId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The model has already decided to delegate and which agent to use; honor\n\t\t\t// it. Validate the requested agent against the registry (no routing gate).\n\t\t\tconst registry = loadAgentRegistry({ cwd: ctx.cwd });\n\t\t\tconst def = registry.get(params.subagent_type);\n\t\t\tif (!def) {\n\t\t\t\tconst available = registry\n\t\t\t\t\t.list()\n\t\t\t\t\t.map((a) => a.name)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Unknown subagent_type: \"${params.subagent_type}\". Available agents: ${available || \"(none)\"}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\n\t\t\t// Background agents: dispatch detached and return a handle immediately so\n\t\t\t// the parent keeps reasoning. The parent polls via the TaskOutput tool.\n\t\t\tif (def.background) {\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\tconst dispatched = pool.dispatchDetached(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\tconst poolTaskId = dispatched.task_id;\n\t\t\t\tif (poolTaskId) trackBackgroundTask(pool, poolTaskId, task.id);\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\" as const,\n\t\t\t\t\t\t\ttext: `Background subagent (${params.subagent_type}) started with task_id \"${poolTaskId}\". It runs without blocking you. Call the TaskOutput tool with this task_id to check its status and collect the final answer.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tsubagent_type: params.subagent_type,\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\ttaskId: task.id,\n\t\t\t\t\t\tpoolTaskId,\n\t\t\t\t\t\tbackground: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst dispatchResult = await pool.dispatch(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, dispatchResult.task_id);\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 type = args.subagent_type ?? \"agent\";\n\t\t\tconst preview = summarize(args.description ?? args.prompt ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"Task \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${type}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n\n/** Extract the final answer from a finished dispatch, updating the task panel. */\nfunction finalizeForegroundResult(\n\tdispatchResult: TaskResult,\n\tsubagentType: string,\n\ttaskStoreId: number,\n\tresumeHandle: string | undefined,\n): { content: Array<{ type: \"text\"; text: string }>; details: TaskToolDetails } {\n\tconst result = dispatchResult.result;\n\tconst resultData = result?.result_data as SubagentResultFile | undefined;\n\tconst usage = resultData?.usage;\n\n\tif (!result || !result.ok) {\n\t\t// Signal failure by throwing: the agent loop derives a tool's error state\n\t\t// from a thrown error, not from a returned flag.\n\t\ttaskStore.update(taskStoreId, { status: \"failed\", usage });\n\t\tconst reason = result?.error ?? (result?.status ? `subagent ${result.status}` : \"unknown error\");\n\t\tthrow new Error(`Subagent (${subagentType}) failed: ${reason}`);\n\t}\n\n\t// Leave the task in the store with its final status; it stays visible in the\n\t// task panel until the next user message arrives.\n\ttaskStore.update(taskStoreId, { status: \"done\", usage });\n\tlet answer = resultData?.summary || \"(subagent returned no output)\";\n\t// Partial results are resumable; surface the handle so the parent can continue.\n\tif (result.status === \"partial\" && resumeHandle) {\n\t\tanswer += `\\n\\n[Partial result. To continue this subagent, call Task again with resume_task_id=\"${resumeHandle}\".]`;\n\t}\n\treturn {\n\t\tcontent: [{ type: \"text\", text: answer }],\n\t\tdetails: { subagent_type: subagentType, ok: true, taskId: taskStoreId, poolTaskId: resumeHandle },\n\t};\n}\n\n/**\n * Keep the task panel in sync for a detached background subagent: when the pool\n * reports the task finished, update the stored task's status and detach.\n */\nfunction trackBackgroundTask(pool: SubagentPool, poolTaskId: string, taskStoreId: number): void {\n\tfunction finish(status: \"done\" | \"failed\"): void {\n\t\ttaskStore.update(taskStoreId, { status });\n\t\tpool.off(\"task_done\", onDone);\n\t\tpool.off(\"task_failed\", onFail);\n\t\tpool.off(\"task_stalled\", onFail);\n\t\tpool.off(\"task_timeout\", onFail);\n\t}\n\tfunction onDone(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"done\");\n\t}\n\tfunction onFail(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"failed\");\n\t}\n\tpool.on(\"task_done\", onDone);\n\tpool.on(\"task_failed\", onFail);\n\tpool.on(\"task_stalled\", onFail);\n\tpool.on(\"task_timeout\", onFail);\n}\n\nconst taskOutputParams = Type.Object({\n\ttask_id: Type.String({\n\t\tdescription: \"The task_id of a background (or previously dispatched) subagent, as returned by the Task tool.\",\n\t}),\n});\n\ntype TaskOutputParams = Static<typeof taskOutputParams>;\n\n/**\n * TaskOutput tool: poll a background subagent and collect its final answer.\n * Returns the current status while running, or the subagent's final answer once\n * complete. Registered alongside the Task tool when subagents are enabled.\n */\nexport function createTaskOutputToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof taskOutputParams, TaskOutputDetails>({\n\t\tname: \"TaskOutput\",\n\t\tlabel: \"TaskOutput\",\n\t\tdescription: [\n\t\t\t\"Check the status of a background subagent and collect its final answer once it finishes.\",\n\t\t\t\"Pass the task_id returned by a background Task call. While the subagent runs this reports its status; once complete it returns only the subagent's final answer.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"check status / collect the result of a background subagent\",\n\t\tparameters: taskOutputParams,\n\n\t\tasync execute(_toolCallId, params: TaskOutputParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\t\t\tconst status = pool.get_status(params.task_id);\n\t\t\tif (status === \"running\" || status === \"queued\") {\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\" as const,\n\t\t\t\t\t\t\ttext: `Subagent task \"${params.task_id}\" is ${status}. Call TaskOutput again later to collect its result.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { task_id: params.task_id, status, ok: true },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = pool.collect(params.task_id);\n\t\t\tif (!result) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No result available for task \"${params.task_id}\" (status: ${status}). It may not exist or its result was already collected.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!result.ok) {\n\t\t\t\tconst reason = result.error ?? (result.status ? `subagent ${result.status}` : status);\n\t\t\t\tthrow new Error(`Background subagent \"${params.task_id}\" failed: ${reason}`);\n\t\t\t}\n\t\t\tconst resultData = result.result_data as SubagentResultFile | undefined;\n\t\t\tconst answer = resultData?.summary || \"(subagent returned no output)\";\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: answer }],\n\t\t\t\tdetails: { task_id: params.task_id, status: result.status ?? \"complete\", ok: true },\n\t\t\t};\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst text = theme.fg(\"toolTitle\", theme.bold(\"TaskOutput \")) + theme.fg(\"dim\", String(args.task_id ?? \"\"));\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;;;;;;;;;;;GAWG;AAKH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAQ7D;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAwBrE;AASD;0EAC0E;AAC1E,wBAAgB,mBAAmB,CAAC,GAAG,GAAE,MAAsB,GAAG,MAAM,CAoBvE;AAuBD,MAAM,WAAW,eAAe;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,EAAE,OAAO,CAAC;CACZ;AAeD,gFAAgF;AAChF,wBAAgB,wBAAwB,CAAC,GAAG,GAAE,MAAsB,GAAG,cAAc,CA6IpF;AAmED;;;;GAIG;AACH,wBAAgB,8BAA8B,IAAI,cAAc,CAiD/D","sourcesContent":["/**\n * Task tool: delegate a focused task to a specialized subagent.\n *\n * Mirrors the Claude Code `Task` tool. The parent agent decides *when* to\n * delegate based on each agent's `description` (there is no deterministic gate)\n * and selects *which* agent via `subagent_type`. The chosen agent runs in a\n * fresh, isolated child process (SubagentPool) and only its final answer is\n * returned to the parent.\n *\n * It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { loadAgentRegistry } from \"../agent-registry.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport { getProviderExhaustion } from \"../provider-health.js\";\nimport type { SubagentPool, TaskResult } from \"../subagent-pool.js\";\nimport { getSubagentPool } from \"../subagent-pool-instance.js\";\nimport type { SubagentResultFile } from \"../subagent-result.js\";\nimport { taskStore } from \"../task-store.js\";\n\n/**\n * Condense a (possibly multi-line, bulleted) agent description into a single\n * useful one-liner for the agent picker list.\n *\n * Built-in agent descriptions open with a boilerplate header (\"Use this\n * subagent ONLY when:\") followed by \"when to use\" bullets and a \"DO NOT use\"\n * section. Taking the first line alone yields that identical header for every\n * agent, so instead surface the first meaningful bullets (or the first prose\n * line) from the positive \"when to use\" region.\n */\nexport function summarizeAgentDescription(description: string): string {\n\tconst lines = description\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (lines.length === 0) return \"\";\n\n\t// Keep only the positive region: everything before a \"DO NOT use\" section.\n\tconst stop = lines.findIndex((line) => /^(do\\s*not|don'?t|avoid)\\b/i.test(line));\n\tconst region = stop === -1 ? lines : lines.slice(0, stop);\n\n\t// Drop a leading header line (e.g. \"Use this subagent ONLY when:\").\n\tconst body = region.length > 1 && region[0]!.endsWith(\":\") ? region.slice(1) : region;\n\n\tconst stripBullet = (line: string) => line.replace(/^[-*\\u2022]\\s+/, \"\").trim();\n\tconst bullets = body\n\t\t.filter((line) => /^[-*\\u2022]\\s+/.test(line))\n\t\t.map(stripBullet)\n\t\t.filter((line) => line.length > 0);\n\n\tconst summary = bullets.length > 0 ? bullets.slice(0, 3).join(\"; \") : (body[0] ?? lines[0] ?? \"\").replace(/:$/, \"\");\n\n\tconst MAX = 200;\n\treturn summary.length > MAX ? `${summary.slice(0, MAX - 1).trimEnd()}\\u2026` : summary;\n}\n\n/** Render the available agents as a \"- name: description\" list for prompts. */\nfunction describeAvailableAgents(cwd: string): string {\n\tconst agents = loadAgentRegistry({ cwd }).list();\n\tif (agents.length === 0) return \"(no agents available)\";\n\treturn agents.map((a) => `- ${a.name}: ${summarizeAgentDescription(a.description)}`).join(\"\\n\");\n}\n\n/** System prompt appendix for the main session when the Task tool is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport function buildTaskMainPrompt(cwd: string = process.cwd()): string {\n\treturn `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.\n\nAvailable agents (choose one via \\`subagent_type\\`):\n${describeAvailableAgents(cwd)}\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- Choose the agent whose description best matches the task.\n- Make every task specific and self-contained. The subagent cannot see this conversation; pass all necessary context (files, constraints, prior findings) in \\`prompt\\`.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Its intermediate reasoning, tool calls, and output are hidden from you.\n- Default to handling small, quick, or single-file work inline; delegate only self-contained units.\n- Some agents are configured to run in the background (non-blocking). For those, Task returns immediately with a task_id; use the **TaskOutput** tool with that task_id to check status and collect the final answer.\n- 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.`;\n}\n\nconst taskParams = Type.Object({\n\tdescription: Type.String({\n\t\tdescription: \"A short (3-5 word) description of the task, shown in the task panel.\",\n\t}),\n\tprompt: Type.String({\n\t\tdescription:\n\t\t\t\"The full, self-contained task for the subagent. It cannot see this conversation, so include all needed context, files, and constraints.\",\n\t}),\n\tsubagent_type: Type.String({\n\t\tdescription: \"The name of the specialized agent to delegate to. Must be one of the available agents.\",\n\t}),\n\tresume_task_id: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"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.\",\n\t\t}),\n\t),\n});\n\ntype TaskParams = Static<typeof taskParams>;\n\nexport interface TaskToolDetails {\n\tsubagent_type: string;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** Pool-level task id usable for resume/polling. */\n\tpoolTaskId?: string;\n\t/** True when dispatched as a non-blocking background task. */\n\tbackground?: boolean;\n}\n\nexport interface TaskOutputDetails {\n\ttask_id: string;\n\tstatus: string;\n\tok: boolean;\n}\n\n/**\n * A short, human-readable task name for the task panel: the first line limited\n * to ~8 words so it stays glanceable. A character cap guards a single 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/** Create the Task tool definition. Registered as a customTool when enabled. */\nexport function createTaskToolDefinition(cwd: string = process.cwd()): ToolDefinition {\n\tconst agentList = describeAvailableAgents(cwd);\n\treturn defineTool<typeof taskParams, TaskToolDetails>({\n\t\tname: \"Task\",\n\t\tlabel: \"Task\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a specialized subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Select the agent via `subagent_type`; pass everything it needs via `prompt`. The subagent returns only its final answer.\",\n\t\t\t\"Available agents:\",\n\t\t\tagentList,\n\t\t\t\"WHEN TO USE: (1) self-contained work where you only need the final result;\",\n\t\t\t\"(2) parallel investigation/edits without losing your reasoning chain;\",\n\t\t\t\"(3) a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs);\",\n\t\t\t\"(4) a long command or test suite you want to run without blocking your reasoning.\",\n\t\t\t\"Do NOT use for tasks needing tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\",\n\t\t\t\"Prefer handling small, quick, or single-file tasks yourself; delegate only self-contained units of work.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"delegate a self-contained task to a specialized subagent (choose via subagent_type)\",\n\t\tparameters: taskParams,\n\n\t\tasync execute(_toolCallId, params: TaskParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\n\t\t\t// Pre-flight: if the inherited provider recently exhausted its quota (the\n\t\t\t// parent's own turn failed with a usage/rate-limit error that did not\n\t\t\t// recover), skip the spawn. Subagents run on the same provider, so this\n\t\t\t// would only burn another failed attempt. The signal self-expires and is\n\t\t\t// cleared on the next successful response.\n\t\t\tconst provider = ctx.model?.provider;\n\t\t\tconst exhaustion = provider ? getProviderExhaustion(provider) : undefined;\n\t\t\tif (exhaustion) {\n\t\t\t\tconst skipped = taskStore.create(params.description?.trim() || summarize(params.prompt), {\n\t\t\t\t\tsubagentMode: params.subagent_type,\n\t\t\t\t});\n\t\t\t\ttaskStore.update(skipped.id, { status: \"failed\" });\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\" as const,\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\t`Did not dispatch subagent \"${params.subagent_type}\": the \"${provider}\" provider appears ` +\n\t\t\t\t\t\t\t\t`exhausted or rate-limited (this session just failed with: ${exhaustion.message}). ` +\n\t\t\t\t\t\t\t\t`Subagents run on the same provider, so dispatching would fail too. Wait for the quota to ` +\n\t\t\t\t\t\t\t\t`reset or switch model/provider, then retry — or complete the work directly in this session.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { subagent_type: params.subagent_type, ok: false, taskId: skipped.id },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Resume path: continue a previously dispatched subagent with a follow-up\n\t\t\t// prompt, reusing its persisted session (full prior transcript).\n\t\t\tconst resumeId = params.resume_task_id?.trim();\n\t\t\tif (resumeId) {\n\t\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\ttry {\n\t\t\t\t\tconst dispatchResult = await pool.resume(resumeId, params.prompt, {\n\t\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t\t});\n\t\t\t\t\t// The session lives under the original task id; keep it as the resume handle.\n\t\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, resumeId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The model has already decided to delegate and which agent to use; honor\n\t\t\t// it. Validate the requested agent against the registry (no routing gate).\n\t\t\tconst registry = loadAgentRegistry({ cwd: ctx.cwd });\n\t\t\tconst def = registry.get(params.subagent_type);\n\t\t\tif (!def) {\n\t\t\t\tconst available = registry\n\t\t\t\t\t.list()\n\t\t\t\t\t.map((a) => a.name)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Unknown subagent_type: \"${params.subagent_type}\". Available agents: ${available || \"(none)\"}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\n\t\t\t// Background agents: dispatch detached and return a handle immediately so\n\t\t\t// the parent keeps reasoning. The parent polls via the TaskOutput tool.\n\t\t\tif (def.background) {\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\tconst dispatched = pool.dispatchDetached(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\tconst poolTaskId = dispatched.task_id;\n\t\t\t\tif (poolTaskId) trackBackgroundTask(pool, poolTaskId, task.id);\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\" as const,\n\t\t\t\t\t\t\ttext: `Background subagent (${params.subagent_type}) started with task_id \"${poolTaskId}\". It runs without blocking you. Call the TaskOutput tool with this task_id to check its status and collect the final answer.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tsubagent_type: params.subagent_type,\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\ttaskId: task.id,\n\t\t\t\t\t\tpoolTaskId,\n\t\t\t\t\t\tbackground: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst dispatchResult = await pool.dispatch(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, dispatchResult.task_id);\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 type = args.subagent_type ?? \"agent\";\n\t\t\tconst preview = summarize(args.description ?? args.prompt ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"Task \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${type}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n\n/** Extract the final answer from a finished dispatch, updating the task panel. */\nfunction finalizeForegroundResult(\n\tdispatchResult: TaskResult,\n\tsubagentType: string,\n\ttaskStoreId: number,\n\tresumeHandle: string | undefined,\n): { content: Array<{ type: \"text\"; text: string }>; details: TaskToolDetails } {\n\tconst result = dispatchResult.result;\n\tconst resultData = result?.result_data as SubagentResultFile | undefined;\n\tconst usage = resultData?.usage;\n\n\tif (!result || !result.ok) {\n\t\t// Signal failure by throwing: the agent loop derives a tool's error state\n\t\t// from a thrown error, not from a returned flag.\n\t\ttaskStore.update(taskStoreId, { status: \"failed\", usage });\n\t\tconst reason = result?.error ?? (result?.status ? `subagent ${result.status}` : \"unknown error\");\n\t\tthrow new Error(`Subagent (${subagentType}) failed: ${reason}`);\n\t}\n\n\t// Leave the task in the store with its final status; it stays visible in the\n\t// task panel until the next user message arrives.\n\ttaskStore.update(taskStoreId, { status: \"done\", usage });\n\tlet answer = resultData?.summary || \"(subagent returned no output)\";\n\t// Partial results are resumable; surface the handle so the parent can continue.\n\tif (result.status === \"partial\" && resumeHandle) {\n\t\tanswer += `\\n\\n[Partial result. To continue this subagent, call Task again with resume_task_id=\"${resumeHandle}\".]`;\n\t}\n\treturn {\n\t\tcontent: [{ type: \"text\", text: answer }],\n\t\tdetails: { subagent_type: subagentType, ok: true, taskId: taskStoreId, poolTaskId: resumeHandle },\n\t};\n}\n\n/**\n * Keep the task panel in sync for a detached background subagent: when the pool\n * reports the task finished, update the stored task's status and detach.\n */\nfunction trackBackgroundTask(pool: SubagentPool, poolTaskId: string, taskStoreId: number): void {\n\tfunction finish(status: \"done\" | \"failed\"): void {\n\t\ttaskStore.update(taskStoreId, { status });\n\t\tpool.off(\"task_done\", onDone);\n\t\tpool.off(\"task_failed\", onFail);\n\t\tpool.off(\"task_stalled\", onFail);\n\t\tpool.off(\"task_timeout\", onFail);\n\t}\n\tfunction onDone(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"done\");\n\t}\n\tfunction onFail(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"failed\");\n\t}\n\tpool.on(\"task_done\", onDone);\n\tpool.on(\"task_failed\", onFail);\n\tpool.on(\"task_stalled\", onFail);\n\tpool.on(\"task_timeout\", onFail);\n}\n\nconst taskOutputParams = Type.Object({\n\ttask_id: Type.String({\n\t\tdescription: \"The task_id of a background (or previously dispatched) subagent, as returned by the Task tool.\",\n\t}),\n});\n\ntype TaskOutputParams = Static<typeof taskOutputParams>;\n\n/**\n * TaskOutput tool: poll a background subagent and collect its final answer.\n * Returns the current status while running, or the subagent's final answer once\n * complete. Registered alongside the Task tool when subagents are enabled.\n */\nexport function createTaskOutputToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof taskOutputParams, TaskOutputDetails>({\n\t\tname: \"TaskOutput\",\n\t\tlabel: \"TaskOutput\",\n\t\tdescription: [\n\t\t\t\"Check the status of a background subagent and collect its final answer once it finishes.\",\n\t\t\t\"Pass the task_id returned by a background Task call. While the subagent runs this reports its status; once complete it returns only the subagent's final answer.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"check status / collect the result of a background subagent\",\n\t\tparameters: taskOutputParams,\n\n\t\tasync execute(_toolCallId, params: TaskOutputParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\t\t\tconst status = pool.get_status(params.task_id);\n\t\t\tif (status === \"running\" || status === \"queued\") {\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\" as const,\n\t\t\t\t\t\t\ttext: `Subagent task \"${params.task_id}\" is ${status}. Call TaskOutput again later to collect its result.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { task_id: params.task_id, status, ok: true },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = pool.collect(params.task_id);\n\t\t\tif (!result) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No result available for task \"${params.task_id}\" (status: ${status}). It may not exist or its result was already collected.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!result.ok) {\n\t\t\t\tconst reason = result.error ?? (result.status ? `subagent ${result.status}` : status);\n\t\t\t\tthrow new Error(`Background subagent \"${params.task_id}\" failed: ${reason}`);\n\t\t\t}\n\t\t\tconst resultData = result.result_data as SubagentResultFile | undefined;\n\t\t\tconst answer = resultData?.summary || \"(subagent returned no output)\";\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: answer }],\n\t\t\t\tdetails: { task_id: params.task_id, status: result.status ?? \"complete\", ok: true },\n\t\t\t};\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst text = theme.fg(\"toolTitle\", theme.bold(\"TaskOutput \")) + theme.fg(\"dim\", String(args.task_id ?? \"\"));\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n"]}
|
|
@@ -14,6 +14,7 @@ import { Text } from "@kolisachint/hoocode-tui";
|
|
|
14
14
|
import { Type } from "typebox";
|
|
15
15
|
import { loadAgentRegistry } from "../agent-registry.js";
|
|
16
16
|
import { defineTool } from "../extensions/types.js";
|
|
17
|
+
import { getProviderExhaustion } from "../provider-health.js";
|
|
17
18
|
import { getSubagentPool } from "../subagent-pool-instance.js";
|
|
18
19
|
import { taskStore } from "../task-store.js";
|
|
19
20
|
/**
|
|
@@ -127,6 +128,31 @@ export function createTaskToolDefinition(cwd = process.cwd()) {
|
|
|
127
128
|
parameters: taskParams,
|
|
128
129
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
129
130
|
const pool = getSubagentPool(ctx.cwd);
|
|
131
|
+
// Pre-flight: if the inherited provider recently exhausted its quota (the
|
|
132
|
+
// parent's own turn failed with a usage/rate-limit error that did not
|
|
133
|
+
// recover), skip the spawn. Subagents run on the same provider, so this
|
|
134
|
+
// would only burn another failed attempt. The signal self-expires and is
|
|
135
|
+
// cleared on the next successful response.
|
|
136
|
+
const provider = ctx.model?.provider;
|
|
137
|
+
const exhaustion = provider ? getProviderExhaustion(provider) : undefined;
|
|
138
|
+
if (exhaustion) {
|
|
139
|
+
const skipped = taskStore.create(params.description?.trim() || summarize(params.prompt), {
|
|
140
|
+
subagentMode: params.subagent_type,
|
|
141
|
+
});
|
|
142
|
+
taskStore.update(skipped.id, { status: "failed" });
|
|
143
|
+
return {
|
|
144
|
+
content: [
|
|
145
|
+
{
|
|
146
|
+
type: "text",
|
|
147
|
+
text: `Did not dispatch subagent "${params.subagent_type}": the "${provider}" provider appears ` +
|
|
148
|
+
`exhausted or rate-limited (this session just failed with: ${exhaustion.message}). ` +
|
|
149
|
+
`Subagents run on the same provider, so dispatching would fail too. Wait for the quota to ` +
|
|
150
|
+
`reset or switch model/provider, then retry — or complete the work directly in this session.`,
|
|
151
|
+
},
|
|
152
|
+
],
|
|
153
|
+
details: { subagent_type: params.subagent_type, ok: false, taskId: skipped.id },
|
|
154
|
+
};
|
|
155
|
+
}
|
|
130
156
|
// Resume path: continue a previously dispatched subagent with a follow-up
|
|
131
157
|
// prompt, reusing its persisted session (full prior transcript).
|
|
132
158
|
const resumeId = params.resume_task_id?.trim();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEpD,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CAAC,WAAmB,EAAU;IACtE,MAAM,KAAK,GAAG,WAAW;SACvB,KAAK,CAAC,IAAI,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC1B,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACpC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAElC,2EAA2E;IAC3E,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CA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ACtF,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,CAAC,OAAO,aAAa,MAAM,EAAE,CAAC,CAAC;YAC9E,CAAC;YACD,MAAM,UAAU,GAAG,MAAM,CAAC,WAA6C,CAAC;YACxE,MAAM,MAAM,GAAG,UAAU,EAAE,OAAO,IAAI,+BAA+B,CAAC;YACtE,OAAO;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;gBAClD,OAAO,EAAE,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,UAAU,EAAE,EAAE,EAAE,IAAI,EAAE;aACnF,CAAC;QAAA,CACF;QAED,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE;YACvB,MAAM,IAAI,GAAG,KAAK,CAAC,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;YAC5G,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAAA,CAC5B;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Task tool: delegate a focused task to a specialized subagent.\n *\n * Mirrors the Claude Code `Task` tool. The parent agent decides *when* to\n * delegate based on each agent's `description` (there is no deterministic gate)\n * and selects *which* agent via `subagent_type`. The chosen agent runs in a\n * fresh, isolated child process (SubagentPool) and only its final answer is\n * returned to the parent.\n *\n * It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { loadAgentRegistry } from \"../agent-registry.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport type { SubagentPool, TaskResult } from \"../subagent-pool.js\";\nimport { getSubagentPool } from \"../subagent-pool-instance.js\";\nimport type { SubagentResultFile } from \"../subagent-result.js\";\nimport { taskStore } from \"../task-store.js\";\n\n/**\n * Condense a (possibly multi-line, bulleted) agent description into a single\n * useful one-liner for the agent picker list.\n *\n * Built-in agent descriptions open with a boilerplate header (\"Use this\n * subagent ONLY when:\") followed by \"when to use\" bullets and a \"DO NOT use\"\n * section. Taking the first line alone yields that identical header for every\n * agent, so instead surface the first meaningful bullets (or the first prose\n * line) from the positive \"when to use\" region.\n */\nexport function summarizeAgentDescription(description: string): string {\n\tconst lines = description\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (lines.length === 0) return \"\";\n\n\t// Keep only the positive region: everything before a \"DO NOT use\" section.\n\tconst stop = lines.findIndex((line) => /^(do\\s*not|don'?t|avoid)\\b/i.test(line));\n\tconst region = stop === -1 ? lines : lines.slice(0, stop);\n\n\t// Drop a leading header line (e.g. \"Use this subagent ONLY when:\").\n\tconst body = region.length > 1 && region[0]!.endsWith(\":\") ? region.slice(1) : region;\n\n\tconst stripBullet = (line: string) => line.replace(/^[-*\\u2022]\\s+/, \"\").trim();\n\tconst bullets = body\n\t\t.filter((line) => /^[-*\\u2022]\\s+/.test(line))\n\t\t.map(stripBullet)\n\t\t.filter((line) => line.length > 0);\n\n\tconst summary = bullets.length > 0 ? bullets.slice(0, 3).join(\"; \") : (body[0] ?? lines[0] ?? \"\").replace(/:$/, \"\");\n\n\tconst MAX = 200;\n\treturn summary.length > MAX ? `${summary.slice(0, MAX - 1).trimEnd()}\\u2026` : summary;\n}\n\n/** Render the available agents as a \"- name: description\" list for prompts. */\nfunction describeAvailableAgents(cwd: string): string {\n\tconst agents = loadAgentRegistry({ cwd }).list();\n\tif (agents.length === 0) return \"(no agents available)\";\n\treturn agents.map((a) => `- ${a.name}: ${summarizeAgentDescription(a.description)}`).join(\"\\n\");\n}\n\n/** System prompt appendix for the main session when the Task tool is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport function buildTaskMainPrompt(cwd: string = process.cwd()): string {\n\treturn `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.\n\nAvailable agents (choose one via \\`subagent_type\\`):\n${describeAvailableAgents(cwd)}\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- Choose the agent whose description best matches the task.\n- Make every task specific and self-contained. The subagent cannot see this conversation; pass all necessary context (files, constraints, prior findings) in \\`prompt\\`.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Its intermediate reasoning, tool calls, and output are hidden from you.\n- Default to handling small, quick, or single-file work inline; delegate only self-contained units.\n- Some agents are configured to run in the background (non-blocking). For those, Task returns immediately with a task_id; use the **TaskOutput** tool with that task_id to check status and collect the final answer.\n- 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.`;\n}\n\nconst taskParams = Type.Object({\n\tdescription: Type.String({\n\t\tdescription: \"A short (3-5 word) description of the task, shown in the task panel.\",\n\t}),\n\tprompt: Type.String({\n\t\tdescription:\n\t\t\t\"The full, self-contained task for the subagent. It cannot see this conversation, so include all needed context, files, and constraints.\",\n\t}),\n\tsubagent_type: Type.String({\n\t\tdescription: \"The name of the specialized agent to delegate to. Must be one of the available agents.\",\n\t}),\n\tresume_task_id: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"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.\",\n\t\t}),\n\t),\n});\n\ntype TaskParams = Static<typeof taskParams>;\n\nexport interface TaskToolDetails {\n\tsubagent_type: string;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** Pool-level task id usable for resume/polling. */\n\tpoolTaskId?: string;\n\t/** True when dispatched as a non-blocking background task. */\n\tbackground?: boolean;\n}\n\nexport interface TaskOutputDetails {\n\ttask_id: string;\n\tstatus: string;\n\tok: boolean;\n}\n\n/**\n * A short, human-readable task name for the task panel: the first line limited\n * to ~8 words so it stays glanceable. A character cap guards a single 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/** Create the Task tool definition. Registered as a customTool when enabled. */\nexport function createTaskToolDefinition(cwd: string = process.cwd()): ToolDefinition {\n\tconst agentList = describeAvailableAgents(cwd);\n\treturn defineTool<typeof taskParams, TaskToolDetails>({\n\t\tname: \"Task\",\n\t\tlabel: \"Task\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a specialized subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Select the agent via `subagent_type`; pass everything it needs via `prompt`. The subagent returns only its final answer.\",\n\t\t\t\"Available agents:\",\n\t\t\tagentList,\n\t\t\t\"WHEN TO USE: (1) self-contained work where you only need the final result;\",\n\t\t\t\"(2) parallel investigation/edits without losing your reasoning chain;\",\n\t\t\t\"(3) a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs);\",\n\t\t\t\"(4) a long command or test suite you want to run without blocking your reasoning.\",\n\t\t\t\"Do NOT use for tasks needing tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\",\n\t\t\t\"Prefer handling small, quick, or single-file tasks yourself; delegate only self-contained units of work.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"delegate a self-contained task to a specialized subagent (choose via subagent_type)\",\n\t\tparameters: taskParams,\n\n\t\tasync execute(_toolCallId, params: TaskParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\n\t\t\t// Resume path: continue a previously dispatched subagent with a follow-up\n\t\t\t// prompt, reusing its persisted session (full prior transcript).\n\t\t\tconst resumeId = params.resume_task_id?.trim();\n\t\t\tif (resumeId) {\n\t\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\ttry {\n\t\t\t\t\tconst dispatchResult = await pool.resume(resumeId, params.prompt, {\n\t\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t\t});\n\t\t\t\t\t// The session lives under the original task id; keep it as the resume handle.\n\t\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, resumeId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The model has already decided to delegate and which agent to use; honor\n\t\t\t// it. Validate the requested agent against the registry (no routing gate).\n\t\t\tconst registry = loadAgentRegistry({ cwd: ctx.cwd });\n\t\t\tconst def = registry.get(params.subagent_type);\n\t\t\tif (!def) {\n\t\t\t\tconst available = registry\n\t\t\t\t\t.list()\n\t\t\t\t\t.map((a) => a.name)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Unknown subagent_type: \"${params.subagent_type}\". Available agents: ${available || \"(none)\"}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\n\t\t\t// Background agents: dispatch detached and return a handle immediately so\n\t\t\t// the parent keeps reasoning. The parent polls via the TaskOutput tool.\n\t\t\tif (def.background) {\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\tconst dispatched = pool.dispatchDetached(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\tconst poolTaskId = dispatched.task_id;\n\t\t\t\tif (poolTaskId) trackBackgroundTask(pool, poolTaskId, task.id);\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\" as const,\n\t\t\t\t\t\t\ttext: `Background subagent (${params.subagent_type}) started with task_id \"${poolTaskId}\". It runs without blocking you. Call the TaskOutput tool with this task_id to check its status and collect the final answer.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tsubagent_type: params.subagent_type,\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\ttaskId: task.id,\n\t\t\t\t\t\tpoolTaskId,\n\t\t\t\t\t\tbackground: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst dispatchResult = await pool.dispatch(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, dispatchResult.task_id);\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 type = args.subagent_type ?? \"agent\";\n\t\t\tconst preview = summarize(args.description ?? args.prompt ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"Task \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${type}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n\n/** Extract the final answer from a finished dispatch, updating the task panel. */\nfunction finalizeForegroundResult(\n\tdispatchResult: TaskResult,\n\tsubagentType: string,\n\ttaskStoreId: number,\n\tresumeHandle: string | undefined,\n): { content: Array<{ type: \"text\"; text: string }>; details: TaskToolDetails } {\n\tconst result = dispatchResult.result;\n\tconst resultData = result?.result_data as SubagentResultFile | undefined;\n\tconst usage = resultData?.usage;\n\n\tif (!result || !result.ok) {\n\t\t// Signal failure by throwing: the agent loop derives a tool's error state\n\t\t// from a thrown error, not from a returned flag.\n\t\ttaskStore.update(taskStoreId, { status: \"failed\", usage });\n\t\tconst reason = result?.error ?? (result?.status ? `subagent ${result.status}` : \"unknown error\");\n\t\tthrow new Error(`Subagent (${subagentType}) failed: ${reason}`);\n\t}\n\n\t// Leave the task in the store with its final status; it stays visible in the\n\t// task panel until the next user message arrives.\n\ttaskStore.update(taskStoreId, { status: \"done\", usage });\n\tlet answer = resultData?.summary || \"(subagent returned no output)\";\n\t// Partial results are resumable; surface the handle so the parent can continue.\n\tif (result.status === \"partial\" && resumeHandle) {\n\t\tanswer += `\\n\\n[Partial result. To continue this subagent, call Task again with resume_task_id=\"${resumeHandle}\".]`;\n\t}\n\treturn {\n\t\tcontent: [{ type: \"text\", text: answer }],\n\t\tdetails: { subagent_type: subagentType, ok: true, taskId: taskStoreId, poolTaskId: resumeHandle },\n\t};\n}\n\n/**\n * Keep the task panel in sync for a detached background subagent: when the pool\n * reports the task finished, update the stored task's status and detach.\n */\nfunction trackBackgroundTask(pool: SubagentPool, poolTaskId: string, taskStoreId: number): void {\n\tfunction finish(status: \"done\" | \"failed\"): void {\n\t\ttaskStore.update(taskStoreId, { status });\n\t\tpool.off(\"task_done\", onDone);\n\t\tpool.off(\"task_failed\", onFail);\n\t\tpool.off(\"task_stalled\", onFail);\n\t\tpool.off(\"task_timeout\", onFail);\n\t}\n\tfunction onDone(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"done\");\n\t}\n\tfunction onFail(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"failed\");\n\t}\n\tpool.on(\"task_done\", onDone);\n\tpool.on(\"task_failed\", onFail);\n\tpool.on(\"task_stalled\", onFail);\n\tpool.on(\"task_timeout\", onFail);\n}\n\nconst taskOutputParams = Type.Object({\n\ttask_id: Type.String({\n\t\tdescription: \"The task_id of a background (or previously dispatched) subagent, as returned by the Task tool.\",\n\t}),\n});\n\ntype TaskOutputParams = Static<typeof taskOutputParams>;\n\n/**\n * TaskOutput tool: poll a background subagent and collect its final answer.\n * Returns the current status while running, or the subagent's final answer once\n * complete. Registered alongside the Task tool when subagents are enabled.\n */\nexport function createTaskOutputToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof taskOutputParams, TaskOutputDetails>({\n\t\tname: \"TaskOutput\",\n\t\tlabel: \"TaskOutput\",\n\t\tdescription: [\n\t\t\t\"Check the status of a background subagent and collect its final answer once it finishes.\",\n\t\t\t\"Pass the task_id returned by a background Task call. While the subagent runs this reports its status; once complete it returns only the subagent's final answer.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"check status / collect the result of a background subagent\",\n\t\tparameters: taskOutputParams,\n\n\t\tasync execute(_toolCallId, params: TaskOutputParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\t\t\tconst status = pool.get_status(params.task_id);\n\t\t\tif (status === \"running\" || status === \"queued\") {\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\" as const,\n\t\t\t\t\t\t\ttext: `Subagent task \"${params.task_id}\" is ${status}. Call TaskOutput again later to collect its result.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { task_id: params.task_id, status, ok: true },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = pool.collect(params.task_id);\n\t\t\tif (!result) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No result available for task \"${params.task_id}\" (status: ${status}). It may not exist or its result was already collected.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!result.ok) {\n\t\t\t\tconst reason = result.error ?? (result.status ? `subagent ${result.status}` : status);\n\t\t\t\tthrow new Error(`Background subagent \"${params.task_id}\" failed: ${reason}`);\n\t\t\t}\n\t\t\tconst resultData = result.result_data as SubagentResultFile | undefined;\n\t\t\tconst answer = resultData?.summary || \"(subagent returned no output)\";\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: answer }],\n\t\t\t\tdetails: { task_id: params.task_id, status: result.status ?? \"complete\", ok: true },\n\t\t\t};\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst text = theme.fg(\"toolTitle\", theme.bold(\"TaskOutput \")) + theme.fg(\"dim\", String(args.task_id ?? \"\"));\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;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,EAAE,eAAe,EAAE,MA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AAC;YACD,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;gBAChB,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,YAAY,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;gBACtF,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,CAAC,OAAO,aAAa,MAAM,EAAE,CAAC,CAAC;YAC9E,CAAC;YACD,MAAM,UAAU,GAAG,MAAM,CAAC,WAA6C,CAAC;YACxE,MAAM,MAAM,GAAG,UAAU,EAAE,OAAO,IAAI,+BAA+B,CAAC;YACtE,OAAO;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;gBAClD,OAAO,EAAE,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,UAAU,EAAE,EAAE,EAAE,IAAI,EAAE;aACnF,CAAC;QAAA,CACF;QAED,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE;YACvB,MAAM,IAAI,GAAG,KAAK,CAAC,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;YAC5G,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAAA,CAC5B;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Task tool: delegate a focused task to a specialized subagent.\n *\n * Mirrors the Claude Code `Task` tool. The parent agent decides *when* to\n * delegate based on each agent's `description` (there is no deterministic gate)\n * and selects *which* agent via `subagent_type`. The chosen agent runs in a\n * fresh, isolated child process (SubagentPool) and only its final answer is\n * returned to the parent.\n *\n * It is an optional, opt-in tool (enabled via --subagent or the\n * `enableSubagent` setting); see buildSessionOptions in main.ts.\n */\n\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { loadAgentRegistry } from \"../agent-registry.js\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport { defineTool } from \"../extensions/types.js\";\nimport { getProviderExhaustion } from \"../provider-health.js\";\nimport type { SubagentPool, TaskResult } from \"../subagent-pool.js\";\nimport { getSubagentPool } from \"../subagent-pool-instance.js\";\nimport type { SubagentResultFile } from \"../subagent-result.js\";\nimport { taskStore } from \"../task-store.js\";\n\n/**\n * Condense a (possibly multi-line, bulleted) agent description into a single\n * useful one-liner for the agent picker list.\n *\n * Built-in agent descriptions open with a boilerplate header (\"Use this\n * subagent ONLY when:\") followed by \"when to use\" bullets and a \"DO NOT use\"\n * section. Taking the first line alone yields that identical header for every\n * agent, so instead surface the first meaningful bullets (or the first prose\n * line) from the positive \"when to use\" region.\n */\nexport function summarizeAgentDescription(description: string): string {\n\tconst lines = description\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (lines.length === 0) return \"\";\n\n\t// Keep only the positive region: everything before a \"DO NOT use\" section.\n\tconst stop = lines.findIndex((line) => /^(do\\s*not|don'?t|avoid)\\b/i.test(line));\n\tconst region = stop === -1 ? lines : lines.slice(0, stop);\n\n\t// Drop a leading header line (e.g. \"Use this subagent ONLY when:\").\n\tconst body = region.length > 1 && region[0]!.endsWith(\":\") ? region.slice(1) : region;\n\n\tconst stripBullet = (line: string) => line.replace(/^[-*\\u2022]\\s+/, \"\").trim();\n\tconst bullets = body\n\t\t.filter((line) => /^[-*\\u2022]\\s+/.test(line))\n\t\t.map(stripBullet)\n\t\t.filter((line) => line.length > 0);\n\n\tconst summary = bullets.length > 0 ? bullets.slice(0, 3).join(\"; \") : (body[0] ?? lines[0] ?? \"\").replace(/:$/, \"\");\n\n\tconst MAX = 200;\n\treturn summary.length > MAX ? `${summary.slice(0, MAX - 1).trimEnd()}\\u2026` : summary;\n}\n\n/** Render the available agents as a \"- name: description\" list for prompts. */\nfunction describeAvailableAgents(cwd: string): string {\n\tconst agents = loadAgentRegistry({ cwd }).list();\n\tif (agents.length === 0) return \"(no agents available)\";\n\treturn agents.map((a) => `- ${a.name}: ${summarizeAgentDescription(a.description)}`).join(\"\\n\");\n}\n\n/** System prompt appendix for the main session when the Task tool is enabled.\n * Instructs the parent agent on when and how to delegate effectively. */\nexport function buildTaskMainPrompt(cwd: string = process.cwd()): string {\n\treturn `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.\n\nAvailable agents (choose one via \\`subagent_type\\`):\n${describeAvailableAgents(cwd)}\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- Choose the agent whose description best matches the task.\n- Make every task specific and self-contained. The subagent cannot see this conversation; pass all necessary context (files, constraints, prior findings) in \\`prompt\\`.\n- Do NOT delegate tasks that require tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\n- The subagent returns ONLY its final answer. Its intermediate reasoning, tool calls, and output are hidden from you.\n- Default to handling small, quick, or single-file work inline; delegate only self-contained units.\n- Some agents are configured to run in the background (non-blocking). For those, Task returns immediately with a task_id; use the **TaskOutput** tool with that task_id to check status and collect the final answer.\n- 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.`;\n}\n\nconst taskParams = Type.Object({\n\tdescription: Type.String({\n\t\tdescription: \"A short (3-5 word) description of the task, shown in the task panel.\",\n\t}),\n\tprompt: Type.String({\n\t\tdescription:\n\t\t\t\"The full, self-contained task for the subagent. It cannot see this conversation, so include all needed context, files, and constraints.\",\n\t}),\n\tsubagent_type: Type.String({\n\t\tdescription: \"The name of the specialized agent to delegate to. Must be one of the available agents.\",\n\t}),\n\tresume_task_id: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"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.\",\n\t\t}),\n\t),\n});\n\ntype TaskParams = Static<typeof taskParams>;\n\nexport interface TaskToolDetails {\n\tsubagent_type: string;\n\tok: boolean;\n\terror?: string;\n\ttaskId: number;\n\t/** Pool-level task id usable for resume/polling. */\n\tpoolTaskId?: string;\n\t/** True when dispatched as a non-blocking background task. */\n\tbackground?: boolean;\n}\n\nexport interface TaskOutputDetails {\n\ttask_id: string;\n\tstatus: string;\n\tok: boolean;\n}\n\n/**\n * A short, human-readable task name for the task panel: the first line limited\n * to ~8 words so it stays glanceable. A character cap guards a single 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/** Create the Task tool definition. Registered as a customTool when enabled. */\nexport function createTaskToolDefinition(cwd: string = process.cwd()): ToolDefinition {\n\tconst agentList = describeAvailableAgents(cwd);\n\treturn defineTool<typeof taskParams, TaskToolDetails>({\n\t\tname: \"Task\",\n\t\tlabel: \"Task\",\n\t\tdescription: [\n\t\t\t\"Delegate a focused task to a specialized subagent that runs in a fresh, isolated context (it cannot see this conversation).\",\n\t\t\t\"Select the agent via `subagent_type`; pass everything it needs via `prompt`. The subagent returns only its final answer.\",\n\t\t\t\"Available agents:\",\n\t\t\tagentList,\n\t\t\t\"WHEN TO USE: (1) self-contained work where you only need the final result;\",\n\t\t\t\"(2) parallel investigation/edits without losing your reasoning chain;\",\n\t\t\t\"(3) a discrete unit (explore one module, run one test file, review one PR, fix one isolated bug, write docs);\",\n\t\t\t\"(4) a long command or test suite you want to run without blocking your reasoning.\",\n\t\t\t\"Do NOT use for tasks needing tight back-and-forth with your current reasoning, or edits to files you are actively reasoning about.\",\n\t\t\t\"Prefer handling small, quick, or single-file tasks yourself; delegate only self-contained units of work.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"delegate a self-contained task to a specialized subagent (choose via subagent_type)\",\n\t\tparameters: taskParams,\n\n\t\tasync execute(_toolCallId, params: TaskParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\n\t\t\t// Pre-flight: if the inherited provider recently exhausted its quota (the\n\t\t\t// parent's own turn failed with a usage/rate-limit error that did not\n\t\t\t// recover), skip the spawn. Subagents run on the same provider, so this\n\t\t\t// would only burn another failed attempt. The signal self-expires and is\n\t\t\t// cleared on the next successful response.\n\t\t\tconst provider = ctx.model?.provider;\n\t\t\tconst exhaustion = provider ? getProviderExhaustion(provider) : undefined;\n\t\t\tif (exhaustion) {\n\t\t\t\tconst skipped = taskStore.create(params.description?.trim() || summarize(params.prompt), {\n\t\t\t\t\tsubagentMode: params.subagent_type,\n\t\t\t\t});\n\t\t\t\ttaskStore.update(skipped.id, { status: \"failed\" });\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\" as const,\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\t`Did not dispatch subagent \"${params.subagent_type}\": the \"${provider}\" provider appears ` +\n\t\t\t\t\t\t\t\t`exhausted or rate-limited (this session just failed with: ${exhaustion.message}). ` +\n\t\t\t\t\t\t\t\t`Subagents run on the same provider, so dispatching would fail too. Wait for the quota to ` +\n\t\t\t\t\t\t\t\t`reset or switch model/provider, then retry — or complete the work directly in this session.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { subagent_type: params.subagent_type, ok: false, taskId: skipped.id },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Resume path: continue a previously dispatched subagent with a follow-up\n\t\t\t// prompt, reusing its persisted session (full prior transcript).\n\t\t\tconst resumeId = params.resume_task_id?.trim();\n\t\t\tif (resumeId) {\n\t\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\ttry {\n\t\t\t\t\tconst dispatchResult = await pool.resume(resumeId, params.prompt, {\n\t\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t\t});\n\t\t\t\t\t// The session lives under the original task id; keep it as the resume handle.\n\t\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, resumeId);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttaskStore.update(task.id, { status: \"failed\" });\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// The model has already decided to delegate and which agent to use; honor\n\t\t\t// it. Validate the requested agent against the registry (no routing gate).\n\t\t\tconst registry = loadAgentRegistry({ cwd: ctx.cwd });\n\t\t\tconst def = registry.get(params.subagent_type);\n\t\t\tif (!def) {\n\t\t\t\tconst available = registry\n\t\t\t\t\t.list()\n\t\t\t\t\t.map((a) => a.name)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Unknown subagent_type: \"${params.subagent_type}\". Available agents: ${available || \"(none)\"}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst summary = params.description?.trim() || summarize(params.prompt);\n\t\t\tconst task = taskStore.create(summary, { subagentMode: params.subagent_type });\n\n\t\t\t// Background agents: dispatch detached and return a handle immediately so\n\t\t\t// the parent keeps reasoning. The parent polls via the TaskOutput tool.\n\t\t\tif (def.background) {\n\t\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\t\tconst dispatched = pool.dispatchDetached(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\tconst poolTaskId = dispatched.task_id;\n\t\t\t\tif (poolTaskId) trackBackgroundTask(pool, poolTaskId, task.id);\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\" as const,\n\t\t\t\t\t\t\ttext: `Background subagent (${params.subagent_type}) started with task_id \"${poolTaskId}\". It runs without blocking you. Call the TaskOutput tool with this task_id to check its status and collect the final answer.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tsubagent_type: params.subagent_type,\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\ttaskId: task.id,\n\t\t\t\t\t\tpoolTaskId,\n\t\t\t\t\t\tbackground: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttaskStore.update(task.id, { status: \"in_progress\" });\n\t\t\ttry {\n\t\t\t\tconst dispatchResult = await pool.dispatch(params.prompt, {\n\t\t\t\t\tforceAgent: params.subagent_type,\n\t\t\t\t\tcontext: \"\",\n\t\t\t\t\tmodel: ctx.model?.id,\n\t\t\t\t\tprovider: ctx.model?.provider,\n\t\t\t\t});\n\t\t\t\treturn finalizeForegroundResult(dispatchResult, params.subagent_type, task.id, dispatchResult.task_id);\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 type = args.subagent_type ?? \"agent\";\n\t\t\tconst preview = summarize(args.description ?? args.prompt ?? \"\");\n\t\t\tconst text =\n\t\t\t\ttheme.fg(\"toolTitle\", theme.bold(\"Task \")) +\n\t\t\t\ttheme.fg(\"accent\", `[${type}]`) +\n\t\t\t\ttheme.fg(\"dim\", ` ${preview}`);\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n\n/** Extract the final answer from a finished dispatch, updating the task panel. */\nfunction finalizeForegroundResult(\n\tdispatchResult: TaskResult,\n\tsubagentType: string,\n\ttaskStoreId: number,\n\tresumeHandle: string | undefined,\n): { content: Array<{ type: \"text\"; text: string }>; details: TaskToolDetails } {\n\tconst result = dispatchResult.result;\n\tconst resultData = result?.result_data as SubagentResultFile | undefined;\n\tconst usage = resultData?.usage;\n\n\tif (!result || !result.ok) {\n\t\t// Signal failure by throwing: the agent loop derives a tool's error state\n\t\t// from a thrown error, not from a returned flag.\n\t\ttaskStore.update(taskStoreId, { status: \"failed\", usage });\n\t\tconst reason = result?.error ?? (result?.status ? `subagent ${result.status}` : \"unknown error\");\n\t\tthrow new Error(`Subagent (${subagentType}) failed: ${reason}`);\n\t}\n\n\t// Leave the task in the store with its final status; it stays visible in the\n\t// task panel until the next user message arrives.\n\ttaskStore.update(taskStoreId, { status: \"done\", usage });\n\tlet answer = resultData?.summary || \"(subagent returned no output)\";\n\t// Partial results are resumable; surface the handle so the parent can continue.\n\tif (result.status === \"partial\" && resumeHandle) {\n\t\tanswer += `\\n\\n[Partial result. To continue this subagent, call Task again with resume_task_id=\"${resumeHandle}\".]`;\n\t}\n\treturn {\n\t\tcontent: [{ type: \"text\", text: answer }],\n\t\tdetails: { subagent_type: subagentType, ok: true, taskId: taskStoreId, poolTaskId: resumeHandle },\n\t};\n}\n\n/**\n * Keep the task panel in sync for a detached background subagent: when the pool\n * reports the task finished, update the stored task's status and detach.\n */\nfunction trackBackgroundTask(pool: SubagentPool, poolTaskId: string, taskStoreId: number): void {\n\tfunction finish(status: \"done\" | \"failed\"): void {\n\t\ttaskStore.update(taskStoreId, { status });\n\t\tpool.off(\"task_done\", onDone);\n\t\tpool.off(\"task_failed\", onFail);\n\t\tpool.off(\"task_stalled\", onFail);\n\t\tpool.off(\"task_timeout\", onFail);\n\t}\n\tfunction onDone(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"done\");\n\t}\n\tfunction onFail(data: { task_id?: string }): void {\n\t\tif (data?.task_id === poolTaskId) finish(\"failed\");\n\t}\n\tpool.on(\"task_done\", onDone);\n\tpool.on(\"task_failed\", onFail);\n\tpool.on(\"task_stalled\", onFail);\n\tpool.on(\"task_timeout\", onFail);\n}\n\nconst taskOutputParams = Type.Object({\n\ttask_id: Type.String({\n\t\tdescription: \"The task_id of a background (or previously dispatched) subagent, as returned by the Task tool.\",\n\t}),\n});\n\ntype TaskOutputParams = Static<typeof taskOutputParams>;\n\n/**\n * TaskOutput tool: poll a background subagent and collect its final answer.\n * Returns the current status while running, or the subagent's final answer once\n * complete. Registered alongside the Task tool when subagents are enabled.\n */\nexport function createTaskOutputToolDefinition(): ToolDefinition {\n\treturn defineTool<typeof taskOutputParams, TaskOutputDetails>({\n\t\tname: \"TaskOutput\",\n\t\tlabel: \"TaskOutput\",\n\t\tdescription: [\n\t\t\t\"Check the status of a background subagent and collect its final answer once it finishes.\",\n\t\t\t\"Pass the task_id returned by a background Task call. While the subagent runs this reports its status; once complete it returns only the subagent's final answer.\",\n\t\t].join(\"\\n\"),\n\t\tpromptSnippet: \"check status / collect the result of a background subagent\",\n\t\tparameters: taskOutputParams,\n\n\t\tasync execute(_toolCallId, params: TaskOutputParams, _signal, _onUpdate, ctx) {\n\t\t\tconst pool = getSubagentPool(ctx.cwd);\n\t\t\tconst status = pool.get_status(params.task_id);\n\t\t\tif (status === \"running\" || status === \"queued\") {\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\" as const,\n\t\t\t\t\t\t\ttext: `Subagent task \"${params.task_id}\" is ${status}. Call TaskOutput again later to collect its result.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { task_id: params.task_id, status, ok: true },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = pool.collect(params.task_id);\n\t\t\tif (!result) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No result available for task \"${params.task_id}\" (status: ${status}). It may not exist or its result was already collected.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!result.ok) {\n\t\t\t\tconst reason = result.error ?? (result.status ? `subagent ${result.status}` : status);\n\t\t\t\tthrow new Error(`Background subagent \"${params.task_id}\" failed: ${reason}`);\n\t\t\t}\n\t\t\tconst resultData = result.result_data as SubagentResultFile | undefined;\n\t\t\tconst answer = resultData?.summary || \"(subagent returned no output)\";\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: answer }],\n\t\t\t\tdetails: { task_id: params.task_id, status: result.status ?? \"complete\", ok: true },\n\t\t\t};\n\t\t},\n\n\t\trenderCall(args, theme) {\n\t\t\tconst text = theme.fg(\"toolTitle\", theme.bold(\"TaskOutput \")) + theme.fg(\"dim\", String(args.task_id ?? \"\"));\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t});\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-templates.generated.d.ts","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,uBAAuB,EAAE,MAC+Z,CAAC;AAEtc,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAKjD,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,CAAC;AAE5D,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAUzD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution.\"\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\tdoc: \"---\\nname: doc\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing or updating README files\\n - Adding inline code comments or API documentation\\n - Creating user guides, tutorials, or changelogs\\n - Explaining architecture or design decisions\\n\\n DO NOT use for:\\n - Modifying source logic (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Code review (use review agent)\\n\\n Output: Written documentation. Concise, accurate, and well-structured.\\n Cost: Low (read + write docs only)\\n Isolation: Can run in parallel with explore and review tasks\\ntools: read, write, edit, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a documentation subagent running inside hoocode. You write and update documentation. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and write documentation files (README, comments, guides). Do not modify source logic.\\n- Produce concise, accurate, and well-structured documentation.\\n\\nMethod:\\n1. Read the relevant source files to understand what needs documenting.\\n2. Write or update the requested documentation.\\n3. Verify that the documentation is consistent with the code.\\n\\nGuidance:\\n- Focus on clarity and accuracy. Avoid unnecessary verbosity.\\n- Match the project's existing documentation style.\\n- Your final message must contain ONLY the documentation or a summary of what was written.\\n- Do not narrate intermediate steps or include tool logs.\\n\",\n\tedit: \"---\\nname: edit\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing new code or creating new files\\n - Refactoring existing code across one or more files\\n - Fixing bugs or applying targeted corrections\\n - Migrating patterns or renaming symbols\\n\\n DO NOT use for:\\n - Read-only exploration\\n - Running tests (use test agent)\\n - Code review (use review agent)\\n\\n Output: Changed files with path:line descriptions. No narration.\\n Cost: Medium (read + write)\\n Isolation: Should not run concurrently with other edit tasks on the same files\\ntools: read, edit, write, grep, find, ls, bash\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are an edit subagent running inside hoocode. You implement one focused code change. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, edit, and write files, and run commands needed to make the change.\\n- Stay strictly within the requested task. Do not refactor unrelated code.\\n\\nMethod:\\n1. Read the relevant files before changing them.\\n2. Match the existing style: indentation, naming, import order.\\n3. Make the smallest change that fully satisfies the task.\\n4. Verify your edits by re-reading the changed regions.\\n\\nGuidance:\\n- Break down multi-file tasks. Handle one logical unit at a time.\\n- Your final answer must contain ONLY your answer — it is the only thing the caller receives.\\n- Summarize what you changed and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running tests or linting\\n - Reviewing code quality\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls, bash\\nmodel: haiku\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files. Use bash only for read-only inspection (e.g. git log, wc, tree).\\n- Use read, grep, find, and ls (and read-only shell commands) to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No specialized agent (explore, edit, review, test, doc) clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer a specialized agent when the task is clearly read-only (explore),\\n a focused code change (edit), a review (review), running tests (test), or\\n documentation (doc).\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with edit tasks on the same files\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\treview:\n\t\t\"---\\nname: review\\ndescription: |\\n Use this subagent ONLY when:\\n - Reviewing code for correctness, clarity, or risk\\n - Auditing for security vulnerabilities\\n - Checking compliance with project conventions\\n - Evaluating performance or architecture concerns\\n\\n DO NOT use for:\\n - Making code changes (use edit agent)\\n - Running tests (use test agent)\\n - Read-only exploration (use explore agent)\\n\\n Output: Verdict + findings ordered by severity with path:line and suggestions.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with explore and doc tasks\\ntools: read, grep, find, ls\\nmodel: haiku\\n---\\nYou are a review subagent running inside hoocode. You review code and report issues. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- READ ONLY. Do not modify files.\\n- Review the code or change named in the task for correctness, clarity, and risk.\\n\\nMethod:\\n1. Read the relevant code (and any diff or context provided).\\n2. Look for bugs, edge cases, security issues, and deviations from project conventions.\\n3. Prioritize correctness over style nits.\\n\\nGuidance:\\n- Start with an overall verdict (approve / approve with minor suggestions / needs changes).\\n- List findings ordered by severity, each with path:line and a concrete suggestion.\\n- If nothing is wrong, say so explicitly.\\n- Do not narrate your reading process or include tool logs.\\n- Your final message must contain ONLY your answer.\\n\",\n\ttest: \"---\\nname: test\\ndescription: |\\n Use this subagent ONLY when:\\n - Running test suites or individual tests\\n - Validating functionality after changes\\n - Checking test coverage or generating coverage reports\\n - Diagnosing test failures\\n\\n DO NOT use for:\\n - Modifying source code (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Security audits (use review agent)\\n\\n Output: Pass/fail counts, failing test paths, and root causes.\\n Cost: Medium (read + run)\\n Isolation: Can run in parallel with explore tasks; should not run during active edits\\ntools: read, bash, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a test subagent running inside hoocode. You run tests and report results. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and run commands (test runners, build, lint). Do not modify source files.\\n- Run the tests the task names; if unspecified, find and run the most relevant suite.\\n\\nMethod:\\n1. Locate the test command from package.json, config, or the task instructions.\\n2. Run it. Capture pass/fail counts and the first meaningful failures.\\n3. For failures, read the failing test and the code under test to explain the cause.\\n\\nGuidance:\\n- Report: (1) command(s) run, (2) overall result (pass/fail with counts), (3) for each failure: path:line, error message, and likely cause.\\n- Keep failure descriptions concise; do not dump full logs.\\n- If tests pass, confirm that the relevant area is covered.\\n- Your final message must contain ONLY your answer.\\n\",\n};\n"]}
|
|
1
|
+
{"version":3,"file":"init-templates.generated.d.ts","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,uBAAuB,EAAE,MAC+Z,CAAC;AAEtc,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAKjD,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,CAAC;AAE5D,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAUzD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution.\"\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\tdoc: \"---\\nname: doc\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing or updating README files\\n - Adding inline code comments or API documentation\\n - Creating user guides, tutorials, or changelogs\\n - Explaining architecture or design decisions\\n\\n DO NOT use for:\\n - Modifying source logic (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Code review (use review agent)\\n\\n Output: Written documentation. Concise, accurate, and well-structured.\\n Cost: Low (read + write docs only)\\n Isolation: Can run in parallel with explore and review tasks\\ntools: read, write, edit, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a documentation subagent running inside hoocode. You write and update documentation. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and write documentation files (README, comments, guides). Do not modify source logic.\\n- Produce concise, accurate, and well-structured documentation.\\n\\nMethod:\\n1. Read the relevant source files to understand what needs documenting.\\n2. Write or update the requested documentation.\\n3. Verify that the documentation is consistent with the code.\\n\\nGuidance:\\n- Focus on clarity and accuracy. Avoid unnecessary verbosity.\\n- Match the project's existing documentation style.\\n- Your final message must contain ONLY the documentation or a summary of what was written.\\n- Do not narrate intermediate steps or include tool logs.\\n\",\n\tedit: \"---\\nname: edit\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing new code or creating new files\\n - Refactoring existing code across one or more files\\n - Fixing bugs or applying targeted corrections\\n - Migrating patterns or renaming symbols\\n\\n DO NOT use for:\\n - Read-only exploration\\n - Running tests (use test agent)\\n - Code review (use review agent)\\n\\n Output: Changed files with path:line descriptions. No narration.\\n Cost: Medium (read + write)\\n Isolation: Should not run concurrently with other edit tasks on the same files\\ntools: read, edit, write, grep, find, ls, bash\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are an edit subagent running inside hoocode. You implement one focused code change. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, edit, and write files, and run commands needed to make the change.\\n- Stay strictly within the requested task. Do not refactor unrelated code.\\n\\nMethod:\\n1. Read the relevant files before changing them.\\n2. Match the existing style: indentation, naming, import order.\\n3. Make the smallest change that fully satisfies the task.\\n4. Verify your edits by re-reading the changed regions.\\n\\nGuidance:\\n- Break down multi-file tasks. Handle one logical unit at a time.\\n- Your final answer must contain ONLY your answer — it is the only thing the caller receives.\\n- Summarize what you changed and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running tests or linting\\n - Reviewing code quality\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls, bash\\nmodel: haiku\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files. Use bash only for read-only inspection (e.g. git log, wc, tree).\\n- Use read, grep, find, and ls (and read-only shell commands) to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No specialized agent (explore, edit, review, test, doc) clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer a specialized agent when the task is clearly read-only (explore),\\n a focused code change (edit), a review (review), running tests (test), or\\n documentation (doc).\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with edit tasks on the same files\\ntools: read, bash, edit, write, grep, find, ls\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\treview:\n\t\t\"---\\nname: review\\ndescription: |\\n Use this subagent ONLY when:\\n - Reviewing code for correctness, clarity, or risk\\n - Auditing for security vulnerabilities\\n - Checking compliance with project conventions\\n - Evaluating performance or architecture concerns\\n\\n DO NOT use for:\\n - Making code changes (use edit agent)\\n - Running tests (use test agent)\\n - Read-only exploration (use explore agent)\\n\\n Output: Verdict + findings ordered by severity with path:line and suggestions.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with explore and doc tasks\\ntools: read, grep, find, ls\\nmodel: haiku\\n---\\nYou are a review subagent running inside hoocode. You review code and report issues. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- READ ONLY. Do not modify files.\\n- Review the code or change named in the task for correctness, clarity, and risk.\\n\\nMethod:\\n1. Read the relevant code (and any diff or context provided).\\n2. Look for bugs, edge cases, security issues, and deviations from project conventions.\\n3. Prioritize correctness over style nits.\\n\\nGuidance:\\n- Start with an overall verdict (approve / approve with minor suggestions / needs changes).\\n- List findings ordered by severity, each with path:line and a concrete suggestion.\\n- If nothing is wrong, say so explicitly.\\n- Do not narrate your reading process or include tool logs.\\n- Your final message must contain ONLY your answer.\\n\",\n\ttest: \"---\\nname: test\\ndescription: |\\n Use this subagent ONLY when:\\n - Running test suites or individual tests\\n - Validating functionality after changes\\n - Checking test coverage or generating coverage reports\\n - Diagnosing test failures\\n\\n DO NOT use for:\\n - Modifying source code (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Security audits (use review agent)\\n\\n Output: Pass/fail counts, failing test paths, and root causes.\\n Cost: Medium (read + run)\\n Isolation: Can run in parallel with explore tasks; should not run during active edits\\ntools: read, bash, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a test subagent running inside hoocode. You run tests and report results. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and run commands (test runners, build, lint). Do not modify source files.\\n- Run the tests the task names; if unspecified, find and run the most relevant suite.\\n\\nMethod:\\n1. Locate the test command from package.json, config, or the task instructions.\\n2. Run it. Capture pass/fail counts and the first meaningful failures.\\n3. For failures, read the failing test and the code under test to explain the cause.\\n\\nGuidance:\\n- Report: (1) command(s) run, (2) overall result (pass/fail with counts), (3) for each failure: path:line, error message, and likely cause.\\n- Keep failure descriptions concise; do not dump full logs.\\n- If tests pass, confirm that the relevant area is covered.\\n- Your final message must contain ONLY your answer.\\n\",\n};\n"]}
|
|
@@ -13,7 +13,7 @@ export const EMBEDDED_AGENT_PROMPTS = {
|
|
|
13
13
|
doc: "---\nname: doc\ndescription: |\n Use this subagent ONLY when:\n - Writing or updating README files\n - Adding inline code comments or API documentation\n - Creating user guides, tutorials, or changelogs\n - Explaining architecture or design decisions\n\n DO NOT use for:\n - Modifying source logic (use edit agent)\n - Read-only exploration (use explore agent)\n - Code review (use review agent)\n\n Output: Written documentation. Concise, accurate, and well-structured.\n Cost: Low (read + write docs only)\n Isolation: Can run in parallel with explore and review tasks\ntools: read, write, edit, grep, find, ls\nmodel: sonnet\n---\nYou are a documentation subagent running inside hoocode. You write and update documentation. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- You may read files and write documentation files (README, comments, guides). Do not modify source logic.\n- Produce concise, accurate, and well-structured documentation.\n\nMethod:\n1. Read the relevant source files to understand what needs documenting.\n2. Write or update the requested documentation.\n3. Verify that the documentation is consistent with the code.\n\nGuidance:\n- Focus on clarity and accuracy. Avoid unnecessary verbosity.\n- Match the project's existing documentation style.\n- Your final message must contain ONLY the documentation or a summary of what was written.\n- Do not narrate intermediate steps or include tool logs.\n",
|
|
14
14
|
edit: "---\nname: edit\ndescription: |\n Use this subagent ONLY when:\n - Writing new code or creating new files\n - Refactoring existing code across one or more files\n - Fixing bugs or applying targeted corrections\n - Migrating patterns or renaming symbols\n\n DO NOT use for:\n - Read-only exploration\n - Running tests (use test agent)\n - Code review (use review agent)\n\n Output: Changed files with path:line descriptions. No narration.\n Cost: Medium (read + write)\n Isolation: Should not run concurrently with other edit tasks on the same files\ntools: read, edit, write, grep, find, ls, bash\nmodel: sonnet\nmaxTurns: 25\n---\nYou are an edit subagent running inside hoocode. You implement one focused code change. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- You may read, edit, and write files, and run commands needed to make the change.\n- Stay strictly within the requested task. Do not refactor unrelated code.\n\nMethod:\n1. Read the relevant files before changing them.\n2. Match the existing style: indentation, naming, import order.\n3. Make the smallest change that fully satisfies the task.\n4. Verify your edits by re-reading the changed regions.\n\nGuidance:\n- Break down multi-file tasks. Handle one logical unit at a time.\n- Your final answer must contain ONLY your answer — it is the only thing the caller receives.\n- Summarize what you changed and where (path:line), and any follow-up the caller should know.\n- Do not narrate intermediate steps or include tool logs.\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\n",
|
|
15
15
|
explore: "---\nname: explore\ndescription: |\n Use this subagent ONLY when:\n - Reading or understanding code without changes\n - Scouting a codebase for plans or maps\n - Analyzing dependencies, imports, project structure\n - Investigating errors or tracing execution flow\n - Estimating scope before edits\n\n DO NOT use for:\n - Writing or modifying code\n - Running tests or linting\n - Reviewing code quality\n\n Output: Concise summary, file list, or plan. No code changes.\n Cost: Low (read-only)\n Isolation: Can run in parallel with other explore tasks\ntools: read, grep, find, ls, bash\nmodel: haiku\n---\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- Do not modify, create, or delete files. Use bash only for read-only inspection (e.g. git log, wc, tree).\n- Use read, grep, find, and ls (and read-only shell commands) to locate and understand code.\n\nMethod:\n1. Break the task into concrete questions.\n2. Search broadly, then read the specific files that matter.\n3. Trace logic across files; note exact paths and line numbers.\n\nGuidance:\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\n- Do not narrate your search or include tool logs.\n",
|
|
16
|
-
"general-purpose": "---\nname: general-purpose\ndescription: |\n Use this subagent when:\n - A task is multi-step or open-ended and needs both investigation and action\n - No specialized agent (explore, edit, review, test, doc) clearly fits\n - You are searching for code or a pattern and are unsure where it lives\n - The work spans reading, editing, and running commands together\n\n Prefer a specialized agent when the task is clearly read-only (explore),\n a focused code change (edit), a review (review), running tests (test), or\n documentation (doc).\n\n Output: The completed result plus a summary of what was done and where.\n Cost: Variable (read + write + run)\n Isolation: Should not run concurrently with edit tasks on the same files\nmodel: sonnet\nmaxTurns: 25\n---\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- You may read, search, edit, and write files, and run commands needed to complete the task.\n- Stay within the requested task. Do not refactor or change unrelated code.\n\nMethod:\n1. Break the task into concrete steps.\n2. Investigate before acting: read the relevant files and trace the logic.\n3. Make the smallest changes that fully satisfy the task, matching existing style.\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\n\nGuidance:\n- Your final answer is the only thing the caller receives. Make it self-contained.\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\n- Do not narrate intermediate steps or include tool logs.\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\n",
|
|
16
|
+
"general-purpose": "---\nname: general-purpose\ndescription: |\n Use this subagent when:\n - A task is multi-step or open-ended and needs both investigation and action\n - No specialized agent (explore, edit, review, test, doc) clearly fits\n - You are searching for code or a pattern and are unsure where it lives\n - The work spans reading, editing, and running commands together\n\n Prefer a specialized agent when the task is clearly read-only (explore),\n a focused code change (edit), a review (review), running tests (test), or\n documentation (doc).\n\n Output: The completed result plus a summary of what was done and where.\n Cost: Variable (read + write + run)\n Isolation: Should not run concurrently with edit tasks on the same files\ntools: read, bash, edit, write, grep, find, ls\nmodel: sonnet\nmaxTurns: 25\n---\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- You may read, search, edit, and write files, and run commands needed to complete the task.\n- Stay within the requested task. Do not refactor or change unrelated code.\n\nMethod:\n1. Break the task into concrete steps.\n2. Investigate before acting: read the relevant files and trace the logic.\n3. Make the smallest changes that fully satisfy the task, matching existing style.\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\n\nGuidance:\n- Your final answer is the only thing the caller receives. Make it self-contained.\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\n- Do not narrate intermediate steps or include tool logs.\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\n",
|
|
17
17
|
review: "---\nname: review\ndescription: |\n Use this subagent ONLY when:\n - Reviewing code for correctness, clarity, or risk\n - Auditing for security vulnerabilities\n - Checking compliance with project conventions\n - Evaluating performance or architecture concerns\n\n DO NOT use for:\n - Making code changes (use edit agent)\n - Running tests (use test agent)\n - Read-only exploration (use explore agent)\n\n Output: Verdict + findings ordered by severity with path:line and suggestions.\n Cost: Low (read-only)\n Isolation: Can run in parallel with explore and doc tasks\ntools: read, grep, find, ls\nmodel: haiku\n---\nYou are a review subagent running inside hoocode. You review code and report issues. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- READ ONLY. Do not modify files.\n- Review the code or change named in the task for correctness, clarity, and risk.\n\nMethod:\n1. Read the relevant code (and any diff or context provided).\n2. Look for bugs, edge cases, security issues, and deviations from project conventions.\n3. Prioritize correctness over style nits.\n\nGuidance:\n- Start with an overall verdict (approve / approve with minor suggestions / needs changes).\n- List findings ordered by severity, each with path:line and a concrete suggestion.\n- If nothing is wrong, say so explicitly.\n- Do not narrate your reading process or include tool logs.\n- Your final message must contain ONLY your answer.\n",
|
|
18
18
|
test: "---\nname: test\ndescription: |\n Use this subagent ONLY when:\n - Running test suites or individual tests\n - Validating functionality after changes\n - Checking test coverage or generating coverage reports\n - Diagnosing test failures\n\n DO NOT use for:\n - Modifying source code (use edit agent)\n - Read-only exploration (use explore agent)\n - Security audits (use review agent)\n\n Output: Pass/fail counts, failing test paths, and root causes.\n Cost: Medium (read + run)\n Isolation: Can run in parallel with explore tasks; should not run during active edits\ntools: read, bash, grep, find, ls\nmodel: sonnet\n---\nYou are a test subagent running inside hoocode. You run tests and report results. You run in an isolated context and cannot see the parent conversation.\n\nScope:\n- You may read files and run commands (test runners, build, lint). Do not modify source files.\n- Run the tests the task names; if unspecified, find and run the most relevant suite.\n\nMethod:\n1. Locate the test command from package.json, config, or the task instructions.\n2. Run it. Capture pass/fail counts and the first meaningful failures.\n3. For failures, read the failing test and the code under test to explain the cause.\n\nGuidance:\n- Report: (1) command(s) run, (2) overall result (pass/fail with counts), (3) for each failure: path:line, error message, and likely cause.\n- Keep failure descriptions concise; do not dump full logs.\n- If tests pass, confirm that the relevant area is covered.\n- Your final message must contain ONLY your answer.\n",
|
|
19
19
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-templates.generated.js","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAAA,iEAA+D;AAC/D,sDAAsD;AACtD,wCAAwC;AAExC,MAAM,CAAC,MAAM,uBAAuB,GACnC,ocAAoc,CAAC;AAEtc,MAAM,CAAC,MAAM,cAAc,GAA2B;IACrD,GAAG,EAAE,ogBAAkgB;IACvgB,KAAK,EAAE,unBAAmnB;IAC1nB,KAAK,EAAE,6pBAAipB;IACxpB,IAAI,EAAE,isBAAqrB;CAC3rB,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAA2B,EAAE,CAAC;AAE5D,MAAM,CAAC,MAAM,sBAAsB,GAA2B;IAC7D,GAAG,EAAE,g8CAAg8C;IACr8C,IAAI,EAAE,wmDAAsmD;IAC5mD,OAAO,EACN,u9CAAu9C;IACx9C,iBAAiB,EAChB,4vDAA4vD;IAC7vD,MAAM,EACL,i8CAAi8C;IACl8C,IAAI,EAAE,4hDAA4hD;CACliD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution.\"\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\tdoc: \"---\\nname: doc\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing or updating README files\\n - Adding inline code comments or API documentation\\n - Creating user guides, tutorials, or changelogs\\n - Explaining architecture or design decisions\\n\\n DO NOT use for:\\n - Modifying source logic (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Code review (use review agent)\\n\\n Output: Written documentation. Concise, accurate, and well-structured.\\n Cost: Low (read + write docs only)\\n Isolation: Can run in parallel with explore and review tasks\\ntools: read, write, edit, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a documentation subagent running inside hoocode. You write and update documentation. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and write documentation files (README, comments, guides). Do not modify source logic.\\n- Produce concise, accurate, and well-structured documentation.\\n\\nMethod:\\n1. Read the relevant source files to understand what needs documenting.\\n2. Write or update the requested documentation.\\n3. Verify that the documentation is consistent with the code.\\n\\nGuidance:\\n- Focus on clarity and accuracy. Avoid unnecessary verbosity.\\n- Match the project's existing documentation style.\\n- Your final message must contain ONLY the documentation or a summary of what was written.\\n- Do not narrate intermediate steps or include tool logs.\\n\",\n\tedit: \"---\\nname: edit\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing new code or creating new files\\n - Refactoring existing code across one or more files\\n - Fixing bugs or applying targeted corrections\\n - Migrating patterns or renaming symbols\\n\\n DO NOT use for:\\n - Read-only exploration\\n - Running tests (use test agent)\\n - Code review (use review agent)\\n\\n Output: Changed files with path:line descriptions. No narration.\\n Cost: Medium (read + write)\\n Isolation: Should not run concurrently with other edit tasks on the same files\\ntools: read, edit, write, grep, find, ls, bash\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are an edit subagent running inside hoocode. You implement one focused code change. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, edit, and write files, and run commands needed to make the change.\\n- Stay strictly within the requested task. Do not refactor unrelated code.\\n\\nMethod:\\n1. Read the relevant files before changing them.\\n2. Match the existing style: indentation, naming, import order.\\n3. Make the smallest change that fully satisfies the task.\\n4. Verify your edits by re-reading the changed regions.\\n\\nGuidance:\\n- Break down multi-file tasks. Handle one logical unit at a time.\\n- Your final answer must contain ONLY your answer — it is the only thing the caller receives.\\n- Summarize what you changed and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running tests or linting\\n - Reviewing code quality\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls, bash\\nmodel: haiku\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files. Use bash only for read-only inspection (e.g. git log, wc, tree).\\n- Use read, grep, find, and ls (and read-only shell commands) to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No specialized agent (explore, edit, review, test, doc) clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer a specialized agent when the task is clearly read-only (explore),\\n a focused code change (edit), a review (review), running tests (test), or\\n documentation (doc).\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with edit tasks on the same files\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\treview:\n\t\t\"---\\nname: review\\ndescription: |\\n Use this subagent ONLY when:\\n - Reviewing code for correctness, clarity, or risk\\n - Auditing for security vulnerabilities\\n - Checking compliance with project conventions\\n - Evaluating performance or architecture concerns\\n\\n DO NOT use for:\\n - Making code changes (use edit agent)\\n - Running tests (use test agent)\\n - Read-only exploration (use explore agent)\\n\\n Output: Verdict + findings ordered by severity with path:line and suggestions.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with explore and doc tasks\\ntools: read, grep, find, ls\\nmodel: haiku\\n---\\nYou are a review subagent running inside hoocode. You review code and report issues. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- READ ONLY. Do not modify files.\\n- Review the code or change named in the task for correctness, clarity, and risk.\\n\\nMethod:\\n1. Read the relevant code (and any diff or context provided).\\n2. Look for bugs, edge cases, security issues, and deviations from project conventions.\\n3. Prioritize correctness over style nits.\\n\\nGuidance:\\n- Start with an overall verdict (approve / approve with minor suggestions / needs changes).\\n- List findings ordered by severity, each with path:line and a concrete suggestion.\\n- If nothing is wrong, say so explicitly.\\n- Do not narrate your reading process or include tool logs.\\n- Your final message must contain ONLY your answer.\\n\",\n\ttest: \"---\\nname: test\\ndescription: |\\n Use this subagent ONLY when:\\n - Running test suites or individual tests\\n - Validating functionality after changes\\n - Checking test coverage or generating coverage reports\\n - Diagnosing test failures\\n\\n DO NOT use for:\\n - Modifying source code (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Security audits (use review agent)\\n\\n Output: Pass/fail counts, failing test paths, and root causes.\\n Cost: Medium (read + run)\\n Isolation: Can run in parallel with explore tasks; should not run during active edits\\ntools: read, bash, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a test subagent running inside hoocode. You run tests and report results. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and run commands (test runners, build, lint). Do not modify source files.\\n- Run the tests the task names; if unspecified, find and run the most relevant suite.\\n\\nMethod:\\n1. Locate the test command from package.json, config, or the task instructions.\\n2. Run it. Capture pass/fail counts and the first meaningful failures.\\n3. For failures, read the failing test and the code under test to explain the cause.\\n\\nGuidance:\\n- Report: (1) command(s) run, (2) overall result (pass/fail with counts), (3) for each failure: path:line, error message, and likely cause.\\n- Keep failure descriptions concise; do not dump full logs.\\n- If tests pass, confirm that the relevant area is covered.\\n- Your final message must contain ONLY your answer.\\n\",\n};\n"]}
|
|
1
|
+
{"version":3,"file":"init-templates.generated.js","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAAA,iEAA+D;AAC/D,sDAAsD;AACtD,wCAAwC;AAExC,MAAM,CAAC,MAAM,uBAAuB,GACnC,ocAAoc,CAAC;AAEtc,MAAM,CAAC,MAAM,cAAc,GAA2B;IACrD,GAAG,EAAE,ogBAAkgB;IACvgB,KAAK,EAAE,unBAAmnB;IAC1nB,KAAK,EAAE,6pBAAipB;IACxpB,IAAI,EAAE,isBAAqrB;CAC3rB,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAA2B,EAAE,CAAC;AAE5D,MAAM,CAAC,MAAM,sBAAsB,GAA2B;IAC7D,GAAG,EAAE,g8CAAg8C;IACr8C,IAAI,EAAE,wmDAAsmD;IAC5mD,OAAO,EACN,u9CAAu9C;IACx9C,iBAAiB,EAChB,4yDAA4yD;IAC7yD,MAAM,EACL,i8CAAi8C;IACl8C,IAAI,EAAE,4hDAA4hD;CACliD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution.\"\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\tdoc: \"---\\nname: doc\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing or updating README files\\n - Adding inline code comments or API documentation\\n - Creating user guides, tutorials, or changelogs\\n - Explaining architecture or design decisions\\n\\n DO NOT use for:\\n - Modifying source logic (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Code review (use review agent)\\n\\n Output: Written documentation. Concise, accurate, and well-structured.\\n Cost: Low (read + write docs only)\\n Isolation: Can run in parallel with explore and review tasks\\ntools: read, write, edit, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a documentation subagent running inside hoocode. You write and update documentation. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and write documentation files (README, comments, guides). Do not modify source logic.\\n- Produce concise, accurate, and well-structured documentation.\\n\\nMethod:\\n1. Read the relevant source files to understand what needs documenting.\\n2. Write or update the requested documentation.\\n3. Verify that the documentation is consistent with the code.\\n\\nGuidance:\\n- Focus on clarity and accuracy. Avoid unnecessary verbosity.\\n- Match the project's existing documentation style.\\n- Your final message must contain ONLY the documentation or a summary of what was written.\\n- Do not narrate intermediate steps or include tool logs.\\n\",\n\tedit: \"---\\nname: edit\\ndescription: |\\n Use this subagent ONLY when:\\n - Writing new code or creating new files\\n - Refactoring existing code across one or more files\\n - Fixing bugs or applying targeted corrections\\n - Migrating patterns or renaming symbols\\n\\n DO NOT use for:\\n - Read-only exploration\\n - Running tests (use test agent)\\n - Code review (use review agent)\\n\\n Output: Changed files with path:line descriptions. No narration.\\n Cost: Medium (read + write)\\n Isolation: Should not run concurrently with other edit tasks on the same files\\ntools: read, edit, write, grep, find, ls, bash\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are an edit subagent running inside hoocode. You implement one focused code change. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, edit, and write files, and run commands needed to make the change.\\n- Stay strictly within the requested task. Do not refactor unrelated code.\\n\\nMethod:\\n1. Read the relevant files before changing them.\\n2. Match the existing style: indentation, naming, import order.\\n3. Make the smallest change that fully satisfies the task.\\n4. Verify your edits by re-reading the changed regions.\\n\\nGuidance:\\n- Break down multi-file tasks. Handle one logical unit at a time.\\n- Your final answer must contain ONLY your answer — it is the only thing the caller receives.\\n- Summarize what you changed and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running tests or linting\\n - Reviewing code quality\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls, bash\\nmodel: haiku\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files. Use bash only for read-only inspection (e.g. git log, wc, tree).\\n- Use read, grep, find, and ls (and read-only shell commands) to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No specialized agent (explore, edit, review, test, doc) clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer a specialized agent when the task is clearly read-only (explore),\\n a focused code change (edit), a review (review), running tests (test), or\\n documentation (doc).\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with edit tasks on the same files\\ntools: read, bash, edit, write, grep, find, ls\\nmodel: sonnet\\nmaxTurns: 25\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\treview:\n\t\t\"---\\nname: review\\ndescription: |\\n Use this subagent ONLY when:\\n - Reviewing code for correctness, clarity, or risk\\n - Auditing for security vulnerabilities\\n - Checking compliance with project conventions\\n - Evaluating performance or architecture concerns\\n\\n DO NOT use for:\\n - Making code changes (use edit agent)\\n - Running tests (use test agent)\\n - Read-only exploration (use explore agent)\\n\\n Output: Verdict + findings ordered by severity with path:line and suggestions.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with explore and doc tasks\\ntools: read, grep, find, ls\\nmodel: haiku\\n---\\nYou are a review subagent running inside hoocode. You review code and report issues. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- READ ONLY. Do not modify files.\\n- Review the code or change named in the task for correctness, clarity, and risk.\\n\\nMethod:\\n1. Read the relevant code (and any diff or context provided).\\n2. Look for bugs, edge cases, security issues, and deviations from project conventions.\\n3. Prioritize correctness over style nits.\\n\\nGuidance:\\n- Start with an overall verdict (approve / approve with minor suggestions / needs changes).\\n- List findings ordered by severity, each with path:line and a concrete suggestion.\\n- If nothing is wrong, say so explicitly.\\n- Do not narrate your reading process or include tool logs.\\n- Your final message must contain ONLY your answer.\\n\",\n\ttest: \"---\\nname: test\\ndescription: |\\n Use this subagent ONLY when:\\n - Running test suites or individual tests\\n - Validating functionality after changes\\n - Checking test coverage or generating coverage reports\\n - Diagnosing test failures\\n\\n DO NOT use for:\\n - Modifying source code (use edit agent)\\n - Read-only exploration (use explore agent)\\n - Security audits (use review agent)\\n\\n Output: Pass/fail counts, failing test paths, and root causes.\\n Cost: Medium (read + run)\\n Isolation: Can run in parallel with explore tasks; should not run during active edits\\ntools: read, bash, grep, find, ls\\nmodel: sonnet\\n---\\nYou are a test subagent running inside hoocode. You run tests and report results. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read files and run commands (test runners, build, lint). Do not modify source files.\\n- Run the tests the task names; if unspecified, find and run the most relevant suite.\\n\\nMethod:\\n1. Locate the test command from package.json, config, or the task instructions.\\n2. Run it. Capture pass/fail counts and the first meaningful failures.\\n3. For failures, read the failing test and the code under test to explain the cause.\\n\\nGuidance:\\n- Report: (1) command(s) run, (2) overall result (pass/fail with counts), (3) for each failure: path:line, error message, and likely cause.\\n- Keep failure descriptions concise; do not dump full logs.\\n- If tests pass, confirm that the relevant area is covered.\\n- Your final message must contain ONLY your answer.\\n\",\n};\n"]}
|