kaizen-agent 1.82.0 → 1.83.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/whatsapp.ts CHANGED
@@ -1,12 +1,20 @@
1
- // Kaizen WhatsApp: manages the background Baileys bridge (~/.kaizen/whatsapp/bridge.ts)
2
- // and proxies requests to it over the local Unix domain socket.
3
- import { existsSync } from "node:fs";
4
- import { join } from "node:path";
1
+ // Kaizen WhatsApp: manages the background Baileys bridge (cli/whatsapp-bridge.ts, shipped
2
+ // with kaizen) and proxies requests to it over a loopback port. Its data --
3
+ // login, chat list and the Baileys dependencies, installed on the first link -- lives in
4
+ // ~/.kaizen/whatsapp.
5
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
6
+ import { basename, join, resolve } from "node:path";
5
7
  import { homedir } from "node:os";
6
8
 
7
9
  export const WA_DIR = join(homedir(), ".kaizen", "whatsapp");
8
- export const BRIDGE_SCRIPT = join(WA_DIR, "bridge.ts");
9
- export const SOCK_PATH = join(WA_DIR, "bridge.sock");
10
+ export const BRIDGE_SCRIPT = join(import.meta.dir, "whatsapp-bridge.ts");
11
+ // Exact versions: an unofficial client, so upgrades are deliberate.
12
+ const DEPS = ["@whiskeysockets/baileys@7.0.0-rc14", "qrcode@1.5.4"];
13
+ const depsReady = () => existsSync(join(WA_DIR, "node_modules", "@whiskeysockets", "baileys")) && existsSync(join(WA_DIR, "node_modules", "qrcode"));
14
+ // Port and token the running bridge wrote; see cli/whatsapp-bridge.ts.
15
+ const INFO = join(WA_DIR, "bridge.json");
16
+ // The bun that runs kaizen also runs the bridge; no PATH lookup of a bare "bun".
17
+ const bunBin = () => Bun.which("bun") ?? process.execPath;
10
18
 
11
19
  export type WAStatus = {
12
20
  installed: boolean;
@@ -20,13 +28,12 @@ export type WAStatus = {
20
28
  export type WAChat = { id: string; name: string; type: string };
21
29
 
22
30
  async function callBridge(path: string, options: RequestInit = {}, timeoutMs = 4000): Promise<any> {
23
- if (!existsSync(SOCK_PATH)) return null;
31
+ let info: { port: number; token: string };
32
+ try { info = JSON.parse(readFileSync(INFO, "utf8")); } catch { return null; }
24
33
  try {
25
- const res = await fetch(`http://localhost${path}`, {
26
- // Bun unix socket option
27
- // @ts-ignore
28
- unix: SOCK_PATH,
34
+ const res = await fetch(`http://127.0.0.1:${info.port}${path}`, {
29
35
  ...options,
36
+ headers: { ...(options.headers as Record<string, string> | undefined), authorization: `Bearer ${info.token}` },
30
37
  signal: AbortSignal.timeout(timeoutMs),
31
38
  });
32
39
  if (!res.ok) return null;
@@ -36,18 +43,35 @@ async function callBridge(path: string, options: RequestInit = {}, timeoutMs = 4
36
43
  }
37
44
  }
38
45
 
46
+ // First link only: fetch the Baileys dependencies next to the login data.
47
+ export async function installDeps(): Promise<string | null> {
48
+ if (depsReady()) return null;
49
+ const bun = bunBin();
50
+ try {
51
+ mkdirSync(WA_DIR, { recursive: true });
52
+ if (!existsSync(join(WA_DIR, "package.json"))) writeFileSync(join(WA_DIR, "package.json"), '{"name":"kaizen-whatsapp","private":true}\n');
53
+ const p = Bun.spawn([bun, "add", "--exact", ...DEPS], { cwd: WA_DIR, stdout: "ignore", stderr: "pipe", windowsHide: true, timeout: 180_000 });
54
+ const err = await new Response(p.stderr).text();
55
+ if ((await p.exited) !== 0 || !depsReady()) return `Could not install the WhatsApp libraries: ${err.trim().split("\n").pop() || "bun add failed"}`;
56
+ } catch (e: any) {
57
+ return `Could not install the WhatsApp libraries: ${String(e?.message ?? e).slice(0, 200)}`;
58
+ }
59
+ return null;
60
+ }
61
+
39
62
  export async function ensureDaemon(ms = 3000): Promise<boolean> {
40
- if (!existsSync(BRIDGE_SCRIPT)) return false;
63
+ if (!existsSync(BRIDGE_SCRIPT) || !depsReady()) return false;
41
64
  // If already answering, we are good
42
65
  const st = await callBridge("/status", {}, 1000);
43
66
  if (st) return true;
44
67
 
45
68
  try {
46
- const p = Bun.spawn(["bun", BRIDGE_SCRIPT], {
69
+ const p = Bun.spawn([bunBin(), BRIDGE_SCRIPT], {
47
70
  cwd: WA_DIR,
48
71
  stdio: ["ignore", "ignore", "ignore"],
49
72
  env: process.env,
50
- windowsHide: true,
73
+ windowsHide: true, // no console window on Windows
74
+ detached: true,
51
75
  });
52
76
  p.unref();
53
77
 
@@ -62,7 +86,8 @@ export async function ensureDaemon(ms = 3000): Promise<boolean> {
62
86
  }
63
87
 
64
88
  export async function whatsappStatus(): Promise<WAStatus> {
65
- const installed = existsSync(BRIDGE_SCRIPT);
89
+ // "installed" = the libraries are there; the bridge script itself ships with kaizen.
90
+ const installed = existsSync(BRIDGE_SCRIPT) && depsReady();
66
91
  if (!installed) {
67
92
  return { installed: false, running: false, connected: false, user: null, qrSvg: null, error: null };
68
93
  }
@@ -83,8 +108,16 @@ export async function whatsappStatus(): Promise<WAStatus> {
83
108
  }
84
109
 
85
110
  export async function whatsappConnect(): Promise<WAStatus> {
86
- await ensureDaemon();
87
- await callBridge("/connect", { method: "POST" });
111
+ const bad = await installDeps();
112
+ if (bad) return { ...(await whatsappStatus()), error: bad };
113
+ if (!(await ensureDaemon(8000))) return { ...(await whatsappStatus()), error: "The WhatsApp bridge did not start" };
114
+ await callBridge("/connect", { method: "POST" }, 8000);
115
+ // The QR appears a moment after the daemon begins the link.
116
+ for (let i = 0; i < 15; i++) {
117
+ const st = await whatsappStatus();
118
+ if (st.qrSvg || st.connected || st.error) return st;
119
+ await Bun.sleep(400);
120
+ }
88
121
  return whatsappStatus();
89
122
  }
90
123
 
@@ -110,3 +143,48 @@ export async function whatsappSend(target: string, text: string, file: string):
110
143
  if (!res) return null;
111
144
  return res.ok ? { ok: true } : { ok: false, error: res.error || "Send failed" };
112
145
  }
146
+
147
+ // `kaizen send --whatsapp <file>... [--to <chat name | self>] [--text "<caption>"]`: an agent's way to
148
+ // send a file through the linked WhatsApp. Without --to the file goes to yourself.
149
+ const WA_USAGE = 'kaizen send --whatsapp <file>... [--to <chat name | self>] [--text "<caption>"]';
150
+ export async function cli(argv: string[], log: (s: string) => void = console.log): Promise<number> {
151
+ const files: string[] = [];
152
+ let to = "", text = "";
153
+ for (let i = 0; i < argv.length; i++) {
154
+ const a = argv[i]!;
155
+ if (a === "--whatsapp") continue;
156
+ else if (a === "--to") to = argv[++i] ?? "";
157
+ else if (a === "--text") text = argv[++i] ?? "";
158
+ else if (a === "-h" || a === "--help") { log(`\n ${WA_USAGE}\n`); return 0; }
159
+ else files.push(a);
160
+ }
161
+ if (!files.length) { log(`\n ${WA_USAGE}\n`); return 1; }
162
+ for (const f of files) if (!existsSync(f) || !statSync(f).isFile()) { log(`\n no such file: ${f}\n`); return 1; }
163
+ // A freshly started bridge needs a few seconds to bring a saved login back.
164
+ let linked = false;
165
+ if (await ensureDaemon(8000)) {
166
+ for (let i = 0; i < 40 && !(linked = (await whatsappStatus()).connected); i++) {
167
+ if (!existsSync(join(WA_DIR, "auth", "creds.json"))) break;
168
+ await Bun.sleep(500);
169
+ }
170
+ }
171
+ if (!linked) {
172
+ log("\n WhatsApp is not linked. Open the board: Settings → Phone → WhatsApp Bridge → Link WhatsApp\n");
173
+ return 1;
174
+ }
175
+ const chats = (await whatsappChats()) ?? [];
176
+ const w = to.trim().toLowerCase();
177
+ const pool = !w || w === "self" || w === "me" ? chats.filter((c) => c.type === "self")
178
+ : chats.filter((c) => c.name.toLowerCase() === w);
179
+ const hit = pool.length ? pool : chats.filter((c) => c.name.toLowerCase().includes(w));
180
+ if (hit.length !== 1) {
181
+ log(hit.length ? `\n more than one chat matches "${to}":\n${hit.slice(0, 10).map((c) => ` ${c.name}`).join("\n")}\n` : `\n no WhatsApp chat named "${to}"\n`);
182
+ return 1;
183
+ }
184
+ for (const f of files) {
185
+ const r = await whatsappSend(hit[0]!.id, text, resolve(f));
186
+ if (!r || !r.ok) { log(` ${r ? r.error : "the bridge did not answer"}`); return 1; }
187
+ log(` sent to ${hit[0]!.name}: ${basename(f)}`);
188
+ }
189
+ return 0;
190
+ }
package/cli/worktree.ts CHANGED
@@ -10,7 +10,33 @@ export type Out = { ok: boolean; out: string; why: string };
10
10
  export type Run = (cmd: string[], cwd: string, ms?: number) => Out;
11
11
 
12
12
  const SLUG = /^\d{4}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]*$/;
13
- const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
13
+
14
+ if (process.platform === "win32") {
15
+ const progFiles = process.env["ProgramFiles"] ?? "C:\\Program Files";
16
+ const progFilesX86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
17
+ const gitDirs = [
18
+ join(progFiles, "Git", "cmd"),
19
+ join(progFiles, "Git", "bin"),
20
+ join(progFiles, "Git", "usr", "bin"),
21
+ join(progFilesX86, "Git", "cmd"),
22
+ join(progFilesX86, "Git", "bin"),
23
+ join(progFilesX86, "Git", "usr", "bin"),
24
+ join(homedir(), "AppData", "Local", "Programs", "Git", "cmd"),
25
+ join(homedir(), "AppData", "Local", "Programs", "MinGit", "cmd"),
26
+ dirname(process.execPath),
27
+ ].filter((p) => existsSync(p));
28
+ if (gitDirs.length > 0) {
29
+ const cur = process.env.PATH ?? process.env.Path ?? "";
30
+ const toAdd = gitDirs.filter((d) => !cur.toLowerCase().includes(d.toLowerCase())).join(";");
31
+ if (toAdd) {
32
+ const full = `${toAdd};${cur}`;
33
+ process.env.PATH = full;
34
+ process.env.Path = full;
35
+ }
36
+ }
37
+ }
38
+
39
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true" };
14
40
 
15
41
  export const run: Run = (cmd, cwd, ms = 120_000) => {
16
42
  try {
@@ -128,7 +154,7 @@ const readGit = (text: string, key: string) => {
128
154
  // A command run through `sh -c`: a project's config.yml that git tracks came with a clone, so it may not set one.
129
155
  const COMMAND_KEYS = new Set(["land_check", "rebuild_on_land"]);
130
156
  const tracked = (project: string, f: string) => {
131
- try { return Bun.spawnSync(["git", "-C", project, "ls-files", "--error-unmatch", f], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exitCode === 0; } catch { return false; }
157
+ try { return Bun.spawnSync(["git", "-C", project, "ls-files", "--error-unmatch", f], { env, stdout: "ignore", stderr: "ignore", windowsHide: true }).exitCode === 0; } catch { return false; }
132
158
  };
133
159
  const gitSetting = (project: string, key: string, fallback: string) => {
134
160
  for (const f of [join(project, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.82.0",
3
+ "version": "1.83.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": {
@@ -54,7 +54,7 @@ anything.
54
54
  | `kaizen preview <localhost url \| image>` | Show a change in the board (page → Browser tab, screenshot → Preview tab), not a new browser window |
55
55
  | `kaizen search "<query>" [--recent h\|d\|w\|m\|y] [--read] [--limit N]` | Web search through Firecrawl with your own key (Settings → Integrations → Research); exit 2 when no key is set |
56
56
  | `kaizen scrape <url>` | One web page as markdown, through the same Firecrawl key |
57
- | `kaizen send <file>... [--to <name \| address>]` | Send files to a phone or computer through LocalSend; they accept on the device. `--default <name \| address>` saves where files go (over Tailscale, the phone's address); `--devices` lists what is nearby |
57
+ | `kaizen send <file>... [--to <name \| address>]` | Send files to a phone or computer through LocalSend; they accept on the device. `--default <name \| address>` saves where files go (over Tailscale, the phone's address); `--devices` lists what is nearby. `--whatsapp [--to <chat name \| self>] [--text "caption"]` sends through the WhatsApp linked in Settings → Phone instead (to yourself when `--to` is left out) |
58
58
  | `kaizen recall [--track t] [--tags a,b] [--query "<words>"]` | Lessons from other projects that match (global knowledge, `~/.kaizen/knowledge/`) |
59
59
  | `kaizen remember --track t --tags a,b --applies "<where>" --run <id> "<lesson>"` | Save a lesson that holds beyond this project; the reviewer calls it |
60
60
 
@@ -189,6 +189,20 @@ function projectView(t: TaskView): Safe | string {
189
189
  </form>
190
190
  </section>`;
191
191
  }
192
+ function visibleMessages(messages: TaskView["messages"] = []) {
193
+ if (!messages?.length) return [];
194
+ const clean = messages.filter((m) => {
195
+ if (m.type === "boundary") return false;
196
+ if (m.role === "user" && m.text.includes("Continue production under the frozen task policy")) return false;
197
+ return true;
198
+ });
199
+ const lastResultIdx = clean.reduce((last, m, idx) => (m.type === "result" ? idx : last), -1);
200
+ return clean.filter((m, idx) => {
201
+ if (m.type === "result" && idx !== lastResultIdx) return false;
202
+ return true;
203
+ });
204
+ }
205
+
192
206
  function conversationView(t: TaskView): Safe {
193
207
  return html`${projectView(t)}${decisionView(t)}
194
208
  ${
@@ -202,7 +216,7 @@ function conversationView(t: TaskView): Safe {
202
216
  : ""
203
217
  }
204
218
  <div class="tp-messages" role="log" aria-label="Task conversation" aria-live="polite" aria-relevant="additions">
205
- ${(t.messages ?? []).map((m) => {
219
+ ${visibleMessages(t.messages).map((m) => {
206
220
  const long = m.text.length > 320;
207
221
  const body = long
208
222
  ? html`<details class="tp-long"><summary>${m.text.slice(0, 280).trimEnd()}… <span>Show more</span></summary>${m.text}</details>`
@@ -94,6 +94,8 @@ export function artifactView(a: TaskArtifact, selected = false): Safe {
94
94
  view = html`<p class="dim">
95
95
  Download this file to open it. Executable files are kept separate from this task page.
96
96
  </p>`;
97
+ else if (selected)
98
+ view = html`<p class="dim">Preview is unavailable for this format. Download to open it in your app.</p>`;
97
99
  return html`<section class="tp-artifact">
98
100
  <div class="tp-artifact-head">
99
101
  <span
@@ -77,6 +77,12 @@ export async function mountWhatsApp(el: HTMLElement) {
77
77
  return;
78
78
  }
79
79
 
80
+ // Bridge up, no QR and not linked: mid-scan or reconnecting. Keep polling, say so.
81
+ if (s.running) {
82
+ el.innerHTML = String(html`<div><p class="ph-h">WhatsApp Bridge</p><p class="ph-wait">Connecting…</p>${e}</div>`);
83
+ return;
84
+ }
85
+
80
86
  el.innerHTML = String(html`
81
87
  <div>
82
88
  <p class="ph-h">WhatsApp Bridge</p>
@@ -105,7 +111,7 @@ export async function mountWhatsApp(el: HTMLElement) {
105
111
  clearInterval(timer);
106
112
  return;
107
113
  }
108
- if (s && !s.connected && (s.qrSvg || busy)) {
114
+ if (s && !s.connected && (s.qrSvg || busy || s.running)) {
109
115
  const r = await callWA();
110
116
  if (!r.error) {
111
117
  s = r;
@@ -236,9 +236,16 @@ function drawList() {
236
236
  .filter((p) => !filt.dirs.length || filt.dirs.includes(p.dir))
237
237
  .map((p) => {
238
238
  const rows = p.workspaces
239
- .map((w) => ({ w, cs: by.get(p.dir + "\0" + w.path) ?? [] }))
240
- // An empty workspace or one with a run going is active; one holding only finished runs is done.
241
- .filter(({ w, cs }) => cs.length || shownAgents(wsAgents(last.agents ?? [], p.dir, w.path, wsOfCard, now)).length)
239
+ .map((w) => {
240
+ const cs = by.get(p.dir + "\0" + w.path) ?? [];
241
+ const allCs = (last.cards ?? []).filter((c) => c.state === p.dir && wsOfCard(c) === w.path && listed(c, now));
242
+ const onlyDone = allCs.length > 0 && allCs.every((c) => ["done", "abandoned"].includes(stateOf(c)));
243
+ const ags = shownAgents(wsAgents(last.agents ?? [], p.dir, w.path, wsOfCard, now)).length;
244
+ // An empty workspace or one with a run going is active; one holding only finished runs is done.
245
+ const keep = cs.length > 0 || ags > 0 || (filt.running && (w.main || !onlyDone));
246
+ return { w, cs, keep };
247
+ })
248
+ .filter((r) => r.keep)
242
249
  // Pinned worktrees first (a stable sort keeps the rest in git's order).
243
250
  .sort((a, b) => +pins.has(p.dir + "\0" + b.w.path) - +pins.has(p.dir + "\0" + a.w.path));
244
251
  return { p, rows, top: Math.min(9, ...rows.map((r) => top(r.cs))) };
@@ -267,7 +274,8 @@ function drawList() {
267
274
  shut = folded.has(dir) || !rows.length;
268
275
  // A + for a new worktree on git projects (the main checkout has a branch).
269
276
  const git = p.workspaces.some((w) => w.branch);
270
- return html`<div class="pgrp"><button type="button" class="proj${shut ? " shut" : ""}" data-fold="${dir}" title="${dir}" aria-expanded="${String(!shut)}">${logo(dir, name, last.projects)}<span class="pname">${name}</span><svg class="fchev" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>${git ? html`<button type="button" class="wadd" data-wadd="${dir}" title="New workspace in ${name}" aria-label="New workspace in ${name}"><svg aria-hidden="true"><use href="#i-plus"/></svg></button>` : ""}</div>${shut ? "" : raw('<div class="pws">')}${shut ? "" : rows.map(({ w, cs }) => {
277
+ const mainWs = p.workspaces?.find((w) => w.main)?.path ?? p.workspaces?.[0]?.path ?? dir;
278
+ return html`<div class="pgrp"><button type="button" class="proj${shut ? " shut" : ""}" data-proj="${dir}" data-ws="${mainWs}" data-fold="${dir}" title="${dir}" aria-expanded="${String(!shut)}">${logo(dir, name, last.projects)}<span class="pname">${name}</span><svg class="fchev" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>${git ? html`<button type="button" class="wadd" data-wadd="${dir}" title="New workspace in ${name}" aria-label="New workspace in ${name}"><svg aria-hidden="true"><use href="#i-plus"/></svg></button>` : ""}</div>${shut ? "" : raw('<div class="pws">')}${shut ? "" : rows.map(({ w, cs }) => {
271
279
  // The dot: the most urgent run there, or an agent asking (amber) or working (spinner).
272
280
  const rows = shownAgents(wsAgents(last.agents ?? [], dir, w.path, wsOfCard, now));
273
281
  const st0 = cs.length ? stateOf([...cs].sort((a, b) => RANK[stateOf(a)] - RANK[stateOf(b)])[0]) : "";
@@ -298,6 +306,18 @@ function drawList() {
298
306
  if (tog) return void (e.preventDefault(), toggleList(tog.dataset.dir!, tog.dataset.ws!));
299
307
  const add = t.closest<HTMLElement>("[data-wadd]")?.dataset.wadd;
300
308
  if (add) return void (e.preventDefault(), openAdd({ dir: add, start: "ws" }));
309
+ const chev = t.closest<HTMLElement>(".fchev");
310
+ if (chev) {
311
+ const d = t.closest<HTMLElement>("[data-fold]")?.dataset.fold;
312
+ if (d) return void (e.preventDefault(), fold(d));
313
+ }
314
+ const proj = t.closest<HTMLElement>("[data-proj]");
315
+ if (proj) {
316
+ e.preventDefault();
317
+ const dir = proj.dataset.proj!, ws = proj.dataset.ws || dir;
318
+ if (folded.has(dir)) fold(dir);
319
+ if (ask("kz-open-ws", { dir, ws })) return;
320
+ }
301
321
  const d = t.closest<HTMLElement>("[data-fold]")?.dataset.fold;
302
322
  if (d) (e.preventDefault(), fold(d));
303
323
  };
package/web/board.html CHANGED
@@ -172,6 +172,7 @@ html.desk body.runv #panel>header{padding-right:calc(12px + var(--wco))}
172
172
  html.desk body.runv .pstrip{padding-top:calc(10px + var(--wch))}
173
173
  html.desk.mac .rail>.top{padding-top:22px}
174
174
  /* end side menu */
175
+ html.desk body.runv:not(.rflip) #rbar{padding-right:6px}
175
176
  @media(max-width:640px){
176
177
  body .hdr{padding:10px 16px 12px;gap:8px;border-bottom:0}
177
178
  body aside.docked>header{padding-top:10px}