kaizen-agent 1.69.1 → 1.71.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/README.md +2 -2
- package/cli/annotate-proxy.ts +135 -0
- package/cli/annotate.ts +86 -0
- package/cli/automations.ts +10 -3
- package/cli/browser.ts +1 -1
- package/cli/chat.ts +9 -1
- package/cli/chatgpt.ts +2 -1
- package/cli/docs.ts +1 -1
- package/cli/google.ts +2 -1
- package/cli/handoff.ts +1 -1
- package/cli/install.ts +28 -8
- package/cli/knowledge.ts +1 -1
- package/cli/notes.ts +10 -1
- package/cli/pty.ts +21 -0
- package/cli/settings.ts +5 -1
- package/cli/sources.ts +3 -2
- package/cli/state.ts +43 -5
- package/cli/versions.ts +1 -1
- package/cli/video.ts +1 -1
- package/cli/web.ts +137 -35
- package/cli/workers.ts +20 -7
- package/cli/worktree.ts +55 -15
- package/package.json +1 -1
- package/skills/kaizen/SKILL.md +12 -8
- package/skills/kaizen/config.default.yml +18 -2
- package/skills/kaizen/settings.md +3 -1
- package/skills/kaizen/spec-build.md +13 -2
- package/skills/kaizen/spec-main.md +2 -0
- package/skills/kaizen-help/SKILL.md +1 -0
- package/skills/media/kaizen-game/SKILL.md +96 -0
- package/skills/media/kaizen-game/assets/gdd.css +12 -0
- package/skills/media/kaizen-game/references/build.md +81 -0
- package/skills/media/kaizen-game/references/content.md +32 -0
- package/skills/media/kaizen-game/references/design.md +81 -0
- package/skills/media/kaizen-game/references/ship.md +34 -0
- package/skills/media/kaizen-game/references/verify.md +33 -0
- package/skills/media/kaizen-game/scripts/check.sh +13 -0
- package/skills/media/kaizen-game/scripts/frames.mjs +34 -0
- package/skills/media/kaizen-game/scripts/gdd-pdf.mjs +19 -0
- package/skills/media/kaizen-game/scripts/pw.mjs +18 -0
- package/skills/media/kaizen-game/scripts/serve.mjs +53 -0
- package/skills/media/kaizen-game/scripts/serve.test.mjs +18 -0
- package/skills/media/kaizen-game/scripts/setup.sh +9 -0
- package/skills/media/kaizen-game/scripts/smoke.mjs +40 -0
- package/skills/media/kaizen-game/skill.json +1 -0
- package/web/annotate.js +382 -0
- package/web/board/annotate-lib.ts +15 -0
- package/web/board/annotate.ts +181 -0
- package/web/board/badge.ts +12 -0
- package/web/board/icebox.ts +6 -3
- package/web/board/markdown.ts +7 -2
- package/web/board/run-view.ts +83 -9
- package/web/board/settings-orchestration.ts +1 -1
- package/web/board/settings-pages.ts +1 -0
- package/web/board/settings-skills.ts +1 -0
- package/web/board/settings.ts +2 -2
- package/web/board.html +5 -3
- package/web/board.js +119 -119
- package/web/notebook.js +23 -23
- package/web/term.js +48 -48
- package/web/term.ts +16 -4
- package/web/video.js +25 -25
package/cli/state.ts
CHANGED
|
@@ -129,6 +129,39 @@ export function agentFlags(projectDir: string, cmd: string, configText?: string,
|
|
|
129
129
|
];
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
+
// subagents.<key> through the config chain, project first. inherit, default and empty
|
|
133
|
+
// count as unset, so they fall through to the next file.
|
|
134
|
+
function subagentSetting(projectDir: string, key: string): string | null {
|
|
135
|
+
const re = new RegExp(`^subagents:\\n(?:[ \\t#][^\\n]*\\n|\\n)*?[ \\t]+${key}:[ \\t]*["']?([^"'\\s#]*)`, "m");
|
|
136
|
+
for (const t of configTexts(projectDir)) {
|
|
137
|
+
const v = re.exec(t)?.[1];
|
|
138
|
+
if (v && v !== "inherit" && v !== "default") return v;
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export type SubagentStage = "planner" | "builder" | "reviewer";
|
|
144
|
+
export const SUBAGENT_STAGES: SubagentStage[] = ["planner", "builder", "reviewer"];
|
|
145
|
+
|
|
146
|
+
// The model a Claude Code stage subagent runs on: its own subagents.<stage>, else
|
|
147
|
+
// subagents.model. Null: inherit the session's.
|
|
148
|
+
export function subagentModel(projectDir: string, stage?: SubagentStage): string | null {
|
|
149
|
+
const v = (stage && subagentSetting(projectDir, stage)) || subagentSetting(projectDir, "model");
|
|
150
|
+
return v && plainModel(v) ? v : null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// What a Claude Code launch carries so its subagents get subagents.model and .effort
|
|
154
|
+
// even when the agent forgets to pass them. Claude Code reads these as defaults: a model
|
|
155
|
+
// on the Agent call, or a model:/effort: line in the agent file, still wins.
|
|
156
|
+
export function subagentEnv(projectDir: string, cmd: string): string[] {
|
|
157
|
+
if (cmd !== "claude") return [];
|
|
158
|
+
const m = subagentModel(projectDir), e = subagentSetting(projectDir, "effort");
|
|
159
|
+
return [
|
|
160
|
+
...(m ? [`CLAUDE_CODE_SUBAGENT_MODEL=${m}`] : []),
|
|
161
|
+
...(e && /^(low|medium|high|xhigh|max)$/.test(e) ? [`CLAUDE_CODE_SUBAGENT_EFFORT=${e}`] : []),
|
|
162
|
+
];
|
|
163
|
+
}
|
|
164
|
+
|
|
132
165
|
// What the board's Run form offers: the installed tools, the one it would pick, and
|
|
133
166
|
// each one's configured model to start the field from.
|
|
134
167
|
export function agentChoices(projectDir: string) {
|
|
@@ -1580,7 +1613,7 @@ function isSession(pid: number, s: Session): boolean | null {
|
|
|
1580
1613
|
}
|
|
1581
1614
|
const ps = onPath("ps");
|
|
1582
1615
|
if (!ps) return null;
|
|
1583
|
-
const m = /^\s*(\S+)\s+(.*)$/.exec(Bun.spawnSync([ps, "-o", "etime=,args=", "-p", String(pid)], { stdin: "ignore", timeout: 5000 }).stdout.toString().trim());
|
|
1616
|
+
const m = /^\s*(\S+)\s+(.*)$/.exec(Bun.spawnSync([ps, "-o", "etime=,args=", "-p", String(pid)], { stdin: "ignore", timeout: 5000, windowsHide: true }).stdout.toString().trim());
|
|
1584
1617
|
if (!m) return null;
|
|
1585
1618
|
// etime is [[dd-]hh:]mm:ss
|
|
1586
1619
|
const [d, rest] = m[1].includes("-") ? m[1].split("-") : ["0", m[1]];
|
|
@@ -1753,15 +1786,18 @@ export function sessionLaunch(projectDir: string, cmd: string, base: string[], p
|
|
|
1753
1786
|
// time, in Claude's own config. Best effort: any failure just means Claude asks.
|
|
1754
1787
|
export function trustFolder(dir: string, cfg = join(process.env.CLAUDE_CONFIG_DIR ?? homedir(), ".claude.json")) {
|
|
1755
1788
|
try {
|
|
1756
|
-
const top = Bun.spawnSync(["git", "-C", dir, "rev-parse", "--show-toplevel"], { stderr: "ignore" });
|
|
1789
|
+
const top = Bun.spawnSync(["git", "-C", dir, "rev-parse", "--show-toplevel"], { stderr: "ignore", windowsHide: true });
|
|
1757
1790
|
// Claude Code keys its projects with forward slashes on Windows, as git prints them.
|
|
1758
1791
|
const found = top.success ? top.stdout.toString().trim() || dir : dir;
|
|
1759
1792
|
const root = process.platform === "win32" ? found.replace(/\\/g, "/") : found;
|
|
1760
1793
|
const d = JSON.parse(readFileSync(cfg, "utf8"));
|
|
1761
1794
|
if (d.projects?.[root]?.hasTrustDialogAccepted) return;
|
|
1795
|
+
// A repo that brings its own hooks, MCP servers or settings is the case the dialog is for: let Claude ask.
|
|
1796
|
+
if ([".mcp.json", join(".claude", "settings.json"), join(".claude", "settings.local.json")].some((x) => existsSync(join(root, x)))) return;
|
|
1762
1797
|
d.projects ??= {};
|
|
1763
1798
|
d.projects[root] = { ...d.projects[root], hasTrustDialogAccepted: true };
|
|
1764
|
-
|
|
1799
|
+
// Keep the file's own mode: it holds account data, and a fresh .tmp would take the umask's.
|
|
1800
|
+
writeFileSync(cfg + ".tmp", JSON.stringify(d, null, 2), { mode: statSync(cfg).mode & 0o777 });
|
|
1765
1801
|
renameSync(cfg + ".tmp", cfg);
|
|
1766
1802
|
} catch { /* Claude asks as before */ }
|
|
1767
1803
|
}
|
|
@@ -1818,7 +1854,8 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1818
1854
|
const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? `${acct.envVar}=${shq(acct.dir)}` : "");
|
|
1819
1855
|
// Only what is started carries env: the returned `cmd` reaches the page.
|
|
1820
1856
|
// A run the board knows hears which one it is; a new run has no id yet and passes --run.
|
|
1821
|
-
const
|
|
1857
|
+
const vars = [...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...subagentEnv(projectDir, agent.cmd), ...accountEnv(acct)];
|
|
1858
|
+
const identity = vars.length && process.platform !== "win32" ? ["env", ...vars] : [];
|
|
1822
1859
|
const started = [...identity, ...withEnv(s.fullCmd, agent.cmd, prefs)];
|
|
1823
1860
|
const drop = () => { if (s.record) rmSync(s.record, { force: true }); };
|
|
1824
1861
|
|
|
@@ -1934,7 +1971,8 @@ export function gitStatus(projectDir: string): GitStatus {
|
|
|
1934
1971
|
// The path of a `git status --porcelain` line; for a rename, the new one.
|
|
1935
1972
|
// ponytail: only the surrounding quotes are undone, so a name git escapes (non-ASCII,
|
|
1936
1973
|
// a quote, a backslash) never matches a report; read `status -z` if that comes up.
|
|
1937
|
-
|
|
1974
|
+
// " -> " separates a rename or copy only; an untracked file may be named `a -> b`.
|
|
1975
|
+
const statusPath = (line: string) => (/[RC]/.test(line.slice(0, 2)) ? line.slice(3).split(" -> ").pop()! : line.slice(3)).replace(/^"|"$/g, "");
|
|
1938
1976
|
|
|
1939
1977
|
// What a run reported changing: 03-impl.md and its fix rounds, the parts of them that
|
|
1940
1978
|
// list changes (`named`), and when the newest of them was written.
|
package/cli/versions.ts
CHANGED
|
@@ -42,7 +42,7 @@ function writeStore(place: string, name: string, s: Store) {
|
|
|
42
42
|
// Returns { value } when it ran, null when another holder had the lock.
|
|
43
43
|
function locked<T>(place: string, name: string, fn: () => T): { value: T } | null {
|
|
44
44
|
const lock = join(place, "videos", name, ".versions.lock");
|
|
45
|
-
try { if (Date.now() - statSync(lock).mtimeMs > 60_000)
|
|
45
|
+
try { if (Date.now() - statSync(lock).mtimeMs > 60_000) { const aside = `${lock}.${process.pid}.stale`; renameSync(lock, aside); unlinkSync(aside); } } catch { /* none */ }
|
|
46
46
|
let fd: number;
|
|
47
47
|
try { fd = openSync(lock, "wx"); } catch { return null; }
|
|
48
48
|
try { return { value: fn() }; } finally { closeSync(fd); try { unlinkSync(lock); } catch { /* gone */ } }
|
package/cli/video.ts
CHANGED
|
@@ -63,7 +63,7 @@ function seconds(f: string): number | null {
|
|
|
63
63
|
let key: string;
|
|
64
64
|
try { key = `${f}:${statSync(f).mtimeMs}`; } catch { return null; }
|
|
65
65
|
if (!probed.has(key)) {
|
|
66
|
-
const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f], { encoding: "utf8" });
|
|
66
|
+
const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f], { encoding: "utf8", windowsHide: true });
|
|
67
67
|
const n = parseFloat(r.stdout ?? "");
|
|
68
68
|
probed.set(key, Number.isFinite(n) ? Math.round(n) : null);
|
|
69
69
|
}
|
package/cli/web.ts
CHANGED
|
@@ -16,10 +16,10 @@ import { readReport, signalOf } from "./report.ts";
|
|
|
16
16
|
import { MAX_IMAGE, saveImage } from "./term-image.ts";
|
|
17
17
|
import { bundledSkills, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
|
|
18
18
|
import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
|
|
19
|
-
import { agentLine, failStart, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
|
|
19
|
+
import { agentLine, failStart, handoffModel, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
|
|
20
20
|
import { childDied, childQuiet, markWoken, move, requestOpen, readHandoff, refused, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
|
|
21
21
|
import { processTable, storage, systemMemory, treeRss, type Root } from "./resources.ts";
|
|
22
|
-
import { attachPty, writePty, submitPty, resizePty, exitPty, killPty, panePid, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
|
|
22
|
+
import { attachPty, frames, writePty, submitPty, resizePty, exitPty, killPty, panePid, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
|
|
23
23
|
import { snapshot, snapWorker } from "./state-snap.ts";
|
|
24
24
|
import { claudeUsage, claudeUsageAt, codexUsage, codexUsageAt, phonePeers, type Usage } from "./usage.ts";
|
|
25
25
|
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";
|
|
@@ -28,6 +28,8 @@ import * as chatgpt from "./chatgpt.ts";
|
|
|
28
28
|
import * as google from "./google.ts";
|
|
29
29
|
import { writeBacks } from "./writeback.ts";
|
|
30
30
|
import { postLink, sendReply } from "./browser.ts";
|
|
31
|
+
import { openProxy, closeAllProxies } from "./annotate-proxy.ts";
|
|
32
|
+
import { parseNotes, line as annLine, markdown as annMarkdown, saveCrops, LEVELS, type Level } from "./annotate.ts";
|
|
31
33
|
import { tailnetName } from "./setup.ts";
|
|
32
34
|
import { connectPhone, loginUrl, readPhone } from "./phone-setup.ts";
|
|
33
35
|
import { listNotes, saveNote, renameNote, deleteNote, boardIndex, linksTo } from "./notes.ts";
|
|
@@ -59,7 +61,7 @@ const VIDEO_JS = join(dirname(import.meta.dir), "web", "video.js");
|
|
|
59
61
|
const DEFAULT_PORT = 7420;
|
|
60
62
|
// Gathered posts a reply is going out to right now: one send per item at a time.
|
|
61
63
|
const replying = new Set<string>();
|
|
62
|
-
type PtySock = { key: string; detach: (() => void) | null };
|
|
64
|
+
type PtySock = { key: string; detach: (() => void) | null; out?: ReturnType<typeof frames> };
|
|
63
65
|
// Read once at start: a board keeps the code it started with, so this is what it
|
|
64
66
|
// runs, not what is installed now. `/` sends it; `current()` compares the two.
|
|
65
67
|
const installed = () => {
|
|
@@ -285,7 +287,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
285
287
|
const sameOrigin = (req: Request) => {
|
|
286
288
|
const origin = req.headers.get("origin");
|
|
287
289
|
let same = !origin;
|
|
288
|
-
try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host")
|
|
290
|
+
try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host"); } } catch { /* bad origin */ }
|
|
289
291
|
return same;
|
|
290
292
|
};
|
|
291
293
|
// One-time token for turning an off-by-default skill on; each GET /skills mints a new one. It stops
|
|
@@ -303,6 +305,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
303
305
|
// Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
|
|
304
306
|
const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; ws?: string; pid?: number }>();
|
|
305
307
|
const SHELL_CAP = 8;
|
|
308
|
+
// The argv each of those started with, kept off the page's copy: saveLive writes it so the next board can start them again.
|
|
309
|
+
const shellCmd = new Map<string, string[]>();
|
|
306
310
|
// A terminal shows where its live run builds, not where it launched: tabs follow `run`, the rail `ws`.
|
|
307
311
|
const shown = <S extends { key: string; dir: string; run: string; ws?: string }>(x: S): S => {
|
|
308
312
|
const w = linkedWs(x.dir, x.key), project = projectOf(x.dir);
|
|
@@ -394,9 +398,11 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
394
398
|
const written = new Map<string, number>();
|
|
395
399
|
const owners = new Map<string, { dir: string; run: string | null }>(), unrecorded = new Set<string>();
|
|
396
400
|
let stopping = false, lastList = "";
|
|
401
|
+
const sidOf = new Map<string, string>();
|
|
397
402
|
const saveLive = (crash = false) => {
|
|
398
403
|
if (stopping) return;
|
|
399
404
|
const live = new Set(ptyKeys().filter((k) => ptyState(k)?.alive));
|
|
405
|
+
for (const k of sidOf.keys()) if (!live.has(k)) sidOf.delete(k);
|
|
400
406
|
if (!live.size) {
|
|
401
407
|
if (crash && lastList) { rmSync(RESUME_LIST, { force: true }); lastList = ""; }
|
|
402
408
|
return;
|
|
@@ -417,14 +423,22 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
417
423
|
const o = owners.get(key);
|
|
418
424
|
return o ? [{ dir: o.dir, key, run: o.run, ...(ptyTmux(key) ? { tmux: ptyTmux(key)! } : {}), ...(autoResumed.has(key) ? { resumed: autoResumed.get(key) } : {}) }] : [];
|
|
419
425
|
});
|
|
426
|
+
// Terminals and agents the board's own + menu started (no run owns them): started again by their argv, a Claude
|
|
427
|
+
// agent with its conversation (--resume). The session id is kept per key, as Claude drops its file on /exit.
|
|
428
|
+
const shellList = [...shells.values()].flatMap((x) => {
|
|
429
|
+
const cmd = shellCmd.get(x.key), st = ptyState(x.key);
|
|
430
|
+
if (!cmd || !st?.alive || !x.ws) return [];
|
|
431
|
+
if (x.agent === "claude" && st.pid && !sidOf.has(x.key)) { const sid = claudeSid(st.pid); if (sid) sidOf.set(x.key, sid); }
|
|
432
|
+
return [{ dir: x.dir, title: x.title, agent: x.agent, run: x.run, ws: x.ws, cmd, sid: sidOf.get(x.key), key: x.key }];
|
|
433
|
+
});
|
|
420
434
|
try {
|
|
421
435
|
mkdirSync(TAILS, { recursive: true });
|
|
422
436
|
for (const { key } of list) {
|
|
423
437
|
const total = ptyState(key)!.total, t = written.get(key) === total ? null : ptyTail(key);
|
|
424
438
|
if (t) { writeFileSync(tailOf(key), t); written.set(key, total); }
|
|
425
439
|
}
|
|
426
|
-
const body = JSON.stringify(list);
|
|
427
|
-
if (!crash || body !== lastList) writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), crash, list }));
|
|
440
|
+
const body = JSON.stringify([list, shellList]);
|
|
441
|
+
if (!crash || body !== lastList) writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), crash, list, shells: shellList }));
|
|
428
442
|
lastList = body;
|
|
429
443
|
} catch { /* nothing resumes; the card offers Resume */ }
|
|
430
444
|
if (crash) return;
|
|
@@ -488,7 +502,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
488
502
|
const cwd = codeDir(project, id), key = "sh-" + crypto.randomUUID().slice(0, 8);
|
|
489
503
|
const prompt = `/kaizen run ${id}. You are the worktree agent of this run: the project is ${project}, its run files are in ${join(dir, "runs", id)}, and you work in ${cwd}. ` +
|
|
490
504
|
`Build, review and run the fix loop as the spec says. Do not run kaizen done or land. When finished run: kaizen handoff done. If you cannot go on run: kaizen handoff blocked "<reason>".`;
|
|
491
|
-
const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own");
|
|
505
|
+
const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own", undefined, handoffModel(project, id));
|
|
492
506
|
if (typeof l === "string") { refused(dir, id, l); changed(); return; }
|
|
493
507
|
if (!started(dir, id, key)) return; // declined meanwhile: the first agent is building
|
|
494
508
|
for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
|
|
@@ -681,7 +695,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
681
695
|
// {t:"i",d} and {t:"r",c,r}. A null from the session means the agent ended.
|
|
682
696
|
websocket: {
|
|
683
697
|
open(ws: Bun.ServerWebSocket<PtySock>) {
|
|
684
|
-
|
|
698
|
+
const out = (ws.data.out = frames((d) => ws.send(d)));
|
|
699
|
+
ws.data.detach = attachPty(ws.data.key, (d) => { if (d === null) { out.flush(); ws.close(1000, "ended"); } else out.push(d); });
|
|
685
700
|
},
|
|
686
701
|
message(ws: Bun.ServerWebSocket<PtySock>, raw) {
|
|
687
702
|
let m: any;
|
|
@@ -689,13 +704,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
689
704
|
if (m?.t === "i" && typeof m.d === "string") writePty(ws.data.key, m.d);
|
|
690
705
|
else if (m?.t === "r") resizePty(ws.data.key, Number(m.c), Number(m.r));
|
|
691
706
|
},
|
|
692
|
-
close(ws: Bun.ServerWebSocket<PtySock>) { ws.data.detach?.(); },
|
|
707
|
+
close(ws: Bun.ServerWebSocket<PtySock>) { ws.data.detach?.(); ws.data.out?.stop(); },
|
|
693
708
|
},
|
|
694
709
|
async fetch(req, srv) {
|
|
695
710
|
// Host first: a hostname rebound to 127.0.0.1 by an attacker's DNS still
|
|
696
711
|
// arrives with that hostname in Host, and gets nothing.
|
|
697
712
|
const hostname = (req.headers.get("host") ?? "").toLowerCase().replace(/:\d+$/, "");
|
|
698
713
|
if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
|
|
714
|
+
// `tailscale serve` stamps every tailnet request with the caller's login; `tailscale funnel` (the
|
|
715
|
+
// public internet) does not. A tailnet name reached without it is not a tailnet peer.
|
|
716
|
+
if (hostname.endsWith(".ts.net") && !req.headers.get("tailscale-user-login")) return new Response("forbidden", { status: 403 });
|
|
699
717
|
if (req.method !== "GET") { stateGen++; gitGen++; }
|
|
700
718
|
const url = new URL(req.url);
|
|
701
719
|
const path = url.pathname;
|
|
@@ -747,7 +765,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
747
765
|
// board when no window shows it) and close the popup. Hyprland moves windows;
|
|
748
766
|
// elsewhere only the popup opens and closes.
|
|
749
767
|
if (req.method === "POST" && (path === "/popup/open" || path === "/popup/board")) {
|
|
768
|
+
const refused = strict(req);
|
|
769
|
+
if (refused) return refused;
|
|
750
770
|
const body = await req.json().catch(() => ({}));
|
|
771
|
+
if (body?.id != null && !/^(?!\.+$)[\w.-]+$/.test(String(body.id))) return bad("bad id");
|
|
751
772
|
const chat = (...a: string[]) => Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "chat", "--port", String(new URL(req.url).port || DEFAULT_PORT), ...a], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exited;
|
|
752
773
|
const hypr = !!process.env.HYPRLAND_INSTANCE_SIGNATURE && !!Bun.which("hyprctl");
|
|
753
774
|
const json = async (cmd: string) => await Bun.$`hyprctl ${cmd} -j`.quiet().nothrow().json().catch(() => null);
|
|
@@ -764,7 +785,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
764
785
|
if ((await Bun.$`hyprctl dispatch ${lua}`.quiet().nothrow().text()).trim() !== "ok") await Bun.$`hyprctl dispatch ${legacy}`.quiet().nothrow();
|
|
765
786
|
};
|
|
766
787
|
if (path === "/popup/open") {
|
|
767
|
-
const id = typeof body.id === "string" && /^[\w.-]+$/.test(body.id) ? body.id : "";
|
|
788
|
+
const id = typeof body.id === "string" && /^(?!\.+$)[\w.-]+$/.test(body.id) ? body.id : "";
|
|
768
789
|
await chat("--show", ...(id ? ["--chat", id] : []));
|
|
769
790
|
if (w) await dispatch(`hl.dsp.window.move({ workspace = "special:kaizen", follow = false, window = "${w}" })`, ["movetoworkspacesilent", `special:kaizen,${w}`]);
|
|
770
791
|
// Typing goes to the popup, not to whatever was under the hidden board.
|
|
@@ -893,7 +914,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
893
914
|
if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
|
|
894
915
|
if (!/^image\//i.test(req.headers.get("content-type") ?? "")) return bad("image body expected", 415);
|
|
895
916
|
if (Number(req.headers.get("content-length") ?? 0) > MAX_IMAGE) return bad("image too large", 413);
|
|
896
|
-
const
|
|
917
|
+
const bytes = new Uint8Array(await req.arrayBuffer());
|
|
918
|
+
if (bytes.length > MAX_IMAGE) return bad("image too large", 413); // a chunked body has no content-length
|
|
919
|
+
const saved = saveImage(bytes);
|
|
897
920
|
return saved ? json({ path: saved }) : bad("not an image", 415);
|
|
898
921
|
}
|
|
899
922
|
if (req.method === "POST" && path === "/shell") {
|
|
@@ -978,6 +1001,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
978
1001
|
const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key, ...(dev ? { __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: ".ts.net" } : {}) } });
|
|
979
1002
|
// The run workspace that opened it (its card key), so each run keeps its own centre.
|
|
980
1003
|
shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
|
|
1004
|
+
shellCmd.set(key, cmd);
|
|
981
1005
|
changed();
|
|
982
1006
|
return json(shells.get(key));
|
|
983
1007
|
}
|
|
@@ -1189,6 +1213,43 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1189
1213
|
} catch { return json({ frameable: null }); }
|
|
1190
1214
|
}
|
|
1191
1215
|
|
|
1216
|
+
// The annotator (cli/annotate.ts, cli/annotate-proxy.ts): open a loopback page through the proxy that adds
|
|
1217
|
+
// the annotator script, turn notes into text for Copy, or type them into the run's agent.
|
|
1218
|
+
if (req.method === "POST" && path === "/annotate/open") {
|
|
1219
|
+
const refused = strict(req);
|
|
1220
|
+
if (refused) return refused;
|
|
1221
|
+
let body: any;
|
|
1222
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1223
|
+
let u: URL;
|
|
1224
|
+
try { u = new URL(String(body.url ?? "")); } catch { return bad("not a url"); }
|
|
1225
|
+
if (!/^https?:$/.test(u.protocol) || !isLoopback(u)) return bad("only a localhost address", 400);
|
|
1226
|
+
// Not the board itself: a proxy to it would forward /pty with an Origin rewritten to the board's own.
|
|
1227
|
+
if (u.port === (new URL(req.url).port || "80")) return bad("that is the board's own port", 400);
|
|
1228
|
+
try {
|
|
1229
|
+
const px = openProxy(u);
|
|
1230
|
+
return json({ ok: true, origin: px.origin, token: px.token, url: px.origin + u.pathname + u.search + u.hash });
|
|
1231
|
+
} catch (e) { return bad((e as Error).message, 500); }
|
|
1232
|
+
}
|
|
1233
|
+
if (req.method === "POST" && (path === "/annotate/format" || path === "/annotate/send")) {
|
|
1234
|
+
const refused = strict(req);
|
|
1235
|
+
if (refused) return refused;
|
|
1236
|
+
let body: any;
|
|
1237
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1238
|
+
const level = (LEVELS as readonly string[]).includes(body.level) ? (body.level as Level) : "standard";
|
|
1239
|
+
const comps = body.components !== false;
|
|
1240
|
+
const notes = parseNotes(body.notes);
|
|
1241
|
+
if (!notes.length) return bad("no notes to use", 400);
|
|
1242
|
+
if (path === "/annotate/format") return json({ ok: true, text: annMarkdown(notes, level, comps) });
|
|
1243
|
+
const dir = canonState(String(body.dir ?? ""));
|
|
1244
|
+
const id = String(body.id ?? "");
|
|
1245
|
+
if (!states(true).includes(dir) || dir === join(home, ".kaizen") || !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("choose a run", 404);
|
|
1246
|
+
const live = liveAgent(dir, id);
|
|
1247
|
+
if (!live) return bad("this run has no agent open to send to", 409);
|
|
1248
|
+
const crops = saveCrops(dir, id, notes);
|
|
1249
|
+
submitPty(live.key, annLine(notes, level, comps, crops));
|
|
1250
|
+
return json({ ok: true, sent: notes.length, crops: crops.filter(Boolean).length });
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1192
1253
|
// The footer: each installed agent's plan usage (cached a minute, ?refresh=1 asks
|
|
1193
1254
|
// again) and whether a phone is on the tailnet.
|
|
1194
1255
|
if (req.method === "GET" && path === "/usage") {
|
|
@@ -1382,7 +1443,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1382
1443
|
if (req.method === "GET" && path.startsWith("/run/")) {
|
|
1383
1444
|
const id = decodeURIComponent(path.slice(5));
|
|
1384
1445
|
const dir = qdir() ?? state;
|
|
1385
|
-
if (!dir || !states(true).includes(dir) || !/^[\w.-]+$/.test(id)) return bad("no such run", 404);
|
|
1446
|
+
if (!dir || !states(true).includes(dir) || !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("no such run", 404);
|
|
1386
1447
|
const base = join(dir, "runs", id);
|
|
1387
1448
|
if (!existsSync(base)) return bad("no such run", 404);
|
|
1388
1449
|
const read = (f: string) => existsSync(join(base, f)) ? readText(join(base, f)) : null;
|
|
@@ -1752,11 +1813,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1752
1813
|
const dir = qdir() ?? state;
|
|
1753
1814
|
const p = url.searchParams.get("p") ?? "";
|
|
1754
1815
|
if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
1755
|
-
if (!/^(runs\/[\w.-]+\/)?attachments\/[\w.-]+$/.test(p)) return bad("bad path");
|
|
1816
|
+
if (!/^(runs\/[\w.-]+\/)?attachments\/(?!\.+$)[\w.-]+$/.test(p)) return bad("bad path");
|
|
1756
1817
|
const f = join(dir, p);
|
|
1757
1818
|
if (!existsSync(f)) return bad("no such file", 404);
|
|
1758
1819
|
// no-cache: a revise retakes a screenshot under the same name, and the browser must ask again.
|
|
1759
|
-
|
|
1820
|
+
// sandbox + nosniff: an attached .html/.svg opened directly must run nothing on the board origin.
|
|
1821
|
+
return new Response(Bun.file(f), { headers: { "cache-control": "private, no-cache", "content-security-policy": "sandbox", "x-content-type-options": "nosniff" } });
|
|
1760
1822
|
}
|
|
1761
1823
|
|
|
1762
1824
|
// An icebox image, sent on to a link read fresh from its source: the one kept
|
|
@@ -1793,13 +1855,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1793
1855
|
return c ? json({ ...c, busy: chatBusy(base, c.id) }) : bad("no such chat", 404);
|
|
1794
1856
|
}
|
|
1795
1857
|
if (req.method !== "POST") return bad("method not allowed", 405);
|
|
1796
|
-
|
|
1858
|
+
// sameOrigin, not local(): a multipart form is a simple request any page can send, and a chat starts an agent.
|
|
1859
|
+
if (!sameOrigin(req)) return bad("cross-origin write refused", 403);
|
|
1797
1860
|
let body: any;
|
|
1798
1861
|
let uploads: ChatUpload[] = [];
|
|
1799
1862
|
if (path === "/chat" && req.headers.get("content-type")?.startsWith("multipart/form-data")) {
|
|
1800
1863
|
if (Number(req.headers.get("content-length")) > 320 * 1024 * 1024) return bad("attachments too large", 413);
|
|
1801
1864
|
let form: FormData;
|
|
1802
|
-
try { form = await req.formData(); } catch { return bad("form data expected"); }
|
|
1865
|
+
try { form = await req.formData(); } catch { return bad("form data expected"); } // the per-file and total caps below also cover a chunked body
|
|
1803
1866
|
const files = form.getAll("files");
|
|
1804
1867
|
if (files.length > 20 || files.some((f) => !(f instanceof File) || f.size > 100 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 300 * 1024 * 1024) return bad("up to 20 files, 100 MB each and 300 MB total", 413);
|
|
1805
1868
|
body = { id: form.get("id"), text: form.get("text") ?? "", project: form.get("project") };
|
|
@@ -1849,7 +1912,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1849
1912
|
}
|
|
1850
1913
|
|
|
1851
1914
|
if (req.method === "POST") {
|
|
1852
|
-
|
|
1915
|
+
// strict, not local(): this block starts agents (/run yolo, /fix, /shell-like ops), so a
|
|
1916
|
+
// page on another local port or a text/plain no-cors POST must not reach it.
|
|
1917
|
+
const refused = strict(req);
|
|
1918
|
+
if (refused) return refused;
|
|
1853
1919
|
let body: any;
|
|
1854
1920
|
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1855
1921
|
for (const k of ["dir", "to"]) if (typeof body?.[k] === "string" && body[k]) body[k] = canonState(body[k]);
|
|
@@ -2158,7 +2224,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2158
2224
|
if (path === "/archive") {
|
|
2159
2225
|
const archived = body.archived !== false;
|
|
2160
2226
|
if (typeof body.id === "string") {
|
|
2161
|
-
if (!/^[\w.-]+$/.test(body.id)) return bad("bad run id");
|
|
2227
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(body.id)) return bad("bad run id");
|
|
2162
2228
|
setArchived(dir, body.id, archived);
|
|
2163
2229
|
} else if (typeof body.text === "string") {
|
|
2164
2230
|
const text = body.text.trim();
|
|
@@ -2176,7 +2242,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2176
2242
|
// from the message so the note carries its own attachments.
|
|
2177
2243
|
if (path === "/note") {
|
|
2178
2244
|
const id = typeof body.id === "string" ? body.id : null;
|
|
2179
|
-
if (id !== null && !/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2245
|
+
if (id !== null && !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2246
|
+
if (id !== null && !existsSync(join(dir, "runs", id, "state.json"))) return bad("no such run", 404); // no attachments folder for a run that is not there
|
|
2180
2247
|
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
2181
2248
|
const files: { name: string; data: string }[] = Array.isArray(body.files) ? body.files : [];
|
|
2182
2249
|
let total = 0;
|
|
@@ -2195,7 +2262,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2195
2262
|
|
|
2196
2263
|
if (path === "/notes") {
|
|
2197
2264
|
const id = String(body.id ?? "");
|
|
2198
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2265
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2199
2266
|
const failed = writeNotes(dir, id, String(body.text ?? ""));
|
|
2200
2267
|
changed();
|
|
2201
2268
|
return failed ? bad(failed, 404) : json({ ok: true });
|
|
@@ -2220,7 +2287,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2220
2287
|
// global state dir: $HOME may be a repository, and it is not the run's project.
|
|
2221
2288
|
if (path === "/commit") {
|
|
2222
2289
|
const id = String(body.id ?? "");
|
|
2223
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2290
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2224
2291
|
if (dir === join(home, ".kaizen")) return bad("no project to commit", 409);
|
|
2225
2292
|
let run: any;
|
|
2226
2293
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
@@ -2236,7 +2303,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2236
2303
|
// takes and only on the run's own files (stageFiles refuses any other path).
|
|
2237
2304
|
if (path === "/stage") {
|
|
2238
2305
|
const id = String(body.id ?? "");
|
|
2239
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2306
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2240
2307
|
if (dir === join(home, ".kaizen")) return bad("no project", 409);
|
|
2241
2308
|
let run: any;
|
|
2242
2309
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
@@ -2251,7 +2318,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2251
2318
|
// The sparkle button: a commit message for the run's files, written from their diff.
|
|
2252
2319
|
if (path === "/commit-message") {
|
|
2253
2320
|
const id = String(body.id ?? "");
|
|
2254
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2321
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2255
2322
|
if (dir === join(home, ".kaizen")) return bad("no project", 409);
|
|
2256
2323
|
const r = await suggestMessage(dir, id);
|
|
2257
2324
|
return r.ok ? json(r) : bad(r.why, 409);
|
|
@@ -2261,7 +2328,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2261
2328
|
// request, merge it, then remove the worktree once its work is on the base.
|
|
2262
2329
|
if (path === "/pr") {
|
|
2263
2330
|
const id = String(body.id ?? "");
|
|
2264
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2331
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2265
2332
|
// One step per run at a time: a second tab's Merge or Remove waits its turn.
|
|
2266
2333
|
const lock = `${dir}\0${id}`;
|
|
2267
2334
|
if (prBusy.has(lock)) return bad("Another git step is running on this run. Try again when it finishes.", 409);
|
|
@@ -2288,7 +2355,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2288
2355
|
// not there. Only numbers the review itself holds reach the prompt.
|
|
2289
2356
|
if (path === "/fix") {
|
|
2290
2357
|
const id = String(body.id ?? "");
|
|
2291
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2358
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2292
2359
|
if (dir === join(home, ".kaizen")) return bad("no project to fix in", 409);
|
|
2293
2360
|
let run: any;
|
|
2294
2361
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
@@ -2320,7 +2387,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2320
2387
|
// the approval it saw: one already answered elsewhere is not answered twice.
|
|
2321
2388
|
if (path === "/decide") {
|
|
2322
2389
|
const id = String(body.id ?? "");
|
|
2323
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2390
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2324
2391
|
if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
|
|
2325
2392
|
let run: any;
|
|
2326
2393
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
@@ -2365,7 +2432,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2365
2432
|
// only, no agent is started.
|
|
2366
2433
|
if (path === "/accept") {
|
|
2367
2434
|
const id = String(body.id ?? "");
|
|
2368
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2435
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2369
2436
|
if (gateOf(dir, id) !== "needs") return bad("this run is not waiting on your approval", 409);
|
|
2370
2437
|
// Only a finished-but-unapproved run: a genuine review goes through /decide.
|
|
2371
2438
|
let st: any = {};
|
|
@@ -2381,7 +2448,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2381
2448
|
// Start a run's agent again after it ended mid-stage (resumeRun).
|
|
2382
2449
|
if (path === "/resume") {
|
|
2383
2450
|
const id = String(body.id ?? "");
|
|
2384
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2451
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2385
2452
|
if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
|
|
2386
2453
|
const r = resumeRun(dir, id);
|
|
2387
2454
|
if ("error" in r) return bad(r.error, r.status);
|
|
@@ -2392,7 +2459,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2392
2459
|
|
|
2393
2460
|
if (path === "/to-task" || path === "/to-idea") { // /to-idea: the old name, kept for open tabs
|
|
2394
2461
|
const id = String(body.id ?? "");
|
|
2395
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2462
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2396
2463
|
const failed = runToTask(dir, id);
|
|
2397
2464
|
changed();
|
|
2398
2465
|
return failed ? bad(failed, 409) : json({ ok: true });
|
|
@@ -2401,7 +2468,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2401
2468
|
if (path === "/abort") {
|
|
2402
2469
|
const id = String(body.id ?? "");
|
|
2403
2470
|
const why = String(body.why ?? "").trim() || "abandoned from the web";
|
|
2404
|
-
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2471
|
+
if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
|
|
2405
2472
|
const failed = abandonRun(dir, id, why);
|
|
2406
2473
|
changed();
|
|
2407
2474
|
return failed ? bad(failed, 409) : json({ ok: true });
|
|
@@ -2419,11 +2486,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2419
2486
|
// Every agent starts again in its card, never in a window: a board set to open
|
|
2420
2487
|
// terminals leaves those runs on their Resume button.
|
|
2421
2488
|
if (existsSync(RESUME_LIST)) {
|
|
2422
|
-
let saved: { at?: number; crash?: boolean; list?: Live[] } = {};
|
|
2489
|
+
let saved: { at?: number; crash?: boolean; list?: Live[]; shells?: { dir: string; title: string; agent: string; run: string; ws: string; cmd: string[]; sid?: string; key: string }[] } = {};
|
|
2423
2490
|
try { saved = JSON.parse(readText(RESUME_LIST)); } catch { /* unreadable: nothing to resume */ }
|
|
2424
2491
|
rmSync(RESUME_LIST, { force: true });
|
|
2425
|
-
const done = new Set<string>();
|
|
2426
|
-
|
|
2492
|
+
const done = new Set<string>(), viaRun = new Set<string>();
|
|
2493
|
+
const fresh = saved.crash || Date.now() - (saved.at ?? 0) < 3600_000;
|
|
2494
|
+
for (const { dir, key, run, tmux, resumed } of fresh ? saved.list ?? [] : []) {
|
|
2427
2495
|
// Kept in tmux and still there: the same agent, mid-step, shown in its card again.
|
|
2428
2496
|
if (tmux && tmuxAlive(tmux)) {
|
|
2429
2497
|
try {
|
|
@@ -2436,12 +2504,25 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2436
2504
|
const id = run ?? (s ? ownerOf(dir, s) : null);
|
|
2437
2505
|
if (!id || done.has(`${dir}\0${id}`)) continue;
|
|
2438
2506
|
done.add(`${dir}\0${id}`);
|
|
2507
|
+
viaRun.add(key);
|
|
2439
2508
|
if (saved.crash && resumed && Date.now() - resumed < CRASH_AGAIN_MS) { console.log(` not resuming ${id}: the board died again right after resuming it`); continue; }
|
|
2440
2509
|
if (launchMode(projectOf(dir)) !== "card") continue;
|
|
2441
2510
|
const r = resumeRun(dir, id);
|
|
2442
2511
|
if (saved.crash && "pty" in r && r.pty) autoResumed.set(r.pty, Date.now());
|
|
2443
2512
|
console.log(` ${"error" in r || !r.ok ? "could not resume" : "resumed"} ${id}${"error" in r ? ` (${r.error})` : !r.ok ? ` (${r.why})` : ""}`);
|
|
2444
2513
|
}
|
|
2514
|
+
// The + menu's terminals and agents, unless a run's own resume above already brought that agent back.
|
|
2515
|
+
for (const x of fresh ? saved.shells ?? [] : []) {
|
|
2516
|
+
try {
|
|
2517
|
+
if (viaRun.has(x.key) || !states(true).includes(x.dir) || !existsSync(x.ws) || !Array.isArray(x.cmd) || !x.cmd.every((a) => typeof a === "string")) continue;
|
|
2518
|
+
const key = "sh-" + crypto.randomUUID().slice(0, 8);
|
|
2519
|
+
const cmd = x.sid && /^[\w-]{8,80}$/.test(x.sid) && !x.cmd.includes("--resume") ? [...x.cmd, "--resume", x.sid] : x.cmd;
|
|
2520
|
+
const pid = startPty(key, cmd, x.ws, undefined, changed, { env: { KAIZEN_TERM: key } });
|
|
2521
|
+
shells.set(key, { key, dir: x.dir, title: x.title, agent: x.agent, run: x.run, ws: x.ws, pid });
|
|
2522
|
+
shellCmd.set(key, x.cmd);
|
|
2523
|
+
console.log(` resumed ${x.title}${x.sid ? " (conversation)" : ""}`);
|
|
2524
|
+
} catch (err: any) { console.log(` could not resume ${x.title}: ${err?.message ?? err}`); }
|
|
2525
|
+
}
|
|
2445
2526
|
}
|
|
2446
2527
|
// Last screens nothing picked up: a run left on its Resume button keeps its own a day.
|
|
2447
2528
|
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 */ }
|
|
@@ -2464,6 +2545,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2464
2545
|
const live = ptyKeys().some((k) => ptyState(k)?.alive);
|
|
2465
2546
|
saveLive();
|
|
2466
2547
|
awake.stop();
|
|
2548
|
+
closeAllProxies();
|
|
2467
2549
|
clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(automate); clearInterval(loop); clearInterval(keepList);
|
|
2468
2550
|
for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
|
|
2469
2551
|
setTimeout(() => { server.stop(true); resolve(); }, live ? 400 : 0);
|
|
@@ -2503,6 +2585,26 @@ export function sessionPty(id: string): string | null {
|
|
|
2503
2585
|
return null;
|
|
2504
2586
|
}
|
|
2505
2587
|
|
|
2588
|
+
// The Claude session running under a pty (its pid, or a child of it): the reverse of sessionPty. Linux only.
|
|
2589
|
+
export function claudeSid(ptyPid: number): string | null {
|
|
2590
|
+
const root = join(home, ".claude", "sessions");
|
|
2591
|
+
try {
|
|
2592
|
+
for (const f of readdirSync(root)) {
|
|
2593
|
+
if (!/^\d+\.json$/.test(f)) continue;
|
|
2594
|
+
try {
|
|
2595
|
+
const rec = JSON.parse(readFileSync(join(root, f), "utf8"));
|
|
2596
|
+
if (typeof rec.sessionId !== "string" || !/^[\w-]{8,80}$/.test(rec.sessionId)) continue;
|
|
2597
|
+
let pid = Number(rec.pid);
|
|
2598
|
+
for (let i = 0; i < 32 && pid > 1; i++) {
|
|
2599
|
+
if (pid === ptyPid) return rec.sessionId;
|
|
2600
|
+
pid = Number(/^PPid:\s*(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, "utf8"))?.[1]);
|
|
2601
|
+
}
|
|
2602
|
+
} catch { /* gone or unreadable */ }
|
|
2603
|
+
}
|
|
2604
|
+
} catch { /* no such folder, or no /proc */ }
|
|
2605
|
+
return null;
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2506
2608
|
// Whether a Claude Code session is running somewhere: a process whose command line names
|
|
2507
2609
|
// it (Linux /proc), or its transcript written in the last 90 s (every platform).
|
|
2508
2610
|
export function sessionLive(id: string): boolean {
|
|
@@ -2590,9 +2692,9 @@ export async function openApp(url: string, profile?: string) {
|
|
|
2590
2692
|
}
|
|
2591
2693
|
|
|
2592
2694
|
async function openDefault(url: string) {
|
|
2593
|
-
// `start
|
|
2695
|
+
// Not `cmd /c start`: cmd splits a URL at `&`, `|` or `^` and would run what follows.
|
|
2594
2696
|
if (process.platform === "win32") {
|
|
2595
|
-
try { await Bun
|
|
2697
|
+
try { await Bun.spawn(["rundll32", "url.dll,FileProtocolHandler", url], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exited; return true; } catch { return false; }
|
|
2596
2698
|
}
|
|
2597
2699
|
const opener = process.platform === "darwin" ? "open" : "xdg-open";
|
|
2598
2700
|
if (!Bun.which(opener)) return false;
|