kaizen-agent 1.85.0 → 1.85.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/accounts.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Named logins for Claude and Codex. Each has its own folder, which the tool itself fills:
1
+ // Named logins for Claude, Codex and Gemini CLI. Each has its own folder, which the tool itself fills:
2
2
  // kaizen stores no token. ~/.kaizen/accounts.json lists them. No accounts means every launch
3
3
  // stays on the normal login. A chosen account that can't be used refuses the launch: falling
4
4
  // back would run the work, and bill it, under another account.
@@ -6,16 +6,25 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync,
6
6
  import { homedir } from "node:os";
7
7
  import { join } from "node:path";
8
8
 
9
- export type Tool = "claude" | "codex";
9
+ export type Tool = "claude" | "codex" | "gemini";
10
10
  export type Account = { id: string; tool: Tool; name: string };
11
11
  export type Accounts = { accounts: Account[]; default: Partial<Record<Tool, string>> };
12
12
 
13
- export const ACCOUNT_VAR: Record<Tool, string> = { claude: "CLAUDE_CONFIG_DIR", codex: "CODEX_HOME" };
13
+ // Gemini CLI's GEMINI_CLI_HOME stands in for the home folder: it keeps its login in <that>/.gemini.
14
+ export const ACCOUNT_VAR: Record<Tool, string> = { claude: "CLAUDE_CONFIG_DIR", codex: "CODEX_HOME", gemini: "GEMINI_CLI_HOME" };
15
+ export const TOOL_NAME: Record<Tool, string> = { claude: "Claude", codex: "Codex", gemini: "Gemini" };
16
+ // Gemini CLI keeps its login in the system keychain under one fixed name ("gemini-cli-oauth" /
17
+ // "main-account"), whatever GEMINI_CLI_HOME says: an account signing in there would replace the
18
+ // normal login. Forced to file storage, it keeps each account's login in <folder>/.gemini instead.
19
+ export const ACCOUNT_EXTRA: Partial<Record<Tool, string[]>> = { gemini: ["GEMINI_FORCE_FILE_STORAGE=true"] };
20
+ // The tool's own folder for an account folder, or for the normal login (dir undefined).
21
+ const toolDir = (tool: Tool, dir?: string, home = homedir()) =>
22
+ tool === "gemini" ? join(dir ?? home, ".gemini") : dir ?? join(home, tool === "claude" ? ".claude" : ".codex");
14
23
  const root = () => process.env.KAIZEN_ACCOUNTS_HOME ?? join(homedir(), ".kaizen");
15
24
  const file = () => join(root(), "accounts.json");
16
25
  const validId = (id: string) => /^[a-z0-9]{8,32}$/.test(id);
17
26
  export const accountDir = (id: string) => join(root(), "accounts", id);
18
- const isTool = (t: unknown): t is Tool => t === "claude" || t === "codex";
27
+ const isTool = (t: unknown): t is Tool => t === "claude" || t === "codex" || t === "gemini";
19
28
 
20
29
  export function readAccounts(): Accounts {
21
30
  try {
@@ -34,7 +43,8 @@ function save(a: Accounts) {
34
43
  }
35
44
 
36
45
  // Kaizen's own links, copied from the normal login's folder, so a run works under the account.
37
- export function linkKaizen(dir: string, tool: Tool, from = join(homedir(), tool === "claude" ? ".claude" : ".codex")) {
46
+ export function linkKaizen(dir: string, tool: Tool, from = toolDir(tool)) {
47
+ if (tool === "gemini") dir = join(dir, ".gemini");
38
48
  for (const sub of tool === "claude" ? ["skills", "agents", "commands"] : ["skills"]) {
39
49
  let names: string[] = [];
40
50
  try { names = readdirSync(join(from, sub)).filter((n) => n.startsWith("kaizen")); } catch { continue; }
@@ -63,7 +73,7 @@ export function addAccount(tool: unknown, name: unknown): { id: string } | { err
63
73
  if (!isTool(tool)) return { error: "unknown tool" };
64
74
  const a = readAccounts();
65
75
  // No name: the tool's, numbered. It can be renamed after sign-in.
66
- const base = tool === "claude" ? "Claude" : "Codex";
76
+ const base = TOOL_NAME[tool];
67
77
  let auto = base;
68
78
  for (let i = 2; a.accounts.some((x) => x.tool === tool && x.name === auto); i++) auto = `${base} ${i}`;
69
79
  const n = cleanName(name) || auto;
@@ -80,7 +90,28 @@ export function addAccount(tool: unknown, name: unknown): { id: string } | { err
80
90
 
81
91
  // The folder holds the login and that account's conversations, so it goes only when asked.
82
92
  // Whether the tool has saved a login here. The file is only looked at, never read.
83
- export const signedIn = (dir: string, tool: Tool) => existsSync(join(dir, tool === "claude" ? ".credentials.json" : "auth.json"));
93
+ // Gemini: its file storage (gemini-credentials.json, encrypted) or the older oauth_creds.json.
94
+ export const signedIn = (dir: string, tool: Tool) =>
95
+ tool === "gemini"
96
+ ? ["gemini-credentials.json", "oauth_creds.json"].some((f) => existsSync(join(dir, ".gemini", f)))
97
+ : existsSync(join(dir, tool === "claude" ? ".credentials.json" : "auth.json"));
98
+ // Whether the system keychain holds an entry, by its existence only: the lookup's output (the
99
+ // secret) goes to /dev/null and never reaches kaizen.
100
+ async function keychainHas(service: string, account: string, attr = "account"): Promise<boolean> {
101
+ const argv = process.platform === "darwin"
102
+ ? ["security", "find-generic-password", "-s", service, "-a", account]
103
+ : process.platform === "linux" ? ["secret-tool", "lookup", "service", service, attr, account] : null;
104
+ if (!argv || !Bun.which(argv[0]!)) return false;
105
+ try {
106
+ const p = Bun.spawn(argv, { stdin: "ignore", stdout: "ignore", stderr: "ignore", windowsHide: true, timeout: 3000 });
107
+ return (await p.exited) === 0;
108
+ } catch { return false; }
109
+ }
110
+ // Antigravity (agy) has no accounts here: only whether its own login is saved, which it keeps in the
111
+ // keychain through go-keyring (service "gemini", user "antigravity").
112
+ export const agyLogin = async (): Promise<Login> => ({ signedIn: await keychainHas("gemini", "antigravity", "username"), checked: "file" });
113
+ // Whether the system keychain holds Gemini CLI's normal login.
114
+ const geminiKeychain = () => keychainHas("gemini-cli-oauth", "main-account");
84
115
 
85
116
  // Who is signed in, as the tool itself says: `claude auth status --json` / `codex login status`,
86
117
  // pointed at an account folder (`dir`) or at the normal login. kaizen never opens the login
@@ -88,7 +119,16 @@ export const signedIn = (dir: string, tool: Tool) => existsSync(join(dir, tool =
88
119
  export type Login = { signedIn: boolean; who?: string; plan?: string; via?: string; checked: "cli" | "file" };
89
120
  export async function loginStatus(tool: Tool, dir?: string, env: NodeJS.ProcessEnv = process.env, timeoutMs = 5000): Promise<Login> {
90
121
  const home = env.HOME || homedir();
91
- const fallback = (): Login => ({ signedIn: signedIn(dir ?? join(home, tool === "claude" ? ".claude" : ".codex"), tool), checked: "file" });
122
+ const fallback = (): Login => ({ signedIn: tool === "gemini" ? signedIn(dir ?? home, tool) : signedIn(dir ?? join(home, tool === "claude" ? ".claude" : ".codex"), tool), checked: "file" });
123
+ // Gemini CLI has no status command: the login file's presence, and the address it lists in
124
+ // google_accounts.json (no token there).
125
+ if (tool === "gemini") {
126
+ let who: string | undefined;
127
+ try { const a = JSON.parse(readFileSync(join(toolDir(tool, dir, home), "google_accounts.json"), "utf8"))?.active; if (typeof a === "string" && a.trim()) who = a.trim().slice(0, 120); } catch { /* none */ }
128
+ const f = fallback();
129
+ // The normal login lives in the keychain (Gemini CLI 0.68); an account's, in its folder (forced file storage).
130
+ return { ...f, signedIn: f.signedIn || (!dir && (await geminiKeychain())), who };
131
+ }
92
132
  const bin = Bun.which(tool, { PATH: env.PATH ?? "" });
93
133
  if (!bin) return fallback();
94
134
  const e: Record<string, string> = {};
@@ -140,7 +180,7 @@ export function setDefaultAccount(tool: unknown, id: string): string | null {
140
180
  }
141
181
 
142
182
  // `wanted`: an id, "" for the normal login, undefined for the tool's default.
143
- export type Resolved = { account?: Account; dir?: string; envVar?: string; error?: string };
183
+ export type Resolved = { account?: Account; dir?: string; envVar?: string; extra?: string[]; error?: string };
144
184
  export function resolveAccount(cmd: string, wanted?: string, win = process.platform === "win32"): Resolved {
145
185
  if (!isTool(cmd) || wanted === "") return {};
146
186
  const a = readAccounts(), id = wanted ?? a.default[cmd];
@@ -150,5 +190,5 @@ export function resolveAccount(cmd: string, wanted?: string, win = process.platf
150
190
  if (win) return { error: "Accounts aren't supported on Windows yet." };
151
191
  const dir = accountDir(id);
152
192
  if (!existsSync(dir)) return { error: `The folder for ${account.name} is missing.` };
153
- return { account, dir, envVar: ACCOUNT_VAR[cmd] };
193
+ return { account, dir, envVar: ACCOUNT_VAR[cmd], extra: ACCOUNT_EXTRA[cmd] };
154
194
  }
package/cli/install.ts CHANGED
@@ -1369,31 +1369,24 @@ function initProject() {
1369
1369
  // ("add a discount cap") does not reach kaizen unless the project says it should.
1370
1370
  // One line in the agent instructions is what makes it the default here.
1371
1371
  function writePointer() {
1372
- const block = `\n## Kaizen workflow\n\nNon-trivial work in this repository follows the staged workflow in\n\`.kaizen/spec.md\`: plan, human approval, build, independent review, bounded fix\nloop. Invoke the \`kaizen\` skill for it — do not carry the stages out inline.\n\nA run costs several times what the same change costs in one session, so spend it\nwhere being wrong is expensive: money, data loss, a migration or anything else hard\nto undo, work a customer sees, or a part of the system nobody has read in a year.\n\nWork where being wrong is cheap and obvious does not start a run. Answering a\nquestion, reading code, a one-line fix, a rename the compiler checks — do those\ndirectly. When it is genuinely unclear, ask rather than assuming the expensive path.\n\nBefore non-trivial work, run \`kaizen recall --track <track> --query "<topic>"\` and\ntreat what it returns as past experience from other projects to verify, not as rules.\n\nAfter you change something a person can look at (a page, an app screen, a UI), show it\nbefore saying done: start the app\'s dev server if it is not running, then run\n\`kaizen preview <localhost url>\` (or \`kaizen preview <screenshot.png>\` for a static result).\nA page opens in the kaizen board\'s Browser tab and a screenshot in its Preview tab, never a new browser window.\n\nWhen the person asks for a file on their phone (or another device), send it with\n\`kaizen send <file>...\` (\`--to <device name | address>\` for a device other than their\ndefault). It goes through LocalSend; they tap Accept on the device.\n\nWhen the person asks for a file on their WhatsApp, send it with\n\`kaizen send --whatsapp <file>...\` (\`--to <chat name>\`, \`--text \"<caption>\"\`); with no\n\`--to\` it goes to their own message-yourself chat. Use it instead of LocalSend or any\nother route. If it says WhatsApp is not linked, tell them to link it in the board:\nSettings → Phone → WhatsApp Bridge.\n\nRun state lives in \`.kaizen/runs/<id>/\`. Read \`state.json\` first and continue from\nthe stage it names; never advance a run whose \`awaiting\` field is non-null without a\nrecorded human decision.\n`;
1372
+ const block = `\n## Kaizen workflow\n\nNon-trivial work in this repository follows the staged workflow in\n\`.kaizen/spec.md\`: plan, human approval, build, independent review, bounded fix\nloop. Invoke the \`kaizen\` skill for it — do not carry the stages out inline.\n\nWhen a request is what one of the kaizen skills does, invoke that skill first instead\nof doing the work inline: \`kaizen-concept\` for concepts, mockups or design options\nbefore a build; \`kaizen-explore\` to question an idea before planning; \`kaizen-deck\`,\n\`kaizen-video\`, \`kaizen-book\` and \`kaizen-game\` for a pitch deck, a video, a book or\na game. The skill holds the steps and the quality bar the work needs.\n\nA run costs several times what the same change costs in one session, so spend it\nwhere being wrong is expensive: money, data loss, a migration or anything else hard\nto undo, work a customer sees, or a part of the system nobody has read in a year.\n\nWork where being wrong is cheap and obvious does not start a run. Answering a\nquestion, reading code, a one-line fix, a rename the compiler checks — do those\ndirectly. When it is genuinely unclear, ask rather than assuming the expensive path.\n\nBefore non-trivial work, run \`kaizen recall --track <track> --query "<topic>"\` and\ntreat what it returns as past experience from other projects to verify, not as rules.\n\nAfter you change something a person can look at (a page, an app screen, a UI), show it\nbefore saying done: start the app\'s dev server if it is not running, then run\n\`kaizen preview <localhost url>\` (or \`kaizen preview <screenshot.png>\` for a static result).\nA page opens in the kaizen board\'s Browser tab and a screenshot in its Preview tab, never a new browser window.\n\nWhen the person asks for a file on their phone (or another device), send it with\n\`kaizen send <file>...\` (\`--to <device name | address>\` for a device other than their\ndefault). It goes through LocalSend; they tap Accept on the device.\n\nWhen the person asks for a file on their WhatsApp, send it with\n\`kaizen send --whatsapp <file>...\` (\`--to <chat name>\`, \`--text \"<caption>\"\`); with no\n\`--to\` it goes to their own message-yourself chat. Use it instead of LocalSend or any\nother route. If it says WhatsApp is not linked, tell them to link it in the board:\nSettings → Phone → WhatsApp Bridge.\n\nRun state lives in \`.kaizen/runs/<id>/\`. Read \`state.json\` first and continue from\nthe stage it names; never advance a run whose \`awaiting\` field is non-null without a\nrecorded human decision.\n`;
1373
1373
 
1374
1374
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
1375
1375
  const f = join(process.cwd(), name);
1376
1376
  const current = existsSync(f) ? readFileSync(f, "utf8") : "";
1377
1377
  if (current.includes("## Kaizen workflow")) {
1378
- // Projects set up before `kaizen preview` get its paragraph on the next init.
1379
- if (!current.includes("kaizen preview")) {
1380
- const para = block.slice(block.indexOf("After you change something"), block.indexOf("Run state lives"));
1381
- writeFileSync(f, current.replace("\nRun state lives in", "\n" + para + "Run state lives in"));
1382
- step(`added the preview line to ${name}`);
1383
- }
1384
- // …and before `kaizen send`, its paragraph.
1385
- const now = readFileSync(f, "utf8");
1386
- if (!now.includes("kaizen send") && now.includes("\nRun state lives in")) {
1387
- const para = block.slice(block.indexOf("When the person asks for a file"), block.indexOf("Run state lives"));
1378
+ // Projects set up before a paragraph existed get it on the next init.
1379
+ for (const [label, marker, from, to] of [
1380
+ ["preview", "kaizen preview", "After you change something", "Run state lives"],
1381
+ ["send", "kaizen send", "When the person asks for a file", "Run state lives"],
1382
+ ["WhatsApp send", "kaizen send --whatsapp", "When the person asks for a file on their WhatsApp", "Run state lives"],
1383
+ ["skills-first", "one of the kaizen skills does", "When a request is what one", "A run costs several"],
1384
+ ]) {
1385
+ const now = readFileSync(f, "utf8");
1386
+ if (now.includes(marker) || !now.includes("\nRun state lives in")) continue;
1387
+ const para = block.slice(block.indexOf(from), block.indexOf(to));
1388
1388
  writeFileSync(f, now.replace("\nRun state lives in", "\n" + para + "Run state lives in"));
1389
- step(`added the send line to ${name}`);
1390
- }
1391
- // …and before `kaizen send --whatsapp`, its paragraph.
1392
- const wa = readFileSync(f, "utf8");
1393
- if (!wa.includes("kaizen send --whatsapp") && wa.includes("\nRun state lives in")) {
1394
- const para = block.slice(block.indexOf("When the person asks for a file on their WhatsApp"), block.indexOf("Run state lives"));
1395
- writeFileSync(f, wa.replace("\nRun state lives in", "\n" + para + "Run state lives in"));
1396
- step(`added the WhatsApp send line to ${name}`);
1389
+ step(`added the ${label} line to ${name}`);
1397
1390
  }
1398
1391
  continue;
1399
1392
  }
package/cli/state.ts CHANGED
@@ -1606,7 +1606,7 @@ export function keepAlive(projectDir: string): "off" | "tmux" {
1606
1606
  return "off";
1607
1607
  }
1608
1608
 
1609
- export const accountEnv = (r: Resolved) => (r.dir ? [`${r.envVar}=${r.dir}`] : []);
1609
+ export const accountEnv = (r: Resolved) => (r.dir ? [`${r.envVar}=${r.dir}`, ...(r.extra ?? [])] : []);
1610
1610
  const stageEnv = (projectDir: string, run: string) => {
1611
1611
  try { const s = JSON.parse(readText(join(projectDir, ".kaizen", "runs", run, "state.json"))).stage; return /^\w+$/.test(s) ? [`KAIZEN_STAGE=${s}`] : []; } catch { return []; }
1612
1612
  };
@@ -1887,7 +1887,7 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
1887
1887
  try { const rec = JSON.parse(readText(s.record)); rec.task_id = pick.task.id; rec.task_policy = { requirePlanConfirmation: pick.task.requirePlanConfirmation }; writeFileSync(s.record, JSON.stringify(rec)); }
1888
1888
  catch { return { ok: false, agent, prompt, projectDir, manual: "", why: "Could not preserve task launch identity. The goal remains saved." }; }
1889
1889
  }
1890
- const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? `${acct.envVar}=${shq(acct.dir)}` : "");
1890
+ const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? [`${acct.envVar}=${shq(acct.dir)}`, ...(acct.extra ?? [])].join(" ") : "");
1891
1891
  // Only what is started carries env: the returned `cmd` reaches the page.
1892
1892
  // A run the board knows hears which one it is; a new run has no id yet and passes --run.
1893
1893
  const vars = [...(pick.task ? [`KAIZEN_TASK_ID=${pick.task.id}`] : []), ...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...subagentEnv(projectDir, agent.cmd), ...accountEnv(acct)];
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);
@@ -930,6 +933,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
930
933
  return bad("not found", 404);
931
934
  }
932
935
 
936
+ // The annotator, for the desktop app to run inside a public site's page (the proxy serves its own copy).
937
+ if (req.method === "GET" && path === "/annotate.js") {
938
+ const body = served(ANNOTATE_JS);
939
+ if (body === null) return new Response(`${path} missing`, { status: 500 });
940
+ return new Response(body, { headers: { "content-type": "application/javascript; charset=utf-8", "cache-control": "no-store" } });
941
+ }
942
+
933
943
  if (req.method === "GET" && (path === "/term.js" || path === "/term.css")) {
934
944
  const [f, type] = path === "/term.js" ? [TERM_JS, "application/javascript; charset=utf-8"] : [TERM_CSS, "text/css; charset=utf-8"];
935
945
  const body = served(f);
@@ -1054,7 +1064,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1054
1064
  const acct = resolveAccount(a.cmd, signIn ? body.account : undefined);
1055
1065
  if (acct.error) return bad(acct.error, 400);
1056
1066
  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);
1067
+ // A first message for the agent (the Storage panel's Cleanup: "/disk-cleanup"), passed as its
1068
+ // argument the way a run's prompt is (promptArgs), never through a shell.
1069
+ const first = !signIn && typeof body.prompt === "string" && body.prompt.trim() && body.prompt.length <= 2000 ? body.prompt.trim() : "";
1070
+ 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
1071
  cmd = acct.dir ? ["env", ...accountEnv(acct), ...line] : line;
1059
1072
  } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
1060
1073
  // A workspace folder: only an exact path from this project's own `git worktree list`.
@@ -1083,7 +1096,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
1083
1096
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
1084
1097
  const title = dev ? "dev server" : agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
1085
1098
  // 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, {
1099
+ // Home terminals run in the user's home folder (~); HOME_WS stays their record (dir and ws), which the
1100
+ // Home window, restart resume and the phone match on.
1101
+ const pid = startPty(key, cmd, homeWs ? home : cwd, undefined, changed, {
1087
1102
  env: {
1088
1103
  KAIZEN_TERM: key,
1089
1104
  ...(process.platform === "win32" ? { AGY_CLI_DISABLE_AUTO_UPDATE: "1", CLAUDE_CODE_DISABLE_AUTO_UPDATER: "1", DISABLE_AUTO_UPDATER: "1" } : {}),
@@ -1261,7 +1276,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1261
1276
  out = await new Response(p.stdout).text();
1262
1277
  } catch { return json([]); }
1263
1278
  // 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));
1279
+ 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
1280
  }
1266
1281
  // A phone on the tailnet cannot reach this computer's localhost. Serves that loopback port
1267
1282
  // to the tailnet (`tailscale serve --https=<port>`, never funnel) and answers the address
@@ -1667,7 +1682,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1667
1682
  }
1668
1683
  const a = readAccounts();
1669
1684
  // 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> => {
1685
+ const who = async (key: string, tool: Tool, dir?: string): Promise<Login> => {
1671
1686
  const hit = acctLogin.get(key);
1672
1687
  if (hit && Date.now() - hit.at < 60_000) return hit.login;
1673
1688
  const login = await loginStatus(tool, dir);
@@ -1678,24 +1693,32 @@ export async function web(repoDir: string, opts: Opts = {}) {
1678
1693
  const dir = accountDir(x.id);
1679
1694
  let hit = acctUsage.get(x.id);
1680
1695
  if (!hit || Date.now() - hit.at > 60_000) {
1681
- hit = { at: Date.now(), usage: x.tool === "claude" ? await claudeUsageAt(dir) : codexUsageAt(dir) };
1696
+ // Gemini CLI keeps no plan usage kaizen can read: none shown.
1697
+ hit = { at: Date.now(), usage: x.tool === "claude" ? await claudeUsageAt(dir) : x.tool === "codex" ? codexUsageAt(dir) : null };
1682
1698
  acctUsage.set(x.id, hit);
1683
1699
  }
1684
1700
  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" : ""}` };
1701
+ 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
1702
  }));
1687
1703
  // The normal login of each installed tool (~/.claude, ~/.codex): the one runs use unless an
1688
1704
  // account above is the default.
1689
- const normal = await Promise.all((["claude", "codex"] as const).filter((t) => onPath(t)).map(async (t) => {
1705
+ const normal = await Promise.all((["claude", "codex", "gemini"] as const).filter((t) => onPath(t)).map(async (t) => {
1690
1706
  const key = "normal:" + t;
1691
1707
  let hit = acctUsage.get(key);
1692
1708
  if (!hit || Date.now() - hit.at > 60_000) {
1693
- hit = { at: Date.now(), usage: t === "claude" ? await claudeUsage(home) : codexUsage(home) };
1709
+ hit = { at: Date.now(), usage: t === "claude" ? await claudeUsage(home) : t === "codex" ? codexUsage(home) : null };
1694
1710
  acctUsage.set(key, hit);
1695
1711
  }
1696
1712
  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" };
1713
+ 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
1714
  }));
1715
+ // Antigravity: no accounts, only whether its own login is saved (keychain, existence only).
1716
+ if (onPath("agy")) {
1717
+ const hit = acctLogin.get("normal:agy");
1718
+ const l = hit && Date.now() - hit.at < 60_000 ? hit.login : await agyLogin();
1719
+ acctLogin.set("normal:agy", { at: Date.now(), login: l });
1720
+ normal.push({ tool: "agy", isDefault: true, signedIn: l.signedIn, usage: null, signIn: "agy", usageKnown: false, noAccounts: true } as any);
1721
+ }
1699
1722
  return json({ accounts: rows, normal, windows: process.platform === "win32", ...(added ? { added } : {}) });
1700
1723
  }
1701
1724
 
@@ -2814,7 +2837,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
2814
2837
  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
2838
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
2816
2839
  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 } });
2840
+ // A Home terminal ran in ~ (its record says ~/.kaizen/home): resume there, where Claude keeps that conversation.
2841
+ const pid = startPty(key, cmd, x.dir === HOME_WS ? home : x.ws, undefined, changed, { env: { KAIZEN_TERM: key } });
2818
2842
  shells.set(key, { key, dir: x.dir, title: x.title, agent: x.agent, run: x.run, ws: x.ws, pid });
2819
2843
  shellCmd.set(key, x.cmd);
2820
2844
  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.0",
3
+ "version": "1.85.2",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
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) {
50
- const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ home: true, ...(agent ? { agent } : {}) }) }).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 {}
@@ -172,29 +172,31 @@ function drag(el: HTMLElement, handle: HTMLElement, key: string, skip: (e: Point
172
172
  }
173
173
 
174
174
  // Search, the resource monitor and the phone's Agents list open a terminal by kz-open-term: a Home one
175
- // opens in this panel, or on a phone the Terminal page. Registered at import, so ahead of the run view's
175
+ // opens in this panel (full screen on a phone). Registered at import, so ahead of the run view's
176
176
  // listener (initRunView), which would open a workspace view that does not exist for it.
177
177
  if (typeof window !== "undefined")
178
178
  addEventListener("kz-open-term", (e: any) => {
179
179
  if (!isHomeDir(e.detail?.dir)) return;
180
180
  e.preventDefault();
181
181
  e.stopImmediatePropagation();
182
- if (isPhone() || !$("hws")) return void (location.href = "/?view=terminal");
182
+ if (!$("hws")) return void (location.href = "/?view=terminal");
183
183
  on = String(e.detail.key ?? "");
184
184
  st = "open";
185
- save();
185
+ if (!isPhone()) save(); // a phone opens Home only when asked, never on the next page load
186
186
  void refresh();
187
187
  });
188
188
 
189
189
  export function initHomeWs() {
190
190
  if (!$("plist")) return;
191
- try { const v = localStorage.getItem(KEY); if (v === "open" || v === "min") st = v; } catch {}
191
+ // A phone shows Home full screen, only when asked: it never opens by itself on a page load.
192
+ try { const v = localStorage.getItem(KEY); if (!isPhone() && (v === "open" || v === "min")) st = v; } catch {}
192
193
  // Sent here by wsHref() for a Home terminal (Search on the notebook or video page).
193
194
  const q = new URLSearchParams(location.search);
194
195
  if (q.has("homews")) {
195
196
  q.delete("homews");
196
197
  history.replaceState(history.state, "", "/?" + q);
197
- if (!isPhone()) (st = "open"), save();
198
+ st = "open";
199
+ if (!isPhone()) save();
198
200
  }
199
201
  document.body.insertAdjacentHTML(
200
202
  "beforeend",
@@ -206,11 +208,21 @@ export function initHomeWs() {
206
208
  `<div class="plist hwsslot" id="hwsrow" hidden><div class="pgrp"><button type="button" class="proj" id="hwsopen" title="Home workspace: agents outside any project (Ctrl+Alt+A)"><svg class="plogo hwsico" aria-hidden="true"><use href="#i-home"/></svg><span class="pname">Home</span><span class="c"></span></button><button type="button" class="wadd hwsrx" id="hwsrx" title="Close the Home workspace" aria-label="Close the Home workspace"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7 7 17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button></div></div>`,
207
209
  );
208
210
  const p = $("hws");
209
- drag(p, p.querySelector<HTMLElement>(".hwsh")!, "kz-home-ws-at", (e) => max || !!(e.target as Element).closest("button,summary,.menu-pop"));
211
+ drag(p, p.querySelector<HTMLElement>(".hwsh")!, "kz-home-ws-at", (e) => isPhone() || max || !!(e.target as Element).closest("button,summary,.menu-pop"));
210
212
  drag($("hwsbtn"), $("hwsbtn"), "kz-home-ws-btn", () => false);
211
213
  $("hwsbtn").onclick = () => (dragged ? (dragged = false) : toggleHome());
212
214
  $("hwsopen").onclick = () => set("open");
213
- $("hwsrx").onclick = $("hwsx").onclick = () => void closeAll();
215
+ $("hwsrx").onclick = () => void closeAll();
216
+ // On a phone × goes back and leaves the agents running (a tab's × ends one); on a computer it ends them all.
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"); the Storage panel's
219
+ // Cleanup starts Claude Code on /disk-cleanup (detail.prompt).
220
+ addEventListener("kz-home-start", (e: any) => {
221
+ st = "open";
222
+ if (!isPhone()) save();
223
+ draw();
224
+ void start(e.detail?.agent || undefined, !!e.detail?.yolo, typeof e.detail?.prompt === "string" ? e.detail.prompt : undefined);
225
+ });
214
226
  $("hwsmin").onclick = () => set("min");
215
227
  $("hwsmax").onclick = () => ((max = !max), draw());
216
228
  const add = $("hwsadd") as HTMLDetailsElement;
@@ -80,19 +80,22 @@ function pickAgent(rows: { a: Agent; st: Status }[]) {
80
80
  async function newSheet(dir?: string, ws?: string) {
81
81
  const spots = (railData().projects ?? []).flatMap((p) => (p.workspaces ?? []).map((w) => ({ dir: p.dir as string, ws: w.path as string, name: w.branch || w.path.split(/[\\/]/).pop() })));
82
82
  const first = agentGroups(Date.now())[0]?.rows[0].a;
83
- const on = spots.find((x) => x.dir === (dir ?? first?.dir) && x.ws === (ws ?? first?.ws)) ?? spots[0];
84
- if (!on) return toast("Add a project on a computer first");
85
- const list = await fetch("/agents?dir=" + encodeURIComponent(on.dir)).then((r) => r.json(), () => null);
83
+ // Home (no project) is listed first; it is picked when no project workspace is in view.
84
+ const on = spots.find((x) => x.dir === (dir ?? first?.dir) && x.ws === (ws ?? first?.ws)) ?? null;
85
+ const list = await fetch(on ? "/agents?dir=" + encodeURIComponent(on.dir) : "/agents?home=1").then((r) => r.json(), () => null);
86
86
  const kinds: { cmd: string; name: string; yolo?: boolean; bypassDefault?: boolean }[] = [...(list?.agents ?? []), { cmd: "", name: "Shell" }];
87
87
  const d = document.createElement("dialog");
88
88
  d.className = "pagsheet";
89
- d.innerHTML = String(html`<h4>New in</h4><select class="sel" aria-label="Workspace">${spots.map((x, i) => html`<option value="${String(i)}"${raw(x === on ? " selected" : "")}>${projName(x.dir)} ${x.name}</option>`)}</select><label class="agent-yolo"><span>Yolo / bypass permissions<small>Run commands without permission prompts</small></span>${toggleSwitch(!!list?.agents?.find((a) => a.cmd === list.default)?.bypassDefault, { box: true, attrs: { "aria-label": "Yolo / bypass permissions" } })}</label>${kinds.map((k, i) => html`<button type="button" data-i="${String(i)}">${k.cmd ? agentIco({ agent: k.cmd } as Agent) : raw(`<svg class="pag-ico" aria-hidden="true"><use href="#i-term"/></svg>`)}${k.name}</button>`)}`);
89
+ d.innerHTML = String(html`<h4>New in</h4><select class="sel" aria-label="Workspace"><option value="home"${raw(on ? "" : " selected")}>Home — no project</option>${spots.map((x, i) => html`<option value="${String(i)}"${raw(x === on ? " selected" : "")}>${projName(x.dir)} ${x.name}</option>`)}</select><label class="agent-yolo"><span>Yolo / bypass permissions<small>Run commands without permission prompts</small></span>${toggleSwitch(!!list?.agents?.find((a) => a.cmd === list.default)?.bypassDefault, { box: true, attrs: { "aria-label": "Yolo / bypass permissions" } })}</label>${kinds.map((k, i) => html`<button type="button" data-i="${String(i)}">${k.cmd ? agentIco({ agent: k.cmd } as Agent) : raw(`<svg class="pag-ico" aria-hidden="true"><use href="#i-term"/></svg>`)}${k.name}</button>`)}`);
90
90
  d.addEventListener("click", async (e) => {
91
91
  const b = (e.target as HTMLElement).closest<HTMLButtonElement>("button");
92
92
  if (e.target === d) return d.close();
93
93
  if (!b) return;
94
- const at = spots[Number(d.querySelector("select")!.value)], cmd = kinds[Number(b.dataset.i)].cmd;
94
+ const pick = d.querySelector("select")!.value, cmd = kinds[Number(b.dataset.i)].cmd;
95
95
  d.close();
96
+ // Home: the Home window starts it (POST /shell {home:true}) and opens full screen.
97
+ if (pick === "home") return void dispatchEvent(new CustomEvent("kz-home-start", { detail: { agent: cmd, yolo: !!kinds[Number(b.dataset.i)].yolo && !!d.querySelector<HTMLInputElement>('input[type="checkbox"]')?.checked } }));
98
+ const at = spots[Number(pick)];
96
99
  const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: at.dir, ws: at.ws, run: wsKey(at.dir, at.ws), ...(cmd ? { agent: cmd, yolo: !!kinds[Number(b.dataset.i)].yolo && d.querySelector<HTMLInputElement>('input[type="checkbox"]')!.checked } : {}) }) }).catch(() => null);
97
100
  const sh = r?.ok ? await r.json() : null;
98
101
  if (sh) openTerm({ dir: at.dir, ws: at.ws, key: sh.key } as Agent);