kaizen-agent 1.82.1 → 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/install.ts CHANGED
@@ -312,7 +312,8 @@ if (Bun.argv[2] === "search" || Bun.argv[2] === "scrape") {
312
312
 
313
313
  // `kaizen send <file>…`: files to the person's phone through LocalSend, see cli/localsend.ts.
314
314
  if (Bun.argv[2] === "send") {
315
- const { cli } = await import("./localsend.ts");
315
+ // --whatsapp: the same command through the linked WhatsApp, see cli/whatsapp.ts.
316
+ const { cli } = await import(Bun.argv.includes("--whatsapp") ? "./whatsapp.ts" : "./localsend.ts");
316
317
  process.exit(await cli(Bun.argv.slice(3)));
317
318
  }
318
319
 
@@ -1368,7 +1369,7 @@ function initProject() {
1368
1369
  // ("add a discount cap") does not reach kaizen unless the project says it should.
1369
1370
  // One line in the agent instructions is what makes it the default here.
1370
1371
  function writePointer() {
1371
- const block = `\n## Kaizen workflow\n\nNon-trivial work in this repository follows the staged workflow in\n\`.kaizen/spec.md\`: plan, human approval, build, independent review, bounded fix\nloop. Invoke the \`kaizen\` skill for it — do not carry the stages out inline.\n\nA run costs several times what the same change costs in one session, so spend it\nwhere being wrong is expensive: money, data loss, a migration or anything else hard\nto undo, work a customer sees, or a part of the system nobody has read in a year.\n\nWork where being wrong is cheap and obvious does not start a run. Answering a\nquestion, reading code, a one-line fix, a rename the compiler checks — do those\ndirectly. When it is genuinely unclear, ask rather than assuming the expensive path.\n\nBefore non-trivial work, run \`kaizen recall --track <track> --query "<topic>"\` and\ntreat what it returns as past experience from other projects to verify, not as rules.\n\nAfter you change something a person can look at (a page, an app screen, a UI), show it\nbefore saying done: start the app\'s dev server if it is not running, then run\n\`kaizen preview <localhost url>\` (or \`kaizen preview <screenshot.png>\` for a static result).\nA page opens in the kaizen board\'s Browser tab and a screenshot in its Preview tab, never a new browser window.\n\nWhen the person asks for a file on their phone (or another device), send it with\n\`kaizen send <file>...\` (\`--to <device name | address>\` for a device other than their\ndefault). It goes through LocalSend; they tap Accept on the device.\n\nRun state lives in \`.kaizen/runs/<id>/\`. Read \`state.json\` first and continue from\nthe stage it names; never advance a run whose \`awaiting\` field is non-null without a\nrecorded human decision.\n`;
1372
+ const block = `\n## Kaizen workflow\n\nNon-trivial work in this repository follows the staged workflow in\n\`.kaizen/spec.md\`: plan, human approval, build, independent review, bounded fix\nloop. Invoke the \`kaizen\` skill for it — do not carry the stages out inline.\n\nA run costs several times what the same change costs in one session, so spend it\nwhere being wrong is expensive: money, data loss, a migration or anything else hard\nto undo, work a customer sees, or a part of the system nobody has read in a year.\n\nWork where being wrong is cheap and obvious does not start a run. Answering a\nquestion, reading code, a one-line fix, a rename the compiler checks — do those\ndirectly. When it is genuinely unclear, ask rather than assuming the expensive path.\n\nBefore non-trivial work, run \`kaizen recall --track <track> --query "<topic>"\` and\ntreat what it returns as past experience from other projects to verify, not as rules.\n\nAfter you change something a person can look at (a page, an app screen, a UI), show it\nbefore saying done: start the app\'s dev server if it is not running, then run\n\`kaizen preview <localhost url>\` (or \`kaizen preview <screenshot.png>\` for a static result).\nA page opens in the kaizen board\'s Browser tab and a screenshot in its Preview tab, never a new browser window.\n\nWhen the person asks for a file on their phone (or another device), send it with\n\`kaizen send <file>...\` (\`--to <device name | address>\` for a device other than their\ndefault). It goes through LocalSend; they tap Accept on the device.\n\nWhen the person asks for a file on their WhatsApp, send it with\n\`kaizen send --whatsapp <file>...\` (\`--to <chat name>\`, \`--text \"<caption>\"\`); with no\n\`--to\` it goes to their own message-yourself chat. Use it instead of LocalSend or any\nother route. If it says WhatsApp is not linked, tell them to link it in the board:\nSettings → Phone → WhatsApp Bridge.\n\nRun state lives in \`.kaizen/runs/<id>/\`. Read \`state.json\` first and continue from\nthe stage it names; never advance a run whose \`awaiting\` field is non-null without a\nrecorded human decision.\n`;
1372
1373
 
1373
1374
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
1374
1375
  const f = join(process.cwd(), name);
@@ -1387,6 +1388,13 @@ function writePointer() {
1387
1388
  writeFileSync(f, now.replace("\nRun state lives in", "\n" + para + "Run state lives in"));
1388
1389
  step(`added the send line to ${name}`);
1389
1390
  }
1391
+ // …and before `kaizen send --whatsapp`, its paragraph.
1392
+ const wa = readFileSync(f, "utf8");
1393
+ if (!wa.includes("kaizen send --whatsapp") && wa.includes("\nRun state lives in")) {
1394
+ const para = block.slice(block.indexOf("When the person asks for a file on their WhatsApp"), block.indexOf("Run state lives"));
1395
+ writeFileSync(f, wa.replace("\nRun state lives in", "\n" + para + "Run state lives in"));
1396
+ step(`added the WhatsApp send line to ${name}`);
1397
+ }
1390
1398
  continue;
1391
1399
  }
1392
1400
  if (!current && name === "AGENTS.md") continue; // do not create one that was never there
@@ -0,0 +1,198 @@
1
+ // Kaizen WhatsApp bridge: a small background daemon that holds one WhatsApp Web link
2
+ // (Baileys) and answers the board over a Unix socket. Started by cli/whatsapp.ts with
3
+ // its working directory set to ~/.kaizen/whatsapp, where its login (auth/), chat list
4
+ // and dependencies (node_modules, installed on first link) live. It listens on a
5
+ // random 127.0.0.1 port (the same on Linux, macOS and Windows) and writes the port and
6
+ // a one-run token to bridge.json; every request must carry that token, so a web page
7
+ // that guesses the port cannot drive it.
8
+ //
9
+ // GET /status -> { connected, user, qrSvg, error }
10
+ // POST /connect -> start (or restart) the link; a QR appears in /status
11
+ // POST /disconnect -> log out and forget the login
12
+ // GET /chats -> { chats: [{ id, name, type }] }
13
+ // POST /send -> { target, text, file } -> { ok } | { ok: false, error }
14
+ import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
15
+ import { randomUUID } from "node:crypto";
16
+ import { basename, extname, join } from "node:path";
17
+
18
+ const DIR = process.cwd();
19
+ const INFO = join(DIR, "bridge.json");
20
+ const TOKEN = randomUUID();
21
+ const AUTH = join(DIR, "auth");
22
+ const CHATS = join(DIR, "chats.json");
23
+
24
+ // This file lives in kaizen's cli/, the libraries in the data folder: resolve from there.
25
+ const load = (name: string) => import(Bun.resolveSync(name, DIR));
26
+ const baileys: any = await load("@whiskeysockets/baileys");
27
+ const QRCode: any = (await load("qrcode")).default;
28
+ const makeWASocket = baileys.default ?? baileys.makeWASocket;
29
+ const { useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion, Browsers } = baileys;
30
+
31
+ const quiet: any = { level: "silent", trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return quiet; } };
32
+
33
+ // Filled squares, not the library's strokes: the board's .ph-qr rule clears every stroke.
34
+ function qrToSvg(text: string): string {
35
+ const { modules } = QRCode.create(text, { errorCorrectionLevel: "L" });
36
+ const n: number = modules.size, m = 2;
37
+ let d = "";
38
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (modules.get(x, y)) d += `M${x + m} ${y + m}h1v1h-1z`;
39
+ const t = n + 2 * m;
40
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${t} ${t}" shape-rendering="crispEdges"><rect width="${t}" height="${t}" fill="#fff"/><path fill="#000" d="${d}"/></svg>`;
41
+ }
42
+
43
+ let sock: any = null;
44
+ let connected = false;
45
+ let user: string | null = null;
46
+ let qrSvg: string | null = null;
47
+ let error: string | null = null;
48
+ let starting = false;
49
+ let wantLink = false;
50
+
51
+ type Chat = { id: string; name: string; type: string };
52
+ const chats = new Map<string, Chat>();
53
+ try {
54
+ for (const c of JSON.parse(readFileSync(CHATS, "utf8"))) chats.set(c.id, c);
55
+ } catch {}
56
+ const saveChats = () => { try { writeFileSync(CHATS, JSON.stringify([...chats.values()])); } catch {} };
57
+
58
+ // "6281…:12@s.whatsapp.net" -> "6281…@s.whatsapp.net": the device part is not an address.
59
+ const bare = (jid: string) => jid.replace(/:\d+@/, "@");
60
+
61
+ function note(id: string, name: string | undefined, type: string) {
62
+ if (!id || id.endsWith("@broadcast") || id.endsWith("@newsletter")) return;
63
+ const old = chats.get(id);
64
+ if (old && !name) return;
65
+ chats.set(id, { id, name: name || old?.name || id.split("@")[0], type });
66
+ }
67
+
68
+ async function start() {
69
+ if (starting) return;
70
+ starting = true;
71
+ try {
72
+ const { state, saveCreds } = await useMultiFileAuthState(AUTH);
73
+ let version: any;
74
+ try { version = (await fetchLatestBaileysVersion()).version; } catch {}
75
+ const s = makeWASocket({ auth: state, version, logger: quiet, browser: Browsers.macOS("Kaizen"), syncFullHistory: false, markOnlineOnConnect: false });
76
+ sock = s;
77
+ s.ev.on("creds.update", saveCreds);
78
+ s.ev.on("contacts.upsert", (l: any[]) => { for (const c of l) note(c.id, c.name || c.notify, "dm"); saveChats(); });
79
+ s.ev.on("contacts.update", (l: any[]) => { for (const c of l) if (c.id && (c.name || c.notify)) note(c.id, c.name || c.notify, "dm"); saveChats(); });
80
+ s.ev.on("messaging-history.set", ({ chats: cs, contacts }: any) => {
81
+ for (const c of contacts ?? []) note(c.id, c.name || c.notify, "dm");
82
+ for (const c of cs ?? []) note(c.id, c.name, c.id.endsWith("@g.us") ? "group" : "dm");
83
+ saveChats();
84
+ });
85
+ s.ev.on("chats.upsert", (l: any[]) => { for (const c of l) note(c.id, c.name, c.id.endsWith("@g.us") ? "group" : "dm"); saveChats(); });
86
+ s.ev.on("connection.update", async (u: any) => {
87
+ if (s !== sock) return;
88
+ if (u.qr) { qrSvg = qrToSvg(u.qr); error = null; }
89
+ if (u.connection === "open") {
90
+ connected = true; qrSvg = null; error = null; wantLink = false;
91
+ user = s.user?.name || (s.user?.id ? bare(s.user.id).split("@")[0] : "WhatsApp");
92
+ if (s.user?.id) note(bare(s.user.id), "You (message yourself)", "self");
93
+ try {
94
+ for (const g of Object.values(await s.groupFetchAllParticipating()) as any[]) note(g.id, g.subject, "group");
95
+ } catch {}
96
+ saveChats();
97
+ }
98
+ if (u.connection === "close") {
99
+ connected = false; user = null; qrSvg = null;
100
+ const code = u.lastDisconnect?.error?.output?.statusCode;
101
+ if (code === DisconnectReason.loggedOut) {
102
+ rmSync(AUTH, { recursive: true, force: true });
103
+ chats.clear(); saveChats();
104
+ wantLink = false; sock = null;
105
+ return;
106
+ }
107
+ // Any other close (network, restart-required after the QR scan): reconnect.
108
+ starting = false;
109
+ if (wantLink || existsSync(join(AUTH, "creds.json"))) setTimeout(() => void start(), 1500);
110
+ else { error = "WhatsApp closed the link; try again"; sock = null; }
111
+ }
112
+ });
113
+ } catch (e: any) {
114
+ error = String(e?.message ?? e).slice(0, 300);
115
+ sock = null;
116
+ } finally {
117
+ starting = false;
118
+ }
119
+ }
120
+
121
+ const MIME: Record<string, string> = {
122
+ ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".mp3": "audio/mpeg", ".wav": "audio/wav",
123
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml",
124
+ ".pdf": "application/pdf", ".zip": "application/zip", ".txt": "text/plain", ".md": "text/markdown",
125
+ ".srt": "application/x-subrip", ".json": "application/json",
126
+ };
127
+
128
+ async function send(target: string, text: string, file: string) {
129
+ if (!sock || !connected) return { ok: false, error: "WhatsApp is not linked" };
130
+ let jid = target.replace(/^whatsapp:/, "");
131
+ if (!jid.includes("@")) jid = `${jid.replace(/\D/g, "")}@s.whatsapp.net`;
132
+ try {
133
+ if (!file) {
134
+ await sock.sendMessage(jid, { text });
135
+ return { ok: true };
136
+ }
137
+ const size = statSync(file).size;
138
+ if (size > 2_000_000_000) return { ok: false, error: "WhatsApp documents must be 2 GB or smaller" };
139
+ const ext = extname(file).toLowerCase();
140
+ const mimetype = MIME[ext] ?? "application/octet-stream";
141
+ const src = { url: file }; // streamed from disk, not read into memory
142
+ // Small MP4s show as playable video; everything else goes as a document, quality intact.
143
+ const content: any = ext === ".mp4" && size <= 64 * 1024 * 1024
144
+ ? { video: src, mimetype, caption: text || undefined }
145
+ : { document: src, mimetype, fileName: basename(file), caption: text || undefined };
146
+ await sock.sendMessage(jid, content);
147
+ return { ok: true };
148
+ } catch (e: any) {
149
+ return { ok: false, error: String(e?.message ?? e).slice(0, 400) };
150
+ }
151
+ }
152
+
153
+ const json = (o: unknown, status = 200) => Response.json(o, { status });
154
+
155
+ rmSync(INFO, { force: true });
156
+ const server = Bun.serve({
157
+ hostname: "127.0.0.1",
158
+ port: 0,
159
+ idleTimeout: 255,
160
+ async fetch(req) {
161
+ if (req.headers.get("authorization") !== `Bearer ${TOKEN}`) return json({ error: "forbidden" }, 403);
162
+ const path = new URL(req.url).pathname;
163
+ if (path === "/status") return json({ connected, user, qrSvg, error });
164
+ // Only chats a person can pick: yourself, groups and contacts with a real name. WhatsApp
165
+ // also reports thousands of nameless @lid entries.
166
+ if (path === "/chats") return json({ chats: [...chats.values()].filter((c) => c.type === "self" || (/[\p{L}\p{N}]/u.test(c.name) && c.name !== c.id.split("@")[0])).sort((a, b) => (a.type === "self" ? -1 : b.type === "self" ? 1 : a.name.localeCompare(b.name))) });
167
+ if (req.method !== "POST") return json({ error: "not found" }, 404);
168
+ if (path === "/connect") {
169
+ wantLink = true;
170
+ error = null;
171
+ if (!sock && !connected) await start();
172
+ return json({ ok: true });
173
+ }
174
+ if (path === "/disconnect") {
175
+ wantLink = false;
176
+ try { await sock?.logout(); } catch {}
177
+ try { sock?.end(undefined); } catch {}
178
+ sock = null; connected = false; user = null; qrSvg = null;
179
+ rmSync(AUTH, { recursive: true, force: true });
180
+ chats.clear(); saveChats();
181
+ return json({ ok: true });
182
+ }
183
+ if (path === "/send") {
184
+ const b: any = await req.json().catch(() => null);
185
+ if (!b || typeof b.target !== "string") return json({ ok: false, error: "target expected" });
186
+ return json(await send(b.target, String(b.text ?? ""), String(b.file ?? "")));
187
+ }
188
+ return json({ error: "not found" }, 404);
189
+ },
190
+ });
191
+
192
+ writeFileSync(INFO, JSON.stringify({ port: server.port, token: TOKEN, pid: process.pid }), { mode: 0o600 });
193
+ const bye = () => { rmSync(INFO, { force: true }); process.exit(0); };
194
+ process.on("SIGINT", bye);
195
+ process.on("SIGTERM", bye);
196
+
197
+ // A saved login comes back on its own when the daemon (re)starts.
198
+ if (existsSync(join(AUTH, "creds.json"))) void start();
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.82.1",
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
 
@@ -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;