kaizen-agent 1.87.3 → 1.87.4

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 (57) hide show
  1. package/cli/activity.ts +86 -0
  2. package/cli/add-project.ts +64 -1
  3. package/cli/auto-update.ts +33 -0
  4. package/cli/chat.ts +88 -13
  5. package/cli/install.ts +65 -36
  6. package/cli/look.ts +1 -0
  7. package/cli/onboarding.ts +9 -4
  8. package/cli/pty.ts +27 -12
  9. package/cli/release.ts +13 -1
  10. package/cli/settings.ts +39 -7
  11. package/cli/state.ts +54 -1
  12. package/cli/task-service.ts +8 -3
  13. package/cli/usage.ts +15 -2
  14. package/cli/web.ts +88 -41
  15. package/cli/whats-new.json +38 -0
  16. package/cli/whats-new.ts +43 -0
  17. package/cli/workers.ts +2 -2
  18. package/package.json +1 -1
  19. package/skills/kaizen/config.default.yml +3 -0
  20. package/skills/kaizen/spec.md +6 -0
  21. package/skills/kaizen-explore/SKILL.md +7 -0
  22. package/web/components/home/index.ts +1 -0
  23. package/web/components/home/onboarding-dialog.tsx +44 -7
  24. package/web/components/home/works-flow.tsx +119 -0
  25. package/web/components/project/add-project-dialog.tsx +1 -1
  26. package/web/components/rail/rail-list.tsx +8 -6
  27. package/web/components/run/doc-body.tsx +43 -0
  28. package/web/components/settings/agent-rows.tsx +15 -11
  29. package/web/components/settings/browser-row.tsx +1 -1
  30. package/web/components/settings/setting-row.tsx +2 -1
  31. package/web/components/settings/skill-card.tsx +32 -2
  32. package/web/components/settings/update-bar.tsx +53 -35
  33. package/web/components/settings/whats-new-card.tsx +70 -0
  34. package/web/components/shell/rail.tsx +8 -4
  35. package/web/dist/annotate.js +1 -1
  36. package/web/dist/board.css +3 -3
  37. package/web/dist/board.js +83 -58
  38. package/web/dist/boot.js +1 -1
  39. package/web/dist/notebook.css +2 -2
  40. package/web/dist/notebook.js +27 -27
  41. package/web/dist/popup.css +1 -1
  42. package/web/dist/popup.js +1 -1
  43. package/web/dist/term.js +1 -1
  44. package/web/dist/ui.css +2 -2
  45. package/web/dist/video.js +1 -1
  46. package/web/lib/footer/footer-rules.ts +8 -2
  47. package/web/lib/footer/footer-store.ts +2 -2
  48. package/web/lib/home/onboarding.ts +63 -17
  49. package/web/lib/project/add-project.ts +6 -0
  50. package/web/lib/run/panel-derive.ts +1 -1
  51. package/web/lib/run/panel-store.ts +1 -0
  52. package/web/lib/settings/index.ts +1 -0
  53. package/web/lib/settings/settings.ts +6 -1
  54. package/web/lib/settings/whats-new.ts +36 -0
  55. package/web/pages/board/App.tsx +2 -1
  56. package/web/pages/task-page.tsx +17 -4
  57. package/web/ui/legacy/board.css +1 -1
package/cli/pty.ts CHANGED
@@ -15,7 +15,7 @@ const killWinTree = (pid: number) => {
15
15
  try { Bun.spawnSync([join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe"), "/T", "/F", "/PID", String(pid)], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000, windowsHide: true }); } catch { /* already gone */ }
16
16
  };
17
17
 
18
- type Pty = { lastOut?: number; proc: Bun.Subprocess; out: string[]; size: number; listeners: Set<(d: string | null) => void>; exit: number | null; asking: boolean; busy: boolean; quiet?: Timer; total: number; since: number; onChange?: () => void; tmux?: string; last: string; lastAt: number; typedAt: number; born: number; draft?: boolean };
18
+ type Pty = { lastOut?: number; proc: Bun.Subprocess; out: string[]; size: number; listeners: Set<(d: string | null) => void>; exit: number | null; asking: boolean; busy: boolean; quiet?: Timer; total: number; since: number; askedSince: number; askedAt: number; askCheck: number; onChange?: () => void; tmux?: string; last: string; lastAt: number; typedAt: number; born: number; draft?: boolean };
19
19
 
20
20
  // What a page attaching late gets replayed. A full-screen tool redraws often, so the
21
21
  // tail of its output is enough to rebuild the screen.
@@ -53,7 +53,8 @@ const grab = (p: Pty, text: string, every: number) => {
53
53
 
54
54
  // A question the agent stopped on: Claude Code's and Codex's approval and choice prompts.
55
55
  // ponytail: screen-text heuristic, misses a prompt worded otherwise; read agent hooks if that bites.
56
- const ASK = /Would you like to|Do you want to|[❯›>] ?1\. |Type something|\(y\/n\)|\[y\/N\]|Press enter to/i;
56
+ // `[❯›>]\s*1\.`: a menu's first option, with any number of spaces where colour codes were (Claude Code draws "❯ \x1b[..m1. Yes"). "Allow this" is Claude's read-outside-the-folder question.
57
+ const ASK = /Would you like to|Do you want to|Allow this|[❯›>]\s*1\. |Type something|\(y\/n\)|\[y\/N\]|Press enter to/i;
57
58
  // Escape sequences out; a cursor move becomes a space so words drawn apart stay apart.
58
59
  // The agent's working line (Claude Code's "✻ Thinking… (12s · ↓ 1.2k tokens)", Codex's
59
60
  // "Working (12s • esc to interrupt)", Gemini's "(esc to cancel, 12s)", opencode's "esc interrupt")
@@ -70,6 +71,8 @@ export const asking = (screen: string) => {
70
71
  };
71
72
  // How long output stays still before the screen is read for a question.
72
73
  export const QUIET_MS = 700;
74
+ // How often the screen is read for a question while output keeps arriving.
75
+ export const ASK_EVERY = 400;
73
76
  // The latest meaningful line of some terminal output, for the sidebar card: escape sequences, box
74
77
  // drawing, spinners and the TUI's own footer lines out. "" when nothing readable is left.
75
78
  // ponytail: screen-text heuristic over raw chunks; a TUI that repaints oddly shows an older line.
@@ -112,13 +115,25 @@ export const ptySupported = WIN || typeof (Bun as any).Terminal === "function";
112
115
  // outlives the board; null where tmux cannot be used, and the agent runs plainly.
113
116
  export function startPty(key: string, cmd: string[], cwd: string, pidFile?: string, onChange?: () => void, opts: { seed?: string; tmux?: string; attach?: boolean; env?: Record<string, string> } = {}): number {
114
117
  const dec = new TextDecoder();
115
- const p: Pty = { proc: null as unknown as Bun.Subprocess, out: opts.seed ? [opts.seed] : [], size: opts.seed?.length ?? 0, listeners: new Set(), exit: null, asking: false, busy: false, total: 0, since: 0, onChange, last: "", lastAt: 0, typedAt: 0, born: Date.now() };
118
+ const p: Pty = { proc: null as unknown as Bun.Subprocess, out: opts.seed ? [opts.seed] : [], size: opts.seed?.length ?? 0, listeners: new Set(), exit: null, asking: false, busy: false, askedSince: -1, askedAt: 0, askCheck: 0, total: 0, since: 0, onChange, last: "", lastAt: 0, typedAt: 0, born: Date.now() };
116
119
  // attach: the session already runs (kept from a board before this one); only a client is started.
117
120
  if (opts.tmux && tmuxOk()) cmd = opts.attach ? attachCmd(opts.tmux) : tmuxCmd(opts.tmux, cmd);
118
121
  const flag = (v: boolean) => { if (p.asking !== v) { p.asking = v; onChange?.(); } };
119
122
  // busy: the agent's working line (WORK) drawn in the last QUIET_MS. A working agent redraws it many
120
123
  // times a second; other output (a status-line refresh, a repaint on resize or focus) is not work.
121
124
  const work = (v: boolean) => { if (p.busy !== v) { p.busy = v; onChange?.(); } };
125
+ // Is the agent waiting on the user? Read the screen's tail for a question. A question stays open while its screen keeps repainting
126
+ // under it (Claude Code's status line animates every ~600 ms, so output is never quiet) and nothing was typed: it ends when a key is
127
+ // typed (writePty clears it), the agent works again (WORK, in push) or exits.
128
+ const check = () => {
129
+ const tail = p.out.slice(-64).join("").slice(-8192);
130
+ grab(p, tail.slice(-4096), 0);
131
+ // Only what came after the user's last keystroke: a question already answered may still be in the tail.
132
+ const n = Math.min(8192, p.total - p.since);
133
+ const q = p.exit === null && n > 0 && asking(tail.slice(-n));
134
+ if (q && !p.asking) { p.askedSince = p.since; p.askedAt = Date.now(); }
135
+ flag(q || (p.asking && p.exit === null && p.since === p.askedSince));
136
+ };
122
137
  const push = (d: string) => {
123
138
  p.out.push(d);
124
139
  p.lastOut = Date.now();
@@ -126,17 +141,17 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
126
141
  p.total += d.length;
127
142
  while (p.size > CAP && p.out.length > 1) p.size -= p.out.shift()!.length;
128
143
  for (const f of p.listeners) f(d);
129
- if (WORKING.test(d)) work(p.exit === null);
144
+ if (WORKING.test(d)) {
145
+ work(p.exit === null);
146
+ // A working line drawn well after the question was raised: the question was answered some other way.
147
+ if (p.asking && Date.now() - p.askedAt > 400) flag(false);
148
+ }
130
149
  grab(p, d, 1000);
150
+ // Not only when output goes quiet: look every ASK_EVERY while it flows.
151
+ const now = Date.now();
152
+ if (now - p.askCheck >= ASK_EVERY) { p.askCheck = now; check(); }
131
153
  clearTimeout(p.quiet);
132
- p.quiet = setTimeout(() => {
133
- work(false);
134
- const tail = p.out.slice(-8).join("").slice(-4096);
135
- grab(p, tail, 0);
136
- // Only what came after the user's last keystroke: a question already answered may still be in the tail.
137
- const n = Math.min(4096, p.total - p.since);
138
- flag(p.exit === null && n > 0 && asking(tail.slice(-n)));
139
- }, QUIET_MS);
154
+ p.quiet = setTimeout(() => { work(false); check(); }, QUIET_MS);
140
155
  };
141
156
  if (WIN) {
142
157
  const ps = winPs();
package/cli/release.ts CHANGED
@@ -32,6 +32,9 @@ export function summaryOf(subjects: string[]) {
32
32
  if (import.meta.main) {
33
33
  const args = process.argv.slice(2);
34
34
  const forced = ["patch", "minor", "major"].includes(args[0]) ? args.shift() : null;
35
+ // `--no-notes`: publish without a What's New entry for this version (the card then shows nothing for it).
36
+ const noNotes = args.includes("--no-notes");
37
+ if (noNotes) args.splice(args.indexOf("--no-notes"), 1);
35
38
  const pkg = JSON.parse(readFileSync("package.json", "utf8"));
36
39
  const tagged = (v: string) => sh(["git", "tag", "-l", `v${v}`]) !== "";
37
40
  const head = sh(["git", "log", "-1", "--format=%s"]);
@@ -39,7 +42,9 @@ if (import.meta.main) {
39
42
  console.error("release: commit or drop your changes first");
40
43
  process.exit(1);
41
44
  }
42
- if (head.startsWith(`Release ${pkg.version}:`) && !tagged(pkg.version) && !forced) {
45
+ // An interrupted release leaves its bump commit untagged; later commits on top of it do not make it a new release.
46
+ const bumped = () => { try { return sh(["git", "log", "--format=%s", `${sh(["git", "describe", "--tags", "--abbrev=0"])}..HEAD`]).split("\n").some((m) => m.startsWith(`Release ${pkg.version}:`)); } catch { return head.startsWith(`Release ${pkg.version}:`); } };
47
+ if (bumped() && !tagged(pkg.version) && !forced) {
43
48
  console.log(`release: reusing the unpublished bump commit for ${pkg.version}`);
44
49
  } else {
45
50
  const last = sh(["git", "describe", "--tags", "--abbrev=0"]);
@@ -50,6 +55,13 @@ if (import.meta.main) {
50
55
  }
51
56
  const level = forced ?? levelOf(log);
52
57
  const v = nextVersion(pkg.version, level);
58
+ // What's New (cli/whats-new.json) is written by hand: a version with no entry shows people nothing after they update, so the release
59
+ // stops here, before anything is changed, unless it is told it is fine.
60
+ const { hasEntry } = await import("./whats-new.ts");
61
+ if (!hasEntry(v) && !noNotes) {
62
+ console.error(`release: cli/whats-new.json has no entry for ${v}. Add one (highlights and fixes, newest first) and commit it, or run again with --no-notes.`);
63
+ process.exit(1);
64
+ }
53
65
  const summary = args.join(" ") || summaryOf(sh(["git", "log", "--reverse", "--format=%s", `${last}..HEAD`]).split("\n")) || "maintenance";
54
66
  writeFileSync("package.json", readFileSync("package.json", "utf8").replace(`"version": "${pkg.version}"`, `"version": "${v}"`));
55
67
  const note = ".kaizen/notes/Project/Release and testing.md";
package/cli/settings.ts CHANGED
@@ -12,7 +12,8 @@ import { status as chatgptStatus } from "./chatgpt.ts";
12
12
  // `when`: the row only has an effect while that other key holds that value; both
13
13
  // settings screens dim it otherwise, and it stays editable (`/kaizen full` overrides
14
14
  // the runner for one run, so a subagent model still matters under `runner: lite`).
15
- type Setting = { key: string; label: string; group: string; values: string[]; help: string; text?: boolean; folder?: boolean; when?: [string, string] };
15
+ // labels: what an option is called on screen; the value stored in config.yml is the key (see PLAIN below).
16
+ type Setting = { key: string; label: string; group: string; values: string[]; help: string; text?: boolean; folder?: boolean; when?: [string, string]; labels?: Record<string, string> };
16
17
 
17
18
  export type PresetName = "low" | "medium" | "ultra";
18
19
 
@@ -23,7 +24,7 @@ export const PRESETS: Record<PresetName, {
23
24
  }> = {
24
25
  low: {
25
26
  label: "Low",
26
- hint: "inline & manual — lite runner, inline builder, manual approvals, no auto-fix",
27
+ hint: "you approve every step — one session, cheapest, you approve the plan and the result",
27
28
  settings: {
28
29
  mode: "approve",
29
30
  runner: "lite",
@@ -41,7 +42,7 @@ export const PRESETS: Record<PresetName, {
41
42
  },
42
43
  medium: {
43
44
  label: "Medium",
44
- hint: "balanced (recommended) — full runner, subagents, plan approval, auto-fix all findings",
45
+ hint: "balanced (recommended) — separate agents, you approve the plan, problems found are fixed for you",
45
46
  settings: {
46
47
  mode: "approve",
47
48
  runner: "full",
@@ -58,7 +59,7 @@ export const PRESETS: Record<PresetName, {
58
59
  },
59
60
  ultra: {
60
61
  label: "Ultra",
61
- hint: "autonomous — full runner, subagents, auto mode, auto-fix all findings (up to 4 rounds)",
62
+ hint: "hands-off — runs by itself, fixes problems itself (up to 4 rounds) and saves the work in git",
62
63
  settings: {
63
64
  mode: "auto",
64
65
  runner: "full",
@@ -137,7 +138,7 @@ const SETTINGS: Setting[] = [
137
138
  { key: "orchestration.max_workers", label: "Max workers per run", group: "Orchestration", values: ["1", "2", "3", "4", "5", "6"], help: "Total per run", when: ["orchestration.enabled", "true"] },
138
139
  { key: "orchestration.permissions", label: "Worker permissions", group: "Orchestration", values: ["own", "bypass"], help: "own: each agent's own prompts. Bypass skips every prompt in every worker", when: ["orchestration.enabled", "true"] },
139
140
  // One per tool that takes a model flag; a run freezes its own agent's. Empty: the run's own model.
140
- ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `agent.model.${a.cmd}`, label: `Model: ${a.name}`, group: "Agents", values: [], text: true, help: a.cmd === "claude" ? "The session kaizen launches, and every stage subagent left on inherit. Empty: its own default" : "The tool's own model name, for every stage: it runs them in one session. Empty: its own default" })),
141
+ ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `agent.model.${a.cmd}`, label: `Model: ${a.name}`, group: "Agents", values: [], text: true, help: a.cmd === "claude" ? "The session kaizen launches, and every stage agent left on Same as main. Empty: its own default" : "The tool's own model name, for every stage: it runs them in one session. Empty: its own default" })),
141
142
  ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `agent.handoff_model.${a.cmd}`, label: `Handoff model: ${a.name}`, group: "Agents", values: [], text: true, help: "The second agent a worktree run hands off to. Empty: the run's own model" })),
142
143
  ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `orchestration.worker_model.${a.cmd}`, label: `Worker model: ${a.name}`, group: "Orchestration", values: [], text: true, help: "The tool's own model name. Empty: the run's own model", when: ["orchestration.enabled", "true"] })),
143
144
  { key: "review.write_memory", label: "Remember lessons", group: "Project", values: ["true", "false"], help: "" },
@@ -148,11 +149,41 @@ const SETTINGS: Setting[] = [
148
149
  { key: "sources.agent", label: "Who picks social posts", group: "Board", values: ["ask", "chatgpt", "agent"], help: "X, TikTok, Instagram, Threads" },
149
150
  { key: "sources.model", label: "ChatGPT model for the icebox", group: "Board", values: [], text: true, help: "Gathering social posts, sorting captures, drafting tasks. Empty: plan default" },
150
151
  { key: "sources.effort", label: "ChatGPT effort for the icebox", group: "Board", values: ["low", "medium", "high"], help: "Gathering, sorting and task drafts" },
152
+ { key: "board.auto_update", label: "Update automatically", group: "Board", values: ["false", "true"], help: "When a newer version is out, no terminal is running and no board page is open, kaizen updates itself and restarts. Off by default." },
151
153
  { key: "board.projects_dir", label: "Projects folder", group: "Board", values: [], text: true, folder: true, help: "Empty: known projects only" },
152
154
  { key: "board.video_dir", label: "Video library folder", group: "Board", values: [], text: true, folder: true, help: "Empty: ~/.kaizen" },
153
155
  { key: "board.chat_hotkey", label: "Popup chat hotkey", group: "Board", values: [], text: true, help: "Hyprland, e.g. SUPER + ALT + SPACE. Empty: none" },
154
156
  ];
155
157
 
158
+ // Plain option names and hints, applied to the rows above: they change what is shown, never what config.yml holds, which every
159
+ // older install, the skills and the terminal screen read. A hint names the option as the screen shows it, not the stored word.
160
+ const cap = (vs: string[]) => Object.fromEntries(vs.map((v) => [v, v[0]!.toUpperCase() + v.slice(1)]));
161
+ const SAME_MAIN = { inherit: "Same as main" }, SAME_ABOVE = { default: "Same as above" }, MODELS = cap(["opus", "sonnet", "haiku"]);
162
+ const PLAIN: Record<string, { labels?: Record<string, string>; help?: string }> = {
163
+ preset: { help: "Low: you approve every step, one session, cheapest. Medium: separate agents, you approve the plan. Ultra: runs by itself and saves the work in git. Custom: you changed a setting." },
164
+ mode: { labels: { approve: "Ask me", auto: "Automatic", "plan-only": "Plan only", "review-only": "Review only" }, help: "Ask me: it stops where you approve. Automatic: runs start to finish. Plan only: writes the plan and stops. Review only: checks work that already exists." },
165
+ "approvals.review": { help: "Also for automatic runs: a run that changed files waits for your approval, unless \"Auto runs skip final approval\" is on" },
166
+ auto_accept: { help: "On: an automatic run that changed files finishes without waiting for your approval, and is marked auto-accepted" },
167
+ runner: { labels: { full: "Separate agents", lite: "One session" }, help: "Separate agents: a different agent plans, builds and reviews, so the reviewer starts fresh. One session: the same session does every stage, cheaper." },
168
+ "build.executor": { labels: { subagent: "Own agent", inline: "This session", ask: "Ask me" }, help: "The code is written by its own agent, by this session, or you choose when you approve the plan." },
169
+ "review.executor": { labels: { inline: "This session", subagent: "Fresh agent", ask: "Ask me" }, help: "Who checks the work when everything runs in one session: this session, a fresh agent that did not see the work, or you choose before the review." },
170
+ "git.worktree_per_run": { labels: { ask: "Ask me", true: "Yes", false: "No" }, help: "Yes: each run works in its own branch and folder. No: in the project folder. Ask me: choose each time." },
171
+ "subagents.model": { labels: { ...SAME_MAIN, ...MODELS }, help: "The model for Claude Code's stage agents: planner, builder, reviewer" },
172
+ "subagents.effort": { labels: { ...SAME_MAIN, ...cap(["low", "medium", "high"]) } },
173
+ "subagents.planner": { labels: { ...SAME_ABOVE, ...MODELS }, help: "Same as above uses the Stage model" },
174
+ "subagents.builder": { labels: { ...SAME_ABOVE, ...MODELS }, help: "Also runs the fix rounds. Same as above uses the Stage model" },
175
+ "subagents.reviewer": { labels: { ...SAME_ABOVE, ...MODELS }, help: "Also runs the rechecks. Same as above uses the Stage model" },
176
+ "auto_fix.min_severity": { labels: cap(["critical", "high", "medium", "low"]) },
177
+ "auto_guard.stop_on": { labels: cap(["critical", "high", "medium", "low", "off"]) },
178
+ "orchestration.permissions": { labels: { own: "Normal prompts", bypass: "Skip all prompts" }, help: "Normal prompts: each agent asks as it usually does. Skip all prompts: no worker ever asks, so be sure." },
179
+ "agent.keep_awake": { labels: cap(["off", "auto", "on"]), help: "Auto: while kaizen runs agents. On: while kaizen is open. Linux and macOS" },
180
+ "sources.every": { labels: { off: "Off", "1h": "1h", "6h": "6h", "24h": "24h" } },
181
+ "sources.effort": { labels: cap(["low", "medium", "high"]) },
182
+ };
183
+ for (const s of SETTINGS) Object.assign(s, PLAIN[s.key] ?? {});
184
+ // An option as the screen shows it.
185
+ export const optionLabel = (s: Pick<Setting, "labels">, v: string) => s.labels?.[v] ?? v;
186
+
156
187
  // The same rows and the same write the TUI uses, for `kaizen web`'s settings panel:
157
188
  // one place decides what a setting is called, what it may be, and how it is saved.
158
189
  // `project`: undefined resolves from the cwd as the TUI does; null is All projects
@@ -182,7 +213,8 @@ export function listSettings(repoRoot: string, project?: string | null) {
182
213
  // Why a row has no effect right now, or "" while it has one: its `when` is not met.
183
214
  function idle(s: Setting, valueOf: (key: string) => string | null) {
184
215
  if (!s.when || valueOf(s.when[0]) === s.when[1]) return "";
185
- return `No effect unless ${SETTINGS.find((x) => x.key === s.when![0])!.label} is ${s.when[1] === "true" ? "on" : s.when[1]}`;
216
+ const w = SETTINGS.find((x) => x.key === s.when![0])!;
217
+ return `No effect unless ${w.label} is ${s.when[1] === "true" ? "on" : optionLabel(w, s.when[1])}`;
186
218
  }
187
219
 
188
220
  export function setSetting(repoRoot: string, key: string, value: string, project?: string | null) {
@@ -284,7 +316,7 @@ export async function settings(repoRoot: string, standalone = true) {
284
316
  const at = s.values.indexOf(v);
285
317
  return at < 0 ? v : "▮".repeat(at + 1) + "▯".repeat(s.values.length - at - 1) + " " + v;
286
318
  }
287
- return v;
319
+ return optionLabel(s, v);
288
320
  };
289
321
  const valueOf = (k: string) => {
290
322
  const d = SETTINGS.find((x) => x.key === k)!;
package/cli/state.ts CHANGED
@@ -10,6 +10,7 @@ import { join, dirname, sep, win32, posix } from "node:path";
10
10
  import { homedir, arch, cpus, release, totalmem, version as osVersion } from "node:os";
11
11
  import { startPty, ptySupported, killTmux, tmuxName } from "./pty.ts";
12
12
  import { codeDir, projectFromWorktree, wsOf } from "./worktree.ts";
13
+ import { activityMtime } from "./activity.ts";
13
14
 
14
15
  // The real path: process.cwd() is always physical, so a raw $HOME that crosses a
15
16
  // symlink (/home -> var/home) would never compare equal to it.
@@ -96,6 +97,52 @@ export const YOLO_FLAGS: Record<string, string[]> = {
96
97
  codex: ["--dangerously-bypass-approvals-and-sandbox"], gemini: ["--yolo"], opencode: ["--auto"],
97
98
  };
98
99
 
100
+ // The folder that holds kaizen's skills as Claude Code reads them: the real path of the global `kaizen` skill link, one level up
101
+ // (the clone's `skills/`). null when kaizen is not linked there. Only this folder is added to a launch, not the home folder.
102
+ export function skillsReadDir(home = homedir()): string | null {
103
+ try { return dirname(realpathSync(join(home, ".claude", "skills", "kaizen"))); } catch { return null; }
104
+ }
105
+
106
+ // What a bypass (Yolo) launch of `cmd` passes: its skip-everything flag, and for Claude Code also the acceptance of its own first-run
107
+ // "Bypass Permissions mode" warning (No, exit is its default), which a board user would never see. The user chose Yolo here, so the launch
108
+ // accepts it from a settings file for this launch only, not by editing the user's own Claude settings. Every place that starts an agent in
109
+ // bypass (a run, a worker, a board terminal) uses this.
110
+ export function bypassFlags(cmd: string): string[] {
111
+ const accepted = cmd === "claude" ? bypassAcceptedFile() : null;
112
+ return [...(YOLO_FLAGS[cmd] ?? []), ...(accepted ? ["--settings", accepted] : [])];
113
+ }
114
+
115
+ // A settings file that only says the bypass-mode warning is accepted, for `claude --settings` on a Yolo launch. Lives in kaizen's own
116
+ // folder; null if it cannot be written (Claude then asks, as before).
117
+ export function bypassAcceptedFile(home = homedir()): string | null {
118
+ try {
119
+ const f = join(home, ".kaizen", "claude-bypass.json");
120
+ if (!existsSync(f)) { mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, JSON.stringify({ skipDangerousModePermissionPrompt: true }) + "\n"); }
121
+ return f;
122
+ } catch { return null; }
123
+ }
124
+
125
+ // The settings file for a run launch of Claude Code: the hooks that report every tool call to cli/activity.ts (live build activity on the
126
+ // board), and for a Yolo launch also the acceptance of the bypass-mode warning. Claude takes one --settings, so both ride in one file.
127
+ // Written when missing or when its text changed (a moved checkout, another bun). null if it cannot be written: the run then starts
128
+ // without the feed, as before. ponytail: the command is a POSIX-quoted line; Windows hook shells may need another form.
129
+ export function runHooksFile(yolo: boolean, home = homedir()): string | null {
130
+ try {
131
+ const cmd = `${shq(process.execPath)} ${shq(join(import.meta.dir, "activity.ts"))}`;
132
+ const hook = (matcher: string) => [{ matcher, hooks: [{ type: "command", command: cmd, timeout: 5 }] }];
133
+ const text = JSON.stringify({ hooks: { PreToolUse: hook("*"), PostToolUse: hook("Bash") }, ...(yolo ? { skipDangerousModePermissionPrompt: true } : {}) }) + "\n";
134
+ const f = join(home, ".kaizen", yolo ? "claude-run-hooks-bypass.json" : "claude-run-hooks.json");
135
+ if (!existsSync(f) || readFileSync(f, "utf8") !== text) { mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, text); }
136
+ return f;
137
+ } catch { return null; }
138
+ }
139
+ // What a run launch passes for its settings: Claude gets the hooks file (bypass flags without their own --settings when Yolo).
140
+ export function runSettingsFlags(cmd: string, yolo: boolean, home = homedir()): string[] {
141
+ if (cmd !== "claude") return yolo ? bypassFlags(cmd) : [];
142
+ const f = runHooksFile(yolo, home);
143
+ return f ? [...(yolo ? YOLO_FLAGS[cmd] ?? [] : []), "--settings", f] : yolo ? bypassFlags(cmd) : [];
144
+ }
145
+
99
146
  // How each tool takes the opening prompt and stays interactive. agy refuses a bare
100
147
  // argument and exits; opencode reads one as the project folder to open.
101
148
  const PROMPT_FLAGS: Record<string, string[]> = { agy: ["-i"], opencode: ["--prompt"] };
@@ -511,6 +558,8 @@ export function readRuns(state: string): Run[] {
511
558
  let moved = 0;
512
559
  try { moved = statSync(file).mtimeMs; } catch { /* vanished mid-read */ }
513
560
  try { moved = Math.max(moved, statSync(join(dir, id, "progress.md")).mtimeMs); } catch { /* no progress kept */ }
561
+ // And the agent's own tool calls (cli/activity.ts): the surest sign that it is working.
562
+ moved = Math.max(moved, activityMtime(state, s.session));
514
563
  // Done without the user's acceptance is not done: every reader sees it waiting on approval.
515
564
  const unapproved = s.stage === "done" && accepted(state, id).accept === "needs";
516
565
  const run = { id, iteration: Number(s.iteration) || 0, stage: unapproved ? "review" : s.stage ?? "?", awaiting: unapproved ? "approvals.review" : s.awaiting ?? null, moved, runner: s.runner, agent: s.agent, branch: typeof s.branch === "string" ? s.branch : undefined, worktree: typeof s.worktree === "string" ? s.worktree : undefined, workspace: typeof s.workspace === "string" ? s.workspace : undefined, healed: unapproved || (s.healed === true && s.awaiting === "approvals.review") || undefined };
@@ -1854,7 +1903,11 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
1854
1903
  const wasYolo = yoloRecs.some((s) => ownerOf(st, s, idx) === run);
1855
1904
  // Settings' bypass takes the same road, so the session record and the card's mark follow.
1856
1905
  const yolo = (wasYolo || (!!pick.yolo && agent.cmd === pick.agent) || prefersBypass(agent.cmd, prefs)) && !!YOLO_FLAGS[agent.cmd];
1857
- const flags = [...agentFlags(projectDir, agent.cmd, undefined, model), ...(yolo ? YOLO_FLAGS[agent.cmd] : []), ...argsOf(agent.cmd, prefs)];
1906
+ // Claude reads kaizen's skill files (spec.md and the others) from the folder its global link points at, outside every project, and
1907
+ // would stop on a read prompt for each run; with that folder added it does not. `--` ends the flags, because --add-dir takes a list
1908
+ // and would otherwise swallow the prompt that follows as one more folder.
1909
+ const skills = agent.cmd === "claude" && prompt ? skillsReadDir() : null;
1910
+ const flags = [...agentFlags(projectDir, agent.cmd, undefined, model), ...runSettingsFlags(agent.cmd, yolo), ...argsOf(agent.cmd, prefs), ...(skills ? [`--add-dir=${skills}`, "--"] : [])];
1858
1911
  // The task as its run's request will hold it: without the runner word in front.
1859
1912
  // Session lookups read the tool's folder from the environment; for this launch it's the account's.
1860
1913
  const prior = acct.envVar ? process.env[acct.envVar] : undefined;
@@ -14,6 +14,11 @@ type Hooks = { launch: (state:string, run:string, text:string, task:T.Task, pick
14
14
  // The agent stopped on a permission/choice prompt, and the user's yes or no typed into it.
15
15
  asking?:(pty:string)=>boolean; idle?:(pty:string)=>number; answer?:(pty:string,yes:boolean)=>void };
16
16
  export const HUNG_MS=5*60_000;
17
+ // A run left at review with nothing awaited, its result published and its agent quiet this long (or gone), is over:
18
+ // Looks good comes back and finishes it as the review approval. While the agent prints, the review is still running.
19
+ export const QUIET_MS=2*60_000;
20
+ const leftInReview=(run:any,task:T.Task,key:string|undefined,hooks?:Hooks)=>run.stage==='review'&&!run.awaiting&&!!task.currentResult
21
+ &&(!key||!hooks?.alive(key)||(hooks.idle?.(key)??0)>=QUIET_MS);
17
22
  const runtimeLaunches = new Set<string>();
18
23
  const parse = (file:string) => { try { return JSON.parse(readFileSync(file,'utf8')); } catch { return null; } };
19
24
  const put = (file:string,value:unknown) => { const temp = file + `.${process.pid}.${randomUUID()}.tmp`; writeFileSync(temp,JSON.stringify(value,null,2)+'\n'); renameSync(temp,file); };
@@ -31,8 +36,8 @@ export function allowedActions(state:string,task:T.Task,hooks?:Hooks) {
31
36
  let accept=false,acceptWhy:string|undefined;
32
37
  try{T.acceptTask(structuredClone(task),task.currentResult??'');accept=true;}catch{/* not acceptable now */}
33
38
  // Looks good on a run that waits for its review approval (or open findings) is that approval: it is sent to the run.
34
- const approvable=!!run&&!run.healed&&['approvals.review','findings'].includes(run.awaiting)&&!!hooks?.approve;
35
- if(accept&&run&&!finished&&!approvable){accept=false;acceptWhy=run.awaiting?'Resolve the blocking workflow decision first.':'The workflow is still reviewing this result';}
39
+ const approvable=!!run&&!run.healed&&(['approvals.review','findings'].includes(run.awaiting)||leftInReview(run,task,key,hooks))&&!!hooks?.approve;
40
+ if(accept&&run&&!finished&&!approvable){accept=false;acceptWhy=run.awaiting?'Resolve the blocking workflow decision first.':run.stage==='review'&&task.currentResult?'The workflow is still reviewing this result. Looks good appears once the agent has been quiet for two minutes.':'The workflow is still reviewing this result';}
36
41
  return {accept,...(acceptWhy?{acceptWhy}:{}),
37
42
  stop:(live&&['draft','waiting','working','ready'].includes(task.status))||(['failed','interrupted','working'].includes(task.status)&&alive),
38
43
  // A ready task whose run is still in review but whose agent is gone can only finish by relaunching it.
@@ -208,7 +213,7 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
208
213
  const run=runState(state,t);
209
214
  if(run&&t.activeRun){
210
215
  if(run.healed||run.stage==='done'){if(gateOf(state,t.activeRun)==='needs'){const why=recordAcceptance(state,t.activeRun,'board');if(why)throw new T.TaskError(why,409);}if(run.healed){const why=finishRun(state,t.activeRun);if(why)throw new T.TaskError(why,409);}}
211
- else if(['approvals.review','findings'].includes(run.awaiting)){const why=hooks.approve?hooks.approve(state,t.activeRun,run.awaiting):'This board cannot approve the run';if(why)throw new T.TaskError(why,409);}
216
+ else if(['approvals.review','findings'].includes(run.awaiting)||run.stage==='review'){const why=hooks.approve?hooks.approve(state,t.activeRun,run.awaiting||'approvals.review'):'This board cannot approve the run';if(why)throw new T.TaskError(why,409);}
212
217
  }
213
218
  T.acceptTask(t,String(body.resultId??''));
214
219
  }else if(op==='confirm'){
package/cli/usage.ts CHANGED
@@ -58,14 +58,27 @@ export async function claudeUsageAt(dir: string, get: typeof fetch = fetch): Pro
58
58
  }
59
59
  }
60
60
 
61
+ // A phone's name: iOS reports its hostname as "localhost", so it comes from the DNS name ("iphone-11-1" -> "iPhone 11").
62
+ // ponytail: a lone trailing "-<digit>" is taken as Tailscale's duplicate suffix, so "iphone-8" reads "iPhone"; use the
63
+ // admin API's device name if that matters.
64
+ export function phoneName(p: any): string {
65
+ const host = String(p?.HostName ?? "");
66
+ if (host && host !== "localhost") return host;
67
+ const label = String(p?.DNSName ?? "").split(".")[0].replace(/-\d$/, "");
68
+ return label.split("-").filter(Boolean).map((w) => (w === "iphone" ? "iPhone" : w[0].toUpperCase() + w.slice(1))).join(" ") || host;
69
+ }
70
+
61
71
  // Phones on the tailnet from `tailscale status --json`: iOS and Android peers.
62
72
  export type Computer = { name: string; dns: string; os: string; online: boolean };
63
- export function phonePeers(json: string): { running: boolean; phones: { name: string; online: boolean }[]; computers: Computer[]; self: Computer | null } {
73
+ export function phonePeers(json: string): { running: boolean; phones: { name: string; os: string; online: boolean }[]; computers: Computer[]; self: Computer | null } {
64
74
  try {
65
75
  const s = JSON.parse(json);
66
76
  const peers = Object.values<any>(s?.Peer ?? {});
67
77
  const isPhone = (p) => /^(ios|android)$/i.test(p?.OS ?? "");
68
- const phones = peers.filter(isPhone).map((p) => ({ name: String(p.HostName ?? p.DNSName ?? ""), online: !!p.Online }));
78
+ // Your own phones when you have one: a phone another account shared onto the tailnet is not yours.
79
+ const all = peers.filter(isPhone);
80
+ const own = all.filter((p) => s?.Self?.UserID != null && p.UserID === s.Self.UserID);
81
+ const phones = (own.length ? own : all).map((p) => ({ name: phoneName(p), os: String(p.OS), online: !!p.Online }));
69
82
  // The other computers on the tailnet: the phone's Home lists them, a tap opens their board.
70
83
  const comp = (p, online = !!p.Online): Computer => ({ name: String(p.HostName ?? ""), dns: String(p.DNSName ?? "").replace(/\.$/, ""), os: String(p.OS ?? ""), online });
71
84
  const computers = peers.filter((p) => p?.OS && !isPhone(p)).map((p) => comp(p));