@kolisachint/hoocode-agent 0.4.155 → 0.4.157
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 +73 -0
- package/dist/core/context-files.d.ts +14 -4
- package/dist/core/context-files.d.ts.map +1 -1
- package/dist/core/context-files.js +7 -4
- package/dist/core/context-files.js.map +1 -1
- package/dist/core/format-tokens.d.ts +9 -0
- package/dist/core/format-tokens.d.ts.map +1 -0
- package/dist/core/format-tokens.js +19 -0
- package/dist/core/format-tokens.js.map +1 -0
- package/dist/core/mcp-status.d.ts +32 -0
- package/dist/core/mcp-status.d.ts.map +1 -0
- package/dist/core/mcp-status.js +27 -0
- package/dist/core/mcp-status.js.map +1 -0
- package/dist/core/mode-prompts.d.ts.map +1 -1
- package/dist/core/mode-prompts.js +3 -1
- package/dist/core/mode-prompts.js.map +1 -1
- package/dist/core/resource-loader.d.ts +6 -16
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/wordmark.d.ts +2 -2
- package/dist/core/wordmark.d.ts.map +1 -1
- package/dist/core/wordmark.js +4 -4
- package/dist/core/wordmark.js.map +1 -1
- package/dist/extensions/core/hoo-core.d.ts +3 -0
- package/dist/extensions/core/hoo-core.d.ts.map +1 -1
- package/dist/extensions/core/hoo-core.js +3 -0
- package/dist/extensions/core/hoo-core.js.map +1 -1
- package/dist/extensions/core/loop.d.ts +22 -0
- package/dist/extensions/core/loop.d.ts.map +1 -1
- package/dist/extensions/core/loop.js +36 -6
- package/dist/extensions/core/loop.js.map +1 -1
- package/dist/extensions/core/mcp-loader.d.ts.map +1 -1
- package/dist/extensions/core/mcp-loader.js +27 -3
- package/dist/extensions/core/mcp-loader.js.map +1 -1
- package/dist/extensions/core/modes.d.ts +52 -1
- package/dist/extensions/core/modes.d.ts.map +1 -1
- package/dist/extensions/core/modes.js +221 -18
- package/dist/extensions/core/modes.js.map +1 -1
- package/dist/init-templates.generated.d.ts.map +1 -1
- package/dist/init-templates.generated.js +1 -1
- package/dist/init-templates.generated.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -11
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-panel.js +1 -9
- package/dist/modes/interactive/components/task-panel.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +14 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +50 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-controller.d.ts +6 -0
- package/dist/modes/interactive/model-controller.d.ts.map +1 -1
- package/dist/modes/interactive/model-controller.js +33 -14
- package/dist/modes/interactive/model-controller.js.map +1 -1
- package/dist/modes/interactive/resource-display.d.ts +22 -0
- package/dist/modes/interactive/resource-display.d.ts.map +1 -1
- package/dist/modes/interactive/resource-display.js +73 -16
- package/dist/modes/interactive/resource-display.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
- package/templates/modes/plan/system.md +4 -1
|
@@ -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
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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;;;;;;;;;;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,MAAM,aAAa,CAAC;AAE1F,MAAM,WAAW,GAAG,aAAa,EAAE,CAAC;AAEpC;;;GAGG;AACH,SAAS,WAAW,CAAC,GAAW,EAAE,SAAiB,EAAU;IAC5D,OAAO,IA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E,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,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,eAAe,EAA6B,MAAM,WAAW,CAAC;AAEhH,MAAM,WAAW,GAAG,aAAa,EAAE,CAAC;AAEpC;;;GAGG;AACH,SAAS,WAAW,CAAC,GAAW,EAAE,SAAiB,EAAU;IAC5D,OAAO,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,SAAS,KAAK,CAAC,CAAC;AAAA,CACzD;AAED,uFAAuF;AACvF,SAAS,iBAAiB,CAAC,GAAW,EAAU;IAC/C,OAAO,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;AAAA,CACxC;AAED,SAAS,WAAW,CAAC,IAAY,EAAsB;IACtD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE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B,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
|
|
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
|
|
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,
|
|
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"]}
|