kaizen-agent 1.87.0 → 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>) => {
@@ -10,7 +10,10 @@ import { detectDefaultAgent, home, readInbox, writeInbox, replaceTask, abandonRu
10
10
 
11
11
  type Hooks = { launch: (state:string, run:string, text:string, task:T.Task, pick?:any) => {ok:boolean; pty?:string; why?:string}; alive:(pty:string)=>boolean; stop:(pty:string)=>boolean; find?:(state:string,run:string)=>string|undefined;
12
12
  // Sends the run's own Approve (review or open findings) to its agent, as the run panel does.
13
- approve?:(state:string,run:string,awaiting:string)=>string|null };
13
+ approve?:(state:string,run:string,awaiting:string)=>string|null;
14
+ // The agent stopped on a permission/choice prompt, and the user's yes or no typed into it.
15
+ asking?:(pty:string)=>boolean; idle?:(pty:string)=>number; answer?:(pty:string,yes:boolean)=>void };
16
+ export const HUNG_MS=5*60_000;
14
17
  const runtimeLaunches = new Set<string>();
15
18
  const parse = (file:string) => { try { return JSON.parse(readFileSync(file,'utf8')); } catch { return null; } };
16
19
  const put = (file:string,value:unknown) => { const temp = file + `.${process.pid}.${randomUUID()}.tmp`; writeFileSync(temp,JSON.stringify(value,null,2)+'\n'); renameSync(temp,file); };
@@ -40,7 +43,7 @@ export function allowedActions(state:string,task:T.Task,hooks?:Hooks) {
40
43
  export function taskView(state:string,task:T.Task,hooks?:Hooks) {
41
44
  const p=T.taskProjection(task);
42
45
  const run=runState(state,task), finished=run&&(['done','abandoned'].includes(run.stage)||run.healed);
43
- return {...task,actions:allowedActions(state,task,hooks),...(hooks?{agentAlive:!!(agentKey(state,task,hooks)&&hooks.alive(agentKey(state,task,hooks)!))}:{}),activeRun:finished&&['ready','accepted'].includes(task.status)?null:task.activeRun,projectName:task.project?.split(/[\\/]/).pop()??'Choose a project',dir:state,updatedAt:task.updated,attention:{category:p.filter,reason:p.reason,action:p.action},statusLabel:p.label,decision:!task.project?{id:'project',kind:'project',text:'Choose a named project for your saved goal.'}:task.pendingDecision,messages:task.events,runs:task.runIds,currentResultId:task.currentResult,acceptedResultId:task.acceptedResult};
46
+ return {...task,actions:allowedActions(state,task,hooks),runStage:run&&!finished?String(run.stage??''):undefined,...(hooks?.asking?{agentAsking:!!(agentKey(state,task,hooks)&&hooks.asking(agentKey(state,task,hooks)!))}:{}),...(hooks?{agentAlive:!!(agentKey(state,task,hooks)&&hooks.alive(agentKey(state,task,hooks)!))}:{}),activeRun:finished&&['ready','accepted'].includes(task.status)?null:task.activeRun,projectName:task.project?.split(/[\\/]/).pop()??'Choose a project',dir:state,updatedAt:task.updated,attention:{category:p.filter,reason:p.reason,action:p.action},statusLabel:p.label,decision:!task.project?{id:'project',kind:'project',text:'Choose a named project for your saved goal.'}:task.pendingDecision,messages:task.events,runs:task.runIds,currentResultId:task.currentResult,acceptedResultId:task.acceptedResult};
44
47
  }
45
48
  export function taskList(states:string[],hooks?:Hooks) {
46
49
  const tasks=states.flatMap(state=>T.listTasks(state).filter(t=>!t.archived).map(t=>taskView(state,reconcile(state,t,hooks),hooks)));
@@ -81,7 +84,8 @@ export function reconcile(state:string,task:T.Task,hooks?:Hooks):T.Task {
81
84
  return T.mutateTask(state,task.id,{revision:task.revision,opId:`stopped:${task.revision}`},t=>stopped(t,key));
82
85
  }
83
86
  if(task.launch && ['intent','started'].includes(task.launch.phase) && !runtimeLaunches.has(task.launch.id) && hooks && !(task.launch.pty&&hooks.alive(task.launch.pty))) reason='The launch was interrupted before the agent acknowledged it. Review the existing session before resuming.';
84
- else if(task.status==='working'&&task.launch?.pty&&hooks&&!hooks.alive(task.launch.pty)&&!task.safe)reason='The agent ended before reporting a safe handback. Your requests and previous results are saved.';
87
+ // No terminal id on record (or none left): the agent is gone when none is found for the run and the launch is old enough not to be starting.
88
+ else if(task.status==='working'&&task.launch&&hooks&&!task.safe&&!(agentKey(state,task,hooks)&&hooks.alive(agentKey(state,task,hooks)!))&&(task.launch.pty||Date.now()-task.launch.at>60_000))reason='The agent ended before reporting a safe handback. Your requests and previous results are saved.';
85
89
  if(reason) return T.mutateTask(state,task.id,{revision:task.revision,opId:`interrupted:${task.launch?.id}`},t=>{T.recoverLaunch(t);t.status='interrupted';t.error=reason;t.queuePaused=true;});
86
90
  return task;
87
91
  }
@@ -161,6 +165,12 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
161
165
  if(task.operations.includes(operationId))return {state,task};
162
166
  const allowed=allowedActions(state,task,hooks);
163
167
  if(op==='start'){task=T.mutateTask(state,task.id,mutation,t=>{if(t.status!=='draft')throw new T.TaskError('Task already started');});return {state,task:dispatchReady(state,task.id,hooks,true,body.pick&&typeof body.pick==='object'?body.pick:undefined)};}
168
+ if(op==='prompt'){
169
+ // The agent waits on a permission prompt: the user's answer goes into its terminal, so nobody has to open it.
170
+ const key=agentKey(state,task,hooks);
171
+ if(!key||!hooks.asking?.(key)||!hooks.answer)throw new T.TaskError('The agent is not waiting for an answer',409);
172
+ hooks.answer(key,body.answer==='yes');return {state,task};
173
+ }
164
174
  if(op==='delete'||op==='archive'||op==='abandon'){
165
175
  // Closing a task: Delete only before any run exists; Archive hides it; Abandon ends its run.
166
176
  if(op==='delete'){
@@ -211,7 +221,17 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
211
221
  if(key&&hooks.alive(key))hooks.stop(key);
212
222
  else try{task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':stopped'},t=>stopped(t,key));}
213
223
  catch{task=T.readTask(state,task.id)!;/* the pump confirmed the stop first: same outcome */}
214
- }else if(['message','confirm','resume'].includes(op))task=dispatchReady(state,task.id,hooks,op==='resume'&&!task.inputs.some(i=>['queued','received'].includes(i.state)));
224
+ }else if(['message','confirm','resume'].includes(op)){
225
+ // A working agent that has printed nothing for HUNG_MS is hung (a live one redraws its spinner every second): a message ends it,
226
+ // and the recovery below, or the pump once the process is gone, starts it again with the message.
227
+ const hung=agentKey(state,task,hooks);
228
+ if(op==='message'&&task.status==='working'&&hung&&hooks.alive(hung)&&!hooks.asking?.(hung)&&(hooks.idle?.(hung)??0)>HUNG_MS){
229
+ hooks.stop(hung);
230
+ task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':hung'},t=>{t.status='interrupted';t.queuePaused=true;t.safe=false;t.error='The agent ended because it stopped responding.';});
231
+ }
232
+ // The agent is gone (interrupted/failed, queue paused): a message is the user asking to go on, so recover instead of leaving it queued.
233
+ if(op==='message'&&['interrupted','failed'].includes(task.status)&&allowedActions(state,task,hooks).resume)task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':recover'},t=>{T.resumeTask(t);});
234
+ task=dispatchReady(state,task.id,hooks,op==='resume'&&!task.inputs.some(i=>['queued','received'].includes(i.state)));}
215
235
  return {state,task};
216
236
  }
217
237
 
@@ -271,3 +291,15 @@ export function taskEvent(state:string,id:string,runId:string,event:any,operatio
271
291
  throw error;
272
292
  }
273
293
  }
294
+
295
+ // A run's agent that ended mid-work (crash, closed terminal, the board restarting) is started again by itself, so the user never
296
+ // has to open the terminal to Resume. Three tries, then one more every half hour; a launch that cannot start stays failed.
297
+ const ENDED=/^(The agent ended|The launch was interrupted)/;
298
+ export function autoRecover(state:string,task:T.Task,hooks:Hooks):T.Task {
299
+ if(!['interrupted','failed'].includes(task.status)||!task.queuePaused||task.archived||!ENDED.test(task.error??''))return task;
300
+ const run=runState(state,task);if(!run||['done','abandoned'].includes(run.stage)||run.healed)return task;
301
+ const n=task.recoveries??0;if(n>=3&&Date.now()-(task.recoveredAt??0)<30*60_000)return task;
302
+ if(!allowedActions(state,task,hooks).resume)return task;
303
+ task=T.mutateTask(state,task.id,{revision:task.revision,opId:`auto-recover:${task.revision}`},t=>{T.resumeTask(t);t.recoveries=n>=3?1:n+1;t.recoveredAt=Date.now();t.events.push({id:randomUUID(),at:Date.now(),role:'system',type:'auto-resume',text:'The agent ended, so kaizen started it again and it continues from the saved run.'} as any);});
304
+ return dispatchReady(state,task.id,hooks,!task.inputs.some(i=>['queued','received'].includes(i.state)));
305
+ }
package/cli/tasks.ts CHANGED
@@ -14,7 +14,7 @@ export type Task = {
14
14
  status: "draft" | "waiting" | "working" | "ready" | "accepted" | "stopping" | "interrupted" | "failed";
15
15
  runIds: string[]; activeRun: string | null; currentResult: string | null; acceptedResult: string | null;
16
16
  pendingDecision: TaskDecision | null; inputs: TaskInput[]; events: TaskEvent[]; operations: string[];
17
- files: { name: string; path: string }[]; launch: TaskLaunch | null; safe: boolean; queuePaused: boolean;
17
+ files: { name: string; path: string }[]; launch: TaskLaunch | null; safe: boolean; queuePaused: boolean; recoveries?: number; recoveredAt?: number;
18
18
  initialConfirmed: boolean; writePhase: boolean; error?: string; legacyKey?: string; archived?: boolean; alias?: { state: string; id: string };
19
19
  };
20
20
  export type Mutation = { revision: number; opId: string };
package/cli/web.ts CHANGED
@@ -327,6 +327,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
327
327
  return launchRun({ severity: null, where: null, text, raw: text }, dir, id, { ...inCard, ...(pick ? { agent: KNOWN_AGENTS.some((a) => a.cmd === pick.agent) ? pick.agent : undefined, account: typeof pick.account === "string" ? pick.account : undefined, explore: typeof pick.explore === "boolean" ? pick.explore : undefined, yolo: pick.yolo === true } : {}), task: { id: task.id, requirePlanConfirmation: !task.initialConfirmed } });
328
328
  },
329
329
  alive: (key: string) => ptyState(key)?.alive === true,
330
+ idle: (key: string) => { const s = ptyState(key); return s ? Date.now() - (s.lastOut ?? s.born) : 0; },
331
+ asking: (key: string) => ptyState(key)?.asking === true,
332
+ // Claude Code and Codex menus take a digit, Esc backs out. ponytail: per-agent keys, a prompt worded otherwise still needs the terminal.
333
+ answer: (key: string, yes: boolean) => writePty(key, yes ? "1" : "\x1b"),
330
334
  stop: (key: string) => killPty(key),
331
335
  find: (dir: string, run: string) => liveAgent(dir, run)?.key,
332
336
  };
@@ -335,6 +339,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
335
339
  // A stopping task is asked to stop again until its terminal is gone, not only when someone opens it.
336
340
  // A ready task also picks up its run's acceptance given in the agent terminal (kaizen done --user-approved).
337
341
  if ((task.status === "stopping" || task.status === "ready") && !task.archived) { try { if (taskService.reconcile(dir, task, taskHooks).revision !== task.revision) changed(); } catch { /* next pass */ } if (task.status === "stopping") continue; }
342
+ // A working task whose agent died is noticed and started again here, not only when someone opens it.
343
+ if (["working", "interrupted", "failed"].includes(task.status) && !task.archived) { try { const r = taskService.autoRecover(dir, taskService.reconcile(dir, task, taskHooks), taskHooks); if (r.revision !== task.revision) changed(); } catch { /* next pass */ } continue; }
338
344
  if (!task.safe || task.queuePaused || task.pendingDecision || !task.inputs.some(i => i.state === "queued")) continue;
339
345
  try { taskService.dispatchReady(dir, task.id, taskHooks); changed(); } catch { /* CAS conflict: next pass reads the new state */ }
340
346
  }
@@ -1092,7 +1098,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1092
1098
  const dir = homeWs ? HOME_WS : canonState(String(body.dir ?? ""));
1093
1099
  if (!homeWs && (!states(true).includes(dir) || dir === join(home, ".kaizen"))) return bad("choose a project", 404);
1094
1100
  if (homeWs) mkdirSync(HOME_WS, { recursive: true });
1095
- let cmd: string[];
1101
+ let cmd: string[] | undefined;
1096
1102
  let agent = "";
1097
1103
  let bypass = false;
1098
1104
  // The run's own agent session, resumed here ("run:<dir>:<id>" names the run; the session
@@ -1140,7 +1146,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1140
1146
  const first = !signIn && typeof body.prompt === "string" && body.prompt.trim() && body.prompt.length <= 2000 ? body.prompt.trim() : "";
1141
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);
1142
1148
  cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
1143
- } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
1149
+ }
1144
1150
  // A workspace folder: only an exact path from this project's own `git worktree list`.
1145
1151
  let cwd = homeWs ? HOME_WS : projectOf(dir);
1146
1152
  if (body.ws != null) {
@@ -1162,6 +1168,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1162
1168
  cmd = process.platform === "win32" ? ["cmd.exe", "/c", ...d] : [process.env.SHELL || "sh", "-lc", d.join(" ")];
1163
1169
  dev = true;
1164
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
+ }
1165
1177
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
1166
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);
1167
1179
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
@@ -1169,7 +1181,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1169
1181
  // A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
1170
1182
  // Home terminals run in the user's home folder (~); HOME_WS stays their record (dir and ws), which the
1171
1183
  // Home window, restart resume and the phone match on.
1172
- const pid = startPty(key, cmd, homeWs ? home : cwd, undefined, changed, {
1184
+ const pid = startPty(key, cmd, targetDir, undefined, changed, {
1173
1185
  env: {
1174
1186
  KAIZEN_TERM: key,
1175
1187
  ...(process.platform === "win32" ? { AGY_CLI_DISABLE_AUTO_UPDATE: "1", CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1", DISABLE_AUTO_UPDATER: "1" } : {}),
@@ -2257,6 +2269,19 @@ export async function web(repoDir: string, opts: Opts = {}) {
2257
2269
  return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
2258
2270
  },
2259
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
+ },
2260
2285
  // As POST /run starts a task, without one on the inbox.
2261
2286
  run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
2262
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.0",
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": {
@@ -5,15 +5,23 @@ import { ArtifactView } from "./artifact-view.tsx";
5
5
 
6
6
  // What the task made: the building state, an empty promise, or the selected result with its outputs rail and
7
7
  // the viewer for the selected output. `working` is the status line shown while the agent builds.
8
+ const VERB: Record<string, string> = { explore: "exploring", plan: "planning", build: "building", review: "reviewing" };
9
+
8
10
  export function ResultView({
9
11
  result,
10
12
  artifactId,
11
13
  working,
14
+ stage,
15
+ alive,
16
+ waiting,
12
17
  onSelect,
13
18
  }: {
14
19
  result?: TaskResult;
15
20
  artifactId?: string;
16
21
  working?: string;
22
+ stage?: string;
23
+ alive?: boolean;
24
+ waiting?: boolean;
17
25
  onSelect: (id: string) => void;
18
26
  }) {
19
27
  if (!result && working)
@@ -23,14 +31,16 @@ export function ResultView({
23
31
  className="grid min-h-60 place-content-center justify-items-center gap-1.5 p-5 text-center text-muted-foreground"
24
32
  >
25
33
  <Spinner className="mb-1.5" />
26
- <h3 className="font-semibold text-foreground">The agent is building</h3>
34
+ <h3 className="font-semibold text-foreground">{alive === false ? "The agent is not running" : `The agent is ${VERB[stage ?? ""] ?? "working"}`}</h3>
27
35
  <p className="line-clamp-3 max-w-[52ch]">{working}</p>
28
36
  </div>
29
37
  );
30
38
  if (!result)
31
39
  return (
32
40
  <div className="grid min-h-60 place-content-center p-5 text-center text-muted-foreground">
33
- <h3 className="mb-2 font-semibold text-foreground">Your result will appear here</h3>
41
+ <h3 className="mb-2 font-semibold text-foreground">
42
+ {waiting ? "Waiting for you" : "Your result will appear here"}
43
+ </h3>
34
44
  <p>Answer any questions in the conversation. You approve a short plan before the build starts.</p>
35
45
  </div>
36
46
  );
@@ -1,4 +1,4 @@
1
- /* kaizen annotator page script 89ee1824202278a1 -- generated by bun run build:web from web/annotate/annotate.ts; do not edit */
1
+ /* kaizen annotator page script df179b2b6cc14e38 -- generated by bun run build:web from web/annotate/annotate.ts; do not edit */
2
2
  (()=>{var Z=(o)=>o.length<24&&!/\d{3,}|^css-|^_|^sc-|^jsx-/.test(o),dt=(o)=>{let i=Math.min(...o.map((f)=>f.left)),d=Math.min(...o.map((f)=>f.top)),u=Math.max(...o.map((f)=>f.right)),b=Math.max(...o.map((f)=>f.bottom));return{left:i,top:d,right:u,bottom:b,width:u-i,height:b-d}},tt=(o)=>{let i=Math.min(o.x0,o.x1),d=Math.min(o.y0,o.y1),u=Math.abs(o.x1-o.x0),b=Math.abs(o.y1-o.y0);return{left:i,top:d,width:u,height:b,right:i+u,bottom:d+b}},pt=(o)=>o.width>=8&&o.height>=8,ut=(o,i)=>o.width>=4&&o.height>=4&&o.left>=i.left-1&&o.top>=i.top-1&&o.right<=i.right+1&&o.bottom<=i.bottom+1,mt=20,ft=(o,i)=>{let d=o.replace(/\s+/g," ").trim();return d?`"${d.slice(0,60)}${d.length>60?"…":""}"`:i},gt=(o,i)=>`area ${Math.round(o.width)}x${Math.round(o.height)} (${i} elements)`,ht=(o,i,d)=>({left:Math.max(8,Math.min(i-316,o.left)),top:o.bottom+330<d?Math.min(o.bottom+8,d-200):Math.max(8,o.top-190)}),xt=(o,i)=>({left:Math.min(i-12,o.left+o.width),top:Math.max(12,o.top)}),bt=(o,i,d)=>({left:Math.max(8,Math.min(i-268,o.left)),top:Math.min(o.top+o.height+8,d-90)}),yt=(o,i,d,u)=>({kind:o.kind,comment:d.comment,intent:d.intent,severity:d.severity,selector:i.selector,items:o.count>1?i.items:[],path:i.path,text:i.text.slice(0,200),tag:i.tag,url:i.url,box:`${Math.round(o.rect.left+u.x)},${Math.round(o.rect.top+u.y)} ${Math.round(o.rect.width)}x${Math.round(o.rect.height)}`,pb:{x:o.rect.left+u.x,y:o.rect.top+u.y,w:o.rect.width,h:o.rect.height},page:i.page,attrs:i.attrs,styles:i.styles,nearby:i.nearby,selected:o.selected||"",source:i.source,components:i.components});var wt=1500,kt=1300000,et=(o)=>o.width>2400||o.height>2400,vt=(o,i)=>{if(o.width<2||o.height<2||et(o))return null;let d=Math.ceil(o.width),u=Math.ceil(o.height),b=Math.max(0,i.left-o.left),f=Math.max(0,i.top-o.top),l=Math.min(d-b,i.width),C=Math.min(u-f,i.height);return l<2||C<2?null:{w:d,h:u,sx:b,sy:f,sw:l,sh:C}},Et=(o,i,d)=>{let u=[];for(let b=Math.min(2,d||1);b>=0.5;b-=0.5)u.push(Math.min(b,1600/Math.max(o,i)));return u};(()=>{let o=window,i=window.parent!==window||o.__kzHost===!0;if(o.__kzAnnotate||!i)return;o.__kzAnnotate=!0;let d=document.currentScript,u=typeof o.__kzAnnToken==="string"?o.__kzAnnToken:"";if(!u)try{u=new URL(d.src).searchParams.get("t")||""}catch{}let b=window.parent,f=(e)=>b.postMessage({kz:1,t:u,out:1,...e},"*"),l={on:!1,mode:"element",hide:!1,block:!0,color:"#3c82f7",components:!0},C=[],g=null,y=[],E=null,U=!1,j=[],I=[],F=[],nt=window.requestAnimationFrame.bind(window);window.requestAnimationFrame=(e)=>U?(F.push(e),F.length):nt(e);let H=document.createElement("style");H.textContent="*,*::before,*::after{animation-play-state:paused!important;transition:none!important}";function At(e){if(e===U)return;if(U=e,e){document.documentElement.append(H);try{j=document.getAnimations().filter((t)=>t.playState==="running"),j.forEach((t)=>t.pause())}catch{}I=[...document.querySelectorAll("video,audio")].filter((t)=>!t.paused),I.forEach((t)=>t.pause())}else H.remove(),j.forEach((t)=>{try{t.play()}catch{}}),I.forEach((t)=>t.play().catch(()=>{})),j=[],I=[],F.splice(0).forEach((t)=>nt(t))}let z=(e)=>window.CSS&&CSS.escape?CSS.escape(e):e.replace(/[^\w-]/g,"\\$&"),D=(e)=>{try{return document.querySelectorAll(e).length===1}catch{return!1}};function ot(e){if(e.id&&D("#"+z(e.id)))return"#"+z(e.id);let t=e.getAttribute("data-testid");if(t&&D(`[data-testid="${t.replace(/"/g,"\\\"")}"]`))return`[data-testid="${t.replace(/"/g,"\\\"")}"]`;let n=[];for(let r=e;r&&r.nodeType===1&&r!==document.documentElement;r=r.parentElement){let s=r.tagName.toLowerCase();if(r.id){if(n.unshift("#"+z(r.id)),D(n.join(" > ")))break;n.shift()}let c=[...r.classList].filter(Z).slice(0,2);if(c.length)s+=c.map((w)=>"."+z(w)).join("");let p=r.parentElement?[...r.parentElement.children].filter((w)=>w.tagName===r.tagName):[];if(p.length>1&&!(c.length&&r.parentElement.querySelectorAll(":scope > "+s).length===1))s+=`:nth-of-type(${p.indexOf(r)+1})`;if(n.unshift(s),D(n.join(" > ")))break}return n.join(" > ")}let Ct=(e)=>{let t=[];for(let n=e;n&&n.nodeType===1;n=n.parentElement)t.unshift(n.tagName.toLowerCase()+(n.id?"#"+n.id:""));return t.join(" > ")},K=(e)=>e.tagName.toLowerCase()+(e.id?"#"+e.id:"")+[...e.classList].filter(Z).slice(0,2).map((t)=>"."+t).join(""),Y=(e)=>(e.innerText||e.textContent||e.getAttribute("aria-label")||e.getAttribute("alt")||"").replace(/\s+/g," ").trim(),_t=["id","class","role","aria-label","href","type","name","placeholder","alt","data-testid"],St=(e)=>_t.filter((t)=>e.hasAttribute(t)).map((t)=>`${t}="${e.getAttribute(t).slice(0,80)}"`).join(" "),Rt=["color","background-color","font-family","font-size","font-weight","line-height","padding","margin","display","position","border-radius","width","height"],Mt=(e)=>{let t=getComputedStyle(e);return Rt.map((n)=>`${n}: ${t.getPropertyValue(n)}`).join("; ")};function $t(e){let t="",n=[];for(let r=e,s=0;r&&r.nodeType===1&&s<14;r=r.parentElement,s++){let c=r.getAttribute("data-astro-source-file");if(c&&!t)t=c+(r.getAttribute("data-astro-source-loc")?":"+r.getAttribute("data-astro-source-loc").replace(/:/,":"):"");let p=r.__svelte_meta&&r.__svelte_meta.loc;if(p&&!t)t=`${p.file}:${p.line}`;let w=r.__vueParentComponent;for(let a=w,v=0;a&&v<6;a=a.parent,v++){let m=a.type&&(a.type.name||a.type.__name);if(m&&!n.includes(m))n.push(m);if(a.type&&a.type.__file&&!t)t=a.type.__file}if(r.__vue__&&r.__vue__.$options){let a=r.__vue__.$options;if(a.name&&!n.includes(a.name))n.push(a.name);if(a.__file&&!t)t=a.__file}let P=Object.keys(r).find((a)=>a.startsWith("__reactFiber$"));if(P)for(let a=r[P],v=0;a&&v<40;a=a.return,v++){if(a._debugSource&&!t)t=`${a._debugSource.fileName}:${a._debugSource.lineNumber}`;let m=a.type;if(typeof m==="function"||m&&typeof m==="object"){let S=m.displayName||m.name||m.render&&m.render.name||"";if(S&&!n.includes(S)&&n.length<8)n.push(S)}}if(t&&n.length)break}return{source:t,components:n.reverse().join(" > ")}}let M=document.createElement("div");M.style.cssText="all:initial;position:fixed;inset:0;z-index:2147483647;pointer-events:none";let Tt=M.attachShadow({mode:"closed"}),rt=document.createElement("style");rt.textContent=`
3
3
  *{box-sizing:border-box;font:12px/1.4 system-ui,sans-serif}
4
4
  .b{position:fixed;pointer-events:none;border:2px solid var(--c);background:color-mix(in srgb,var(--c) 14%,transparent);border-radius:2px}