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/web.ts CHANGED
@@ -4,7 +4,7 @@ import { existsSync, readdirSync, statSync, watch, appendFileSync, mkdirSync, cp
4
4
  import { join, dirname, resolve, sep, basename } from "node:path";
5
5
  import {
6
6
  home, type Item, type Card, boardCards, knownProjects, remember, locate, label, tilde, searchRoots, findProjects,
7
- readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
7
+ readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
8
8
  appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, notice, notifier, LOGO,
9
9
  reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, nativePath, closeSessions, sweepSessions, issueUrl,
10
10
  launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
@@ -20,6 +20,7 @@ import { listNotes, saveNote, renameNote, deleteNote, boardIndex, linksTo } from
20
20
  import * as video from "./video.ts";
21
21
  import * as localsend from "./localsend.ts";
22
22
  import * as hermes from "./hermes.ts";
23
+ import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
23
24
 
24
25
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
25
26
  // The board's script: web/board/*.ts, bundled into one file by `bun run build:web`.
@@ -33,6 +34,9 @@ const TERM_JS = join(dirname(import.meta.dir), "web", "term.js");
33
34
  const TERM_CSS = join(dirname(import.meta.dir), "web", "term.css");
34
35
  // The Video page (kaizen-video's library, editor and renders) and its bundle.
35
36
  const VIDEO_PAGE = join(dirname(import.meta.dir), "web", "video.html");
37
+ const POPUP_PAGE = join(dirname(import.meta.dir), "web", "popup.html");
38
+ // The chat the popup was on when its Back button was pressed, until Home takes it.
39
+ let popupChat: string | null = null;
36
40
  const VIDEO_JS = join(dirname(import.meta.dir), "web", "video.js");
37
41
  const DEFAULT_PORT = 7420;
38
42
  // Gathered posts a reply is going out to right now: one send per item at a time.
@@ -158,6 +162,30 @@ export async function web(repoDir: string, opts: Opts = {}) {
158
162
  .filter((d) => existsSync(join(d, ".kaizen")) ? (remember(d), false) : true).sort();
159
163
  };
160
164
 
165
+ // New project…: a folder in the Projects folder setting (else ~/Projects) or at `to`,
166
+ // empty or new, with .kaizen, registered. check: only say where it would go.
167
+ async function makeProject(name: string, t = "", check = false): Promise<{ dir: string } | { to: string } | { error: string; status?: number }> {
168
+ // Windows' rules on every platform, so a project made here also opens there:
169
+ // no reserved device names (CON, NUL, COM1…), no trailing dot or space.
170
+ const winBad = (n: string) => !n || /[\\/:*?"<>|\x00-\x1f]/.test(n) || /[. ]$/.test(n)
171
+ || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(n);
172
+ const to = t ? resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t))
173
+ : join((await projectsRoot()) || join(home, "Projects"), name);
174
+ // The page asks while the name is typed: "con" on the way to "config" is no error yet.
175
+ if (check) return { to };
176
+ if (winBad(name)) return { error: "name the project: a folder name, without / \\ : * ? \" < > |, not ending in a dot or space, and not CON, NUL, COM1 or the like" };
177
+ if (winBad(basename(to))) return { error: `${basename(to)} cannot be a folder name on Windows` };
178
+ let used = false;
179
+ try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
180
+ if (used) return { error: `${to} already exists and is not empty`, status: 409 };
181
+ // A drive that is not there, a read-only folder, a path too long: said in a toast, not a crash.
182
+ try { mkdirSync(join(to, ".kaizen"), { recursive: true }); }
183
+ catch (e) { return { error: `could not create ${to}: ${(e as Error).message}` }; }
184
+ remember(to);
185
+ changed();
186
+ return { dir: join(to, ".kaizen") };
187
+ }
188
+
161
189
  const states = (all: boolean, cur = boardState) => (all || !cur
162
190
  ? [...knownProjects().map((d) => join(d, ".kaizen")), join(home, ".kaizen")]
163
191
  : [cur]
@@ -220,9 +248,6 @@ export async function web(repoDir: string, opts: Opts = {}) {
220
248
  return { key, alive: st.alive, asking: st.asking };
221
249
  };
222
250
  };
223
- // Dev: the page reloads itself when board.html or its bundle is saved. Server code needs
224
- // `bun --watch cli/install.ts web`; the page reconnects and reloads on hello.
225
- for (const f of [PAGE, BOARD_JS]) try { watch(f, () => { for (const c of clients) { try { c.enqueue("data: reload\n\n"); } catch { clients.delete(c); } } }); } catch { /* no dev reload */ }
226
251
  const watchers: FSWatcher[] = [];
227
252
  const watchAll = () => {
228
253
  for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
@@ -386,6 +411,63 @@ export async function web(repoDir: string, opts: Opts = {}) {
386
411
  return new Response(body, { headers: { "content-type": type, "cache-control": "no-store" } });
387
412
  }
388
413
 
414
+ // `kaizen chat`: the small chat window over the desktop.
415
+ if (req.method === "GET" && path === "/popup") {
416
+ const body = served(POPUP_PAGE);
417
+ if (body === null) return new Response("web/popup.html missing", { status: 500 });
418
+ return new Response(body, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } });
419
+ }
420
+
421
+ // Handing the chat between Home and the popup (`kaizen chat`). /popup/open:
422
+ // open the popup on Home's chat and hide the board's browser window in a
423
+ // special workspace. /popup/board: bring that window back, focus it (open the
424
+ // board when no window shows it) and close the popup. Hyprland moves windows;
425
+ // elsewhere only the popup opens and closes.
426
+ if (req.method === "POST" && (path === "/popup/open" || path === "/popup/board")) {
427
+ const body = await req.json().catch(() => ({}));
428
+ const chat = (...a: string[]) => Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "chat", "--port", String(new URL(req.url).port || DEFAULT_PORT), ...a], { stdout: "ignore", stderr: "ignore" }).exited;
429
+ const hypr = !!process.env.HYPRLAND_INSTANCE_SIGNATURE && !!Bun.which("hyprctl");
430
+ const json = async (cmd: string) => await Bun.$`hyprctl ${cmd} -j`.quiet().nothrow().json().catch(() => null);
431
+ // Several windows can show a board: Pop out takes the one clicked in (the active
432
+ // one), Back the one Pop out hid.
433
+ const isBoard = (c: any) => c && /(^|\) )kaizen( [—-] |$)/.test(String(c.title));
434
+ const all: any[] = hypr ? (await json("clients")) || [] : [];
435
+ const active = hypr ? await json("activewindow") : null;
436
+ const board = path === "/popup/open" ? (isBoard(active) ? active : all.find(isBoard))
437
+ : all.find((c) => isBoard(c) && c.workspace?.name === "special:kaizen") ?? all.find(isBoard);
438
+ const w = board && `address:${board.address}`;
439
+ // Lua grammar first (Hyprland 0.55+ with a Lua config), the classic words after.
440
+ const dispatch = async (lua: string, legacy: string[]) => {
441
+ if ((await Bun.$`hyprctl dispatch ${lua}`.quiet().nothrow().text()).trim() !== "ok") await Bun.$`hyprctl dispatch ${legacy}`.quiet().nothrow();
442
+ };
443
+ if (path === "/popup/open") {
444
+ const id = typeof body.id === "string" && /^[\w.-]+$/.test(body.id) ? body.id : "";
445
+ await chat("--show", ...(id ? ["--chat", id] : []));
446
+ if (w) await dispatch(`hl.dsp.window.move({ workspace = "special:kaizen", follow = false, window = "${w}" })`, ["movetoworkspacesilent", `special:kaizen,${w}`]);
447
+ // Typing goes to the popup, not to whatever was under the hidden board.
448
+ const pop = hypr && ((await json("clients")) || []).find((c: any) => c.class === "kaizen-chat" || String(c.class).startsWith("chrome-127.0.0.1__popup"));
449
+ if (pop) await dispatch(`hl.dsp.focus({ window = "address:${pop.address}" })`, ["focuswindow", `address:${pop.address}`]);
450
+ return Response.json({ ok: true, hidden: !!w });
451
+ }
452
+ if (!w) Bun.spawn([process.platform === "darwin" ? "open" : "xdg-open", new URL("/", req.url).href], { stdout: "ignore", stderr: "ignore" });
453
+ else {
454
+ if (String(board.workspace?.name).startsWith("special:")) {
455
+ const ws = (await json("activeworkspace"))?.id ?? 1;
456
+ await dispatch(`hl.dsp.window.move({ workspace = "${ws}", window = "${w}" })`, ["movetoworkspace", `${ws},${w}`]);
457
+ }
458
+ await dispatch(`hl.dsp.focus({ window = "${w}" })`, ["focuswindow", w]);
459
+ }
460
+ if (typeof body.id === "string") popupChat = body.id;
461
+ await chat("--close");
462
+ return Response.json({ ok: true });
463
+ }
464
+ // Home, refocused after Back, takes the popup's chat once.
465
+ if (req.method === "GET" && path === "/popup/handoff") {
466
+ const id = popupChat;
467
+ popupChat = null;
468
+ return Response.json({ id });
469
+ }
470
+
389
471
  if (req.method === "GET" && (path === "/video" || path === "/video.js")) {
390
472
  const [f, type] = path === "/video" ? [VIDEO_PAGE, "text/html; charset=utf-8"] : [VIDEO_JS, "application/javascript; charset=utf-8"];
391
473
  const body = served(f);
@@ -784,6 +866,71 @@ export async function web(repoDir: string, opts: Opts = {}) {
784
866
  });
785
867
  }
786
868
 
869
+ // Home's chat: chats live in ~/.kaizen/chats, each in a project of the board or in none.
870
+ // A send answers with the turn as NDJSON.
871
+ if (path === "/chats" || path === "/chat" || path === "/chat/stop" || path === "/chat/delete") {
872
+ const base = join(home, ".kaizen");
873
+ if (req.method === "GET" && path === "/chats") return json({ chats: listChats(base) });
874
+ if (req.method === "GET" && path === "/chat") {
875
+ const c = readChat(base, url.searchParams.get("id") ?? "");
876
+ return c ? json({ ...c, busy: chatBusy(base, c.id) }) : bad("no such chat", 404);
877
+ }
878
+ if (req.method !== "POST") return bad("method not allowed", 405);
879
+ if (!local(req)) return bad("cross-origin write refused", 403);
880
+ let body: any;
881
+ let uploads: ChatUpload[] = [];
882
+ if (path === "/chat" && req.headers.get("content-type")?.startsWith("multipart/form-data")) {
883
+ if (Number(req.headers.get("content-length")) > 28 * 1024 * 1024) return bad("attachments too large", 413);
884
+ let form: FormData;
885
+ try { form = await req.formData(); } catch { return bad("form data expected"); }
886
+ const files = form.getAll("files");
887
+ if (files.length > 5 || files.some((f) => !(f instanceof File) || f.size > 10 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 20 * 1024 * 1024) return bad("up to 5 files, 10 MB each and 20 MB total", 413);
888
+ body = { id: form.get("id"), text: form.get("text") ?? "", project: form.get("project") };
889
+ uploads = await Promise.all(files.map(async (f) => ({ name: (f as File).name, bytes: new Uint8Array(await (f as File).arrayBuffer()) })));
890
+ } else try { body = await req.json(); } catch { return bad("json body expected"); }
891
+ const id = body.id == null || body.id === "" ? null : body.id;
892
+ if (id !== null && !okChatId(id)) return bad("bad chat id");
893
+ if (path === "/chat/stop") return stopChat(base, id ?? "") ? json({ ok: true }) : bad("not working", 409);
894
+ if (path === "/chat/delete") { const why = deleteChat(base, id ?? ""); return why ? bad(why, 409) : json({ ok: true }); }
895
+ const text = String(body.text ?? "").trim();
896
+ if (!text && !uploads.length) return bad("empty message");
897
+ if (text.length > 20000) return bad("message too long");
898
+ const board = {
899
+ projects: states(true).filter((d) => d !== base).map((d) => ({ dir: d, label: basename(dirname(d)) })),
900
+ create: async (name: string) => {
901
+ const r = await makeProject(name);
902
+ return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
903
+ },
904
+ agents: KNOWN_AGENTS.filter((a) => onPath(a.cmd)).map((a) => a.cmd),
905
+ // As POST /run starts an idea, without one on the inbox.
906
+ run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
907
+ const r = launchRun(parseItem(`${runner} ${text}`), d, undefined, { agent, ...inCard(d) });
908
+ changed();
909
+ return r.ok ? { agent: r.agent.cmd } : { error: r.why };
910
+ },
911
+ };
912
+ let ctl!: ReadableStreamDefaultController;
913
+ const stream = new ReadableStream({ start: (c) => { ctl = c; } });
914
+ const enc = new TextEncoder();
915
+ let chatId = id, moved = false, continued = false;
916
+ const emitChat = (e: ChatEvent) => {
917
+ if (e.t === "chat") chatId = e.id;
918
+ if (e.t === "project") moved = true;
919
+ if (e.t === "done" && moved && !continued && chatId) {
920
+ continued = true;
921
+ const why = sendChat(base, chatId, "Continue the user's pending request now that this chat is in the new project. Use the conversation context; finish the task without asking the user to repeat it. If they only asked to switch projects, stop after acknowledging the switch.", null, board, emitChat, true);
922
+ if (!why) return;
923
+ emitChat({ t: "error", error: why });
924
+ }
925
+ try { ctl.enqueue(enc.encode(JSON.stringify(e) + "\n")); if (e.t === "done") ctl.close(); } catch {}
926
+ // A turn often starts a run or edits the board's files.
927
+ if (e.t === "done") changed();
928
+ };
929
+ const why = sendChat(base, id, text, typeof body.project === "string" ? body.project : null, board, emitChat, false, uploads);
930
+ if (why) return bad(why, why === "no such chat" ? 404 : 409);
931
+ return new Response(stream, { headers: { "content-type": "application/x-ndjson", "cache-control": "no-store" } });
932
+ }
933
+
787
934
  if (req.method === "POST") {
788
935
  if (!local(req)) return bad("cross-origin write refused", 403);
789
936
  let body: any;
@@ -879,27 +1026,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
879
1026
  // where the page names, set up at once. /find only sees folders that already
880
1027
  // have a .kaizen, so a folder made by hand never shows there.
881
1028
  if (path === "/new-project") {
882
- const name = typeof body.name === "string" ? body.name.trim() : "";
883
- // Windows' rules on every platform, so a project made here also opens there:
884
- // no reserved device names (CON, NUL, COM1…), no trailing dot or space.
885
- const winBad = (n: string) => !n || /[\\/:*?"<>|\x00-\x1f]/.test(n) || /[. ]$/.test(n)
886
- || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(n);
887
- const t = typeof body.to === "string" ? body.to.trim() : "";
888
- const to = t ? resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t))
889
- : join((await projectsRoot()) || join(home, "Projects"), name);
890
- // The page asks while the name is typed: "con" on the way to "config" is no error yet.
891
- if (body.check) return json({ ok: true, to });
892
- if (winBad(name)) return bad("name the project: a folder name, without / \\ : * ? \" < > |, not ending in a dot or space, and not CON, NUL, COM1 or the like");
893
- if (winBad(basename(to))) return bad(`${basename(to)} cannot be a folder name on Windows`);
894
- let used = false;
895
- try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
896
- if (used) return bad(`${to} already exists and is not empty`, 409);
897
- // A drive that is not there, a read-only folder, a path too long: said in a toast, not a crash.
898
- try { mkdirSync(join(to, ".kaizen"), { recursive: true }); }
899
- catch (e) { return bad(`could not create ${to}: ${(e as Error).message}`); }
900
- remember(to);
901
- changed();
902
- return json({ ok: true, dir: join(to, ".kaizen") });
1029
+ const r = await makeProject(typeof body.name === "string" ? body.name.trim() : "", typeof body.to === "string" ? body.to.trim() : "", !!body.check);
1030
+ return "error" in r ? bad(r.error, r.status) : json({ ok: true, ...r });
903
1031
  }
904
1032
 
905
1033
  // Clone a GitHub repository into the projects folder (else ~/Projects) and
@@ -1457,7 +1585,9 @@ export async function shortcut() {
1457
1585
  // style 0 starts `kaizen web --daemon` with no window at all; the daemon outlives
1458
1586
  // that launcher and `kaizen web --stop` ends it. A crash has no console to land
1459
1587
  // in, so web() writes it to ~/.kaizen/web.log instead. A .lnk icon must be an .ico.
1460
- const lnk = join(home, "Desktop", "Kaizen.lnk");
1588
+ // OneDrive moves the Desktop (C:\Users\x\OneDrive\Desktop), so ask Windows for it.
1589
+ const desk = (await Bun.$`${powershellExe()} -NoProfile -Command [Environment]::GetFolderPath('Desktop')`.quiet().nothrow().text()).trim();
1590
+ const lnk = join(desk || join(home, "Desktop"), "Kaizen.lnk");
1461
1591
  const ico = join(dirname(import.meta.dir), "assets", "kaizen.ico");
1462
1592
  const vbs = join(home, ".kaizen", "kaizen-web.vbs");
1463
1593
  mkdirSync(dirname(vbs), { recursive: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.51.0",
3
+ "version": "1.53.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -159,6 +159,10 @@ board:
159
159
  # Where `kaizen web` opens the board: browser (a tab in your default browser) or
160
160
  # app (a Chrome, Edge or Brave window with no tabs or address bar).
161
161
  open: browser
162
+ # The key that opens and closes `kaizen chat`, the popup chat window. kaizen
163
+ # writes it into your Hyprland config (bindings.lua or hyprland.conf), taking the
164
+ # key over from whatever held it. Empty: no hotkey. Hyprland only for now.
165
+ chat_hotkey: "SUPER + ALT + SPACE"
162
166
 
163
167
  sources:
164
168
  # How often the web board checks your request sources (links added in the board's
package/web/board/api.ts CHANGED
@@ -30,6 +30,8 @@ export async function load(quiet) {
30
30
  }
31
31
  const was = store.openKey && store.S.cards.find((x) => key(x) === store.openKey);
32
32
  store.S = await r.json();
33
+ // Home follows a project switch without the board importing it.
34
+ dispatchEvent(new Event("kz-state"));
33
35
  {
34
36
  const seen = new Map();
35
37
  for (const c of store.S.cards) {