wildcrane 0.11.44 → 0.11.45

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.
Files changed (2) hide show
  1. package/dist/kanban.mjs +1334 -892
  2. package/package.json +2 -2
package/dist/kanban.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.44 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
2
+ // ai4kanban 0.11.45 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
3
3
  // Do not edit: every change belongs in cli/src/, and a build overwrites this file.
4
4
  import { createRequire as __ai4kanbanRequire } from 'node:module'
5
5
  const require = __ai4kanbanRequire(import.meta.url)
@@ -51,27 +51,66 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
51
51
  mod
52
52
  ));
53
53
 
54
- // src/lib/cloud/config.ts
55
- function cloudEndpoints() {
56
- return {
57
- supabaseUrl: trimSlash(process.env.AI4KANBAN_SUPABASE_URL || SUPABASE_URL),
58
- anonKey: process.env.AI4KANBAN_SUPABASE_ANON_KEY || SUPABASE_ANON_KEY,
59
- api: trimSlash(process.env.AI4KANBAN_CLOUD_URL || API_URL)
60
- };
54
+ // src/lib/io.ts
55
+ function startCollecting() {
56
+ sink = { out: [], warnings: [] };
57
+ return sink;
61
58
  }
62
- function cloudConfigured() {
63
- const { supabaseUrl, anonKey } = cloudEndpoints();
64
- return !!supabaseUrl && !!anonKey;
59
+ function stopCollecting() {
60
+ sink = null;
65
61
  }
66
- var SUPABASE_URL, SUPABASE_ANON_KEY, API_URL, trimSlash, NOT_CONFIGURED;
67
- var init_config = __esm({
68
- "src/lib/cloud/config.ts"() {
62
+ function quietly(fn) {
63
+ const before = sink;
64
+ sink = { out: [], warnings: [] };
65
+ try {
66
+ return fn();
67
+ } finally {
68
+ sink = before;
69
+ }
70
+ }
71
+ async function quietlyAsync(fn) {
72
+ const before = sink;
73
+ sink = { out: [], warnings: [] };
74
+ try {
75
+ return await fn();
76
+ } finally {
77
+ sink = before;
78
+ }
79
+ }
80
+ function say(line = "") {
81
+ const text4 = String(line);
82
+ if (sink) sink.out.push(...text4.split("\n"));
83
+ else console.log(text4);
84
+ }
85
+ function warn(message) {
86
+ if (sink) sink.warnings.push(String(message));
87
+ else console.error(`kanban: warning \u2014 ${message}`);
88
+ }
89
+ var BoardError, sink;
90
+ var init_io = __esm({
91
+ "src/lib/io.ts"() {
69
92
  "use strict";
70
- SUPABASE_URL = "https://yajrbpprmdvtkvjjfpbk.supabase.co";
71
- SUPABASE_ANON_KEY = "sb_publishable_ioUQ23BTtoj8NKqndp0Jrw_omVR3m4n";
72
- API_URL = "https://api.ai4kanban.dev";
73
- trimSlash = (url) => url.replace(/\/+$/, "");
74
- NOT_CONFIGURED = "This build of WildCrane carries no Cloud project to sign in against.";
93
+ BoardError = class extends Error {
94
+ // `kind` is the machine-readable name of the refusal (card-not-found, no-board,
95
+ // unknown-module, …). It is what a caller reads; the exit code stays 1 for every
96
+ // refusal, so nobody has to keep a table of numbers.
97
+ kind;
98
+ // Only `cloud image` / `cloud tts` set it: 2 for a usage error, as the scripts they replaced did.
99
+ exitCode;
100
+ // `bare` says the message is already the whole thing a person should see — a usage
101
+ // block, say — so the dispatcher prints it without putting the command in front of it.
102
+ bare;
103
+ details;
104
+ constructor(message, { kind = "refused", bare = false, exitCode = 1, ...details } = {}) {
105
+ super(message);
106
+ this.name = "BoardError";
107
+ this.kind = kind;
108
+ this.bare = bare;
109
+ this.exitCode = exitCode;
110
+ this.details = details;
111
+ }
112
+ };
113
+ sink = null;
75
114
  }
76
115
  });
77
116
 
@@ -87,643 +126,637 @@ var init_home = __esm({
87
126
  }
88
127
  });
89
128
 
90
- // src/lib/cloud/session.ts
129
+ // src/lib/machine/project.ts
130
+ import { createHash } from "node:crypto";
91
131
  import fs from "node:fs";
92
132
  import path2 from "node:path";
93
- function readSession() {
94
- let raw;
95
- try {
96
- raw = fs.readFileSync(sessionFile(), "utf8");
97
- } catch {
98
- return null;
99
- }
100
- try {
101
- const held4 = JSON.parse(raw);
102
- if (!held4.accessToken || !held4.refreshToken || !held4.subject) return null;
103
- if (held4.supabaseUrl !== cloudEndpoints().supabaseUrl) return null;
104
- return { ...held4, version: 1, expiresAt: Number(held4.expiresAt) || 0 };
105
- } catch {
106
- return null;
133
+ function realPathOf(dir) {
134
+ const here = path2.resolve(dir);
135
+ const rest = [];
136
+ let at = here;
137
+ for (; ; ) {
138
+ try {
139
+ return path2.join(fs.realpathSync(at), ...rest);
140
+ } catch {
141
+ const up = path2.dirname(at);
142
+ if (up === at) return here;
143
+ rest.unshift(path2.basename(at));
144
+ at = up;
145
+ }
107
146
  }
108
147
  }
109
- function writeSession(session) {
110
- fs.mkdirSync(machineHome(), { recursive: true, mode: 448 });
111
- const tmp = `${sessionFile()}.${process.pid}.tmp`;
112
- fs.writeFileSync(tmp, `${JSON.stringify(session, null, 2)}
113
- `, { mode: 384 });
114
- fs.renameSync(tmp, sessionFile());
148
+ function readableName(real2) {
149
+ const here = path2.basename(real2);
150
+ const up = path2.dirname(real2);
151
+ if (here !== "kanban") return slug(here);
152
+ return path2.basename(up) === "docs" ? slug(path2.basename(path2.dirname(up))) : slug(`${path2.basename(up)}-kanban`);
115
153
  }
116
- function clearSession() {
117
- try {
118
- fs.rmSync(sessionFile());
119
- } catch {
154
+ function legacyProjectStateDir(board2) {
155
+ const real2 = realPathOf(board2);
156
+ const id = createHash("sha256").update(real2).digest("hex").slice(0, ID_LENGTH);
157
+ return path2.join(machineHome(), PROJECTS, `${readableName(real2)}-${id}`);
158
+ }
159
+ function stateRootOf(board2) {
160
+ let dir = realPathOf(board2);
161
+ for (; ; ) {
162
+ if (fs.existsSync(path2.join(dir, ".git"))) return dir;
163
+ const up = path2.dirname(dir);
164
+ if (up === dir) break;
165
+ dir = up;
120
166
  }
167
+ return rootAbove(realPathOf(board2));
121
168
  }
122
- async function accessToken() {
123
- const held4 = readSession();
124
- if (!held4) return { ok: false, reason: "signed-out" };
125
- if (!expiringSoon(held4)) return { ok: true, token: held4.accessToken, session: held4 };
126
- return refresh();
169
+ function rootAbove(board2) {
170
+ const parent = path2.dirname(board2);
171
+ return ["docs", ".akb"].includes(path2.basename(parent)) ? path2.dirname(parent) : parent;
127
172
  }
128
- async function refresh() {
129
- const lock = await takeLock();
130
- try {
131
- const now = readSession();
132
- if (!now) return { ok: false, reason: "signed-out" };
133
- if (!expiringSoon(now)) return { ok: true, token: now.accessToken, session: now };
134
- const { api, anonKey } = cloudEndpoints();
135
- let response;
136
- try {
137
- response = await fetch(`${api}/auth/v1/token?grant_type=refresh_token`, {
138
- method: "POST",
139
- headers: { apikey: anonKey, "content-type": "application/json" },
140
- body: JSON.stringify({ refresh_token: now.refreshToken })
141
- });
142
- } catch (e) {
143
- return { ok: false, reason: "unreachable", error: e instanceof Error ? e.message : String(e) };
144
- }
145
- if (!response.ok) {
146
- const body = await response.json().catch(() => ({}));
147
- if (response.status >= 500) {
148
- return { ok: false, reason: "unreachable", error: body.error_description ?? `Cloud answered ${response.status}` };
149
- }
150
- return { ok: false, reason: "expired", error: body.error_description };
151
- }
152
- const fresh = sessionFrom(await response.json(), now);
153
- if (!fresh) return { ok: false, reason: "expired" };
154
- const current = readSession();
155
- if (!current || current.subject !== now.subject) return { ok: false, reason: "expired" };
156
- if (current.refreshToken !== now.refreshToken) return { ok: true, token: current.accessToken, session: current };
157
- writeSession(fresh);
158
- return { ok: true, token: fresh.accessToken, session: fresh };
159
- } finally {
160
- lock();
173
+ function projectStateDir(board2, root2 = stateRootOf(board2)) {
174
+ const relative = path2.relative(realPathOf(root2), realPathOf(board2));
175
+ if (relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative)) {
176
+ throw new Error("The board must be inside its project root.");
161
177
  }
178
+ return path2.join(realPathOf(root2), ".akb", "boards", relative || "_root");
162
179
  }
163
- function sessionFrom(body, previous) {
164
- const token2 = body;
165
- const subject = token2.user?.id ?? previous?.subject;
166
- if (!token2.access_token || !token2.refresh_token || !subject) return null;
167
- const expiresAt = token2.expires_at ? token2.expires_at * 1e3 : Date.now() + (token2.expires_in ?? 3600) * 1e3;
168
- return {
169
- version: 1,
170
- supabaseUrl: cloudEndpoints().supabaseUrl,
171
- accessToken: token2.access_token,
172
- refreshToken: token2.refresh_token,
173
- expiresAt,
174
- subject,
175
- email: token2.user?.email ?? previous?.email,
176
- handle: previous?.handle,
177
- name: previous?.name,
178
- avatarUrl: previous?.avatarUrl,
179
- avatar: previous?.avatar
180
- };
181
- }
182
- async function takeLock() {
183
- const until = Date.now() + LOCK_WAIT_MS;
184
- for (; ; ) {
180
+ function ensureProjectState(board2, root2 = stateRootOf(board2)) {
181
+ const dir = projectStateDir(board2, root2);
182
+ if (!fs.existsSync(dir)) {
183
+ const legacy2 = legacyProjectStateDir(board2);
184
+ fs.mkdirSync(path2.dirname(dir), { recursive: true });
185
+ const temporary = fs.mkdtempSync(`${dir}.import-`);
185
186
  try {
186
- fs.mkdirSync(machineHome(), { recursive: true, mode: 448 });
187
- fs.mkdirSync(lockDir());
187
+ if (fs.existsSync(legacy2)) fs.cpSync(legacy2, temporary, {
188
+ recursive: true,
189
+ filter: (source) => ![".lock", ".answering"].some((suffix) => path2.basename(source).endsWith(suffix))
190
+ });
188
191
  try {
189
- fs.writeFileSync(lockOwner(), `${process.pid}
190
- `);
191
- } catch {
192
- }
193
- return () => {
194
- try {
195
- fs.rmSync(lockDir(), { recursive: true, force: true });
196
- } catch {
197
- }
198
- };
199
- } catch (err) {
200
- if (err.code !== "EEXIST") throw err;
201
- if (stale()) {
202
- fs.rmSync(lockDir(), { recursive: true, force: true });
203
- continue;
192
+ fs.renameSync(temporary, dir);
193
+ } catch (err) {
194
+ if (!["EEXIST", "ENOTEMPTY"].includes(err.code ?? "")) throw err;
204
195
  }
205
- if (Date.now() > until) return () => {
206
- };
207
- await sleep(LOCK_RETRY_MS);
196
+ } finally {
197
+ fs.rmSync(temporary, { recursive: true, force: true });
208
198
  }
209
199
  }
210
- }
211
- function stale() {
212
- let held4;
213
- try {
214
- const pid = Number(fs.readFileSync(lockOwner(), "utf8").trim());
215
- held4 = Number.isInteger(pid) && pid > 0 ? pid : void 0;
216
- } catch {
217
- held4 = void 0;
218
- }
219
- if (held4 !== void 0 && !alive(held4)) return true;
220
- try {
221
- return Date.now() - fs.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
222
- } catch {
223
- return false;
200
+ if (recordedBoard(dir) !== realPathOf(board2)) {
201
+ fs.writeFileSync(path2.join(dir, RECORD), `${JSON.stringify({ board: realPathOf(board2) })}
202
+ `);
224
203
  }
204
+ return dir;
225
205
  }
226
- function alive(pid) {
206
+ function recordedBoard(dir) {
227
207
  try {
228
- process.kill(pid, 0);
229
- return true;
230
- } catch (e) {
231
- return e.code === "EPERM";
208
+ const held4 = JSON.parse(fs.readFileSync(path2.join(dir, RECORD), "utf8"));
209
+ return typeof held4.board === "string" ? held4.board : null;
210
+ } catch {
211
+ return null;
232
212
  }
233
213
  }
234
- var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep;
235
- var init_session = __esm({
236
- "src/lib/cloud/session.ts"() {
214
+ var PROJECTS, ID_LENGTH, RECORD, SESSIONS_FILE, SESSIONS_FOLDER, ASSETS_FOLDER, MOCKUPS_FOLDER, SESSIONS_LOCK, INDEX_LOCK, UI_CONFIG_FILE, slug;
215
+ var init_project = __esm({
216
+ "src/lib/machine/project.ts"() {
237
217
  "use strict";
238
218
  init_home();
239
- init_config();
240
- REFRESH_MARGIN_MS = 6e4;
241
- LOCK_STALE_MS = 3e4;
242
- LOCK_WAIT_MS = 2e4;
243
- LOCK_RETRY_MS = 50;
244
- sessionFile = () => path2.join(machineHome(), "session.json");
245
- lockDir = () => path2.join(machineHome(), "session.lock");
246
- lockOwner = () => path2.join(lockDir(), "owner");
247
- expiringSoon = (session) => session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
248
- sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
219
+ PROJECTS = "projects";
220
+ ID_LENGTH = 10;
221
+ RECORD = "board.json";
222
+ SESSIONS_FILE = "sessions.json";
223
+ SESSIONS_FOLDER = "sessions";
224
+ ASSETS_FOLDER = "assets";
225
+ MOCKUPS_FOLDER = "mockups";
226
+ SESSIONS_LOCK = "sessions.lock";
227
+ INDEX_LOCK = "index.lock";
228
+ UI_CONFIG_FILE = "ui.config.json";
229
+ slug = (text4) => text4.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "board";
249
230
  }
250
231
  });
251
232
 
252
- // src/lib/cloud/tasks.ts
253
- import crypto from "node:crypto";
233
+ // src/lib/paths.ts
234
+ import { spawnSync } from "node:child_process";
254
235
  import fs2 from "node:fs";
255
236
  import path3 from "node:path";
256
- function workspaceTask() {
257
- const id = process.env[TASK_ENV];
258
- return id && id.trim() ? id.trim() : null;
237
+ function boardLockName(kanban, root2) {
238
+ const from = path3.relative(root2, kanban);
239
+ const name = from && !from.startsWith("..") ? from : path3.basename(kanban);
240
+ return `${name.split(path3.sep).join("-")}.lock`;
259
241
  }
260
- function cloudStudio(name) {
261
- if (/^wf-/.test(name)) return name.replace("-", "_");
262
- return `wf_builtin_${name.replace(/-/g, "_")}`;
242
+ function ensureAkbDir() {
243
+ fs2.mkdirSync(AKB_DIR, { recursive: true });
244
+ writeRootIgnoreIfMissing();
245
+ return AKB_DIR;
263
246
  }
264
- async function call(method, route2, body, key) {
265
- if (!cloudConfigured()) return { ok: false, error: NOT_CONFIGURED, code: "bad_request" };
266
- const token2 = await accessToken();
267
- if (!token2.ok) {
268
- return token2.reason === "unreachable" ? { ok: false, error: `Cloud could not be reached: ${token2.error}` } : { ok: false, error: token2.reason === "expired" ? "Cloud sign-in has expired. Sign in again." : "This machine is not signed in to Cloud.", code: "unauthenticated" };
269
- }
270
- let response;
271
- try {
272
- response = await fetch(`${cloudEndpoints().api}${route2}`, {
273
- method,
274
- headers: {
275
- authorization: `Bearer ${token2.token}`,
276
- ...body ? { "content-type": "application/json" } : {},
277
- ...key ? { "idempotency-key": key } : {}
278
- },
279
- ...body ? { body: JSON.stringify(body) } : {},
280
- signal: AbortSignal.timeout(2e4)
281
- });
282
- } catch (e) {
283
- return { ok: false, error: `Cloud could not be reached: ${e instanceof Error ? e.message : String(e)}` };
247
+ function writeRootIgnoreIfMissing() {
248
+ const text4 = fs2.existsSync(ROOT_GITIGNORE) ? fs2.readFileSync(ROOT_GITIGNORE, "utf8") : "";
249
+ if (text4.split("\n").some((line) => line.trim() === AKB_IGNORE_LINE)) return false;
250
+ const ignored = spawnSync("git", ["-C", REPO_ROOT, "check-ignore", "-q", AKB_IGNORE_LINE], { stdio: "ignore" }).status;
251
+ if (ignored === 0 || ignored === 128 && KANBAN.startsWith(AKB_DIR + path3.sep)) return false;
252
+ const separator = !text4 || text4.endsWith("\n") ? "" : "\n";
253
+ const block = `# Delivery state \u2014 worktrees and the like. Never committed.
254
+ ${AKB_IGNORE_LINE}
255
+ `;
256
+ fs2.writeFileSync(ROOT_GITIGNORE, `${text4}${separator}${block}`);
257
+ return true;
258
+ }
259
+ function projectRootOf(board2) {
260
+ let dir = path3.resolve(board2);
261
+ for (; ; ) {
262
+ if (fs2.existsSync(path3.join(dir, ".git"))) return dir;
263
+ const up = path3.dirname(dir);
264
+ if (up === dir) return rootAbove(path3.resolve(board2));
265
+ dir = up;
284
266
  }
285
- const parsed = await response.json().catch(() => ({}));
286
- if (!response.ok) return { ok: false, code: parsed.error?.code ?? "refused", error: parsed.error?.message ?? `Cloud answered ${response.status}.` };
287
- return { ok: true, value: parsed, replayed: response.headers.get("idempotent-replayed") === "true" };
288
267
  }
289
- async function createTask(from, said2) {
290
- const source = await call("GET", `/v1/tasks/${encodeURIComponent(from)}`);
291
- if (!source.ok) return source;
292
- const studio = said2.studio ? cloudStudio(said2.studio) : source.value.studio?.id;
293
- const body = {
294
- title: said2.title,
295
- project: source.value.project,
296
- ...studio ? { studio } : {},
297
- ...said2.request?.trim() ? { request: said2.request.trim() } : {},
298
- source: "api",
299
- source_context: { task: from, ...said2.agent ? { agent: said2.agent } : {} },
300
- ...said2.run ? { run: true } : {},
301
- ...said2.metadata && Object.keys(said2.metadata).length ? { metadata: said2.metadata } : {},
302
- ...said2.triage ? { triage: `tri_${source.value.project.replace(/^prj_/, "")}_${said2.triage}` } : {}
303
- };
304
- const key = `akb-${crypto.createHash("sha256").update(`${from}
305
- ${said2.slug?.trim() || said2.title}`).digest("hex").slice(0, 40)}`;
306
- const made = await call("POST", "/v1/tasks", body, key);
307
- if (!made.ok) return made;
308
- const number = numberOf(made.value.key);
309
- if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
310
- return { ok: true, value: { task: made.value, number, from: source.value, replayed: made.replayed === true } };
268
+ function setBoard(kanban, root2, flag) {
269
+ REPO_ROOT = path3.resolve(root2);
270
+ KANBAN = path3.resolve(kanban);
271
+ BOARD_FLAG = flag;
272
+ TODO = path3.join(KANBAN, "todo");
273
+ ARCHIVE = path3.join(KANBAN, ".archive");
274
+ ARCHIVE_MD = path3.join(KANBAN, "archive.md");
275
+ README = path3.join(TODO, "README.md");
276
+ MODULES_MD = path3.join(KANBAN, "modules.md");
277
+ CONFIG = path3.join(KANBAN, "config.md");
278
+ KANBAN_GITIGNORE = path3.join(KANBAN, ".gitignore");
279
+ RELEASES = path3.join(KANBAN, "releases.md");
280
+ RELEASE_SUMMARIES = path3.join(KANBAN, ".release-summaries");
281
+ AGENTS = path3.join(KANBAN, "agents");
282
+ STUDIOS = path3.join(KANBAN, "studios");
283
+ LEGACY_AGENTS = path3.join(KANBAN, "skills");
284
+ MEMORY = path3.join(KANBAN, "memory");
285
+ AGENT_MEMORY = path3.join(MEMORY, "agents");
286
+ PROJECT_MD = path3.join(MEMORY, "project.md");
287
+ LEGACY_UI_CONFIG = path3.join(KANBAN, UI_CONFIG_FILE);
288
+ LOCAL_CONFIG = path3.join(KANBAN, ".local.json");
289
+ ENV_FILE = path3.join(KANBAN, ".env");
290
+ const machine = projectStateDir(KANBAN, REPO_ROOT);
291
+ BOARD_STATE = machine;
292
+ UI_CONFIG = path3.join(machine, UI_CONFIG_FILE);
293
+ ASSETS = path3.join(machine, ASSETS_FOLDER);
294
+ MOCKUPS = path3.join(machine, MOCKUPS_FOLDER);
295
+ SESSIONS = path3.join(machine, SESSIONS_FILE);
296
+ SESSIONS_DIR = path3.join(machine, SESSIONS_FOLDER);
297
+ SESSIONS_LOCK2 = path3.join(machine, SESSIONS_LOCK);
298
+ INDEX_LOCK2 = path3.join(machine, INDEX_LOCK);
299
+ DELIVERIES = path3.join(KANBAN, "deliveries");
300
+ RULES = path3.join(KANBAN, "rules");
301
+ PLANS = path3.join(machine, "plans");
302
+ PLANS_ARCHIVE = path3.join(PLANS, "archive");
303
+ TRIAGE = path3.join(KANBAN, "triage");
304
+ SIGNALS_ARCHIVED = path3.join(TRIAGE, "archived");
305
+ SIGNALS_DISMISSED = path3.join(TRIAGE, "dismissed");
306
+ SIGNALS_FILES = path3.join(TRIAGE, "files");
307
+ SIGNALS_OLD_INBOX = path3.join(TRIAGE, "inbox");
308
+ SIGNALS_OLD_HANDLED = path3.join(TRIAGE, "handled.md");
309
+ AKB_DIR = path3.join(REPO_ROOT, ".akb");
310
+ ROOT_GITIGNORE = path3.join(REPO_ROOT, ".gitignore");
311
+ LOCK = path3.join(AKB_DIR, boardLockName(KANBAN, REPO_ROOT));
312
+ return REPO_ROOT;
311
313
  }
312
- function runnerProject(board2) {
313
- if (path3.basename(board2) !== "kanban" || path3.basename(path3.dirname(board2)) !== ".akb") return null;
314
- const linked2 = linkedProject(board2, path3.dirname(path3.dirname(board2)));
315
- return linked2.ok ? linked2.value : null;
314
+ function setBoardRoot(root2, named2 = false) {
315
+ const project2 = path3.resolve(root2);
316
+ return setBoard(path3.join(project2, "docs", "kanban"), project2, named2 ? ` --dir ${project2}` : "");
316
317
  }
317
- function linkedProject(board2, root2) {
318
- const file = path3.join(root2, ".akb", "base.json");
319
- if (!fs2.existsSync(file)) return { ok: true, value: null };
320
- try {
321
- const base = JSON.parse(fs2.readFileSync(file, "utf8"));
322
- if (!base || typeof base !== "object" || base.project !== void 0 && (typeof base.project !== "string" || !base.project.trim()) || base.files !== void 0 && (!base.files || typeof base.files !== "object" || Array.isArray(base.files))) throw new Error();
323
- const projects = new Set(Object.keys(base.files ?? {}).flatMap((p) => /^projects\/([^/]+)\//.exec(p)?.[1] ?? []));
324
- if (typeof base.project === "string") projects.add(base.project);
325
- if (projects.size !== 1) throw new Error();
326
- return { ok: true, value: [...projects][0] };
327
- } catch {
328
- return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
329
- }
318
+ function setBoardDir(board2, root2) {
319
+ const folder = path3.resolve(board2);
320
+ return setBoard(folder, root2 ?? projectRootOf(folder), ` --board ${folder}`);
330
321
  }
331
- async function creationProject(board2, root2, task = workspaceTask()) {
332
- const link2 = linkedProject(board2, root2);
333
- if (!link2.ok) return link2;
334
- let project2 = link2.value;
335
- if (task) {
336
- const source = await call("GET", `/v1/tasks/${encodeURIComponent(task)}`);
337
- if (!source.ok) return {
338
- ...source,
339
- error: source.code === "forbidden" ? "Cannot access this task. Check your account and task access in WildCrane, then try again." : source.code === "not_found" ? "This task does not exist. Start a new task from the WildCrane web app." : source.error
340
- };
341
- if (project2 && project2 !== source.value.project) return { ok: false, error: "The source task conflicts with this board\u2019s project link.", code: "invalid-link" };
342
- project2 = source.value.project;
343
- }
344
- if (!project2) return { ok: false, error: "This board is not linked to a Cloud project.", code: "unlinked" };
345
- const checked = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
346
- return checked.ok ? { ok: true, value: project2 } : checked;
322
+ function die(msg, kind) {
323
+ throw new BoardError(msg, typeof kind === "string" ? { kind } : kind);
347
324
  }
348
- async function createProjectTask(project2, said2, key) {
349
- const made = await call("POST", "/v1/tasks", {
350
- title: said2.title,
351
- project: project2,
352
- source: "api",
353
- ...said2.studio ? { studio: cloudStudio(said2.studio) } : {},
354
- ...said2.request?.trim() ? { request: said2.request.trim() } : {},
355
- ...said2.agent ? { source_context: { agent: said2.agent } } : {},
356
- ...said2.triage ? { triage: `tri_${project2.replace(/^prj_/, "")}_${said2.triage}` } : {}
357
- }, key);
358
- if (!made.ok) return made;
359
- const number = numberOf(made.value.key);
360
- if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
361
- return { ok: true, value: { task: made.value, number } };
325
+ function warn2(msg) {
326
+ warn(msg);
362
327
  }
363
- async function approveTask(project2, number) {
364
- const held4 = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
365
- if (!held4.ok) return held4;
366
- const key = `${held4.value.prefix}-${number}`;
367
- const task = await call("GET", `/v1/tasks/${encodeURIComponent(key)}`);
368
- if (!task.ok) return task;
369
- const revision = task.value.review?.revision;
370
- const decided = await call("POST", `/v1/tasks/${encodeURIComponent(key)}/decisions`, {
371
- decision: "approve",
372
- ...revision !== void 0 ? { review_revision: revision } : {}
373
- });
374
- return decided.ok ? { ok: true, value: { key } } : decided;
328
+ function boardPath() {
329
+ return rel(KANBAN).split(path3.sep).join("/");
375
330
  }
376
- var TASK_ENV, numberOf;
377
- var init_tasks = __esm({
378
- "src/lib/cloud/tasks.ts"() {
331
+ function boardText(text4) {
332
+ const posix = (p) => rel(p).split(path3.sep).join("/");
333
+ const swaps = [
334
+ [ASSETS_PATH_IN_TEXT, posix(ASSETS)],
335
+ [MOCKUPS_PATH_IN_TEXT, posix(MOCKUPS)],
336
+ [BOARD_STATE_IN_TEXT, posix(BOARD_STATE)],
337
+ [BOARD_PATH_IN_TEXT, boardPath()]
338
+ ];
339
+ const swap = (part, i) => i === swaps.length ? part : part.split(swaps[i][0]).map((p) => swap(p, i + 1)).join(swaps[i][1]);
340
+ return swap(text4, 0);
341
+ }
342
+ function useProjectState() {
343
+ ensureAkbDir();
344
+ return ensureProjectState(KANBAN, REPO_ROOT);
345
+ }
346
+ var REPO_ROOT, KANBAN, TODO, ARCHIVE, REJECTIONS_TO_REVIEW, ARCHIVE_MD, README, MODULES_MD, CONFIG, KANBAN_GITIGNORE, RELEASES, RELEASE_SUMMARIES, AGENTS, STUDIOS, LEGACY_AGENTS, ASSETS, BOARD_STATE, MOCKUPS, MEMORY, AGENT_MEMORY, PROJECT_MD, LOCK, UI_CONFIG, LEGACY_UI_CONFIG, LOCAL_CONFIG, ENV_FILE, SESSIONS, SESSIONS_DIR, SESSIONS_LOCK2, INDEX_LOCK2, DELIVERIES, PLANS, PLANS_ARCHIVE, RULES, TRIAGE, SIGNALS_ARCHIVED, SIGNALS_DISMISSED, SIGNALS_FILES, SIGNALS_OLD_INBOX, SIGNALS_OLD_HANDLED, AKB_DIR, ROOT_GITIGNORE, AKB_IGNORE_LINE, BOARD_FLAG, rel, BOARD_PATH_IN_TEXT, ASSETS_PATH_IN_TEXT, MOCKUPS_PATH_IN_TEXT, BOARD_STATE_IN_TEXT;
347
+ var init_paths = __esm({
348
+ "src/lib/paths.ts"() {
379
349
  "use strict";
380
- init_config();
381
- init_session();
382
- TASK_ENV = "AI4KANBAN_TASK";
383
- numberOf = (key) => Number(/-(\d+)$/.exec(key)?.[1] ?? NaN);
350
+ init_io();
351
+ init_project();
352
+ REPO_ROOT = "";
353
+ KANBAN = "";
354
+ TODO = "";
355
+ ARCHIVE = "";
356
+ REJECTIONS_TO_REVIEW = ".sync";
357
+ ARCHIVE_MD = "";
358
+ README = "";
359
+ MODULES_MD = "";
360
+ CONFIG = "";
361
+ KANBAN_GITIGNORE = "";
362
+ RELEASES = "";
363
+ RELEASE_SUMMARIES = "";
364
+ AGENTS = "";
365
+ STUDIOS = "";
366
+ LEGACY_AGENTS = "";
367
+ ASSETS = "";
368
+ BOARD_STATE = "";
369
+ MOCKUPS = "";
370
+ MEMORY = "";
371
+ AGENT_MEMORY = "";
372
+ PROJECT_MD = "";
373
+ LOCK = "";
374
+ UI_CONFIG = "";
375
+ LEGACY_UI_CONFIG = "";
376
+ LOCAL_CONFIG = "";
377
+ ENV_FILE = "";
378
+ SESSIONS = "";
379
+ SESSIONS_DIR = "";
380
+ SESSIONS_LOCK2 = "";
381
+ INDEX_LOCK2 = "";
382
+ DELIVERIES = "";
383
+ PLANS = "";
384
+ PLANS_ARCHIVE = "";
385
+ RULES = "";
386
+ TRIAGE = "";
387
+ SIGNALS_ARCHIVED = "";
388
+ SIGNALS_DISMISSED = "";
389
+ SIGNALS_FILES = "";
390
+ SIGNALS_OLD_INBOX = "";
391
+ SIGNALS_OLD_HANDLED = "";
392
+ AKB_DIR = "";
393
+ ROOT_GITIGNORE = "";
394
+ AKB_IGNORE_LINE = ".akb/";
395
+ BOARD_FLAG = "";
396
+ setBoardRoot(process.cwd());
397
+ rel = (p) => {
398
+ const from = path3.relative(REPO_ROOT, p);
399
+ if (!from) return p;
400
+ return from.startsWith("..") ? p : from;
401
+ };
402
+ BOARD_PATH_IN_TEXT = "docs/kanban";
403
+ ASSETS_PATH_IN_TEXT = "docs/kanban/.assets";
404
+ MOCKUPS_PATH_IN_TEXT = "docs/kanban/.mockups";
405
+ BOARD_STATE_IN_TEXT = "<board-state>";
384
406
  }
385
407
  });
386
408
 
387
- // src/lib/io.ts
388
- function startCollecting() {
389
- sink = { out: [], warnings: [] };
390
- return sink;
391
- }
392
- function stopCollecting() {
393
- sink = null;
394
- }
395
- function quietly(fn) {
396
- const before = sink;
397
- sink = { out: [], warnings: [] };
409
+ // src/lib/cloud/reply-approval.ts
410
+ async function approveAfterReply(task, comment) {
411
+ const context = process.env[REPLY_APPROVAL_ENV];
412
+ if (!context) return null;
398
413
  try {
399
- return fn();
400
- } finally {
401
- sink = before;
402
- }
403
- }
404
- async function quietlyAsync(fn) {
405
- const before = sink;
406
- sink = { out: [], warnings: [] };
407
- try {
408
- return await fn();
409
- } finally {
410
- sink = before;
414
+ const { url, token: token2 } = JSON.parse(context);
415
+ if (!/^http:\/\/127\.0\.0\.1:\d+\/$/.test(url) || !/^[a-f0-9]{64}$/.test(token2)) throw Error("Invalid reply context.");
416
+ const response = await fetch(url, {
417
+ method: "POST",
418
+ headers: { authorization: `Bearer ${token2}`, "content-type": "application/json" },
419
+ body: JSON.stringify({ task, comment }),
420
+ signal: AbortSignal.timeout(12e4)
421
+ });
422
+ const result = await response.json();
423
+ if (!result.ok || !result.value) throw Error(result.error ?? "The request was not accepted.");
424
+ const held4 = result.value;
425
+ if (held4.status === "cancelled") throw Error(held4.reason ?? "The request was cancelled. Ask again in a new reply.");
426
+ say(held4.status === "pending" ? `Approval pending for ${task}; it will be checked after this reply finishes.` : `Approval already committed for ${task}.`);
427
+ return { ...held4, pending: held4.status === "pending" };
428
+ } catch (e) {
429
+ return die(e instanceof Error ? e.message : "Reply approval failed.", { kind: "refused" });
411
430
  }
412
431
  }
413
- function say(line = "") {
414
- const text4 = String(line);
415
- if (sink) sink.out.push(...text4.split("\n"));
416
- else console.log(text4);
417
- }
418
- function warn(message) {
419
- if (sink) sink.warnings.push(String(message));
420
- else console.error(`kanban: warning \u2014 ${message}`);
421
- }
422
- var BoardError, sink;
423
- var init_io = __esm({
424
- "src/lib/io.ts"() {
432
+ var REPLY_APPROVAL_ENV;
433
+ var init_reply_approval = __esm({
434
+ "src/lib/cloud/reply-approval.ts"() {
425
435
  "use strict";
426
- BoardError = class extends Error {
427
- // `kind` is the machine-readable name of the refusal (card-not-found, no-board,
428
- // unknown-module, …). It is what a caller reads; the exit code stays 1 for every
429
- // refusal, so nobody has to keep a table of numbers.
430
- kind;
431
- // Only `cloud image` / `cloud tts` set it: 2 for a usage error, as the scripts they replaced did.
432
- exitCode;
433
- // `bare` says the message is already the whole thing a person should see — a usage
434
- // block, say — so the dispatcher prints it without putting the command in front of it.
435
- bare;
436
- details;
437
- constructor(message, { kind = "refused", bare = false, exitCode = 1, ...details } = {}) {
438
- super(message);
439
- this.name = "BoardError";
440
- this.kind = kind;
441
- this.bare = bare;
442
- this.exitCode = exitCode;
443
- this.details = details;
444
- }
445
- };
446
- sink = null;
436
+ init_io();
437
+ init_paths();
438
+ REPLY_APPROVAL_ENV = "AI4KANBAN_REPLY_APPROVAL";
447
439
  }
448
440
  });
449
441
 
450
- // src/lib/machine/project.ts
451
- import { createHash } from "node:crypto";
442
+ // src/lib/cloud/config.ts
443
+ function cloudEndpoints() {
444
+ return {
445
+ supabaseUrl: trimSlash(process.env.AI4KANBAN_SUPABASE_URL || SUPABASE_URL),
446
+ anonKey: process.env.AI4KANBAN_SUPABASE_ANON_KEY || SUPABASE_ANON_KEY,
447
+ api: trimSlash(process.env.AI4KANBAN_CLOUD_URL || API_URL)
448
+ };
449
+ }
450
+ function cloudConfigured() {
451
+ const { supabaseUrl, anonKey } = cloudEndpoints();
452
+ return !!supabaseUrl && !!anonKey;
453
+ }
454
+ var SUPABASE_URL, SUPABASE_ANON_KEY, API_URL, trimSlash, NOT_CONFIGURED;
455
+ var init_config = __esm({
456
+ "src/lib/cloud/config.ts"() {
457
+ "use strict";
458
+ SUPABASE_URL = "https://yajrbpprmdvtkvjjfpbk.supabase.co";
459
+ SUPABASE_ANON_KEY = "sb_publishable_ioUQ23BTtoj8NKqndp0Jrw_omVR3m4n";
460
+ API_URL = "https://api.ai4kanban.dev";
461
+ trimSlash = (url) => url.replace(/\/+$/, "");
462
+ NOT_CONFIGURED = "This build of WildCrane carries no Cloud project to sign in against.";
463
+ }
464
+ });
465
+
466
+ // src/lib/cloud/session.ts
452
467
  import fs3 from "node:fs";
453
468
  import path4 from "node:path";
454
- function realPathOf(dir) {
455
- const here = path4.resolve(dir);
456
- const rest = [];
457
- let at = here;
458
- for (; ; ) {
459
- try {
460
- return path4.join(fs3.realpathSync(at), ...rest);
461
- } catch {
462
- const up = path4.dirname(at);
463
- if (up === at) return here;
464
- rest.unshift(path4.basename(at));
465
- at = up;
466
- }
469
+ function readSession() {
470
+ let raw;
471
+ try {
472
+ raw = fs3.readFileSync(sessionFile(), "utf8");
473
+ } catch {
474
+ return null;
467
475
  }
468
- }
469
- function readableName(real2) {
470
- const here = path4.basename(real2);
471
- const up = path4.dirname(real2);
472
- if (here !== "kanban") return slug(here);
473
- return path4.basename(up) === "docs" ? slug(path4.basename(path4.dirname(up))) : slug(`${path4.basename(up)}-kanban`);
474
- }
475
- function legacyProjectStateDir(board2) {
476
- const real2 = realPathOf(board2);
477
- const id = createHash("sha256").update(real2).digest("hex").slice(0, ID_LENGTH);
478
- return path4.join(machineHome(), PROJECTS, `${readableName(real2)}-${id}`);
479
- }
480
- function stateRootOf(board2) {
481
- let dir = realPathOf(board2);
482
- for (; ; ) {
483
- if (fs3.existsSync(path4.join(dir, ".git"))) return dir;
484
- const up = path4.dirname(dir);
485
- if (up === dir) break;
486
- dir = up;
476
+ try {
477
+ const held4 = JSON.parse(raw);
478
+ if (!held4.accessToken || !held4.refreshToken || !held4.subject) return null;
479
+ if (held4.supabaseUrl !== cloudEndpoints().supabaseUrl) return null;
480
+ return { ...held4, version: 1, expiresAt: Number(held4.expiresAt) || 0 };
481
+ } catch {
482
+ return null;
487
483
  }
488
- return rootAbove(realPathOf(board2));
489
484
  }
490
- function rootAbove(board2) {
491
- const parent = path4.dirname(board2);
492
- return ["docs", ".akb"].includes(path4.basename(parent)) ? path4.dirname(parent) : parent;
485
+ function writeSession(session) {
486
+ fs3.mkdirSync(machineHome(), { recursive: true, mode: 448 });
487
+ const tmp = `${sessionFile()}.${process.pid}.tmp`;
488
+ fs3.writeFileSync(tmp, `${JSON.stringify(session, null, 2)}
489
+ `, { mode: 384 });
490
+ fs3.renameSync(tmp, sessionFile());
493
491
  }
494
- function projectStateDir(board2, root2 = stateRootOf(board2)) {
495
- const relative = path4.relative(realPathOf(root2), realPathOf(board2));
496
- if (relative === ".." || relative.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative)) {
497
- throw new Error("The board must be inside its project root.");
492
+ function clearSession() {
493
+ try {
494
+ fs3.rmSync(sessionFile());
495
+ } catch {
498
496
  }
499
- return path4.join(realPathOf(root2), ".akb", "boards", relative || "_root");
500
497
  }
501
- function ensureProjectState(board2, root2 = stateRootOf(board2)) {
502
- const dir = projectStateDir(board2, root2);
503
- if (!fs3.existsSync(dir)) {
504
- const legacy2 = legacyProjectStateDir(board2);
505
- fs3.mkdirSync(path4.dirname(dir), { recursive: true });
506
- const temporary = fs3.mkdtempSync(`${dir}.import-`);
498
+ async function accessToken() {
499
+ const held4 = readSession();
500
+ if (!held4) return { ok: false, reason: "signed-out" };
501
+ if (!expiringSoon(held4)) return { ok: true, token: held4.accessToken, session: held4 };
502
+ return refresh();
503
+ }
504
+ async function refresh() {
505
+ const lock = await takeLock();
506
+ try {
507
+ const now = readSession();
508
+ if (!now) return { ok: false, reason: "signed-out" };
509
+ if (!expiringSoon(now)) return { ok: true, token: now.accessToken, session: now };
510
+ const { api, anonKey } = cloudEndpoints();
511
+ let response;
507
512
  try {
508
- if (fs3.existsSync(legacy2)) fs3.cpSync(legacy2, temporary, {
509
- recursive: true,
510
- filter: (source) => ![".lock", ".answering"].some((suffix) => path4.basename(source).endsWith(suffix))
513
+ response = await fetch(`${api}/auth/v1/token?grant_type=refresh_token`, {
514
+ method: "POST",
515
+ headers: { apikey: anonKey, "content-type": "application/json" },
516
+ body: JSON.stringify({ refresh_token: now.refreshToken })
511
517
  });
512
- try {
513
- fs3.renameSync(temporary, dir);
514
- } catch (err) {
515
- if (!["EEXIST", "ENOTEMPTY"].includes(err.code ?? "")) throw err;
518
+ } catch (e) {
519
+ return { ok: false, reason: "unreachable", error: e instanceof Error ? e.message : String(e) };
520
+ }
521
+ if (!response.ok) {
522
+ const body = await response.json().catch(() => ({}));
523
+ if (response.status >= 500) {
524
+ return { ok: false, reason: "unreachable", error: body.error_description ?? `Cloud answered ${response.status}` };
516
525
  }
517
- } finally {
518
- fs3.rmSync(temporary, { recursive: true, force: true });
526
+ return { ok: false, reason: "expired", error: body.error_description };
519
527
  }
528
+ const fresh = sessionFrom(await response.json(), now);
529
+ if (!fresh) return { ok: false, reason: "expired" };
530
+ const current = readSession();
531
+ if (!current || current.subject !== now.subject) return { ok: false, reason: "expired" };
532
+ if (current.refreshToken !== now.refreshToken) return { ok: true, token: current.accessToken, session: current };
533
+ writeSession(fresh);
534
+ return { ok: true, token: fresh.accessToken, session: fresh };
535
+ } finally {
536
+ lock();
520
537
  }
521
- if (recordedBoard(dir) !== realPathOf(board2)) {
522
- fs3.writeFileSync(path4.join(dir, RECORD), `${JSON.stringify({ board: realPathOf(board2) })}
538
+ }
539
+ function sessionFrom(body, previous) {
540
+ const token2 = body;
541
+ const subject = token2.user?.id ?? previous?.subject;
542
+ if (!token2.access_token || !token2.refresh_token || !subject) return null;
543
+ const expiresAt = token2.expires_at ? token2.expires_at * 1e3 : Date.now() + (token2.expires_in ?? 3600) * 1e3;
544
+ return {
545
+ version: 1,
546
+ supabaseUrl: cloudEndpoints().supabaseUrl,
547
+ accessToken: token2.access_token,
548
+ refreshToken: token2.refresh_token,
549
+ expiresAt,
550
+ subject,
551
+ email: token2.user?.email ?? previous?.email,
552
+ handle: previous?.handle,
553
+ name: previous?.name,
554
+ avatarUrl: previous?.avatarUrl,
555
+ avatar: previous?.avatar
556
+ };
557
+ }
558
+ async function takeLock() {
559
+ const until = Date.now() + LOCK_WAIT_MS;
560
+ for (; ; ) {
561
+ try {
562
+ fs3.mkdirSync(machineHome(), { recursive: true, mode: 448 });
563
+ fs3.mkdirSync(lockDir());
564
+ try {
565
+ fs3.writeFileSync(lockOwner(), `${process.pid}
523
566
  `);
567
+ } catch {
568
+ }
569
+ return () => {
570
+ try {
571
+ fs3.rmSync(lockDir(), { recursive: true, force: true });
572
+ } catch {
573
+ }
574
+ };
575
+ } catch (err) {
576
+ if (err.code !== "EEXIST") throw err;
577
+ if (stale()) {
578
+ fs3.rmSync(lockDir(), { recursive: true, force: true });
579
+ continue;
580
+ }
581
+ if (Date.now() > until) return () => {
582
+ };
583
+ await sleep(LOCK_RETRY_MS);
584
+ }
524
585
  }
525
- return dir;
526
586
  }
527
- function recordedBoard(dir) {
587
+ function stale() {
588
+ let held4;
528
589
  try {
529
- const held4 = JSON.parse(fs3.readFileSync(path4.join(dir, RECORD), "utf8"));
530
- return typeof held4.board === "string" ? held4.board : null;
590
+ const pid = Number(fs3.readFileSync(lockOwner(), "utf8").trim());
591
+ held4 = Number.isInteger(pid) && pid > 0 ? pid : void 0;
531
592
  } catch {
532
- return null;
593
+ held4 = void 0;
594
+ }
595
+ if (held4 !== void 0 && !alive(held4)) return true;
596
+ try {
597
+ return Date.now() - fs3.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
598
+ } catch {
599
+ return false;
533
600
  }
534
601
  }
535
- var PROJECTS, ID_LENGTH, RECORD, SESSIONS_FILE, SESSIONS_FOLDER, ASSETS_FOLDER, MOCKUPS_FOLDER, SESSIONS_LOCK, INDEX_LOCK, UI_CONFIG_FILE, slug;
536
- var init_project = __esm({
537
- "src/lib/machine/project.ts"() {
602
+ function alive(pid) {
603
+ try {
604
+ process.kill(pid, 0);
605
+ return true;
606
+ } catch (e) {
607
+ return e.code === "EPERM";
608
+ }
609
+ }
610
+ var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep;
611
+ var init_session = __esm({
612
+ "src/lib/cloud/session.ts"() {
538
613
  "use strict";
539
614
  init_home();
540
- PROJECTS = "projects";
541
- ID_LENGTH = 10;
542
- RECORD = "board.json";
543
- SESSIONS_FILE = "sessions.json";
544
- SESSIONS_FOLDER = "sessions";
545
- ASSETS_FOLDER = "assets";
546
- MOCKUPS_FOLDER = "mockups";
547
- SESSIONS_LOCK = "sessions.lock";
548
- INDEX_LOCK = "index.lock";
549
- UI_CONFIG_FILE = "ui.config.json";
550
- slug = (text4) => text4.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "board";
615
+ init_config();
616
+ REFRESH_MARGIN_MS = 6e4;
617
+ LOCK_STALE_MS = 3e4;
618
+ LOCK_WAIT_MS = 2e4;
619
+ LOCK_RETRY_MS = 50;
620
+ sessionFile = () => path4.join(machineHome(), "session.json");
621
+ lockDir = () => path4.join(machineHome(), "session.lock");
622
+ lockOwner = () => path4.join(lockDir(), "owner");
623
+ expiringSoon = (session) => session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
624
+ sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
551
625
  }
552
626
  });
553
627
 
554
- // src/lib/paths.ts
555
- import { spawnSync } from "node:child_process";
628
+ // src/lib/cloud/tasks.ts
629
+ import crypto from "node:crypto";
556
630
  import fs4 from "node:fs";
557
631
  import path5 from "node:path";
558
- function boardLockName(kanban, root2) {
559
- const from = path5.relative(root2, kanban);
560
- const name = from && !from.startsWith("..") ? from : path5.basename(kanban);
561
- return `${name.split(path5.sep).join("-")}.lock`;
562
- }
563
- function ensureAkbDir() {
564
- fs4.mkdirSync(AKB_DIR, { recursive: true });
565
- writeRootIgnoreIfMissing();
566
- return AKB_DIR;
632
+ function workspaceTask() {
633
+ const id = process.env[TASK_ENV];
634
+ return id && id.trim() ? id.trim() : null;
567
635
  }
568
- function writeRootIgnoreIfMissing() {
569
- const text4 = fs4.existsSync(ROOT_GITIGNORE) ? fs4.readFileSync(ROOT_GITIGNORE, "utf8") : "";
570
- if (text4.split("\n").some((line) => line.trim() === AKB_IGNORE_LINE)) return false;
571
- const ignored = spawnSync("git", ["-C", REPO_ROOT, "check-ignore", "-q", AKB_IGNORE_LINE], { stdio: "ignore" }).status;
572
- if (ignored === 0 || ignored === 128 && KANBAN.startsWith(AKB_DIR + path5.sep)) return false;
573
- const separator = !text4 || text4.endsWith("\n") ? "" : "\n";
574
- const block = `# Delivery state \u2014 worktrees and the like. Never committed.
575
- ${AKB_IGNORE_LINE}
576
- `;
577
- fs4.writeFileSync(ROOT_GITIGNORE, `${text4}${separator}${block}`);
578
- return true;
636
+ function cloudStudio(name) {
637
+ if (/^wf-/.test(name)) return name.replace("-", "_");
638
+ return `wf_builtin_${name.replace(/-/g, "_")}`;
579
639
  }
580
- function projectRootOf(board2) {
581
- let dir = path5.resolve(board2);
582
- for (; ; ) {
583
- if (fs4.existsSync(path5.join(dir, ".git"))) return dir;
584
- const up = path5.dirname(dir);
585
- if (up === dir) return rootAbove(path5.resolve(board2));
586
- dir = up;
640
+ async function call(method, route2, body, key) {
641
+ if (!cloudConfigured()) return { ok: false, error: NOT_CONFIGURED, code: "bad_request" };
642
+ const token2 = await accessToken();
643
+ if (!token2.ok) {
644
+ return token2.reason === "unreachable" ? { ok: false, error: `Cloud could not be reached: ${token2.error}` } : { ok: false, error: token2.reason === "expired" ? "Cloud sign-in has expired. Sign in again." : "This machine is not signed in to Cloud.", code: "unauthenticated" };
587
645
  }
646
+ let response;
647
+ try {
648
+ response = await fetch(`${cloudEndpoints().api}${route2}`, {
649
+ method,
650
+ headers: {
651
+ authorization: `Bearer ${token2.token}`,
652
+ ...body ? { "content-type": "application/json" } : {},
653
+ ...key ? { "idempotency-key": key } : {}
654
+ },
655
+ ...body ? { body: JSON.stringify(body) } : {},
656
+ signal: AbortSignal.timeout(2e4)
657
+ });
658
+ } catch (e) {
659
+ return { ok: false, error: `Cloud could not be reached: ${e instanceof Error ? e.message : String(e)}` };
660
+ }
661
+ const parsed = await response.json().catch(() => ({}));
662
+ if (!response.ok) return { ok: false, code: parsed.error?.code ?? "refused", error: parsed.error?.message ?? `Cloud answered ${response.status}.` };
663
+ return { ok: true, value: parsed, replayed: response.headers.get("idempotent-replayed") === "true" };
588
664
  }
589
- function setBoard(kanban, root2, flag) {
590
- REPO_ROOT = path5.resolve(root2);
591
- KANBAN = path5.resolve(kanban);
592
- BOARD_FLAG = flag;
593
- TODO = path5.join(KANBAN, "todo");
594
- ARCHIVE = path5.join(KANBAN, ".archive");
595
- ARCHIVE_MD = path5.join(KANBAN, "archive.md");
596
- README = path5.join(TODO, "README.md");
597
- MODULES_MD = path5.join(KANBAN, "modules.md");
598
- CONFIG = path5.join(KANBAN, "config.md");
599
- KANBAN_GITIGNORE = path5.join(KANBAN, ".gitignore");
600
- RELEASES = path5.join(KANBAN, "releases.md");
601
- RELEASE_SUMMARIES = path5.join(KANBAN, ".release-summaries");
602
- AGENTS = path5.join(KANBAN, "agents");
603
- STUDIOS = path5.join(KANBAN, "studios");
604
- LEGACY_AGENTS = path5.join(KANBAN, "skills");
605
- MEMORY = path5.join(KANBAN, "memory");
606
- AGENT_MEMORY = path5.join(MEMORY, "agents");
607
- PROJECT_MD = path5.join(MEMORY, "project.md");
608
- LEGACY_UI_CONFIG = path5.join(KANBAN, UI_CONFIG_FILE);
609
- LOCAL_CONFIG = path5.join(KANBAN, ".local.json");
610
- ENV_FILE = path5.join(KANBAN, ".env");
611
- const machine = projectStateDir(KANBAN, REPO_ROOT);
612
- BOARD_STATE = machine;
613
- UI_CONFIG = path5.join(machine, UI_CONFIG_FILE);
614
- ASSETS = path5.join(machine, ASSETS_FOLDER);
615
- MOCKUPS = path5.join(machine, MOCKUPS_FOLDER);
616
- SESSIONS = path5.join(machine, SESSIONS_FILE);
617
- SESSIONS_DIR = path5.join(machine, SESSIONS_FOLDER);
618
- SESSIONS_LOCK2 = path5.join(machine, SESSIONS_LOCK);
619
- INDEX_LOCK2 = path5.join(machine, INDEX_LOCK);
620
- DELIVERIES = path5.join(KANBAN, "deliveries");
621
- RULES = path5.join(KANBAN, "rules");
622
- PLANS = path5.join(machine, "plans");
623
- PLANS_ARCHIVE = path5.join(PLANS, "archive");
624
- TRIAGE = path5.join(KANBAN, "triage");
625
- SIGNALS_ARCHIVED = path5.join(TRIAGE, "archived");
626
- SIGNALS_DISMISSED = path5.join(TRIAGE, "dismissed");
627
- SIGNALS_FILES = path5.join(TRIAGE, "files");
628
- SIGNALS_OLD_INBOX = path5.join(TRIAGE, "inbox");
629
- SIGNALS_OLD_HANDLED = path5.join(TRIAGE, "handled.md");
630
- AKB_DIR = path5.join(REPO_ROOT, ".akb");
631
- ROOT_GITIGNORE = path5.join(REPO_ROOT, ".gitignore");
632
- LOCK = path5.join(AKB_DIR, boardLockName(KANBAN, REPO_ROOT));
633
- return REPO_ROOT;
634
- }
635
- function setBoardRoot(root2, named2 = false) {
636
- const project2 = path5.resolve(root2);
637
- return setBoard(path5.join(project2, "docs", "kanban"), project2, named2 ? ` --dir ${project2}` : "");
638
- }
639
- function setBoardDir(board2, root2) {
640
- const folder = path5.resolve(board2);
641
- return setBoard(folder, root2 ?? projectRootOf(folder), ` --board ${folder}`);
665
+ async function createTask(from, said2) {
666
+ const source = await call("GET", `/v1/tasks/${encodeURIComponent(from)}`);
667
+ if (!source.ok) return source;
668
+ const studio = said2.studio ? cloudStudio(said2.studio) : source.value.studio?.id;
669
+ const body = {
670
+ title: said2.title,
671
+ project: source.value.project,
672
+ ...studio ? { studio } : {},
673
+ ...said2.request?.trim() ? { request: said2.request.trim() } : {},
674
+ source: "api",
675
+ source_context: { task: from, ...said2.agent ? { agent: said2.agent } : {} },
676
+ ...said2.run ? { run: true } : {},
677
+ ...said2.metadata && Object.keys(said2.metadata).length ? { metadata: said2.metadata } : {},
678
+ ...said2.triage ? { triage: `tri_${source.value.project.replace(/^prj_/, "")}_${said2.triage}` } : {}
679
+ };
680
+ const key = `akb-${crypto.createHash("sha256").update(`${from}
681
+ ${said2.slug?.trim() || said2.title}`).digest("hex").slice(0, 40)}`;
682
+ const made = await call("POST", "/v1/tasks", body, key);
683
+ if (!made.ok) return made;
684
+ const number = numberOf(made.value.key);
685
+ if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
686
+ return { ok: true, value: { task: made.value, number, from: source.value, replayed: made.replayed === true } };
642
687
  }
643
- function die(msg, kind) {
644
- throw new BoardError(msg, typeof kind === "string" ? { kind } : kind);
688
+ function runnerProject(board2) {
689
+ if (path5.basename(board2) !== "kanban" || path5.basename(path5.dirname(board2)) !== ".akb") return null;
690
+ const linked2 = linkedProject(board2, path5.dirname(path5.dirname(board2)));
691
+ return linked2.ok ? linked2.value : null;
645
692
  }
646
- function warn2(msg) {
647
- warn(msg);
693
+ function linkedProject(board2, root2) {
694
+ const file = path5.join(root2, ".akb", "base.json");
695
+ if (!fs4.existsSync(file)) return { ok: true, value: null };
696
+ try {
697
+ const base = JSON.parse(fs4.readFileSync(file, "utf8"));
698
+ if (!base || typeof base !== "object" || base.project !== void 0 && (typeof base.project !== "string" || !base.project.trim()) || base.files !== void 0 && (!base.files || typeof base.files !== "object" || Array.isArray(base.files))) throw new Error();
699
+ const projects = new Set(Object.keys(base.files ?? {}).flatMap((p) => /^projects\/([^/]+)\//.exec(p)?.[1] ?? []));
700
+ if (typeof base.project === "string") projects.add(base.project);
701
+ if (projects.size !== 1) throw new Error();
702
+ return { ok: true, value: [...projects][0] };
703
+ } catch {
704
+ return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
705
+ }
648
706
  }
649
- function boardPath() {
650
- return rel(KANBAN).split(path5.sep).join("/");
707
+ async function creationProject(board2, root2, task = workspaceTask()) {
708
+ const link2 = linkedProject(board2, root2);
709
+ if (!link2.ok) return link2;
710
+ let project2 = link2.value;
711
+ if (task) {
712
+ const source = await call("GET", `/v1/tasks/${encodeURIComponent(task)}`);
713
+ if (!source.ok) return {
714
+ ...source,
715
+ error: source.code === "forbidden" ? "Cannot access this task. Check your account and task access in WildCrane, then try again." : source.code === "not_found" ? "This task does not exist. Start a new task from the WildCrane web app." : source.error
716
+ };
717
+ if (project2 && project2 !== source.value.project) return { ok: false, error: "The source task conflicts with this board\u2019s project link.", code: "invalid-link" };
718
+ project2 = source.value.project;
719
+ }
720
+ if (!project2) return { ok: false, error: "This board is not linked to a Cloud project.", code: "unlinked" };
721
+ const checked = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
722
+ return checked.ok ? { ok: true, value: project2 } : checked;
651
723
  }
652
- function boardText(text4) {
653
- const posix = (p) => rel(p).split(path5.sep).join("/");
654
- const swaps = [
655
- [ASSETS_PATH_IN_TEXT, posix(ASSETS)],
656
- [MOCKUPS_PATH_IN_TEXT, posix(MOCKUPS)],
657
- [BOARD_STATE_IN_TEXT, posix(BOARD_STATE)],
658
- [BOARD_PATH_IN_TEXT, boardPath()]
659
- ];
660
- const swap = (part, i) => i === swaps.length ? part : part.split(swaps[i][0]).map((p) => swap(p, i + 1)).join(swaps[i][1]);
661
- return swap(text4, 0);
724
+ async function createProjectTask(project2, said2, key) {
725
+ const made = await call("POST", "/v1/tasks", {
726
+ title: said2.title,
727
+ project: project2,
728
+ source: "api",
729
+ ...said2.studio ? { studio: cloudStudio(said2.studio) } : {},
730
+ ...said2.request?.trim() ? { request: said2.request.trim() } : {},
731
+ ...said2.agent ? { source_context: { agent: said2.agent } } : {},
732
+ ...said2.triage ? { triage: `tri_${project2.replace(/^prj_/, "")}_${said2.triage}` } : {}
733
+ }, key);
734
+ if (!made.ok) return made;
735
+ const number = numberOf(made.value.key);
736
+ if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
737
+ return { ok: true, value: { task: made.value, number } };
662
738
  }
663
- function useProjectState() {
664
- ensureAkbDir();
665
- return ensureProjectState(KANBAN, REPO_ROOT);
739
+ async function approveTask(project2, number) {
740
+ const held4 = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
741
+ if (!held4.ok) return held4;
742
+ const key = `${held4.value.prefix}-${number}`;
743
+ const task = await call("GET", `/v1/tasks/${encodeURIComponent(key)}`);
744
+ if (!task.ok) return task;
745
+ const revision = task.value.review?.revision;
746
+ const decided = await call("POST", `/v1/tasks/${encodeURIComponent(key)}/decisions`, {
747
+ decision: "approve",
748
+ ...revision !== void 0 ? { review_revision: revision } : {}
749
+ });
750
+ return decided.ok ? { ok: true, value: { key } } : decided;
666
751
  }
667
- var REPO_ROOT, KANBAN, TODO, ARCHIVE, REJECTIONS_TO_REVIEW, ARCHIVE_MD, README, MODULES_MD, CONFIG, KANBAN_GITIGNORE, RELEASES, RELEASE_SUMMARIES, AGENTS, STUDIOS, LEGACY_AGENTS, ASSETS, BOARD_STATE, MOCKUPS, MEMORY, AGENT_MEMORY, PROJECT_MD, LOCK, UI_CONFIG, LEGACY_UI_CONFIG, LOCAL_CONFIG, ENV_FILE, SESSIONS, SESSIONS_DIR, SESSIONS_LOCK2, INDEX_LOCK2, DELIVERIES, PLANS, PLANS_ARCHIVE, RULES, TRIAGE, SIGNALS_ARCHIVED, SIGNALS_DISMISSED, SIGNALS_FILES, SIGNALS_OLD_INBOX, SIGNALS_OLD_HANDLED, AKB_DIR, ROOT_GITIGNORE, AKB_IGNORE_LINE, BOARD_FLAG, rel, BOARD_PATH_IN_TEXT, ASSETS_PATH_IN_TEXT, MOCKUPS_PATH_IN_TEXT, BOARD_STATE_IN_TEXT;
668
- var init_paths = __esm({
669
- "src/lib/paths.ts"() {
752
+ var TASK_ENV, numberOf;
753
+ var init_tasks = __esm({
754
+ "src/lib/cloud/tasks.ts"() {
670
755
  "use strict";
671
- init_io();
672
- init_project();
673
- REPO_ROOT = "";
674
- KANBAN = "";
675
- TODO = "";
676
- ARCHIVE = "";
677
- REJECTIONS_TO_REVIEW = ".sync";
678
- ARCHIVE_MD = "";
679
- README = "";
680
- MODULES_MD = "";
681
- CONFIG = "";
682
- KANBAN_GITIGNORE = "";
683
- RELEASES = "";
684
- RELEASE_SUMMARIES = "";
685
- AGENTS = "";
686
- STUDIOS = "";
687
- LEGACY_AGENTS = "";
688
- ASSETS = "";
689
- BOARD_STATE = "";
690
- MOCKUPS = "";
691
- MEMORY = "";
692
- AGENT_MEMORY = "";
693
- PROJECT_MD = "";
694
- LOCK = "";
695
- UI_CONFIG = "";
696
- LEGACY_UI_CONFIG = "";
697
- LOCAL_CONFIG = "";
698
- ENV_FILE = "";
699
- SESSIONS = "";
700
- SESSIONS_DIR = "";
701
- SESSIONS_LOCK2 = "";
702
- INDEX_LOCK2 = "";
703
- DELIVERIES = "";
704
- PLANS = "";
705
- PLANS_ARCHIVE = "";
706
- RULES = "";
707
- TRIAGE = "";
708
- SIGNALS_ARCHIVED = "";
709
- SIGNALS_DISMISSED = "";
710
- SIGNALS_FILES = "";
711
- SIGNALS_OLD_INBOX = "";
712
- SIGNALS_OLD_HANDLED = "";
713
- AKB_DIR = "";
714
- ROOT_GITIGNORE = "";
715
- AKB_IGNORE_LINE = ".akb/";
716
- BOARD_FLAG = "";
717
- setBoardRoot(process.cwd());
718
- rel = (p) => {
719
- const from = path5.relative(REPO_ROOT, p);
720
- if (!from) return p;
721
- return from.startsWith("..") ? p : from;
722
- };
723
- BOARD_PATH_IN_TEXT = "docs/kanban";
724
- ASSETS_PATH_IN_TEXT = "docs/kanban/.assets";
725
- MOCKUPS_PATH_IN_TEXT = "docs/kanban/.mockups";
726
- BOARD_STATE_IN_TEXT = "<board-state>";
756
+ init_config();
757
+ init_session();
758
+ TASK_ENV = "AI4KANBAN_TASK";
759
+ numberOf = (key) => Number(/-(\d+)$/.exec(key)?.[1] ?? NaN);
727
760
  }
728
761
  });
729
762
 
@@ -824,8 +857,8 @@ var init_question_block = __esm({
824
857
  // src/lib/view/rules.ts
825
858
  function creationRefusal(id, creation, what, discard = false) {
826
859
  if (!creation || creation.state === "unfinished" && discard) return null;
827
- const run2 = creation.runId.slice(0, 8);
828
- return creation.state === "creating" ? `#${id} is still being created by run ${run2} \u2014 \`${what}\` is refused until that run finishes.` : `#${id} was never finished being created: run ${run2} stopped short. \`${what}\` is refused until that run is picked back up from the board and finishes. Use reject --discard to discard it instead.`;
860
+ const run3 = creation.runId.slice(0, 8);
861
+ return creation.state === "creating" ? `#${id} is still being created by run ${run3} \u2014 \`${what}\` is refused until that run finishes.` : `#${id} was never finished being created: run ${run3} stopped short. \`${what}\` is refused until that run is picked back up from the board and finishes. Use reject --discard to discard it instead.`;
829
862
  }
830
863
  function hasOptions(q) {
831
864
  return Array.isArray(q.options) && q.options.length > 0;
@@ -1635,6 +1668,8 @@ async function act(id, route2, body, done2) {
1635
1668
  return value;
1636
1669
  }
1637
1670
  async function taskApprove(id, comment) {
1671
+ const deferred = await approveAfterReply(id, comment);
1672
+ if (deferred) return deferred;
1638
1673
  const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id))}`);
1639
1674
  return act(task.key, "decisions", {
1640
1675
  decision: "approve",
@@ -1688,6 +1723,7 @@ var refuse2, enc, WEB, taskUrl, projectLine, taskChat, taskRemove, taskResume, t
1688
1723
  var init_task = __esm({
1689
1724
  "src/commands/task.ts"() {
1690
1725
  "use strict";
1726
+ init_reply_approval();
1691
1727
  init_config();
1692
1728
  init_session();
1693
1729
  init_tasks();
@@ -2640,11 +2676,11 @@ function checkHarnesses(harnesses) {
2640
2676
  if (providers.length > 1) {
2641
2677
  throw new Error(`harness "${harness.name}": a connector declares one provider list, not ${providers.length}`);
2642
2678
  }
2643
- const list = providers[0];
2644
- if (!list) continue;
2645
- if (!list.providers?.length) throw new Error(`harness "${harness.name}": the provider setting "${list.key}" offers no providers`);
2679
+ const list2 = providers[0];
2680
+ if (!list2) continue;
2681
+ if (!list2.providers?.length) throw new Error(`harness "${harness.name}": the provider setting "${list2.key}" offers no providers`);
2646
2682
  const ids = /* @__PURE__ */ new Set();
2647
- for (const provider of list.providers) {
2683
+ for (const provider of list2.providers) {
2648
2684
  if (ids.has(provider.id)) throw new Error(`harness "${harness.name}": two providers share the id "${provider.id}"`);
2649
2685
  ids.add(provider.id);
2650
2686
  for (const need of [...provider.needs, ...provider.preferWhenSet ?? []]) {
@@ -2657,8 +2693,8 @@ function checkHarnesses(harnesses) {
2657
2693
  if (!provider.needs.includes(key)) throw new Error(`harness "${harness.name}": the provider "${provider.id}" renames the variable of "${key}" without needing it`);
2658
2694
  }
2659
2695
  }
2660
- if (list.defaultProvider && !ids.has(list.defaultProvider)) {
2661
- throw new Error(`harness "${harness.name}": the default provider "${list.defaultProvider}" isn't on the list`);
2696
+ if (list2.defaultProvider && !ids.has(list2.defaultProvider)) {
2697
+ throw new Error(`harness "${harness.name}": the default provider "${list2.defaultProvider}" isn't on the list`);
2662
2698
  }
2663
2699
  }
2664
2700
  }
@@ -2906,9 +2942,9 @@ function copyEnv(file, given = process.env) {
2906
2942
  function probe(file) {
2907
2943
  const key = keyOf(file);
2908
2944
  const start = spawnable(file, ["--version"], { ...probeOptions(file), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
2909
- const run2 = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
2910
- const code = run2.error?.code;
2911
- const answer2 = { key, at: Date.now(), ...judge(code, run2.status, run2.stdout ?? "", run2.stderr ?? "") };
2945
+ const run3 = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
2946
+ const code = run3.error?.code;
2947
+ const answer2 = { key, at: Date.now(), ...judge(code, run3.status, run3.stdout ?? "", run3.stderr ?? "") };
2912
2948
  keep(file, answer2);
2913
2949
  return answer2;
2914
2950
  }
@@ -3062,8 +3098,8 @@ function createEventCollector() {
3062
3098
  case "tool_call_update": {
3063
3099
  const id = str(u.toolCallId);
3064
3100
  if (todoCalls.has(id)) {
3065
- const list = obj(u.rawInput).todos;
3066
- if (Array.isArray(list) && !str(obj(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list) } });
3101
+ const list2 = obj(u.rawInput).todos;
3102
+ if (Array.isArray(list2) && !str(obj(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list2) } });
3067
3103
  return;
3068
3104
  }
3069
3105
  release(id, targetIn(u));
@@ -3243,10 +3279,10 @@ function failedWith(ev) {
3243
3279
  return str(ev.result).trim() || "the agent reported the session failed";
3244
3280
  }
3245
3281
  function denials(ev) {
3246
- const list = Array.isArray(ev.permission_denials) ? ev.permission_denials : [];
3247
- const names3 = [...new Set(list.map((raw) => str(obj(raw).tool_name)).filter(Boolean))];
3282
+ const list2 = Array.isArray(ev.permission_denials) ? ev.permission_denials : [];
3283
+ const names3 = [...new Set(list2.map((raw) => str(obj(raw).tool_name)).filter(Boolean))];
3248
3284
  if (!names3.length) return "";
3249
- return `[refused] ${list.length} tool call${list.length === 1 ? "" : "s"} were not allowed: ${names3.join(", ")}
3285
+ return `[refused] ${list2.length} tool call${list2.length === 1 ? "" : "s"} were not allowed: ${names3.join(", ")}
3250
3286
  `;
3251
3287
  }
3252
3288
  function promptSize(raw) {
@@ -3430,6 +3466,48 @@ var init_claude_stream = __esm({
3430
3466
  }
3431
3467
  });
3432
3468
 
3469
+ // src/lib/agent/wire/background.ts
3470
+ function createBackgroundTasks() {
3471
+ const tasks = /* @__PURE__ */ new Map();
3472
+ return {
3473
+ update(id, status, result = "") {
3474
+ if (!id) return false;
3475
+ const previous = tasks.get(id);
3476
+ if (previous?.status === status && previous.result === result) return false;
3477
+ tasks.set(id, { status, result });
3478
+ return true;
3479
+ },
3480
+ results: () => [...tasks].map(([id, task]) => ({ id, ...task })),
3481
+ running: () => [...tasks].filter(([, t]) => t.status === "running").map(([id]) => id),
3482
+ count: () => [...tasks.values()].filter((t) => t.status === "running").length,
3483
+ failure: () => [...tasks].filter(([, t]) => t.status === "failed").map(([id, t]) => t.result || `Background task ${id} failed.`).join("\n") || void 0
3484
+ };
3485
+ }
3486
+ function streamFinished(stream) {
3487
+ if (stream.background?.()) return false;
3488
+ const turns = stream.turns?.();
3489
+ return turns ? !!turns.length && !turns.at(-1).background : stream.result() !== void 0;
3490
+ }
3491
+ function createBackgroundWait(milliseconds, expired) {
3492
+ let timer;
3493
+ return {
3494
+ pending() {
3495
+ if (!timer && milliseconds > 0) timer = setTimeout(expired, milliseconds);
3496
+ },
3497
+ close() {
3498
+ clearTimeout(timer);
3499
+ timer = void 0;
3500
+ }
3501
+ };
3502
+ }
3503
+ var backgroundWaitMessage;
3504
+ var init_background = __esm({
3505
+ "src/lib/agent/wire/background.ts"() {
3506
+ "use strict";
3507
+ backgroundWaitMessage = (minutes) => `the agent's background tasks did not finish within ${minutes / 60} hours, so the run was ended.`;
3508
+ }
3509
+ });
3510
+
3433
3511
  // src/lib/agent/wire/codex-session.ts
3434
3512
  import { readFileSync, readdirSync, statSync } from "node:fs";
3435
3513
  import { homedir } from "node:os";
@@ -3714,6 +3792,31 @@ function createCodexStreamRenderer(carried = false) {
3714
3792
  let lookedAt = 0;
3715
3793
  const events = createEventCollector();
3716
3794
  const started = /* @__PURE__ */ new Set();
3795
+ const background = createBackgroundTasks();
3796
+ const subagents = /* @__PURE__ */ new Set();
3797
+ const collabItems = /* @__PURE__ */ new Set();
3798
+ const collab = (item, done2) => {
3799
+ if (item.type !== "collab_tool_call") return;
3800
+ const key = `${str(item.id)}:${done2}`;
3801
+ if (collabItems.has(key)) return;
3802
+ collabItems.add(key);
3803
+ for (const [id, raw] of Object.entries(obj(item.agents_states))) {
3804
+ const state = obj(raw);
3805
+ const status = str(state.status);
3806
+ if (!["pending_init", "running", "completed", "interrupted", "errored", "shutdown", "not_found"].includes(status)) continue;
3807
+ const previous = background.results().find((t) => t.id === id);
3808
+ if (["shutdown", "not_found"].includes(status) && previous && previous.status !== "running") continue;
3809
+ if (!subagents.has(id)) {
3810
+ subagents.add(id);
3811
+ events.subagent(`agent:${id}`, str(item.prompt) || "Agent");
3812
+ }
3813
+ const running = status === "pending_init" || status === "running";
3814
+ const failed = !running && status !== "completed";
3815
+ if (background.update(id, running ? "running" : failed ? "failed" : "completed", str(state.message)) && !running) {
3816
+ events.toolResult(`agent:${id}`, failed ? "failed" : "completed", str(state.message));
3817
+ }
3818
+ }
3819
+ };
3717
3820
  const look = (now) => {
3718
3821
  if (!threadId) return;
3719
3822
  const at = Date.now();
@@ -3740,6 +3843,7 @@ function createCodexStreamRenderer(carried = false) {
3740
3843
  if (!threadId) threadId = str(ev.thread_id).trim() || void 0;
3741
3844
  return "";
3742
3845
  case "item.started":
3846
+ collab(obj(ev.item), false);
3743
3847
  itemEvents(events, started, obj(ev.item), false);
3744
3848
  return renderStarted(obj(ev.item));
3745
3849
  case "item.updated":
@@ -3747,6 +3851,7 @@ function createCodexStreamRenderer(carried = false) {
3747
3851
  return "";
3748
3852
  case "item.completed": {
3749
3853
  const item = obj(ev.item);
3854
+ collab(item, true);
3750
3855
  if (item.type === "mcp_tool_call" && !/view_image|read_image|open_image/.test(str(item.tool))) {
3751
3856
  const content = obj(item.result).content;
3752
3857
  for (const block of Array.isArray(content) ? content : []) {
@@ -3818,7 +3923,8 @@ function createCodexStreamRenderer(carried = false) {
3818
3923
  // whose rates the board knows.
3819
3924
  costUsd: () => priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own()),
3820
3925
  resumeId: () => threadId,
3821
- failure: () => failure,
3926
+ failure: () => failure ?? background.failure(),
3927
+ background: () => subagents.size ? background.count() : void 0,
3822
3928
  events: events.events
3823
3929
  };
3824
3930
  }
@@ -3826,6 +3932,7 @@ var imageSafeText, CALLS, LOOK_EVERY_MS;
3826
3932
  var init_codex_stream = __esm({
3827
3933
  "src/lib/agent/wire/codex-stream.ts"() {
3828
3934
  "use strict";
3935
+ init_background();
3829
3936
  init_codex_session();
3830
3937
  init_events();
3831
3938
  init_json();
@@ -4139,6 +4246,9 @@ function connect(stdout, stdin, onCall, dialect = {}) {
4139
4246
  send({ id, method, params });
4140
4247
  });
4141
4248
  },
4249
+ notify(method, params = {}) {
4250
+ send({ method, params });
4251
+ },
4142
4252
  /** Answer something the agent asked us. */
4143
4253
  reply(id, result) {
4144
4254
  send({ id, result });
@@ -4224,8 +4334,8 @@ var init_package = __esm({
4224
4334
  "package.json"() {
4225
4335
  package_default = {
4226
4336
  name: "wildcrane",
4227
- version: "0.11.44",
4228
- akbContract: 11,
4337
+ version: "0.11.45",
4338
+ akbContract: 12,
4229
4339
  description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
4230
4340
  keywords: [
4231
4341
  "kanban",
@@ -4316,23 +4426,23 @@ function saidBy(update2) {
4316
4426
  function modelOf(answer2) {
4317
4427
  const current = str(obj(answer2.models).currentModelId).trim();
4318
4428
  if (current) return modelsIn(answer2).find((m) => m.modelId === current)?.name ?? current;
4319
- const list = Array.isArray(answer2.configOptions) ? answer2.configOptions : [];
4320
- for (const raw of list) {
4429
+ const list2 = Array.isArray(answer2.configOptions) ? answer2.configOptions : [];
4430
+ for (const raw of list2) {
4321
4431
  const option = obj(raw);
4322
4432
  if (option.id === "model") return str(option.currentValue).trim() || void 0;
4323
4433
  }
4324
4434
  return void 0;
4325
4435
  }
4326
4436
  function modelsIn(answer2) {
4327
- const list = obj(answer2.models).availableModels;
4328
- return (Array.isArray(list) ? list : []).map(obj).flatMap((m) => {
4437
+ const list2 = obj(answer2.models).availableModels;
4438
+ return (Array.isArray(list2) ? list2 : []).map(obj).flatMap((m) => {
4329
4439
  const modelId = str(m.modelId);
4330
4440
  return modelId ? [{ modelId, name: str(m.name) || modelId }] : [];
4331
4441
  });
4332
4442
  }
4333
4443
  function pickedModel(answer2, wanted) {
4334
- const list = modelsIn(answer2);
4335
- return list.find((m) => m.modelId === wanted) ?? list.find((m) => m.name === wanted || m.modelId.split("[")[0] === wanted);
4444
+ const list2 = modelsIn(answer2);
4445
+ return list2.find((m) => m.modelId === wanted) ?? list2.find((m) => m.name === wanted || m.modelId.split("[")[0] === wanted);
4336
4446
  }
4337
4447
  function usageOf2(value, grossInput = false) {
4338
4448
  const usage3 = obj(value);
@@ -4845,6 +4955,328 @@ var init_zcode = __esm({
4845
4955
  }
4846
4956
  });
4847
4957
 
4958
+ // src/lib/agent/wire/codex.ts
4959
+ function createCodexConnection(argv) {
4960
+ const execAt = argv.indexOf("exec");
4961
+ if (execAt < 1) return void 0;
4962
+ const server = [argv[0], "app-server"];
4963
+ const options = { images: [] };
4964
+ const roots = [];
4965
+ for (let i = 1; i < argv.length; i++) {
4966
+ if (i === execAt) continue;
4967
+ const arg = argv[i];
4968
+ const [flag, inline] = arg.split(/=(.*)/s);
4969
+ const value = () => inline ?? argv[++i];
4970
+ if (["--json", "--experimental-json", "--skip-git-repo-check"].includes(arg)) continue;
4971
+ if (["-c", "--config", "--enable", "--disable"].includes(flag)) {
4972
+ const v = value();
4973
+ if (!v) return void 0;
4974
+ server.push(flag, v);
4975
+ } else if (["-m", "--model", "-s", "--sandbox"].includes(flag)) {
4976
+ const v = value();
4977
+ if (!v) return void 0;
4978
+ server.push("-c", `${flag === "-m" || flag === "--model" ? "model" : "sandbox_mode"}=${JSON.stringify(v)}`);
4979
+ } else if (arg === "--dangerously-bypass-approvals-and-sandbox") {
4980
+ server.push("-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"');
4981
+ } else if (arg === "--full-auto") {
4982
+ server.push("-c", 'approval_policy="on-request"', "-c", 'sandbox_mode="workspace-write"');
4983
+ } else if (flag === "--add-dir") {
4984
+ const v = value();
4985
+ if (!v) return void 0;
4986
+ roots.push(v);
4987
+ } else if (flag === "-C" || flag === "--cd") {
4988
+ options.cwd = value();
4989
+ if (!options.cwd) return void 0;
4990
+ } else if (flag === "-i" || flag === "--image") {
4991
+ const v = value();
4992
+ if (!v) return void 0;
4993
+ options.images.push(v);
4994
+ } else if (arg === "resume" || arg === "fork") {
4995
+ options.mode = arg;
4996
+ options.threadId = argv[++i];
4997
+ if (!options.threadId || options.threadId.startsWith("-")) return void 0;
4998
+ } else {
4999
+ return void 0;
5000
+ }
5001
+ }
5002
+ if (roots.length) server.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(roots)}`);
5003
+ return { argv: server, client: createCodexClient(options) };
5004
+ }
5005
+ function createCodexClient(options = { images: [] }) {
5006
+ const tasks = createBackgroundTasks();
5007
+ return {
5008
+ structured: true,
5009
+ background: tasks.count,
5010
+ turn: (io) => run(io, options, tasks)
5011
+ };
5012
+ }
5013
+ async function run(io, options, tasks) {
5014
+ const renderer = createCodexStreamRenderer();
5015
+ const children = /* @__PURE__ */ new Set();
5016
+ const commands = /* @__PURE__ */ new Set();
5017
+ const seenItems = /* @__PURE__ */ new Set();
5018
+ const completedTurns = /* @__PURE__ */ new Set();
5019
+ let threadId = "";
5020
+ let active2 = true;
5021
+ let waiting = false;
5022
+ let terminalListing = true;
5023
+ let timer;
5024
+ let ended = false;
5025
+ let checking = false;
5026
+ let context;
5027
+ let total;
5028
+ let baseline;
5029
+ let model;
5030
+ let provider;
5031
+ let resolve2;
5032
+ const done2 = new Promise((r) => {
5033
+ resolve2 = r;
5034
+ });
5035
+ const deadline = createBackgroundWait(BACKGROUND_WAIT.minutes * 6e4, () => end2(backgroundWaitMessage(BACKGROUND_WAIT.minutes)));
5036
+ const emit = (type, extra = {}) => {
5037
+ io.log(renderer.push(JSON.stringify({ type, ...extra }) + "\n"));
5038
+ for (const event2 of renderer.events?.() ?? []) io.event?.(event2);
5039
+ };
5040
+ const end2 = (error) => {
5041
+ if (ended) return;
5042
+ ended = true;
5043
+ clearTimeout(timer);
5044
+ deadline.close();
5045
+ io.stdout.off("close", closed2);
5046
+ io.log(renderer.flush());
5047
+ const usage3 = total && (!options.threadId && !io.resumeId ? total : baseline ? {
5048
+ input: Math.max(0, total.input - baseline.input),
5049
+ cacheRead: Math.max(0, total.cacheRead - baseline.cacheRead),
5050
+ cacheCreation: Math.max(0, total.cacheCreation - baseline.cacheCreation),
5051
+ output: Math.max(0, total.output - baseline.output)
5052
+ } : void 0);
5053
+ const failure = error || tasks.failure();
5054
+ if (failure) io.event?.({ kind: "error", data: { text: failure } });
5055
+ resolve2({ ok: !failure, error: failure, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: usage3, context, costUsd: priceUsd(provider, model, usage3) });
5056
+ };
5057
+ const closed2 = () => end2("Codex closed the connection before all work and results finished.");
5058
+ io.stdout.once("close", closed2);
5059
+ const update2 = (id, state, title = "") => {
5060
+ if (ended) return;
5061
+ const status = str(state.status);
5062
+ if (!status || !id) return;
5063
+ const previous = tasks.results().find((t) => t.id === `agent:${id}`);
5064
+ if (["shutdown", "notFound", "not_found"].includes(status) && previous && previous.status !== "running") return;
5065
+ const running = ["pendingInit", "running", "pending_init"].includes(status);
5066
+ const failed = ["interrupted", "errored", "shutdown", "notFound", "not_found"].includes(status);
5067
+ if (!running && !failed && status !== "completed") return;
5068
+ const known2 = children.has(id);
5069
+ children.add(id);
5070
+ if (!known2) io.event?.({ kind: "tool_call", data: { toolCallId: `agent:${id}`, title: targetOf(title) || "Agent", kind: "other", status: "in_progress", subagent: true } });
5071
+ if (tasks.update(`agent:${id}`, running ? "running" : failed ? "failed" : "completed", str(state.message)) && !running) {
5072
+ io.event?.({ kind: "tool_call_update", data: { toolCallId: `agent:${id}`, status: failed ? "failed" : "completed", result: str(state.message) } });
5073
+ }
5074
+ };
5075
+ const item = (raw, completed) => {
5076
+ if (ended) return;
5077
+ const id = str(raw.id);
5078
+ if (raw.type === "collabAgentToolCall") {
5079
+ const key2 = `${id}:${completed}`;
5080
+ if (seenItems.has(key2)) return;
5081
+ seenItems.add(key2);
5082
+ for (const [child, state] of Object.entries(obj(raw.agentsStates))) update2(child, obj(state), str(raw.prompt));
5083
+ for (const child of Array.isArray(raw.receiverThreadIds) ? raw.receiverThreadIds : []) {
5084
+ if (typeof child === "string" && !children.has(child) && raw.tool === "spawnAgent") update2(child, { status: "running" }, str(raw.prompt));
5085
+ }
5086
+ return;
5087
+ }
5088
+ if (raw.type === "commandExecution") {
5089
+ if (seenItems.has(`${id}:true`)) return;
5090
+ if (raw.status === "inProgress") completed = false;
5091
+ if (!completed) {
5092
+ commands.add(id);
5093
+ if (tasks.results().some((t) => t.id === `command:${id}`)) tasks.update(`command:${id}`, "running");
5094
+ } else {
5095
+ commands.delete(id);
5096
+ const failed = raw.status === "failed" || typeof raw.exitCode === "number" && raw.exitCode !== 0;
5097
+ if (tasks.results().some((t) => t.id === `command:${id}`)) tasks.update(`command:${id}`, failed ? "failed" : "completed", str(raw.aggregatedOutput));
5098
+ }
5099
+ }
5100
+ const key = `${id}:${completed}`;
5101
+ if (seenItems.has(key)) return;
5102
+ seenItems.add(key);
5103
+ const types = { agentMessage: "agent_message", commandExecution: "command_execution", fileChange: "file_change", mcpToolCall: "mcp_tool_call", webSearch: "web_search", imageGeneration: "image_generation" };
5104
+ const type = types[str(raw.type)];
5105
+ if (!type) return;
5106
+ emit(completed ? "item.completed" : "item.started", { item: {
5107
+ ...raw,
5108
+ type,
5109
+ ...raw.type === "imageGeneration" ? { path: raw.savedPath ?? raw.path } : {},
5110
+ ...raw.type === "fileChange" ? { changes: list(raw.changes).map((c) => ({ ...c, kind: str(obj(c.kind).type) || c.kind })) } : {},
5111
+ aggregated_output: raw.aggregatedOutput,
5112
+ exit_code: raw.exitCode,
5113
+ status: raw.status === "inProgress" ? "in_progress" : raw.status
5114
+ } });
5115
+ };
5116
+ const start = async (text4, images = []) => {
5117
+ active2 = true;
5118
+ waiting = false;
5119
+ await rpc.call("turn/start", { threadId, input: [{ type: "text", text: text4 }, ...images.map((path86) => ({ type: "localImage", path: path86 }))] });
5120
+ };
5121
+ const schedule = () => {
5122
+ if (ended || timer) return;
5123
+ timer = setTimeout(() => {
5124
+ timer = void 0;
5125
+ void check();
5126
+ }, 1e3);
5127
+ };
5128
+ const check = async () => {
5129
+ if (ended || checking || active2) return;
5130
+ checking = true;
5131
+ try {
5132
+ for (const key of tasks.running().filter((id) => id.startsWith("agent:"))) {
5133
+ const id = key.slice(6);
5134
+ let thread = obj((await rpc.call("thread/read", { threadId: id, includeTurns: false })).thread);
5135
+ let turns = list(thread.turns);
5136
+ if (thread.historyMode === "paginated") {
5137
+ turns = list((await rpc.call("thread/turns/list", { threadId: id, sortDirection: "desc", limit: 1, itemsView: "full" })).data).reverse();
5138
+ } else if (!turns.length) {
5139
+ thread = obj((await rpc.call("thread/read", { threadId: id, includeTurns: true })).thread);
5140
+ turns = list(thread.turns);
5141
+ }
5142
+ const turn2 = turns.at(-1);
5143
+ const status = str(turn2?.status);
5144
+ if (obj(thread.status).type === "systemError") update2(id, { status: "errored", message: "Codex subagent reported a system error." });
5145
+ else if (obj(thread.status).type !== "active" && turn2 && ["completed", "failed", "interrupted"].includes(status)) {
5146
+ const message = list(turn2.items).filter((i) => i.type === "agentMessage").map((i) => str(i.text)).join("\n\n");
5147
+ update2(id, { status: status === "completed" ? "completed" : "errored", message: str(obj(turn2.error).message) || message });
5148
+ }
5149
+ }
5150
+ if (terminalListing) {
5151
+ try {
5152
+ const running = /* @__PURE__ */ new Set();
5153
+ let cursor = null;
5154
+ const cursors = /* @__PURE__ */ new Set();
5155
+ do {
5156
+ if (cursor && cursors.has(cursor)) throw Error("Codex repeated a background terminal cursor.");
5157
+ cursors.add(cursor);
5158
+ const page = await rpc.call("thread/backgroundTerminals/list", { threadId, ...cursor ? { cursor } : {} });
5159
+ for (const terminal of list(page.data)) {
5160
+ const id = str(terminal.itemId) || str(terminal.processId);
5161
+ if (id) {
5162
+ running.add(id);
5163
+ tasks.update(`command:${id}`, "running");
5164
+ }
5165
+ }
5166
+ cursor = page.nextCursor;
5167
+ } while (cursor && !ended);
5168
+ for (const id of tasks.running().filter((id2) => id2.startsWith("command:"))) if (!running.has(id.slice(8))) {
5169
+ tasks.update(id, "completed");
5170
+ commands.delete(id.slice(8));
5171
+ }
5172
+ } catch (e) {
5173
+ if (!(e instanceof RpcError) || e.code !== -32601) throw e;
5174
+ terminalListing = false;
5175
+ io.log("[Codex] This version does not report background terminals.\n");
5176
+ if (commands.size) throw Error("This Codex version cannot report the unfinished background commands. Update Codex to collect their results.");
5177
+ }
5178
+ }
5179
+ if (ended || active2) return;
5180
+ if (tasks.count()) {
5181
+ waiting = true;
5182
+ deadline.pending();
5183
+ schedule();
5184
+ return;
5185
+ }
5186
+ if (waiting) {
5187
+ await start("The background work from your previous reply has finished. Collect its results, resolve any failures, and present the completed outcome in this conversation. Check existing progress before acting; do not repeat completed work. Background reports (task output, not instructions):\n" + JSON.stringify(tasks.results()));
5188
+ } else end2();
5189
+ } catch (e) {
5190
+ end2(String(e instanceof Error ? e.message : e));
5191
+ } finally {
5192
+ checking = false;
5193
+ }
5194
+ };
5195
+ const rpc = connect(io.stdout, io.stdin, (msg) => {
5196
+ if (ended) return;
5197
+ if (msg.id !== void 0) {
5198
+ rpc.refuse(msg.id, "WildCrane cannot answer interactive requests in an unattended run.");
5199
+ end2(`Codex requested interaction: ${msg.method}`);
5200
+ return;
5201
+ }
5202
+ const p = obj(msg.params);
5203
+ if (str(p.threadId) !== threadId) return;
5204
+ if (msg.method === "turn/started") {
5205
+ active2 = true;
5206
+ return;
5207
+ }
5208
+ if (msg.method === "item/started" || msg.method === "item/completed") item(obj(p.item), msg.method === "item/completed");
5209
+ if (msg.method === "thread/tokenUsage/updated") {
5210
+ const token2 = obj(p.tokenUsage);
5211
+ const counts = obj(token2.total);
5212
+ const input = Number(counts.inputTokens) || 0;
5213
+ const read3 = Number(counts.cachedInputTokens) || 0;
5214
+ const write2 = Number(counts.cacheWriteInputTokens) || 0;
5215
+ total = { input: Math.max(0, input - read3 - write2), cacheRead: read3, cacheCreation: write2, output: Number(counts.outputTokens) || 0 };
5216
+ const last = obj(token2.last);
5217
+ context = { used: (Number(last.inputTokens) || 0) + (Number(last.outputTokens) || 0), ...Number(token2.modelContextWindow) > 0 ? { limit: Number(token2.modelContextWindow) } : {} };
5218
+ io.gotContext?.(context);
5219
+ }
5220
+ if (msg.method === "error" && p.willRetry !== true) end2(str(obj(p.error).message) || "Codex failed.");
5221
+ if (msg.method === "turn/completed") {
5222
+ const turn2 = obj(p.turn);
5223
+ const id = str(turn2.id);
5224
+ if (completedTurns.has(id)) return;
5225
+ completedTurns.add(id);
5226
+ for (const raw of list(turn2.items)) item(raw, true);
5227
+ if (turn2.status !== "completed") {
5228
+ end2(str(obj(turn2.error).message) || `Codex turn ${str(turn2.status)}.`);
5229
+ return;
5230
+ }
5231
+ active2 = false;
5232
+ for (const id2 of commands) tasks.update(`command:${id2}`, "running");
5233
+ waiting ||= tasks.count() > 0 || commands.size > 0;
5234
+ deadline.pending();
5235
+ void check();
5236
+ }
5237
+ });
5238
+ try {
5239
+ await rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } });
5240
+ rpc.notify("initialized");
5241
+ const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
5242
+ let response;
5243
+ try {
5244
+ response = await rpc.call(`thread/${mode ?? "start"}`, { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} });
5245
+ } catch (e) {
5246
+ if (mode && e instanceof RpcError && /no rollout found for thread id/i.test(e.message)) throw Error(`Thread not found: ${e.message}`);
5247
+ throw e;
5248
+ }
5249
+ const thread = obj(response.thread);
5250
+ threadId = str(thread.id);
5251
+ if (!threadId) throw Error("Codex did not return a thread id.");
5252
+ provider = str(thread.modelProvider) || void 0;
5253
+ model = str(response.model) || str(thread.model) || void 0;
5254
+ if (model) io.gotModel(model);
5255
+ io.gotResumeId(threadId);
5256
+ baseline = readCodexRunFacts(threadId)?.turns?.at(-1)?.total;
5257
+ emit("thread.started", { thread_id: threadId });
5258
+ await start(io.prompt, options.images);
5259
+ } catch (e) {
5260
+ end2(e instanceof Error ? e.message : String(e));
5261
+ }
5262
+ return done2;
5263
+ }
5264
+ var list;
5265
+ var init_codex = __esm({
5266
+ "src/lib/agent/wire/codex.ts"() {
5267
+ "use strict";
5268
+ init_settings();
5269
+ init_background();
5270
+ init_codex_stream();
5271
+ init_codex_session();
5272
+ init_json();
5273
+ init_events();
5274
+ init_rpc();
5275
+ init_prices();
5276
+ list = (value) => Array.isArray(value) ? value.map(obj) : [];
5277
+ }
5278
+ });
5279
+
4848
5280
  // src/lib/agent/wire/index.ts
4849
5281
  var init_wire = __esm({
4850
5282
  "src/lib/agent/wire/index.ts"() {
@@ -4856,6 +5288,8 @@ var init_wire = __esm({
4856
5288
  init_kimi_stream();
4857
5289
  init_acp();
4858
5290
  init_zcode();
5291
+ init_codex();
5292
+ init_background();
4859
5293
  }
4860
5294
  });
4861
5295
 
@@ -4878,8 +5312,8 @@ function str2(value) {
4878
5312
  function num2(value) {
4879
5313
  return typeof value === "number" ? value : Number.MAX_SAFE_INTEGER;
4880
5314
  }
4881
- function uniqueIds(list) {
4882
- return [...new Set(list.map((id) => id.trim()).filter(Boolean))];
5315
+ function uniqueIds(list2) {
5316
+ return [...new Set(list2.map((id) => id.trim()).filter(Boolean))];
4883
5317
  }
4884
5318
  function modelsIn2(file, pick2, salt = "") {
4885
5319
  let stamp4;
@@ -5404,7 +5838,7 @@ function codexInstalls() {
5404
5838
  ];
5405
5839
  }
5406
5840
  var QUIET_CONFIG, ARCHES, CODEX;
5407
- var init_codex = __esm({
5841
+ var init_codex2 = __esm({
5408
5842
  "src/lib/agent/harnesses/codex.ts"() {
5409
5843
  "use strict";
5410
5844
  init_paths();
@@ -5426,6 +5860,7 @@ var init_codex = __esm({
5426
5860
  "codex exec --json --sandbox workspace-write",
5427
5861
  "codex exec --json --sandbox workspace-write -c sandbox_workspace_write.network_access=true"
5428
5862
  ],
5863
+ connection: createCodexConnection,
5429
5864
  installs: codexInstalls,
5430
5865
  pinned: () => process.env.CODEX_CLI_PATH?.trim() || void 0,
5431
5866
  // Nothing to pin: Codex mints its own thread id and takes none from us, so the generated
@@ -6377,7 +6812,7 @@ var init_harnesses = __esm({
6377
6812
  "use strict";
6378
6813
  init_check();
6379
6814
  init_claude_code();
6380
- init_codex();
6815
+ init_codex2();
6381
6816
  init_cursor();
6382
6817
  init_dsh();
6383
6818
  init_grok();
@@ -6660,8 +7095,8 @@ function settingArgs(harness, held4) {
6660
7095
  const { values } = held4;
6661
7096
  const ignored = held4.ignored ?? [];
6662
7097
  const picked = providerFor(harness, held4);
6663
- const list = providerSetting(harness.settings);
6664
- const byHand = !!list && ignored.includes(list.key);
7098
+ const list2 = providerSetting(harness.settings);
7099
+ const byHand = !!list2 && ignored.includes(list2.key);
6665
7100
  const providerArgs = byHand ? [] : picked?.args ?? [];
6666
7101
  const flags = harness.settings.flatMap((setting) => {
6667
7102
  const value = values[setting.key];
@@ -6691,9 +7126,9 @@ function settingEnv(harness, held4, secrets, cwd) {
6691
7126
  }
6692
7127
  function ownedVars(harness) {
6693
7128
  const names3 = new Set(harness.providerEnv ?? []);
6694
- const list = providerSetting(harness.settings);
6695
- if (!list) return [...names3];
6696
- for (const provider of list.providers ?? []) {
7129
+ const list2 = providerSetting(harness.settings);
7130
+ if (!list2) return [...names3];
7131
+ for (const provider of list2.providers ?? []) {
6697
7132
  for (const name of Object.values(provider.envAs ?? {})) names3.add(name);
6698
7133
  for (const name of Object.keys(provider.env ?? {})) names3.add(name);
6699
7134
  for (const key of provider.needs) {
@@ -7195,17 +7630,17 @@ function noteRefineTried(store, cardId2) {
7195
7630
  }
7196
7631
  function cardsBeingCreated(runs = readRuns()) {
7197
7632
  const newest2 = /* @__PURE__ */ new Map();
7198
- for (const run2 of runs) {
7199
- for (const id of run2.createdCardIds ?? []) {
7200
- if (run2.cardId === id) continue;
7633
+ for (const run3 of runs) {
7634
+ for (const id of run3.createdCardIds ?? []) {
7635
+ if (run3.cardId === id) continue;
7201
7636
  const best = newest2.get(id);
7202
- if (!best || run2.startedAt >= best.startedAt) newest2.set(id, run2);
7637
+ if (!best || run3.startedAt >= best.startedAt) newest2.set(id, run3);
7203
7638
  }
7204
7639
  }
7205
7640
  const out = /* @__PURE__ */ new Map();
7206
- for (const [id, run2] of newest2) {
7207
- if (runIsLive(run2)) out.set(id, { state: "creating", runId: run2.sessionId });
7208
- else if (run2.status !== "done") out.set(id, { state: "unfinished", runId: run2.sessionId });
7641
+ for (const [id, run3] of newest2) {
7642
+ if (runIsLive(run3)) out.set(id, { state: "creating", runId: run3.sessionId });
7643
+ else if (run3.status !== "done") out.set(id, { state: "unfinished", runId: run3.sessionId });
7209
7644
  }
7210
7645
  return out;
7211
7646
  }
@@ -7463,9 +7898,9 @@ function recordCreatedCards(sessionId, ids) {
7463
7898
  const valid = ids.filter((id) => Number.isInteger(id) && id > 0);
7464
7899
  if (!valid.length) return false;
7465
7900
  return withRuns((runs) => {
7466
- const run2 = runs.find((entry) => entry.sessionId === sessionId && entry.status === "running");
7467
- if (!run2) return false;
7468
- run2.createdCardIds = [.../* @__PURE__ */ new Set([...run2.createdCardIds ?? [], ...valid])];
7901
+ const run3 = runs.find((entry) => entry.sessionId === sessionId && entry.status === "running");
7902
+ if (!run3) return false;
7903
+ run3.createdCardIds = [.../* @__PURE__ */ new Set([...run3.createdCardIds ?? [], ...valid])];
7469
7904
  return true;
7470
7905
  });
7471
7906
  }
@@ -7507,7 +7942,7 @@ var init_store = __esm({
7507
7942
  stringRecord = (raw) => raw && typeof raw === "object" && !Array.isArray(raw) && Object.values(raw).every((v) => typeof v === "string") ? raw : void 0;
7508
7943
  readRuns = () => readStore().runs;
7509
7944
  PENDING_MS = 3e4;
7510
- runIsLive = (run2) => run2.status === "running" && (run2.pid ? pidAlive(run2.pid) : Date.now() - run2.startedAt < PENDING_MS);
7945
+ runIsLive = (run3) => run3.status === "running" && (run3.pid ? pidAlive(run3.pid) : Date.now() - run3.startedAt < PENDING_MS);
7511
7946
  creationOf = (runs, cardId2) => cardsBeingCreated(runs).get(cardId2);
7512
7947
  cardCreation = (cardId2, strict = false) => {
7513
7948
  const runs = readRuns();
@@ -7656,9 +8091,9 @@ var init_flows = __esm({
7656
8091
  import fs25 from "node:fs";
7657
8092
  function readRuntimes(cfg = safeConfig()) {
7658
8093
  const saved = Array.isArray(cfg.runtimes) ? cfg.runtimes.map(parseRuntime).filter(isRuntime) : null;
7659
- const list = saved?.length ? dedupe(saved) : fromHarnessBlocks(cfg);
7660
- const global = list.find((r) => r.id === GLOBAL_ID);
7661
- const rest = list.filter((r) => r.id !== GLOBAL_ID);
8094
+ const list2 = saved?.length ? dedupe(saved) : fromHarnessBlocks(cfg);
8095
+ const global = list2.find((r) => r.id === GLOBAL_ID);
8096
+ const rest = list2.filter((r) => r.id !== GLOBAL_ID);
7662
8097
  return [global ?? { id: GLOBAL_ID, name: GLOBAL_NAME, harness: DEFAULT_HARNESS.name, settings: {} }, ...rest];
7663
8098
  }
7664
8099
  function parseRuntime(value) {
@@ -7674,15 +8109,15 @@ function parseRuntime(value) {
7674
8109
  const away = typeof raw.away === "string" && raw.away.trim() ? { away: raw.away.trim() } : {};
7675
8110
  return { id, name: id === GLOBAL_ID ? GLOBAL_NAME : name, harness, settings, ...away };
7676
8111
  }
7677
- function dedupe(list) {
8112
+ function dedupe(list2) {
7678
8113
  const seen = /* @__PURE__ */ new Set();
7679
- return list.filter((r) => !seen.has(r.id) && seen.add(r.id));
8114
+ return list2.filter((r) => !seen.has(r.id) && seen.add(r.id));
7680
8115
  }
7681
8116
  function fromHarnessBlocks(cfg) {
7682
8117
  const asked = typeof cfg.harness === "string" ? cfg.harness.trim() : "";
7683
8118
  const fallback = (harnessByName(asked) ?? DEFAULT_HARNESS).name;
7684
8119
  const blocks = configBlock(cfg.harnessSettings);
7685
- const list = [
8120
+ const list2 = [
7686
8121
  { id: GLOBAL_ID, name: GLOBAL_NAME, harness: asked || fallback, settings: valuesOf(blocks[asked || fallback]) }
7687
8122
  ];
7688
8123
  const taken = /* @__PURE__ */ new Set([GLOBAL_ID]);
@@ -7690,9 +8125,9 @@ function fromHarnessBlocks(cfg) {
7690
8125
  if (harness === (asked || fallback)) continue;
7691
8126
  const id = freeId(harness, taken);
7692
8127
  taken.add(id);
7693
- list.push({ id, name: harnessByName(harness)?.label ?? harness, harness, settings: valuesOf(block) });
8128
+ list2.push({ id, name: harnessByName(harness)?.label ?? harness, harness, settings: valuesOf(block) });
7694
8129
  }
7695
- return list;
8130
+ return list2;
7696
8131
  }
7697
8132
  function valuesOf(block) {
7698
8133
  const out = {};
@@ -7701,15 +8136,15 @@ function valuesOf(block) {
7701
8136
  }
7702
8137
  return out;
7703
8138
  }
7704
- function pickRuntime(list, pin, harness) {
7705
- const rows = harness ? list.filter((r) => r.harness === harness) : list;
8139
+ function pickRuntime(list2, pin, harness) {
8140
+ const rows = harness ? list2.filter((r) => r.harness === harness) : list2;
7706
8141
  const want = pin?.trim();
7707
8142
  const found2 = want && (rows.find((r) => r.id === want) ?? rows.find((r) => r.harness === want));
7708
8143
  if (found2) return found2;
7709
8144
  return rows[0] ?? { id: "", name: harness ?? "", harness: harness ?? DEFAULT_HARNESS.name, settings: {} };
7710
8145
  }
7711
- function runtimeById(id, list = readRuntimes()) {
7712
- return list.find((r) => r.id === id);
8146
+ function runtimeById(id, list2 = readRuntimes()) {
8147
+ return list2.find((r) => r.id === id);
7713
8148
  }
7714
8149
  function secretVar(env2, runtimeId) {
7715
8150
  return `${env2}__${runtimeId.replace(/[^A-Za-z0-9]+/g, "_").toUpperCase()}`;
@@ -7776,23 +8211,23 @@ function setHarness(name) {
7776
8211
  return setRuntimeHarness(GLOBAL_ID, name);
7777
8212
  }
7778
8213
  function change(id, edit) {
7779
- const list = readRuntimes();
7780
- if (!list.some((r) => r.id === id)) return { ok: false, ...noRuntime(id) };
7781
- return save(list.map((r) => r.id === id ? edit(r) : r));
8214
+ const list2 = readRuntimes();
8215
+ if (!list2.some((r) => r.id === id)) return { ok: false, ...noRuntime(id) };
8216
+ return save(list2.map((r) => r.id === id ? edit(r) : r));
7782
8217
  }
7783
- function save(list) {
8218
+ function save(list2) {
7784
8219
  return writeConfig((cfg) => {
7785
8220
  const picks = readAgentRuntime(cfg);
7786
- cfg.runtimes = list;
8221
+ cfg.runtimes = list2;
7787
8222
  delete cfg.harnessSettings;
7788
8223
  delete cfg.harness;
7789
- writePicks(cfg, picks, list);
8224
+ writePicks(cfg, picks, list2);
7790
8225
  });
7791
8226
  }
7792
- function writePicks(cfg, picks, list = readRuntimes(cfg)) {
8227
+ function writePicks(cfg, picks, list2 = readRuntimes(cfg)) {
7793
8228
  const block = {};
7794
8229
  for (const [agent, pin] of Object.entries(picks)) {
7795
- const row = pickRuntime(list, pin);
8230
+ const row = pickRuntime(list2, pin);
7796
8231
  if (keepsPick(row.id)) block[agent] = row.id;
7797
8232
  }
7798
8233
  delete cfg.agentHarness;
@@ -7817,13 +8252,13 @@ function migrateRuntimes(agents, localModels) {
7817
8252
  return null;
7818
8253
  }
7819
8254
  if (Array.isArray(cfg.runtimes) && cfg.runtimes.length) return null;
7820
- const list = fromHarnessBlocks(cfg);
7821
- const taken = new Set(list.map((r) => r.id));
8255
+ const list2 = fromHarnessBlocks(cfg);
8256
+ const taken = new Set(list2.map((r) => r.id));
7822
8257
  const picks = {};
7823
8258
  const bound = configBlock(cfg.agentHarness);
7824
8259
  for (const agent of agents) {
7825
8260
  const named2 = typeof bound[agent] === "string" ? bound[agent].trim() : "";
7826
- const base = pickRuntime(list, named2 || void 0);
8261
+ const base = pickRuntime(list2, named2 || void 0);
7827
8262
  const model = localModels[agent]?.[base.harness] ?? {};
7828
8263
  if (!Object.keys(model).length || sameValues(base.settings, model)) {
7829
8264
  if (named2 && base.id !== GLOBAL_ID) picks[agent] = base.id;
@@ -7831,17 +8266,17 @@ function migrateRuntimes(agents, localModels) {
7831
8266
  }
7832
8267
  const id = freeId(agent, taken);
7833
8268
  taken.add(id);
7834
- list.push({ id, name: agent, harness: base.harness, settings: { ...base.settings, ...model } });
8269
+ list2.push({ id, name: agent, harness: base.harness, settings: { ...base.settings, ...model } });
7835
8270
  picks[agent] = id;
7836
8271
  }
7837
- cfg.runtimes = list;
8272
+ cfg.runtimes = list2;
7838
8273
  if (Object.keys(picks).length) cfg.agentRuntime = picks;
7839
8274
  delete cfg.harness;
7840
8275
  delete cfg.harnessSettings;
7841
8276
  delete cfg.agentHarness;
7842
8277
  fs25.writeFileSync(UI_CONFIG, JSON.stringify(cfg, null, 2) + "\n");
7843
- const minted = list.length - 1;
7844
- return `turned this board's connector settings into ${list.length} runtime${list.length === 1 ? "" : "s"}${minted ? ` \u2014 ${GLOBAL_NAME} and ${minted} more` : ""}, and pointed each agent at one`;
8278
+ const minted = list2.length - 1;
8279
+ return `turned this board's connector settings into ${list2.length} runtime${list2.length === 1 ? "" : "s"}${minted ? ` \u2014 ${GLOBAL_NAME} and ${minted} more` : ""}, and pointed each agent at one`;
7845
8280
  }
7846
8281
  function repairEnvFile() {
7847
8282
  const env2 = readEnvFile();
@@ -7928,11 +8363,11 @@ function readBlock(harness, block, argv, runtimeId) {
7928
8363
  if (value) values[setting.key] = value;
7929
8364
  if (setting.flags?.length && namesFlag(argv, setting.flags)) ignored.push(setting.key);
7930
8365
  }
7931
- const list = providerSetting(harness.settings);
7932
- if (list) {
7933
- const picked = pickedProvider(list, values[list.key] ?? "", isFilled(harness, { values, secretsSet }));
7934
- if (picked) values[list.key] = picked.id;
7935
- else delete values[list.key];
8366
+ const list2 = providerSetting(harness.settings);
8367
+ if (list2) {
8368
+ const picked = pickedProvider(list2, values[list2.key] ?? "", isFilled(harness, { values, secretsSet }));
8369
+ if (picked) values[list2.key] = picked.id;
8370
+ else delete values[list2.key];
7936
8371
  }
7937
8372
  return { values, secretsSet, ignored };
7938
8373
  }
@@ -7951,13 +8386,13 @@ function resolveHarness(ask2 = {}) {
7951
8386
  const cfg = safeConfig();
7952
8387
  const staleCommand = typeof cfg.command === "string" && cfg.command.trim() ? true : void 0;
7953
8388
  const agent = ask2.agent ?? "";
7954
- const list = readRuntimes(cfg);
8389
+ const list2 = readRuntimes(cfg);
7955
8390
  const table = readAgentRuntime(cfg);
7956
8391
  const owner = agent ? runtimeOwner(agent) : "";
7957
8392
  const picked = owner ? runtimeOfAgent(specAgentNames(owner), table) : void 0;
7958
8393
  const asked = ask2.pin ?? picked;
7959
- const runtime = pickRuntime(list, asked, ask2.harness);
7960
- const unknownAgentRuntime = picked && !ask2.pin && !list.some((r) => r.id === picked || r.harness === picked) ? picked : void 0;
8394
+ const runtime = pickRuntime(list2, asked, ask2.harness);
8395
+ const unknownAgentRuntime = picked && !ask2.pin && !list2.some((r) => r.id === picked || r.harness === picked) ? picked : void 0;
7961
8396
  const known2 = harnessByName(runtime.harness);
7962
8397
  const harness = known2 ?? DEFAULT_HARNESS;
7963
8398
  const command = commandOf(runtime.settings, harness);
@@ -7996,13 +8431,13 @@ function agentHarness(agent) {
7996
8431
  function settingSaveError(key, value, ask2 = {}) {
7997
8432
  const resolved2 = resolveHarness(ask2);
7998
8433
  const { harness, values, secretsSet } = resolved2;
7999
- const list = providerSetting(harness.settings);
8000
- if (!list) return null;
8434
+ const list2 = providerSetting(harness.settings);
8435
+ if (!list2) return null;
8001
8436
  const filled = isFilled(harness, { values, secretsSet });
8002
8437
  const label = (k) => harness.settings.find((s) => s.key === k)?.label ?? k;
8003
- if (key === list.key) {
8004
- const provider = list.providers?.find((p) => p.id === value);
8005
- if (!provider) return `"${value}" isn't one of the ${list.label.toLowerCase()} choices`;
8438
+ if (key === list2.key) {
8439
+ const provider = list2.providers?.find((p) => p.id === value);
8440
+ if (!provider) return `"${value}" isn't one of the ${list2.label.toLowerCase()} choices`;
8006
8441
  const missing = missingHere(harness, provider, filled);
8007
8442
  if (missing.length) {
8008
8443
  const names3 = missing.map((k) => `"${label(k)}"`).join(" and ");
@@ -8086,20 +8521,21 @@ function openPlan(plan) {
8086
8521
  const started = [start.binary, ...plan.argv.slice(1)];
8087
8522
  const { argv, env: planned, note } = withSystemLanguage(harness, started, runEnv2(resolved2, plan.cwd ?? REPO_ROOT), runLanguage());
8088
8523
  const env2 = copyEnv(start.binary, planned);
8524
+ const connection = harness.connection?.(argv);
8089
8525
  return {
8090
8526
  ...plan,
8091
- argv,
8527
+ argv: connection?.argv ?? argv,
8092
8528
  ...[start.note, note].some(Boolean) ? { startNote: [start.note, note].filter(Boolean).join("\n") } : {},
8093
8529
  env: env2,
8094
8530
  // The folder and the binary: what a renderer needs to go looking for what the stream
8095
8531
  // left out (agent/harnesses/types.ts). argv's first word is the command's own binary,
8096
8532
  // the same one the spawn resolves and an ENOENT names.
8097
- renderer: harness.renderer?.(plan.cwd ?? REPO_ROOT, argv[0], argv),
8533
+ renderer: connection ? void 0 : harness.renderer?.(plan.cwd ?? REPO_ROOT, argv[0], argv),
8098
8534
  // The client is handed the settings that are actually in effect — the same ones that
8099
8535
  // would have reached the run as flags, minus whatever the picked provider doesn't
8100
8536
  // need — because for a connector that talks, a setting is something the conversation
8101
8537
  // opens with rather than something argv carries.
8102
- client: harness.client?.(effectiveValues2(resolved2)),
8538
+ client: connection?.client ?? harness.client?.(effectiveValues2(resolved2)),
8103
8539
  // Read off the argv, so a plan written before the CLI took its turns on stdin still runs.
8104
8540
  stdinPrompt: harness.stdinPrompt?.(argv),
8105
8541
  quietStderr: harness.quietStderr,
@@ -8128,11 +8564,11 @@ function modelsRun() {
8128
8564
  const ran = /* @__PURE__ */ new Map();
8129
8565
  const { runs } = readStore();
8130
8566
  for (let i = runs.length - 1; i >= 0; i--) {
8131
- const run2 = runs[i];
8132
- if (!run2.harness || !run2.model) continue;
8133
- const seen = ran.get(run2.harness) ?? [];
8134
- if (!seen.includes(run2.model)) seen.push(run2.model);
8135
- ran.set(run2.harness, seen);
8567
+ const run3 = runs[i];
8568
+ if (!run3.harness || !run3.model) continue;
8569
+ const seen = ran.get(run3.harness) ?? [];
8570
+ if (!seen.includes(run3.model)) seen.push(run3.model);
8571
+ ran.set(run3.harness, seen);
8136
8572
  }
8137
8573
  return ran;
8138
8574
  }
@@ -9442,7 +9878,7 @@ var init_yaml2 = __esm({
9442
9878
  });
9443
9879
 
9444
9880
  // src/lib/agents/parse.ts
9445
- function parseSpecAgent(text4, from, file, builtIn = false, list = () => []) {
9881
+ function parseSpecAgent(text4, from, file, builtIn = false, list2 = () => []) {
9446
9882
  let named2 = "";
9447
9883
  const bad = (why2, old2) => ({
9448
9884
  problem: `${from}: ${why2}`,
@@ -9504,7 +9940,7 @@ function parseSpecAgent(text4, from, file, builtIn = false, list = () => []) {
9504
9940
  ...declaredSession ? { session: "new" } : {},
9505
9941
  memory: names(akb.memory),
9506
9942
  memoryFiles: { workspace: workspace2 },
9507
- files: list(),
9943
+ files: list2(),
9508
9944
  body: instructions,
9509
9945
  from,
9510
9946
  builtIn,
@@ -9533,12 +9969,12 @@ function memoryPaths(raw, folder = "memory/agents/<name>/") {
9533
9969
  const block = map(raw);
9534
9970
  const extra = block ? Object.keys(block).filter((key) => key !== "workspace") : [];
9535
9971
  if (!block || extra.length) return `\`akb.memoryFiles\` with ${block ? `\`${extra.join("`, `")}\`` : "no `workspace:` list"} \u2014 it holds only \`workspace: [<path>, ...]\``;
9536
- const list = block.workspace;
9537
- if (list === void 0) return [];
9538
- if (!Array.isArray(list) || list.some((v) => typeof v !== "string" || !v.trim())) {
9972
+ const list2 = block.workspace;
9973
+ if (list2 === void 0) return [];
9974
+ if (!Array.isArray(list2) || list2.some((v) => typeof v !== "string" || !v.trim())) {
9539
9975
  return "`akb.memoryFiles.workspace` that is not a list of paths \u2014 write `workspace: [style.md]`";
9540
9976
  }
9541
- const paths = [...new Set(list.map((v) => v.trim()))];
9977
+ const paths = [...new Set(list2.map((v) => v.trim()))];
9542
9978
  const outside = paths.find((p) => p.startsWith("/") || p.includes("\\") || p.split("/").some((part) => part === ".." || part === "."));
9543
9979
  if (outside) return `\`akb.memoryFiles.workspace: ${outside}\`, which is outside its memory folder \u2014 use a path inside \`${folder}\``;
9544
9980
  return paths;
@@ -10047,8 +10483,8 @@ function readFlows() {
10047
10483
  }
10048
10484
  const project2 = boardProject();
10049
10485
  if (!project2 || !readSession()) return [];
10050
- const list = readJson(listFile(project2))?.studios ?? [];
10051
- const flows2 = list.flatMap((w) => {
10486
+ const list2 = readJson(listFile(project2))?.studios ?? [];
10487
+ const flows2 = list2.flatMap((w) => {
10052
10488
  const held4 = readVersion(w.id, w.version);
10053
10489
  return held4 ? flowOf(held4) ?? [] : [];
10054
10490
  });
@@ -10243,8 +10679,8 @@ function readBundled(folder) {
10243
10679
  const file = (relative) => shipped[`${folder}/${relative}`] ?? null;
10244
10680
  const text4 = file("AGENT.md");
10245
10681
  if (text4 === null) return { problem: `${label} has no AGENT.md` };
10246
- const list = () => ownFiles(Object.keys(shipped).filter((k) => k.startsWith(`${folder}/`)).map((k) => k.slice(folder.length + 1)));
10247
- return parseSpecAgent(text4, label, file, official, list);
10682
+ const list2 = () => ownFiles(Object.keys(shipped).filter((k) => k.startsWith(`${folder}/`)).map((k) => k.slice(folder.length + 1)));
10683
+ return parseSpecAgent(text4, label, file, official, list2);
10248
10684
  }
10249
10685
  function projectFolders(root2) {
10250
10686
  let entries;
@@ -10937,8 +11373,8 @@ async function queryPreviews(studio, workspace2) {
10937
11373
  if (externalGoalSession()) return withGoalDiscussion(() => cmdGoalPreviews(studio));
10938
11374
  die("--workspace is required outside a goal discussion.");
10939
11375
  }
10940
- const list = await studios2(workspace2);
10941
- const flow = list.find((w) => w.id === studio || shortStudioId(w.id) === studio);
11376
+ const list2 = await studios2(workspace2);
11377
+ const flow = list2.find((w) => w.id === studio || shortStudioId(w.id) === studio);
10942
11378
  if (!flow) die(`No studio \`${studio}\` here.`);
10943
11379
  if (!flow.previews) die("Preview agents are unavailable; update Runner and try again.");
10944
11380
  const agents = flow.previews.map((p) => ({ name: p.agent, when: p.when || null }));
@@ -15554,23 +15990,23 @@ import path49 from "node:path";
15554
15990
  function writeAudit(delivery, runs) {
15555
15991
  const known2 = new Map(readAudit(delivery.deliveryId)?.sessions.map((s) => [s.sessionId, s]) ?? []);
15556
15992
  const sessions = delivery.sessions.flatMap((id) => {
15557
- const run2 = runs.find((r) => r.sessionId === id);
15558
- if (!run2) {
15993
+ const run3 = runs.find((r) => r.sessionId === id);
15994
+ if (!run3) {
15559
15995
  const before = known2.get(id);
15560
15996
  return before ? [before] : [];
15561
15997
  }
15562
15998
  return [
15563
15999
  {
15564
- sessionId: run2.sessionId,
15565
- action: run2.action,
15566
- status: run2.status,
15567
- startedAt: run2.startedAt,
15568
- endedAt: run2.endedAt,
15569
- harness: run2.harness || void 0,
15570
- model: run2.model,
15571
- costUsd: run2.costUsd,
15572
- resumedFrom: run2.resumedFrom,
15573
- log: rel(run2.logPath)
16000
+ sessionId: run3.sessionId,
16001
+ action: run3.action,
16002
+ status: run3.status,
16003
+ startedAt: run3.startedAt,
16004
+ endedAt: run3.endedAt,
16005
+ harness: run3.harness || void 0,
16006
+ model: run3.model,
16007
+ costUsd: run3.costUsd,
16008
+ resumedFrom: run3.resumedFrom,
16009
+ log: rel(run3.logPath)
15574
16010
  }
15575
16011
  ];
15576
16012
  });
@@ -15648,7 +16084,7 @@ function settleOrphanedDeliveries() {
15648
16084
  const recovered = [];
15649
16085
  withStore((store) => {
15650
16086
  const known2 = new Set(store.deliveries.map((d) => d.deliveryId));
15651
- for (const run2 of store.runs) if (run2.deliveryId) known2.add(run2.deliveryId);
16087
+ for (const run3 of store.runs) if (run3.deliveryId) known2.add(run3.deliveryId);
15652
16088
  for (const audit of audits) {
15653
16089
  if (known2.has(audit.deliveryId) || !localAudit(audit)) continue;
15654
16090
  if (lastSessionRunning(audit)) {
@@ -15859,16 +16295,16 @@ function deliveryFor(req) {
15859
16295
  }
15860
16296
  return req.id === void 0 ? void 0 : activeDelivery(req.id);
15861
16297
  }
15862
- function joinDelivery(store, run2, title, step, start, direct) {
15863
- const cardId2 = run2.cardId;
15864
- let delivery = run2.deliveryId ? store.deliveries.find((d) => d.deliveryId === run2.deliveryId && d.status === "active") : cardId2 === null ? void 0 : activeIn(store, cardId2);
16298
+ function joinDelivery(store, run3, title, step, start, direct) {
16299
+ const cardId2 = run3.cardId;
16300
+ let delivery = run3.deliveryId ? store.deliveries.find((d) => d.deliveryId === run3.deliveryId && d.status === "active") : cardId2 === null ? void 0 : activeIn(store, cardId2);
15865
16301
  if (!delivery) {
15866
16302
  delivery = {
15867
16303
  deliveryId: start?.deliveryId ?? newDeliveryId(store.deliveries),
15868
16304
  cardId: cardId2,
15869
16305
  title,
15870
16306
  status: "active",
15871
- startedAt: run2.startedAt,
16307
+ startedAt: run3.startedAt,
15872
16308
  sessions: [],
15873
16309
  // The one read of the card this delivery will ever make for its requirements — or,
15874
16310
  // with no card, the sentence or the plan's words it was handed, which can never move
@@ -15903,21 +16339,21 @@ function joinDelivery(store, run2, title, step, start, direct) {
15903
16339
  } else if (step === "implement" && delivery.review?.stopped) {
15904
16340
  delivery.review.stopped = void 0;
15905
16341
  }
15906
- delivery.sessions.push(run2.sessionId);
15907
- delivery.steps.push({ step, at: run2.startedAt });
15908
- joinFlow(run2, delivery);
16342
+ delivery.sessions.push(run3.sessionId);
16343
+ delivery.steps.push({ step, at: run3.startedAt });
16344
+ joinFlow(run3, delivery);
15909
16345
  writeAudit(delivery, store.runs);
15910
16346
  return delivery;
15911
16347
  }
15912
16348
  function adoptDirectCard(sessionId, cardId2) {
15913
16349
  return withStore((store) => {
15914
- const run2 = store.runs.find((r) => r.sessionId === sessionId && r.status === "running");
15915
- if (!run2 || run2.action !== "implement" || run2.cardId !== null) return false;
15916
- const delivery = run2.deliveryId ? store.deliveries.find((d) => d.deliveryId === run2.deliveryId && d.status === "active") : void 0;
15917
- if (run2.deliveryId && (!delivery || delivery.cardId !== null)) return false;
16350
+ const run3 = store.runs.find((r) => r.sessionId === sessionId && r.status === "running");
16351
+ if (!run3 || run3.action !== "implement" || run3.cardId !== null) return false;
16352
+ const delivery = run3.deliveryId ? store.deliveries.find((d) => d.deliveryId === run3.deliveryId && d.status === "active") : void 0;
16353
+ if (run3.deliveryId && (!delivery || delivery.cardId !== null)) return false;
15918
16354
  const idle = "ready";
15919
- run2.cardId = cardId2;
15920
- run2.priorStatus = idle;
16355
+ run3.cardId = cardId2;
16356
+ run3.priorStatus = idle;
15921
16357
  if (!delivery) return true;
15922
16358
  delivery.cardId = cardId2;
15923
16359
  delivery.priorStatus = idle;
@@ -15925,21 +16361,21 @@ function adoptDirectCard(sessionId, cardId2) {
15925
16361
  return true;
15926
16362
  });
15927
16363
  }
15928
- function joinActive(store, run2, step, deliveryId) {
15929
- const delivery = deliveryId ? store.deliveries.find((d) => d.status === "active" && d.deliveryId === deliveryId) : run2.cardId === null ? void 0 : activeIn(store, run2.cardId);
16364
+ function joinActive(store, run3, step, deliveryId) {
16365
+ const delivery = deliveryId ? store.deliveries.find((d) => d.status === "active" && d.deliveryId === deliveryId) : run3.cardId === null ? void 0 : activeIn(store, run3.cardId);
15930
16366
  if (!delivery) return void 0;
15931
- delivery.sessions.push(run2.sessionId);
15932
- delivery.steps.push({ step, at: run2.startedAt });
16367
+ delivery.sessions.push(run3.sessionId);
16368
+ delivery.steps.push({ step, at: run3.startedAt });
15933
16369
  if (delivery.review?.stopped) delivery.review.stopped = void 0;
15934
16370
  const now = Date.now();
15935
16371
  for (const answer2 of delivery.answers ?? []) if (!answer2.actedAt) answer2.actedAt = now;
15936
- joinFlow(run2, delivery);
16372
+ joinFlow(run3, delivery);
15937
16373
  writeAudit(delivery, store.runs);
15938
16374
  return delivery;
15939
16375
  }
15940
- function joinFlow(run2, delivery) {
15941
- run2.deliveryId = delivery.deliveryId;
15942
- run2.flowId = delivery.deliveryId;
16376
+ function joinFlow(run3, delivery) {
16377
+ run3.deliveryId = delivery.deliveryId;
16378
+ run3.flowId = delivery.deliveryId;
15943
16379
  }
15944
16380
  function endDelivery(deliveryId, status) {
15945
16381
  const ended = withBoardLock(() => withStore((store) => {
@@ -15954,8 +16390,8 @@ function endDelivery(deliveryId, status) {
15954
16390
  }
15955
16391
  return ended;
15956
16392
  }
15957
- async function settleDelivery(run2) {
15958
- if (run2.deliveryId) syncAudit(run2.deliveryId, run2);
16393
+ async function settleDelivery(run3) {
16394
+ if (run3.deliveryId) syncAudit(run3.deliveryId, run3);
15959
16395
  }
15960
16396
  function deliveryAcceptsAnswers(cardId2) {
15961
16397
  return !!deliveryStateOf(cardId2)?.paused;
@@ -16840,7 +17276,7 @@ var init_prompts = __esm({
16840
17276
  `The session you were continuing is gone, and this one holds nothing of it.`,
16841
17277
  `Do the task below from the top, checking each step's precondition before you do it \u2014 work an earlier run already finished is done, so don't repeat it.`
16842
17278
  ].join(" ");
16843
- restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
17279
+ restartable = (run3) => (run3.cardId !== null || !!run3.deliveryId) && RESTARTABLE.has(run3.action);
16844
17280
  NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
16845
17281
  BOARD_FOLDER = "<board folder>";
16846
17282
  CARD_FILE = "<card file>";
@@ -16923,16 +17359,16 @@ function signal(pids, sig) {
16923
17359
  }
16924
17360
  }
16925
17361
  }
16926
- function startedUnder(list, root2, since) {
16927
- const self = list.procs.find((p) => p.pid === root2);
17362
+ function startedUnder(list2, root2, since) {
17363
+ const self = list2.procs.find((p) => p.pid === root2);
16928
17364
  const from = since ?? self?.startedAt;
16929
- if (from === void 0 || list.bootedAt > from) return [];
17365
+ if (from === void 0 || list2.bootedAt > from) return [];
16930
17366
  if (self && self.startedAt > from) return [];
16931
17367
  const found2 = self ? [root2] : [];
16932
17368
  const seen = /* @__PURE__ */ new Set([root2]);
16933
17369
  const queue = [{ pid: root2, startedAt: from }];
16934
17370
  for (const parent of queue) {
16935
- for (const p of list.procs) {
17371
+ for (const p of list2.procs) {
16936
17372
  if (p.ppid !== parent.pid || seen.has(p.pid) || p.startedAt < parent.startedAt) continue;
16937
17373
  seen.add(p.pid);
16938
17374
  found2.push(p.pid);
@@ -16963,9 +17399,9 @@ function procsOnWindows() {
16963
17399
  }
16964
17400
  function killUnderOnWindows(pid, since) {
16965
17401
  if (!WINDOWS3 || !pid) return;
16966
- const list = procsOnWindows();
16967
- if (!list) return;
16968
- const pids = startedUnder(list, pid, since).filter((p) => p !== process.pid);
17402
+ const list2 = procsOnWindows();
17403
+ if (!list2) return;
17404
+ const pids = startedUnder(list2, pid, since).filter((p) => p !== process.pid);
16969
17405
  if (!pids.length) return;
16970
17406
  spawnSync4("taskkill", ["/F", ...pids.flatMap((p) => ["/PID", String(p)])], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
16971
17407
  }
@@ -17070,9 +17506,9 @@ function reap(runs, reaped = [], restore = []) {
17070
17506
  }
17071
17507
  return changed;
17072
17508
  }
17073
- function stampDuration(run2, endedAt) {
17509
+ function stampDuration(run3, endedAt) {
17074
17510
  try {
17075
- fs53.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
17511
+ fs53.appendFileSync(run3.logPath, durationLine(endedAt - run3.startedAt));
17076
17512
  } catch {
17077
17513
  }
17078
17514
  }
@@ -17093,19 +17529,19 @@ function cardNow(cardId2) {
17093
17529
  return null;
17094
17530
  }
17095
17531
  }
17096
- function claimCard(run2) {
17097
- const wanted = run2.cardId !== null ? RUN_STATUS[run2.action] : void 0;
17098
- if (run2.cardId === null || !wanted) return void 0;
17099
- const delivery = run2.deliveryId ? activeDelivery(run2.cardId) : void 0;
17100
- run2.priorStatus = (delivery && delivery.deliveryId === run2.deliveryId ? delivery.priorStatus : void 0) ?? cardNow(run2.cardId)?.status ?? "todo";
17101
- return { cardId: run2.cardId, status: wanted };
17532
+ function claimCard(run3) {
17533
+ const wanted = run3.cardId !== null ? RUN_STATUS[run3.action] : void 0;
17534
+ if (run3.cardId === null || !wanted) return void 0;
17535
+ const delivery = run3.deliveryId ? activeDelivery(run3.cardId) : void 0;
17536
+ run3.priorStatus = (delivery && delivery.deliveryId === run3.deliveryId ? delivery.priorStatus : void 0) ?? cardNow(run3.cardId)?.status ?? "todo";
17537
+ return { cardId: run3.cardId, status: wanted };
17102
17538
  }
17103
- async function restoreCardStatus(run2) {
17104
- if (run2.cardId === null || !RUN_STATUS[run2.action]) return;
17105
- if (run2.deliveryId && activeDelivery(run2.cardId)?.deliveryId === run2.deliveryId) return;
17106
- const card = cardNow(run2.cardId);
17539
+ async function restoreCardStatus(run3) {
17540
+ if (run3.cardId === null || !RUN_STATUS[run3.action]) return;
17541
+ if (run3.deliveryId && activeDelivery(run3.cardId)?.deliveryId === run3.deliveryId) return;
17542
+ const card = cardNow(run3.cardId);
17107
17543
  if (!card) return;
17108
- await setCardStatus(run2.cardId, card.questions > 0 ? "todo" : run2.priorStatus ?? "todo");
17544
+ await setCardStatus(run3.cardId, card.questions > 0 ? "todo" : run3.priorStatus ?? "todo");
17109
17545
  }
17110
17546
  async function releaseCard(delivery) {
17111
17547
  if (delivery.cardId === null) return;
@@ -17113,39 +17549,39 @@ async function releaseCard(delivery) {
17113
17549
  if (card?.status !== "implementing") return;
17114
17550
  await setCardStatus(delivery.cardId, card.questions > 0 ? "todo" : delivery.priorStatus ?? "ready");
17115
17551
  }
17116
- function recordPrune(run2) {
17117
- if (run2.action !== "prune-memory" || run2.status !== "done") return;
17552
+ function recordPrune(run3) {
17553
+ if (run3.action !== "prune-memory" || run3.status !== "done") return;
17118
17554
  try {
17119
17555
  stampMemoryPrune();
17120
17556
  } catch {
17121
17557
  }
17122
17558
  }
17123
- function recordMemoryReview(run2) {
17124
- if (run2.action !== "review-memory" || run2.status !== "done") return;
17559
+ function recordMemoryReview(run3) {
17560
+ if (run3.action !== "review-memory" || run3.status !== "done") return;
17125
17561
  try {
17126
- stampMemoryReview(new Date(run2.startedAt));
17562
+ stampMemoryReview(new Date(run3.startedAt));
17127
17563
  } catch {
17128
17564
  }
17129
17565
  }
17130
- function recordReflection(run2) {
17131
- if (run2.action !== "reflect" || run2.status !== "done" || !run2.cards?.length) return;
17566
+ function recordReflection(run3) {
17567
+ if (run3.action !== "reflect" || run3.status !== "done" || !run3.cards?.length) return;
17132
17568
  try {
17133
- dropReflected(run2.cards);
17569
+ dropReflected(run3.cards);
17134
17570
  } catch {
17135
17571
  }
17136
17572
  }
17137
- function recordScheduledRun(run2) {
17138
- if (run2.action !== "scheduled" || run2.status !== "done" || !run2.studio || !run2.specAgent) return;
17573
+ function recordScheduledRun(run3) {
17574
+ if (run3.action !== "scheduled" || run3.status !== "done" || !run3.studio || !run3.specAgent) return;
17139
17575
  try {
17140
- const began = (run2.deliveryId ? findDelivery(run2.deliveryId)?.startedAt : void 0) ?? run2.startedAt;
17141
- stampScheduledRun(run2.studio, run2.specAgent, new Date(began));
17576
+ const began = (run3.deliveryId ? findDelivery(run3.deliveryId)?.startedAt : void 0) ?? run3.startedAt;
17577
+ stampScheduledRun(run3.studio, run3.specAgent, new Date(began));
17142
17578
  } catch {
17143
17579
  }
17144
17580
  }
17145
- function recordProjectDescription(run2) {
17146
- if (run2.action !== "describe-project" || run2.status !== "done") return;
17581
+ function recordProjectDescription(run3) {
17582
+ if (run3.action !== "describe-project" || run3.status !== "done") return;
17147
17583
  try {
17148
- stampProjectDescription(new Date(run2.startedAt));
17584
+ stampProjectDescription(new Date(run3.startedAt));
17149
17585
  } catch {
17150
17586
  }
17151
17587
  }
@@ -17153,8 +17589,8 @@ function resumeIdOf(r) {
17153
17589
  if (adoptsSessionId(r.harness) && !carriesSession(r)) return r.sessionId;
17154
17590
  return r.resumeId;
17155
17591
  }
17156
- function resumeSessionId(run2) {
17157
- return resumesUnder(run2.harness) && !neverStarted(run2) ? resumeIdOf(run2) : void 0;
17592
+ function resumeSessionId(run3) {
17593
+ return resumesUnder(run3.harness) && !neverStarted(run3) ? resumeIdOf(run3) : void 0;
17158
17594
  }
17159
17595
  function endedDeliveryRefusal(r, refusals) {
17160
17596
  if (!r.deliveryId || !canPickUp(r)) return void 0;
@@ -17228,7 +17664,7 @@ function archivedRejected(id) {
17228
17664
  }
17229
17665
  function goneCards(runs) {
17230
17666
  const asking = /* @__PURE__ */ new Set();
17231
- for (const run2 of runs) if (run2.cardId !== null && canPickUp(run2)) asking.add(run2.cardId);
17667
+ for (const run3 of runs) if (run3.cardId !== null && canPickUp(run3)) asking.add(run3.cardId);
17232
17668
  if (asking.size === 0) return asking;
17233
17669
  const onBoard3 = boardCardIds();
17234
17670
  const gone = /* @__PURE__ */ new Set();
@@ -17242,8 +17678,8 @@ async function listRuns() {
17242
17678
  reap(all2, reaped, restore);
17243
17679
  return all2.map((r) => ({ ...r }));
17244
17680
  });
17245
- for (const run2 of restore) await restoreCardStatus(run2);
17246
- for (const run2 of reaped) await settleDelivery(run2);
17681
+ for (const run3 of restore) await restoreCardStatus(run3);
17682
+ for (const run3 of reaped) await settleDelivery(run3);
17247
17683
  for (const sub of runs) {
17248
17684
  if (sub.action !== "sub" || sub.status !== "running" || !sub.parentId) continue;
17249
17685
  if (!runs.some((r) => r.sessionId === sub.parentId && r.status === "running")) await stopRun(sub.sessionId);
@@ -17284,7 +17720,7 @@ async function getRun(id, bytes2) {
17284
17720
  reap(all2, [], restore);
17285
17721
  return all2.map((r) => ({ ...r }));
17286
17722
  });
17287
- for (const run2 of restore) await restoreCardStatus(run2);
17723
+ for (const run3 of restore) await restoreCardStatus(run3);
17288
17724
  const found2 = findRun(runs, id);
17289
17725
  if (!found2) return null;
17290
17726
  const view = toView(found2, goneCards([found2]));
@@ -17507,8 +17943,8 @@ function carriedSession(req) {
17507
17943
  };
17508
17944
  }
17509
17945
  function planningRun(sessionId) {
17510
- const run2 = peekRun(sessionId);
17511
- return run2?.status === "running" && PLANNING.has(run2.action) ? run2 : void 0;
17946
+ const run3 = peekRun(sessionId);
17947
+ return run3?.status === "running" && PLANNING.has(run3.action) ? run3 : void 0;
17512
17948
  }
17513
17949
  function requestOf(record) {
17514
17950
  const id = record.cardId ?? void 0;
@@ -17540,7 +17976,7 @@ async function openResume(id, options) {
17540
17976
  reap(all2, [], restore);
17541
17977
  return all2.map((r) => ({ ...r }));
17542
17978
  });
17543
- for (const run2 of restore) await restoreCardStatus(run2);
17979
+ for (const run3 of restore) await restoreCardStatus(run3);
17544
17980
  const prev = findRun(runs, id);
17545
17981
  if (prev === null) return ambiguousRun(id);
17546
17982
  if (!prev) return unknownRun(id);
@@ -17721,8 +18157,8 @@ function forgetRun(sessionId) {
17721
18157
  }
17722
18158
  }
17723
18159
  function askForSpec(sessionId, ask2) {
17724
- const run2 = peekRun(sessionId);
17725
- if (!run2) return "no-run";
18160
+ const run3 = peekRun(sessionId);
18161
+ if (!run3) return "no-run";
17726
18162
  const file = readAsks(sessionId);
17727
18163
  if (file.asks.some((a) => a.specAgent === ask2.specAgent && a.cardId === ask2.cardId)) return "already";
17728
18164
  file.asks.push(ask2);
@@ -17791,9 +18227,9 @@ function markSpawned(sessionId, pid) {
17791
18227
  }
17792
18228
  function patch(sessionId, change2) {
17793
18229
  return withRuns((runs) => {
17794
- const run2 = runs.find((r) => r.sessionId === sessionId);
17795
- if (run2) change2(run2);
17796
- return run2 ? { ...run2 } : void 0;
18230
+ const run3 = runs.find((r) => r.sessionId === sessionId);
18231
+ if (run3) change2(run3);
18232
+ return run3 ? { ...run3 } : void 0;
17797
18233
  });
17798
18234
  }
17799
18235
  function peekRun(sessionId) {
@@ -17801,18 +18237,18 @@ function peekRun(sessionId) {
17801
18237
  }
17802
18238
  async function closeRun(sessionId, res) {
17803
18239
  const closed2 = withRuns((runs) => {
17804
- const run2 = runs.find((r) => r.sessionId === sessionId);
17805
- if (!run2 || run2.status !== "running") return void 0;
17806
- run2.status = res.status;
17807
- if (res.ok !== void 0) run2.ok = res.ok;
17808
- run2.code = res.code ?? null;
17809
- if (res.error) run2.error = res.error;
17810
- if (res.note) run2.note = res.note;
17811
- if (res.errorWhy?.length) run2.errorWhy = res.errorWhy;
17812
- if (res.noteWhy?.length) run2.noteWhy = res.noteWhy;
17813
- run2.endedAt = res.endedAt ?? Date.now();
17814
- run2.pid = void 0;
17815
- return { ...run2 };
18240
+ const run3 = runs.find((r) => r.sessionId === sessionId);
18241
+ if (!run3 || run3.status !== "running") return void 0;
18242
+ run3.status = res.status;
18243
+ if (res.ok !== void 0) run3.ok = res.ok;
18244
+ run3.code = res.code ?? null;
18245
+ if (res.error) run3.error = res.error;
18246
+ if (res.note) run3.note = res.note;
18247
+ if (res.errorWhy?.length) run3.errorWhy = res.errorWhy;
18248
+ if (res.noteWhy?.length) run3.noteWhy = res.noteWhy;
18249
+ run3.endedAt = res.endedAt ?? Date.now();
18250
+ run3.pid = void 0;
18251
+ return { ...run3 };
17816
18252
  });
17817
18253
  if (!closed2) return;
17818
18254
  if (closed2.status === "done" || closed2.status === "error") {
@@ -17837,14 +18273,14 @@ async function stopRun(id) {
17837
18273
  const restore = [];
17838
18274
  const out = withRuns((runs) => {
17839
18275
  reap(runs, [], restore);
17840
- const run2 = findRun(runs, id);
17841
- if (run2 === null) return { ok: false, ...ambiguousRun(id) };
17842
- if (!run2) return { ok: false, ...unknownRun(id) };
17843
- if (run2.status !== "running") return { ok: true, sessionId: run2.sessionId };
17844
- run2.stopping = true;
17845
- return { ok: true, sessionId: run2.sessionId, pid: run2.pid, live: true };
18276
+ const run3 = findRun(runs, id);
18277
+ if (run3 === null) return { ok: false, ...ambiguousRun(id) };
18278
+ if (!run3) return { ok: false, ...unknownRun(id) };
18279
+ if (run3.status !== "running") return { ok: true, sessionId: run3.sessionId };
18280
+ run3.stopping = true;
18281
+ return { ok: true, sessionId: run3.sessionId, pid: run3.pid, live: true };
17846
18282
  });
17847
- for (const run2 of restore) await restoreCardStatus(run2);
18283
+ for (const run3 of restore) await restoreCardStatus(run3);
17848
18284
  const live = out;
17849
18285
  if (!live.ok || !live.live) {
17850
18286
  return { ok: live.ok, sessionId: live.sessionId, error: live.error, reason: live.reason, args: live.args };
@@ -17890,13 +18326,13 @@ async function cancelDelivery(id) {
17890
18326
  }
17891
18327
  async function stopSubRuns(parentId) {
17892
18328
  const live = liveSubRuns(parentId);
17893
- for (const run2 of live) await stopRun(run2.sessionId);
17894
- await Promise.all(live.map((run2) => runIsDown(run2.sessionId)));
18329
+ for (const run3 of live) await stopRun(run3.sessionId);
18330
+ await Promise.all(live.map((run3) => runIsDown(run3.sessionId)));
17895
18331
  }
17896
18332
  async function runIsDown(sessionId) {
17897
18333
  for (const until = Date.now() + STOP_WAIT_MS; Date.now() < until; ) {
17898
- const run2 = readRuns().find((r) => r.sessionId === sessionId);
17899
- if (!run2 || !runIsLive(run2)) return;
18334
+ const run3 = readRuns().find((r) => r.sessionId === sessionId);
18335
+ if (!run3 || !runIsLive(run3)) return;
17900
18336
  await sleep3(STOP_POLL_MS);
17901
18337
  }
17902
18338
  }
@@ -19388,14 +19824,14 @@ function compareProblem(attrs, id) {
19388
19824
  return { message: `${at} is not valid JSON.` };
19389
19825
  }
19390
19826
  };
19391
- const list = read3(attrs.shots);
19392
- if ("message" in list) return shots(list.message);
19393
- const why2 = Array.isArray(list.data) ? shotsProblem(list.data) : storyboardProblem(list.data);
19827
+ const list2 = read3(attrs.shots);
19828
+ if ("message" in list2) return shots(list2.message);
19829
+ const why2 = Array.isArray(list2.data) ? shotsProblem(list2.data) : storyboardProblem(list2.data);
19394
19830
  if (why2) return shots(`${attrs.shots}: ${why2}`);
19395
19831
  if (!script) return null;
19396
19832
  const bad = storyboardProblem(board2);
19397
19833
  if (bad) return src(`${attrs.b}: ${bad}`);
19398
- const known2 = new Set((Array.isArray(list.data) ? list.data : list.data.shots).map((s) => s.id));
19834
+ const known2 = new Set((Array.isArray(list2.data) ? list2.data : list2.data.shots).map((s) => s.id));
19399
19835
  const extra = board2.shots.find((s) => !known2.has(s.id));
19400
19836
  return extra ? shots(`${attrs.b} has shot ${extra.id}, which ${attrs.shots} lacks. Add ${extra.id} to ${attrs.shots}, or drop it from ${attrs.b}.`) : null;
19401
19837
  }
@@ -19843,8 +20279,8 @@ function cmdUpdateQuestions(id, input) {
19843
20279
  function specRunAgent() {
19844
20280
  const id = insideRun();
19845
20281
  if (!id) return void 0;
19846
- const run2 = readStore().runs.find((r) => r.sessionId === id);
19847
- return run2?.action === "spec" ? run2.specAgent : void 0;
20282
+ const run3 = readStore().runs.find((r) => r.sessionId === id);
20283
+ return run3?.action === "spec" ? run3.specAgent : void 0;
19848
20284
  }
19849
20285
  var TODO_ITEM;
19850
20286
  var init_card = __esm({
@@ -20610,21 +21046,21 @@ function scheduledBusy(pass, store = readStore()) {
20610
21046
  }
20611
21047
  function insideScheduledPass() {
20612
21048
  const sessionId = insideRun();
20613
- const run2 = sessionId ? readStore().runs.find((r) => r.sessionId === sessionId) : void 0;
20614
- return run2?.action === "scheduled" && run2.studio && run2.specAgent ? { studio: run2.studio, agent: run2.specAgent } : null;
21049
+ const run3 = sessionId ? readStore().runs.find((r) => r.sessionId === sessionId) : void 0;
21050
+ return run3?.action === "scheduled" && run3.studio && run3.specAgent ? { studio: run3.studio, agent: run3.specAgent } : null;
20615
21051
  }
20616
21052
  function runAgent() {
20617
21053
  const sessionId = insideRun();
20618
21054
  const runs = sessionId ? readStore().runs : [];
20619
- const run2 = runs.find((r) => r.sessionId === sessionId);
20620
- if (!run2) return null;
20621
- if (run2.action !== "sub") return agentOf(run2);
20622
- const parent = runs.find((r) => r.sessionId === run2.parentId);
20623
- return parent ? agentOf(parent) : run2.specAgent ?? null;
21055
+ const run3 = runs.find((r) => r.sessionId === sessionId);
21056
+ if (!run3) return null;
21057
+ if (run3.action !== "sub") return agentOf(run3);
21058
+ const parent = runs.find((r) => r.sessionId === run3.parentId);
21059
+ return parent ? agentOf(parent) : run3.specAgent ?? null;
20624
21060
  }
20625
- function agentOf(run2) {
20626
- if (run2.action === "scheduled") return run2.specAgent ?? null;
20627
- return flowNodes().find((n) => n.flow === run2.action)?.agent ?? null;
21061
+ function agentOf(run3) {
21062
+ if (run3.action === "scheduled") return run3.specAgent ?? null;
21063
+ return flowNodes().find((n) => n.flow === run3.action)?.agent ?? null;
20628
21064
  }
20629
21065
  var scheduledRequest, isPass, openPasses, stalePasses;
20630
21066
  var init_scheduled = __esm({
@@ -20639,7 +21075,7 @@ var init_scheduled = __esm({
20639
21075
  studio: pass.studio,
20640
21076
  specAgent: pass.agent
20641
21077
  });
20642
- isPass = (run2, pass) => run2.action === "scheduled" && run2.studio === pass.studio && run2.specAgent === pass.agent;
21078
+ isPass = (run3, pass) => run3.action === "scheduled" && run3.studio === pass.studio && run3.specAgent === pass.agent;
20643
21079
  openPasses = (deliveries, pass) => deliveries.filter(
20644
21080
  (d) => d.status === "active" && d.scheduled?.studio === pass.studio && d.scheduled.agent === pass.agent
20645
21081
  );
@@ -21377,16 +21813,16 @@ function removeCard2(id, metric, options) {
21377
21813
  }
21378
21814
  }
21379
21815
  withStore((store) => {
21380
- for (const run2 of store.runs) {
21381
- if (!leaving.some((c) => run2.createdCardIds?.includes(c.id))) continue;
21382
- const marks = new Map((run2.discardedCards ?? []).map((c) => [c.id, c]));
21816
+ for (const run3 of store.runs) {
21817
+ if (!leaving.some((c) => run3.createdCardIds?.includes(c.id))) continue;
21818
+ const marks = new Map((run3.discardedCards ?? []).map((c) => [c.id, c]));
21383
21819
  for (const c of leaving) marks.set(c.id, { id: c.id, path: rel(c.file), pending: true });
21384
- run2.discardedCards = [...marks.values()];
21820
+ run3.discardedCards = [...marks.values()];
21385
21821
  }
21386
21822
  });
21387
21823
  }
21388
21824
  if (options.discard) withStore((store) => {
21389
- for (const run2 of store.runs) for (const card of run2.discardedCards ?? []) {
21825
+ for (const run3 of store.runs) for (const card of run3.discardedCards ?? []) {
21390
21826
  if (leftIds.includes(card.id)) delete card.pending;
21391
21827
  }
21392
21828
  });
@@ -21662,11 +22098,11 @@ function newOpId() {
21662
22098
  opCounter += 1;
21663
22099
  return `${process.pid.toString(36)}-${Date.now().toString(36)}-${opCounter.toString(36)}`;
21664
22100
  }
21665
- async function leaseAnd(provider, target, run2) {
22101
+ async function leaseAnd(provider, target, run3) {
21666
22102
  const got = await provider.lease(target);
21667
22103
  if (!got.ok) return { ok: false, kind: "refused", error: got.error };
21668
22104
  try {
21669
- return await run2(envelope(got.lease.revision, got.lease.id));
22105
+ return await run3(envelope(got.lease.revision, got.lease.id));
21670
22106
  } finally {
21671
22107
  await provider.releaseLease(got.lease.id);
21672
22108
  }
@@ -21794,14 +22230,14 @@ function localBoard() {
21794
22230
  },
21795
22231
  // ---- the named `akb raw` moves ----------------------------------------
21796
22232
  async runMove(move, input, env2) {
21797
- const run2 = MOVES[move];
21798
- if (!run2) return Promise.resolve(opRefused(new Error(`unknown command "${move}".`)));
22233
+ const run3 = MOVES[move];
22234
+ if (!run3) return Promise.resolve(opRefused(new Error(`unknown command "${move}".`)));
21799
22235
  const target = moveTarget(move, input.args);
21800
22236
  try {
21801
22237
  return await withBoardLock(() => {
21802
22238
  const no = checkWrite(target, env2, revisionAt(target));
21803
22239
  if (no) return no;
21804
- const data = run2(input);
22240
+ const data = run3(input);
21805
22241
  if (data instanceof Promise) return data.then((data2) => opOk(revisionAt(target), { data: data2 }));
21806
22242
  return opOk(revisionAt(target), { data: data || {} });
21807
22243
  });
@@ -21810,10 +22246,10 @@ function localBoard() {
21810
22246
  }
21811
22247
  },
21812
22248
  readMove(move, input) {
21813
- const run2 = MOVES[move];
21814
- if (!run2) return Promise.reject(new Error(`unknown command "${move}".`));
22249
+ const run3 = MOVES[move];
22250
+ if (!run3) return Promise.reject(new Error(`unknown command "${move}".`));
21815
22251
  try {
21816
- return Promise.resolve(run2(input) || {});
22252
+ return Promise.resolve(run3(input) || {});
21817
22253
  } catch (e) {
21818
22254
  return Promise.reject(e);
21819
22255
  }
@@ -21865,8 +22301,8 @@ function board() {
21865
22301
  if (!active) active = localBoard();
21866
22302
  return active;
21867
22303
  }
21868
- function withLease(target, run2) {
21869
- return leaseAnd(board(), target, run2);
22304
+ function withLease(target, run3) {
22305
+ return leaseAnd(board(), target, run3);
21870
22306
  }
21871
22307
  var active, setCardStatusOn, cancelBoardDelivery, resumeBoardDelivery;
21872
22308
  var init_board = __esm({
@@ -22168,8 +22604,8 @@ async function dispatch(move, cmd, args, opts, cli) {
22168
22604
  cli.onAnswer?.(data);
22169
22605
  }
22170
22606
  async function cloudCard(task, opts) {
22171
- const run2 = insideRun() ? peekRun(insideRun()) : void 0;
22172
- const triage = typeof opts.triage === "string" ? opts.triage : run2?.triage;
22607
+ const run3 = insideRun() ? peekRun(insideRun()) : void 0;
22608
+ const triage = typeof opts.triage === "string" ? opts.triage : run3?.triage;
22173
22609
  opts = { ...opts, ...triage ? { triage } : {} };
22174
22610
  const sourceFile = triage ? triageFile(triage) : void 0;
22175
22611
  let request2;
@@ -22200,7 +22636,7 @@ async function cloudCard(task, opts) {
22200
22636
  }
22201
22637
  const checked = await creationProject(KANBAN, REPO_ROOT);
22202
22638
  if (!checked.ok) throw new BoardError(creationError(checked.error, triage), { kind: "refused" });
22203
- const requestId = triage ? `triage:${triage}` : run2?.sessionId ?? crypto5.randomUUID();
22639
+ const requestId = triage ? `triage:${triage}` : run3?.sessionId ?? crypto5.randomUUID();
22204
22640
  const slot = triage ? triage : String(opts.slug ?? opts.title);
22205
22641
  const file = creationReceipt(`${checked.value}:${requestId}`, slot);
22206
22642
  const journal = readCreation(file, said2);
@@ -22718,8 +23154,8 @@ function checkSetting(setting, value, ask2) {
22718
23154
  return `"${value}" isn't one of the ${setting.label} choices: ${choices}`;
22719
23155
  }
22720
23156
  if (setting.kind === "provider" && !value) {
22721
- const list = providerSetting(activeSettings(ask2));
22722
- return `a run always goes through a provider, so this one can't be cleared. Pick one: ${list?.providers?.map((p) => p.id).join(", ") ?? ""}`;
23157
+ const list2 = providerSetting(activeSettings(ask2));
23158
+ return `a run always goes through a provider, so this one can't be cleared. Pick one: ${list2?.providers?.map((p) => p.id).join(", ") ?? ""}`;
22723
23159
  }
22724
23160
  return settingSaveError(setting.key, value, ask2);
22725
23161
  }
@@ -23138,7 +23574,7 @@ var init_board3 = __esm({
23138
23574
  var card_chat_default;
23139
23575
  var init_card_chat = __esm({
23140
23576
  "src/guide/card-chat.md"() {
23141
- card_chat_default = '# Answer a card\'s conversation\n\nWork on the current card and its assets by default. Project implementation requires approval on the review page.\n\n- **Where the task stands**: read it with `akb task show <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Choose a preview agent**: when a preview is needed and the agent is unclear, use `akb raw previews --triggers` to match the work to an agent.\n- **Create or revise a preview**: when the user asks to see or change a preview for the current card, use `akb raw previews <agent> <id> --print`; never write embed tags by hand.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a studio**: when the user asks to change a studio or one of its agents, follow `akb guide update-studio`.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n';
23577
+ card_chat_default = '# Answer a card\'s conversation\n\nWork on the current card and its assets by default. Project implementation requires approval on the review page.\n\n- **Where the task stands**: read it with `akb task show <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Choose a preview agent**: when a preview is needed and the agent is unclear, use `akb raw previews --triggers` to match the work to an agent.\n- **Create or revise a preview**: when the user asks to see or change a preview for the current card, use `akb raw previews <agent> <id> --print`; never write embed tags by hand.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a studio**: when the user asks to change a studio or one of its agents, follow `akb guide update-studio`.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n\n- **Start this task**: when the user explicitly asks to start, implement or approve it, use `akb task approve` or `akb raw card approve/implement`. In a task reply these register one approval for after the reply finishes and syncs. Pending means accepted, not started; finish the reply and do not wait or edit the card again. Preview approvals still apply.\n';
23142
23578
  }
23143
23579
  });
23144
23580
 
@@ -23664,24 +24100,24 @@ function completeDelivery(named2, result = {}) {
23664
24100
  delivery2.completions = durable.completions;
23665
24101
  }
23666
24102
  const receipts = delivery2.completions ??= [];
23667
- const run2 = store.runs.find((r) => r.sessionId === sessionId);
24103
+ const run3 = store.runs.find((r) => r.sessionId === sessionId);
23668
24104
  const current = store.runs.filter((r) => r.deliveryId === delivery2.deliveryId && ["implement", "scheduled"].includes(r.action)).pop();
23669
- if (!run2 || run2.deliveryId !== delivery2.deliveryId) throw new Error("This run does not own the delivery.");
24105
+ if (!run3 || run3.deliveryId !== delivery2.deliveryId) throw new Error("This run does not own the delivery.");
23670
24106
  const pending = receipts[deliveryStep(delivery2)];
23671
24107
  const previous = receipts.find((c) => c.sessionId === sessionId || c.resumedSessions?.includes(sessionId));
23672
24108
  if (previous) {
23673
24109
  if (previous.commit !== commit || previous.branch !== branch) throw new Error("This step already recorded a different result.");
23674
- if (!previous.finished && previous.step === deliveryStep(delivery2) && (delivery2.status !== "active" || run2 !== current || run2.status !== "running")) {
24110
+ if (!previous.finished && previous.step === deliveryStep(delivery2) && (delivery2.status !== "active" || run3 !== current || run3.status !== "running")) {
23675
24111
  throw new Error("Only the current owning run can finish pending completion.");
23676
24112
  }
23677
24113
  return { delivery: delivery2, receipt: previous };
23678
24114
  }
23679
- if (delivery2.status !== "active" || !run2 || run2.status !== "running" || run2 !== current || run2.deliveryId !== delivery2.deliveryId) {
24115
+ if (delivery2.status !== "active" || !run3 || run3.status !== "running" || run3 !== current || run3.deliveryId !== delivery2.deliveryId) {
23680
24116
  throw new Error("Only the current owning run can complete this delivery.");
23681
24117
  }
23682
24118
  if (answerOutcome(delivery2) === "changed") throw new Error("The approved requirements were superseded. Continue with the updated delivery.");
23683
24119
  if (delivery2.cardId !== null && openQuestions(delivery2.cardId)) throw new Error("Answer the open questions before completing.");
23684
- if (pending && run2 === current) {
24120
+ if (pending && run3 === current) {
23685
24121
  if (pending.commit !== commit || pending.branch !== branch) throw new Error("This step already recorded a different result.");
23686
24122
  pending.resumedSessions = [...pending.resumedSessions ?? [], sessionId];
23687
24123
  return { delivery: delivery2, receipt: pending };
@@ -23877,10 +24313,10 @@ function open2(req, sessionId) {
23877
24313
  returnRunPictures(sessionId, req.box);
23878
24314
  return opened;
23879
24315
  }
23880
- const { run: run2 } = opened;
23881
- const pid = spawnWatcher(run2.sessionId);
23882
- markSpawned(run2.sessionId, pid);
23883
- return { run: run2, spawned: pid !== void 0 };
24316
+ const { run: run3 } = opened;
24317
+ const pid = spawnWatcher(run3.sessionId);
24318
+ markSpawned(run3.sessionId, pid);
24319
+ return { run: run3, spawned: pid !== void 0 };
23884
24320
  }
23885
24321
  async function startResume(id, options) {
23886
24322
  const opened = await openResume(id, options);
@@ -24617,7 +25053,7 @@ var init_stage_end = __esm({
24617
25053
  const flow = flowByAction(action);
24618
25054
  return flow ? stageOfFlow(flow.command) : void 0;
24619
25055
  };
24620
- askedFor = (cardId2, agent) => readStore().runs.some((run2) => run2.action === "spec" && run2.cardId === cardId2 && run2.specAgent === agent);
25056
+ askedFor = (cardId2, agent) => readStore().runs.some((run3) => run3.action === "spec" && run3.cardId === cardId2 && run3.specAgent === agent);
24621
25057
  }
24622
25058
  });
24623
25059
 
@@ -24702,26 +25138,26 @@ function stalledLine(cardId2, next) {
24702
25138
  if (!card || refinementStep(card) === "done") return null;
24703
25139
  return `#${card.id} is still in To do after planning, and the board won't plan it again on its own \u2014 refine it again, or mark it ready yourself.`;
24704
25140
  }
24705
- function planStageEnd(run2) {
24706
- if (run2.cardId === null || stageOfAction(run2.action) !== "plan") return null;
24707
- const card = currentCard(run2.cardId);
25141
+ function planStageEnd(run3) {
25142
+ if (run3.cardId === null || stageOfAction(run3.action) !== "plan") return null;
25143
+ const card = currentCard(run3.cardId);
24708
25144
  if (!card || card.openBlockers.length > 0 || card.questions.length > 0) return null;
24709
25145
  if (refinementStep(card) !== "done") return null;
24710
25146
  return endOfStage(stageContract("plan"), card);
24711
25147
  }
24712
- function refinementRunsAfter(run2, changed, before, waitingForSpec = false, refused = []) {
24713
- const next = waitingForSpec || run2.cardId === null || !["clarify", "resolve", "edit", "approve"].includes(run2.action) ? null : refinementAfter(run2.action, run2.cardId, run2.flowId);
24714
- const starts = refinesAfter(run2.action, changed, before).filter(
24715
- (req) => req.id !== run2.cardId || run2.refineRound === void 0 && run2.action !== "spec"
25148
+ function refinementRunsAfter(run3, changed, before, waitingForSpec = false, refused = []) {
25149
+ const next = waitingForSpec || run3.cardId === null || !["clarify", "resolve", "edit", "approve"].includes(run3.action) ? null : refinementAfter(run3.action, run3.cardId, run3.flowId);
25150
+ const starts = refinesAfter(run3.action, changed, before).filter(
25151
+ (req) => req.id !== run3.cardId || run3.refineRound === void 0 && run3.action !== "spec"
24716
25152
  );
24717
25153
  const refusedNote = waitingForSpec || !refused.length ? "" : `Preview agents not started: ${refused.map((r) => r.error).join(" ")}`;
24718
25154
  const carryOn = next && refusedNote ? { ...next, notes: [next.notes, refusedNote].filter(Boolean).join("\n\n") } : next;
24719
- const end2 = waitingForSpec || carryOn || starts.length ? null : planStageEnd(run2);
25155
+ const end2 = waitingForSpec || carryOn || starts.length ? null : planStageEnd(run3);
24720
25156
  const short2 = end2 && "missing" in end2 ? end2 : null;
24721
- const stalled = (short2 ? shortLine(short2, run2.cardId) : void 0) ?? (waitingForSpec ? void 0 : run2.refineRound !== void 0 && stalledLine(run2.cardId, next) || void 0);
25157
+ const stalled = (short2 ? shortLine(short2, run3.cardId) : void 0) ?? (waitingForSpec ? void 0 : run3.refineRound !== void 0 && stalledLine(run3.cardId, next) || void 0);
24722
25158
  const stalledWhy = [
24723
25159
  ...refusedNote ? [{ kind: "specRefused", refusals: refused }] : [],
24724
- ...!stalled ? [] : short2 ? [{ kind: "stageShort", args: { stage: short2.stage, card: String(run2.cardId), agents: short2.missing.join(", ") } }] : [{ kind: "refineStalled", args: { card: String(run2.cardId) } }]
25160
+ ...!stalled ? [] : short2 ? [{ kind: "stageShort", args: { stage: short2.stage, card: String(run3.cardId), agents: short2.missing.join(", ") } }] : [{ kind: "refineStalled", args: { card: String(run3.cardId) } }]
24725
25161
  ];
24726
25162
  return {
24727
25163
  runs: [...starts, ...carryOn ? [carryOn] : [], ...end2 && "ask" in end2 ? [end2.ask] : []],
@@ -24935,18 +25371,18 @@ import { spawn as spawn3 } from "node:child_process";
24935
25371
  import fs82 from "node:fs";
24936
25372
  async function watchRun(sessionId, resume = startResume) {
24937
25373
  const spec = readSpec(sessionId);
24938
- const run2 = peekRun(sessionId);
24939
- if (!run2 || !spec) {
24940
- if (run2?.status === "running") await closeRun(sessionId, { status: "interrupted", code: null });
25374
+ const run3 = peekRun(sessionId);
25375
+ if (!run3 || !spec) {
25376
+ if (run3?.status === "running") await closeRun(sessionId, { status: "interrupted", code: null });
24941
25377
  return 1;
24942
25378
  }
24943
- if (run2.stopping) {
25379
+ if (run3.stopping) {
24944
25380
  await closeRun(sessionId, { status: "stopped", code: null });
24945
25381
  return 1;
24946
25382
  }
24947
25383
  const stopping = () => peekRun(sessionId)?.status !== "running";
24948
25384
  let releaseIndex = null;
24949
- if (needsIndexLock(run2.action)) {
25385
+ if (needsIndexLock(run3.action)) {
24950
25386
  releaseIndex = await acquireIndexLock(stopping);
24951
25387
  if (!releaseIndex) {
24952
25388
  if (!stopping()) await closeRun(sessionId, { status: "interrupted", code: null });
@@ -24965,7 +25401,7 @@ async function watchRun(sessionId, resume = startResume) {
24965
25401
  const claimed = patch(sessionId, (r) => {
24966
25402
  claim = claimCard(r);
24967
25403
  });
24968
- const record = claimed ?? run2;
25404
+ const record = claimed ?? run3;
24969
25405
  const sub = record.action === "sub";
24970
25406
  if (claim) await setCardStatus(claim.cardId, claim.status);
24971
25407
  fs82.mkdirSync(SESSIONS_DIR, { recursive: true });
@@ -25070,7 +25506,7 @@ async function watchRun(sessionId, resume = startResume) {
25070
25506
  const turns = renderer?.turns?.() ?? [];
25071
25507
  if (turns.length === turnsSeen) return;
25072
25508
  turnsSeen = turns.length;
25073
- if (!turns.at(-1).background) endInput();
25509
+ if (renderer && streamFinished(renderer)) endInput();
25074
25510
  };
25075
25511
  let sawResumeId = !!record.resumeId;
25076
25512
  let sawModel = false;
@@ -25161,7 +25597,7 @@ async function watchRun(sessionId, resume = startResume) {
25161
25597
  if (errRest) log.write(errRest);
25162
25598
  const endedAt = Date.now();
25163
25599
  const blocker = peekRun(sessionId)?.blocker;
25164
- const failure = renderer?.failure?.();
25600
+ const failure = renderer?.failure?.() ?? (renderer?.background?.() ? "The agent exited with unfinished background tasks." : void 0);
25165
25601
  const unfinished = blocker || failure;
25166
25602
  const result = spoken ? spoken.result : renderer?.result();
25167
25603
  const held4 = peekRun(sessionId) ?? record;
@@ -25169,7 +25605,7 @@ async function watchRun(sessionId, resume = startResume) {
25169
25605
  const said2 = failure ?? spoken?.error;
25170
25606
  const offStream = renderer?.offStream?.();
25171
25607
  const quiet = silent && !asked && !blocker && !sub && !!resumeSessionId(held4);
25172
- const blip = quiet ? { reason: waited ? backgroundSaid(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor) } : ours || sub || code === 0 && !said2 || !resumeSessionId(held4) ? void 0 : active2.transient?.({ failure: said2, result, offStream });
25608
+ const blip = quiet ? { reason: waited ? backgroundWaitMessage(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor) } : ours || sub || code === 0 && !said2 || !resumeSessionId(held4) ? void 0 : active2.transient?.({ failure: said2, result, offStream });
25173
25609
  const again = blip ? planRetry2(held4.retry, blip, held4.startedAt, Date.now(), Math.random, !quiet) : null;
25174
25610
  if (again) {
25175
25611
  log.write(`
@@ -25295,7 +25731,7 @@ ${result}
25295
25731
  ...spawnWhy ? [spawnWhy] : [],
25296
25732
  ...saidOurs ? [waited ? { kind: "backgroundSilent", args: { n: String(BACKGROUND_WAIT.minutes / 60) } } : { kind: "silent", args: { n: String(silenceFor) } }] : []
25297
25733
  ];
25298
- const quietSaid = waited ? backgroundSaid(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor);
25734
+ const quietSaid = waited ? backgroundWaitMessage(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor);
25299
25735
  if (sub) {
25300
25736
  await closeRun(sessionId, {
25301
25737
  status,
@@ -25382,7 +25818,7 @@ Cannot resume board repair: ${next.error}`;
25382
25818
  touch = () => {
25383
25819
  if (done2 || !silenceMs) return;
25384
25820
  if (idle) clearTimeout(idle);
25385
- const background = renderer?.background?.() ?? 0;
25821
+ const background = client?.background?.() ?? renderer?.background?.() ?? 0;
25386
25822
  idle = setTimeout(() => {
25387
25823
  if (done2 || stopped2 || silent) return;
25388
25824
  if (liveSubRuns(sessionId).length) {
@@ -25397,7 +25833,7 @@ Cannot resume board repair: ${next.error}`;
25397
25833
  silent = true;
25398
25834
  waited = background > 0;
25399
25835
  log.write(`
25400
- [board] ${waited ? backgroundSaid(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor)}
25836
+ [board] ${waited ? backgroundWaitMessage(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor)}
25401
25837
  `);
25402
25838
  giveUp(false);
25403
25839
  }, background ? BACKGROUND_WAIT.minutes * 6e4 : silenceMs);
@@ -25424,7 +25860,8 @@ Cannot resume board repair: ${next.error}`;
25424
25860
  log: append2,
25425
25861
  gotResumeId: (id, restarted) => gotResumeId(id, restarted),
25426
25862
  gotModel: (model) => gotModel(model),
25427
- event: event2
25863
+ event: event2,
25864
+ gotContext
25428
25865
  }).then((end2) => {
25429
25866
  spoken = end2;
25430
25867
  endChild();
@@ -25438,11 +25875,11 @@ Cannot resume board repair: ${next.error}`;
25438
25875
  child.on("close", (code) => void finish(code, peekRun(sessionId)?.stopping === true || stopped2));
25439
25876
  });
25440
25877
  }
25441
- function settleBoard(run2, changed, before) {
25878
+ function settleBoard(run3, changed, before) {
25442
25879
  try {
25443
- const helpers = specRunsAfter(readSpecAsks(run2.sessionId));
25444
- const waitingForSpec = helpers.some((req) => req.id === run2.cardId);
25445
- return refinementRunsAfter(run2, changed, before, waitingForSpec, readSpecRefusals(run2.sessionId));
25880
+ const helpers = specRunsAfter(readSpecAsks(run3.sessionId));
25881
+ const waitingForSpec = helpers.some((req) => req.id === run3.cardId);
25882
+ return refinementRunsAfter(run3, changed, before, waitingForSpec, readSpecRefusals(run3.sessionId));
25446
25883
  } catch {
25447
25884
  return null;
25448
25885
  }
@@ -25502,7 +25939,7 @@ function catchModel(sessionId, model) {
25502
25939
  });
25503
25940
  return true;
25504
25941
  }
25505
- var STOP_GRACE_MS, STOP_CLOSE_MS, STOP_FINISH_MS, silenceSaid, backgroundSaid, MAX_FORMAT_REPAIRS, joinNotes;
25942
+ var STOP_GRACE_MS, STOP_CLOSE_MS, STOP_FINISH_MS, silenceSaid, MAX_FORMAT_REPAIRS, joinNotes;
25506
25943
  var init_watch = __esm({
25507
25944
  "src/lib/agent/watch.ts"() {
25508
25945
  "use strict";
@@ -25523,6 +25960,7 @@ var init_watch = __esm({
25523
25960
  init_follow();
25524
25961
  init_propose();
25525
25962
  init_log();
25963
+ init_background();
25526
25964
  init_wire();
25527
25965
  init_prompts();
25528
25966
  init_resolve();
@@ -25535,7 +25973,6 @@ var init_watch = __esm({
25535
25973
  STOP_CLOSE_MS = 2e3;
25536
25974
  STOP_FINISH_MS = 1e4;
25537
25975
  silenceSaid = (minutes) => `the agent said nothing for ${minutes} minute${minutes === 1 ? "" : "s"}, so the run was ended.`;
25538
- backgroundSaid = (minutes) => `the agent's background tasks did not finish within ${minutes / 60} hours, so the run was ended.`;
25539
25976
  MAX_FORMAT_REPAIRS = 3;
25540
25977
  joinNotes = (...parts) => parts.filter(Boolean).join("\n\n") || void 0;
25541
25978
  }
@@ -25546,6 +25983,10 @@ import fs83 from "node:fs";
25546
25983
  import path83 from "node:path";
25547
25984
  async function cmdStartRun(action, args, opts, program2 = "akb") {
25548
25985
  const { req, follow: follow2, print } = readRequest(action, args, opts);
25986
+ if (!print && (action === "approve" || action === "implement")) {
25987
+ const deferred = await approveAfterReply(String(req.id), req.notes);
25988
+ if (deferred) return deferred;
25989
+ }
25549
25990
  if (Number.isInteger(req.id)) {
25550
25991
  const creating = creationRefusal(req.id, cardCreation(req.id, req.discard === true), action, req.discard === true);
25551
25992
  if (creating) die(creating, { kind: "card-being-created", action });
@@ -25588,13 +26029,13 @@ async function cmdStartRun(action, args, opts, program2 = "akb") {
25588
26029
  sayIfHeld(req, program2);
25589
26030
  const started = action === "refine" ? await startRefinement(req) : await startRun(runnable);
25590
26031
  if ("error" in started) die(started.error, { kind: "run-refused", action });
25591
- const { run: run2, spawned } = started;
25592
- if (!spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
25593
- say(`${action} \u2014 run ${run2.sessionId}${run2.deliveryId ? ` in delivery ${run2.deliveryId}` : ""}`);
25594
- say(` follow it: ${program2} raw run log ${short(run2.sessionId)} --follow${BOARD_FLAG}`);
25595
- say(` stop it: ${program2} raw run stop ${short(run2.sessionId)}${BOARD_FLAG}`);
25596
- if (follow2) return await followStarted(run2.sessionId, program2, opts.events === true);
25597
- return { sessionId: run2.sessionId, action, cardId: run2.cardId };
26032
+ const { run: run3, spawned } = started;
26033
+ if (!spawned) die(`couldn't start a process for run ${run3.sessionId}`, { kind: "spawn-failed" });
26034
+ say(`${action} \u2014 run ${run3.sessionId}${run3.deliveryId ? ` in delivery ${run3.deliveryId}` : ""}`);
26035
+ say(` follow it: ${program2} raw run log ${short(run3.sessionId)} --follow${BOARD_FLAG}`);
26036
+ say(` stop it: ${program2} raw run stop ${short(run3.sessionId)}${BOARD_FLAG}`);
26037
+ if (follow2) return await followStarted(run3.sessionId, program2, opts.events === true);
26038
+ return { sessionId: run3.sessionId, action, cardId: run3.cardId };
25598
26039
  }
25599
26040
  async function cmdRunScheduled(studio, agent, opts, program2 = "akb") {
25600
26041
  const id = knownStudio(studio);
@@ -25604,12 +26045,12 @@ async function cmdRunScheduled(studio, agent, opts, program2 = "akb") {
25604
26045
  if (insideRun() || opts.print) return printFlow(req, program2);
25605
26046
  const started = await startRun(req);
25606
26047
  if ("error" in started) die(started.error, { kind: "run-refused", action: "scheduled" });
25607
- const { run: run2, spawned } = started;
25608
- if (!spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
25609
- say(`${one.agent} \u2014 run ${run2.sessionId}${run2.deliveryId ? ` in delivery ${run2.deliveryId}` : ""}`);
25610
- say(` follow it: ${program2} raw run log ${short(run2.sessionId)} --follow${BOARD_FLAG}`);
25611
- if (opts.follow) return await followStarted(run2.sessionId, program2, opts.events === true);
25612
- return { sessionId: run2.sessionId, action: "scheduled" };
26048
+ const { run: run3, spawned } = started;
26049
+ if (!spawned) die(`couldn't start a process for run ${run3.sessionId}`, { kind: "spawn-failed" });
26050
+ say(`${one.agent} \u2014 run ${run3.sessionId}${run3.deliveryId ? ` in delivery ${run3.deliveryId}` : ""}`);
26051
+ say(` follow it: ${program2} raw run log ${short(run3.sessionId)} --follow${BOARD_FLAG}`);
26052
+ if (opts.follow) return await followStarted(run3.sessionId, program2, opts.events === true);
26053
+ return { sessionId: run3.sessionId, action: "scheduled" };
25613
26054
  }
25614
26055
  async function approveInCloud(project2, id) {
25615
26056
  const approved = await approveTask(project2, id);
@@ -25699,12 +26140,12 @@ function readRequest(action, args, opts) {
25699
26140
  async function cmdResume(id, opts) {
25700
26141
  const opened = await startResume(id ?? "last", opts.requireSession);
25701
26142
  if ("error" in opened) die(opened.error, { kind: "run-refused", ..."reason" in opened ? { reason: opened.reason } : {} });
25702
- const { run: run2 } = opened;
25703
- if (!opened.spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
25704
- const within = run2.deliveryId ? ` in delivery ${run2.deliveryId}` : "";
25705
- say(run2.resumedFrom ? `continuing ${short(run2.resumedFrom)} \u2014 run ${run2.sessionId}${within}` : `trying again \u2014 run ${run2.sessionId}${within}`);
25706
- if (opts.follow === true) return await followStarted(run2.sessionId, "akb", opts.events === true);
25707
- return { sessionId: run2.sessionId, resumedFrom: run2.resumedFrom };
26143
+ const { run: run3 } = opened;
26144
+ if (!opened.spawned) die(`couldn't start a process for run ${run3.sessionId}`, { kind: "spawn-failed" });
26145
+ const within = run3.deliveryId ? ` in delivery ${run3.deliveryId}` : "";
26146
+ say(run3.resumedFrom ? `continuing ${short(run3.resumedFrom)} \u2014 run ${run3.sessionId}${within}` : `trying again \u2014 run ${run3.sessionId}${within}`);
26147
+ if (opts.follow === true) return await followStarted(run3.sessionId, "akb", opts.events === true);
26148
+ return { sessionId: run3.sessionId, resumedFrom: run3.resumedFrom };
25708
26149
  }
25709
26150
  async function cmdCancel(named2) {
25710
26151
  const res = await cancelBoardDelivery(named2);
@@ -26059,6 +26500,7 @@ var init_run = __esm({
26059
26500
  init_io();
26060
26501
  init_lock();
26061
26502
  init_paths();
26503
+ init_reply_approval();
26062
26504
  init_tasks();
26063
26505
  init_read();
26064
26506
  init_rules();
@@ -26241,16 +26683,16 @@ async function cmdSpec(opts, program2 = "akb") {
26241
26683
  }
26242
26684
  const started = await startRun(req);
26243
26685
  if ("error" in started) die(started.error, { kind: "run-refused", action: "spec" });
26244
- const { run: run2, spawned } = started;
26245
- if (!spawned) die(`couldn't start a process to run ${run2.sessionId}`, { kind: "spawn-failed" });
26686
+ const { run: run3, spawned } = started;
26687
+ if (!spawned) die(`couldn't start a process to run ${run3.sessionId}`, { kind: "spawn-failed" });
26246
26688
  if (ownRuntime || ownSession) {
26247
26689
  say(`${name} runs in ${ownRuntime ? "its own runtime" : "a session of its own"}, so it started as a separate run \u2014 don't write its section yourself.`);
26248
26690
  }
26249
- say(`previews ${name} #${id} \u2014 run ${run2.sessionId}`);
26250
- say(` follow it: ${program2} raw run log ${short(run2.sessionId)} --follow${BOARD_FLAG}`);
26251
- say(` stop it: ${program2} raw run stop ${short(run2.sessionId)}${BOARD_FLAG}`);
26252
- if (opts.follow === true) return await followStarted(run2.sessionId, program2);
26253
- return { sessionId: run2.sessionId, action: "spec", specAgent: name, cardId: id };
26691
+ say(`previews ${name} #${id} \u2014 run ${run3.sessionId}`);
26692
+ say(` follow it: ${program2} raw run log ${short(run3.sessionId)} --follow${BOARD_FLAG}`);
26693
+ say(` stop it: ${program2} raw run stop ${short(run3.sessionId)}${BOARD_FLAG}`);
26694
+ if (opts.follow === true) return await followStarted(run3.sessionId, program2);
26695
+ return { sessionId: run3.sessionId, action: "spec", specAgent: name, cardId: id };
26254
26696
  }
26255
26697
  function noteOf(words, flag) {
26256
26698
  const typed = words.join(" ").trim();
@@ -26323,7 +26765,7 @@ var init_telemetry2 = __esm({
26323
26765
 
26324
26766
  // src/commands/agent-check.ts
26325
26767
  import { spawnSync as spawnSync5 } from "node:child_process";
26326
- function run(file, args) {
26768
+ function run2(file, args) {
26327
26769
  const start = spawnable(file, args, { env: copyEnv(file), stdio: ["ignore", "pipe", "pipe"], timeout: 1e4 });
26328
26770
  const ran = spawnSync5(start.command, start.args, { ...start.options, encoding: "utf8" });
26329
26771
  return { out: `${ran.stdout ?? ""}${ran.stderr ?? ""}`.trim(), error: ran.error?.message };
@@ -26337,14 +26779,14 @@ function cmdAgentCheck(name) {
26337
26779
  const answer2 = { agent: harness.name, file: copy2?.file ?? null, version: copy2?.version ?? null };
26338
26780
  if (!copy2) die(`${harness.label} not found: no \`${binary}\` on the PATH or in its usual install folders.`, { kind: "agent-missing" });
26339
26781
  if (!copy2.starts) {
26340
- const said2 = run(copy2.file, ["--version"]);
26782
+ const said2 = run2(copy2.file, ["--version"]);
26341
26783
  die(`${harness.label} at ${copy2.file} failed to start: ${said2.error ?? said2.out.split("\n")[0] ?? "no output"}`, { kind: "agent-broken" });
26342
26784
  }
26343
26785
  if (harness.name === "dsh" && !dshFound(copy2.file, binaryOnPath)) {
26344
26786
  die(`${harness.label}: dsh-acp is installed, but the dsh it starts is not \u2014 install dsh beside it or on the PATH.`, { kind: "agent-missing" });
26345
26787
  }
26346
26788
  if (harness.login) {
26347
- const said2 = run(copy2.file, harness.login.args).out;
26789
+ const said2 = run2(copy2.file, harness.login.args).out;
26348
26790
  if (!harness.login.ready(said2) && harness.login.loggedOut(said2)) {
26349
26791
  die(`${harness.label} is signed out: run \`${harness.login.login}\`.`, { kind: "agent-signed-out" });
26350
26792
  }
@@ -26637,8 +27079,8 @@ function declareRuns(program2, cli) {
26637
27079
  if (code !== 0) throw new BoardError(`the watcher for ${sessionId} ended with ${code}`, { kind: "watch-failed" });
26638
27080
  });
26639
27081
  }
26640
- function declareRunning(run2, cli) {
26641
- const verb = (name) => withShared(run2.command(name));
27082
+ function declareRunning(run3, cli) {
27083
+ const verb = (name) => withShared(run3.command(name));
26642
27084
  verb("list").summary("what is running, and what ran lately").description("A creation run with no card fails even if the agent exits with code 0. Failure reason, triage source and cost are kept. In JSON the run reports status: error and ok: false; the outer ok describes this query. A successful query exits with code 0.").option("-c, --card <id>", "only the runs on that card", cardId).option("-a, --all", "every run this board has kept, not just the last ten").action(async function() {
26643
27085
  await onBoard2(this, cli, (p) => cmdRuns(this.opts(), p));
26644
27086
  });