kaizen-agent 1.51.0 → 1.53.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/cli/chat.ts ADDED
@@ -0,0 +1,322 @@
1
+ // Home's chat: conversations with kaizen's main agent, kept under ~/.kaizen/chats/<id>.json.
2
+ // A chat may be in a project (its .kaizen dir) or in none; the agent can move it to another
3
+ // project or make a new one. The agent is Codex, run headless per message (`codex exec
4
+ // --json`), and a follow-up continues its thread with `exec resume`.
5
+ import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
7
+ import { basename, dirname, join } from "node:path";
8
+ import { CHILD_ENV, readText } from "./state.ts";
9
+
10
+ export type Step = { kind: "cmd" | "edit" | "tool" | "project"; text: string; ok?: boolean };
11
+ export type Attachment = { name: string; path: string; image: boolean };
12
+ export type Upload = { name: string; bytes: Uint8Array };
13
+ export type Msg = { role: "user" | "agent"; text: string; files?: Attachment[]; steps?: Step[]; error?: string; activity?: string; at: string };
14
+ export type Chat = { id: string; title: string; project?: string; thread?: string; created: string; updated: string; messages: Msg[] };
15
+ // What the page is streamed while a turn runs, one JSON object per line.
16
+ export type Event =
17
+ | { t: "chat"; id: string }
18
+ | { t: "text"; text: string }
19
+ | { t: "status"; text: string }
20
+ | { t: "step"; step: Step }
21
+ | { t: "project"; dir: string | null }
22
+ | { t: "run"; dir: string }
23
+ | { t: "error"; error: string }
24
+ | { t: "done" };
25
+ // What the board knows, handed in by the server: its projects (state dirs), how it makes one,
26
+ // the agents installed, and how it starts a kaizen run in a project.
27
+ export type Board = {
28
+ projects: { dir: string; label: string }[];
29
+ create: (name: string) => Promise<{ dir: string } | { error: string }>;
30
+ agents: string[];
31
+ run: (dir: string, runner: "lite" | "full", agent: string, text: string) => Promise<{ agent: string } | { error: string }>;
32
+ };
33
+ // The project folders the agent may write in: every listed one, capped like the brief's list.
34
+ const roots = (board: Board) => board.projects.slice(0, 80).map((p) => dirname(p.dir));
35
+
36
+ export const okId = (id: unknown): id is string => typeof id === "string" && /^[\w-]{1,80}$/.test(id);
37
+ const file = (base: string, id: string) => join(base, "chats", `${id}.json`);
38
+ const uploadDir = (base: string, id: string) => join(base, "chats", id, "attachments");
39
+ const imageFile = (b: Uint8Array) =>
40
+ (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) ||
41
+ (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) ||
42
+ (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) ||
43
+ (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && String.fromCharCode(...b.slice(8, 12)) === "WEBP");
44
+
45
+ function saveUploads(base: string, id: string, uploads: Upload[]): Attachment[] {
46
+ const dir = uploadDir(base, id);
47
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
48
+ const paths: string[] = [];
49
+ try {
50
+ return uploads.map((u) => {
51
+ const name = u.name.replace(/[^\w.-]+/g, "_").replace(/^\.+/, "").slice(0, 100) || "file";
52
+ const path = join(dir, `${randomUUID()}-${name}`);
53
+ paths.push(path);
54
+ writeFileSync(path, u.bytes, { mode: 0o600 });
55
+ return { name, path, image: imageFile(u.bytes) };
56
+ });
57
+ } catch (err) {
58
+ for (const path of paths) rmSync(path, { force: true });
59
+ throw err;
60
+ }
61
+ }
62
+
63
+ // Ahead of every message, so a switch or a new project is known on the next turn; the page never shows it.
64
+ export function brief(c: Chat, board: Board) {
65
+ const here = board.projects.find((p) => p.dir === c.project);
66
+ const list = board.projects.slice(0, 80).map((p) => `- ${p.label} — ${dirname(p.dir)}`).join("\n");
67
+ return `[kaizen board context, not written by the user]
68
+ You are kaizen's main agent, talking with the user from the kaizen board's Home page.
69
+ Project of this chat: ${here ? `${here.label} (${dirname(here.dir)})` : "none — you are in a scratch folder"}.
70
+ Projects on the board:
71
+ ${list || "(none)"}
72
+ You can read, analyse and edit files in any project folder listed above directly by its path; you do not need to switch to it. Do not write outside those folders and your working folder.
73
+ Switching only changes this chat's home project (where you run and which project the board shows). On a line of its own write [[kaizen:project <folder>]] to switch to a listed project, or [[kaizen:new-project <name>]] to create one (a plain folder name). Switch only when the user asks; when what they want fits no listed project, ask whether to create a new one. After a successful move, the board starts one follow-up turn in the new project to finish the pending request; do not ask the user to repeat it.
74
+ When the user asks you to develop, fix, change or enhance something (not a question, analysis or reading), first ask which way, as numbered options, and do nothing until they pick:
75
+ 1. Start a kaizen run for it: lite (cheap, one session) or full (independent review), with which agent (installed: ${board.agents.join(", ") || "none"}), in which project.
76
+ 2. Let you handle it here in the chat.
77
+ For 1, once they pick, write on a line of its own [[kaizen:run <project folder> | <lite or full> | <agent> | <the request, one line>]]; the board starts the run in that project and it shows there. Do not start it yourself with /kaizen. For 2, do the work directly.
78
+ Keep replies short.
79
+ [end of context]
80
+
81
+ `;
82
+ }
83
+
84
+ export function readChat(base: string, id: string): Chat | null {
85
+ if (!okId(id)) return null;
86
+ try { return JSON.parse(readText(file(base, id))); } catch { return null; }
87
+ }
88
+
89
+ function save(base: string, c: Chat) {
90
+ mkdirSync(join(base, "chats"), { recursive: true });
91
+ writeFileSync(file(base, c.id), JSON.stringify(c, null, 2));
92
+ }
93
+
94
+ // Newest first, without the messages.
95
+ export function listChats(base: string) {
96
+ const d = join(base, "chats");
97
+ if (!existsSync(d)) return [];
98
+ return readdirSync(d).filter((f) => f.endsWith(".json"))
99
+ .map((f) => readChat(base, f.slice(0, -5)))
100
+ .filter((c): c is Chat => !!c)
101
+ .map(({ id, title, project, updated }) => ({ id, title, project: project ?? null, updated, busy: live.has(base + "|" + id) }))
102
+ .sort((a, b) => b.updated.localeCompare(a.updated));
103
+ }
104
+
105
+ export function deleteChat(base: string, id: string) {
106
+ if (!okId(id)) return "bad chat id";
107
+ if (live.has(base + "|" + id)) return "this chat is still working";
108
+ rmSync(file(base, id), { force: true });
109
+ rmSync(join(base, "chats", id), { recursive: true, force: true });
110
+ return null;
111
+ }
112
+
113
+ // One turn at a time per chat; the page can leave and the turn still finishes and saves.
114
+ const live = new Map<string, { kill: () => void }>();
115
+ export const busy = (base: string, id: string) => live.has(base + "|" + id);
116
+
117
+ export function stopChat(base: string, id: string) {
118
+ const p = live.get(base + "|" + id);
119
+ p?.kill();
120
+ return !!p;
121
+ }
122
+
123
+ const short = (s: string, n = 120) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
124
+ const command = (s: unknown) => short(String(s ?? "").replace(/^\S*\/(?:ba|z)?sh -lc (?:(['"])([\s\S]*)\1|([\s\S]*))$/, "$2$3"));
125
+
126
+ // One `codex exec --json` line as what the page shows; null for what it does not.
127
+ export function parseLine(line: string): Event | { t: "thread"; id: string } | null {
128
+ let e: any;
129
+ try { e = JSON.parse(line); } catch { return null; }
130
+ if (e?.type === "thread.started" && typeof e.thread_id === "string") return { t: "thread", id: e.thread_id };
131
+ if (e?.type === "turn.failed") return { t: "error", error: String(e.error?.message ?? "the agent failed") };
132
+ if (e?.type === "turn.started") return { t: "status", text: "Thinking…" };
133
+ if (e?.type === "item.started" && e.item) {
134
+ const it = e.item;
135
+ if (it.type === "command_execution") return { t: "status", text: `Running ${command(it.command) || "a command"}` };
136
+ if (it.type === "mcp_tool_call") return { t: "status", text: `Using ${short(`${it.server ?? ""} ${it.tool ?? ""}`.trim()) || "a tool"}` };
137
+ if (it.type === "web_search") return { t: "status", text: "Searching the web…" };
138
+ if (it.type === "file_change") return { t: "status", text: "Editing files…" };
139
+ if (it.type === "reasoning") return { t: "status", text: "Thinking…" };
140
+ if (it.type === "agent_message") return { t: "status", text: "Writing reply…" };
141
+ return null;
142
+ }
143
+ if (e?.type !== "item.completed" || !e.item) return null;
144
+ const it = e.item;
145
+ if (it.type === "agent_message" && it.text) return { t: "text", text: String(it.text) };
146
+ if (it.type === "command_execution")
147
+ return { t: "step", step: { kind: "cmd", text: command(it.command), ok: it.exit_code === 0 } };
148
+ if (it.type === "file_change" && Array.isArray(it.changes))
149
+ return { t: "step", step: { kind: "edit", text: short(it.changes.map((c: any) => c.path).join(", ")), ok: it.status !== "failed" } };
150
+ if (it.type === "mcp_tool_call") return { t: "step", step: { kind: "tool", text: short(`${it.server ?? ""} ${it.tool ?? ""}`.trim()), ok: it.status !== "failed" } };
151
+ if (it.type === "web_search") return { t: "step", step: { kind: "tool", text: "Web search", ok: it.status !== "failed" } };
152
+ return null;
153
+ }
154
+
155
+ // The agent's move and run lines: taken out of what the user reads; the last of each counts.
156
+ const MOVE = /^[ \t]*\[\[kaizen:(project|new-project|run)[ \t]+([^\]\n]+?)\]\][ \t]*$/gm;
157
+ export type RunAsk = { project: string; runner: string; agent: string; text: string };
158
+ export function takeMoves(text: string) {
159
+ let move: { op: "project" | "new-project"; arg: string } | null = null;
160
+ let run: RunAsk | null = null;
161
+ const rest = text.replace(MOVE, (_, op, arg) => {
162
+ if (op !== "run") move = { op, arg: arg.trim() };
163
+ else {
164
+ const [project = "", runner = "", agent = "", ...t] = arg.split("|").map((x: string) => x.trim());
165
+ run = { project, runner, agent, text: t.join(" | ").trim() };
166
+ }
167
+ return "";
168
+ }).replace(/\n{3,}/g, "\n\n").trim();
169
+ return { text: rest, move: move as { op: "project" | "new-project"; arg: string } | null, run: run as RunAsk | null };
170
+ }
171
+
172
+ // Not winShim: the message goes in on stdin, so the .cmd shim's newline limit never applies.
173
+ const codexBin = () => Bun.which("codex", { PATH: process.env.PATH });
174
+
175
+ // project: where a new chat starts (a state dir the board knows), ignored for an existing chat.
176
+ export function sendChat(base: string, id: string | null, text: string, project: string | null, board: Board, emit: (e: Event) => void, reuseReply = false, uploads: Upload[] = []): string | null {
177
+ const bin = codexBin();
178
+ if (!bin) return "Chat needs Codex: install it (npm i -g @openai/codex) and sign in.";
179
+ const now = new Date().toISOString();
180
+ let c = id ? readChat(base, id) : null;
181
+ if (id && !c) return "no such chat";
182
+ if (!c) c = {
183
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, title: short(text.split("\n")[0] || uploads[0]?.name || "Chat", 60),
184
+ project: board.projects.some((p) => p.dir === project) ? project! : undefined, created: now, updated: now, messages: [],
185
+ };
186
+ const key = base + "|" + c.id;
187
+ if (live.has(key)) return "this chat is still working";
188
+ const chat = c;
189
+ if (reuseReply && chat.messages.at(-1)?.role !== "agent") return "no reply to continue";
190
+ if (uploads.length > 5 || uploads.some((u) => !u.name || u.bytes.length > 10 * 1024 * 1024) || uploads.reduce((n, u) => n + u.bytes.length, 0) > 20 * 1024 * 1024) return "up to 5 files, 10 MB each and 20 MB total";
191
+ // A project that left the board since: the chat goes on without one.
192
+ if (chat.project && !board.projects.some((p) => p.dir === chat.project)) chat.project = undefined;
193
+ let files: Attachment[] = [];
194
+ try { if (uploads.length) files = saveUploads(base, chat.id, uploads); }
195
+ catch (err: any) { return `Could not save attachment: ${err?.message ?? err}`; }
196
+ if (!reuseReply) chat.messages.push({ role: "user", text, ...(files.length ? { files } : {}), at: now });
197
+ const reply: Msg = reuseReply ? chat.messages.at(-1)! : { role: "agent", text: "", steps: [], at: now };
198
+ if (!reuseReply) chat.messages.push(reply);
199
+ reply.activity = "Thinking…";
200
+ chat.updated = now;
201
+ save(base, chat);
202
+
203
+ // No project: a scratch folder outside every project.
204
+ const scratch = join(base, "chats", "scratch");
205
+ if (!chat.project) mkdirSync(scratch, { recursive: true });
206
+ const cwd = chat.project ? dirname(chat.project) : scratch;
207
+ // Same scrub as launchRun: a board started inside an agent session must not hand that identity on.
208
+ const env: Record<string, string> = {};
209
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !CHILD_ENV.test(k)) env[k] = v;
210
+ const images = files.filter((f) => f.image).flatMap((f) => ["-i", f.path]);
211
+ // Every listed project is writable, so the agent works on any of them without a switch.
212
+ const dirs = roots(board).filter((d) => d !== cwd).flatMap((d) => ["--add-dir", d]);
213
+ const argv = [bin, "exec", "--json", "--skip-git-repo-check", "-s", "workspace-write", ...dirs,
214
+ "-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium", ...(chat.thread ? ["resume", chat.thread] : []), ...images, "-"];
215
+ let p;
216
+ try { p = Bun.spawn(argv, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" }); }
217
+ catch (err: any) {
218
+ reply.error = `Could not start codex: ${err?.message ?? err}`;
219
+ delete reply.activity;
220
+ save(base, chat);
221
+ return reply.error;
222
+ }
223
+ p.stdin.write(brief(chat, board) + text + (files.length ? `\n\nAttached files (read these paths as needed):\n${files.map((f) => `- ${f.name}: ${f.path}`).join("\n")}` : ""));
224
+ p.stdin.end();
225
+ // Read alongside stdout: an undrained stderr pipe fills and stalls the agent.
226
+ const errText = new Response(p.stderr).text();
227
+ let stopped = false;
228
+ // Stop also lets go of stdout: a grandchild the agent started can hold the pipe open after it dies.
229
+ const reader = (p.stdout as ReadableStream<Uint8Array>).getReader();
230
+ live.set(key, { kill: () => { stopped = true; p.kill(); reader.cancel().catch(() => {}); } });
231
+ emit({ t: "chat", id: chat.id });
232
+
233
+ (async () => {
234
+ const dec = new TextDecoder();
235
+ let buf = "";
236
+ let move: ReturnType<typeof takeMoves>["move"] = null;
237
+ let run: RunAsk | null = null;
238
+ const take = (line: string) => {
239
+ const e = parseLine(line);
240
+ if (!e) return;
241
+ if (e.t === "thread") { chat.thread = e.id; save(base, chat); return; }
242
+ if (e.t === "text") {
243
+ const m = takeMoves(e.text);
244
+ if (m.move) move = m.move;
245
+ if (m.run) run = m.run;
246
+ if (!m.text) return;
247
+ e.text = m.text;
248
+ reply.text += (reply.text ? "\n\n" : "") + e.text;
249
+ }
250
+ if (e.t === "step") reply.steps!.push(e.step);
251
+ if (e.t === "status") reply.activity = e.text;
252
+ if (e.t === "step") reply.activity = "Thinking…";
253
+ if (e.t === "error") reply.error = e.error;
254
+ save(base, chat);
255
+ emit(e);
256
+ };
257
+ try {
258
+ for (let r; !(r = await reader.read()).done;) {
259
+ buf += dec.decode(r.value, { stream: true });
260
+ let i;
261
+ while ((i = buf.indexOf("\n")) >= 0) { take(buf.slice(0, i)); buf = buf.slice(i + 1); }
262
+ }
263
+ if (buf.trim()) take(buf);
264
+ const code = await p.exited;
265
+ if (stopped) { reply.error = "Stopped."; emit({ t: "error", error: reply.error }); }
266
+ else if (code !== 0 && !reply.error && !reply.text) {
267
+ const err = (await errText).trim().split("\n").filter((l) => !/^\S+Z\s+(WARN|ERROR) /.test(l)).slice(-3).join("\n");
268
+ reply.error = err || `codex exited with code ${code}`;
269
+ emit({ t: "error", error: reply.error });
270
+ }
271
+ if (run && !stopped) await startRun(reply, run, board, emit);
272
+ if (move && !stopped) await moveChat(chat, reply, move, board, emit);
273
+ } finally {
274
+ delete reply.activity;
275
+ chat.updated = new Date().toISOString();
276
+ save(base, chat);
277
+ live.delete(key);
278
+ emit({ t: "done" });
279
+ }
280
+ })();
281
+ return null;
282
+ }
283
+
284
+ const findProject = (board: Board, arg: string) => {
285
+ const a = arg.replace(/[\\/]+$/, "");
286
+ return board.projects.find((x) => x.dir === a || dirname(x.dir) === a || x.dir === join(a, ".kaizen"))
287
+ ?? board.projects.find((x) => x.label === a || basename(dirname(x.dir)) === a);
288
+ };
289
+
290
+ // Start the run the user picked: only in a listed project, with an installed agent.
291
+ async function startRun(reply: Msg, ask: RunAsk, board: Board, emit: (e: Event) => void) {
292
+ const step = (text: string, ok: boolean) => { const s: Step = { kind: "project", text, ok }; reply.steps!.push(s); emit({ t: "step", step: s }); };
293
+ const p = findProject(board, ask.project);
294
+ if (!p) return step(`No project ${ask.project} on the board`, false);
295
+ if (ask.runner !== "lite" && ask.runner !== "full") return step(`Unknown runner ${ask.runner}`, false);
296
+ if (!board.agents.includes(ask.agent)) return step(`Agent ${ask.agent} is not installed`, false);
297
+ if (!ask.text) return step("No request for the run", false);
298
+ const r = await board.run(p.dir, ask.runner, ask.agent, ask.text);
299
+ if ("error" in r) return step(`Could not start the run: ${r.error}`, false);
300
+ step(`Started a ${ask.runner} run in ${p.label} with ${r.agent}`, true);
301
+ emit({ t: "run", dir: p.dir });
302
+ }
303
+
304
+ // Apply the agent's move: only to a project the board lists, or one the board's own rules create.
305
+ async function moveChat(chat: Chat, reply: Msg, move: { op: string; arg: string }, board: Board, emit: (e: Event) => void) {
306
+ const step = (text: string, ok: boolean) => { const s: Step = { kind: "project", text, ok }; reply.steps!.push(s); emit({ t: "step", step: s }); };
307
+ let dir: string | null = null;
308
+ if (move.op === "project") {
309
+ const p = findProject(board, move.arg);
310
+ if (!p) return step(`No project ${move.arg} on the board`, false);
311
+ dir = p.dir;
312
+ } else {
313
+ const r = await board.create(move.arg);
314
+ if ("error" in r) return step(`Could not create ${move.arg}: ${r.error}`, false);
315
+ dir = r.dir;
316
+ board.projects.push({ dir, label: move.arg });
317
+ }
318
+ if (dir === chat.project) return;
319
+ chat.project = dir;
320
+ step(`${move.op === "new-project" ? "Created" : "Switched to"} ${board.projects.find((x) => x.dir === dir)?.label ?? move.arg}`, true);
321
+ emit({ t: "project", dir });
322
+ }
package/cli/install.ts CHANGED
@@ -460,6 +460,77 @@ if (args.has("prune")) {
460
460
  process.exit(0);
461
461
  }
462
462
 
463
+ // `kaizen chat`: Home's chat in a small window over the desktop, like Hermes's HUD.
464
+ // Bind it to a hotkey: run again while the window is open and it closes.
465
+ if (Bun.argv[2] === "chat") {
466
+ const at = Bun.argv.indexOf("--port");
467
+ const port = at !== -1 ? Number(Bun.argv[at + 1]) || 7420 : 7420;
468
+ const url = `http://127.0.0.1:${port}/`;
469
+ const { current } = await import("./web.ts");
470
+ if (!(await current(url))) await Bun.spawn([process.execPath, Bun.main, "web", "--daemon", "--no-open", "--port", String(port)], { stdout: "ignore", stderr: "inherit" }).exited;
471
+ // Chromium on Wayland ignores --class: the app window's class comes from the URL.
472
+ const isChat = (c: any) => c.class === "kaizen-chat" || String(c.class).startsWith("chrome-127.0.0.1__popup");
473
+ const hypr = !!process.env.HYPRLAND_INSTANCE_SIGNATURE && !!Bun.which("hyprctl");
474
+ const clients = async (): Promise<any[]> => hypr ? await Bun.$`hyprctl clients -j`.quiet().nothrow().json().catch(() => []) : [];
475
+ if (hypr) {
476
+ const { listSettings, bindChatHotkey } = await import("./settings.ts");
477
+ const keys = listSettings(dirname(import.meta.dir)).rows.find((r) => r.key === "board.chat_hotkey")?.value;
478
+ if (keys) bindChatHotkey(String(keys), undefined, true);
479
+ }
480
+ const open = (await clients()).find(isChat);
481
+ // Where the window was left, so the next one opens there.
482
+ const spot = join(home, ".kaizen", "chat-window.json");
483
+ // --show only opens (the board's Pop out), --close only closes (the popup's Back);
484
+ // plain `kaizen chat` toggles, for a hotkey.
485
+ if (open && Bun.argv.includes("--show")) {
486
+ await Bun.$`hyprctl dispatch ${`hl.dsp.focus({ window = "address:${open.address}" })`}`.quiet().nothrow();
487
+ process.exit(0);
488
+ }
489
+ if (!open && Bun.argv.includes("--close")) process.exit(0);
490
+ if (open) {
491
+ try { writeFileSync(spot, JSON.stringify({ x: open.at[0], y: open.at[1] })); } catch {}
492
+ try { process.kill(open.pid, "SIGTERM"); } catch {}
493
+ process.exit(0);
494
+ }
495
+ // A see-through WebKitGTK window when python3 has it; Chromium paints a background.
496
+ const ci = Bun.argv.indexOf("--chat"), chatId = ci !== -1 ? Bun.argv[ci + 1] ?? "" : "";
497
+ const page = `${url}popup${/^[\w.-]+$/.test(chatId) ? `?chat=${chatId}` : ""}`;
498
+ const shell = join(import.meta.dir, "chat-window.py");
499
+ const py = Bun.which("python3");
500
+ const bin = ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "microsoft-edge", "brave", "brave-browser"].map((b) => Bun.which(b)).find(Boolean);
501
+ const cmd = py && Bun.spawnSync([py, shell, "--check"], { stdout: "ignore", stderr: "ignore" }).exitCode === 0 ? [py, shell, page]
502
+ // Its own profile, so it is its own process: closing it never takes the browser along.
503
+ : bin ? [bin, `--app=${page}`, `--user-data-dir=${join(home, ".kaizen", "chat-window")}`, "--window-size=420,600"] : null;
504
+ if (!cmd) { console.log(` no Chromium-based browser found; open ${url}popup instead`); process.exit(1); }
505
+ Bun.spawn(cmd, { stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true }).unref();
506
+ if (hypr) {
507
+ let win: any;
508
+ for (let i = 0; i < 50 && !(win = (await clients()).find(isChat)); i++) await Bun.sleep(100);
509
+ if (win) {
510
+ // Hyprland 0.55+ on a Lua config reads dispatch as Lua; older ones want the classic words.
511
+ const w = `address:${win.address}`;
512
+ const mon = (await Bun.$`hyprctl monitors -j`.quiet().nothrow().json().catch(() => [])).find((m: any) => m.id === win.monitor);
513
+ let x = mon ? mon.x + Math.round(mon.width / mon.scale) - 440 : 100, y = mon ? mon.y + Math.round(mon.height / mon.scale) - 640 : 100;
514
+ // The saved spot, while it is still on a connected monitor.
515
+ const was = (() => { try { return JSON.parse(readFileSync(spot, "utf8")); } catch { return null; } })();
516
+ const mons: any[] = await Bun.$`hyprctl monitors -j`.quiet().nothrow().json().catch(() => []);
517
+ if (Number.isFinite(was?.x) && Number.isFinite(was?.y) && mons.some((m) => was.x >= m.x && was.y >= m.y && was.x < m.x + m.width / m.scale && was.y < m.y + m.height / m.scale)) ({ x, y } = was);
518
+ const steps = [
519
+ [`hl.dsp.window.float({ action = "enable", window = "${w}" })`, `setfloating ${w}`],
520
+ [`hl.dsp.window.pin({ action = "enable", window = "${w}" })`, `pin ${w}`],
521
+ // No border, rounding or shadow: only the bubbles show.
522
+ [`hl.dsp.window.set_prop({ prop = "no_shadow", value = "1", window = "${w}" })`, `setprop ${w} no_shadow 1`],
523
+ [`hl.dsp.window.set_prop({ prop = "border_size", value = "0", window = "${w}" })`, `setprop ${w} border_size 0`],
524
+ [`hl.dsp.window.resize({ x = 420, y = 600, window = "${w}" })`, `resizewindowpixel exact 420 600,${w}`],
525
+ [`hl.dsp.window.move({ x = ${x}, y = ${y}, window = "${w}" })`, `movewindowpixel exact ${x} ${y},${w}`],
526
+ ];
527
+ for (const [lua, legacy] of steps)
528
+ if ((await Bun.$`hyprctl dispatch ${lua}`.quiet().nothrow().text()).trim() !== "ok") await Bun.$`hyprctl dispatch ${legacy.split(" ")}`.quiet().nothrow();
529
+ }
530
+ }
531
+ process.exit(0);
532
+ }
533
+
463
534
  if (wantWeb) {
464
535
  if (args.has("--shortcut")) { const { shortcut } = await import("./web.ts"); console.log(`\n kaizen web shortcut ${await shortcut()}\n`); process.exit(0); }
465
536
  const at = Bun.argv.indexOf("--port");
@@ -957,8 +1028,12 @@ function installLauncher() {
957
1028
  ? join(process.env.BUN_INSTALL ?? join(home, ".bun"), "bin")
958
1029
  : join(home, ".local", "bin");
959
1030
  const bin = join(binDir, win ? "kaizen.cmd" : "kaizen");
1031
+ // Windows calls bun by full path: cmd.exe on some machines cannot find bun on PATH
1032
+ // even when PowerShell can, and `kaizen` then fails with "'bun' is not recognized".
1033
+ // POSIX keeps `bun`, since version managers (mise, asdf) put bun under a versioned
1034
+ // path that an upgrade removes.
960
1035
  const script = win
961
- ? `@echo off\r\nrem kaizen launcher -- installed by kaizen-agent\r\nbun run "${entry}" %*\r\n`
1036
+ ? `@echo off\r\nrem kaizen launcher -- installed by kaizen-agent\r\n"${process.execPath}" run "${entry}" %*\r\n`
962
1037
  : `#!/bin/sh\n# kaizen launcher -- installed by kaizen-agent\nexec bun run ${entry} "$@"\n`;
963
1038
  try {
964
1039
  if (existsSync(bin) && readFileSync(bin, "utf8") === script) return;
package/cli/settings.ts CHANGED
@@ -127,6 +127,7 @@ const SETTINGS: Setting[] = [
127
127
  { key: "board.projects_dir", label: "Projects folder", group: "Board", values: [], text: true, folder: true, help: "Empty: known projects only" },
128
128
  { key: "board.video_dir", label: "Video library folder", group: "Board", values: [], text: true, folder: true, help: "Empty: ~/.kaizen" },
129
129
  { key: "board.open", label: "Open the board in", group: "Board", values: ["browser", "app"], help: "" },
130
+ { key: "board.chat_hotkey", label: "Popup chat hotkey", group: "Board", values: [], text: true, help: "Hyprland, e.g. SUPER + ALT + SPACE. Empty: none" },
130
131
  { key: "ui.mouse", label: "Enable mouse", group: "Terminal", values: ["false", "true"], help: "" },
131
132
  ];
132
133
 
@@ -169,7 +170,9 @@ export function setSetting(repoRoot: string, key: string, value: string) {
169
170
  updated = write(updated, "preset", detectPreset(updated, defaults), defaults);
170
171
  if (read(updated, key) !== value) return { error: `${key} did not save; edit ${tilde(file)} by hand` };
171
172
  }
173
+ if (key === "board.chat_hotkey" && !HOTKEY.test(value)) return { error: "keys are words joined by +, e.g. SUPER + ALT + SPACE" };
172
174
  writeFileSync(file, updated);
175
+ if (key === "board.chat_hotkey") bindChatHotkey(value);
173
176
  return { ok: true };
174
177
  }
175
178
 
@@ -493,3 +496,25 @@ function tilde(p: string) {
493
496
  const h = homedir();
494
497
  return p.startsWith(h) ? "~" + p.slice(h.length) : p;
495
498
  }
499
+
500
+ // `board.chat_hotkey`: the key that toggles `kaizen chat`, written into the Hyprland
501
+ // config as a marked block, unbinding whatever held the key first. Hyprland reloads
502
+ // the file by itself. Elsewhere there is nowhere to bind it; returns where it went.
503
+ const HOTKEY = /^$|^[A-Za-z0-9_]+( *\+ *[A-Za-z0-9_]+)*$/;
504
+ const BEGIN = "kaizen chat hotkey (written by kaizen; change it in kaizen settings)", END = "end kaizen chat hotkey";
505
+ // `missingOnly`: leave a block already there alone (`kaizen chat` applying the default).
506
+ export function bindChatHotkey(keys: string, dir = join(homedir(), ".config", "hypr"), missingOnly = false) {
507
+ if (!HOTKEY.test(keys)) return null;
508
+ const lua = join(dir, "bindings.lua"), conf = join(dir, "hyprland.conf");
509
+ const file = existsSync(lua) ? lua : existsSync(conf) ? conf : null;
510
+ if (!file || (missingOnly && readText(file).includes(BEGIN))) return null;
511
+ const k = keys.split("+").map((x) => x.trim().toUpperCase());
512
+ const cmd = Bun.which("kaizen") ?? "kaizen";
513
+ const c = file === lua ? "--" : "#";
514
+ const body = !keys ? "" : file === lua
515
+ ? `pcall(hl.unbind, "${k.join(" + ")}")\no.bind("${k.join(" + ")}", "kaizen chat", "${cmd} chat")`
516
+ : `unbind = ${k.slice(0, -1).join(" ")}, ${k.at(-1)}\nbind = ${k.slice(0, -1).join(" ")}, ${k.at(-1)}, exec, ${cmd} chat`;
517
+ const text = readText(file).replace(new RegExp(`\\n?${c} ${BEGIN.replace(/[()]/g, "\\$&")}[\\s\\S]*?${c} ${END}\\n?`), "\n");
518
+ writeFileSync(file, text.replace(/\n*$/, "\n") + (body ? `\n${c} ${BEGIN}\n${body}\n${c} ${END}\n` : ""));
519
+ return file;
520
+ }
package/cli/state.ts CHANGED
@@ -128,7 +128,7 @@ const shq = (a: string) => `'${a.replace(/'/g, `'\\''`)}'`;
128
128
  // every `key:\n` regex the same silent way, so line endings are made LF here too.
129
129
  export const readText = (file: string) => readFileSync(file, "utf8").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
130
130
 
131
- const onPath = (bin: string) => Bun.which(bin, { PATH: process.env.PATH });
131
+ export const onPath = (bin: string) => Bun.which(bin, { PATH: process.env.PATH });
132
132
 
133
133
  // npm installs a Windows tool as x.cmd with x.ps1 beside it. PowerShell hands a .cmd to
134
134
  // cmd.exe, which ends the command line at the first newline -- a prompt with notes lost
@@ -1636,7 +1636,7 @@ export function trustFolder(dir: string, cfg = join(process.env.CLAUDE_CONFIG_DI
1636
1636
  // pick: the tool, model and yolo chosen for a new run; a decision takes the run's own
1637
1637
  // tool and model, and stays in Yolo when the run was started in it. card: run it inside the board (agent.launch: card),
1638
1638
  // where a pseudo-terminal exists; onChange is told when that agent ends.
1639
- const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_SESSION|SESSION_ATTENDED|MESSAGING_SOCKET|MESSAGING_TOKEN))$/;
1639
+ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_SESSION|SESSION_ATTENDED|MESSAGING_SOCKET|MESSAGING_TOKEN))$/;
1640
1640
 
1641
1641
  // skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
1642
1642
  // a work folder that may not be a project, so it is not remembered as one. A session record is