kaizen-agent 1.87.1 → 1.87.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/chat.ts CHANGED
@@ -7,6 +7,7 @@ import { randomUUID } from "node:crypto";
7
7
  import { basename, dirname, join } from "node:path";
8
8
  import { hostname, platform, release, arch } from "node:os";
9
9
  import { CHILD_ENV, readRuns, readText } from "./state.ts";
10
+ import { listTasks } from "./tasks.ts";
10
11
 
11
12
  export type Step = { kind: "cmd" | "edit" | "tool" | "project"; text: string; ok?: boolean };
12
13
  export type Attachment = { name: string; path: string; image: boolean };
@@ -29,6 +30,10 @@ export type Board = {
29
30
  projects: { dir: string; label: string }[];
30
31
  create: (name: string) => Promise<{ dir: string } | { error: string }>;
31
32
  agents: string[];
33
+ // Saves a goal as a task in the project's Tasks list, without starting an agent.
34
+ task: (dir: string, goal: string) => { error: string } | { ok: true };
35
+ // Sends a message to an existing task, as the task page's box does (an agent may pick it up).
36
+ taskAdd: (dir: string, id: string, text: string) => { error: string } | { ok: true };
32
37
  run: (dir: string, runner: "lite" | "full", agent: string, text: string) => Promise<{ agent: string } | { error: string }>;
33
38
  };
34
39
  // The project folders the agent may write in: every listed one, capped like the brief's list.
@@ -69,6 +74,8 @@ export function brief(c: Chat, board: Board) {
69
74
  const waiting = board.projects.slice(0, 80).flatMap((p) => readRuns(p.dir)
70
75
  .filter((r) => r.awaiting && r.stage !== "done" && r.stage !== "abandoned")
71
76
  .map((r) => `- ${p.label}: ${r.id} (${r.stage}, waiting on ${r.awaiting})`)).join("\n");
77
+ const tasksList = board.projects.slice(0, 80).flatMap((p) => { try { return listTasks(p.dir).filter((t) => !t.archived && t.status !== "accepted").slice(0, 30)
78
+ .map((t) => `- ${p.label}: ${t.id} (${t.status}) ${short(t.title || t.goal, 80)}`); } catch { return []; } }).join("\n");
72
79
  return `[kaizen board context, not written by the user]
73
80
  You are kaizen's main agent, talking with the user from the kaizen board's Home page.
74
81
  Board server machine: hostname ${hostname()}, OS ${platform()} ${release()}, architecture ${arch()}. This is the machine hosting the board, not necessarily the user's phone or browser. A scratch folder is only your working directory, not a separate machine.
@@ -80,9 +87,12 @@ Projects on the board:
80
87
  ${list || "(none)"}
81
88
  Runs waiting on the user:
82
89
  ${waiting || "(none)"}
90
+ Open tasks (project: id (status) title):
91
+ ${tasksList || "(none)"}
83
92
  Each project's kaizen runs live in <project>/.kaizen/runs/<id>/ (state.json has stage and awaiting; 01-plan.md, 04-review.md, 06-backlog.md beside it); read them to answer questions about the board.
84
93
  You can read, analyse and edit files in any project folder listed above directly by its path; you do not need to switch to it. Do not write outside those folders and your working folder.
85
94
  Switching only changes this chat's home project (where you run and which project the board shows). On a line of its own write [[kaizen:project <folder>]] to switch to a listed project, or [[kaizen:new-project <name>]] to create one (a plain folder name). Switch only when the user asks; when what they want fits no listed project, ask whether to create a new one. After a successful move, the board starts one follow-up turn in the new project to finish the pending request; do not ask the user to repeat it.
95
+ When the user asks to add, create or save a task (or put something on the task list), write on a line of its own [[kaizen:task <project folder> | <the goal, one line>]]; the board saves it in that project's Tasks list without starting anything. Do not ask the lite/full question for this, and do not edit files to fake a task. To add something to a task that already exists (a note, an extra requirement, a change), write [[kaizen:task-add <project folder> | <task id from the list> | <what to add, one line>]]; the board sends it to that task like the task page's message box.
86
96
  When the user asks you to develop, fix, change or enhance something (not a question, analysis or reading), first ask which way, as numbered options, and do nothing until they pick:
87
97
  1. Start a kaizen run for it: lite (cheap, one session) or full (independent review), with which agent (installed: ${board.agents.join(", ") || "none"}), in which project.
88
98
  2. Let you handle it here in the chat.
@@ -165,20 +175,30 @@ export function parseLine(line: string): Event | { t: "thread"; id: string } | n
165
175
  }
166
176
 
167
177
  // The agent's move and run lines: taken out of what the user reads; the last of each counts.
168
- const MOVE = /^[ \t]*\[\[kaizen:(project|new-project|run)[ \t]+([^\]\n]+?)\]\][ \t]*$/gm;
178
+ const MOVE = /^[ \t]*\[\[kaizen:(project|new-project|run|task-add|task)[ \t]+([^\]\n]+?)\]\][ \t]*$/gm;
179
+ export type TaskAddAsk = { project: string; id: string; text: string };
180
+ export type TaskAsk = { project: string; goal: string };
169
181
  export type RunAsk = { project: string; runner: string; agent: string; text: string };
170
182
  export function takeMoves(text: string) {
171
183
  let move: { op: "project" | "new-project"; arg: string } | null = null;
172
184
  let run: RunAsk | null = null;
185
+ let task: TaskAsk | null = null;
186
+ let taskAdd: TaskAddAsk | null = null;
173
187
  const rest = text.replace(MOVE, (_, op, arg) => {
174
- if (op !== "run") move = { op, arg: arg.trim() };
188
+ if (op === "task-add") {
189
+ const [project = "", id = "", ...t] = arg.split("|").map((x: string) => x.trim());
190
+ taskAdd = { project, id, text: t.join(" | ").trim() };
191
+ } else if (op === "task") {
192
+ const [project = "", ...g] = arg.split("|").map((x: string) => x.trim());
193
+ task = { project, goal: g.join(" | ").trim() };
194
+ } else if (op !== "run") move = { op, arg: arg.trim() };
175
195
  else {
176
196
  const [project = "", runner = "", agent = "", ...t] = arg.split("|").map((x: string) => x.trim());
177
197
  run = { project, runner, agent, text: t.join(" | ").trim() };
178
198
  }
179
199
  return "";
180
200
  }).replace(/\n{3,}/g, "\n\n").trim();
181
- return { text: rest, move: move as { op: "project" | "new-project"; arg: string } | null, run: run as RunAsk | null };
201
+ return { text: rest, move: move as { op: "project" | "new-project"; arg: string } | null, run: run as RunAsk | null, task: task as TaskAsk | null, taskAdd: taskAdd as TaskAddAsk | null };
182
202
  }
183
203
 
184
204
  // Not winShim: the message goes in on stdin, so the .cmd shim's newline limit never applies.
@@ -254,6 +274,8 @@ export function sendChat(base: string, id: string | null, text: string, project:
254
274
  let buf = "";
255
275
  let move: ReturnType<typeof takeMoves>["move"] = null;
256
276
  let run: RunAsk | null = null;
277
+ let task: TaskAsk | null = null;
278
+ let taskAdd: TaskAddAsk | null = null;
257
279
  const take = (line: string) => {
258
280
  const e = parseLine(line);
259
281
  if (!e) return;
@@ -262,6 +284,8 @@ export function sendChat(base: string, id: string | null, text: string, project:
262
284
  const m = takeMoves(e.text);
263
285
  if (m.move) move = m.move;
264
286
  if (m.run) run = m.run;
287
+ if (m.task) task = m.task;
288
+ if (m.taskAdd) taskAdd = m.taskAdd;
265
289
  if (!m.text) return;
266
290
  e.text = m.text;
267
291
  reply.text += (reply.text ? "\n\n" : "") + e.text;
@@ -291,6 +315,8 @@ export function sendChat(base: string, id: string | null, text: string, project:
291
315
  if (offered) await startRun(reply, run, board, emit);
292
316
  else { const s: Step = { kind: "project", text: "Not started: ask me to pick lite or full first", ok: false }; reply.steps!.push(s); emit({ t: "step", step: s }); }
293
317
  }
318
+ if (task && !stopped) addTask(reply, task, board, emit);
319
+ if (taskAdd && !stopped) addToTask(reply, taskAdd, board, emit);
294
320
  if (move && !stopped) await moveChat(chat, reply, move, board, emit);
295
321
  } finally {
296
322
  delete reply.activity;
@@ -323,6 +349,30 @@ async function startRun(reply: Msg, ask: RunAsk, board: Board, emit: (e: Event)
323
349
  emit({ t: "run", dir: p.dir });
324
350
  }
325
351
 
352
+ // Save the goal the user asked for as a task: only in a listed project.
353
+ function addTask(reply: Msg, ask: TaskAsk, board: Board, emit: (e: Event) => void) {
354
+ const step = (text: string, ok: boolean) => { const s: Step = { kind: "project", text, ok }; reply.steps!.push(s); emit({ t: "step", step: s }); };
355
+ const p = findProject(board, ask.project);
356
+ if (!p) return step(`No project ${ask.project} on the board`, false);
357
+ if (!ask.goal) return step("No goal for the task", false);
358
+ const r = board.task(p.dir, ask.goal);
359
+ if ("error" in r) return step(`Could not add the task: ${r.error}`, false);
360
+ step(`Added a task in ${p.label}`, true);
361
+ emit({ t: "run", dir: p.dir });
362
+ }
363
+
364
+ // Send text to a task the board lists, by id, in a listed project.
365
+ function addToTask(reply: Msg, ask: TaskAddAsk, board: Board, emit: (e: Event) => void) {
366
+ const step = (text: string, ok: boolean) => { const s: Step = { kind: "project", text, ok }; reply.steps!.push(s); emit({ t: "step", step: s }); };
367
+ const p = findProject(board, ask.project);
368
+ if (!p) return step(`No project ${ask.project} on the board`, false);
369
+ if (!ask.id || !ask.text) return step("Need a task id and the text to add", false);
370
+ const r = board.taskAdd(p.dir, ask.id, ask.text);
371
+ if ("error" in r) return step(`Could not add to the task: ${r.error}`, false);
372
+ step(`Added to a task in ${p.label}`, true);
373
+ emit({ t: "run", dir: p.dir });
374
+ }
375
+
326
376
  // Apply the agent's move: only to a project the board lists, or one the board's own rules create.
327
377
  async function moveChat(chat: Chat, reply: Msg, move: { op: string; arg: string }, board: Board, emit: (e: Event) => void) {
328
378
  const step = (text: string, ok: boolean) => { const s: Step = { kind: "project", text, ok }; reply.steps!.push(s); emit({ t: "step", step: s }); };
package/cli/conpty.ts CHANGED
@@ -23,7 +23,7 @@ public static class KzPty {
23
23
  [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
24
24
  static COORD Size(int c, int r) { COORD s; s.X = (short)c; s.Y = (short)r; return s; }
25
25
  static FileStream Of(IntPtr h, FileAccess a) { return new FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(h, true), a); }
26
- public static int Run(string cmd, int cols, int rows) {
26
+ public static int Run(string cmd, int cols, int rows, string cwd = null) {
27
27
  IntPtr inR, inW, outR, outW, hpc;
28
28
  if (!CreatePipe(out inR, out inW, IntPtr.Zero, 0) || !CreatePipe(out outR, out outW, IntPtr.Zero, 0)) return 1;
29
29
  int hr = CreatePseudoConsole(Size(cols, rows), inR, outW, 0, out hpc);
@@ -38,7 +38,7 @@ public static class KzPty {
38
38
  if (!InitializeProcThreadAttributeList(si.attrs, 1, 0, ref sz)
39
39
  || !UpdateProcThreadAttribute(si.attrs, 0, (IntPtr)0x20016, hpc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero)) return 1;
40
40
  PI pi;
41
- if (!CreateProcessW(null, cmd, IntPtr.Zero, IntPtr.Zero, false, 0x80000, IntPtr.Zero, null, ref si, out pi)) {
41
+ if (!CreateProcessW(null, cmd, IntPtr.Zero, IntPtr.Zero, false, 0x80000, IntPtr.Zero, string.IsNullOrEmpty(cwd) ? null : cwd, ref si, out pi)) {
42
42
  Console.Error.WriteLine("CreateProcess failed: " + Marshal.GetLastWin32Error()); return 1; }
43
43
  // The console holds its own copies; ours would keep the pipes open past its end.
44
44
  CloseHandle(inR); CloseHandle(outW);
@@ -84,8 +84,11 @@ const SCRIPT = `$ProgressPreference = 'SilentlyContinue'
84
84
  Add-Type -TypeDefinition @'
85
85
  ${HOST}
86
86
  '@
87
- Set-Location -LiteralPath $env:KZ_PTY_CWD
88
- exit [KzPty]::Run($env:KZ_PTY_CMD, [int]$env:KZ_PTY_COLS, [int]$env:KZ_PTY_ROWS)`;
87
+ if ($env:KZ_PTY_CWD) {
88
+ try { [System.IO.Directory]::SetCurrentDirectory($env:KZ_PTY_CWD) } catch {}
89
+ try { Set-Location -LiteralPath $env:KZ_PTY_CWD } catch {}
90
+ }
91
+ exit [KzPty]::Run($env:KZ_PTY_CMD, [int]$env:KZ_PTY_COLS, [int]$env:KZ_PTY_ROWS, $env:KZ_PTY_CWD)`;
89
92
 
90
93
  export const conptyHost = () => Buffer.from(SCRIPT, "utf16le").toString("base64");
91
94
 
package/cli/pty.ts CHANGED
@@ -140,9 +140,13 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
140
140
  };
141
141
  if (WIN) {
142
142
  const ps = winPs();
143
+ let winCmd = cmd;
144
+ if (winCmd.length === 1 && /^(powershell|pwsh)(\.exe)?$/i.test(winCmd[0].split(/[/\\]/).pop() ?? "")) {
145
+ winCmd = [winCmd[0], "-NoExit", "-Command", `Set-Location -LiteralPath '${cwd.replace(/'/g, "''")}'`];
146
+ }
143
147
  p.proc = Bun.spawn([ps, "-NoProfile", "-NonInteractive", "-EncodedCommand", conptyHost()], {
144
148
  cwd,
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" },
149
+ env: { ...defaultChildEnv(), ...opts.env, KAIZEN_BOARD_PID: String(process.pid), KZ_PTY_CMD: innerCommand(ps, winCmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
146
150
  stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true,
147
151
  });
148
152
  const read = async (s: ReadableStream<Uint8Array>) => {
package/cli/web.ts CHANGED
@@ -1098,7 +1098,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1098
1098
  const dir = homeWs ? HOME_WS : canonState(String(body.dir ?? ""));
1099
1099
  if (!homeWs && (!states(true).includes(dir) || dir === join(home, ".kaizen"))) return bad("choose a project", 404);
1100
1100
  if (homeWs) mkdirSync(HOME_WS, { recursive: true });
1101
- let cmd: string[];
1101
+ let cmd: string[] | undefined;
1102
1102
  let agent = "";
1103
1103
  let bypass = false;
1104
1104
  // The run's own agent session, resumed here ("run:<dir>:<id>" names the run; the session
@@ -1146,7 +1146,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1146
1146
  const first = !signIn && typeof body.prompt === "string" && body.prompt.trim() && body.prompt.length <= 2000 ? body.prompt.trim() : "";
1147
1147
  const line = signIn ? [commandOf(a.cmd), ...(a.cmd === "codex" ? ["login"] : [])] : withEnv([commandOf(a.cmd), ...(bypass ? YOLO_FLAGS[a.cmd]! : []), ...argsOf(a.cmd), ...promptArgs(a.cmd, first)], a.cmd);
1148
1148
  cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
1149
- } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
1149
+ }
1150
1150
  // A workspace folder: only an exact path from this project's own `git worktree list`.
1151
1151
  let cwd = homeWs ? HOME_WS : projectOf(dir);
1152
1152
  if (body.ws != null) {
@@ -1168,6 +1168,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1168
1168
  cmd = process.platform === "win32" ? ["cmd.exe", "/c", ...d] : [process.env.SHELL || "sh", "-lc", d.join(" ")];
1169
1169
  dev = true;
1170
1170
  }
1171
+ const targetDir = homeWs ? home : cwd;
1172
+ if (!cmd) {
1173
+ cmd = process.platform === "win32"
1174
+ ? [powershellExe(), "-NoExit", "-Command", `Set-Location -LiteralPath '${targetDir.replace(/'/g, "''")}'`]
1175
+ : [process.env.SHELL || "sh", "-l"];
1176
+ }
1171
1177
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
1172
1178
  if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per ${homeWs ? "workspace" : "project"}: close one first`, 429);
1173
1179
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
@@ -1175,7 +1181,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1175
1181
  // A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
1176
1182
  // Home terminals run in the user's home folder (~); HOME_WS stays their record (dir and ws), which the
1177
1183
  // Home window, restart resume and the phone match on.
1178
- const pid = startPty(key, cmd, homeWs ? home : cwd, undefined, changed, {
1184
+ const pid = startPty(key, cmd, targetDir, undefined, changed, {
1179
1185
  env: {
1180
1186
  KAIZEN_TERM: key,
1181
1187
  ...(process.platform === "win32" ? { AGY_CLI_DISABLE_AUTO_UPDATE: "1", CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1", DISABLE_AUTO_UPDATER: "1" } : {}),
@@ -2263,6 +2269,19 @@ export async function web(repoDir: string, opts: Opts = {}) {
2263
2269
  return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
2264
2270
  },
2265
2271
  agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => a.cmd),
2272
+ // A draft task: saved on the Tasks list, no agent started (the task page starts it).
2273
+ task: (d: string, goal: string) => {
2274
+ try { tasks.createTask(d, { goal, project: dirname(d) }, `chat:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); changed(); return { ok: true as const }; }
2275
+ catch (e) { return { error: (e as Error).message }; }
2276
+ },
2277
+ taskAdd: (d: string, taskId: string, text: string) => {
2278
+ try {
2279
+ const found = tasks.resolveTask(d, taskId);
2280
+ if (!found || !states(true).includes(found.state)) return { error: "unknown task" };
2281
+ taskService.taskAction(found.state, { op: "message", id: found.task.id, text, revision: found.task.revision, operationId: `chat:${Date.now()}:${Math.random().toString(36).slice(2, 8)}` }, taskHooks);
2282
+ changed(); return { ok: true as const };
2283
+ } catch (e) { return { error: (e as Error).message }; }
2284
+ },
2266
2285
  // As POST /run starts a task, without one on the inbox.
2267
2286
  run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
2268
2287
  const r = launchRun(parseItem(`${runner} ${text}`), d, undefined, { agent, ...inCard });
@@ -71,7 +71,16 @@ async function start() {
71
71
  try {
72
72
  const { state, saveCreds } = await useMultiFileAuthState(AUTH);
73
73
  let version: any;
74
- try { version = (await fetchLatestBaileysVersion()).version; } catch {}
74
+ // Baileys' own lookup swallows its errors and returns a stale built-in version (isLatest: false), which WhatsApp
75
+ // refuses; so try its raw version file too before giving up on a fresh one.
76
+ try { const r = await fetchLatestBaileysVersion(); if (r.isLatest !== false) version = r.version; } catch {}
77
+ if (!version) {
78
+ try {
79
+ const r = await fetch("https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json", { signal: AbortSignal.timeout(8000) });
80
+ const v = (await r.json() as any)?.version;
81
+ if (Array.isArray(v) && v.length === 3) version = v;
82
+ } catch {}
83
+ }
75
84
  const s = makeWASocket({ auth: state, version, logger: quiet, browser: Browsers.macOS("Kaizen"), syncFullHistory: false, markOnlineOnConnect: false });
76
85
  sock = s;
77
86
  s.ev.on("creds.update", saveCreds);
@@ -104,7 +113,10 @@ async function start() {
104
113
  wantLink = false; sock = null;
105
114
  return;
106
115
  }
107
- // Any other close (network, restart-required after the QR scan): reconnect.
116
+ // Any other close (network, restart-required after the QR scan): reconnect. Say why, so the card is not
117
+ // stuck on "Connecting" with no hint; the next open or QR clears it.
118
+ if (code !== DisconnectReason.restartRequired)
119
+ error = `WhatsApp refused the connection (${code ?? u.lastDisconnect?.error?.message ?? "no answer"}). Check the network and that the computer's clock is right; retrying`;
108
120
  starting = false;
109
121
  if (wantLink || existsSync(join(AUTH, "creds.json"))) setTimeout(() => void start(), 1500);
110
122
  else { error = "WhatsApp closed the link; try again"; sock = null; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.87.1",
3
+ "version": "1.87.2",
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": {