kaizen-agent 1.59.1 → 1.60.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/add-project.test.ts +169 -0
- package/cli/add-project.ts +132 -0
- package/cli/board.test.ts +15 -0
- package/cli/chat.ts +1 -1
- package/cli/dashboard.ts +6 -2
- package/cli/install.test.ts +1 -1
- package/cli/install.ts +18 -9
- package/cli/pty.test.ts +82 -3
- package/cli/pty.ts +122 -6
- package/cli/restart.test.ts +169 -0
- package/cli/settings.test.ts +35 -0
- package/cli/settings.ts +69 -18
- package/cli/state.test.ts +119 -3
- package/cli/state.ts +171 -13
- package/cli/usage.test.ts +130 -1
- package/cli/web-accept.test.ts +54 -0
- package/cli/web-symlink.test.ts +28 -0
- package/cli/web.ts +320 -100
- package/cli/worktree.test.ts +43 -1
- package/cli/worktree.ts +97 -2
- package/cli/writeback.ts +1 -1
- package/package.json +1 -1
- package/skills/kaizen/SKILL.md +5 -1
- package/skills/kaizen/config.default.yml +15 -2
- package/skills/kaizen/settings.md +1 -0
- package/skills/kaizen/spec-main.md +28 -2
- package/skills/kaizen-help/SKILL.md +1 -0
- package/web/board/add-project.ts +136 -0
- package/web/board/api.ts +1 -1
- package/web/board/badge.ts +5 -5
- package/web/board/cards.ts +11 -3
- package/web/board/context.ts +1 -0
- package/web/board/fixes.ts +3 -2
- package/web/board/git.ts +2 -0
- package/web/board/home.ts +7 -1
- package/web/board/ideas.ts +20 -3
- package/web/board/live.ts +1 -1
- package/web/board/main.ts +26 -9
- package/web/board/panel.ts +18 -3
- package/web/board/phone.ts +26 -3
- package/web/board/projects.ts +6 -85
- package/web/board/run-pick.ts +41 -0
- package/web/board/run-view.ts +261 -104
- package/web/board/settings.ts +42 -5
- package/web/board/store.ts +3 -1
- package/web/board/toast.ts +4 -1
- package/web/board/views.ts +6 -2
- package/web/board/workspace.ts +125 -38
- package/web/board/ws-board-ui.ts +84 -0
- package/web/board/ws-board.test.ts +71 -0
- package/web/board/ws-board.ts +45 -0
- package/web/board/ws-tabs.test.ts +171 -0
- package/web/board/ws-tabs.ts +170 -0
- package/web/board.html +92 -43
- package/web/board.js +44 -43
- package/web/notebook.js +24 -25
- package/web/notes.html +26 -21
- package/web/term.js +1 -1
- package/web/video.html +26 -21
- package/web/video.js +56 -57
package/cli/web.ts
CHANGED
|
@@ -3,15 +3,15 @@
|
|
|
3
3
|
import { existsSync, readdirSync, statSync, lstatSync, realpathSync, readFileSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
|
|
4
4
|
import { join, dirname, resolve, sep, basename } from "node:path";
|
|
5
5
|
import {
|
|
6
|
-
home, type Item, type Card, boardCards, knownProjects, remember, locate, label, tilde, searchRoots, findProjects,
|
|
6
|
+
home, type Item, type Card, boardCards, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
|
|
7
7
|
readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
|
|
8
8
|
appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, notice, notifier, LOGO,
|
|
9
|
-
reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, nativePath, closeSessions, sweepSessions, issueUrl,
|
|
9
|
+
reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
|
|
10
10
|
launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
|
|
11
11
|
} from "./state.ts";
|
|
12
|
-
import { attachPty, writePty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported } from "./pty.ts";
|
|
12
|
+
import { attachPty, writePty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
|
|
13
13
|
import { claudeUsage, codexUsage, phonePeers, type Usage } from "./usage.ts";
|
|
14
|
-
import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem,
|
|
14
|
+
import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
|
|
15
15
|
import { projectLogo, LOGO_TYPES } from "./logo.ts";
|
|
16
16
|
import * as chatgpt from "./chatgpt.ts";
|
|
17
17
|
import * as google from "./google.ts";
|
|
@@ -22,6 +22,8 @@ import * as video from "./video.ts";
|
|
|
22
22
|
import * as localsend from "./localsend.ts";
|
|
23
23
|
import * as hermes from "./hermes.ts";
|
|
24
24
|
import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
|
|
25
|
+
import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, run } from "./worktree.ts";
|
|
26
|
+
import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
|
|
25
27
|
|
|
26
28
|
const PAGE = join(dirname(import.meta.dir), "web", "board.html");
|
|
27
29
|
// The board's script: web/board/*.ts, bundled into one file by `bun run build:web`.
|
|
@@ -60,6 +62,17 @@ const served = (f: string) => installed() === VERSION && existsSync(f) ? readTex
|
|
|
60
62
|
|
|
61
63
|
// A board answers at url and runs the installed version. A board from before the
|
|
62
64
|
// version header sends none, so it counts as stale too.
|
|
65
|
+
// Which terminal the board launched for which stage of a run (plan, impl, review): runs/<id>/terminals.json.
|
|
66
|
+
// Loopback hosts only; shared by /open-url and /frameable so the board is never a way to reach other sites.
|
|
67
|
+
const isLoopback = (u: URL) => ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
|
|
68
|
+
|
|
69
|
+
export const stagesOf = (dir: string, id: string): Record<string, string> => { try { return JSON.parse(readText(join(dir, "runs", id, "terminals.json"))) ?? {}; } catch { return {}; } };
|
|
70
|
+
export const markStage = (dir: string, id: string, stage: string, key?: string) => {
|
|
71
|
+
if (!stage || !key || !id || /^\.+$/.test(id)) return;
|
|
72
|
+
try { if (!statSync(join(dir, "runs", id)).isDirectory()) return; } catch { return; } // only an existing runs/<id>
|
|
73
|
+
try { writeFileSync(join(dir, "runs", id, "terminals.json"), JSON.stringify({ ...stagesOf(dir, id), [stage]: key })); } catch { /* the run dir is gone */ }
|
|
74
|
+
};
|
|
75
|
+
|
|
63
76
|
export async function current(url: string) {
|
|
64
77
|
const r = await fetch(url, { signal: AbortSignal.timeout(1500) }).catch(() => null);
|
|
65
78
|
return !!r?.ok && r.headers.get("x-kaizen-version") === VERSION;
|
|
@@ -165,29 +178,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
165
178
|
};
|
|
166
179
|
|
|
167
180
|
// New project…: a folder in the Projects folder setting (else ~/Projects) or at `to`,
|
|
168
|
-
// empty or new, with .kaizen
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const winBad = (n: string) => !n || /[\\/:*?"<>|\x00-\x1f]/.test(n) || /[. ]$/.test(n)
|
|
173
|
-
|| /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(n);
|
|
174
|
-
const to = t ? resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t))
|
|
175
|
-
: join((await projectsRoot()) || join(home, "Projects"), name);
|
|
181
|
+
// empty or new, with .kaizen (and a git repository when asked), registered.
|
|
182
|
+
// check: only say where it would go.
|
|
183
|
+
async function makeProject(name: string, t = "", check = false, git = false): Promise<{ dir: string; git?: boolean } | { to: string } | { error: string; status?: number }> {
|
|
184
|
+
const dflt = join((await projectsRoot()) || join(home, "Projects"), name);
|
|
176
185
|
// The page asks while the name is typed: "con" on the way to "config" is no error yet.
|
|
177
|
-
if (check) return { to };
|
|
186
|
+
if (check) return { to: t ? resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t)) : dflt };
|
|
178
187
|
if (winBad(name)) return { error: "name the project: a folder name, without / \\ : * ? \" < > |, not ending in a dot or space, and not CON, NUL, COM1 or the like" };
|
|
179
|
-
|
|
188
|
+
const d = destDir(t || dflt, home, knownProjects(), await projectsRoot());
|
|
189
|
+
if ("error" in d) return { error: d.error };
|
|
190
|
+
const to = d.dir;
|
|
180
191
|
let used = false;
|
|
181
192
|
try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
|
|
182
193
|
if (used) return { error: `${to} already exists and is not empty`, status: 409 };
|
|
183
194
|
// A drive that is not there, a read-only folder, a path too long: said in a toast, not a crash.
|
|
184
195
|
try { mkdirSync(join(to, ".kaizen"), { recursive: true }); }
|
|
185
196
|
catch (e) { return { error: `could not create ${to}: ${(e as Error).message}` }; }
|
|
197
|
+
// A failed git init leaves a project without a repository: said, not rolled back.
|
|
198
|
+
const inited = git ? run(["git", "init", "-q", "--", to], to).ok : undefined;
|
|
199
|
+
if (inited) try { ignoreKaizen(to); } catch { /* the project still works */ }
|
|
186
200
|
remember(to);
|
|
187
201
|
changed();
|
|
188
|
-
return { dir: join(to, ".kaizen") };
|
|
202
|
+
return { dir: join(to, ".kaizen"), ...(git ? { git: inited } : {}) };
|
|
189
203
|
}
|
|
190
204
|
|
|
205
|
+
// Settings' scope, named by a project's state dir or "all": the project folder, null
|
|
206
|
+
// for All projects (~/.kaizen/config.yml), false for a folder the board does not know.
|
|
207
|
+
// No scope at all keeps the old resolution from the board's cwd, for older callers.
|
|
208
|
+
const settingsScope = (s: string | null) =>
|
|
209
|
+
!s ? undefined : s === "all" ? null : s !== join(home, ".kaizen") && states(true).includes(canonState(s)) ? dirname(canonState(s)) : false as const;
|
|
210
|
+
|
|
211
|
+
// An incoming state dir in the registry's spelling (symlinks resolved), so a symlinked project still matches.
|
|
212
|
+
const canonState = (d: string) => { const c = join(canonPath(dirname(d)), basename(d)); return c !== d && states(true).includes(c) ? c : d; };
|
|
191
213
|
const states = (all: boolean, cur = boardState) => (all || !cur
|
|
192
214
|
? [...knownProjects().map((d) => join(d, ".kaizen")), join(home, ".kaizen")]
|
|
193
215
|
: [cur]
|
|
@@ -226,7 +248,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
226
248
|
// works and a slow poll where it does not.
|
|
227
249
|
const clients = new Set<ReadableStreamDefaultController>();
|
|
228
250
|
// Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
|
|
229
|
-
const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; pid?: number }>();
|
|
251
|
+
const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; ws?: string; pid?: number }>();
|
|
230
252
|
const SHELL_CAP = 8;
|
|
231
253
|
let usageCache: Usage[] = [];
|
|
232
254
|
let usageAt = 0;
|
|
@@ -256,29 +278,76 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
256
278
|
if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
|
|
257
279
|
const text = quiet ? "" : resumePrompt(id);
|
|
258
280
|
const before = Date.now();
|
|
259
|
-
|
|
281
|
+
// What the card showed before the board went away (saveLive), then a line saying so.
|
|
282
|
+
const idx = runIndex(dir);
|
|
283
|
+
const prev = readSessions(dir).filter((s) => ownerOf(dir, s, idx) === id && existsSync(tailOf(s.key))).pop();
|
|
284
|
+
let seed: string | undefined;
|
|
285
|
+
try { if (prev) seed = readText(tailOf(prev.key)) + RESUMED; } catch { /* shown without it */ }
|
|
286
|
+
const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, { ...inCard(dir), seed });
|
|
260
287
|
if (r.ok) closeSessions(dir, id, { before });
|
|
288
|
+
if (r.ok && prev) rmSync(tailOf(prev.key), { force: true });
|
|
261
289
|
changed();
|
|
262
290
|
return r;
|
|
263
291
|
};
|
|
264
292
|
|
|
265
|
-
// Runs whose in-card agent was live when Settings' Update
|
|
266
|
-
// agents end with the old board, so the new one starts them
|
|
267
|
-
// entry keeps its session key, so an idea whose run had not
|
|
268
|
-
// matched to its run by the new board, once that run exists.
|
|
269
|
-
// not left to the board's exit, so none outlives
|
|
293
|
+
// Runs whose in-card agent was live when the board stopped (Settings' Update, Ctrl-C,
|
|
294
|
+
// systemd) or died: the agents end with the old board, so the new one starts them
|
|
295
|
+
// again (resumeRun). Each entry keeps its session key, so an idea whose run had not
|
|
296
|
+
// written state.json yet is matched to its run by the new board, once that run exists.
|
|
297
|
+
// On a stop the agents are ended here, not left to the board's exit, so none outlives
|
|
298
|
+
// it beside its resumed self; a tmux-kept one is only detached and is attached again.
|
|
299
|
+
// While the board runs the list is kept current (crash: true), so a board that died
|
|
300
|
+
// without stopping leaves it too. Each card's last screen goes beside it (tailOf).
|
|
270
301
|
const RESUME_LIST = join(home, ".kaizen", "resume-after-upgrade.json");
|
|
271
|
-
const
|
|
302
|
+
const TAILS = join(home, ".kaizen", "pty");
|
|
303
|
+
const tailOf = (key: string) => join(TAILS, `${key}.log`);
|
|
304
|
+
type Live = { dir: string; key: string; run: string | null; tmux?: string; resumed?: number };
|
|
305
|
+
// Sessions this board started again after a crash, and when: written into the list so
|
|
306
|
+
// a board that dies again within CRASH_AGAIN_MS does not start them a third time.
|
|
307
|
+
const autoResumed = new Map<string, number>();
|
|
308
|
+
const CRASH_AGAIN_MS = 120_000;
|
|
309
|
+
const written = new Map<string, number>();
|
|
310
|
+
const owners = new Map<string, { dir: string; run: string | null }>(), unrecorded = new Set<string>();
|
|
311
|
+
let stopping = false, lastList = "";
|
|
312
|
+
const saveLive = (crash = false) => {
|
|
313
|
+
if (stopping) return;
|
|
272
314
|
const live = new Set(ptyKeys().filter((k) => ptyState(k)?.alive));
|
|
273
|
-
if (!live.size)
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
const idx = runIndex(d);
|
|
277
|
-
for (const s of readSessions(d)) if (live.has(s.key)) list.push({ dir: d, key: s.key, run: ownerOf(d, s, idx) });
|
|
315
|
+
if (!live.size) {
|
|
316
|
+
if (crash && lastList) { rmSync(RESUME_LIST, { force: true }); lastList = ""; }
|
|
317
|
+
return;
|
|
278
318
|
}
|
|
279
|
-
|
|
280
|
-
for
|
|
319
|
+
// Which project and run each session belongs to, found once: a run owns its session
|
|
320
|
+
// for good, so only new sessions and ideas' ones send the walk through every project.
|
|
321
|
+
// A key no project records (a Terminal page shell) is looked for once.
|
|
322
|
+
for (const m of [owners, written, autoResumed]) for (const k of m.keys()) if (!live.has(k)) m.delete(k);
|
|
323
|
+
for (const k of unrecorded) if (!live.has(k)) unrecorded.delete(k);
|
|
324
|
+
if ([...live].some((k) => !unrecorded.has(k) && !owners.get(k)?.run)) {
|
|
325
|
+
for (const d of states(true)) {
|
|
326
|
+
const idx = runIndex(d);
|
|
327
|
+
for (const s of readSessions(d)) if (live.has(s.key) && !owners.get(s.key)?.run) owners.set(s.key, { dir: d, run: ownerOf(d, s, idx) });
|
|
328
|
+
}
|
|
329
|
+
for (const k of live) if (!owners.has(k)) unrecorded.add(k);
|
|
330
|
+
}
|
|
331
|
+
const list: Live[] = [...live].flatMap((key) => {
|
|
332
|
+
const o = owners.get(key);
|
|
333
|
+
return o ? [{ dir: o.dir, key, run: o.run, ...(ptyTmux(key) ? { tmux: ptyTmux(key)! } : {}), ...(autoResumed.has(key) ? { resumed: autoResumed.get(key) } : {}) }] : [];
|
|
334
|
+
});
|
|
335
|
+
try {
|
|
336
|
+
mkdirSync(TAILS, { recursive: true });
|
|
337
|
+
for (const { key } of list) {
|
|
338
|
+
const total = ptyState(key)!.total, t = written.get(key) === total ? null : ptyTail(key);
|
|
339
|
+
if (t) { writeFileSync(tailOf(key), t); written.set(key, total); }
|
|
340
|
+
}
|
|
341
|
+
const body = JSON.stringify(list);
|
|
342
|
+
if (!crash || body !== lastList) writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), crash, list }));
|
|
343
|
+
lastList = body;
|
|
344
|
+
} catch { /* nothing resumes; the card offers Resume */ }
|
|
345
|
+
if (crash) return;
|
|
346
|
+
stopping = true;
|
|
347
|
+
for (const k of live) if (!detachPty(k)) exitPty(k, 200);
|
|
281
348
|
};
|
|
349
|
+
// ponytail: a 3s tick, so a crash loses up to 3s of screen; hook push() if that matters.
|
|
350
|
+
const keepList = setInterval(() => saveLive(true), 3000);
|
|
282
351
|
// An idea's session, until its run exists and owns it (ownerOf).
|
|
283
352
|
const ideaPty = new Map<string, string>();
|
|
284
353
|
// Backlog items this board launched whose run has not written its state.json yet:
|
|
@@ -292,11 +361,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
292
361
|
const live = new Set(ptyKeys());
|
|
293
362
|
if (!live.size) return () => undefined;
|
|
294
363
|
const runs = new Map<string, string[]>();
|
|
364
|
+
const planKeys = new Set(ideaPty.values());
|
|
295
365
|
for (const d of new Set(cards.filter((c) => c.kind === "run").map((c) => c.state))) {
|
|
296
366
|
const ids = runIndex(d);
|
|
297
367
|
for (const s of readSessions(d))
|
|
298
368
|
if (live.has(s.key)) {
|
|
299
|
-
const
|
|
369
|
+
const owner = ownerOf(d, s, ids);
|
|
370
|
+
const k = `${d}\0${owner}`;
|
|
371
|
+
// The idea's agent that began this run is its plan terminal: recorded once the run exists.
|
|
372
|
+
if (owner && planKeys.has(s.key) && !stagesOf(d, owner).plan) markStage(d, owner, "plan", s.key);
|
|
300
373
|
runs.set(k, [...(runs.get(k) ?? []), s.key]); // oldest first: the newest is the card's
|
|
301
374
|
}
|
|
302
375
|
}
|
|
@@ -309,7 +382,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
309
382
|
if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
|
|
310
383
|
// Every agent session the run has had on this board, for the workspace's Agent tabs.
|
|
311
384
|
const all = keys.filter((k) => ptyState(k)?.alive || k === key);
|
|
312
|
-
return { key, alive: st.alive, asking: st.asking, busy: st.busy, all };
|
|
385
|
+
return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
|
|
313
386
|
};
|
|
314
387
|
};
|
|
315
388
|
const watchers: FSWatcher[] = [];
|
|
@@ -451,7 +524,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
451
524
|
if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
|
|
452
525
|
const url = new URL(req.url);
|
|
453
526
|
const path = url.pathname;
|
|
454
|
-
const
|
|
527
|
+
const qdir = () => { const v = url.searchParams.get("dir"); return v == null ? v : canonState(v); };
|
|
528
|
+
const asked0 = req.headers.get("x-kz-dir");
|
|
529
|
+
const asked = asked0 && canonState(asked0);
|
|
455
530
|
const state = asked && states(true).includes(asked) ? asked : boardState;
|
|
456
531
|
const project = state ? label(state) : null;
|
|
457
532
|
|
|
@@ -630,7 +705,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
630
705
|
if (!ptySupported) return bad("terminals need a newer Bun", 501);
|
|
631
706
|
let body: any;
|
|
632
707
|
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
633
|
-
const dir = String(body.dir ?? "");
|
|
708
|
+
const dir = canonState(String(body.dir ?? ""));
|
|
634
709
|
if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
635
710
|
let cmd: string[];
|
|
636
711
|
let agent = "";
|
|
@@ -668,24 +743,99 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
668
743
|
agent = a.cmd;
|
|
669
744
|
cmd = [a.cmd];
|
|
670
745
|
} else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
|
|
746
|
+
// A workspace folder: only an exact path from this project's own `git worktree list`.
|
|
747
|
+
let cwd = projectOf(dir);
|
|
748
|
+
if (body.ws != null) {
|
|
749
|
+
// A miss rechecks past a cache older than 1 s: a worktree made since is real, and a
|
|
750
|
+
// burst of bad paths runs git at most once a second.
|
|
751
|
+
const known = () => workspaces(cwd).some((w) => w.path === body.ws);
|
|
752
|
+
if (typeof body.ws !== "string" || !(known() || (workspacesAge(cwd) > 1000 && (forgetWorkspaces(cwd), known())))) return bad("not a workspace of this project", 400);
|
|
753
|
+
cwd = body.ws;
|
|
754
|
+
}
|
|
671
755
|
for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
|
|
672
756
|
if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
|
|
673
757
|
const key = "sh-" + crypto.randomUUID().slice(0, 8);
|
|
674
758
|
const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name : "shell";
|
|
675
|
-
const pid = startPty(key, cmd,
|
|
759
|
+
const pid = startPty(key, cmd, cwd, undefined, changed);
|
|
676
760
|
// The run workspace that opened it (its card key), so each run keeps its own centre.
|
|
677
|
-
shells.set(key, { key, dir, title, agent, run: runKey, pid });
|
|
761
|
+
shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
|
|
678
762
|
changed();
|
|
679
763
|
return json(shells.get(key));
|
|
680
764
|
}
|
|
765
|
+
// The rail's + on a project: a new worktree and branch under <project>/.kaizen/wt/.
|
|
766
|
+
// Runs git, so /shell's guards; the branch name is checked by git check-ref-format
|
|
767
|
+
// and every call is an argv array.
|
|
768
|
+
if (req.method === "POST" && path === "/worktree") {
|
|
769
|
+
const refused = strict(req);
|
|
770
|
+
if (refused) return refused;
|
|
771
|
+
let body: any;
|
|
772
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
773
|
+
const dir = canonState(String(body.dir ?? ""));
|
|
774
|
+
if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
775
|
+
const r = addWorktree(projectOf(dir), String(body.branch ?? "").trim(), undefined, typeof body.base === "string" && body.base.trim() ? body.base.trim() : undefined);
|
|
776
|
+
if (!r.ok) return bad(r.why);
|
|
777
|
+
changed();
|
|
778
|
+
return json(r);
|
|
779
|
+
}
|
|
780
|
+
// The rail's + sheet. Each of these starts git, makes a folder or registers one, so
|
|
781
|
+
// they take /worktree's guards and read their paths from the raw body (the generic
|
|
782
|
+
// POST block below would normalise a `..` away before destDir sees it).
|
|
783
|
+
if (req.method === "POST" && (path === "/new-project" || path === "/clone" || path === "/add-project")) {
|
|
784
|
+
const refused = strict(req);
|
|
785
|
+
if (refused) return refused;
|
|
786
|
+
let body: any;
|
|
787
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
788
|
+
if (!body || typeof body !== "object") return bad("json body expected");
|
|
789
|
+
const text = (k: string) => typeof body[k] === "string" ? body[k].trim() : "";
|
|
790
|
+
if (path === "/new-project") {
|
|
791
|
+
const r = await makeProject(text("name"), text("to"), !!body.check, body.git !== false);
|
|
792
|
+
return "error" in r ? bad(r.error, r.status) : json({ ok: true, ...r });
|
|
793
|
+
}
|
|
794
|
+
if (path === "/add-project") {
|
|
795
|
+
const d = destDir(text("path"), home, knownProjects(), await projectsRoot());
|
|
796
|
+
if ("error" in d) return bad(d.error);
|
|
797
|
+
let isDir = false;
|
|
798
|
+
try { isDir = statSync(d.dir).isDirectory(); } catch { /* absent */ }
|
|
799
|
+
if (!isDir) return bad(`${d.dir} is not a folder`);
|
|
800
|
+
const already = knownProjects().includes(d.dir);
|
|
801
|
+
try { mkdirSync(join(d.dir, ".kaizen"), { recursive: true }); }
|
|
802
|
+
catch (e) { return bad(`could not set up ${d.dir}: ${(e as Error).message}`); }
|
|
803
|
+
remember(d.dir);
|
|
804
|
+
changed();
|
|
805
|
+
return json({ ok: true, dir: join(d.dir, ".kaizen"), already });
|
|
806
|
+
}
|
|
807
|
+
// /clone: any https or ssh git URL, into a folder that is new or empty.
|
|
808
|
+
const g = gitUrl(body.url);
|
|
809
|
+
if ("error" in g) return bad(g.error);
|
|
810
|
+
const root = (await projectsRoot()) || join(home, "Projects");
|
|
811
|
+
const d = destDir(text("to") || join(root, g.name), home, knownProjects(), root);
|
|
812
|
+
if ("error" in d) return bad(d.error);
|
|
813
|
+
const to = d.dir;
|
|
814
|
+
if (body.check) return json({ ok: true, to, name: g.name });
|
|
815
|
+
let used = false;
|
|
816
|
+
try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
|
|
817
|
+
if (used) return bad(`${to} already exists and is not empty`, 409);
|
|
818
|
+
const c = await cloneInto(g.url, to);
|
|
819
|
+
if (!c.ok) return bad(c.why, 500);
|
|
820
|
+
mkdirSync(join(to, ".kaizen"), { recursive: true });
|
|
821
|
+
remember(to);
|
|
822
|
+
changed();
|
|
823
|
+
return json({ ok: true, dir: join(to, ".kaizen") });
|
|
824
|
+
}
|
|
825
|
+
// The branches a new workspace can start from, for a project the board knows.
|
|
826
|
+
if (req.method === "GET" && path === "/branches") {
|
|
827
|
+
const dir = canonState(url.searchParams.get("dir") ?? "");
|
|
828
|
+
if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
829
|
+
return json(branchesOf(projectOf(dir)));
|
|
830
|
+
}
|
|
681
831
|
if (req.method === "GET" && path === "/shells") {
|
|
682
|
-
const dir =
|
|
832
|
+
const dir = qdir();
|
|
683
833
|
for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
|
|
684
834
|
return json([...shells.values()].filter((s) => !dir || s.dir === dir));
|
|
685
835
|
}
|
|
686
836
|
// The localhost tab's "Open in browser": a Chromium app window on this computer, for
|
|
687
|
-
//
|
|
688
|
-
// http(s) address, passed as one --app= argument, never a shell string.
|
|
837
|
+
// localhost pages that refuse to be framed. Launches a process, so /shell's guards, and only a
|
|
838
|
+
// loopback http(s) address, passed as one --app= argument, never a shell string.
|
|
689
839
|
if (req.method === "POST" && path === "/open-url") {
|
|
690
840
|
const refused = strict(req);
|
|
691
841
|
if (refused) return refused;
|
|
@@ -694,6 +844,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
694
844
|
let u: URL;
|
|
695
845
|
try { u = new URL(String(body.url ?? "")); } catch { return bad("not a url"); }
|
|
696
846
|
if (!/^https?:$/.test(u.protocol)) return bad("only an http(s) address", 400);
|
|
847
|
+
// Loopback only: the board must not be a way to open arbitrary sites on this computer.
|
|
848
|
+
if (!isLoopback(u)) return bad("only a localhost address", 400);
|
|
697
849
|
return json({ ok: await openApp(u.href, join(home, ".kaizen", "app-window")) });
|
|
698
850
|
}
|
|
699
851
|
// Whether a page may be framed: X-Frame-Options or a CSP frame-ancestors that is not
|
|
@@ -705,8 +857,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
705
857
|
let u: URL;
|
|
706
858
|
try { u = new URL(url.searchParams.get("url") ?? ""); } catch { return bad("not a url"); }
|
|
707
859
|
if (!/^https?:$/.test(u.protocol)) return bad("only an http(s) address", 400);
|
|
860
|
+
if (!isLoopback(u)) return bad("only a localhost address", 400);
|
|
708
861
|
try {
|
|
709
|
-
const r = await fetch(u.href, { redirect: "
|
|
862
|
+
const r = await fetch(u.href, { redirect: "manual", signal: AbortSignal.timeout(4000) });
|
|
863
|
+
if (r.status >= 300 && r.status < 400) return json({ frameable: null }); // never follow: a redirect could lead off localhost
|
|
710
864
|
r.body?.cancel().catch(() => {});
|
|
711
865
|
const xfo = (r.headers.get("x-frame-options") ?? "").trim();
|
|
712
866
|
const fa = /frame-ancestors([^;]*)/i.exec(r.headers.get("content-security-policy") ?? "")?.[1].trim() ?? "";
|
|
@@ -742,13 +896,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
742
896
|
|
|
743
897
|
// Every note of one project, text included: search, tags and backlinks are the page's.
|
|
744
898
|
if (req.method === "GET" && path === "/vault") {
|
|
745
|
-
const dir =
|
|
899
|
+
const dir = qdir() ?? state ?? join(home, ".kaizen");
|
|
746
900
|
if (!states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
747
901
|
return json({ dir, notes: listNotes(dir) });
|
|
748
902
|
}
|
|
749
903
|
|
|
750
904
|
if (req.method === "GET" && (path === "/project-tree" || path === "/project-text")) {
|
|
751
|
-
const treeState =
|
|
905
|
+
const treeState = qdir() ?? state;
|
|
752
906
|
if (!treeState || !states(true).includes(treeState) || treeState === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
753
907
|
const rel = url.searchParams.get("path") ?? "";
|
|
754
908
|
const parts = rel ? rel.split("/") : [];
|
|
@@ -780,7 +934,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
780
934
|
|
|
781
935
|
// What a note can link to on this project's board: runs, findings, backlog, ideas.
|
|
782
936
|
if (req.method === "GET" && path === "/links") {
|
|
783
|
-
const dir =
|
|
937
|
+
const dir = qdir() ?? state ?? join(home, ".kaizen");
|
|
784
938
|
if (!states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
785
939
|
return json(boardIndex(dir));
|
|
786
940
|
}
|
|
@@ -800,7 +954,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
800
954
|
// A project's own logo, for the project pickers: only a known project, only the fixed
|
|
801
955
|
// names in LOGOS, sandboxed so an SVG opened directly runs nothing on this origin.
|
|
802
956
|
if (req.method === "GET" && path === "/project-logo") {
|
|
803
|
-
const dir =
|
|
957
|
+
const dir = qdir() ?? "";
|
|
804
958
|
const f = states(true).includes(dir) ? projectLogo(dir) : null;
|
|
805
959
|
if (!f) return bad("no logo", 404);
|
|
806
960
|
const ext = f.slice(f.lastIndexOf(".") + 1).toLowerCase();
|
|
@@ -837,20 +991,44 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
837
991
|
return !root || d === state || (fold(p).startsWith(inside)
|
|
838
992
|
&& (!isGroup(p) || filled(d) || fold(dirname(p)) !== fold(root)));
|
|
839
993
|
});
|
|
994
|
+
for (const d of dirs) healRuns(d);
|
|
840
995
|
const cards = boardCards(dirs, Date.now()), pty = ptyOf(cards);
|
|
841
996
|
// The git mark, for the cards whose panel offers commit and push: one status per project.
|
|
842
|
-
const marks = new Map<string, Record<string, string>>();
|
|
997
|
+
const marks = new Map<string, Record<string, string>>(), dues = new Map<string, Record<string, "commit" | "push">>();
|
|
843
998
|
const markable = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen");
|
|
844
999
|
for (const d of new Set(cards.filter(markable).map((c) => c.state)))
|
|
845
|
-
marks.set(d, cardsGit(d, cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!)));
|
|
1000
|
+
marks.set(d, cardsGit(d, cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!), dues.set(d, {}).get(d)));
|
|
846
1001
|
// Open findings the panel's Fix findings form would offer, on the same runs.
|
|
847
1002
|
const openFindings = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "findings" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen")
|
|
848
1003
|
? reviewFindings(c.state, c.id!).filter((f) => !f.done).length || undefined : undefined;
|
|
1004
|
+
// The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
|
|
1005
|
+
// shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
|
|
1006
|
+
// What an agent printed goes only to a viewer on this machine, not to a tailnet host or a phone.
|
|
1007
|
+
const ip = srv.requestIP(req)?.address ?? "";
|
|
1008
|
+
const loopback = (hostname === "127.0.0.1" || hostname === "localhost") && /^(127\.|::1$|::ffff:127\.)/.test(ip)
|
|
1009
|
+
&& !["x-forwarded-for", "x-forwarded-host", "forwarded", "tailscale-user-login", "tailscale-user-name"].some((h) => req.headers.has(h));
|
|
1010
|
+
const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
|
|
1011
|
+
const addAgent = (key: string, dir: string, ws: string | undefined, cmd: string | undefined, run?: string) => {
|
|
1012
|
+
const st = seenKey.has(key) ? null : ptyState(key);
|
|
1013
|
+
if (!st?.alive) return;
|
|
1014
|
+
seenKey.add(key);
|
|
1015
|
+
const name = KNOWN_AGENTS.find((k) => k.cmd === cmd)?.name.split(" ")[0] ?? "Agent";
|
|
1016
|
+
agents.push({ key, dir, ws, agent: cmd, name, run, asking: st.asking, busy: st.busy, born: st.born, ...(loopback ? { last: st.last || undefined, at: st.at || undefined } : {}) });
|
|
1017
|
+
};
|
|
1018
|
+
for (const x of shells.values()) if (x.agent) addAgent(x.key, x.dir, x.ws, x.agent, x.run);
|
|
1019
|
+
cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
|
|
1020
|
+
const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
|
|
1021
|
+
workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
|
|
849
1022
|
return json({
|
|
850
1023
|
project, all, dir: state,
|
|
851
|
-
|
|
1024
|
+
// Each project's workspaces (git worktrees, or the one folder); the global queue is its own one.
|
|
1025
|
+
projects: picker.map(entry),
|
|
1026
|
+
// Dirs with a card the picker leaves out (the global queue, a project outside the
|
|
1027
|
+
// Projects folder): the rail still needs their workspaces so a waiting run shows.
|
|
1028
|
+
rail: [...new Set(cards.map((c) => c.state))].filter((d) => !picker.includes(d)).map(entry),
|
|
852
1029
|
fresh: unset.map((d) => ({ dir: join(d, ".kaizen"), label: tilde(d) })),
|
|
853
|
-
|
|
1030
|
+
agents,
|
|
1031
|
+
cards: cards.map((c, i) => ({ ...c, notice: notice(c), git: markable(c) ? marks.get(c.state)?.[c.id!] : undefined, gitDue: markable(c) ? dues.get(c.state)?.[c.id!] : undefined, open: openFindings(c), pty: ptys[i] })),
|
|
854
1032
|
backlog: backlogCards(dirs).map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
|
|
855
1033
|
now: Date.now(),
|
|
856
1034
|
});
|
|
@@ -858,7 +1036,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
858
1036
|
|
|
859
1037
|
if (req.method === "GET" && path.startsWith("/run/")) {
|
|
860
1038
|
const id = decodeURIComponent(path.slice(5));
|
|
861
|
-
const dir =
|
|
1039
|
+
const dir = qdir() ?? state;
|
|
862
1040
|
if (!dir || !states(true).includes(dir) || !/^[\w.-]+$/.test(id)) return bad("no such run", 404);
|
|
863
1041
|
const base = join(dir, "runs", id);
|
|
864
1042
|
if (!existsSync(base)) return bad("no such run", 404);
|
|
@@ -880,7 +1058,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
880
1058
|
if (req.method === "GET" && path === "/sources") {
|
|
881
1059
|
// One project's sources, or with no dir every known project's: each entry
|
|
882
1060
|
// says which project it belongs to. Nothing is assumed from where the board started.
|
|
883
|
-
const dir =
|
|
1061
|
+
const dir = qdir();
|
|
884
1062
|
if (dir && !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
885
1063
|
const sources = [], icebox = [], dismissed = [], failed = [];
|
|
886
1064
|
for (const d of dir ? [dir] : states(true)) {
|
|
@@ -908,14 +1086,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
908
1086
|
}
|
|
909
1087
|
|
|
910
1088
|
if (req.method === "GET" && path === "/agents") {
|
|
911
|
-
const dir =
|
|
1089
|
+
const dir = qdir();
|
|
912
1090
|
if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
913
1091
|
return json(agentChoices(projectOf(dir)));
|
|
914
1092
|
}
|
|
915
1093
|
|
|
916
1094
|
if (req.method === "GET" && path === "/settings") {
|
|
917
1095
|
const { listSettings } = await import("./settings.ts");
|
|
918
|
-
const
|
|
1096
|
+
const scope = settingsScope(url.searchParams.get("scope"));
|
|
1097
|
+
if (scope === false) return bad("unknown project", 404);
|
|
1098
|
+
const cfg = listSettings(repoDir, scope);
|
|
1099
|
+
Object.assign(cfg, {
|
|
1100
|
+
scope: scope ? join(scope, ".kaizen") : "all",
|
|
1101
|
+
projects: states(true).filter((d) => d !== join(home, ".kaizen")).map((d) => ({ dir: d, label: label(d) })),
|
|
1102
|
+
});
|
|
919
1103
|
Object.assign(cfg, { phoneUrls: [...webHosts()].filter((h) => /^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.ts\.net$/.test(h)).map((h) => `https://${h}`) });
|
|
920
1104
|
// Connected, the model is chosen from what the plan offers rather than typed.
|
|
921
1105
|
const m = cfg.rows.find((r) => r.key === "sources.model");
|
|
@@ -1029,8 +1213,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1029
1213
|
if (!local(req)) return bad("cross-origin write refused", 403);
|
|
1030
1214
|
let body: any;
|
|
1031
1215
|
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1032
|
-
const { setSetting } = await import("./settings.ts");
|
|
1033
|
-
const
|
|
1216
|
+
const { setSetting, resetSetting } = await import("./settings.ts");
|
|
1217
|
+
const scope = settingsScope(body.scope == null ? null : String(body.scope));
|
|
1218
|
+
if (body.reset && typeof scope !== "string") return bad("only a project's own value can be reset");
|
|
1219
|
+
if (scope === false) return bad("unknown project", 404);
|
|
1220
|
+
const r = body.reset
|
|
1221
|
+
? resetSetting(repoDir, String(body.key ?? ""), scope as string)
|
|
1222
|
+
: setSetting(repoDir, String(body.key ?? ""), String(body.value ?? ""), scope);
|
|
1034
1223
|
return "error" in r ? bad(r.error) : json(r);
|
|
1035
1224
|
}
|
|
1036
1225
|
|
|
@@ -1043,7 +1232,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1043
1232
|
if (!cmd) return bad("No folder dialog found: install zenity or kdialog, or type the path");
|
|
1044
1233
|
picking = true;
|
|
1045
1234
|
try {
|
|
1046
|
-
const p = Bun.spawn(cmd, { stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
1235
|
+
const p = Bun.spawn(cmd, { stdin: "ignore", stdout: "pipe", stderr: "pipe", windowsHide: true });
|
|
1047
1236
|
const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
|
|
1048
1237
|
// osascript ends a folder with "/"; a bare root (/, C:\) keeps its own.
|
|
1049
1238
|
const picked = /^([A-Za-z]:)?[\\/]$/.test(out.trim()) ? out.trim() : out.trim().replace(/[\\/]+$/, "");
|
|
@@ -1059,7 +1248,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1059
1248
|
// Attachments only, never a run's own files: the path must sit under an
|
|
1060
1249
|
// attachments/ directory of a known state dir, with no way back up.
|
|
1061
1250
|
if (req.method === "GET" && path === "/file") {
|
|
1062
|
-
const dir =
|
|
1251
|
+
const dir = qdir() ?? state;
|
|
1063
1252
|
const p = url.searchParams.get("p") ?? "";
|
|
1064
1253
|
if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
1065
1254
|
if (!/^(runs\/[\w.-]+\/)?attachments\/[\w.-]+$/.test(p)) return bad("bad path");
|
|
@@ -1072,7 +1261,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1072
1261
|
// An icebox image, sent on to a link read fresh from its source: the one kept
|
|
1073
1262
|
// since the gather may have expired. Only an https link the item holds is followed.
|
|
1074
1263
|
if (req.method === "GET" && path === "/ice-image") {
|
|
1075
|
-
const dir =
|
|
1264
|
+
const dir = qdir() ?? "";
|
|
1076
1265
|
if (!states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
1077
1266
|
const u = (await freshImages(dir, url.searchParams.get("id") ?? ""))[Number(url.searchParams.get("i"))];
|
|
1078
1267
|
if (!u || !/^https:\/\//.test(u)) return bad("no such image", 404);
|
|
@@ -1162,6 +1351,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1162
1351
|
if (!local(req)) return bad("cross-origin write refused", 403);
|
|
1163
1352
|
let body: any;
|
|
1164
1353
|
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1354
|
+
for (const k of ["dir", "to"]) if (typeof body?.[k] === "string" && body[k]) body[k] = canonState(body[k]);
|
|
1165
1355
|
|
|
1166
1356
|
// The Video page: a place by index, a video folder by name, both checked in video.ts.
|
|
1167
1357
|
if (path.startsWith("/video/")) {
|
|
@@ -1249,49 +1439,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1249
1439
|
return json({ ok: true, added: knownProjects().length - before });
|
|
1250
1440
|
}
|
|
1251
1441
|
|
|
1252
|
-
// A new, empty project: a folder in the projects folder (else ~/Projects), or
|
|
1253
|
-
// where the page names, set up at once. /find only sees folders that already
|
|
1254
|
-
// have a .kaizen, so a folder made by hand never shows there.
|
|
1255
|
-
if (path === "/new-project") {
|
|
1256
|
-
const r = await makeProject(typeof body.name === "string" ? body.name.trim() : "", typeof body.to === "string" ? body.to.trim() : "", !!body.check);
|
|
1257
|
-
return "error" in r ? bad(r.error, r.status) : json({ ok: true, ...r });
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
// Clone a GitHub repository into the projects folder (else ~/Projects) and
|
|
1261
|
-
// set it up as a project. Arguments go to git as an array: no shell.
|
|
1262
|
-
if (path === "/clone") {
|
|
1263
|
-
const link = typeof body.url === "string" ? body.url.trim() : "";
|
|
1264
|
-
const name = githubRepo(link);
|
|
1265
|
-
if (!name) return bad("paste a GitHub link: https://github.com/owner/repo or git@github.com:owner/repo.git");
|
|
1266
|
-
const root = (await projectsRoot()) || join(home, "Projects");
|
|
1267
|
-
// The page may name the folder: typed (~ allowed, relative to home) or picked.
|
|
1268
|
-
// A new one is made, parents too; an empty one is used; anything else refused.
|
|
1269
|
-
let to = join(root, name);
|
|
1270
|
-
if (typeof body.to === "string" && body.to.trim()) {
|
|
1271
|
-
const t = body.to.trim();
|
|
1272
|
-
to = resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t));
|
|
1273
|
-
}
|
|
1274
|
-
if (body.check) return json({ ok: true, to, name });
|
|
1275
|
-
let used = false;
|
|
1276
|
-
try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
|
|
1277
|
-
if (used) return bad(`${to} already exists and is not empty`, 409);
|
|
1278
|
-
mkdirSync(to, { recursive: true });
|
|
1279
|
-
const p = Bun.spawn(["git", "clone", "--", link, to], { stdin: "ignore", stdout: "ignore", stderr: "pipe", env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? "ssh -o BatchMode=yes" }, windowsHide: true });
|
|
1280
|
-
const [err, code] = await Promise.all([new Response(p.stderr).text(), p.exited]);
|
|
1281
|
-
if (code !== 0) return bad(err.trim().split("\n").filter(Boolean).pop() || "git clone failed", 500);
|
|
1282
|
-
mkdirSync(join(to, ".kaizen"), { recursive: true });
|
|
1283
|
-
remember(to);
|
|
1284
|
-
changed();
|
|
1285
|
-
return json({ ok: true, dir: join(to, ".kaizen") });
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
1442
|
// No project here means the global inbox, which is where the TUI puts ideas too.
|
|
1289
|
-
|
|
1443
|
+
let dir: string = body.dir ?? state ?? join(home, ".kaizen");
|
|
1290
1444
|
// Choosing a folder from the projects folder is what sets it up: an empty
|
|
1291
1445
|
// .kaizen, which the first run fills in. Only folders the board offered.
|
|
1292
1446
|
if (path === "/cd" && dir === join(dirname(dir), ".kaizen") && (await fresh()).includes(dirname(dir))) {
|
|
1293
1447
|
mkdirSync(dir, { recursive: true });
|
|
1294
1448
|
remember(dirname(dir));
|
|
1449
|
+
dir = canonState(dir);
|
|
1295
1450
|
}
|
|
1296
1451
|
if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
1297
1452
|
|
|
@@ -1587,11 +1742,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1587
1742
|
const nums = pickFindings(dir, id, body.nums);
|
|
1588
1743
|
if (!nums) return bad("pick open findings of this review");
|
|
1589
1744
|
const text = fixPrompt(id, nums);
|
|
1745
|
+
// An agent already open in this run's card takes the fix there, busy or not:
|
|
1746
|
+
// the text queues in it, and no second agent opens beside it.
|
|
1747
|
+
const live = readSessions(dir).find((s) => ptyState(s.key)?.alive && ownerOf(dir, s) === id);
|
|
1748
|
+
if (live) {
|
|
1749
|
+
writePty(live.key, text + "\r");
|
|
1750
|
+
markStage(dir, id, "review", live.key);
|
|
1751
|
+
changed();
|
|
1752
|
+
return json({ ok: true, pty: live.key, reused: true });
|
|
1753
|
+
}
|
|
1590
1754
|
// The run's conversation picks the fix up, and once that window is open the
|
|
1591
1755
|
// waiting one ends. A failed launch leaves it: the decision has nowhere else.
|
|
1592
1756
|
const before = Date.now();
|
|
1593
1757
|
const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
|
|
1594
|
-
if (r.ok) closeSessions(dir, id, { before });
|
|
1758
|
+
if (r.ok) (closeSessions(dir, id, { before }), markStage(dir, id, "review", r.pty));
|
|
1595
1759
|
changed();
|
|
1596
1760
|
return json(r.ok
|
|
1597
1761
|
? { ok: true, agent: r.agent, pty: r.pty }
|
|
@@ -1606,6 +1770,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1606
1770
|
if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
|
|
1607
1771
|
let run: any;
|
|
1608
1772
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
1773
|
+
// A healed run (done by its agent, never approved) has no agent to continue: approving
|
|
1774
|
+
// it is /accept's record + finish, for any caller; a revise has nothing to send back to.
|
|
1775
|
+
if (run.healed === true && body.awaiting === "approvals.review") {
|
|
1776
|
+
if (body.why !== undefined) return bad("this run is already finished: approve or archive it", 409);
|
|
1777
|
+
const why = recordAcceptance(dir, id, "board");
|
|
1778
|
+
if (why) return bad(why, 409);
|
|
1779
|
+
finishRun(dir, id);
|
|
1780
|
+
changed();
|
|
1781
|
+
return json({ ok: true });
|
|
1782
|
+
}
|
|
1609
1783
|
if (!canApproveAwaiting(run.awaiting) || run.awaiting !== body.awaiting) return bad("this run is not waiting on that approval", 409);
|
|
1610
1784
|
if (run.awaiting === "findings" && body.why !== undefined) return bad("open findings can only be approved as-is or fixed individually", 409);
|
|
1611
1785
|
if (body.why !== undefined && !String(body.why).trim()) return bad("a revise needs a comment");
|
|
@@ -1619,12 +1793,34 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1619
1793
|
const before = Date.now();
|
|
1620
1794
|
const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
|
|
1621
1795
|
if (r.ok) closeSessions(dir, id, { before });
|
|
1796
|
+
// The plan's approval starts the build; fixing open findings is the review stage again.
|
|
1797
|
+
if (r.ok) markStage(dir, id, run.awaiting === "approvals.plan" ? "impl" : run.awaiting === "findings" ? "review" : "", r.pty);
|
|
1798
|
+
// Approving the review as-is is the user's acceptance, on record before the
|
|
1799
|
+
// agent marks the run done; a revise is not.
|
|
1800
|
+
if (r.ok && body.why === undefined && (run.awaiting === "approvals.review" || run.awaiting === "findings")) recordAcceptance(dir, id, "board");
|
|
1622
1801
|
changed();
|
|
1623
1802
|
return json(r.ok
|
|
1624
1803
|
? { ok: true, agent: r.agent, pty: r.pty }
|
|
1625
1804
|
: { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
|
|
1626
1805
|
}
|
|
1627
1806
|
|
|
1807
|
+
// Approve a run an agent marked done without the user's acceptance (healed): the line
|
|
1808
|
+
// only, no agent is started.
|
|
1809
|
+
if (path === "/accept") {
|
|
1810
|
+
const id = String(body.id ?? "");
|
|
1811
|
+
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
1812
|
+
if (gateOf(dir, id) !== "needs") return bad("this run is not waiting on your approval", 409);
|
|
1813
|
+
// Only a finished-but-unapproved run: a genuine review goes through /decide.
|
|
1814
|
+
let st: any = {};
|
|
1815
|
+
try { st = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch {}
|
|
1816
|
+
if (st.stage !== "done" && st.healed !== true) return bad("this run is in review: approve it with the review's Approve", 409);
|
|
1817
|
+
const why = recordAcceptance(dir, id, "board");
|
|
1818
|
+
if (why) return bad(why, 409);
|
|
1819
|
+
finishRun(dir, id);
|
|
1820
|
+
changed();
|
|
1821
|
+
return json({ ok: true });
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1628
1824
|
// Start a run's agent again after it ended mid-stage (resumeRun).
|
|
1629
1825
|
if (path === "/resume") {
|
|
1630
1826
|
const id = String(body.id ?? "");
|
|
@@ -1660,22 +1856,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1660
1856
|
}); }
|
|
1661
1857
|
|
|
1662
1858
|
// Read once and removed first, so a board that fails to start one does not retry it
|
|
1663
|
-
// forever. A list older than an hour is from an upgrade whose board never came
|
|
1664
|
-
// (a failed Windows hand-off): too late to pick its runs up unasked.
|
|
1859
|
+
// forever. A stop's list older than an hour is from an upgrade whose board never came
|
|
1860
|
+
// back (a failed Windows hand-off): too late to pick its runs up unasked. A crash's
|
|
1861
|
+
// list is current to the last few seconds of the board that wrote it, however old.
|
|
1862
|
+
// Every agent starts again in its card, never in a window: a board set to open
|
|
1863
|
+
// terminals leaves those runs on their Resume button.
|
|
1665
1864
|
if (existsSync(RESUME_LIST)) {
|
|
1666
|
-
let saved: { at?: number;
|
|
1865
|
+
let saved: { at?: number; crash?: boolean; list?: Live[] } = {};
|
|
1667
1866
|
try { saved = JSON.parse(readText(RESUME_LIST)); } catch { /* unreadable: nothing to resume */ }
|
|
1668
1867
|
rmSync(RESUME_LIST, { force: true });
|
|
1669
1868
|
const done = new Set<string>();
|
|
1670
|
-
for (const { dir, key, run } of Date.now() - (saved.at ?? 0) < 3600_000 ? saved.list ?? [] : []) {
|
|
1869
|
+
for (const { dir, key, run, tmux, resumed } of saved.crash || Date.now() - (saved.at ?? 0) < 3600_000 ? saved.list ?? [] : []) {
|
|
1870
|
+
// Kept in tmux and still there: the same agent, mid-step, shown in its card again.
|
|
1871
|
+
if (tmux && tmuxAlive(tmux)) {
|
|
1872
|
+
try {
|
|
1873
|
+
startPty(key, [], projectOf(dir), join(dir, "sessions", `${key}.pid`), changed, { tmux, attach: true });
|
|
1874
|
+
console.log(` reattached ${run ?? key}`);
|
|
1875
|
+
continue;
|
|
1876
|
+
} catch { /* started again below */ }
|
|
1877
|
+
}
|
|
1671
1878
|
const s = run ? null : readSessions(dir).find((x) => x.key === key);
|
|
1672
1879
|
const id = run ?? (s ? ownerOf(dir, s) : null);
|
|
1673
1880
|
if (!id || done.has(`${dir}\0${id}`)) continue;
|
|
1674
1881
|
done.add(`${dir}\0${id}`);
|
|
1882
|
+
if (saved.crash && resumed && Date.now() - resumed < CRASH_AGAIN_MS) { console.log(` not resuming ${id}: the board died again right after resuming it`); continue; }
|
|
1883
|
+
if (launchMode(projectOf(dir)) !== "card") continue;
|
|
1675
1884
|
const r = resumeRun(dir, id);
|
|
1885
|
+
if (saved.crash && "pty" in r && r.pty) autoResumed.set(r.pty, Date.now());
|
|
1676
1886
|
console.log(` ${"error" in r || !r.ok ? "could not resume" : "resumed"} ${id}${"error" in r ? ` (${r.error})` : !r.ok ? ` (${r.why})` : ""}`);
|
|
1677
1887
|
}
|
|
1678
1888
|
}
|
|
1889
|
+
// Last screens nothing picked up: a run left on its Resume button keeps its own a day.
|
|
1890
|
+
try { for (const f of readdirSync(TAILS)) if (Date.now() - statSync(join(TAILS, f)).mtimeMs > 86_400_000) rmSync(join(TAILS, f), { force: true }); } catch { /* no folder yet */ }
|
|
1679
1891
|
|
|
1680
1892
|
const url = `http://127.0.0.1:${server.port}/`;
|
|
1681
1893
|
console.log(`\n kaizen web ${url}`);
|
|
@@ -1684,7 +1896,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1684
1896
|
if (opts.open !== false) await openApp(url);
|
|
1685
1897
|
|
|
1686
1898
|
await new Promise<void>((resolve) => {
|
|
1687
|
-
|
|
1899
|
+
// The card agents are listed for the next board and ended (saveLive); the short wait
|
|
1900
|
+
// lets each take its /exit, or be ended with what it started, before this process goes.
|
|
1901
|
+
const stop = () => {
|
|
1902
|
+
const live = ptyKeys().some((k) => ptyState(k)?.alive);
|
|
1903
|
+
saveLive();
|
|
1904
|
+
clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(loop); clearInterval(keepList);
|
|
1905
|
+
for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
|
|
1906
|
+
setTimeout(() => { server.stop(true); resolve(); }, live ? 400 : 0);
|
|
1907
|
+
};
|
|
1688
1908
|
process.on("SIGINT", stop);
|
|
1689
1909
|
process.on("SIGTERM", stop);
|
|
1690
1910
|
});
|