kaizen-agent 1.51.0 → 1.52.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/chat.test.ts +241 -0
- package/cli/chat.ts +279 -0
- package/cli/state.ts +1 -1
- package/cli/web.ts +85 -24
- package/package.json +1 -1
- package/web/board/api.ts +2 -0
- package/web/board/home.ts +399 -0
- package/web/board/live.ts +13 -5
- package/web/board/projects.ts +1 -1
- package/web/board/views.ts +14 -8
- package/web/board.html +64 -4
- package/web/board.js +37 -34
- package/web/notebook.js +1 -1
- package/web/notes.html +7 -4
- package/web/term.js +1 -1
- package/web/video.html +7 -4
- package/web/video.js +1 -1
package/cli/chat.test.ts
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// Home's chat: a fake `codex` on PATH stands in for the agent, prints the JSONL that
|
|
2
|
+
// `codex exec --json` prints, and records the argv, working folder and stdin it was given.
|
|
3
|
+
import { test, expect, beforeEach, afterEach } from "bun:test";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, chmodSync } from "node:fs";
|
|
5
|
+
import { join, delimiter } from "node:path";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { sendChat, readChat, listChats, deleteChat, stopChat, parseLine, takeMoves, type Event, type Board, type Upload } from "./chat.ts";
|
|
8
|
+
|
|
9
|
+
let root = "", base = "", bin = "", projA = "", projD = "", board: Board, created: string[] = [];
|
|
10
|
+
const PATH = process.env.PATH;
|
|
11
|
+
const posix = process.platform !== "win32";
|
|
12
|
+
|
|
13
|
+
function fake(body: string) {
|
|
14
|
+
writeFileSync(join(bin, "codex"), `#!/bin/sh\nprintf '%s\\n' "$@" > "${bin}/argv"\npwd > "${bin}/cwd"\ncat > "${bin}/stdin"\n${body}\n`);
|
|
15
|
+
chmodSync(join(bin, "codex"), 0o755);
|
|
16
|
+
}
|
|
17
|
+
const say = (text: string) => `cat <<'J'
|
|
18
|
+
{"type":"thread.started","thread_id":"T1"}
|
|
19
|
+
{"type":"turn.started"}
|
|
20
|
+
{"type":"item.started","item":{"id":"i0","type":"command_execution","command":"/usr/bin/zsh -lc ls"}}
|
|
21
|
+
{"type":"item.completed","item":{"id":"i0","type":"command_execution","command":"/usr/bin/zsh -lc ls","exit_code":0,"status":"completed"}}
|
|
22
|
+
{"type":"item.started","item":{"id":"i1","type":"agent_message"}}
|
|
23
|
+
{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":${JSON.stringify(text)}}}
|
|
24
|
+
{"type":"turn.completed"}
|
|
25
|
+
J`;
|
|
26
|
+
const argv = () => readFileSync(join(bin, "argv"), "utf8").trim().split("\n");
|
|
27
|
+
|
|
28
|
+
function turn(id: string | null, text: string, project: string | null = null, uploads: Upload[] = []) {
|
|
29
|
+
const events: Event[] = [];
|
|
30
|
+
return new Promise<{ events: Event[]; why: string | null; id: string }>((res) => {
|
|
31
|
+
const why = sendChat(base, id, text, project, board, (e) => {
|
|
32
|
+
events.push(e);
|
|
33
|
+
if (e.t === "done") res({ events, why: null, id: (events[0] as any).id });
|
|
34
|
+
}, false, uploads);
|
|
35
|
+
if (why) res({ events, why, id: "" });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
root = mkdtempSync(join(tmpdir(), "kaizen-chat-"));
|
|
41
|
+
base = join(root, "home", ".kaizen");
|
|
42
|
+
projA = join(root, "A", ".kaizen");
|
|
43
|
+
projD = join(root, "D", ".kaizen");
|
|
44
|
+
for (const d of [base, projA, projD]) mkdirSync(d, { recursive: true });
|
|
45
|
+
bin = join(root, "bin");
|
|
46
|
+
mkdirSync(bin);
|
|
47
|
+
process.env.PATH = bin + delimiter + PATH;
|
|
48
|
+
created = [];
|
|
49
|
+
board = {
|
|
50
|
+
projects: [{ dir: projA, label: "A" }, { dir: projD, label: "D" }],
|
|
51
|
+
create: async (name) => {
|
|
52
|
+
if (name.includes("/")) return { error: "bad name" };
|
|
53
|
+
const d = join(root, name, ".kaizen");
|
|
54
|
+
mkdirSync(d, { recursive: true });
|
|
55
|
+
created.push(d);
|
|
56
|
+
return { dir: d };
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
afterEach(() => { process.env.PATH = PATH; });
|
|
61
|
+
|
|
62
|
+
test.if(posix)("a message streams the reply, saves both sides, runs in the chat's project, and resumes its thread", async () => {
|
|
63
|
+
fake(say("Hi."));
|
|
64
|
+
const { events, why, id } = await turn(null, "say hi", projA);
|
|
65
|
+
expect(why).toBeNull();
|
|
66
|
+
expect(events.map((e) => e.t)).toEqual(["chat", "status", "status", "step", "status", "text", "done"]);
|
|
67
|
+
expect((events[2] as any).text).toBe("Running ls");
|
|
68
|
+
expect((events[3] as any).step).toEqual({ kind: "cmd", text: "ls", ok: true });
|
|
69
|
+
const c = readChat(base, id)!;
|
|
70
|
+
expect(c).toMatchObject({ thread: "T1", project: projA });
|
|
71
|
+
expect(c.messages.map((m) => [m.role, m.text])).toEqual([["user", "say hi"], ["agent", "Hi."]]);
|
|
72
|
+
expect(c.messages[1].activity).toBeUndefined();
|
|
73
|
+
expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(root, "A"));
|
|
74
|
+
const stdin = readFileSync(join(bin, "stdin"), "utf8");
|
|
75
|
+
expect(stdin).toContain(`Project of this chat: A (${join(root, "A")})`);
|
|
76
|
+
expect(stdin).toContain(`- D — ${join(root, "D")}`);
|
|
77
|
+
expect(stdin.endsWith("say hi")).toBe(true);
|
|
78
|
+
expect(argv()).toContain("workspace-write");
|
|
79
|
+
expect(argv().slice(5, 9)).toEqual(["-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium"]);
|
|
80
|
+
expect(argv()).not.toContain("resume");
|
|
81
|
+
expect(listChats(base).map((x) => [x.id, x.project])).toEqual([[id, projA]]);
|
|
82
|
+
|
|
83
|
+
fake(say("Again."));
|
|
84
|
+
await turn(id, "again");
|
|
85
|
+
expect(argv().slice(5, 9)).toEqual(["-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium"]);
|
|
86
|
+
expect(argv().slice(-3)).toEqual(["resume", "T1", "-"]);
|
|
87
|
+
expect(readChat(base, id)!.messages).toHaveLength(4);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test.if(posix)("no project: a read-only scratch folder outside every project", async () => {
|
|
91
|
+
fake(say("Which project?"));
|
|
92
|
+
const { id } = await turn(null, "hello");
|
|
93
|
+
expect(readChat(base, id)!.project).toBeUndefined();
|
|
94
|
+
expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(base, "chats", "scratch"));
|
|
95
|
+
expect(argv()).toContain("read-only");
|
|
96
|
+
expect(readFileSync(join(bin, "stdin"), "utf8")).toContain("Project of this chat: none");
|
|
97
|
+
// A project the page names that the board does not list is not taken.
|
|
98
|
+
const r = await turn(null, "hi", join(root, "elsewhere", ".kaizen"));
|
|
99
|
+
expect(readChat(base, r.id)!.project).toBeUndefined();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test.if(posix)("uploaded images reach Codex and other files remain readable after reload", async () => {
|
|
103
|
+
fake(say("I can see both files."));
|
|
104
|
+
const image = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]);
|
|
105
|
+
const { id } = await turn(null, "", projA, [
|
|
106
|
+
{ name: "../reference.png", bytes: image },
|
|
107
|
+
{ name: "brief.txt", bytes: new TextEncoder().encode("hello") },
|
|
108
|
+
]);
|
|
109
|
+
const c = readChat(base, id)!;
|
|
110
|
+
expect(c.title).toBe("../reference.png");
|
|
111
|
+
expect(c.messages[0].files?.map((f) => [f.name, f.image])).toEqual([["_reference.png", true], ["brief.txt", false]]);
|
|
112
|
+
for (const f of c.messages[0].files!) expect(existsSync(f.path)).toBe(true);
|
|
113
|
+
expect(argv()).toContain("-i");
|
|
114
|
+
expect(argv()[argv().indexOf("-i") + 1]).toBe(c.messages[0].files![0].path);
|
|
115
|
+
expect(readFileSync(join(bin, "stdin"), "utf8")).toContain(c.messages[0].files![1].path);
|
|
116
|
+
fake(say("Again."));
|
|
117
|
+
await turn(id, "check this too", null, [{ name: "more.png", bytes: image }]);
|
|
118
|
+
expect(argv().slice(-5)).toEqual(["resume", "T1", "-i", readChat(base, id)!.messages[2].files![0].path, "-"]);
|
|
119
|
+
expect(deleteChat(base, id)).toBeNull();
|
|
120
|
+
expect(existsSync(c.messages[0].files![0].path)).toBe(false);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test.if(posix)("the agent switches the chat to a listed project; the move line is not shown and the next turn runs there", async () => {
|
|
124
|
+
fake(say(`Switching to D.\n[[kaizen:project ${join(root, "D")}]]`));
|
|
125
|
+
const { events, id } = await turn(null, "let's work on D", projA);
|
|
126
|
+
expect(events.filter((e) => e.t === "text")).toEqual([{ t: "text", text: "Switching to D." }]);
|
|
127
|
+
expect(events.find((e) => e.t === "project")).toEqual({ t: "project", dir: projD });
|
|
128
|
+
expect(readChat(base, id)!.project).toBe(projD);
|
|
129
|
+
expect(readChat(base, id)!.messages[1].steps!.at(-1)).toEqual({ kind: "project", text: "Switched to D", ok: true });
|
|
130
|
+
fake(say("Here."));
|
|
131
|
+
await turn(id, "go on");
|
|
132
|
+
expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(root, "D"));
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test.if(posix)("a switched chat can continue the pending request in the same reply", async () => {
|
|
136
|
+
fake(say("Switching.\n[[kaizen:project D]]"));
|
|
137
|
+
const { id } = await turn(null, "check the latest build in D", projA);
|
|
138
|
+
fake(say("The latest build changed the shop."));
|
|
139
|
+
await new Promise<void>((res) => sendChat(base, id, "Continue the pending request.", null, board, (e) => {
|
|
140
|
+
if (e.t === "done") res();
|
|
141
|
+
}, true));
|
|
142
|
+
const c = readChat(base, id)!;
|
|
143
|
+
expect(c.messages).toHaveLength(2);
|
|
144
|
+
expect(c.messages[1].text).toBe("Switching.\n\nThe latest build changed the shop.");
|
|
145
|
+
expect(c.messages[1].activity).toBeUndefined();
|
|
146
|
+
expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(root, "D"));
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test.if(posix)("a switch to a path the board does not list is refused and the chat stays", async () => {
|
|
150
|
+
fake(say("[[kaizen:project /etc]]"));
|
|
151
|
+
const { events, id } = await turn(null, "go to etc", projA);
|
|
152
|
+
expect(events.some((e) => e.t === "project")).toBe(false);
|
|
153
|
+
expect(readChat(base, id)!.project).toBe(projA);
|
|
154
|
+
expect(readChat(base, id)!.messages[1].steps!.at(-1)).toMatchObject({ kind: "project", ok: false });
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test.if(posix)("the agent creates a new project through the board's rules and moves there", async () => {
|
|
158
|
+
fake(say("Creating it.\n[[kaizen:new-project Shop]]"));
|
|
159
|
+
const { events, id } = await turn(null, "start a shop app");
|
|
160
|
+
const d = join(root, "Shop", ".kaizen");
|
|
161
|
+
expect(created).toEqual([d]);
|
|
162
|
+
expect(events.find((e) => e.t === "project")).toEqual({ t: "project", dir: d });
|
|
163
|
+
expect(readChat(base, id)!.project).toBe(d);
|
|
164
|
+
fake(say("[[kaizen:new-project ../x]]"));
|
|
165
|
+
const r = await turn(null, "bad");
|
|
166
|
+
expect(readChat(base, r.id)!.messages[1].steps!.at(-1)).toMatchObject({ kind: "project", ok: false });
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test("chat ids that could leave chats/ are refused before any disk access", () => {
|
|
170
|
+
for (const bad of ["../x", "a/b", "..", "", "x".repeat(81)]) {
|
|
171
|
+
expect(readChat(base, bad)).toBeNull();
|
|
172
|
+
expect(deleteChat(base, bad)).toBe("bad chat id");
|
|
173
|
+
}
|
|
174
|
+
expect(existsSync(join(base, "chats"))).toBe(false);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test.if(posix)("too many attachments are refused before a chat is created", async () => {
|
|
178
|
+
fake(say("should not run"));
|
|
179
|
+
const { why } = await turn(null, "files", projA, Array.from({ length: 6 }, (_, i) => ({ name: `${i}.txt`, bytes: new Uint8Array([i]) })));
|
|
180
|
+
expect(why).toMatch(/up to 5 files/);
|
|
181
|
+
expect(listChats(base)).toEqual([]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test.if(posix)("stop kills the agent and keeps what was said so far", async () => {
|
|
185
|
+
fake(`echo '{"type":"thread.started","thread_id":"T2"}'\necho '{"type":"item.started","item":{"type":"command_execution","command":"/bin/sh -lc ls"}}'\necho '{"type":"item.completed","item":{"type":"agent_message","text":"Working"}}'\nsleep 30`);
|
|
186
|
+
const events: Event[] = [];
|
|
187
|
+
await new Promise<void>((res) => sendChat(base, null, "long job", projA, board, (e) => {
|
|
188
|
+
events.push(e);
|
|
189
|
+
if (e.t === "status") expect(readChat(base, (events[0] as any).id)!.messages[1].activity).toBe("Running ls");
|
|
190
|
+
if (e.t === "text") stopChat(base, (events[0] as any).id);
|
|
191
|
+
if (e.t === "done") res();
|
|
192
|
+
}));
|
|
193
|
+
const c = readChat(base, (events[0] as any).id)!;
|
|
194
|
+
expect(c.messages[1]).toMatchObject({ role: "agent", text: "Working", error: "Stopped." });
|
|
195
|
+
expect(c.messages[1].activity).toBeUndefined();
|
|
196
|
+
expect(listChats(base)[0].busy).toBe(false);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
test.if(posix)("a turn persists activity and finishes independently of the page", async () => {
|
|
200
|
+
fake(`echo '{"type":"item.started","item":{"type":"command_execution","command":"/bin/sh -lc build"}}'\nsleep 0.05\necho '{"type":"item.completed","item":{"type":"agent_message","text":"Built."}}'`);
|
|
201
|
+
let id = "";
|
|
202
|
+
await new Promise<void>((res) => sendChat(base, null, "build", projA, board, (e) => {
|
|
203
|
+
if (e.t === "chat") id = e.id;
|
|
204
|
+
if (e.t === "status") expect(readChat(base, id)!.messages.at(-1)?.activity).toBe("Running build");
|
|
205
|
+
if (e.t === "done") res();
|
|
206
|
+
}));
|
|
207
|
+
expect(readChat(base, id)!.messages.at(-1)).toMatchObject({ text: "Built." });
|
|
208
|
+
expect(readChat(base, id)!.messages.at(-1)?.activity).toBeUndefined();
|
|
209
|
+
expect(listChats(base)[0].busy).toBe(false);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test.if(posix)("a failed turn reports the agent's error", async () => {
|
|
213
|
+
fake(`echo '{"type":"turn.failed","error":{"message":"model not supported"}}'; exit 1`);
|
|
214
|
+
const { events } = await turn(null, "x");
|
|
215
|
+
expect(events.find((e) => e.t === "error")).toEqual({ t: "error", error: "model not supported" });
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("no codex on PATH: a message says how to get it", async () => {
|
|
219
|
+
process.env.PATH = bin;
|
|
220
|
+
const { why } = await turn(null, "hi");
|
|
221
|
+
expect(why).toMatch(/needs Codex/);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
test("parseLine and takeMoves", () => {
|
|
225
|
+
expect(parseLine("not json")).toBeNull();
|
|
226
|
+
expect(parseLine(`{"type":"turn.started"}`)).toEqual({ t: "status", text: "Thinking…" });
|
|
227
|
+
expect(parseLine(`{"type":"item.started","item":{"type":"mcp_tool_call","server":"docs","tool":"search"}}`))
|
|
228
|
+
.toEqual({ t: "status", text: "Using docs search" });
|
|
229
|
+
expect(parseLine(`{"type":"item.started","item":{"type":"web_search"}}`))
|
|
230
|
+
.toEqual({ t: "status", text: "Searching the web…" });
|
|
231
|
+
expect(parseLine(`{"type":"item.completed","item":{"type":"web_search","status":"completed"}}`))
|
|
232
|
+
.toEqual({ t: "step", step: { kind: "tool", text: "Web search", ok: true } });
|
|
233
|
+
expect(parseLine(`{"type":"item.completed","item":{"type":"error","message":"metadata"}}`)).toBeNull();
|
|
234
|
+
expect(parseLine(JSON.stringify({ type: "item.completed", item: { type: "command_execution", command: `/bin/bash -lc "cat a.md"`, exit_code: 1 } })))
|
|
235
|
+
.toEqual({ t: "step", step: { kind: "cmd", text: "cat a.md", ok: false } });
|
|
236
|
+
expect(parseLine(`{"type":"item.completed","item":{"type":"file_change","changes":[{"path":"a.ts"}],"status":"completed"}}`))
|
|
237
|
+
.toEqual({ t: "step", step: { kind: "edit", text: "a.ts", ok: true } });
|
|
238
|
+
expect(takeMoves("ok\n\n[[kaizen:project A]]\n")).toEqual({ text: "ok", move: { op: "project", arg: "A" } });
|
|
239
|
+
// Only a line of its own counts: a move quoted inside a sentence is text.
|
|
240
|
+
expect(takeMoves("write `[[kaizen:project A]]` to move").move).toBeNull();
|
|
241
|
+
});
|
package/cli/chat.ts
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// Home's chat: conversations with kaizen's main agent, kept under ~/.kaizen/chats/<id>.json.
|
|
2
|
+
// A chat may be in a project (its .kaizen dir) or in none; the agent can move it to another
|
|
3
|
+
// project or make a new one. The agent is Codex, run headless per message (`codex exec
|
|
4
|
+
// --json`), and a follow-up continues its thread with `exec resume`.
|
|
5
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { basename, dirname, join } from "node:path";
|
|
8
|
+
import { CHILD_ENV, readText } from "./state.ts";
|
|
9
|
+
|
|
10
|
+
export type Step = { kind: "cmd" | "edit" | "tool" | "project"; text: string; ok?: boolean };
|
|
11
|
+
export type Attachment = { name: string; path: string; image: boolean };
|
|
12
|
+
export type Upload = { name: string; bytes: Uint8Array };
|
|
13
|
+
export type Msg = { role: "user" | "agent"; text: string; files?: Attachment[]; steps?: Step[]; error?: string; activity?: string; at: string };
|
|
14
|
+
export type Chat = { id: string; title: string; project?: string; thread?: string; created: string; updated: string; messages: Msg[] };
|
|
15
|
+
// What the page is streamed while a turn runs, one JSON object per line.
|
|
16
|
+
export type Event =
|
|
17
|
+
| { t: "chat"; id: string }
|
|
18
|
+
| { t: "text"; text: string }
|
|
19
|
+
| { t: "status"; text: string }
|
|
20
|
+
| { t: "step"; step: Step }
|
|
21
|
+
| { t: "project"; dir: string | null }
|
|
22
|
+
| { t: "error"; error: string }
|
|
23
|
+
| { t: "done" };
|
|
24
|
+
// What the board knows, handed in by the server: its projects (state dirs) and how it makes one.
|
|
25
|
+
export type Board = {
|
|
26
|
+
projects: { dir: string; label: string }[];
|
|
27
|
+
create: (name: string) => Promise<{ dir: string } | { error: string }>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const okId = (id: unknown): id is string => typeof id === "string" && /^[\w-]{1,80}$/.test(id);
|
|
31
|
+
const file = (base: string, id: string) => join(base, "chats", `${id}.json`);
|
|
32
|
+
const uploadDir = (base: string, id: string) => join(base, "chats", id, "attachments");
|
|
33
|
+
const imageFile = (b: Uint8Array) =>
|
|
34
|
+
(b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) ||
|
|
35
|
+
(b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) ||
|
|
36
|
+
(b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) ||
|
|
37
|
+
(b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && String.fromCharCode(...b.slice(8, 12)) === "WEBP");
|
|
38
|
+
|
|
39
|
+
function saveUploads(base: string, id: string, uploads: Upload[]): Attachment[] {
|
|
40
|
+
const dir = uploadDir(base, id);
|
|
41
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
42
|
+
const paths: string[] = [];
|
|
43
|
+
try {
|
|
44
|
+
return uploads.map((u) => {
|
|
45
|
+
const name = u.name.replace(/[^\w.-]+/g, "_").replace(/^\.+/, "").slice(0, 100) || "file";
|
|
46
|
+
const path = join(dir, `${randomUUID()}-${name}`);
|
|
47
|
+
paths.push(path);
|
|
48
|
+
writeFileSync(path, u.bytes, { mode: 0o600 });
|
|
49
|
+
return { name, path, image: imageFile(u.bytes) };
|
|
50
|
+
});
|
|
51
|
+
} catch (err) {
|
|
52
|
+
for (const path of paths) rmSync(path, { force: true });
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Ahead of every message, so a switch or a new project is known on the next turn; the page never shows it.
|
|
58
|
+
export function brief(c: Chat, board: Board) {
|
|
59
|
+
const here = board.projects.find((p) => p.dir === c.project);
|
|
60
|
+
const list = board.projects.slice(0, 80).map((p) => `- ${p.label} — ${dirname(p.dir)}`).join("\n");
|
|
61
|
+
return `[kaizen board context, not written by the user]
|
|
62
|
+
You are kaizen's main agent, talking with the user from the kaizen board's Home page.
|
|
63
|
+
Project of this chat: ${here ? `${here.label} (${dirname(here.dir)})` : "none — you are in a scratch folder and cannot edit files"}.
|
|
64
|
+
Projects on the board:
|
|
65
|
+
${list || "(none)"}
|
|
66
|
+
You can move this chat. On a line of its own write [[kaizen:project <folder>]] to switch to a project listed above, or [[kaizen:new-project <name>]] to create one (a plain folder name). Do it when the user asks. When they talk about another listed project, ask whether to switch; 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. Do not touch files outside your working folder.
|
|
67
|
+
kaizen is installed: for work worth a plan and an independent review, start a run with /kaizen <request> (the kaizen skill); it shows on the board. Small things you may do directly. Keep replies short.
|
|
68
|
+
[end of context]
|
|
69
|
+
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function readChat(base: string, id: string): Chat | null {
|
|
74
|
+
if (!okId(id)) return null;
|
|
75
|
+
try { return JSON.parse(readText(file(base, id))); } catch { return null; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function save(base: string, c: Chat) {
|
|
79
|
+
mkdirSync(join(base, "chats"), { recursive: true });
|
|
80
|
+
writeFileSync(file(base, c.id), JSON.stringify(c, null, 2));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Newest first, without the messages.
|
|
84
|
+
export function listChats(base: string) {
|
|
85
|
+
const d = join(base, "chats");
|
|
86
|
+
if (!existsSync(d)) return [];
|
|
87
|
+
return readdirSync(d).filter((f) => f.endsWith(".json"))
|
|
88
|
+
.map((f) => readChat(base, f.slice(0, -5)))
|
|
89
|
+
.filter((c): c is Chat => !!c)
|
|
90
|
+
.map(({ id, title, project, updated }) => ({ id, title, project: project ?? null, updated, busy: live.has(base + "|" + id) }))
|
|
91
|
+
.sort((a, b) => b.updated.localeCompare(a.updated));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function deleteChat(base: string, id: string) {
|
|
95
|
+
if (!okId(id)) return "bad chat id";
|
|
96
|
+
if (live.has(base + "|" + id)) return "this chat is still working";
|
|
97
|
+
rmSync(file(base, id), { force: true });
|
|
98
|
+
rmSync(join(base, "chats", id), { recursive: true, force: true });
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// One turn at a time per chat; the page can leave and the turn still finishes and saves.
|
|
103
|
+
const live = new Map<string, { kill: () => void }>();
|
|
104
|
+
export const busy = (base: string, id: string) => live.has(base + "|" + id);
|
|
105
|
+
|
|
106
|
+
export function stopChat(base: string, id: string) {
|
|
107
|
+
const p = live.get(base + "|" + id);
|
|
108
|
+
p?.kill();
|
|
109
|
+
return !!p;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const short = (s: string, n = 120) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
|
113
|
+
const command = (s: unknown) => short(String(s ?? "").replace(/^\S*\/(?:ba|z)?sh -lc (?:(['"])([\s\S]*)\1|([\s\S]*))$/, "$2$3"));
|
|
114
|
+
|
|
115
|
+
// One `codex exec --json` line as what the page shows; null for what it does not.
|
|
116
|
+
export function parseLine(line: string): Event | { t: "thread"; id: string } | null {
|
|
117
|
+
let e: any;
|
|
118
|
+
try { e = JSON.parse(line); } catch { return null; }
|
|
119
|
+
if (e?.type === "thread.started" && typeof e.thread_id === "string") return { t: "thread", id: e.thread_id };
|
|
120
|
+
if (e?.type === "turn.failed") return { t: "error", error: String(e.error?.message ?? "the agent failed") };
|
|
121
|
+
if (e?.type === "turn.started") return { t: "status", text: "Thinking…" };
|
|
122
|
+
if (e?.type === "item.started" && e.item) {
|
|
123
|
+
const it = e.item;
|
|
124
|
+
if (it.type === "command_execution") return { t: "status", text: `Running ${command(it.command) || "a command"}` };
|
|
125
|
+
if (it.type === "mcp_tool_call") return { t: "status", text: `Using ${short(`${it.server ?? ""} ${it.tool ?? ""}`.trim()) || "a tool"}` };
|
|
126
|
+
if (it.type === "web_search") return { t: "status", text: "Searching the web…" };
|
|
127
|
+
if (it.type === "file_change") return { t: "status", text: "Editing files…" };
|
|
128
|
+
if (it.type === "reasoning") return { t: "status", text: "Thinking…" };
|
|
129
|
+
if (it.type === "agent_message") return { t: "status", text: "Writing reply…" };
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (e?.type !== "item.completed" || !e.item) return null;
|
|
133
|
+
const it = e.item;
|
|
134
|
+
if (it.type === "agent_message" && it.text) return { t: "text", text: String(it.text) };
|
|
135
|
+
if (it.type === "command_execution")
|
|
136
|
+
return { t: "step", step: { kind: "cmd", text: command(it.command), ok: it.exit_code === 0 } };
|
|
137
|
+
if (it.type === "file_change" && Array.isArray(it.changes))
|
|
138
|
+
return { t: "step", step: { kind: "edit", text: short(it.changes.map((c: any) => c.path).join(", ")), ok: it.status !== "failed" } };
|
|
139
|
+
if (it.type === "mcp_tool_call") return { t: "step", step: { kind: "tool", text: short(`${it.server ?? ""} ${it.tool ?? ""}`.trim()), ok: it.status !== "failed" } };
|
|
140
|
+
if (it.type === "web_search") return { t: "step", step: { kind: "tool", text: "Web search", ok: it.status !== "failed" } };
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The agent's move lines: taken out of what the user reads; the last one counts.
|
|
145
|
+
const MOVE = /^[ \t]*\[\[kaizen:(project|new-project)[ \t]+([^\]\n]+?)\]\][ \t]*$/gm;
|
|
146
|
+
export function takeMoves(text: string) {
|
|
147
|
+
let move: { op: "project" | "new-project"; arg: string } | null = null;
|
|
148
|
+
const rest = text.replace(MOVE, (_, op, arg) => { move = { op, arg: arg.trim() }; return ""; }).replace(/\n{3,}/g, "\n\n").trim();
|
|
149
|
+
return { text: rest, move: move as { op: "project" | "new-project"; arg: string } | null };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Not winShim: the message goes in on stdin, so the .cmd shim's newline limit never applies.
|
|
153
|
+
const codexBin = () => Bun.which("codex", { PATH: process.env.PATH });
|
|
154
|
+
|
|
155
|
+
// project: where a new chat starts (a state dir the board knows), ignored for an existing chat.
|
|
156
|
+
export function sendChat(base: string, id: string | null, text: string, project: string | null, board: Board, emit: (e: Event) => void, reuseReply = false, uploads: Upload[] = []): string | null {
|
|
157
|
+
const bin = codexBin();
|
|
158
|
+
if (!bin) return "Chat needs Codex: install it (npm i -g @openai/codex) and sign in.";
|
|
159
|
+
const now = new Date().toISOString();
|
|
160
|
+
let c = id ? readChat(base, id) : null;
|
|
161
|
+
if (id && !c) return "no such chat";
|
|
162
|
+
if (!c) c = {
|
|
163
|
+
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, title: short(text.split("\n")[0] || uploads[0]?.name || "Chat", 60),
|
|
164
|
+
project: board.projects.some((p) => p.dir === project) ? project! : undefined, created: now, updated: now, messages: [],
|
|
165
|
+
};
|
|
166
|
+
const key = base + "|" + c.id;
|
|
167
|
+
if (live.has(key)) return "this chat is still working";
|
|
168
|
+
const chat = c;
|
|
169
|
+
if (reuseReply && chat.messages.at(-1)?.role !== "agent") return "no reply to continue";
|
|
170
|
+
if (uploads.length > 5 || uploads.some((u) => !u.name || u.bytes.length > 10 * 1024 * 1024) || uploads.reduce((n, u) => n + u.bytes.length, 0) > 20 * 1024 * 1024) return "up to 5 files, 10 MB each and 20 MB total";
|
|
171
|
+
// A project that left the board since: the chat goes on without one.
|
|
172
|
+
if (chat.project && !board.projects.some((p) => p.dir === chat.project)) chat.project = undefined;
|
|
173
|
+
let files: Attachment[] = [];
|
|
174
|
+
try { if (uploads.length) files = saveUploads(base, chat.id, uploads); }
|
|
175
|
+
catch (err: any) { return `Could not save attachment: ${err?.message ?? err}`; }
|
|
176
|
+
if (!reuseReply) chat.messages.push({ role: "user", text, ...(files.length ? { files } : {}), at: now });
|
|
177
|
+
const reply: Msg = reuseReply ? chat.messages.at(-1)! : { role: "agent", text: "", steps: [], at: now };
|
|
178
|
+
if (!reuseReply) chat.messages.push(reply);
|
|
179
|
+
reply.activity = "Thinking…";
|
|
180
|
+
chat.updated = now;
|
|
181
|
+
save(base, chat);
|
|
182
|
+
|
|
183
|
+
// No project: a scratch folder outside every project, read-only.
|
|
184
|
+
const scratch = join(base, "chats", "scratch");
|
|
185
|
+
if (!chat.project) mkdirSync(scratch, { recursive: true });
|
|
186
|
+
const cwd = chat.project ? dirname(chat.project) : scratch;
|
|
187
|
+
// Same scrub as launchRun: a board started inside an agent session must not hand that identity on.
|
|
188
|
+
const env: Record<string, string> = {};
|
|
189
|
+
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !CHILD_ENV.test(k)) env[k] = v;
|
|
190
|
+
const images = files.filter((f) => f.image).flatMap((f) => ["-i", f.path]);
|
|
191
|
+
const argv = [bin, "exec", "--json", "--skip-git-repo-check", "-s", chat.project ? "workspace-write" : "read-only",
|
|
192
|
+
"-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium", ...(chat.thread ? ["resume", chat.thread] : []), ...images, "-"];
|
|
193
|
+
let p;
|
|
194
|
+
try { p = Bun.spawn(argv, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" }); }
|
|
195
|
+
catch (err: any) {
|
|
196
|
+
reply.error = `Could not start codex: ${err?.message ?? err}`;
|
|
197
|
+
delete reply.activity;
|
|
198
|
+
save(base, chat);
|
|
199
|
+
return reply.error;
|
|
200
|
+
}
|
|
201
|
+
p.stdin.write(brief(chat, board) + text + (files.length ? `\n\nAttached files (read these paths as needed):\n${files.map((f) => `- ${f.name}: ${f.path}`).join("\n")}` : ""));
|
|
202
|
+
p.stdin.end();
|
|
203
|
+
// Read alongside stdout: an undrained stderr pipe fills and stalls the agent.
|
|
204
|
+
const errText = new Response(p.stderr).text();
|
|
205
|
+
let stopped = false;
|
|
206
|
+
// Stop also lets go of stdout: a grandchild the agent started can hold the pipe open after it dies.
|
|
207
|
+
const reader = (p.stdout as ReadableStream<Uint8Array>).getReader();
|
|
208
|
+
live.set(key, { kill: () => { stopped = true; p.kill(); reader.cancel().catch(() => {}); } });
|
|
209
|
+
emit({ t: "chat", id: chat.id });
|
|
210
|
+
|
|
211
|
+
(async () => {
|
|
212
|
+
const dec = new TextDecoder();
|
|
213
|
+
let buf = "";
|
|
214
|
+
let move: ReturnType<typeof takeMoves>["move"] = null;
|
|
215
|
+
const take = (line: string) => {
|
|
216
|
+
const e = parseLine(line);
|
|
217
|
+
if (!e) return;
|
|
218
|
+
if (e.t === "thread") { chat.thread = e.id; save(base, chat); return; }
|
|
219
|
+
if (e.t === "text") {
|
|
220
|
+
const m = takeMoves(e.text);
|
|
221
|
+
if (m.move) move = m.move;
|
|
222
|
+
if (!m.text) return;
|
|
223
|
+
e.text = m.text;
|
|
224
|
+
reply.text += (reply.text ? "\n\n" : "") + e.text;
|
|
225
|
+
}
|
|
226
|
+
if (e.t === "step") reply.steps!.push(e.step);
|
|
227
|
+
if (e.t === "status") reply.activity = e.text;
|
|
228
|
+
if (e.t === "step") reply.activity = "Thinking…";
|
|
229
|
+
if (e.t === "error") reply.error = e.error;
|
|
230
|
+
save(base, chat);
|
|
231
|
+
emit(e);
|
|
232
|
+
};
|
|
233
|
+
try {
|
|
234
|
+
for (let r; !(r = await reader.read()).done;) {
|
|
235
|
+
buf += dec.decode(r.value, { stream: true });
|
|
236
|
+
let i;
|
|
237
|
+
while ((i = buf.indexOf("\n")) >= 0) { take(buf.slice(0, i)); buf = buf.slice(i + 1); }
|
|
238
|
+
}
|
|
239
|
+
if (buf.trim()) take(buf);
|
|
240
|
+
const code = await p.exited;
|
|
241
|
+
if (stopped) { reply.error = "Stopped."; emit({ t: "error", error: reply.error }); }
|
|
242
|
+
else if (code !== 0 && !reply.error && !reply.text) {
|
|
243
|
+
const err = (await errText).trim().split("\n").filter((l) => !/^\S+Z\s+(WARN|ERROR) /.test(l)).slice(-3).join("\n");
|
|
244
|
+
reply.error = err || `codex exited with code ${code}`;
|
|
245
|
+
emit({ t: "error", error: reply.error });
|
|
246
|
+
}
|
|
247
|
+
if (move && !stopped) await moveChat(chat, reply, move, board, emit);
|
|
248
|
+
} finally {
|
|
249
|
+
delete reply.activity;
|
|
250
|
+
chat.updated = new Date().toISOString();
|
|
251
|
+
save(base, chat);
|
|
252
|
+
live.delete(key);
|
|
253
|
+
emit({ t: "done" });
|
|
254
|
+
}
|
|
255
|
+
})();
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Apply the agent's move: only to a project the board lists, or one the board's own rules create.
|
|
260
|
+
async function moveChat(chat: Chat, reply: Msg, move: { op: string; arg: string }, board: Board, emit: (e: Event) => void) {
|
|
261
|
+
const step = (text: string, ok: boolean) => { const s: Step = { kind: "project", text, ok }; reply.steps!.push(s); emit({ t: "step", step: s }); };
|
|
262
|
+
let dir: string | null = null;
|
|
263
|
+
if (move.op === "project") {
|
|
264
|
+
const a = move.arg.replace(/[\\/]+$/, "");
|
|
265
|
+
const p = board.projects.find((x) => x.dir === a || dirname(x.dir) === a || x.dir === join(a, ".kaizen"))
|
|
266
|
+
?? board.projects.find((x) => x.label === a || basename(dirname(x.dir)) === a);
|
|
267
|
+
if (!p) return step(`No project ${move.arg} on the board`, false);
|
|
268
|
+
dir = p.dir;
|
|
269
|
+
} else {
|
|
270
|
+
const r = await board.create(move.arg);
|
|
271
|
+
if ("error" in r) return step(`Could not create ${move.arg}: ${r.error}`, false);
|
|
272
|
+
dir = r.dir;
|
|
273
|
+
board.projects.push({ dir, label: move.arg });
|
|
274
|
+
}
|
|
275
|
+
if (dir === chat.project) return;
|
|
276
|
+
chat.project = dir;
|
|
277
|
+
step(`${move.op === "new-project" ? "Created" : "Switched to"} ${board.projects.find((x) => x.dir === dir)?.label ?? move.arg}`, true);
|
|
278
|
+
emit({ t: "project", dir });
|
|
279
|
+
}
|
package/cli/state.ts
CHANGED
|
@@ -1636,7 +1636,7 @@ export function trustFolder(dir: string, cfg = join(process.env.CLAUDE_CONFIG_DI
|
|
|
1636
1636
|
// pick: the tool, model and yolo chosen for a new run; a decision takes the run's own
|
|
1637
1637
|
// tool and model, and stays in Yolo when the run was started in it. card: run it inside the board (agent.launch: card),
|
|
1638
1638
|
// where a pseudo-terminal exists; onChange is told when that agent ends.
|
|
1639
|
-
const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_SESSION|SESSION_ATTENDED|MESSAGING_SOCKET|MESSAGING_TOKEN))$/;
|
|
1639
|
+
export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_SESSION|SESSION_ATTENDED|MESSAGING_SOCKET|MESSAGING_TOKEN))$/;
|
|
1640
1640
|
|
|
1641
1641
|
// skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
|
|
1642
1642
|
// a work folder that may not be a project, so it is not remembered as one. A session record is
|