kaizen-agent 1.61.6 → 1.62.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 (107) hide show
  1. package/README.md +2 -2
  2. package/agents/kaizen-builder.md +3 -0
  3. package/agents/kaizen-planner.md +3 -0
  4. package/agents/kaizen-reviewer.md +2 -0
  5. package/assets/kaizen-logo.png +0 -0
  6. package/assets/kaizen.ico +0 -0
  7. package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
  8. package/cli/accounts.test.ts +126 -0
  9. package/cli/accounts.ts +116 -0
  10. package/cli/add-project.ts +4 -2
  11. package/cli/agent-prefs.test.ts +127 -0
  12. package/cli/agent-prefs.ts +106 -0
  13. package/cli/board.test.ts +4 -5
  14. package/cli/computer-helper.py +299 -0
  15. package/cli/computer.test.ts +155 -0
  16. package/cli/computer.ts +66 -0
  17. package/cli/dashboard.ts +14 -15
  18. package/cli/install.ts +67 -4
  19. package/cli/keep-awake.ts +30 -0
  20. package/cli/project-tree.test.ts +1 -0
  21. package/cli/pty.test.ts +2 -1
  22. package/cli/pty.ts +6 -5
  23. package/cli/report.test.ts +59 -0
  24. package/cli/report.ts +62 -0
  25. package/cli/restart.test.ts +1 -0
  26. package/cli/settings.test.ts +21 -1
  27. package/cli/settings.ts +19 -11
  28. package/cli/setup.test.ts +2 -2
  29. package/cli/skills.test.ts +89 -0
  30. package/cli/skills.ts +112 -0
  31. package/cli/state.test.ts +46 -4
  32. package/cli/state.ts +127 -41
  33. package/cli/term-image.test.ts +23 -0
  34. package/cli/term-image.ts +26 -0
  35. package/cli/usage.test.ts +8 -2
  36. package/cli/usage.ts +8 -6
  37. package/cli/video.test.ts +5 -5
  38. package/cli/web-accept.test.ts +1 -0
  39. package/cli/web-decide.test.ts +1 -0
  40. package/cli/web-pr.test.ts +1 -0
  41. package/cli/web-skills.test.ts +32 -0
  42. package/cli/web-symlink.test.ts +1 -0
  43. package/cli/web.ts +179 -20
  44. package/cli/workers.test.ts +319 -0
  45. package/cli/workers.ts +380 -0
  46. package/cli/worktree.test.ts +21 -2
  47. package/cli/worktree.ts +21 -2
  48. package/package.json +1 -1
  49. package/skills/kaizen/config.default.yml +33 -1
  50. package/skills/kaizen/settings.md +1 -1
  51. package/skills/kaizen/skill.json +1 -0
  52. package/skills/kaizen/spec-build.md +22 -2
  53. package/skills/kaizen/spec-main.md +9 -0
  54. package/skills/kaizen/spec-plan.md +18 -1
  55. package/skills/kaizen/spec-review.md +4 -0
  56. package/skills/kaizen/spec.md +15 -0
  57. package/skills/kaizen-help/SKILL.md +1 -0
  58. package/skills/kaizen-help/skill.json +1 -0
  59. package/skills/media/kaizen-book/skill.json +1 -0
  60. package/skills/media/kaizen-deck/skill.json +1 -0
  61. package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
  62. package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
  63. package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
  64. package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
  65. package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
  66. package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
  67. package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
  68. package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
  69. package/skills/media/kaizen-video/skill.json +1 -0
  70. package/skills/optional/kaizen-computer/SKILL.md +38 -0
  71. package/skills/optional/kaizen-computer/skill.json +1 -0
  72. package/web/board/add-project.ts +3 -3
  73. package/web/board/agent-favicons.ts +9 -0
  74. package/web/board/agent-term.ts +1 -1
  75. package/web/board/api.ts +1 -1
  76. package/web/board/approvals.ts +1 -1
  77. package/web/board/cards.ts +50 -7
  78. package/web/board/dictation.ts +46 -3
  79. package/web/board/fixes.ts +1 -1
  80. package/web/board/home.ts +1 -1
  81. package/web/board/icebox.ts +1 -1
  82. package/web/board/keys.ts +5 -15
  83. package/web/board/onboarding.ts +1 -1
  84. package/web/board/panel.ts +24 -20
  85. package/web/board/phone.ts +4 -1
  86. package/web/board/run-view.ts +11 -6
  87. package/web/board/settings-accounts.ts +60 -0
  88. package/web/board/settings-agents.ts +102 -0
  89. package/web/board/settings-orchestration.ts +32 -0
  90. package/web/board/settings-pages.test.ts +5 -0
  91. package/web/board/settings-pages.ts +10 -4
  92. package/web/board/settings-skills.ts +47 -0
  93. package/web/board/settings-voice.test.ts +18 -0
  94. package/web/board/settings-voice.ts +28 -0
  95. package/web/board/settings.ts +40 -4
  96. package/web/board/terms.ts +2 -2
  97. package/web/board/update.ts +1 -1
  98. package/web/board/ws-board.test.ts +6 -0
  99. package/web/board/ws-board.ts +2 -0
  100. package/web/board.html +15 -3
  101. package/web/board.js +134 -84
  102. package/web/notebook.js +2 -2
  103. package/web/notes.html +3 -3
  104. package/web/term.js +27 -27
  105. package/web/term.ts +25 -3
  106. package/web/video.html +2 -2
  107. package/web/video.js +2 -2
@@ -0,0 +1,23 @@
1
+ import { expect, test } from "bun:test";
2
+ import { existsSync, mkdtempSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { imageExt, MAX_IMAGE, saveImage } from "./term-image.ts";
6
+
7
+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]);
8
+
9
+ test("the type comes from the bytes", () => {
10
+ expect(imageExt(png)).toBe("png");
11
+ expect(imageExt(new TextEncoder().encode("RIFF0000WEBP"))).toBe("webp");
12
+ expect(imageExt(new TextEncoder().encode("<svg onload=x>"))).toBeNull();
13
+ });
14
+
15
+ test("saves an image and refuses the rest", () => {
16
+ const dir = mkdtempSync(join(tmpdir(), "kz-img-"));
17
+ const f = saveImage(png, dir)!;
18
+ expect(f.endsWith(".png") && existsSync(f)).toBe(true);
19
+ expect(saveImage(new Uint8Array(4), dir)).toBeNull();
20
+ const big = new Uint8Array(MAX_IMAGE + 1);
21
+ big.set(png);
22
+ expect(saveImage(big, dir)).toBeNull();
23
+ });
@@ -0,0 +1,26 @@
1
+ // Images pasted into a board terminal. The type comes from the file's own first bytes, never
2
+ // from the page, and the name is random, so nothing the page sends reaches the path.
3
+ import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ export const MAX_IMAGE = 10 * 1024 * 1024;
8
+
9
+ export function imageExt(b: Uint8Array) {
10
+ const at = (o: number, s: string) => [...s].every((c, i) => b[o + i] === c.charCodeAt(0));
11
+ if (b[0] === 0x89 && at(1, "PNG")) return "png";
12
+ if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "jpg";
13
+ if (at(0, "GIF8")) return "gif";
14
+ if (at(0, "RIFF") && at(8, "WEBP")) return "webp";
15
+ return null;
16
+ }
17
+
18
+ export function saveImage(b: Uint8Array, dir = join(homedir(), ".kaizen", "term-images")) {
19
+ const ext = b.length <= MAX_IMAGE ? imageExt(b) : null;
20
+ if (!ext) return null;
21
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
22
+ const file = join(dir, `${crypto.randomUUID()}.${ext}`);
23
+ writeFileSync(file, b, { mode: 0o600 });
24
+ try { chmodSync(file, 0o600); } catch { /* Windows */ }
25
+ return file;
26
+ }
package/cli/usage.test.ts CHANGED
@@ -39,7 +39,7 @@ test("claudeUsage: maps the windows; a failure is an error that never carries th
39
39
  const e = await claudeUsage(h, fail);
40
40
  expect(e).toHaveProperty("error");
41
41
  expect(JSON.stringify(e)).not.toContain("SECRET");
42
- expect(await claudeUsage(h, (async () => new Response("", { status: 401 })) as any)).toEqual({ agent: "claude", error: "HTTP 401" });
42
+ expect(await claudeUsage(h, (async () => new Response("", { status: 401 })) as any)).toEqual({ agent: "claude", error: "HTTP 401", expired: true });
43
43
  });
44
44
 
45
45
  test("phonePeers: online, offline, no phone, not running", () => {
@@ -196,7 +196,13 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
196
196
  writeFileSync(join(g, "config.yml"), readFileSync(join(repo, "skills", "kaizen", "config.default.yml"), "utf8").replace('projects_dir: ""', "projects_dir: ~/Projects"));
197
197
  mkdirSync(join(g, "runs", "g1"), { recursive: true });
198
198
  writeFileSync(join(g, "runs", "g1", "state.json"), JSON.stringify({ id: "g1", stage: "plan", awaiting: "approvals.plan" }));
199
- const G = await (await fetch(at + "/state?all=1")).json() as any;
199
+ // The board's snapshot refreshes behind the request: wait for the run to appear.
200
+ let G: any;
201
+ for (let i = 0; i < 50; i++) {
202
+ G = await (await fetch(at + "/state?all=1")).json();
203
+ if (G.cards.some((c: any) => c.id === "g1")) break;
204
+ await Bun.sleep(100);
205
+ }
200
206
  expect(G.cards.find((c: any) => c.id === "g1")?.ws).toBe(g);
201
207
  expect(G.projects.some((p: any) => p.dir === g)).toBe(false);
202
208
  expect(G.rail.find((p: any) => p.dir === g)?.workspaces).toEqual([{ path: g, branch: "", main: true }]);
package/cli/usage.ts CHANGED
@@ -6,14 +6,15 @@ import { existsSync, readFileSync, statSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
 
8
8
  export type Window = { pct: number; resetsAt: number | null };
9
- export type Usage = { agent: string; five: Window | null; week: Window | null } | { agent: string; error: string };
9
+ export type Usage = { agent: string; five: Window | null; week: Window | null } | { agent: string; error: string; expired?: boolean };
10
10
 
11
11
  const win = (pct: unknown, resets: unknown): Window | null =>
12
12
  typeof pct === "number" ? { pct: Math.round(pct), resetsAt: typeof resets === "number" ? resets * 1000 : typeof resets === "string" ? Date.parse(resets) || null : null } : null;
13
13
 
14
14
  // The last rate_limits in the newest ~/.codex/sessions/**/rollout-*.jsonl that has one, or null.
15
- export function codexUsage(home: string): Usage | null {
16
- const root = join(home, ".codex", "sessions");
15
+ export const codexUsage = (home: string) => codexUsageAt(join(home, ".codex"));
16
+ export function codexUsageAt(dir: string): Usage | null {
17
+ const root = join(dir, "sessions");
17
18
  if (!existsSync(root)) return null;
18
19
  // Newest first: a session that has only just started has no rate_limits line yet.
19
20
  const files = [...new Bun.Glob("**/rollout-*.jsonl").scanSync({ cwd: root })]
@@ -41,13 +42,14 @@ export function codexUsage(home: string): Usage | null {
41
42
 
42
43
  // Claude's plan usage, or null when there is no Claude login. A failure is an error
43
44
  // entry, so the footer says "usage unavailable" instead of showing 0%.
44
- export async function claudeUsage(home: string, get: typeof fetch = fetch): Promise<Usage | null> {
45
+ export const claudeUsage = (home: string, get: typeof fetch = fetch) => claudeUsageAt(join(home, ".claude"), get);
46
+ export async function claudeUsageAt(dir: string, get: typeof fetch = fetch): Promise<Usage | null> {
45
47
  let token = "";
46
- try { token = JSON.parse(readFileSync(join(home, ".claude", ".credentials.json"), "utf8"))?.claudeAiOauth?.accessToken ?? ""; } catch { return null; }
48
+ try { token = JSON.parse(readFileSync(join(dir, ".credentials.json"), "utf8"))?.claudeAiOauth?.accessToken ?? ""; } catch { return null; }
47
49
  if (!token) return null;
48
50
  try {
49
51
  const r = await get("https://api.anthropic.com/api/oauth/usage", { headers: { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" }, signal: AbortSignal.timeout(8000) });
50
- if (!r.ok) return { agent: "claude", error: `HTTP ${r.status}` };
52
+ if (!r.ok) return { agent: "claude", error: `HTTP ${r.status}`, ...(r.status === 401 ? { expired: true } : {}) };
51
53
  const d: any = await r.json();
52
54
  return { agent: "claude", five: win(d?.five_hour?.utilization, d?.five_hour?.resets_at), week: win(d?.seven_day?.utilization, d?.seven_day?.resets_at) };
53
55
  } catch (e) {
package/cli/video.test.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // paths a page may ask for, and the job queue the skill's scripts run in.
3
3
  import { test, expect } from "bun:test";
4
4
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync, readdirSync, cpSync, rmSync, truncateSync } from "node:fs";
5
- import { join, dirname } from "node:path";
5
+ import { basename, join, dirname } from "node:path";
6
6
  import { tmpdir } from "node:os";
7
7
 
8
8
  const repo = dirname(import.meta.dir);
@@ -52,7 +52,7 @@ test("the library lists films and footage, with each rendered shape and the word
52
52
  const proj = mkdtempSync(join(tmpdir(), "kaizen-video-proj-"));
53
53
  mkdirSync(join(proj, "videos"));
54
54
  const all = video.places(lib, [proj, lib, mkdtempSync(join(tmpdir(), "kaizen-novideo-"))]);
55
- expect(all.map((p) => p.label)).toEqual(["library", proj.split("/").pop()!]);
55
+ expect(all.map((p) => p.label)).toEqual(["library", basename(proj)]);
56
56
  const list = video.listVideos(all);
57
57
  const demo = list.find((v) => v.name === "demo")!;
58
58
  expect(demo.mode).toBe("film");
@@ -142,9 +142,9 @@ test("jobs run the skill's scripts as argv, in the background, one at a time", a
142
142
  await until(() => video.jobOf(lib, "talk")?.state === "done");
143
143
  expect(video.jobOf(lib, "demo")).toMatchObject({ state: "done", step: 2, total: 2 });
144
144
  expect(readFileSync(calls, "utf8").trim().split("\n").map((l) => JSON.parse(l))).toEqual([
145
- ["videos/demo", "--format", "9x16", "--render"], ["videos/demo", "--format", "4x5", "--render"],
145
+ [join("videos", "demo"), "--format", "9x16", "--render"], [join("videos", "demo"), "--format", "4x5", "--render"],
146
146
  ]);
147
- expect(JSON.parse(readFileSync(join(lib, "videos", "talk", "calls.txt"), "utf8"))).toEqual(["videos/talk"]);
147
+ expect(JSON.parse(readFileSync(join(lib, "videos", "talk", "calls.txt"), "utf8"))).toEqual([join("videos", "talk")]);
148
148
  expect(typeof b).toBe("object");
149
149
  delete process.env.FAKE_SLEEP;
150
150
  });
@@ -212,7 +212,7 @@ test("the board serves sound assets and the Video page, and refuses unsafe paths
212
212
  const calls = join(homeDir, ".kaizen", "videos", "demo", "calls.txt");
213
213
  await until(() => existsSync(calls) && readFileSync(calls, "utf8").trim().split("\n").length === 2);
214
214
  expect(readFileSync(calls, "utf8").trim().split("\n").map((l) => JSON.parse(l))).toEqual([
215
- ["videos/demo", "--format", "9x16", "--render"], ["videos/demo", "--format", "16x9", "--render"],
215
+ [join("videos", "demo"), "--format", "9x16", "--render"], [join("videos", "demo"), "--format", "16x9", "--render"],
216
216
  ]);
217
217
  } finally { proc.kill(); await proc.exited; }
218
218
  }, 30000);
@@ -28,6 +28,7 @@ test.skipIf(process.platform === "win32")("board /accept finishes a healed run w
28
28
  const run = (id: string) => JSON.parse(readFileSync(join(st, "runs", id, "state.json"), "utf8"));
29
29
  expect(run("2026-10-29-healed").healed).toBe(true);
30
30
  const port = 20000 + Math.floor(Math.random() * 20000);
31
+ mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
31
32
  const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
32
33
  { env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
33
34
  try {
@@ -18,6 +18,7 @@ test.skipIf(process.platform === "win32")("board /decide reuses the run's open a
18
18
  const waiting = (awaiting: string) => writeFileSync(join(d, "state.json"), JSON.stringify({ id: "2026-10-30-r", agent: "claude", stage: "plan", awaiting }));
19
19
  waiting("approvals.plan");
20
20
  const port = 20000 + Math.floor(Math.random() * 20000);
21
+ mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
21
22
  const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
22
23
  { env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz"), PATH: `${bin}:${process.env.PATH}` }, stdout: "ignore", stderr: "ignore" });
23
24
  try {
@@ -24,6 +24,7 @@ test.skipIf(process.platform === "win32")("board /pr refuses unfinished, unappro
24
24
  mk("2026-10-30-building", { stage: "build" });
25
25
  mk("2026-10-30-unapproved", { stage: "done" }); // done with changed files, no accepted: line
26
26
  const port = 20000 + Math.floor(Math.random() * 20000);
27
+ mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
27
28
  const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
28
29
  { env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
29
30
  try {
@@ -0,0 +1,32 @@
1
+ import { expect, test } from "bun:test";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ // Turning an off-by-default skill on needs the one-time token from GET /skills; a bare
7
+ // POST with confirm:true (what curl sends) is refused, and a token works once.
8
+ test("board refuses to turn Desktop control on without the page's one-time token", async () => {
9
+ const home = realpathSync(mkdtempSync(join(tmpdir(), "kz-sk-")));
10
+ mkdirSync(join(home, ".claude"), { recursive: true });
11
+ mkdirSync(join(home, ".kaizen"), { recursive: true });
12
+ const port = 20000 + Math.floor(Math.random() * 20000);
13
+ const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
14
+ { env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
15
+ try {
16
+ const base = `http://127.0.0.1:${port}`;
17
+ for (let i = 0; i < 100; i++) { try { if ((await fetch(base + "/")).ok) break; } catch { /* not up yet */ } await Bun.sleep(100); }
18
+ const post = (body: object) => fetch(base + "/skills", { method: "POST", headers: { origin: base, "content-type": "application/json" }, body: JSON.stringify({ id: "kaizen-computer", on: true, ...body }) });
19
+ const on = () => existsSync(join(home, ".kaizen", "skills-on.json")) && readFileSync(join(home, ".kaizen", "skills-on.json"), "utf8").includes("kaizen-computer");
20
+ expect((await post({ confirm: true })).status).toBe(400);
21
+ const { token } = await (await fetch(base + "/skills")).json() as { token: string };
22
+ expect((await post({ confirm: true, token: "wrong" })).status).toBe(400);
23
+ expect(on()).toBe(false);
24
+ const t2 = (await (await fetch(base + "/skills")).json() as { token: string }).token;
25
+ expect(t2).not.toBe(token);
26
+ expect((await post({ confirm: true, token })).status).toBe(400); // an older token is dead
27
+ const t3 = (await (await fetch(base + "/skills")).json() as { token: string }).token;
28
+ expect((await post({ confirm: true, token: t3 })).status).toBe(200);
29
+ expect(on()).toBe(true);
30
+ expect((await post({ confirm: true, token: t3 })).status).toBe(400); // spent: a token works once
31
+ } finally { p.kill(); }
32
+ }, 20000);
@@ -14,6 +14,7 @@ test.skipIf(process.platform === "win32")("board accepts a symlink spelling of a
14
14
  symlinkSync(real, link);
15
15
  writeFileSync(join(home, ".kaizen", "projects"), real + "\n");
16
16
  const port = 20000 + Math.floor(Math.random() * 20000);
17
+ mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
17
18
  const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
18
19
  { env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
19
20
  try {
package/cli/web.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  // `kaizen web`: the board in a browser. A loopback HTTP server over state.ts and
2
2
  // one HTML page; the page never sees the filesystem, only JSON.
3
+ import { agentEnabled, argsOf, commandOf, prefersBypass, publicPref, readPrefs, savePrefs, withEnv } from "./agent-prefs.ts";
4
+ import { awakeHolder, wantAwake } from "./keep-awake.ts";
3
5
  import { existsSync, readdirSync, statSync, lstatSync, realpathSync, readFileSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
4
6
  import { join, dirname, resolve, sep, basename } from "node:path";
5
7
  import {
@@ -9,9 +11,15 @@ import {
9
11
  reviewFindings, pickFindings, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
10
12
  launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
11
13
  } from "./state.ts";
14
+ import { ACCOUNT_VAR, accountDir, addAccount, readAccounts, renameAccount, signedIn, removeAccount, resolveAccount, setDefaultAccount } from "./accounts.ts";
15
+ import { readReport, signalOf } from "./report.ts";
16
+ import { MAX_IMAGE, saveImage } from "./term-image.ts";
17
+ import { bundledSkills, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
18
+ import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
19
+ import { failStart, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
12
20
  import { attachPty, writePty, submitPty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
13
21
  import { snapshot, snapWorker } from "./state-snap.ts";
14
- import { claudeUsage, codexUsage, phonePeers, type Usage } from "./usage.ts";
22
+ import { claudeUsage, claudeUsageAt, codexUsage, codexUsageAt, phonePeers, type Usage } from "./usage.ts";
15
23
  import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
16
24
  import { projectLogo, LOGO_TYPES } from "./logo.ts";
17
25
  import * as chatgpt from "./chatgpt.ts";
@@ -23,7 +31,7 @@ import * as video from "./video.ts";
23
31
  import * as localsend from "./localsend.ts";
24
32
  import * as hermes from "./hermes.ts";
25
33
  import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
26
- import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
34
+ import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, linkedWs, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
27
35
  import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
28
36
 
29
37
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
@@ -236,11 +244,17 @@ export async function web(repoDir: string, opts: Opts = {}) {
236
244
  // Stricter than local(), for routes that start a process: another local server's page
237
245
  // (the dev server a localhost tab frames) shares the hostname, so the port must match
238
246
  // too, and a JSON content type forces a preflight that a foreign page cannot pass.
239
- const strict = (req: Request) => {
247
+ const sameOrigin = (req: Request) => {
240
248
  const origin = req.headers.get("origin");
241
249
  let same = !origin;
242
250
  try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host") || extraHosts.has(o.hostname); } } catch { /* bad origin */ }
243
- if (!same) return bad("cross-origin request refused", 403);
251
+ return same;
252
+ };
253
+ // One-time token for turning an off-by-default skill on; each GET /skills mints a new one. It stops
254
+ // an agent switching itself on by accident, not a local process that reads the board's own page.
255
+ let skillToken = "";
256
+ const strict = (req: Request) => {
257
+ if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
244
258
  if (!/^application\/json\b/i.test(req.headers.get("content-type") ?? "")) return bad("json body expected", 415);
245
259
  return null;
246
260
  };
@@ -251,8 +265,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
251
265
  // Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
252
266
  const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; ws?: string; pid?: number }>();
253
267
  const SHELL_CAP = 8;
268
+ // A terminal shows where its live run builds, not where it launched: tabs follow `run`, the rail `ws`.
269
+ const shown = <S extends { key: string; dir: string; run: string; ws?: string }>(x: S): S => {
270
+ const w = linkedWs(x.dir, x.key), project = projectOf(x.dir);
271
+ // A worktree the run just made: refresh the list now, or the rail has no row to put it under.
272
+ if (w && !workspaces(project).some((p) => p.path === w) && workspacesAge(project) > 1000) { forgetWorkspaces(project); workspaces(project); }
273
+ return w ? { ...x, ws: w, run: `ws:${x.dir}:${w}` } : x;
274
+ };
254
275
  let usageCache: Usage[] = [];
255
276
  let usageAt = 0;
277
+ const acctUsage = new Map<string, { at: number; usage: Usage | null }>();
256
278
  let pending: ReturnType<typeof setTimeout> | null = null;
257
279
  const prBusy = new Set<string>();
258
280
  // /state costs ~250 ms of this one thread on a big board (git status per project), and
@@ -297,7 +319,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
297
319
  let run: any;
298
320
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return { error: "no such run", status: 404 }; }
299
321
  if (run.stage === "abandoned") return { error: "this run was abandoned", status: 409 };
300
- if (liveAgent(dir, id)) return { error: "its agent is still running in its card", status: 409 };
322
+ if (liveAgent(dir, id)) return { error: "its agent is still running in its workspace", status: 409 };
301
323
  const quiet = run.stage === "done" || !!run.awaiting;
302
324
  const own = quiet ? runAgent(dir, id) : null;
303
325
  if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
@@ -410,9 +432,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
410
432
  if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
411
433
  // Every agent session the run has had on this board, for the workspace's Agent tabs.
412
434
  const all = keys.filter((k) => ptyState(k)?.alive || k === key);
413
- return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, agent: cmdOf.get(key), stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
435
+ return { key, alive: st.alive, asking: st.asking, busy: st.busy, lastOut: st.lastOut, all, agent: cmdOf.get(key), stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
414
436
  }, { cmd: (k: string) => cmdOf.get(k) });
415
437
  };
438
+ // Orchestration: the only place a worker's terminal starts. A worker asks for it in workers.json
439
+ // (`kaizen worker start`); with the mode off no such file exists, so this finds nothing.
440
+ // startWorker re-checks the stage, the frozen settings, the count and the plan before anything runs.
441
+ let workersAt = 0;
442
+ const spawnWorkers = () => {
443
+ if (process.platform === "win32" || !ptySupported || Date.now() - workersAt < 300) return;
444
+ workersAt = Date.now();
445
+ for (const dir of states(true)) {
446
+ if (dir === join(home, ".kaizen")) continue;
447
+ const project = projectOf(dir);
448
+ for (const { id, wid } of requested(project)) {
449
+ const r = startWorker(project, id, wid);
450
+ if (!r.ok) { failStart(project, id, wid, r.why); continue; }
451
+ const l = r.launch, key = "sh-" + crypto.randomUUID().slice(0, 8);
452
+ for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
453
+ if (l.agent === "claude") trustFolder(l.cwd, l.trust);
454
+ try {
455
+ const pid = startPty(key, l.argv, l.cwd, undefined, changed, { env: { ...l.env, KAIZEN_TERM: key } });
456
+ shells.set(key, { key, dir, title: l.title, agent: l.agent, run: `run:${dir}:${id}`, ws: l.cwd, pid });
457
+ markRunning(project, id, wid, key, l);
458
+ } catch (err: any) { failStart(project, id, wid, err?.message ?? String(err)); }
459
+ changed();
460
+ }
461
+ try {
462
+ const runs = join(dir, "runs");
463
+ for (const id of existsSync(runs) ? readdirSync(runs) : []) if (sweep(project, id, (k) => !!ptyState(k)?.alive)) changed();
464
+ } catch { /* the next tick tries again */ }
465
+ }
466
+ };
416
467
  const watchers: FSWatcher[] = [];
417
468
  const watchAll = () => {
418
469
  for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
@@ -420,7 +471,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
420
471
  for (const dir of states(true)) {
421
472
  // An unhandled 'error' on a watcher (Windows: a watched dir renamed, EPERM on
422
473
  // a locked file) would end the process; the poll covers what the watch misses.
423
- try { watchers.push(watch(dir, { recursive: true }, changed).on("error", () => {})); } catch { /* poll covers it */ }
474
+ try { watchers.push(watch(dir, { recursive: true }, () => { changed(); spawnWorkers(); }).on("error", () => {})); } catch { /* poll covers it */ }
424
475
  }
425
476
  };
426
477
  watchAll();
@@ -439,12 +490,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
439
490
  let last = fingerprint();
440
491
  let seen = states(true).join("\n");
441
492
  let ticks = 0;
493
+ const awake = awakeHolder();
442
494
  const poll = setInterval(() => {
495
+ awake.sync(wantAwake(keepAwake(), ptyKeys().some((k) => ptyState(k)?.alive && !(shells.has(k) && !shells.get(k)!.agent))));
443
496
  // Once a minute: windows of runs finished or abandoned past the grace are closed.
444
497
  if (++ticks % 30 === 0) for (const dir of states(true)) sweepSessions(dir);
445
498
  // A project registered since start (a run launched into a fresh dir) gets a watcher too.
446
499
  const now = states(true).join("\n"); if (now !== seen) { seen = now; watchAll(); }
447
500
  const fp = fingerprint(); if (fp !== last) { last = fp; changed(); }
501
+ spawnWorkers();
448
502
  }, 2000);
449
503
 
450
504
  // The schedule: once a minute, gather every request source that is due. It writes
@@ -736,6 +790,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
736
790
  // workspace's + menu. Code execution, so local() as for every write, a registered
737
791
  // project, and an agent only from KNOWN_AGENTS: no argv ever comes from the page.
738
792
  // Its keys (sh-…) are /pty keys, so /pty's exact-origin check covers the socket.
793
+ // An image pasted into a terminal: saved here so its path can be typed into the agent.
794
+ // Raw bytes, so not strict()'s JSON, but an image content type still forces a preflight.
795
+ if (req.method === "POST" && path === "/term-image") {
796
+ if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
797
+ if (!/^image\//i.test(req.headers.get("content-type") ?? "")) return bad("image body expected", 415);
798
+ if (Number(req.headers.get("content-length") ?? 0) > MAX_IMAGE) return bad("image too large", 413);
799
+ const saved = saveImage(new Uint8Array(await req.arrayBuffer()));
800
+ return saved ? json({ path: saved }) : bad("not an image", 415);
801
+ }
739
802
  if (req.method === "POST" && path === "/shell") {
740
803
  const refused = strict(req);
741
804
  if (refused) return refused;
@@ -746,6 +809,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
746
809
  if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
747
810
  let cmd: string[];
748
811
  let agent = "";
812
+ let bypass = false;
749
813
  // The run's own agent session, resumed here ("run:<dir>:<id>" names the run; the session
750
814
  // id is read from that run's state.json, never taken from the page). Claude only: it is
751
815
  // the agent whose session id runs record. Refused while that session is still running
@@ -773,12 +837,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
773
837
  }
774
838
  if (sessionLive(sid)) return json({ live: true }, 409);
775
839
  agent = "claude";
776
- cmd = ["claude", "--resume", sid];
840
+ const acct = accountForRun(projectOf(dir), id, "claude");
841
+ if (acct.error) return bad(acct.error, 400);
842
+ cmd = acct.dir ? ["env", ...accountEnv(acct), "claude", "--resume", sid] : ["claude", "--resume", sid];
777
843
  } else if (body.agent != null) {
778
844
  const a = KNOWN_AGENTS.find((k) => k.cmd === body.agent);
779
- if (!a || !onPath(a.cmd)) return bad("unknown agent", 400);
845
+ if (!a || !agentUsable(a.cmd)) return bad("unknown agent", 400);
780
846
  agent = a.cmd;
781
- cmd = [a.cmd];
847
+ // A sign-in names its account and runs plain: no bypass, no arguments.
848
+ const signIn = typeof body.account === "string" && body.account !== "";
849
+ const acct = resolveAccount(a.cmd, signIn ? body.account : undefined);
850
+ if (acct.error) return bad(acct.error, 400);
851
+ bypass = !signIn && prefersBypass(a.cmd) && !!YOLO_FLAGS[a.cmd];
852
+ const line = signIn ? [commandOf(a.cmd), ...(a.cmd === "codex" ? ["login"] : [])] : withEnv([commandOf(a.cmd), ...(bypass ? YOLO_FLAGS[a.cmd]! : []), ...argsOf(a.cmd)], a.cmd);
853
+ cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
782
854
  } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
783
855
  // A workspace folder: only an exact path from this project's own `git worktree list`.
784
856
  let cwd = projectOf(dir);
@@ -792,8 +864,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
792
864
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
793
865
  if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
794
866
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
795
- const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name : "shell";
796
- const pid = startPty(key, cmd, cwd, undefined, changed);
867
+ const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
868
+ const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key } });
797
869
  // The run workspace that opened it (its card key), so each run keeps its own centre.
798
870
  shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
799
871
  changed();
@@ -889,7 +961,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
889
961
  if (req.method === "GET" && path === "/shells") {
890
962
  const dir = qdir();
891
963
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
892
- return json([...shells.values()].filter((s) => !dir || s.dir === dir));
964
+ return json([...shells.values()].filter((s) => !dir || s.dir === dir).map(shown));
893
965
  }
894
966
  // The localhost tab's "Open in browser": a Chromium app window on this computer, for
895
967
  // localhost pages that refuse to be framed. Launches a process, so /shell's guards, and only a
@@ -1059,7 +1131,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1059
1131
  if (hit?.gen === gen && Date.now() - hit.at < STATE_MS) return new Response(hit.body, { headers: { "content-type": "application/json" } });
1060
1132
  // Off this thread: it also relays every terminal, and a rebuild here froze their typing.
1061
1133
  const { cards, extra, backlog } = await buildSnap(dirs, gitGen).catch(() => snapshot(dirs, gitGen));
1062
- const pty = ptyOf(cards);
1134
+ const pty = ptyOf(cards), beat = heartbeatMinutes();
1063
1135
  // The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
1064
1136
  // shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
1065
1137
  const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
@@ -1071,7 +1143,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1071
1143
  agents.push({ key, dir, ws, agent: cmd, name, run, asking: st.asking, busy: st.busy, born: st.born, ...(loopback ? { last: st.last || undefined, at: st.at || undefined } : {}) });
1072
1144
  };
1073
1145
  // A plain shell counts too while an agent typed into it runs there.
1074
- for (const x of shells.values()) { const cmd = x.agent || (x.pid ? shellAgent(x.pid, KNOWN_AGENTS.map((k) => k.cmd)) : undefined); if (cmd) addAgent(x.key, x.dir, x.ws, cmd, x.run); }
1146
+ for (const raw of shells.values()) { const x = shown(raw), cmd = x.agent || (x.pid ? shellAgent(x.pid, KNOWN_AGENTS.map((k) => k.cmd)) : undefined); if (cmd) addAgent(x.key, x.dir, x.ws, cmd, x.run); }
1075
1147
  cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, pty.cmd(k) ?? KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
1076
1148
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1077
1149
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
@@ -1084,7 +1156,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1084
1156
  rail: [...new Set(cards.map((c) => c.state))].filter((d) => !picker.includes(d)).map(entry),
1085
1157
  fresh: unset.map((d) => ({ dir: join(d, ".kaizen"), label: tilde(d) })),
1086
1158
  agents,
1087
- cards: cards.map((c, i) => ({ ...c, notice: notice(c), ...extra[i], pty: ptys[i] })),
1159
+ cards: cards.map((c, i) => {
1160
+ const rep = c.kind === "run" && c.id && c.status !== "done" && c.status !== "abandoned" ? readReport(c.state, c.id) : null;
1161
+ const signal = signalOf(c, rep, ptys[i] as any, Date.now(), beat);
1162
+ // Only a run that has workers.json carries `workers`: any other card is as it was.
1163
+ const ws = c.kind === "run" && c.id ? readWorkers(projectOf(c.state), c.id) : null;
1164
+ return { ...c, notice: notice(c), ...extra[i], pty: ptys[i], signal, ...(ws ? { workers: ws.workers.map((x) => ({ id: x.id, title: x.title, status: workerStale(x, x.key ? ptyState(x.key) : null, Date.now(), beat) ? "stale" : x.status, bypass: x.bypass })), ...(ws.merge && ws.merge.status !== "merged" ? { workersMerge: ws.merge.status } : {}) } : {}), ...(rep?.phase ? { phase: rep.phase } : {}), ...(signal === "blocked" ? { blocked: rep!.blocked } : {}) };
1165
+ }),
1088
1166
  backlog: backlog.map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1089
1167
  now: Date.now(),
1090
1168
  });
@@ -1161,6 +1239,81 @@ export async function web(repoDir: string, opts: Opts = {}) {
1161
1239
  return json({ ...onboardingView(home, projects), default: ch.default, installed: ch.agents.map((a) => a.cmd), agents: KNOWN_AGENTS.map((a) => ({ cmd: a.cmd, name: a.name })), install: installHelp(process.platform === "win32") });
1162
1240
  }
1163
1241
 
1242
+ // Names, folders' sign-in lines and usage only: tokens stay in the tools' own files.
1243
+ if (path === "/accounts" && (req.method === "GET" || req.method === "POST")) {
1244
+ let added: string | undefined;
1245
+ if (req.method === "POST") {
1246
+ const refused = strict(req);
1247
+ if (refused) return refused;
1248
+ let body: any;
1249
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1250
+ const r: any = body?.op === "add" ? addAccount(body.tool, body.name)
1251
+ : body?.op === "rename" ? renameAccount(String(body.id ?? ""), body.name)
1252
+ : body?.op === "remove" ? removeAccount(String(body.id ?? ""), body.deleteFolder === true)
1253
+ : body?.op === "default" ? setDefaultAccount(body.tool, String(body.id ?? ""))
1254
+ : "unknown op";
1255
+ const why = typeof r === "string" ? r : r?.error;
1256
+ if (why) return bad(why);
1257
+ added = r?.id;
1258
+ acctUsage.clear();
1259
+ changed();
1260
+ }
1261
+ const a = readAccounts();
1262
+ const rows = await Promise.all(a.accounts.map(async (x) => {
1263
+ const dir = accountDir(x.id);
1264
+ let hit = acctUsage.get(x.id);
1265
+ if (!hit || Date.now() - hit.at > 60_000) {
1266
+ hit = { at: Date.now(), usage: x.tool === "claude" ? await claudeUsageAt(dir) : codexUsageAt(dir) };
1267
+ acctUsage.set(x.id, hit);
1268
+ }
1269
+ return { ...x, isDefault: a.default[x.tool] === x.id, signedIn: signedIn(dir, x.tool), usage: hit.usage, signIn: `${ACCOUNT_VAR[x.tool]}=${dir} ${x.tool}${x.tool === "codex" ? " login" : ""}` };
1270
+ }));
1271
+ return json({ accounts: rows, windows: process.platform === "win32", ...(added ? { added } : {}) });
1272
+ }
1273
+
1274
+ if (path === "/skills" && (req.method === "GET" || req.method === "POST")) {
1275
+ if (req.method === "POST") {
1276
+ const refused = strict(req);
1277
+ if (refused) return refused;
1278
+ let body: any;
1279
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1280
+ // Turning an off-by-default skill on needs the one-time token the page got with its last
1281
+ // GET: the warning is a step a person takes, not a flag a caller can send.
1282
+ const tokenOk = !!skillToken && body?.token === skillToken;
1283
+ skillToken = "";
1284
+ const why = setSkill(repoDir, home, String(body?.id ?? ""), body?.on === true, body?.confirm === true && tokenOk);
1285
+ if (why) return bad(why);
1286
+ }
1287
+ const off = [...skillsOff(home), ...skillsHeld(repoDir, home)];
1288
+ skillToken = crypto.randomUUID();
1289
+ // The desktop-control skill shows what this machine lacks, from the helper's own check.
1290
+ const check = bundledSkills(repoDir).some((s) => s.id === "kaizen-computer") ? (await import("./computer.ts")).computerCheck() : null;
1291
+ 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 } : {}) })) });
1292
+ }
1293
+
1294
+ // Per user, so no scope. A saved environment value is never in either answer.
1295
+ if (path === "/agent-prefs" && (req.method === "GET" || req.method === "POST")) {
1296
+ if (req.method === "POST") {
1297
+ const refused = strict(req);
1298
+ if (refused) return refused;
1299
+ let body: any;
1300
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1301
+ const r = savePrefs(body ?? {}, KNOWN_AGENTS.map((a) => a.cmd));
1302
+ if ("error" in r) return bad(r.error);
1303
+ // The default may not name an agent turned off; the global one moves to Auto.
1304
+ if (body.enabled === false) {
1305
+ const { listSettings, setSetting } = await import("./settings.ts");
1306
+ if (listSettings(repoDir, null).rows.find((x) => x.key === "agent.default")?.value === String(body.agent)) setSetting(repoDir, "agent.default", "auto", null);
1307
+ }
1308
+ changed();
1309
+ }
1310
+ const prefs = readPrefs();
1311
+ return json({
1312
+ permissions: prefs.permissions, envWorks: process.platform !== "win32",
1313
+ agents: KNOWN_AGENTS.map((a) => ({ cmd: a.cmd, name: a.name, installed: !!onPath(commandOf(a.cmd, prefs)), bypass: !!YOLO_FLAGS[a.cmd], ...publicPref(a.cmd, prefs), preview: launchPreview(repoDir, a.cmd, prefs) })),
1314
+ });
1315
+ }
1316
+
1164
1317
  if (req.method === "GET" && path === "/agents") {
1165
1318
  const dir = qdir();
1166
1319
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
@@ -1176,6 +1329,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1176
1329
  scope: scope ? join(scope, ".kaizen") : "all",
1177
1330
  projects: states(true).filter((d) => d !== join(home, ".kaizen")).map((d) => ({ dir: d, label: label(d) })),
1178
1331
  });
1332
+ Object.assign(cfg, { windows: process.platform === "win32" });
1333
+ // A worker model row per installed tool that takes a model flag; the others have nothing to set.
1334
+ const prefs = readPrefs();
1335
+ cfg.rows = cfg.rows.filter((r) => { const t = /^orchestration\.worker_model\.(\w+)$/.exec(r.key)?.[1]; return !t || !!onPath(commandOf(t, prefs)); });
1179
1336
  Object.assign(cfg, { phoneUrls: [...webHosts()].filter((h) => /^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.ts\.net$/.test(h)).map((h) => `https://${h}`) });
1180
1337
  // Connected, the model is chosen from what the plan offers rather than typed.
1181
1338
  const m = cfg.rows.find((r) => r.key === "sources.model");
@@ -1290,6 +1447,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1290
1447
  let body: any;
1291
1448
  try { body = await req.json(); } catch { return bad("json body expected"); }
1292
1449
  const { setSetting, resetSetting } = await import("./settings.ts");
1450
+ if (body.key === "agent.default" && body.value !== "auto" && !agentEnabled(String(body.value))) return bad("That agent is turned off");
1293
1451
  const scope = settingsScope(body.scope == null ? null : String(body.scope));
1294
1452
  if (body.reset && typeof scope !== "string") return bad("only a project's own value can be reset");
1295
1453
  if (scope === false) return bad("unknown project", 404);
@@ -1393,7 +1551,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1393
1551
  const r = await makeProject(name);
1394
1552
  return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
1395
1553
  },
1396
- agents: KNOWN_AGENTS.filter((a) => onPath(a.cmd)).map((a) => a.cmd),
1554
+ agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => a.cmd),
1397
1555
  // As POST /run starts an idea, without one on the inbox.
1398
1556
  run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
1399
1557
  const r = launchRun(parseItem(`${runner} ${text}`), d, undefined, { agent, ...inCard(d) });
@@ -1705,7 +1863,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1705
1863
  const p = parseItem(line.text);
1706
1864
  const it: Item = { ...p, text: kind ? `${kind} ${p.text}` : p.text };
1707
1865
  it.notes = [source !== "orphan" ? `Parent: ${source}` : "", `Backlog: ${source}#${n}`, p.text !== line.text ? `Backlog item: ${line.text}` : ""].filter(Boolean).join("\n");
1708
- const r = launchRun(it, dir, undefined, { agent, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
1866
+ const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
1709
1867
  if (r.ok) backlogLaunched.add(`${dir}\0${source}#${n}`);
1710
1868
  changed();
1711
1869
  return json(r.ok
@@ -1716,7 +1874,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1716
1874
  // A `started` idea may be run again: the terminal the first launch opened
1717
1875
  // can come up empty, and nothing else tells the board a run never began.
1718
1876
  it.notes = readInbox(dir).find((l) => (l.status === "open" || l.status === "started") && l.text === text)?.notes;
1719
- const r = launchRun(it, dir, undefined, { agent, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
1877
+ const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
1720
1878
  if (r.ok) replaceIdea(dir, text, { status: "started", text });
1721
1879
  if (r.ok && r.pty) {
1722
1880
  for (const [k, v] of ideaPty) if (!ptyState(v)) ideaPty.delete(k); // sessions already dropped
@@ -1975,7 +2133,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1975
2133
 
1976
2134
  if (path === "/abort") {
1977
2135
  const id = String(body.id ?? "");
1978
- const why = String(body.why ?? "").trim() || "abandoned from the web board";
2136
+ const why = String(body.why ?? "").trim() || "abandoned from the web";
1979
2137
  if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1980
2138
  const failed = abandonRun(dir, id, why);
1981
2139
  changed();
@@ -2038,6 +2196,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2038
2196
  setTimeout(() => process.exit(0), 3000).unref();
2039
2197
  const live = ptyKeys().some((k) => ptyState(k)?.alive);
2040
2198
  saveLive();
2199
+ awake.stop();
2041
2200
  clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(loop); clearInterval(keepList);
2042
2201
  for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
2043
2202
  setTimeout(() => { server.stop(true); resolve(); }, live ? 400 : 0);