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
package/README.md CHANGED
@@ -41,7 +41,7 @@
41
41
  </details>
42
42
 
43
43
  <p align="center">
44
- <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/assets/hero.gif" alt="Animated walkthrough of the kaizen board, from a gathered request to a reviewed, fixed run" width="100%">
44
+ <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/site/media/workspace.gif" alt="Animated walkthrough of a kaizen run in the workspace: plan, approval, build, a fresh review and the finished app" width="100%">
45
45
  </p>
46
46
 
47
47
  ## The problem
@@ -65,7 +65,7 @@ None of this is a lack of intelligence. It is a missing workflow. Many assistant
65
65
  3. **Open the board** with `kaizen web`, or type `/kaizen <request>` in your agent.
66
66
 
67
67
  <p align="center">
68
- <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/assets/board-v2.png" alt="The kaizen board: icebox, ideas, plan, build, review and done columns" width="100%">
68
+ <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/site/media/workspace.png" alt="The kaizen workspace: agent tabs, the app in a browser pane, and the plan waiting for review" width="100%">
69
69
  </p>
70
70
 
71
71
  ## Requirements
@@ -19,6 +19,7 @@ copy, a runbook, or a memo, and everything below applies the same way to each.
19
19
 
20
20
  ## Rules
21
21
 
22
+ - **Workers.** A plan with an approved `## Workers` section makes you the coordinator: `kaizen worker init`, `start`, `status`, then `merge`, and stop on any failed, blocked or unverified worker, as the build stage describes. Without one, build as usual.
22
23
  - **Stay inside the plan's scope.** The plan's *Not included* list is binding.
23
24
  Something out of scope that clearly needs doing goes into `03-impl.md` as a note
24
25
  for the user, and stays unproduced.
@@ -87,3 +88,5 @@ change — do not refactor around it. Write what you changed to
87
88
  Return: what you produced or touched, whether verification passed, and any deviation
88
89
  or blocker.
89
90
  Keep it short — the detail is on disk, and the reviewer reads it there.
91
+
92
+ Report progress and finish with `kaizen report`, as *Reporting to the board* in `spec.md` says.
@@ -250,6 +250,7 @@ software — a document or a runbook has no stdlib to reach for.
250
250
  large refactor, say so in Risks and offer the narrow version as an alternative.
251
251
  - Match the repo's existing conventions; do not introduce a new pattern, library, or
252
252
  dependency without justifying it in the plan.
253
+ - Only when `kaizen worker config <run id>` prints `on` and the work has two or more independent halves, add a `## Workers` section as the planning stage describes; otherwise plan no workers.
253
254
  - If the request cannot be planned without an answer from the user, ask — and if the
254
255
  answer is not available, put it in Open questions rather than picking a default and
255
256
  burying it in a step.
@@ -259,3 +260,5 @@ software — a document or a runbook has no stdlib to reach for.
259
260
  Return a short summary: the track in one line, your framing in one line, the goal in
260
261
  one line, the number of steps, the top risk, and any open questions. The main thread relays this to the user
261
262
  — do not restate the whole plan, it is already on disk.
263
+
264
+ Report progress and finish with `kaizen report`, as *Reporting to the board* in `spec.md` says.
@@ -161,3 +161,5 @@ evidenced, new — recall before saving), generalized, with `--applies` naming t
161
161
 
162
162
  Return the verdict line, the critical and high findings, and every `CANNOT VERIFY`
163
163
  line. The full list is on disk.
164
+
165
+ Report progress and finish with `kaizen report`, as *Reporting to the board* in `spec.md` says.
Binary file
package/assets/kaizen.ico CHANGED
Binary file
@@ -0,0 +1,126 @@
1
+ import { afterEach, beforeEach, expect, test } from "bun:test";
2
+ import { existsSync, mkdirSync, mkdtempSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { accountDir, addAccount, signedIn, renameAccount, linkKaizen, readAccounts, removeAccount, resolveAccount, setDefaultAccount } from "./accounts.ts";
6
+ import { claudeUsageAt } from "./usage.ts";
7
+
8
+ let t: string;
9
+ beforeEach(() => { t = mkdtempSync(join(tmpdir(), "kz-acct-")); process.env.KAIZEN_ACCOUNTS_HOME = t; });
10
+ afterEach(() => { delete process.env.KAIZEN_ACCOUNTS_HOME; rmSync(t, { recursive: true, force: true }); });
11
+ const add = (tool = "claude", name = "Work") => (addAccount(tool, name) as { id: string }).id;
12
+
13
+ test("no accounts: normal login, no env", () => {
14
+ expect(resolveAccount("claude", undefined, false)).toEqual({});
15
+ expect(resolveAccount("gemini", undefined, false)).toEqual({});
16
+ });
17
+ test("default, pick and normal login resolve; modes are private", () => {
18
+ const id = add();
19
+ setDefaultAccount("claude", "");
20
+ if (process.platform !== "win32") { // no POSIX modes there
21
+ expect(statSync(accountDir(id)).mode & 0o777).toBe(0o700);
22
+ expect(statSync(join(t, "accounts.json")).mode & 0o777).toBe(0o600);
23
+ }
24
+ expect(resolveAccount("claude", undefined, false)).toEqual({});
25
+ setDefaultAccount("claude", id);
26
+ expect(resolveAccount("claude", undefined, false)).toMatchObject({ dir: accountDir(id), envVar: "CLAUDE_CONFIG_DIR" });
27
+ expect(resolveAccount("claude", "", false)).toEqual({});
28
+ expect(resolveAccount("codex", undefined, false)).toEqual({});
29
+ });
30
+ test("missing, unknown, wrong-tool or Windows accounts refuse, with no fallback", () => {
31
+ const id = add();
32
+ setDefaultAccount("claude", id);
33
+ rmSync(accountDir(id), { recursive: true });
34
+ expect(resolveAccount("claude", undefined, false).error).toMatch(/missing/);
35
+ expect(resolveAccount("claude", "abcdefgh1234", false).error).toMatch(/no longer/);
36
+ expect(resolveAccount("codex", id, false).error).toMatch(/no longer/);
37
+ mkdirSync(accountDir(id));
38
+ expect(resolveAccount("claude", id, true).error).toMatch(/Windows/);
39
+ });
40
+ test("remove keeps the folder unless asked; ids can't leave the folder", () => {
41
+ const id = add();
42
+ setDefaultAccount("claude", id);
43
+ expect(removeAccount(id)).toBeNull();
44
+ expect(existsSync(accountDir(id))).toBe(true);
45
+ expect(readAccounts().default.claude).toBeUndefined();
46
+ const b = add("codex", "B");
47
+ expect(removeAccount(b, true)).toBeNull();
48
+ expect(existsSync(accountDir(b))).toBe(false);
49
+ for (const bad of ["../x", "..", "a/b", ""]) expect(removeAccount(bad, true)).toBe("unknown account");
50
+ expect(existsSync(t)).toBe(true);
51
+ });
52
+ test("names are validated", () => {
53
+ expect("error" in addAccount("gemini", "x")).toBe(true);
54
+ add();
55
+ expect("error" in addAccount("claude", "Work")).toBe(true);
56
+ });
57
+ test("kaizen's links follow into an account folder", () => {
58
+ const from = join(t, "from"), target = join(t, "skill-src");
59
+ mkdirSync(join(from, "skills"), { recursive: true });
60
+ mkdirSync(target);
61
+ symlinkSync(target, join(from, "skills", "kaizen"));
62
+ symlinkSync(target, join(from, "skills", "other"));
63
+ linkKaizen(join(t, "acct"), "claude", from);
64
+ expect(readlinkSync(join(t, "acct/skills/kaizen"))).toBe(realpathSync(target));
65
+ expect(existsSync(join(t, "acct/skills/other"))).toBe(false);
66
+ });
67
+ test("usage reads the account folder; a 401 says sign in, with no token in the answer", async () => {
68
+ const dir = join(t, "c");
69
+ mkdirSync(dir);
70
+ await Bun.write(join(dir, ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "tok-secret" } }));
71
+ let header = "";
72
+ const r = await claudeUsageAt(dir, (async (_: string, o: any) => { header = o.headers.authorization; return new Response("", { status: 401 }); }) as any);
73
+ expect(header).toContain("tok-secret");
74
+ expect(r).toMatchObject({ expired: true });
75
+ expect(JSON.stringify(r)).not.toContain("tok-secret");
76
+ expect(await claudeUsageAt(join(t, "none"))).toBeNull();
77
+ });
78
+
79
+ test.skipIf(process.platform === "win32")("a run resumes on its own account and finds its conversation there, in a child with a fake claude", async () => {
80
+ const dir = join(t, "proj"), id = add();
81
+ mkdirSync(join(dir, ".kaizen", "runs", "r1"), { recursive: true });
82
+ writeFileSync(join(dir, ".kaizen", "runs", "r1", "state.json"), "{}");
83
+ mkdirSync(join(t, "bin"));
84
+ writeFileSync(join(t, "bin", "claude"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
85
+ const go = (pick: string) => {
86
+ const script = `const { launchRun } = await import(${JSON.stringify(join(import.meta.dir, "state.ts"))});
87
+ const r = launchRun({ severity: null, where: null, text: "x", raw: "x" }, ${JSON.stringify(dir)}, "r1", { agent: "claude", cwd: ${JSON.stringify(dir)}, card: true, ...${pick} });
88
+ console.log(JSON.stringify(r)); process.exit(0);`;
89
+ return JSON.parse(Bun.spawnSync([process.execPath, "-e", script], { env: { ...process.env, PATH: `${join(t, "bin")}:${process.env.PATH}` } }).stdout.toString());
90
+ };
91
+ const first = go(`{ account: ${JSON.stringify(id)} }`);
92
+ if (!first.ok) return; // no pseudo-terminal here
93
+ const sid = first.cmd[first.cmd.indexOf("--session-id") + 1];
94
+ // macOS's temp path has two spellings; the launch keeps the one it was given.
95
+ for (const d of [dir, realpathSync(dir)]) {
96
+ const convo = join(accountDir(id), "projects", d.replace(/[^A-Za-z0-9]/g, "-"));
97
+ mkdirSync(convo, { recursive: true });
98
+ writeFileSync(join(convo, `${sid}.jsonl`), "{}\n");
99
+ }
100
+ // Every caller of firstSession, the board's Resume among them, with no env set here.
101
+ const { firstSession, manualCommand } = await import("./state.ts");
102
+ expect(firstSession(join(dir, ".kaizen"), "r1", "claude", realpathSync(dir))?.sessionId).toBe(sid);
103
+ expect(manualCommand("/p", "claude", "", [], "CLAUDE_CONFIG_DIR='/a b'")).toBe("cd '/p' && CLAUDE_CONFIG_DIR='/a b' claude");
104
+ const again = go("{}");
105
+ expect(again.cmd).toContain("--resume");
106
+ expect(again.cmd).toContain(sid);
107
+ rmSync(accountDir(id), { recursive: true });
108
+ expect(go("{}").why).toMatch(/missing/);
109
+ }, 20000);
110
+
111
+ test("no name: the tool's, numbered; rename after", () => {
112
+ addAccount("claude", "");
113
+ const b = (addAccount("claude", "") as { id: string }).id;
114
+ expect(readAccounts().accounts.map((x) => x.name)).toEqual(["Claude", "Claude 2"]);
115
+ expect(renameAccount(b, "Work")).toBeNull();
116
+ expect(renameAccount(b, "Claude")).toMatch(/taken/);
117
+ expect(renameAccount(b, "")).toBeTruthy();
118
+ expect(renameAccount("nope", "x")).toBe("unknown account");
119
+ });
120
+
121
+ test("signed in follows the tool's login file", () => {
122
+ const id = add("codex", "C");
123
+ expect(signedIn(accountDir(id), "codex")).toBe(false);
124
+ writeFileSync(join(accountDir(id), "auth.json"), "{}");
125
+ expect(signedIn(accountDir(id), "codex")).toBe(true);
126
+ });
@@ -0,0 +1,116 @@
1
+ // Named logins for Claude and Codex. Each has its own folder, which the tool itself fills:
2
+ // kaizen stores no token. ~/.kaizen/accounts.json lists them. No accounts means every launch
3
+ // stays on the normal login. A chosen account that can't be used refuses the launch: falling
4
+ // back would run the work, and bill it, under another account.
5
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ export type Tool = "claude" | "codex";
10
+ export type Account = { id: string; tool: Tool; name: string };
11
+ export type Accounts = { accounts: Account[]; default: Partial<Record<Tool, string>> };
12
+
13
+ export const ACCOUNT_VAR: Record<Tool, string> = { claude: "CLAUDE_CONFIG_DIR", codex: "CODEX_HOME" };
14
+ const root = () => process.env.KAIZEN_ACCOUNTS_HOME ?? join(homedir(), ".kaizen");
15
+ const file = () => join(root(), "accounts.json");
16
+ const validId = (id: string) => /^[a-z0-9]{8,32}$/.test(id);
17
+ export const accountDir = (id: string) => join(root(), "accounts", id);
18
+ const isTool = (t: unknown): t is Tool => t === "claude" || t === "codex";
19
+
20
+ export function readAccounts(): Accounts {
21
+ try {
22
+ const r = JSON.parse(readFileSync(file(), "utf8"));
23
+ const accounts = (Array.isArray(r.accounts) ? r.accounts : []).filter((a: any) => a && validId(a.id) && isTool(a.tool) && typeof a.name === "string");
24
+ return { accounts, default: r.default && typeof r.default === "object" ? r.default : {} };
25
+ } catch { return { accounts: [], default: {} }; }
26
+ }
27
+
28
+ function save(a: Accounts) {
29
+ mkdirSync(root(), { recursive: true });
30
+ const tmp = `${file()}.tmp`;
31
+ writeFileSync(tmp, JSON.stringify(a, null, 2) + "\n", { mode: 0o600 });
32
+ chmodSync(tmp, 0o600);
33
+ renameSync(tmp, file());
34
+ }
35
+
36
+ // Kaizen's own links, copied from the normal login's folder, so a run works under the account.
37
+ export function linkKaizen(dir: string, tool: Tool, from = join(homedir(), tool === "claude" ? ".claude" : ".codex")) {
38
+ for (const sub of tool === "claude" ? ["skills", "agents", "commands"] : ["skills"]) {
39
+ let names: string[] = [];
40
+ try { names = readdirSync(join(from, sub)).filter((n) => n.startsWith("kaizen")); } catch { continue; }
41
+ mkdirSync(join(dir, sub), { recursive: true });
42
+ for (const n of names) {
43
+ const to = join(dir, sub, n);
44
+ try { lstatSync(to); continue; } catch { /* free */ }
45
+ try { symlinkSync(realpathSync(join(from, sub, n)), to, process.platform === "win32" ? "junction" : undefined); } catch { /* the run says what's missing */ }
46
+ }
47
+ }
48
+ }
49
+
50
+ const cleanName = (v: unknown) => String(v ?? "").replace(/[\0-\x1f\x7f]/g, "").trim();
51
+
52
+ export function renameAccount(id: string, name: unknown): string | null {
53
+ const n = cleanName(name), a = readAccounts(), me = a.accounts.find((x) => x.id === id);
54
+ if (!me) return "unknown account";
55
+ if (!n || n.length > 60) return "Name it, in 60 characters or fewer";
56
+ if (a.accounts.some((x) => x !== me && x.tool === me.tool && x.name === n)) return "That name is taken";
57
+ me.name = n;
58
+ save(a);
59
+ return null;
60
+ }
61
+
62
+ export function addAccount(tool: unknown, name: unknown): { id: string } | { error: string } {
63
+ if (!isTool(tool)) return { error: "unknown tool" };
64
+ const a = readAccounts();
65
+ // No name: the tool's, numbered. It can be renamed after sign-in.
66
+ const base = tool === "claude" ? "Claude" : "Codex";
67
+ let auto = base;
68
+ for (let i = 2; a.accounts.some((x) => x.tool === tool && x.name === auto); i++) auto = `${base} ${i}`;
69
+ const n = cleanName(name) || auto;
70
+ if (n.length > 60) return { error: "Keep the name to 60 characters" };
71
+ if (a.accounts.some((x) => x.tool === tool && x.name === n)) return { error: "That name is taken" };
72
+ const id = crypto.randomUUID().replace(/-/g, "").slice(0, 16), dir = accountDir(id);
73
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
74
+ chmodSync(dir, 0o700);
75
+ linkKaizen(dir, tool);
76
+ a.accounts.push({ id, tool, name: n });
77
+ save(a);
78
+ return { id };
79
+ }
80
+
81
+ // The folder holds the login and that account's conversations, so it goes only when asked.
82
+ // Whether the tool has saved a login here. The file is only looked at, never read.
83
+ export const signedIn = (dir: string, tool: Tool) => existsSync(join(dir, tool === "claude" ? ".credentials.json" : "auth.json"));
84
+
85
+ export function removeAccount(id: string, deleteFolder = false): string | null {
86
+ const a = readAccounts();
87
+ if (!validId(id) || !a.accounts.some((x) => x.id === id)) return "unknown account";
88
+ a.accounts = a.accounts.filter((x) => x.id !== id);
89
+ for (const t of Object.keys(a.default) as Tool[]) if (a.default[t] === id) delete a.default[t];
90
+ save(a);
91
+ if (deleteFolder) rmSync(accountDir(id), { recursive: true, force: true });
92
+ return null;
93
+ }
94
+
95
+ export function setDefaultAccount(tool: unknown, id: string): string | null {
96
+ const a = readAccounts();
97
+ if (!isTool(tool)) return "unknown tool";
98
+ if (id && !a.accounts.some((x) => x.id === id && x.tool === tool)) return "unknown account";
99
+ if (id) a.default[tool] = id; else delete a.default[tool];
100
+ save(a);
101
+ return null;
102
+ }
103
+
104
+ // `wanted`: an id, "" for the normal login, undefined for the tool's default.
105
+ export type Resolved = { account?: Account; dir?: string; envVar?: string; error?: string };
106
+ export function resolveAccount(cmd: string, wanted?: string, win = process.platform === "win32"): Resolved {
107
+ if (!isTool(cmd) || wanted === "") return {};
108
+ const a = readAccounts(), id = wanted ?? a.default[cmd];
109
+ if (!id) return {};
110
+ const account = a.accounts.find((x) => x.id === id && x.tool === cmd);
111
+ if (!account) return { error: "That account no longer exists. Pick another in Settings → AI Provider Accounts." };
112
+ if (win) return { error: "Accounts aren't supported on Windows yet." };
113
+ const dir = accountDir(id);
114
+ if (!existsSync(dir)) return { error: `The folder for ${account.name} is missing.` };
115
+ return { account, dir, envVar: ACCOUNT_VAR[cmd] };
116
+ }
@@ -2,7 +2,7 @@
2
2
  // create a folder, branch off a base. Everything here is a pure check or an argv call,
3
3
  // so each refusal can be tested without a board. No shell string anywhere.
4
4
  import { appendFileSync, existsSync, lstatSync, readdirSync, readFileSync, rmSync } from "node:fs";
5
- import { basename, dirname, join, parse, resolve, sep } from "node:path";
5
+ import { isAbsolute, basename, dirname, join, parse, resolve, sep } from "node:path";
6
6
  import { canonPath, nativePath } from "./state.ts";
7
7
  import { run, type Run } from "./worktree.ts";
8
8
 
@@ -50,7 +50,9 @@ export function destDir(raw: unknown, home: string, known: string[] = [], projec
50
50
  const t = typeof raw === "string" ? raw.trim() : "";
51
51
  if (!t || t.length > 1000 || t.includes("\0")) return { error: "name a folder" };
52
52
  if (t.split(/[\\/]/).includes("..")) return { error: "a folder path cannot contain .." };
53
- const p = resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t));
53
+ // A relative name is under home: nativePath alone would resolve it against the working folder.
54
+ const full = t.startsWith("~") ? home + t.slice(1) : t;
55
+ const p = resolve(home, isAbsolute(full) || /^\/[a-zA-Z](\/|$)/.test(full) ? nativePath(full) : full);
54
56
  try { if (lstatSync(p).isSymbolicLink()) return { error: "that folder is a symbolic link; name the real folder" }; } catch { /* absent */ }
55
57
  const dir = existsSync(p) ? canonPath(p) : join(canonPath(dirname(p)), basename(p)), h = canonPath(home);
56
58
  if (parse(dir).root === dir || dir === h) return { error: "choose a folder of its own, not the root or your home" };
@@ -0,0 +1,127 @@
1
+ import { afterEach, beforeEach, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { agentEnabled, argsOf, commandOf, prefersBypass, publicPref, readPrefs, savePrefs, withEnv } from "./agent-prefs.ts";
6
+ import { awakeHolder, inhibitArgv, wantAwake } from "./keep-awake.ts";
7
+ import { agentChoices, detectDefaultAgent, launchPreview, launchRun, keepAwake } from "./state.ts";
8
+
9
+ let dir: string, file: string;
10
+ const known = ["claude", "codex", "cursor"];
11
+ beforeEach(() => {
12
+ dir = mkdtempSync(join(tmpdir(), "kz-prefs-"));
13
+ file = join(dir, "agents.json");
14
+ process.env.KAIZEN_AGENT_PREFS = file;
15
+ });
16
+ afterEach(() => {
17
+ delete process.env.KAIZEN_AGENT_PREFS;
18
+ rmSync(dir, { recursive: true, force: true });
19
+ });
20
+
21
+ test("no file: defaults, and launch parts stay as they were", () => {
22
+ const p = readPrefs(file);
23
+ expect(agentEnabled("claude", p)).toBe(true);
24
+ expect(commandOf("claude", p)).toBe("claude");
25
+ expect(argsOf("claude", p)).toEqual([]);
26
+ expect(prefersBypass("claude", p)).toBe(false);
27
+ expect(withEnv(["claude", "x"], "claude", p, false)).toEqual(["claude", "x"]);
28
+ expect(launchPreview(dir, "claude", p)).toBe("claude");
29
+ });
30
+
31
+ test("the file is private, and env values never reach the page's view", () => {
32
+ expect(savePrefs({ agent: "claude", envName: "TOKEN", envValue: "s3cret" }, known, file)).toEqual({ ok: true });
33
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); // no POSIX modes there
34
+ expect(JSON.stringify(publicPref("claude", readPrefs(file)))).not.toContain("s3cret");
35
+ expect(publicPref("claude", readPrefs(file)).env).toEqual(["TOKEN"]);
36
+ expect(launchPreview(dir, "claude", readPrefs(file))).not.toContain("s3cret");
37
+ expect(withEnv(["claude"], "claude", readPrefs(file), false)).toEqual(["env", "TOKEN=s3cret", "claude"]);
38
+ expect(savePrefs({ agent: "claude", envRemove: "TOKEN" }, known, file)).toEqual({ ok: true });
39
+ expect(publicPref("claude", readPrefs(file)).env).toEqual([]);
40
+ });
41
+
42
+ test("shell characters and dangerous names are refused, on save and on a hand-edited file", () => {
43
+ for (const command of ["claude; rm -rf /", "$(x)", "a b", "`x`", "-x"]) expect("error" in savePrefs({ agent: "claude", command }, known, file)).toBe(true);
44
+ for (const args of ["a;b", "$(x)", "'q'", "a|b"]) expect("error" in savePrefs({ agent: "claude", args }, known, file)).toBe(true);
45
+ for (const n of ["PATH", "LD_PRELOAD", "DYLD_X", "a b", "1A", "NODE_OPTIONS"]) expect("error" in savePrefs({ agent: "claude", envName: n, envValue: "1" }, known, file)).toBe(true);
46
+ expect("error" in savePrefs({ agent: "claude", envName: "A", envValue: "x\ny" }, known, file)).toBe(true);
47
+ expect("error" in savePrefs({ agent: "nope", enabled: false }, known, file)).toBe(true);
48
+ writeFileSync(file, JSON.stringify({ agents: { claude: { command: "x;y", args: ["$(z)", "--ok"], env: { PATH: "/x", OK: "1" } } } }));
49
+ const p = readPrefs(file);
50
+ expect(commandOf("claude", p)).toBe("claude");
51
+ expect(argsOf("claude", p)).toEqual(["--ok"]);
52
+ expect(Object.keys(p.agents.claude!.env!)).toEqual(["OK"]);
53
+ });
54
+
55
+ test("a metacharacter in an env value stays one argv entry", () => {
56
+ savePrefs({ agent: "claude", envName: "A", envValue: "$(touch x); `y` 'z'" }, known, file);
57
+ expect(withEnv(["claude"], "claude", readPrefs(file), false)[1]).toBe("A=$(touch x); `y` 'z'");
58
+ });
59
+
60
+ test("bypass comes only from the setting; one agent can differ", () => {
61
+ savePrefs({ permissions: "bypass" }, known, file);
62
+ expect(prefersBypass("codex", readPrefs(file))).toBe(true);
63
+ savePrefs({ agent: "codex", agentPermissions: "own" }, known, file);
64
+ expect(prefersBypass("codex", readPrefs(file))).toBe(false);
65
+ expect(launchPreview(dir, "claude", readPrefs(file))).toContain("--dangerously-skip-permissions");
66
+ });
67
+
68
+ test("a disabled agent is not offered, not picked, and refused when named", () => {
69
+ for (const a of known) savePrefs({ agent: a, enabled: false }, known, file);
70
+ const all = ["agy", "opencode", "gemini"];
71
+ for (const a of all) savePrefs({ agent: a, enabled: false }, [...known, ...all], file);
72
+ expect(agentChoices(dir).agents).toEqual([]);
73
+ expect(detectDefaultAgent(dir, "claude").note ?? "").toMatch(/turned off/);
74
+ const r = launchRun({ severity: null, where: null, text: "x", raw: "x" }, dir, undefined, { agent: "claude", cwd: dir });
75
+ expect(r.ok).toBe(false);
76
+ expect(r.why).toMatch(/turned off/);
77
+ });
78
+
79
+ test("keep awake: the holder follows the wanted state and stops", () => {
80
+ let kills = 0, starts = 0;
81
+ const h = awakeHolder(() => (starts++, { kill: () => kills++ }), ["x"]);
82
+ h.sync(wantAwake("auto", true)); h.sync(true);
83
+ expect([starts, h.held()]).toEqual([1, true]);
84
+ h.sync(wantAwake("auto", false));
85
+ expect([kills, h.held()]).toEqual([1, false]);
86
+ h.sync(wantAwake("on", false)); h.stop();
87
+ expect([kills, h.held()]).toEqual([2, false]);
88
+ h.sync(wantAwake("off", true));
89
+ expect(h.held()).toBe(false);
90
+ expect(inhibitArgv("linux", 7)).toContain("--pid=7");
91
+ expect(inhibitArgv("darwin", 7)).toEqual(["caffeinate", "-i", "-w", "7"]);
92
+ expect(inhibitArgv("win32")).toBeNull();
93
+ expect(keepAwake("agent:\n keep_awake: auto\n")).toBe("auto");
94
+ expect(keepAwake("")).toBe("off");
95
+ });
96
+
97
+ test("launch: nothing set keeps the line; bypass and overrides reach it and the session record", () => {
98
+ // A child with a fake claude: a real terminal in this process breaks the suite's other tests.
99
+ mkdirSync(join(dir, ".kaizen"));
100
+ mkdirSync(join(dir, "bin"));
101
+ writeFileSync(join(dir, "bin", "claude"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
102
+ const script = `const { launchRun } = await import(${JSON.stringify(join(import.meta.dir, "state.ts"))});
103
+ const r = launchRun({ severity: null, where: null, text: "x", raw: "x" }, ${JSON.stringify(dir)}, undefined, { agent: "claude", cwd: ${JSON.stringify(dir)}, card: true });
104
+ console.log(JSON.stringify(r)); process.exit(0);`;
105
+ const go = () => JSON.parse(Bun.spawnSync([process.execPath, "-e", script], { env: { ...process.env, PATH: `${join(dir, "bin")}:${process.env.PATH}` } }).stdout.toString());
106
+ const plain = go();
107
+ if (!plain.ok) return; // no pseudo-terminal here
108
+ expect(plain.cmd).not.toContain("--dangerously-skip-permissions");
109
+ expect(plain.cmd[0]).toEndWith("claude");
110
+ savePrefs({ permissions: "bypass" }, known, file);
111
+ savePrefs({ agent: "claude", args: "--verbose", envName: "A", envValue: "secret" }, known, file);
112
+ const r = go();
113
+ expect(r.cmd).toContain("--dangerously-skip-permissions");
114
+ expect(r.cmd).toContain("--verbose");
115
+ expect(JSON.stringify(r)).not.toContain("secret");
116
+ const recs = readdirSync(join(dir, ".kaizen", "sessions")).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(readFileSync(join(dir, ".kaizen", "sessions", f), "utf8")));
117
+ expect(recs.filter((x) => x.yolo).length).toBe(1);
118
+ }, 15000);
119
+
120
+ test("a blank value keeps a saved one; bypass flags are refused as arguments", () => {
121
+ savePrefs({ agent: "claude", envName: "A", envValue: "1" }, known, file);
122
+ savePrefs({ agent: "claude", envName: "A", envValue: "" }, known, file);
123
+ expect(readPrefs(file).agents.claude!.env).toEqual({ A: "1" });
124
+ for (const args of ["--dangerously-skip-permissions", "--yolo", "-y", "--auto"]) expect("error" in savePrefs({ agent: "claude", args }, known, file)).toBe(true);
125
+ writeFileSync(file, JSON.stringify({ agents: { claude: { args: ["--yolo", "--ok"] } } }));
126
+ expect(argsOf("claude", readPrefs(file))).toEqual(["--ok"]);
127
+ });
@@ -0,0 +1,106 @@
1
+ // How each agent starts, per user: ~/.kaizen/agents.json, never config.yml, which is
2
+ // committed and differs by project while a command path differs by machine. No file
3
+ // means every launch stays as it was. Values may be hand-edited, so reads check them too.
4
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+
8
+ export type Permissions = "all" | "own" | "bypass";
9
+ export type AgentPref = { enabled?: boolean; permissions?: Permissions; command?: string; args?: string[]; env?: Record<string, string> };
10
+ export type Prefs = { permissions: "own" | "bypass"; agents: Record<string, AgentPref> };
11
+ export type PrefPatch = { permissions?: unknown; agent?: unknown; enabled?: unknown; agentPermissions?: unknown; command?: unknown; args?: unknown; envName?: unknown; envValue?: unknown; envRemove?: unknown };
12
+
13
+ export const prefsFile = () => process.env.KAIZEN_AGENT_PREFS ?? join(homedir(), ".kaizen", "agents.json");
14
+
15
+ // The manual command joins these unquoted, so a shell-free argv is not enough.
16
+ const plainCommand = (s: string) => s.length <= 512 && /^[A-Za-z0-9_./\\:+@-]+$/.test(s) && !s.startsWith("-");
17
+ const plainArg = (s: string) => s.length <= 512 && /^[A-Za-z0-9_./\\:+@=,%-]+$/.test(s);
18
+ // Bypass has one road, the Permissions setting, which the card's mark follows.
19
+ // ponytail: known flags only; extend when an agent adds another spelling.
20
+ export const bypassArg = (s: string) => /^(--dangerously|--yolo$|--auto$|-y$|--full-auto$|--approval-mode|--permission-mode|--sandbox|--ask-for-approval|-a$)/.test(s);
21
+ const envName = (s: string) => /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(s) && !/^(PATH|HOME|SHELL|IFS|ENV|BASH_ENV|NODE_OPTIONS|LD_.*|DYLD_.*)$/i.test(s);
22
+ const envValue = (s: string) => s.length <= 8192 && !/[\0\r\n]/.test(s);
23
+
24
+ function clean(raw: any): Prefs {
25
+ const agents: Prefs["agents"] = {};
26
+ for (const [cmd, p] of Object.entries<any>(raw?.agents && typeof raw.agents === "object" ? raw.agents : {})) {
27
+ if (!p || typeof p !== "object") continue;
28
+ const a: AgentPref = {};
29
+ if (p.enabled === false) a.enabled = false;
30
+ if (p.permissions === "own" || p.permissions === "bypass") a.permissions = p.permissions;
31
+ if (typeof p.command === "string" && plainCommand(p.command)) a.command = p.command;
32
+ if (Array.isArray(p.args)) { const v = p.args.filter((x: unknown) => typeof x === "string" && plainArg(x) && !bypassArg(x)); if (v.length) a.args = v; }
33
+ if (p.env && typeof p.env === "object") {
34
+ const v = Object.fromEntries(Object.entries(p.env).filter(([k, x]) => envName(k) && typeof x === "string" && envValue(x))) as Record<string, string>;
35
+ if (Object.keys(v).length) a.env = v;
36
+ }
37
+ agents[cmd] = a;
38
+ }
39
+ return { permissions: raw?.permissions === "bypass" ? "bypass" : "own", agents };
40
+ }
41
+
42
+ export function readPrefs(file = prefsFile()): Prefs {
43
+ try { return clean(JSON.parse(readFileSync(file, "utf8"))); } catch { return clean(null); }
44
+ }
45
+
46
+ export const agentEnabled = (cmd: string, p = readPrefs()) => p.agents[cmd]?.enabled !== false;
47
+ export const commandOf = (cmd: string, p = readPrefs()) => p.agents[cmd]?.command ?? cmd;
48
+ export const argsOf = (cmd: string, p = readPrefs()) => p.agents[cmd]?.args ?? [];
49
+ export const prefersBypass = (cmd: string, p = readPrefs()) => {
50
+ const own = p.agents[cmd]?.permissions;
51
+ return own === "bypass" || (own !== "own" && p.permissions === "bypass");
52
+ };
53
+ // Through env, so a value is never read by a shell. Windows has no env(1): the page says so.
54
+ export const withEnv = (argv: string[], cmd: string, p = readPrefs(), win = process.platform === "win32") => {
55
+ const e = Object.entries(p.agents[cmd]?.env ?? {});
56
+ return e.length && !win ? ["env", ...e.map(([k, v]) => `${k}=${v}`), ...argv] : argv;
57
+ };
58
+
59
+ // What the page may see: an environment value never leaves this file.
60
+ export function publicPref(cmd: string, p = readPrefs()) {
61
+ const a = p.agents[cmd] ?? {};
62
+ return { enabled: a.enabled !== false, permissions: a.permissions ?? "all", command: a.command ?? "", args: (a.args ?? []).join(" "), env: Object.keys(a.env ?? {}) };
63
+ }
64
+
65
+ // Applies one change; the error never quotes an environment value.
66
+ export function savePrefs(patch: PrefPatch, known: string[], file = prefsFile()): { ok: true } | { error: string } {
67
+ const p = readPrefs(file);
68
+ if (patch.permissions !== undefined) {
69
+ if (patch.permissions !== "own" && patch.permissions !== "bypass") return { error: "unknown permission mode" };
70
+ p.permissions = patch.permissions;
71
+ }
72
+ if (patch.agent !== undefined) {
73
+ const cmd = String(patch.agent);
74
+ if (!known.includes(cmd)) return { error: "unknown agent" };
75
+ const a = (p.agents[cmd] ??= {});
76
+ if (patch.enabled !== undefined) { if (patch.enabled) delete a.enabled; else a.enabled = false; }
77
+ if (patch.agentPermissions !== undefined) {
78
+ if (patch.agentPermissions === "all") delete a.permissions;
79
+ else if (patch.agentPermissions === "own" || patch.agentPermissions === "bypass") a.permissions = patch.agentPermissions;
80
+ else return { error: "unknown permission mode" };
81
+ }
82
+ if (patch.command !== undefined) {
83
+ const c = String(patch.command).trim();
84
+ if (c && !plainCommand(c)) return { error: "A command is one program name or path, with no spaces or shell characters" };
85
+ if (c) a.command = c; else delete a.command;
86
+ }
87
+ if (patch.args !== undefined) {
88
+ const v = String(patch.args).trim().split(/\s+/).filter(Boolean);
89
+ if (!v.every(plainArg)) return { error: "Arguments can't hold quotes or shell characters" };
90
+ if (v.some(bypassArg)) return { error: "Use Permissions for bypass, so the card can show it" };
91
+ if (v.length) a.args = v; else delete a.args;
92
+ }
93
+ if (patch.envName !== undefined) {
94
+ const k = String(patch.envName), v = String(patch.envValue ?? "");
95
+ if (!envName(k)) return { error: "That variable name isn't allowed" };
96
+ if (!envValue(v)) return { error: "An environment value can't hold line breaks" };
97
+ // Blank keeps a saved value.
98
+ if (v || a.env?.[k] === undefined) (a.env ??= {})[k] = v;
99
+ }
100
+ if (patch.envRemove !== undefined && a.env) delete a.env[String(patch.envRemove)];
101
+ }
102
+ mkdirSync(dirname(file), { recursive: true });
103
+ writeFileSync(file, JSON.stringify(p, null, 2) + "\n", { mode: 0o600 });
104
+ chmodSync(file, 0o600);
105
+ return { ok: true };
106
+ }