kaizen-agent 1.68.0 → 1.69.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 -0
- package/cli/install.ts +46 -0
- package/cli/knowledge.ts +18 -2
- package/cli/settings.ts +2 -0
- package/cli/state.ts +34 -1
- package/cli/stats.ts +172 -0
- package/package.json +1 -1
- package/skills/kaizen/SKILL.md +15 -39
- package/skills/kaizen/config.default.yml +10 -0
- package/skills/kaizen/spec-build.md +6 -0
- package/skills/kaizen/spec-main.md +12 -0
- package/skills/kaizen/spec-plan.md +11 -1
- package/skills/kaizen/spec-review.md +8 -1
- package/skills/kaizen/spec.md +9 -1
- package/skills/kaizen-help/SKILL.md +3 -0
- package/web/board/settings-pages.ts +1 -0
- package/web/board.js +2 -2
- package/web/notebook.js +1 -1
- package/web/term.js +1 -1
- package/web/video.js +1 -1
package/README.md
CHANGED
|
@@ -52,6 +52,8 @@ None of this is a lack of intelligence. It is a missing workflow. Many assistant
|
|
|
52
52
|
|
|
53
53
|
## Install
|
|
54
54
|
|
|
55
|
+
Prefer a window of its own? [Download the desktop app](https://kaizen.sarahdigital.id/#desktop) for macOS, Windows or Linux.
|
|
56
|
+
|
|
55
57
|
1. **Install** on macOS or Linux:
|
|
56
58
|
```bash
|
|
57
59
|
curl -fsSL https://bun.sh/install | bash && ~/.bun/bin/bunx kaizen-agent
|
package/cli/install.ts
CHANGED
|
@@ -26,6 +26,23 @@ const force = args.has("--force");
|
|
|
26
26
|
const verbose = args.has("--verbose");
|
|
27
27
|
const interactive = process.stdin.isTTY && !check && !upgrade && !args.has("--yes");
|
|
28
28
|
|
|
29
|
+
// Every top-level word kaizen dispatches on. Anything else used to fall through to the
|
|
30
|
+
// installer, so a typo or a command from a newer kaizen reinstalled instead of failing.
|
|
31
|
+
// cli/install-unknown.test.ts fails if a dispatched word is missing here.
|
|
32
|
+
const COMMANDS = ["automation", "help", "init", "browser", "card", "chat", "computer", "config", "docs", "done", "gather", "handoff",
|
|
33
|
+
"icebox", "issue", "prune", "recall", "related", "remember", "report", "roadmap", "settings", "setup", "sources",
|
|
34
|
+
"state", "stats", "uninstall", "upgrade", "version", "web", "worker", "worktree"];
|
|
35
|
+
const first = Bun.argv[2];
|
|
36
|
+
const commandList = ` commands: ${COMMANDS.join(", ")}\n plain \`kaizen\` opens the board; \`kaizen --yes\` installs; \`kaizen init\` sets up this folder\n`;
|
|
37
|
+
if (first && !first.startsWith("-") && !COMMANDS.includes(first)) {
|
|
38
|
+
console.log(`\n unknown command "${first}"\n\n${commandList}`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
if (first === "help") { console.log(`\n${commandList}`); process.exit(0); }
|
|
42
|
+
// `kaizen init` (README) has always run the installer, which sets up the project folder;
|
|
43
|
+
// keep that, and set up this folder even when it is not a git root.
|
|
44
|
+
if (first === "init") args.add("--init-project");
|
|
45
|
+
|
|
29
46
|
function parsePresetArg(): PresetName | null {
|
|
30
47
|
for (const a of Bun.argv.slice(2)) {
|
|
31
48
|
if (a.startsWith("--preset=")) {
|
|
@@ -228,6 +245,35 @@ if (Bun.argv[2] === "done") {
|
|
|
228
245
|
process.exit(0);
|
|
229
246
|
}
|
|
230
247
|
|
|
248
|
+
// `kaizen state <run id> key=value ...`: set stage, awaiting, iteration (or any other key)
|
|
249
|
+
// in a run's state.json in one atomic write, refusing words no board understands.
|
|
250
|
+
if (Bun.argv[2] === "state") {
|
|
251
|
+
const { locate, setRunState } = await import("./state.ts");
|
|
252
|
+
const [id, ...pairs] = Bun.argv.slice(3);
|
|
253
|
+
if (!id) { console.log(`\n kaizen state <run id> key=value [key=value ...]\n`); process.exit(1); }
|
|
254
|
+
const why = setRunState(locate() ?? join(home, ".kaizen"), id, pairs);
|
|
255
|
+
if (why) { console.log(`\n ${why}\n`); process.exit(1); }
|
|
256
|
+
console.log(`\n ${id}: ${pairs.join(" ")}\n`);
|
|
257
|
+
process.exit(0);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// `kaizen stats [<run id>] [--json]` and `kaizen related <path...>`: read-only, cli/stats.ts.
|
|
261
|
+
if (Bun.argv[2] === "stats" || Bun.argv[2] === "related") {
|
|
262
|
+
const { locate } = await import("./state.ts");
|
|
263
|
+
const { statsText, related } = await import("./stats.ts");
|
|
264
|
+
const state = locate() ?? join(home, ".kaizen");
|
|
265
|
+
const rest = Bun.argv.slice(3), json = rest.includes("--json"), words = rest.filter((a) => a !== "--json");
|
|
266
|
+
if (Bun.argv[2] === "stats") {
|
|
267
|
+
const out = statsText(state, words[0], json);
|
|
268
|
+
console.log(out);
|
|
269
|
+
process.exit(out.startsWith("no run ") ? 1 : 0);
|
|
270
|
+
}
|
|
271
|
+
if (!words.length) { console.log(`\n kaizen related <path> [<path> ...]\n`); process.exit(1); }
|
|
272
|
+
const r = related(state, words);
|
|
273
|
+
console.log(json ? JSON.stringify(r, null, 2) : r.length ? r.map((x) => `${x.id} — ${x.title}${x.open ? ` — ${x.open} open backlog` : ""}`).join("\n") : "Related: none");
|
|
274
|
+
process.exit(0);
|
|
275
|
+
}
|
|
276
|
+
|
|
231
277
|
// `kaizen remember …` / `kaizen recall …`: global knowledge, see cli/knowledge.ts.
|
|
232
278
|
if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
|
|
233
279
|
const { cli } = await import("./knowledge.ts");
|
package/cli/knowledge.ts
CHANGED
|
@@ -17,6 +17,21 @@ import { homedir } from "node:os";
|
|
|
17
17
|
export const TRACKS = ["code", "writing", "communication", "operations", "research", "preferences"];
|
|
18
18
|
// preferences.md is the user's to write by hand in v1: taste is never inferred from work.
|
|
19
19
|
const WRITABLE = TRACKS.filter((t) => t !== "preferences");
|
|
20
|
+
// Planners describe a track in their own words (spec.md: no fixed taxonomy), so the
|
|
21
|
+
// stored label drifts: `software` and `code` name the same work. Map the label, never
|
|
22
|
+
// the inference. A mix ("code+writing") takes its first known part.
|
|
23
|
+
const ALIAS: Record<string, string> = {
|
|
24
|
+
software: "code", app: "code", web: "code", cli: "code", feature: "code", bugfix: "code",
|
|
25
|
+
docs: "writing", documentation: "writing", book: "writing",
|
|
26
|
+
marketing: "communication", copy: "communication",
|
|
27
|
+
ops: "operations", devops: "operations", release: "operations",
|
|
28
|
+
analysis: "research", operational: "operations",
|
|
29
|
+
};
|
|
30
|
+
export function trackOf(t: string): string {
|
|
31
|
+
// Free-form labels ("code: ci flake", "software-enhancement") lead with their kind.
|
|
32
|
+
const parts = t.toLowerCase().split(/[^a-z]+/).filter(Boolean).map((p) => ALIAS[p] ?? p);
|
|
33
|
+
return parts.find((p) => TRACKS.includes(p)) ?? t.toLowerCase().trim();
|
|
34
|
+
}
|
|
20
35
|
export const SESSION_HEADER = "Past experience from other projects (kaizen recall) — verify before applying, project rules win:";
|
|
21
36
|
// A session hook only injects lines that share at least one tool with the project.
|
|
22
37
|
const SESSION_MIN_SCORE = 2;
|
|
@@ -75,6 +90,7 @@ export type Remembered = { ok: true; line: string; n: number; similar: string[]
|
|
|
75
90
|
// Appends by default; replaces a line only when told which one. It never judges two
|
|
76
91
|
// lessons the same itself: it hands back the same-tag lines for the caller to decide.
|
|
77
92
|
export function remember(o: { track: string; tags: string; text: string; applies: string; source: string; replace?: number; projectDir: string }): Remembered {
|
|
93
|
+
o = { ...o, track: trackOf(o.track) };
|
|
78
94
|
if (!WRITABLE.includes(o.track)) return { ok: false, why: o.track === "preferences" ? "preferences are written by hand, not by remember" : `unknown track "${o.track}" (${WRITABLE.join(", ")})` };
|
|
79
95
|
if (!globalAllowed(o.projectDir)) return { ok: false, why: "knowledge.global is false for this project; nothing written" };
|
|
80
96
|
const tags = tagsOf(o.tags);
|
|
@@ -112,7 +128,7 @@ export function remember(o: { track: string; tags: string; text: string; applies
|
|
|
112
128
|
export function recall(o: { track?: string; tags?: string; query?: string; limit?: number; min?: number }): string[] {
|
|
113
129
|
const want = tagsOf(o.tags ?? "");
|
|
114
130
|
const words = (o.query ?? "").toLowerCase().split(/\W+/).filter((w) => w.length > 2);
|
|
115
|
-
const tracks = o.track ? [o.track] : TRACKS;
|
|
131
|
+
const tracks = o.track ? [trackOf(o.track)] : TRACKS;
|
|
116
132
|
const scored = tracks.flatMap((t) => lines(t)).map((l) => {
|
|
117
133
|
const bare = l.tags.map((t) => t.split("@")[0]);
|
|
118
134
|
// An exact tag (bun@1.2) outranks the same tool at another version (bun@1.1).
|
|
@@ -193,7 +209,7 @@ export function cli(argv: string[], cwd = process.cwd()): number {
|
|
|
193
209
|
if (rest.includes("--session")) { process.stdout.write(sessionText(cwd)); return 0; }
|
|
194
210
|
const track = flag("--track"), tags = flag("--tags"), query = flag("--query"), limit = Number(flag("--limit") ?? 20);
|
|
195
211
|
if (!Number.isInteger(limit) || limit < 1) { console.log("--limit must be a whole number above 0"); return 1; }
|
|
196
|
-
if (track && !TRACKS.includes(track)) { console.log(`unknown track "${track}"`); return 1; }
|
|
212
|
+
if (track && !TRACKS.includes(trackOf(track))) { console.log(`unknown track "${track}"`); return 1; }
|
|
197
213
|
const out = recall({ track, tags, query: query ?? rest.join(" "), limit });
|
|
198
214
|
console.log(out.length ? out.join("\n") : "Recalled: none");
|
|
199
215
|
return 0;
|
package/cli/settings.ts
CHANGED
|
@@ -120,6 +120,8 @@ const SETTINGS: Setting[] = [
|
|
|
120
120
|
{ key: "auto_fix.enabled", label: "Fix findings automatically", group: "Auto-fix", values: ["true", "false"], help: "" },
|
|
121
121
|
{ key: "auto_fix.min_severity", label: "Lowest severity to fix", group: "Auto-fix", values: ["critical", "high", "medium", "low"], help: "", when: ["auto_fix.enabled", "true"] },
|
|
122
122
|
{ key: "auto_fix.max_iterations", label: "Max fix rounds", group: "Auto-fix", values: ["1", "2", "3", "4", "5"], help: "", when: ["auto_fix.enabled", "true"] },
|
|
123
|
+
{ key: "auto_guard.max_files", label: "Auto mode: stop above this many changed files", group: "Auto-fix", values: ["10", "25", "50", "0"], help: "0 turns the check off" },
|
|
124
|
+
{ key: "auto_guard.stop_on", label: "Auto mode: stop on an open finding at", group: "Auto-fix", values: ["critical", "high", "medium", "low", "off"], help: "" },
|
|
123
125
|
{ key: "git.auto_commit", label: "Commit when done", group: "Git", values: ["false", "true"], help: "Never pushes" },
|
|
124
126
|
{ key: "git.worktree_per_run", label: "Branch and folder per run", group: "Git", values: ["ask", "true", "false"], help: "" },
|
|
125
127
|
{ key: "git.generated", label: "Generated files", group: "Git", values: [], text: true, help: "Path patterns, space-separated. A land takes the base's side on conflict. Empty: none" },
|
package/cli/state.ts
CHANGED
|
@@ -2035,6 +2035,39 @@ function setStage(file: string, change: (s: any) => boolean): boolean {
|
|
|
2035
2035
|
return true;
|
|
2036
2036
|
} catch { return false; }
|
|
2037
2037
|
}
|
|
2038
|
+
// `kaizen state <id> key=value ...`: the one writer agents use for a run's state.json,
|
|
2039
|
+
// so stage and awaiting can only take the words every reader knows (spec.md, Stage 0).
|
|
2040
|
+
// `done` is refused: finishing goes through finishRun, which checks the review gate.
|
|
2041
|
+
const STAGES = ["plan", "build", "review", "abandoned"];
|
|
2042
|
+
const AWAITING = [null, "approvals.plan", "approvals.review", "approvals.each_file", "findings"];
|
|
2043
|
+
export function setRunState(state: string, id: string, pairs: string[]): string | null {
|
|
2044
|
+
const file = join(state, "runs", id, "state.json");
|
|
2045
|
+
if (!existsSync(file)) return `no run ${id} under ${state}`;
|
|
2046
|
+
if (!pairs.length) return "nothing to set: pass key=value";
|
|
2047
|
+
const set: Record<string, unknown> = {};
|
|
2048
|
+
for (const p of pairs) {
|
|
2049
|
+
const i = p.indexOf("=");
|
|
2050
|
+
if (i < 1) return `not key=value: ${p}`;
|
|
2051
|
+
const k = p.slice(0, i), raw = p.slice(i + 1);
|
|
2052
|
+
const v = raw === "null" ? null : raw;
|
|
2053
|
+
if (k === "id" || k === "updated") return `${k} is not set by hand`;
|
|
2054
|
+
if (k === "stage" && v === "done") return "stage done: use kaizen done <id>, which checks the final approval";
|
|
2055
|
+
if (k === "stage" && !STAGES.includes(String(v))) return `stage must be one of ${STAGES.join(", ")} (done: kaizen done)`;
|
|
2056
|
+
if (k === "awaiting" && !AWAITING.includes(v as any)) return `awaiting must be null or one of ${AWAITING.slice(1).join(", ")}`;
|
|
2057
|
+
if (k === "iteration") { if (!/^\d+$/.test(raw)) return "iteration must be a whole number"; set[k] = Number(raw); continue; }
|
|
2058
|
+
set[k] = v;
|
|
2059
|
+
}
|
|
2060
|
+
let now: any = null;
|
|
2061
|
+
if (!setStage(file, (s) => { Object.assign(s, set); now = s; return true; })) return `state.json for ${id} changed while writing or is not valid JSON; read it and retry`;
|
|
2062
|
+
if ("stage" in set || "awaiting" in set) logStage(state, id, now.stage, now.awaiting);
|
|
2063
|
+
return null;
|
|
2064
|
+
}
|
|
2065
|
+
// runs/<id>/stages.log: one line per stage or awaiting change, `<iso> <stage> <awaiting|->`.
|
|
2066
|
+
// File mtimes cannot time stages (02-approval.md gains its accepted line at done), so
|
|
2067
|
+
// `kaizen stats` reads this. Only writes through kaizen state / kaizen done are logged.
|
|
2068
|
+
export function logStage(state: string, id: string, stage: string, awaiting: string | null) {
|
|
2069
|
+
try { appendFileSync(join(state, "runs", id, "stages.log"), `${new Date().toISOString()} ${stage} ${awaiting ?? "-"}\n`); } catch { /* timing is best effort */ }
|
|
2070
|
+
}
|
|
2038
2071
|
// Rewrites runs an agent marked done without acceptance (gate on) to review /
|
|
2039
2072
|
// approvals.review; returns the ids. Not part of readRuns: reads stay pure (mtime is liveness).
|
|
2040
2073
|
export function healRuns(state: string): string[] {
|
|
@@ -2067,7 +2100,7 @@ export function finishRun(state: string, id: string, userApproved = false): stri
|
|
|
2067
2100
|
const why = recordAcceptance(state, id, "chat");
|
|
2068
2101
|
if (why) return why;
|
|
2069
2102
|
}
|
|
2070
|
-
setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; });
|
|
2103
|
+
if (setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; })) logStage(state, id, "done", null);
|
|
2071
2104
|
return null;
|
|
2072
2105
|
}
|
|
2073
2106
|
const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
|
package/cli/stats.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// `kaizen stats [<id>] [--json]` and `kaizen related <path...>`: read-only views over
|
|
2
|
+
// the files every run already writes. Nothing here writes, so old runs get stats too.
|
|
3
|
+
// Stage times come from runs/<id>/stages.log (written by kaizen state / kaizen done), not
|
|
4
|
+
// file mtimes: files are rewritten later in a run, so their times say nothing per stage.
|
|
5
|
+
// A run with no log (every run before it existed) shows "–".
|
|
6
|
+
import { readFileSync, readdirSync, statSync, existsSync, openSync, readSync, closeSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { changedPaths, projectOf } from "./state.ts";
|
|
10
|
+
import { trackOf } from "./knowledge.ts";
|
|
11
|
+
|
|
12
|
+
const read = (f: string) => { try { return readFileSync(f, "utf8"); } catch { return ""; } };
|
|
13
|
+
const mtime = (f: string) => { try { return statSync(f).mtimeMs; } catch { return 0; } };
|
|
14
|
+
|
|
15
|
+
export type RunStat = {
|
|
16
|
+
id: string; stage: string; track: string; runner: string; mode: string;
|
|
17
|
+
reviewed: boolean; fixed: boolean; unverified: boolean;
|
|
18
|
+
plan: number | null; wait: number | null; build: number | null; review: number | null;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export function runStat(state: string, id: string): RunStat | null {
|
|
22
|
+
const dir = join(state, "runs", id);
|
|
23
|
+
let s: any;
|
|
24
|
+
try { s = JSON.parse(read(join(dir, "state.json"))); } catch { return null; }
|
|
25
|
+
const t = (f: string) => mtime(join(dir, f));
|
|
26
|
+
let iters: string[] = [];
|
|
27
|
+
try { iters = readdirSync(join(dir, "05-iterations")); } catch { /* none */ }
|
|
28
|
+
return {
|
|
29
|
+
id, stage: String(s.stage ?? "?"), track: s.track ? trackOf(String(s.track)) : "?",
|
|
30
|
+
runner: String(s.runner ?? "?"), mode: String(s.mode ?? "?"),
|
|
31
|
+
reviewed: existsSync(join(dir, "04-review.md")),
|
|
32
|
+
fixed: iters.length > 0,
|
|
33
|
+
unverified: /CANNOT VERIFY/.test(read(join(dir, "04-review.md"))),
|
|
34
|
+
...stageTimes(read(join(dir, "stages.log")), t("00-request.md")),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Each interval between log lines is charged to the state at its start: waiting when
|
|
39
|
+
// awaiting is set, else the stage. The interval before the first line is planning,
|
|
40
|
+
// from the request's write (00-request.md is written once, at intake).
|
|
41
|
+
export function stageTimes(log: string, start: number) {
|
|
42
|
+
const out = { plan: null as number | null, wait: null as number | null, build: null as number | null, review: null as number | null };
|
|
43
|
+
const rows = log.split("\n").map((l) => l.trim().split(/\s+/)).filter((r) => r.length >= 3 && !isNaN(Date.parse(r[0]!)))
|
|
44
|
+
.map(([at, stage, awaiting]) => ({ at: Date.parse(at!), stage: stage!, waiting: awaiting !== "-" }));
|
|
45
|
+
if (!rows.length) return out;
|
|
46
|
+
// Only a log that starts at plan or build covers planning; one that starts later (the
|
|
47
|
+
// run began on an older kaizen, or by hand) has an unknown gap, left uncounted.
|
|
48
|
+
const lead = start && start <= rows[0]!.at && (rows[0]!.stage === "plan" || rows[0]!.stage === "build");
|
|
49
|
+
const seq = lead ? [{ at: start, stage: "plan", waiting: false }, ...rows] : rows;
|
|
50
|
+
for (let i = 0; i + 1 < seq.length; i++) {
|
|
51
|
+
const a = seq[i]!, d = seq[i + 1]!.at - a.at;
|
|
52
|
+
if (d < 0 || a.stage === "done" || a.stage === "abandoned") continue;
|
|
53
|
+
const k = a.waiting ? "wait" : (a.stage as keyof typeof out);
|
|
54
|
+
if (k in out) out[k] = (out[k] ?? 0) + d;
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function allStats(state: string): RunStat[] {
|
|
60
|
+
let ids: string[] = [];
|
|
61
|
+
try { ids = readdirSync(join(state, "runs")); } catch { return []; }
|
|
62
|
+
return ids.sort().map((id) => runStat(state, id)).filter((r): r is RunStat => !!r);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const median = (xs: number[]) => {
|
|
66
|
+
if (!xs.length) return null;
|
|
67
|
+
const s = [...xs].sort((a, b) => a - b), m = s.length >> 1;
|
|
68
|
+
return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
|
|
69
|
+
};
|
|
70
|
+
const count = (rs: RunStat[], k: keyof RunStat) => rs.reduce((o, r) => { const v = String(r[k]); o[v] = (o[v] ?? 0) + 1; return o; }, {} as Record<string, number>);
|
|
71
|
+
|
|
72
|
+
export function summary(rs: RunStat[]) {
|
|
73
|
+
const reviewed = rs.filter((r) => r.reviewed);
|
|
74
|
+
const med = (k: "plan" | "wait" | "build" | "review") => median(rs.map((r) => r[k]).filter((v): v is number => v !== null));
|
|
75
|
+
return {
|
|
76
|
+
runs: rs.length,
|
|
77
|
+
stage: count(rs, "stage"), track: count(rs, "track"), runner: count(rs, "runner"), mode: count(rs, "mode"),
|
|
78
|
+
reviewed: reviewed.length,
|
|
79
|
+
fixed: rs.filter((r) => r.fixed).length,
|
|
80
|
+
unverified: rs.filter((r) => r.unverified).length,
|
|
81
|
+
timed: rs.filter((r) => r.plan !== null || r.build !== null).length,
|
|
82
|
+
median: { plan: med("plan"), wait: med("wait"), build: med("build"), review: med("review") },
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Tokens a Claude run used, from its session log: `~/.claude/projects/*/<session>.jsonl`.
|
|
87
|
+
// One session can carry several runs, so only lines inside [from, to] count.
|
|
88
|
+
export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number; turns: number };
|
|
89
|
+
export function sessionLog(session: string, home = homedir()): string | null {
|
|
90
|
+
const root = join(home, ".claude", "projects");
|
|
91
|
+
let dirs: string[] = [];
|
|
92
|
+
try { dirs = readdirSync(root); } catch { return null; }
|
|
93
|
+
for (const d of dirs) { const f = join(root, d, `${session}.jsonl`); if (existsSync(f)) return f; }
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
export function tokensIn(file: string, from: number, to: number): Tokens {
|
|
97
|
+
const t: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
|
|
98
|
+
// Streamed in chunks: a long session log runs to hundreds of MB.
|
|
99
|
+
const fd = openSync(file, "r"), buf = Buffer.alloc(1 << 20);
|
|
100
|
+
let rest = "";
|
|
101
|
+
const line = (l: string) => {
|
|
102
|
+
if (!l.includes('"usage"')) return;
|
|
103
|
+
let j: any;
|
|
104
|
+
try { j = JSON.parse(l); } catch { return; }
|
|
105
|
+
const at = Date.parse(j.timestamp ?? ""), u = j.message?.usage;
|
|
106
|
+
if (!u || !(at >= from && at <= to)) return;
|
|
107
|
+
t.input += u.input_tokens ?? 0; t.output += u.output_tokens ?? 0;
|
|
108
|
+
t.cacheRead += u.cache_read_input_tokens ?? 0; t.cacheWrite += u.cache_creation_input_tokens ?? 0;
|
|
109
|
+
t.turns++;
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) {
|
|
113
|
+
const parts = (rest + buf.toString("utf8", 0, n)).split("\n");
|
|
114
|
+
rest = parts.pop()!;
|
|
115
|
+
parts.forEach(line);
|
|
116
|
+
}
|
|
117
|
+
line(rest);
|
|
118
|
+
} finally { closeSync(fd); }
|
|
119
|
+
return t;
|
|
120
|
+
}
|
|
121
|
+
export function runTokens(state: string, id: string, home = homedir()): Tokens | null {
|
|
122
|
+
const dir = join(state, "runs", id);
|
|
123
|
+
let s: any;
|
|
124
|
+
try { s = JSON.parse(read(join(dir, "state.json"))); } catch { return null; }
|
|
125
|
+
if (!s.session || (s.agent && s.agent !== "claude")) return null;
|
|
126
|
+
const log = sessionLog(String(s.session), home);
|
|
127
|
+
if (!log) return null;
|
|
128
|
+
const from = mtime(join(dir, "00-request.md")), to = Date.parse(s.updated ?? "") || mtime(join(dir, "state.json"));
|
|
129
|
+
return from ? tokensIn(log, from, to) : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Earlier runs whose report names any of these paths as changed, newest first.
|
|
133
|
+
export function related(state: string, paths: string[], limit = 5): { id: string; title: string; open: number }[] {
|
|
134
|
+
const want = new Set(paths.map((p) => p.replace(/^\.\//, "")));
|
|
135
|
+
const project = projectOf(state);
|
|
136
|
+
let ids: string[] = [];
|
|
137
|
+
try { ids = readdirSync(join(state, "runs")).sort().reverse(); } catch { return []; }
|
|
138
|
+
const out: { id: string; title: string; open: number }[] = [];
|
|
139
|
+
for (const id of ids) {
|
|
140
|
+
const dir = join(state, "runs", id), impl = read(join(dir, "03-impl.md"));
|
|
141
|
+
if (!impl || !changedPaths(impl, project).some((p) => want.has(p))) continue;
|
|
142
|
+
const title = read(join(dir, "00-request.md")).split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").slice(0, 90) ?? "";
|
|
143
|
+
const open = (read(join(dir, "06-backlog.md")).match(/^- open:/gm) ?? []).length;
|
|
144
|
+
out.push({ id, title, open });
|
|
145
|
+
if (out.length >= limit) break;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const dur = (ms: number | null) => ms === null ? "–" : ms < 3.6e6 ? `${Math.round(ms / 6e4)}m` : `${(ms / 3.6e6).toFixed(1)}h`;
|
|
151
|
+
const pct = (n: number, d: number) => (d ? `${Math.round((100 * n) / d)}%` : "–");
|
|
152
|
+
const kv = (o: Record<string, number>) => Object.entries(o).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`).join(", ");
|
|
153
|
+
|
|
154
|
+
export function statsText(state: string, id?: string, json = false): string {
|
|
155
|
+
if (id) {
|
|
156
|
+
const r = runStat(state, id);
|
|
157
|
+
if (!r) return `no run ${id}`;
|
|
158
|
+
const t = runTokens(state, id);
|
|
159
|
+
if (json) return JSON.stringify({ ...r, tokens: t }, null, 2);
|
|
160
|
+
const tok = t ? `${t.input + t.cacheWrite + t.cacheRead} in (${t.cacheRead} from cache), ${t.output} out, ${t.turns} turns` : "n/a";
|
|
161
|
+
return [`${r.id} ${r.stage} · ${r.track} · ${r.runner} · ${r.mode}`,
|
|
162
|
+
`plan ${dur(r.plan)} · waiting for approval ${dur(r.wait)} · build ${dur(r.build)} · review ${dur(r.review)} (from stages.log)`,
|
|
163
|
+
`fix round: ${r.fixed ? "yes" : "no"} · CANNOT VERIFY: ${r.unverified ? "yes" : "no"}`,
|
|
164
|
+
`tokens: ${tok}`].join("\n");
|
|
165
|
+
}
|
|
166
|
+
const s = summary(allStats(state));
|
|
167
|
+
if (json) return JSON.stringify(s, null, 2);
|
|
168
|
+
return [`${s.runs} runs — ${kv(s.stage)}`,
|
|
169
|
+
`track: ${kv(s.track)}`, `runner: ${kv(s.runner)} · mode: ${kv(s.mode)}`,
|
|
170
|
+
`fix round: ${s.fixed} of ${s.reviewed} reviewed (${pct(s.fixed, s.reviewed)}) · CANNOT VERIFY in ${s.unverified} reviews (${pct(s.unverified, s.reviewed)})`,
|
|
171
|
+
`median: plan ${dur(s.median.plan)} · waiting for approval ${dur(s.median.wait)} · build ${dur(s.median.build)} · review ${dur(s.median.review)} (runs with a stages.log: ${s.timed})`].join("\n");
|
|
172
|
+
}
|
package/package.json
CHANGED
package/skills/kaizen/SKILL.md
CHANGED
|
@@ -110,9 +110,8 @@ A tool that charges the same for a typo and a payroll change gets turned off for
|
|
|
110
110
|
files or fifty lines, run the stages in this session (`runner: lite`, below)
|
|
111
111
|
rather than dispatching them. Keep the plan and review brief, then apply the same
|
|
112
112
|
bounded fix loop to review findings. Small size does not leave a finding for a later
|
|
113
|
-
run when it can be fixed within this one.
|
|
114
|
-
|
|
115
|
-
**Short work still gets a run.** A one-line change is not skipped past the stages: the card on the board moves through plan, build and review like any other. Run it with `runner: lite` and the short path above — a brief plan, the build, a short review — so the cost stays small and the run stays visible.
|
|
113
|
+
run when it can be fixed within this one. Even a one-line change gets a run this way,
|
|
114
|
+
so its card still moves through plan, build and review.
|
|
116
115
|
|
|
117
116
|
This is a judgement, not a threshold to enforce: fifty lines that change how money is
|
|
118
117
|
rounded are not a small change. Say which path you took (short or full) and why, in one line, when the
|
|
@@ -128,7 +127,8 @@ Set by `mode` in config, overridable per invocation.
|
|
|
128
127
|
- **`approve`** (default) — stop at every approval enabled in config and wait for an
|
|
129
128
|
explicit human decision.
|
|
130
129
|
- **`auto`** — run every stage back to back with no approval, report at the end. The fix
|
|
131
|
-
loop still respects `max_iterations
|
|
130
|
+
loop still respects `max_iterations`, and `auto_guard` stops a run that changed too
|
|
131
|
+
many files or kept a serious finding (*Auto guard* in `spec-main.md`).
|
|
132
132
|
- **`review-only`** — skip plan and implementation, run the reviewer against existing
|
|
133
133
|
code or a diff.
|
|
134
134
|
|
|
@@ -247,19 +247,13 @@ final report, so nobody reads a same-session review as an independent one.
|
|
|
247
247
|
|
|
248
248
|
## Running a stage
|
|
249
249
|
|
|
250
|
-
**
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
only its declared inputs, write its artifact before moving on, and when reviewing,
|
|
254
|
-
judge the work on its own terms rather than defending the reasoning you used writing
|
|
255
|
-
it. Everything else in this file holds unchanged.
|
|
256
|
-
|
|
257
|
-
**Check `runner` first.**
|
|
250
|
+
**Check `runner` first.** A tool with no subagents (Codex, anything that runs one
|
|
251
|
+
session at a time) runs as `lite` whatever the setting, following
|
|
252
|
+
[`adapters.md`](adapters.md); do not fake subagents.
|
|
258
253
|
|
|
259
|
-
- `runner: lite` — do not call the Agent tool, except for the review as below. You run
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
agent for every row.
|
|
254
|
+
- `runner: lite` — do not call the Agent tool, except for the review as below. You run
|
|
255
|
+
plan, build and review yourself, as *Who runs the stages* says; the stage table below
|
|
256
|
+
still applies, and you are the agent for every row.
|
|
263
257
|
Read `spec-build.md` before building and `spec-main.md` before moving the run to
|
|
264
258
|
`review`: being the main thread does not excuse a stage its contract. Its *Preview
|
|
265
259
|
gate* holds in full — a result that shows on a screen needs a real screenshot under
|
|
@@ -296,7 +290,7 @@ knob: when it is not `inherit`, make sure the frontmatter of the agent's definit
|
|
|
296
290
|
carries `effort: <value>` — edit or add that one line, nothing else — before the
|
|
297
291
|
first dispatch of the run. `inherit` means leave the file alone.
|
|
298
292
|
|
|
299
|
-
After a subagent returns, update `state.json` yourself in the main thread. Subagents
|
|
293
|
+
After a subagent returns, update `state.json` yourself in the main thread, with `kaizen state` from 1.69.0, by hand before that (`spec.md`, Stage 0). Subagents
|
|
300
294
|
report; the main thread owns the state machine.
|
|
301
295
|
Before moving any run from `build` to `review`, under either runner, apply the
|
|
302
296
|
*Preview gate* in [`spec-main.md`](spec-main.md): no `## Preview` with a screenshot
|
|
@@ -351,28 +345,10 @@ shown automatically.
|
|
|
351
345
|
state.json
|
|
352
346
|
```
|
|
353
347
|
|
|
354
|
-
`state.json` is the resume point
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
```json
|
|
359
|
-
{
|
|
360
|
-
"id": "2026-09-02-add-oauth",
|
|
361
|
-
"mode": "approve",
|
|
362
|
-
"runner": "full",
|
|
363
|
-
"agent": "claude",
|
|
364
|
-
"stage": "review",
|
|
365
|
-
"awaiting": "approvals.review",
|
|
366
|
-
"iteration": 1,
|
|
367
|
-
"updated": "2026-09-02T14:31:00+07:00"
|
|
368
|
-
}
|
|
369
|
-
```
|
|
370
|
-
|
|
371
|
-
Every run writes all nine keys, from intake on: `id`, `mode`, `runner`, `agent`,
|
|
372
|
-
`track`, `stage`, `awaiting`, `iteration` (0 until the fix loop runs), `updated`. Where
|
|
373
|
-
the environment has `CLAUDE_CODE_SESSION_ID`, also `session` with its value: without it
|
|
374
|
-
a card launched from the board can stay stuck in planning beside its own run. The
|
|
375
|
-
legal values of `stage` and `awaiting` are in [`spec.md`](spec.md).
|
|
348
|
+
`state.json` is the resume point. Its keys (all nine from intake on, plus `session`
|
|
349
|
+
where `CLAUDE_CODE_SESSION_ID` is set, and `review_executor` on a lite run), their legal
|
|
350
|
+
values, and why `runner` and `agent` are frozen at intake are in *Stage 0* of
|
|
351
|
+
[`spec.md`](spec.md), with when to write it through `kaizen state` (1.69.0 and later) and when by hand.
|
|
376
352
|
|
|
377
353
|
In a git repository, `init` also adds a gitignore entry that ignores run state but
|
|
378
354
|
keeps the workflow: it ignores `.kaizen/*` and un-ignores `.kaizen/spec*.md` and
|
|
@@ -62,6 +62,16 @@ auto_fix:
|
|
|
62
62
|
# knob in the file. A third round rarely closes what two could not.
|
|
63
63
|
max_iterations: 2
|
|
64
64
|
|
|
65
|
+
# Stops for auto mode only (mode: auto); approve mode already stops at every approval.
|
|
66
|
+
# Auto runs every stage back to back, so these are what bring a runaway run back to you:
|
|
67
|
+
# the run stops at the final approval with the reason instead of finishing.
|
|
68
|
+
auto_guard:
|
|
69
|
+
# Stop when the build changed more files than this. 0 turns this check off.
|
|
70
|
+
max_files: 25
|
|
71
|
+
# Stop when a finding at or above this severity is still open after the fix loop.
|
|
72
|
+
# critical | high | medium | low | off
|
|
73
|
+
stop_on: high
|
|
74
|
+
|
|
65
75
|
review:
|
|
66
76
|
# Who reviews a lite run. Only read when runner is lite; under full the reviewer is
|
|
67
77
|
# always its own agent.
|
|
@@ -209,6 +209,12 @@ be run, opened, or read by someone, doing so is part of building it: the suite r
|
|
|
209
209
|
the page opened and clicked, the runbook walked start to finish, the copy read aloud.
|
|
210
210
|
A gate item whose evidence is an argument that the code should work is a `FAIL`.
|
|
211
211
|
|
|
212
|
+
Then check the request itself, as the reviewer will: each requirement in the verbatim
|
|
213
|
+
request and its *done* and *wrong* lines in `00-request.md` that no `G-nn` covers gets a
|
|
214
|
+
line `R PASS: <what was tried and what came back>` or `R FAIL: <what>`. The reviewer
|
|
215
|
+
writes its own criteria cold and trusts none of these; they exist so a gap the plan
|
|
216
|
+
missed is found here instead of costing a fix round.
|
|
217
|
+
|
|
212
218
|
The stage does not hand off with a `FAIL` standing. Fix it and re-run the gate, or —
|
|
213
219
|
if it cannot be fixed inside the plan's scope — stop and report, exactly as with an
|
|
214
220
|
impossible step. A `FAIL` carried into review wastes the reviewer's pass on something
|
|
@@ -153,6 +153,18 @@ whose changes leave every note true touches nothing and says so in one line.
|
|
|
153
153
|
|
|
154
154
|
---
|
|
155
155
|
|
|
156
|
+
## Auto guard
|
|
157
|
+
|
|
158
|
+
Only in `auto` mode. After the fix loop ends and before the final approval, check
|
|
159
|
+
`auto_guard` from config: the build changed more files than `max_files` (count the
|
|
160
|
+
changed paths `03-impl.md` names; `0` turns this off), or a finding at or above
|
|
161
|
+
`stop_on` is still open (`off` turns this off). Either way, stop: `kaizen state <id>
|
|
162
|
+
awaiting=approvals.review` (by hand before 1.69.0), and tell the user in one line which
|
|
163
|
+
check fired. The run then waits for an explicit accept as in *Final approval*, even with
|
|
164
|
+
`auto_accept` on. Neither check fires in `approve` mode, which already stops.
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
156
168
|
## Final approval
|
|
157
169
|
|
|
158
170
|
Controlled by `approvals.review`. `auto` skips every stop before it, not this one, unless `auto_accept` is on.
|
|
@@ -14,7 +14,10 @@ notes it lists for areas the request touches — the output of
|
|
|
14
14
|
`kaizen recall --track <track> --tags <stack tags> --query "<words from the request>"`
|
|
15
15
|
— past experience from other projects, to verify against this one, never binding
|
|
16
16
|
like project rules; the Framing ends with `Recalled: <n> lessons; used: <the lines it
|
|
17
|
-
relied on>` or `Recalled: none` —
|
|
17
|
+
relied on>` or `Recalled: none` — the output of `kaizen related <the File manifest's
|
|
18
|
+
paths>` (1.69.0 and later): earlier runs that changed those files, whose plans, findings
|
|
19
|
+
and open backlog may bear on this one; the Framing adds `Related: <ids it used>` or
|
|
20
|
+
`Related: none` — and the existing material —
|
|
18
21
|
the codebase, the manuscript, the current campaign, whatever this run builds on.
|
|
19
22
|
**Output:** `01-plan.md`.
|
|
20
23
|
|
|
@@ -207,6 +210,13 @@ The planner reads code but writes none. Its plan must contain:
|
|
|
207
210
|
Reviewer severity `medium`.
|
|
208
211
|
- **lock** — consistency with what is already there. Reviewer severity `low`.
|
|
209
212
|
|
|
213
|
+
End every item with `— proof: <how>`: the test or command to run, the screenshot to
|
|
214
|
+
take, the source to check a claim against, the person who reads it. The builder
|
|
215
|
+
produces that proof and the reviewer re-runs it, so a check nobody can run is found
|
|
216
|
+
at the approval rather than as `CANNOT VERIFY` after the build. Where the only proof
|
|
217
|
+
needs something no agent has (a live account, a real device, taste), say so in the
|
|
218
|
+
proof: it is a human check from the start.
|
|
219
|
+
|
|
210
220
|
Phrase every item so the answer is yes or no. "Handles errors well" is not a gate
|
|
211
221
|
item; "every new query path has a covering test" is. A tier fixes the severity
|
|
212
222
|
before the reviewer has an opinion, which is what stops the same class of problem
|
|
@@ -111,6 +111,10 @@ G-02 FAIL: see finding 3
|
|
|
111
111
|
R-01 CANNOT VERIFY: needs a live Stripe account; the test-mode fixture skips webhooks. Human: refund one real charge and confirm the ledger row.
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
+
A `G-nn` item's `— proof:` is the first check to run. `CANNOT VERIFY` on an item
|
|
115
|
+
whose proof the reviewer could run is not an answer: run it. Where the plan already
|
|
116
|
+
marked the proof a human check, `CANNOT VERIFY` is expected and names that check.
|
|
117
|
+
|
|
114
118
|
`CANNOT VERIFY` is for a check that needs something the reviewer does not have —
|
|
115
119
|
taste, a live account or device, a real reader, production data, a person's decision.
|
|
116
120
|
It states what was tried, why that does not settle it, and exactly what a human must
|
|
@@ -132,7 +136,10 @@ human check never reads as a clean pass.
|
|
|
132
136
|
Where `review.write_memory` is true (the default), the reviewer also appends any
|
|
133
137
|
durable lesson about this material to `memory.md` —
|
|
134
138
|
a recurring bug pattern, a non-obvious constraint, a convention worth keeping. Not
|
|
135
|
-
run-specific detail; only what the next run would want to know.
|
|
139
|
+
run-specific detail; only what the next run would want to know. Where the state
|
|
140
|
+
directory has `notes/Project/Index.md`, a lesson about one area's files goes to that
|
|
141
|
+
area's note under `## Watch out` instead, since planners open only the notes for the
|
|
142
|
+
areas they touch; `memory.md` keeps the lessons that hold across the project.
|
|
136
143
|
|
|
137
144
|
`memory.md` is read by every stage of every future run, so its size is a tax on all of
|
|
138
145
|
them. Keep it under `review.memory_max_lines` (default 100): before appending, drop
|
package/skills/kaizen/spec.md
CHANGED
|
@@ -73,7 +73,9 @@ connected in the session: cite what it returns, limitations included. When they
|
|
|
73
73
|
not connected, say the claim is unverified rather than guess at internals.
|
|
74
74
|
|
|
75
75
|
Record the track in `state.json` as `track`, with the three answers written into
|
|
76
|
-
`00-request.md`.
|
|
76
|
+
`00-request.md`. The description stays free; the stored `track` word is the nearest of
|
|
77
|
+
`code`, `writing`, `communication`, `operations`, `research`, or a new word where none
|
|
78
|
+
fits (a mix joined with `+`), because `kaizen recall --track` looks lessons up by it. Every subsequent stage reads them before starting, and the words
|
|
77
79
|
*build*, *verify*, and *finding* below are always to be read in the track's terms.
|
|
78
80
|
|
|
79
81
|
---
|
|
@@ -123,6 +125,12 @@ is building and a recheck is reviewing, whoever runs them and whether the loop o
|
|
|
123
125
|
user picked the findings: `build` with `iteration` raised and `awaiting: null` before
|
|
124
126
|
each iteration's first edit, `review` before its recheck reads. Any other word
|
|
125
127
|
(`implement`, `fix`, `building`) is unknown to every reader and shows as still planning.
|
|
128
|
+
After intake, where `kaizen --version` prints 1.69.0 or later, write these keys with
|
|
129
|
+
`kaizen state <id> stage=build awaiting=null` (`iteration=<n>` likewise): one atomic
|
|
130
|
+
write that refuses unknown words and stamps `updated`. An older `kaizen` reads `state`
|
|
131
|
+
as a plain `kaizen` call and starts the installer, so there, and where no `kaizen` is
|
|
132
|
+
installed, edit `state.json` by hand in its two-space JSON layout. Finish with
|
|
133
|
+
`kaizen done <id>` either way.
|
|
126
134
|
|
|
127
135
|
`awaiting` is `null` or the config key of the approval being waited on —
|
|
128
136
|
`approvals.plan`, `approvals.review`, `approvals.each_file` — or `findings` when the
|
|
@@ -28,6 +28,9 @@ anything.
|
|
|
28
28
|
| `/kaizen review [target]` | Review-only: audit existing code, no plan, no implementation |
|
|
29
29
|
| `/kaizen status` | List every run grouped waiting-on-you / in flight / done / abandoned, plus open backlog count |
|
|
30
30
|
| `kaizen done <id> [--user-approved]` | Finish a run; refused while the review gate waits on the user, `--user-approved` after a clear yes in chat |
|
|
31
|
+
| `kaizen state <id> key=value ...` | (1.69.0+) Set a run's `stage`, `awaiting` or `iteration` in `state.json`; refuses words no board knows (`done` goes through `kaizen done`) |
|
|
32
|
+
| `kaizen stats [<id>] [--json]` | (1.69.0+) Fix-round and CANNOT VERIFY rates, stage times, tokens for one run |
|
|
33
|
+
| `kaizen related <path> ...` | (1.69.0+) Earlier runs that changed these files |
|
|
31
34
|
| `/kaizen backlog` | Print open backlog items across all runs, grouped by source run, rescued items last under `Orphaned` |
|
|
32
35
|
| `/kaizen gather` | Read request sources kaizen cannot read by itself; their requests land in the icebox, nothing starts |
|
|
33
36
|
| `/kaizen discover` | Group what is in the icebox and promote the tasks you pick; nothing starts |
|
|
@@ -38,6 +38,7 @@ const PLACES: [RegExp, string, string][] = [
|
|
|
38
38
|
[/^sources\./, "integrations", "Request sources"],
|
|
39
39
|
[/^(mode|approvals\.|auto_accept)/, "approvals", "Approvals"],
|
|
40
40
|
[/^auto_fix\./, "autofix", "Auto-fix"],
|
|
41
|
+
[/^auto_guard\./, "autofix", "Auto mode guard"],
|
|
41
42
|
[/^git\./, "git", "Git"],
|
|
42
43
|
[/^ui\./, "terminal", "Terminal"],
|
|
43
44
|
[/^board\.chat_hotkey$/, "shortcuts", "Shortcuts"],
|
package/web/board.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen board
|
|
1
|
+
/* kaizen board 523b24f53b2cdc30 -- generated by bun run build:web from web/board/main.ts; do not edit */
|
|
2
2
|
(()=>{var m={S:{project:null,projects:[],cards:[],now:Date.now(),all:!1,dir:null},all:new URLSearchParams(location.search).get("all")!=="0",dir:null,openKey:null,mode:null,modeKey:null,menuKey:null,flash:new Set,tab:"request",lastTab:"request",runDoc:null,clearMenu:!1,sevMenu:!1,wantTerm:null,wantPty:null,shells:[],setQ:"",setScope:"all",setPage:null,setBack:!1,pageGen:0,PL:[],shown:new Set((()=>{try{return JSON.parse(localStorage.getItem("kz-show"))||[]}catch(e){return[]}})())};var r=(e)=>document.getElementById(e),yn=(e)=>String(e).replace(/[&<>"]/g,(t)=>({"&":"&","<":"<",">":">",'"':"""})[t]);class xa{s;constructor(e){this.s=e}toString(){return this.s}}var j=(e)=>new xa(String(e)),Dr=(e)=>e instanceof xa?e.s:Array.isArray(e)?e.map(Dr).join(""):e==null||e===!1?"":yn(e),l=(e,...t)=>j(e.reduce((n,s,o)=>n+Dr(t[o-1])+s)),A=(e)=>j(`<svg><use href="#i-${e}"/></svg>`),Rr=j('<div aria-busy="true" aria-label="Loading"><span class="skel" style="height:16px;width:35%;margin:20px 0 14px"></span>'+'<span class="skel" style="height:44px;margin-bottom:10px"></span>'.repeat(4)+"</div>"),ju=1500000;async function Du(e){if(e.size<=ju||!/^image\/(jpeg|png|webp|bmp|heic|heif)$/.test(e.type))return e;try{let t=await createImageBitmap(e),n=Math.min(1,2560/Math.max(t.width,t.height)),s=document.createElement("canvas");s.width=Math.round(t.width*n),s.height=Math.round(t.height*n),s.getContext("2d").drawImage(t,0,0,s.width,s.height);let o=await new Promise((a)=>s.toBlob(a,"image/jpeg",0.85));return o&&o.size<e.size?new File([o],e.name.replace(/\.\w+$/,"")+".jpg",{type:"image/jpeg"}):e}catch{return e}}var wn=(e)=>Promise.all(e.map(async(t)=>{let n=await Du(t);return new Promise((s)=>{let o=new FileReader;o.onload=()=>s({name:n.name,data:o.result}),o.readAsDataURL(n)})}));function et(e){let t=document.createElement("dialog");return t.className="kz",t.innerHTML=`<form class="inl" method="dialog">${e}</form>`,t.onclose=()=>t.remove(),t.onclick=(n)=>{if(n.target===t)t.close()},document.body.appendChild(t),t.showModal(),t}var ks=()=>{let e=document.documentElement.dataset.motion;return e?e==="full":!matchMedia("(prefers-reduced-motion: reduce)").matches},gt=(e)=>ks()&&document.startViewTransition?document.startViewTransition(e).updateCallbackDone:(e(),Promise.resolve()),Sa=[5,25,50,100];function lo(e){let t=25;try{let n=Number(localStorage.getItem("kz-page:"+e));if(Sa.includes(n))t=n}catch{}return{id:e,size:t,at:0,total:0}}function co(e,t){return e.total=t.length,e.at=Math.max(0,Math.min(e.at,Math.ceil(t.length/e.size)-1)),t.slice(e.at*e.size,(e.at+1)*e.size)}function uo(e){if(e.total<=Sa[0])return"";let t=e.at*e.size+1,n=Math.min(e.total,t+e.size-1);return l`<div class="kpager" id="pg-${e.id}"><label>Rows<select class="sel" aria-label="Rows per page">${Sa.map((s)=>l`<option${s===e.size?j(" selected"):""}>${s}</option>`)}</select></label><span>${t}–${n} of ${e.total}</span><button class="btn sm" type="button" data-to="-1"${e.at?"":j(" disabled")}>Prev</button><button class="btn sm" type="button" data-to="1"${n<e.total?"":j(" disabled")}>Next</button></div>`}function po(e,t){let n=r("pg-"+e.id);if(!n)return;n.querySelector("select").onchange=(s)=>{e.size=+s.target.value,e.at=0;try{localStorage.setItem("kz-page:"+e.id,String(e.size))}catch{}t()},n.querySelectorAll("[data-to]").forEach((s)=>s.onclick=()=>{e.at+=+s.dataset.to,t()})}var Nr="kz-mic",Aa=()=>{try{return localStorage.getItem(Nr)||""}catch{return""}},Pr=(e="")=>({channelCount:1,noiseSuppression:!0,echoCancellation:!0,...e?{deviceId:{exact:e}}:{}});async function Ir(e,t,n){try{return await e(Pr(t))}catch(s){if(!t||s?.name!=="OverconstrainedError")throw s;return n("Chosen microphone not found. Using the default"),e(Pr())}}var Or=()=>l`<select class="sel" id="v-mic" aria-labelledby="v-mic-l"><option value="">System default</option></select>`;async function zr(){let e=r("v-mic");if(!e||!navigator.mediaDevices?.enumerateDevices)return;let t=Aa(),n=(await navigator.mediaDevices.enumerateDevices().catch(()=>[])).filter((s)=>s.kind==="audioinput"&&s.deviceId&&s.deviceId!=="default");e.innerHTML=l`<option value="">System default</option>${n.map((s,o)=>l`<option value="${s.deviceId}">${s.label||`Microphone ${o+1}`}</option>`)}`.s,e.value=n.some((s)=>s.deviceId===t)?t:"",e.onchange=()=>{try{localStorage.setItem(Nr,e.value)}catch{}}}var Br;function L(e,t){let n=r("toast");if(n.textContent=e,n.classList.toggle("rep",!!t),t){let s=document.createElement("a");s.href="/issue?"+new URLSearchParams(t),s.target="_blank",s.rel="noopener",s.textContent="Report",n.append(" ",s)}n.classList.add("on"),clearTimeout(Br),Br=setTimeout(()=>n.classList.remove("on"),t?8000:4000)}function Ct(){try{if(typeof Notification<"u"&&Notification.permission==="default")Notification.requestPermission()}catch(e){}}var Ur=(e,t)=>{try{return localStorage.getItem(e)||t}catch(n){return t}},mo=()=>Ur("kz-notify","on")==="on",Bn=()=>Ur("kz-sound","Bellatrix"),Wr=["Adara","Alya","Bellatrix","Beryllium","Cobalt","Fluorine","Krypton","Palladium","Rubidium","Xenon"],fo=["off",...Wr,"chime","bell","pop"],Kr={chime:[[880,0,0.25],[1320,0.12,0.35]],bell:[[660,0,0.9]],pop:[[520,0,0.08]]},bt;function $s(e=Bn()){try{if(Wr.includes(e)){let n=new Audio(`/sounds/${e}.mp3`);n.volume=0.35,n.play().catch(()=>{});return}if(!Kr[e])return;bt=bt||new AudioContext,bt.resume();let t=bt.currentTime+0.02;for(let[n,s,o]of Kr[e]){let a=bt.createOscillator(),i=bt.createGain();a.type=e==="pop"?"triangle":"sine",a.frequency.value=n,i.gain.setValueAtTime(0.0001,t+s),i.gain.exponentialRampToValueAtTime(0.25,t+s+0.01),i.gain.exponentialRampToValueAtTime(0.0001,t+s+o),a.connect(i).connect(bt.destination),a.start(t+s),a.stop(t+s+o+0.05)}}catch(t){}}addEventListener("pointerdown",()=>{try{bt=bt||new AudioContext,bt.resume()}catch(e){}},{once:!0});function Ea(e,t){if(!mo())return;$s();try{if(typeof Notification<"u"&&Notification.permission==="granted")new Notification("kaizen",{body:e,icon:"/logo.png",tag:t})}catch(n){}}var Ru="https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.0",Gr={tiny:"onnx-community/whisper-tiny",base:"onnx-community/whisper-base",small:"onnx-community/whisper-small","large-v3-turbo":"onnx-community/whisper-large-v3-turbo"},La=null,Pu=`import{pipeline}from"${Ru}";let asr=null;
|
|
3
3
|
onmessage=async e=>{const m=e.data;try{
|
|
4
4
|
if(m.type==="load"){const prog=p=>{if(p.status==="progress")postMessage({type:"progress",file:p.file,pct:p.progress||0})};
|
|
@@ -119,7 +119,7 @@ dialog.gs::backdrop{background:rgb(0 0 0/.35)}
|
|
|
119
119
|
<div class="sk-a">${e.agents.map((t)=>l`<img class="sk-ag${t.state==="installed"?"":" off"}" src="${dt[zp[t.agent]??""]??""}" width="18" height="18" alt="${t.agent}: ${bc[t.state]??t.state}" title="${t.agent}: ${bc[t.state]??t.state}">`)}${e.needs.map((t)=>l`<span class="${t.found?"":"miss"}">Needs ${t.name}${t.found?"":" (not found)"}</span>`)}${e.note?l`<span>${e.note}</span>`:""}</div>
|
|
120
120
|
</div>`,yc=(e)=>l`${Op.filter(([t])=>e.some((n)=>n.group===t)).map(([t,n],s)=>l`<h3 class="sg">${n}${s?"":l` <button type="button" id="sk-recheck">Re-check</button>`}</h3><div class="sgrp">${e.filter((o)=>o.group===t).map(Wp)}</div>`)}`;function wc(e,t=""){let n=r("sk-recheck");if(n)n.onclick=()=>e();r("pbody").querySelectorAll("[data-skill]").forEach((s)=>s.onclick=async()=>{let o=s.dataset.on==="true",a=o&&s.dataset.warn==="true";if(a&&!confirm(`Let agents read and operate the apps on your desktop?
|
|
121
121
|
|
|
122
|
-
They see the window text of the apps they open and can click, set values and type in them, as you. A password manager is blocked by its name only, so one inside a browser or under another name is not. Any other open app is in reach. Turn on?`))return;let i=await R("/skills",{id:s.dataset.skill,on:o,...a?{confirm:!0,token:t}:{}});L(i.error?i.error:"Saved. Applies to new sessions"),await e()})}var vc="https://tailscale.com/download";async function si(e){try{return await(await fetch("/phone/setup",e?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}:void 0)).json()}catch{return{error:"The board did not answer."}}}var jo=(e,t,n=!1)=>l`<button type="button" class="btn${n?" pri":""}" data-ph="${e}">${t}</button>`,kc=(e)=>l`<ol class="ph-steps">${e.map((t)=>l`<li>${t}</li>`)}</ol>`;function Gp(e,t,n){let s=t?l`<p class="ph-err" role="alert">${t}</p>`:"",o=e.account?l`<b>${e.account}</b>`:"the same account";if(e.state==="missing")return l`<p>Your phone reaches this computer through Tailscale, a free private network between your own devices.</p>${kc(["Install Tailscale on this computer and log in.","Install it on your phone too and log in with the same account."])}<div class="ph-row"><a class="btn pri" href="${vc}" target="_blank" rel="noopener">Install Tailscale</a>${jo("check","Check again")}</div>${s}`;if(e.state==="login")return l`<p>Tailscale is installed but not logged in on this computer.</p><div class="ph-row">${jo("login",n?"Opening…":"Log in to Tailscale",!0)}${jo("check","Check again")}</div>${s}`;if(e.state==="ready")return l`<p>Tailscale is running${e.account?l` as ${o}`:""}. Connect to show the code your phone scans.</p><div class="ph-row">${jo("connect",n?"Connecting…":"Connect phone",!0)}</div>${s}`;let a=e.phones.some((i)=>i.online);return l`<div class="ph-on">${e.qr?l`<div class="ph-qr" aria-label="QR code for ${e.url}">${j(e.qr)}</div>`:""}<div><p class="ph-h">On your phone</p>${kc([l`Install Tailscale from the <a href="${vc}" target="_blank" rel="noopener">App Store or Play Store</a>.`,e.account?l`Log in with ${o}, the account this computer uses.`:"Log in with the same account as this computer.",l`Scan this code with the camera, or open <a href="${e.url}" target="_blank" rel="noopener">${e.url}</a>.`,"Choose Add to Home screen so it opens like an app."])}<p class="ph-st"><i class="ph-dot${a?" on":""}"></i>${a?`Phone online: ${e.phones.filter((i)=>i.online).map((i)=>i.name).join(", ")}`:e.phones.length?"Phone on your tailnet, offline right now":"No phone on your tailnet yet"}</p></div></div><p class="ph-note">Anyone on your tailnet can use this board. Keep the tailnet to your own devices, or limit it with Tailscale access rules.</p>${s}`}async function Do(e){let t=null,n="",s=!1,o=()=>{if(t)e.innerHTML=String(Gp(t,n,s))},a=async()=>{let c=await si();if(c.error)n=c.error;else t=c;o()};e.innerHTML='<p class="ph-wait">Checking Tailscale…</p>',e.onclick=async(c)=>{let d=c.target.closest("[data-ph]")?.dataset.ph;if(!d||s)return;if(n="",d==="check")return a();s=!0,o();let u=await si({do:d});if(s=!1,u.error)n=u.error;else if(d==="login"){if(u.url)window.open(u.url,"_blank","noopener");for(let h=0;h<40&&e.isConnected&&t?.state==="login";h++){await new Promise((f)=>setTimeout(f,3000));let y=await si();if(!y.error)t=y}}else t=u;o()},await a();let i=setInterval(()=>e.isConnected?t?.state==="connected"&&!s&&void a():clearInterval(i),1e4)}var oi=[["AI Capabilities",[{id:"agents",title:"Agents",desc:"Manage AI agents, set a default, and customize commands.",ico:"ai"},{id:"accounts",title:"AI Provider Accounts",desc:"Optional. Your normal logins keep working; add accounts only to switch between them.",ico:"link"},{id:"orchestration",title:"Orchestration",desc:"Split a run into workers, each in its own terminal. Off by default.",ico:"ai"},{id:"skills",title:"Skills",desc:"What your agents can do. Changes apply to new sessions.",ico:"note"},{id:"voice",title:"Voice",desc:"Speech-to-text dictation, run in the browser.",ico:"mic"}]],["Set Up",[{id:"general",title:"General",desc:"Which settings you are editing, folders, and maintenance.",ico:"gear"},{id:"integrations",title:"Integrations",desc:"Request sources and your Google account.",ico:"link"},{id:"mobile",title:"Mobile",desc:"Open kaizen from your phone.",ico:"send"}]],["Workflows",[{id:"approvals",title:"Approvals",desc:"Where a run stops and waits for you.",ico:"check"},{id:"autofix",title:"Auto-fix",desc:"What happens to review findings.",ico:"bug"},{id:"automations",title:"Automations",desc:"Schedules that start a run in this project.",ico:"clock"},{id:"git",title:"Git & Source Control",desc:"Branches and commits for each run.",ico:"pen"},{id:"terminal",title:"Terminal",desc:"The terminal dashboard.",ico:"term"}]],["Interface",[{id:"appearance",title:"Appearance",desc:"Theme, color and motion in this browser.",ico:"note"},{id:"notifications",title:"Notifications",desc:"Notices and sounds in this browser.",ico:"clock"},{id:"shortcuts",title:"Shortcuts",desc:"Keyboard shortcuts for common actions.",ico:"kbd"}]]],Fp=[[/^(preset|runner|build\.|review\.executor)/,"agents","Workflow"],[/^(subagents\.|agent\.model\.)/,"agents","Models"],[/^agent\.default$/,"agents","Default agent"],[/^agent\./,"agents","Running agents"],[/^orchestration\./,"orchestration","Workers"],[/^dictation\./,"voice","Dictation"],[/^sources\./,"integrations","Request sources"],[/^(mode|approvals\.|auto_accept)/,"approvals","Approvals"],[/^auto_fix\./,"autofix","Auto-fix"],[/^git\./,"git","Git"],[/^ui\./,"terminal","Terminal"],[/^board\.chat_hotkey$/,"shortcuts","Shortcuts"],[/^board\./,"general","App"],[/^(review\.|state\.)/,"general","Project"]],$c=(e)=>{let t=Fp.find(([n])=>n.test(e));return t?[t[1],t[2]]:["general","Other"]};var ye=null,Jn=null,Yn=globalThis.kaizenDesktop,Cn=Yn?"Kaizen":"kaizen",xc=(e)=>Yn?Yn.check():fetch(e?"/version?fresh=1":"/version").then((t)=>t.json());function Ac(e){Jn=e,ye=e.update?e:null;let t=document.querySelector('.rail a[data-view="settings"]');return t.classList.toggle("upd",!!ye),t.title=ye?`Settings: ${Cn} ${e.latest} is available`:"Settings",!!ye}function ai(){let e=document.createElement("div");if(e.className=`updbar${ye?"":" quiet"}`,!ye)e.innerHTML=l`<span id="upd-msg" aria-live="polite">${Jn?`${Cn} ${Jn.version}`:Cn}</span
|
|
122
|
+
They see the window text of the apps they open and can click, set values and type in them, as you. A password manager is blocked by its name only, so one inside a browser or under another name is not. Any other open app is in reach. Turn on?`))return;let i=await R("/skills",{id:s.dataset.skill,on:o,...a?{confirm:!0,token:t}:{}});L(i.error?i.error:"Saved. Applies to new sessions"),await e()})}var vc="https://tailscale.com/download";async function si(e){try{return await(await fetch("/phone/setup",e?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}:void 0)).json()}catch{return{error:"The board did not answer."}}}var jo=(e,t,n=!1)=>l`<button type="button" class="btn${n?" pri":""}" data-ph="${e}">${t}</button>`,kc=(e)=>l`<ol class="ph-steps">${e.map((t)=>l`<li>${t}</li>`)}</ol>`;function Gp(e,t,n){let s=t?l`<p class="ph-err" role="alert">${t}</p>`:"",o=e.account?l`<b>${e.account}</b>`:"the same account";if(e.state==="missing")return l`<p>Your phone reaches this computer through Tailscale, a free private network between your own devices.</p>${kc(["Install Tailscale on this computer and log in.","Install it on your phone too and log in with the same account."])}<div class="ph-row"><a class="btn pri" href="${vc}" target="_blank" rel="noopener">Install Tailscale</a>${jo("check","Check again")}</div>${s}`;if(e.state==="login")return l`<p>Tailscale is installed but not logged in on this computer.</p><div class="ph-row">${jo("login",n?"Opening…":"Log in to Tailscale",!0)}${jo("check","Check again")}</div>${s}`;if(e.state==="ready")return l`<p>Tailscale is running${e.account?l` as ${o}`:""}. Connect to show the code your phone scans.</p><div class="ph-row">${jo("connect",n?"Connecting…":"Connect phone",!0)}</div>${s}`;let a=e.phones.some((i)=>i.online);return l`<div class="ph-on">${e.qr?l`<div class="ph-qr" aria-label="QR code for ${e.url}">${j(e.qr)}</div>`:""}<div><p class="ph-h">On your phone</p>${kc([l`Install Tailscale from the <a href="${vc}" target="_blank" rel="noopener">App Store or Play Store</a>.`,e.account?l`Log in with ${o}, the account this computer uses.`:"Log in with the same account as this computer.",l`Scan this code with the camera, or open <a href="${e.url}" target="_blank" rel="noopener">${e.url}</a>.`,"Choose Add to Home screen so it opens like an app."])}<p class="ph-st"><i class="ph-dot${a?" on":""}"></i>${a?`Phone online: ${e.phones.filter((i)=>i.online).map((i)=>i.name).join(", ")}`:e.phones.length?"Phone on your tailnet, offline right now":"No phone on your tailnet yet"}</p></div></div><p class="ph-note">Anyone on your tailnet can use this board. Keep the tailnet to your own devices, or limit it with Tailscale access rules.</p>${s}`}async function Do(e){let t=null,n="",s=!1,o=()=>{if(t)e.innerHTML=String(Gp(t,n,s))},a=async()=>{let c=await si();if(c.error)n=c.error;else t=c;o()};e.innerHTML='<p class="ph-wait">Checking Tailscale…</p>',e.onclick=async(c)=>{let d=c.target.closest("[data-ph]")?.dataset.ph;if(!d||s)return;if(n="",d==="check")return a();s=!0,o();let u=await si({do:d});if(s=!1,u.error)n=u.error;else if(d==="login"){if(u.url)window.open(u.url,"_blank","noopener");for(let h=0;h<40&&e.isConnected&&t?.state==="login";h++){await new Promise((f)=>setTimeout(f,3000));let y=await si();if(!y.error)t=y}}else t=u;o()},await a();let i=setInterval(()=>e.isConnected?t?.state==="connected"&&!s&&void a():clearInterval(i),1e4)}var oi=[["AI Capabilities",[{id:"agents",title:"Agents",desc:"Manage AI agents, set a default, and customize commands.",ico:"ai"},{id:"accounts",title:"AI Provider Accounts",desc:"Optional. Your normal logins keep working; add accounts only to switch between them.",ico:"link"},{id:"orchestration",title:"Orchestration",desc:"Split a run into workers, each in its own terminal. Off by default.",ico:"ai"},{id:"skills",title:"Skills",desc:"What your agents can do. Changes apply to new sessions.",ico:"note"},{id:"voice",title:"Voice",desc:"Speech-to-text dictation, run in the browser.",ico:"mic"}]],["Set Up",[{id:"general",title:"General",desc:"Which settings you are editing, folders, and maintenance.",ico:"gear"},{id:"integrations",title:"Integrations",desc:"Request sources and your Google account.",ico:"link"},{id:"mobile",title:"Mobile",desc:"Open kaizen from your phone.",ico:"send"}]],["Workflows",[{id:"approvals",title:"Approvals",desc:"Where a run stops and waits for you.",ico:"check"},{id:"autofix",title:"Auto-fix",desc:"What happens to review findings.",ico:"bug"},{id:"automations",title:"Automations",desc:"Schedules that start a run in this project.",ico:"clock"},{id:"git",title:"Git & Source Control",desc:"Branches and commits for each run.",ico:"pen"},{id:"terminal",title:"Terminal",desc:"The terminal dashboard.",ico:"term"}]],["Interface",[{id:"appearance",title:"Appearance",desc:"Theme, color and motion in this browser.",ico:"note"},{id:"notifications",title:"Notifications",desc:"Notices and sounds in this browser.",ico:"clock"},{id:"shortcuts",title:"Shortcuts",desc:"Keyboard shortcuts for common actions.",ico:"kbd"}]]],Fp=[[/^(preset|runner|build\.|review\.executor)/,"agents","Workflow"],[/^(subagents\.|agent\.model\.)/,"agents","Models"],[/^agent\.default$/,"agents","Default agent"],[/^agent\./,"agents","Running agents"],[/^orchestration\./,"orchestration","Workers"],[/^dictation\./,"voice","Dictation"],[/^sources\./,"integrations","Request sources"],[/^(mode|approvals\.|auto_accept)/,"approvals","Approvals"],[/^auto_fix\./,"autofix","Auto-fix"],[/^auto_guard\./,"autofix","Auto mode guard"],[/^git\./,"git","Git"],[/^ui\./,"terminal","Terminal"],[/^board\.chat_hotkey$/,"shortcuts","Shortcuts"],[/^board\./,"general","App"],[/^(review\.|state\.)/,"general","Project"]],$c=(e)=>{let t=Fp.find(([n])=>n.test(e));return t?[t[1],t[2]]:["general","Other"]};var ye=null,Jn=null,Yn=globalThis.kaizenDesktop,Cn=Yn?"Kaizen":"kaizen",xc=(e)=>Yn?Yn.check():fetch(e?"/version?fresh=1":"/version").then((t)=>t.json());function Ac(e){Jn=e,ye=e.update?e:null;let t=document.querySelector('.rail a[data-view="settings"]');return t.classList.toggle("upd",!!ye),t.title=ye?`Settings: ${Cn} ${e.latest} is available`:"Settings",!!ye}function ai(){let e=document.createElement("div");if(e.className=`updbar${ye?"":" quiet"}`,!ye)e.innerHTML=l`<span id="upd-msg" aria-live="polite">${Jn?`${Cn} ${Jn.version}`:Cn}</span
|
|
123
123
|
><button class="btn" id="upd-chk">Check for updates</button>`;else{let s=(ye.notes||[]).map((a)=>l`<li><b>${a.v}</b> ${a.text}</li>`),o=s.length?l`<span class="updnew"
|
|
124
124
|
><button class="btn" aria-describedby="upd-notes">What's new</button
|
|
125
125
|
><span class="updpop" id="upd-notes" role="tooltip"
|
package/web/notebook.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen notebook
|
|
1
|
+
/* kaizen notebook 523b24f53b2cdc30 -- generated by bun run build:web from web/notebook.ts; do not edit */
|
|
2
2
|
var Ja=null,eh=(e)=>{Ja=e};function Am(e,t,i){Vr++,Ja?.(e,t,i)}var Vr=0,Ka="",Ur=!1,As=!1;async function Nr(){if(Ur){As=!0;return}Ur=!0;do{As=!1;let e=Vr;try{let t=await fetch("/state?all=1");if(!t.ok)continue;let i=await t.text(),n=i.replace(/"now":\d+\}$/,"");if(n===Ka)continue;let{cards:s,projects:r,rail:o,agents:l}=JSON.parse(i);if(!As&&e===Vr)Ka=n,Am(s,[...r,...o??[]],l)}catch{}}while(As);Ur=!1}var Xm={S:{project:null,projects:[],cards:[],now:Date.now(),all:!1,dir:null},all:new URLSearchParams(location.search).get("all")!=="0",dir:null,openKey:null,mode:null,modeKey:null,menuKey:null,flash:new Set,tab:"request",lastTab:"request",runDoc:null,clearMenu:!1,sevMenu:!1,wantTerm:null,wantPty:null,shells:[],setQ:"",setScope:"all",setPage:null,setBack:!1,pageGen:0,PL:[],shown:new Set((()=>{try{return JSON.parse(localStorage.getItem("kz-show"))||[]}catch(e){return[]}})())};var N=(e)=>document.getElementById(e),Zm=(e)=>String(e).replace(/[&<>"]/g,(t)=>({"&":"&","<":"<",">":">",'"':"""})[t]);class Gr{s;constructor(e){this.s=e}toString(){return this.s}}var Ve=(e)=>new Gr(String(e)),th=(e)=>e instanceof Gr?e.s:Array.isArray(e)?e.map(th).join(""):e==null||e===!1?"":Zm(e),R=(e,...t)=>Ve(e.reduce((i,n,s)=>i+th(t[s-1])+n));var Pw=Ve('<div aria-busy="true" aria-label="Loading"><span class="skel" style="height:16px;width:35%;margin:20px 0 14px"></span>'+'<span class="skel" style="height:44px;margin-bottom:10px"></span>'.repeat(4)+"</div>");function Xs(e){let t=document.createElement("dialog");return t.className="kz",t.innerHTML=`<form class="inl" method="dialog">${e}</form>`,t.onclose=()=>t.remove(),t.onclick=(i)=>{if(i.target===t)t.close()},document.body.appendChild(t),t.showModal(),t}var Mm=!1;try{Mm=localStorage.getItem("kz-res-disk")==="1"}catch{}var mi=(e,t)=>{let i=t-e;return i<3600000?Math.round(i/60000)+"m":i<86400000?Math.round(i/3600000)+"h":Math.round(i/86400000)+"d"};var Kr=(e)=>typeof e==="string"?[e]:e.kids.flatMap(Kr);var Jr=(e,t)=>`ws:${e}:${t}`,rh=(e)=>e.kind==="run"&&e.status==="done"&&e.accept!=="needs"&&!e.archived&&e.git==="pending";var oh=3000,Ms=new Map,vn=(e)=>e.key+"@"+(e.born??0),ih={conflict:0,failed:0,asking:0,working:1,done:2},Zs={conflict:"Conflict",failed:"Land failed",asking:"Asking",working:"Working",done:"Done"},Rm={conflict:"fail",failed:"fail",asking:"wait",working:"build",done:"done"};function jm(e,t,i=Ms){if(e.land)return e.land==="conflict"?"conflict":"failed";if(e.asking)return"asking";if(e.busy)return i.set(vn(e),t),"working";return t-(i.get(vn(e))??-1/0)<oh?"working":"done"}var lh=(e,t,i=Ms)=>Math.min(1/0,...e.filter((n)=>!n.asking&&!n.busy&&i.has(vn(n))).map((n)=>oh-(t-i.get(vn(n)))).filter((n)=>n>0)),ah=(e,t=Ms)=>{let i=new Set(e.map(vn));for(let n of t.keys())if(!i.has(n))t.delete(n)},hh=(e,t,i,n,s,r=Ms)=>e.filter((o)=>o.dir===t&&n({state:o.dir,ws:o.ws})===i).map((o)=>({a:o,st:jm(o,s,r)})).sort((o,l)=>ih[o.st]-ih[l.st]),nh=({a:e,st:t})=>(e.land?"":e.last)||`${Zs[t]} - ${e.name}`,sh=(e,t)=>!e?"":t-e<60000?"now":mi(e,t),Lm=(e,t)=>e+"\x00"+t;function ch(e,t,i){let n=Lm(t,i);if(e[n])delete e[n];else e[n]=!0;return e}var Em=["claude","codex","gemini"],Hr=(e)=>R`<svg aria-hidden="true"><use href="#i-${Em.includes(e.agent??"")?e.agent:"ai"}"/></svg>`,Fr=(e)=>R`<i class="si ${Rm[e]}"></i>`,_m=R`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;function fh(e,t,i,n,s){if(!e.length)return"";let r=R`data-dir="${n}" data-ws="${s}"`;if(e.length===1){let a=e[0];return R`<div class="wag"><button type="button" class="aone" data-term="${a.a.key}" ${r} title="${a.a.name}: open its terminal">${Fr(a.st)}${Hr(a.a)}<span class="atx">${Zs[a.st]} - ${a.a.name}</span><small>${sh(a.a.at,t)}</small></button></div>`}let o=R`<button type="button" class="wchev${i?" on":""}" data-wopen ${r} aria-expanded="${String(i)}" aria-label="${String(e.length)} agents: ${i?"hide":"show"} the list">${_m}</button>`;if(i)return R`<div class="wag"><span class="aht">${String(e.length)} agents</span>${o}</div><div class="alist">${e.map((a)=>R`<button type="button" class="arow" data-term="${a.a.key}" ${r} title="${nh(a)}">${Fr(a.st)}${Hr(a.a)}<span class="atx">${nh(a)}</span><small>${sh(a.a.at,t)}</small></button>`)}</div>`;let l=["conflict","failed","asking","working","done"].map((a)=>({st:a,rs:e.filter((h)=>h.st===a)})).filter((a)=>a.rs.length);return R`<div class="wag"><span class="chips">${l.map((a)=>R`<span class="chip">${Fr(a.st)}${a.rs.map((h)=>R`<button type="button" class="amark" data-term="${h.a.key}" ${r} title="${h.a.name} - ${Zs[a.st]}: open its terminal" aria-label="${h.a.name} - ${Zs[a.st]}: open its terminal">${Hr(h.a)}</button>`)}</span>`)}</span>${o}</div>`}function eo(e){return e.toLowerCase().trim().replace(/[^a-z0-9/._-]+/g,"-").replace(/\.{2,}/g,".").replace(/\/{2,}/g,"/").replace(/(^|\/)[-.]+/g,"$1").slice(0,60).replace(/[-./]+(\/|$)/g,"$1").replace(/\/$/,"").replace(/\.lock(\/|$)/g,"-lock$1")}var zm=(e)=>e.includes("\\")?"\\":"/";async function Ut(e,t){try{let i=await fetch(e,t?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}:void 0),n=await i.json().catch(()=>({}));return{ok:i.ok,d:i.ok?n:{error:n.error||n.why||"that did not work"}}}catch{return{ok:!1,d:{error:"kaizen is offline"}}}}function Pn(e={}){let t=Xs(""),i=t.querySelector("form");t.setAttribute("aria-label","Add a project");let n=e.start==="ws",s=(u)=>i.elements.namedItem(u),r=(u,d,p,O)=>(u.disabled=d,u.textContent=d?p:O),o=n?"":R`<button type="button" class="btn ghost" data-a="back">Back to add options</button>`,l=(u)=>R`<small class="att err" role="alert"></small><div class="row">${o}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">${u}</button></div>`,a=(u)=>i.querySelector(".err").textContent=u,h=(u,d)=>{a(d);try{localStorage.setItem("kz-proj",u)}catch{}setTimeout(()=>location.href="/",900)},c=async(u,d)=>{let p=await Ut("/pick-folder",{});if(p.d.path)u.value=d?p.d.path.replace(/[\\/]+$/,"")+zm(p.d.path)+d():p.d.path},f=(u)=>{let d=uh();if(t.classList.toggle("wsnew",u==="ws"),u==="menu")i.innerHTML=R`<b>Add a project</b><small class="att">Add a project to get started with kaizen.</small><button type="button" class="btn opt" data-go="folder"><b>Existing folder</b><small>A project, a Git repo, or any folder</small></button><small class="att">Other ways to add</small><button type="button" class="btn opt" data-go="clone"><b>Clone from URL</b><small>Clone a remote Git repository</small></button><button type="button" class="btn opt" data-go="create"><b>Create new project</b><small>Start from an empty folder</small></button>${d.length?R`<button type="button" class="btn opt" data-go="ws"><b>New workspace</b><small>A branch in its own folder, in a project you have</small></button>`:""}<div class="row"><button type="button" class="btn ghost" data-a="x">Cancel</button></div>`.toString(),i.querySelectorAll("[data-go]").forEach((O)=>O.onclick=()=>f(O.dataset.go)),i.onsubmit=(O)=>O.preventDefault();else if(u==="folder")i.innerHTML=R`<b>Existing folder</b><small class="att">Pick a folder, or type its path. A .kaizen folder is added to it.</small><div class="row"><input name="path" placeholder="/path/to/folder" aria-label="Folder" autocomplete="off" spellcheck="false" required><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${l("Add project")}`.toString(),s("path").focus(),i.onsubmit=async(O)=>{O.preventDefault();let g=i.querySelector("[data-a=go]");r(g,!0,"Adding...","Add project");let b=await Ut("/add-project",{path:s("path").value.trim()});r(g,!1,"","Add project"),b.ok?h(b.d.dir,b.d.already?"Project already added":"Project added"):a(b.d.error)},i.querySelector("[data-a=pick]").onclick=()=>c(s("path"));else if(u==="clone"){i.innerHTML=R`<b>Clone from URL</b><small class="att">Enter the Git URL (https or ssh) and choose where to clone it.</small><input name="url" placeholder="https://github.com/user/repo.git" aria-label="Git URL" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to clone into" aria-label="Clone into" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${l("Clone")}`.toString(),s("url").focus();let O="",g="",b=async()=>{let y=s("url").value.trim();if(!y)return!1;let S=await Ut("/clone",{url:y,check:!0});if(!S.ok)return a(S.d.error),!1;if(a(""),O=S.d.name,!s("to").value.trim()||s("to").value===g)s("to").value=g=S.d.to;return!0};s("url").onchange=b,i.querySelector("[data-a=pick]").onclick=async()=>await b()?c(s("to"),()=>O):s("url").focus(),i.onsubmit=async(y)=>{if(y.preventDefault(),!await b())return;let S=i.querySelector("[data-a=go]");r(S,!0,"Cloning...","Clone");let x=await Ut("/clone",{url:s("url").value.trim(),to:s("to").value.trim()||void 0});r(S,!1,"","Clone"),x.ok?h(x.d.dir,"Cloned"):a(x.d.error)}}else if(u==="create"){i.innerHTML=R`<b>Create a new project</b><small class="att">Name it and kaizen will create the folder with a .kaizen inside.</small><input name="name" placeholder="my-project" aria-label="Name" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to create" aria-label="Create in" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div><label class="att"><input type="checkbox" name="git" checked> Git repository</label>${l("Create project")}`.toString(),s("name").focus();let O="";s("name").oninput=async()=>{let g=s("name").value.trim();if(!g||/[\\/:*?"<>|]/.test(g)||s("to").value.trim()&&s("to").value!==O)return;let b=await Ut("/new-project",{name:g,check:!0});if(b.ok&&s("name").value.trim()===g)s("to").value=O=b.d.to},i.querySelector("[data-a=pick]").onclick=()=>c(s("to"),()=>s("name").value.trim()),i.onsubmit=async(g)=>{g.preventDefault();let b=i.querySelector("[data-a=go]");r(b,!0,"Creating...","Create project");let y=await Ut("/new-project",{name:s("name").value.trim(),to:s("to").value.trim()||void 0,git:s("git").checked});if(r(b,!1,"","Create project"),!y.ok)return a(y.d.error);h(y.d.dir,y.d.git===!1?"Project created, but git init failed":"Project created")}}else{let O=d.some((S)=>S.dir===e.dir)?e.dir:d[0]?.dir,g=/Mac/.test(navigator.platform)?"⌘":"Ctrl";i.innerHTML=R`<b>New workspace</b><label class="att">Project<select name="project" aria-label="Project">${d.map((S)=>R`<option value="${S.dir}"${S.dir===O?" selected":""}>${S.name}</option>`)}</select></label><div class="wsfrom"><span class="att" id="wsfl">Create from <i>[Optional]</i></span><label class="wsbase">from <select name="base" aria-label="Start from branch"></select></label></div><input name="name" placeholder="What is this workspace for?" aria-labelledby="wsfl" autocomplete="off" spellcheck="false"><details class="wsadv"><summary>Advanced</summary><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false"></label></details><small class="att err" role="alert"></small><div class="row">${o}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">Create workspace</button><kbd class="wskey" aria-hidden="true">${g} ↵</kbd></div>`.toString(),s("name").focus();let b=i.elements.namedItem("base");s("name").oninput=()=>s("branch").placeholder=eo(s("name").value)||"feature/my-branch";let y=async()=>{let S=await Ut("/branches?dir="+encodeURIComponent(s("project").value)),{def:x="",branches:v=[]}=S.ok?S.d:{};b.innerHTML=v.map((X)=>R`<option${X===x?" selected":""}>${X}</option>`.toString()).join("")||'<option value="">current branch</option>'};i.elements.namedItem("project").onchange=y,y(),i.onkeydown=(S)=>{if(S.key==="Enter"&&(S.ctrlKey||S.metaKey))S.preventDefault(),i.requestSubmit()},i.onsubmit=async(S)=>{S.preventDefault();let x=s("project").value,v=i.querySelector("[data-a=go]");if(v.disabled)return;a("");let X=s("branch").value.trim()||eo(s("name").value)||"workspace-"+Math.random().toString(36).slice(2,6);r(v,!0,"Creating...","Create workspace");let T=await Ut("/worktree",{dir:x,branch:X,base:b.value||void 0});r(v,!1,"","Create workspace"),T.ok?(t.close(),location.href=Vt(x,T.d.path)):a(T.d.error)}}i.querySelector("[data-a=x]").onclick=()=>t.close();let p=i.querySelector("[data-a=back]");if(p)p.onclick=()=>f("menu")};f(e.start??"menu")}function dh(e,t){let i=t.toLowerCase().split(/\s+/).filter(Boolean);if(!i.length)return e;let n=t.trim().toLowerCase(),s=(r)=>{let o=r.title.toLowerCase();return o.startsWith(n)?0:o.includes(n)?1:2};return e.filter((r)=>{let o=(r.title+" "+(r.sub??"")+" "+r.hay).toLowerCase();return i.every((l)=>o.includes(l))}).sort((r,o)=>s(r)-s(o)||(o.at??0)-(r.at??0))}var js=(e,t)=>!dispatchEvent(new CustomEvent(e,{cancelable:!0,detail:t})),gi=(e,t)=>()=>{let i=document.querySelector(`.rail a[data-view="${e}"]`);i?i.click():location.href=t},ph=(e,t)=>{if(!js("kz-open-ws",{dir:e,ws:t}))location.href=Vt(e,t)},mh=()=>{try{return JSON.parse(localStorage.getItem("kz-runtabs")||"{}")}catch{return{}}},Ym=(e,t,i)=>{if(js("kz-open-tab",{dir:e,ws:t,id:i}))return;let n=mh(),s=n[Jr(e,t)],r=s?.screens?.find((o)=>Kr(o.tree).includes(i));if(r)try{s.on=r.id,localStorage.setItem("kz-runtabs",JSON.stringify(n))}catch{}location.href=Vt(e,t)},qm=["local","preview","note","history","shell"],Dm=(e)=>{try{return localStorage.getItem("kz-browse:"+e)?.replace(/^https?:\/\//,"").replace(/\/$/,"")}catch{}},Wm={ws:'<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 8v8M18 10c0 4-6 3-12 6"/>',run:'<path d="M5 4l14 8-14 8z"/>',idea:'<path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.5 1 2.5h6c0-1 .3-1.8 1-2.5A6 6 0 0 0 12 3z"/>',chat:'<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/>',term:'<path d="M4 17l6-5-6-5M12 19h8"/>',proj:'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',page:'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 9h16"/>',act:'<path d="M13 3L5 14h6l-1 7 8-11h-6z"/>',tab:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 9h8V5"/>',plus:'<path d="M12 5v14M5 12h14"/>',search:'<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>'},gh=(e)=>Ve(`<svg viewBox="0 0 24 24" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${Wm[e]}</g></svg>`),bh=[];function Bm(){let{cards:e,projects:t=[],agents:i=[]}=kh(),n=Date.now(),s=new URLSearchParams(location.search),r=s.get("id")&&e.find((u)=>u.kind==="run"&&u.state===s.get("dir")&&u.id===s.get("id")),o=s.get("ws")??(r?Yi(r,t):null),l=[],a=mh(),h=new Map;for(let u of e){let d=u.state+"\x00"+Yi(u,t);h.set(d,Math.max(h.get(d)??0,u.moved??0))}for(let u of t){let d=Ne(u.dir,t);for(let p of u.workspaces??[]){let O=s.get("dir")===u.dir&&o===p.path,g=h.get(u.dir+"\x00"+p.path);l.push({group:O?"Current":"Workspaces",title:bi(p),sub:d,when:g?mi(g,n):void 0,hay:`${bi(p)} ${d} ${p.path} workspace`,at:O?1/0:g??0,ico:"ws",act:()=>ph(u.dir,p.path)});let b=Jr(u.dir,p.path),y=a[b];for(let S of y?.tabs??[]){if(!qm.includes(S.kind)||y.hidden?.includes(S.id))continue;let x=S.kind==="local"&&Dm(b)||S.title;l.push({group:"Tabs",title:x,sub:`${bi(p)} · ${d}`,hay:`${x} ${S.title} ${S.kind} ${S.note??""} ${bi(p)} ${d} tab`,ico:"tab",act:()=>Ym(u.dir,p.path,S.id)})}}l.push({group:"Projects",title:d,hay:`${d} ${u.dir} project`,ico:"proj",act:()=>{let p=u.workspaces?.find((O)=>O.main)??u.workspaces?.[0];p?ph(u.dir,p.path):gi("board","/?view=board")()}})}for(let u of e.filter((d)=>!d.archived)){let d=yi(u);l.push({group:u.kind==="run"?"Runs":"Tasks",title:no(u)||u.id,sub:Ne(u.state,t),when:u.moved?mi(u.moved,n):void 0,hay:`${no(u)} ${u.id??""} ${u.text??""} ${Ne(u.state,t)} ${d}`,at:u.moved??0,dot:d,ico:u.kind==="run"?"run":"idea",act:()=>{if(!js("kz-open-card",{dir:u.state,id:u.kind==="run"?u.id:void 0,text:u.text}))location.href=Sh(u)}})}for(let u of bh){let d=Date.parse(u.updated)||0;l.push({group:"Chats & terminals",title:u.title||"Chat",sub:u.project?Ne(u.project,t):void 0,when:d?mi(d,n):void 0,hay:`${u.title} chat ${u.project??""}`,at:d,dot:u.busy?"build":void 0,ico:"chat",act:()=>{try{sessionStorage.setItem("kz-chat",u.id)}catch{}gi("home","/")()}})}for(let u of i)l.push({group:"Chats & terminals",title:u.name||u.agent||"Terminal",sub:Ne(u.dir,t),hay:`${u.name} ${u.agent??""} ${u.run??""} ${u.last??""} ${Ne(u.dir,t)} terminal agent`,at:u.at??u.born??0,dot:u.asking?"wait":u.busy?"build":"done",ico:"term",act:()=>{if(!js("kz-open-term",{dir:u.dir,ws:u.ws,key:u.key}))location.href=Vt(u.dir,u.ws??"")}});let c=(u)=>()=>N(u)?.click(),f=[["Home","page",gi("home","/"),"chat"],["Icebox","page",gi("sources","/?view=icebox"),"requests sources gathered"],["Tasks","page",gi("tasks","/?view=tasks"),"backlog"],["Board","page",gi("board","/?view=board"),"kanban runs"],["Notes","page",()=>location.href="/notebook","notebook docs"],["Settings","page",gi("settings","/?view=settings"),"preferences config"],["New task","act",()=>N("newtop")?N("newtop").click():location.href="/?view=board","create add run"],["Add a project","act",()=>Pn({dir:null}),"clone folder create workspace"],["Toggle theme","act",c("themet"),"dark light"],["Collapse or expand menu","act",c("fold"),"sidebar rail"],["Keyboard shortcuts","act",c("kbd"),"keys help"],["Report an issue","act",()=>open("/issue","_blank","noopener"),"bug feedback"]];for(let[u,d,p,O]of f)l.push({group:"Actions",title:u,hay:`${u} ${O??""}`,ico:d,act:p});return l}var Im=["Current","Workspaces","Tabs","Chats & terminals","Runs","Tasks","Projects","Actions"],Um={Workspaces:5,Tabs:4,"Chats & terminals":5,Runs:5,Tasks:3,Projects:5},H=null,st=[],rt=0;function Rs(){let e=H.querySelector("input").value,t=Bm(),i=e.trim()?dh(t,e):t.slice().sort((o,l)=>(l.at??0)-(o.at??0));st=[];let n=e.trim()?[...new Set(i.map((o)=>o.group))]:Im;for(let o of n){let l=i.filter((a)=>a.group===o);st.push(...l.slice(0,e.trim()?8:Um[o]??l.length))}if(e.trim())st.push({group:"Create",title:`New task "${e.trim()}"`,hay:"",ico:"plus",act:()=>Vm(e.trim())});rt=Math.min(rt,st.length-1);let s=H.querySelector(".gs-list"),r="";s.innerHTML=String(R`${st.map((o,l)=>{let a=o.group!==r?(r=o.group,R`<div class="gs-h" role="presentation">${o.group}</div>`):"";return R`${a}<div class="gs-i" role="option" id="gs-${l}" data-n="${l}" aria-selected="${String(l===rt)}">${gh(o.ico)}${o.dot?R`<span class="si ${o.dot}"></span>`:""}<span class="gs-t">${o.title}</span>${o.sub?R`<span class="gs-s">${o.sub}</span>`:""}${o.when?R`<span class="gs-w">${o.when}</span>`:""}</div>`})}${st.length===1&&e.trim()?R`<div class="gs-none">No results</div>`:""}`),io(rt),H.querySelector(".gs-live").textContent=`${st.length} result${st.length===1?"":"s"} found`}function io(e){H.querySelector(`#gs-${rt}`)?.setAttribute("aria-selected","false"),rt=e;let t=H.querySelector(`#gs-${e}`);t?.setAttribute("aria-selected","true"),H.querySelector("input").setAttribute("aria-activedescendant","gs-"+e),t?.scrollIntoView({block:"nearest"})}function Vm(e){if(!N("newtop"))return void(location.href="/?view=board");N("newtop").click();let t=document.querySelector("dialog[open] textarea");if(t)t.value=e,t.dispatchEvent(new Event("input",{bubbles:!0}))}function Oh(e){let t=st[e];if(!t)return;H.close(),t.act()}function to(){if(H)return H.querySelector("input").focus();H=document.createElement("dialog"),H.className="gs",H.setAttribute("aria-label","Search"),H.innerHTML=String(R`<div class="gs-box"><div class="gs-q">${gh("search")}<input type="text" placeholder="Search" aria-label="Search" role="combobox" aria-expanded="true" aria-controls="gs-list" autocomplete="off" spellcheck="false"></div><div class="gs-list" id="gs-list" role="listbox"></div><span class="gs-live" role="status" aria-live="polite"></span></div>`),document.body.append(H);let e=H.querySelector("input");rt=0,e.oninput=()=>(rt=0,Rs()),e.onkeydown=(i)=>{let n={ArrowDown:1,ArrowUp:-1}[i.key]??(i.ctrlKey&&i.key==="n"?1:i.ctrlKey&&i.key==="p"?-1:0);if(n)i.preventDefault(),io((rt+n+st.length)%st.length);else if(i.key==="Enter")i.preventDefault(),Oh(rt)};let t=H.querySelector(".gs-list");t.onclick=(i)=>{let n=i.target.closest(".gs-i");if(n)Oh(+n.dataset.n)},t.onpointermove=(i)=>{let n=i.target.closest(".gs-i");if(n&&+n.dataset.n!==rt)io(+n.dataset.n)},H.onclick=(i)=>i.target===H&&H.close(),H.onclose=()=>(H.remove(),H=null),H.showModal(),Rs(),fetch("/chats").then((i)=>i.json()).then((i)=>{if(bh=i.chats??[],H)Rs()}).catch(()=>{})}var Nm=`dialog.gs{border:0;padding:0;margin:14vh auto auto;background:none;width:min(560px,calc(100vw - 32px));color:var(--ink);overflow:visible}
|
|
3
3
|
dialog.gs::backdrop{background:rgb(0 0 0/.35)}
|
|
4
4
|
.gs-box{display:flex;flex-direction:column;max-height:min(480px,72vh);background:var(--bg);border:1px solid var(--line);border-radius:10px;box-shadow:0 16px 40px rgb(0 0 0/.25);overflow:hidden}
|
package/web/term.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen terminal
|
|
1
|
+
/* kaizen terminal 523b24f53b2cdc30 -- generated by bun run build:web from web/term.ts; do not edit */
|
|
2
2
|
(()=>{var{defineProperty:sa,getOwnPropertyDescriptor:Nl}=Object,Fl=(e,t)=>{for(var i in t)sa(e,i,{get:t[i],enumerable:!0})},ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?Nl(t,i):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(r=(s?o(t,i,r):o(r))||r);return s&&r&&sa(t,i,r),r},O=(e,t)=>(i,s)=>t(i,s,e),Qn="Terminal input",Sr={get:()=>Qn,set:(e)=>Qn=e},eo="Too much output to announce, navigate to rows manually to read",wr={get:()=>eo,set:(e)=>eo=e};function Wl(e){return e.replace(/\r?\n/g,"\r")}function zl(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function $l(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Hl(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData("text/plain");ra(r,t,i,s)}}function ra(e,t,i,s){e=Wl(e),e=zl(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function na(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function to(e,t,i,s,r){na(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Wt(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function xs(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let n=e[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var Ul=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let n=e.charCodeAt(r++);56320<=n&&n<=57343?t[s++]=(this._interim-55296)*1024+n-56320+65536:(t[s++]=this._interim,t[s++]=n),this._interim=0}for(let n=r;n<i;++n){let o=e.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=i)return this._interim=o,s;let a=e.charCodeAt(n);56320<=a&&a<=57343?t[s++]=(o-55296)*1024+a-56320+65536:(t[s++]=o,t[s++]=a);continue}o!==65279&&(t[s++]=o)}return s}},Kl=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r,n,o,a,l=0,h=0;if(this.interim[0]){let f=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,y;for(;(y=this.interim[++m]&63)&&m<4;)p<<=6,p|=y;let E=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,B=E-m;for(;h<B;){if(h>=i)return 0;if(y=e[h++],(y&192)!==128){h--,f=!0;break}else this.interim[m++]=y,p<<=6,p|=y&63}f||(E===2?p<128?h--:t[s++]=p:E===3?p<2048||p>=55296&&p<=57343||p===65279||(t[s++]=p):p<65536||p>1114111||(t[s++]=p)),this.interim.fill(0)}let d=i-4,c=h;for(;c<i;){for(;c<d&&!((r=e[c])&128)&&!((n=e[c+1])&128)&&!((o=e[c+2])&128)&&!((a=e[c+3])&128);)t[s++]=r,t[s++]=n,t[s++]=o,t[s++]=a,c+=4;if(r=e[c++],r<128)t[s++]=r;else if((r&224)===192){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(l=(r&31)<<6|n&63,l<128){c--;continue}t[s++]=l}else if((r&240)===224){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[c++],(o&192)!==128){c--;continue}if(l=(r&15)<<12|(n&63)<<6|o&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[s++]=l}else if((r&248)===240){if(c>=i)return this.interim[0]=r,s;if(n=e[c++],(n&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,s;if(o=e[c++],(o&192)!==128){c--;continue}if(c>=i)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=o,s;if(a=e[c++],(a&192)!==128){c--;continue}if(l=(r&7)<<18|(n&63)<<12|(o&63)<<6|a&63,l<65536||l>1114111)continue;t[s++]=l}}return s}},oa="",zt=" ",zi=class e{constructor(){this.fg=0,this.bg=0,this.extended=new gs}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},gs=class e{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},tt=class e extends zi{constructor(){super(...arguments);this.content=0,this.fg=0,this.bg=0,this.extended=new gs,this.combinedData=""}static fromCharData(t){let i=new e;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Wt(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(s-55296)*1024+r-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},io="di$target",br="di$dependencies",sr=new Map;function ql(e){return e[br]||[]}function De(e){if(sr.has(e))return sr.get(e);let t=function(i,s,r){if(arguments.length!==3)throw Error("@IServiceName-decorator can only be used to decorate a parameter");Vl(t,i,r)};return t._id=e,sr.set(e,t),t}function Vl(e,t,i){t[io]===t?t[br].push({id:e,index:i}):(t[br]=[{id:e,index:i}],t[io]=t)}var Fe=De("BufferService"),aa=De("CoreMouseService"),ii=De("CoreService"),Gl=De("CharsetService"),Yr=De("InstantiationService"),ha=De("LogService"),We=De("OptionsService"),la=De("OscLinkService"),jl=De("UnicodeService"),$i=De("DecorationService"),yr=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],r=this._optionsService.rawOptions.linkHandler,n=new tt,o=i.getTrimmedLength(),a=-1,l=-1,h=!1;for(let d=0;d<o;d++)if(!(l===-1&&!i.hasContent(d))){if(i.loadCell(d,n),n.hasExtendedAttrs()&&n.extended.urlId)if(l===-1){l=d,a=n.extended.urlId;continue}else h=n.extended.urlId!==a;else l!==-1&&(h=!0);if(h||l!==-1&&d===o-1){let c=this._oscLinkService.getLinkData(a)?.uri;if(c){let f={start:{x:l+1,y:e},end:{x:d+(!h&&d===o-1?1:0),y:e}},p=!1;if(!r?.allowNonHttpProtocols)try{let m=new URL(c);["http:","https:"].includes(m.protocol)||(p=!0)}catch{p=!0}p||s.push({text:c,range:f,activate:(m,y)=>r?r.activate(m,y,f):Yl(m,y),hover:(m,y)=>r?.hover?.(m,y,f),leave:(m,y)=>r?.leave?.(m,y,f)})}h=!1,n.hasExtendedAttrs()&&n.extended.urlId?(l=d,a=n.extended.urlId):(l=-1,a=-1)}}t(s)}};yr=ce([O(0,Fe),O(1,We),O(2,la)],yr);function Yl(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
3
3
|
|
|
4
4
|
WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var ks=De("CharSizeService"),bt=De("CoreBrowserService"),Xr=De("MouseService"),yt=De("RenderService"),Xl=De("SelectionService"),ca=De("CharacterJoinerService"),hi=De("ThemeService"),da=De("LinkProviderService"),Zl=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?so.isErrorNoTelemetry(e)?new so(e.message+`
|
package/web/video.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* kaizen video page
|
|
1
|
+
/* kaizen video page 523b24f53b2cdc30 -- generated by bun run build:web from web/video.ts; do not edit */
|
|
2
2
|
(()=>{var ht=null,bt=(e)=>{ht=e};function dn(e,t,n){Oe++,ht?.(e,t,n)}var Oe=0,gt="",De=!1,we=!1;async function qe(){if(De){we=!0;return}De=!0;do{we=!1;let e=Oe;try{let t=await fetch("/state?all=1");if(!t.ok)continue;let n=await t.text(),a=n.replace(/"now":\d+\}$/,"");if(a===gt)continue;let{cards:s,projects:r,rail:l,agents:i}=JSON.parse(n);if(!we&&e===Oe)gt=a,dn(s,[...r,...l??[]],i)}catch{}}while(we);De=!1}var un={S:{project:null,projects:[],cards:[],now:Date.now(),all:!1,dir:null},all:new URLSearchParams(location.search).get("all")!=="0",dir:null,openKey:null,mode:null,modeKey:null,menuKey:null,flash:new Set,tab:"request",lastTab:"request",runDoc:null,clearMenu:!1,sevMenu:!1,wantTerm:null,wantPty:null,shells:[],setQ:"",setScope:"all",setPage:null,setBack:!1,pageGen:0,PL:[],shown:new Set((()=>{try{return JSON.parse(localStorage.getItem("kz-show"))||[]}catch(e){return[]}})())};var M=(e)=>document.getElementById(e),pn=(e)=>String(e).replace(/[&<>"]/g,(t)=>({"&":"&","<":"<",">":">",'"':"""})[t]);class Fe{s;constructor(e){this.s=e}toString(){return this.s}}var z=(e)=>new Fe(String(e)),vt=(e)=>e instanceof Fe?e.s:Array.isArray(e)?e.map(vt).join(""):e==null||e===!1?"":pn(e),w=(e,...t)=>z(e.reduce((n,a,s)=>n+vt(t[s-1])+a));var os=z('<div aria-busy="true" aria-label="Loading"><span class="skel" style="height:16px;width:35%;margin:20px 0 14px"></span>'+'<span class="skel" style="height:44px;margin-bottom:10px"></span>'.repeat(4)+"</div>");function $e(e){let t=document.createElement("dialog");return t.className="kz",t.innerHTML=`<form class="inl" method="dialog">${e}</form>`,t.onclose=()=>t.remove(),t.onclick=(n)=>{if(n.target===t)t.close()},document.body.appendChild(t),t.showModal(),t}var mn=!1;try{mn=localStorage.getItem("kz-res-disk")==="1"}catch{}var te=(e,t)=>{let n=t-e;return n<3600000?Math.round(n/60000)+"m":n<86400000?Math.round(n/3600000)+"h":Math.round(n/86400000)+"d"};var We=(e)=>typeof e==="string"?[e]:e.kids.flatMap(We);var Ve=(e,t)=>`ws:${e}:${t}`,kt=(e)=>e.kind==="run"&&e.status==="done"&&e.accept!=="needs"&&!e.archived&&e.git==="pending";var xt=3000,xe=new Map,me=(e)=>e.key+"@"+(e.born??0),yt={conflict:0,failed:0,asking:0,working:1,done:2},ke={conflict:"Conflict",failed:"Land failed",asking:"Asking",working:"Working",done:"Done"},fn={conflict:"fail",failed:"fail",asking:"wait",working:"build",done:"done"};function gn(e,t,n=xe){if(e.land)return e.land==="conflict"?"conflict":"failed";if(e.asking)return"asking";if(e.busy)return n.set(me(e),t),"working";return t-(n.get(me(e))??-1/0)<xt?"working":"done"}var Et=(e,t,n=xe)=>Math.min(1/0,...e.filter((a)=>!a.asking&&!a.busy&&n.has(me(a))).map((a)=>xt-(t-n.get(me(a)))).filter((a)=>a>0)),Mt=(e,t=xe)=>{let n=new Set(e.map(me));for(let a of t.keys())if(!n.has(a))t.delete(a)},St=(e,t,n,a,s,r=xe)=>e.filter((l)=>l.dir===t&&a({state:l.dir,ws:l.ws})===n).map((l)=>({a:l,st:gn(l,s,r)})).sort((l,i)=>yt[l.st]-yt[i.st]),wt=({a:e,st:t})=>(e.land?"":e.last)||`${ke[t]} - ${e.name}`,$t=(e,t)=>!e?"":t-e<60000?"now":te(e,t),hn=(e,t)=>e+"\x00"+t;function Lt(e,t,n){let a=hn(t,n);if(e[a])delete e[a];else e[a]=!0;return e}var bn=["claude","codex","gemini"],Ke=(e)=>w`<svg aria-hidden="true"><use href="#i-${bn.includes(e.agent??"")?e.agent:"ai"}"/></svg>`,Ue=(e)=>w`<i class="si ${fn[e]}"></i>`,vn=w`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;function Tt(e,t,n,a,s){if(!e.length)return"";let r=w`data-dir="${a}" data-ws="${s}"`;if(e.length===1){let u=e[0];return w`<div class="wag"><button type="button" class="aone" data-term="${u.a.key}" ${r} title="${u.a.name}: open its terminal">${Ue(u.st)}${Ke(u.a)}<span class="atx">${ke[u.st]} - ${u.a.name}</span><small>${$t(u.a.at,t)}</small></button></div>`}let l=w`<button type="button" class="wchev${n?" on":""}" data-wopen ${r} aria-expanded="${String(n)}" aria-label="${String(e.length)} agents: ${n?"hide":"show"} the list">${vn}</button>`;if(n)return w`<div class="wag"><span class="aht">${String(e.length)} agents</span>${l}</div><div class="alist">${e.map((u)=>w`<button type="button" class="arow" data-term="${u.a.key}" ${r} title="${wt(u)}">${Ue(u.st)}${Ke(u.a)}<span class="atx">${wt(u)}</span><small>${$t(u.a.at,t)}</small></button>`)}</div>`;let i=["conflict","failed","asking","working","done"].map((u)=>({st:u,rs:e.filter((k)=>k.st===u)})).filter((u)=>u.rs.length);return w`<div class="wag"><span class="chips">${i.map((u)=>w`<span class="chip">${Ue(u.st)}${u.rs.map((k)=>w`<button type="button" class="amark" data-term="${k.a.key}" ${r} title="${k.a.name} - ${ke[u.st]}: open its terminal" aria-label="${k.a.name} - ${ke[u.st]}: open its terminal">${Ke(k.a)}</button>`)}</span>`)}</span>${l}</div>`}function Je(e){return e.toLowerCase().trim().replace(/[^a-z0-9/._-]+/g,"-").replace(/\.{2,}/g,".").replace(/\/{2,}/g,"/").replace(/(^|\/)[-.]+/g,"$1").slice(0,60).replace(/[-./]+(\/|$)/g,"$1").replace(/\/$/,"").replace(/\.lock(\/|$)/g,"-lock$1")}var yn=(e)=>e.includes("\\")?"\\":"/";async function Y(e,t){try{let n=await fetch(e,t?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}:void 0),a=await n.json().catch(()=>({}));return{ok:n.ok,d:n.ok?a:{error:a.error||a.why||"that did not work"}}}catch{return{ok:!1,d:{error:"kaizen is offline"}}}}function fe(e={}){let t=$e(""),n=t.querySelector("form");t.setAttribute("aria-label","Add a project");let a=e.start==="ws",s=(o)=>n.elements.namedItem(o),r=(o,c,p,h)=>(o.disabled=c,o.textContent=c?p:h),l=a?"":w`<button type="button" class="btn ghost" data-a="back">Back to add options</button>`,i=(o)=>w`<small class="att err" role="alert"></small><div class="row">${l}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">${o}</button></div>`,u=(o)=>n.querySelector(".err").textContent=o,k=(o,c)=>{u(c);try{localStorage.setItem("kz-proj",o)}catch{}setTimeout(()=>location.href="/",900)},L=async(o,c)=>{let p=await Y("/pick-folder",{});if(p.d.path)o.value=c?p.d.path.replace(/[\\/]+$/,"")+yn(p.d.path)+c():p.d.path},f=(o)=>{let c=jt();if(t.classList.toggle("wsnew",o==="ws"),o==="menu")n.innerHTML=w`<b>Add a project</b><small class="att">Add a project to get started with kaizen.</small><button type="button" class="btn opt" data-go="folder"><b>Existing folder</b><small>A project, a Git repo, or any folder</small></button><small class="att">Other ways to add</small><button type="button" class="btn opt" data-go="clone"><b>Clone from URL</b><small>Clone a remote Git repository</small></button><button type="button" class="btn opt" data-go="create"><b>Create new project</b><small>Start from an empty folder</small></button>${c.length?w`<button type="button" class="btn opt" data-go="ws"><b>New workspace</b><small>A branch in its own folder, in a project you have</small></button>`:""}<div class="row"><button type="button" class="btn ghost" data-a="x">Cancel</button></div>`.toString(),n.querySelectorAll("[data-go]").forEach((h)=>h.onclick=()=>f(h.dataset.go)),n.onsubmit=(h)=>h.preventDefault();else if(o==="folder")n.innerHTML=w`<b>Existing folder</b><small class="att">Pick a folder, or type its path. A .kaizen folder is added to it.</small><div class="row"><input name="path" placeholder="/path/to/folder" aria-label="Folder" autocomplete="off" spellcheck="false" required><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${i("Add project")}`.toString(),s("path").focus(),n.onsubmit=async(h)=>{h.preventDefault();let v=n.querySelector("[data-a=go]");r(v,!0,"Adding...","Add project");let y=await Y("/add-project",{path:s("path").value.trim()});r(v,!1,"","Add project"),y.ok?k(y.d.dir,y.d.already?"Project already added":"Project added"):u(y.d.error)},n.querySelector("[data-a=pick]").onclick=()=>L(s("path"));else if(o==="clone"){n.innerHTML=w`<b>Clone from URL</b><small class="att">Enter the Git URL (https or ssh) and choose where to clone it.</small><input name="url" placeholder="https://github.com/user/repo.git" aria-label="Git URL" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to clone into" aria-label="Clone into" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div>${i("Clone")}`.toString(),s("url").focus();let h="",v="",y=async()=>{let C=s("url").value.trim();if(!C)return!1;let x=await Y("/clone",{url:C,check:!0});if(!x.ok)return u(x.d.error),!1;if(u(""),h=x.d.name,!s("to").value.trim()||s("to").value===v)s("to").value=v=x.d.to;return!0};s("url").onchange=y,n.querySelector("[data-a=pick]").onclick=async()=>await y()?L(s("to"),()=>h):s("url").focus(),n.onsubmit=async(C)=>{if(C.preventDefault(),!await y())return;let x=n.querySelector("[data-a=go]");r(x,!0,"Cloning...","Clone");let E=await Y("/clone",{url:s("url").value.trim(),to:s("to").value.trim()||void 0});r(x,!1,"","Clone"),E.ok?k(E.d.dir,"Cloned"):u(E.d.error)}}else if(o==="create"){n.innerHTML=w`<b>Create a new project</b><small class="att">Name it and kaizen will create the folder with a .kaizen inside.</small><input name="name" placeholder="my-project" aria-label="Name" autocomplete="off" spellcheck="false" required><div class="row"><input name="to" placeholder="Folder to create" aria-label="Create in" autocomplete="off" spellcheck="false"><button type="button" class="btn ghost" data-a="pick">Pick…</button></div><label class="att"><input type="checkbox" name="git" checked> Git repository</label>${i("Create project")}`.toString(),s("name").focus();let h="";s("name").oninput=async()=>{let v=s("name").value.trim();if(!v||/[\\/:*?"<>|]/.test(v)||s("to").value.trim()&&s("to").value!==h)return;let y=await Y("/new-project",{name:v,check:!0});if(y.ok&&s("name").value.trim()===v)s("to").value=h=y.d.to},n.querySelector("[data-a=pick]").onclick=()=>L(s("to"),()=>s("name").value.trim()),n.onsubmit=async(v)=>{v.preventDefault();let y=n.querySelector("[data-a=go]");r(y,!0,"Creating...","Create project");let C=await Y("/new-project",{name:s("name").value.trim(),to:s("to").value.trim()||void 0,git:s("git").checked});if(r(y,!1,"","Create project"),!C.ok)return u(C.d.error);k(C.d.dir,C.d.git===!1?"Project created, but git init failed":"Project created")}}else{let h=c.some((x)=>x.dir===e.dir)?e.dir:c[0]?.dir,v=/Mac/.test(navigator.platform)?"⌘":"Ctrl";n.innerHTML=w`<b>New workspace</b><label class="att">Project<select name="project" aria-label="Project">${c.map((x)=>w`<option value="${x.dir}"${x.dir===h?" selected":""}>${x.name}</option>`)}</select></label><div class="wsfrom"><span class="att" id="wsfl">Create from <i>[Optional]</i></span><label class="wsbase">from <select name="base" aria-label="Start from branch"></select></label></div><input name="name" placeholder="What is this workspace for?" aria-labelledby="wsfl" autocomplete="off" spellcheck="false"><details class="wsadv"><summary>Advanced</summary><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false"></label></details><small class="att err" role="alert"></small><div class="row">${l}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">Create workspace</button><kbd class="wskey" aria-hidden="true">${v} ↵</kbd></div>`.toString(),s("name").focus();let y=n.elements.namedItem("base");s("name").oninput=()=>s("branch").placeholder=Je(s("name").value)||"feature/my-branch";let C=async()=>{let x=await Y("/branches?dir="+encodeURIComponent(s("project").value)),{def:E="",branches:U=[]}=x.ok?x.d:{};y.innerHTML=U.map((G)=>w`<option${G===E?" selected":""}>${G}</option>`.toString()).join("")||'<option value="">current branch</option>'};n.elements.namedItem("project").onchange=C,C(),n.onkeydown=(x)=>{if(x.key==="Enter"&&(x.ctrlKey||x.metaKey))x.preventDefault(),n.requestSubmit()},n.onsubmit=async(x)=>{x.preventDefault();let E=s("project").value,U=n.querySelector("[data-a=go]");if(U.disabled)return;u("");let G=s("branch").value.trim()||Je(s("name").value)||"workspace-"+Math.random().toString(36).slice(2,6);r(U,!0,"Creating...","Create workspace");let pe=await Y("/worktree",{dir:E,branch:G,base:y.value||void 0});r(U,!1,"","Create workspace"),pe.ok?(t.close(),location.href=X(E,pe.d.path)):u(pe.d.error)}}n.querySelector("[data-a=x]").onclick=()=>t.close();let p=n.querySelector("[data-a=back]");if(p)p.onclick=()=>f("menu")};f(e.start??"menu")}function Ct(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);if(!n.length)return e;let a=t.trim().toLowerCase(),s=(r)=>{let l=r.title.toLowerCase();return l.startsWith(a)?0:l.includes(a)?1:2};return e.filter((r)=>{let l=(r.title+" "+(r.sub??"")+" "+r.hay).toLowerCase();return n.every((i)=>l.includes(i))}).sort((r,l)=>s(r)-s(l)||(l.at??0)-(r.at??0))}var Me=(e,t)=>!dispatchEvent(new CustomEvent(e,{cancelable:!0,detail:t})),ne=(e,t)=>()=>{let n=document.querySelector(`.rail a[data-view="${e}"]`);n?n.click():location.href=t},Ht=(e,t)=>{if(!Me("kz-open-ws",{dir:e,ws:t}))location.href=X(e,t)},At=()=>{try{return JSON.parse(localStorage.getItem("kz-runtabs")||"{}")}catch{return{}}},wn=(e,t,n)=>{if(Me("kz-open-tab",{dir:e,ws:t,id:n}))return;let a=At(),s=a[Ve(e,t)],r=s?.screens?.find((l)=>We(l.tree).includes(n));if(r)try{s.on=r.id,localStorage.setItem("kz-runtabs",JSON.stringify(a))}catch{}location.href=X(e,t)},$n=["local","preview","note","history","shell"],kn=(e)=>{try{return localStorage.getItem("kz-browse:"+e)?.replace(/^https?:\/\//,"").replace(/\/$/,"")}catch{}},xn={ws:'<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 8v8M18 10c0 4-6 3-12 6"/>',run:'<path d="M5 4l14 8-14 8z"/>',idea:'<path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.5 1 2.5h6c0-1 .3-1.8 1-2.5A6 6 0 0 0 12 3z"/>',chat:'<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/>',term:'<path d="M4 17l6-5-6-5M12 19h8"/>',proj:'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',page:'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 9h16"/>',act:'<path d="M13 3L5 14h6l-1 7 8-11h-6z"/>',tab:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 9h8V5"/>',plus:'<path d="M12 5v14M5 12h14"/>',search:'<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>'},Rt=(e)=>z(`<svg viewBox="0 0 24 24" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${xn[e]}</g></svg>`),Bt=[];function En(){let{cards:e,projects:t=[],agents:n=[]}=Pt(),a=Date.now(),s=new URLSearchParams(location.search),r=s.get("id")&&e.find((o)=>o.kind==="run"&&o.state===s.get("dir")&&o.id===s.get("id")),l=s.get("ws")??(r?de(r,t):null),i=[],u=At(),k=new Map;for(let o of e){let c=o.state+"\x00"+de(o,t);k.set(c,Math.max(k.get(c)??0,o.moved??0))}for(let o of t){let c=N(o.dir,t);for(let p of o.workspaces??[]){let h=s.get("dir")===o.dir&&l===p.path,v=k.get(o.dir+"\x00"+p.path);i.push({group:h?"Current":"Workspaces",title:se(p),sub:c,when:v?te(v,a):void 0,hay:`${se(p)} ${c} ${p.path} workspace`,at:h?1/0:v??0,ico:"ws",act:()=>Ht(o.dir,p.path)});let y=Ve(o.dir,p.path),C=u[y];for(let x of C?.tabs??[]){if(!$n.includes(x.kind)||C.hidden?.includes(x.id))continue;let E=x.kind==="local"&&kn(y)||x.title;i.push({group:"Tabs",title:E,sub:`${se(p)} · ${c}`,hay:`${E} ${x.title} ${x.kind} ${x.note??""} ${se(p)} ${c} tab`,ico:"tab",act:()=>wn(o.dir,p.path,x.id)})}}i.push({group:"Projects",title:c,hay:`${c} ${o.dir} project`,ico:"proj",act:()=>{let p=o.workspaces?.find((h)=>h.main)??o.workspaces?.[0];p?Ht(o.dir,p.path):ne("board","/?view=board")()}})}for(let o of e.filter((c)=>!c.archived)){let c=ae(o);i.push({group:o.kind==="run"?"Runs":"Tasks",title:Ye(o)||o.id,sub:N(o.state,t),when:o.moved?te(o.moved,a):void 0,hay:`${Ye(o)} ${o.id??""} ${o.text??""} ${N(o.state,t)} ${c}`,at:o.moved??0,dot:c,ico:o.kind==="run"?"run":"idea",act:()=>{if(!Me("kz-open-card",{dir:o.state,id:o.kind==="run"?o.id:void 0,text:o.text}))location.href=Nt(o)}})}for(let o of Bt){let c=Date.parse(o.updated)||0;i.push({group:"Chats & terminals",title:o.title||"Chat",sub:o.project?N(o.project,t):void 0,when:c?te(c,a):void 0,hay:`${o.title} chat ${o.project??""}`,at:c,dot:o.busy?"build":void 0,ico:"chat",act:()=>{try{sessionStorage.setItem("kz-chat",o.id)}catch{}ne("home","/")()}})}for(let o of n)i.push({group:"Chats & terminals",title:o.name||o.agent||"Terminal",sub:N(o.dir,t),hay:`${o.name} ${o.agent??""} ${o.run??""} ${o.last??""} ${N(o.dir,t)} terminal agent`,at:o.at??o.born??0,dot:o.asking?"wait":o.busy?"build":"done",ico:"term",act:()=>{if(!Me("kz-open-term",{dir:o.dir,ws:o.ws,key:o.key}))location.href=X(o.dir,o.ws??"")}});let L=(o)=>()=>M(o)?.click(),f=[["Home","page",ne("home","/"),"chat"],["Icebox","page",ne("sources","/?view=icebox"),"requests sources gathered"],["Tasks","page",ne("tasks","/?view=tasks"),"backlog"],["Board","page",ne("board","/?view=board"),"kanban runs"],["Notes","page",()=>location.href="/notebook","notebook docs"],["Settings","page",ne("settings","/?view=settings"),"preferences config"],["New task","act",()=>M("newtop")?M("newtop").click():location.href="/?view=board","create add run"],["Add a project","act",()=>fe({dir:null}),"clone folder create workspace"],["Toggle theme","act",L("themet"),"dark light"],["Collapse or expand menu","act",L("fold"),"sidebar rail"],["Keyboard shortcuts","act",L("kbd"),"keys help"],["Report an issue","act",()=>open("/issue","_blank","noopener"),"bug feedback"]];for(let[o,c,p,h]of f)i.push({group:"Actions",title:o,hay:`${o} ${h??""}`,ico:c,act:p});return i}var Mn=["Current","Workspaces","Tabs","Chats & terminals","Runs","Tasks","Projects","Actions"],Sn={Workspaces:5,Tabs:4,"Chats & terminals":5,Runs:5,Tasks:3,Projects:5},S=null,O=[],q=0;function Ee(){let e=S.querySelector("input").value,t=En(),n=e.trim()?Ct(t,e):t.slice().sort((l,i)=>(i.at??0)-(l.at??0));O=[];let a=e.trim()?[...new Set(n.map((l)=>l.group))]:Mn;for(let l of a){let i=n.filter((u)=>u.group===l);O.push(...i.slice(0,e.trim()?8:Sn[l]??i.length))}if(e.trim())O.push({group:"Create",title:`New task "${e.trim()}"`,hay:"",ico:"plus",act:()=>Ln(e.trim())});q=Math.min(q,O.length-1);let s=S.querySelector(".gs-list"),r="";s.innerHTML=String(w`${O.map((l,i)=>{let u=l.group!==r?(r=l.group,w`<div class="gs-h" role="presentation">${l.group}</div>`):"";return w`${u}<div class="gs-i" role="option" id="gs-${i}" data-n="${i}" aria-selected="${String(i===q)}">${Rt(l.ico)}${l.dot?w`<span class="si ${l.dot}"></span>`:""}<span class="gs-t">${l.title}</span>${l.sub?w`<span class="gs-s">${l.sub}</span>`:""}${l.when?w`<span class="gs-w">${l.when}</span>`:""}</div>`})}${O.length===1&&e.trim()?w`<div class="gs-none">No results</div>`:""}`),Ge(q),S.querySelector(".gs-live").textContent=`${O.length} result${O.length===1?"":"s"} found`}function Ge(e){S.querySelector(`#gs-${q}`)?.setAttribute("aria-selected","false"),q=e;let t=S.querySelector(`#gs-${e}`);t?.setAttribute("aria-selected","true"),S.querySelector("input").setAttribute("aria-activedescendant","gs-"+e),t?.scrollIntoView({block:"nearest"})}function Ln(e){if(!M("newtop"))return void(location.href="/?view=board");M("newtop").click();let t=document.querySelector("dialog[open] textarea");if(t)t.value=e,t.dispatchEvent(new Event("input",{bubbles:!0}))}function It(e){let t=O[e];if(!t)return;S.close(),t.act()}function _e(){if(S)return S.querySelector("input").focus();S=document.createElement("dialog"),S.className="gs",S.setAttribute("aria-label","Search"),S.innerHTML=String(w`<div class="gs-box"><div class="gs-q">${Rt("search")}<input type="text" placeholder="Search" aria-label="Search" role="combobox" aria-expanded="true" aria-controls="gs-list" autocomplete="off" spellcheck="false"></div><div class="gs-list" id="gs-list" role="listbox"></div><span class="gs-live" role="status" aria-live="polite"></span></div>`),document.body.append(S);let e=S.querySelector("input");q=0,e.oninput=()=>(q=0,Ee()),e.onkeydown=(n)=>{let a={ArrowDown:1,ArrowUp:-1}[n.key]??(n.ctrlKey&&n.key==="n"?1:n.ctrlKey&&n.key==="p"?-1:0);if(a)n.preventDefault(),Ge((q+a+O.length)%O.length);else if(n.key==="Enter")n.preventDefault(),It(q)};let t=S.querySelector(".gs-list");t.onclick=(n)=>{let a=n.target.closest(".gs-i");if(a)It(+a.dataset.n)},t.onpointermove=(n)=>{let a=n.target.closest(".gs-i");if(a&&+a.dataset.n!==q)Ge(+a.dataset.n)},S.onclick=(n)=>n.target===S&&S.close(),S.onclose=()=>(S.remove(),S=null),S.showModal(),Ee(),fetch("/chats").then((n)=>n.json()).then((n)=>{if(Bt=n.chats??[],S)Ee()}).catch(()=>{})}var Tn=`dialog.gs{border:0;padding:0;margin:14vh auto auto;background:none;width:min(560px,calc(100vw - 32px));color:var(--ink);overflow:visible}
|
|
3
3
|
dialog.gs::backdrop{background:rgb(0 0 0/.35)}
|
|
4
4
|
.gs-box{display:flex;flex-direction:column;max-height:min(480px,72vh);background:var(--bg);border:1px solid var(--line);border-radius:10px;box-shadow:0 16px 40px rgb(0 0 0/.25);overflow:hidden}
|