@kolisachint/hoocode-agent 0.4.154 → 0.4.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.156] - 2026-08-07
4
+
5
+ ### Added
6
+
7
+ - `/goal` — works autonomously toward a completion condition. `/goal <objective>`
8
+ takes the objective directly; bare `/goal` reads it from the plan's Goal
9
+ section, and the plan's Verification section becomes the completion condition
10
+ either way, which is the difference between a run that stops when it feels
11
+ finished and one that stops when something it can execute says so. Accepts
12
+ `--max-turns N` for the turn budget. Deliberately linear: a single thread of
13
+ execution that iterates until it reports done or exhausts its budget, with no
14
+ task graph and no subtask fan-out. The run inherits whatever the active mode
15
+ already permits (`enabled_tools`, `allowed_bash_commands`,
16
+ `allowed_write_paths`, `auto_allow`), so how much rope an unattended goal gets
17
+ stays a mode-config decision.
18
+ - `/grill` — stress-tests the current plan before `/approve` executes it. Two
19
+ phases: `/grill me` surfaces the request's unconfirmed assumptions as
20
+ `ask_options` questions, and `/grill plan` attacks the plan file itself,
21
+ verifying its claims against the codebase and revising it where it is weak.
22
+ Bare `/grill` runs both, in that order: underspecification sits upstream of
23
+ plan weakness, so critiquing a plan built on a misread request only produces a
24
+ well-reviewed plan for the wrong job — the user's answers are folded into the
25
+ critique instead. Unlike `/approve` the command only injects a follow-up
26
+ message, so there is no session switch, no mode change, and no config write.
27
+ While a `/loop auto` run is active nobody is present to answer a question, so
28
+ the interrogation phase is dropped and the plan critique runs on its own.
29
+
30
+ ### Changed
31
+
32
+ - Plan mode now points at the whole path out of a plan rather than only
33
+ `/approve`: it offers `/grill` to stress-test first, then `/approve` to execute
34
+ step by step or `/goal` to work toward the plan autonomously, and recommends
35
+ grilling whenever the plan carries real risk. Previously the two new commands
36
+ were reachable only if you already knew to type them.
37
+ - The autonomous loop can now be started over the event bus. `LOOP_AUTO_START`
38
+ mirrors the existing `LOOP_HALT` channel in the opposite direction, letting an
39
+ extension drive a run without reaching into state private to `/loop`, and its
40
+ payload carries an optional `continuePrompt` so a caller with a concrete
41
+ completion condition can restate it on every continuation instead of relying
42
+ on the generic nudge. `/loop auto` now shares that same starter; its behaviour
43
+ is unchanged.
44
+
45
+ ## [0.4.155] - 2026-07-29
46
+
3
47
  ## [0.4.154] - 2026-07-23
4
48
 
5
49
  ### Added
@@ -1 +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's `modes` module) 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
+ {"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,CA4BvD,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's `modes` module) 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 their options: /grill to stress-test it\nfirst, then /approve to execute it step by step or /goal to work toward it\nautonomously. Recommend /grill when the plan carries real risk.`,\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"]}
@@ -22,7 +22,9 @@ Cite specific file paths and line numbers in your answers.`,
22
22
  Explore the codebase thoroughly. Understand the current structure.
23
23
  Draft a complete plan with sections: Goal, Files to modify, New files, Tests, Verification.
24
24
  Write the plan to {{PLAN_PATH}}.
25
- When the plan is complete, tell the user to run /approve to execute it.`,
25
+ When the plan is complete, tell the user their options: /grill to stress-test it
26
+ first, then /approve to execute it step by step or /goal to work toward it
27
+ autonomously. Recommend /grill when the plan carries real risk.`,
26
28
  build: `You are in BUILD mode — careful implementation.
27
29
  Read files before editing them. Show diffs before non-trivial changes.
28
30
  Ask for confirmation before destructive operations (delete, reformat).
@@ -1 +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's `modes` module) 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
+ {"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;;;;;;gEAMyD;IAE/D,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's `modes` module) 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 their options: /grill to stress-test it\nfirst, then /approve to execute it step by step or /goal to work toward it\nautonomously. Recommend /grill when the plan carries real risk.`,\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"]}
@@ -11,6 +11,8 @@
11
11
  * /loop auto [--max-turns N] <task> keep iterating until the task says LOOP_DONE
12
12
  */
13
13
  import type { ExtensionAPI } from "../../core/extensions/types.js";
14
+ /** Sentinel the agent replies with to declare the autonomous loop finished. */
15
+ export declare const AUTO_LOOP_DONE_TOKEN = "LOOP_DONE";
14
16
  /**
15
17
  * Event-bus channel: the autonomous-loop active state changed.
16
18
  * Payload: `{ active: boolean }`. Emitted whenever `/loop auto` starts or stops
@@ -23,5 +25,25 @@ export declare const LOOP_AUTO_CHANGED = "loop:auto-changed";
23
25
  * blocker that requires a human decision the loop cannot safely make on its own.
24
26
  */
25
27
  export declare const LOOP_HALT = "loop:halt";
28
+ /**
29
+ * Event-bus channel: start the autonomous loop.
30
+ * Payload: {@link LoopAutoStartPayload}. Mirrors LOOP_HALT in the opposite
31
+ * direction, letting another extension (e.g. `/goal`) drive the loop without
32
+ * reaching into state that lives inside this module's closure.
33
+ */
34
+ export declare const LOOP_AUTO_START = "loop:auto-start";
35
+ /** Payload for {@link LOOP_AUTO_START}. */
36
+ export interface LoopAutoStartPayload {
37
+ /** The task to work toward, delivered as the loop's first user message. */
38
+ task: string;
39
+ /** Turn budget before the loop stops itself. Defaults to 10. */
40
+ maxTurns?: number;
41
+ /**
42
+ * Message re-sent on each continuation. Callers with a concrete completion
43
+ * condition should restate it here, so the target does not drift out of view
44
+ * as the transcript grows. Defaults to a generic nudge.
45
+ */
46
+ continuePrompt?: string;
47
+ }
26
48
  export declare function setupLoop(pi: ExtensionAPI): void;
27
49
  //# sourceMappingURL=loop.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../../../src/extensions/core/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,KAAK,EACX,YAAY,EAIZ,MAAM,gCAAgC,CAAC;AAOxC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,sBAAsB,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,SAAS,cAAc,CAAC;AAkCrC,wBAAgB,SAAS,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAsOhD","sourcesContent":["/**\n * /loop — cron scheduler, Cron* tools, and autonomous continuation.\n *\n * `/loop` schedules prompts via cron and drives autonomous continuation. The same\n * scheduler backs the agent-callable CronCreate/CronList/CronDelete tools.\n *\n * /loop \"<cron>\" <prompt> schedule recurring (5-field cron, local time)\n * /loop <5m|2h|1d> <prompt> schedule recurring at a simple interval\n * /loop once \"<cron>\" <prompt> schedule a one-shot\n * /loop list | /loop delete <id> | /loop stop\n * /loop auto [--max-turns N] <task> keep iterating until the task says LOOP_DONE\n */\n\nimport { join } from \"node:path\";\nimport { Type } from \"typebox\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { defineTool } from \"../../core/extensions/types.js\";\nimport { TaskScheduler } from \"../../core/scheduler.js\";\n\nconst AUTO_LOOP_DONE_TOKEN = \"LOOP_DONE\";\nconst DEFAULT_AUTO_MAX_TURNS = 10;\n\n/**\n * Event-bus channel: the autonomous-loop active state changed.\n * Payload: `{ active: boolean }`. Emitted whenever `/loop auto` starts or stops\n * so other extensions (e.g. ask_options) can adapt to running unattended.\n */\nexport const LOOP_AUTO_CHANGED = \"loop:auto-changed\";\n\n/**\n * Event-bus channel: request to halt the autonomous loop.\n * Payload: `{ reason: string }`. Sent by another extension when it hits a\n * blocker that requires a human decision the loop cannot safely make on its own.\n */\nexport const LOOP_HALT = \"loop:halt\";\n\n/** Convert a simple interval token (\"5m\", \"2h\", \"1d\") to a 5-field cron, or null. */\nfunction intervalToCron(token: string): string | null {\n\tconst m = /^(\\d+)(m|h|d)$/.exec(token.trim());\n\tif (!m) return null;\n\tconst n = Number(m[1]);\n\tif (n < 1) return null;\n\tif (m[2] === \"m\") return `*/${n} * * * *`;\n\tif (m[2] === \"h\") return `0 */${n} * * *`;\n\treturn `0 0 */${n} * *`; // days\n}\n\n/** Pull a quoted cron expression off the front of an argument string. */\nfunction extractQuotedCron(args: string): { cron: string; rest: string } | null {\n\tconst m = /^\"([^\"]+)\"\\s*(.*)$/.exec(args.trim());\n\treturn m ? { cron: m[1].trim(), rest: m[2].trim() } : null;\n}\n\nfunction isFiveFieldCron(expr: string): boolean {\n\treturn expr.trim().split(/\\s+/).length === 5;\n}\n\n/** Flatten an assistant message's text blocks. */\nfunction assistantText(message: { content: unknown }): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter((b): b is { type: \"text\"; text: string } => !!b && (b as { type?: string }).type === \"text\")\n\t\t.map((b) => b.text)\n\t\t.join(\"\\n\");\n}\n\nexport function setupLoop(pi: ExtensionAPI): void {\n\tlet scheduler: TaskScheduler | undefined;\n\tlet auto: { remaining: number } | null = null;\n\tlet activeCtx: ExtensionContext | undefined;\n\n\t/** Set the autonomous-loop state and broadcast the active flag on the bus. */\n\tfunction setAuto(next: { remaining: number } | null): void {\n\t\tconst was = auto !== null;\n\t\tauto = next;\n\t\tif (was !== (next !== null)) pi.events.emit(LOOP_AUTO_CHANGED, { active: next !== null });\n\t}\n\n\t// Another extension (e.g. ask_options) hit a decision it cannot safely make\n\t// while unattended. Stop iterating and let the model report the blocker.\n\tpi.events.on(LOOP_HALT, (data) => {\n\t\tif (!auto) return;\n\t\tconst reason = (data as { reason?: string })?.reason?.trim() || \"a decision that needs the user.\";\n\t\tsetAuto(null);\n\t\tactiveCtx?.ui.notify(`Autonomous loop halted: ${reason}`, \"warning\");\n\t});\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\tactiveCtx = ctx;\n\t\tif (scheduler) return;\n\t\tconst isIdle = () => {\n\t\t\ttry {\n\t\t\t\treturn ctx.isIdle();\n\t\t\t} catch {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\t\tscheduler = new TaskScheduler({\n\t\t\t// `.agents/` is the primary, cross-vendor home; the legacy `.hoocode/`\n\t\t\t// store is read once and migrates forward on the next persist.\n\t\t\tstorePath: join(ctx.cwd, \".agents\", \"scheduled_tasks.json\"),\n\t\t\tlegacyStorePath: join(ctx.cwd, \".hoocode\", \"scheduled_tasks.json\"),\n\t\t\tfire: (prompt) => pi.sendUserMessage(prompt, { deliverAs: \"followUp\" }),\n\t\t\tisIdle,\n\t\t});\n\t\tscheduler.start();\n\t});\n\n\tpi.on(\"session_shutdown\", () => {\n\t\tscheduler?.stop();\n\t\tsetAuto(null);\n\t});\n\n\t// Autonomous continuation: re-prompt on each agent_end until LOOP_DONE or budget.\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tif (!auto) return;\n\t\tif (ctx.hasPendingMessages()) return; // user is steering — yield\n\t\tconst last = [...event.messages].reverse().find((m) => m.role === \"assistant\");\n\t\tconst text = last ? assistantText(last) : \"\";\n\t\tif (text.includes(AUTO_LOOP_DONE_TOKEN)) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop complete.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (auto.remaining <= 0) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop stopped: max turns reached.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tauto.remaining -= 1;\n\t\tpi.sendUserMessage(`Continue working toward the goal. Reply with ${AUTO_LOOP_DONE_TOKEN} when fully complete.`, {\n\t\t\tdeliverAs: \"followUp\",\n\t\t});\n\t});\n\n\t// ── Cron* tools (agent-callable) ──────────────────────────────────────────\n\tconst toolText = (s: string) => ({ content: [{ type: \"text\" as const, text: s }], details: undefined });\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronCreate\",\n\t\t\tlabel: \"Schedule Task\",\n\t\t\tdescription:\n\t\t\t\t\"Schedule a prompt to be re-submitted on a cron schedule (5-field, local time: minute hour day-of-month month day-of-week). recurring=false fires once then deletes.\",\n\t\t\tparameters: Type.Object({\n\t\t\t\tcron: Type.String({ description: \"5-field cron expression in local time\" }),\n\t\t\t\tprompt: Type.String({ description: \"Prompt to enqueue at each fire time\" }),\n\t\t\t\trecurring: Type.Optional(Type.Boolean({ description: \"Fire repeatedly (default true) or once\" })),\n\t\t\t}),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tif (!scheduler) return toolText(\"Scheduler not ready.\");\n\t\t\t\tif (!isFiveFieldCron(params.cron)) return toolText(`Invalid cron \"${params.cron}\" (need 5 fields).`);\n\t\t\t\tconst task = scheduler.create({\n\t\t\t\t\tcron: params.cron,\n\t\t\t\t\tprompt: params.prompt,\n\t\t\t\t\trecurring: params.recurring ?? true,\n\t\t\t\t});\n\t\t\t\treturn toolText(`Scheduled ${task.id}: \"${task.cron}\" (${task.recurring ? \"recurring\" : \"once\"})`);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronList\",\n\t\t\tlabel: \"List Scheduled Tasks\",\n\t\t\tdescription: \"List all scheduled tasks (id, cron, recurring, prompt).\",\n\t\t\tparameters: Type.Object({}),\n\t\t\tasync execute() {\n\t\t\t\tconst tasks = scheduler?.list() ?? [];\n\t\t\t\tif (tasks.length === 0) return toolText(\"No scheduled tasks.\");\n\t\t\t\treturn toolText(\n\t\t\t\t\ttasks\n\t\t\t\t\t\t.map((t) => `${t.id} ${t.cron} ${t.recurring ? \"recurring\" : \"once\"} ${JSON.stringify(t.prompt)}`)\n\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronDelete\",\n\t\t\tlabel: \"Delete Scheduled Task\",\n\t\t\tdescription: \"Delete a scheduled task by id.\",\n\t\t\tparameters: Type.Object({ id: Type.String({ description: \"Task id from CronCreate/CronList\" }) }),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tconst removed = scheduler?.delete(params.id) ?? false;\n\t\t\t\treturn toolText(removed ? `Deleted ${params.id}.` : `No task ${params.id}.`);\n\t\t\t},\n\t\t}),\n\t);\n\n\t// ── /loop command ─────────────────────────────────────────────────────────\n\tpi.registerCommand(\"loop\", {\n\t\tdescription:\n\t\t\t'Schedule prompts via cron or run an autonomous loop. /loop \"<cron>\" <prompt> | /loop <5m|2h> <prompt> | /loop once \"<cron>\" <prompt> | /loop list | /loop delete <id> | /loop stop | /loop auto [--max-turns N] <task>',\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\t[\"list\", \"delete\", \"stop\", \"once\", \"auto\"]\n\t\t\t\t.filter((s) => s.startsWith(prefix))\n\t\t\t\t.map((s) => ({ value: s, label: s })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tif (!scheduler) {\n\t\t\t\tctx.ui.notify(\"Scheduler not ready yet.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!trimmed || trimmed === \"list\") {\n\t\t\t\tconst tasks = scheduler.list();\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\ttasks.length === 0\n\t\t\t\t\t\t? auto\n\t\t\t\t\t\t\t? `Autonomous loop active (${auto.remaining} turns left).`\n\t\t\t\t\t\t\t: \"No scheduled tasks.\"\n\t\t\t\t\t\t: tasks.map((t) => `${t.id}: ${t.cron} ${t.recurring ? \"\" : \"(once) \"}— ${t.prompt}`).join(\"\\n\"),\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed === \"stop\") {\n\t\t\t\tconst had = scheduler.list().length > 0 || auto !== null;\n\t\t\t\tscheduler.clear();\n\t\t\t\tsetAuto(null);\n\t\t\t\tctx.ui.notify(had ? \"Stopped all loops and scheduled tasks.\" : \"Nothing to stop.\", \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"delete\")) {\n\t\t\t\tconst id = trimmed.slice(\"delete\".length).trim();\n\t\t\t\tif (!id) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop delete <id>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tctx.ui.notify(scheduler.delete(id) ? `Deleted ${id}.` : `No task ${id}.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"auto\")) {\n\t\t\t\tlet rest = trimmed.slice(\"auto\".length).trim();\n\t\t\t\tlet maxTurns = DEFAULT_AUTO_MAX_TURNS;\n\t\t\t\tconst flag = /^--max-turns\\s+(\\d+)\\s*(.*)$/.exec(rest);\n\t\t\t\tif (flag) {\n\t\t\t\t\tmaxTurns = Number(flag[1]);\n\t\t\t\t\trest = flag[2].trim();\n\t\t\t\t}\n\t\t\t\tif (!rest) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop auto [--max-turns N] <task>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsetAuto({ remaining: maxTurns });\n\t\t\t\tpi.sendUserMessage(\n\t\t\t\t\t`${rest}\\n\\n(Autonomous loop: keep working until the task is fully complete, then reply with ${AUTO_LOOP_DONE_TOKEN}.)`,\n\t\t\t\t\t{ deliverAs: \"followUp\" },\n\t\t\t\t);\n\t\t\t\tctx.ui.notify(`Autonomous loop started (max ${maxTurns} turns). Stop with /loop stop.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Scheduling: one-shot or recurring, via quoted cron or interval token.\n\t\t\tlet recurring = true;\n\t\t\tlet body = trimmed;\n\t\t\tif (body.startsWith(\"once\")) {\n\t\t\t\trecurring = false;\n\t\t\t\tbody = body.slice(\"once\".length).trim();\n\t\t\t}\n\n\t\t\tlet cron: string | null = null;\n\t\t\tlet prompt = \"\";\n\t\t\tconst quoted = extractQuotedCron(body);\n\t\t\tif (quoted) {\n\t\t\t\tcron = quoted.cron;\n\t\t\t\tprompt = quoted.rest;\n\t\t\t} else {\n\t\t\t\tconst [first, ...restWords] = body.split(/\\s+/);\n\t\t\t\tcron = intervalToCron(first);\n\t\t\t\tprompt = restWords.join(\" \").trim();\n\t\t\t}\n\n\t\t\tif (!cron || !isFiveFieldCron(cron)) {\n\t\t\t\tctx.ui.notify('Usage: /loop \"<cron>\" <prompt> or /loop <5m|2h|1d> <prompt>', \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!prompt) {\n\t\t\t\tctx.ui.notify(\"Nothing to schedule — provide a prompt after the schedule.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst task = scheduler.create({ cron, prompt, recurring });\n\t\t\tctx.ui.notify(\n\t\t\t\t`Scheduled ${task.id}: \"${cron}\" ${recurring ? \"recurring\" : \"once\"} — \"${prompt}\". Manage with /loop list • /loop delete ${task.id}.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../../../src/extensions/core/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,KAAK,EACX,YAAY,EAIZ,MAAM,gCAAgC,CAAC;AAIxC,+EAA+E;AAC/E,eAAO,MAAM,oBAAoB,cAAc,CAAC;AAGhD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,sBAAsB,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,SAAS,cAAc,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,eAAe,oBAAoB,CAAC;AAEjD,2CAA2C;AAC3C,MAAM,WAAW,oBAAoB;IACpC,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC;IACb,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAkCD,wBAAgB,SAAS,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAiQhD","sourcesContent":["/**\n * /loop — cron scheduler, Cron* tools, and autonomous continuation.\n *\n * `/loop` schedules prompts via cron and drives autonomous continuation. The same\n * scheduler backs the agent-callable CronCreate/CronList/CronDelete tools.\n *\n * /loop \"<cron>\" <prompt> schedule recurring (5-field cron, local time)\n * /loop <5m|2h|1d> <prompt> schedule recurring at a simple interval\n * /loop once \"<cron>\" <prompt> schedule a one-shot\n * /loop list | /loop delete <id> | /loop stop\n * /loop auto [--max-turns N] <task> keep iterating until the task says LOOP_DONE\n */\n\nimport { join } from \"node:path\";\nimport { Type } from \"typebox\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { defineTool } from \"../../core/extensions/types.js\";\nimport { TaskScheduler } from \"../../core/scheduler.js\";\n\n/** Sentinel the agent replies with to declare the autonomous loop finished. */\nexport const AUTO_LOOP_DONE_TOKEN = \"LOOP_DONE\";\nconst DEFAULT_AUTO_MAX_TURNS = 10;\n\n/**\n * Event-bus channel: the autonomous-loop active state changed.\n * Payload: `{ active: boolean }`. Emitted whenever `/loop auto` starts or stops\n * so other extensions (e.g. ask_options) can adapt to running unattended.\n */\nexport const LOOP_AUTO_CHANGED = \"loop:auto-changed\";\n\n/**\n * Event-bus channel: request to halt the autonomous loop.\n * Payload: `{ reason: string }`. Sent by another extension when it hits a\n * blocker that requires a human decision the loop cannot safely make on its own.\n */\nexport const LOOP_HALT = \"loop:halt\";\n\n/**\n * Event-bus channel: start the autonomous loop.\n * Payload: {@link LoopAutoStartPayload}. Mirrors LOOP_HALT in the opposite\n * direction, letting another extension (e.g. `/goal`) drive the loop without\n * reaching into state that lives inside this module's closure.\n */\nexport const LOOP_AUTO_START = \"loop:auto-start\";\n\n/** Payload for {@link LOOP_AUTO_START}. */\nexport interface LoopAutoStartPayload {\n\t/** The task to work toward, delivered as the loop's first user message. */\n\ttask: string;\n\t/** Turn budget before the loop stops itself. Defaults to 10. */\n\tmaxTurns?: number;\n\t/**\n\t * Message re-sent on each continuation. Callers with a concrete completion\n\t * condition should restate it here, so the target does not drift out of view\n\t * as the transcript grows. Defaults to a generic nudge.\n\t */\n\tcontinuePrompt?: string;\n}\n\n/** Convert a simple interval token (\"5m\", \"2h\", \"1d\") to a 5-field cron, or null. */\nfunction intervalToCron(token: string): string | null {\n\tconst m = /^(\\d+)(m|h|d)$/.exec(token.trim());\n\tif (!m) return null;\n\tconst n = Number(m[1]);\n\tif (n < 1) return null;\n\tif (m[2] === \"m\") return `*/${n} * * * *`;\n\tif (m[2] === \"h\") return `0 */${n} * * *`;\n\treturn `0 0 */${n} * *`; // days\n}\n\n/** Pull a quoted cron expression off the front of an argument string. */\nfunction extractQuotedCron(args: string): { cron: string; rest: string } | null {\n\tconst m = /^\"([^\"]+)\"\\s*(.*)$/.exec(args.trim());\n\treturn m ? { cron: m[1].trim(), rest: m[2].trim() } : null;\n}\n\nfunction isFiveFieldCron(expr: string): boolean {\n\treturn expr.trim().split(/\\s+/).length === 5;\n}\n\n/** Flatten an assistant message's text blocks. */\nfunction assistantText(message: { content: unknown }): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter((b): b is { type: \"text\"; text: string } => !!b && (b as { type?: string }).type === \"text\")\n\t\t.map((b) => b.text)\n\t\t.join(\"\\n\");\n}\n\nexport function setupLoop(pi: ExtensionAPI): void {\n\tlet scheduler: TaskScheduler | undefined;\n\tlet auto: { remaining: number; continuePrompt?: string } | null = null;\n\tlet activeCtx: ExtensionContext | undefined;\n\n\t/** Set the autonomous-loop state and broadcast the active flag on the bus. */\n\tfunction setAuto(next: { remaining: number; continuePrompt?: string } | null): void {\n\t\tconst was = auto !== null;\n\t\tauto = next;\n\t\tif (was !== (next !== null)) pi.events.emit(LOOP_AUTO_CHANGED, { active: next !== null });\n\t}\n\n\t/**\n\t * Arms the turn budget and delivers the task. Shared by `/loop auto` and the\n\t * LOOP_AUTO_START channel so both start from identical state. Returns the\n\t * budget actually applied, for the caller's notification.\n\t *\n\t * A caller-supplied 0 is honoured (the loop stops at the first continuation);\n\t * only a missing or nonsensical budget falls back to the default.\n\t */\n\tfunction startAuto({ task, maxTurns, continuePrompt }: LoopAutoStartPayload): number {\n\t\tconst budget =\n\t\t\ttypeof maxTurns === \"number\" && Number.isFinite(maxTurns) && maxTurns >= 0 ? maxTurns : DEFAULT_AUTO_MAX_TURNS;\n\t\tsetAuto({ remaining: budget, continuePrompt });\n\t\tpi.sendUserMessage(\n\t\t\t`${task}\\n\\n(Autonomous loop: keep working until the task is fully complete, then reply with ${AUTO_LOOP_DONE_TOKEN}.)`,\n\t\t\t{ deliverAs: \"followUp\" },\n\t\t);\n\t\treturn budget;\n\t}\n\n\t// Another extension asked for an autonomous run. Ignore payloads without a\n\t// task rather than arming a loop with nothing to work on.\n\tpi.events.on(LOOP_AUTO_START, (data) => {\n\t\tconst payload = (data ?? {}) as Partial<LoopAutoStartPayload>;\n\t\tconst task = payload.task?.trim();\n\t\tif (!task) return;\n\t\tconst budget = startAuto({ task, maxTurns: payload.maxTurns, continuePrompt: payload.continuePrompt });\n\t\tactiveCtx?.ui.notify(`Autonomous loop started (max ${budget} turns). Stop with /loop stop.`, \"info\");\n\t});\n\n\t// Another extension (e.g. ask_options) hit a decision it cannot safely make\n\t// while unattended. Stop iterating and let the model report the blocker.\n\tpi.events.on(LOOP_HALT, (data) => {\n\t\tif (!auto) return;\n\t\tconst reason = (data as { reason?: string })?.reason?.trim() || \"a decision that needs the user.\";\n\t\tsetAuto(null);\n\t\tactiveCtx?.ui.notify(`Autonomous loop halted: ${reason}`, \"warning\");\n\t});\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\tactiveCtx = ctx;\n\t\tif (scheduler) return;\n\t\tconst isIdle = () => {\n\t\t\ttry {\n\t\t\t\treturn ctx.isIdle();\n\t\t\t} catch {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\t\tscheduler = new TaskScheduler({\n\t\t\t// `.agents/` is the primary, cross-vendor home; the legacy `.hoocode/`\n\t\t\t// store is read once and migrates forward on the next persist.\n\t\t\tstorePath: join(ctx.cwd, \".agents\", \"scheduled_tasks.json\"),\n\t\t\tlegacyStorePath: join(ctx.cwd, \".hoocode\", \"scheduled_tasks.json\"),\n\t\t\tfire: (prompt) => pi.sendUserMessage(prompt, { deliverAs: \"followUp\" }),\n\t\t\tisIdle,\n\t\t});\n\t\tscheduler.start();\n\t});\n\n\tpi.on(\"session_shutdown\", () => {\n\t\tscheduler?.stop();\n\t\tsetAuto(null);\n\t});\n\n\t// Autonomous continuation: re-prompt on each agent_end until LOOP_DONE or budget.\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tif (!auto) return;\n\t\tif (ctx.hasPendingMessages()) return; // user is steering — yield\n\t\tconst last = [...event.messages].reverse().find((m) => m.role === \"assistant\");\n\t\tconst text = last ? assistantText(last) : \"\";\n\t\tif (text.includes(AUTO_LOOP_DONE_TOKEN)) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop complete.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (auto.remaining <= 0) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop stopped: max turns reached.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tauto.remaining -= 1;\n\t\tpi.sendUserMessage(\n\t\t\tauto.continuePrompt ??\n\t\t\t\t`Continue working toward the goal. Reply with ${AUTO_LOOP_DONE_TOKEN} when fully complete.`,\n\t\t\t{ deliverAs: \"followUp\" },\n\t\t);\n\t});\n\n\t// ── Cron* tools (agent-callable) ──────────────────────────────────────────\n\tconst toolText = (s: string) => ({ content: [{ type: \"text\" as const, text: s }], details: undefined });\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronCreate\",\n\t\t\tlabel: \"Schedule Task\",\n\t\t\tdescription:\n\t\t\t\t\"Schedule a prompt to be re-submitted on a cron schedule (5-field, local time: minute hour day-of-month month day-of-week). recurring=false fires once then deletes.\",\n\t\t\tparameters: Type.Object({\n\t\t\t\tcron: Type.String({ description: \"5-field cron expression in local time\" }),\n\t\t\t\tprompt: Type.String({ description: \"Prompt to enqueue at each fire time\" }),\n\t\t\t\trecurring: Type.Optional(Type.Boolean({ description: \"Fire repeatedly (default true) or once\" })),\n\t\t\t}),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tif (!scheduler) return toolText(\"Scheduler not ready.\");\n\t\t\t\tif (!isFiveFieldCron(params.cron)) return toolText(`Invalid cron \"${params.cron}\" (need 5 fields).`);\n\t\t\t\tconst task = scheduler.create({\n\t\t\t\t\tcron: params.cron,\n\t\t\t\t\tprompt: params.prompt,\n\t\t\t\t\trecurring: params.recurring ?? true,\n\t\t\t\t});\n\t\t\t\treturn toolText(`Scheduled ${task.id}: \"${task.cron}\" (${task.recurring ? \"recurring\" : \"once\"})`);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronList\",\n\t\t\tlabel: \"List Scheduled Tasks\",\n\t\t\tdescription: \"List all scheduled tasks (id, cron, recurring, prompt).\",\n\t\t\tparameters: Type.Object({}),\n\t\t\tasync execute() {\n\t\t\t\tconst tasks = scheduler?.list() ?? [];\n\t\t\t\tif (tasks.length === 0) return toolText(\"No scheduled tasks.\");\n\t\t\t\treturn toolText(\n\t\t\t\t\ttasks\n\t\t\t\t\t\t.map((t) => `${t.id} ${t.cron} ${t.recurring ? \"recurring\" : \"once\"} ${JSON.stringify(t.prompt)}`)\n\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronDelete\",\n\t\t\tlabel: \"Delete Scheduled Task\",\n\t\t\tdescription: \"Delete a scheduled task by id.\",\n\t\t\tparameters: Type.Object({ id: Type.String({ description: \"Task id from CronCreate/CronList\" }) }),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tconst removed = scheduler?.delete(params.id) ?? false;\n\t\t\t\treturn toolText(removed ? `Deleted ${params.id}.` : `No task ${params.id}.`);\n\t\t\t},\n\t\t}),\n\t);\n\n\t// ── /loop command ─────────────────────────────────────────────────────────\n\tpi.registerCommand(\"loop\", {\n\t\tdescription:\n\t\t\t'Schedule prompts via cron or run an autonomous loop. /loop \"<cron>\" <prompt> | /loop <5m|2h> <prompt> | /loop once \"<cron>\" <prompt> | /loop list | /loop delete <id> | /loop stop | /loop auto [--max-turns N] <task>',\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\t[\"list\", \"delete\", \"stop\", \"once\", \"auto\"]\n\t\t\t\t.filter((s) => s.startsWith(prefix))\n\t\t\t\t.map((s) => ({ value: s, label: s })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tif (!scheduler) {\n\t\t\t\tctx.ui.notify(\"Scheduler not ready yet.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!trimmed || trimmed === \"list\") {\n\t\t\t\tconst tasks = scheduler.list();\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\ttasks.length === 0\n\t\t\t\t\t\t? auto\n\t\t\t\t\t\t\t? `Autonomous loop active (${auto.remaining} turns left).`\n\t\t\t\t\t\t\t: \"No scheduled tasks.\"\n\t\t\t\t\t\t: tasks.map((t) => `${t.id}: ${t.cron} ${t.recurring ? \"\" : \"(once) \"}— ${t.prompt}`).join(\"\\n\"),\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed === \"stop\") {\n\t\t\t\tconst had = scheduler.list().length > 0 || auto !== null;\n\t\t\t\tscheduler.clear();\n\t\t\t\tsetAuto(null);\n\t\t\t\tctx.ui.notify(had ? \"Stopped all loops and scheduled tasks.\" : \"Nothing to stop.\", \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"delete\")) {\n\t\t\t\tconst id = trimmed.slice(\"delete\".length).trim();\n\t\t\t\tif (!id) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop delete <id>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tctx.ui.notify(scheduler.delete(id) ? `Deleted ${id}.` : `No task ${id}.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"auto\")) {\n\t\t\t\tlet rest = trimmed.slice(\"auto\".length).trim();\n\t\t\t\tlet maxTurns = DEFAULT_AUTO_MAX_TURNS;\n\t\t\t\tconst flag = /^--max-turns\\s+(\\d+)\\s*(.*)$/.exec(rest);\n\t\t\t\tif (flag) {\n\t\t\t\t\tmaxTurns = Number(flag[1]);\n\t\t\t\t\trest = flag[2].trim();\n\t\t\t\t}\n\t\t\t\tif (!rest) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop auto [--max-turns N] <task>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstartAuto({ task: rest, maxTurns });\n\t\t\t\tctx.ui.notify(`Autonomous loop started (max ${maxTurns} turns). Stop with /loop stop.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Scheduling: one-shot or recurring, via quoted cron or interval token.\n\t\t\tlet recurring = true;\n\t\t\tlet body = trimmed;\n\t\t\tif (body.startsWith(\"once\")) {\n\t\t\t\trecurring = false;\n\t\t\t\tbody = body.slice(\"once\".length).trim();\n\t\t\t}\n\n\t\t\tlet cron: string | null = null;\n\t\t\tlet prompt = \"\";\n\t\t\tconst quoted = extractQuotedCron(body);\n\t\t\tif (quoted) {\n\t\t\t\tcron = quoted.cron;\n\t\t\t\tprompt = quoted.rest;\n\t\t\t} else {\n\t\t\t\tconst [first, ...restWords] = body.split(/\\s+/);\n\t\t\t\tcron = intervalToCron(first);\n\t\t\t\tprompt = restWords.join(\" \").trim();\n\t\t\t}\n\n\t\t\tif (!cron || !isFiveFieldCron(cron)) {\n\t\t\t\tctx.ui.notify('Usage: /loop \"<cron>\" <prompt> or /loop <5m|2h|1d> <prompt>', \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!prompt) {\n\t\t\t\tctx.ui.notify(\"Nothing to schedule — provide a prompt after the schedule.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst task = scheduler.create({ cron, prompt, recurring });\n\t\t\tctx.ui.notify(\n\t\t\t\t`Scheduled ${task.id}: \"${cron}\" ${recurring ? \"recurring\" : \"once\"} — \"${prompt}\". Manage with /loop list • /loop delete ${task.id}.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
@@ -14,7 +14,8 @@ import { join } from "node:path";
14
14
  import { Type } from "typebox";
15
15
  import { defineTool } from "../../core/extensions/types.js";
16
16
  import { TaskScheduler } from "../../core/scheduler.js";
17
- const AUTO_LOOP_DONE_TOKEN = "LOOP_DONE";
17
+ /** Sentinel the agent replies with to declare the autonomous loop finished. */
18
+ export const AUTO_LOOP_DONE_TOKEN = "LOOP_DONE";
18
19
  const DEFAULT_AUTO_MAX_TURNS = 10;
19
20
  /**
20
21
  * Event-bus channel: the autonomous-loop active state changed.
@@ -28,6 +29,13 @@ export const LOOP_AUTO_CHANGED = "loop:auto-changed";
28
29
  * blocker that requires a human decision the loop cannot safely make on its own.
29
30
  */
30
31
  export const LOOP_HALT = "loop:halt";
32
+ /**
33
+ * Event-bus channel: start the autonomous loop.
34
+ * Payload: {@link LoopAutoStartPayload}. Mirrors LOOP_HALT in the opposite
35
+ * direction, letting another extension (e.g. `/goal`) drive the loop without
36
+ * reaching into state that lives inside this module's closure.
37
+ */
38
+ export const LOOP_AUTO_START = "loop:auto-start";
31
39
  /** Convert a simple interval token ("5m", "2h", "1d") to a 5-field cron, or null. */
32
40
  function intervalToCron(token) {
33
41
  const m = /^(\d+)(m|h|d)$/.exec(token.trim());
@@ -73,6 +81,30 @@ export function setupLoop(pi) {
73
81
  if (was !== (next !== null))
74
82
  pi.events.emit(LOOP_AUTO_CHANGED, { active: next !== null });
75
83
  }
84
+ /**
85
+ * Arms the turn budget and delivers the task. Shared by `/loop auto` and the
86
+ * LOOP_AUTO_START channel so both start from identical state. Returns the
87
+ * budget actually applied, for the caller's notification.
88
+ *
89
+ * A caller-supplied 0 is honoured (the loop stops at the first continuation);
90
+ * only a missing or nonsensical budget falls back to the default.
91
+ */
92
+ function startAuto({ task, maxTurns, continuePrompt }) {
93
+ const budget = typeof maxTurns === "number" && Number.isFinite(maxTurns) && maxTurns >= 0 ? maxTurns : DEFAULT_AUTO_MAX_TURNS;
94
+ setAuto({ remaining: budget, continuePrompt });
95
+ pi.sendUserMessage(`${task}\n\n(Autonomous loop: keep working until the task is fully complete, then reply with ${AUTO_LOOP_DONE_TOKEN}.)`, { deliverAs: "followUp" });
96
+ return budget;
97
+ }
98
+ // Another extension asked for an autonomous run. Ignore payloads without a
99
+ // task rather than arming a loop with nothing to work on.
100
+ pi.events.on(LOOP_AUTO_START, (data) => {
101
+ const payload = (data ?? {});
102
+ const task = payload.task?.trim();
103
+ if (!task)
104
+ return;
105
+ const budget = startAuto({ task, maxTurns: payload.maxTurns, continuePrompt: payload.continuePrompt });
106
+ activeCtx?.ui.notify(`Autonomous loop started (max ${budget} turns). Stop with /loop stop.`, "info");
107
+ });
76
108
  // Another extension (e.g. ask_options) hit a decision it cannot safely make
77
109
  // while unattended. Stop iterating and let the model report the blocker.
78
110
  pi.events.on(LOOP_HALT, (data) => {
@@ -127,9 +159,8 @@ export function setupLoop(pi) {
127
159
  return;
128
160
  }
129
161
  auto.remaining -= 1;
130
- pi.sendUserMessage(`Continue working toward the goal. Reply with ${AUTO_LOOP_DONE_TOKEN} when fully complete.`, {
131
- deliverAs: "followUp",
132
- });
162
+ pi.sendUserMessage(auto.continuePrompt ??
163
+ `Continue working toward the goal. Reply with ${AUTO_LOOP_DONE_TOKEN} when fully complete.`, { deliverAs: "followUp" });
133
164
  });
134
165
  // ── Cron* tools (agent-callable) ──────────────────────────────────────────
135
166
  const toolText = (s) => ({ content: [{ type: "text", text: s }], details: undefined });
@@ -228,8 +259,7 @@ export function setupLoop(pi) {
228
259
  ctx.ui.notify("Usage: /loop auto [--max-turns N] <task>", "warning");
229
260
  return;
230
261
  }
231
- setAuto({ remaining: maxTurns });
232
- pi.sendUserMessage(`${rest}\n\n(Autonomous loop: keep working until the task is fully complete, then reply with ${AUTO_LOOP_DONE_TOKEN}.)`, { deliverAs: "followUp" });
262
+ startAuto({ task: rest, maxTurns });
233
263
  ctx.ui.notify(`Autonomous loop started (max ${maxTurns} turns). Stop with /loop stop.`, "info");
234
264
  return;
235
265
  }
@@ -1 +1 @@
1
- {"version":3,"file":"loop.js","sourceRoot":"","sources":["../../../src/extensions/core/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAO/B,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAExD,MAAM,oBAAoB,GAAG,WAAW,CAAC;AACzC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAElC;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,mBAAmB,CAAC;AAErD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,WAAW,CAAC;AAErC,qFAAqF;AACrF,SAAS,cAAc,CAAC,KAAa,EAAiB;IACrD,MAAM,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAC9C,IAAI,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IACpB,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACvB,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;QAAE,OAAO,KAAK,CAAC,UAAU,CAAC;IAC1C,IAAI,CAAC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CAAC,CAAC;YACvC,IAAI,MAAM,EAAE,CAAC;gBACZ,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;gBACnB,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC;YACtB,CAAC;iBAAM,CAAC;gBACP,MAAM,CAAC,KAAK,EAAE,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAChD,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC7B,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACrC,CAAC;YAED,IAAI,CAAC,IAAI,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrC,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,+DAA+D,EAAE,SAAS,CAAC,CAAC;gBAC1F,OAAO;YACR,CAAC;YACD,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,8DAA4D,EAAE,SAAS,CAAC,CAAC;gBACvF,OAAO;YACR,CAAC;YAED,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;YAC3D,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,aAAa,IAAI,CAAC,EAAE,MAAM,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,SAAO,MAAM,8CAA4C,IAAI,CAAC,EAAE,GAAG,EACtI,MAAM,CACN,CAAC;QAAA,CACF;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * /loop — cron scheduler, Cron* tools, and autonomous continuation.\n *\n * `/loop` schedules prompts via cron and drives autonomous continuation. The same\n * scheduler backs the agent-callable CronCreate/CronList/CronDelete tools.\n *\n * /loop \"<cron>\" <prompt> schedule recurring (5-field cron, local time)\n * /loop <5m|2h|1d> <prompt> schedule recurring at a simple interval\n * /loop once \"<cron>\" <prompt> schedule a one-shot\n * /loop list | /loop delete <id> | /loop stop\n * /loop auto [--max-turns N] <task> keep iterating until the task says LOOP_DONE\n */\n\nimport { join } from \"node:path\";\nimport { Type } from \"typebox\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { defineTool } from \"../../core/extensions/types.js\";\nimport { TaskScheduler } from \"../../core/scheduler.js\";\n\nconst AUTO_LOOP_DONE_TOKEN = \"LOOP_DONE\";\nconst DEFAULT_AUTO_MAX_TURNS = 10;\n\n/**\n * Event-bus channel: the autonomous-loop active state changed.\n * Payload: `{ active: boolean }`. Emitted whenever `/loop auto` starts or stops\n * so other extensions (e.g. ask_options) can adapt to running unattended.\n */\nexport const LOOP_AUTO_CHANGED = \"loop:auto-changed\";\n\n/**\n * Event-bus channel: request to halt the autonomous loop.\n * Payload: `{ reason: string }`. Sent by another extension when it hits a\n * blocker that requires a human decision the loop cannot safely make on its own.\n */\nexport const LOOP_HALT = \"loop:halt\";\n\n/** Convert a simple interval token (\"5m\", \"2h\", \"1d\") to a 5-field cron, or null. */\nfunction intervalToCron(token: string): string | null {\n\tconst m = /^(\\d+)(m|h|d)$/.exec(token.trim());\n\tif (!m) return null;\n\tconst n = Number(m[1]);\n\tif (n < 1) return null;\n\tif (m[2] === \"m\") return `*/${n} * * * *`;\n\tif (m[2] === \"h\") return `0 */${n} * * *`;\n\treturn `0 0 */${n} * *`; // days\n}\n\n/** Pull a quoted cron expression off the front of an argument string. */\nfunction extractQuotedCron(args: string): { cron: string; rest: string } | null {\n\tconst m = /^\"([^\"]+)\"\\s*(.*)$/.exec(args.trim());\n\treturn m ? { cron: m[1].trim(), rest: m[2].trim() } : null;\n}\n\nfunction isFiveFieldCron(expr: string): boolean {\n\treturn expr.trim().split(/\\s+/).length === 5;\n}\n\n/** Flatten an assistant message's text blocks. */\nfunction assistantText(message: { content: unknown }): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter((b): b is { type: \"text\"; text: string } => !!b && (b as { type?: string }).type === \"text\")\n\t\t.map((b) => b.text)\n\t\t.join(\"\\n\");\n}\n\nexport function setupLoop(pi: ExtensionAPI): void {\n\tlet scheduler: TaskScheduler | undefined;\n\tlet auto: { remaining: number } | null = null;\n\tlet activeCtx: ExtensionContext | undefined;\n\n\t/** Set the autonomous-loop state and broadcast the active flag on the bus. */\n\tfunction setAuto(next: { remaining: number } | null): void {\n\t\tconst was = auto !== null;\n\t\tauto = next;\n\t\tif (was !== (next !== null)) pi.events.emit(LOOP_AUTO_CHANGED, { active: next !== null });\n\t}\n\n\t// Another extension (e.g. ask_options) hit a decision it cannot safely make\n\t// while unattended. Stop iterating and let the model report the blocker.\n\tpi.events.on(LOOP_HALT, (data) => {\n\t\tif (!auto) return;\n\t\tconst reason = (data as { reason?: string })?.reason?.trim() || \"a decision that needs the user.\";\n\t\tsetAuto(null);\n\t\tactiveCtx?.ui.notify(`Autonomous loop halted: ${reason}`, \"warning\");\n\t});\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\tactiveCtx = ctx;\n\t\tif (scheduler) return;\n\t\tconst isIdle = () => {\n\t\t\ttry {\n\t\t\t\treturn ctx.isIdle();\n\t\t\t} catch {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\t\tscheduler = new TaskScheduler({\n\t\t\t// `.agents/` is the primary, cross-vendor home; the legacy `.hoocode/`\n\t\t\t// store is read once and migrates forward on the next persist.\n\t\t\tstorePath: join(ctx.cwd, \".agents\", \"scheduled_tasks.json\"),\n\t\t\tlegacyStorePath: join(ctx.cwd, \".hoocode\", \"scheduled_tasks.json\"),\n\t\t\tfire: (prompt) => pi.sendUserMessage(prompt, { deliverAs: \"followUp\" }),\n\t\t\tisIdle,\n\t\t});\n\t\tscheduler.start();\n\t});\n\n\tpi.on(\"session_shutdown\", () => {\n\t\tscheduler?.stop();\n\t\tsetAuto(null);\n\t});\n\n\t// Autonomous continuation: re-prompt on each agent_end until LOOP_DONE or budget.\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tif (!auto) return;\n\t\tif (ctx.hasPendingMessages()) return; // user is steering — yield\n\t\tconst last = [...event.messages].reverse().find((m) => m.role === \"assistant\");\n\t\tconst text = last ? assistantText(last) : \"\";\n\t\tif (text.includes(AUTO_LOOP_DONE_TOKEN)) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop complete.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (auto.remaining <= 0) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop stopped: max turns reached.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tauto.remaining -= 1;\n\t\tpi.sendUserMessage(`Continue working toward the goal. Reply with ${AUTO_LOOP_DONE_TOKEN} when fully complete.`, {\n\t\t\tdeliverAs: \"followUp\",\n\t\t});\n\t});\n\n\t// ── Cron* tools (agent-callable) ──────────────────────────────────────────\n\tconst toolText = (s: string) => ({ content: [{ type: \"text\" as const, text: s }], details: undefined });\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronCreate\",\n\t\t\tlabel: \"Schedule Task\",\n\t\t\tdescription:\n\t\t\t\t\"Schedule a prompt to be re-submitted on a cron schedule (5-field, local time: minute hour day-of-month month day-of-week). recurring=false fires once then deletes.\",\n\t\t\tparameters: Type.Object({\n\t\t\t\tcron: Type.String({ description: \"5-field cron expression in local time\" }),\n\t\t\t\tprompt: Type.String({ description: \"Prompt to enqueue at each fire time\" }),\n\t\t\t\trecurring: Type.Optional(Type.Boolean({ description: \"Fire repeatedly (default true) or once\" })),\n\t\t\t}),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tif (!scheduler) return toolText(\"Scheduler not ready.\");\n\t\t\t\tif (!isFiveFieldCron(params.cron)) return toolText(`Invalid cron \"${params.cron}\" (need 5 fields).`);\n\t\t\t\tconst task = scheduler.create({\n\t\t\t\t\tcron: params.cron,\n\t\t\t\t\tprompt: params.prompt,\n\t\t\t\t\trecurring: params.recurring ?? true,\n\t\t\t\t});\n\t\t\t\treturn toolText(`Scheduled ${task.id}: \"${task.cron}\" (${task.recurring ? \"recurring\" : \"once\"})`);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronList\",\n\t\t\tlabel: \"List Scheduled Tasks\",\n\t\t\tdescription: \"List all scheduled tasks (id, cron, recurring, prompt).\",\n\t\t\tparameters: Type.Object({}),\n\t\t\tasync execute() {\n\t\t\t\tconst tasks = scheduler?.list() ?? [];\n\t\t\t\tif (tasks.length === 0) return toolText(\"No scheduled tasks.\");\n\t\t\t\treturn toolText(\n\t\t\t\t\ttasks\n\t\t\t\t\t\t.map((t) => `${t.id} ${t.cron} ${t.recurring ? \"recurring\" : \"once\"} ${JSON.stringify(t.prompt)}`)\n\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronDelete\",\n\t\t\tlabel: \"Delete Scheduled Task\",\n\t\t\tdescription: \"Delete a scheduled task by id.\",\n\t\t\tparameters: Type.Object({ id: Type.String({ description: \"Task id from CronCreate/CronList\" }) }),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tconst removed = scheduler?.delete(params.id) ?? false;\n\t\t\t\treturn toolText(removed ? `Deleted ${params.id}.` : `No task ${params.id}.`);\n\t\t\t},\n\t\t}),\n\t);\n\n\t// ── /loop command ─────────────────────────────────────────────────────────\n\tpi.registerCommand(\"loop\", {\n\t\tdescription:\n\t\t\t'Schedule prompts via cron or run an autonomous loop. /loop \"<cron>\" <prompt> | /loop <5m|2h> <prompt> | /loop once \"<cron>\" <prompt> | /loop list | /loop delete <id> | /loop stop | /loop auto [--max-turns N] <task>',\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\t[\"list\", \"delete\", \"stop\", \"once\", \"auto\"]\n\t\t\t\t.filter((s) => s.startsWith(prefix))\n\t\t\t\t.map((s) => ({ value: s, label: s })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tif (!scheduler) {\n\t\t\t\tctx.ui.notify(\"Scheduler not ready yet.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!trimmed || trimmed === \"list\") {\n\t\t\t\tconst tasks = scheduler.list();\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\ttasks.length === 0\n\t\t\t\t\t\t? auto\n\t\t\t\t\t\t\t? `Autonomous loop active (${auto.remaining} turns left).`\n\t\t\t\t\t\t\t: \"No scheduled tasks.\"\n\t\t\t\t\t\t: tasks.map((t) => `${t.id}: ${t.cron} ${t.recurring ? \"\" : \"(once) \"}— ${t.prompt}`).join(\"\\n\"),\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed === \"stop\") {\n\t\t\t\tconst had = scheduler.list().length > 0 || auto !== null;\n\t\t\t\tscheduler.clear();\n\t\t\t\tsetAuto(null);\n\t\t\t\tctx.ui.notify(had ? \"Stopped all loops and scheduled tasks.\" : \"Nothing to stop.\", \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"delete\")) {\n\t\t\t\tconst id = trimmed.slice(\"delete\".length).trim();\n\t\t\t\tif (!id) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop delete <id>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tctx.ui.notify(scheduler.delete(id) ? `Deleted ${id}.` : `No task ${id}.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"auto\")) {\n\t\t\t\tlet rest = trimmed.slice(\"auto\".length).trim();\n\t\t\t\tlet maxTurns = DEFAULT_AUTO_MAX_TURNS;\n\t\t\t\tconst flag = /^--max-turns\\s+(\\d+)\\s*(.*)$/.exec(rest);\n\t\t\t\tif (flag) {\n\t\t\t\t\tmaxTurns = Number(flag[1]);\n\t\t\t\t\trest = flag[2].trim();\n\t\t\t\t}\n\t\t\t\tif (!rest) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop auto [--max-turns N] <task>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsetAuto({ remaining: maxTurns });\n\t\t\t\tpi.sendUserMessage(\n\t\t\t\t\t`${rest}\\n\\n(Autonomous loop: keep working until the task is fully complete, then reply with ${AUTO_LOOP_DONE_TOKEN}.)`,\n\t\t\t\t\t{ deliverAs: \"followUp\" },\n\t\t\t\t);\n\t\t\t\tctx.ui.notify(`Autonomous loop started (max ${maxTurns} turns). Stop with /loop stop.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Scheduling: one-shot or recurring, via quoted cron or interval token.\n\t\t\tlet recurring = true;\n\t\t\tlet body = trimmed;\n\t\t\tif (body.startsWith(\"once\")) {\n\t\t\t\trecurring = false;\n\t\t\t\tbody = body.slice(\"once\".length).trim();\n\t\t\t}\n\n\t\t\tlet cron: string | null = null;\n\t\t\tlet prompt = \"\";\n\t\t\tconst quoted = extractQuotedCron(body);\n\t\t\tif (quoted) {\n\t\t\t\tcron = quoted.cron;\n\t\t\t\tprompt = quoted.rest;\n\t\t\t} else {\n\t\t\t\tconst [first, ...restWords] = body.split(/\\s+/);\n\t\t\t\tcron = intervalToCron(first);\n\t\t\t\tprompt = restWords.join(\" \").trim();\n\t\t\t}\n\n\t\t\tif (!cron || !isFiveFieldCron(cron)) {\n\t\t\t\tctx.ui.notify('Usage: /loop \"<cron>\" <prompt> or /loop <5m|2h|1d> <prompt>', \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!prompt) {\n\t\t\t\tctx.ui.notify(\"Nothing to schedule — provide a prompt after the schedule.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst task = scheduler.create({ cron, prompt, recurring });\n\t\t\tctx.ui.notify(\n\t\t\t\t`Scheduled ${task.id}: \"${cron}\" ${recurring ? \"recurring\" : \"once\"} — \"${prompt}\". Manage with /loop list • /loop delete ${task.id}.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../../../src/extensions/core/loop.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAO/B,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAExD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,oBAAoB,GAAG,WAAW,CAAC;AAChD,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAElC;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,mBAAmB,CAAC;AAErD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,WAAW,CAAC;AAErC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAgBjD,qFAAqF;AACrF,SAAS,cAAc,CAAC,KAAa,EAAiB;IACrD,MAAM,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAC9C,IAAI,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IACpB,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvB,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;I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G,SAAS,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAChD,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;gBAC7B,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACrC,CAAC;YAED,IAAI,CAAC,IAAI,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrC,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,+DAA+D,EAAE,SAAS,CAAC,CAAC;gBAC1F,OAAO;YACR,CAAC;YACD,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,8DAA4D,EAAE,SAAS,CAAC,CAAC;gBACvF,OAAO;YACR,CAAC;YAED,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;YAC3D,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,aAAa,IAAI,CAAC,EAAE,MAAM,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,SAAO,MAAM,8CAA4C,IAAI,CAAC,EAAE,GAAG,EACtI,MAAM,CACN,CAAC;QAAA,CACF;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * /loop — cron scheduler, Cron* tools, and autonomous continuation.\n *\n * `/loop` schedules prompts via cron and drives autonomous continuation. The same\n * scheduler backs the agent-callable CronCreate/CronList/CronDelete tools.\n *\n * /loop \"<cron>\" <prompt> schedule recurring (5-field cron, local time)\n * /loop <5m|2h|1d> <prompt> schedule recurring at a simple interval\n * /loop once \"<cron>\" <prompt> schedule a one-shot\n * /loop list | /loop delete <id> | /loop stop\n * /loop auto [--max-turns N] <task> keep iterating until the task says LOOP_DONE\n */\n\nimport { join } from \"node:path\";\nimport { Type } from \"typebox\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { defineTool } from \"../../core/extensions/types.js\";\nimport { TaskScheduler } from \"../../core/scheduler.js\";\n\n/** Sentinel the agent replies with to declare the autonomous loop finished. */\nexport const AUTO_LOOP_DONE_TOKEN = \"LOOP_DONE\";\nconst DEFAULT_AUTO_MAX_TURNS = 10;\n\n/**\n * Event-bus channel: the autonomous-loop active state changed.\n * Payload: `{ active: boolean }`. Emitted whenever `/loop auto` starts or stops\n * so other extensions (e.g. ask_options) can adapt to running unattended.\n */\nexport const LOOP_AUTO_CHANGED = \"loop:auto-changed\";\n\n/**\n * Event-bus channel: request to halt the autonomous loop.\n * Payload: `{ reason: string }`. Sent by another extension when it hits a\n * blocker that requires a human decision the loop cannot safely make on its own.\n */\nexport const LOOP_HALT = \"loop:halt\";\n\n/**\n * Event-bus channel: start the autonomous loop.\n * Payload: {@link LoopAutoStartPayload}. Mirrors LOOP_HALT in the opposite\n * direction, letting another extension (e.g. `/goal`) drive the loop without\n * reaching into state that lives inside this module's closure.\n */\nexport const LOOP_AUTO_START = \"loop:auto-start\";\n\n/** Payload for {@link LOOP_AUTO_START}. */\nexport interface LoopAutoStartPayload {\n\t/** The task to work toward, delivered as the loop's first user message. */\n\ttask: string;\n\t/** Turn budget before the loop stops itself. Defaults to 10. */\n\tmaxTurns?: number;\n\t/**\n\t * Message re-sent on each continuation. Callers with a concrete completion\n\t * condition should restate it here, so the target does not drift out of view\n\t * as the transcript grows. Defaults to a generic nudge.\n\t */\n\tcontinuePrompt?: string;\n}\n\n/** Convert a simple interval token (\"5m\", \"2h\", \"1d\") to a 5-field cron, or null. */\nfunction intervalToCron(token: string): string | null {\n\tconst m = /^(\\d+)(m|h|d)$/.exec(token.trim());\n\tif (!m) return null;\n\tconst n = Number(m[1]);\n\tif (n < 1) return null;\n\tif (m[2] === \"m\") return `*/${n} * * * *`;\n\tif (m[2] === \"h\") return `0 */${n} * * *`;\n\treturn `0 0 */${n} * *`; // days\n}\n\n/** Pull a quoted cron expression off the front of an argument string. */\nfunction extractQuotedCron(args: string): { cron: string; rest: string } | null {\n\tconst m = /^\"([^\"]+)\"\\s*(.*)$/.exec(args.trim());\n\treturn m ? { cron: m[1].trim(), rest: m[2].trim() } : null;\n}\n\nfunction isFiveFieldCron(expr: string): boolean {\n\treturn expr.trim().split(/\\s+/).length === 5;\n}\n\n/** Flatten an assistant message's text blocks. */\nfunction assistantText(message: { content: unknown }): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter((b): b is { type: \"text\"; text: string } => !!b && (b as { type?: string }).type === \"text\")\n\t\t.map((b) => b.text)\n\t\t.join(\"\\n\");\n}\n\nexport function setupLoop(pi: ExtensionAPI): void {\n\tlet scheduler: TaskScheduler | undefined;\n\tlet auto: { remaining: number; continuePrompt?: string } | null = null;\n\tlet activeCtx: ExtensionContext | undefined;\n\n\t/** Set the autonomous-loop state and broadcast the active flag on the bus. */\n\tfunction setAuto(next: { remaining: number; continuePrompt?: string } | null): void {\n\t\tconst was = auto !== null;\n\t\tauto = next;\n\t\tif (was !== (next !== null)) pi.events.emit(LOOP_AUTO_CHANGED, { active: next !== null });\n\t}\n\n\t/**\n\t * Arms the turn budget and delivers the task. Shared by `/loop auto` and the\n\t * LOOP_AUTO_START channel so both start from identical state. Returns the\n\t * budget actually applied, for the caller's notification.\n\t *\n\t * A caller-supplied 0 is honoured (the loop stops at the first continuation);\n\t * only a missing or nonsensical budget falls back to the default.\n\t */\n\tfunction startAuto({ task, maxTurns, continuePrompt }: LoopAutoStartPayload): number {\n\t\tconst budget =\n\t\t\ttypeof maxTurns === \"number\" && Number.isFinite(maxTurns) && maxTurns >= 0 ? maxTurns : DEFAULT_AUTO_MAX_TURNS;\n\t\tsetAuto({ remaining: budget, continuePrompt });\n\t\tpi.sendUserMessage(\n\t\t\t`${task}\\n\\n(Autonomous loop: keep working until the task is fully complete, then reply with ${AUTO_LOOP_DONE_TOKEN}.)`,\n\t\t\t{ deliverAs: \"followUp\" },\n\t\t);\n\t\treturn budget;\n\t}\n\n\t// Another extension asked for an autonomous run. Ignore payloads without a\n\t// task rather than arming a loop with nothing to work on.\n\tpi.events.on(LOOP_AUTO_START, (data) => {\n\t\tconst payload = (data ?? {}) as Partial<LoopAutoStartPayload>;\n\t\tconst task = payload.task?.trim();\n\t\tif (!task) return;\n\t\tconst budget = startAuto({ task, maxTurns: payload.maxTurns, continuePrompt: payload.continuePrompt });\n\t\tactiveCtx?.ui.notify(`Autonomous loop started (max ${budget} turns). Stop with /loop stop.`, \"info\");\n\t});\n\n\t// Another extension (e.g. ask_options) hit a decision it cannot safely make\n\t// while unattended. Stop iterating and let the model report the blocker.\n\tpi.events.on(LOOP_HALT, (data) => {\n\t\tif (!auto) return;\n\t\tconst reason = (data as { reason?: string })?.reason?.trim() || \"a decision that needs the user.\";\n\t\tsetAuto(null);\n\t\tactiveCtx?.ui.notify(`Autonomous loop halted: ${reason}`, \"warning\");\n\t});\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\tactiveCtx = ctx;\n\t\tif (scheduler) return;\n\t\tconst isIdle = () => {\n\t\t\ttry {\n\t\t\t\treturn ctx.isIdle();\n\t\t\t} catch {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\t\tscheduler = new TaskScheduler({\n\t\t\t// `.agents/` is the primary, cross-vendor home; the legacy `.hoocode/`\n\t\t\t// store is read once and migrates forward on the next persist.\n\t\t\tstorePath: join(ctx.cwd, \".agents\", \"scheduled_tasks.json\"),\n\t\t\tlegacyStorePath: join(ctx.cwd, \".hoocode\", \"scheduled_tasks.json\"),\n\t\t\tfire: (prompt) => pi.sendUserMessage(prompt, { deliverAs: \"followUp\" }),\n\t\t\tisIdle,\n\t\t});\n\t\tscheduler.start();\n\t});\n\n\tpi.on(\"session_shutdown\", () => {\n\t\tscheduler?.stop();\n\t\tsetAuto(null);\n\t});\n\n\t// Autonomous continuation: re-prompt on each agent_end until LOOP_DONE or budget.\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tif (!auto) return;\n\t\tif (ctx.hasPendingMessages()) return; // user is steering — yield\n\t\tconst last = [...event.messages].reverse().find((m) => m.role === \"assistant\");\n\t\tconst text = last ? assistantText(last) : \"\";\n\t\tif (text.includes(AUTO_LOOP_DONE_TOKEN)) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop complete.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (auto.remaining <= 0) {\n\t\t\tsetAuto(null);\n\t\t\tctx.ui.notify(\"Autonomous loop stopped: max turns reached.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tauto.remaining -= 1;\n\t\tpi.sendUserMessage(\n\t\t\tauto.continuePrompt ??\n\t\t\t\t`Continue working toward the goal. Reply with ${AUTO_LOOP_DONE_TOKEN} when fully complete.`,\n\t\t\t{ deliverAs: \"followUp\" },\n\t\t);\n\t});\n\n\t// ── Cron* tools (agent-callable) ──────────────────────────────────────────\n\tconst toolText = (s: string) => ({ content: [{ type: \"text\" as const, text: s }], details: undefined });\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronCreate\",\n\t\t\tlabel: \"Schedule Task\",\n\t\t\tdescription:\n\t\t\t\t\"Schedule a prompt to be re-submitted on a cron schedule (5-field, local time: minute hour day-of-month month day-of-week). recurring=false fires once then deletes.\",\n\t\t\tparameters: Type.Object({\n\t\t\t\tcron: Type.String({ description: \"5-field cron expression in local time\" }),\n\t\t\t\tprompt: Type.String({ description: \"Prompt to enqueue at each fire time\" }),\n\t\t\t\trecurring: Type.Optional(Type.Boolean({ description: \"Fire repeatedly (default true) or once\" })),\n\t\t\t}),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tif (!scheduler) return toolText(\"Scheduler not ready.\");\n\t\t\t\tif (!isFiveFieldCron(params.cron)) return toolText(`Invalid cron \"${params.cron}\" (need 5 fields).`);\n\t\t\t\tconst task = scheduler.create({\n\t\t\t\t\tcron: params.cron,\n\t\t\t\t\tprompt: params.prompt,\n\t\t\t\t\trecurring: params.recurring ?? true,\n\t\t\t\t});\n\t\t\t\treturn toolText(`Scheduled ${task.id}: \"${task.cron}\" (${task.recurring ? \"recurring\" : \"once\"})`);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronList\",\n\t\t\tlabel: \"List Scheduled Tasks\",\n\t\t\tdescription: \"List all scheduled tasks (id, cron, recurring, prompt).\",\n\t\t\tparameters: Type.Object({}),\n\t\t\tasync execute() {\n\t\t\t\tconst tasks = scheduler?.list() ?? [];\n\t\t\t\tif (tasks.length === 0) return toolText(\"No scheduled tasks.\");\n\t\t\t\treturn toolText(\n\t\t\t\t\ttasks\n\t\t\t\t\t\t.map((t) => `${t.id} ${t.cron} ${t.recurring ? \"recurring\" : \"once\"} ${JSON.stringify(t.prompt)}`)\n\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t);\n\t\t\t},\n\t\t}),\n\t);\n\n\tpi.registerTool(\n\t\tdefineTool({\n\t\t\tname: \"CronDelete\",\n\t\t\tlabel: \"Delete Scheduled Task\",\n\t\t\tdescription: \"Delete a scheduled task by id.\",\n\t\t\tparameters: Type.Object({ id: Type.String({ description: \"Task id from CronCreate/CronList\" }) }),\n\t\t\tasync execute(_id, params) {\n\t\t\t\tconst removed = scheduler?.delete(params.id) ?? false;\n\t\t\t\treturn toolText(removed ? `Deleted ${params.id}.` : `No task ${params.id}.`);\n\t\t\t},\n\t\t}),\n\t);\n\n\t// ── /loop command ─────────────────────────────────────────────────────────\n\tpi.registerCommand(\"loop\", {\n\t\tdescription:\n\t\t\t'Schedule prompts via cron or run an autonomous loop. /loop \"<cron>\" <prompt> | /loop <5m|2h> <prompt> | /loop once \"<cron>\" <prompt> | /loop list | /loop delete <id> | /loop stop | /loop auto [--max-turns N] <task>',\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\t[\"list\", \"delete\", \"stop\", \"once\", \"auto\"]\n\t\t\t\t.filter((s) => s.startsWith(prefix))\n\t\t\t\t.map((s) => ({ value: s, label: s })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst trimmed = args.trim();\n\t\t\tif (!scheduler) {\n\t\t\t\tctx.ui.notify(\"Scheduler not ready yet.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!trimmed || trimmed === \"list\") {\n\t\t\t\tconst tasks = scheduler.list();\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\ttasks.length === 0\n\t\t\t\t\t\t? auto\n\t\t\t\t\t\t\t? `Autonomous loop active (${auto.remaining} turns left).`\n\t\t\t\t\t\t\t: \"No scheduled tasks.\"\n\t\t\t\t\t\t: tasks.map((t) => `${t.id}: ${t.cron} ${t.recurring ? \"\" : \"(once) \"}— ${t.prompt}`).join(\"\\n\"),\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed === \"stop\") {\n\t\t\t\tconst had = scheduler.list().length > 0 || auto !== null;\n\t\t\t\tscheduler.clear();\n\t\t\t\tsetAuto(null);\n\t\t\t\tctx.ui.notify(had ? \"Stopped all loops and scheduled tasks.\" : \"Nothing to stop.\", \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"delete\")) {\n\t\t\t\tconst id = trimmed.slice(\"delete\".length).trim();\n\t\t\t\tif (!id) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop delete <id>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tctx.ui.notify(scheduler.delete(id) ? `Deleted ${id}.` : `No task ${id}.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (trimmed.startsWith(\"auto\")) {\n\t\t\t\tlet rest = trimmed.slice(\"auto\".length).trim();\n\t\t\t\tlet maxTurns = DEFAULT_AUTO_MAX_TURNS;\n\t\t\t\tconst flag = /^--max-turns\\s+(\\d+)\\s*(.*)$/.exec(rest);\n\t\t\t\tif (flag) {\n\t\t\t\t\tmaxTurns = Number(flag[1]);\n\t\t\t\t\trest = flag[2].trim();\n\t\t\t\t}\n\t\t\t\tif (!rest) {\n\t\t\t\t\tctx.ui.notify(\"Usage: /loop auto [--max-turns N] <task>\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstartAuto({ task: rest, maxTurns });\n\t\t\t\tctx.ui.notify(`Autonomous loop started (max ${maxTurns} turns). Stop with /loop stop.`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Scheduling: one-shot or recurring, via quoted cron or interval token.\n\t\t\tlet recurring = true;\n\t\t\tlet body = trimmed;\n\t\t\tif (body.startsWith(\"once\")) {\n\t\t\t\trecurring = false;\n\t\t\t\tbody = body.slice(\"once\".length).trim();\n\t\t\t}\n\n\t\t\tlet cron: string | null = null;\n\t\t\tlet prompt = \"\";\n\t\t\tconst quoted = extractQuotedCron(body);\n\t\t\tif (quoted) {\n\t\t\t\tcron = quoted.cron;\n\t\t\t\tprompt = quoted.rest;\n\t\t\t} else {\n\t\t\t\tconst [first, ...restWords] = body.split(/\\s+/);\n\t\t\t\tcron = intervalToCron(first);\n\t\t\t\tprompt = restWords.join(\" \").trim();\n\t\t\t}\n\n\t\t\tif (!cron || !isFiveFieldCron(cron)) {\n\t\t\t\tctx.ui.notify('Usage: /loop \"<cron>\" <prompt> or /loop <5m|2h|1d> <prompt>', \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!prompt) {\n\t\t\t\tctx.ui.notify(\"Nothing to schedule — provide a prompt after the schedule.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst task = scheduler.create({ cron, prompt, recurring });\n\t\t\tctx.ui.notify(\n\t\t\t\t`Scheduled ${task.id}: \"${cron}\" ${recurring ? \"recurring\" : \"once\"} — \"${prompt}\". Manage with /loop list • /loop delete ${task.id}.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Mode system — resolves the active mode (ask/plan/build/debug), loads the
3
3
  * mode's system prompt, filters active tools, and exposes the /mode, /plan,
4
- * and /approve commands.
4
+ * /grill, /goal, and /approve commands.
5
5
  *
6
6
  * Mode prompt search order (first hit wins):
7
7
  * - `./.hoocode/modes/{mode}/system.md`
@@ -52,5 +52,56 @@ export declare function parsePlanSections(planContent: string): PlanSections;
52
52
  * 4. Run verification commands
53
53
  */
54
54
  export declare function buildApproveMessage(sections: PlanSections): string;
55
+ /** Which half (or both) of the grill flow to run. */
56
+ export type GrillTarget = "both" | "me" | "plan";
57
+ /**
58
+ * Parses the `/grill` argument into a target.
59
+ *
60
+ * Bare `/grill` runs both phases, `/grill me` only questions the user, and
61
+ * `/grill plan` only critiques the plan. Anything else returns undefined so the
62
+ * caller shows usage rather than guessing at intent.
63
+ */
64
+ export declare function parseGrillTarget(args: string): GrillTarget | undefined;
65
+ /**
66
+ * Builds the follow-up message injected by `/grill`.
67
+ *
68
+ * The two phases are ordered rather than alternative: underspecification sits
69
+ * upstream of plan weakness, so critiquing a plan built on a misread request
70
+ * produces a well-reviewed plan for the wrong job. Bare `/grill` therefore asks
71
+ * first and folds the answers into the critique.
72
+ */
73
+ export declare function buildGrillMessage(sections: PlanSections, target: GrillTarget): string;
74
+ /** A parsed `/goal` invocation. */
75
+ export interface GoalInvocation {
76
+ /** Explicit objective; falls back to the plan's Goal section when absent. */
77
+ objective?: string;
78
+ /** Turn budget passed through to the autonomous loop. */
79
+ maxTurns?: number;
80
+ }
81
+ /**
82
+ * Parses `/goal [--max-turns N] [objective]`.
83
+ *
84
+ * Returns undefined when `--max-turns` is present but not followed by a
85
+ * non-negative integer, so the caller shows usage instead of silently running
86
+ * with the default budget.
87
+ */
88
+ export declare function parseGoalArgs(args: string): GoalInvocation | undefined;
89
+ /** The two messages `/goal` hands to the autonomous loop. */
90
+ export interface GoalMessages {
91
+ /** Delivered once, to start the run. */
92
+ task: string;
93
+ /** Re-sent on each continuation to keep the target in view. */
94
+ continuePrompt: string;
95
+ }
96
+ /**
97
+ * Builds the messages for a `/goal` run.
98
+ *
99
+ * When the plan carries a Verification section it becomes the completion
100
+ * condition, which is the difference between a loop that stops when it feels
101
+ * finished and one that stops when something it can run says so. Both messages
102
+ * restate the objective, because the loop's continuation prompt is all that
103
+ * holds the target in place as the transcript grows.
104
+ */
105
+ export declare function buildGoalMessages(objective: string, verification?: string): GoalMessages;
55
106
  export declare function setupMode(pi: ExtensionAPI): void;
56
107
  //# sourceMappingURL=modes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modes.d.ts","sourceRoot":"","sources":["../../../src/extensions/core/modes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,OAAO,KAAK,EAGX,YAAY,EAIZ,MAAM,gCAAgC,CAAC;AA+CxC;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG,MAAM,GAAG,SAAS,CAGnH;AAMD,MAAM,WAAW,YAAY;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;CACZ;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,YAAY,CA2BnE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,YAAY,GAAG,MAAM,CAwBlE;AAMD,wBAAgB,SAAS,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAoJhD","sourcesContent":["/**\n * Mode system — resolves the active mode (ask/plan/build/debug), loads the\n * mode's system prompt, filters active tools, and exposes the /mode, /plan,\n * and /approve commands.\n *\n * Mode prompt search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each configured/contributed external dir in declared order\n * - built-in MODE_DEFAULTS for the four known modes\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { getHooCodeDir } from \"../../config.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { isLightModeEnv } from \"../../core/light.js\";\nimport { DEFAULT_MODE, DEFAULT_MODE_PROMPTS as MODE_DEFAULTS } from \"../../core/mode-prompts.js\";\nimport { mergeSearchPaths, readConfig, readMergedConfig, writeConfig } from \"./config.js\";\n\nconst HOOCODE_DIR = getHooCodeDir();\n\n/**\n * Per-session plan file path. Keying on sessionId lets concurrent or resumed\n * plan sessions keep distinct plans instead of clobbering each other.\n */\nfunction getPlanPath(cwd: string, sessionId: string): string {\n\treturn join(cwd, \".hoocode\", \"plans\", `${sessionId}.md`);\n}\n\n/** Legacy single-file plan location, retained as a read-only fallback for /approve. */\nfunction getLegacyPlanPath(cwd: string): string {\n\treturn join(cwd, \".hoocode\", \"plan.md\");\n}\n\nfunction tryReadFile(path: string): string | undefined {\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst text = readFileSync(path, \"utf8\").trim();\n\t\treturn text || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Walks search dirs in precedence order and returns the first existing\n * `modes/{name}/system.md` content. Order: project → user → externalDirs.\n */\nfunction resolveModeFile(name: string, cwd: string, externalDirs: string[]): string | undefined {\n\tconst candidates: string[] = [\n\t\tjoin(cwd, \".hoocode\", \"modes\", name, \"system.md\"),\n\t\tjoin(HOOCODE_DIR, \"modes\", name, \"system.md\"),\n\t\t...externalDirs.map((dir) => join(dir, name, \"system.md\")),\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst content = tryReadFile(candidate);\n\t\tif (content !== undefined) return content;\n\t}\n\treturn undefined;\n}\n\n/**\n * Returns the system prompt for the active mode.\n *\n * Search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each of `externalDirs` in declared order (config + CLI + extension contributions)\n * - built-in MODE_DEFAULTS for the four known modes\n */\nexport function buildSystemPrompt(mode: string, cwd: string, options?: { modePaths?: string[] }): string | undefined {\n\tconst modePaths = options?.modePaths ?? [];\n\treturn resolveModeFile(mode, cwd, modePaths) ?? MODE_DEFAULTS[mode];\n}\n\n// ============================================================================\n// Plan file: section parsing and step-by-step execution message\n// ============================================================================\n\nexport interface PlanSections {\n\tgoal?: string;\n\tfilesToModify?: string;\n\tnewFiles?: string;\n\ttests?: string;\n\tverification?: string;\n\t/** Original full text, used as fallback if no sections parsed */\n\traw: string;\n}\n\n/**\n * Parses `.hoocode/plan.md` into named sections.\n *\n * Recognises both ATX headings (`## Goal`) and bold labels (`**Goal**`).\n * Section names matched (case-insensitive): Goal, Files to modify, New files,\n * Tests, Verification.\n */\nexport function parsePlanSections(planContent: string): PlanSections {\n\tconst result: PlanSections = { raw: planContent };\n\n\t// Match `## Heading text` or `**Heading text**` followed by content until\n\t// the next heading of the same style.\n\tconst sectionPattern =\n\t\t/^(?:#{1,3}\\s+(.+?)|(?:\\*\\*(.+?)\\*\\*))\\s*\\n([\\s\\S]*?)(?=(?:^#{1,3}\\s+|\\*\\*[^*\\n]+\\*\\*\\s*\\n)|$)/gm;\n\n\tfor (const match of planContent.matchAll(sectionPattern)) {\n\t\tconst heading = (match[1] ?? match[2] ?? \"\").toLowerCase().trim();\n\t\tconst content = match[3].trim();\n\t\tif (!content) continue;\n\n\t\tif (/^goal/.test(heading)) {\n\t\t\tresult.goal = content;\n\t\t} else if (/files?\\s+to\\s+modif|^modif/.test(heading)) {\n\t\t\tresult.filesToModify = content;\n\t\t} else if (/new\\s+files?/.test(heading)) {\n\t\t\tresult.newFiles = content;\n\t\t} else if (/^tests?/.test(heading)) {\n\t\t\tresult.tests = content;\n\t\t} else if (/^verif/.test(heading)) {\n\t\t\tresult.verification = content;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Builds the user message sent to the agent when `/approve` is run.\n *\n * If the plan has recognisable sections, each is presented as a numbered step\n * so the agent works through them sequentially. Otherwise the raw plan is used.\n *\n * Execution order:\n * 1. Modify existing files\n * 2. Create new files\n * 3. Update / add tests\n * 4. Run verification commands\n */\nexport function buildApproveMessage(sections: PlanSections): string {\n\tconst steps: string[] = [];\n\n\tif (sections.goal) {\n\t\tsteps.push(`**Goal:** ${sections.goal}`);\n\t}\n\tif (sections.filesToModify) {\n\t\tsteps.push(`**Step 1 — Modify existing files:**\\n${sections.filesToModify}`);\n\t}\n\tif (sections.newFiles) {\n\t\tsteps.push(`**Step 2 — Create new files:**\\n${sections.newFiles}`);\n\t}\n\tif (sections.tests) {\n\t\tsteps.push(`**Step 3 — Update tests:**\\n${sections.tests}`);\n\t}\n\tif (sections.verification) {\n\t\tsteps.push(`**Step 4 — Verify:**\\n${sections.verification}`);\n\t}\n\n\tif (steps.length === 0) {\n\t\treturn `Execute the following plan:\\n\\n${sections.raw}`;\n\t}\n\n\treturn `Execute this plan step by step. Complete each step fully before moving to the next.\\n\\n${steps.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// setupMode\n// ============================================================================\n\nexport function setupMode(pi: ExtensionAPI): void {\n\tlet cachedMode = DEFAULT_MODE;\n\tlet cachedSystemPrompt: string | undefined;\n\tlet cachedPlanPath: string | undefined;\n\n\t// ── session_start ─────────────────────────────────────────────────────────\n\t// Config resolution order:\n\t// 1. Read global config (~/.hoocode/hoo-config.json)\n\t// 2. Read project config (./.hoocode/hoo-config.json) if present\n\t// 3. Merge — project scalars win; arrays are unioned\n\t// 4. Re-resolve active_mode from the merged result\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\t// Light mode strips every fixed prompt appendix. Leaving\n\t\t// cachedSystemPrompt unset makes before_agent_start a no-op, so no\n\t\t// `<!-- hoo-core: mode= -->` block is appended.\n\t\tif (isLightModeEnv()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Steps 1–3: merge global + project configs\n\t\tconst config = readMergedConfig(ctx.cwd);\n\n\t\t// Step 4: resolve mode from the merged config\n\t\tcachedMode = config.active_mode ?? DEFAULT_MODE;\n\t\t// External search dirs come from two channels:\n\t\t// - HooConfig.mode_paths (config-declared)\n\t\t// - pi.addModeSearchPath (CLI flags + extension contributions)\n\t\tconst modePaths = mergeSearchPaths(config.mode_paths, pi.getModeSearchPaths());\n\t\tconst rawSystemPrompt = buildSystemPrompt(cachedMode, ctx.cwd, { modePaths });\n\n\t\t// Per-session plan path so concurrent sessions don't overwrite each other.\n\t\t// The `{{PLAN_PATH}}` token in plan-mode templates is substituted here.\n\t\tcachedPlanPath = getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\tconst relPlanPath = relative(ctx.cwd, cachedPlanPath) || cachedPlanPath;\n\t\tcachedSystemPrompt = rawSystemPrompt?.replace(/\\{\\{PLAN_PATH\\}\\}/g, relPlanPath);\n\n\t\t// Update footer with active mode\n\t\tif (ctx.hasUI) {\n\t\t\tctx.ui.setMode(cachedMode);\n\t\t}\n\n\t\t// Apply tool filter from mode enabled_tools\n\t\tconst modeCfg = config.modes?.[cachedMode];\n\t\tif (modeCfg?.enabled_tools && modeCfg.enabled_tools.length > 0) {\n\t\t\tpi.setActiveTools(modeCfg.enabled_tools);\n\t\t}\n\t});\n\n\t// ── before_agent_start ────────────────────────────────────────────────────\n\n\tpi.on(\"before_agent_start\", (event: BeforeAgentStartEvent): BeforeAgentStartEventResult | undefined => {\n\t\tif (!cachedSystemPrompt) return;\n\t\treturn {\n\t\t\tsystemPrompt: `${event.systemPrompt}\\n\\n<!-- hoo-core: mode=${cachedMode} -->\\n${cachedSystemPrompt}`,\n\t\t};\n\t});\n\n\t// ── /mode command ─────────────────────────────────────────────────────────\n\n\tconst KNOWN_MODES = [\"ask\", \"plan\", \"build\", \"debug\"];\n\n\tpi.registerCommand(\"mode\", {\n\t\tdescription: \"Switch active mode. Usage: /mode <ask|plan|build|debug>\",\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\tKNOWN_MODES.filter((m) => m.startsWith(prefix)).map((m) => ({ value: m, label: m })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst name = args.trim();\n\t\t\tif (!name) {\n\t\t\t\tctx.ui.notify(`Active mode: ${cachedMode}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = name === DEFAULT_MODE ? undefined : name;\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"${name}\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /plan command (shorthand for /mode plan) ──────────────────────────────\n\n\tpi.registerCommand(\"plan\", {\n\t\tdescription: \"Switch to plan mode. Shorthand for /mode plan.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"plan\";\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"plan\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /approve command ──────────────────────────────────────────────────────\n\t// Reads .hoocode/plan.md, parses it into named sections (Goal, Files to\n\t// modify, New files, Tests, Verification), switches to build mode, then\n\t// injects a step-by-step execution message into the new session.\n\n\tpi.registerCommand(\"approve\", {\n\t\tdescription: \"Approve the current plan and switch to build mode to execute it.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tif (cachedMode !== \"plan\") {\n\t\t\t\tctx.ui.notify(`/approve is only available in plan mode (current mode: \"${cachedMode}\")`, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Prefer the per-session plan file, fall back to the legacy single file.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst candidatePaths = [sessionPlanPath, getLegacyPlanPath(ctx.cwd)];\n\t\t\tlet approveMessage: string | undefined;\n\n\t\t\tfor (const planPath of candidatePaths) {\n\t\t\t\tif (!existsSync(planPath)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst raw = readFileSync(planPath, \"utf8\").trim();\n\t\t\t\t\tif (raw) {\n\t\t\t\t\t\tconst sections = parsePlanSections(raw);\n\t\t\t\t\t\tapproveMessage = buildApproveMessage(sections);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, planPath) || planPath}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Switch global config to build mode\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"build\";\n\t\t\twriteConfig(config);\n\n\t\t\tif (approveMessage) {\n\t\t\t\t// Open a new build-mode session and deliver the parsed plan as the\n\t\t\t\t// first user message so the agent starts executing immediately\n\t\t\t\tawait ctx.newSession({\n\t\t\t\t\twithSession: async (replacedCtx) => {\n\t\t\t\t\t\tawait replacedCtx.sendUserMessage(approveMessage!, { deliverAs: \"followUp\" });\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(`Switched to build mode. No ${relPlan} found — describe what to build.`, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"modes.d.ts","sourceRoot":"","sources":["../../../src/extensions/core/modes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,OAAO,KAAK,EAGX,YAAY,EAIZ,MAAM,gCAAgC,CAAC;AAwExC;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG,MAAM,GAAG,SAAS,CAGnH;AAMD,MAAM,WAAW,YAAY;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;CACZ;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,YAAY,CA2BnE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,YAAY,GAAG,MAAM,CAwBlE;AAMD,qDAAqD;AACrD,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,IAAI,GAAG,MAAM,CAAC;AAEjD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAKtE;AAqCD;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM,CASrF;AAMD,mCAAmC;AACnC,MAAM,WAAW,cAAc;IAC9B,6EAA6E;IAC7E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAatE;AAED,6DAA6D;AAC7D,MAAM,WAAW,YAAY;IAC5B,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,+DAA+D;IAC/D,cAAc,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,YAAY,CAWxF;AAMD,wBAAgB,SAAS,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CA6OhD","sourcesContent":["/**\n * Mode system — resolves the active mode (ask/plan/build/debug), loads the\n * mode's system prompt, filters active tools, and exposes the /mode, /plan,\n * /grill, /goal, and /approve commands.\n *\n * Mode prompt search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each configured/contributed external dir in declared order\n * - built-in MODE_DEFAULTS for the four known modes\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { getHooCodeDir } from \"../../config.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { isLightModeEnv } from \"../../core/light.js\";\nimport { DEFAULT_MODE, DEFAULT_MODE_PROMPTS as MODE_DEFAULTS } from \"../../core/mode-prompts.js\";\nimport { mergeSearchPaths, readConfig, readMergedConfig, writeConfig } from \"./config.js\";\nimport { AUTO_LOOP_DONE_TOKEN, LOOP_AUTO_CHANGED, LOOP_AUTO_START, type LoopAutoStartPayload } from \"./loop.js\";\n\nconst HOOCODE_DIR = getHooCodeDir();\n\n/**\n * Per-session plan file path. Keying on sessionId lets concurrent or resumed\n * plan sessions keep distinct plans instead of clobbering each other.\n */\nfunction getPlanPath(cwd: string, sessionId: string): string {\n\treturn join(cwd, \".hoocode\", \"plans\", `${sessionId}.md`);\n}\n\n/** Legacy single-file plan location, retained as a read-only fallback for /approve. */\nfunction getLegacyPlanPath(cwd: string): string {\n\treturn join(cwd, \".hoocode\", \"plan.md\");\n}\n\nfunction tryReadFile(path: string): string | undefined {\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst text = readFileSync(path, \"utf8\").trim();\n\t\treturn text || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Outcome of reading the first usable plan file out of a candidate list. */\ntype PlanLoadResult =\n\t| { status: \"loaded\"; sections: PlanSections }\n\t| { status: \"missing\" }\n\t| { status: \"error\"; path: string };\n\n/**\n * Reads the first candidate plan file that exists and is non-empty, parsed into\n * sections. Missing and blank files fall through to the next candidate; an\n * unreadable one stops the walk so the caller can report the specific path.\n */\nfunction loadPlanSections(candidatePaths: string[]): PlanLoadResult {\n\tfor (const planPath of candidatePaths) {\n\t\tif (!existsSync(planPath)) continue;\n\t\ttry {\n\t\t\tconst raw = readFileSync(planPath, \"utf8\").trim();\n\t\t\tif (raw) return { status: \"loaded\", sections: parsePlanSections(raw) };\n\t\t} catch {\n\t\t\treturn { status: \"error\", path: planPath };\n\t\t}\n\t}\n\treturn { status: \"missing\" };\n}\n\n/**\n * Walks search dirs in precedence order and returns the first existing\n * `modes/{name}/system.md` content. Order: project → user → externalDirs.\n */\nfunction resolveModeFile(name: string, cwd: string, externalDirs: string[]): string | undefined {\n\tconst candidates: string[] = [\n\t\tjoin(cwd, \".hoocode\", \"modes\", name, \"system.md\"),\n\t\tjoin(HOOCODE_DIR, \"modes\", name, \"system.md\"),\n\t\t...externalDirs.map((dir) => join(dir, name, \"system.md\")),\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst content = tryReadFile(candidate);\n\t\tif (content !== undefined) return content;\n\t}\n\treturn undefined;\n}\n\n/**\n * Returns the system prompt for the active mode.\n *\n * Search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each of `externalDirs` in declared order (config + CLI + extension contributions)\n * - built-in MODE_DEFAULTS for the four known modes\n */\nexport function buildSystemPrompt(mode: string, cwd: string, options?: { modePaths?: string[] }): string | undefined {\n\tconst modePaths = options?.modePaths ?? [];\n\treturn resolveModeFile(mode, cwd, modePaths) ?? MODE_DEFAULTS[mode];\n}\n\n// ============================================================================\n// Plan file: section parsing and step-by-step execution message\n// ============================================================================\n\nexport interface PlanSections {\n\tgoal?: string;\n\tfilesToModify?: string;\n\tnewFiles?: string;\n\ttests?: string;\n\tverification?: string;\n\t/** Original full text, used as fallback if no sections parsed */\n\traw: string;\n}\n\n/**\n * Parses `.hoocode/plan.md` into named sections.\n *\n * Recognises both ATX headings (`## Goal`) and bold labels (`**Goal**`).\n * Section names matched (case-insensitive): Goal, Files to modify, New files,\n * Tests, Verification.\n */\nexport function parsePlanSections(planContent: string): PlanSections {\n\tconst result: PlanSections = { raw: planContent };\n\n\t// Match `## Heading text` or `**Heading text**` followed by content until\n\t// the next heading of the same style.\n\tconst sectionPattern =\n\t\t/^(?:#{1,3}\\s+(.+?)|(?:\\*\\*(.+?)\\*\\*))\\s*\\n([\\s\\S]*?)(?=(?:^#{1,3}\\s+|\\*\\*[^*\\n]+\\*\\*\\s*\\n)|$)/gm;\n\n\tfor (const match of planContent.matchAll(sectionPattern)) {\n\t\tconst heading = (match[1] ?? match[2] ?? \"\").toLowerCase().trim();\n\t\tconst content = match[3].trim();\n\t\tif (!content) continue;\n\n\t\tif (/^goal/.test(heading)) {\n\t\t\tresult.goal = content;\n\t\t} else if (/files?\\s+to\\s+modif|^modif/.test(heading)) {\n\t\t\tresult.filesToModify = content;\n\t\t} else if (/new\\s+files?/.test(heading)) {\n\t\t\tresult.newFiles = content;\n\t\t} else if (/^tests?/.test(heading)) {\n\t\t\tresult.tests = content;\n\t\t} else if (/^verif/.test(heading)) {\n\t\t\tresult.verification = content;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Builds the user message sent to the agent when `/approve` is run.\n *\n * If the plan has recognisable sections, each is presented as a numbered step\n * so the agent works through them sequentially. Otherwise the raw plan is used.\n *\n * Execution order:\n * 1. Modify existing files\n * 2. Create new files\n * 3. Update / add tests\n * 4. Run verification commands\n */\nexport function buildApproveMessage(sections: PlanSections): string {\n\tconst steps: string[] = [];\n\n\tif (sections.goal) {\n\t\tsteps.push(`**Goal:** ${sections.goal}`);\n\t}\n\tif (sections.filesToModify) {\n\t\tsteps.push(`**Step 1 — Modify existing files:**\\n${sections.filesToModify}`);\n\t}\n\tif (sections.newFiles) {\n\t\tsteps.push(`**Step 2 — Create new files:**\\n${sections.newFiles}`);\n\t}\n\tif (sections.tests) {\n\t\tsteps.push(`**Step 3 — Update tests:**\\n${sections.tests}`);\n\t}\n\tif (sections.verification) {\n\t\tsteps.push(`**Step 4 — Verify:**\\n${sections.verification}`);\n\t}\n\n\tif (steps.length === 0) {\n\t\treturn `Execute the following plan:\\n\\n${sections.raw}`;\n\t}\n\n\treturn `Execute this plan step by step. Complete each step fully before moving to the next.\\n\\n${steps.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Grill: plan interrogation\n// ============================================================================\n\n/** Which half (or both) of the grill flow to run. */\nexport type GrillTarget = \"both\" | \"me\" | \"plan\";\n\n/**\n * Parses the `/grill` argument into a target.\n *\n * Bare `/grill` runs both phases, `/grill me` only questions the user, and\n * `/grill plan` only critiques the plan. Anything else returns undefined so the\n * caller shows usage rather than guessing at intent.\n */\nexport function parseGrillTarget(args: string): GrillTarget | undefined {\n\tconst arg = args.trim().toLowerCase();\n\tif (!arg) return \"both\";\n\tif (arg === \"me\" || arg === \"plan\") return arg;\n\treturn undefined;\n}\n\n/**\n * Renders the parsed plan back into the message so the agent reviews a concrete\n * artifact rather than whatever it remembers writing. Falls back to the raw plan\n * text when no sections were recognised.\n */\nfunction renderPlanForReview(sections: PlanSections): string {\n\tconst parts: string[] = [];\n\tif (sections.goal) parts.push(`**Goal**\\n${sections.goal}`);\n\tif (sections.filesToModify) parts.push(`**Files to modify**\\n${sections.filesToModify}`);\n\tif (sections.newFiles) parts.push(`**New files**\\n${sections.newFiles}`);\n\tif (sections.tests) parts.push(`**Tests**\\n${sections.tests}`);\n\tif (sections.verification) parts.push(`**Verification**\\n${sections.verification}`);\n\treturn parts.length > 0 ? parts.join(\"\\n\\n\") : sections.raw;\n}\n\n/** Phase 1 — interrogate the request, surfacing unknowns as ask_options questions. */\nconst GRILL_ME_PROMPT = `You are interrogating the *request*, not writing code.\n\nRe-read the plan below and find where it rests on assumptions nobody confirmed: ambiguous requirements, unstated constraints, decisions you made silently because the request did not specify them, and places where a different reasonable reading of the request would produce a materially different plan.\n\nPut the most consequential of those to the user with the ask_options tool. Ask only what would actually change the plan — settle anything you can from the codebase or from convention yourself. Prefer two to four sharp questions over an exhaustive list, and mark a recommended option wherever you have a genuine preference.\n\nDo not edit files and do not revise the plan yet.`;\n\n/** Phase 2 — adversarial self-critique of the plan file. */\nconst GRILL_PLAN_PROMPT = `You are attacking the plan below, not executing it.\n\nReview it as a skeptical reviewer would:\n- Which steps rest on assumptions you have not verified in the codebase? Read the relevant files and verify them now.\n- Where could this fail silently — wrong-but-plausible behaviour rather than a loud error?\n- What does the goal require that the plan does not cover? What does the plan cover that the goal does not need?\n- Does the verification section prove the goal is met, or only that the code runs?\n\nReport what you find. Where a weakness is real, revise the plan file and state what changed. Where the plan holds up, say so plainly rather than inventing criticism. Do not implement anything.`;\n\n/**\n * Builds the follow-up message injected by `/grill`.\n *\n * The two phases are ordered rather than alternative: underspecification sits\n * upstream of plan weakness, so critiquing a plan built on a misread request\n * produces a well-reviewed plan for the wrong job. Bare `/grill` therefore asks\n * first and folds the answers into the critique.\n */\nexport function buildGrillMessage(sections: PlanSections, target: GrillTarget): string {\n\tconst plan = renderPlanForReview(sections);\n\tif (target === \"me\") return `${GRILL_ME_PROMPT}\\n\\n---\\n\\n${plan}`;\n\tif (target === \"plan\") return `${GRILL_PLAN_PROMPT}\\n\\n---\\n\\n${plan}`;\n\treturn (\n\t\t`${GRILL_ME_PROMPT}\\n\\n` +\n\t\t`Once the user has answered, fold their answers into the plan and immediately continue with this review:\\n\\n` +\n\t\t`${GRILL_PLAN_PROMPT}\\n\\n---\\n\\n${plan}`\n\t);\n}\n\n// ============================================================================\n// Goal: autonomous execution toward a completion condition\n// ============================================================================\n\n/** A parsed `/goal` invocation. */\nexport interface GoalInvocation {\n\t/** Explicit objective; falls back to the plan's Goal section when absent. */\n\tobjective?: string;\n\t/** Turn budget passed through to the autonomous loop. */\n\tmaxTurns?: number;\n}\n\n/**\n * Parses `/goal [--max-turns N] [objective]`.\n *\n * Returns undefined when `--max-turns` is present but not followed by a\n * non-negative integer, so the caller shows usage instead of silently running\n * with the default budget.\n */\nexport function parseGoalArgs(args: string): GoalInvocation | undefined {\n\tlet rest = args.trim();\n\tlet maxTurns: number | undefined;\n\n\tconst flag = /^--max-turns(?:\\s+(\\S+))?([\\s\\S]*)$/.exec(rest);\n\tif (flag) {\n\t\tconst raw = flag[1];\n\t\tif (!raw || !/^\\d+$/.test(raw)) return undefined;\n\t\tmaxTurns = Number(raw);\n\t\trest = flag[2].trim();\n\t}\n\n\treturn { objective: rest || undefined, maxTurns };\n}\n\n/** The two messages `/goal` hands to the autonomous loop. */\nexport interface GoalMessages {\n\t/** Delivered once, to start the run. */\n\ttask: string;\n\t/** Re-sent on each continuation to keep the target in view. */\n\tcontinuePrompt: string;\n}\n\n/**\n * Builds the messages for a `/goal` run.\n *\n * When the plan carries a Verification section it becomes the completion\n * condition, which is the difference between a loop that stops when it feels\n * finished and one that stops when something it can run says so. Both messages\n * restate the objective, because the loop's continuation prompt is all that\n * holds the target in place as the transcript grows.\n */\nexport function buildGoalMessages(objective: string, verification?: string): GoalMessages {\n\tconst condition = verification\n\t\t? `\\n\\nThe goal counts as complete only once this verification passes. Run it, and if it fails, fix what it reports and run it again:\\n\\n${verification}`\n\t\t: \"\";\n\n\treturn {\n\t\ttask: `Work autonomously toward this goal:\\n\\n${objective}${condition}`,\n\t\tcontinuePrompt:\n\t\t\t`Keep working toward the goal:\\n\\n${objective}${condition}\\n\\n` +\n\t\t\t`Reply with ${AUTO_LOOP_DONE_TOKEN} only when it is genuinely complete — not when it is merely close.`,\n\t};\n}\n\n// ============================================================================\n// setupMode\n// ============================================================================\n\nexport function setupMode(pi: ExtensionAPI): void {\n\tlet cachedMode = DEFAULT_MODE;\n\tlet cachedSystemPrompt: string | undefined;\n\tlet cachedPlanPath: string | undefined;\n\n\t// `/grill me` asks the user a question via ask_options, which an unattended\n\t// `/loop auto` run has nobody to answer. Track the loop's broadcast state so\n\t// the command can drop its interrogation phase instead of stalling the run.\n\tlet autoLoopActive = false;\n\tpi.events.on(LOOP_AUTO_CHANGED, (data) => {\n\t\tautoLoopActive = (data as { active?: boolean } | undefined)?.active === true;\n\t});\n\n\t// ── session_start ─────────────────────────────────────────────────────────\n\t// Config resolution order:\n\t// 1. Read global config (~/.hoocode/hoo-config.json)\n\t// 2. Read project config (./.hoocode/hoo-config.json) if present\n\t// 3. Merge — project scalars win; arrays are unioned\n\t// 4. Re-resolve active_mode from the merged result\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\t// Light mode strips every fixed prompt appendix. Leaving\n\t\t// cachedSystemPrompt unset makes before_agent_start a no-op, so no\n\t\t// `<!-- hoo-core: mode= -->` block is appended.\n\t\tif (isLightModeEnv()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Steps 1–3: merge global + project configs\n\t\tconst config = readMergedConfig(ctx.cwd);\n\n\t\t// Step 4: resolve mode from the merged config\n\t\tcachedMode = config.active_mode ?? DEFAULT_MODE;\n\t\t// External search dirs come from two channels:\n\t\t// - HooConfig.mode_paths (config-declared)\n\t\t// - pi.addModeSearchPath (CLI flags + extension contributions)\n\t\tconst modePaths = mergeSearchPaths(config.mode_paths, pi.getModeSearchPaths());\n\t\tconst rawSystemPrompt = buildSystemPrompt(cachedMode, ctx.cwd, { modePaths });\n\n\t\t// Per-session plan path so concurrent sessions don't overwrite each other.\n\t\t// The `{{PLAN_PATH}}` token in plan-mode templates is substituted here.\n\t\tcachedPlanPath = getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\tconst relPlanPath = relative(ctx.cwd, cachedPlanPath) || cachedPlanPath;\n\t\tcachedSystemPrompt = rawSystemPrompt?.replace(/\\{\\{PLAN_PATH\\}\\}/g, relPlanPath);\n\n\t\t// Update footer with active mode\n\t\tif (ctx.hasUI) {\n\t\t\tctx.ui.setMode(cachedMode);\n\t\t}\n\n\t\t// Apply tool filter from mode enabled_tools\n\t\tconst modeCfg = config.modes?.[cachedMode];\n\t\tif (modeCfg?.enabled_tools && modeCfg.enabled_tools.length > 0) {\n\t\t\tpi.setActiveTools(modeCfg.enabled_tools);\n\t\t}\n\t});\n\n\t// ── before_agent_start ────────────────────────────────────────────────────\n\n\tpi.on(\"before_agent_start\", (event: BeforeAgentStartEvent): BeforeAgentStartEventResult | undefined => {\n\t\tif (!cachedSystemPrompt) return;\n\t\treturn {\n\t\t\tsystemPrompt: `${event.systemPrompt}\\n\\n<!-- hoo-core: mode=${cachedMode} -->\\n${cachedSystemPrompt}`,\n\t\t};\n\t});\n\n\t// ── /mode command ─────────────────────────────────────────────────────────\n\n\tconst KNOWN_MODES = [\"ask\", \"plan\", \"build\", \"debug\"];\n\n\tpi.registerCommand(\"mode\", {\n\t\tdescription: \"Switch active mode. Usage: /mode <ask|plan|build|debug>\",\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\tKNOWN_MODES.filter((m) => m.startsWith(prefix)).map((m) => ({ value: m, label: m })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst name = args.trim();\n\t\t\tif (!name) {\n\t\t\t\tctx.ui.notify(`Active mode: ${cachedMode}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = name === DEFAULT_MODE ? undefined : name;\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"${name}\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /plan command (shorthand for /mode plan) ──────────────────────────────\n\n\tpi.registerCommand(\"plan\", {\n\t\tdescription: \"Switch to plan mode. Shorthand for /mode plan.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"plan\";\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"plan\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /grill command ────────────────────────────────────────────────────────\n\t// Stress-tests the current plan in two phases: `me` surfaces the request's\n\t// unconfirmed assumptions as ask_options questions, `plan` critiques the plan\n\t// file itself. Unlike /approve this only injects a follow-up message — no\n\t// session switch, no mode change, no config write.\n\n\tpi.registerCommand(\"grill\", {\n\t\tdescription: \"Stress-test the current plan. Usage: /grill [me|plan]\",\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\t[\"me\", \"plan\"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst requested = parseGrillTarget(args);\n\t\t\tif (!requested) {\n\t\t\t\tctx.ui.notify(\"Usage: /grill [me|plan]\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Same lookup as /approve: per-session plan first, legacy file second.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);\n\t\t\tif (loaded.status === \"error\") {\n\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (loaded.status === \"missing\") {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(`No plan to grill — ${relPlan} not found. Run /plan first.`, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Nobody is present to answer during an autonomous loop, so keep the\n\t\t\t// half of the flow that still works rather than blocking on a question.\n\t\t\tlet target = requested;\n\t\t\tif (autoLoopActive && target !== \"plan\") {\n\t\t\t\ttarget = \"plan\";\n\t\t\t\tctx.ui.notify(\"Autonomous loop active — grilling the plan only, skipping questions.\", \"info\");\n\t\t\t}\n\n\t\t\tpi.sendUserMessage(buildGrillMessage(loaded.sections, target), { deliverAs: \"followUp\" });\n\t\t},\n\t});\n\n\t// ── /goal command ─────────────────────────────────────────────────────────\n\t// Works autonomously toward a completion condition by driving the loop in\n\t// loop.ts over the LOOP_AUTO_START channel. Linear by design: a single thread\n\t// of execution that iterates until it reports done or exhausts its budget —\n\t// there is no task graph here, and no subtask fan-out.\n\t//\n\t// The run inherits whatever the active mode already permits (enabled_tools,\n\t// allowed_bash_commands, allowed_write_paths, auto_allow), so how much rope\n\t// an unattended goal gets is a mode-config decision, not one made here.\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Work autonomously toward a goal. Usage: /goal [--max-turns N] [objective]\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst parsed = parseGoalArgs(args);\n\t\t\tif (!parsed) {\n\t\t\t\tctx.ui.notify(\"Usage: /goal [--max-turns N] [objective]\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The plan supplies the objective when none was typed, and its\n\t\t\t// verification section becomes the completion condition either way.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);\n\t\t\tif (loaded.status === \"error\") {\n\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst sections = loaded.status === \"loaded\" ? loaded.sections : undefined;\n\n\t\t\tconst objective = parsed.objective ?? sections?.goal;\n\t\t\tif (!objective) {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`No objective — pass one as /goal <objective>, or write a Goal section in ${relPlan}.`,\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst { task, continuePrompt } = buildGoalMessages(objective, sections?.verification);\n\t\t\t// The loop announces itself on start, so nothing to notify here.\n\t\t\tpi.events.emit(LOOP_AUTO_START, {\n\t\t\t\ttask,\n\t\t\t\tmaxTurns: parsed.maxTurns,\n\t\t\t\tcontinuePrompt,\n\t\t\t} satisfies LoopAutoStartPayload);\n\t\t},\n\t});\n\n\t// ── /approve command ──────────────────────────────────────────────────────\n\t// Reads .hoocode/plan.md, parses it into named sections (Goal, Files to\n\t// modify, New files, Tests, Verification), switches to build mode, then\n\t// injects a step-by-step execution message into the new session.\n\n\tpi.registerCommand(\"approve\", {\n\t\tdescription: \"Approve the current plan and switch to build mode to execute it.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tif (cachedMode !== \"plan\") {\n\t\t\t\tctx.ui.notify(`/approve is only available in plan mode (current mode: \"${cachedMode}\")`, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Prefer the per-session plan file, fall back to the legacy single file.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);\n\t\t\tif (loaded.status === \"error\") {\n\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst approveMessage = loaded.status === \"loaded\" ? buildApproveMessage(loaded.sections) : undefined;\n\n\t\t\t// Switch global config to build mode\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"build\";\n\t\t\twriteConfig(config);\n\n\t\t\tif (approveMessage) {\n\t\t\t\t// Open a new build-mode session and deliver the parsed plan as the\n\t\t\t\t// first user message so the agent starts executing immediately\n\t\t\t\tawait ctx.newSession({\n\t\t\t\t\twithSession: async (replacedCtx) => {\n\t\t\t\t\t\tawait replacedCtx.sendUserMessage(approveMessage!, { deliverAs: \"followUp\" });\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(`Switched to build mode. No ${relPlan} found — describe what to build.`, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Mode system — resolves the active mode (ask/plan/build/debug), loads the
3
3
  * mode's system prompt, filters active tools, and exposes the /mode, /plan,
4
- * and /approve commands.
4
+ * /grill, /goal, and /approve commands.
5
5
  *
6
6
  * Mode prompt search order (first hit wins):
7
7
  * - `./.hoocode/modes/{mode}/system.md`
@@ -15,6 +15,7 @@ import { getHooCodeDir } from "../../config.js";
15
15
  import { isLightModeEnv } from "../../core/light.js";
16
16
  import { DEFAULT_MODE, DEFAULT_MODE_PROMPTS as MODE_DEFAULTS } from "../../core/mode-prompts.js";
17
17
  import { mergeSearchPaths, readConfig, readMergedConfig, writeConfig } from "./config.js";
18
+ import { AUTO_LOOP_DONE_TOKEN, LOOP_AUTO_CHANGED, LOOP_AUTO_START } from "./loop.js";
18
19
  const HOOCODE_DIR = getHooCodeDir();
19
20
  /**
20
21
  * Per-session plan file path. Keying on sessionId lets concurrent or resumed
@@ -38,6 +39,26 @@ function tryReadFile(path) {
38
39
  return undefined;
39
40
  }
40
41
  }
42
+ /**
43
+ * Reads the first candidate plan file that exists and is non-empty, parsed into
44
+ * sections. Missing and blank files fall through to the next candidate; an
45
+ * unreadable one stops the walk so the caller can report the specific path.
46
+ */
47
+ function loadPlanSections(candidatePaths) {
48
+ for (const planPath of candidatePaths) {
49
+ if (!existsSync(planPath))
50
+ continue;
51
+ try {
52
+ const raw = readFileSync(planPath, "utf8").trim();
53
+ if (raw)
54
+ return { status: "loaded", sections: parsePlanSections(raw) };
55
+ }
56
+ catch {
57
+ return { status: "error", path: planPath };
58
+ }
59
+ }
60
+ return { status: "missing" };
61
+ }
41
62
  /**
42
63
  * Walks search dirs in precedence order and returns the first existing
43
64
  * `modes/{name}/system.md` content. Order: project → user → externalDirs.
@@ -137,6 +158,115 @@ export function buildApproveMessage(sections) {
137
158
  }
138
159
  return `Execute this plan step by step. Complete each step fully before moving to the next.\n\n${steps.join("\n\n")}`;
139
160
  }
161
+ /**
162
+ * Parses the `/grill` argument into a target.
163
+ *
164
+ * Bare `/grill` runs both phases, `/grill me` only questions the user, and
165
+ * `/grill plan` only critiques the plan. Anything else returns undefined so the
166
+ * caller shows usage rather than guessing at intent.
167
+ */
168
+ export function parseGrillTarget(args) {
169
+ const arg = args.trim().toLowerCase();
170
+ if (!arg)
171
+ return "both";
172
+ if (arg === "me" || arg === "plan")
173
+ return arg;
174
+ return undefined;
175
+ }
176
+ /**
177
+ * Renders the parsed plan back into the message so the agent reviews a concrete
178
+ * artifact rather than whatever it remembers writing. Falls back to the raw plan
179
+ * text when no sections were recognised.
180
+ */
181
+ function renderPlanForReview(sections) {
182
+ const parts = [];
183
+ if (sections.goal)
184
+ parts.push(`**Goal**\n${sections.goal}`);
185
+ if (sections.filesToModify)
186
+ parts.push(`**Files to modify**\n${sections.filesToModify}`);
187
+ if (sections.newFiles)
188
+ parts.push(`**New files**\n${sections.newFiles}`);
189
+ if (sections.tests)
190
+ parts.push(`**Tests**\n${sections.tests}`);
191
+ if (sections.verification)
192
+ parts.push(`**Verification**\n${sections.verification}`);
193
+ return parts.length > 0 ? parts.join("\n\n") : sections.raw;
194
+ }
195
+ /** Phase 1 — interrogate the request, surfacing unknowns as ask_options questions. */
196
+ const GRILL_ME_PROMPT = `You are interrogating the *request*, not writing code.
197
+
198
+ Re-read the plan below and find where it rests on assumptions nobody confirmed: ambiguous requirements, unstated constraints, decisions you made silently because the request did not specify them, and places where a different reasonable reading of the request would produce a materially different plan.
199
+
200
+ Put the most consequential of those to the user with the ask_options tool. Ask only what would actually change the plan — settle anything you can from the codebase or from convention yourself. Prefer two to four sharp questions over an exhaustive list, and mark a recommended option wherever you have a genuine preference.
201
+
202
+ Do not edit files and do not revise the plan yet.`;
203
+ /** Phase 2 — adversarial self-critique of the plan file. */
204
+ const GRILL_PLAN_PROMPT = `You are attacking the plan below, not executing it.
205
+
206
+ Review it as a skeptical reviewer would:
207
+ - Which steps rest on assumptions you have not verified in the codebase? Read the relevant files and verify them now.
208
+ - Where could this fail silently — wrong-but-plausible behaviour rather than a loud error?
209
+ - What does the goal require that the plan does not cover? What does the plan cover that the goal does not need?
210
+ - Does the verification section prove the goal is met, or only that the code runs?
211
+
212
+ Report what you find. Where a weakness is real, revise the plan file and state what changed. Where the plan holds up, say so plainly rather than inventing criticism. Do not implement anything.`;
213
+ /**
214
+ * Builds the follow-up message injected by `/grill`.
215
+ *
216
+ * The two phases are ordered rather than alternative: underspecification sits
217
+ * upstream of plan weakness, so critiquing a plan built on a misread request
218
+ * produces a well-reviewed plan for the wrong job. Bare `/grill` therefore asks
219
+ * first and folds the answers into the critique.
220
+ */
221
+ export function buildGrillMessage(sections, target) {
222
+ const plan = renderPlanForReview(sections);
223
+ if (target === "me")
224
+ return `${GRILL_ME_PROMPT}\n\n---\n\n${plan}`;
225
+ if (target === "plan")
226
+ return `${GRILL_PLAN_PROMPT}\n\n---\n\n${plan}`;
227
+ return (`${GRILL_ME_PROMPT}\n\n` +
228
+ `Once the user has answered, fold their answers into the plan and immediately continue with this review:\n\n` +
229
+ `${GRILL_PLAN_PROMPT}\n\n---\n\n${plan}`);
230
+ }
231
+ /**
232
+ * Parses `/goal [--max-turns N] [objective]`.
233
+ *
234
+ * Returns undefined when `--max-turns` is present but not followed by a
235
+ * non-negative integer, so the caller shows usage instead of silently running
236
+ * with the default budget.
237
+ */
238
+ export function parseGoalArgs(args) {
239
+ let rest = args.trim();
240
+ let maxTurns;
241
+ const flag = /^--max-turns(?:\s+(\S+))?([\s\S]*)$/.exec(rest);
242
+ if (flag) {
243
+ const raw = flag[1];
244
+ if (!raw || !/^\d+$/.test(raw))
245
+ return undefined;
246
+ maxTurns = Number(raw);
247
+ rest = flag[2].trim();
248
+ }
249
+ return { objective: rest || undefined, maxTurns };
250
+ }
251
+ /**
252
+ * Builds the messages for a `/goal` run.
253
+ *
254
+ * When the plan carries a Verification section it becomes the completion
255
+ * condition, which is the difference between a loop that stops when it feels
256
+ * finished and one that stops when something it can run says so. Both messages
257
+ * restate the objective, because the loop's continuation prompt is all that
258
+ * holds the target in place as the transcript grows.
259
+ */
260
+ export function buildGoalMessages(objective, verification) {
261
+ const condition = verification
262
+ ? `\n\nThe goal counts as complete only once this verification passes. Run it, and if it fails, fix what it reports and run it again:\n\n${verification}`
263
+ : "";
264
+ return {
265
+ task: `Work autonomously toward this goal:\n\n${objective}${condition}`,
266
+ continuePrompt: `Keep working toward the goal:\n\n${objective}${condition}\n\n` +
267
+ `Reply with ${AUTO_LOOP_DONE_TOKEN} only when it is genuinely complete — not when it is merely close.`,
268
+ };
269
+ }
140
270
  // ============================================================================
141
271
  // setupMode
142
272
  // ============================================================================
@@ -144,6 +274,13 @@ export function setupMode(pi) {
144
274
  let cachedMode = DEFAULT_MODE;
145
275
  let cachedSystemPrompt;
146
276
  let cachedPlanPath;
277
+ // `/grill me` asks the user a question via ask_options, which an unattended
278
+ // `/loop auto` run has nobody to answer. Track the loop's broadcast state so
279
+ // the command can drop its interrogation phase instead of stalling the run.
280
+ let autoLoopActive = false;
281
+ pi.events.on(LOOP_AUTO_CHANGED, (data) => {
282
+ autoLoopActive = data?.active === true;
283
+ });
147
284
  // ── session_start ─────────────────────────────────────────────────────────
148
285
  // Config resolution order:
149
286
  // 1. Read global config (~/.hoocode/hoo-config.json)
@@ -219,6 +356,84 @@ export function setupMode(pi) {
219
356
  await ctx.reload();
220
357
  },
221
358
  });
359
+ // ── /grill command ────────────────────────────────────────────────────────
360
+ // Stress-tests the current plan in two phases: `me` surfaces the request's
361
+ // unconfirmed assumptions as ask_options questions, `plan` critiques the plan
362
+ // file itself. Unlike /approve this only injects a follow-up message — no
363
+ // session switch, no mode change, no config write.
364
+ pi.registerCommand("grill", {
365
+ description: "Stress-test the current plan. Usage: /grill [me|plan]",
366
+ getArgumentCompletions: (prefix) => ["me", "plan"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s })),
367
+ handler: async (args, ctx) => {
368
+ const requested = parseGrillTarget(args);
369
+ if (!requested) {
370
+ ctx.ui.notify("Usage: /grill [me|plan]", "warning");
371
+ return;
372
+ }
373
+ // Same lookup as /approve: per-session plan first, legacy file second.
374
+ const sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());
375
+ const loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);
376
+ if (loaded.status === "error") {
377
+ ctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, "error");
378
+ return;
379
+ }
380
+ if (loaded.status === "missing") {
381
+ const relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;
382
+ ctx.ui.notify(`No plan to grill — ${relPlan} not found. Run /plan first.`, "warning");
383
+ return;
384
+ }
385
+ // Nobody is present to answer during an autonomous loop, so keep the
386
+ // half of the flow that still works rather than blocking on a question.
387
+ let target = requested;
388
+ if (autoLoopActive && target !== "plan") {
389
+ target = "plan";
390
+ ctx.ui.notify("Autonomous loop active — grilling the plan only, skipping questions.", "info");
391
+ }
392
+ pi.sendUserMessage(buildGrillMessage(loaded.sections, target), { deliverAs: "followUp" });
393
+ },
394
+ });
395
+ // ── /goal command ─────────────────────────────────────────────────────────
396
+ // Works autonomously toward a completion condition by driving the loop in
397
+ // loop.ts over the LOOP_AUTO_START channel. Linear by design: a single thread
398
+ // of execution that iterates until it reports done or exhausts its budget —
399
+ // there is no task graph here, and no subtask fan-out.
400
+ //
401
+ // The run inherits whatever the active mode already permits (enabled_tools,
402
+ // allowed_bash_commands, allowed_write_paths, auto_allow), so how much rope
403
+ // an unattended goal gets is a mode-config decision, not one made here.
404
+ pi.registerCommand("goal", {
405
+ description: "Work autonomously toward a goal. Usage: /goal [--max-turns N] [objective]",
406
+ getArgumentCompletions: () => [],
407
+ handler: async (args, ctx) => {
408
+ const parsed = parseGoalArgs(args);
409
+ if (!parsed) {
410
+ ctx.ui.notify("Usage: /goal [--max-turns N] [objective]", "warning");
411
+ return;
412
+ }
413
+ // The plan supplies the objective when none was typed, and its
414
+ // verification section becomes the completion condition either way.
415
+ const sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());
416
+ const loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);
417
+ if (loaded.status === "error") {
418
+ ctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, "error");
419
+ return;
420
+ }
421
+ const sections = loaded.status === "loaded" ? loaded.sections : undefined;
422
+ const objective = parsed.objective ?? sections?.goal;
423
+ if (!objective) {
424
+ const relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;
425
+ ctx.ui.notify(`No objective — pass one as /goal <objective>, or write a Goal section in ${relPlan}.`, "warning");
426
+ return;
427
+ }
428
+ const { task, continuePrompt } = buildGoalMessages(objective, sections?.verification);
429
+ // The loop announces itself on start, so nothing to notify here.
430
+ pi.events.emit(LOOP_AUTO_START, {
431
+ task,
432
+ maxTurns: parsed.maxTurns,
433
+ continuePrompt,
434
+ });
435
+ },
436
+ });
222
437
  // ── /approve command ──────────────────────────────────────────────────────
223
438
  // Reads .hoocode/plan.md, parses it into named sections (Goal, Files to
224
439
  // modify, New files, Tests, Verification), switches to build mode, then
@@ -233,24 +448,12 @@ export function setupMode(pi) {
233
448
  }
234
449
  // Prefer the per-session plan file, fall back to the legacy single file.
235
450
  const sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());
236
- const candidatePaths = [sessionPlanPath, getLegacyPlanPath(ctx.cwd)];
237
- let approveMessage;
238
- for (const planPath of candidatePaths) {
239
- if (!existsSync(planPath))
240
- continue;
241
- try {
242
- const raw = readFileSync(planPath, "utf8").trim();
243
- if (raw) {
244
- const sections = parsePlanSections(raw);
245
- approveMessage = buildApproveMessage(sections);
246
- break;
247
- }
248
- }
249
- catch {
250
- ctx.ui.notify(`Could not read ${relative(ctx.cwd, planPath) || planPath}`, "error");
251
- return;
252
- }
451
+ const loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);
452
+ if (loaded.status === "error") {
453
+ ctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, "error");
454
+ return;
253
455
  }
456
+ const approveMessage = loaded.status === "loaded" ? buildApproveMessage(loaded.sections) : undefined;
254
457
  // Switch global config to build mode
255
458
  const config = readConfig();
256
459
  config.active_mode = "build";
@@ -1 +1 @@
1
- {"version":3,"file":"modes.js","sourceRoot":"","sources":["../../../src/extensions/core/modes.ts"],"names":[],"mappings":"AAAA;;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qC;YACrC,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;YAC5B,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC;YAC7B,WAAW,CAAC,MAAM,CAAC,CAAC;YAEpB,IAAI,cAAc,EAAE,CAAC;gBACpB,mEAAmE;gBACnE,+DAA+D;gBAC/D,MAAM,GAAG,CAAC,UAAU,CAAC;oBACpB,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC;wBACnC,MAAM,WAAW,CAAC,eAAe,CAAC,cAAe,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC,CAAC;oBAAA,CAC9E;iBACD,CAAC,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACP,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,eAAe,CAAC,IAAI,eAAe,CAAC;gBACtE,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,8BAA8B,OAAO,oCAAkC,EAAE,MAAM,CAAC,CAAC;gBAC/F,MAAM,GAAG,CAAC,MAAM,EAAE,CAAC;YACpB,CAAC;QAAA,CACD;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Mode system — resolves the active mode (ask/plan/build/debug), loads the\n * mode's system prompt, filters active tools, and exposes the /mode, /plan,\n * and /approve commands.\n *\n * Mode prompt search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each configured/contributed external dir in declared order\n * - built-in MODE_DEFAULTS for the four known modes\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { getHooCodeDir } from \"../../config.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { isLightModeEnv } from \"../../core/light.js\";\nimport { DEFAULT_MODE, DEFAULT_MODE_PROMPTS as MODE_DEFAULTS } from \"../../core/mode-prompts.js\";\nimport { mergeSearchPaths, readConfig, readMergedConfig, writeConfig } from \"./config.js\";\n\nconst HOOCODE_DIR = getHooCodeDir();\n\n/**\n * Per-session plan file path. Keying on sessionId lets concurrent or resumed\n * plan sessions keep distinct plans instead of clobbering each other.\n */\nfunction getPlanPath(cwd: string, sessionId: string): string {\n\treturn join(cwd, \".hoocode\", \"plans\", `${sessionId}.md`);\n}\n\n/** Legacy single-file plan location, retained as a read-only fallback for /approve. */\nfunction getLegacyPlanPath(cwd: string): string {\n\treturn join(cwd, \".hoocode\", \"plan.md\");\n}\n\nfunction tryReadFile(path: string): string | undefined {\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst text = readFileSync(path, \"utf8\").trim();\n\t\treturn text || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Walks search dirs in precedence order and returns the first existing\n * `modes/{name}/system.md` content. Order: project → user → externalDirs.\n */\nfunction resolveModeFile(name: string, cwd: string, externalDirs: string[]): string | undefined {\n\tconst candidates: string[] = [\n\t\tjoin(cwd, \".hoocode\", \"modes\", name, \"system.md\"),\n\t\tjoin(HOOCODE_DIR, \"modes\", name, \"system.md\"),\n\t\t...externalDirs.map((dir) => join(dir, name, \"system.md\")),\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst content = tryReadFile(candidate);\n\t\tif (content !== undefined) return content;\n\t}\n\treturn undefined;\n}\n\n/**\n * Returns the system prompt for the active mode.\n *\n * Search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each of `externalDirs` in declared order (config + CLI + extension contributions)\n * - built-in MODE_DEFAULTS for the four known modes\n */\nexport function buildSystemPrompt(mode: string, cwd: string, options?: { modePaths?: string[] }): string | undefined {\n\tconst modePaths = options?.modePaths ?? [];\n\treturn resolveModeFile(mode, cwd, modePaths) ?? MODE_DEFAULTS[mode];\n}\n\n// ============================================================================\n// Plan file: section parsing and step-by-step execution message\n// ============================================================================\n\nexport interface PlanSections {\n\tgoal?: string;\n\tfilesToModify?: string;\n\tnewFiles?: string;\n\ttests?: string;\n\tverification?: string;\n\t/** Original full text, used as fallback if no sections parsed */\n\traw: string;\n}\n\n/**\n * Parses `.hoocode/plan.md` into named sections.\n *\n * Recognises both ATX headings (`## Goal`) and bold labels (`**Goal**`).\n * Section names matched (case-insensitive): Goal, Files to modify, New files,\n * Tests, Verification.\n */\nexport function parsePlanSections(planContent: string): PlanSections {\n\tconst result: PlanSections = { raw: planContent };\n\n\t// Match `## Heading text` or `**Heading text**` followed by content until\n\t// the next heading of the same style.\n\tconst sectionPattern =\n\t\t/^(?:#{1,3}\\s+(.+?)|(?:\\*\\*(.+?)\\*\\*))\\s*\\n([\\s\\S]*?)(?=(?:^#{1,3}\\s+|\\*\\*[^*\\n]+\\*\\*\\s*\\n)|$)/gm;\n\n\tfor (const match of planContent.matchAll(sectionPattern)) {\n\t\tconst heading = (match[1] ?? match[2] ?? \"\").toLowerCase().trim();\n\t\tconst content = match[3].trim();\n\t\tif (!content) continue;\n\n\t\tif (/^goal/.test(heading)) {\n\t\t\tresult.goal = content;\n\t\t} else if (/files?\\s+to\\s+modif|^modif/.test(heading)) {\n\t\t\tresult.filesToModify = content;\n\t\t} else if (/new\\s+files?/.test(heading)) {\n\t\t\tresult.newFiles = content;\n\t\t} else if (/^tests?/.test(heading)) {\n\t\t\tresult.tests = content;\n\t\t} else if (/^verif/.test(heading)) {\n\t\t\tresult.verification = content;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Builds the user message sent to the agent when `/approve` is run.\n *\n * If the plan has recognisable sections, each is presented as a numbered step\n * so the agent works through them sequentially. Otherwise the raw plan is used.\n *\n * Execution order:\n * 1. Modify existing files\n * 2. Create new files\n * 3. Update / add tests\n * 4. Run verification commands\n */\nexport function buildApproveMessage(sections: PlanSections): string {\n\tconst steps: string[] = [];\n\n\tif (sections.goal) {\n\t\tsteps.push(`**Goal:** ${sections.goal}`);\n\t}\n\tif (sections.filesToModify) {\n\t\tsteps.push(`**Step 1 — Modify existing files:**\\n${sections.filesToModify}`);\n\t}\n\tif (sections.newFiles) {\n\t\tsteps.push(`**Step 2 — Create new files:**\\n${sections.newFiles}`);\n\t}\n\tif (sections.tests) {\n\t\tsteps.push(`**Step 3 — Update tests:**\\n${sections.tests}`);\n\t}\n\tif (sections.verification) {\n\t\tsteps.push(`**Step 4 — Verify:**\\n${sections.verification}`);\n\t}\n\n\tif (steps.length === 0) {\n\t\treturn `Execute the following plan:\\n\\n${sections.raw}`;\n\t}\n\n\treturn `Execute this plan step by step. Complete each step fully before moving to the next.\\n\\n${steps.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// setupMode\n// ============================================================================\n\nexport function setupMode(pi: ExtensionAPI): void {\n\tlet cachedMode = DEFAULT_MODE;\n\tlet cachedSystemPrompt: string | undefined;\n\tlet cachedPlanPath: string | undefined;\n\n\t// ── session_start ─────────────────────────────────────────────────────────\n\t// Config resolution order:\n\t// 1. Read global config (~/.hoocode/hoo-config.json)\n\t// 2. Read project config (./.hoocode/hoo-config.json) if present\n\t// 3. Merge — project scalars win; arrays are unioned\n\t// 4. Re-resolve active_mode from the merged result\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\t// Light mode strips every fixed prompt appendix. Leaving\n\t\t// cachedSystemPrompt unset makes before_agent_start a no-op, so no\n\t\t// `<!-- hoo-core: mode= -->` block is appended.\n\t\tif (isLightModeEnv()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Steps 1–3: merge global + project configs\n\t\tconst config = readMergedConfig(ctx.cwd);\n\n\t\t// Step 4: resolve mode from the merged config\n\t\tcachedMode = config.active_mode ?? DEFAULT_MODE;\n\t\t// External search dirs come from two channels:\n\t\t// - HooConfig.mode_paths (config-declared)\n\t\t// - pi.addModeSearchPath (CLI flags + extension contributions)\n\t\tconst modePaths = mergeSearchPaths(config.mode_paths, pi.getModeSearchPaths());\n\t\tconst rawSystemPrompt = buildSystemPrompt(cachedMode, ctx.cwd, { modePaths });\n\n\t\t// Per-session plan path so concurrent sessions don't overwrite each other.\n\t\t// The `{{PLAN_PATH}}` token in plan-mode templates is substituted here.\n\t\tcachedPlanPath = getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\tconst relPlanPath = relative(ctx.cwd, cachedPlanPath) || cachedPlanPath;\n\t\tcachedSystemPrompt = rawSystemPrompt?.replace(/\\{\\{PLAN_PATH\\}\\}/g, relPlanPath);\n\n\t\t// Update footer with active mode\n\t\tif (ctx.hasUI) {\n\t\t\tctx.ui.setMode(cachedMode);\n\t\t}\n\n\t\t// Apply tool filter from mode enabled_tools\n\t\tconst modeCfg = config.modes?.[cachedMode];\n\t\tif (modeCfg?.enabled_tools && modeCfg.enabled_tools.length > 0) {\n\t\t\tpi.setActiveTools(modeCfg.enabled_tools);\n\t\t}\n\t});\n\n\t// ── before_agent_start ────────────────────────────────────────────────────\n\n\tpi.on(\"before_agent_start\", (event: BeforeAgentStartEvent): BeforeAgentStartEventResult | undefined => {\n\t\tif (!cachedSystemPrompt) return;\n\t\treturn {\n\t\t\tsystemPrompt: `${event.systemPrompt}\\n\\n<!-- hoo-core: mode=${cachedMode} -->\\n${cachedSystemPrompt}`,\n\t\t};\n\t});\n\n\t// ── /mode command ─────────────────────────────────────────────────────────\n\n\tconst KNOWN_MODES = [\"ask\", \"plan\", \"build\", \"debug\"];\n\n\tpi.registerCommand(\"mode\", {\n\t\tdescription: \"Switch active mode. Usage: /mode <ask|plan|build|debug>\",\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\tKNOWN_MODES.filter((m) => m.startsWith(prefix)).map((m) => ({ value: m, label: m })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst name = args.trim();\n\t\t\tif (!name) {\n\t\t\t\tctx.ui.notify(`Active mode: ${cachedMode}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = name === DEFAULT_MODE ? undefined : name;\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"${name}\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /plan command (shorthand for /mode plan) ──────────────────────────────\n\n\tpi.registerCommand(\"plan\", {\n\t\tdescription: \"Switch to plan mode. Shorthand for /mode plan.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"plan\";\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"plan\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /approve command ──────────────────────────────────────────────────────\n\t// Reads .hoocode/plan.md, parses it into named sections (Goal, Files to\n\t// modify, New files, Tests, Verification), switches to build mode, then\n\t// injects a step-by-step execution message into the new session.\n\n\tpi.registerCommand(\"approve\", {\n\t\tdescription: \"Approve the current plan and switch to build mode to execute it.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tif (cachedMode !== \"plan\") {\n\t\t\t\tctx.ui.notify(`/approve is only available in plan mode (current mode: \"${cachedMode}\")`, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Prefer the per-session plan file, fall back to the legacy single file.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst candidatePaths = [sessionPlanPath, getLegacyPlanPath(ctx.cwd)];\n\t\t\tlet approveMessage: string | undefined;\n\n\t\t\tfor (const planPath of candidatePaths) {\n\t\t\t\tif (!existsSync(planPath)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst raw = readFileSync(planPath, \"utf8\").trim();\n\t\t\t\t\tif (raw) {\n\t\t\t\t\t\tconst sections = parsePlanSections(raw);\n\t\t\t\t\t\tapproveMessage = buildApproveMessage(sections);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, planPath) || planPath}`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Switch global config to build mode\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"build\";\n\t\t\twriteConfig(config);\n\n\t\t\tif (approveMessage) {\n\t\t\t\t// Open a new build-mode session and deliver the parsed plan as the\n\t\t\t\t// first user message so the agent starts executing immediately\n\t\t\t\tawait ctx.newSession({\n\t\t\t\t\twithSession: async (replacedCtx) => {\n\t\t\t\t\t\tawait replacedCtx.sendUserMessage(approveMessage!, { deliverAs: \"followUp\" });\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(`Switched to build mode. No ${relPlan} found — describe what to build.`, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"modes.js","sourceRoot":"","sources":["../../../src/extensions/core/modes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAShD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,oBAAoB,IAAI,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,gBAAgB,EAAE,WAAW,EAAE,M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,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC;gBAC1F,OAAO;YACR,CAAC;YACD,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAErG,qCAAqC;YACrC,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;YAC5B,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC;YAC7B,WAAW,CAAC,MAAM,CAAC,CAAC;YAEpB,IAAI,cAAc,EAAE,CAAC;gBACpB,mEAAmE;gBACnE,+DAA+D;gBAC/D,MAAM,GAAG,CAAC,UAAU,CAAC;oBACpB,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC;wBACnC,MAAM,WAAW,CAAC,eAAe,CAAC,cAAe,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC,CAAC;oBAAA,CAC9E;iBACD,CAAC,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACP,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,eAAe,CAAC,IAAI,eAAe,CAAC;gBACtE,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,8BAA8B,OAAO,oCAAkC,EAAE,MAAM,CAAC,CAAC;gBAC/F,MAAM,GAAG,CAAC,MAAM,EAAE,CAAC;YACpB,CAAC;QAAA,CACD;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Mode system — resolves the active mode (ask/plan/build/debug), loads the\n * mode's system prompt, filters active tools, and exposes the /mode, /plan,\n * /grill, /goal, and /approve commands.\n *\n * Mode prompt search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each configured/contributed external dir in declared order\n * - built-in MODE_DEFAULTS for the four known modes\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { getHooCodeDir } from \"../../config.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tSessionStartEvent,\n} from \"../../core/extensions/types.js\";\nimport { isLightModeEnv } from \"../../core/light.js\";\nimport { DEFAULT_MODE, DEFAULT_MODE_PROMPTS as MODE_DEFAULTS } from \"../../core/mode-prompts.js\";\nimport { mergeSearchPaths, readConfig, readMergedConfig, writeConfig } from \"./config.js\";\nimport { AUTO_LOOP_DONE_TOKEN, LOOP_AUTO_CHANGED, LOOP_AUTO_START, type LoopAutoStartPayload } from \"./loop.js\";\n\nconst HOOCODE_DIR = getHooCodeDir();\n\n/**\n * Per-session plan file path. Keying on sessionId lets concurrent or resumed\n * plan sessions keep distinct plans instead of clobbering each other.\n */\nfunction getPlanPath(cwd: string, sessionId: string): string {\n\treturn join(cwd, \".hoocode\", \"plans\", `${sessionId}.md`);\n}\n\n/** Legacy single-file plan location, retained as a read-only fallback for /approve. */\nfunction getLegacyPlanPath(cwd: string): string {\n\treturn join(cwd, \".hoocode\", \"plan.md\");\n}\n\nfunction tryReadFile(path: string): string | undefined {\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst text = readFileSync(path, \"utf8\").trim();\n\t\treturn text || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Outcome of reading the first usable plan file out of a candidate list. */\ntype PlanLoadResult =\n\t| { status: \"loaded\"; sections: PlanSections }\n\t| { status: \"missing\" }\n\t| { status: \"error\"; path: string };\n\n/**\n * Reads the first candidate plan file that exists and is non-empty, parsed into\n * sections. Missing and blank files fall through to the next candidate; an\n * unreadable one stops the walk so the caller can report the specific path.\n */\nfunction loadPlanSections(candidatePaths: string[]): PlanLoadResult {\n\tfor (const planPath of candidatePaths) {\n\t\tif (!existsSync(planPath)) continue;\n\t\ttry {\n\t\t\tconst raw = readFileSync(planPath, \"utf8\").trim();\n\t\t\tif (raw) return { status: \"loaded\", sections: parsePlanSections(raw) };\n\t\t} catch {\n\t\t\treturn { status: \"error\", path: planPath };\n\t\t}\n\t}\n\treturn { status: \"missing\" };\n}\n\n/**\n * Walks search dirs in precedence order and returns the first existing\n * `modes/{name}/system.md` content. Order: project → user → externalDirs.\n */\nfunction resolveModeFile(name: string, cwd: string, externalDirs: string[]): string | undefined {\n\tconst candidates: string[] = [\n\t\tjoin(cwd, \".hoocode\", \"modes\", name, \"system.md\"),\n\t\tjoin(HOOCODE_DIR, \"modes\", name, \"system.md\"),\n\t\t...externalDirs.map((dir) => join(dir, name, \"system.md\")),\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst content = tryReadFile(candidate);\n\t\tif (content !== undefined) return content;\n\t}\n\treturn undefined;\n}\n\n/**\n * Returns the system prompt for the active mode.\n *\n * Search order (first hit wins):\n * - `./.hoocode/modes/{mode}/system.md`\n * - `~/.hoocode/modes/{mode}/system.md`\n * - each of `externalDirs` in declared order (config + CLI + extension contributions)\n * - built-in MODE_DEFAULTS for the four known modes\n */\nexport function buildSystemPrompt(mode: string, cwd: string, options?: { modePaths?: string[] }): string | undefined {\n\tconst modePaths = options?.modePaths ?? [];\n\treturn resolveModeFile(mode, cwd, modePaths) ?? MODE_DEFAULTS[mode];\n}\n\n// ============================================================================\n// Plan file: section parsing and step-by-step execution message\n// ============================================================================\n\nexport interface PlanSections {\n\tgoal?: string;\n\tfilesToModify?: string;\n\tnewFiles?: string;\n\ttests?: string;\n\tverification?: string;\n\t/** Original full text, used as fallback if no sections parsed */\n\traw: string;\n}\n\n/**\n * Parses `.hoocode/plan.md` into named sections.\n *\n * Recognises both ATX headings (`## Goal`) and bold labels (`**Goal**`).\n * Section names matched (case-insensitive): Goal, Files to modify, New files,\n * Tests, Verification.\n */\nexport function parsePlanSections(planContent: string): PlanSections {\n\tconst result: PlanSections = { raw: planContent };\n\n\t// Match `## Heading text` or `**Heading text**` followed by content until\n\t// the next heading of the same style.\n\tconst sectionPattern =\n\t\t/^(?:#{1,3}\\s+(.+?)|(?:\\*\\*(.+?)\\*\\*))\\s*\\n([\\s\\S]*?)(?=(?:^#{1,3}\\s+|\\*\\*[^*\\n]+\\*\\*\\s*\\n)|$)/gm;\n\n\tfor (const match of planContent.matchAll(sectionPattern)) {\n\t\tconst heading = (match[1] ?? match[2] ?? \"\").toLowerCase().trim();\n\t\tconst content = match[3].trim();\n\t\tif (!content) continue;\n\n\t\tif (/^goal/.test(heading)) {\n\t\t\tresult.goal = content;\n\t\t} else if (/files?\\s+to\\s+modif|^modif/.test(heading)) {\n\t\t\tresult.filesToModify = content;\n\t\t} else if (/new\\s+files?/.test(heading)) {\n\t\t\tresult.newFiles = content;\n\t\t} else if (/^tests?/.test(heading)) {\n\t\t\tresult.tests = content;\n\t\t} else if (/^verif/.test(heading)) {\n\t\t\tresult.verification = content;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Builds the user message sent to the agent when `/approve` is run.\n *\n * If the plan has recognisable sections, each is presented as a numbered step\n * so the agent works through them sequentially. Otherwise the raw plan is used.\n *\n * Execution order:\n * 1. Modify existing files\n * 2. Create new files\n * 3. Update / add tests\n * 4. Run verification commands\n */\nexport function buildApproveMessage(sections: PlanSections): string {\n\tconst steps: string[] = [];\n\n\tif (sections.goal) {\n\t\tsteps.push(`**Goal:** ${sections.goal}`);\n\t}\n\tif (sections.filesToModify) {\n\t\tsteps.push(`**Step 1 — Modify existing files:**\\n${sections.filesToModify}`);\n\t}\n\tif (sections.newFiles) {\n\t\tsteps.push(`**Step 2 — Create new files:**\\n${sections.newFiles}`);\n\t}\n\tif (sections.tests) {\n\t\tsteps.push(`**Step 3 — Update tests:**\\n${sections.tests}`);\n\t}\n\tif (sections.verification) {\n\t\tsteps.push(`**Step 4 — Verify:**\\n${sections.verification}`);\n\t}\n\n\tif (steps.length === 0) {\n\t\treturn `Execute the following plan:\\n\\n${sections.raw}`;\n\t}\n\n\treturn `Execute this plan step by step. Complete each step fully before moving to the next.\\n\\n${steps.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Grill: plan interrogation\n// ============================================================================\n\n/** Which half (or both) of the grill flow to run. */\nexport type GrillTarget = \"both\" | \"me\" | \"plan\";\n\n/**\n * Parses the `/grill` argument into a target.\n *\n * Bare `/grill` runs both phases, `/grill me` only questions the user, and\n * `/grill plan` only critiques the plan. Anything else returns undefined so the\n * caller shows usage rather than guessing at intent.\n */\nexport function parseGrillTarget(args: string): GrillTarget | undefined {\n\tconst arg = args.trim().toLowerCase();\n\tif (!arg) return \"both\";\n\tif (arg === \"me\" || arg === \"plan\") return arg;\n\treturn undefined;\n}\n\n/**\n * Renders the parsed plan back into the message so the agent reviews a concrete\n * artifact rather than whatever it remembers writing. Falls back to the raw plan\n * text when no sections were recognised.\n */\nfunction renderPlanForReview(sections: PlanSections): string {\n\tconst parts: string[] = [];\n\tif (sections.goal) parts.push(`**Goal**\\n${sections.goal}`);\n\tif (sections.filesToModify) parts.push(`**Files to modify**\\n${sections.filesToModify}`);\n\tif (sections.newFiles) parts.push(`**New files**\\n${sections.newFiles}`);\n\tif (sections.tests) parts.push(`**Tests**\\n${sections.tests}`);\n\tif (sections.verification) parts.push(`**Verification**\\n${sections.verification}`);\n\treturn parts.length > 0 ? parts.join(\"\\n\\n\") : sections.raw;\n}\n\n/** Phase 1 — interrogate the request, surfacing unknowns as ask_options questions. */\nconst GRILL_ME_PROMPT = `You are interrogating the *request*, not writing code.\n\nRe-read the plan below and find where it rests on assumptions nobody confirmed: ambiguous requirements, unstated constraints, decisions you made silently because the request did not specify them, and places where a different reasonable reading of the request would produce a materially different plan.\n\nPut the most consequential of those to the user with the ask_options tool. Ask only what would actually change the plan — settle anything you can from the codebase or from convention yourself. Prefer two to four sharp questions over an exhaustive list, and mark a recommended option wherever you have a genuine preference.\n\nDo not edit files and do not revise the plan yet.`;\n\n/** Phase 2 — adversarial self-critique of the plan file. */\nconst GRILL_PLAN_PROMPT = `You are attacking the plan below, not executing it.\n\nReview it as a skeptical reviewer would:\n- Which steps rest on assumptions you have not verified in the codebase? Read the relevant files and verify them now.\n- Where could this fail silently — wrong-but-plausible behaviour rather than a loud error?\n- What does the goal require that the plan does not cover? What does the plan cover that the goal does not need?\n- Does the verification section prove the goal is met, or only that the code runs?\n\nReport what you find. Where a weakness is real, revise the plan file and state what changed. Where the plan holds up, say so plainly rather than inventing criticism. Do not implement anything.`;\n\n/**\n * Builds the follow-up message injected by `/grill`.\n *\n * The two phases are ordered rather than alternative: underspecification sits\n * upstream of plan weakness, so critiquing a plan built on a misread request\n * produces a well-reviewed plan for the wrong job. Bare `/grill` therefore asks\n * first and folds the answers into the critique.\n */\nexport function buildGrillMessage(sections: PlanSections, target: GrillTarget): string {\n\tconst plan = renderPlanForReview(sections);\n\tif (target === \"me\") return `${GRILL_ME_PROMPT}\\n\\n---\\n\\n${plan}`;\n\tif (target === \"plan\") return `${GRILL_PLAN_PROMPT}\\n\\n---\\n\\n${plan}`;\n\treturn (\n\t\t`${GRILL_ME_PROMPT}\\n\\n` +\n\t\t`Once the user has answered, fold their answers into the plan and immediately continue with this review:\\n\\n` +\n\t\t`${GRILL_PLAN_PROMPT}\\n\\n---\\n\\n${plan}`\n\t);\n}\n\n// ============================================================================\n// Goal: autonomous execution toward a completion condition\n// ============================================================================\n\n/** A parsed `/goal` invocation. */\nexport interface GoalInvocation {\n\t/** Explicit objective; falls back to the plan's Goal section when absent. */\n\tobjective?: string;\n\t/** Turn budget passed through to the autonomous loop. */\n\tmaxTurns?: number;\n}\n\n/**\n * Parses `/goal [--max-turns N] [objective]`.\n *\n * Returns undefined when `--max-turns` is present but not followed by a\n * non-negative integer, so the caller shows usage instead of silently running\n * with the default budget.\n */\nexport function parseGoalArgs(args: string): GoalInvocation | undefined {\n\tlet rest = args.trim();\n\tlet maxTurns: number | undefined;\n\n\tconst flag = /^--max-turns(?:\\s+(\\S+))?([\\s\\S]*)$/.exec(rest);\n\tif (flag) {\n\t\tconst raw = flag[1];\n\t\tif (!raw || !/^\\d+$/.test(raw)) return undefined;\n\t\tmaxTurns = Number(raw);\n\t\trest = flag[2].trim();\n\t}\n\n\treturn { objective: rest || undefined, maxTurns };\n}\n\n/** The two messages `/goal` hands to the autonomous loop. */\nexport interface GoalMessages {\n\t/** Delivered once, to start the run. */\n\ttask: string;\n\t/** Re-sent on each continuation to keep the target in view. */\n\tcontinuePrompt: string;\n}\n\n/**\n * Builds the messages for a `/goal` run.\n *\n * When the plan carries a Verification section it becomes the completion\n * condition, which is the difference between a loop that stops when it feels\n * finished and one that stops when something it can run says so. Both messages\n * restate the objective, because the loop's continuation prompt is all that\n * holds the target in place as the transcript grows.\n */\nexport function buildGoalMessages(objective: string, verification?: string): GoalMessages {\n\tconst condition = verification\n\t\t? `\\n\\nThe goal counts as complete only once this verification passes. Run it, and if it fails, fix what it reports and run it again:\\n\\n${verification}`\n\t\t: \"\";\n\n\treturn {\n\t\ttask: `Work autonomously toward this goal:\\n\\n${objective}${condition}`,\n\t\tcontinuePrompt:\n\t\t\t`Keep working toward the goal:\\n\\n${objective}${condition}\\n\\n` +\n\t\t\t`Reply with ${AUTO_LOOP_DONE_TOKEN} only when it is genuinely complete — not when it is merely close.`,\n\t};\n}\n\n// ============================================================================\n// setupMode\n// ============================================================================\n\nexport function setupMode(pi: ExtensionAPI): void {\n\tlet cachedMode = DEFAULT_MODE;\n\tlet cachedSystemPrompt: string | undefined;\n\tlet cachedPlanPath: string | undefined;\n\n\t// `/grill me` asks the user a question via ask_options, which an unattended\n\t// `/loop auto` run has nobody to answer. Track the loop's broadcast state so\n\t// the command can drop its interrogation phase instead of stalling the run.\n\tlet autoLoopActive = false;\n\tpi.events.on(LOOP_AUTO_CHANGED, (data) => {\n\t\tautoLoopActive = (data as { active?: boolean } | undefined)?.active === true;\n\t});\n\n\t// ── session_start ─────────────────────────────────────────────────────────\n\t// Config resolution order:\n\t// 1. Read global config (~/.hoocode/hoo-config.json)\n\t// 2. Read project config (./.hoocode/hoo-config.json) if present\n\t// 3. Merge — project scalars win; arrays are unioned\n\t// 4. Re-resolve active_mode from the merged result\n\n\tpi.on(\"session_start\", (_event: SessionStartEvent, ctx: ExtensionContext) => {\n\t\t// Light mode strips every fixed prompt appendix. Leaving\n\t\t// cachedSystemPrompt unset makes before_agent_start a no-op, so no\n\t\t// `<!-- hoo-core: mode= -->` block is appended.\n\t\tif (isLightModeEnv()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Steps 1–3: merge global + project configs\n\t\tconst config = readMergedConfig(ctx.cwd);\n\n\t\t// Step 4: resolve mode from the merged config\n\t\tcachedMode = config.active_mode ?? DEFAULT_MODE;\n\t\t// External search dirs come from two channels:\n\t\t// - HooConfig.mode_paths (config-declared)\n\t\t// - pi.addModeSearchPath (CLI flags + extension contributions)\n\t\tconst modePaths = mergeSearchPaths(config.mode_paths, pi.getModeSearchPaths());\n\t\tconst rawSystemPrompt = buildSystemPrompt(cachedMode, ctx.cwd, { modePaths });\n\n\t\t// Per-session plan path so concurrent sessions don't overwrite each other.\n\t\t// The `{{PLAN_PATH}}` token in plan-mode templates is substituted here.\n\t\tcachedPlanPath = getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\tconst relPlanPath = relative(ctx.cwd, cachedPlanPath) || cachedPlanPath;\n\t\tcachedSystemPrompt = rawSystemPrompt?.replace(/\\{\\{PLAN_PATH\\}\\}/g, relPlanPath);\n\n\t\t// Update footer with active mode\n\t\tif (ctx.hasUI) {\n\t\t\tctx.ui.setMode(cachedMode);\n\t\t}\n\n\t\t// Apply tool filter from mode enabled_tools\n\t\tconst modeCfg = config.modes?.[cachedMode];\n\t\tif (modeCfg?.enabled_tools && modeCfg.enabled_tools.length > 0) {\n\t\t\tpi.setActiveTools(modeCfg.enabled_tools);\n\t\t}\n\t});\n\n\t// ── before_agent_start ────────────────────────────────────────────────────\n\n\tpi.on(\"before_agent_start\", (event: BeforeAgentStartEvent): BeforeAgentStartEventResult | undefined => {\n\t\tif (!cachedSystemPrompt) return;\n\t\treturn {\n\t\t\tsystemPrompt: `${event.systemPrompt}\\n\\n<!-- hoo-core: mode=${cachedMode} -->\\n${cachedSystemPrompt}`,\n\t\t};\n\t});\n\n\t// ── /mode command ─────────────────────────────────────────────────────────\n\n\tconst KNOWN_MODES = [\"ask\", \"plan\", \"build\", \"debug\"];\n\n\tpi.registerCommand(\"mode\", {\n\t\tdescription: \"Switch active mode. Usage: /mode <ask|plan|build|debug>\",\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\tKNOWN_MODES.filter((m) => m.startsWith(prefix)).map((m) => ({ value: m, label: m })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst name = args.trim();\n\t\t\tif (!name) {\n\t\t\t\tctx.ui.notify(`Active mode: ${cachedMode}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = name === DEFAULT_MODE ? undefined : name;\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"${name}\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /plan command (shorthand for /mode plan) ──────────────────────────────\n\n\tpi.registerCommand(\"plan\", {\n\t\tdescription: \"Switch to plan mode. Shorthand for /mode plan.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"plan\";\n\t\t\twriteConfig(config);\n\t\t\tctx.ui.notify(`Mode set to \"plan\" — reloading…`, \"info\");\n\t\t\tawait ctx.reload();\n\t\t},\n\t});\n\n\t// ── /grill command ────────────────────────────────────────────────────────\n\t// Stress-tests the current plan in two phases: `me` surfaces the request's\n\t// unconfirmed assumptions as ask_options questions, `plan` critiques the plan\n\t// file itself. Unlike /approve this only injects a follow-up message — no\n\t// session switch, no mode change, no config write.\n\n\tpi.registerCommand(\"grill\", {\n\t\tdescription: \"Stress-test the current plan. Usage: /grill [me|plan]\",\n\t\tgetArgumentCompletions: (prefix: string) =>\n\t\t\t[\"me\", \"plan\"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s })),\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst requested = parseGrillTarget(args);\n\t\t\tif (!requested) {\n\t\t\t\tctx.ui.notify(\"Usage: /grill [me|plan]\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Same lookup as /approve: per-session plan first, legacy file second.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);\n\t\t\tif (loaded.status === \"error\") {\n\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (loaded.status === \"missing\") {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(`No plan to grill — ${relPlan} not found. Run /plan first.`, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Nobody is present to answer during an autonomous loop, so keep the\n\t\t\t// half of the flow that still works rather than blocking on a question.\n\t\t\tlet target = requested;\n\t\t\tif (autoLoopActive && target !== \"plan\") {\n\t\t\t\ttarget = \"plan\";\n\t\t\t\tctx.ui.notify(\"Autonomous loop active — grilling the plan only, skipping questions.\", \"info\");\n\t\t\t}\n\n\t\t\tpi.sendUserMessage(buildGrillMessage(loaded.sections, target), { deliverAs: \"followUp\" });\n\t\t},\n\t});\n\n\t// ── /goal command ─────────────────────────────────────────────────────────\n\t// Works autonomously toward a completion condition by driving the loop in\n\t// loop.ts over the LOOP_AUTO_START channel. Linear by design: a single thread\n\t// of execution that iterates until it reports done or exhausts its budget —\n\t// there is no task graph here, and no subtask fan-out.\n\t//\n\t// The run inherits whatever the active mode already permits (enabled_tools,\n\t// allowed_bash_commands, allowed_write_paths, auto_allow), so how much rope\n\t// an unattended goal gets is a mode-config decision, not one made here.\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Work autonomously toward a goal. Usage: /goal [--max-turns N] [objective]\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tconst parsed = parseGoalArgs(args);\n\t\t\tif (!parsed) {\n\t\t\t\tctx.ui.notify(\"Usage: /goal [--max-turns N] [objective]\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The plan supplies the objective when none was typed, and its\n\t\t\t// verification section becomes the completion condition either way.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);\n\t\t\tif (loaded.status === \"error\") {\n\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst sections = loaded.status === \"loaded\" ? loaded.sections : undefined;\n\n\t\t\tconst objective = parsed.objective ?? sections?.goal;\n\t\t\tif (!objective) {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`No objective — pass one as /goal <objective>, or write a Goal section in ${relPlan}.`,\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst { task, continuePrompt } = buildGoalMessages(objective, sections?.verification);\n\t\t\t// The loop announces itself on start, so nothing to notify here.\n\t\t\tpi.events.emit(LOOP_AUTO_START, {\n\t\t\t\ttask,\n\t\t\t\tmaxTurns: parsed.maxTurns,\n\t\t\t\tcontinuePrompt,\n\t\t\t} satisfies LoopAutoStartPayload);\n\t\t},\n\t});\n\n\t// ── /approve command ──────────────────────────────────────────────────────\n\t// Reads .hoocode/plan.md, parses it into named sections (Goal, Files to\n\t// modify, New files, Tests, Verification), switches to build mode, then\n\t// injects a step-by-step execution message into the new session.\n\n\tpi.registerCommand(\"approve\", {\n\t\tdescription: \"Approve the current plan and switch to build mode to execute it.\",\n\t\tgetArgumentCompletions: () => [],\n\t\thandler: async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {\n\t\t\tif (cachedMode !== \"plan\") {\n\t\t\t\tctx.ui.notify(`/approve is only available in plan mode (current mode: \"${cachedMode}\")`, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Prefer the per-session plan file, fall back to the legacy single file.\n\t\t\tconst sessionPlanPath = cachedPlanPath ?? getPlanPath(ctx.cwd, ctx.sessionManager.getSessionId());\n\t\t\tconst loaded = loadPlanSections([sessionPlanPath, getLegacyPlanPath(ctx.cwd)]);\n\t\t\tif (loaded.status === \"error\") {\n\t\t\t\tctx.ui.notify(`Could not read ${relative(ctx.cwd, loaded.path) || loaded.path}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst approveMessage = loaded.status === \"loaded\" ? buildApproveMessage(loaded.sections) : undefined;\n\n\t\t\t// Switch global config to build mode\n\t\t\tconst config = readConfig();\n\t\t\tconfig.active_mode = \"build\";\n\t\t\twriteConfig(config);\n\n\t\t\tif (approveMessage) {\n\t\t\t\t// Open a new build-mode session and deliver the parsed plan as the\n\t\t\t\t// first user message so the agent starts executing immediately\n\t\t\t\tawait ctx.newSession({\n\t\t\t\t\twithSession: async (replacedCtx) => {\n\t\t\t\t\t\tawait replacedCtx.sendUserMessage(approveMessage!, { deliverAs: \"followUp\" });\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst relPlan = relative(ctx.cwd, sessionPlanPath) || sessionPlanPath;\n\t\t\t\tctx.ui.notify(`Switched to build mode. No ${relPlan} found — describe what to build.`, \"info\");\n\t\t\t\tawait ctx.reload();\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"init-templates.generated.d.ts","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,uBAAuB,EAAE,MAC+Z,CAAC;AAEtc,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAKjD,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,CAAC;AAE5D,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAMzD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution.\"\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running commands that change state\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls\\nmodel: fast\\nbackground: true\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No other agent clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer the explore agent when the task is clearly read-only.\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with other write tasks on the same files\\ntools: read, bash, edit, write, grep, find, ls\\nmodel: standard\\ndelegate: true\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nDelegation:\\n- When the Task tool is available (subagents enabled and the nesting cap allows it), you may delegate self-contained, independent subtasks — for example dispatch an `explore` subagent to investigate a separate area while you work. Otherwise do the work directly.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\tplan: \"---\\nname: plan\\ndescription: |\\n Use this subagent when:\\n - You need to research a codebase before proposing an implementation plan\\n - A task requires understanding scope, affected files, and approach without\\n making any changes yet\\n - You are in plan mode and want focused investigation to back the plan\\n\\n DO NOT use for:\\n - Making code changes (this agent is read-only)\\n - Quick single-file lookups (use explore)\\n\\n Output: A concrete plan — the approach, the files to change, and the steps.\\n Cost: Low–medium (read-only)\\n Isolation: Can run in parallel with explore tasks\\ntools: read, grep, find, ls\\nmodel: standard\\nbackground: true\\n---\\nYou are a planning agent running inside hoocode. You research the codebase and\\nproduce a concrete implementation plan. You NEVER modify files. You run in an\\nisolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not create, modify, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to understand the code and its structure.\\n\\nMethod:\\n1. Restate the goal and identify what you need to learn to plan it.\\n2. Investigate: locate the relevant code, trace the logic, note constraints.\\n3. Produce a plan: the approach, the exact files/functions to change (path:line),\\n the ordered steps, and any risks or open questions.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make the plan\\n self-contained and actionable.\\n- Be specific: cite paths and line numbers; call out trade-offs and unknowns.\\n- Do not narrate your search or include tool logs.\\n\",\n};\n"]}
1
+ {"version":3,"file":"init-templates.generated.d.ts","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,uBAAuB,EAAE,MAC+Z,CAAC;AAEtc,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAKjD,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,CAAC;AAE5D,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAMzD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run\\n `/grill` to stress-test it, then `/approve` to execute it step by step or\\n `/goal` to work toward it autonomously.\" Recommend `/grill` first whenever the\\n plan carries real risk — it surfaces weak assumptions before any code changes.\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running commands that change state\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls\\nmodel: fast\\nbackground: true\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No other agent clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer the explore agent when the task is clearly read-only.\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with other write tasks on the same files\\ntools: read, bash, edit, write, grep, find, ls\\nmodel: standard\\ndelegate: true\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nDelegation:\\n- When the Task tool is available (subagents enabled and the nesting cap allows it), you may delegate self-contained, independent subtasks — for example dispatch an `explore` subagent to investigate a separate area while you work. Otherwise do the work directly.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\tplan: \"---\\nname: plan\\ndescription: |\\n Use this subagent when:\\n - You need to research a codebase before proposing an implementation plan\\n - A task requires understanding scope, affected files, and approach without\\n making any changes yet\\n - You are in plan mode and want focused investigation to back the plan\\n\\n DO NOT use for:\\n - Making code changes (this agent is read-only)\\n - Quick single-file lookups (use explore)\\n\\n Output: A concrete plan — the approach, the files to change, and the steps.\\n Cost: Low–medium (read-only)\\n Isolation: Can run in parallel with explore tasks\\ntools: read, grep, find, ls\\nmodel: standard\\nbackground: true\\n---\\nYou are a planning agent running inside hoocode. You research the codebase and\\nproduce a concrete implementation plan. You NEVER modify files. You run in an\\nisolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not create, modify, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to understand the code and its structure.\\n\\nMethod:\\n1. Restate the goal and identify what you need to learn to plan it.\\n2. Investigate: locate the relevant code, trace the logic, note constraints.\\n3. Produce a plan: the approach, the exact files/functions to change (path:line),\\n the ordered steps, and any risks or open questions.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make the plan\\n self-contained and actionable.\\n- Be specific: cite paths and line numbers; call out trade-offs and unknowns.\\n- Do not narrate your search or include tool logs.\\n\",\n};\n"]}
@@ -6,7 +6,7 @@ export const EMBEDDED_MODES = {
6
6
  ask: "You are in **ask mode** — read-only Q&A.\n\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\nForbidden: edit files, write files, run commands that modify state.\n\nWhen answering:\n- Cite file paths and line numbers.\n- Prefer precise over verbose.\n- If a question requires a code change to answer properly, describe the change; do not apply it.\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\n",
7
7
  build: "You are in **build mode** — implement carefully, one step at a time.\n\nRules:\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\n- **Read before editing.** Never write to a file you have not read in this session.\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\n- **Match existing style** — indentation, naming, import order.\n- **Run tests** after every logical unit of change. Fix failures before continuing.\n",
8
8
  debug: "You are in **debug mode** — root-cause analysis only, no file modifications.\n\nProcess:\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\n2. **Reproduce** — identify the minimal condition that triggers the bug.\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\n4. **State the root cause** in one clear sentence.\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\n\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\n",
9
- plan: 'You are in **plan mode** — explore and design, no source edits.\n\nYour job: produce a complete, actionable implementation plan.\n\nSteps:\n1. Read relevant files and ask clarifying questions before drafting.\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\n - **Goal** — one sentence.\n - **Files to modify** — path, line range, what changes.\n - **New files** — path, purpose.\n - **Tests** — what to add or update.\n - **Verification** — commands to confirm correctness.\n3. After writing the plan, tell the user: "Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution."\n\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\n',
9
+ plan: 'You are in **plan mode** — explore and design, no source edits.\n\nYour job: produce a complete, actionable implementation plan.\n\nSteps:\n1. Read relevant files and ask clarifying questions before drafting.\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\n - **Goal** — one sentence.\n - **Files to modify** — path, line range, what changes.\n - **New files** — path, purpose.\n - **Tests** — what to add or update.\n - **Verification** — commands to confirm correctness.\n3. After writing the plan, tell the user: "Plan written to `{{PLAN_PATH}}`. Run\n `/grill` to stress-test it, then `/approve` to execute it step by step or\n `/goal` to work toward it autonomously." Recommend `/grill` first whenever the\n plan carries real risk — it surfaces weak assumptions before any code changes.\n\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\n',
10
10
  };
11
11
  export const EMBEDDED_PROFILES = {};
12
12
  export const EMBEDDED_AGENT_PROMPTS = {
@@ -1 +1 @@
1
- {"version":3,"file":"init-templates.generated.js","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAAA,iEAA+D;AAC/D,sDAAsD;AACtD,wCAAwC;AAExC,MAAM,CAAC,MAAM,uBAAuB,GACnC,ocAAoc,CAAC;AAEtc,MAAM,CAAC,MAAM,cAAc,GAA2B;IACrD,GAAG,EAAE,ogBAAkgB;IACvgB,KAAK,EAAE,unBAAmnB;IAC1nB,KAAK,EAAE,6pBAAipB;IACxpB,IAAI,EAAE,isBAAqrB;CAC3rB,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAA2B,EAAE,CAAC;AAE5D,MAAM,CAAC,MAAM,sBAAsB,GAA2B;IAC7D,OAAO,EACN,y4CAAy4C;IAC14C,iBAAiB,EAChB,s7DAAo7D;IACr7D,IAAI,EAAE,0jDAAsjD;CAC5jD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution.\"\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running commands that change state\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls\\nmodel: fast\\nbackground: true\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No other agent clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer the explore agent when the task is clearly read-only.\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with other write tasks on the same files\\ntools: read, bash, edit, write, grep, find, ls\\nmodel: standard\\ndelegate: true\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nDelegation:\\n- When the Task tool is available (subagents enabled and the nesting cap allows it), you may delegate self-contained, independent subtasks — for example dispatch an `explore` subagent to investigate a separate area while you work. Otherwise do the work directly.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\tplan: \"---\\nname: plan\\ndescription: |\\n Use this subagent when:\\n - You need to research a codebase before proposing an implementation plan\\n - A task requires understanding scope, affected files, and approach without\\n making any changes yet\\n - You are in plan mode and want focused investigation to back the plan\\n\\n DO NOT use for:\\n - Making code changes (this agent is read-only)\\n - Quick single-file lookups (use explore)\\n\\n Output: A concrete plan — the approach, the files to change, and the steps.\\n Cost: Low–medium (read-only)\\n Isolation: Can run in parallel with explore tasks\\ntools: read, grep, find, ls\\nmodel: standard\\nbackground: true\\n---\\nYou are a planning agent running inside hoocode. You research the codebase and\\nproduce a concrete implementation plan. You NEVER modify files. You run in an\\nisolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not create, modify, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to understand the code and its structure.\\n\\nMethod:\\n1. Restate the goal and identify what you need to learn to plan it.\\n2. Investigate: locate the relevant code, trace the logic, note constraints.\\n3. Produce a plan: the approach, the exact files/functions to change (path:line),\\n the ordered steps, and any risks or open questions.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make the plan\\n self-contained and actionable.\\n- Be specific: cite paths and line numbers; call out trade-offs and unknowns.\\n- Do not narrate your search or include tool logs.\\n\",\n};\n"]}
1
+ {"version":3,"file":"init-templates.generated.js","sourceRoot":"","sources":["../src/init-templates.generated.ts"],"names":[],"mappings":"AAAA,iEAA+D;AAC/D,sDAAsD;AACtD,wCAAwC;AAExC,MAAM,CAAC,MAAM,uBAAuB,GACnC,ocAAoc,CAAC;AAEtc,MAAM,CAAC,MAAM,cAAc,GAA2B;IACrD,GAAG,EAAE,ogBAAkgB;IACvgB,KAAK,EAAE,unBAAmnB;IAC1nB,KAAK,EAAE,6pBAAipB;IACxpB,IAAI,EAAE,u5BAAy4B;CAC/4B,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAA2B,EAAE,CAAC;AAE5D,MAAM,CAAC,MAAM,sBAAsB,GAA2B;IAC7D,OAAO,EACN,y4CAAy4C;IAC14C,iBAAiB,EAChB,s7DAAo7D;IACr7D,IAAI,EAAE,0jDAAsjD;CAC5jD,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/embed-templates.mjs — do not edit.\n// Source of truth: packages/coding-agent/templates/**\n// Regenerated on every `npm run build`.\n\nexport const EMBEDDED_DEFAULT_CONFIG: string =\n\t'{\\n \"version\": \"1.0\",\\n \"active_mode\": \"build\",\\n \"llm\": {\\n \"default_provider\": \"anthropic\",\\n \"providers\": {\\n \"anthropic\": { \"api_key_env\": \"ANTHROPIC_API_KEY\" },\\n \"openai\": { \"api_key_env\": \"OPENAI_API_KEY\" }\\n }\\n },\\n \"modes\": {\\n \"ask\": { \"auto_allow\": [\"read\"] },\\n \"plan\": { \"auto_allow\": [\"read\", \"write\"] },\\n \"build\": { \"auto_allow\": [\"read\"] },\\n \"debug\": { \"auto_allow\": [\"read\", \"bash\"] }\\n }\\n}\\n';\n\nexport const EMBEDDED_MODES: Record<string, string> = {\n\task: \"You are in **ask mode** — read-only Q&A.\\n\\nPermitted: read files, run grep/find, explain code, trace logic, compare approaches, debug conceptually.\\nForbidden: edit files, write files, run commands that modify state.\\n\\nWhen answering:\\n- Cite file paths and line numbers.\\n- Prefer precise over verbose.\\n- If a question requires a code change to answer properly, describe the change; do not apply it.\\n- If the user asks you to edit something, decline and suggest switching to build mode with `/mode build`.\\n\",\n\tbuild: \"You are in **build mode** — implement carefully, one step at a time.\\n\\nRules:\\n- **One tool per turn.** Plan the action, call the tool, wait for the result before proceeding.\\n- **Read before editing.** Never write to a file you have not read in this session.\\n- **Show diffs** before applying non-trivial edits; wait for implicit acceptance.\\n- **Dangerous ops** (delete, force-push, drop table, rm -rf): state what you are about to do and wait for explicit confirmation.\\n- **Match existing style** — indentation, naming, import order.\\n- **Run tests** after every logical unit of change. Fix failures before continuing.\\n\",\n\tdebug: \"You are in **debug mode** — root-cause analysis only, no file modifications.\\n\\nProcess:\\n1. **Gather evidence** — read logs, error traces, and relevant source. Run safe diagnostic commands (grep, find, read, non-mutating shell commands).\\n2. **Reproduce** — identify the minimal condition that triggers the bug.\\n3. **Trace** — follow the full call path from entry point to failure site, citing file and line at each step.\\n4. **State the root cause** in one clear sentence.\\n5. **Describe the fix** — files, lines, and what to change — but do not apply it.\\n\\nForbidden: edit or write any file. To apply a fix, switch to build mode with `/mode build`.\\n\",\n\tplan: 'You are in **plan mode** — explore and design, no source edits.\\n\\nYour job: produce a complete, actionable implementation plan.\\n\\nSteps:\\n1. Read relevant files and ask clarifying questions before drafting.\\n2. Write the finished plan to `{{PLAN_PATH}}` with these sections:\\n - **Goal** — one sentence.\\n - **Files to modify** — path, line range, what changes.\\n - **New files** — path, purpose.\\n - **Tests** — what to add or update.\\n - **Verification** — commands to confirm correctness.\\n3. After writing the plan, tell the user: \"Plan written to `{{PLAN_PATH}}`. Run\\n `/grill` to stress-test it, then `/approve` to execute it step by step or\\n `/goal` to work toward it autonomously.\" Recommend `/grill` first whenever the\\n plan carries real risk — it surfaces weak assumptions before any code changes.\\n\\nForbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.\\n',\n};\n\nexport const EMBEDDED_PROFILES: Record<string, string> = {};\n\nexport const EMBEDDED_AGENT_PROMPTS: Record<string, string> = {\n\texplore:\n\t\t\"---\\nname: explore\\ndescription: |\\n Use this subagent ONLY when:\\n - Reading or understanding code without changes\\n - Scouting a codebase for plans or maps\\n - Analyzing dependencies, imports, project structure\\n - Investigating errors or tracing execution flow\\n - Estimating scope before edits\\n\\n DO NOT use for:\\n - Writing or modifying code\\n - Running commands that change state\\n\\n Output: Concise summary, file list, or plan. No code changes.\\n Cost: Low (read-only)\\n Isolation: Can run in parallel with other explore tasks\\ntools: read, grep, find, ls\\nmodel: fast\\nbackground: true\\n---\\nYou are an explore-only agent running inside hoocode. You read code and produce summaries. You NEVER edit files. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not modify, create, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to locate and understand code.\\n\\nMethod:\\n1. Break the task into concrete questions.\\n2. Search broadly, then read the specific files that matter.\\n3. Trace logic across files; note exact paths and line numbers.\\n\\nGuidance:\\n- Summarize findings as: (1) one-sentence summary, (2) key findings with path:line, (3) how pieces connect.\\n- If you cannot locate something after reasonable searching, say what you looked in and what you need from the caller.\\n- Do not narrate your search or include tool logs.\\n\",\n\t\"general-purpose\":\n\t\t\"---\\nname: general-purpose\\ndescription: |\\n Use this subagent when:\\n - A task is multi-step or open-ended and needs both investigation and action\\n - No other agent clearly fits\\n - You are searching for code or a pattern and are unsure where it lives\\n - The work spans reading, editing, and running commands together\\n\\n Prefer the explore agent when the task is clearly read-only.\\n\\n Output: The completed result plus a summary of what was done and where.\\n Cost: Variable (read + write + run)\\n Isolation: Should not run concurrently with other write tasks on the same files\\ntools: read, bash, edit, write, grep, find, ls\\nmodel: standard\\ndelegate: true\\n---\\nYou are a general-purpose subagent running inside hoocode. You handle multi-step and open-ended tasks end to end. You run in an isolated context and cannot see the parent conversation.\\n\\nScope:\\n- You may read, search, edit, and write files, and run commands needed to complete the task.\\n- Stay within the requested task. Do not refactor or change unrelated code.\\n\\nMethod:\\n1. Break the task into concrete steps.\\n2. Investigate before acting: read the relevant files and trace the logic.\\n3. Make the smallest changes that fully satisfy the task, matching existing style.\\n4. Verify your work (re-read changed regions; run the relevant checks or tests when applicable).\\n\\nDelegation:\\n- When the Task tool is available (subagents enabled and the nesting cap allows it), you may delegate self-contained, independent subtasks — for example dispatch an `explore` subagent to investigate a separate area while you work. Otherwise do the work directly.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make it self-contained.\\n- Summarize what you did and where (path:line), and any follow-up the caller should know.\\n- Do not narrate intermediate steps or include tool logs.\\n- If you hit a blocker, stop and report it. Do not leave the codebase in a broken state.\\n\",\n\tplan: \"---\\nname: plan\\ndescription: |\\n Use this subagent when:\\n - You need to research a codebase before proposing an implementation plan\\n - A task requires understanding scope, affected files, and approach without\\n making any changes yet\\n - You are in plan mode and want focused investigation to back the plan\\n\\n DO NOT use for:\\n - Making code changes (this agent is read-only)\\n - Quick single-file lookups (use explore)\\n\\n Output: A concrete plan — the approach, the files to change, and the steps.\\n Cost: Low–medium (read-only)\\n Isolation: Can run in parallel with explore tasks\\ntools: read, grep, find, ls\\nmodel: standard\\nbackground: true\\n---\\nYou are a planning agent running inside hoocode. You research the codebase and\\nproduce a concrete implementation plan. You NEVER modify files. You run in an\\nisolated context and cannot see the parent conversation.\\n\\nScope:\\n- Do not create, modify, or delete files, and do not run commands.\\n- Use read, grep, find, and ls to understand the code and its structure.\\n\\nMethod:\\n1. Restate the goal and identify what you need to learn to plan it.\\n2. Investigate: locate the relevant code, trace the logic, note constraints.\\n3. Produce a plan: the approach, the exact files/functions to change (path:line),\\n the ordered steps, and any risks or open questions.\\n\\nGuidance:\\n- Your final answer is the only thing the caller receives. Make the plan\\n self-contained and actionable.\\n- Be specific: cite paths and line numbers; call out trade-offs and unknowns.\\n- Do not narrate your search or include tool logs.\\n\",\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kolisachint/hoocode-extension-custom-provider-anthropic",
3
3
  "private": true,
4
- "version": "0.2.151",
4
+ "version": "0.2.153",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "bun": ">=1.0.0"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kolisachint/hoocode-extension-custom-provider-gitlab-duo",
3
3
  "private": true,
4
- "version": "0.2.151",
4
+ "version": "0.2.153",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "bun": ">=1.0.0"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kolisachint/hoocode-extension-sandbox",
3
3
  "private": true,
4
- "version": "0.2.151",
4
+ "version": "0.2.153",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "bun": ">=1.0.0"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kolisachint/hoocode-extension-with-deps",
3
3
  "private": true,
4
- "version": "0.2.151",
4
+ "version": "0.2.153",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "bun": ">=1.0.0"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kolisachint/hoocode-agent",
3
- "version": "0.4.154",
3
+ "version": "0.4.156",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "hoocodeConfig": {
@@ -45,9 +45,9 @@
45
45
  "prepublishOnly": "npm run clean && npm run build"
46
46
  },
47
47
  "dependencies": {
48
- "@kolisachint/hoocode-agent-core": "^0.4.154",
49
- "@kolisachint/hoocode-ai": "^0.4.154",
50
- "@kolisachint/hoocode-tui": "^0.4.154",
48
+ "@kolisachint/hoocode-agent-core": "^0.4.156",
49
+ "@kolisachint/hoocode-ai": "^0.4.156",
50
+ "@kolisachint/hoocode-tui": "^0.4.156",
51
51
  "@silvia-odwyer/photon-node": "^0.3.4",
52
52
  "chalk": "^5.5.0",
53
53
  "cli-highlight": "^2.1.11",
@@ -10,6 +10,9 @@ Steps:
10
10
  - **New files** — path, purpose.
11
11
  - **Tests** — what to add or update.
12
12
  - **Verification** — commands to confirm correctness.
13
- 3. After writing the plan, tell the user: "Plan written to `{{PLAN_PATH}}`. Run `/approve` to begin execution."
13
+ 3. After writing the plan, tell the user: "Plan written to `{{PLAN_PATH}}`. Run
14
+ `/grill` to stress-test it, then `/approve` to execute it step by step or
15
+ `/goal` to work toward it autonomously." Recommend `/grill` first whenever the
16
+ plan carries real risk — it surfaces weak assumptions before any code changes.
14
17
 
15
18
  Forbidden: edit any source file. Only `{{PLAN_PATH}}` may be written.