@kolisachint/hoocode-agent 0.4.66 → 0.4.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/core/agent-frontmatter.d.ts +8 -0
  3. package/dist/core/agent-frontmatter.d.ts.map +1 -1
  4. package/dist/core/agent-frontmatter.js +8 -0
  5. package/dist/core/agent-frontmatter.js.map +1 -1
  6. package/dist/core/agent-registry.d.ts +7 -0
  7. package/dist/core/agent-registry.d.ts.map +1 -1
  8. package/dist/core/agent-registry.js +26 -0
  9. package/dist/core/agent-registry.js.map +1 -1
  10. package/dist/core/mode-prompts.d.ts +16 -0
  11. package/dist/core/mode-prompts.d.ts.map +1 -0
  12. package/dist/core/mode-prompts.js +39 -0
  13. package/dist/core/mode-prompts.js.map +1 -0
  14. package/dist/core/system-prompt.d.ts +1 -1
  15. package/dist/core/system-prompt.d.ts.map +1 -1
  16. package/dist/core/system-prompt.js +3 -2
  17. package/dist/core/system-prompt.js.map +1 -1
  18. package/dist/core/tools/index.d.ts +2 -0
  19. package/dist/core/tools/index.d.ts.map +1 -1
  20. package/dist/core/tools/index.js +3 -0
  21. package/dist/core/tools/index.js.map +1 -1
  22. package/dist/core/tools/subagent.d.ts +1 -1
  23. package/dist/core/tools/subagent.d.ts.map +1 -1
  24. package/dist/core/tools/subagent.js +3 -2
  25. package/dist/core/tools/subagent.js.map +1 -1
  26. package/dist/core/tools/todo.d.ts.map +1 -1
  27. package/dist/core/tools/todo.js +3 -2
  28. package/dist/core/tools/todo.js.map +1 -1
  29. package/dist/extensions/core/hoo-core.d.ts.map +1 -1
  30. package/dist/extensions/core/hoo-core.js +4 -28
  31. package/dist/extensions/core/hoo-core.js.map +1 -1
  32. package/dist/index.d.ts +7 -2
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +12 -1
  35. package/dist/index.js.map +1 -1
  36. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  37. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  38. package/examples/extensions/sandbox/package.json +1 -1
  39. package/examples/extensions/with-deps/package.json +1 -1
  40. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.67] - 2026-06-16
4
+
5
+ ### Added
6
+
7
+ - Public API surface for downstream apps that build their own agents on top of
8
+ hoocode's prompt/tool machinery:
9
+ - System prompt: `buildSystemPrompt`, plus the built-in mode prompts
10
+ `DEFAULT_MODE_PROMPTS` and `DEFAULT_MODE` (extracted to
11
+ `core/mode-prompts.ts`).
12
+ - Tool registry: `createTool`, `createToolDefinition`, `createAllTools`,
13
+ `createAllToolDefinitions`, `createCodingToolDefinitions`,
14
+ `createReadOnlyToolDefinitions`, `allToolNames`, and the `Tool` / `ToolDef`
15
+ / `ToolName` types.
16
+ - Opt-in tools: `createTaskToolDefinition`, `createTaskOutputToolDefinition`,
17
+ `createTodoWriteToolDefinition`, and `buildTaskMainPrompt`.
18
+ - Prompt templates: `loadPromptTemplates`, `expandPromptTemplate`,
19
+ `tryExpandPromptTemplate`, `parseCommandArgs`, `substituteArgs`, and their
20
+ option/result types.
21
+ - Skills/agents: `LoadSkillsOptions`, `AgentRegistry`, `loadAgentRegistry`,
22
+ `LoadAgentRegistryOptions`, `formatAgentsForPrompt`, `AgentDefinition`, and
23
+ `HOOCODE_TOOL_NAMES`.
24
+ - `loadAgentRegistry` now accepts an explicit `agentPaths` option (files or
25
+ directories, resolved against `cwd` with `~` expansion), mirroring
26
+ `skillPaths`/`promptPaths` on the skills and prompt-template loaders. These
27
+ override discovered agents by name and yield to CLI `--agent` paths.
28
+ - Canonical opt-in tool-name constants `TASK_TOOL_NAME` and
29
+ `TODO_WRITE_TOOL_NAME`, now the single source of truth at the tool
30
+ definition sites and in system-prompt gating, so downstream callers
31
+ reference a value instead of hardcoding case-sensitive strings.
32
+
3
33
  ## [0.4.66] - 2026-06-16
4
34
 
5
35
  ## [0.4.65] - 2026-06-16
@@ -26,6 +26,14 @@ export declare const MODEL_INHERIT = "inherit";
26
26
  * against this set; unknown tools are dropped with a diagnostic.
27
27
  */
28
28
  export declare const HOOCODE_TOOL_NAMES: readonly string[];
29
+ /**
30
+ * Canonical registered names of the two opt-in tools. These are case-sensitive
31
+ * identifiers the system prompt and tool gating match exactly, so downstream
32
+ * callers should reference these constants instead of hardcoding the strings
33
+ * (a mis-cased `"task"` silently disables the agents/skills prompt sections).
34
+ */
35
+ export declare const TASK_TOOL_NAME = "Task";
36
+ export declare const TODO_WRITE_TOOL_NAME = "TodoWrite";
29
37
  /**
30
38
  * D7 — Claude Code compatibility shim.
31
39
  *
@@ -1 +1 @@
1
- {"version":3,"file":"agent-frontmatter.d.ts","sourceRoot":"","sources":["../../src/core/agent-frontmatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D,gFAAgF;AAChF,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,GAAG,aAAa,GAAG,gBAAgB,CAAC;AAE5F,wFAAwF;AACxF,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,MAAM,EAA4D,CAAC;AAE7G;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAShE,CAAC;AAEF,6DAA6D;AAC7D,MAAM,WAAW,gBAAgB;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC1B,qFAAqF;IACrF,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC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ACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAK5E;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,GACxE;IAAE,KAAK,EAAE,eAAe,GAAG,IAAI,CAAC;IAAC,WAAW,EAAE,kBAAkB,EAAE,CAAA;CAAE,CA6ItE","sourcesContent":["/**\n * Agent frontmatter: schema, validation, and Claude Code compatibility shim.\n *\n * Agent definitions are Markdown files with YAML frontmatter, mirroring the\n * Claude Code subagent format so `.claude/agents/*.md` files import natively:\n *\n * ---\n * name: explore\n * description: When and why to use this agent (drives auto-delegation).\n * tools: Read, Grep, Glob, Bash # optional allowlist; omit = inherit all\n * model: sonnet # optional; sonnet|opus|haiku|inherit|pattern\n * ---\n * <system prompt body>\n *\n * The body becomes the subagent system prompt. Validation is non-fatal: we emit\n * diagnostics (warnings) and still load the agent when possible, matching the\n * behavior of skills.ts.\n */\n\nimport { basename } from \"path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Max name length, aligned with skills. */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length, aligned with skills. */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\n/** Where an agent definition came from. Used for precedence and diagnostics. */\nexport type AgentSource = \"builtin\" | \"user\" | \"project\" | \"claude-user\" | \"claude-project\";\n\n/** Sentinel meaning \"use the parent session's model\" (Claude Code `model: inherit`). */\nexport const MODEL_INHERIT = \"inherit\";\n\n/**\n * The seven built-in hoocode tools. An agent's `tools` allowlist is normalized\n * against this set; unknown tools are dropped with a diagnostic.\n */\nexport const HOOCODE_TOOL_NAMES: readonly string[] = [\"bash\", \"edit\", \"find\", \"grep\", \"ls\", \"read\", \"write\"];\n\n/**\n * D7 — Claude Code compatibility shim.\n *\n * Maps Claude Code tool names (case-insensitive) to their hoocode equivalents.\n * Claude tools without a hoocode counterpart (MultiEdit, Task, WebFetch,\n * WebSearch, TodoWrite, NotebookEdit, MCP tools, ...) are intentionally absent\n * and get dropped during normalization.\n */\nexport const CLAUDE_TOOL_ALIASES: Readonly<Record<string, string>> = {\n\tread: \"read\",\n\twrite: \"write\",\n\tedit: \"edit\",\n\tbash: \"bash\",\n\tgrep: \"grep\",\n\tglob: \"find\",\n\tfind: \"find\",\n\tls: \"ls\",\n};\n\n/** Raw frontmatter shape before validation/normalization. */\nexport interface AgentFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t/** Claude Code uses a comma-separated string; a YAML list is also accepted. */\n\ttools?: string | string[];\n\t/** Tools to subtract from the agent's set (allow + deny), Claude Code compatible. */\n\tdisallowedTools?: string | string[];\n\t/** sonnet | opus | haiku | inherit | a model id/pattern. */\n\tmodel?: string;\n\t/** hoocode extension (not part of the Claude Code format): turn cap. */\n\tmaxTurns?: number;\n\t/** Claude Code extension: run this agent detached (non-blocking) so the parent polls for its result. */\n\tbackground?: boolean;\n\t/**\n\t * hoocode extension: opt a agent into delegating via the Task tool (subject to the\n\t * tree-wide nesting cap). `true` = any subagent type; a comma-separated string or\n\t * YAML list = only those types. Opt-in per agent so the deliberate \"Task is not a\n\t * normal tool\" boundary stays intact for everyone else.\n\t */\n\tdelegate?: boolean | string | string[];\n\t/**\n\t * When true, this agent inherits the parent's full conversation (a fork) instead\n\t * of starting from a fresh context, reusing the parent's prompt cache.\n\t */\n\tfork?: boolean;\n\t[key: string]: unknown;\n}\n\n/** A validated, normalized agent definition. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Resolved hoocode tool allowlist. `undefined` means \"inherit all parent\n\t * tools\" (Claude Code behavior when `tools` is omitted).\n\t */\n\ttools?: string[];\n\t/** Resolved denylist subtracted from the agent's tool set. */\n\tdisallowedTools?: string[];\n\t/**\n\t * Model alias/pattern, the `inherit` sentinel, or `undefined` for the\n\t * subagent default.\n\t */\n\tmodel?: string;\n\t/** System prompt body (frontmatter stripped). */\n\tprompt: string;\n\t/** Origin of this definition. */\n\tsource: AgentSource;\n\t/** Absolute path of the source file, when loaded from disk. */\n\tfilePath?: string;\n\t/** hoocode extension: optional per-agent turn cap. */\n\tmaxTurns?: number;\n\t/** When true, dispatch is non-blocking: the parent receives a handle and polls for the result. */\n\tbackground?: boolean;\n\t/** When true, this agent may delegate via the Task tool, subject to the nesting cap. */\n\tdelegate?: boolean;\n\t/** Restricts delegation to these subagent types (undefined = any when `delegate` is true). */\n\tdelegateTo?: string[];\n\t/** When true, the agent inherits the parent's full conversation (a fork). */\n\tfork?: boolean;\n}\n\nconst KNOWN_MODEL_ALIASES = new Set([\"sonnet\", \"opus\", \"haiku\", \"inherit\"]);\n\n/** Validate an agent name. Returns warning messages (empty when valid). */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\tif (!name) {\n\t\terrors.push(\"name is required\");\n\t\treturn errors;\n\t}\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(\"name must not start or end with a hyphen\");\n\t}\n\tif (name.includes(\"--\")) {\n\t\terrors.push(\"name must not contain consecutive hyphens\");\n\t}\n\treturn errors;\n}\n\n/** Validate a description. Returns warning messages (empty when valid). */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction validateModel(value: string): string[] {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return [];\n\tif (KNOWN_MODEL_ALIASES.has(trimmed)) return [];\n\tif (/^claude-/.test(trimmed)) return [];\n\treturn [\n\t\t`model \"${trimmed}\" is not a recognized Claude alias (sonnet | opus | haiku | inherit) or full model ID (claude-*); the agent may not load correctly`,\n\t];\n}\n\n/** Split a `tools` frontmatter value (string or list) into raw token names. */\nfunction splitToolsValue(value: string | string[]): string[] {\n\tconst tokens = Array.isArray(value) ? value : value.split(\",\");\n\treturn tokens.map((t) => t.trim()).filter((t) => t.length > 0);\n}\n\n/**\n * Normalize a raw `tools` allowlist into hoocode tool names via the Claude Code\n * alias map. Returns the deduped, resolved list plus diagnostics for any tokens\n * that could not be mapped.\n *\n * Emits a warning when `value` is a YAML list rather than a comma-separated\n * string — the Claude Code standard format is `tools: read, bash` (string).\n */\nexport function normalizeTools(\n\tvalue: string | string[],\n\tfilePath?: string,\n): { tools: string[]; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tif (Array.isArray(value)) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"warning\",\n\t\t\tmessage:\n\t\t\t\t'tools: use a comma-separated string (\"tools: read, bash\") instead of a YAML list for Claude Code compatibility',\n\t\t\tpath: filePath,\n\t\t});\n\t}\n\tconst resolved: string[] = [];\n\tfor (const raw of splitToolsValue(value)) {\n\t\tconst mapped = CLAUDE_TOOL_ALIASES[raw.toLowerCase()];\n\t\tif (!mapped) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `tool \"${raw}\" has no hoocode equivalent and was dropped from the allowlist`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!resolved.includes(mapped)) {\n\t\t\tresolved.push(mapped);\n\t\t}\n\t}\n\treturn { tools: resolved, diagnostics };\n}\n\n/**\n * Normalize a `model` frontmatter value. `inherit` is preserved as a sentinel;\n * any other non-empty string is passed through to the model resolver as-is\n * (so Claude aliases like `sonnet`/`opus`/`haiku` resolve via pattern match).\n */\nexport function normalizeModel(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return undefined;\n\treturn trimmed;\n}\n\n/**\n * Parse and validate a single agent definition from raw Markdown content.\n *\n * `fallbackName` is used when frontmatter omits `name` (e.g. the filename, or\n * the embedded-template key). Returns `agent: null` only when the definition\n * is unusable (missing description). Other problems surface as diagnostics.\n */\nexport function parseAgentDefinition(\n\trawContent: string,\n\toptions: { source: AgentSource; filePath?: string; fallbackName?: string },\n): { agent: AgentDefinition | null; diagnostics: ResourceDiagnostic[] } {\n\tconst { source, filePath } = options;\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tlet frontmatter: AgentFrontmatter;\n\tlet body: string;\n\ttry {\n\t\tconst parsed = parseFrontmatter<AgentFrontmatter>(rawContent);\n\t\tfrontmatter = parsed.frontmatter;\n\t\tbody = parsed.body;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse agent frontmatter\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tconst fallbackName = options.fallbackName ?? (filePath ? basename(filePath, \".md\") : \"\");\n\tconst name = (frontmatter.name ?? fallbackName).trim();\n\n\tfor (const error of validateName(name)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Description is mandatory: it drives delegation. Without it the agent is unusable.\n\tif (!description) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\t// A usable name is required as the registry key.\n\tif (!name || !/^[a-z0-9-]+$/.test(name)) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tlet tools: string[] | undefined;\n\tif (frontmatter.tools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.tools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\ttools = normalized.tools;\n\t}\n\n\tlet disallowedTools: string[] | undefined;\n\tif (frontmatter.disallowedTools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.disallowedTools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\tdisallowedTools = normalized.tools.length > 0 ? normalized.tools : undefined;\n\t}\n\n\tconst model = normalizeModel(frontmatter.model);\n\tif (model !== undefined) {\n\t\tfor (const error of validateModel(model)) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\t}\n\n\tconst maxTurns =\n\t\ttypeof frontmatter.maxTurns === \"number\" && Number.isInteger(frontmatter.maxTurns) && frontmatter.maxTurns > 0\n\t\t\t? frontmatter.maxTurns\n\t\t\t: undefined;\n\n\tlet background: boolean | undefined;\n\tif (frontmatter.background !== undefined) {\n\t\tif (typeof frontmatter.background !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `background must be a boolean (true or false), got \"${frontmatter.background}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tbackground = frontmatter.background === true ? true : undefined;\n\t\t}\n\t}\n\n\t// `delegate` accepts a boolean (delegate to any agent) or a comma-separated\n\t// string / YAML list of agent type names (delegate only to those).\n\tlet fork: boolean | undefined;\n\tif (frontmatter.fork !== undefined) {\n\t\tif (typeof frontmatter.fork !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `fork must be a boolean (true or false), got \"${frontmatter.fork}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tfork = frontmatter.fork === true ? true : undefined;\n\t\t}\n\t}\n\n\tlet delegate: boolean | undefined;\n\tlet delegateTo: string[] | undefined;\n\tif (frontmatter.delegate !== undefined) {\n\t\tconst value = frontmatter.delegate;\n\t\tif (value === true) {\n\t\t\tdelegate = true;\n\t\t} else if (value === false) {\n\t\t\tdelegate = undefined;\n\t\t} else if (typeof value === \"string\" || Array.isArray(value)) {\n\t\t\tconst names = (Array.isArray(value) ? value.join(\",\") : value)\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim().toLowerCase())\n\t\t\t\t.filter((s) => /^[a-z0-9-]+$/.test(s));\n\t\t\tif (names.length > 0) {\n\t\t\t\tdelegate = true;\n\t\t\t\tdelegateTo = [...new Set(names)];\n\t\t\t} else {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `delegate list \"${value}\" contained no valid agent names — field ignored`,\n\t\t\t\t\tpath: filePath,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `delegate must be a boolean or a list of agent names, got \"${value}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tmodel,\n\t\t\tprompt: body.trim(),\n\t\t\tsource,\n\t\t\tfilePath,\n\t\t\tmaxTurns,\n\t\t\tbackground,\n\t\t\tdelegate,\n\t\t\tdelegateTo,\n\t\t\tfork,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n"]}
1
+ {"version":3,"file":"agent-frontmatter.d.ts","sourceRoot":"","sources":["../../src/core/agent-frontmatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQ3D,gFAAgF;AAChF,MAAM,MAAM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CAAC,EAAE,MAAM,CAAC;IACf,iDAAiD;IACjD,MAAM,EAAE,MAAM,CAAC;IACf,iCAAiC;IACjC,MAAM,EAAE,WAAW,CAAC;IACpB,+DAA+D;IAC/D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sDAAsD;IACtD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kGAAkG;IAClG,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,wFAAwF;IACxF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,8FAA8F;IAC9F,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,6EAA6E;IAC7E,IAAI,CAAC,EAAE,OAAO,CAAC;CACf;AAqDD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC7B,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,EACxB,QAAQ,CAAC,EAAE,MAAM,GACf;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,WAAW,EAAE,kBAAkB,EAAE,CAAA;CAAE,CA0BxD;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAK5E;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,GACxE;IAAE,KAAK,EAAE,eAAe,GAAG,IAAI,CAAC;IAAC,WAAW,EAAE,kBAAkB,EAAE,CAAA;CAAE,CA6ItE","sourcesContent":["/**\n * Agent frontmatter: schema, validation, and Claude Code compatibility shim.\n *\n * Agent definitions are Markdown files with YAML frontmatter, mirroring the\n * Claude Code subagent format so `.claude/agents/*.md` files import natively:\n *\n * ---\n * name: explore\n * description: When and why to use this agent (drives auto-delegation).\n * tools: Read, Grep, Glob, Bash # optional allowlist; omit = inherit all\n * model: sonnet # optional; sonnet|opus|haiku|inherit|pattern\n * ---\n * <system prompt body>\n *\n * The body becomes the subagent system prompt. Validation is non-fatal: we emit\n * diagnostics (warnings) and still load the agent when possible, matching the\n * behavior of skills.ts.\n */\n\nimport { basename } from \"path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Max name length, aligned with skills. */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length, aligned with skills. */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\n/** Where an agent definition came from. Used for precedence and diagnostics. */\nexport type AgentSource = \"builtin\" | \"user\" | \"project\" | \"claude-user\" | \"claude-project\";\n\n/** Sentinel meaning \"use the parent session's model\" (Claude Code `model: inherit`). */\nexport const MODEL_INHERIT = \"inherit\";\n\n/**\n * The seven built-in hoocode tools. An agent's `tools` allowlist is normalized\n * against this set; unknown tools are dropped with a diagnostic.\n */\nexport const HOOCODE_TOOL_NAMES: readonly string[] = [\"bash\", \"edit\", \"find\", \"grep\", \"ls\", \"read\", \"write\"];\n\n/**\n * Canonical registered names of the two opt-in tools. These are case-sensitive\n * identifiers the system prompt and tool gating match exactly, so downstream\n * callers should reference these constants instead of hardcoding the strings\n * (a mis-cased `\"task\"` silently disables the agents/skills prompt sections).\n */\nexport const TASK_TOOL_NAME = \"Task\";\nexport const TODO_WRITE_TOOL_NAME = \"TodoWrite\";\n\n/**\n * D7 — Claude Code compatibility shim.\n *\n * Maps Claude Code tool names (case-insensitive) to their hoocode equivalents.\n * Claude tools without a hoocode counterpart (MultiEdit, Task, WebFetch,\n * WebSearch, TodoWrite, NotebookEdit, MCP tools, ...) are intentionally absent\n * and get dropped during normalization.\n */\nexport const CLAUDE_TOOL_ALIASES: Readonly<Record<string, string>> = {\n\tread: \"read\",\n\twrite: \"write\",\n\tedit: \"edit\",\n\tbash: \"bash\",\n\tgrep: \"grep\",\n\tglob: \"find\",\n\tfind: \"find\",\n\tls: \"ls\",\n};\n\n/** Raw frontmatter shape before validation/normalization. */\nexport interface AgentFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t/** Claude Code uses a comma-separated string; a YAML list is also accepted. */\n\ttools?: string | string[];\n\t/** Tools to subtract from the agent's set (allow + deny), Claude Code compatible. */\n\tdisallowedTools?: string | string[];\n\t/** sonnet | opus | haiku | inherit | a model id/pattern. */\n\tmodel?: string;\n\t/** hoocode extension (not part of the Claude Code format): turn cap. */\n\tmaxTurns?: number;\n\t/** Claude Code extension: run this agent detached (non-blocking) so the parent polls for its result. */\n\tbackground?: boolean;\n\t/**\n\t * hoocode extension: opt a agent into delegating via the Task tool (subject to the\n\t * tree-wide nesting cap). `true` = any subagent type; a comma-separated string or\n\t * YAML list = only those types. Opt-in per agent so the deliberate \"Task is not a\n\t * normal tool\" boundary stays intact for everyone else.\n\t */\n\tdelegate?: boolean | string | string[];\n\t/**\n\t * When true, this agent inherits the parent's full conversation (a fork) instead\n\t * of starting from a fresh context, reusing the parent's prompt cache.\n\t */\n\tfork?: boolean;\n\t[key: string]: unknown;\n}\n\n/** A validated, normalized agent definition. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Resolved hoocode tool allowlist. `undefined` means \"inherit all parent\n\t * tools\" (Claude Code behavior when `tools` is omitted).\n\t */\n\ttools?: string[];\n\t/** Resolved denylist subtracted from the agent's tool set. */\n\tdisallowedTools?: string[];\n\t/**\n\t * Model alias/pattern, the `inherit` sentinel, or `undefined` for the\n\t * subagent default.\n\t */\n\tmodel?: string;\n\t/** System prompt body (frontmatter stripped). */\n\tprompt: string;\n\t/** Origin of this definition. */\n\tsource: AgentSource;\n\t/** Absolute path of the source file, when loaded from disk. */\n\tfilePath?: string;\n\t/** hoocode extension: optional per-agent turn cap. */\n\tmaxTurns?: number;\n\t/** When true, dispatch is non-blocking: the parent receives a handle and polls for the result. */\n\tbackground?: boolean;\n\t/** When true, this agent may delegate via the Task tool, subject to the nesting cap. */\n\tdelegate?: boolean;\n\t/** Restricts delegation to these subagent types (undefined = any when `delegate` is true). */\n\tdelegateTo?: string[];\n\t/** When true, the agent inherits the parent's full conversation (a fork). */\n\tfork?: boolean;\n}\n\nconst KNOWN_MODEL_ALIASES = new Set([\"sonnet\", \"opus\", \"haiku\", \"inherit\"]);\n\n/** Validate an agent name. Returns warning messages (empty when valid). */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\tif (!name) {\n\t\terrors.push(\"name is required\");\n\t\treturn errors;\n\t}\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(\"name must not start or end with a hyphen\");\n\t}\n\tif (name.includes(\"--\")) {\n\t\terrors.push(\"name must not contain consecutive hyphens\");\n\t}\n\treturn errors;\n}\n\n/** Validate a description. Returns warning messages (empty when valid). */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction validateModel(value: string): string[] {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return [];\n\tif (KNOWN_MODEL_ALIASES.has(trimmed)) return [];\n\tif (/^claude-/.test(trimmed)) return [];\n\treturn [\n\t\t`model \"${trimmed}\" is not a recognized Claude alias (sonnet | opus | haiku | inherit) or full model ID (claude-*); the agent may not load correctly`,\n\t];\n}\n\n/** Split a `tools` frontmatter value (string or list) into raw token names. */\nfunction splitToolsValue(value: string | string[]): string[] {\n\tconst tokens = Array.isArray(value) ? value : value.split(\",\");\n\treturn tokens.map((t) => t.trim()).filter((t) => t.length > 0);\n}\n\n/**\n * Normalize a raw `tools` allowlist into hoocode tool names via the Claude Code\n * alias map. Returns the deduped, resolved list plus diagnostics for any tokens\n * that could not be mapped.\n *\n * Emits a warning when `value` is a YAML list rather than a comma-separated\n * string — the Claude Code standard format is `tools: read, bash` (string).\n */\nexport function normalizeTools(\n\tvalue: string | string[],\n\tfilePath?: string,\n): { tools: string[]; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tif (Array.isArray(value)) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"warning\",\n\t\t\tmessage:\n\t\t\t\t'tools: use a comma-separated string (\"tools: read, bash\") instead of a YAML list for Claude Code compatibility',\n\t\t\tpath: filePath,\n\t\t});\n\t}\n\tconst resolved: string[] = [];\n\tfor (const raw of splitToolsValue(value)) {\n\t\tconst mapped = CLAUDE_TOOL_ALIASES[raw.toLowerCase()];\n\t\tif (!mapped) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `tool \"${raw}\" has no hoocode equivalent and was dropped from the allowlist`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!resolved.includes(mapped)) {\n\t\t\tresolved.push(mapped);\n\t\t}\n\t}\n\treturn { tools: resolved, diagnostics };\n}\n\n/**\n * Normalize a `model` frontmatter value. `inherit` is preserved as a sentinel;\n * any other non-empty string is passed through to the model resolver as-is\n * (so Claude aliases like `sonnet`/`opus`/`haiku` resolve via pattern match).\n */\nexport function normalizeModel(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return undefined;\n\treturn trimmed;\n}\n\n/**\n * Parse and validate a single agent definition from raw Markdown content.\n *\n * `fallbackName` is used when frontmatter omits `name` (e.g. the filename, or\n * the embedded-template key). Returns `agent: null` only when the definition\n * is unusable (missing description). Other problems surface as diagnostics.\n */\nexport function parseAgentDefinition(\n\trawContent: string,\n\toptions: { source: AgentSource; filePath?: string; fallbackName?: string },\n): { agent: AgentDefinition | null; diagnostics: ResourceDiagnostic[] } {\n\tconst { source, filePath } = options;\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tlet frontmatter: AgentFrontmatter;\n\tlet body: string;\n\ttry {\n\t\tconst parsed = parseFrontmatter<AgentFrontmatter>(rawContent);\n\t\tfrontmatter = parsed.frontmatter;\n\t\tbody = parsed.body;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse agent frontmatter\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tconst fallbackName = options.fallbackName ?? (filePath ? basename(filePath, \".md\") : \"\");\n\tconst name = (frontmatter.name ?? fallbackName).trim();\n\n\tfor (const error of validateName(name)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Description is mandatory: it drives delegation. Without it the agent is unusable.\n\tif (!description) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\t// A usable name is required as the registry key.\n\tif (!name || !/^[a-z0-9-]+$/.test(name)) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tlet tools: string[] | undefined;\n\tif (frontmatter.tools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.tools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\ttools = normalized.tools;\n\t}\n\n\tlet disallowedTools: string[] | undefined;\n\tif (frontmatter.disallowedTools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.disallowedTools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\tdisallowedTools = normalized.tools.length > 0 ? normalized.tools : undefined;\n\t}\n\n\tconst model = normalizeModel(frontmatter.model);\n\tif (model !== undefined) {\n\t\tfor (const error of validateModel(model)) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\t}\n\n\tconst maxTurns =\n\t\ttypeof frontmatter.maxTurns === \"number\" && Number.isInteger(frontmatter.maxTurns) && frontmatter.maxTurns > 0\n\t\t\t? frontmatter.maxTurns\n\t\t\t: undefined;\n\n\tlet background: boolean | undefined;\n\tif (frontmatter.background !== undefined) {\n\t\tif (typeof frontmatter.background !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `background must be a boolean (true or false), got \"${frontmatter.background}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tbackground = frontmatter.background === true ? true : undefined;\n\t\t}\n\t}\n\n\t// `delegate` accepts a boolean (delegate to any agent) or a comma-separated\n\t// string / YAML list of agent type names (delegate only to those).\n\tlet fork: boolean | undefined;\n\tif (frontmatter.fork !== undefined) {\n\t\tif (typeof frontmatter.fork !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `fork must be a boolean (true or false), got \"${frontmatter.fork}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tfork = frontmatter.fork === true ? true : undefined;\n\t\t}\n\t}\n\n\tlet delegate: boolean | undefined;\n\tlet delegateTo: string[] | undefined;\n\tif (frontmatter.delegate !== undefined) {\n\t\tconst value = frontmatter.delegate;\n\t\tif (value === true) {\n\t\t\tdelegate = true;\n\t\t} else if (value === false) {\n\t\t\tdelegate = undefined;\n\t\t} else if (typeof value === \"string\" || Array.isArray(value)) {\n\t\t\tconst names = (Array.isArray(value) ? value.join(\",\") : value)\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim().toLowerCase())\n\t\t\t\t.filter((s) => /^[a-z0-9-]+$/.test(s));\n\t\t\tif (names.length > 0) {\n\t\t\t\tdelegate = true;\n\t\t\t\tdelegateTo = [...new Set(names)];\n\t\t\t} else {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `delegate list \"${value}\" contained no valid agent names — field ignored`,\n\t\t\t\t\tpath: filePath,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `delegate must be a boolean or a list of agent names, got \"${value}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tmodel,\n\t\t\tprompt: body.trim(),\n\t\t\tsource,\n\t\t\tfilePath,\n\t\t\tmaxTurns,\n\t\t\tbackground,\n\t\t\tdelegate,\n\t\t\tdelegateTo,\n\t\t\tfork,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n"]}
@@ -29,6 +29,14 @@ export const MODEL_INHERIT = "inherit";
29
29
  * against this set; unknown tools are dropped with a diagnostic.
30
30
  */
31
31
  export const HOOCODE_TOOL_NAMES = ["bash", "edit", "find", "grep", "ls", "read", "write"];
32
+ /**
33
+ * Canonical registered names of the two opt-in tools. These are case-sensitive
34
+ * identifiers the system prompt and tool gating match exactly, so downstream
35
+ * callers should reference these constants instead of hardcoding the strings
36
+ * (a mis-cased `"task"` silently disables the agents/skills prompt sections).
37
+ */
38
+ export const TASK_TOOL_NAME = "Task";
39
+ export const TODO_WRITE_TOOL_NAME = "TodoWrite";
32
40
  /**
33
41
  * D7 — Claude Code compatibility shim.
34
42
  *
@@ -1 +1 @@
1
- {"version":3,"file":"agent-frontmatter.js","sourceRoot":"","sources":["../../src/core/agent-frontmatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,QAAQ,EAA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AAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACtB,QAAQ,GAAG,IAAI,CAAC;gBAChB,UAAU,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;YAClC,CAAC;iBAAM,CAAC;gBACP,WAAW,CAAC,IAAI,CAAC;oBAChB,IAAI,EAAE,SAAS;oBACf,OAAO,EAAE,kBAAkB,KAAK,oDAAkD;oBAClF,IAAI,EAAE,QAAQ;iBACd,CAAC,CAAC;YACJ,CAAC;QACF,CAAC;aAAM,CAAC;YACP,WAAW,CAAC,IAAI,CAAC;gBAChB,IAAI,EAAE,SAAS;gBACf,OAAO,EAAE,6DAA6D,KAAK,qBAAmB;gBAC9F,IAAI,EAAE,QAAQ;aACd,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IAED,OAAO;QACN,KAAK,EAAE;YACN,IAAI;YACJ,WAAW;YACX,KAAK;YACL,eAAe;YACf,KAAK;YACL,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE;YACnB,MAAM;YACN,QAAQ;YACR,QAAQ;YACR,UAAU;YACV,QAAQ;YACR,UAAU;YACV,IAAI;SACJ;QACD,WAAW;KACX,CAAC;AAAA,CACF","sourcesContent":["/**\n * Agent frontmatter: schema, validation, and Claude Code compatibility shim.\n *\n * Agent definitions are Markdown files with YAML frontmatter, mirroring the\n * Claude Code subagent format so `.claude/agents/*.md` files import natively:\n *\n * ---\n * name: explore\n * description: When and why to use this agent (drives auto-delegation).\n * tools: Read, Grep, Glob, Bash # optional allowlist; omit = inherit all\n * model: sonnet # optional; sonnet|opus|haiku|inherit|pattern\n * ---\n * <system prompt body>\n *\n * The body becomes the subagent system prompt. Validation is non-fatal: we emit\n * diagnostics (warnings) and still load the agent when possible, matching the\n * behavior of skills.ts.\n */\n\nimport { basename } from \"path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Max name length, aligned with skills. */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length, aligned with skills. */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\n/** Where an agent definition came from. Used for precedence and diagnostics. */\nexport type AgentSource = \"builtin\" | \"user\" | \"project\" | \"claude-user\" | \"claude-project\";\n\n/** Sentinel meaning \"use the parent session's model\" (Claude Code `model: inherit`). */\nexport const MODEL_INHERIT = \"inherit\";\n\n/**\n * The seven built-in hoocode tools. An agent's `tools` allowlist is normalized\n * against this set; unknown tools are dropped with a diagnostic.\n */\nexport const HOOCODE_TOOL_NAMES: readonly string[] = [\"bash\", \"edit\", \"find\", \"grep\", \"ls\", \"read\", \"write\"];\n\n/**\n * D7 — Claude Code compatibility shim.\n *\n * Maps Claude Code tool names (case-insensitive) to their hoocode equivalents.\n * Claude tools without a hoocode counterpart (MultiEdit, Task, WebFetch,\n * WebSearch, TodoWrite, NotebookEdit, MCP tools, ...) are intentionally absent\n * and get dropped during normalization.\n */\nexport const CLAUDE_TOOL_ALIASES: Readonly<Record<string, string>> = {\n\tread: \"read\",\n\twrite: \"write\",\n\tedit: \"edit\",\n\tbash: \"bash\",\n\tgrep: \"grep\",\n\tglob: \"find\",\n\tfind: \"find\",\n\tls: \"ls\",\n};\n\n/** Raw frontmatter shape before validation/normalization. */\nexport interface AgentFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t/** Claude Code uses a comma-separated string; a YAML list is also accepted. */\n\ttools?: string | string[];\n\t/** Tools to subtract from the agent's set (allow + deny), Claude Code compatible. */\n\tdisallowedTools?: string | string[];\n\t/** sonnet | opus | haiku | inherit | a model id/pattern. */\n\tmodel?: string;\n\t/** hoocode extension (not part of the Claude Code format): turn cap. */\n\tmaxTurns?: number;\n\t/** Claude Code extension: run this agent detached (non-blocking) so the parent polls for its result. */\n\tbackground?: boolean;\n\t/**\n\t * hoocode extension: opt a agent into delegating via the Task tool (subject to the\n\t * tree-wide nesting cap). `true` = any subagent type; a comma-separated string or\n\t * YAML list = only those types. Opt-in per agent so the deliberate \"Task is not a\n\t * normal tool\" boundary stays intact for everyone else.\n\t */\n\tdelegate?: boolean | string | string[];\n\t/**\n\t * When true, this agent inherits the parent's full conversation (a fork) instead\n\t * of starting from a fresh context, reusing the parent's prompt cache.\n\t */\n\tfork?: boolean;\n\t[key: string]: unknown;\n}\n\n/** A validated, normalized agent definition. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Resolved hoocode tool allowlist. `undefined` means \"inherit all parent\n\t * tools\" (Claude Code behavior when `tools` is omitted).\n\t */\n\ttools?: string[];\n\t/** Resolved denylist subtracted from the agent's tool set. */\n\tdisallowedTools?: string[];\n\t/**\n\t * Model alias/pattern, the `inherit` sentinel, or `undefined` for the\n\t * subagent default.\n\t */\n\tmodel?: string;\n\t/** System prompt body (frontmatter stripped). */\n\tprompt: string;\n\t/** Origin of this definition. */\n\tsource: AgentSource;\n\t/** Absolute path of the source file, when loaded from disk. */\n\tfilePath?: string;\n\t/** hoocode extension: optional per-agent turn cap. */\n\tmaxTurns?: number;\n\t/** When true, dispatch is non-blocking: the parent receives a handle and polls for the result. */\n\tbackground?: boolean;\n\t/** When true, this agent may delegate via the Task tool, subject to the nesting cap. */\n\tdelegate?: boolean;\n\t/** Restricts delegation to these subagent types (undefined = any when `delegate` is true). */\n\tdelegateTo?: string[];\n\t/** When true, the agent inherits the parent's full conversation (a fork). */\n\tfork?: boolean;\n}\n\nconst KNOWN_MODEL_ALIASES = new Set([\"sonnet\", \"opus\", \"haiku\", \"inherit\"]);\n\n/** Validate an agent name. Returns warning messages (empty when valid). */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\tif (!name) {\n\t\terrors.push(\"name is required\");\n\t\treturn errors;\n\t}\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(\"name must not start or end with a hyphen\");\n\t}\n\tif (name.includes(\"--\")) {\n\t\terrors.push(\"name must not contain consecutive hyphens\");\n\t}\n\treturn errors;\n}\n\n/** Validate a description. Returns warning messages (empty when valid). */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction validateModel(value: string): string[] {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return [];\n\tif (KNOWN_MODEL_ALIASES.has(trimmed)) return [];\n\tif (/^claude-/.test(trimmed)) return [];\n\treturn [\n\t\t`model \"${trimmed}\" is not a recognized Claude alias (sonnet | opus | haiku | inherit) or full model ID (claude-*); the agent may not load correctly`,\n\t];\n}\n\n/** Split a `tools` frontmatter value (string or list) into raw token names. */\nfunction splitToolsValue(value: string | string[]): string[] {\n\tconst tokens = Array.isArray(value) ? value : value.split(\",\");\n\treturn tokens.map((t) => t.trim()).filter((t) => t.length > 0);\n}\n\n/**\n * Normalize a raw `tools` allowlist into hoocode tool names via the Claude Code\n * alias map. Returns the deduped, resolved list plus diagnostics for any tokens\n * that could not be mapped.\n *\n * Emits a warning when `value` is a YAML list rather than a comma-separated\n * string — the Claude Code standard format is `tools: read, bash` (string).\n */\nexport function normalizeTools(\n\tvalue: string | string[],\n\tfilePath?: string,\n): { tools: string[]; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tif (Array.isArray(value)) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"warning\",\n\t\t\tmessage:\n\t\t\t\t'tools: use a comma-separated string (\"tools: read, bash\") instead of a YAML list for Claude Code compatibility',\n\t\t\tpath: filePath,\n\t\t});\n\t}\n\tconst resolved: string[] = [];\n\tfor (const raw of splitToolsValue(value)) {\n\t\tconst mapped = CLAUDE_TOOL_ALIASES[raw.toLowerCase()];\n\t\tif (!mapped) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `tool \"${raw}\" has no hoocode equivalent and was dropped from the allowlist`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!resolved.includes(mapped)) {\n\t\t\tresolved.push(mapped);\n\t\t}\n\t}\n\treturn { tools: resolved, diagnostics };\n}\n\n/**\n * Normalize a `model` frontmatter value. `inherit` is preserved as a sentinel;\n * any other non-empty string is passed through to the model resolver as-is\n * (so Claude aliases like `sonnet`/`opus`/`haiku` resolve via pattern match).\n */\nexport function normalizeModel(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return undefined;\n\treturn trimmed;\n}\n\n/**\n * Parse and validate a single agent definition from raw Markdown content.\n *\n * `fallbackName` is used when frontmatter omits `name` (e.g. the filename, or\n * the embedded-template key). Returns `agent: null` only when the definition\n * is unusable (missing description). Other problems surface as diagnostics.\n */\nexport function parseAgentDefinition(\n\trawContent: string,\n\toptions: { source: AgentSource; filePath?: string; fallbackName?: string },\n): { agent: AgentDefinition | null; diagnostics: ResourceDiagnostic[] } {\n\tconst { source, filePath } = options;\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tlet frontmatter: AgentFrontmatter;\n\tlet body: string;\n\ttry {\n\t\tconst parsed = parseFrontmatter<AgentFrontmatter>(rawContent);\n\t\tfrontmatter = parsed.frontmatter;\n\t\tbody = parsed.body;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse agent frontmatter\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tconst fallbackName = options.fallbackName ?? (filePath ? basename(filePath, \".md\") : \"\");\n\tconst name = (frontmatter.name ?? fallbackName).trim();\n\n\tfor (const error of validateName(name)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Description is mandatory: it drives delegation. Without it the agent is unusable.\n\tif (!description) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\t// A usable name is required as the registry key.\n\tif (!name || !/^[a-z0-9-]+$/.test(name)) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tlet tools: string[] | undefined;\n\tif (frontmatter.tools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.tools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\ttools = normalized.tools;\n\t}\n\n\tlet disallowedTools: string[] | undefined;\n\tif (frontmatter.disallowedTools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.disallowedTools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\tdisallowedTools = normalized.tools.length > 0 ? normalized.tools : undefined;\n\t}\n\n\tconst model = normalizeModel(frontmatter.model);\n\tif (model !== undefined) {\n\t\tfor (const error of validateModel(model)) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\t}\n\n\tconst maxTurns =\n\t\ttypeof frontmatter.maxTurns === \"number\" && Number.isInteger(frontmatter.maxTurns) && frontmatter.maxTurns > 0\n\t\t\t? frontmatter.maxTurns\n\t\t\t: undefined;\n\n\tlet background: boolean | undefined;\n\tif (frontmatter.background !== undefined) {\n\t\tif (typeof frontmatter.background !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `background must be a boolean (true or false), got \"${frontmatter.background}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tbackground = frontmatter.background === true ? true : undefined;\n\t\t}\n\t}\n\n\t// `delegate` accepts a boolean (delegate to any agent) or a comma-separated\n\t// string / YAML list of agent type names (delegate only to those).\n\tlet fork: boolean | undefined;\n\tif (frontmatter.fork !== undefined) {\n\t\tif (typeof frontmatter.fork !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `fork must be a boolean (true or false), got \"${frontmatter.fork}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tfork = frontmatter.fork === true ? true : undefined;\n\t\t}\n\t}\n\n\tlet delegate: boolean | undefined;\n\tlet delegateTo: string[] | undefined;\n\tif (frontmatter.delegate !== undefined) {\n\t\tconst value = frontmatter.delegate;\n\t\tif (value === true) {\n\t\t\tdelegate = true;\n\t\t} else if (value === false) {\n\t\t\tdelegate = undefined;\n\t\t} else if (typeof value === \"string\" || Array.isArray(value)) {\n\t\t\tconst names = (Array.isArray(value) ? value.join(\",\") : value)\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim().toLowerCase())\n\t\t\t\t.filter((s) => /^[a-z0-9-]+$/.test(s));\n\t\t\tif (names.length > 0) {\n\t\t\t\tdelegate = true;\n\t\t\t\tdelegateTo = [...new Set(names)];\n\t\t\t} else {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `delegate list \"${value}\" contained no valid agent names — field ignored`,\n\t\t\t\t\tpath: filePath,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `delegate must be a boolean or a list of agent names, got \"${value}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tmodel,\n\t\t\tprompt: body.trim(),\n\t\t\tsource,\n\t\t\tfilePath,\n\t\t\tmaxTurns,\n\t\t\tbackground,\n\t\t\tdelegate,\n\t\t\tdelegateTo,\n\t\t\tfork,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n"]}
1
+ {"version":3,"file":"agent-frontmatter.js","sourceRoot":"","sources":["../../src/core/agent-frontmatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAG3D,4CAA4C;AAC5C,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,mDAAmD;AACnD,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAKpC,wFAAwF;AACxF,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AAEvC;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAE7G;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC;AACrC,MAAM,CAAC,MAAM,oBAAoB,GAAG,WAAW,CAAC;AAEhD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAqC;IACpE,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,OAAO;IACd,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,MAAM;IACZ,EAAE,EAAE,IAAI;CACR,CAAC;AAiEF,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC;AAE5E,2EAA2E;AAC3E,SAAS,YAAY,CAA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n * Agent definitions are Markdown files with YAML frontmatter, mirroring the\n * Claude Code subagent format so `.claude/agents/*.md` files import natively:\n *\n * ---\n * name: explore\n * description: When and why to use this agent (drives auto-delegation).\n * tools: Read, Grep, Glob, Bash # optional allowlist; omit = inherit all\n * model: sonnet # optional; sonnet|opus|haiku|inherit|pattern\n * ---\n * <system prompt body>\n *\n * The body becomes the subagent system prompt. Validation is non-fatal: we emit\n * diagnostics (warnings) and still load the agent when possible, matching the\n * behavior of skills.ts.\n */\n\nimport { basename } from \"path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Max name length, aligned with skills. */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length, aligned with skills. */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\n/** Where an agent definition came from. Used for precedence and diagnostics. */\nexport type AgentSource = \"builtin\" | \"user\" | \"project\" | \"claude-user\" | \"claude-project\";\n\n/** Sentinel meaning \"use the parent session's model\" (Claude Code `model: inherit`). */\nexport const MODEL_INHERIT = \"inherit\";\n\n/**\n * The seven built-in hoocode tools. An agent's `tools` allowlist is normalized\n * against this set; unknown tools are dropped with a diagnostic.\n */\nexport const HOOCODE_TOOL_NAMES: readonly string[] = [\"bash\", \"edit\", \"find\", \"grep\", \"ls\", \"read\", \"write\"];\n\n/**\n * Canonical registered names of the two opt-in tools. These are case-sensitive\n * identifiers the system prompt and tool gating match exactly, so downstream\n * callers should reference these constants instead of hardcoding the strings\n * (a mis-cased `\"task\"` silently disables the agents/skills prompt sections).\n */\nexport const TASK_TOOL_NAME = \"Task\";\nexport const TODO_WRITE_TOOL_NAME = \"TodoWrite\";\n\n/**\n * D7 — Claude Code compatibility shim.\n *\n * Maps Claude Code tool names (case-insensitive) to their hoocode equivalents.\n * Claude tools without a hoocode counterpart (MultiEdit, Task, WebFetch,\n * WebSearch, TodoWrite, NotebookEdit, MCP tools, ...) are intentionally absent\n * and get dropped during normalization.\n */\nexport const CLAUDE_TOOL_ALIASES: Readonly<Record<string, string>> = {\n\tread: \"read\",\n\twrite: \"write\",\n\tedit: \"edit\",\n\tbash: \"bash\",\n\tgrep: \"grep\",\n\tglob: \"find\",\n\tfind: \"find\",\n\tls: \"ls\",\n};\n\n/** Raw frontmatter shape before validation/normalization. */\nexport interface AgentFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t/** Claude Code uses a comma-separated string; a YAML list is also accepted. */\n\ttools?: string | string[];\n\t/** Tools to subtract from the agent's set (allow + deny), Claude Code compatible. */\n\tdisallowedTools?: string | string[];\n\t/** sonnet | opus | haiku | inherit | a model id/pattern. */\n\tmodel?: string;\n\t/** hoocode extension (not part of the Claude Code format): turn cap. */\n\tmaxTurns?: number;\n\t/** Claude Code extension: run this agent detached (non-blocking) so the parent polls for its result. */\n\tbackground?: boolean;\n\t/**\n\t * hoocode extension: opt a agent into delegating via the Task tool (subject to the\n\t * tree-wide nesting cap). `true` = any subagent type; a comma-separated string or\n\t * YAML list = only those types. Opt-in per agent so the deliberate \"Task is not a\n\t * normal tool\" boundary stays intact for everyone else.\n\t */\n\tdelegate?: boolean | string | string[];\n\t/**\n\t * When true, this agent inherits the parent's full conversation (a fork) instead\n\t * of starting from a fresh context, reusing the parent's prompt cache.\n\t */\n\tfork?: boolean;\n\t[key: string]: unknown;\n}\n\n/** A validated, normalized agent definition. */\nexport interface AgentDefinition {\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Resolved hoocode tool allowlist. `undefined` means \"inherit all parent\n\t * tools\" (Claude Code behavior when `tools` is omitted).\n\t */\n\ttools?: string[];\n\t/** Resolved denylist subtracted from the agent's tool set. */\n\tdisallowedTools?: string[];\n\t/**\n\t * Model alias/pattern, the `inherit` sentinel, or `undefined` for the\n\t * subagent default.\n\t */\n\tmodel?: string;\n\t/** System prompt body (frontmatter stripped). */\n\tprompt: string;\n\t/** Origin of this definition. */\n\tsource: AgentSource;\n\t/** Absolute path of the source file, when loaded from disk. */\n\tfilePath?: string;\n\t/** hoocode extension: optional per-agent turn cap. */\n\tmaxTurns?: number;\n\t/** When true, dispatch is non-blocking: the parent receives a handle and polls for the result. */\n\tbackground?: boolean;\n\t/** When true, this agent may delegate via the Task tool, subject to the nesting cap. */\n\tdelegate?: boolean;\n\t/** Restricts delegation to these subagent types (undefined = any when `delegate` is true). */\n\tdelegateTo?: string[];\n\t/** When true, the agent inherits the parent's full conversation (a fork). */\n\tfork?: boolean;\n}\n\nconst KNOWN_MODEL_ALIASES = new Set([\"sonnet\", \"opus\", \"haiku\", \"inherit\"]);\n\n/** Validate an agent name. Returns warning messages (empty when valid). */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\tif (!name) {\n\t\terrors.push(\"name is required\");\n\t\treturn errors;\n\t}\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(\"name must not start or end with a hyphen\");\n\t}\n\tif (name.includes(\"--\")) {\n\t\terrors.push(\"name must not contain consecutive hyphens\");\n\t}\n\treturn errors;\n}\n\n/** Validate a description. Returns warning messages (empty when valid). */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction validateModel(value: string): string[] {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return [];\n\tif (KNOWN_MODEL_ALIASES.has(trimmed)) return [];\n\tif (/^claude-/.test(trimmed)) return [];\n\treturn [\n\t\t`model \"${trimmed}\" is not a recognized Claude alias (sonnet | opus | haiku | inherit) or full model ID (claude-*); the agent may not load correctly`,\n\t];\n}\n\n/** Split a `tools` frontmatter value (string or list) into raw token names. */\nfunction splitToolsValue(value: string | string[]): string[] {\n\tconst tokens = Array.isArray(value) ? value : value.split(\",\");\n\treturn tokens.map((t) => t.trim()).filter((t) => t.length > 0);\n}\n\n/**\n * Normalize a raw `tools` allowlist into hoocode tool names via the Claude Code\n * alias map. Returns the deduped, resolved list plus diagnostics for any tokens\n * that could not be mapped.\n *\n * Emits a warning when `value` is a YAML list rather than a comma-separated\n * string — the Claude Code standard format is `tools: read, bash` (string).\n */\nexport function normalizeTools(\n\tvalue: string | string[],\n\tfilePath?: string,\n): { tools: string[]; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tif (Array.isArray(value)) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"warning\",\n\t\t\tmessage:\n\t\t\t\t'tools: use a comma-separated string (\"tools: read, bash\") instead of a YAML list for Claude Code compatibility',\n\t\t\tpath: filePath,\n\t\t});\n\t}\n\tconst resolved: string[] = [];\n\tfor (const raw of splitToolsValue(value)) {\n\t\tconst mapped = CLAUDE_TOOL_ALIASES[raw.toLowerCase()];\n\t\tif (!mapped) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `tool \"${raw}\" has no hoocode equivalent and was dropped from the allowlist`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!resolved.includes(mapped)) {\n\t\t\tresolved.push(mapped);\n\t\t}\n\t}\n\treturn { tools: resolved, diagnostics };\n}\n\n/**\n * Normalize a `model` frontmatter value. `inherit` is preserved as a sentinel;\n * any other non-empty string is passed through to the model resolver as-is\n * (so Claude aliases like `sonnet`/`opus`/`haiku` resolve via pattern match).\n */\nexport function normalizeModel(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return undefined;\n\treturn trimmed;\n}\n\n/**\n * Parse and validate a single agent definition from raw Markdown content.\n *\n * `fallbackName` is used when frontmatter omits `name` (e.g. the filename, or\n * the embedded-template key). Returns `agent: null` only when the definition\n * is unusable (missing description). Other problems surface as diagnostics.\n */\nexport function parseAgentDefinition(\n\trawContent: string,\n\toptions: { source: AgentSource; filePath?: string; fallbackName?: string },\n): { agent: AgentDefinition | null; diagnostics: ResourceDiagnostic[] } {\n\tconst { source, filePath } = options;\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tlet frontmatter: AgentFrontmatter;\n\tlet body: string;\n\ttry {\n\t\tconst parsed = parseFrontmatter<AgentFrontmatter>(rawContent);\n\t\tfrontmatter = parsed.frontmatter;\n\t\tbody = parsed.body;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse agent frontmatter\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tconst fallbackName = options.fallbackName ?? (filePath ? basename(filePath, \".md\") : \"\");\n\tconst name = (frontmatter.name ?? fallbackName).trim();\n\n\tfor (const error of validateName(name)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Description is mandatory: it drives delegation. Without it the agent is unusable.\n\tif (!description) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\t// A usable name is required as the registry key.\n\tif (!name || !/^[a-z0-9-]+$/.test(name)) {\n\t\treturn { agent: null, diagnostics };\n\t}\n\n\tlet tools: string[] | undefined;\n\tif (frontmatter.tools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.tools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\ttools = normalized.tools;\n\t}\n\n\tlet disallowedTools: string[] | undefined;\n\tif (frontmatter.disallowedTools !== undefined) {\n\t\tconst normalized = normalizeTools(frontmatter.disallowedTools, filePath);\n\t\tdiagnostics.push(...normalized.diagnostics);\n\t\tdisallowedTools = normalized.tools.length > 0 ? normalized.tools : undefined;\n\t}\n\n\tconst model = normalizeModel(frontmatter.model);\n\tif (model !== undefined) {\n\t\tfor (const error of validateModel(model)) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\t}\n\n\tconst maxTurns =\n\t\ttypeof frontmatter.maxTurns === \"number\" && Number.isInteger(frontmatter.maxTurns) && frontmatter.maxTurns > 0\n\t\t\t? frontmatter.maxTurns\n\t\t\t: undefined;\n\n\tlet background: boolean | undefined;\n\tif (frontmatter.background !== undefined) {\n\t\tif (typeof frontmatter.background !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `background must be a boolean (true or false), got \"${frontmatter.background}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tbackground = frontmatter.background === true ? true : undefined;\n\t\t}\n\t}\n\n\t// `delegate` accepts a boolean (delegate to any agent) or a comma-separated\n\t// string / YAML list of agent type names (delegate only to those).\n\tlet fork: boolean | undefined;\n\tif (frontmatter.fork !== undefined) {\n\t\tif (typeof frontmatter.fork !== \"boolean\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `fork must be a boolean (true or false), got \"${frontmatter.fork}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t} else {\n\t\t\tfork = frontmatter.fork === true ? true : undefined;\n\t\t}\n\t}\n\n\tlet delegate: boolean | undefined;\n\tlet delegateTo: string[] | undefined;\n\tif (frontmatter.delegate !== undefined) {\n\t\tconst value = frontmatter.delegate;\n\t\tif (value === true) {\n\t\t\tdelegate = true;\n\t\t} else if (value === false) {\n\t\t\tdelegate = undefined;\n\t\t} else if (typeof value === \"string\" || Array.isArray(value)) {\n\t\t\tconst names = (Array.isArray(value) ? value.join(\",\") : value)\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim().toLowerCase())\n\t\t\t\t.filter((s) => /^[a-z0-9-]+$/.test(s));\n\t\t\tif (names.length > 0) {\n\t\t\t\tdelegate = true;\n\t\t\t\tdelegateTo = [...new Set(names)];\n\t\t\t} else {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `delegate list \"${value}\" contained no valid agent names — field ignored`,\n\t\t\t\t\tpath: filePath,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `delegate must be a boolean or a list of agent names, got \"${value}\" — field ignored`,\n\t\t\t\tpath: filePath,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tmodel,\n\t\t\tprompt: body.trim(),\n\t\t\tsource,\n\t\t\tfilePath,\n\t\t\tmaxTurns,\n\t\t\tbackground,\n\t\t\tdelegate,\n\t\t\tdelegateTo,\n\t\t\tfork,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n"]}
@@ -47,6 +47,13 @@ export interface LoadAgentRegistryOptions {
47
47
  includeBuiltins?: boolean;
48
48
  /** Discover `.claude/agents/` directories for native Claude Code import (D7). Defaults to true. */
49
49
  includeClaude?: boolean;
50
+ /**
51
+ * Explicit agent definition paths (files or directories), resolved relative
52
+ * to `cwd` (with `~` expansion). Mirrors `skillPaths`/`promptPaths` on the
53
+ * skills and prompt-template loaders. These override all discovered sources
54
+ * by name but yield to CLI-injected `--agent` paths.
55
+ */
56
+ agentPaths?: string[];
50
57
  }
51
58
  /** Build an AgentRegistry from all configured locations, applying precedence. */
52
59
  export declare function loadAgentRegistry(options: LoadAgentRegistryOptions): AgentRegistry;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-registry.d.ts","sourceRoot":"","sources":["../../src/core/agent-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAOH,OAAO,EAAE,KAAK,eAAe,EAA0C,MAAM,wBAAwB,CAAC;AAEtG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,mDAAmD;AACnD,qBAAa,aAAa;IACzB,OAAO,CAAC,MAAM,CAAsC;IACpD,OAAO,CAAC,WAAW,CAA4B;IAE/C;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,eAAe,GAAG,IAAI,CAkBnC;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAE7C;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEzB;IAED,IAAI,IAAI,eAAe,EAAE,CAExB;IAED,2DAA2D;IAC3D,cAAc,IAAI,kBAAkB,EAAE,CAErC;IAED,uEAAuE;IACvE,cAAc,CAAC,WAAW,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAEtD;CACD;AA8ED,MAAM,WAAW,wBAAwB;IACxC,kDAAkD;IAClD,GAAG,EAAE,MAAM,CAAC;IACZ,0FAA0F;IAC1F,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,mGAAmG;IACnG,aAAa,CAAC,EAAE,OAAO,CAAC;CACxB;AAED,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,aAAa,CA4ClF;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,CA0BvE","sourcesContent":["/**\n * Agent registry: data-driven loading of subagent definitions.\n *\n * Replaces the hardcoded `SubagentMode` enum + `MODE_TOOLS` map with frontmatter\n * `.md` files (see agent-frontmatter.ts). Definitions are discovered from, in\n * increasing order of precedence:\n *\n * 1. builtin embedded templates (EMBEDDED_AGENT_PROMPTS)\n * 2. package-manifest paths from hoocode.agents in package.json\n * 3. claude-user ~/.claude/agents/*.md (D7 native import)\n * 4. user ~/.hoocode/agents/*.md\n * 5. ancestor-walk <git-root..cwd>/.agents/agents/*.md\n * 6. claude-project <cwd>/.claude/agents/*.md (D7 native import)\n * 7. project <cwd>/.hoocode/agents/*.md\n * 8. cli paths injected via --agent <path>\n *\n * Higher-precedence sources override lower ones by name. Overrides are recorded\n * as collision diagnostics. Loading never throws; problems surface as\n * diagnostics, matching skills.ts.\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.js\";\nimport { EMBEDDED_AGENT_PROMPTS } from \"../init-templates.generated.js\";\nimport { type AgentDefinition, type AgentSource, parseAgentDefinition } from \"./agent-frontmatter.js\";\nimport { getAgentCliPaths, getAgentManifestPaths } from \"./agent-manifest-paths.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Registry of agent definitions keyed by name. */\nexport class AgentRegistry {\n\tprivate agents = new Map<string, AgentDefinition>();\n\tprivate diagnostics: ResourceDiagnostic[] = [];\n\n\t/**\n\t * Add or override a definition. Later registrations win (used both by the\n\t * loader for precedence and as an escape hatch for programmatic agents).\n\t * Overriding an existing name records a collision diagnostic.\n\t */\n\tregister(def: AgentDefinition): void {\n\t\tconst existing = this.agents.get(def.name);\n\t\tif (existing) {\n\t\t\tthis.diagnostics.push({\n\t\t\t\ttype: \"collision\",\n\t\t\t\tmessage: `agent \"${def.name}\" from ${def.source} overrides ${existing.source}`,\n\t\t\t\tpath: def.filePath,\n\t\t\t\tcollision: {\n\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\tname: def.name,\n\t\t\t\t\twinnerPath: def.filePath ?? `<${def.source}>`,\n\t\t\t\t\tloserPath: existing.filePath ?? `<${existing.source}>`,\n\t\t\t\t\twinnerSource: def.source,\n\t\t\t\t\tloserSource: existing.source,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tthis.agents.set(def.name, def);\n\t}\n\n\tget(name: string): AgentDefinition | undefined {\n\t\treturn this.agents.get(name);\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.agents.has(name);\n\t}\n\n\tlist(): AgentDefinition[] {\n\t\treturn Array.from(this.agents.values());\n\t}\n\n\t/** Diagnostics accumulated during loading/registration. */\n\tgetDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.diagnostics;\n\t}\n\n\t/** Append externally-produced diagnostics (e.g. from a parse step). */\n\taddDiagnostics(diagnostics: ResourceDiagnostic[]): void {\n\t\tthis.diagnostics.push(...diagnostics);\n\t}\n}\n\n/** Load and register every built-in (embedded) agent definition. */\nfunction registerBuiltins(registry: AgentRegistry): void {\n\tfor (const [key, raw] of Object.entries(EMBEDDED_AGENT_PROMPTS)) {\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source: \"builtin\", fallbackName: key });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t}\n}\n\n/** Load flat `*.md` agent files from a directory. Non-`.md` entries and\n * subdirectories are skipped (so runtime dispatch dirs are ignored). */\nfunction registerDir(registry: AgentRegistry, dir: string, source: AgentSource): void {\n\tif (!existsSync(dir)) return;\n\tlet entries: string[];\n\ttry {\n\t\tentries = readdirSync(dir);\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const entry of entries) {\n\t\tif (entry.startsWith(\".\") || !entry.endsWith(\".md\")) continue;\n\t\tconst filePath = join(dir, entry);\n\t\ttry {\n\t\t\tif (!statSync(filePath).isFile()) continue;\n\t\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\t\tregistry.addDiagnostics(diagnostics);\n\t\t\tif (agent) registry.register(agent);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t\t}\n\t}\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Collect `.agents/agents/` dirs from cwd up to the git root (cwd-first order). */\nfunction collectAncestorAgentsDirs(startDir: string): string[] {\n\tconst dirs: string[] = [];\n\tconst resolvedStart = resolve(startDir);\n\tconst gitRoot = findGitRepoRoot(resolvedStart);\n\tlet dir = resolvedStart;\n\twhile (true) {\n\t\tdirs.push(join(dir, \".agents\", \"agents\"));\n\t\tif (gitRoot && dir === gitRoot) break;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\treturn dirs;\n}\n\n/** Register a single file as an agent. */\nfunction registerFile(registry: AgentRegistry, filePath: string, source: AgentSource): void {\n\tif (!existsSync(filePath)) return;\n\ttry {\n\t\tif (!statSync(filePath).isFile()) return;\n\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t}\n}\n\nexport interface LoadAgentRegistryOptions {\n\t/** Working directory for project-local agents. */\n\tcwd: string;\n\t/** User agent config directory (contains `agents/` subdir). Defaults to getAgentDir(). */\n\tagentDir?: string;\n\t/** Include embedded built-in agents. Defaults to true. */\n\tincludeBuiltins?: boolean;\n\t/** Discover `.claude/agents/` directories for native Claude Code import (D7). Defaults to true. */\n\tincludeClaude?: boolean;\n}\n\n/** Build an AgentRegistry from all configured locations, applying precedence. */\nexport function loadAgentRegistry(options: LoadAgentRegistryOptions): AgentRegistry {\n\tconst { cwd, includeBuiltins = true, includeClaude = true } = options;\n\tconst userAgentDir = options.agentDir ?? getAgentDir();\n\tconst registry = new AgentRegistry();\n\n\t// Lowest precedence first; later sources override earlier ones by name.\n\tif (includeBuiltins) {\n\t\tregisterBuiltins(registry);\n\t}\n\n\t// Package-manifest agents (declared via `hoocode.agents` in package.json).\n\tfor (const filePath of getAgentManifestPaths()) {\n\t\tregisterFile(registry, filePath, \"user\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, join(homedir(), \".claude\", \"agents\"), \"claude-user\");\n\t}\n\tregisterDir(registry, join(userAgentDir, \"agents\"), \"user\");\n\n\t// Ancestor-walk .agents/agents/ dirs (git-root first so cwd-level overrides ancestors).\n\tfor (const dir of collectAncestorAgentsDirs(cwd).reverse()) {\n\t\tregisterDir(registry, dir, \"project\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, resolve(cwd, \".claude\", \"agents\"), \"claude-project\");\n\t}\n\tregisterDir(registry, resolve(cwd, CONFIG_DIR_NAME, \"agents\"), \"project\");\n\n\t// CLI-injected paths have highest precedence (support both files and dirs).\n\tfor (const p of getAgentCliPaths()) {\n\t\tif (!existsSync(p)) {\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message: `Agent path does not exist: ${p}`, path: p }]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (statSync(p).isDirectory()) {\n\t\t\tregisterDir(registry, p, \"user\");\n\t\t} else {\n\t\t\tregisterFile(registry, p, \"user\");\n\t\t}\n\t}\n\n\treturn registry;\n}\n\n/**\n * Format a list of agent definitions as an XML block for inclusion in a system\n * prompt, mirroring the `<available_skills>` format used by formatSkillsForPrompt.\n * Only intended for display when the Task tool is active.\n */\nexport function formatAgentsForPrompt(agents: AgentDefinition[]): string {\n\tif (agents.length === 0) return \"\";\n\n\tconst lines = [\n\t\t\"\\n\\nThe following specialized agents are available for delegation via the Task tool.\",\n\t\t\"Choose the agent whose description best matches the task and pass it as `subagent_type`.\",\n\t\t\"\",\n\t\t\"<available_agents>\",\n\t];\n\n\tfor (const agent of agents) {\n\t\tlines.push(\" <agent>\");\n\t\tlines.push(` <name>${escapeXml(agent.name)}</name>`);\n\t\tlines.push(` <description>${escapeXml(agent.description)}</description>`);\n\t\tif (agent.tools && agent.tools.length > 0) {\n\t\t\tlines.push(` <tools>${escapeXml(agent.tools.join(\", \"))}</tools>`);\n\t\t}\n\t\tif (agent.model) {\n\t\t\tlines.push(` <model>${escapeXml(agent.model)}</model>`);\n\t\t}\n\t\tlines.push(\" </agent>\");\n\t}\n\n\tlines.push(\"</available_agents>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n"]}
1
+ {"version":3,"file":"agent-registry.d.ts","sourceRoot":"","sources":["../../src/core/agent-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAOH,OAAO,EAAE,KAAK,eAAe,EAA0C,MAAM,wBAAwB,CAAC;AAEtG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,mDAAmD;AACnD,qBAAa,aAAa;IACzB,OAAO,CAAC,MAAM,CAAsC;IACpD,OAAO,CAAC,WAAW,CAA4B;IAE/C;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,eAAe,GAAG,IAAI,CAkBnC;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAE7C;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEzB;IAED,IAAI,IAAI,eAAe,EAAE,CAExB;IAED,2DAA2D;IAC3D,cAAc,IAAI,kBAAkB,EAAE,CAErC;IAED,uEAAuE;IACvE,cAAc,CAAC,WAAW,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAEtD;CACD;AA8ED,MAAM,WAAW,wBAAwB;IACxC,kDAAkD;IAClD,GAAG,EAAE,MAAM,CAAC;IACZ,0FAA0F;IAC1F,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,mGAAmG;IACnG,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB;AAYD,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,aAAa,CA0DlF;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,CA0BvE","sourcesContent":["/**\n * Agent registry: data-driven loading of subagent definitions.\n *\n * Replaces the hardcoded `SubagentMode` enum + `MODE_TOOLS` map with frontmatter\n * `.md` files (see agent-frontmatter.ts). Definitions are discovered from, in\n * increasing order of precedence:\n *\n * 1. builtin embedded templates (EMBEDDED_AGENT_PROMPTS)\n * 2. package-manifest paths from hoocode.agents in package.json\n * 3. claude-user ~/.claude/agents/*.md (D7 native import)\n * 4. user ~/.hoocode/agents/*.md\n * 5. ancestor-walk <git-root..cwd>/.agents/agents/*.md\n * 6. claude-project <cwd>/.claude/agents/*.md (D7 native import)\n * 7. project <cwd>/.hoocode/agents/*.md\n * 8. cli paths injected via --agent <path>\n *\n * Higher-precedence sources override lower ones by name. Overrides are recorded\n * as collision diagnostics. Loading never throws; problems surface as\n * diagnostics, matching skills.ts.\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.js\";\nimport { EMBEDDED_AGENT_PROMPTS } from \"../init-templates.generated.js\";\nimport { type AgentDefinition, type AgentSource, parseAgentDefinition } from \"./agent-frontmatter.js\";\nimport { getAgentCliPaths, getAgentManifestPaths } from \"./agent-manifest-paths.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Registry of agent definitions keyed by name. */\nexport class AgentRegistry {\n\tprivate agents = new Map<string, AgentDefinition>();\n\tprivate diagnostics: ResourceDiagnostic[] = [];\n\n\t/**\n\t * Add or override a definition. Later registrations win (used both by the\n\t * loader for precedence and as an escape hatch for programmatic agents).\n\t * Overriding an existing name records a collision diagnostic.\n\t */\n\tregister(def: AgentDefinition): void {\n\t\tconst existing = this.agents.get(def.name);\n\t\tif (existing) {\n\t\t\tthis.diagnostics.push({\n\t\t\t\ttype: \"collision\",\n\t\t\t\tmessage: `agent \"${def.name}\" from ${def.source} overrides ${existing.source}`,\n\t\t\t\tpath: def.filePath,\n\t\t\t\tcollision: {\n\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\tname: def.name,\n\t\t\t\t\twinnerPath: def.filePath ?? `<${def.source}>`,\n\t\t\t\t\tloserPath: existing.filePath ?? `<${existing.source}>`,\n\t\t\t\t\twinnerSource: def.source,\n\t\t\t\t\tloserSource: existing.source,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tthis.agents.set(def.name, def);\n\t}\n\n\tget(name: string): AgentDefinition | undefined {\n\t\treturn this.agents.get(name);\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.agents.has(name);\n\t}\n\n\tlist(): AgentDefinition[] {\n\t\treturn Array.from(this.agents.values());\n\t}\n\n\t/** Diagnostics accumulated during loading/registration. */\n\tgetDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.diagnostics;\n\t}\n\n\t/** Append externally-produced diagnostics (e.g. from a parse step). */\n\taddDiagnostics(diagnostics: ResourceDiagnostic[]): void {\n\t\tthis.diagnostics.push(...diagnostics);\n\t}\n}\n\n/** Load and register every built-in (embedded) agent definition. */\nfunction registerBuiltins(registry: AgentRegistry): void {\n\tfor (const [key, raw] of Object.entries(EMBEDDED_AGENT_PROMPTS)) {\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source: \"builtin\", fallbackName: key });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t}\n}\n\n/** Load flat `*.md` agent files from a directory. Non-`.md` entries and\n * subdirectories are skipped (so runtime dispatch dirs are ignored). */\nfunction registerDir(registry: AgentRegistry, dir: string, source: AgentSource): void {\n\tif (!existsSync(dir)) return;\n\tlet entries: string[];\n\ttry {\n\t\tentries = readdirSync(dir);\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const entry of entries) {\n\t\tif (entry.startsWith(\".\") || !entry.endsWith(\".md\")) continue;\n\t\tconst filePath = join(dir, entry);\n\t\ttry {\n\t\t\tif (!statSync(filePath).isFile()) continue;\n\t\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\t\tregistry.addDiagnostics(diagnostics);\n\t\t\tif (agent) registry.register(agent);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t\t}\n\t}\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Collect `.agents/agents/` dirs from cwd up to the git root (cwd-first order). */\nfunction collectAncestorAgentsDirs(startDir: string): string[] {\n\tconst dirs: string[] = [];\n\tconst resolvedStart = resolve(startDir);\n\tconst gitRoot = findGitRepoRoot(resolvedStart);\n\tlet dir = resolvedStart;\n\twhile (true) {\n\t\tdirs.push(join(dir, \".agents\", \"agents\"));\n\t\tif (gitRoot && dir === gitRoot) break;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\treturn dirs;\n}\n\n/** Register a single file as an agent. */\nfunction registerFile(registry: AgentRegistry, filePath: string, source: AgentSource): void {\n\tif (!existsSync(filePath)) return;\n\ttry {\n\t\tif (!statSync(filePath).isFile()) return;\n\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t}\n}\n\nexport interface LoadAgentRegistryOptions {\n\t/** Working directory for project-local agents. */\n\tcwd: string;\n\t/** User agent config directory (contains `agents/` subdir). Defaults to getAgentDir(). */\n\tagentDir?: string;\n\t/** Include embedded built-in agents. Defaults to true. */\n\tincludeBuiltins?: boolean;\n\t/** Discover `.claude/agents/` directories for native Claude Code import (D7). Defaults to true. */\n\tincludeClaude?: boolean;\n\t/**\n\t * Explicit agent definition paths (files or directories), resolved relative\n\t * to `cwd` (with `~` expansion). Mirrors `skillPaths`/`promptPaths` on the\n\t * skills and prompt-template loaders. These override all discovered sources\n\t * by name but yield to CLI-injected `--agent` paths.\n\t */\n\tagentPaths?: string[];\n}\n\n/** Resolve an explicit path: expand a leading `~` and resolve against `cwd`. */\nfunction normalizeAgentPath(input: string, cwd: string): string {\n\tconst trimmed = input.trim();\n\tlet expanded = trimmed;\n\tif (trimmed === \"~\") expanded = homedir();\n\telse if (trimmed.startsWith(\"~/\")) expanded = join(homedir(), trimmed.slice(2));\n\telse if (trimmed.startsWith(\"~\")) expanded = join(homedir(), trimmed.slice(1));\n\treturn resolve(cwd, expanded);\n}\n\n/** Build an AgentRegistry from all configured locations, applying precedence. */\nexport function loadAgentRegistry(options: LoadAgentRegistryOptions): AgentRegistry {\n\tconst { cwd, includeBuiltins = true, includeClaude = true } = options;\n\tconst userAgentDir = options.agentDir ?? getAgentDir();\n\tconst registry = new AgentRegistry();\n\n\t// Lowest precedence first; later sources override earlier ones by name.\n\tif (includeBuiltins) {\n\t\tregisterBuiltins(registry);\n\t}\n\n\t// Package-manifest agents (declared via `hoocode.agents` in package.json).\n\tfor (const filePath of getAgentManifestPaths()) {\n\t\tregisterFile(registry, filePath, \"user\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, join(homedir(), \".claude\", \"agents\"), \"claude-user\");\n\t}\n\tregisterDir(registry, join(userAgentDir, \"agents\"), \"user\");\n\n\t// Ancestor-walk .agents/agents/ dirs (git-root first so cwd-level overrides ancestors).\n\tfor (const dir of collectAncestorAgentsDirs(cwd).reverse()) {\n\t\tregisterDir(registry, dir, \"project\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, resolve(cwd, \".claude\", \"agents\"), \"claude-project\");\n\t}\n\tregisterDir(registry, resolve(cwd, CONFIG_DIR_NAME, \"agents\"), \"project\");\n\n\t// Explicit caller-provided paths override discovered sources (files or dirs).\n\tfor (const rawPath of options.agentPaths ?? []) {\n\t\tconst p = normalizeAgentPath(rawPath, cwd);\n\t\tif (!existsSync(p)) {\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message: `Agent path does not exist: ${p}`, path: p }]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (statSync(p).isDirectory()) {\n\t\t\tregisterDir(registry, p, \"project\");\n\t\t} else {\n\t\t\tregisterFile(registry, p, \"project\");\n\t\t}\n\t}\n\n\t// CLI-injected paths have highest precedence (support both files and dirs).\n\tfor (const p of getAgentCliPaths()) {\n\t\tif (!existsSync(p)) {\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message: `Agent path does not exist: ${p}`, path: p }]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (statSync(p).isDirectory()) {\n\t\t\tregisterDir(registry, p, \"user\");\n\t\t} else {\n\t\t\tregisterFile(registry, p, \"user\");\n\t\t}\n\t}\n\n\treturn registry;\n}\n\n/**\n * Format a list of agent definitions as an XML block for inclusion in a system\n * prompt, mirroring the `<available_skills>` format used by formatSkillsForPrompt.\n * Only intended for display when the Task tool is active.\n */\nexport function formatAgentsForPrompt(agents: AgentDefinition[]): string {\n\tif (agents.length === 0) return \"\";\n\n\tconst lines = [\n\t\t\"\\n\\nThe following specialized agents are available for delegation via the Task tool.\",\n\t\t\"Choose the agent whose description best matches the task and pass it as `subagent_type`.\",\n\t\t\"\",\n\t\t\"<available_agents>\",\n\t];\n\n\tfor (const agent of agents) {\n\t\tlines.push(\" <agent>\");\n\t\tlines.push(` <name>${escapeXml(agent.name)}</name>`);\n\t\tlines.push(` <description>${escapeXml(agent.description)}</description>`);\n\t\tif (agent.tools && agent.tools.length > 0) {\n\t\t\tlines.push(` <tools>${escapeXml(agent.tools.join(\", \"))}</tools>`);\n\t\t}\n\t\tif (agent.model) {\n\t\t\tlines.push(` <model>${escapeXml(agent.model)}</model>`);\n\t\t}\n\t\tlines.push(\" </agent>\");\n\t}\n\n\tlines.push(\"</available_agents>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n"]}
@@ -157,6 +157,18 @@ function registerFile(registry, filePath, source) {
157
157
  registry.addDiagnostics([{ type: "warning", message, path: filePath }]);
158
158
  }
159
159
  }
160
+ /** Resolve an explicit path: expand a leading `~` and resolve against `cwd`. */
161
+ function normalizeAgentPath(input, cwd) {
162
+ const trimmed = input.trim();
163
+ let expanded = trimmed;
164
+ if (trimmed === "~")
165
+ expanded = homedir();
166
+ else if (trimmed.startsWith("~/"))
167
+ expanded = join(homedir(), trimmed.slice(2));
168
+ else if (trimmed.startsWith("~"))
169
+ expanded = join(homedir(), trimmed.slice(1));
170
+ return resolve(cwd, expanded);
171
+ }
160
172
  /** Build an AgentRegistry from all configured locations, applying precedence. */
161
173
  export function loadAgentRegistry(options) {
162
174
  const { cwd, includeBuiltins = true, includeClaude = true } = options;
@@ -182,6 +194,20 @@ export function loadAgentRegistry(options) {
182
194
  registerDir(registry, resolve(cwd, ".claude", "agents"), "claude-project");
183
195
  }
184
196
  registerDir(registry, resolve(cwd, CONFIG_DIR_NAME, "agents"), "project");
197
+ // Explicit caller-provided paths override discovered sources (files or dirs).
198
+ for (const rawPath of options.agentPaths ?? []) {
199
+ const p = normalizeAgentPath(rawPath, cwd);
200
+ if (!existsSync(p)) {
201
+ registry.addDiagnostics([{ type: "warning", message: `Agent path does not exist: ${p}`, path: p }]);
202
+ continue;
203
+ }
204
+ if (statSync(p).isDirectory()) {
205
+ registerDir(registry, p, "project");
206
+ }
207
+ else {
208
+ registerFile(registry, p, "project");
209
+ }
210
+ }
185
211
  // CLI-injected paths have highest precedence (support both files and dirs).
186
212
  for (const p of getAgentCliPaths()) {
187
213
  if (!existsSync(p)) {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-registry.js","sourceRoot":"","sources":["../../src/core/agent-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAA0C,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACtG,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,2BAA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AAC,UAAU,CAAC,CAAC;QACvE,CAAC;QACD,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACjB,KAAK,CAAC,IAAI,CAAC,cAAc,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC5D,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;IAElC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB;AAED,SAAS,SAAS,CAAC,GAAW,EAAU;IACvC,OAAO,GAAG;SACR,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Agent registry: data-driven loading of subagent definitions.\n *\n * Replaces the hardcoded `SubagentMode` enum + `MODE_TOOLS` map with frontmatter\n * `.md` files (see agent-frontmatter.ts). Definitions are discovered from, in\n * increasing order of precedence:\n *\n * 1. builtin embedded templates (EMBEDDED_AGENT_PROMPTS)\n * 2. package-manifest paths from hoocode.agents in package.json\n * 3. claude-user ~/.claude/agents/*.md (D7 native import)\n * 4. user ~/.hoocode/agents/*.md\n * 5. ancestor-walk <git-root..cwd>/.agents/agents/*.md\n * 6. claude-project <cwd>/.claude/agents/*.md (D7 native import)\n * 7. project <cwd>/.hoocode/agents/*.md\n * 8. cli paths injected via --agent <path>\n *\n * Higher-precedence sources override lower ones by name. Overrides are recorded\n * as collision diagnostics. Loading never throws; problems surface as\n * diagnostics, matching skills.ts.\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.js\";\nimport { EMBEDDED_AGENT_PROMPTS } from \"../init-templates.generated.js\";\nimport { type AgentDefinition, type AgentSource, parseAgentDefinition } from \"./agent-frontmatter.js\";\nimport { getAgentCliPaths, getAgentManifestPaths } from \"./agent-manifest-paths.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Registry of agent definitions keyed by name. */\nexport class AgentRegistry {\n\tprivate agents = new Map<string, AgentDefinition>();\n\tprivate diagnostics: ResourceDiagnostic[] = [];\n\n\t/**\n\t * Add or override a definition. Later registrations win (used both by the\n\t * loader for precedence and as an escape hatch for programmatic agents).\n\t * Overriding an existing name records a collision diagnostic.\n\t */\n\tregister(def: AgentDefinition): void {\n\t\tconst existing = this.agents.get(def.name);\n\t\tif (existing) {\n\t\t\tthis.diagnostics.push({\n\t\t\t\ttype: \"collision\",\n\t\t\t\tmessage: `agent \"${def.name}\" from ${def.source} overrides ${existing.source}`,\n\t\t\t\tpath: def.filePath,\n\t\t\t\tcollision: {\n\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\tname: def.name,\n\t\t\t\t\twinnerPath: def.filePath ?? `<${def.source}>`,\n\t\t\t\t\tloserPath: existing.filePath ?? `<${existing.source}>`,\n\t\t\t\t\twinnerSource: def.source,\n\t\t\t\t\tloserSource: existing.source,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tthis.agents.set(def.name, def);\n\t}\n\n\tget(name: string): AgentDefinition | undefined {\n\t\treturn this.agents.get(name);\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.agents.has(name);\n\t}\n\n\tlist(): AgentDefinition[] {\n\t\treturn Array.from(this.agents.values());\n\t}\n\n\t/** Diagnostics accumulated during loading/registration. */\n\tgetDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.diagnostics;\n\t}\n\n\t/** Append externally-produced diagnostics (e.g. from a parse step). */\n\taddDiagnostics(diagnostics: ResourceDiagnostic[]): void {\n\t\tthis.diagnostics.push(...diagnostics);\n\t}\n}\n\n/** Load and register every built-in (embedded) agent definition. */\nfunction registerBuiltins(registry: AgentRegistry): void {\n\tfor (const [key, raw] of Object.entries(EMBEDDED_AGENT_PROMPTS)) {\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source: \"builtin\", fallbackName: key });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t}\n}\n\n/** Load flat `*.md` agent files from a directory. Non-`.md` entries and\n * subdirectories are skipped (so runtime dispatch dirs are ignored). */\nfunction registerDir(registry: AgentRegistry, dir: string, source: AgentSource): void {\n\tif (!existsSync(dir)) return;\n\tlet entries: string[];\n\ttry {\n\t\tentries = readdirSync(dir);\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const entry of entries) {\n\t\tif (entry.startsWith(\".\") || !entry.endsWith(\".md\")) continue;\n\t\tconst filePath = join(dir, entry);\n\t\ttry {\n\t\t\tif (!statSync(filePath).isFile()) continue;\n\t\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\t\tregistry.addDiagnostics(diagnostics);\n\t\t\tif (agent) registry.register(agent);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t\t}\n\t}\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Collect `.agents/agents/` dirs from cwd up to the git root (cwd-first order). */\nfunction collectAncestorAgentsDirs(startDir: string): string[] {\n\tconst dirs: string[] = [];\n\tconst resolvedStart = resolve(startDir);\n\tconst gitRoot = findGitRepoRoot(resolvedStart);\n\tlet dir = resolvedStart;\n\twhile (true) {\n\t\tdirs.push(join(dir, \".agents\", \"agents\"));\n\t\tif (gitRoot && dir === gitRoot) break;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\treturn dirs;\n}\n\n/** Register a single file as an agent. */\nfunction registerFile(registry: AgentRegistry, filePath: string, source: AgentSource): void {\n\tif (!existsSync(filePath)) return;\n\ttry {\n\t\tif (!statSync(filePath).isFile()) return;\n\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t}\n}\n\nexport interface LoadAgentRegistryOptions {\n\t/** Working directory for project-local agents. */\n\tcwd: string;\n\t/** User agent config directory (contains `agents/` subdir). Defaults to getAgentDir(). */\n\tagentDir?: string;\n\t/** Include embedded built-in agents. Defaults to true. */\n\tincludeBuiltins?: boolean;\n\t/** Discover `.claude/agents/` directories for native Claude Code import (D7). Defaults to true. */\n\tincludeClaude?: boolean;\n}\n\n/** Build an AgentRegistry from all configured locations, applying precedence. */\nexport function loadAgentRegistry(options: LoadAgentRegistryOptions): AgentRegistry {\n\tconst { cwd, includeBuiltins = true, includeClaude = true } = options;\n\tconst userAgentDir = options.agentDir ?? getAgentDir();\n\tconst registry = new AgentRegistry();\n\n\t// Lowest precedence first; later sources override earlier ones by name.\n\tif (includeBuiltins) {\n\t\tregisterBuiltins(registry);\n\t}\n\n\t// Package-manifest agents (declared via `hoocode.agents` in package.json).\n\tfor (const filePath of getAgentManifestPaths()) {\n\t\tregisterFile(registry, filePath, \"user\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, join(homedir(), \".claude\", \"agents\"), \"claude-user\");\n\t}\n\tregisterDir(registry, join(userAgentDir, \"agents\"), \"user\");\n\n\t// Ancestor-walk .agents/agents/ dirs (git-root first so cwd-level overrides ancestors).\n\tfor (const dir of collectAncestorAgentsDirs(cwd).reverse()) {\n\t\tregisterDir(registry, dir, \"project\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, resolve(cwd, \".claude\", \"agents\"), \"claude-project\");\n\t}\n\tregisterDir(registry, resolve(cwd, CONFIG_DIR_NAME, \"agents\"), \"project\");\n\n\t// CLI-injected paths have highest precedence (support both files and dirs).\n\tfor (const p of getAgentCliPaths()) {\n\t\tif (!existsSync(p)) {\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message: `Agent path does not exist: ${p}`, path: p }]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (statSync(p).isDirectory()) {\n\t\t\tregisterDir(registry, p, \"user\");\n\t\t} else {\n\t\t\tregisterFile(registry, p, \"user\");\n\t\t}\n\t}\n\n\treturn registry;\n}\n\n/**\n * Format a list of agent definitions as an XML block for inclusion in a system\n * prompt, mirroring the `<available_skills>` format used by formatSkillsForPrompt.\n * Only intended for display when the Task tool is active.\n */\nexport function formatAgentsForPrompt(agents: AgentDefinition[]): string {\n\tif (agents.length === 0) return \"\";\n\n\tconst lines = [\n\t\t\"\\n\\nThe following specialized agents are available for delegation via the Task tool.\",\n\t\t\"Choose the agent whose description best matches the task and pass it as `subagent_type`.\",\n\t\t\"\",\n\t\t\"<available_agents>\",\n\t];\n\n\tfor (const agent of agents) {\n\t\tlines.push(\" <agent>\");\n\t\tlines.push(` <name>${escapeXml(agent.name)}</name>`);\n\t\tlines.push(` <description>${escapeXml(agent.description)}</description>`);\n\t\tif (agent.tools && agent.tools.length > 0) {\n\t\t\tlines.push(` <tools>${escapeXml(agent.tools.join(\", \"))}</tools>`);\n\t\t}\n\t\tif (agent.model) {\n\t\t\tlines.push(` <model>${escapeXml(agent.model)}</model>`);\n\t\t}\n\t\tlines.push(\" </agent>\");\n\t}\n\n\tlines.push(\"</available_agents>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n"]}
1
+ {"version":3,"file":"agent-registry.js","sourceRoot":"","sources":["../../src/core/agent-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAA0C,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACtG,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAGpF,mDAAmD;AACnD,MAAM,OAAO,aAAa;IACjB,MAAM,GAAG,IAAI,GAAG,EAA2B,CAAC;IAC5C,WAAW,GAAyB,EAAE,CAAC;IAE/C;;;;OAIG;IACH,QAAQ,CAAC,GAAoB,EAAQ;QACpC,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC3C,IAAI,QAAQ,EAAE,CAAC;YACd,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;gBACrB,IAAI,EAAE,WAAW;gBACjB,OAAO,EAAE,UAAU,GAAG,CAAC,IAAI,UAAU,GAAG,CAAC,MAAM,cAAc,QAAQ,CAAC,MAAM,EAAE;gBAC9E,IAAI,EAAE,GAAG,CAAC,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AAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Agent registry: data-driven loading of subagent definitions.\n *\n * Replaces the hardcoded `SubagentMode` enum + `MODE_TOOLS` map with frontmatter\n * `.md` files (see agent-frontmatter.ts). Definitions are discovered from, in\n * increasing order of precedence:\n *\n * 1. builtin embedded templates (EMBEDDED_AGENT_PROMPTS)\n * 2. package-manifest paths from hoocode.agents in package.json\n * 3. claude-user ~/.claude/agents/*.md (D7 native import)\n * 4. user ~/.hoocode/agents/*.md\n * 5. ancestor-walk <git-root..cwd>/.agents/agents/*.md\n * 6. claude-project <cwd>/.claude/agents/*.md (D7 native import)\n * 7. project <cwd>/.hoocode/agents/*.md\n * 8. cli paths injected via --agent <path>\n *\n * Higher-precedence sources override lower ones by name. Overrides are recorded\n * as collision diagnostics. Loading never throws; problems surface as\n * diagnostics, matching skills.ts.\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.js\";\nimport { EMBEDDED_AGENT_PROMPTS } from \"../init-templates.generated.js\";\nimport { type AgentDefinition, type AgentSource, parseAgentDefinition } from \"./agent-frontmatter.js\";\nimport { getAgentCliPaths, getAgentManifestPaths } from \"./agent-manifest-paths.js\";\nimport type { ResourceDiagnostic } from \"./diagnostics.js\";\n\n/** Registry of agent definitions keyed by name. */\nexport class AgentRegistry {\n\tprivate agents = new Map<string, AgentDefinition>();\n\tprivate diagnostics: ResourceDiagnostic[] = [];\n\n\t/**\n\t * Add or override a definition. Later registrations win (used both by the\n\t * loader for precedence and as an escape hatch for programmatic agents).\n\t * Overriding an existing name records a collision diagnostic.\n\t */\n\tregister(def: AgentDefinition): void {\n\t\tconst existing = this.agents.get(def.name);\n\t\tif (existing) {\n\t\t\tthis.diagnostics.push({\n\t\t\t\ttype: \"collision\",\n\t\t\t\tmessage: `agent \"${def.name}\" from ${def.source} overrides ${existing.source}`,\n\t\t\t\tpath: def.filePath,\n\t\t\t\tcollision: {\n\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\tname: def.name,\n\t\t\t\t\twinnerPath: def.filePath ?? `<${def.source}>`,\n\t\t\t\t\tloserPath: existing.filePath ?? `<${existing.source}>`,\n\t\t\t\t\twinnerSource: def.source,\n\t\t\t\t\tloserSource: existing.source,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tthis.agents.set(def.name, def);\n\t}\n\n\tget(name: string): AgentDefinition | undefined {\n\t\treturn this.agents.get(name);\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.agents.has(name);\n\t}\n\n\tlist(): AgentDefinition[] {\n\t\treturn Array.from(this.agents.values());\n\t}\n\n\t/** Diagnostics accumulated during loading/registration. */\n\tgetDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.diagnostics;\n\t}\n\n\t/** Append externally-produced diagnostics (e.g. from a parse step). */\n\taddDiagnostics(diagnostics: ResourceDiagnostic[]): void {\n\t\tthis.diagnostics.push(...diagnostics);\n\t}\n}\n\n/** Load and register every built-in (embedded) agent definition. */\nfunction registerBuiltins(registry: AgentRegistry): void {\n\tfor (const [key, raw] of Object.entries(EMBEDDED_AGENT_PROMPTS)) {\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source: \"builtin\", fallbackName: key });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t}\n}\n\n/** Load flat `*.md` agent files from a directory. Non-`.md` entries and\n * subdirectories are skipped (so runtime dispatch dirs are ignored). */\nfunction registerDir(registry: AgentRegistry, dir: string, source: AgentSource): void {\n\tif (!existsSync(dir)) return;\n\tlet entries: string[];\n\ttry {\n\t\tentries = readdirSync(dir);\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const entry of entries) {\n\t\tif (entry.startsWith(\".\") || !entry.endsWith(\".md\")) continue;\n\t\tconst filePath = join(dir, entry);\n\t\ttry {\n\t\t\tif (!statSync(filePath).isFile()) continue;\n\t\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\t\tregistry.addDiagnostics(diagnostics);\n\t\t\tif (agent) registry.register(agent);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t\t}\n\t}\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Collect `.agents/agents/` dirs from cwd up to the git root (cwd-first order). */\nfunction collectAncestorAgentsDirs(startDir: string): string[] {\n\tconst dirs: string[] = [];\n\tconst resolvedStart = resolve(startDir);\n\tconst gitRoot = findGitRepoRoot(resolvedStart);\n\tlet dir = resolvedStart;\n\twhile (true) {\n\t\tdirs.push(join(dir, \".agents\", \"agents\"));\n\t\tif (gitRoot && dir === gitRoot) break;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\treturn dirs;\n}\n\n/** Register a single file as an agent. */\nfunction registerFile(registry: AgentRegistry, filePath: string, source: AgentSource): void {\n\tif (!existsSync(filePath)) return;\n\ttry {\n\t\tif (!statSync(filePath).isFile()) return;\n\t\tconst raw = readFileSync(filePath, \"utf-8\");\n\t\tconst { agent, diagnostics } = parseAgentDefinition(raw, { source, filePath });\n\t\tregistry.addDiagnostics(diagnostics);\n\t\tif (agent) registry.register(agent);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to read agent file\";\n\t\tregistry.addDiagnostics([{ type: \"warning\", message, path: filePath }]);\n\t}\n}\n\nexport interface LoadAgentRegistryOptions {\n\t/** Working directory for project-local agents. */\n\tcwd: string;\n\t/** User agent config directory (contains `agents/` subdir). Defaults to getAgentDir(). */\n\tagentDir?: string;\n\t/** Include embedded built-in agents. Defaults to true. */\n\tincludeBuiltins?: boolean;\n\t/** Discover `.claude/agents/` directories for native Claude Code import (D7). Defaults to true. */\n\tincludeClaude?: boolean;\n\t/**\n\t * Explicit agent definition paths (files or directories), resolved relative\n\t * to `cwd` (with `~` expansion). Mirrors `skillPaths`/`promptPaths` on the\n\t * skills and prompt-template loaders. These override all discovered sources\n\t * by name but yield to CLI-injected `--agent` paths.\n\t */\n\tagentPaths?: string[];\n}\n\n/** Resolve an explicit path: expand a leading `~` and resolve against `cwd`. */\nfunction normalizeAgentPath(input: string, cwd: string): string {\n\tconst trimmed = input.trim();\n\tlet expanded = trimmed;\n\tif (trimmed === \"~\") expanded = homedir();\n\telse if (trimmed.startsWith(\"~/\")) expanded = join(homedir(), trimmed.slice(2));\n\telse if (trimmed.startsWith(\"~\")) expanded = join(homedir(), trimmed.slice(1));\n\treturn resolve(cwd, expanded);\n}\n\n/** Build an AgentRegistry from all configured locations, applying precedence. */\nexport function loadAgentRegistry(options: LoadAgentRegistryOptions): AgentRegistry {\n\tconst { cwd, includeBuiltins = true, includeClaude = true } = options;\n\tconst userAgentDir = options.agentDir ?? getAgentDir();\n\tconst registry = new AgentRegistry();\n\n\t// Lowest precedence first; later sources override earlier ones by name.\n\tif (includeBuiltins) {\n\t\tregisterBuiltins(registry);\n\t}\n\n\t// Package-manifest agents (declared via `hoocode.agents` in package.json).\n\tfor (const filePath of getAgentManifestPaths()) {\n\t\tregisterFile(registry, filePath, \"user\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, join(homedir(), \".claude\", \"agents\"), \"claude-user\");\n\t}\n\tregisterDir(registry, join(userAgentDir, \"agents\"), \"user\");\n\n\t// Ancestor-walk .agents/agents/ dirs (git-root first so cwd-level overrides ancestors).\n\tfor (const dir of collectAncestorAgentsDirs(cwd).reverse()) {\n\t\tregisterDir(registry, dir, \"project\");\n\t}\n\n\tif (includeClaude) {\n\t\tregisterDir(registry, resolve(cwd, \".claude\", \"agents\"), \"claude-project\");\n\t}\n\tregisterDir(registry, resolve(cwd, CONFIG_DIR_NAME, \"agents\"), \"project\");\n\n\t// Explicit caller-provided paths override discovered sources (files or dirs).\n\tfor (const rawPath of options.agentPaths ?? []) {\n\t\tconst p = normalizeAgentPath(rawPath, cwd);\n\t\tif (!existsSync(p)) {\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message: `Agent path does not exist: ${p}`, path: p }]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (statSync(p).isDirectory()) {\n\t\t\tregisterDir(registry, p, \"project\");\n\t\t} else {\n\t\t\tregisterFile(registry, p, \"project\");\n\t\t}\n\t}\n\n\t// CLI-injected paths have highest precedence (support both files and dirs).\n\tfor (const p of getAgentCliPaths()) {\n\t\tif (!existsSync(p)) {\n\t\t\tregistry.addDiagnostics([{ type: \"warning\", message: `Agent path does not exist: ${p}`, path: p }]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (statSync(p).isDirectory()) {\n\t\t\tregisterDir(registry, p, \"user\");\n\t\t} else {\n\t\t\tregisterFile(registry, p, \"user\");\n\t\t}\n\t}\n\n\treturn registry;\n}\n\n/**\n * Format a list of agent definitions as an XML block for inclusion in a system\n * prompt, mirroring the `<available_skills>` format used by formatSkillsForPrompt.\n * Only intended for display when the Task tool is active.\n */\nexport function formatAgentsForPrompt(agents: AgentDefinition[]): string {\n\tif (agents.length === 0) return \"\";\n\n\tconst lines = [\n\t\t\"\\n\\nThe following specialized agents are available for delegation via the Task tool.\",\n\t\t\"Choose the agent whose description best matches the task and pass it as `subagent_type`.\",\n\t\t\"\",\n\t\t\"<available_agents>\",\n\t];\n\n\tfor (const agent of agents) {\n\t\tlines.push(\" <agent>\");\n\t\tlines.push(` <name>${escapeXml(agent.name)}</name>`);\n\t\tlines.push(` <description>${escapeXml(agent.description)}</description>`);\n\t\tif (agent.tools && agent.tools.length > 0) {\n\t\t\tlines.push(` <tools>${escapeXml(agent.tools.join(\", \"))}</tools>`);\n\t\t}\n\t\tif (agent.model) {\n\t\t\tlines.push(` <model>${escapeXml(agent.model)}</model>`);\n\t\t}\n\t\tlines.push(\" </agent>\");\n\t}\n\n\tlines.push(\"</available_agents>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n"]}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Canonical built-in mode prompts and the default active mode.
3
+ *
4
+ * These are the fallback system prompts hoocode ships for its four built-in
5
+ * modes (ask / plan / build / debug). They are resolved only when a project or
6
+ * user has not supplied a `modes/{name}/system.md` override.
7
+ *
8
+ * Extracted into a standalone module (instead of living inside the internal
9
+ * `hoo-core` extension) so downstream apps embedding hoocode can import,
10
+ * inspect, and extend the shipped prompts without copy-pasting them.
11
+ */
12
+ /** Mode used when no `active_mode` is configured. */
13
+ export declare const DEFAULT_MODE = "build";
14
+ /** Built-in fallback system prompts keyed by mode name. */
15
+ export declare const DEFAULT_MODE_PROMPTS: Record<string, string>;
16
+ //# sourceMappingURL=mode-prompts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mode-prompts.d.ts","sourceRoot":"","sources":["../../src/core/mode-prompts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,qDAAqD;AACrD,eAAO,MAAM,YAAY,UAAU,CAAC;AAEpC,2DAA2D;AAC3D,eAAO,MAAM,oBAAoB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA0BvD,CAAC","sourcesContent":["/**\n * Canonical built-in mode prompts and the default active mode.\n *\n * These are the fallback system prompts hoocode ships for its four built-in\n * modes (ask / plan / build / debug). They are resolved only when a project or\n * user has not supplied a `modes/{name}/system.md` override.\n *\n * Extracted into a standalone module (instead of living inside the internal\n * `hoo-core` extension) so downstream apps embedding hoocode can import,\n * inspect, and extend the shipped prompts without copy-pasting them.\n */\n\n/** Mode used when no `active_mode` is configured. */\nexport const DEFAULT_MODE = \"build\";\n\n/** Built-in fallback system prompts keyed by mode name. */\nexport const DEFAULT_MODE_PROMPTS: Record<string, string> = {\n\task: `You are in ASK mode — read-only Q&A.\nAnswer questions about the codebase. Trace logic, compare approaches, explain patterns.\nYou may read any file but NEVER write, edit, or execute commands.\nIf asked to make changes, refuse and suggest switching to /mode build.\nCite specific file paths and line numbers in your answers.`,\n\n\tplan: `You are in PLAN mode — exploration and planning.\nExplore the codebase thoroughly. Understand the current structure.\nDraft a complete plan with sections: Goal, Files to modify, New files, Tests, Verification.\nWrite the plan to {{PLAN_PATH}}.\nWhen the plan is complete, tell the user to run /approve to execute it.`,\n\n\tbuild: `You are in BUILD mode — careful implementation.\nRead files before editing them. Show diffs before non-trivial changes.\nAsk for confirmation before destructive operations (delete, reformat).\nRun tests after every logical unit of work.\nPrefer the smallest change that achieves the goal.\nFollow existing code patterns and conventions.`,\n\n\tdebug: `You are in DEBUG mode — root cause analysis.\nGather evidence: read files, check logs, reproduce the issue.\nTrace the call path from entry to failure point.\nState the root cause in one sentence.\nDescribe the fix precisely but do NOT apply it.\nTo fix, switch to /mode build.`,\n};\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Canonical built-in mode prompts and the default active mode.
3
+ *
4
+ * These are the fallback system prompts hoocode ships for its four built-in
5
+ * modes (ask / plan / build / debug). They are resolved only when a project or
6
+ * user has not supplied a `modes/{name}/system.md` override.
7
+ *
8
+ * Extracted into a standalone module (instead of living inside the internal
9
+ * `hoo-core` extension) so downstream apps embedding hoocode can import,
10
+ * inspect, and extend the shipped prompts without copy-pasting them.
11
+ */
12
+ /** Mode used when no `active_mode` is configured. */
13
+ export const DEFAULT_MODE = "build";
14
+ /** Built-in fallback system prompts keyed by mode name. */
15
+ export const DEFAULT_MODE_PROMPTS = {
16
+ ask: `You are in ASK mode — read-only Q&A.
17
+ Answer questions about the codebase. Trace logic, compare approaches, explain patterns.
18
+ You may read any file but NEVER write, edit, or execute commands.
19
+ If asked to make changes, refuse and suggest switching to /mode build.
20
+ Cite specific file paths and line numbers in your answers.`,
21
+ plan: `You are in PLAN mode — exploration and planning.
22
+ Explore the codebase thoroughly. Understand the current structure.
23
+ Draft a complete plan with sections: Goal, Files to modify, New files, Tests, Verification.
24
+ Write the plan to {{PLAN_PATH}}.
25
+ When the plan is complete, tell the user to run /approve to execute it.`,
26
+ build: `You are in BUILD mode — careful implementation.
27
+ Read files before editing them. Show diffs before non-trivial changes.
28
+ Ask for confirmation before destructive operations (delete, reformat).
29
+ Run tests after every logical unit of work.
30
+ Prefer the smallest change that achieves the goal.
31
+ Follow existing code patterns and conventions.`,
32
+ debug: `You are in DEBUG mode — root cause analysis.
33
+ Gather evidence: read files, check logs, reproduce the issue.
34
+ Trace the call path from entry to failure point.
35
+ State the root cause in one sentence.
36
+ Describe the fix precisely but do NOT apply it.
37
+ To fix, switch to /mode build.`,
38
+ };
39
+ //# sourceMappingURL=mode-prompts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mode-prompts.js","sourceRoot":"","sources":["../../src/core/mode-prompts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,qDAAqD;AACrD,MAAM,CAAC,MAAM,YAAY,GAAG,OAAO,CAAC;AAEpC,2DAA2D;AAC3D,MAAM,CAAC,MAAM,oBAAoB,GAA2B;IAC3D,GAAG,EAAE;;;;2DAIqD;IAE1D,IAAI,EAAE;;;;wEAIiE;IAEvE,KAAK,EAAE;;;;;+CAKuC;IAE9C,KAAK,EAAE;;;;;+BAKuB;CAC9B,CAAC","sourcesContent":["/**\n * Canonical built-in mode prompts and the default active mode.\n *\n * These are the fallback system prompts hoocode ships for its four built-in\n * modes (ask / plan / build / debug). They are resolved only when a project or\n * user has not supplied a `modes/{name}/system.md` override.\n *\n * Extracted into a standalone module (instead of living inside the internal\n * `hoo-core` extension) so downstream apps embedding hoocode can import,\n * inspect, and extend the shipped prompts without copy-pasting them.\n */\n\n/** Mode used when no `active_mode` is configured. */\nexport const DEFAULT_MODE = \"build\";\n\n/** Built-in fallback system prompts keyed by mode name. */\nexport const DEFAULT_MODE_PROMPTS: Record<string, string> = {\n\task: `You are in ASK mode — read-only Q&A.\nAnswer questions about the codebase. Trace logic, compare approaches, explain patterns.\nYou may read any file but NEVER write, edit, or execute commands.\nIf asked to make changes, refuse and suggest switching to /mode build.\nCite specific file paths and line numbers in your answers.`,\n\n\tplan: `You are in PLAN mode — exploration and planning.\nExplore the codebase thoroughly. Understand the current structure.\nDraft a complete plan with sections: Goal, Files to modify, New files, Tests, Verification.\nWrite the plan to {{PLAN_PATH}}.\nWhen the plan is complete, tell the user to run /approve to execute it.`,\n\n\tbuild: `You are in BUILD mode — careful implementation.\nRead files before editing them. Show diffs before non-trivial changes.\nAsk for confirmation before destructive operations (delete, reformat).\nRun tests after every logical unit of work.\nPrefer the smallest change that achieves the goal.\nFollow existing code patterns and conventions.`,\n\n\tdebug: `You are in DEBUG mode — root cause analysis.\nGather evidence: read files, check logs, reproduce the issue.\nTrace the call path from entry to failure point.\nState the root cause in one sentence.\nDescribe the fix precisely but do NOT apply it.\nTo fix, switch to /mode build.`,\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * System prompt construction and project context loading
3
3
  */
4
- import type { AgentDefinition } from "./agent-frontmatter.js";
4
+ import { type AgentDefinition } from "./agent-frontmatter.js";
5
5
  import { type Skill } from "./skills.js";
6
6
  export interface BuildSystemPromptOptions {
7
7
  /** Custom system prompt (replaces default). */
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qFAAqF;IACrF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB;;;;OAIG;IACH,MAAM,CAAC,EAAE,eAAe,EAAE,CAAC;CAC3B;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CA0J3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport type { AgentDefinition } from \"./agent-frontmatter.js\";\nimport { formatAgentsForPrompt } from \"./agent-registry.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, grep, find, ls] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/**\n\t * Available agents for delegation, emitted as `<available_agents>` XML.\n\t * Only populated when the Task tool is active so the model knows which\n\t * agents exist without re-reading the agent registry each turn.\n\t */\n\tagents?: AgentDefinition[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tagents: providedAgents,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst agents = providedAgents ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst hasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (hasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append agents section (only when Task tool is active)\n\t\tconst hasTask = !selectedTools || selectedTools.includes(\"Task\");\n\t\tif (hasTask && agents.length > 0) {\n\t\t\tprompt += formatAgentsForPrompt(agents);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines. Name only the tools that are actually\n\t// registered (the condition used to OR the three but hardcode all three\n\t// names, advertising tools that might not exist) and map each to its job so\n\t// the model picks the right one instead of defaulting to its bash habit.\n\tconst explore: string[] = [];\n\tif (hasGrep) explore.push(\"grep (search file contents)\");\n\tif (hasFind) explore.push(\"find (locate files by name/glob)\");\n\tif (hasLs) explore.push(\"ls (list directory contents)\");\n\tif (explore.length > 0) {\n\t\taddGuideline(\n\t\t\t`For file exploration use the dedicated tools — ${explore.join(\", \")} — instead of bash (grep/find/ls in the shell); they are faster, and respect .gitignore where applicable`,\n\t\t);\n\t} else if (hasBash) {\n\t\taddGuideline(\"Use bash for file exploration (ls, rg/grep, find)\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside hoocode, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append agents section (only when Task tool is active)\n\tconst hasTask = tools.includes(\"Task\");\n\tif (hasTask && agents.length > 0) {\n\t\tprompt += formatAgentsForPrompt(agents);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,KAAK,eAAe,EAAkB,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qFAAqF;IACrF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB;;;;OAIG;IACH,MAAM,CAAC,EAAE,eAAe,EAAE,CAAC;CAC3B;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CA0J3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { type AgentDefinition, TASK_TOOL_NAME } from \"./agent-frontmatter.js\";\nimport { formatAgentsForPrompt } from \"./agent-registry.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, grep, find, ls] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/**\n\t * Available agents for delegation, emitted as `<available_agents>` XML.\n\t * Only populated when the Task tool is active so the model knows which\n\t * agents exist without re-reading the agent registry each turn.\n\t */\n\tagents?: AgentDefinition[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tagents: providedAgents,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst agents = providedAgents ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst hasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (hasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append agents section (only when Task tool is active)\n\t\tconst hasTask = !selectedTools || selectedTools.includes(TASK_TOOL_NAME);\n\t\tif (hasTask && agents.length > 0) {\n\t\t\tprompt += formatAgentsForPrompt(agents);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines. Name only the tools that are actually\n\t// registered (the condition used to OR the three but hardcode all three\n\t// names, advertising tools that might not exist) and map each to its job so\n\t// the model picks the right one instead of defaulting to its bash habit.\n\tconst explore: string[] = [];\n\tif (hasGrep) explore.push(\"grep (search file contents)\");\n\tif (hasFind) explore.push(\"find (locate files by name/glob)\");\n\tif (hasLs) explore.push(\"ls (list directory contents)\");\n\tif (explore.length > 0) {\n\t\taddGuideline(\n\t\t\t`For file exploration use the dedicated tools — ${explore.join(\", \")} — instead of bash (grep/find/ls in the shell); they are faster, and respect .gitignore where applicable`,\n\t\t);\n\t} else if (hasBash) {\n\t\taddGuideline(\"Use bash for file exploration (ls, rg/grep, find)\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside hoocode, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append agents section (only when Task tool is active)\n\tconst hasTask = tools.includes(TASK_TOOL_NAME);\n\tif (hasTask && agents.length > 0) {\n\t\tprompt += formatAgentsForPrompt(agents);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]}