kaizen-agent 1.70.0 → 1.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +2 -2
  2. package/cli/annotate-proxy.ts +5 -0
  3. package/cli/automations.ts +10 -3
  4. package/cli/browser.ts +1 -1
  5. package/cli/chat.ts +9 -1
  6. package/cli/chatgpt.ts +2 -1
  7. package/cli/docs.ts +1 -1
  8. package/cli/google.ts +2 -1
  9. package/cli/handoff.ts +1 -1
  10. package/cli/install.ts +63 -17
  11. package/cli/knowledge.ts +1 -1
  12. package/cli/notes.ts +10 -1
  13. package/cli/preflight.ts +149 -0
  14. package/cli/rea.ts +199 -0
  15. package/cli/settings.ts +5 -1
  16. package/cli/sources.ts +3 -2
  17. package/cli/state.ts +43 -5
  18. package/cli/versions.ts +1 -1
  19. package/cli/video.ts +1 -1
  20. package/cli/web.ts +111 -28
  21. package/cli/workers.ts +20 -7
  22. package/cli/worktree.ts +65 -21
  23. package/package.json +1 -1
  24. package/skills/kaizen/SKILL.md +12 -8
  25. package/skills/kaizen/config.default.yml +18 -2
  26. package/skills/kaizen/settings.md +3 -1
  27. package/skills/kaizen/spec-build.md +13 -2
  28. package/skills/kaizen/spec-main.md +15 -0
  29. package/skills/kaizen/spec-plan.md +4 -1
  30. package/skills/kaizen-help/SKILL.md +2 -0
  31. package/skills/media/kaizen-game/SKILL.md +96 -0
  32. package/skills/media/kaizen-game/assets/gdd.css +12 -0
  33. package/skills/media/kaizen-game/references/build.md +81 -0
  34. package/skills/media/kaizen-game/references/content.md +32 -0
  35. package/skills/media/kaizen-game/references/design.md +81 -0
  36. package/skills/media/kaizen-game/references/ship.md +34 -0
  37. package/skills/media/kaizen-game/references/verify.md +33 -0
  38. package/skills/media/kaizen-game/scripts/check.sh +13 -0
  39. package/skills/media/kaizen-game/scripts/frames.mjs +34 -0
  40. package/skills/media/kaizen-game/scripts/gdd-pdf.mjs +19 -0
  41. package/skills/media/kaizen-game/scripts/pw.mjs +18 -0
  42. package/skills/media/kaizen-game/scripts/serve.mjs +53 -0
  43. package/skills/media/kaizen-game/scripts/serve.test.mjs +18 -0
  44. package/skills/media/kaizen-game/scripts/setup.sh +9 -0
  45. package/skills/media/kaizen-game/scripts/smoke.mjs +40 -0
  46. package/skills/media/kaizen-game/skill.json +1 -0
  47. package/web/board/git.ts +23 -6
  48. package/web/board/icebox.ts +6 -3
  49. package/web/board/markdown.ts +7 -2
  50. package/web/board/run-view.ts +1 -1
  51. package/web/board/settings-orchestration.ts +1 -1
  52. package/web/board/settings-pages.ts +1 -0
  53. package/web/board/settings-skills.ts +28 -2
  54. package/web/board/settings.ts +2 -2
  55. package/web/board.html +1 -1
  56. package/web/board.js +96 -82
  57. package/web/notebook.js +1 -1
  58. package/web/term.js +48 -48
  59. package/web/term.ts +16 -4
  60. package/web/video.js +1 -1
package/cli/web.ts CHANGED
@@ -15,8 +15,9 @@ import { ACCOUNT_VAR, accountDir, addAccount, readAccounts, renameAccount, signe
15
15
  import { readReport, signalOf } from "./report.ts";
16
16
  import { MAX_IMAGE, saveImage } from "./term-image.ts";
17
17
  import { bundledSkills, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
18
+ import * as rea from "./rea.ts";
18
19
  import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
19
- import { agentLine, failStart, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
20
+ import { agentLine, failStart, handoffModel, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
20
21
  import { childDied, childQuiet, markWoken, move, requestOpen, readHandoff, refused, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
21
22
  import { processTable, storage, systemMemory, treeRss, type Root } from "./resources.ts";
22
23
  import { attachPty, frames, writePty, submitPty, resizePty, exitPty, killPty, panePid, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
@@ -287,12 +288,33 @@ export async function web(repoDir: string, opts: Opts = {}) {
287
288
  const sameOrigin = (req: Request) => {
288
289
  const origin = req.headers.get("origin");
289
290
  let same = !origin;
290
- try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host") || extraHosts.has(o.hostname); } } catch { /* bad origin */ }
291
+ try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host"); } } catch { /* bad origin */ }
291
292
  return same;
292
293
  };
293
294
  // One-time token for turning an off-by-default skill on; each GET /skills mints a new one. It stops
294
295
  // an agent switching itself on by accident, not a local process that reads the board's own page.
295
296
  let skillToken = "";
297
+ // A preflight that stopped a land: its one-time go-ahead, per run and step, and what it found.
298
+ const preflights = new Map<string, { token: string; p: import("./preflight.ts").Preflight }>();
299
+ // Runs the preflight before a push or merge. null: go on. Otherwise the 409 to send back.
300
+ const gatePreflight = async (dir: string, id: string, op: string, override: unknown, extraFiles: string[] = []) => {
301
+ const { preflight, writePreflight } = await import("./preflight.ts");
302
+ const project = dirname(dir), k = `${dir}\0${id}\0${op}`, held = preflights.get(k);
303
+ if (held && typeof override === "string" && override === held.token) {
304
+ preflights.delete(k);
305
+ writePreflight(project, id, held.p, "go ahead (user)");
306
+ return null;
307
+ }
308
+ preflights.delete(k);
309
+ const p = await preflight(project, id, { extraFiles });
310
+ writePreflight(project, id, p, p.clean ? "clean" : "stopped");
311
+ if (p.clean) return null;
312
+ const token = crypto.randomUUID();
313
+ preflights.set(k, { token, p });
314
+ return json({ ok: false, why: "Stopped before landing: other work needs a look first.", preflight: { issues: p.issues, notes: p.notes, base: p.base, branch: p.branch }, token }, 409);
315
+ };
316
+ // REA: a plan the page showed, bound to its one-time token. Only that plan is ever applied.
317
+ let reaPending: { token: string; version: string; clients: string[] } | null = null;
296
318
  const strict = (req: Request) => {
297
319
  if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
298
320
  if (!/^application\/json\b/i.test(req.headers.get("content-type") ?? "")) return bad("json body expected", 415);
@@ -502,7 +524,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
502
524
  const cwd = codeDir(project, id), key = "sh-" + crypto.randomUUID().slice(0, 8);
503
525
  const prompt = `/kaizen run ${id}. You are the worktree agent of this run: the project is ${project}, its run files are in ${join(dir, "runs", id)}, and you work in ${cwd}. ` +
504
526
  `Build, review and run the fix loop as the spec says. Do not run kaizen done or land. When finished run: kaizen handoff done. If you cannot go on run: kaizen handoff blocked "<reason>".`;
505
- const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own");
527
+ const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own", undefined, handoffModel(project, id));
506
528
  if (typeof l === "string") { refused(dir, id, l); changed(); return; }
507
529
  if (!started(dir, id, key)) return; // declined meanwhile: the first agent is building
508
530
  for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
@@ -711,6 +733,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
711
733
  // arrives with that hostname in Host, and gets nothing.
712
734
  const hostname = (req.headers.get("host") ?? "").toLowerCase().replace(/:\d+$/, "");
713
735
  if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
736
+ // `tailscale serve` stamps every tailnet request with the caller's login; `tailscale funnel` (the
737
+ // public internet) does not. A tailnet name reached without it is not a tailnet peer.
738
+ if (hostname.endsWith(".ts.net") && !req.headers.get("tailscale-user-login")) return new Response("forbidden", { status: 403 });
714
739
  if (req.method !== "GET") { stateGen++; gitGen++; }
715
740
  const url = new URL(req.url);
716
741
  const path = url.pathname;
@@ -762,7 +787,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
762
787
  // board when no window shows it) and close the popup. Hyprland moves windows;
763
788
  // elsewhere only the popup opens and closes.
764
789
  if (req.method === "POST" && (path === "/popup/open" || path === "/popup/board")) {
790
+ const refused = strict(req);
791
+ if (refused) return refused;
765
792
  const body = await req.json().catch(() => ({}));
793
+ if (body?.id != null && !/^(?!\.+$)[\w.-]+$/.test(String(body.id))) return bad("bad id");
766
794
  const chat = (...a: string[]) => Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "chat", "--port", String(new URL(req.url).port || DEFAULT_PORT), ...a], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exited;
767
795
  const hypr = !!process.env.HYPRLAND_INSTANCE_SIGNATURE && !!Bun.which("hyprctl");
768
796
  const json = async (cmd: string) => await Bun.$`hyprctl ${cmd} -j`.quiet().nothrow().json().catch(() => null);
@@ -779,7 +807,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
779
807
  if ((await Bun.$`hyprctl dispatch ${lua}`.quiet().nothrow().text()).trim() !== "ok") await Bun.$`hyprctl dispatch ${legacy}`.quiet().nothrow();
780
808
  };
781
809
  if (path === "/popup/open") {
782
- const id = typeof body.id === "string" && /^[\w.-]+$/.test(body.id) ? body.id : "";
810
+ const id = typeof body.id === "string" && /^(?!\.+$)[\w.-]+$/.test(body.id) ? body.id : "";
783
811
  await chat("--show", ...(id ? ["--chat", id] : []));
784
812
  if (w) await dispatch(`hl.dsp.window.move({ workspace = "special:kaizen", follow = false, window = "${w}" })`, ["movetoworkspacesilent", `special:kaizen,${w}`]);
785
813
  // Typing goes to the popup, not to whatever was under the hidden board.
@@ -908,7 +936,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
908
936
  if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
909
937
  if (!/^image\//i.test(req.headers.get("content-type") ?? "")) return bad("image body expected", 415);
910
938
  if (Number(req.headers.get("content-length") ?? 0) > MAX_IMAGE) return bad("image too large", 413);
911
- const saved = saveImage(new Uint8Array(await req.arrayBuffer()));
939
+ const bytes = new Uint8Array(await req.arrayBuffer());
940
+ if (bytes.length > MAX_IMAGE) return bad("image too large", 413); // a chunked body has no content-length
941
+ const saved = saveImage(bytes);
912
942
  return saved ? json({ path: saved }) : bad("not an image", 415);
913
943
  }
914
944
  if (req.method === "POST" && path === "/shell") {
@@ -1215,6 +1245,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1215
1245
  let u: URL;
1216
1246
  try { u = new URL(String(body.url ?? "")); } catch { return bad("not a url"); }
1217
1247
  if (!/^https?:$/.test(u.protocol) || !isLoopback(u)) return bad("only a localhost address", 400);
1248
+ // Not the board itself: a proxy to it would forward /pty with an Origin rewritten to the board's own.
1249
+ if (u.port === (new URL(req.url).port || "80")) return bad("that is the board's own port", 400);
1218
1250
  try {
1219
1251
  const px = openProxy(u);
1220
1252
  return json({ ok: true, origin: px.origin, token: px.token, url: px.origin + u.pathname + u.search + u.hash });
@@ -1232,7 +1264,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1232
1264
  if (path === "/annotate/format") return json({ ok: true, text: annMarkdown(notes, level, comps) });
1233
1265
  const dir = canonState(String(body.dir ?? ""));
1234
1266
  const id = String(body.id ?? "");
1235
- if (!states(true).includes(dir) || dir === join(home, ".kaizen") || !/^[\w.-]+$/.test(id)) return bad("choose a run", 404);
1267
+ if (!states(true).includes(dir) || dir === join(home, ".kaizen") || !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("choose a run", 404);
1236
1268
  const live = liveAgent(dir, id);
1237
1269
  if (!live) return bad("this run has no agent open to send to", 409);
1238
1270
  const crops = saveCrops(dir, id, notes);
@@ -1433,7 +1465,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1433
1465
  if (req.method === "GET" && path.startsWith("/run/")) {
1434
1466
  const id = decodeURIComponent(path.slice(5));
1435
1467
  const dir = qdir() ?? state;
1436
- if (!dir || !states(true).includes(dir) || !/^[\w.-]+$/.test(id)) return bad("no such run", 404);
1468
+ if (!dir || !states(true).includes(dir) || !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("no such run", 404);
1437
1469
  const base = join(dir, "runs", id);
1438
1470
  if (!existsSync(base)) return bad("no such run", 404);
1439
1471
  const read = (f: string) => existsSync(join(base, f)) ? readText(join(base, f)) : null;
@@ -1603,7 +1635,41 @@ export async function web(repoDir: string, opts: Opts = {}) {
1603
1635
  skillToken = crypto.randomUUID();
1604
1636
  // The desktop-control skill shows what this machine lacks, from the helper's own check.
1605
1637
  const check = bundledSkills(repoDir).some((s) => s.id === "kaizen-computer") ? (await import("./computer.ts")).computerCheck() : null;
1606
- return json({ token: skillToken, skills: bundledSkills(repoDir).map((s) => ({ ...s, off: off.includes(s.id), agents: skillStatus(s, home), needs: [...s.needs.map((n) => ({ name: n, found: !!onPath(n) })), ...(s.id === "kaizen-computer" && check ? check.needs : [])], ...(s.id === "kaizen-computer" && check ? { note: check.note } : {}) })) });
1638
+ return json({ token: skillToken, skills: [...bundledSkills(repoDir).map((s) => ({ ...s, off: off.includes(s.id), agents: skillStatus(s, home), needs: [...s.needs.map((n) => ({ name: n, found: !!onPath(n) })), ...(s.id === "kaizen-computer" && check ? check.needs : [])], ...(s.id === "kaizen-computer" && check ? { note: check.note } : {}) })), rea.reaRow(home)] });
1639
+ }
1640
+
1641
+ // REA's switch. `plan` runs REA's dry run and hands back a token; `apply` sets up exactly
1642
+ // that plan and only with that token; `off` runs REA's uninstall. Kaizen writes no agent config.
1643
+ if (path === "/rea" && req.method === "POST") {
1644
+ const refused = strict(req);
1645
+ if (refused) return refused;
1646
+ let body: any;
1647
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1648
+ if (body?.step === "plan") {
1649
+ reaPending = null;
1650
+ const version = await rea.reaLatest();
1651
+ if (!version) return bad("can't reach npm to find REA's version");
1652
+ const want = body?.update === true ? rea.reaSaved(home)?.clients ?? rea.reaRegistered(home).map((r) => r.client) : rea.reaClients(home).map((c) => c.client);
1653
+ const p = await rea.reaPlan(home, version, want);
1654
+ if (!p.ok) return bad(p.why);
1655
+ reaPending = { token: crypto.randomUUID(), version: p.version, clients: p.clients };
1656
+ return json({ token: reaPending.token, version: p.version, clients: p.clients, files: p.files });
1657
+ }
1658
+ if (body?.step === "apply") {
1659
+ const plan = reaPending;
1660
+ reaPending = null;
1661
+ if (!plan || body?.confirm !== true || body?.token !== plan.token) return bad("confirm required");
1662
+ const r = await rea.reaApply(home, plan.version, plan.clients);
1663
+ rea.forgetDoctor(); rea.forgetLatest();
1664
+ return r.ok ? json({ ok: true, version: r.version }) : bad(r.why);
1665
+ }
1666
+ if (body?.step === "off") {
1667
+ reaPending = null;
1668
+ const r = await rea.reaRemove(home);
1669
+ rea.forgetDoctor(); rea.forgetLatest();
1670
+ return r.ok ? json(r) : bad(r.why);
1671
+ }
1672
+ return bad("step: plan, apply or off");
1607
1673
  }
1608
1674
 
1609
1675
  // Per user, so no scope. A saved environment value is never in either answer.
@@ -1803,11 +1869,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1803
1869
  const dir = qdir() ?? state;
1804
1870
  const p = url.searchParams.get("p") ?? "";
1805
1871
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
1806
- if (!/^(runs\/[\w.-]+\/)?attachments\/[\w.-]+$/.test(p)) return bad("bad path");
1872
+ if (!/^(runs\/[\w.-]+\/)?attachments\/(?!\.+$)[\w.-]+$/.test(p)) return bad("bad path");
1807
1873
  const f = join(dir, p);
1808
1874
  if (!existsSync(f)) return bad("no such file", 404);
1809
1875
  // no-cache: a revise retakes a screenshot under the same name, and the browser must ask again.
1810
- return new Response(Bun.file(f), { headers: { "cache-control": "private, no-cache" } });
1876
+ // sandbox + nosniff: an attached .html/.svg opened directly must run nothing on the board origin.
1877
+ return new Response(Bun.file(f), { headers: { "cache-control": "private, no-cache", "content-security-policy": "sandbox", "x-content-type-options": "nosniff" } });
1811
1878
  }
1812
1879
 
1813
1880
  // An icebox image, sent on to a link read fresh from its source: the one kept
@@ -1844,13 +1911,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
1844
1911
  return c ? json({ ...c, busy: chatBusy(base, c.id) }) : bad("no such chat", 404);
1845
1912
  }
1846
1913
  if (req.method !== "POST") return bad("method not allowed", 405);
1847
- if (!local(req)) return bad("cross-origin write refused", 403);
1914
+ // sameOrigin, not local(): a multipart form is a simple request any page can send, and a chat starts an agent.
1915
+ if (!sameOrigin(req)) return bad("cross-origin write refused", 403);
1848
1916
  let body: any;
1849
1917
  let uploads: ChatUpload[] = [];
1850
1918
  if (path === "/chat" && req.headers.get("content-type")?.startsWith("multipart/form-data")) {
1851
1919
  if (Number(req.headers.get("content-length")) > 320 * 1024 * 1024) return bad("attachments too large", 413);
1852
1920
  let form: FormData;
1853
- try { form = await req.formData(); } catch { return bad("form data expected"); }
1921
+ try { form = await req.formData(); } catch { return bad("form data expected"); } // the per-file and total caps below also cover a chunked body
1854
1922
  const files = form.getAll("files");
1855
1923
  if (files.length > 20 || files.some((f) => !(f instanceof File) || f.size > 100 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 300 * 1024 * 1024) return bad("up to 20 files, 100 MB each and 300 MB total", 413);
1856
1924
  body = { id: form.get("id"), text: form.get("text") ?? "", project: form.get("project") };
@@ -1900,7 +1968,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1900
1968
  }
1901
1969
 
1902
1970
  if (req.method === "POST") {
1903
- if (!local(req)) return bad("cross-origin write refused", 403);
1971
+ // strict, not local(): this block starts agents (/run yolo, /fix, /shell-like ops), so a
1972
+ // page on another local port or a text/plain no-cors POST must not reach it.
1973
+ const refused = strict(req);
1974
+ if (refused) return refused;
1904
1975
  let body: any;
1905
1976
  try { body = await req.json(); } catch { return bad("json body expected"); }
1906
1977
  for (const k of ["dir", "to"]) if (typeof body?.[k] === "string" && body[k]) body[k] = canonState(body[k]);
@@ -2209,7 +2280,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2209
2280
  if (path === "/archive") {
2210
2281
  const archived = body.archived !== false;
2211
2282
  if (typeof body.id === "string") {
2212
- if (!/^[\w.-]+$/.test(body.id)) return bad("bad run id");
2283
+ if (!/^(?!\.+$)[\w.-]+$/.test(body.id)) return bad("bad run id");
2213
2284
  setArchived(dir, body.id, archived);
2214
2285
  } else if (typeof body.text === "string") {
2215
2286
  const text = body.text.trim();
@@ -2227,7 +2298,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
2227
2298
  // from the message so the note carries its own attachments.
2228
2299
  if (path === "/note") {
2229
2300
  const id = typeof body.id === "string" ? body.id : null;
2230
- if (id !== null && !/^[\w.-]+$/.test(id)) return bad("bad run id");
2301
+ if (id !== null && !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2302
+ if (id !== null && !existsSync(join(dir, "runs", id, "state.json"))) return bad("no such run", 404); // no attachments folder for a run that is not there
2231
2303
  const text = typeof body.text === "string" ? body.text.trim() : "";
2232
2304
  const files: { name: string; data: string }[] = Array.isArray(body.files) ? body.files : [];
2233
2305
  let total = 0;
@@ -2246,7 +2318,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2246
2318
 
2247
2319
  if (path === "/notes") {
2248
2320
  const id = String(body.id ?? "");
2249
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2321
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2250
2322
  const failed = writeNotes(dir, id, String(body.text ?? ""));
2251
2323
  changed();
2252
2324
  return failed ? bad(failed, 404) : json({ ok: true });
@@ -2271,12 +2343,17 @@ export async function web(repoDir: string, opts: Opts = {}) {
2271
2343
  // global state dir: $HOME may be a repository, and it is not the run's project.
2272
2344
  if (path === "/commit") {
2273
2345
  const id = String(body.id ?? "");
2274
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2346
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2275
2347
  if (dir === join(home, ".kaizen")) return bad("no project to commit", 409);
2276
2348
  let run: any;
2277
2349
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
2278
2350
  if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
2279
2351
  const files = Array.isArray(body.files) ? body.files.map(String) : [];
2352
+ // A run with no worktree pushes the project's own branch, the base itself: that push is a land.
2353
+ if (body.push !== false && codeDir(dirname(dir), id) === dirname(dir)) {
2354
+ const stop = await gatePreflight(dir, id, "push", body.override, files);
2355
+ if (stop) return stop;
2356
+ }
2280
2357
  // `push: false` is the tab's plain Commit: what is staged, nothing pushed.
2281
2358
  const r = body.push === false ? commitStaged(dir, id, String(body.message ?? ""), files) : await commitPush(dir, id, String(body.message ?? ""), files);
2282
2359
  changed();
@@ -2287,7 +2364,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2287
2364
  // takes and only on the run's own files (stageFiles refuses any other path).
2288
2365
  if (path === "/stage") {
2289
2366
  const id = String(body.id ?? "");
2290
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2367
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2291
2368
  if (dir === join(home, ".kaizen")) return bad("no project", 409);
2292
2369
  let run: any;
2293
2370
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2302,7 +2379,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2302
2379
  // The sparkle button: a commit message for the run's files, written from their diff.
2303
2380
  if (path === "/commit-message") {
2304
2381
  const id = String(body.id ?? "");
2305
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2382
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2306
2383
  if (dir === join(home, ".kaizen")) return bad("no project", 409);
2307
2384
  const r = await suggestMessage(dir, id);
2308
2385
  return r.ok ? json(r) : bad(r.why, 409);
@@ -2312,7 +2389,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2312
2389
  // request, merge it, then remove the worktree once its work is on the base.
2313
2390
  if (path === "/pr") {
2314
2391
  const id = String(body.id ?? "");
2315
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2392
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2316
2393
  // One step per run at a time: a second tab's Merge or Remove waits its turn.
2317
2394
  const lock = `${dir}\0${id}`;
2318
2395
  if (prBusy.has(lock)) return bad("Another git step is running on this run. Try again when it finishes.", 409);
@@ -2322,6 +2399,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
2322
2399
  if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
2323
2400
  const project = dirname(dir);
2324
2401
  if (body.op !== "remove" && gateOf(dir, id) === "needs") return bad("This run is not approved yet. Approve it first.", 409);
2402
+ if (body.op === "create" || body.op === "merge") {
2403
+ prBusy.add(lock);
2404
+ let stop: Response | null;
2405
+ try { stop = await gatePreflight(dir, id, body.op, body.override); } finally { prBusy.delete(lock); }
2406
+ if (stop) return stop;
2407
+ }
2325
2408
  prBusy.add(lock);
2326
2409
  let r: { ok: boolean };
2327
2410
  try {
@@ -2339,7 +2422,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2339
2422
  // not there. Only numbers the review itself holds reach the prompt.
2340
2423
  if (path === "/fix") {
2341
2424
  const id = String(body.id ?? "");
2342
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2425
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2343
2426
  if (dir === join(home, ".kaizen")) return bad("no project to fix in", 409);
2344
2427
  let run: any;
2345
2428
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2371,7 +2454,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2371
2454
  // the approval it saw: one already answered elsewhere is not answered twice.
2372
2455
  if (path === "/decide") {
2373
2456
  const id = String(body.id ?? "");
2374
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2457
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2375
2458
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
2376
2459
  let run: any;
2377
2460
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2416,7 +2499,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2416
2499
  // only, no agent is started.
2417
2500
  if (path === "/accept") {
2418
2501
  const id = String(body.id ?? "");
2419
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2502
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2420
2503
  if (gateOf(dir, id) !== "needs") return bad("this run is not waiting on your approval", 409);
2421
2504
  // Only a finished-but-unapproved run: a genuine review goes through /decide.
2422
2505
  let st: any = {};
@@ -2432,7 +2515,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2432
2515
  // Start a run's agent again after it ended mid-stage (resumeRun).
2433
2516
  if (path === "/resume") {
2434
2517
  const id = String(body.id ?? "");
2435
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2518
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2436
2519
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
2437
2520
  const r = resumeRun(dir, id);
2438
2521
  if ("error" in r) return bad(r.error, r.status);
@@ -2443,7 +2526,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2443
2526
 
2444
2527
  if (path === "/to-task" || path === "/to-idea") { // /to-idea: the old name, kept for open tabs
2445
2528
  const id = String(body.id ?? "");
2446
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2529
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2447
2530
  const failed = runToTask(dir, id);
2448
2531
  changed();
2449
2532
  return failed ? bad(failed, 409) : json({ ok: true });
@@ -2452,7 +2535,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2452
2535
  if (path === "/abort") {
2453
2536
  const id = String(body.id ?? "");
2454
2537
  const why = String(body.why ?? "").trim() || "abandoned from the web";
2455
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2538
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2456
2539
  const failed = abandonRun(dir, id, why);
2457
2540
  changed();
2458
2541
  return failed ? bad(failed, 409) : json({ ok: true });
@@ -2676,9 +2759,9 @@ export async function openApp(url: string, profile?: string) {
2676
2759
  }
2677
2760
 
2678
2761
  async function openDefault(url: string) {
2679
- // `start` is a cmd builtin, not a program, so it has to go through cmd.
2762
+ // Not `cmd /c start`: cmd splits a URL at `&`, `|` or `^` and would run what follows.
2680
2763
  if (process.platform === "win32") {
2681
- try { await Bun.$`${cmdExe()} /c start "" ${url}`.quiet(); return true; } catch { return false; }
2764
+ try { await Bun.spawn(["rundll32", "url.dll,FileProtocolHandler", url], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exited; return true; } catch { return false; }
2682
2765
  }
2683
2766
  const opener = process.platform === "darwin" ? "open" : "xdg-open";
2684
2767
  if (!Bun.which(opener)) return false;
package/cli/workers.ts CHANGED
@@ -9,8 +9,8 @@ import { join } from "node:path";
9
9
  import { argsOf, commandOf, readPrefs, withEnv, type Prefs } from "./agent-prefs.ts";
10
10
  import { clip, reportBlocked, reportUnblock, validId } from "./report.ts";
11
11
  import { read } from "./settings.ts";
12
- import { accountEnv, accountForRun, agentFlags, agentUsable, detectDefaultAgent, MODEL_FLAGS, plainModel, promptArgs, readText, runAgent, YOLO_FLAGS } from "./state.ts";
13
- import { branchOf, run as sh } from "./worktree.ts";
12
+ import { accountEnv, accountForRun, agentFlags, agentUsable, detectDefaultAgent, MODEL_FLAGS, plainModel, promptArgs, readText, runAgent, subagentEnv, YOLO_FLAGS } from "./state.ts";
13
+ import { branchFor, branchOf, run as sh } from "./worktree.ts";
14
14
 
15
15
  export type Status = "planned" | "requested" | "running" | "blocked" | "succeeded" | "failed" | "unverified" | "conflict" | "merged" | "stopped";
16
16
  export type Worker = {
@@ -42,7 +42,7 @@ function locked<T>(project: string, id: string, fn: () => T): T {
42
42
  const lock = fileOf(project, id) + ".lock";
43
43
  for (let i = 0; ; i++) {
44
44
  try { mkdirSync(lock); break; } catch {
45
- try { if (Date.now() - statSync(lock).mtimeMs > 10_000) rmSync(lock, { recursive: true }); } catch { /* gone */ }
45
+ try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { const aside = `${lock}.${process.pid}.${i}.stale`; renameSync(lock, aside); rmSync(aside, { recursive: true, force: true }); } } catch { /* gone */ }
46
46
  if (i > 60) throw new Error("workers.json is locked: try again");
47
47
  Bun.sleepSync(50);
48
48
  }
@@ -200,6 +200,17 @@ export function launchOf(project: string, id: string, x: Worker, permissions: "o
200
200
  return { ...l, title: `Worker ${x.id}${l.bypass ? " · bypass" : ""}`, cwd: x.worktree, env: { KAIZEN_RUN_ID: id, KAIZEN_WORKER: x.id } };
201
201
  }
202
202
 
203
+ /** The model for this run's handoff agent: agent.handoff_model.<the run's tool>, project first. "": the run's own. */
204
+ export function handoffModel(project: string, id: string): string {
205
+ const cmd = runAgent(join(project, ".kaizen"), id)?.cmd ?? stateOf(project, id)?.agent;
206
+ if (typeof cmd !== "string" || !/^\w+$/.test(cmd)) return "";
207
+ for (const f of [join(project, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
208
+ const v = existsSync(f) ? read(readText(f), `agent.handoff_model.${cmd}`) : null;
209
+ if (v) return plainModel(v) ? v : "";
210
+ }
211
+ return "";
212
+ }
213
+
203
214
  /** The run's agent as a command line with `prompt`. Shared with the handoff; the caller names the terminal. */
204
215
  export function agentLine(project: string, id: string, prompt: string, permissions: "own" | "bypass", prefs: Prefs = readPrefs(), pick = ""): Omit<Launch, "title" | "cwd" | "env"> | string {
205
216
  const own = runAgent(join(project, ".kaizen"), id), st = stateOf(project, id);
@@ -213,8 +224,10 @@ export function agentLine(project: string, id: string, prompt: string, permissio
213
224
  const bypass = permissions === "bypass" && !!YOLO_FLAGS[agent.cmd];
214
225
  const flags = [...agentFlags(project, agent.cmd, undefined, model), ...(bypass ? YOLO_FLAGS[agent.cmd]! : []), ...argsOf(agent.cmd, prefs)];
215
226
  const line = withEnv([commandOf(agent.cmd, prefs), ...flags, ...promptArgs(agent.cmd, prompt)], agent.cmd, prefs);
227
+ // Windows has no env command: there only an account, as before, gets one.
228
+ const vars = [...(process.platform !== "win32" ? subagentEnv(project, agent.cmd) : []), ...accountEnv(acct)];
216
229
  return {
217
- argv: acct.dir ? ["env", ...accountEnv(acct), ...line] : line, bypass, agent: agent.cmd,
230
+ argv: vars.length ? ["env", ...vars, ...line] : line, bypass, agent: agent.cmd,
218
231
  model: picked ? (MODEL_FLAGS[agent.cmd] ? picked : undefined) : model ?? agentFlags(project, agent.cmd).join(" ").match(/\S+$/)?.[0],
219
232
  modelNote: picked && !MODEL_FLAGS[agent.cmd] ? `${agent.name} takes no model flag: "${picked}" was ignored` : undefined,
220
233
  trust: acct.dir ? join(acct.dir, ".claude.json") : undefined,
@@ -238,7 +251,7 @@ export function startWorker(project: string, id: string, wid: string, prefs?: Pr
238
251
  const have = git(project, "rev-parse", "--verify", "--quiet", `refs/heads/${x.branch}`).ok;
239
252
  // A dependent worker starts from the worker it follows, so it sees that code; any further `after` workers are merged in.
240
253
  const dep = x.after.map((a) => w.workers.find((o) => o.id === a)!.branch);
241
- const add = git(project, "worktree", "add", ...(have ? [x.worktree, x.branch] : ["--no-track", "-b", x.branch, x.worktree, dep[0] ?? st.branch]));
254
+ const add = git(project, "worktree", "add", ...(have ? [x.worktree, x.branch] : ["--no-track", "-b", x.branch, x.worktree, dep[0] ?? branchFor(project, id)]));
242
255
  if (!add.ok) return { ok: false, why: add.why };
243
256
  if (!have) for (const b of dep.slice(1)) {
244
257
  const m = git(x.worktree, "merge", "--no-edit", b);
@@ -326,12 +339,12 @@ export function merge(project: string, id: string): { ok: true; shas: string[];
326
339
  if (not) return { ok: false, why: `${not.id} is ${not.status}, so nothing is merged: ${NEXT[not.status]?.replace("<wid>", not.id)}` };
327
340
  const cwd = st.worktree as string;
328
341
  if (!cwd || !existsSync(cwd)) return { ok: false, why: "the run has no worktree to merge into" };
329
- if (git(cwd, "rev-parse", "--abbrev-ref", "HEAD").out !== st.branch) return { ok: false, why: `the run's worktree is not on ${st.branch}: check it out there first` };
342
+ if (git(cwd, "rev-parse", "--abbrev-ref", "HEAD").out !== branchFor(project, id)) return { ok: false, why: `the run's worktree is not on ${branchFor(project, id)}: check it out there first` };
330
343
  if (git(cwd, "status", "--porcelain").out) return { ok: false, why: "the run's worktree has uncommitted changes: commit them first, then merge" };
331
344
  // A branch may change only what its worker owns. Commits it took from the workers it follows are theirs, not its own.
332
345
  for (const x of w.workers) {
333
346
  const skip = x.after.flatMap((a) => ["^" + w.workers.find((o) => o.id === a)!.branch]);
334
- const out = git(cwd, "log", "--no-merges", "--name-only", "--format=", x.branch, "^" + st.branch, ...skip).out.split("\n").filter(Boolean);
347
+ const out = git(cwd, "log", "--no-merges", "--name-only", "--format=", x.branch, "^" + branchFor(project, id), ...skip).out.split("\n").filter(Boolean);
335
348
  const stray = [...new Set(out)].filter((p) => !x.owns.some((o) => p === o || p.startsWith(o + "/")));
336
349
  if (stray.length) return { ok: false, why: `${x.id} changed paths it does not own (${stray.slice(0, 5).join(", ")}): nothing is merged. Move those changes out of its branch, or tell the user` };
337
350
  }