kaizen-agent 1.85.1 → 1.86.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/web.ts CHANGED
@@ -11,13 +11,13 @@ import {
11
11
  reviewFindings, pickFindings, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
12
12
  launchMode, pruneRuns, pruneSessions, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
13
13
  } from "./state.ts";
14
- import { ACCOUNT_VAR, accountDir, addAccount, loginStatus, readAccounts, renameAccount, removeAccount, resolveAccount, setDefaultAccount, type Login } from "./accounts.ts";
14
+ import { ACCOUNT_EXTRA, ACCOUNT_VAR, accountDir, agyLogin, addAccount, loginStatus, readAccounts, renameAccount, removeAccount, resolveAccount, setDefaultAccount, type Login, type Tool } from "./accounts.ts";
15
15
  import { readReport, signalOf } from "./report.ts";
16
16
  import { MAX_IMAGE, saveImage } from "./term-image.ts";
17
17
  import { shellHistory } from "./term-history.ts";
18
18
  import { bundledSkills, repairSkill, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
19
19
  import * as rea from "./rea.ts";
20
- import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
20
+ import { accountEnv, accountForRun, agentUsable, CHILD_ENV, promptArgs, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
21
21
  import { agentLine, failStart, handoffModel, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
22
22
  import { childDied, childQuiet, markWoken, move, requestOpen, readHandoff, refused, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
23
23
  import { processTable, storage, systemMemory, treeRss, type Root } from "./resources.ts";
@@ -56,6 +56,7 @@ const ICO = join(dirname(import.meta.dir), "assets", "kaizen.ico");
56
56
  const NOTES_JS = join(dirname(import.meta.dir), "web", "notebook.js");
57
57
  // The in-card terminal (agent.launch: card): xterm.js, bundled the same way.
58
58
  const TERM_JS = join(dirname(import.meta.dir), "web", "term.js");
59
+ const ANNOTATE_JS = join(dirname(import.meta.dir), "web", "annotate.js");
59
60
  const TERM_CSS = join(dirname(import.meta.dir), "web", "term.css");
60
61
  // The Video page (kaizen-video's library, editor and renders) and its bundle.
61
62
  const VIDEO_PAGE = join(dirname(import.meta.dir), "web", "video.html");
@@ -86,7 +87,7 @@ delete process.env.KAIZEN_DESKTOP_BUNDLED;
86
87
  // page newer than its server sends ops the server does not know ("unknown op").
87
88
  // So the pages are kept as they were at start, and read live (dev edits) only while
88
89
  // the installed version is still the one this board runs.
89
- const AT_START = new Map([PAGE, BOARD_JS, NOTES_PAGE, NOTES_JS, TERM_JS, TERM_CSS, VIDEO_PAGE, VIDEO_JS].map((f) => [f, existsSync(f) ? readText(f) : null]));
90
+ const AT_START = new Map([PAGE, BOARD_JS, NOTES_PAGE, NOTES_JS, TERM_JS, TERM_CSS, VIDEO_PAGE, VIDEO_JS, ANNOTATE_JS].map((f) => [f, existsSync(f) ? readText(f) : null]));
90
91
  const served = (f: string) => installed() === VERSION && existsSync(f) ? readText(f) : AT_START.get(f) ?? null;
91
92
 
92
93
  // A board answers at url and runs the installed version. A board from before the
@@ -108,10 +109,12 @@ export function devCommand(dir: string): string[] | null {
108
109
  return [pm, "run", name];
109
110
  }
110
111
 
111
- // From `ss -ltnpH`: the ports listened on by a process whose working folder is inside ws.
112
- export function devPorts(ss: string, cwdOf: (pid: string) => string, ws: string): number[] {
112
+ // From `ss -ltnpH`: the ports listened on by a process whose working folder is inside ws. A process
113
+ // named in `skip` (the agents: Claude Code listens on a local port of its own) is never the app.
114
+ export function devPorts(ss: string, cwdOf: (pid: string) => string, ws: string, skip: string[] = []): number[] {
113
115
  const ports = new Set<number>();
114
116
  for (const line of ss.split("\n")) {
117
+ if (skip.includes(/users:\(\("([^"]+)"/.exec(line)?.[1] ?? "")) continue;
115
118
  const port = /:(\d+)\s+\S+:\*/.exec(line)?.[1];
116
119
  for (const [, pid] of line.matchAll(/pid=(\d+)/g)) {
117
120
  const cwd = cwdOf(pid);
@@ -287,9 +290,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
287
290
  },
288
291
  alive: (key: string) => ptyState(key)?.alive === true,
289
292
  stop: (key: string) => killPty(key),
293
+ find: (dir: string, run: string) => liveAgent(dir, run)?.key,
290
294
  };
291
295
  const taskPump = setInterval(() => {
292
296
  for (const dir of states(true)) for (const task of tasks.listTasks(dir)) {
297
+ // A stopping task is asked to stop again until its terminal is gone, not only when someone opens it.
298
+ if (task.status === "stopping" && !task.archived) { try { if (taskService.reconcile(dir, task, taskHooks).revision !== task.revision) changed(); } catch { /* next pass */ } continue; }
293
299
  if (!task.safe || task.queuePaused || task.pendingDecision || !task.inputs.some(i => i.state === "queued")) continue;
294
300
  try { taskService.dispatchReady(dir, task.id, taskHooks); changed(); } catch { /* CAS conflict: next pass reads the new state */ }
295
301
  }
@@ -930,6 +936,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
930
936
  return bad("not found", 404);
931
937
  }
932
938
 
939
+ // The annotator, for the desktop app to run inside a public site's page (the proxy serves its own copy).
940
+ if (req.method === "GET" && path === "/annotate.js") {
941
+ const body = served(ANNOTATE_JS);
942
+ if (body === null) return new Response(`${path} missing`, { status: 500 });
943
+ return new Response(body, { headers: { "content-type": "application/javascript; charset=utf-8", "cache-control": "no-store" } });
944
+ }
945
+
933
946
  if (req.method === "GET" && (path === "/term.js" || path === "/term.css")) {
934
947
  const [f, type] = path === "/term.js" ? [TERM_JS, "application/javascript; charset=utf-8"] : [TERM_CSS, "text/css; charset=utf-8"];
935
948
  const body = served(f);
@@ -1054,7 +1067,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1054
1067
  const acct = resolveAccount(a.cmd, signIn ? body.account : undefined);
1055
1068
  if (acct.error) return bad(acct.error, 400);
1056
1069
  bypass = !signIn && bypassForLaunch(a.cmd, body.yolo, !!YOLO_FLAGS[a.cmd]);
1057
- const line = signIn ? [commandOf(a.cmd), ...(a.cmd === "codex" ? ["login"] : [])] : withEnv([commandOf(a.cmd), ...(bypass ? YOLO_FLAGS[a.cmd]! : []), ...argsOf(a.cmd)], a.cmd);
1070
+ // A first message for the agent (the Storage panel's Cleanup: "/disk-cleanup"), passed as its
1071
+ // argument the way a run's prompt is (promptArgs), never through a shell.
1072
+ const first = !signIn && typeof body.prompt === "string" && body.prompt.trim() && body.prompt.length <= 2000 ? body.prompt.trim() : "";
1073
+ const line = signIn ? [commandOf(a.cmd), ...(a.cmd === "codex" ? ["login"] : [])] : withEnv([commandOf(a.cmd), ...(bypass ? YOLO_FLAGS[a.cmd]! : []), ...argsOf(a.cmd), ...promptArgs(a.cmd, first)], a.cmd);
1058
1074
  cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
1059
1075
  } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
1060
1076
  // A workspace folder: only an exact path from this project's own `git worktree list`.
@@ -1083,7 +1099,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
1083
1099
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
1084
1100
  const title = dev ? "dev server" : agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
1085
1101
  // A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
1086
- const pid = startPty(key, cmd, cwd, undefined, changed, {
1102
+ // Home terminals run in the user's home folder (~); HOME_WS stays their record (dir and ws), which the
1103
+ // Home window, restart resume and the phone match on.
1104
+ const pid = startPty(key, cmd, homeWs ? home : cwd, undefined, changed, {
1087
1105
  env: {
1088
1106
  KAIZEN_TERM: key,
1089
1107
  ...(process.platform === "win32" ? { AGY_CLI_DISABLE_AUTO_UPDATE: "1", CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1", DISABLE_AUTO_UPDATER: "1" } : {}),
@@ -1261,7 +1279,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1261
1279
  out = await new Response(p.stdout).text();
1262
1280
  } catch { return json([]); }
1263
1281
  // Never the board itself: `kaizen web` started inside the workspace listens there too.
1264
- return json(devPorts(out, (pid) => { try { return readlinkSync(`/proc/${pid}/cwd`); } catch { return ""; } }, ws).filter((p) => p !== port));
1282
+ return json(devPorts(out, (pid) => { try { return readlinkSync(`/proc/${pid}/cwd`); } catch { return ""; } }, ws, [...KNOWN_AGENTS.map((a) => a.cmd), "cursor-agent"]).filter((p) => p !== port));
1265
1283
  }
1266
1284
  // A phone on the tailnet cannot reach this computer's localhost. Serves that loopback port
1267
1285
  // to the tailnet (`tailscale serve --https=<port>`, never funnel) and answers the address
@@ -1494,7 +1512,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1494
1512
  if (path === "/task-artifact") return taskArtifactResponse(found.state, found.task.id, url.searchParams.get("result") ?? "", url.searchParams.get("artifact") ?? "", req, url.searchParams.get("download") === "1");
1495
1513
  let task = taskService.reconcile(found.state, found.task, taskHooks);
1496
1514
  if (task.safe && !task.queuePaused && !task.pendingDecision && task.inputs.some(i => i.state === "queued")) task = taskService.dispatchReady(found.state, task.id, taskHooks);
1497
- return json({ task: taskService.taskView(found.state, task), results: taskService.resultViews(found.state, task.id), projects: taskProjects(), defaults: taskService.taskDefaults(found.state) });
1515
+ return json({ task: taskService.taskView(found.state, task, taskHooks), results: taskService.resultViews(found.state, task.id), projects: taskProjects(), defaults: taskService.taskDefaults(found.state) });
1498
1516
  } catch (e) { return bad((e as Error).message, e instanceof tasks.TaskError ? e.status : 400); }
1499
1517
  }
1500
1518
 
@@ -1667,7 +1685,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1667
1685
  }
1668
1686
  const a = readAccounts();
1669
1687
  // Who is signed in, asked of the tool itself (cli/accounts.ts loginStatus), a minute at a time.
1670
- const who = async (key: string, tool: "claude" | "codex", dir?: string): Promise<Login> => {
1688
+ const who = async (key: string, tool: Tool, dir?: string): Promise<Login> => {
1671
1689
  const hit = acctLogin.get(key);
1672
1690
  if (hit && Date.now() - hit.at < 60_000) return hit.login;
1673
1691
  const login = await loginStatus(tool, dir);
@@ -1678,24 +1696,32 @@ export async function web(repoDir: string, opts: Opts = {}) {
1678
1696
  const dir = accountDir(x.id);
1679
1697
  let hit = acctUsage.get(x.id);
1680
1698
  if (!hit || Date.now() - hit.at > 60_000) {
1681
- hit = { at: Date.now(), usage: x.tool === "claude" ? await claudeUsageAt(dir) : codexUsageAt(dir) };
1699
+ // Gemini CLI keeps no plan usage kaizen can read: none shown.
1700
+ hit = { at: Date.now(), usage: x.tool === "claude" ? await claudeUsageAt(dir) : x.tool === "codex" ? codexUsageAt(dir) : null };
1682
1701
  acctUsage.set(x.id, hit);
1683
1702
  }
1684
1703
  const l = await who(x.id, x.tool, dir);
1685
- return { ...x, isDefault: a.default[x.tool] === x.id, signedIn: l.signedIn, who: l.who, plan: l.plan, via: l.via, usage: hit.usage, signIn: `${ACCOUNT_VAR[x.tool]}=${dir} ${x.tool}${x.tool === "codex" ? " login" : ""}` };
1704
+ return { ...x, isDefault: a.default[x.tool] === x.id, signedIn: l.signedIn, who: l.who, plan: l.plan, via: l.via, usage: hit.usage, signIn: `${[...(ACCOUNT_EXTRA[x.tool] ?? []), `${ACCOUNT_VAR[x.tool]}=${dir}`].join(" ")} ${x.tool}${x.tool === "codex" ? " login" : ""}`, usageKnown: x.tool !== "gemini" };
1686
1705
  }));
1687
1706
  // The normal login of each installed tool (~/.claude, ~/.codex): the one runs use unless an
1688
1707
  // account above is the default.
1689
- const normal = await Promise.all((["claude", "codex"] as const).filter((t) => onPath(t)).map(async (t) => {
1708
+ const normal = await Promise.all((["claude", "codex", "gemini"] as const).filter((t) => onPath(t)).map(async (t) => {
1690
1709
  const key = "normal:" + t;
1691
1710
  let hit = acctUsage.get(key);
1692
1711
  if (!hit || Date.now() - hit.at > 60_000) {
1693
- hit = { at: Date.now(), usage: t === "claude" ? await claudeUsage(home) : codexUsage(home) };
1712
+ hit = { at: Date.now(), usage: t === "claude" ? await claudeUsage(home) : t === "codex" ? codexUsage(home) : null };
1694
1713
  acctUsage.set(key, hit);
1695
1714
  }
1696
1715
  const l = await who(key, t);
1697
- return { tool: t, isDefault: !a.default[t], signedIn: l.signedIn, who: l.who, plan: l.plan, via: l.via, usage: hit.usage, signIn: t === "claude" ? "claude auth login" : "codex login" };
1716
+ return { tool: t, isDefault: !a.default[t], signedIn: l.signedIn, who: l.who, plan: l.plan, via: l.via, usage: hit.usage, signIn: t === "claude" ? "claude auth login" : t === "codex" ? "codex login" : "gemini", usageKnown: t !== "gemini" };
1698
1717
  }));
1718
+ // Antigravity: no accounts, only whether its own login is saved (keychain, existence only).
1719
+ if (onPath("agy")) {
1720
+ const hit = acctLogin.get("normal:agy");
1721
+ const l = hit && Date.now() - hit.at < 60_000 ? hit.login : await agyLogin();
1722
+ acctLogin.set("normal:agy", { at: Date.now(), login: l });
1723
+ normal.push({ tool: "agy", isDefault: true, signedIn: l.signedIn, usage: null, signIn: "agy", usageKnown: false, noAccounts: true } as any);
1724
+ }
1699
1725
  return json({ accounts: rows, normal, windows: process.platform === "win32", ...(added ? { added } : {}) });
1700
1726
  }
1701
1727
 
@@ -1807,7 +1833,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
1807
1833
  rea.forgetDoctor(); rea.forgetLatest();
1808
1834
  return r.ok ? json(r) : bad(r.why);
1809
1835
  }
1810
- return bad("step: plan, apply or off");
1836
+ // Node.js for REA: runs only the command nodeFix builds here, after the page's confirm
1837
+ // and with the one-time token the Skills page got; never a command from the request.
1838
+ if (body?.step === "node") {
1839
+ const tokenOk = !!skillToken && body?.token === skillToken;
1840
+ skillToken = "";
1841
+ if (body?.confirm !== true || !tokenOk) return bad("confirm required");
1842
+ const r = await rea.installNode();
1843
+ return r.ok ? json({ ok: true }) : bad(r.why);
1844
+ }
1845
+ return bad("step: plan, apply, off or node");
1811
1846
  }
1812
1847
 
1813
1848
  // Per user, so no scope. A saved environment value is never in either answer.
@@ -2247,14 +2282,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
2247
2282
  if (!destination || !states(true).includes(destination) || destination === join(home, ".kaizen")) return bad("Choose a named project", 400);
2248
2283
  const task = tasks.transferDraft(found.state, found.task.id, destination, dirname(destination));
2249
2284
  const result = taskService.taskAction(destination, { op: "start", id: task.id, revision: task.revision, operationId: String(body.operationId) + ":start" }, taskHooks);
2250
- changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task) });
2285
+ changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task, taskHooks) });
2251
2286
  }
2252
2287
  if (!["create", "adopt"].includes(body.op)) {
2253
2288
  const found = tasks.resolveTask(dir, String(body.id ?? ""));
2254
2289
  if (!found || !states(true).includes(found.state)) return bad("unknown task", 404);
2255
2290
  }
2256
2291
  const result = taskService.taskAction(dir, body, taskHooks);
2257
- changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task) });
2292
+ changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task, taskHooks) });
2258
2293
  } catch (e) { return bad((e as Error).message, e instanceof tasks.TaskError ? e.status : 400); }
2259
2294
  }
2260
2295
 
@@ -2814,7 +2849,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
2814
2849
  if (viaRun.has(x.key) || !(states(true).includes(x.dir) || x.dir === HOME_WS) || !existsSync(x.ws) || !Array.isArray(x.cmd) || !x.cmd.every((a) => typeof a === "string")) continue;
2815
2850
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
2816
2851
  const cmd = x.sid && /^[\w-]{8,80}$/.test(x.sid) && !x.cmd.includes("--resume") ? [...x.cmd, "--resume", x.sid] : x.cmd;
2817
- const pid = startPty(key, cmd, x.ws, undefined, changed, { env: { KAIZEN_TERM: key } });
2852
+ // A Home terminal ran in ~ (its record says ~/.kaizen/home): resume there, where Claude keeps that conversation.
2853
+ const pid = startPty(key, cmd, x.dir === HOME_WS ? home : x.ws, undefined, changed, { env: { KAIZEN_TERM: key } });
2818
2854
  shells.set(key, { key, dir: x.dir, title: x.title, agent: x.agent, run: x.run, ws: x.ws, pid });
2819
2855
  shellCmd.set(key, x.cmd);
2820
2856
  console.log(` resumed ${x.title}${x.sid ? " (conversation)" : ""}`);
package/cli/whatsapp.ts CHANGED
@@ -18,6 +18,8 @@ const bunBin = () => Bun.which("bun") ?? process.execPath;
18
18
 
19
19
  export type WAStatus = {
20
20
  installed: boolean;
21
+ // A login is saved on disk (auth/creds.json): the bridge reconnects with it, no QR needed.
22
+ saved: boolean;
21
23
  running: boolean;
22
24
  connected: boolean;
23
25
  user: string | null;
@@ -85,20 +87,29 @@ export async function ensureDaemon(ms = 3000): Promise<boolean> {
85
87
  return false;
86
88
  }
87
89
 
90
+ export const savedLogin = () => existsSync(join(WA_DIR, "auth", "creds.json"));
91
+ // One background start at a time: the Phone page polls every few seconds.
92
+ let reviving: Promise<boolean> | null = null;
93
+
88
94
  export async function whatsappStatus(): Promise<WAStatus> {
89
95
  // "installed" = the libraries are there; the bridge script itself ships with kaizen.
90
96
  const installed = existsSync(BRIDGE_SCRIPT) && depsReady();
97
+ const saved = savedLogin();
91
98
  if (!installed) {
92
- return { installed: false, running: false, connected: false, user: null, qrSvg: null, error: null };
99
+ return { installed: false, saved, running: false, connected: false, user: null, qrSvg: null, error: null };
93
100
  }
94
101
 
95
102
  const res = await callBridge("/status", {}, 1500);
96
103
  if (!res) {
97
- return { installed: true, running: false, connected: false, user: null, qrSvg: null, error: null };
104
+ // A saved login and no bridge (the app or the computer restarted): bring it back. The bridge
105
+ // reconnects from the saved login by itself (whatsapp-bridge.ts), so no QR is shown.
106
+ if (saved && !reviving) reviving = ensureDaemon(8000).finally(() => (reviving = null));
107
+ return { installed: true, saved, running: false, connected: false, user: null, qrSvg: null, error: null };
98
108
  }
99
109
 
100
110
  return {
101
111
  installed: true,
112
+ saved,
102
113
  running: true,
103
114
  connected: !!res.connected,
104
115
  user: res.user ?? null,
@@ -122,6 +133,8 @@ export async function whatsappConnect(): Promise<WAStatus> {
122
133
  }
123
134
 
124
135
  export async function whatsappDisconnect(): Promise<{ ok: boolean }> {
136
+ // Unlink with the bridge down (a saved login after a restart): start it, so it logs out properly.
137
+ if (savedLogin()) await ensureDaemon(8000);
125
138
  const res = await callBridge("/disconnect", { method: "POST" });
126
139
  return { ok: !!res?.ok };
127
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.85.1",
3
+ "version": "1.86.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -239,7 +239,8 @@ input ids; acknowledge the launch before doing anything else:
239
239
  publishes a typed version. Paths must be regular files inside the project/worktree.
240
240
  Do not snapshot source trees or databases. HTML/SVG files download only. Include
241
241
  specialized Video identity as `video:{name,letter,revision}` when relevant, without
242
- changing its recipes. A copy/disk failure retains earlier versions and needs recovery.
242
+ changing its recipes. A refused result does not pause the task; fix the cause and publish again.
243
+ Only a failed copy to disk pauses it, retains earlier versions and needs recovery.
243
244
 
244
245
  A question/status reply never authorizes production. Queued change requests are not
245
246
  already applied: keep their ids and report receipts. Stop requests cancellation and
@@ -0,0 +1,60 @@
1
+ ---
2
+ name: disk-cleanup
3
+ description: Audit disk usage on this PC and clean it up safely. Shows terminal box charts of what is fat (home dirs, Steam games, caches, rebuildable build output), then a verdict panel and a pick-what-to-delete question. Use when the user asks to tidy files and dirs, free disk space, find what is safe to delete, prune caches, or "what is eating my disk".
4
+ ---
5
+
6
+ # Disk cleanup
7
+
8
+ Audit first, delete only what the user picks. Never delete without an explicit pick.
9
+
10
+ ## Rules learned the hard way
11
+
12
+ - **Verify before saying "safe".** Look inside (`ls`, `du`, `diff -rq`, read `project.json`) before calling anything cache or a copy. A dir named `.cache` can hold a venv, a backup, or project history.
13
+ - **Never total unlike things.** A sum of cache dirs is not "reclaimable". Report each group on its own and state what is regenerable and what is not.
14
+ - **Use real numbers.** Say what a number is (apparent vs on-disk). The disk is btrfs with zstd, so use `du -x` and `df -h /home`.
15
+ - Delete only on a pick. Prefer move-to-Archive for anything not obviously regenerable.
16
+ - Report outcomes faithfully: freed space comes from `df` before/after, not from the plan.
17
+
18
+ ## Procedure
19
+
20
+ 1. **Overview.** `df -h /home`, then `du -xsh ~/.[!.]* ~/* | sort -rh | head -25`. Expect `~/.local/share/Steam` to dominate; drill into it separately.
21
+ 2. **Drill the fat ones** with `du -xh --max-depth=1 <dir> | sort -rh | head`:
22
+ - Steam: `steamapps/common`, `shadercache`, `compatdata`. Game name, size and last played come from `steamapps/appmanifest_*.acf` (`name`, `SizeOnDisk`, `LastPlayed`; missing or 0 = never played).
23
+ - Projects: rebuildable output = `node_modules`, `target`, `.next`, `dist` (`find Projects -name node_modules -type d -prune`).
24
+ - `~/.cache`, `~/.config` browser profiles, `~/.hermes`, `~/.local/share/mise/installs` (old tool versions).
25
+ 3. **Round 1: show charts, then ask where to go.** Print the box charts as chat text (see Format), then `AskUserQuestion` with: explore outside Steam / explore Steam / continue to cleanup. Do the exploration the user picks, show new boxes, ask again.
26
+ 4. **Round 2: verdict, then ask what to run.** Print the verdict panel as chat text, then `AskUserQuestion` (multiSelect, max 4 options; overflow items go via "Other") whose options are the verdict rows.
27
+ 5. **Run only the picks.** Close Steam before touching `steamapps`. Re-run `df -h /home` and report freed space.
28
+
29
+ ## Verdict tiers
30
+
31
+ | Tier | Meaning | Examples |
32
+ |---|---|---|
33
+ | ✓ SAFE NOW | regenerates, no work lost | Steam `shadercache`, `node_modules`/`target`/`.next`, `.zcompdump`, empty dirs, stale `.claude.json.tmp.*` |
34
+ | ✓ RE-DOWNLOAD | recoverable, costs time | never-played Steam games, model caches under `~/.cache/huggingface` |
35
+ | ? YOUR CALL | depends on use | idle games (2+ months), old `mise` versions, VMs, headless browser profiles |
36
+ | ✗ KEEP | never offer | `Projects` source, `Documents`, `.ssh`, `.gnupg`, `.kaizen`, `Games/roms` |
37
+
38
+ Watch for: `whisperx-venv` is a venv, not cache; `kaizen-video` needs it. Desktop shortcuts in `~` for a "never played" game mean the user may be about to play it.
39
+
40
+ ## Format
41
+
42
+ Boxes are 38 wide, two per row. No scale text in the title: the title is bold, the top-right shows the box's used total and a 5-cell gauge. Sizes show as TB, GB, MB or KB (never bare `G`); a blank line separates the title from the rows. Row bars fill the width up to the right-aligned size column and scale to the box's biggest row (`▌` half, `▏` under one half-cell). Mark never-played games `✗`.
43
+
44
+ Gauge = box total ÷ the limit (the disk size for HOME and STEAM boxes; the biggest dir's parent for others). Each filled cell is an emoji square coloured by that ratio: 🟩 <50%, 🟨 <75%, 🟧 <90%, 🟥 ≥90%; empty cells are ⬜. Both are 2 cells wide, so `box` counts them double. Bold titles use Unicode bold letters (`𝗛𝗢𝗠𝗘`) because markdown bold does not work inside a code block. Never hand-draw boxes: import the shared component `tui.py` (same dir as this file) for every report that uses a box.
45
+
46
+ ```python
47
+ import sys, os; sys.path.insert(0, os.path.expanduser("~/.claude/skills/disk-cleanup"))
48
+ from tui import box, panel, render, storage, GB, MB, KB
49
+ render(box("HOME", [("Steam", GB(1500)), ("Projects", GB(52))], GB(1552), GB(1900)), box("CACHE", [("huggingface", GB(12)), ("tmp", MB(300), "✗")], GB(12), GB(1900)))
50
+ ```
51
+
52
+ `box(title, [(name, bytes, flag?)], used, limit)` makes a bold-title box: sizes in bytes (`GB()`, `MB()`, `KB()` build them; shown as GB, MB, KB), bars fill the row up to the size column and scale to the box's biggest row, the top-right gauge is box total vs `limit`; `panel(title, [(line, note)], foot)` the verdict panel; `render` prints two per row. `storage([(label, bytes)], total, free)` returns the full-width DISK box: one bar split by pattern (█ ▓ ▒, then ░ other, blank free; chat text cannot colour per section), real disk size top-right, and a one-line legend underneath (short lowercase labels, sizes without a space, so it fits one line). Print it above every chart set, using disjoint sections (e.g. steam games, steam other, home rest) and the real `df` total and free. A box total must be the real `du` figure, not the sum of the rows shown.
53
+
54
+ Every box line must be 40 cells wide by `w()` (emoji = 2); check before printing.
55
+
56
+ Verdict panel: `panel()`, one numbered row per option (`[1] ✓ SAFE NOW <what> <size>` with a `└` note line), a `✗ KEEP` footer.
57
+
58
+ The user sees chat text and the question dialog, but a question dialog shows only its own text, so charts go in chat before the call, never inside the question.
59
+
60
+ **Bash output is collapsed in the user's terminal ("Ran 2 shell commands"), so a chart printed by `render` is invisible.** After running `tui.py`, copy its output verbatim into your own reply inside a ``` code block, before the `AskUserQuestion` call. Never ask "next step?" until the chart is in reply text. Same for the verdict panel.
@@ -0,0 +1 @@
1
+ {"title": "Disk cleanup", "group": "optional", "status": "beta", "needs": ["python3"]}
@@ -0,0 +1,90 @@
1
+ """Shared box/panel component for disk-cleanup reports.
2
+ Use: sys.path.insert(0, os.path.expanduser("~/.claude/skills/disk-cleanup")); from tui import *
3
+ Sizes are bytes everywhere. Helpers: GB(n), MB(n), KB(n) build bytes."""
4
+ W = 38 # box inner width
5
+ KB = lambda n: int(n * 1024)
6
+ MB = lambda n: int(n * 1024**2)
7
+ GB = lambda n: int(n * 1024**3)
8
+
9
+ def size(b):
10
+ """Bytes -> '1.5 TB' / '1500 GB' / '52 MB' / '4 KB' / '0 B' (TB from 1024 GB)."""
11
+ for u, d in (("TB", 1024**4), ("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)):
12
+ if b >= d:
13
+ v = b / d
14
+ return f"{v:.0f} {u}" if v >= 10 else f"{v:.1f} {u}"
15
+ return f"{b} B"
16
+
17
+ def bold(s):
18
+ return "".join(chr(0x1D5D4+ord(c)-65) if "A"<=c<="Z" else chr(0x1D5EE+ord(c)-97) if "a"<=c<="z" else chr(0x1D7EC+ord(c)-48) if c.isdigit() else c for c in s)
19
+
20
+ def w(s):
21
+ """Display width: emoji squares = 2 cells."""
22
+ return sum(2 if ord(c) >= 0x1F000 or c == "⬜" else 1 for c in s)
23
+
24
+ def gauge(used, limit, n=5):
25
+ r = used / limit; f = min(n, round(r * n))
26
+ c = "🟩" if r < .5 else "🟨" if r < .75 else "🟧" if r < .9 else "🟥"
27
+ return c * f + "⬜" * (n - f)
28
+
29
+ def bar(b, top, bw):
30
+ h = round(b / top * bw * 2) # half-cells, scaled to the box's biggest row
31
+ return ("▏" if h == 0 else "█" * (h // 2) + ("▌" if h % 2 else "")).ljust(bw)
32
+
33
+ def box(title, rows, used, limit):
34
+ """rows = [(name, bytes, flag)]; flag optional ('✗'). Bars scale to the box's biggest row; gauge shows box total vs limit."""
35
+ rows = [(r + ("",))[:3] for r in rows]
36
+ top = max(b for _, b, _ in rows)
37
+ lw = max(len(n) for n, _, _ in rows)
38
+ sw = max(len(size(b)) for _, b, _ in rows)
39
+ fw = max(len(f) for _, _, f in rows)
40
+ bw = W - 2 - lw - sw - 2 - (fw + 1 if fw else 0) # bar fills the gap
41
+ body = ["│ " + (f"{n:<{lw}} {bar(b, top, bw)} {size(b):>{sw}}" + (f" {f}" if fw else "")).ljust(W - 1) + "│"
42
+ for n, b, f in rows]
43
+ tag = f"{size(used)} {gauge(used, limit)}"
44
+ head = "┌─ " + bold(title) + " " + "─" * (W - len(title) - w(tag) - 5) + " " + tag + " ┐"
45
+ return [head, "│" + " " * W + "│"] + body + ["└" + "─" * W + "┘"]
46
+
47
+ def side_by_side(a, b):
48
+ n = max(len(a), len(b)); a += [" " * 40] * (n - len(a)); b += [" " * 40] * (n - len(b))
49
+ return [x + " " * (41 - w(x)) + y for x, y in zip(a, b)]
50
+
51
+ def panel(title, rows, foot, pw=62):
52
+ """Verdict panel: rows = [(line, note)], double-line box."""
53
+ out = ["╔═ " + bold(title) + " " + "═" * (pw - len(title) - 3) + "╗"]
54
+ for i, (line, note) in enumerate(rows, 1):
55
+ out += ["║ " + f"[{i}] {line}".ljust(pw - 1) + "║", "║ " + f" └ {note}".ljust(pw - 1) + "║"]
56
+ return out + ["╠" + "═" * pw + "╣", "║ " + foot.ljust(pw - 1) + "║", "╚" + "═" * pw + "╝"]
57
+
58
+ FILL = "█▓▒" # block-element glyphs only (▤ ▚ fell back to another font and broke widths)
59
+
60
+ def storage(segments, total, free, title="DISK", width=79):
61
+ """Full-width disk bar in one box (Apple-storage style). segments = [(label, bytes)], disjoint,
62
+ drawn in order with patterns █ ▤ ▚ ░; rest of used = other (░ if free), unused = FREE (blank).
63
+ Top-right of the box = real disk size. Returns lines, same width as two boxes side by side."""
64
+ other = max(0, total - free - sum(b for _, b in segments))
65
+ parts = [(l, b, FILL[i % 3]) for i, (l, b) in enumerate(segments)] + [("other", other, "░"), ("free", free, " ")]
66
+ n = width - 2
67
+ raw = [b / total * n for _, b, _ in parts]
68
+ cells = [int(r) for r in raw]
69
+ for i in sorted(range(len(parts)), key=lambda i: raw[i] - cells[i], reverse=True)[: n - sum(cells)]:
70
+ cells[i] += 1
71
+ for i, (_, b, _) in enumerate(parts): # never hide a non-empty part
72
+ if b and not cells[i]:
73
+ cells[cells.index(max(cells))] -= 1; cells[i] = 1
74
+ legend, cur = [], ""
75
+ for l, b, c in parts:
76
+ item = f"{c} {l.lower()} {size(b).replace(' ', '')}".strip()
77
+ if cur and len(cur) + 2 + len(item) > n:
78
+ legend.append(cur); cur = item
79
+ else:
80
+ cur = f"{cur} {item}" if cur else item
81
+ legend.append(cur)
82
+ tag = size(total)
83
+ head = "┌─ " + bold(title) + " " + "─" * (width - len(title) - len(tag) - 5) + " " + tag + " ┐"
84
+ row = lambda t: "│ " + t.ljust(n) + " │"
85
+ return [head, row(""), row("".join(c * k for (_, _, c), k in zip(parts, cells)))] + [row(x) for x in legend] + ["└" + "─" * width + "┘"]
86
+
87
+ def render(*boxes):
88
+ """Print boxes two per row."""
89
+ for i in range(0, len(boxes), 2):
90
+ print("\n".join(side_by_side(boxes[i], boxes[i+1]) if i+1 < len(boxes) else boxes[i]))
package/web/annotate.js CHANGED
@@ -10,8 +10,10 @@
10
10
  if (window.__kzAnnotate || !hosted) return;
11
11
  window.__kzAnnotate = true;
12
12
  const script = document.currentScript;
13
- let token = "";
14
- try { token = new URL(script.src).searchParams.get("t") || ""; } catch {}
13
+ // The proxy's <script src="…?t=token">, or (desktop app, public site) the token the board set
14
+ // before running this script in the page.
15
+ let token = typeof window.__kzAnnToken === "string" ? window.__kzAnnToken : "";
16
+ if (!token) try { token = new URL(script.src).searchParams.get("t") || ""; } catch {}
15
17
  const parent = window.parent;
16
18
  // `out` marks what the page says, so the webview's relay forwards it and not what the board sends.
17
19
  const send = (m) => parent.postMessage({ kz: 1, t: token, out: 1, ...m }, "*");
@@ -113,6 +115,7 @@
113
115
  root.innerHTML = `<style>
114
116
  *{box-sizing:border-box;font:12px/1.4 system-ui,sans-serif}
115
117
  .b{position:fixed;pointer-events:none;border:2px solid var(--c);background:color-mix(in srgb,var(--c) 14%,transparent);border-radius:2px}
118
+ .b.mk{border-width:1.5px;border-style:dashed;background:color-mix(in srgb,var(--c) 6%,transparent)}.b.mk.on{border-style:solid;background:color-mix(in srgb,var(--c) 14%,transparent)}
116
119
  .b.g{--c:#34c759}.b.sel{border-style:dashed}
117
120
  .l{position:fixed;pointer-events:none;background:var(--c);color:#fff;padding:1px 6px;border-radius:3px;white-space:nowrap;max-width:60vw;overflow:hidden;text-overflow:ellipsis}
118
121
  .m{position:fixed;width:22px;height:22px;margin:-11px 0 0 -11px;border-radius:50%;background:var(--c);color:#fff;font-weight:600;border:2px solid #fff;display:grid;place-items:center;pointer-events:auto;cursor:pointer;box-shadow:0 1px 4px #0006}
@@ -167,6 +170,8 @@
167
170
  try { const e = m.kind === "area" ? null : document.querySelector(m.items && m.items[0] ? m.items[0] : m.selector); if (e) r = e.getBoundingClientRect(); } catch {}
168
171
  if (!r && m.pb) r = { left: m.pb.x - scrollX, top: m.pb.y - scrollY, width: m.pb.w, height: m.pb.h };
169
172
  if (!r) return;
173
+ // What the note marks stays outlined (dashed; solid while its number is hovered), not only its number.
174
+ add(box(r, "b mk" + (m.kind === "multi" || m.kind === "area" ? " g" : "") + (tip === m ? " on" : "")));
170
175
  const d = el("m dyn" + (m.kind === "multi" || m.kind === "area" ? " g" : ""), `left:${Math.min(innerWidth - 12, r.left + r.width)}px;top:${Math.max(12, r.top)}px`, String(m.n));
171
176
  d.onclick = (e) => { e.stopPropagation(); send({ type: "marker", n: m.n }); };
172
177
  d.onmouseenter = () => { tip = m; paint(); };
@@ -180,12 +180,34 @@ export function annotator(o: {
180
180
  }
181
181
  };
182
182
  addEventListener("message", onMsg);
183
+ // A public site in the desktop app's webview: no proxy can add the script, so the board puts it in
184
+ // after each load, with this open's token (annotate.js reads __kzAnnToken). The webview's preload
185
+ // relays its messages; only ones carrying the token are taken (acceptHost).
186
+ let inject = false, src: string | null = null;
187
+ const injectNow = async () => {
188
+ if (!web || !inject || !px) return;
189
+ try { px.origin = px.target = new URL(web.getURL()).origin; } catch { /* about:blank */ }
190
+ src ??= await fetch("/annotate.js").then((r) => (r.ok ? r.text() : null), () => null);
191
+ if (!src || !inject || !px) return;
192
+ web.executeJavaScript(`window.__kzAnnToken=${JSON.stringify(px.token)};\n${src}`).catch(() => {});
193
+ };
194
+ web?.addEventListener("dom-ready", () => void injectNow());
183
195
  web?.addEventListener("ipc-message", (e: any) => { if (px && o.host.isConnected && e.channel === "kz-ann" && acceptHost(e.args?.[0], px.token)) handle(e.args[0]); });
184
196
 
185
197
  return {
186
198
  proxied: () => !!px,
187
199
  active: () => on,
188
200
  async open(u) {
201
+ inject = false;
202
+ if (want && web && /^https?:\/\//.test(u) && !/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(u)) {
203
+ const token = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");
204
+ const origin = new URL(u).origin;
205
+ px = { origin, token, target: origin };
206
+ inject = true;
207
+ on = false;
208
+ draw();
209
+ return null; // loaded directly; dom-ready puts the annotator in
210
+ }
189
211
  if (!want || !/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(u)) { px = null; on = false; pause = false; draw(); return null; }
190
212
  const r = await post("/annotate/open", { url: u });
191
213
  if (!r?.ok) { want = false; px = null; draw(); return null; }
@@ -193,7 +215,7 @@ export function annotator(o: {
193
215
  draw();
194
216
  return r.url;
195
217
  },
196
- closeProxy() { px = null; on = false; pause = false; draw(); },
218
+ closeProxy() { px = null; inject = false; on = false; pause = false; draw(); },
197
219
  toggle() { want = !want; o.reload(); },
198
220
  };
199
221
  }
@@ -46,8 +46,8 @@ async function refresh() {
46
46
  }
47
47
 
48
48
  // No `yolo`: the server applies that agent's saved bypass setting, as a run workspace's + does by default.
49
- async function start(agent?: string, yolo?: boolean) {
50
- const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ home: true, ...(agent ? { agent, ...(yolo ? { yolo } : {}) } : {}) }) }).catch(() => null);
49
+ async function start(agent?: string, yolo?: boolean, prompt?: string) {
50
+ const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ home: true, ...(agent ? { agent, ...(yolo ? { yolo } : {}), ...(prompt ? { prompt } : {}) } : {}) }) }).catch(() => null);
51
51
  if (!r?.ok) {
52
52
  let why = "";
53
53
  try { why = (await r!.json()).error; } catch {}
@@ -215,12 +215,13 @@ export function initHomeWs() {
215
215
  $("hwsrx").onclick = () => void closeAll();
216
216
  // On a phone × goes back and leaves the agents running (a tab's × ends one); on a computer it ends them all.
217
217
  $("hwsx").onclick = () => (isPhone() ? ((st = "closed"), draw()) : void closeAll());
218
- // The phone's New sheet starts an agent or a shell here ("Home — no project").
218
+ // The phone's New sheet starts an agent or a shell here ("Home — no project"); the Storage panel's
219
+ // Cleanup starts Claude Code on /disk-cleanup (detail.prompt).
219
220
  addEventListener("kz-home-start", (e: any) => {
220
221
  st = "open";
221
222
  if (!isPhone()) save();
222
223
  draw();
223
- void start(e.detail?.agent || undefined, !!e.detail?.yolo);
224
+ void start(e.detail?.agent || undefined, !!e.detail?.yolo, typeof e.detail?.prompt === "string" ? e.detail.prompt : undefined);
224
225
  });
225
226
  $("hwsmin").onclick = () => set("min");
226
227
  $("hwsmax").onclick = () => ((max = !max), draw());