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/accounts.ts +50 -10
- package/cli/install.ts +12 -19
- package/cli/rea.ts +99 -11
- package/cli/state.ts +2 -2
- package/cli/task-service.ts +73 -23
- package/cli/tasks.ts +7 -1
- package/cli/web.ts +55 -19
- package/cli/whatsapp.ts +15 -2
- package/package.json +1 -1
- package/skills/kaizen/spec.md +2 -1
- package/skills/optional/disk-cleanup/SKILL.md +60 -0
- package/skills/optional/disk-cleanup/skill.json +1 -0
- package/skills/optional/disk-cleanup/tui.py +90 -0
- package/web/annotate.js +7 -2
- package/web/board/annotate.ts +23 -1
- package/web/board/home-ws.ts +5 -4
- package/web/board/resources.ts +48 -30
- package/web/board/run-view.ts +5 -1
- package/web/board/settings-accounts.ts +13 -11
- package/web/board/settings-skills.ts +19 -2
- package/web/board/settings.ts +50 -8
- package/web/board/task-page.ts +18 -5
- package/web/board/whatsapp-setup.ts +7 -1
- package/web/board.html +34 -11
- package/web/board.js +222 -209
- package/web/notebook.js +171 -161
- package/web/term-paste.ts +10 -0
- package/web/term.js +48 -48
- package/web/term.ts +77 -11
- package/web/video.js +203 -193
package/cli/accounts.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Named logins for Claude and
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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
|
-
|
|
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
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
const para = block.slice(block.indexOf(
|
|
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
|
|
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/rea.ts
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
// `setup`, `uninstall` and `doctor` do, through `npx` pinned to an exact version. Kaizen keeps
|
|
4
4
|
// only its switch in ~/.kaizen/rea.json and reads agent configs to see what is registered.
|
|
5
5
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
6
|
+
import { delimiter, join, posix, win32 } from "node:path";
|
|
7
7
|
import { SKILL_HOMES } from "./skills.ts";
|
|
8
8
|
|
|
9
|
-
export type Run = (argv: string[]) => Promise<{ ok: boolean; out: string }>;
|
|
9
|
+
export type Run = (argv: string[], ms?: number) => Promise<{ ok: boolean; out: string; err?: string }>;
|
|
10
10
|
export type Reg = { client: string; version: string | null };
|
|
11
11
|
export type Saved = { on: boolean; version: string; clients: string[] };
|
|
12
12
|
|
|
@@ -21,14 +21,16 @@ const npx = process.platform === "win32" ? "npx.cmd" : "npx";
|
|
|
21
21
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
22
22
|
const pkg = (version: string) => `rea-agents@${version}`;
|
|
23
23
|
|
|
24
|
-
// Up to 5 minutes: a first npx run downloads REA (about 50 MB). A missing npx is a failure, not a throw.
|
|
25
|
-
export const run: Run = async (argv) => {
|
|
24
|
+
// Up to 5 minutes by default: a first npx run downloads REA (about 50 MB). A missing npx is a failure, not a throw.
|
|
25
|
+
export const run: Run = async (argv, ms = 5 * 60_000) => {
|
|
26
26
|
try {
|
|
27
27
|
const p = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe", stdin: "ignore", windowsHide: true });
|
|
28
|
-
const timer = setTimeout(() => p.kill(),
|
|
28
|
+
const timer = setTimeout(() => p.kill(), ms);
|
|
29
29
|
const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
|
|
30
30
|
clearTimeout(timer);
|
|
31
|
-
|
|
31
|
+
// `out` stays one stream, as REA's JSON parsing expects; `err` is there for callers that
|
|
32
|
+
// want the reason a package manager put on stderr after its progress on stdout.
|
|
33
|
+
return { ok: code === 0, out: out || err, err };
|
|
32
34
|
} catch (e: any) { return { ok: false, out: `${argv[0]} not found: ${e?.message ?? e}` }; }
|
|
33
35
|
};
|
|
34
36
|
|
|
@@ -57,7 +59,10 @@ export function doctorMissing(j: any): string[] {
|
|
|
57
59
|
if (Array.isArray(v)) return v.forEach(walk);
|
|
58
60
|
if (!v || typeof v !== "object") return;
|
|
59
61
|
const bad = v.ok === false || v.passed === false || /^(fail|failed|error|missing)$/i.test(String(v.status ?? ""));
|
|
60
|
-
|
|
62
|
+
// A failed `node` check is the PC's Node.js being too old: name what it needs, like oldNode.
|
|
63
|
+
const need = v.name === "node" && /^Install (Node\.js .+?)\.?$/.exec(String(v.remediation ?? ""))?.[1]?.replace(/, or /, ", ");
|
|
64
|
+
if (bad && need) out.add(`${need} (this PC has ${v.detail ?? "an older one"})`);
|
|
65
|
+
else if (bad && (v.name || v.id || v.message)) out.add(String(v.name ?? v.id ?? v.message).slice(0, 80));
|
|
61
66
|
for (const x of Object.values(v)) if (x && typeof x === "object") walk(x);
|
|
62
67
|
};
|
|
63
68
|
if (j) for (const k of ["scope_checks", "informational_checks", "providerInspections", "checks"]) walk(j[k]);
|
|
@@ -107,8 +112,82 @@ const validClients = (home: string, clients: string[]) => {
|
|
|
107
112
|
return clients.length > 0 && clients.every((c) => known.has(c));
|
|
108
113
|
};
|
|
109
114
|
const clientArgs = (clients: string[]) => clients.flatMap((c) => ["--client", c]);
|
|
115
|
+
// REA refuses a Node.js older than it supports with one plain line, no JSON. On Windows npx
|
|
116
|
+
// runs the PC's own Node.js, which kaizen cannot update, so say what is needed and how.
|
|
117
|
+
export function oldNode(out: string): { need: string; have: string } | null {
|
|
118
|
+
const m = /REA requires (Node\.js .+?); this process runs Node\.js v?(\d+(?:\.\d+)*)/.exec(out);
|
|
119
|
+
return m ? { need: m[1]!.replace(/, or /, ", "), have: m[2]! } : null;
|
|
120
|
+
}
|
|
121
|
+
const NODE_FIX = "Use Update Node.js on the REA row in Settings → Skills, or install the current Node.js LTS from nodejs.org, then try again.";
|
|
122
|
+
|
|
123
|
+
// ---- Node.js for REA: missing (no node on PATH) or old (REA said so). Installed only on the
|
|
124
|
+
// user's click and yes, through the platform's own package manager; otherwise a download link.
|
|
125
|
+
let nodeOld: { need: string; have: string } | null = null;
|
|
126
|
+
export const forgetNodeOld = () => { nodeOld = null; };
|
|
127
|
+
export const NODE_URL = "https://nodejs.org/en/download";
|
|
128
|
+
export type NodeFix = { how: "winget" | "brew"; argv: string[]; command: string; bin: string } | { how: "link"; url: string };
|
|
129
|
+
|
|
130
|
+
// Where a package manager lives when a desktop app's PATH does not list it (macOS GUI apps).
|
|
131
|
+
const BREWS = ["/opt/homebrew/bin/brew", "/usr/local/bin/brew"];
|
|
132
|
+
export function nodeFix(platform = process.platform, which: (b: string) => string | null = (b) => Bun.which(b, { PATH: process.env.PATH }), exists = existsSync, env = process.env): NodeFix {
|
|
133
|
+
if (platform === "win32") {
|
|
134
|
+
const winget = which("winget");
|
|
135
|
+
// `install` upgrades a package winget already knows, so one command covers both cases.
|
|
136
|
+
const argv = ["winget", "install", "--id", "OpenJS.NodeJS.LTS", "--exact", "--source", "winget", "--accept-package-agreements", "--accept-source-agreements", "--disable-interactivity"];
|
|
137
|
+
if (winget) return { how: "winget", argv: [winget, ...argv.slice(1)], command: argv.join(" "), bin: win32.join(env.ProgramFiles ?? "C:\\Program Files", "nodejs") };
|
|
138
|
+
}
|
|
139
|
+
if (platform === "darwin") {
|
|
140
|
+
const brew = which("brew") ?? BREWS.find((b) => exists(b)) ?? null;
|
|
141
|
+
// `brew install` of an outdated formula upgrades it.
|
|
142
|
+
if (brew) return { how: "brew", argv: [brew, "install", "node"], command: "brew install node", bin: posix.dirname(brew) }; // Homebrew paths are POSIX
|
|
143
|
+
}
|
|
144
|
+
return { how: "link", url: NODE_URL };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// What the row shows: null when Node.js is there and REA has not called it too old.
|
|
148
|
+
export function nodeState(which: (b: string) => string | null = (b) => Bun.which(b, { PATH: process.env.PATH })) {
|
|
149
|
+
const state = !which("node") ? "missing" as const : nodeOld ? "old" as const : null;
|
|
150
|
+
if (!state) return null;
|
|
151
|
+
const fix = nodeFix();
|
|
152
|
+
return { state, ...(state === "old" ? { need: nodeOld!.need, have: nodeOld!.have } : {}), ...(fix.how === "link" ? { how: fix.how, url: fix.url } : { how: fix.how, command: fix.command }) };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Runs the fix nodeFix built here, never a command from the page. Up to 10 minutes: winget
|
|
156
|
+
// downloads and runs Node's installer, and Windows shows its own admin prompt. On success the
|
|
157
|
+
// new Node.js folder goes first on this process's PATH, so REA's npx finds it without a restart.
|
|
158
|
+
let nodeBusy = false;
|
|
159
|
+
export async function installNode(sh: Run = run, fix: NodeFix = nodeFix(), env: Record<string, string | undefined> = process.env) {
|
|
160
|
+
if (fix.how === "link") return { ok: false as const, why: `Download Node.js from ${fix.url}`, url: fix.url };
|
|
161
|
+
if (nodeBusy) return { ok: false as const, why: "Node.js is already being installed" };
|
|
162
|
+
nodeBusy = true;
|
|
163
|
+
try {
|
|
164
|
+
const r = await sh(fix.argv, 10 * 60_000);
|
|
165
|
+
// Already the newest: winget exits non-zero. The old Node.js REA sees then comes from
|
|
166
|
+
// somewhere else on PATH (nvm, Volta, another installer), which kaizen does not touch.
|
|
167
|
+
const said = [r.out, r.err ?? ""].join("\n");
|
|
168
|
+
if (!r.ok && /No (available upgrade|newer package versions) (found|are available)/i.test(said)) {
|
|
169
|
+
return { ok: false as const, why: `Node.js from ${fix.how} is already the newest, but an older Node.js comes first on PATH (nvm, Volta or another installer?). Update or remove that one, then restart kaizen.` };
|
|
170
|
+
}
|
|
171
|
+
// The last real line: winget redraws its spinner with \r, so split on both.
|
|
172
|
+
if (!r.ok) return { ok: false as const, why: (said.split(/[\r\n]+/).map((l) => l.trim()).filter((l) => l && !/^[-\\|/\s█▒░]+$/.test(l)).pop() ?? `${fix.command} failed`).slice(0, 300) };
|
|
173
|
+
// Windows keeps both PATH and Path here (adoptLoginEnv sets both): update every spelling.
|
|
174
|
+
const keys = Object.keys(env).filter((k) => k.toUpperCase() === "PATH");
|
|
175
|
+
for (const key of keys.length ? keys : ["PATH"]) {
|
|
176
|
+
const parts = (env[key] ?? "").split(delimiter).filter((d) => d && d.toLowerCase() !== fix.bin.toLowerCase());
|
|
177
|
+
env[key] = [fix.bin, ...parts].join(delimiter);
|
|
178
|
+
}
|
|
179
|
+
nodeOld = null;
|
|
180
|
+
forgetDoctor();
|
|
181
|
+
return { ok: true as const };
|
|
182
|
+
} finally { nodeBusy = false; }
|
|
183
|
+
}
|
|
110
184
|
// REA's own words when a step did not go through: its message, else the first line it printed.
|
|
111
|
-
const reason = (j: any, out: string) =>
|
|
185
|
+
const reason = (j: any, out: string) => {
|
|
186
|
+
const n = oldNode(out);
|
|
187
|
+
if (n) nodeOld = n;
|
|
188
|
+
if (n) return `REA needs ${n.need}; this PC has Node.js ${n.have}. ${NODE_FIX}`;
|
|
189
|
+
return String(j?.message ?? j?.error ?? j?.reason ?? (out.trim().split("\n")[0] || "REA did not answer")).slice(0, 300);
|
|
190
|
+
};
|
|
112
191
|
|
|
113
192
|
export async function reaLatest(sh: Run = run): Promise<string | null> {
|
|
114
193
|
const r = await sh([npm, "view", "rea-agents", "version"]);
|
|
@@ -143,6 +222,7 @@ export async function reaRemove(home: string, sh: Run = run) {
|
|
|
143
222
|
const r = await sh([npx, "-y", pkg(version), "uninstall", "--json"]);
|
|
144
223
|
if (!r.ok) return { ok: false as const, why: reason(parse(r.out), r.out) };
|
|
145
224
|
save(home, null);
|
|
225
|
+
nodeOld = null;
|
|
146
226
|
const left = reaRegistered(home).map((x) => x.client);
|
|
147
227
|
return { ok: true as const, left, ...(left.includes("claude_code") ? { hint: "claude mcp remove --scope user rea" } : {}) };
|
|
148
228
|
}
|
|
@@ -155,7 +235,14 @@ export function reaDoctor(version: string, sh: Run = run, now = Date.now()) {
|
|
|
155
235
|
const entry: { at: number; p: Promise<any>; v?: any } = { at: now, p: Promise.resolve(null) };
|
|
156
236
|
entry.p = sh([npx, "-y", pkg(version), "doctor", "--json"]).then((r) => {
|
|
157
237
|
const j = parse(r.out);
|
|
158
|
-
|
|
238
|
+
const n = j ? null : oldNode(r.out);
|
|
239
|
+
if (n) nodeOld = n;
|
|
240
|
+
else if (j) {
|
|
241
|
+
// Doctor ran, so it settles the question either way: a failed node check is old, else fine.
|
|
242
|
+
const check = (Array.isArray(j.scope_checks) ? j.scope_checks : []).find((c: any) => c?.name === "node");
|
|
243
|
+
nodeOld = check?.ok === false ? { need: "a newer Node.js", have: String(check.detail ?? "") } : null;
|
|
244
|
+
}
|
|
245
|
+
entry.v = n ? { healthy: false, missing: [`${n.need} (this PC has ${n.have})`] } : j ? { healthy: j.healthy === true, missing: doctorMissing(j) } : null;
|
|
159
246
|
return entry.v;
|
|
160
247
|
});
|
|
161
248
|
doctorCache.set(version, entry);
|
|
@@ -186,14 +273,15 @@ export function reaRow(home: string, sh: Run = run, now = Date.now()) {
|
|
|
186
273
|
const latest = on ? cachedLatest(sh, now) : null;
|
|
187
274
|
const doc = on && installed ? reaDoctor(installed, sh, now) : null;
|
|
188
275
|
const regd = new Set(reg.map((r) => r.client));
|
|
276
|
+
const node = nodeState();
|
|
189
277
|
const note = !on ? undefined
|
|
190
278
|
: `REA ${installed ?? "(version unknown)"}${!saved ? " · set up outside kaizen" : ""}${latest && installed && newer(latest, installed) ? ` · ${latest} available` : ""}${doc === undefined ? " · checking what it needs…" : ""}`;
|
|
191
279
|
return {
|
|
192
280
|
id: "rea", title: "Reverse engineering (REA)", group: "optional", offByDefault: true, status: "beta",
|
|
193
281
|
description: "Lets agents study apps, binaries, packages and file formats whose source isn't here, through REA's MCP tools.",
|
|
194
|
-
off: !on, needs: (doc?.missing ?? []).map((name) => ({ name, found: false })),
|
|
282
|
+
off: !on, needs: [...(node?.state === "missing" ? ["Node.js"] : []), ...(doc?.missing ?? [])].map((name) => ({ name, found: false })),
|
|
195
283
|
agents: reaClients(home).map((c) => ({ agent: c.agent, state: regd.has(c.client) ? "installed" : "missing" })),
|
|
196
284
|
...(note ? { note } : {}),
|
|
197
|
-
rea: { installed, latest, update: !!(latest && installed && newer(latest, installed)), outside: on && !saved, clients: reaClients(home).map((c) => c.client) },
|
|
285
|
+
rea: { installed, latest, update: !!(latest && installed && newer(latest, installed)), outside: on && !saved, clients: reaClients(home).map((c) => c.client), node },
|
|
198
286
|
};
|
|
199
287
|
}
|
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/task-service.ts
CHANGED
|
@@ -8,7 +8,7 @@ import * as R from './task-results.ts';
|
|
|
8
8
|
import { read as scalar } from './config-values.ts';
|
|
9
9
|
import { detectDefaultAgent, home, readInbox, writeInbox, replaceTask, abandonRun, setArchived, readRuns, readText, saveAttachment, acceptance, gateOf } from './state.ts';
|
|
10
10
|
|
|
11
|
-
type Hooks = { launch: (state:string, run:string, text:string, task:T.Task, pick?:any) => {ok:boolean; pty?:string; why?:string}; alive:(pty:string)=>boolean; stop:(pty:string)=>boolean };
|
|
11
|
+
type Hooks = { launch: (state:string, run:string, text:string, task:T.Task, pick?:any) => {ok:boolean; pty?:string; why?:string}; alive:(pty:string)=>boolean; stop:(pty:string)=>boolean; find?:(state:string,run:string)=>string|undefined };
|
|
12
12
|
const runtimeLaunches = new Set<string>();
|
|
13
13
|
const parse = (file:string) => { try { return JSON.parse(readFileSync(file,'utf8')); } catch { return null; } };
|
|
14
14
|
const put = (file:string,value:unknown) => { const temp = file + `.${process.pid}.${randomUUID()}.tmp`; writeFileSync(temp,JSON.stringify(value,null,2)+'\n'); renameSync(temp,file); };
|
|
@@ -18,13 +18,29 @@ export const taskDefaults = (state:string) => ({ agent: detectDefaultAgent(dirna
|
|
|
18
18
|
export function resultViews(state:string,id:string) {
|
|
19
19
|
return R.listResults(state,id).map((r:any)=>({...r,createdAt:r.createdAt??r.created,summary:r.summary??'',checks:r.checks??r.validation??[],artifacts:r.artifacts.map((a:any)=>({...a,url:a.url??`/task-artifact?dir=${encodeURIComponent(state)}&task=${id}&result=${r.id}&artifact=${a.id}`,preview:a.preview??'download'}))}));
|
|
20
20
|
}
|
|
21
|
-
|
|
21
|
+
// The one place that says which buttons a task may use; the page only draws this list and taskAction refuses the rest.
|
|
22
|
+
const agentKey=(state:string,t:T.Task,hooks?:Hooks)=>t.launch?.pty??(t.activeRun?hooks?.find?.(state,t.activeRun):undefined);
|
|
23
|
+
export function allowedActions(state:string,task:T.Task,hooks?:Hooks) {
|
|
24
|
+
const run=runState(state,task),finished=!!run&&(['done','abandoned'].includes(run.stage)||!!run.healed),live=!!task.activeRun&&!!run&&!finished;
|
|
25
|
+
const key=agentKey(state,task,hooks),alive=!!(key&&hooks?.alive(key));
|
|
26
|
+
let accept=false,acceptWhy:string|undefined;
|
|
27
|
+
try{T.acceptTask(structuredClone(task),task.currentResult??'');accept=true;}catch{/* not acceptable now */}
|
|
28
|
+
if(accept&&run&&!finished){accept=false;acceptWhy='The workflow is still reviewing this result';}
|
|
29
|
+
else if(accept&&run?.awaiting&&!run.healed){accept=false;acceptWhy='Resolve the blocking workflow decision first.';}
|
|
30
|
+
return {accept,...(acceptWhy?{acceptWhy}:{}),
|
|
31
|
+
stop:(live&&['draft','waiting','working','ready'].includes(task.status))||(['failed','interrupted','working'].includes(task.status)&&alive),
|
|
32
|
+
// A ready task whose run is still in review but whose agent is gone can only finish by relaunching it.
|
|
33
|
+
resume:(['interrupted','failed','stopping'].includes(task.status)||(task.status==='ready'&&live))&&!alive,
|
|
34
|
+
abandon:live||task.status==='stopping',archive:true,delete:!task.runIds.length&&!task.activeRun,
|
|
35
|
+
start:task.status==='draft'&&!task.activeRun&&!task.currentResult&&!!task.project};
|
|
36
|
+
}
|
|
37
|
+
export function taskView(state:string,task:T.Task,hooks?:Hooks) {
|
|
22
38
|
const p=T.taskProjection(task);
|
|
23
39
|
const run=runState(state,task), finished=run&&(['done','abandoned'].includes(run.stage)||run.healed);
|
|
24
|
-
return {...task,activeRun:finished&&['ready','accepted'].includes(task.status)?null:task.activeRun,projectName:task.project?.split(/[\\/]/).pop()??'Choose a project',dir:state,updatedAt:task.updated,attention:{category:p.filter,reason:p.reason,action:p.action},statusLabel:p.label,decision:!task.project?{id:'project',kind:'project',text:'Choose a named project for your saved goal.'}:task.pendingDecision,messages:task.events,runs:task.runIds,currentResultId:task.currentResult,acceptedResultId:task.acceptedResult};
|
|
40
|
+
return {...task,actions:allowedActions(state,task,hooks),...(hooks?{agentAlive:!!(agentKey(state,task,hooks)&&hooks.alive(agentKey(state,task,hooks)!))}:{}),activeRun:finished&&['ready','accepted'].includes(task.status)?null:task.activeRun,projectName:task.project?.split(/[\\/]/).pop()??'Choose a project',dir:state,updatedAt:task.updated,attention:{category:p.filter,reason:p.reason,action:p.action},statusLabel:p.label,decision:!task.project?{id:'project',kind:'project',text:'Choose a named project for your saved goal.'}:task.pendingDecision,messages:task.events,runs:task.runIds,currentResultId:task.currentResult,acceptedResultId:task.acceptedResult};
|
|
25
41
|
}
|
|
26
42
|
export function taskList(states:string[],hooks?:Hooks) {
|
|
27
|
-
const tasks=states.flatMap(state=>T.listTasks(state).filter(t=>!t.archived).map(t=>taskView(state,reconcile(state,t,hooks))));
|
|
43
|
+
const tasks=states.flatMap(state=>T.listTasks(state).filter(t=>!t.archived).map(t=>taskView(state,reconcile(state,t,hooks),hooks)));
|
|
28
44
|
// Legacy rows become durable only when opened. Stable keys include stamps/index,
|
|
29
45
|
// never a title-based merge; existing inbox and run files are left intact.
|
|
30
46
|
for(const state of states) {
|
|
@@ -42,12 +58,28 @@ export function taskList(states:string[],hooks?:Hooks) {
|
|
|
42
58
|
const readTextSafe=(f:string)=>{try{return readText(f);}catch{return null;}};
|
|
43
59
|
export function reconcile(state:string,task:T.Task,hooks?:Hooks):T.Task {
|
|
44
60
|
let reason='';
|
|
45
|
-
if(
|
|
61
|
+
if(T.normalizePause(structuredClone(task)))task=T.mutateTask(state,task.id,{revision:task.revision,opId:`heal:${task.revision}`},t=>{T.normalizePause(t);});
|
|
62
|
+
// The run finished with a saved result and nothing left to apply: the task is ready, whatever became of the agent.
|
|
63
|
+
// Not while its agent is still alive: clearing launch would stop tracking it; the heal runs once it ends.
|
|
64
|
+
if(['working','interrupted'].includes(task.status)&&task.currentResult&&!task.pendingDecision&&task.inputs.every(i=>['applied','failed'].includes(i.state))&&!(hooks&&task.launch?.pty&&hooks.alive(task.launch.pty))){
|
|
65
|
+
const run=runState(state,task);
|
|
66
|
+
if(run&&(run.stage==='done'||run.healed))return T.mutateTask(state,task.id,{revision:task.revision,opId:`finished:${task.revision}`},t=>{t.status='ready';t.safe=true;t.writePhase=false;t.queuePaused=false;t.error=undefined;t.launch=null;T.addEvent(t,'system','finished','The run finished and the saved result is ready to review.');});
|
|
67
|
+
}
|
|
68
|
+
if(task.status==='stopping'&&hooks){
|
|
69
|
+
// Stop is finished when the terminal is gone, or when there is none to wait for. A live one is asked again.
|
|
70
|
+
const key=agentKey(state,task,hooks);
|
|
71
|
+
if(key&&hooks.alive(key)){hooks.stop(key);return task;}
|
|
72
|
+
return T.mutateTask(state,task.id,{revision:task.revision,opId:`stopped:${task.revision}`},t=>stopped(t,key));
|
|
73
|
+
}
|
|
46
74
|
if(task.launch && ['intent','started'].includes(task.launch.phase) && !runtimeLaunches.has(task.launch.id) && hooks && !(task.launch.pty&&hooks.alive(task.launch.pty))) reason='The launch was interrupted before the agent acknowledged it. Review the existing session before resuming.';
|
|
47
75
|
else if(task.status==='working'&&task.launch?.pty&&hooks&&!hooks.alive(task.launch.pty)&&!task.safe)reason='The agent ended before reporting a safe handback. Your requests and previous results are saved.';
|
|
48
76
|
if(reason) return T.mutateTask(state,task.id,{revision:task.revision,opId:`interrupted:${task.launch?.id}`},t=>{T.recoverLaunch(t);t.status='interrupted';t.error=reason;t.queuePaused=true;});
|
|
49
77
|
return task;
|
|
50
78
|
}
|
|
79
|
+
function stopped(t:T.Task,key?:string) {
|
|
80
|
+
T.confirmStopped(t);
|
|
81
|
+
if(!key)T.addEvent(t,'system','stop-unverified','No agent terminal was found on this board. If the agent runs somewhere else it may still be working. Resume starts a new session.');
|
|
82
|
+
}
|
|
51
83
|
function runState(state:string,task:T.Task) { return task.activeRun?parse(join(state,'runs',task.activeRun,'state.json')):null; }
|
|
52
84
|
export function dispatchReady(state:string,id:string,hooks:Hooks,initial=false,pick?:any):T.Task {
|
|
53
85
|
let task=T.readTask(state,id)!;
|
|
@@ -115,23 +147,30 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
|
|
|
115
147
|
return {state,task};
|
|
116
148
|
}
|
|
117
149
|
const found=T.resolveTask(state,String(body.id??''));if(!found)throw new T.TaskError('Unknown task',404);state=found.state;let task=reconcile(state,found.task,hooks);
|
|
118
|
-
|
|
150
|
+
// Reconcile may bump the revision between the page's read and this call; a page that held the revision read just before it is not stale.
|
|
151
|
+
const mutation={revision:Number(body.revision)===found.task.revision&&['stop','abandon','archive'].includes(op)?task.revision:Number(body.revision),opId:operationId};
|
|
119
152
|
if(task.operations.includes(operationId))return {state,task};
|
|
153
|
+
const allowed=allowedActions(state,task,hooks);
|
|
120
154
|
if(op==='start'){task=T.mutateTask(state,task.id,mutation,t=>{if(t.status!=='draft')throw new T.TaskError('Task already started');});return {state,task:dispatchReady(state,task.id,hooks,true,body.pick&&typeof body.pick==='object'?body.pick:undefined)};}
|
|
121
155
|
if(op==='delete'||op==='archive'||op==='abandon'){
|
|
122
156
|
// Closing a task: Delete only before any run exists; Archive hides it; Abandon ends its run.
|
|
123
157
|
if(op==='delete'){
|
|
124
|
-
if(
|
|
158
|
+
if(!allowed.delete)throw new T.TaskError('A run already started. Archive or abandon it instead.');
|
|
125
159
|
replaceTask(state,task.goal,null);T.deleteTask(state,task.id);return {state,task};
|
|
126
160
|
}
|
|
127
|
-
if(op==='abandon')
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
161
|
+
if(op==='abandon'&&!task.activeRun)throw new T.TaskError('No run to abandon');
|
|
162
|
+
// Side effects run inside the mutation, after the revision check and under the task lock, so a stale page changes nothing.
|
|
163
|
+
// A run that is already done, already abandoned or gone counts as success: the task is archived either way.
|
|
164
|
+
return {state,task:T.mutateTask(state,task.id,mutation,t=>{
|
|
165
|
+
if(op==='abandon'){
|
|
166
|
+
const run=runState(state,t);
|
|
167
|
+
if(run&&!['done','abandoned'].includes(run.stage)){const key=agentKey(state,t,hooks);if(key&&hooks.alive(key))hooks.stop(key);const bad=abandonRun(state,t.activeRun!,String(body.why??'').trim()||'abandoned from the task page');if(bad)throw new T.TaskError(bad);}
|
|
168
|
+
}else if(t.activeRun)setArchived(state,t.activeRun,true);
|
|
169
|
+
else{const lines=readInbox(state),at=lines.findIndex(l=>l.status==='open'&&l.text===t.goal);if(at>=0){lines[at]={...lines[at]!,status:'archived'};writeInbox(state,lines);}}
|
|
170
|
+
t.archived=true;
|
|
171
|
+
})};
|
|
134
172
|
}
|
|
173
|
+
if(op==='stop'&&!allowed.stop)return {state,task};
|
|
135
174
|
task=T.mutateTask(state,task.id,mutation,t=>{
|
|
136
175
|
if(op==='message'){
|
|
137
176
|
const text=String(body.text??'').trim();const status=body.intent==='question'||/^\s*(status\??|what(?:'s| is) (?:the )?(?:status|progress)\??|how (?:is|are) (?:it|things|the task) (?:going|doing)\??)\s*$/i.test(text);
|
|
@@ -140,10 +179,9 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
|
|
|
140
179
|
T.receiveInput(t,{id:operationId,text,intent:answer?'answer':'change',baseResult:body.baseResultId??null});
|
|
141
180
|
if(answer||t.pendingDecision?.kind==='proposal'){t.pendingDecision=null;t.safe=true;t.status='draft';}
|
|
142
181
|
}else if(op==='stop'){T.requestStop(t);}
|
|
143
|
-
else if(op==='resume'){if(
|
|
182
|
+
else if(op==='resume'){const key=agentKey(state,t,hooks);if(key&&hooks.alive(key))throw new T.TaskError('The existing agent is still alive. Stop it or reconcile it in Technical details before resuming.');if(!allowed.resume)throw new T.TaskError('This task does not need recovery');T.resumeTask(t);}
|
|
144
183
|
else if(op==='accept'){
|
|
145
|
-
|
|
146
|
-
if(run?.awaiting&&!run.healed)throw new T.TaskError('Resolve the blocking workflow decision first.');
|
|
184
|
+
if(!allowed.accept)throw new T.TaskError(allowed.acceptWhy??'Finish the active work and pending decisions before accepting this result');
|
|
147
185
|
T.acceptTask(t,String(body.resultId??''));
|
|
148
186
|
}else if(op==='confirm'){
|
|
149
187
|
const d=t.pendingDecision;if(!d||d.kind!=='proposal'||d.id!==body.decisionId||d.run!==t.activeRun||d.result!==t.currentResult)throw new T.TaskError('This proposal changed. Refresh and review it again.');
|
|
@@ -156,9 +194,10 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
|
|
|
156
194
|
}else throw new T.TaskError('Unknown task action',400);
|
|
157
195
|
});
|
|
158
196
|
if(op==='stop'){
|
|
159
|
-
const key=task
|
|
160
|
-
|
|
161
|
-
else task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':
|
|
197
|
+
const key=agentKey(state,task,hooks);
|
|
198
|
+
if(key&&hooks.alive(key))hooks.stop(key);
|
|
199
|
+
else try{task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':stopped'},t=>stopped(t,key));}
|
|
200
|
+
catch{task=T.readTask(state,task.id)!;/* the pump confirmed the stop first: same outcome */}
|
|
162
201
|
}else if(['message','confirm','resume'].includes(op))task=dispatchReady(state,task.id,hooks,op==='resume'&&!task.inputs.some(i=>['queued','received'].includes(i.state)));
|
|
163
202
|
return {state,task};
|
|
164
203
|
}
|
|
@@ -166,6 +205,7 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
|
|
|
166
205
|
// CLI-only structured events. Raw terminal text is never an acknowledgement.
|
|
167
206
|
export function taskEvent(state:string,id:string,runId:string,event:any,operationId:string):T.Task {
|
|
168
207
|
const task=T.readTask(state,id);if(!task||task.activeRun!==runId)throw new T.TaskError('This run does not own the task');
|
|
208
|
+
let preserving=false;
|
|
169
209
|
try { return T.mutateTask(state,id,{revision:task.revision,opId:operationId},t=>{
|
|
170
210
|
const run=runState(state,t);if(!run||run.task_id!==id)throw new T.TaskError('Run task identity does not match');
|
|
171
211
|
if(event.type==='ack'){T.acknowledgeLaunch(t,String(event.launchId),runId,t.launch?.pty);}
|
|
@@ -183,11 +223,21 @@ export function taskEvent(state:string,id:string,runId:string,event:any,operatio
|
|
|
183
223
|
else if(event.type==='result'){
|
|
184
224
|
if(run.task_policy?.requirePlanConfirmation&&!run.task_confirmed)throw new T.TaskError('Proposal confirmation is required');
|
|
185
225
|
if(t.inputs.some(i=>i.state==='dispatched'))throw new T.TaskError('Acknowledge the dispatched requests before publishing a result');
|
|
186
|
-
const result=R.publishResult(state,id,{...event,runId,iteration:run.iteration??0,roots:[dirname(state),...(typeof run.worktree==='string'?[run.worktree]:[])],id:stableUuid(`${id}:${runId}:${operationId}`)});
|
|
187
|
-
|
|
226
|
+
preserving=true;const result=R.publishResult(state,id,{...event,runId,iteration:run.iteration??0,roots:[dirname(state),...(typeof run.worktree==='string'?[run.worktree]:[])],id:stableUuid(`${id}:${runId}:${operationId}`)});
|
|
227
|
+
preserving=false;
|
|
228
|
+
// A result that lands while the task is stopping is saved, but the stop stands.
|
|
229
|
+
if(['stopping','interrupted'].includes(t.status)){t.currentResult=result.id;t.acceptedResult=null;T.addEvent(t,'assistant','result',String(event.summary??event.title??'Result ready'));return;}
|
|
230
|
+
t.currentResult=result.id;t.acceptedResult=null;t.status='ready';t.safe=true;t.pendingDecision=null;t.queuePaused=false;t.error=undefined;if(t.launch)t.launch.phase='acknowledged';T.addEvent(t,'assistant','result',String(event.summary??event.title??'Result ready'));
|
|
188
231
|
}else throw new T.TaskError('Unknown task event',400);
|
|
189
232
|
}); } catch (error) {
|
|
190
|
-
if(event.type==='result'){
|
|
233
|
+
if(event.type==='result'){
|
|
234
|
+
const current=T.readTask(state,id)!,disk=preserving&&((error as T.TaskError).status===507||!(error instanceof T.TaskError));
|
|
235
|
+
// Only a failed copy to disk pauses the task. A refused result (unreceipted input, unconfirmed proposal, bad output) is fixed and published again.
|
|
236
|
+
T.mutateTask(state,id,{revision:current.revision,opId:operationId+':preservation-failed'},t=>{
|
|
237
|
+
if(disk){t.error=(error as Error).message;t.status='failed';t.queuePaused=true;T.addEvent(t,'system','preservation-failed',`This result could not be preserved. ${t.error} Earlier saved results remain available.`);}
|
|
238
|
+
else T.addEvent(t,'system','result-refused',`The result was not accepted yet: ${(error as Error).message}. The agent can fix this and publish again.`);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
191
241
|
throw error;
|
|
192
242
|
}
|
|
193
243
|
}
|
package/cli/tasks.ts
CHANGED
|
@@ -179,13 +179,19 @@ export function recoverLaunch(task: Task) {
|
|
|
179
179
|
export function requestStop(task: Task) { task.queuePaused = true; task.status = "stopping"; task.safe = false; addEvent(task, "system", "stop", "Stop requested. Waiting for the agent to stop; existing edits are retained."); }
|
|
180
180
|
export function confirmStopped(task: Task) { if (task.status !== "stopping") throw new TaskError("Stop was not requested"); task.status = "interrupted"; if (task.launch) task.launch.phase = "interrupted"; addEvent(task, "system", "stopped", "The agent stopped. Queued requests are saved. This does not undo edits."); }
|
|
181
181
|
export function resumeTask(task: Task) {
|
|
182
|
-
if (!["interrupted", "failed"].includes(task.status)) throw new TaskError("This task does not need recovery");
|
|
182
|
+
if (!["interrupted", "failed", "stopping", "ready"].includes(task.status)) throw new TaskError("This task does not need recovery");
|
|
183
183
|
task.queuePaused = false; task.safe = true; task.launch = null; task.error = undefined;
|
|
184
184
|
// Explicit recovery preserves ids and makes ambiguous work visible for reconciliation.
|
|
185
185
|
for (const i of task.inputs) if (i.state === "dispatched" || i.state === "failed") i.state = "queued";
|
|
186
186
|
task.status = task.currentResult ? "ready" : "draft";
|
|
187
187
|
addEvent(task, "system", "resume", "Resume requested. Reconcile existing edits before applying the saved requests.");
|
|
188
188
|
}
|
|
189
|
+
// A pause only means something while the task is stopping, interrupted or failed. Anywhere else it
|
|
190
|
+
// is a leftover that blocks Looks good, so it is cleared. Returns whether anything changed.
|
|
191
|
+
export function normalizePause(task: Task): boolean {
|
|
192
|
+
if (["stopping", "interrupted", "failed"].includes(task.status) || !(task.queuePaused || task.error)) return false;
|
|
193
|
+
task.queuePaused = false; task.error = undefined; return true;
|
|
194
|
+
}
|
|
189
195
|
export function acceptTask(task: Task, result: string) {
|
|
190
196
|
if (!result || result !== task.currentResult) throw new TaskError("This result is no longer current");
|
|
191
197
|
if (task.status !== "ready" || !task.safe || task.writePhase || task.pendingDecision || task.queuePaused || task.inputs.some((i) => !["applied", "failed"].includes(i.state))) throw new TaskError("Finish the active work and pending decisions before accepting this result");
|