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/accounts.ts +1 -1
- package/cli/add-project.ts +4 -1
- package/cli/computer.ts +2 -2
- package/cli/conpty.ts +9 -4
- package/cli/install.ts +10 -2
- package/cli/keep-awake.ts +1 -1
- package/cli/pty.ts +68 -11
- package/cli/settings.ts +2 -2
- package/cli/setup.ts +2 -2
- package/cli/skills.ts +1 -1
- package/cli/state.ts +17 -6
- package/cli/web.ts +7 -1
- package/cli/whatsapp-bridge.ts +198 -0
- package/cli/whatsapp.ts +95 -17
- package/cli/worktree.ts +28 -2
- package/package.json +1 -1
- package/skills/kaizen-help/SKILL.md +1 -1
- package/web/board/task-page.ts +15 -1
- package/web/board/task-results.ts +2 -0
- package/web/board/whatsapp-setup.ts +7 -1
- package/web/board/workspace.ts +24 -4
- package/web/board.html +1 -0
- package/web/board.js +122 -122
- package/web/notebook.js +129 -129
- package/web/term.js +1 -1
- package/web/video.js +160 -160
package/cli/accounts.ts
CHANGED
|
@@ -99,7 +99,7 @@ export async function loginStatus(tool: Tool, dir?: string, env: NodeJS.ProcessE
|
|
|
99
99
|
// answer never waits on the pipes past the timeout.
|
|
100
100
|
const late = new Promise<Login>((done) => { timer = setTimeout(() => { try { p?.kill(); } catch { /* gone */ } done(fallback()); }, timeoutMs); });
|
|
101
101
|
const ask = (async (): Promise<Login> => {
|
|
102
|
-
p = Bun.spawn(tool === "claude" ? [bin, "auth", "status", "--json"] : [bin, "login", "status"], { env: e, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
102
|
+
p = Bun.spawn(tool === "claude" ? [bin, "auth", "status", "--json"] : [bin, "login", "status"], { env: e, stdin: "ignore", stdout: "pipe", stderr: "pipe", windowsHide: true });
|
|
103
103
|
const [out, err] = await Promise.all([new Response(p.stdout as ReadableStream).text(), new Response(p.stderr as ReadableStream).text()]);
|
|
104
104
|
await p.exited;
|
|
105
105
|
return read(out, err);
|
package/cli/add-project.ts
CHANGED
|
@@ -61,8 +61,11 @@ export function destDir(raw: unknown, home: string, known: string[] = [], projec
|
|
|
61
61
|
if (winBad(basename(dir))) return { error: `${basename(dir)} cannot be a folder name on Windows` };
|
|
62
62
|
const under = (r: string) => !!r && (dir === canonPath(r) || dir.startsWith(canonPath(r) + sep));
|
|
63
63
|
if (!under(h) && !under(projects)) return { error: "choose a folder inside your home, or set Settings → Projects folder (board.projects_dir) to allow another place" };
|
|
64
|
+
const proj = projects ? canonPath(projects) : "";
|
|
64
65
|
for (let a = dirname(dir); ; a = dirname(a)) {
|
|
65
|
-
if (known.includes(a)
|
|
66
|
+
if (known.includes(a)) return { error: `that folder is inside the project ${a}` };
|
|
67
|
+
if (a === h || (proj && a === proj)) break;
|
|
68
|
+
if (existsSync(join(a, ".kaizen"))) return { error: `that folder is inside the project ${a}` };
|
|
66
69
|
if (dirname(a) === a) break;
|
|
67
70
|
}
|
|
68
71
|
return { dir };
|
package/cli/computer.ts
CHANGED
|
@@ -42,7 +42,7 @@ export async function computer(argv: string[], o: Opts): Promise<{ out: Record<s
|
|
|
42
42
|
const py = o.cmd ? null : Bun.which("python3");
|
|
43
43
|
if (!o.cmd && !py) return fail("no-python", "python3 not found");
|
|
44
44
|
// Argv only: the model's text reaches the helper as plain arguments, never a shell line.
|
|
45
|
-
const p = Bun.spawn([...(o.cmd ?? [py!, "-I", HELPER]), verb, ...args], { stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: TIMEOUT });
|
|
45
|
+
const p = Bun.spawn([...(o.cmd ?? [py!, "-I", HELPER]), verb, ...args], { stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: TIMEOUT, windowsHide: true });
|
|
46
46
|
const text = await new Response(p.stdout).text();
|
|
47
47
|
await p.exited;
|
|
48
48
|
if (p.signalCode) return fail("timeout", "helper timed out");
|
|
@@ -59,7 +59,7 @@ export function computerCheck(cmd?: string[]): { needs: { name: string; found: b
|
|
|
59
59
|
const note = (wayland ? "Wayland: keyboard shortcuts and screenshots are not available. Values, accessibility actions and typing into fields work where the app exposes them. " : "") + "Password managers are blocked by app name only: one in a browser or under another name is not.";
|
|
60
60
|
const py = Bun.which("python3");
|
|
61
61
|
if (!cmd && (process.platform !== "linux" || !py)) return { needs: [{ name: process.platform === "linux" ? "python3" : "Linux", found: false }], note };
|
|
62
|
-
const r = Bun.spawnSync([...(cmd ?? [py!, "-I", HELPER]), "check"], { stdout: "pipe", stderr: "ignore", timeout: 5000 });
|
|
62
|
+
const r = Bun.spawnSync([...(cmd ?? [py!, "-I", HELPER]), "check"], { stdout: "pipe", stderr: "ignore", timeout: 5000, windowsHide: true });
|
|
63
63
|
let c: any = {};
|
|
64
64
|
try { c = JSON.parse(r.stdout.toString()); } catch { /* an unreadable check counts as missing */ }
|
|
65
65
|
return { needs: [{ name: "AT-SPI bindings", found: c.atspi === true }, { name: "accessibility on", found: c.a11y === true }], note };
|
package/cli/conpty.ts
CHANGED
|
@@ -31,8 +31,9 @@ public static class KzPty {
|
|
|
31
31
|
IntPtr sz = IntPtr.Zero;
|
|
32
32
|
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref sz);
|
|
33
33
|
var si = new STARTUPINFOEX(); si.si.cb = Marshal.SizeOf(typeof(STARTUPINFOEX));
|
|
34
|
-
// STARTF_USESTDHANDLES
|
|
35
|
-
si.si.fl =
|
|
34
|
+
// STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW (SW_HIDE = 0): otherwise the child takes this host's piped stdio or flashes a console window.
|
|
35
|
+
si.si.fl = 0x101;
|
|
36
|
+
si.si.sw = 0;
|
|
36
37
|
si.attrs = Marshal.AllocHGlobal(sz);
|
|
37
38
|
if (!InitializeProcThreadAttributeList(si.attrs, 1, 0, ref sz)
|
|
38
39
|
|| !UpdateProcThreadAttribute(si.attrs, 0, (IntPtr)0x20016, hpc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero)) return 1;
|
|
@@ -79,7 +80,8 @@ public static class KzPty {
|
|
|
79
80
|
|
|
80
81
|
// The PowerShell that hosts it: the child's command line, size and directory come in
|
|
81
82
|
// through the environment, so nothing the agent is given passes through a quoting layer.
|
|
82
|
-
const SCRIPT =
|
|
83
|
+
const SCRIPT = `$ProgressPreference = 'SilentlyContinue'
|
|
84
|
+
Add-Type -TypeDefinition @'
|
|
83
85
|
${HOST}
|
|
84
86
|
'@
|
|
85
87
|
Set-Location -LiteralPath $env:KZ_PTY_CWD
|
|
@@ -92,8 +94,11 @@ export const resizeSeq = (cols: number, rows: number) => `\x1b]kzr;${cols};${row
|
|
|
92
94
|
// The command line the pseudo console starts: PowerShell running cmd. It finds .cmd
|
|
93
95
|
// shims (npm installs claude as one), which CreateProcess alone does not, and takes
|
|
94
96
|
// the arguments as -EncodedCommand, as findTerminal does, so newlines survive.
|
|
97
|
+
// Windows PowerShell 5.1 strips unescaped `"` when building the Win32 command line for
|
|
98
|
+
// native executables, so embedded double quotes are escaped for non-.ps1 targets.
|
|
95
99
|
export function innerCommand(shell: string, cmd: string[]): string {
|
|
96
|
-
const
|
|
100
|
+
const ps1 = /\.ps1$/i.test(cmd[0] ?? "");
|
|
101
|
+
const q = (a: string, i: number) => `'${(i > 0 && !ps1 ? a.replace(/"/g, '\\"') : a).replace(/'/g, "''")}'`;
|
|
97
102
|
const enc = Buffer.from(`& ${cmd.map(q).join(" ")}`, "utf16le").toString("base64");
|
|
98
103
|
return `"${shell}" -NoProfile -ExecutionPolicy Bypass -EncodedCommand ${enc}`;
|
|
99
104
|
}
|
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
|
-
|
|
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
|
package/cli/keep-awake.ts
CHANGED
|
@@ -10,7 +10,7 @@ export function inhibitArgv(platform = process.platform as string, pid = process
|
|
|
10
10
|
|
|
11
11
|
export const wantAwake = (mode: string, agentsRunning: boolean) => mode === "on" || (mode === "auto" && agentsRunning);
|
|
12
12
|
|
|
13
|
-
export function awakeHolder(start: (argv: string[]) => { kill: () => void; exited?: Promise<unknown> } = (a) => Bun.spawn(a, { stdin: "ignore", stdout: "ignore", stderr: "ignore" }), argv = inhibitArgv()) {
|
|
13
|
+
export function awakeHolder(start: (argv: string[]) => { kill: () => void; exited?: Promise<unknown> } = (a) => Bun.spawn(a, { stdin: "ignore", stdout: "ignore", stderr: "ignore", windowsHide: true }), argv = inhibitArgv()) {
|
|
14
14
|
let held: { kill: () => void } | null = null;
|
|
15
15
|
const stop = () => { held?.kill(); held = null; };
|
|
16
16
|
return {
|
package/cli/pty.ts
CHANGED
|
@@ -3,13 +3,17 @@
|
|
|
3
3
|
// They live in this process: the board stopping ends them, as closing a terminal
|
|
4
4
|
// window ends the agent in it. Bun has no pseudo-terminal on Windows; there the
|
|
5
5
|
// agent runs under a ConPTY host (conpty.ts) spoken to over pipes.
|
|
6
|
-
import { writeFileSync } from "node:fs";
|
|
6
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
7
8
|
import { join } from "node:path";
|
|
8
9
|
import { conptyHost, innerCommand, resizeSeq } from "./conpty.ts";
|
|
9
10
|
|
|
10
11
|
const WIN = process.platform === "win32";
|
|
11
12
|
// Windows PowerShell, which every Windows has, both hosts the console and runs the agent in it.
|
|
12
13
|
const winPs = () => join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
14
|
+
const killWinTree = (pid: number) => {
|
|
15
|
+
try { Bun.spawnSync([join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe"), "/T", "/F", "/PID", String(pid)], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000, windowsHide: true }); } catch { /* already gone */ }
|
|
16
|
+
};
|
|
13
17
|
|
|
14
18
|
type Pty = { lastOut?: number; proc: Bun.Subprocess; out: string[]; size: number; listeners: Set<(d: string | null) => void>; exit: number | null; asking: boolean; busy: boolean; quiet?: Timer; total: number; since: number; onChange?: () => void; tmux?: string; last: string; lastAt: number; typedAt: number; born: number; draft?: boolean };
|
|
15
19
|
|
|
@@ -24,6 +28,18 @@ const ptys = new Map<string, Pty>();
|
|
|
24
28
|
// A board started from a colourless place (an agent's shell, CI) carries NO_COLOR; its terminals show colour anyway.
|
|
25
29
|
export const colorEnv = (env: Record<string, string | undefined> = process.env) => { const { NO_COLOR: _, ...rest } = env; return rest; };
|
|
26
30
|
|
|
31
|
+
// On Windows, background update checks spawned by CLI agents (like agy's background updater or Claude's)
|
|
32
|
+
// are console executables; if detached or spawned without CREATE_NO_WINDOW by the agent runtime, Windows 11
|
|
33
|
+
// delegates them to Windows Terminal, which briefly flashes an unwanted terminal window.
|
|
34
|
+
export const defaultChildEnv = (env: Record<string, string | undefined> = process.env) => ({
|
|
35
|
+
...colorEnv(env),
|
|
36
|
+
...(WIN ? {
|
|
37
|
+
AGY_CLI_DISABLE_AUTO_UPDATE: "1",
|
|
38
|
+
CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1",
|
|
39
|
+
DISABLE_AUTO_UPDATER: "1",
|
|
40
|
+
} : {}),
|
|
41
|
+
});
|
|
42
|
+
|
|
27
43
|
// What the sidebar shows for an agent: the latest line the agent printed. Keystrokes are never kept,
|
|
28
44
|
// and nothing is read while a question is open or within ECHO_MS of a keystroke: a terminal echoes
|
|
29
45
|
// what is typed, so that line could be a password. Memory only.
|
|
@@ -126,7 +142,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
|
|
|
126
142
|
const ps = winPs();
|
|
127
143
|
p.proc = Bun.spawn([ps, "-NoProfile", "-NonInteractive", "-EncodedCommand", conptyHost()], {
|
|
128
144
|
cwd,
|
|
129
|
-
env: { ...
|
|
145
|
+
env: { ...defaultChildEnv(), ...opts.env, KAIZEN_BOARD_PID: String(process.pid), KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
|
|
130
146
|
stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true,
|
|
131
147
|
});
|
|
132
148
|
const read = async (s: ReadableStream<Uint8Array>) => {
|
|
@@ -134,11 +150,25 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
|
|
|
134
150
|
for await (const c of s) push(d.decode(c, { stream: true }));
|
|
135
151
|
};
|
|
136
152
|
read(p.proc.stdout as ReadableStream<Uint8Array>).catch(() => {});
|
|
137
|
-
// The host's own failures (Add-Type, CreateProcess) land on the screen, not nowhere
|
|
138
|
-
|
|
153
|
+
// The host's own failures (Add-Type, CreateProcess) land on the screen, not nowhere;
|
|
154
|
+
// strip PowerShell's `#< CLIXML ... </Objs>` progress records when stderr is piped.
|
|
155
|
+
(async (s: ReadableStream<Uint8Array>) => {
|
|
156
|
+
const d = new TextDecoder();
|
|
157
|
+
let xml = "";
|
|
158
|
+
for await (const c of s) {
|
|
159
|
+
const t = xml + d.decode(c, { stream: true });
|
|
160
|
+
if (t.startsWith("#< CLIXML") || xml) {
|
|
161
|
+
const end = t.lastIndexOf("</Objs>");
|
|
162
|
+
if (end < 0) { xml = t; continue; }
|
|
163
|
+
xml = "";
|
|
164
|
+
const rest = t.slice(end + 7).replace(/^[\r\n]+/, "");
|
|
165
|
+
if (rest) push(rest);
|
|
166
|
+
} else push(t);
|
|
167
|
+
}
|
|
168
|
+
})(p.proc.stderr as ReadableStream<Uint8Array>).catch(() => {});
|
|
139
169
|
} else p.proc = Bun.spawn(cmd, {
|
|
140
170
|
cwd,
|
|
141
|
-
env: { ...
|
|
171
|
+
env: { ...defaultChildEnv(), ...opts.env, TERM: "xterm-256color", COLORTERM: "truecolor", KAIZEN_BOARD_PID: String(process.pid) },
|
|
142
172
|
terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
|
|
143
173
|
});
|
|
144
174
|
if (opts.tmux && tmuxOk()) p.tmux = opts.tmux;
|
|
@@ -168,7 +198,8 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
|
|
|
168
198
|
// What the agent started and left behind (a test run, a dev server) goes with it. The
|
|
169
199
|
// pty made it a session and group leader, so its group id is its PID; a tmux client's
|
|
170
200
|
// group holds only the client, never the tmux server the agent runs under.
|
|
171
|
-
if (
|
|
201
|
+
if (WIN) killWinTree(p.proc.pid);
|
|
202
|
+
else { try { process.kill(-p.proc.pid, "SIGTERM"); } catch { /* group already empty */ } }
|
|
172
203
|
// Dropped: pages showing it (the Terminal page) refresh, or its tile lingers until some other change.
|
|
173
204
|
setTimeout(() => { if (ptys.get(key) === p) { ptys.delete(key); onChange?.(); } }, KEEP_MS).unref();
|
|
174
205
|
onChange?.();
|
|
@@ -248,7 +279,7 @@ export function exitPty(key: string, grace = 5000): boolean {
|
|
|
248
279
|
send(p, "\x1b");
|
|
249
280
|
setTimeout(() => send(p, "/exit\r"), 100);
|
|
250
281
|
setTimeout(() => {
|
|
251
|
-
if (p.exit === null) { if (WIN) p.proc.kill(); else { try { process.kill(-p.proc.pid, "SIGKILL"); } catch { p.proc.kill(); } } }
|
|
282
|
+
if (p.exit === null) { if (WIN) { killWinTree(p.proc.pid); p.proc.kill(); } else { try { process.kill(-p.proc.pid, "SIGKILL"); } catch { p.proc.kill(); } } }
|
|
252
283
|
if (p.tmux) killTmux(p.tmux);
|
|
253
284
|
}, grace).unref();
|
|
254
285
|
return true;
|
|
@@ -260,7 +291,7 @@ export function killPty(key: string): boolean {
|
|
|
260
291
|
const p = ptys.get(key);
|
|
261
292
|
if (!p || p.exit !== null) return false;
|
|
262
293
|
if (p.tmux) killTmux(p.tmux);
|
|
263
|
-
if (WIN) p.proc.kill();
|
|
294
|
+
if (WIN) { killWinTree(p.proc.pid); p.proc.kill(); }
|
|
264
295
|
else { try { process.kill(-p.proc.pid, "SIGKILL"); } catch { p.proc.kill(); } }
|
|
265
296
|
return true;
|
|
266
297
|
}
|
|
@@ -306,7 +337,7 @@ export const scopeCmd = () => {
|
|
|
306
337
|
if (scoped) return scoped;
|
|
307
338
|
const run = process.platform === "linux" ? Bun.which("systemd-run") : null;
|
|
308
339
|
const cmd = run ? [run, "--user", "--scope", "--quiet", "--collect"] : [];
|
|
309
|
-
try { scoped = run && Bun.spawnSync([...cmd, "true"], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000 }).exitCode === 0 ? cmd : []; } catch { scoped = []; }
|
|
340
|
+
try { scoped = run && Bun.spawnSync([...cmd, "true"], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000, windowsHide: true }).exitCode === 0 ? cmd : []; } catch { scoped = []; }
|
|
310
341
|
return scoped;
|
|
311
342
|
};
|
|
312
343
|
// tmux draws on the alternate screen, which has no scrollback, so the card could not scroll
|
|
@@ -323,12 +354,12 @@ export const tmuxCmd = (name: string, cmd: string[]) => [...scopeCmd(), tmuxBin(
|
|
|
323
354
|
export const attachCmd = (name: string) => [tmuxBin()!, ...TMUX, "attach-session", "-t", name];
|
|
324
355
|
const tmux = (...a: string[]) => {
|
|
325
356
|
const bin = tmuxBin();
|
|
326
|
-
try { return !!bin && Bun.spawnSync([bin, ...TMUX, ...a], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000 }).exitCode === 0; } catch { return false; }
|
|
357
|
+
try { return !!bin && Bun.spawnSync([bin, ...TMUX, ...a], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000, windowsHide: true }).exitCode === 0; } catch { return false; }
|
|
327
358
|
};
|
|
328
359
|
export const tmuxAlive = (name: string) => tmux("has-session", "-t", `=${name}`);
|
|
329
360
|
export const panePid = (name: string): number | null => {
|
|
330
361
|
const bin = tmuxBin();
|
|
331
|
-
try { return bin ? Number(Bun.spawnSync([bin, ...TMUX, "display-message", "-p", "-t", `=${name}:`, "#{pane_pid}"], { stdin: "ignore", stderr: "ignore", timeout: 3000 }).stdout.toString().trim()) || null : null; } catch { return null; }
|
|
362
|
+
try { return bin ? Number(Bun.spawnSync([bin, ...TMUX, "display-message", "-p", "-t", `=${name}:`, "#{pane_pid}"], { stdin: "ignore", stderr: "ignore", timeout: 3000, windowsHide: true }).stdout.toString().trim()) || null : null; } catch { return null; }
|
|
332
363
|
};
|
|
333
364
|
export const killTmux = (name: string) => tmux("kill-session", "-t", `=${name}`);
|
|
334
365
|
|
|
@@ -373,7 +404,33 @@ export function loginEnv(shell = process.env.SHELL): Record<string, string> | nu
|
|
|
373
404
|
// entries are appended after the board's own. What the board was started with wins
|
|
374
405
|
// everywhere, so a variable or PATH set on the command line is never overridden.
|
|
375
406
|
// SIGKILL above: a shell stopped by job control ignores the timeout's SIGTERM.
|
|
407
|
+
const origWhich = Bun.which.bind(Bun);
|
|
376
408
|
export function adoptLoginEnv(env = loginEnv()) {
|
|
409
|
+
if (WIN && !env) {
|
|
410
|
+
const reg = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "reg.exe");
|
|
411
|
+
const regPath = (key: string) => {
|
|
412
|
+
try {
|
|
413
|
+
const out = Bun.spawnSync([reg, "query", key, "/v", "Path"], { stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: 2000, windowsHide: true }).stdout.toString();
|
|
414
|
+
const m = /^\s*Path\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(out);
|
|
415
|
+
return m ? m[1]!.trim().replace(/%([^%]+)%/g, (_, k) => process.env[k] ?? _) : "";
|
|
416
|
+
} catch { return ""; }
|
|
417
|
+
};
|
|
418
|
+
const pf = process.env["ProgramFiles"] ?? "C:\\Program Files", pfx86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)", h = homedir();
|
|
419
|
+
const local = process.env.LOCALAPPDATA ?? join(h, "AppData", "Local"), roam = process.env.APPDATA ?? join(h, "AppData", "Roaming");
|
|
420
|
+
const extra = [
|
|
421
|
+
...regPath("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment").split(";"),
|
|
422
|
+
...regPath("HKCU\\Environment").split(";"),
|
|
423
|
+
join(local, "agy", "bin"), join(h, ".local", "bin"), join(roam, "npm"),
|
|
424
|
+
join(pf, "Git", "cmd"), join(pf, "Git", "bin"), join(pfx86, "Git", "cmd"), join(pfx86, "Git", "bin"),
|
|
425
|
+
join(local, "Programs", "Git", "cmd"), join(local, "Programs", "MinGit", "cmd"),
|
|
426
|
+
].map((d) => d.trim()).filter((d) => d && existsSync(d));
|
|
427
|
+
const cur = (process.env.PATH ?? process.env.Path ?? "").split(";").map((d) => d.trim()).filter(Boolean);
|
|
428
|
+
const seen = new Set(cur.map((d) => d.toLowerCase()));
|
|
429
|
+
for (const d of extra) if (!seen.has(d.toLowerCase())) { seen.add(d.toLowerCase()); cur.push(d); }
|
|
430
|
+
process.env.PATH = process.env.Path = cur.join(";");
|
|
431
|
+
Bun.which = ((bin: string, opts?: Parameters<typeof Bun.which>[1]) => origWhich(bin, { PATH: process.env.PATH ?? process.env.Path, ...opts })) as typeof Bun.which;
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
377
434
|
if (!env) return;
|
|
378
435
|
// The shell's own bookkeeping describes that shell, not this process.
|
|
379
436
|
for (const [k, v] of Object.entries(env)) if (process.env[k] === undefined && !["PWD", "OLDPWD", "SHLVL", "_"].includes(k)) process.env[k] = v;
|
package/cli/settings.ts
CHANGED
|
@@ -452,8 +452,8 @@ export async function settings(repoRoot: string, standalone = true) {
|
|
|
452
452
|
// project that has not written one of its own is edited globally, so one setting
|
|
453
453
|
// changed in ~/.kaizen/config.yml reaches every project.
|
|
454
454
|
function locate() {
|
|
455
|
-
|
|
456
|
-
for (
|
|
455
|
+
const h = homedir();
|
|
456
|
+
for (let dir = process.cwd(); dir !== h; ) {
|
|
457
457
|
const conf = join(dir, ".kaizen", "config.yml");
|
|
458
458
|
if (existsSync(conf)) return conf;
|
|
459
459
|
if (existsSync(join(dir, ".git"))) break;
|
package/cli/setup.ts
CHANGED
|
@@ -59,7 +59,7 @@ export async function setup(ui: Ui) {
|
|
|
59
59
|
const project = projectStep(process.cwd(), home);
|
|
60
60
|
const needsProject = !(project && "ready" in project);
|
|
61
61
|
const tailnetNow = () => {
|
|
62
|
-
try { return tailnetName(Bun.spawnSync(["tailscale", "status", "--json"]).stdout.toString()); } catch { return null; /* not installed */ }
|
|
62
|
+
try { return tailnetName(Bun.spawnSync(["tailscale", "status", "--json"], { windowsHide: true }).stdout.toString()); } catch { return null; /* not installed */ }
|
|
63
63
|
};
|
|
64
64
|
let tailnet = tailnetNow();
|
|
65
65
|
const total = 3 + (needsProject ? 1 : 0);
|
|
@@ -69,7 +69,7 @@ export async function setup(ui: Ui) {
|
|
|
69
69
|
out(`\n ${c.bold("kaizen setup")} ${c.dim("Press Enter to take the first choice. Nothing changes without an answer.")}`);
|
|
70
70
|
|
|
71
71
|
const initProject = (dir: string) => {
|
|
72
|
-
const r = Bun.spawnSync([process.execPath, INSTALL, "--yes", "--init-project"], { cwd: dir });
|
|
72
|
+
const r = Bun.spawnSync([process.execPath, INSTALL, "--yes", "--init-project"], { cwd: dir, windowsHide: true });
|
|
73
73
|
if (r.exitCode === 0 && existsSync(join(dir, ".kaizen"))) { remember(dir); out(` ${c.green("+")} ${dir} is ready`); }
|
|
74
74
|
else out(` ${c.dim(`Could not set up ${dir}. Run kaizen setup from inside it to try again.`)}`);
|
|
75
75
|
};
|
package/cli/skills.ts
CHANGED
|
@@ -114,7 +114,7 @@ export function setSkill(repo: string, home: string, id: string, on: boolean, co
|
|
|
114
114
|
for (const h of SKILL_HOMES) {
|
|
115
115
|
if (!existsSync(join(home, h.dir))) continue;
|
|
116
116
|
const dir = join(home, h.dir, "skills"), p = join(dir, id);
|
|
117
|
-
if (!on) { if (ours(p, skill.rel)) unlinkSync(p); continue; }
|
|
117
|
+
if (!on) { if (ours(p, skill.rel)) { try { unlinkSync(p); } catch { rmdirSync(p); } } continue; }
|
|
118
118
|
if (existsSync(p) || isLink(p)) continue;
|
|
119
119
|
mkdirSync(dir, { recursive: true });
|
|
120
120
|
symlinkSync(join(clone, "skills", skill.rel), p, process.platform === "win32" ? "junction" : undefined);
|
package/cli/state.ts
CHANGED
|
@@ -234,13 +234,14 @@ export function findTerminal(cwd: string, fullCmd: string[], pidFile?: string):
|
|
|
234
234
|
// own arguments on -- neither survives as a plain -Command string. Windows
|
|
235
235
|
// Terminal hosts the shell when installed; otherwise `start` gives it a window.
|
|
236
236
|
if (process.platform === "win32") {
|
|
237
|
-
const
|
|
237
|
+
const ps1 = /\.ps1$/i.test(fullCmd[0] ?? "");
|
|
238
|
+
const q = (a: string, i = 0) => `'${(i > 0 && !ps1 ? a.replace(/"/g, '\\"') : a).replace(/'/g, "''")}'`;
|
|
238
239
|
const shell = powershellExe();
|
|
239
240
|
// This PowerShell's PID: ending its tree closes the -NoExit tab or window.
|
|
240
241
|
// The pid file gone after the agent means closeSessions ended it: exit 0, which closes
|
|
241
242
|
// the tab (Windows Terminal keeps one open after a non-zero exit). An agent that ends
|
|
242
243
|
// by itself leaves the window open, -NoExit, so what it printed can still be read.
|
|
243
|
-
const ps = `${pidFile ? `$PID | Set-Content -LiteralPath ${q(pidFile)}; ` : ""}Set-Location ${q(cwd)}; & ${fullCmd.map(q).join(" ")}${pidFile ? `; if (-not (Test-Path -LiteralPath ${q(pidFile)})) { exit 0 }` : ""}`;
|
|
244
|
+
const ps = `${pidFile ? `$PID | Set-Content -LiteralPath ${q(pidFile)}; ` : ""}Set-Location ${q(cwd)}; & ${fullCmd.map((a, i) => q(a, i)).join(" ")}${pidFile ? `; if (-not (Test-Path -LiteralPath ${q(pidFile)})) { exit 0 }` : ""}`;
|
|
244
245
|
const enc = Buffer.from(ps, "utf16le").toString("base64");
|
|
245
246
|
// herdr (beta on Windows) first, as elsewhere: a new tab, and the run typed into
|
|
246
247
|
// its PowerShell. Typed text ends at a newline, so what is typed is one line, the
|
|
@@ -1870,12 +1871,19 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1870
1871
|
const vars = [...(pick.task ? [`KAIZEN_TASK_ID=${pick.task.id}`] : []), ...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...subagentEnv(projectDir, agent.cmd), ...accountEnv(acct)];
|
|
1871
1872
|
const identity = vars.length && process.platform !== "win32" ? ["env", ...vars] : [];
|
|
1872
1873
|
const started = [...identity, ...withEnv(s.fullCmd, agent.cmd, prefs)];
|
|
1874
|
+
const winEnv = process.platform === "win32" ? {
|
|
1875
|
+
AGY_CLI_DISABLE_AUTO_UPDATE: "1",
|
|
1876
|
+
CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1",
|
|
1877
|
+
DISABLE_AUTO_UPDATER: "1",
|
|
1878
|
+
...(prefs.agents[agent.cmd]?.env ?? {}),
|
|
1879
|
+
...Object.fromEntries(vars.map((kv) => { const eq = kv.indexOf("="); return [kv.slice(0, eq), kv.slice(eq + 1)]; })),
|
|
1880
|
+
} : undefined;
|
|
1873
1881
|
const drop = () => { if (s.record) rmSync(s.record, { force: true }); };
|
|
1874
1882
|
|
|
1875
1883
|
if (pick.card && ptySupported) {
|
|
1876
1884
|
const key = s.key ?? `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1877
1885
|
try {
|
|
1878
|
-
startPty(key, started, projectDir, s.pidFile, pick.onChange, { seed: pick.seed, tmux: keepAlive(projectDir) === "tmux" ? tmuxName(key) : undefined });
|
|
1886
|
+
startPty(key, started, projectDir, s.pidFile, pick.onChange, { seed: pick.seed, tmux: keepAlive(projectDir) === "tmux" ? tmuxName(key) : undefined, env: winEnv });
|
|
1879
1887
|
return { ok: true, agent, prompt, projectDir, cmd: s.fullCmd, pty: key };
|
|
1880
1888
|
} catch (err: any) {
|
|
1881
1889
|
drop();
|
|
@@ -1900,8 +1908,9 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1900
1908
|
stderr: "ignore",
|
|
1901
1909
|
detached: term.detached,
|
|
1902
1910
|
// A detached launch is the terminal window itself; anything else (herdr's
|
|
1903
|
-
// launcher
|
|
1904
|
-
|
|
1911
|
+
// launcher, or `cmd.exe /c start` which opens its own PowerShell window and exits)
|
|
1912
|
+
// is plumbing, and must not flash a console on Windows.
|
|
1913
|
+
windowsHide: !term.detached || (process.platform === "win32" && /cmd\.exe$/i.test(term.cmd[0] ?? "")),
|
|
1905
1914
|
});
|
|
1906
1915
|
if (term.detached) proc.unref();
|
|
1907
1916
|
return { ok: true, agent, prompt, projectDir, cmd: term.cmd };
|
|
@@ -1915,7 +1924,9 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1915
1924
|
export async function pidOnPort(port: number): Promise<number | null> {
|
|
1916
1925
|
try {
|
|
1917
1926
|
if (process.platform === "win32") {
|
|
1918
|
-
const
|
|
1927
|
+
const p = Bun.spawn([sysExe("netstat.exe"), "-ano", "-p", "tcp"], { stdin: "ignore", stdout: "pipe", stderr: "ignore", windowsHide: true });
|
|
1928
|
+
const out = await new Response(p.stdout).text();
|
|
1929
|
+
await p.exited;
|
|
1919
1930
|
const m = new RegExp(`127\\.0\\.0\\.1:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`).exec(out);
|
|
1920
1931
|
return m ? Number(m[1]) : null;
|
|
1921
1932
|
}
|
package/cli/web.ts
CHANGED
|
@@ -1077,7 +1077,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1077
1077
|
const key = "sh-" + crypto.randomUUID().slice(0, 8);
|
|
1078
1078
|
const title = dev ? "dev server" : agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
|
|
1079
1079
|
// A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
|
|
1080
|
-
const pid = startPty(key, cmd, cwd, undefined, changed, {
|
|
1080
|
+
const pid = startPty(key, cmd, cwd, undefined, changed, {
|
|
1081
|
+
env: {
|
|
1082
|
+
KAIZEN_TERM: key,
|
|
1083
|
+
...(process.platform === "win32" ? { AGY_CLI_DISABLE_AUTO_UPDATE: "1", CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1", DISABLE_AUTO_UPDATER: "1" } : {}),
|
|
1084
|
+
...(dev ? { __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: ".ts.net" } : {}),
|
|
1085
|
+
},
|
|
1086
|
+
});
|
|
1081
1087
|
// The run workspace that opened it (its card key), so each run keeps its own centre.
|
|
1082
1088
|
shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
|
|
1083
1089
|
shellCmd.set(key, cmd);
|
|
@@ -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();
|