kaizen-agent 1.79.0 → 1.80.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/hermes.ts +20 -0
- package/cli/install.ts +20 -1
- package/cli/localsend.ts +61 -4
- package/cli/report.ts +7 -4
- package/cli/settings.ts +2 -8
- package/cli/state.ts +19 -3
- package/cli/task-results.ts +133 -0
- package/cli/task-service.ts +180 -0
- package/cli/tasks.ts +201 -0
- package/cli/ui-audit.allow.json +6 -0
- package/cli/ui-audit.ts +427 -0
- package/cli/web.ts +72 -1
- package/cli/whatsapp.ts +112 -0
- package/package.json +2 -1
- package/skills/kaizen/SKILL.md +4 -0
- package/skills/kaizen/adapters.md +4 -0
- package/skills/kaizen/spec-build.md +5 -1
- package/skills/kaizen/spec-main.md +4 -0
- package/skills/kaizen/spec-plan.md +4 -0
- package/skills/kaizen/spec-review.md +4 -0
- package/skills/kaizen/spec.md +52 -0
- package/web/board/add-project.ts +1 -1
- package/web/board/badge.ts +70 -8
- package/web/board/cards.ts +4 -2
- package/web/board/dom.ts +10 -0
- package/web/board/icebox.ts +2 -2
- package/web/board/keys.ts +1 -1
- package/web/board/live.ts +9 -5
- package/web/board/phone.ts +4 -3
- package/web/board/rich.ts +4 -2
- package/web/board/run-view.ts +16 -14
- package/web/board/settings-automations.ts +2 -2
- package/web/board/settings-skills.ts +2 -2
- package/web/board/settings.ts +12 -14
- package/web/board/task-page.ts +672 -0
- package/web/board/task-results.ts +235 -0
- package/web/board/tasks.ts +214 -200
- package/web/board/terms.ts +17 -2
- package/web/board/views.ts +35 -9
- package/web/board/whatsapp-setup.ts +137 -0
- package/web/board/workspace.ts +24 -2
- package/web/board.html +62 -35
- package/web/board.js +403 -142
- package/web/notebook.js +388 -153
- package/web/notes.html +21 -11
- package/web/term.js +1 -1
- package/web/video.html +27 -11
- package/web/video.js +415 -180
- package/web/video.ts +5 -5
- package/web/board/new-agent.ts +0 -20
package/cli/hermes.ts
CHANGED
|
@@ -32,6 +32,16 @@ function run(args: string[], ms: number): Promise<Out> {
|
|
|
32
32
|
const lastLine = (s: string) => s.trim().split("\n").filter(Boolean).pop()?.replace(/^hermes send:\s*/, "") ?? "";
|
|
33
33
|
|
|
34
34
|
export async function targets(): Promise<{ chats: Chat[] } | { error: string }> {
|
|
35
|
+
try {
|
|
36
|
+
const { whatsappChats, whatsappStatus } = await import("./whatsapp.ts");
|
|
37
|
+
const st = await whatsappStatus();
|
|
38
|
+
if (st.connected) {
|
|
39
|
+
const wa = await whatsappChats();
|
|
40
|
+
if (wa && wa.length) {
|
|
41
|
+
return { chats: wa.map((c) => ({ id: `whatsapp:${c.id}`, name: c.name, type: c.type })) };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
} catch {}
|
|
35
45
|
const r = await run(["send", "--list", "whatsapp", "--json"], 10_000);
|
|
36
46
|
if (typeof r.code === "string") return { error: r.code };
|
|
37
47
|
let j: any;
|
|
@@ -58,6 +68,16 @@ export function message(text: string, file: string): string | { error: string }
|
|
|
58
68
|
export async function sendMedia(target: string, text: string, file: string): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
59
69
|
const m = message(text, file);
|
|
60
70
|
if (typeof m !== "string") return { ok: false, error: m.error };
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
const { whatsappSend, whatsappStatus } = await import("./whatsapp.ts");
|
|
74
|
+
const st = await whatsappStatus();
|
|
75
|
+
if (st.connected) {
|
|
76
|
+
const res = await whatsappSend(target, text, file);
|
|
77
|
+
if (res) return res;
|
|
78
|
+
}
|
|
79
|
+
} catch {}
|
|
80
|
+
|
|
61
81
|
// "--" so a message starting with "-" is text, not an option.
|
|
62
82
|
const r = await run(["send", "-t", target, "--json", "--", m], 5 * 60_000);
|
|
63
83
|
if (typeof r.code === "string") return { ok: false, error: r.code };
|
package/cli/install.ts
CHANGED
|
@@ -31,7 +31,7 @@ const interactive = process.stdin.isTTY && !check && !upgrade && !args.has("--ye
|
|
|
31
31
|
// cli/install-unknown.test.ts fails if a dispatched word is missing here.
|
|
32
32
|
const COMMANDS = ["automation", "help", "init", "browser", "card", "chat", "computer", "config", "docs", "done", "gather", "handoff",
|
|
33
33
|
"icebox", "issue", "model", "preflight", "preview", "prune", "recall", "related", "remember", "report", "roadmap", "scrape", "search", "send", "settings", "setup", "sources",
|
|
34
|
-
"state", "stats", "uninstall", "upgrade", "version", "web", "worker", "worktree"];
|
|
34
|
+
"state", "stats", "task", "uninstall", "upgrade", "version", "web", "worker", "worktree"];
|
|
35
35
|
const first = Bun.argv[2];
|
|
36
36
|
const commandList = ` commands: ${COMMANDS.join(", ")}\n plain \`kaizen\` opens the board; \`kaizen --yes\` installs; \`kaizen init\` sets up this folder\n`;
|
|
37
37
|
if (first && !first.startsWith("-") && !COMMANDS.includes(first)) {
|
|
@@ -184,6 +184,25 @@ if (Bun.argv[2] === "computer") {
|
|
|
184
184
|
process.exit(code);
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
+
// Validated structured task events are the portable handshake for every agent.
|
|
188
|
+
if (Bun.argv[2] === "task") {
|
|
189
|
+
const { locate } = await import("./state.ts");
|
|
190
|
+
const { stateOf } = await import("./report.ts");
|
|
191
|
+
const { taskEvent, taskView } = await import("./task-service.ts");
|
|
192
|
+
const { readTask } = await import("./tasks.ts");
|
|
193
|
+
const a = Bun.argv.slice(3), flag = (n: string) => { const i = a.indexOf(n); return i < 0 ? undefined : a.splice(i, 2)[1]; };
|
|
194
|
+
const id = flag("--task") ?? process.env.KAIZEN_TASK_ID, run = flag("--run") ?? process.env.KAIZEN_RUN_ID;
|
|
195
|
+
const payload = flag("--json"), operationId = flag("--operation") ?? crypto.randomUUID();
|
|
196
|
+
const state = stateOf(process.cwd(), locate());
|
|
197
|
+
try {
|
|
198
|
+
if (!state || !id) throw new Error("kaizen task show | event --task <uuid> --run <id> --operation <stable-id> --json '<event>'");
|
|
199
|
+
if (a[0] === "show") { const t = readTask(state, id); if (!t) throw new Error("Unknown task"); console.log(JSON.stringify(taskView(state,t))); }
|
|
200
|
+
else if (a[0] === "event" && payload && run) console.log(JSON.stringify(taskView(state,taskEvent(state,id,run,JSON.parse(payload),operationId))));
|
|
201
|
+
else throw new Error("Use task show or task event with --json and --run");
|
|
202
|
+
} catch (e) { console.error((e as Error).message); process.exit(1); }
|
|
203
|
+
process.exit(0);
|
|
204
|
+
}
|
|
205
|
+
|
|
187
206
|
// `kaizen report`: how an agent tells the board about its run. See cli/report.ts.
|
|
188
207
|
if (Bun.argv[2] === "report") {
|
|
189
208
|
const { locate } = await import("./state.ts");
|
package/cli/localsend.ts
CHANGED
|
@@ -50,7 +50,50 @@ const device = (m: any, ip: string): Device | null => {
|
|
|
50
50
|
// Announce on the multicast group and collect who answers for `ms`: devices reply by
|
|
51
51
|
// POSTing /register to the port we announced, or by multicast. The LocalSend app on this
|
|
52
52
|
// computer may hold UDP 53317 already; reuseAddr shares it on Linux and macOS, and where
|
|
53
|
-
// binding still fails we announce from any port and rely on the HTTP replies.
|
|
53
|
+
// binding still fails we announce from any port and rely on the HTTP replies. Also probes
|
|
54
|
+
// active Tailscale peer IPs on port 53317, so devices on a tailnet are discovered without multicast.
|
|
55
|
+
export async function probePeer(ip: string, timeoutMs = 2000, port = PORT): Promise<Device | null> {
|
|
56
|
+
const { cert, key } = identity();
|
|
57
|
+
for (const protocol of ["https", "http"] as const) {
|
|
58
|
+
try {
|
|
59
|
+
const tls = protocol === "https" ? { rejectUnauthorized: false, cert, key } : undefined;
|
|
60
|
+
const res = await fetch(`${protocol}://${ip.includes(":") ? `[${ip}]` : ip}:${port}/api/localsend/v2/info`, {
|
|
61
|
+
tls,
|
|
62
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
63
|
+
} as RequestInit);
|
|
64
|
+
if (res.ok) {
|
|
65
|
+
const j = await res.json().catch(() => null);
|
|
66
|
+
if (j && typeof j === "object") {
|
|
67
|
+
return device({ ...j, protocol, port }, ip);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
// not available on this protocol or not reachable
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function tailscaleIps(): Promise<string[]> {
|
|
78
|
+
try {
|
|
79
|
+
const p = Bun.spawn(["tailscale", "status", "--json"], { stdout: "pipe", stderr: "ignore", windowsHide: true });
|
|
80
|
+
const text = await new Response(p.stdout).text();
|
|
81
|
+
if (!text.trim()) return [];
|
|
82
|
+
const s = JSON.parse(text);
|
|
83
|
+
const ips: string[] = [];
|
|
84
|
+
for (const p of Object.values<any>(s?.Peer ?? {})) {
|
|
85
|
+
if (p?.Online && Array.isArray(p?.TailscaleIPs)) {
|
|
86
|
+
for (const ip of p.TailscaleIPs) {
|
|
87
|
+
if (typeof ip === "string" && !ip.includes(":")) ips.push(ip);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return ips;
|
|
92
|
+
} catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
54
97
|
export async function discover(ms = 3000): Promise<{ devices: Device[]; note: string | null }> {
|
|
55
98
|
const found = new Map<string, Device>();
|
|
56
99
|
const add = (d: Device | null) => { if (d) found.set(d.fingerprint, d); };
|
|
@@ -63,6 +106,17 @@ export async function discover(ms = 3000): Promise<{ devices: Device[]; note: st
|
|
|
63
106
|
} });
|
|
64
107
|
const sock = createSocket({ type: "udp4", reuseAddr: true });
|
|
65
108
|
let note: string | null = null;
|
|
109
|
+
const probeTailnet = async () => {
|
|
110
|
+
try {
|
|
111
|
+
const ips = await tailscaleIps();
|
|
112
|
+
if (ips.length) {
|
|
113
|
+
const results = await Promise.allSettled(ips.map((ip) => probePeer(ip, Math.max(1000, ms - 500))));
|
|
114
|
+
for (const r of results) {
|
|
115
|
+
if (r.status === "fulfilled" && r.value) add(r.value);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} catch { /* tailscale probe best-effort */ }
|
|
119
|
+
};
|
|
66
120
|
try {
|
|
67
121
|
sock.on("message", (buf, r) => { try { add(device(JSON.parse(String(buf)), r.address)); } catch { /* not LocalSend */ } });
|
|
68
122
|
await new Promise<void>((ok) => {
|
|
@@ -70,9 +124,12 @@ export async function discover(ms = 3000): Promise<{ devices: Device[]; note: st
|
|
|
70
124
|
sock.bind(PORT, () => { try { sock.addMembership(GROUP); } catch { /* no multicast route; replies still come over HTTP */ } ok(); });
|
|
71
125
|
});
|
|
72
126
|
const hello = Buffer.from(JSON.stringify({ ...me(), port: http.port, protocol: "http", announce: true }));
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
127
|
+
const multicasts = (async () => {
|
|
128
|
+
// Twice, as the app does: one datagram on a busy Wi-Fi is easy to lose.
|
|
129
|
+
for (const wait of [0, 600]) { await Bun.sleep(wait); sock.send(hello, PORT, GROUP); }
|
|
130
|
+
await Bun.sleep(Math.max(0, ms - 600));
|
|
131
|
+
})();
|
|
132
|
+
await Promise.all([multicasts, probeTailnet()]);
|
|
76
133
|
} catch (e) { note = `discovery failed: ${e instanceof Error ? e.message : e}`; }
|
|
77
134
|
finally { try { sock.close(); } catch { /* closed */ } http.stop(true); }
|
|
78
135
|
return { devices: [...found.values()].sort((a, b) => a.alias.localeCompare(b.alias)), note };
|
package/cli/report.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
|
|
7
|
-
export type Handback = { stage: string; iteration?: number; outcome: "succeeded" | "failed"; summary: string; files: string[] };
|
|
7
|
+
export type Handback = { stage: string; iteration?: number; outcome: "succeeded" | "failed"; summary: string; files: string[]; task?: { id: string; result: string | null } };
|
|
8
8
|
export type Report = { phase?: string; at: number; blocked?: { question: string; options: string[] }; handback?: Handback };
|
|
9
9
|
export type Signal = "blocked" | "stale" | "unverified" | null;
|
|
10
10
|
|
|
@@ -38,9 +38,12 @@ export const reportBlocked = (state: string, id: string, question: string, optio
|
|
|
38
38
|
export const reportUnblock = (state: string, id: string) => write(state, id, (r) => { delete r.blocked; });
|
|
39
39
|
export function reportDone(state: string, id: string, stage: string, outcome: string, summary: string, files: string[]) {
|
|
40
40
|
if (outcome !== "succeeded" && outcome !== "failed") return "outcome is succeeded or failed";
|
|
41
|
-
let iteration = 0;
|
|
42
|
-
try {
|
|
43
|
-
|
|
41
|
+
let iteration = 0, task: Handback["task"];
|
|
42
|
+
try {
|
|
43
|
+
const run = JSON.parse(readFileSync(join(state, "runs", id, "state.json"), "utf8")); iteration = Number(run.iteration) || 0;
|
|
44
|
+
if (typeof run.task_id === "string") { const t = JSON.parse(readFileSync(join(state, "tasks", run.task_id, "task.json"), "utf8")); task = { id: t.id, result: t.currentResult ?? null }; }
|
|
45
|
+
} catch { /* write() reports it */ }
|
|
46
|
+
return write(state, id, (r) => { r.handback = { stage: clip(stage, 20), iteration, outcome, summary: clip(summary, 600), files: files.slice(0, 200).map((f) => clip(f, 300)), ...(task ? { task } : {}) }; delete r.blocked; });
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
// What the card shows. `pty` is the board's terminal for the run; without one the agent
|
package/cli/settings.ts
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
import { lineOf, read } from "./config-values.ts";
|
|
4
4
|
export { read } from "./config-values.ts";
|
|
5
5
|
import { existsSync, writeFileSync, copyFileSync, mkdirSync } from "node:fs";
|
|
6
|
-
import { join, dirname
|
|
6
|
+
import { join, dirname } from "node:path";
|
|
7
7
|
import { homedir } from "node:os";
|
|
8
|
-
import { readText,
|
|
8
|
+
import { readText, KNOWN_AGENTS, MODEL_FLAGS } from "./state.ts";
|
|
9
9
|
|
|
10
10
|
// `text` is a value typed rather than chosen: a path. It has no values to cycle.
|
|
11
11
|
// `when`: the row only has an effect while that other key holds that value; both
|
|
@@ -168,18 +168,12 @@ export function listSettings(repoRoot: string, project?: string | null) {
|
|
|
168
168
|
const scoped = typeof project === "string";
|
|
169
169
|
const base = scoped ? board : "";
|
|
170
170
|
const preset = detectPreset(text, base, defaults);
|
|
171
|
-
// All projects: the projects whose own config sets a key to something else, since
|
|
172
|
-
// that value, not the one shown, is what their runs use.
|
|
173
|
-
const others = project === null
|
|
174
|
-
? knownProjects().map((d) => ({ label: basename(d), text: load(join(d, ".kaizen", "config.yml")) })).filter((o) => o.text)
|
|
175
|
-
: [];
|
|
176
171
|
const rows = SETTINGS.map((s) => {
|
|
177
172
|
const value = s.key === "preset" ? preset : (read(s.group === "Board" ? board : text, s.key) ?? (s.group === "Board" ? null : read(base, s.key)) ?? read(defaults, s.key)) ?? s.values[0] ?? "";
|
|
178
173
|
const local = s.group !== "Board" && s.key !== "preset";
|
|
179
174
|
return {
|
|
180
175
|
...s, value,
|
|
181
176
|
...(scoped && local && read(text, s.key) !== null ? { own: true } : {}),
|
|
182
|
-
...(others.length && local ? { overrides: others.flatMap((o) => { const v = read(o.text, s.key); return v !== null && v !== value ? [{ label: o.label, value: v }] : []; }) } : {}),
|
|
183
177
|
};
|
|
184
178
|
});
|
|
185
179
|
const valueOf = (k: string) => rows.find((r) => r.key === k)?.value ?? null;
|
package/cli/state.ts
CHANGED
|
@@ -1817,7 +1817,7 @@ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_
|
|
|
1817
1817
|
// skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
|
|
1818
1818
|
// a work folder that may not be a project, so it is not remembered as one. A session record is
|
|
1819
1819
|
// written only where that folder has a .kaizen (a project place does; the library usually not).
|
|
1820
|
-
export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; account?: string; model?: string; explore?: boolean; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
|
|
1820
|
+
export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; account?: string; model?: string; explore?: boolean; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string; task?: { id: string; requirePlanConfirmation: boolean } } = {}): Launch {
|
|
1821
1821
|
const projectDir = pick.cwd ?? projectOf(from);
|
|
1822
1822
|
// The run will be born here; the board must know the dir or the task never retires.
|
|
1823
1823
|
if (!pick.cwd) remember(projectDir);
|
|
@@ -1839,7 +1839,9 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1839
1839
|
// A skill other than kaizen: Claude Code takes it as a slash command; other agents are told to use it.
|
|
1840
1840
|
const lead = !pick.skill ? "/kaizen" : agent.cmd === "claude" ? `/${pick.skill}` : `Use the ${pick.skill} skill.`;
|
|
1841
1841
|
const exploreChoice = !run && !pick.skill && typeof pick.explore === "boolean" ? `\n\n[Kaizen launch option: explore=${pick.explore ? "on" : "off"}. Freeze this per-run override at intake; it does not change the saved setting.]` : "";
|
|
1842
|
-
const prompt = !it.text ? "" : requestOf(it.where ? `${lead} ${it.text} (${it.where})` : `${lead} ${it.text}`, it.notes, from) + exploreChoice
|
|
1842
|
+
const prompt = !it.text ? "" : requestOf(it.where ? `${lead} ${it.text} (${it.where})` : `${lead} ${it.text}`, it.notes, from) + exploreChoice + (pick.task ? `
|
|
1843
|
+
|
|
1844
|
+
[Task context: task=${pick.task.id}; run=${run ?? "new"}; initial proposal confirmation=${pick.task.requirePlanConfirmation ? "required" : "already confirmed"}. Read task.json in .kaizen/tasks/${pick.task.id}/. Preserve task identity and frozen task_policy. Use kaizen task events for replies/questions/proposals/work receipts/results; questions do not authorize production. Do not produce until the current proposal is explicitly confirmed. Keep real tool permissions unchanged.]` : "");
|
|
1843
1845
|
const wanted = pick.model ?? (own?.cmd === agent.cmd ? own.model : null) ?? undefined;
|
|
1844
1846
|
const model = wanted && plainModel(wanted) ? wanted : undefined;
|
|
1845
1847
|
// Yolo was picked for one tool; a fallback to another opens in its normal mode.
|
|
@@ -1858,10 +1860,14 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1858
1860
|
let s: ReturnType<typeof sessionLaunch>;
|
|
1859
1861
|
try { s = sessionLaunch(projectDir, agent.cmd, [agentBin, ...flags], prompt, it.text.replace(/^(lite|full|auto|plan)\s+/i, ""), run, model, yolo, acct.account?.id); }
|
|
1860
1862
|
finally { if (acct.envVar) { if (prior === undefined) delete process.env[acct.envVar]; else process.env[acct.envVar] = prior; } }
|
|
1863
|
+
if (pick.task && s.record) {
|
|
1864
|
+
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)); }
|
|
1865
|
+
catch { return { ok: false, agent, prompt, projectDir, manual: "", why: "Could not preserve task launch identity. The goal remains saved." }; }
|
|
1866
|
+
}
|
|
1861
1867
|
const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? `${acct.envVar}=${shq(acct.dir)}` : "");
|
|
1862
1868
|
// Only what is started carries env: the returned `cmd` reaches the page.
|
|
1863
1869
|
// A run the board knows hears which one it is; a new run has no id yet and passes --run.
|
|
1864
|
-
const vars = [...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...subagentEnv(projectDir, agent.cmd), ...accountEnv(acct)];
|
|
1870
|
+
const vars = [...(pick.task ? [`KAIZEN_TASK_ID=${pick.task.id}`] : []), ...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...subagentEnv(projectDir, agent.cmd), ...accountEnv(acct)];
|
|
1865
1871
|
const identity = vars.length && process.platform !== "win32" ? ["env", ...vars] : [];
|
|
1866
1872
|
const started = [...identity, ...withEnv(s.fullCmd, agent.cmd, prefs)];
|
|
1867
1873
|
const drop = () => { if (s.record) rmSync(s.record, { force: true }); };
|
|
@@ -2103,6 +2109,13 @@ export function setRunState(state: string, id: string, pairs: string[]): string
|
|
|
2103
2109
|
if (k === "iteration") { if (!/^\d+$/.test(raw)) return "iteration must be a whole number"; set[k] = Number(raw); continue; }
|
|
2104
2110
|
set[k] = v;
|
|
2105
2111
|
}
|
|
2112
|
+
let existing: any;
|
|
2113
|
+
try { existing = JSON.parse(readText(file)); } catch { return "invalid state.json"; }
|
|
2114
|
+
if (existing.task_policy) {
|
|
2115
|
+
if (["task_policy", "task_id", "task_confirmed"].some((k) => k in set)) return "task policy is frozen; confirm the current proposal in Tasks";
|
|
2116
|
+
if ((set.stage === "build" || set.stage === "review") && existing.task_policy.requirePlanConfirmation && !existing.task_confirmed)
|
|
2117
|
+
return "task production needs explicit confirmation of the current proposal in Tasks";
|
|
2118
|
+
}
|
|
2106
2119
|
let now: any = null;
|
|
2107
2120
|
if (!setStage(file, (s) => { Object.assign(s, set); now = s; return true; })) return `state.json for ${id} changed while writing or is not valid JSON; read it and retry`;
|
|
2108
2121
|
if ("stage" in set || "awaiting" in set) logStage(state, id, now.stage, now.awaiting);
|
|
@@ -2141,6 +2154,9 @@ export function healRuns(state: string): string[] {
|
|
|
2141
2154
|
export function finishRun(state: string, id: string, userApproved = false): string | null {
|
|
2142
2155
|
const file = join(state, "runs", id, "state.json");
|
|
2143
2156
|
if (!existsSync(file)) return `No run ${id}.`;
|
|
2157
|
+
let taskRun: any = {};
|
|
2158
|
+
try { taskRun = JSON.parse(readText(file)); } catch {}
|
|
2159
|
+
if (taskRun.task_policy?.requirePlanConfirmation && !taskRun.task_confirmed) return "task proposal has not been confirmed";
|
|
2144
2160
|
if (gateOf(state, id) === "needs") {
|
|
2145
2161
|
if (!userApproved) return `Run ${id} changed files and the user has not approved it. Ask the user; on a clear yes run: kaizen done ${id} --user-approved`;
|
|
2146
2162
|
const why = recordAcceptance(state, id, "chat");
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// A result is published only after every regular output has been copied, hashed,
|
|
2
|
+
// and atomically renamed into its own private directory. Live URLs remain mutable.
|
|
3
|
+
import { constants, closeSync, fstatSync, mkdirSync, openSync, readSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
4
|
+
import { basename, extname, join, resolve, sep } from "node:path";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { taskDir, TaskError, taskId, acquireTaskLock } from "./tasks.ts";
|
|
7
|
+
|
|
8
|
+
export type ArtifactKind = "website" | "text" | "markdown" | "pdf" | "image" | "video" | "audio" | "download";
|
|
9
|
+
export type ResultArtifact = { id: string; name: string; kind: ArtifactKind; mediaType: string; preview: "live" | "text" | "pdf" | "image" | "video" | "audio" | "download"; source: string; size: number; hash: string | null; file?: string; url?: string; mutable?: boolean; video?: { name: string; letter: string; revision: number } };
|
|
10
|
+
export type TaskResult = { schema: 1; id: string; taskId: string; runId: string; iteration: number; version: number; created: number; title: string; summary: string; artifacts: ResultArtifact[]; checks: string[]; limitations: string[]; size: number };
|
|
11
|
+
export type ArtifactInput = { path?: string; url?: string; name?: string; kind?: ArtifactKind; mediaType?: string; video?: ResultArtifact["video"] };
|
|
12
|
+
export type PublishResult = { runId: string; iteration?: number; title: string; summary: string; artifacts: ArtifactInput[]; checks?: string[]; limitations?: string[]; roots: string[]; id?: string; settleMs?: number; maxBytes?: number };
|
|
13
|
+
const json = (file: string) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; } };
|
|
14
|
+
const validResult = (id: string) => taskId(id);
|
|
15
|
+
const rootOf = (state: string, task: string) => join(taskDir(state, task), "results");
|
|
16
|
+
const below = (root: string, file: string) => file !== root && file.startsWith(root + sep);
|
|
17
|
+
const mime: Record<string, [ArtifactKind, string, ResultArtifact["preview"]]> = {
|
|
18
|
+
".txt": ["text", "text/plain; charset=utf-8", "text"], ".md": ["markdown", "text/plain; charset=utf-8", "text"], ".markdown": ["markdown", "text/plain; charset=utf-8", "text"], ".json": ["text", "text/plain; charset=utf-8", "text"], ".csv": ["text", "text/plain; charset=utf-8", "text"],
|
|
19
|
+
".pdf": ["pdf", "application/pdf", "pdf"], ".png": ["image", "image/png", "image"], ".jpg": ["image", "image/jpeg", "image"], ".jpeg": ["image", "image/jpeg", "image"], ".webp": ["image", "image/webp", "image"], ".gif": ["image", "image/gif", "image"],
|
|
20
|
+
".mp4": ["video", "video/mp4", "video"], ".webm": ["video", "video/webm", "video"], ".mov": ["video", "video/quicktime", "video"], ".mp3": ["audio", "audio/mpeg", "audio"], ".wav": ["audio", "audio/wav", "audio"], ".ogg": ["audio", "audio/ogg", "audio"], ".m4a": ["audio", "audio/mp4", "audio"],
|
|
21
|
+
};
|
|
22
|
+
export function artifactType(name: string): { kind: ArtifactKind; mediaType: string; preview: ResultArtifact["preview"] } {
|
|
23
|
+
const [kind, mediaType, preview] = mime[extname(name).toLowerCase()] ?? ["download", "application/octet-stream", "download"];
|
|
24
|
+
return { kind, mediaType, preview };
|
|
25
|
+
}
|
|
26
|
+
export function liveUrl(value: string): string | null {
|
|
27
|
+
try { const url = new URL(value); return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password ? url.href : null; } catch { return null; }
|
|
28
|
+
}
|
|
29
|
+
// A path must be lexically below an allowed root AND resolve below it. Relative
|
|
30
|
+
// paths use the first root; neither symlink traversal nor ../ aliases are accepted.
|
|
31
|
+
export function resultSource(roots: string[], file: string): string | null {
|
|
32
|
+
if (!file || file.includes("\0") || file.replace(/\\/g, "/").split("/").includes("..")) return null;
|
|
33
|
+
const want = resolve(roots[0] || ".", file);
|
|
34
|
+
for (const root of roots) {
|
|
35
|
+
const top = resolve(root); if (!below(top, want)) continue;
|
|
36
|
+
try { const real = realpathSync(want), realRoot = realpathSync(top); if (below(realRoot, real) && statSync(real).isFile()) return real; } catch { /* not a settled file */ }
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
export function readResult(state: string, task: string, id: string): TaskResult | null {
|
|
41
|
+
if (!validResult(id)) return null;
|
|
42
|
+
try {
|
|
43
|
+
const root = taskDir(state, task), dir = join(rootOf(state, task), id);
|
|
44
|
+
if (!below(realpathSync(root), realpathSync(dir))) return null;
|
|
45
|
+
const manifest = resultSource([dir], "result.json"); if (!manifest) return null;
|
|
46
|
+
const result = json(manifest);
|
|
47
|
+
return result?.schema === 1 && result.id === id && result.taskId === task && Array.isArray(result.artifacts) ? result : null;
|
|
48
|
+
} catch { return null; }
|
|
49
|
+
}
|
|
50
|
+
export function listResults(state: string, task: string): TaskResult[] {
|
|
51
|
+
try { return readdirSync(rootOf(state, task)).filter(validResult).map((id) => readResult(state, task, id)).filter((r): r is TaskResult => !!r).sort((a, b) => b.version - a.version); } catch { return []; }
|
|
52
|
+
}
|
|
53
|
+
export function publishResult(state: string, task: string, input: PublishResult): TaskResult {
|
|
54
|
+
const id = input.id ?? randomUUID(); if (!validResult(id)) throw new TaskError("Invalid result id", 400);
|
|
55
|
+
const previous = readResult(state, task, id); if (previous) return previous;
|
|
56
|
+
if (!input.artifacts?.length || input.artifacts.length > 100) throw new TaskError("Publish between one and 100 named outputs", 400);
|
|
57
|
+
if (!input.roots.length) throw new TaskError("Result source roots are required", 400);
|
|
58
|
+
const results = rootOf(state, task); mkdirSync(results, { recursive: true, mode: 0o700 });
|
|
59
|
+
const release = acquireTaskLock(join(results, "publication.lock"));
|
|
60
|
+
const temp = join(results, `.pending-${id}-${randomUUID()}`); mkdirSync(temp, { mode: 0o700 });
|
|
61
|
+
try {
|
|
62
|
+
const artifacts: ResultArtifact[] = []; let size = 0;
|
|
63
|
+
for (const item of input.artifacts) {
|
|
64
|
+
if (!!item.path === !!item.url) throw new TaskError("An output needs one file or live URL", 400);
|
|
65
|
+
const artifactId = randomUUID();
|
|
66
|
+
if (item.url) {
|
|
67
|
+
const url = liveUrl(item.url); if (!url) throw new TaskError("Only HTTP and HTTPS preview links are supported", 400);
|
|
68
|
+
artifacts.push({ id: artifactId, name: item.name || "Live preview", kind: "website", preview: "live", mediaType: "text/html", source: url, url, mutable: true, size: 0, hash: null }); continue;
|
|
69
|
+
}
|
|
70
|
+
const source = resultSource(input.roots, item.path!); if (!source) throw new TaskError(`Cannot preserve output: ${basename(item.path!)} is missing or outside the project`, 400);
|
|
71
|
+
const before = statSync(source), settle = input.settleMs ?? 500;
|
|
72
|
+
if (settle > 0 && Date.now() - before.mtimeMs < settle) throw new TaskError(`Output is still changing: ${basename(source)}. Wait and publish again.`);
|
|
73
|
+
size += before.size; if (size > (input.maxBytes ?? 2_000_000_000)) throw new TaskError("Saved result exceeds the 2GB copy limit. Publish smaller deliverable files.", 413);
|
|
74
|
+
const name = basename(item.name || source).replace(/[\0-\x1f\x7f]/g, "_").slice(0, 240) || "download";
|
|
75
|
+
const file = artifactId + extname(source).replace(/[^.\w-]/g, "").slice(0, 12);
|
|
76
|
+
const target = join(temp, file);
|
|
77
|
+
// Open without following a final symlink; compare inode/size after copy so
|
|
78
|
+
// an actively replaced source never becomes a purported immutable result.
|
|
79
|
+
const fd = openSync(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
80
|
+
let saved: number | undefined; const digest = createHash("sha256"); let copied = 0;
|
|
81
|
+
try {
|
|
82
|
+
const opened = fstatSync(fd); if (!opened.isFile() || opened.ino !== before.ino || opened.dev !== before.dev) throw new TaskError("Output changed during preservation. Publish again.");
|
|
83
|
+
saved = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
|
84
|
+
const chunk = Buffer.allocUnsafe(1024 * 1024); let bytes = 0;
|
|
85
|
+
while ((bytes = readSync(fd, chunk, 0, chunk.length, null)) > 0) {
|
|
86
|
+
copied += bytes; if (copied > before.size) throw new TaskError("Output grew during preservation. Publish again.");
|
|
87
|
+
digest.update(chunk.subarray(0, bytes)); let written = 0;
|
|
88
|
+
while (written < bytes) written += writeSync(saved, chunk, written, bytes - written);
|
|
89
|
+
}
|
|
90
|
+
const after = statSync(source), held = fstatSync(fd);
|
|
91
|
+
if (after.ino !== before.ino || after.size !== before.size || after.mtimeMs !== before.mtimeMs || held.size !== before.size || held.mtimeMs !== before.mtimeMs) throw new TaskError("Output changed during preservation. Publish again.");
|
|
92
|
+
} finally { closeSync(fd); if (saved !== undefined) closeSync(saved); }
|
|
93
|
+
if (copied !== before.size) throw new TaskError("Incomplete saved output. Publish again.");
|
|
94
|
+
const type = artifactType(source);
|
|
95
|
+
// Claimed types never upgrade active formats such as HTML/SVG to same-origin previews.
|
|
96
|
+
artifacts.push({ id: artifactId, name, ...type, source: item.path!, size: copied, hash: digest.digest("hex"), file, ...(item.video ? { video: item.video } : {}) });
|
|
97
|
+
}
|
|
98
|
+
const result: TaskResult = { schema: 1, id, taskId: task, runId: input.runId, iteration: input.iteration ?? 0, version: (listResults(state, task)[0]?.version ?? 0) + 1, created: Date.now(), title: input.title, summary: input.summary, artifacts, checks: input.checks ?? [], limitations: input.limitations ?? [], size };
|
|
99
|
+
writeFileSync(join(temp, "result.json"), JSON.stringify(result, null, 2), { mode: 0o600 });
|
|
100
|
+
renameSync(temp, join(results, id)); return result;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error instanceof TaskError) throw error;
|
|
103
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
104
|
+
throw new TaskError(code === "ENOSPC" ? "Not enough disk space to preserve this result. Free space and retry; earlier results remain available." : `Could not preserve the result (${code || "copy failed"}). Earlier results remain available.`, 507);
|
|
105
|
+
} finally { rmSync(temp, { recursive: true, force: true }); release(); }
|
|
106
|
+
}
|
|
107
|
+
export function resolveArtifact(state: string, task: string, resultId: string, artifactId: string): { result: TaskResult; artifact: ResultArtifact; path: string | null } | null {
|
|
108
|
+
if (!taskId(artifactId)) return null;
|
|
109
|
+
const result = readResult(state, task, resultId), artifact = result?.artifacts.find((a) => a.id === artifactId); if (!result || !artifact) return null;
|
|
110
|
+
if (artifact.url) return { result, artifact, path: null };
|
|
111
|
+
if (!artifact.file || basename(artifact.file) !== artifact.file) return null;
|
|
112
|
+
const dir = join(rootOf(state, task), resultId), path = resultSource([dir], artifact.file); if (!path) return null;
|
|
113
|
+
// Corruption is a missing output, never a different file served under a saved id.
|
|
114
|
+
try { if (statSync(path).size !== artifact.size) return null; } catch { return null; }
|
|
115
|
+
return { result, artifact, path };
|
|
116
|
+
}
|
|
117
|
+
export function artifactResponse(state: string, task: string, result: string, artifact: string, request: Request, download = false): Response {
|
|
118
|
+
const found = resolveArtifact(state, task, result, artifact); if (!found?.path) return new Response("Saved output is unavailable. Choose another result or retry preservation.", { status: 404 });
|
|
119
|
+
const a = found.artifact, forceDownload = download || a.preview === "download";
|
|
120
|
+
const name = a.name.replace(/["\\\r\n]/g, "_");
|
|
121
|
+
const headers = new Headers({ "Content-Type": a.mediaType, "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'; media-src 'self'; img-src 'self' data:", "Content-Disposition": `${forceDownload ? "attachment" : "inline"}; filename="${name.replace(/[^\x20-\x7e]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(name)}`, "Accept-Ranges": "bytes", "Cache-Control": "private, max-age=31536000, immutable" });
|
|
122
|
+
const file = Bun.file(found.path), range = request.headers.get("Range");
|
|
123
|
+
if (range) {
|
|
124
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(range); let start = 0, end = a.size - 1;
|
|
125
|
+
if (!match || (!match[1] && !match[2])) return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${a.size}` } });
|
|
126
|
+
if (!match[1]) start = Math.max(0, a.size - Number(match[2]));
|
|
127
|
+
else { start = Number(match[1]); if (match[2]) end = Math.min(end, Number(match[2])); }
|
|
128
|
+
if (start > end || start >= a.size || !Number.isSafeInteger(start) || !Number.isSafeInteger(end)) return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${a.size}` } });
|
|
129
|
+
headers.set("Content-Range", `bytes ${start}-${end}/${a.size}`); headers.set("Content-Length", String(end - start + 1));
|
|
130
|
+
return new Response(request.method === "HEAD" ? null : file.slice(start, end + 1), { status: 206, headers });
|
|
131
|
+
}
|
|
132
|
+
headers.set("Content-Length", String(a.size)); return new Response(request.method === "HEAD" ? null : file, { headers });
|
|
133
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Coordinates durable Tasks with the existing workflow launcher. The store never
|
|
2
|
+
// starts a process: launch intent is committed before this adapter calls the agent.
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { mkdirSync, readFileSync, writeFileSync, renameSync, existsSync } from 'node:fs';
|
|
5
|
+
import { join, dirname } from 'node:path';
|
|
6
|
+
import * as T from './tasks.ts';
|
|
7
|
+
import * as R from './task-results.ts';
|
|
8
|
+
import { read as scalar } from './config-values.ts';
|
|
9
|
+
import { detectDefaultAgent, home, readInbox, readRuns, readText, saveAttachment, acceptance, gateOf } from './state.ts';
|
|
10
|
+
|
|
11
|
+
type Hooks = { launch: (state:string, run:string, text:string, task:T.Task) => {ok:boolean; pty?:string; why?:string}; alive:(pty:string)=>boolean; stop:(pty:string)=>boolean };
|
|
12
|
+
const runtimeLaunches = new Set<string>();
|
|
13
|
+
const parse = (file:string) => { try { return JSON.parse(readFileSync(file,'utf8')); } catch { return null; } };
|
|
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); };
|
|
15
|
+
const stableUuid=(key:string)=>{const h=createHash('sha256').update(key).digest('hex');return `${h.slice(0,8)}-${h.slice(8,12)}-4${h.slice(13,16)}-a${h.slice(17,20)}-${h.slice(20,32)}`;};
|
|
16
|
+
const config = (state:string,key:string,fallback:string) => [join(state,'config.yml'),join(home,'.kaizen','config.yml')].map(f=>{try{return scalar(readText(f),key);}catch{return null;}}).find(x=>x!==null) ?? fallback;
|
|
17
|
+
export const taskDefaults = (state:string) => ({ agent: detectDefaultAgent(dirname(state)).name, workflow:config(state,'runner','full'), permissions:'Uses your configured account and tool permissions. Permission requests remain explicit in Technical details.' });
|
|
18
|
+
export function resultViews(state:string,id:string) {
|
|
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
|
+
}
|
|
21
|
+
export function taskView(state:string,task:T.Task) {
|
|
22
|
+
const p=T.taskProjection(task);
|
|
23
|
+
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};
|
|
25
|
+
}
|
|
26
|
+
export function taskList(states:string[],hooks?:Hooks) {
|
|
27
|
+
const tasks=states.flatMap(state=>T.listTasks(state).map(t=>taskView(state,reconcile(state,t,hooks))));
|
|
28
|
+
// Legacy rows become durable only when opened. Stable keys include stamps/index,
|
|
29
|
+
// never a title-based merge; existing inbox and run files are left intact.
|
|
30
|
+
for(const state of states) {
|
|
31
|
+
const adopted=new Set(T.listTasks(state).map(t=>t.legacyKey));
|
|
32
|
+
for(const run of readRuns(state)) {
|
|
33
|
+
if(adopted.has(`run:${run.id}`)||tasks.some(t=>t.dir===state&&t.runIds.includes(run.id)))continue;
|
|
34
|
+
const goal=readTextSafe(join(state,'runs',run.id,'00-request.md'))?.split('\n').find(l=>l.trim()&&!l.startsWith('#'))??run.id;
|
|
35
|
+
tasks.push({id:`legacy-run-${run.id}`,dir:state,title:goal.slice(0,160),goal,revision:0,updatedAt:run.moved,status:run.stage==='done'?'ready':'working',attention:{category:run.awaiting?'needs-you':'in-progress',reason:run.awaiting?'This existing task needs your decision.':`Existing work: ${run.stage}`,action:'Open task'},legacy:{kind:'run',id:run.id},runIds:[run.id]} as any);
|
|
36
|
+
}
|
|
37
|
+
readInbox(state).forEach((line:any,index:number)=>{const key=`inbox:${line.added??'legacy'}:${index}`;if(line.status!=='open'||adopted.has(key))return;tasks.push({id:`legacy-inbox-${index}`,dir:state,title:line.text,goal:line.text,revision:0,updatedAt:line.added??0,status:'draft',attention:{category:'needs-you',reason:'Ready to start',action:'Open task'},legacy:{kind:'inbox',index,added:line.added},runIds:[]} as any);});
|
|
38
|
+
}
|
|
39
|
+
const ranks:Record<string,number>={'needs-you':0,'in-progress':1,completed:2};
|
|
40
|
+
return tasks.sort((a,b)=>ranks[a.attention.category]-ranks[b.attention.category]||b.updatedAt-a.updatedAt);
|
|
41
|
+
}
|
|
42
|
+
const readTextSafe=(f:string)=>{try{return readText(f);}catch{return null;}};
|
|
43
|
+
export function reconcile(state:string,task:T.Task,hooks?:Hooks):T.Task {
|
|
44
|
+
let reason='';
|
|
45
|
+
if(task.status==='stopping'&&task.launch?.pty&&hooks&&!hooks.alive(task.launch.pty))return T.mutateTask(state,task.id,{revision:task.revision,opId:`stopped:${task.launch.id}`},T.confirmStopped);
|
|
46
|
+
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
|
+
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
|
+
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
|
+
return task;
|
|
50
|
+
}
|
|
51
|
+
function runState(state:string,task:T.Task) { return task.activeRun?parse(join(state,'runs',task.activeRun,'state.json')):null; }
|
|
52
|
+
export function dispatchReady(state:string,id:string,hooks:Hooks,initial=false):T.Task {
|
|
53
|
+
let task=T.readTask(state,id)!;
|
|
54
|
+
if(task.pendingDecision||task.queuePaused||!task.safe||task.status==='accepted')return task;
|
|
55
|
+
const previous=runState(state,task);
|
|
56
|
+
const finished=!previous||['done','abandoned'].includes(previous.stage);
|
|
57
|
+
const run=finished?`${new Date().toISOString().slice(0,10)}-task-${id.slice(0,8)}-${task.runIds.length+1}`:task.activeRun!;
|
|
58
|
+
let ids:string[]=[];
|
|
59
|
+
task=T.mutateTask(state,id,{revision:task.revision,opId:`dispatch:${task.revision}`},t=>{
|
|
60
|
+
const batch=T.dispatchInputs(t);ids=batch.map(i=>i.id);
|
|
61
|
+
if(!initial&&!batch.length)return;
|
|
62
|
+
const launch=T.beginLaunch(t,ids);launch.run=run;
|
|
63
|
+
t.activeRun=run;if(!t.runIds.includes(run))t.runIds.push(run);
|
|
64
|
+
});
|
|
65
|
+
if(!task.launch||task.launch.phase!=='intent')return task;
|
|
66
|
+
if(finished){
|
|
67
|
+
const folder=join(state,'runs',run);mkdirSync(folder,{recursive:true});
|
|
68
|
+
put(join(folder,'state.json'),{id:run,mode:config(state,'mode','auto'),runner:config(state,'runner','full'),agent:detectDefaultAgent(dirname(state)).cmd,track:'code',stage:'plan',awaiting:null,iteration:0,updated:new Date().toISOString(),task_id:id,task_policy:{requirePlanConfirmation:!task.initialConfirmed},...(task.initialConfirmed?{task_confirmed:{direction:'routine revision',at:Date.now()}}:{})});
|
|
69
|
+
writeFileSync(join(folder,'00-request.md'),(ids.length?task.inputs.filter(i=>ids.includes(i.id)).map(i=>i.text).join('\n\n'):task.goal)+`\n\nTask: ${id}\n`+(previous?`Follow-up of: ${previous.id}\n`:'')+task.files.map(f=>`Reference: ${f.name} (${f.path})`).join('\n'));
|
|
70
|
+
}
|
|
71
|
+
const context=JSON.stringify({task:id,launch:task.launch.id,inputIds:ids,currentResult:task.currentResult,initialConfirmed:task.initialConfirmed});
|
|
72
|
+
const command=`${JSON.stringify(process.execPath)} ${JSON.stringify(join(import.meta.dir,'install.ts'))}`;
|
|
73
|
+
const protocol=join(dirname(import.meta.dir),'skills','kaizen','spec.md');
|
|
74
|
+
const text=`Resume run ${run} for the persistent task. Read its state and request. Task context: ${context}. ${task.initialConfirmed?'Routine revision is authorized; preserve the accepted direction. Material scope changes require a new proposal.':'Perform intake/clarification and planning only. Publish a concise proposal and wait for explicit confirmation before any production, even in auto mode.'} Task protocol source: ${protocol}. Use the current implementation command ${command} task (the globally installed kaizen may be older). First acknowledge this launch with ${command} task event --task ${id} --run ${run} --json '${JSON.stringify({type:'ack',launchId:task.launch.id})}'. Structured event types: ack {launchId}, reply/question/proposal {text,details?,options?}, work {text}, receipt {inputIds,outcome:'applied'|'failed'}, boundary {text}, result {title,summary,artifacts:[{path|url,name?}],checks:[],limitations:[]}. Pass --operation a stable id for replay. A receipt acknowledges only dispatched ids; boundary means no active writes. Publish only settled completed files; never claim registration backend checks from a rendered form. Read the source workflow Task protocol. Inputs: ${task.inputs.filter(i=>ids.includes(i.id)).map(i=>`[${i.id}] ${i.text}`).join('\n')}`;
|
|
75
|
+
runtimeLaunches.add(task.launch.id);
|
|
76
|
+
let outcome;try{
|
|
77
|
+
const selected=detectDefaultAgent(dirname(state)), requested=config(state,'agent.default','auto');
|
|
78
|
+
outcome=requested!=='auto' && ![selected.cmd,selected.name].includes(requested) ? {ok:false,why:`Configured agent ${requested} is unavailable. Enable/install it or choose an available default in Settings, then retry. Your goal is saved.`} : hooks.launch(state,run,text,task);
|
|
79
|
+
}catch(e){outcome={ok:false,why:String(e)};}
|
|
80
|
+
task=T.readTask(state,id)!;
|
|
81
|
+
return T.mutateTask(state,id,{revision:task.revision,opId:`launched:${task.launch!.id}`},t=>{if(outcome.ok){if(t.launch!.phase==='intent')t.launch!.phase='started';if(outcome.pty)t.launch!.pty=outcome.pty;}else{t.status='failed';t.error=outcome.why||'Agent could not start. Your goal is saved.';t.launch!.phase='interrupted';t.queuePaused=true;} });
|
|
82
|
+
}
|
|
83
|
+
export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task:T.Task} {
|
|
84
|
+
const op=String(body.op??'');const operationId=String(body.operationId??'');if(!operationId)throw new T.TaskError('A request id is required',400);
|
|
85
|
+
if(op==='create'){
|
|
86
|
+
const goal=String(body.goal??'').trim();if(goal.length>50000)throw new T.TaskError('Goal is too long',400);
|
|
87
|
+
let task=T.createTask(state,{goal,project:state===join(home,'.kaizen')?null:dirname(state)},operationId);
|
|
88
|
+
if(body.files?.length&&!task.files.length){const files=body.files.map((f:any)=>{if(typeof f.name!=='string'||typeof f.data!=='string'||f.data.length>100_000_000)throw new T.TaskError('Invalid attachment',400);const path=saveAttachment(state,null,f.name,Buffer.from(f.data.replace(/^data:[^,]*,/,''),'base64'));return {name:f.name,path:join(state,path)};});task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':files'},t=>{t.files=files;});}
|
|
89
|
+
if(task.project&&task.runIds.length===0)task=dispatchReady(state,task.id,hooks,true);
|
|
90
|
+
return {state,task};
|
|
91
|
+
}
|
|
92
|
+
if(op==='adopt'){
|
|
93
|
+
const l=body.legacy??{};let goal='',key='';
|
|
94
|
+
if(l.kind==='run'){const run=readRuns(state).find(r=>r.id===l.id);if(!run)throw new T.TaskError('Existing run unavailable',404);key=`run:${run.id}`;goal=readTextSafe(join(state,'runs',run.id,'00-request.md'))??run.id;}else{const line=readInbox(state)[Number(l.index)];if(!line||line.added!==l.added)throw new T.TaskError('Task changed; refresh');key=`inbox:${line.added??'legacy'}:${l.index}`;goal=line.text;}
|
|
95
|
+
let task=T.adoptTask(state,key,{goal,project:dirname(state)});
|
|
96
|
+
if(l.kind==='run'&&!task.activeRun)task=T.mutateTask(state,task.id,{revision:task.revision,opId:`link:${l.id}`},t=>{
|
|
97
|
+
const file=join(state,'runs',l.id,'state.json'),run=parse(file);t.activeRun=l.id;t.runIds=[l.id];
|
|
98
|
+
const finished=run&&['done','abandoned'].includes(run.stage);
|
|
99
|
+
if(finished){
|
|
100
|
+
const report=readTextSafe(join(state,'runs',l.id,'03-impl.md'))??'',preview=/^## Preview[^\n]*\n([\s\S]*?)(?=^## |$(?![\s\S]))/m.exec(report)?.[1]??'';
|
|
101
|
+
const artifacts:R.ArtifactInput[]=[];
|
|
102
|
+
for(const m of preview.matchAll(/!?\[([^\]]*)\]\((attachments\/[^)]+)\)/g))artifacts.push({name:m[1]||undefined,path:join(state,'runs',l.id,m[2])});
|
|
103
|
+
for(const m of preview.matchAll(/https?:\/\/[^\s<>\)]+/g)){const url=R.liveUrl(m[0]);if(url&&!artifacts.some(a=>a.url===url))artifacts.push({url,name:'Existing live preview (mutable)'});}
|
|
104
|
+
if(artifacts.length){
|
|
105
|
+
try{const result=R.publishResult(state,t.id,{runId:l.id,title:'Existing result',summary:'Preserved from the existing run Preview.',artifacts,roots:[dirname(state)],limitations:['Legacy checks are available in Technical details. Live links remain mutable; only copied files are preserved.'],id:stableUuid(`legacy-result:${t.id}:${l.id}`)});t.currentResult=result.id;t.status='ready';t.safe=true;}
|
|
106
|
+
catch(e){t.status='failed';t.error=(e as Error).message;}
|
|
107
|
+
}else{t.status='interrupted';t.error='This earlier run has no typed result or Preview output. Its files and evidence remain in Technical details. Resume to publish a result.';}
|
|
108
|
+
}else{
|
|
109
|
+
const plan=readTextSafe(join(state,'runs',l.id,'01-plan.md'));
|
|
110
|
+
put(file,{...run,task_id:t.id,task_policy:{requirePlanConfirmation:run.awaiting==='approvals.plan'}});
|
|
111
|
+
if(run.awaiting==='approvals.plan'&&plan){t.pendingDecision={id:randomUUID(),kind:'proposal',text:'Review the existing plan before production continues.',details:plan,run:l.id,iteration:run.iteration??0,result:null};t.status='waiting';t.safe=true;}
|
|
112
|
+
else{t.status='interrupted';t.error='Existing work is preserved. Review its current session in Technical details before resuming.';}
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
return {state,task};
|
|
116
|
+
}
|
|
117
|
+
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
|
+
const mutation={revision:Number(body.revision),opId:operationId};
|
|
119
|
+
if(task.operations.includes(operationId))return {state,task};
|
|
120
|
+
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)};}
|
|
121
|
+
task=T.mutateTask(state,task.id,mutation,t=>{
|
|
122
|
+
if(op==='message'){
|
|
123
|
+
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);
|
|
124
|
+
if(status){T.receiveInput(t,{id:operationId,text,intent:'status',baseResult:body.baseResultId??null});return;}
|
|
125
|
+
const answer=t.pendingDecision?.kind==='question';
|
|
126
|
+
if(body.intent==='auto'&&!answer&&!/^(please |can you |could you |i want |change|add|remove|make|update|fix|replace|create|build|use|set|move|delete|show|hide|increase|reduce|rewrite)/i.test(text)){T.addEvent(t,'user','message',text);t.pendingDecision={id:randomUUID(),kind:'question',text:'Should I treat that as a change request? Send the change with Request change, or ask for status.',run:t.activeRun,iteration:0,result:t.currentResult,options:['Request change','Status']};t.status='waiting';return;}
|
|
127
|
+
T.receiveInput(t,{id:operationId,text,intent:answer?'answer':'change',baseResult:body.baseResultId??null});
|
|
128
|
+
if(answer||t.pendingDecision?.kind==='proposal'){t.pendingDecision=null;t.safe=true;t.status='draft';}
|
|
129
|
+
}else if(op==='stop'){T.requestStop(t);}
|
|
130
|
+
else if(op==='resume'){if(t.launch?.pty&&hooks.alive(t.launch.pty))throw new T.TaskError('The existing agent is still alive. Stop it or reconcile it in Technical details before resuming.');T.resumeTask(t);}
|
|
131
|
+
else if(op==='accept'){
|
|
132
|
+
const run=runState(state,t);if(run&&!['done','abandoned'].includes(run.stage)&&!run.healed)throw new T.TaskError('Workflow checks are still running. Wait for completed work before accepting.');
|
|
133
|
+
if(run?.awaiting&&!run.healed)throw new T.TaskError('Resolve the blocking workflow decision first.');
|
|
134
|
+
T.acceptTask(t,String(body.resultId??''));
|
|
135
|
+
}else if(op==='confirm'){
|
|
136
|
+
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.');
|
|
137
|
+
const file=join(state,'runs',t.activeRun!,'state.json'),run=parse(file);if(!run||Number(run.iteration??0)!==d.iteration||(run.awaiting!=='approvals.plan'&&run.task_confirmed?.proposal!==d.id))throw new T.TaskError('This run is no longer waiting for this proposal.');
|
|
138
|
+
put(file,{...run,task_confirmed:{proposal:d.id,iteration:d.iteration,at:Date.now()},awaiting:null});
|
|
139
|
+
const approval=join(state,'runs',t.activeRun!,'02-approval.md');writeFileSync(approval,(readTextSafe(approval)??'')+`\nTask proposal ${d.id} explicitly confirmed by user via board at ${new Date().toISOString()}.\n`);
|
|
140
|
+
t.initialConfirmed=true;t.pendingDecision=null;t.safe=true;t.status='draft';T.addEvent(t,'user','confirm','Proposal confirmed.');
|
|
141
|
+
// The same run continues with a durable input receipt.
|
|
142
|
+
T.receiveInput(t,{id:operationId+':continue',text:'The current proposal is confirmed. Continue production under the frozen task policy.',intent:'answer',baseResult:t.currentResult});
|
|
143
|
+
}else throw new T.TaskError('Unknown task action',400);
|
|
144
|
+
});
|
|
145
|
+
if(op==='stop'){
|
|
146
|
+
const key=task.launch?.pty;if(key&&hooks.alive(key))hooks.stop(key);
|
|
147
|
+
else if(key)task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':stopped'},T.confirmStopped);
|
|
148
|
+
else task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':unsupported'},t=>{t.error='This agent is outside the board. Stop it in Technical details and confirm its session has ended before resuming.';});
|
|
149
|
+
}else if(['message','confirm','resume'].includes(op))task=dispatchReady(state,task.id,hooks,op==='resume'&&!task.inputs.some(i=>['queued','received'].includes(i.state)));
|
|
150
|
+
return {state,task};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// CLI-only structured events. Raw terminal text is never an acknowledgement.
|
|
154
|
+
export function taskEvent(state:string,id:string,runId:string,event:any,operationId:string):T.Task {
|
|
155
|
+
const task=T.readTask(state,id);if(!task||task.activeRun!==runId)throw new T.TaskError('This run does not own the task');
|
|
156
|
+
try { return T.mutateTask(state,id,{revision:task.revision,opId:operationId},t=>{
|
|
157
|
+
const run=runState(state,t);if(!run||run.task_id!==id)throw new T.TaskError('Run task identity does not match');
|
|
158
|
+
if(event.type==='ack'){T.acknowledgeLaunch(t,String(event.launchId),runId,t.launch?.pty);}
|
|
159
|
+
else if(event.type==='reply'){T.addEvent(t,'assistant','reply',String(event.text??''));}
|
|
160
|
+
else if(event.type==='question'||event.type==='proposal'){
|
|
161
|
+
if(!event.text?.trim())throw new T.TaskError('Question/proposal text is required',400);
|
|
162
|
+
t.pendingDecision={id:randomUUID(),kind:event.type,text:String(event.text),run:runId,iteration:run.iteration??0,result:t.currentResult,...(event.details?{details:String(event.details)}:{}),...(Array.isArray(event.options)?{options:event.options.map(String)}:{})};t.status='waiting';t.safe=true;T.addEvent(t,'assistant',event.type,event.text);
|
|
163
|
+
if(t.launch)t.launch.phase='acknowledged';
|
|
164
|
+
if(event.type==='proposal')put(join(state,'runs',runId,'state.json'),{...run,awaiting:'approvals.plan',task_policy:{requirePlanConfirmation:true},task_confirmed:null});
|
|
165
|
+
}else if(event.type==='work'){
|
|
166
|
+
if(run.task_policy?.requirePlanConfirmation&&!run.task_confirmed)throw new T.TaskError('Proposal confirmation is required before production');
|
|
167
|
+
t.safe=false;t.status='working';T.addEvent(t,'assistant','work',String(event.text??'Working on the task'));
|
|
168
|
+
}else if(event.type==='receipt'){T.acknowledgeInputs(t,event.inputIds??[],event.outcome==='failed'?'failed':'applied',event.error);}
|
|
169
|
+
else if(event.type==='boundary'){T.safeBoundary(t,runId,String(event.text??'Work reached a safe boundary'));}
|
|
170
|
+
else if(event.type==='result'){
|
|
171
|
+
if(run.task_policy?.requirePlanConfirmation&&!run.task_confirmed)throw new T.TaskError('Proposal confirmation is required');
|
|
172
|
+
if(t.inputs.some(i=>i.state==='dispatched'))throw new T.TaskError('Acknowledge the dispatched requests before publishing a result');
|
|
173
|
+
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}`)});
|
|
174
|
+
t.currentResult=result.id;t.acceptedResult=null;t.status='ready';t.safe=true;t.pendingDecision=null;if(t.launch)t.launch.phase='acknowledged';T.addEvent(t,'assistant','result',String(event.summary??event.title??'Result ready'));
|
|
175
|
+
}else throw new T.TaskError('Unknown task event',400);
|
|
176
|
+
}); } catch (error) {
|
|
177
|
+
if(event.type==='result'){const current=T.readTask(state,id)!;T.mutateTask(state,id,{revision:current.revision,opId:operationId+':preservation-failed'},t=>{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.`);});}
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|