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.
- package/README.md +2 -2
- package/agents/kaizen-builder.md +3 -0
- package/agents/kaizen-planner.md +3 -0
- package/agents/kaizen-reviewer.md +2 -0
- package/assets/kaizen-logo.png +0 -0
- package/assets/kaizen.ico +0 -0
- package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
- package/cli/accounts.test.ts +126 -0
- package/cli/accounts.ts +116 -0
- package/cli/add-project.ts +4 -2
- package/cli/agent-prefs.test.ts +127 -0
- package/cli/agent-prefs.ts +106 -0
- package/cli/automations.test.ts +167 -0
- package/cli/automations.ts +298 -0
- package/cli/board.test.ts +4 -5
- package/cli/computer-helper.py +299 -0
- package/cli/computer.test.ts +155 -0
- package/cli/computer.ts +66 -0
- package/cli/dashboard.ts +15 -22
- package/cli/install.test.ts +16 -0
- package/cli/install.ts +134 -193
- package/cli/keep-awake.ts +30 -0
- package/cli/look.ts +33 -0
- package/cli/project-tree.test.ts +1 -0
- package/cli/pty.test.ts +2 -1
- package/cli/pty.ts +6 -5
- package/cli/report.test.ts +59 -0
- package/cli/report.ts +62 -0
- package/cli/restart.test.ts +1 -0
- package/cli/settings.test.ts +21 -1
- package/cli/settings.ts +22 -13
- package/cli/setup.test.ts +24 -4
- package/cli/setup.ts +101 -51
- package/cli/skills.test.ts +89 -0
- package/cli/skills.ts +112 -0
- package/cli/sources.ts +1 -1
- package/cli/state.test.ts +53 -4
- package/cli/state.ts +132 -42
- package/cli/term-image.test.ts +23 -0
- package/cli/term-image.ts +26 -0
- package/cli/usage.test.ts +8 -2
- package/cli/usage.ts +8 -6
- package/cli/video.test.ts +5 -5
- package/cli/web-accept.test.ts +1 -0
- package/cli/web-decide.test.ts +1 -0
- package/cli/web-pr.test.ts +1 -0
- package/cli/web-skills.test.ts +32 -0
- package/cli/web-symlink.test.ts +1 -0
- package/cli/web.ts +227 -21
- package/cli/workers.test.ts +319 -0
- package/cli/workers.ts +380 -0
- package/cli/worktree.test.ts +21 -2
- package/cli/worktree.ts +21 -2
- package/package.json +1 -1
- package/skills/kaizen/config.default.yml +40 -1
- package/skills/kaizen/settings.md +2 -1
- package/skills/kaizen/skill.json +1 -0
- package/skills/kaizen/spec-build.md +22 -2
- package/skills/kaizen/spec-main.md +9 -0
- package/skills/kaizen/spec-plan.md +18 -1
- package/skills/kaizen/spec-review.md +4 -0
- package/skills/kaizen/spec.md +15 -0
- package/skills/kaizen-help/SKILL.md +2 -0
- package/skills/kaizen-help/skill.json +1 -0
- package/skills/media/kaizen-book/skill.json +1 -0
- package/skills/media/kaizen-deck/SKILL.md +21 -2
- package/skills/media/kaizen-deck/scripts/motion.py +99 -0
- package/skills/media/kaizen-deck/skill.json +1 -0
- package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
- package/skills/media/kaizen-video/skill.json +1 -0
- package/skills/optional/kaizen-computer/SKILL.md +38 -0
- package/skills/optional/kaizen-computer/skill.json +1 -0
- package/web/board/add-project.ts +3 -3
- package/web/board/agent-favicons.ts +9 -0
- package/web/board/agent-term.ts +1 -1
- package/web/board/api.ts +1 -1
- package/web/board/approvals.ts +1 -1
- package/web/board/cards.ts +50 -7
- package/web/board/dictation.ts +46 -3
- package/web/board/fixes.ts +1 -1
- package/web/board/home.ts +1 -1
- package/web/board/icebox.ts +1 -1
- package/web/board/keys.ts +5 -15
- package/web/board/onboarding.ts +1 -1
- package/web/board/panel.ts +24 -20
- package/web/board/phone.ts +6 -1
- package/web/board/run-view.ts +118 -7
- package/web/board/search.ts +6 -0
- package/web/board/settings-accounts.ts +60 -0
- package/web/board/settings-agents.ts +102 -0
- package/web/board/settings-automations.ts +71 -0
- package/web/board/settings-orchestration.ts +32 -0
- package/web/board/settings-pages.test.ts +9 -0
- package/web/board/settings-pages.ts +11 -4
- package/web/board/settings-skills.ts +47 -0
- package/web/board/settings-voice.test.ts +18 -0
- package/web/board/settings-voice.ts +28 -0
- package/web/board/settings.ts +48 -5
- package/web/board/terms.ts +2 -2
- package/web/board/update.ts +1 -1
- package/web/board/workspace.ts +5 -1
- package/web/board/ws-board.test.ts +6 -0
- package/web/board/ws-board.ts +2 -0
- package/web/board/ws-tabs.test.ts +12 -1
- package/web/board/ws-tabs.ts +18 -0
- package/web/board.html +22 -5
- package/web/board.js +156 -85
- package/web/notebook.js +22 -22
- package/web/notes.html +3 -3
- package/web/term.js +27 -27
- package/web/term.ts +25 -3
- package/web/video.html +2 -2
- package/web/video.js +31 -31
package/cli/state.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Everything kaizen knows about a project's state, read from and written to the
|
|
2
2
|
// `.kaizen/` directory. No terminal, no HTTP: the TUI (`dashboard.ts`) and the web
|
|
3
3
|
// board (`web.ts`) both import this and draw it their own way.
|
|
4
|
+
import { readAccounts, resolveAccount, type Resolved } from "./accounts.ts";
|
|
5
|
+
import { agentEnabled, argsOf, commandOf, prefersBypass, readPrefs, withEnv } from "./agent-prefs.ts";
|
|
4
6
|
import { existsSync, readFileSync, readdirSync, appendFileSync, writeFileSync, mkdirSync, statSync, realpathSync, rmSync, renameSync, copyFileSync, openSync, readSync, closeSync } from "node:fs";
|
|
5
7
|
import { Database } from "bun:sqlite";
|
|
6
8
|
import { join, dirname, sep, win32, posix } from "node:path";
|
|
@@ -12,7 +14,7 @@ import { codeDir, projectFromWorktree, wsOf } from "./worktree.ts";
|
|
|
12
14
|
// symlink (/home -> var/home) would never compare equal to it.
|
|
13
15
|
export const home = (() => { try { return realpathSync(homedir()); } catch { return homedir(); } })();
|
|
14
16
|
|
|
15
|
-
export type Run = { id: string; stage: string; awaiting: string | null; moved: number; runner?: string; agent?: string; branch?: string; worktree?: string; workspace?: string; healed?: boolean };
|
|
17
|
+
export type Run = { id: string; iteration?: number; stage: string; awaiting: string | null; moved: number; runner?: string; agent?: string; branch?: string; worktree?: string; workspace?: string; healed?: boolean };
|
|
16
18
|
|
|
17
19
|
export const KNOWN_AGENTS = [
|
|
18
20
|
{ name: "Claude Code", dir: ".claude", cmd: "claude" },
|
|
@@ -23,6 +25,24 @@ export const KNOWN_AGENTS = [
|
|
|
23
25
|
{ name: "Cursor", dir: ".cursor", cmd: "cursor" },
|
|
24
26
|
];
|
|
25
27
|
|
|
28
|
+
// Installed under its own or an overridden command, and not turned off in Settings.
|
|
29
|
+
// The account of a run's latest session of this tool, undefined when it has none. A run started
|
|
30
|
+
// on the normal login stays there ("") even after a default is set: its conversation lives there.
|
|
31
|
+
const runAccount = (st: string, run: string, cmd: string) => {
|
|
32
|
+
const idx = runIndex(st), recs = readSessions(st).filter((s) => s.cmd === cmd && ownerOf(st, s, idx) === run);
|
|
33
|
+
return recs.length ? recs[recs.length - 1]!.account ?? "" : undefined;
|
|
34
|
+
};
|
|
35
|
+
export const accountForRun = (projectDir: string, run: string | undefined, cmd: string, picked?: string) =>
|
|
36
|
+
resolveAccount(cmd, picked ?? (run ? runAccount(join(projectDir, ".kaizen"), run, cmd) : undefined));
|
|
37
|
+
|
|
38
|
+
// Only for a tool with accounts, so with none the Run form's data is as it always was.
|
|
39
|
+
const accountChoices = (cmd: string) => {
|
|
40
|
+
const a = readAccounts(), mine = a.accounts.filter((x) => x.tool === cmd);
|
|
41
|
+
return mine.length ? { accounts: mine.map((x) => ({ id: x.id, name: x.name })), defaultAccount: (a.default as Record<string, string>)[cmd] ?? "" } : {};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const agentUsable = (cmd: string) => agentEnabled(cmd) && !!onPath(commandOf(cmd));
|
|
45
|
+
|
|
26
46
|
export type Agent = { name: string; cmd: string; note?: string };
|
|
27
47
|
|
|
28
48
|
// Each config.yml in the chain, project first: the first one that sets a key decides
|
|
@@ -39,18 +59,18 @@ export function detectDefaultAgent(projectDir: string, want?: string): Agent {
|
|
|
39
59
|
}
|
|
40
60
|
if (!want || want === "auto") return autoAgent(projectDir);
|
|
41
61
|
const found = KNOWN_AGENTS.find((a) => a.cmd === want || a.name.toLowerCase() === want!.toLowerCase());
|
|
42
|
-
if (found &&
|
|
62
|
+
if (found && agentUsable(found.cmd)) return found;
|
|
43
63
|
const a = autoAgent(projectDir);
|
|
44
|
-
return { ...a, note: `${found?.name ?? want} is not installed; opened ${a.name} instead` };
|
|
64
|
+
return { ...a, note: `${found?.name ?? want} is ${found && !agentEnabled(found.cmd) ? "turned off" : "not installed"}; opened ${a.name} instead` };
|
|
45
65
|
}
|
|
46
66
|
|
|
47
67
|
function autoAgent(projectDir: string): Agent {
|
|
48
68
|
for (const a of KNOWN_AGENTS) {
|
|
49
|
-
if (existsSync(join(projectDir, a.dir)) &&
|
|
69
|
+
if (existsSync(join(projectDir, a.dir)) && agentUsable(a.cmd)) return a;
|
|
50
70
|
}
|
|
51
|
-
if (
|
|
71
|
+
if (agentUsable("claude")) return { name: "Claude Code", cmd: "claude" };
|
|
52
72
|
for (const a of KNOWN_AGENTS) {
|
|
53
|
-
if (
|
|
73
|
+
if (agentUsable(a.cmd)) return a;
|
|
54
74
|
}
|
|
55
75
|
return { name: "Claude Code", cmd: "claude" };
|
|
56
76
|
}
|
|
@@ -59,7 +79,7 @@ function autoAgent(projectDir: string): Agent {
|
|
|
59
79
|
// agent:
|
|
60
80
|
// codex: { model: gpt-5, effort: low }
|
|
61
81
|
// Each tool spells the flag its own way; a tool not listed here takes none.
|
|
62
|
-
const MODEL_FLAGS: Record<string, (m: string) => string[]> = {
|
|
82
|
+
export const MODEL_FLAGS: Record<string, (m: string) => string[]> = {
|
|
63
83
|
claude: (m) => ["--model", m], agy: (m) => ["--model", m], codex: (m) => ["-m", m],
|
|
64
84
|
gemini: (m) => ["-m", m], opencode: (m) => ["-m", m],
|
|
65
85
|
};
|
|
@@ -92,7 +112,11 @@ function agentConfig(projectDir: string, cmd: string, configText?: string) {
|
|
|
92
112
|
let block: RegExpExecArray | null = null;
|
|
93
113
|
for (const t of configText === undefined ? configTexts(projectDir) : [configText]) if ((block = re.exec(t))) break;
|
|
94
114
|
const get = (k: string) => block && new RegExp(`\\b${k}:[ \\t]*["']?([^"',}\\s]+)`).exec(block[1])?.[1];
|
|
95
|
-
|
|
115
|
+
// Settings' row (agent.model.<tool>) wins over a hand-written block.
|
|
116
|
+
const row = new RegExp(`^agent:\\n(?:[ \\t#][^\\n]*\\n|\\n)*?[ \\t]+model:[ \\t]*\\n(?:[ \\t]{3,}[^\\n]*\\n)*?[ \\t]{3,}${cmd}:[ \\t]*["']?([^"'\\s#]+)`, "m");
|
|
117
|
+
let set: string | undefined;
|
|
118
|
+
for (const t of configText === undefined ? configTexts(projectDir) : [configText]) if ((set = row.exec(t)?.[1])) break;
|
|
119
|
+
return { model: set || get("model") || undefined, effort: get("effort") || undefined };
|
|
96
120
|
}
|
|
97
121
|
|
|
98
122
|
// `model`: a per-run pick, in place of the configured one. Effort stays configured.
|
|
@@ -110,12 +134,18 @@ export function agentFlags(projectDir: string, cmd: string, configText?: string,
|
|
|
110
134
|
export function agentChoices(projectDir: string) {
|
|
111
135
|
return {
|
|
112
136
|
default: detectDefaultAgent(projectDir).cmd,
|
|
113
|
-
agents: KNOWN_AGENTS.filter((a) =>
|
|
114
|
-
name: a.name, cmd: a.cmd, model: agentConfig(projectDir, a.cmd).model ?? "", models: !!MODEL_FLAGS[a.cmd], yolo: !!YOLO_FLAGS[a.cmd],
|
|
137
|
+
agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => ({
|
|
138
|
+
...accountChoices(a.cmd), name: a.name, cmd: a.cmd, model: agentConfig(projectDir, a.cmd).model ?? "", models: !!MODEL_FLAGS[a.cmd], yolo: !!YOLO_FLAGS[a.cmd],
|
|
115
139
|
})),
|
|
116
140
|
};
|
|
117
141
|
}
|
|
118
142
|
|
|
143
|
+
// The start of the line Settings previews: what a launch runs before its session and prompt.
|
|
144
|
+
export function launchPreview(projectDir: string, cmd: string, p = readPrefs()) {
|
|
145
|
+
const env = Object.keys(p.agents[cmd]?.env ?? {}).map((k) => `${k}=•••`);
|
|
146
|
+
return [...env, commandOf(cmd, p), ...agentFlags(projectDir, cmd), ...(prefersBypass(cmd, p) ? YOLO_FLAGS[cmd] ?? [] : []), ...argsOf(cmd, p)].join(" ");
|
|
147
|
+
}
|
|
148
|
+
|
|
119
149
|
// One argument as a POSIX shell reads it literally: a prompt carries quotes, `$`,
|
|
120
150
|
// backticks and, with notes, newlines.
|
|
121
151
|
const shq = (a: string) => `'${a.replace(/'/g, `'\\''`)}'`;
|
|
@@ -338,10 +368,10 @@ export function nativePath(p: string) {
|
|
|
338
368
|
}
|
|
339
369
|
|
|
340
370
|
// One spelling per folder: no trailing slash, symlinks resolved when the folder exists
|
|
341
|
-
//
|
|
371
|
+
// on every platform, so a project never lists twice.
|
|
342
372
|
export function canonPath(p: string) {
|
|
343
373
|
p = nativePath(p);
|
|
344
|
-
if (process.platform === "win32") return p;
|
|
374
|
+
if (process.platform === "win32") { try { return nativePath(realpathSync.native(p)); } catch { return p; } }
|
|
345
375
|
if (p.length > 1) p = p.replace(/\/+$/, "") || "/";
|
|
346
376
|
try { return realpathSync(p); } catch { return p; }
|
|
347
377
|
}
|
|
@@ -425,7 +455,7 @@ export function readRuns(state: string): Run[] {
|
|
|
425
455
|
try { moved = Math.max(moved, statSync(join(dir, id, "progress.md")).mtimeMs); } catch { /* no progress kept */ }
|
|
426
456
|
// Done without the user's acceptance is not done: every reader sees it waiting on approval.
|
|
427
457
|
const unapproved = s.stage === "done" && accepted(state, id).accept === "needs";
|
|
428
|
-
const run = { id, 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 };
|
|
458
|
+
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 };
|
|
429
459
|
lastRun.set(runDir, run);
|
|
430
460
|
return [run];
|
|
431
461
|
} catch { return existsSync(join(runDir, "state.json")) ? [lastRun.get(runDir)].filter((r): r is Run => !!r) : []; }
|
|
@@ -523,7 +553,7 @@ export function reviewFindings(state: string, id: string) {
|
|
|
523
553
|
const closed = read("06-backlog.md").flatMap((l) => /^-\s*(?:done|rejected):\s*(.*)$/.exec(l)?.[1] ?? []);
|
|
524
554
|
const iter = join(base, "05-iterations");
|
|
525
555
|
const rechecked = new Set((existsSync(iter) ? readdirSync(iter) : []).filter((f) => f.endsWith("-recheck.md"))
|
|
526
|
-
.flatMap((f) => [...readText(join(iter, f)).matchAll(/finding\s+(\d+)\W{1,8}closed/gi)].map((m) => Number(m[1]))));
|
|
556
|
+
.flatMap((f) => [...readText(join(iter, f)).matchAll(/finding\s+(\d+)\W{1,8}(?:closed|pass)\b/gi)].map((m) => Number(m[1]))));
|
|
527
557
|
return lines.flatMap((l) => {
|
|
528
558
|
const m = /^(\d+)\.\s+(.+)$/.exec(l);
|
|
529
559
|
if (!m) return [];
|
|
@@ -749,6 +779,8 @@ export function markBacklogDone(state: string) {
|
|
|
749
779
|
export type Card = {
|
|
750
780
|
kind: "idea" | "run";
|
|
751
781
|
id?: string; // runs only: the directory name
|
|
782
|
+
stage?: string; // runs only: the stage word
|
|
783
|
+
iteration?: number; // runs only: the fix round
|
|
752
784
|
status: string; // what the legend calls this card
|
|
753
785
|
text: string;
|
|
754
786
|
state: string;
|
|
@@ -1251,7 +1283,7 @@ export function boardCards(states: string[], now: number): Card[] {
|
|
|
1251
1283
|
const yolos = new Set(yoloRecs.length ? yoloRecs.map((s) => ownerOf(st, s, indexOf(st))) : []);
|
|
1252
1284
|
for (const r of readRuns(st)) {
|
|
1253
1285
|
next.push({
|
|
1254
|
-
kind: "run", id: r.id, status: statusOf(r, now), text: short(r.id), state: st, where, column: columnOf(r.stage, r.awaiting), moved: r.moved,
|
|
1286
|
+
kind: "run", id: r.id, stage: r.stage, iteration: r.iteration, status: statusOf(r, now), text: short(r.id), state: st, where, column: columnOf(r.stage, r.awaiting), moved: r.moved,
|
|
1255
1287
|
title: requestTitle(body(st, r.id)),
|
|
1256
1288
|
awaiting: r.stage === "abandoned" ? null : r.awaiting,
|
|
1257
1289
|
dim: r.stage === "abandoned",
|
|
@@ -1296,8 +1328,8 @@ export function projectOf(from: string) {
|
|
|
1296
1328
|
: (from.endsWith(".kaizen") ? dirname(from) : from);
|
|
1297
1329
|
}
|
|
1298
1330
|
|
|
1299
|
-
export function manualCommand(projectDir: string, agentCmd: string, prompt: string, flags: string[] = []) {
|
|
1300
|
-
const bin = [agentCmd, ...flags, ...(prompt ? PROMPT_FLAGS[agentCmd] ?? [] : [])].join(" ");
|
|
1331
|
+
export function manualCommand(projectDir: string, agentCmd: string, prompt: string, flags: string[] = [], env = "") {
|
|
1332
|
+
const bin = [...(env ? [env] : []), agentCmd, ...flags, ...(prompt ? PROMPT_FLAGS[agentCmd] ?? [] : [])].join(" ");
|
|
1301
1333
|
// Pasted into whatever shell the user has. fish reads \' and \\ inside single
|
|
1302
1334
|
// quotes as escapes, so ' and \ each go in double quotes, which sh and fish read alike.
|
|
1303
1335
|
const q = (a: string) => `'${a.replace(/['\\]/g, (ch) => (ch === "'" ? `'"'"'` : `'"\\\\"'`))}'`;
|
|
@@ -1310,7 +1342,7 @@ export function manualCommand(projectDir: string, agentCmd: string, prompt: stri
|
|
|
1310
1342
|
// project's state dir ({run, text, cmd, model, sessionId, started}) and `<key>.pid`, which
|
|
1311
1343
|
// the agent writes itself. Only these are ever closed or resumed: a session the user
|
|
1312
1344
|
// opened by hand has no record.
|
|
1313
|
-
export type Session = { key: string; run: string | null; text: string; cmd: string; model?: string | null; yolo?: boolean; resumed?: boolean; sessionId: string | null; started: number };
|
|
1345
|
+
export type Session = { account?: string; key: string; run: string | null; text: string; cmd: string; model?: string | null; yolo?: boolean; resumed?: boolean; sessionId: string | null; started: number };
|
|
1314
1346
|
|
|
1315
1347
|
// How each tool resumes a conversation by id. `start`: the tool takes an id kaizen
|
|
1316
1348
|
// picks at launch. Without it the tool picks its own, and `find` reads it from the
|
|
@@ -1505,6 +1537,22 @@ export function keepAlive(projectDir: string): "off" | "tmux" {
|
|
|
1505
1537
|
return "off";
|
|
1506
1538
|
}
|
|
1507
1539
|
|
|
1540
|
+
export const accountEnv = (r: Resolved) => (r.dir ? [`${r.envVar}=${r.dir}`] : []);
|
|
1541
|
+
const stageEnv = (projectDir: string, run: string) => {
|
|
1542
|
+
try { const s = JSON.parse(readText(join(projectDir, ".kaizen", "runs", run, "state.json"))).stage; return /^\w+$/.test(s) ? [`KAIZEN_STAGE=${s}`] : []; } catch { return []; }
|
|
1543
|
+
};
|
|
1544
|
+
|
|
1545
|
+
// agent.heartbeat_minutes: how long a quiet agent has, in intervals of it, before its card says stale.
|
|
1546
|
+
export function heartbeatMinutes(text = existsSync(join(home, ".kaizen", "config.yml")) ? readText(join(home, ".kaizen", "config.yml")) : "") {
|
|
1547
|
+
const m = /^agent:\n(?:[ \t][^\n]*\n)*?[ \t]+heartbeat_minutes:[ \t]*["']?(\d+)/m.exec(text) || /^agent\.heartbeat_minutes:[ \t]*["']?(\d+)/m.exec(text);
|
|
1548
|
+
return Math.min(Math.max(Number(m?.[1] ?? 5), 1), 60);
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
// agent.keep_awake: machine-wide, so only the global config. Same forms as keepAlive.
|
|
1552
|
+
export function keepAwake(text = existsSync(join(home, ".kaizen", "config.yml")) ? readText(join(home, ".kaizen", "config.yml")) : "") {
|
|
1553
|
+
return (/^agent:\n(?:[ \t][^\n]*\n)*?[ \t]+keep_awake:[ \t]*["']?([^"'\s]+)/m.exec(text) || /^agent\.keep_awake:[ \t]*["']?([^"'\s]+)/m.exec(text))?.[1] ?? "off";
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1508
1556
|
export function launchMode(projectDir: string): "card" | "terminal" {
|
|
1509
1557
|
for (const t of configTexts(projectDir)) {
|
|
1510
1558
|
const m = /^agent:\n(?:[ \t][^\n]*\n)*?[ \t]+launch:[ \t]*["']?([^"'\s]+)/m.exec(t) || /^agent\.launch:[ \t]*["']?([^"'\s]+)/m.exec(t);
|
|
@@ -1605,6 +1653,16 @@ export function sweepSessions(st: string) {
|
|
|
1605
1653
|
// up here, once, and written back so no later record can claim it. None means a fresh
|
|
1606
1654
|
// session, never a guess.
|
|
1607
1655
|
// ponytail: a conversation that begins only after the tool's next launch here is given up (a fresh session), never handed to the wrong run; record a launch marker in the prompt if that bites
|
|
1656
|
+
// Session lookups read the tool's folder from the environment. A record made under an
|
|
1657
|
+
// account is looked up in that account's folder, for every caller.
|
|
1658
|
+
function inAccount<T>(cmd: string, account: string | undefined, fn: () => T): T {
|
|
1659
|
+
const r = account ? resolveAccount(cmd, account) : {};
|
|
1660
|
+
if (!r.envVar) return fn();
|
|
1661
|
+
const prior = process.env[r.envVar];
|
|
1662
|
+
process.env[r.envVar] = r.dir;
|
|
1663
|
+
try { return fn(); } finally { if (prior === undefined) delete process.env[r.envVar!]; else process.env[r.envVar!] = prior; }
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1608
1666
|
export function firstSession(st: string, id: string, cmd: string, cwd: string): Session | null {
|
|
1609
1667
|
const f = SESSION_FLAGS[cmd];
|
|
1610
1668
|
if (!f) return null;
|
|
@@ -1618,14 +1676,14 @@ export function firstSession(st: string, id: string, cmd: string, cwd: string):
|
|
|
1618
1676
|
if (!s.sessionId && f.find) {
|
|
1619
1677
|
// Before the tool's next launch here, any run's: from then on a conversation may be that launch's.
|
|
1620
1678
|
const next = all.find((o) => o.cmd === cmd && o.started > s.started)?.started ?? Infinity;
|
|
1621
|
-
const found = f.find(cwd, s.started, Math.min(next, s.started + FIND_WINDOW_MS), taken);
|
|
1679
|
+
const found = inAccount(cmd, s.account, () => f.find!(cwd, s.started, Math.min(next, s.started + FIND_WINDOW_MS), taken));
|
|
1622
1680
|
if (!found) continue;
|
|
1623
1681
|
taken.add(found);
|
|
1624
1682
|
s.sessionId = found;
|
|
1625
1683
|
const { key, ...rec } = s;
|
|
1626
1684
|
try { writeFileSync(join(sessionsDir(st), key + ".json"), JSON.stringify(rec) + "\n"); } catch { /* found again next time */ }
|
|
1627
1685
|
}
|
|
1628
|
-
if (s.sessionId && f.has(cwd, s.sessionId)) return s;
|
|
1686
|
+
if (s.sessionId && inAccount(cmd, s.account, () => f.has(cwd, s.sessionId!))) return s;
|
|
1629
1687
|
}
|
|
1630
1688
|
return null;
|
|
1631
1689
|
}
|
|
@@ -1645,7 +1703,7 @@ export function runAgent(st: string, id: string): { cmd: string; model: string |
|
|
|
1645
1703
|
// The agent's argv for a launch, and its record. With a run, a decision: it resumes
|
|
1646
1704
|
// the run's conversation when there is one. A project without a state dir gets no
|
|
1647
1705
|
// record; making one here would shadow the user's.
|
|
1648
|
-
export function sessionLaunch(projectDir: string, cmd: string, base: string[], prompt: string, text: string, run?: string, model?: string, yolo?: boolean) {
|
|
1706
|
+
export function sessionLaunch(projectDir: string, cmd: string, base: string[], prompt: string, text: string, run?: string, model?: string, yolo?: boolean, account?: string) {
|
|
1649
1707
|
const st = join(projectDir, ".kaizen");
|
|
1650
1708
|
if (!existsSync(st)) return { fullCmd: [...base, ...promptArgs(cmd, prompt)], key: undefined, pidFile: undefined, record: undefined };
|
|
1651
1709
|
const f = SESSION_FLAGS[cmd];
|
|
@@ -1657,7 +1715,7 @@ export function sessionLaunch(projectDir: string, cmd: string, base: string[], p
|
|
|
1657
1715
|
const key = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1658
1716
|
mkdirSync(sessionsDir(st), { recursive: true });
|
|
1659
1717
|
const record = join(sessionsDir(st), key + ".json");
|
|
1660
|
-
writeFileSync(record, JSON.stringify({ run: run ?? null, text, cmd, model: model ?? null, ...(yolo ? { yolo: true } : {}), ...(prev ? { resumed: true } : {}), sessionId, started: Date.now() }) + "\n");
|
|
1718
|
+
writeFileSync(record, JSON.stringify({ run: run ?? null, text, cmd, model: model ?? null, ...(yolo ? { yolo: true } : {}), ...(account ? { account } : {}), ...(prev ? { resumed: true } : {}), sessionId, started: Date.now() }) + "\n");
|
|
1661
1719
|
return { fullCmd, key, pidFile: join(sessionsDir(st), key + ".pid"), record };
|
|
1662
1720
|
}
|
|
1663
1721
|
|
|
@@ -1689,18 +1747,24 @@ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_
|
|
|
1689
1747
|
// skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
|
|
1690
1748
|
// a work folder that may not be a project, so it is not remembered as one. A session record is
|
|
1691
1749
|
// written only where that folder has a .kaizen (a project place does; the library usually not).
|
|
1692
|
-
export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
|
|
1750
|
+
export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; account?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
|
|
1693
1751
|
const projectDir = pick.cwd ?? projectOf(from);
|
|
1694
1752
|
// The run will be born here; the board must know the dir or the idea never retires.
|
|
1695
1753
|
if (!pick.cwd) remember(projectDir);
|
|
1696
1754
|
const own = run && !pick.agent ? runAgent(join(projectDir, ".kaizen"), run) : null;
|
|
1697
1755
|
const agent = detectDefaultAgent(projectDir, pick.agent ?? own?.cmd);
|
|
1698
|
-
|
|
1756
|
+
// Every agent is off, or the last resort is: nothing may start.
|
|
1757
|
+
if (!agentEnabled(agent.cmd)) return { ok: false, agent, prompt: "", projectDir, manual: "", why: `${agent.name} is turned off in Settings → Agents.` };
|
|
1758
|
+
if (pick.agent && agent.cmd !== pick.agent && !agentEnabled(pick.agent)) return { ok: false, agent, prompt: "", projectDir, manual: "", why: "That agent is turned off in Settings → Agents." };
|
|
1759
|
+
const prefs = readPrefs();
|
|
1760
|
+
const acct = accountForRun(projectDir, run, agent.cmd, pick.account);
|
|
1761
|
+
if (acct.error) return { ok: false, agent, prompt: "", projectDir, manual: "", why: acct.error };
|
|
1762
|
+
if (agent.cmd === "claude") trustFolder(projectDir, acct.dir ? join(acct.dir, ".claude.json") : undefined);
|
|
1699
1763
|
// A board started inside a Claude Code session carries that session's identity. An
|
|
1700
1764
|
// agent inheriting it runs as its child and keeps no transcript, so nothing to resume.
|
|
1701
1765
|
for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
|
|
1702
1766
|
// onPath, not Bun.which: the board may have taken a login shell's PATH after it started.
|
|
1703
|
-
const agentBin = winShim(onPath(agent.cmd) ?? agent.cmd);
|
|
1767
|
+
const agentBin = winShim(onPath(commandOf(agent.cmd, prefs)) ?? commandOf(agent.cmd, prefs));
|
|
1704
1768
|
// No text: a run's conversation reopened as it was, with nothing sent to it.
|
|
1705
1769
|
// A skill other than kaizen: Claude Code takes it as a slash command; other agents are told to use it.
|
|
1706
1770
|
const lead = !pick.skill ? "/kaizen" : agent.cmd === "claude" ? `/${pick.skill}` : `Use the ${pick.skill} skill.`;
|
|
@@ -1713,24 +1777,34 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1713
1777
|
const yoloRecs = run && !pick.agent ? readSessions(st).filter((s) => s.yolo && s.cmd === agent.cmd) : [];
|
|
1714
1778
|
const idx = yoloRecs.length ? runIndex(st) : undefined;
|
|
1715
1779
|
const wasYolo = yoloRecs.some((s) => ownerOf(st, s, idx) === run);
|
|
1716
|
-
|
|
1717
|
-
const
|
|
1780
|
+
// Settings' bypass takes the same road, so the session record and the card's mark follow.
|
|
1781
|
+
const yolo = (wasYolo || (!!pick.yolo && agent.cmd === pick.agent) || prefersBypass(agent.cmd, prefs)) && !!YOLO_FLAGS[agent.cmd];
|
|
1782
|
+
const flags = [...agentFlags(projectDir, agent.cmd, undefined, model), ...(yolo ? YOLO_FLAGS[agent.cmd] : []), ...argsOf(agent.cmd, prefs)];
|
|
1718
1783
|
// The idea as its run's request will hold it: without the runner word in front.
|
|
1719
|
-
|
|
1720
|
-
const
|
|
1784
|
+
// Session lookups read the tool's folder from the environment; for this launch it's the account's.
|
|
1785
|
+
const prior = acct.envVar ? process.env[acct.envVar] : undefined;
|
|
1786
|
+
if (acct.envVar) process.env[acct.envVar] = acct.dir;
|
|
1787
|
+
let s: ReturnType<typeof sessionLaunch>;
|
|
1788
|
+
try { s = sessionLaunch(projectDir, agent.cmd, [agentBin, ...flags], prompt, it.text.replace(/^(lite|full|auto|plan)\s+/i, ""), run, model, yolo, acct.account?.id); }
|
|
1789
|
+
finally { if (acct.envVar) { if (prior === undefined) delete process.env[acct.envVar]; else process.env[acct.envVar] = prior; } }
|
|
1790
|
+
const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? `${acct.envVar}=${shq(acct.dir)}` : "");
|
|
1791
|
+
// Only what is started carries env: the returned `cmd` reaches the page.
|
|
1792
|
+
// A run the board knows hears which one it is; a new run has no id yet and passes --run.
|
|
1793
|
+
const identity = (run || acct.dir) && process.platform !== "win32" ? ["env", ...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...accountEnv(acct)] : [];
|
|
1794
|
+
const started = [...identity, ...withEnv(s.fullCmd, agent.cmd, prefs)];
|
|
1721
1795
|
const drop = () => { if (s.record) rmSync(s.record, { force: true }); };
|
|
1722
1796
|
|
|
1723
1797
|
if (pick.card && ptySupported) {
|
|
1724
1798
|
const key = s.key ?? `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1725
1799
|
try {
|
|
1726
|
-
startPty(key,
|
|
1800
|
+
startPty(key, started, projectDir, s.pidFile, pick.onChange, { seed: pick.seed, tmux: keepAlive(projectDir) === "tmux" ? tmuxName(key) : undefined });
|
|
1727
1801
|
return { ok: true, agent, prompt, projectDir, cmd: s.fullCmd, pty: key };
|
|
1728
1802
|
} catch (err: any) {
|
|
1729
1803
|
drop();
|
|
1730
1804
|
return { ok: false, agent, prompt, projectDir, manual, why: err?.message ?? String(err) };
|
|
1731
1805
|
}
|
|
1732
1806
|
}
|
|
1733
|
-
const term = findTerminal(projectDir,
|
|
1807
|
+
const term = findTerminal(projectDir, started, s.pidFile);
|
|
1734
1808
|
if (!term) {
|
|
1735
1809
|
drop();
|
|
1736
1810
|
return {
|
|
@@ -1780,7 +1854,7 @@ export async function pidOnPort(port: number): Promise<number | null> {
|
|
|
1780
1854
|
const gitOpts = () => ({ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, stdin: "ignore" as const, timeout: 60_000, windowsHide: true });
|
|
1781
1855
|
const gitDone = (code: number | null, stdout: string, stderr: string) => {
|
|
1782
1856
|
const out = stdout.trimEnd(), err = stderr.trim();
|
|
1783
|
-
return { ok: code === 0, out, why: (err || out).split("\n").pop() || "git did not finish" };
|
|
1857
|
+
return { ok: code === 0, code, out, why: (err || out).split("\n").pop() || "git did not finish" };
|
|
1784
1858
|
};
|
|
1785
1859
|
const NO_GIT = { ok: false, out: "", why: "git is not installed" };
|
|
1786
1860
|
function git(dir: string, ...args: string[]) {
|
|
@@ -1798,16 +1872,20 @@ async function gitAsync(dir: string, ...args: string[]) {
|
|
|
1798
1872
|
} catch { return NO_GIT; }
|
|
1799
1873
|
}
|
|
1800
1874
|
|
|
1801
|
-
export type GitStatus = { repo: false } | { repo: true; branch: string; remote: string; files: string[]; ahead: number; others?: number; shared?: string[]; unpushed?: Unpushed[]; rows?: GitRow[]; staged?: string[]; log?: LogLine[] };
|
|
1875
|
+
export type GitStatus = { repo: false; failed?: boolean } | { repo: true; branch: string; remote: string; files: string[]; ahead: number; others?: number; shared?: string[]; unpushed?: Unpushed[]; rows?: GitRow[]; staged?: string[]; log?: LogLine[] };
|
|
1802
1876
|
// One of a run's changed files as the Source control tab lists it. A file with changes
|
|
1803
1877
|
// both staged and not is listed in both groups, as git shows it.
|
|
1804
1878
|
export type GitRow = { path: string; staged: boolean; code: string; add: number; del: number };
|
|
1805
1879
|
export type LogLine = { sha: string; subject: string; refs: string; unpushed: boolean };
|
|
1806
1880
|
type Unpushed = { sha: string; at: number; subject: string; files: string[] };
|
|
1807
1881
|
|
|
1882
|
+
const noRemote = (s: { failed?: boolean }) => (s.failed ? "git did not answer. Try again." : "This project has no git remote.");
|
|
1883
|
+
|
|
1808
1884
|
// A project the board can commit for: a git work tree with somewhere to push.
|
|
1809
1885
|
export function gitStatus(projectDir: string): GitStatus {
|
|
1810
|
-
|
|
1886
|
+
// Only git's own answer (exit 128) means no repo: a killed or missing git says nothing about the folder.
|
|
1887
|
+
const inside = git(projectDir, "rev-parse", "--is-inside-work-tree");
|
|
1888
|
+
if (!inside.ok) return (inside as { code?: number | null }).code === 128 ? { repo: false } : { repo: false, failed: true };
|
|
1811
1889
|
const remote = git(projectDir, "remote").out.split("\n")[0] ?? "";
|
|
1812
1890
|
if (!remote) return { repo: false };
|
|
1813
1891
|
// Every untracked file on its own line: a new directory is never committed whole.
|
|
@@ -1936,7 +2014,14 @@ export function healRuns(state: string): string[] {
|
|
|
1936
2014
|
if (!existsSync(dir)) return [];
|
|
1937
2015
|
return readdirSync(dir).filter((id) => {
|
|
1938
2016
|
const file = join(dir, id, "state.json");
|
|
1939
|
-
|
|
2017
|
+
let text = "";
|
|
2018
|
+
try { text = readText(file); } catch { return false; }
|
|
2019
|
+
// Accepted after it was healed (the line was written just after `done`): it is done, nothing is waiting.
|
|
2020
|
+
if (/"healed":\s*true/.test(text) && gateOf(state, id) === "user") {
|
|
2021
|
+
setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; });
|
|
2022
|
+
return false;
|
|
2023
|
+
}
|
|
2024
|
+
if (!/"stage":\s*"done"/.test(text)) return false; // cheap: skip runs not done
|
|
1940
2025
|
return accepted(state, id).accept === "needs" && setStage(file, (s) => {
|
|
1941
2026
|
if (s.stage !== "done") return false;
|
|
1942
2027
|
s.stage = "review"; s.awaiting = "approvals.review"; s.healed = true;
|
|
@@ -1959,11 +2044,15 @@ export function finishRun(state: string, id: string, userApproved = false): stri
|
|
|
1959
2044
|
}
|
|
1960
2045
|
const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
|
|
1961
2046
|
|
|
1962
|
-
type Report = { id: string; text: string; named: string; at: number; sha?: string };
|
|
2047
|
+
type Report = { id: string; text: string; named: string; at: number; sha?: string; closed?: number };
|
|
1963
2048
|
function runReports(state: string): Report[] {
|
|
1964
2049
|
let ids: string[] = [];
|
|
1965
2050
|
try { ids = readdirSync(join(state, "runs")); } catch {}
|
|
1966
|
-
return ids.map((id) =>
|
|
2051
|
+
return ids.map((id) => {
|
|
2052
|
+
let closed = 0;
|
|
2053
|
+
try { closed = statSync(join(state, "runs", id, "07-commit.md")).mtimeMs; } catch { /* no record */ }
|
|
2054
|
+
return { id, ...runReport(state, id), sha: readCommit(state, id)?.sha, closed };
|
|
2055
|
+
});
|
|
1967
2056
|
}
|
|
1968
2057
|
// A run holds a path at time `t` when its report names it, was written by then, and no
|
|
1969
2058
|
// other run naming it reported in between.
|
|
@@ -1980,7 +2069,8 @@ const editedAfter = (dir: string, p: string, t: number) => {
|
|
|
1980
2069
|
try { return statSync(join(dir, p)).mtimeMs >= t + 1000; } catch { return false; }
|
|
1981
2070
|
};
|
|
1982
2071
|
const runFiles = (dir: string, changed: string[], mine: Report, rest: Report[]) => {
|
|
1983
|
-
|
|
2072
|
+
// A rebased or landed commit has a new SHA, so the recorded one is unknown here: the record's own time stands in.
|
|
2073
|
+
const sealed = commitTime(dir, mine.sha) || (mine.sha && mine.closed) || 0;
|
|
1984
2074
|
return changed.filter((l) => {
|
|
1985
2075
|
const p = statusPath(l);
|
|
1986
2076
|
return owns(mine, rest, p, Infinity) && !(lastCommit(dir, p) > mine.at) && !(sealed >= mine.at - 1000 && sealed > 0 && editedAfter(dir, p, sealed));
|
|
@@ -2084,7 +2174,7 @@ export function branchLog(dir: string, n: number, ahead = 0): LogLine[] {
|
|
|
2084
2174
|
// Discard reverts the work tree side only, as Orca's does; an untracked file is deleted.
|
|
2085
2175
|
export function stageFiles(state: string, id: string, op: "stage" | "unstage" | "discard", paths: string[]): string | null {
|
|
2086
2176
|
const s = runGit(state, id);
|
|
2087
|
-
if (!s.repo) return
|
|
2177
|
+
if (!s.repo) return noRemote(s);
|
|
2088
2178
|
if (!paths.length) return "No files named.";
|
|
2089
2179
|
const mine = new Map(s.files.map((l) => [statusPath(l), l]));
|
|
2090
2180
|
const stray = paths.filter((p) => !mine.has(p));
|
|
@@ -2114,7 +2204,7 @@ export function stageFiles(state: string, id: string, op: "stage" | "unstage" |
|
|
|
2114
2204
|
const HEADLESS_ENV = () => Object.fromEntries(Object.entries(process.env).filter(([k, v]) => v !== undefined && !CHILD_ENV.test(k))) as Record<string, string>;
|
|
2115
2205
|
export async function suggestMessage(state: string, id: string): Promise<{ ok: true; message: string; ai: boolean } | { ok: false; why: string }> {
|
|
2116
2206
|
const s = runGit(state, id);
|
|
2117
|
-
if (!s.repo) return { ok: false, why:
|
|
2207
|
+
if (!s.repo) return { ok: false, why: noRemote(s) };
|
|
2118
2208
|
if (!s.files.length) return { ok: false, why: "No changes to describe." };
|
|
2119
2209
|
const dir = codeDir(dirname(state), id), rows = s.rows ?? [];
|
|
2120
2210
|
const use = (s.staged?.length ? s.staged : [...new Set(rows.map((r) => r.path))]);
|
|
@@ -2143,7 +2233,7 @@ export async function suggestMessage(state: string, id: string): Promise<{ ok: t
|
|
|
2143
2233
|
// for another run) is refused rather than swept into this run's commit.
|
|
2144
2234
|
export function commitStaged(state: string, id: string, message: string, shown: string[]): { ok: true; sha: string } | { ok: false; why: string } {
|
|
2145
2235
|
const dir = codeDir(dirname(state), id), s = runGit(state, id);
|
|
2146
|
-
if (!s.repo) return { ok: false, why:
|
|
2236
|
+
if (!s.repo) return { ok: false, why: noRemote(s) };
|
|
2147
2237
|
if (gateOf(state, id) === "needs") return { ok: false, why: "This run is not approved yet. Approve it first." };
|
|
2148
2238
|
const staged = s.staged ?? [];
|
|
2149
2239
|
if (!staged.length) return { ok: false, why: "Nothing is staged." };
|
|
@@ -2202,7 +2292,7 @@ const COMMIT_TYPE = new RegExp(`^(${COMMIT_TYPES.join("|")})(\\([^)\\n]+\\))?!?:
|
|
|
2202
2292
|
export async function commitPush(state: string, id: string, message: string, shown: string[]): Promise<{ ok: true; sha: string } | { ok: false; why: string }> {
|
|
2203
2293
|
const dir = codeDir(dirname(state), id);
|
|
2204
2294
|
const s = runGit(state, id);
|
|
2205
|
-
if (!s.repo) return { ok: false, why:
|
|
2295
|
+
if (!s.repo) return { ok: false, why: noRemote(s) };
|
|
2206
2296
|
if (gateOf(state, id) === "needs") return { ok: false, why: "This run is not approved yet. Approve it first." };
|
|
2207
2297
|
if (s.files.join("\n") !== shown.join("\n")) return { ok: false, why: "The changed files are no longer the ones shown. Look at the list again." };
|
|
2208
2298
|
if (s.files.length) {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { existsSync, mkdtempSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { imageExt, MAX_IMAGE, saveImage } from "./term-image.ts";
|
|
6
|
+
|
|
7
|
+
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]);
|
|
8
|
+
|
|
9
|
+
test("the type comes from the bytes", () => {
|
|
10
|
+
expect(imageExt(png)).toBe("png");
|
|
11
|
+
expect(imageExt(new TextEncoder().encode("RIFF0000WEBP"))).toBe("webp");
|
|
12
|
+
expect(imageExt(new TextEncoder().encode("<svg onload=x>"))).toBeNull();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("saves an image and refuses the rest", () => {
|
|
16
|
+
const dir = mkdtempSync(join(tmpdir(), "kz-img-"));
|
|
17
|
+
const f = saveImage(png, dir)!;
|
|
18
|
+
expect(f.endsWith(".png") && existsSync(f)).toBe(true);
|
|
19
|
+
expect(saveImage(new Uint8Array(4), dir)).toBeNull();
|
|
20
|
+
const big = new Uint8Array(MAX_IMAGE + 1);
|
|
21
|
+
big.set(png);
|
|
22
|
+
expect(saveImage(big, dir)).toBeNull();
|
|
23
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Images pasted into a board terminal. The type comes from the file's own first bytes, never
|
|
2
|
+
// from the page, and the name is random, so nothing the page sends reaches the path.
|
|
3
|
+
import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
|
|
7
|
+
export const MAX_IMAGE = 10 * 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
export function imageExt(b: Uint8Array) {
|
|
10
|
+
const at = (o: number, s: string) => [...s].every((c, i) => b[o + i] === c.charCodeAt(0));
|
|
11
|
+
if (b[0] === 0x89 && at(1, "PNG")) return "png";
|
|
12
|
+
if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "jpg";
|
|
13
|
+
if (at(0, "GIF8")) return "gif";
|
|
14
|
+
if (at(0, "RIFF") && at(8, "WEBP")) return "webp";
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function saveImage(b: Uint8Array, dir = join(homedir(), ".kaizen", "term-images")) {
|
|
19
|
+
const ext = b.length <= MAX_IMAGE ? imageExt(b) : null;
|
|
20
|
+
if (!ext) return null;
|
|
21
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
22
|
+
const file = join(dir, `${crypto.randomUUID()}.${ext}`);
|
|
23
|
+
writeFileSync(file, b, { mode: 0o600 });
|
|
24
|
+
try { chmodSync(file, 0o600); } catch { /* Windows */ }
|
|
25
|
+
return file;
|
|
26
|
+
}
|
package/cli/usage.test.ts
CHANGED
|
@@ -39,7 +39,7 @@ test("claudeUsage: maps the windows; a failure is an error that never carries th
|
|
|
39
39
|
const e = await claudeUsage(h, fail);
|
|
40
40
|
expect(e).toHaveProperty("error");
|
|
41
41
|
expect(JSON.stringify(e)).not.toContain("SECRET");
|
|
42
|
-
expect(await claudeUsage(h, (async () => new Response("", { status: 401 })) as any)).toEqual({ agent: "claude", error: "HTTP 401" });
|
|
42
|
+
expect(await claudeUsage(h, (async () => new Response("", { status: 401 })) as any)).toEqual({ agent: "claude", error: "HTTP 401", expired: true });
|
|
43
43
|
});
|
|
44
44
|
|
|
45
45
|
test("phonePeers: online, offline, no phone, not running", () => {
|
|
@@ -196,7 +196,13 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
|
|
|
196
196
|
writeFileSync(join(g, "config.yml"), readFileSync(join(repo, "skills", "kaizen", "config.default.yml"), "utf8").replace('projects_dir: ""', "projects_dir: ~/Projects"));
|
|
197
197
|
mkdirSync(join(g, "runs", "g1"), { recursive: true });
|
|
198
198
|
writeFileSync(join(g, "runs", "g1", "state.json"), JSON.stringify({ id: "g1", stage: "plan", awaiting: "approvals.plan" }));
|
|
199
|
-
|
|
199
|
+
// The board's snapshot refreshes behind the request: wait for the run to appear.
|
|
200
|
+
let G: any;
|
|
201
|
+
for (let i = 0; i < 50; i++) {
|
|
202
|
+
G = await (await fetch(at + "/state?all=1")).json();
|
|
203
|
+
if (G.cards.some((c: any) => c.id === "g1")) break;
|
|
204
|
+
await Bun.sleep(100);
|
|
205
|
+
}
|
|
200
206
|
expect(G.cards.find((c: any) => c.id === "g1")?.ws).toBe(g);
|
|
201
207
|
expect(G.projects.some((p: any) => p.dir === g)).toBe(false);
|
|
202
208
|
expect(G.rail.find((p: any) => p.dir === g)?.workspaces).toEqual([{ path: g, branch: "", main: true }]);
|
package/cli/usage.ts
CHANGED
|
@@ -6,14 +6,15 @@ import { existsSync, readFileSync, statSync } from "node:fs";
|
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
|
|
8
8
|
export type Window = { pct: number; resetsAt: number | null };
|
|
9
|
-
export type Usage = { agent: string; five: Window | null; week: Window | null } | { agent: string; error: string };
|
|
9
|
+
export type Usage = { agent: string; five: Window | null; week: Window | null } | { agent: string; error: string; expired?: boolean };
|
|
10
10
|
|
|
11
11
|
const win = (pct: unknown, resets: unknown): Window | null =>
|
|
12
12
|
typeof pct === "number" ? { pct: Math.round(pct), resetsAt: typeof resets === "number" ? resets * 1000 : typeof resets === "string" ? Date.parse(resets) || null : null } : null;
|
|
13
13
|
|
|
14
14
|
// The last rate_limits in the newest ~/.codex/sessions/**/rollout-*.jsonl that has one, or null.
|
|
15
|
-
export
|
|
16
|
-
|
|
15
|
+
export const codexUsage = (home: string) => codexUsageAt(join(home, ".codex"));
|
|
16
|
+
export function codexUsageAt(dir: string): Usage | null {
|
|
17
|
+
const root = join(dir, "sessions");
|
|
17
18
|
if (!existsSync(root)) return null;
|
|
18
19
|
// Newest first: a session that has only just started has no rate_limits line yet.
|
|
19
20
|
const files = [...new Bun.Glob("**/rollout-*.jsonl").scanSync({ cwd: root })]
|
|
@@ -41,13 +42,14 @@ export function codexUsage(home: string): Usage | null {
|
|
|
41
42
|
|
|
42
43
|
// Claude's plan usage, or null when there is no Claude login. A failure is an error
|
|
43
44
|
// entry, so the footer says "usage unavailable" instead of showing 0%.
|
|
44
|
-
export
|
|
45
|
+
export const claudeUsage = (home: string, get: typeof fetch = fetch) => claudeUsageAt(join(home, ".claude"), get);
|
|
46
|
+
export async function claudeUsageAt(dir: string, get: typeof fetch = fetch): Promise<Usage | null> {
|
|
45
47
|
let token = "";
|
|
46
|
-
try { token = JSON.parse(readFileSync(join(
|
|
48
|
+
try { token = JSON.parse(readFileSync(join(dir, ".credentials.json"), "utf8"))?.claudeAiOauth?.accessToken ?? ""; } catch { return null; }
|
|
47
49
|
if (!token) return null;
|
|
48
50
|
try {
|
|
49
51
|
const r = await get("https://api.anthropic.com/api/oauth/usage", { headers: { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" }, signal: AbortSignal.timeout(8000) });
|
|
50
|
-
if (!r.ok) return { agent: "claude", error: `HTTP ${r.status}
|
|
52
|
+
if (!r.ok) return { agent: "claude", error: `HTTP ${r.status}`, ...(r.status === 401 ? { expired: true } : {}) };
|
|
51
53
|
const d: any = await r.json();
|
|
52
54
|
return { agent: "claude", five: win(d?.five_hour?.utilization, d?.five_hour?.resets_at), week: win(d?.seven_day?.utilization, d?.seven_day?.resets_at) };
|
|
53
55
|
} catch (e) {
|
package/cli/video.test.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// paths a page may ask for, and the job queue the skill's scripts run in.
|
|
3
3
|
import { test, expect } from "bun:test";
|
|
4
4
|
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync, readdirSync, cpSync, rmSync, truncateSync } from "node:fs";
|
|
5
|
-
import { join, dirname } from "node:path";
|
|
5
|
+
import { basename, join, dirname } from "node:path";
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
7
7
|
|
|
8
8
|
const repo = dirname(import.meta.dir);
|
|
@@ -52,7 +52,7 @@ test("the library lists films and footage, with each rendered shape and the word
|
|
|
52
52
|
const proj = mkdtempSync(join(tmpdir(), "kaizen-video-proj-"));
|
|
53
53
|
mkdirSync(join(proj, "videos"));
|
|
54
54
|
const all = video.places(lib, [proj, lib, mkdtempSync(join(tmpdir(), "kaizen-novideo-"))]);
|
|
55
|
-
expect(all.map((p) => p.label)).toEqual(["library", proj
|
|
55
|
+
expect(all.map((p) => p.label)).toEqual(["library", basename(proj)]);
|
|
56
56
|
const list = video.listVideos(all);
|
|
57
57
|
const demo = list.find((v) => v.name === "demo")!;
|
|
58
58
|
expect(demo.mode).toBe("film");
|
|
@@ -142,9 +142,9 @@ test("jobs run the skill's scripts as argv, in the background, one at a time", a
|
|
|
142
142
|
await until(() => video.jobOf(lib, "talk")?.state === "done");
|
|
143
143
|
expect(video.jobOf(lib, "demo")).toMatchObject({ state: "done", step: 2, total: 2 });
|
|
144
144
|
expect(readFileSync(calls, "utf8").trim().split("\n").map((l) => JSON.parse(l))).toEqual([
|
|
145
|
-
["videos
|
|
145
|
+
[join("videos", "demo"), "--format", "9x16", "--render"], [join("videos", "demo"), "--format", "4x5", "--render"],
|
|
146
146
|
]);
|
|
147
|
-
expect(JSON.parse(readFileSync(join(lib, "videos", "talk", "calls.txt"), "utf8"))).toEqual(["videos
|
|
147
|
+
expect(JSON.parse(readFileSync(join(lib, "videos", "talk", "calls.txt"), "utf8"))).toEqual([join("videos", "talk")]);
|
|
148
148
|
expect(typeof b).toBe("object");
|
|
149
149
|
delete process.env.FAKE_SLEEP;
|
|
150
150
|
});
|
|
@@ -212,7 +212,7 @@ test("the board serves sound assets and the Video page, and refuses unsafe paths
|
|
|
212
212
|
const calls = join(homeDir, ".kaizen", "videos", "demo", "calls.txt");
|
|
213
213
|
await until(() => existsSync(calls) && readFileSync(calls, "utf8").trim().split("\n").length === 2);
|
|
214
214
|
expect(readFileSync(calls, "utf8").trim().split("\n").map((l) => JSON.parse(l))).toEqual([
|
|
215
|
-
["videos
|
|
215
|
+
[join("videos", "demo"), "--format", "9x16", "--render"], [join("videos", "demo"), "--format", "16x9", "--render"],
|
|
216
216
|
]);
|
|
217
217
|
} finally { proc.kill(); await proc.exited; }
|
|
218
218
|
}, 30000);
|
package/cli/web-accept.test.ts
CHANGED
|
@@ -28,6 +28,7 @@ test.skipIf(process.platform === "win32")("board /accept finishes a healed run w
|
|
|
28
28
|
const run = (id: string) => JSON.parse(readFileSync(join(st, "runs", id, "state.json"), "utf8"));
|
|
29
29
|
expect(run("2026-10-29-healed").healed).toBe(true);
|
|
30
30
|
const port = 20000 + Math.floor(Math.random() * 20000);
|
|
31
|
+
mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
|
|
31
32
|
const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
|
|
32
33
|
{ env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
|
|
33
34
|
try {
|
package/cli/web-decide.test.ts
CHANGED
|
@@ -18,6 +18,7 @@ test.skipIf(process.platform === "win32")("board /decide reuses the run's open a
|
|
|
18
18
|
const waiting = (awaiting: string) => writeFileSync(join(d, "state.json"), JSON.stringify({ id: "2026-10-30-r", agent: "claude", stage: "plan", awaiting }));
|
|
19
19
|
waiting("approvals.plan");
|
|
20
20
|
const port = 20000 + Math.floor(Math.random() * 20000);
|
|
21
|
+
mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
|
|
21
22
|
const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
|
|
22
23
|
{ env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz"), PATH: `${bin}:${process.env.PATH}` }, stdout: "ignore", stderr: "ignore" });
|
|
23
24
|
try {
|
package/cli/web-pr.test.ts
CHANGED
|
@@ -24,6 +24,7 @@ test.skipIf(process.platform === "win32")("board /pr refuses unfinished, unappro
|
|
|
24
24
|
mk("2026-10-30-building", { stage: "build" });
|
|
25
25
|
mk("2026-10-30-unapproved", { stage: "done" }); // done with changed files, no accepted: line
|
|
26
26
|
const port = 20000 + Math.floor(Math.random() * 20000);
|
|
27
|
+
mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
|
|
27
28
|
const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
|
|
28
29
|
{ env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
|
|
29
30
|
try {
|