kaizen-agent 1.61.6 → 1.63.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 (120) 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/automations.test.ts +167 -0
  14. package/cli/automations.ts +298 -0
  15. package/cli/board.test.ts +4 -5
  16. package/cli/computer-helper.py +299 -0
  17. package/cli/computer.test.ts +155 -0
  18. package/cli/computer.ts +66 -0
  19. package/cli/dashboard.ts +15 -22
  20. package/cli/install.test.ts +16 -0
  21. package/cli/install.ts +134 -193
  22. package/cli/keep-awake.ts +30 -0
  23. package/cli/look.ts +33 -0
  24. package/cli/project-tree.test.ts +1 -0
  25. package/cli/pty.test.ts +2 -1
  26. package/cli/pty.ts +6 -5
  27. package/cli/report.test.ts +59 -0
  28. package/cli/report.ts +62 -0
  29. package/cli/restart.test.ts +1 -0
  30. package/cli/settings.test.ts +21 -1
  31. package/cli/settings.ts +22 -13
  32. package/cli/setup.test.ts +24 -4
  33. package/cli/setup.ts +101 -51
  34. package/cli/skills.test.ts +89 -0
  35. package/cli/skills.ts +112 -0
  36. package/cli/sources.ts +1 -1
  37. package/cli/state.test.ts +53 -4
  38. package/cli/state.ts +132 -42
  39. package/cli/term-image.test.ts +23 -0
  40. package/cli/term-image.ts +26 -0
  41. package/cli/usage.test.ts +8 -2
  42. package/cli/usage.ts +8 -6
  43. package/cli/video.test.ts +5 -5
  44. package/cli/web-accept.test.ts +1 -0
  45. package/cli/web-decide.test.ts +1 -0
  46. package/cli/web-pr.test.ts +1 -0
  47. package/cli/web-skills.test.ts +32 -0
  48. package/cli/web-symlink.test.ts +1 -0
  49. package/cli/web.ts +227 -21
  50. package/cli/workers.test.ts +319 -0
  51. package/cli/workers.ts +380 -0
  52. package/cli/worktree.test.ts +21 -2
  53. package/cli/worktree.ts +21 -2
  54. package/package.json +1 -1
  55. package/skills/kaizen/config.default.yml +40 -1
  56. package/skills/kaizen/settings.md +2 -1
  57. package/skills/kaizen/skill.json +1 -0
  58. package/skills/kaizen/spec-build.md +22 -2
  59. package/skills/kaizen/spec-main.md +9 -0
  60. package/skills/kaizen/spec-plan.md +18 -1
  61. package/skills/kaizen/spec-review.md +4 -0
  62. package/skills/kaizen/spec.md +15 -0
  63. package/skills/kaizen-help/SKILL.md +2 -0
  64. package/skills/kaizen-help/skill.json +1 -0
  65. package/skills/media/kaizen-book/skill.json +1 -0
  66. package/skills/media/kaizen-deck/SKILL.md +21 -2
  67. package/skills/media/kaizen-deck/scripts/motion.py +99 -0
  68. package/skills/media/kaizen-deck/skill.json +1 -0
  69. package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
  70. package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
  71. package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
  72. package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
  73. package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
  74. package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
  75. package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
  76. package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
  77. package/skills/media/kaizen-video/skill.json +1 -0
  78. package/skills/optional/kaizen-computer/SKILL.md +38 -0
  79. package/skills/optional/kaizen-computer/skill.json +1 -0
  80. package/web/board/add-project.ts +3 -3
  81. package/web/board/agent-favicons.ts +9 -0
  82. package/web/board/agent-term.ts +1 -1
  83. package/web/board/api.ts +1 -1
  84. package/web/board/approvals.ts +1 -1
  85. package/web/board/cards.ts +50 -7
  86. package/web/board/dictation.ts +46 -3
  87. package/web/board/fixes.ts +1 -1
  88. package/web/board/home.ts +1 -1
  89. package/web/board/icebox.ts +1 -1
  90. package/web/board/keys.ts +5 -15
  91. package/web/board/onboarding.ts +1 -1
  92. package/web/board/panel.ts +24 -20
  93. package/web/board/phone.ts +6 -1
  94. package/web/board/run-view.ts +118 -7
  95. package/web/board/search.ts +6 -0
  96. package/web/board/settings-accounts.ts +60 -0
  97. package/web/board/settings-agents.ts +102 -0
  98. package/web/board/settings-automations.ts +71 -0
  99. package/web/board/settings-orchestration.ts +32 -0
  100. package/web/board/settings-pages.test.ts +9 -0
  101. package/web/board/settings-pages.ts +11 -4
  102. package/web/board/settings-skills.ts +47 -0
  103. package/web/board/settings-voice.test.ts +18 -0
  104. package/web/board/settings-voice.ts +28 -0
  105. package/web/board/settings.ts +48 -5
  106. package/web/board/terms.ts +2 -2
  107. package/web/board/update.ts +1 -1
  108. package/web/board/workspace.ts +5 -1
  109. package/web/board/ws-board.test.ts +6 -0
  110. package/web/board/ws-board.ts +2 -0
  111. package/web/board/ws-tabs.test.ts +12 -1
  112. package/web/board/ws-tabs.ts +18 -0
  113. package/web/board.html +22 -5
  114. package/web/board.js +156 -85
  115. package/web/notebook.js +22 -22
  116. package/web/notes.html +3 -3
  117. package/web/term.js +27 -27
  118. package/web/term.ts +25 -3
  119. package/web/video.html +2 -2
  120. package/web/video.js +31 -31
@@ -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";
@@ -20,10 +28,11 @@ import { writeBacks } from "./writeback.ts";
20
28
  import { postLink, sendReply } from "./browser.ts";
21
29
  import { listNotes, saveNote, renameNote, deleteNote, boardIndex, linksTo } from "./notes.ts";
22
30
  import * as video from "./video.ts";
31
+ import * as auto from "./automations.ts";
23
32
  import * as localsend from "./localsend.ts";
24
33
  import * as hermes from "./hermes.ts";
25
34
  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";
35
+ import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, linkedWs, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
27
36
  import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
28
37
 
29
38
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
@@ -67,6 +76,8 @@ const served = (f: string) => installed() === VERSION && existsSync(f) ? readTex
67
76
  // Loopback hosts only; shared by /open-url and /frameable so the board is never a way to reach other sites.
68
77
  const isLoopback = (u: URL) => ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
69
78
 
79
+ // A run whose launched terminal is still alive (automations treat it as open).
80
+ const runLive = (dir: string, id: string) => Object.values(stagesOf(dir, id)).some((k) => !!ptyState(k)?.alive);
70
81
  export const stagesOf = (dir: string, id: string): Record<string, string> => { try { return JSON.parse(readText(join(dir, "runs", id, "terminals.json"))) ?? {}; } catch { return {}; } };
71
82
  export const markStage = (dir: string, id: string, stage: string, key?: string) => {
72
83
  if (!stage || !key || !id || /^\.+$/.test(id)) return;
@@ -236,11 +247,17 @@ export async function web(repoDir: string, opts: Opts = {}) {
236
247
  // Stricter than local(), for routes that start a process: another local server's page
237
248
  // (the dev server a localhost tab frames) shares the hostname, so the port must match
238
249
  // too, and a JSON content type forces a preflight that a foreign page cannot pass.
239
- const strict = (req: Request) => {
250
+ const sameOrigin = (req: Request) => {
240
251
  const origin = req.headers.get("origin");
241
252
  let same = !origin;
242
253
  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);
254
+ return same;
255
+ };
256
+ // One-time token for turning an off-by-default skill on; each GET /skills mints a new one. It stops
257
+ // an agent switching itself on by accident, not a local process that reads the board's own page.
258
+ let skillToken = "";
259
+ const strict = (req: Request) => {
260
+ if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
244
261
  if (!/^application\/json\b/i.test(req.headers.get("content-type") ?? "")) return bad("json body expected", 415);
245
262
  return null;
246
263
  };
@@ -251,8 +268,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
251
268
  // Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
252
269
  const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; ws?: string; pid?: number }>();
253
270
  const SHELL_CAP = 8;
271
+ // A terminal shows where its live run builds, not where it launched: tabs follow `run`, the rail `ws`.
272
+ const shown = <S extends { key: string; dir: string; run: string; ws?: string }>(x: S): S => {
273
+ const w = linkedWs(x.dir, x.key), project = projectOf(x.dir);
274
+ // A worktree the run just made: refresh the list now, or the rail has no row to put it under.
275
+ if (w && !workspaces(project).some((p) => p.path === w) && workspacesAge(project) > 1000) { forgetWorkspaces(project); workspaces(project); }
276
+ return w ? { ...x, ws: w, run: `ws:${x.dir}:${w}` } : x;
277
+ };
254
278
  let usageCache: Usage[] = [];
255
279
  let usageAt = 0;
280
+ const acctUsage = new Map<string, { at: number; usage: Usage | null }>();
256
281
  let pending: ReturnType<typeof setTimeout> | null = null;
257
282
  const prBusy = new Set<string>();
258
283
  // /state costs ~250 ms of this one thread on a big board (git status per project), and
@@ -297,7 +322,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
297
322
  let run: any;
298
323
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return { error: "no such run", status: 404 }; }
299
324
  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 };
325
+ if (liveAgent(dir, id)) return { error: "its agent is still running in its workspace", status: 409 };
301
326
  const quiet = run.stage === "done" || !!run.awaiting;
302
327
  const own = quiet ? runAgent(dir, id) : null;
303
328
  if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
@@ -410,9 +435,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
410
435
  if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
411
436
  // Every agent session the run has had on this board, for the workspace's Agent tabs.
412
437
  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 };
438
+ 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
439
  }, { cmd: (k: string) => cmdOf.get(k) });
415
440
  };
441
+ // Orchestration: the only place a worker's terminal starts. A worker asks for it in workers.json
442
+ // (`kaizen worker start`); with the mode off no such file exists, so this finds nothing.
443
+ // startWorker re-checks the stage, the frozen settings, the count and the plan before anything runs.
444
+ let workersAt = 0;
445
+ const spawnWorkers = () => {
446
+ if (process.platform === "win32" || !ptySupported || Date.now() - workersAt < 300) return;
447
+ workersAt = Date.now();
448
+ for (const dir of states(true)) {
449
+ if (dir === join(home, ".kaizen")) continue;
450
+ const project = projectOf(dir);
451
+ for (const { id, wid } of requested(project)) {
452
+ const r = startWorker(project, id, wid);
453
+ if (!r.ok) { failStart(project, id, wid, r.why); continue; }
454
+ const l = r.launch, key = "sh-" + crypto.randomUUID().slice(0, 8);
455
+ for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
456
+ if (l.agent === "claude") trustFolder(l.cwd, l.trust);
457
+ try {
458
+ const pid = startPty(key, l.argv, l.cwd, undefined, changed, { env: { ...l.env, KAIZEN_TERM: key } });
459
+ shells.set(key, { key, dir, title: l.title, agent: l.agent, run: `run:${dir}:${id}`, ws: l.cwd, pid });
460
+ markRunning(project, id, wid, key, l);
461
+ } catch (err: any) { failStart(project, id, wid, err?.message ?? String(err)); }
462
+ changed();
463
+ }
464
+ try {
465
+ const runs = join(dir, "runs");
466
+ for (const id of existsSync(runs) ? readdirSync(runs) : []) if (sweep(project, id, (k) => !!ptyState(k)?.alive)) changed();
467
+ } catch { /* the next tick tries again */ }
468
+ }
469
+ };
416
470
  const watchers: FSWatcher[] = [];
417
471
  const watchAll = () => {
418
472
  for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
@@ -420,7 +474,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
420
474
  for (const dir of states(true)) {
421
475
  // An unhandled 'error' on a watcher (Windows: a watched dir renamed, EPERM on
422
476
  // 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 */ }
477
+ try { watchers.push(watch(dir, { recursive: true }, () => { changed(); spawnWorkers(); }).on("error", () => {})); } catch { /* poll covers it */ }
424
478
  }
425
479
  };
426
480
  watchAll();
@@ -439,12 +493,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
439
493
  let last = fingerprint();
440
494
  let seen = states(true).join("\n");
441
495
  let ticks = 0;
496
+ const awake = awakeHolder();
442
497
  const poll = setInterval(() => {
498
+ awake.sync(wantAwake(keepAwake(), ptyKeys().some((k) => ptyState(k)?.alive && !(shells.has(k) && !shells.get(k)!.agent))));
443
499
  // Once a minute: windows of runs finished or abandoned past the grace are closed.
444
500
  if (++ticks % 30 === 0) for (const dir of states(true)) sweepSessions(dir);
445
501
  // A project registered since start (a run launched into a fresh dir) gets a watcher too.
446
502
  const now = states(true).join("\n"); if (now !== seen) { seen = now; watchAll(); }
447
503
  const fp = fingerprint(); if (fp !== last) { last = fp; changed(); }
504
+ spawnWorkers();
448
505
  }, 2000);
449
506
 
450
507
  // The schedule: once a minute, gather every request source that is due. It writes
@@ -488,6 +545,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
488
545
  busy = false;
489
546
  }, 60_000);
490
547
 
548
+ // Automations: a due rule starts a run in its own project. Own busy flag; a fire may wait on a precheck.
549
+ let autoBusy = false;
550
+ const automate = setInterval(async () => {
551
+ if (autoBusy) return;
552
+ autoBusy = true;
553
+ try { if (await auto.tickAutomations(states(true).filter((d) => d !== join(home, ".kaizen")), { pick: inCard, live: runLive })) changed(); } catch { /* the next tick tries again */ }
554
+ autoBusy = false;
555
+ }, 60_000);
556
+
491
557
  // Done requests are reported back to their sources here, on the board's own clock: a
492
558
  // page load only reads, so opening the Icebox never closes an issue.
493
559
  const loop = setInterval(async () => {
@@ -736,6 +802,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
736
802
  // workspace's + menu. Code execution, so local() as for every write, a registered
737
803
  // project, and an agent only from KNOWN_AGENTS: no argv ever comes from the page.
738
804
  // Its keys (sh-…) are /pty keys, so /pty's exact-origin check covers the socket.
805
+ // An image pasted into a terminal: saved here so its path can be typed into the agent.
806
+ // Raw bytes, so not strict()'s JSON, but an image content type still forces a preflight.
807
+ if (req.method === "POST" && path === "/term-image") {
808
+ if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
809
+ if (!/^image\//i.test(req.headers.get("content-type") ?? "")) return bad("image body expected", 415);
810
+ if (Number(req.headers.get("content-length") ?? 0) > MAX_IMAGE) return bad("image too large", 413);
811
+ const saved = saveImage(new Uint8Array(await req.arrayBuffer()));
812
+ return saved ? json({ path: saved }) : bad("not an image", 415);
813
+ }
739
814
  if (req.method === "POST" && path === "/shell") {
740
815
  const refused = strict(req);
741
816
  if (refused) return refused;
@@ -746,6 +821,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
746
821
  if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
747
822
  let cmd: string[];
748
823
  let agent = "";
824
+ let bypass = false;
749
825
  // The run's own agent session, resumed here ("run:<dir>:<id>" names the run; the session
750
826
  // id is read from that run's state.json, never taken from the page). Claude only: it is
751
827
  // the agent whose session id runs record. Refused while that session is still running
@@ -773,12 +849,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
773
849
  }
774
850
  if (sessionLive(sid)) return json({ live: true }, 409);
775
851
  agent = "claude";
776
- cmd = ["claude", "--resume", sid];
852
+ const acct = accountForRun(projectOf(dir), id, "claude");
853
+ if (acct.error) return bad(acct.error, 400);
854
+ cmd = acct.dir ? ["env", ...accountEnv(acct), "claude", "--resume", sid] : ["claude", "--resume", sid];
777
855
  } else if (body.agent != null) {
778
856
  const a = KNOWN_AGENTS.find((k) => k.cmd === body.agent);
779
- if (!a || !onPath(a.cmd)) return bad("unknown agent", 400);
857
+ if (!a || !agentUsable(a.cmd)) return bad("unknown agent", 400);
780
858
  agent = a.cmd;
781
- cmd = [a.cmd];
859
+ // A sign-in names its account and runs plain: no bypass, no arguments.
860
+ const signIn = typeof body.account === "string" && body.account !== "";
861
+ const acct = resolveAccount(a.cmd, signIn ? body.account : undefined);
862
+ if (acct.error) return bad(acct.error, 400);
863
+ bypass = !signIn && prefersBypass(a.cmd) && !!YOLO_FLAGS[a.cmd];
864
+ const line = signIn ? [commandOf(a.cmd), ...(a.cmd === "codex" ? ["login"] : [])] : withEnv([commandOf(a.cmd), ...(bypass ? YOLO_FLAGS[a.cmd]! : []), ...argsOf(a.cmd)], a.cmd);
865
+ cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
782
866
  } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
783
867
  // A workspace folder: only an exact path from this project's own `git worktree list`.
784
868
  let cwd = projectOf(dir);
@@ -792,8 +876,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
792
876
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
793
877
  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
878
  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);
879
+ const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
880
+ const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key } });
797
881
  // The run workspace that opened it (its card key), so each run keeps its own centre.
798
882
  shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
799
883
  changed();
@@ -889,7 +973,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
889
973
  if (req.method === "GET" && path === "/shells") {
890
974
  const dir = qdir();
891
975
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
892
- return json([...shells.values()].filter((s) => !dir || s.dir === dir));
976
+ return json([...shells.values()].filter((s) => !dir || s.dir === dir).map(shown));
893
977
  }
894
978
  // The localhost tab's "Open in browser": a Chromium app window on this computer, for
895
979
  // localhost pages that refuse to be framed. Launches a process, so /shell's guards, and only a
@@ -1059,7 +1143,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1059
1143
  if (hit?.gen === gen && Date.now() - hit.at < STATE_MS) return new Response(hit.body, { headers: { "content-type": "application/json" } });
1060
1144
  // Off this thread: it also relays every terminal, and a rebuild here froze their typing.
1061
1145
  const { cards, extra, backlog } = await buildSnap(dirs, gitGen).catch(() => snapshot(dirs, gitGen));
1062
- const pty = ptyOf(cards);
1146
+ const pty = ptyOf(cards), beat = heartbeatMinutes();
1063
1147
  // The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
1064
1148
  // shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
1065
1149
  const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
@@ -1071,7 +1155,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1071
1155
  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
1156
  };
1073
1157
  // 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); }
1158
+ 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
1159
  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
1160
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1077
1161
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
@@ -1084,7 +1168,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1084
1168
  rail: [...new Set(cards.map((c) => c.state))].filter((d) => !picker.includes(d)).map(entry),
1085
1169
  fresh: unset.map((d) => ({ dir: join(d, ".kaizen"), label: tilde(d) })),
1086
1170
  agents,
1087
- cards: cards.map((c, i) => ({ ...c, notice: notice(c), ...extra[i], pty: ptys[i] })),
1171
+ cards: cards.map((c, i) => {
1172
+ const rep = c.kind === "run" && c.id && c.status !== "done" && c.status !== "abandoned" ? readReport(c.state, c.id) : null;
1173
+ const signal = signalOf(c, rep, ptys[i] as any, Date.now(), beat);
1174
+ // Only a run that has workers.json carries `workers`: any other card is as it was.
1175
+ const ws = c.kind === "run" && c.id ? readWorkers(projectOf(c.state), c.id) : null;
1176
+ 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 } : {}) };
1177
+ }),
1088
1178
  backlog: backlog.map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1089
1179
  now: Date.now(),
1090
1180
  });
@@ -1161,6 +1251,116 @@ export async function web(repoDir: string, opts: Opts = {}) {
1161
1251
  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
1252
  }
1163
1253
 
1254
+ // Names, folders' sign-in lines and usage only: tokens stay in the tools' own files.
1255
+ if (path === "/accounts" && (req.method === "GET" || req.method === "POST")) {
1256
+ let added: string | undefined;
1257
+ if (req.method === "POST") {
1258
+ const refused = strict(req);
1259
+ if (refused) return refused;
1260
+ let body: any;
1261
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1262
+ const r: any = body?.op === "add" ? addAccount(body.tool, body.name)
1263
+ : body?.op === "rename" ? renameAccount(String(body.id ?? ""), body.name)
1264
+ : body?.op === "remove" ? removeAccount(String(body.id ?? ""), body.deleteFolder === true)
1265
+ : body?.op === "default" ? setDefaultAccount(body.tool, String(body.id ?? ""))
1266
+ : "unknown op";
1267
+ const why = typeof r === "string" ? r : r?.error;
1268
+ if (why) return bad(why);
1269
+ added = r?.id;
1270
+ acctUsage.clear();
1271
+ changed();
1272
+ }
1273
+ const a = readAccounts();
1274
+ const rows = await Promise.all(a.accounts.map(async (x) => {
1275
+ const dir = accountDir(x.id);
1276
+ let hit = acctUsage.get(x.id);
1277
+ if (!hit || Date.now() - hit.at > 60_000) {
1278
+ hit = { at: Date.now(), usage: x.tool === "claude" ? await claudeUsageAt(dir) : codexUsageAt(dir) };
1279
+ acctUsage.set(x.id, hit);
1280
+ }
1281
+ 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" : ""}` };
1282
+ }));
1283
+ return json({ accounts: rows, windows: process.platform === "win32", ...(added ? { added } : {}) });
1284
+ }
1285
+
1286
+ if (path === "/automations" && (req.method === "GET" || req.method === "POST")) {
1287
+ if (!state || state === join(home, ".kaizen")) return json({ error: "Open a project first." }, 404);
1288
+ let rules: auto.Rule[];
1289
+ try { rules = auto.readRules(state); } catch (e: any) { return bad(e.message, 500); }
1290
+ if (req.method === "POST") {
1291
+ const refused = strict(req);
1292
+ if (refused) return refused;
1293
+ let body: any;
1294
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1295
+ const id = String(body.id ?? "");
1296
+ let r: unknown = null;
1297
+ if (body.op === "create") r = auto.addRule(state, body);
1298
+ else if (body.op === "update") r = auto.updateRule(state, id, body);
1299
+ else if (body.op === "pause" || body.op === "resume") r = auto.setEnabled(state, id, body.op === "resume");
1300
+ else if (body.op === "delete") r = auto.removeRule(state, id);
1301
+ else if (body.op === "run") {
1302
+ const rule = rules.find((x) => x.id === id);
1303
+ if (!rule) return bad("No such automation.", 404);
1304
+ const h = await auto.fire(state, rule, "manual", Date.now(), { pick: inCard, live: runLive });
1305
+ changed();
1306
+ return json({ ok: h?.status === "launched", status: h?.status, why: h?.reason }, 200);
1307
+ } else return bad("unknown op");
1308
+ if (typeof r === "string") return bad(r);
1309
+ changed();
1310
+ rules = auto.readRules(state);
1311
+ }
1312
+ const hist = auto.readHistory(state);
1313
+ const now = Date.now();
1314
+ return json({
1315
+ zone: Intl.DateTimeFormat().resolvedOptions().timeZone, cap: auto.DAILY_CAP, project: label(state),
1316
+ agents: KNOWN_AGENTS.filter((a) => agentEnabled(a.cmd)).map((a) => ({ cmd: a.cmd, name: a.name })),
1317
+ rules: rules.map((r) => ({ ...r, next: auto.nextRun(r.cron, now), history: hist.filter((h) => h.rule === r.id).sort((a, b) => b.at - a.at).slice(0, 20).map((h) => ({ ...h, ...auto.shown(state, h, now) })) })),
1318
+ });
1319
+ }
1320
+
1321
+ if (path === "/skills" && (req.method === "GET" || req.method === "POST")) {
1322
+ if (req.method === "POST") {
1323
+ const refused = strict(req);
1324
+ if (refused) return refused;
1325
+ let body: any;
1326
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1327
+ // Turning an off-by-default skill on needs the one-time token the page got with its last
1328
+ // GET: the warning is a step a person takes, not a flag a caller can send.
1329
+ const tokenOk = !!skillToken && body?.token === skillToken;
1330
+ skillToken = "";
1331
+ const why = setSkill(repoDir, home, String(body?.id ?? ""), body?.on === true, body?.confirm === true && tokenOk);
1332
+ if (why) return bad(why);
1333
+ }
1334
+ const off = [...skillsOff(home), ...skillsHeld(repoDir, home)];
1335
+ skillToken = crypto.randomUUID();
1336
+ // The desktop-control skill shows what this machine lacks, from the helper's own check.
1337
+ const check = bundledSkills(repoDir).some((s) => s.id === "kaizen-computer") ? (await import("./computer.ts")).computerCheck() : null;
1338
+ 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 } : {}) })) });
1339
+ }
1340
+
1341
+ // Per user, so no scope. A saved environment value is never in either answer.
1342
+ if (path === "/agent-prefs" && (req.method === "GET" || req.method === "POST")) {
1343
+ if (req.method === "POST") {
1344
+ const refused = strict(req);
1345
+ if (refused) return refused;
1346
+ let body: any;
1347
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1348
+ const r = savePrefs(body ?? {}, KNOWN_AGENTS.map((a) => a.cmd));
1349
+ if ("error" in r) return bad(r.error);
1350
+ // The default may not name an agent turned off; the global one moves to Auto.
1351
+ if (body.enabled === false) {
1352
+ const { listSettings, setSetting } = await import("./settings.ts");
1353
+ if (listSettings(repoDir, null).rows.find((x) => x.key === "agent.default")?.value === String(body.agent)) setSetting(repoDir, "agent.default", "auto", null);
1354
+ }
1355
+ changed();
1356
+ }
1357
+ const prefs = readPrefs();
1358
+ return json({
1359
+ permissions: prefs.permissions, envWorks: process.platform !== "win32",
1360
+ 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) })),
1361
+ });
1362
+ }
1363
+
1164
1364
  if (req.method === "GET" && path === "/agents") {
1165
1365
  const dir = qdir();
1166
1366
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
@@ -1176,6 +1376,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1176
1376
  scope: scope ? join(scope, ".kaizen") : "all",
1177
1377
  projects: states(true).filter((d) => d !== join(home, ".kaizen")).map((d) => ({ dir: d, label: label(d) })),
1178
1378
  });
1379
+ Object.assign(cfg, { windows: process.platform === "win32" });
1380
+ // A worker model row per installed tool that takes a model flag; the others have nothing to set.
1381
+ const prefs = readPrefs();
1382
+ cfg.rows = cfg.rows.filter((r) => { const t = /^orchestration\.worker_model\.(\w+)$/.exec(r.key)?.[1]; return !t || !!onPath(commandOf(t, prefs)); });
1179
1383
  Object.assign(cfg, { phoneUrls: [...webHosts()].filter((h) => /^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.ts\.net$/.test(h)).map((h) => `https://${h}`) });
1180
1384
  // Connected, the model is chosen from what the plan offers rather than typed.
1181
1385
  const m = cfg.rows.find((r) => r.key === "sources.model");
@@ -1290,6 +1494,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1290
1494
  let body: any;
1291
1495
  try { body = await req.json(); } catch { return bad("json body expected"); }
1292
1496
  const { setSetting, resetSetting } = await import("./settings.ts");
1497
+ if (body.key === "agent.default" && body.value !== "auto" && !agentEnabled(String(body.value))) return bad("That agent is turned off");
1293
1498
  const scope = settingsScope(body.scope == null ? null : String(body.scope));
1294
1499
  if (body.reset && typeof scope !== "string") return bad("only a project's own value can be reset");
1295
1500
  if (scope === false) return bad("unknown project", 404);
@@ -1393,7 +1598,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1393
1598
  const r = await makeProject(name);
1394
1599
  return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
1395
1600
  },
1396
- agents: KNOWN_AGENTS.filter((a) => onPath(a.cmd)).map((a) => a.cmd),
1601
+ agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => a.cmd),
1397
1602
  // As POST /run starts an idea, without one on the inbox.
1398
1603
  run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
1399
1604
  const r = launchRun(parseItem(`${runner} ${text}`), d, undefined, { agent, ...inCard(d) });
@@ -1705,7 +1910,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1705
1910
  const p = parseItem(line.text);
1706
1911
  const it: Item = { ...p, text: kind ? `${kind} ${p.text}` : p.text };
1707
1912
  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) });
1913
+ 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
1914
  if (r.ok) backlogLaunched.add(`${dir}\0${source}#${n}`);
1710
1915
  changed();
1711
1916
  return json(r.ok
@@ -1716,7 +1921,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1716
1921
  // A `started` idea may be run again: the terminal the first launch opened
1717
1922
  // can come up empty, and nothing else tells the board a run never began.
1718
1923
  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) });
1924
+ 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
1925
  if (r.ok) replaceIdea(dir, text, { status: "started", text });
1721
1926
  if (r.ok && r.pty) {
1722
1927
  for (const [k, v] of ideaPty) if (!ptyState(v)) ideaPty.delete(k); // sessions already dropped
@@ -1975,7 +2180,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1975
2180
 
1976
2181
  if (path === "/abort") {
1977
2182
  const id = String(body.id ?? "");
1978
- const why = String(body.why ?? "").trim() || "abandoned from the web board";
2183
+ const why = String(body.why ?? "").trim() || "abandoned from the web";
1979
2184
  if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1980
2185
  const failed = abandonRun(dir, id, why);
1981
2186
  changed();
@@ -2038,7 +2243,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
2038
2243
  setTimeout(() => process.exit(0), 3000).unref();
2039
2244
  const live = ptyKeys().some((k) => ptyState(k)?.alive);
2040
2245
  saveLive();
2041
- clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(loop); clearInterval(keepList);
2246
+ awake.stop();
2247
+ clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(automate); clearInterval(loop); clearInterval(keepList);
2042
2248
  for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
2043
2249
  setTimeout(() => { server.stop(true); resolve(); }, live ? 400 : 0);
2044
2250
  };