wildcrane-runner 0.6.56 → 0.6.58

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.44 — built by runner/scripts/build.mjs. Do not edit.
2
+ // ai4kanban 0.11.45 — built by runner/scripts/build.mjs. Do not edit.
3
3
  import { createRequire as __ai4kanbanRequire } from 'node:module'
4
4
  const require = __ai4kanbanRequire(import.meta.url)
5
5
  var __create = Object.create;
@@ -50,27 +50,66 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
50
50
  mod
51
51
  ));
52
52
 
53
- // ../cli/src/lib/cloud/config.ts
54
- function cloudEndpoints() {
55
- return {
56
- supabaseUrl: trimSlash(process.env.AI4KANBAN_SUPABASE_URL || SUPABASE_URL),
57
- anonKey: process.env.AI4KANBAN_SUPABASE_ANON_KEY || SUPABASE_ANON_KEY,
58
- api: trimSlash(process.env.AI4KANBAN_CLOUD_URL || API_URL)
59
- };
53
+ // ../cli/src/lib/io.ts
54
+ function startCollecting() {
55
+ sink = { out: [], warnings: [] };
56
+ return sink;
60
57
  }
61
- function cloudConfigured() {
62
- const { supabaseUrl, anonKey } = cloudEndpoints();
63
- return !!supabaseUrl && !!anonKey;
58
+ function stopCollecting() {
59
+ sink = null;
64
60
  }
65
- var SUPABASE_URL, SUPABASE_ANON_KEY, API_URL, trimSlash, NOT_CONFIGURED;
66
- var init_config = __esm({
67
- "../cli/src/lib/cloud/config.ts"() {
61
+ function quietly(fn) {
62
+ const before = sink;
63
+ sink = { out: [], warnings: [] };
64
+ try {
65
+ return fn();
66
+ } finally {
67
+ sink = before;
68
+ }
69
+ }
70
+ async function quietlyAsync(fn) {
71
+ const before = sink;
72
+ sink = { out: [], warnings: [] };
73
+ try {
74
+ return await fn();
75
+ } finally {
76
+ sink = before;
77
+ }
78
+ }
79
+ function say(line = "") {
80
+ const text4 = String(line);
81
+ if (sink) sink.out.push(...text4.split("\n"));
82
+ else console.log(text4);
83
+ }
84
+ function warn(message) {
85
+ if (sink) sink.warnings.push(String(message));
86
+ else console.error(`kanban: warning \u2014 ${message}`);
87
+ }
88
+ var BoardError, sink;
89
+ var init_io = __esm({
90
+ "../cli/src/lib/io.ts"() {
68
91
  "use strict";
69
- SUPABASE_URL = "https://yajrbpprmdvtkvjjfpbk.supabase.co";
70
- SUPABASE_ANON_KEY = "sb_publishable_ioUQ23BTtoj8NKqndp0Jrw_omVR3m4n";
71
- API_URL = "https://api.ai4kanban.dev";
72
- trimSlash = (url) => url.replace(/\/+$/, "");
73
- NOT_CONFIGURED = "This build of WildCrane carries no Cloud project to sign in against.";
92
+ BoardError = class extends Error {
93
+ // `kind` is the machine-readable name of the refusal (card-not-found, no-board,
94
+ // unknown-module, …). It is what a caller reads; the exit code stays 1 for every
95
+ // refusal, so nobody has to keep a table of numbers.
96
+ kind;
97
+ // Only `cloud image` / `cloud tts` set it: 2 for a usage error, as the scripts they replaced did.
98
+ exitCode;
99
+ // `bare` says the message is already the whole thing a person should see — a usage
100
+ // block, say — so the dispatcher prints it without putting the command in front of it.
101
+ bare;
102
+ details;
103
+ constructor(message, { kind = "refused", bare = false, exitCode = 1, ...details } = {}) {
104
+ super(message);
105
+ this.name = "BoardError";
106
+ this.kind = kind;
107
+ this.bare = bare;
108
+ this.exitCode = exitCode;
109
+ this.details = details;
110
+ }
111
+ };
112
+ sink = null;
74
113
  }
75
114
  });
76
115
 
@@ -86,643 +125,637 @@ var init_home = __esm({
86
125
  }
87
126
  });
88
127
 
89
- // ../cli/src/lib/cloud/session.ts
128
+ // ../cli/src/lib/machine/project.ts
129
+ import { createHash } from "node:crypto";
90
130
  import fs from "node:fs";
91
131
  import path2 from "node:path";
92
- function readSession() {
93
- let raw;
94
- try {
95
- raw = fs.readFileSync(sessionFile(), "utf8");
96
- } catch {
97
- return null;
98
- }
99
- try {
100
- const held4 = JSON.parse(raw);
101
- if (!held4.accessToken || !held4.refreshToken || !held4.subject) return null;
102
- if (held4.supabaseUrl !== cloudEndpoints().supabaseUrl) return null;
103
- return { ...held4, version: 1, expiresAt: Number(held4.expiresAt) || 0 };
104
- } catch {
105
- return null;
132
+ function realPathOf(dir) {
133
+ const here = path2.resolve(dir);
134
+ const rest = [];
135
+ let at = here;
136
+ for (; ; ) {
137
+ try {
138
+ return path2.join(fs.realpathSync(at), ...rest);
139
+ } catch {
140
+ const up = path2.dirname(at);
141
+ if (up === at) return here;
142
+ rest.unshift(path2.basename(at));
143
+ at = up;
144
+ }
106
145
  }
107
146
  }
108
- function writeSession(session) {
109
- fs.mkdirSync(machineHome(), { recursive: true, mode: 448 });
110
- const tmp = `${sessionFile()}.${process.pid}.tmp`;
111
- fs.writeFileSync(tmp, `${JSON.stringify(session, null, 2)}
112
- `, { mode: 384 });
113
- fs.renameSync(tmp, sessionFile());
147
+ function readableName(real2) {
148
+ const here = path2.basename(real2);
149
+ const up = path2.dirname(real2);
150
+ if (here !== "kanban") return slug(here);
151
+ return path2.basename(up) === "docs" ? slug(path2.basename(path2.dirname(up))) : slug(`${path2.basename(up)}-kanban`);
114
152
  }
115
- function clearSession() {
116
- try {
117
- fs.rmSync(sessionFile());
118
- } catch {
153
+ function legacyProjectStateDir(board2) {
154
+ const real2 = realPathOf(board2);
155
+ const id = createHash("sha256").update(real2).digest("hex").slice(0, ID_LENGTH);
156
+ return path2.join(machineHome(), PROJECTS, `${readableName(real2)}-${id}`);
157
+ }
158
+ function stateRootOf(board2) {
159
+ let dir = realPathOf(board2);
160
+ for (; ; ) {
161
+ if (fs.existsSync(path2.join(dir, ".git"))) return dir;
162
+ const up = path2.dirname(dir);
163
+ if (up === dir) break;
164
+ dir = up;
119
165
  }
166
+ return rootAbove(realPathOf(board2));
120
167
  }
121
- async function accessToken() {
122
- const held4 = readSession();
123
- if (!held4) return { ok: false, reason: "signed-out" };
124
- if (!expiringSoon(held4)) return { ok: true, token: held4.accessToken, session: held4 };
125
- return refresh();
168
+ function rootAbove(board2) {
169
+ const parent = path2.dirname(board2);
170
+ return ["docs", ".akb"].includes(path2.basename(parent)) ? path2.dirname(parent) : parent;
126
171
  }
127
- async function refresh() {
128
- const lock = await takeLock();
129
- try {
130
- const now = readSession();
131
- if (!now) return { ok: false, reason: "signed-out" };
132
- if (!expiringSoon(now)) return { ok: true, token: now.accessToken, session: now };
133
- const { api, anonKey } = cloudEndpoints();
134
- let response;
135
- try {
136
- response = await fetch(`${api}/auth/v1/token?grant_type=refresh_token`, {
137
- method: "POST",
138
- headers: { apikey: anonKey, "content-type": "application/json" },
139
- body: JSON.stringify({ refresh_token: now.refreshToken })
140
- });
141
- } catch (e) {
142
- return { ok: false, reason: "unreachable", error: e instanceof Error ? e.message : String(e) };
143
- }
144
- if (!response.ok) {
145
- const body = await response.json().catch(() => ({}));
146
- if (response.status >= 500) {
147
- return { ok: false, reason: "unreachable", error: body.error_description ?? `Cloud answered ${response.status}` };
148
- }
149
- return { ok: false, reason: "expired", error: body.error_description };
150
- }
151
- const fresh = sessionFrom(await response.json(), now);
152
- if (!fresh) return { ok: false, reason: "expired" };
153
- const current = readSession();
154
- if (!current || current.subject !== now.subject) return { ok: false, reason: "expired" };
155
- if (current.refreshToken !== now.refreshToken) return { ok: true, token: current.accessToken, session: current };
156
- writeSession(fresh);
157
- return { ok: true, token: fresh.accessToken, session: fresh };
158
- } finally {
159
- lock();
172
+ function projectStateDir(board2, root2 = stateRootOf(board2)) {
173
+ const relative = path2.relative(realPathOf(root2), realPathOf(board2));
174
+ if (relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative)) {
175
+ throw new Error("The board must be inside its project root.");
160
176
  }
177
+ return path2.join(realPathOf(root2), ".akb", "boards", relative || "_root");
161
178
  }
162
- function sessionFrom(body, previous) {
163
- const token2 = body;
164
- const subject = token2.user?.id ?? previous?.subject;
165
- if (!token2.access_token || !token2.refresh_token || !subject) return null;
166
- const expiresAt = token2.expires_at ? token2.expires_at * 1e3 : Date.now() + (token2.expires_in ?? 3600) * 1e3;
167
- return {
168
- version: 1,
169
- supabaseUrl: cloudEndpoints().supabaseUrl,
170
- accessToken: token2.access_token,
171
- refreshToken: token2.refresh_token,
172
- expiresAt,
173
- subject,
174
- email: token2.user?.email ?? previous?.email,
175
- handle: previous?.handle,
176
- name: previous?.name,
177
- avatarUrl: previous?.avatarUrl,
178
- avatar: previous?.avatar
179
- };
180
- }
181
- async function takeLock() {
182
- const until = Date.now() + LOCK_WAIT_MS;
183
- for (; ; ) {
179
+ function ensureProjectState(board2, root2 = stateRootOf(board2)) {
180
+ const dir = projectStateDir(board2, root2);
181
+ if (!fs.existsSync(dir)) {
182
+ const legacy2 = legacyProjectStateDir(board2);
183
+ fs.mkdirSync(path2.dirname(dir), { recursive: true });
184
+ const temporary = fs.mkdtempSync(`${dir}.import-`);
184
185
  try {
185
- fs.mkdirSync(machineHome(), { recursive: true, mode: 448 });
186
- fs.mkdirSync(lockDir());
186
+ if (fs.existsSync(legacy2)) fs.cpSync(legacy2, temporary, {
187
+ recursive: true,
188
+ filter: (source) => ![".lock", ".answering"].some((suffix) => path2.basename(source).endsWith(suffix))
189
+ });
187
190
  try {
188
- fs.writeFileSync(lockOwner(), `${process.pid}
189
- `);
190
- } catch {
191
- }
192
- return () => {
193
- try {
194
- fs.rmSync(lockDir(), { recursive: true, force: true });
195
- } catch {
196
- }
197
- };
198
- } catch (err) {
199
- if (err.code !== "EEXIST") throw err;
200
- if (stale()) {
201
- fs.rmSync(lockDir(), { recursive: true, force: true });
202
- continue;
191
+ fs.renameSync(temporary, dir);
192
+ } catch (err) {
193
+ if (!["EEXIST", "ENOTEMPTY"].includes(err.code ?? "")) throw err;
203
194
  }
204
- if (Date.now() > until) return () => {
205
- };
206
- await sleep(LOCK_RETRY_MS);
195
+ } finally {
196
+ fs.rmSync(temporary, { recursive: true, force: true });
207
197
  }
208
198
  }
209
- }
210
- function stale() {
211
- let held4;
212
- try {
213
- const pid = Number(fs.readFileSync(lockOwner(), "utf8").trim());
214
- held4 = Number.isInteger(pid) && pid > 0 ? pid : void 0;
215
- } catch {
216
- held4 = void 0;
217
- }
218
- if (held4 !== void 0 && !alive(held4)) return true;
219
- try {
220
- return Date.now() - fs.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
221
- } catch {
222
- return false;
199
+ if (recordedBoard(dir) !== realPathOf(board2)) {
200
+ fs.writeFileSync(path2.join(dir, RECORD), `${JSON.stringify({ board: realPathOf(board2) })}
201
+ `);
223
202
  }
203
+ return dir;
224
204
  }
225
- function alive(pid) {
205
+ function recordedBoard(dir) {
226
206
  try {
227
- process.kill(pid, 0);
228
- return true;
229
- } catch (e) {
230
- return e.code === "EPERM";
207
+ const held4 = JSON.parse(fs.readFileSync(path2.join(dir, RECORD), "utf8"));
208
+ return typeof held4.board === "string" ? held4.board : null;
209
+ } catch {
210
+ return null;
231
211
  }
232
212
  }
233
- var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep;
234
- var init_session = __esm({
235
- "../cli/src/lib/cloud/session.ts"() {
213
+ var PROJECTS, ID_LENGTH, RECORD, SESSIONS_FILE, SESSIONS_FOLDER, ASSETS_FOLDER, MOCKUPS_FOLDER, SESSIONS_LOCK, INDEX_LOCK, UI_CONFIG_FILE, slug;
214
+ var init_project = __esm({
215
+ "../cli/src/lib/machine/project.ts"() {
236
216
  "use strict";
237
217
  init_home();
238
- init_config();
239
- REFRESH_MARGIN_MS = 6e4;
240
- LOCK_STALE_MS = 3e4;
241
- LOCK_WAIT_MS = 2e4;
242
- LOCK_RETRY_MS = 50;
243
- sessionFile = () => path2.join(machineHome(), "session.json");
244
- lockDir = () => path2.join(machineHome(), "session.lock");
245
- lockOwner = () => path2.join(lockDir(), "owner");
246
- expiringSoon = (session) => session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
247
- sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
218
+ PROJECTS = "projects";
219
+ ID_LENGTH = 10;
220
+ RECORD = "board.json";
221
+ SESSIONS_FILE = "sessions.json";
222
+ SESSIONS_FOLDER = "sessions";
223
+ ASSETS_FOLDER = "assets";
224
+ MOCKUPS_FOLDER = "mockups";
225
+ SESSIONS_LOCK = "sessions.lock";
226
+ INDEX_LOCK = "index.lock";
227
+ UI_CONFIG_FILE = "ui.config.json";
228
+ slug = (text4) => text4.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "board";
248
229
  }
249
230
  });
250
231
 
251
- // ../cli/src/lib/cloud/tasks.ts
252
- import crypto from "node:crypto";
232
+ // ../cli/src/lib/paths.ts
233
+ import { spawnSync } from "node:child_process";
253
234
  import fs2 from "node:fs";
254
235
  import path3 from "node:path";
255
- function workspaceTask() {
256
- const id = process.env[TASK_ENV];
257
- return id && id.trim() ? id.trim() : null;
236
+ function boardLockName(kanban, root2) {
237
+ const from = path3.relative(root2, kanban);
238
+ const name = from && !from.startsWith("..") ? from : path3.basename(kanban);
239
+ return `${name.split(path3.sep).join("-")}.lock`;
258
240
  }
259
- function cloudStudio(name) {
260
- if (/^wf-/.test(name)) return name.replace("-", "_");
261
- return `wf_builtin_${name.replace(/-/g, "_")}`;
241
+ function ensureAkbDir() {
242
+ fs2.mkdirSync(AKB_DIR, { recursive: true });
243
+ writeRootIgnoreIfMissing();
244
+ return AKB_DIR;
262
245
  }
263
- async function call(method, route2, body, key) {
264
- if (!cloudConfigured()) return { ok: false, error: NOT_CONFIGURED, code: "bad_request" };
265
- const token2 = await accessToken();
266
- if (!token2.ok) {
267
- 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" };
268
- }
269
- let response;
270
- try {
271
- response = await fetch(`${cloudEndpoints().api}${route2}`, {
272
- method,
273
- headers: {
274
- authorization: `Bearer ${token2.token}`,
275
- ...body ? { "content-type": "application/json" } : {},
276
- ...key ? { "idempotency-key": key } : {}
277
- },
278
- ...body ? { body: JSON.stringify(body) } : {},
279
- signal: AbortSignal.timeout(2e4)
280
- });
281
- } catch (e) {
282
- return { ok: false, error: `Cloud could not be reached: ${e instanceof Error ? e.message : String(e)}` };
246
+ function writeRootIgnoreIfMissing() {
247
+ const text4 = fs2.existsSync(ROOT_GITIGNORE) ? fs2.readFileSync(ROOT_GITIGNORE, "utf8") : "";
248
+ if (text4.split("\n").some((line) => line.trim() === AKB_IGNORE_LINE)) return false;
249
+ const ignored = spawnSync("git", ["-C", REPO_ROOT, "check-ignore", "-q", AKB_IGNORE_LINE], { stdio: "ignore" }).status;
250
+ if (ignored === 0 || ignored === 128 && KANBAN.startsWith(AKB_DIR + path3.sep)) return false;
251
+ const separator = !text4 || text4.endsWith("\n") ? "" : "\n";
252
+ const block = `# Delivery state \u2014 worktrees and the like. Never committed.
253
+ ${AKB_IGNORE_LINE}
254
+ `;
255
+ fs2.writeFileSync(ROOT_GITIGNORE, `${text4}${separator}${block}`);
256
+ return true;
257
+ }
258
+ function projectRootOf(board2) {
259
+ let dir = path3.resolve(board2);
260
+ for (; ; ) {
261
+ if (fs2.existsSync(path3.join(dir, ".git"))) return dir;
262
+ const up = path3.dirname(dir);
263
+ if (up === dir) return rootAbove(path3.resolve(board2));
264
+ dir = up;
283
265
  }
284
- const parsed = await response.json().catch(() => ({}));
285
- if (!response.ok) return { ok: false, code: parsed.error?.code ?? "refused", error: parsed.error?.message ?? `Cloud answered ${response.status}.` };
286
- return { ok: true, value: parsed, replayed: response.headers.get("idempotent-replayed") === "true" };
287
266
  }
288
- async function createTask(from, said2) {
289
- const source = await call("GET", `/v1/tasks/${encodeURIComponent(from)}`);
290
- if (!source.ok) return source;
291
- const studio = said2.studio ? cloudStudio(said2.studio) : source.value.studio?.id;
292
- const body = {
293
- title: said2.title,
294
- project: source.value.project,
295
- ...studio ? { studio } : {},
296
- ...said2.request?.trim() ? { request: said2.request.trim() } : {},
297
- source: "api",
298
- source_context: { task: from, ...said2.agent ? { agent: said2.agent } : {} },
299
- ...said2.run ? { run: true } : {},
300
- ...said2.metadata && Object.keys(said2.metadata).length ? { metadata: said2.metadata } : {},
301
- ...said2.triage ? { triage: `tri_${source.value.project.replace(/^prj_/, "")}_${said2.triage}` } : {}
302
- };
303
- const key = `akb-${crypto.createHash("sha256").update(`${from}
304
- ${said2.slug?.trim() || said2.title}`).digest("hex").slice(0, 40)}`;
305
- const made = await call("POST", "/v1/tasks", body, key);
306
- if (!made.ok) return made;
307
- const number = numberOf(made.value.key);
308
- if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
309
- return { ok: true, value: { task: made.value, number, from: source.value, replayed: made.replayed === true } };
267
+ function setBoard(kanban, root2, flag) {
268
+ REPO_ROOT = path3.resolve(root2);
269
+ KANBAN = path3.resolve(kanban);
270
+ BOARD_FLAG = flag;
271
+ TODO = path3.join(KANBAN, "todo");
272
+ ARCHIVE = path3.join(KANBAN, ".archive");
273
+ ARCHIVE_MD = path3.join(KANBAN, "archive.md");
274
+ README = path3.join(TODO, "README.md");
275
+ MODULES_MD = path3.join(KANBAN, "modules.md");
276
+ CONFIG = path3.join(KANBAN, "config.md");
277
+ KANBAN_GITIGNORE = path3.join(KANBAN, ".gitignore");
278
+ RELEASES = path3.join(KANBAN, "releases.md");
279
+ RELEASE_SUMMARIES = path3.join(KANBAN, ".release-summaries");
280
+ AGENTS = path3.join(KANBAN, "agents");
281
+ STUDIOS = path3.join(KANBAN, "studios");
282
+ LEGACY_AGENTS = path3.join(KANBAN, "skills");
283
+ MEMORY = path3.join(KANBAN, "memory");
284
+ AGENT_MEMORY = path3.join(MEMORY, "agents");
285
+ PROJECT_MD = path3.join(MEMORY, "project.md");
286
+ LEGACY_UI_CONFIG = path3.join(KANBAN, UI_CONFIG_FILE);
287
+ LOCAL_CONFIG = path3.join(KANBAN, ".local.json");
288
+ ENV_FILE = path3.join(KANBAN, ".env");
289
+ const machine = projectStateDir(KANBAN, REPO_ROOT);
290
+ BOARD_STATE = machine;
291
+ UI_CONFIG = path3.join(machine, UI_CONFIG_FILE);
292
+ ASSETS = path3.join(machine, ASSETS_FOLDER);
293
+ MOCKUPS = path3.join(machine, MOCKUPS_FOLDER);
294
+ SESSIONS = path3.join(machine, SESSIONS_FILE);
295
+ SESSIONS_DIR = path3.join(machine, SESSIONS_FOLDER);
296
+ SESSIONS_LOCK2 = path3.join(machine, SESSIONS_LOCK);
297
+ INDEX_LOCK2 = path3.join(machine, INDEX_LOCK);
298
+ DELIVERIES = path3.join(KANBAN, "deliveries");
299
+ RULES = path3.join(KANBAN, "rules");
300
+ PLANS = path3.join(machine, "plans");
301
+ PLANS_ARCHIVE = path3.join(PLANS, "archive");
302
+ TRIAGE = path3.join(KANBAN, "triage");
303
+ SIGNALS_ARCHIVED = path3.join(TRIAGE, "archived");
304
+ SIGNALS_DISMISSED = path3.join(TRIAGE, "dismissed");
305
+ SIGNALS_FILES = path3.join(TRIAGE, "files");
306
+ SIGNALS_OLD_INBOX = path3.join(TRIAGE, "inbox");
307
+ SIGNALS_OLD_HANDLED = path3.join(TRIAGE, "handled.md");
308
+ AKB_DIR = path3.join(REPO_ROOT, ".akb");
309
+ ROOT_GITIGNORE = path3.join(REPO_ROOT, ".gitignore");
310
+ LOCK = path3.join(AKB_DIR, boardLockName(KANBAN, REPO_ROOT));
311
+ return REPO_ROOT;
310
312
  }
311
- function runnerProject(board2) {
312
- if (path3.basename(board2) !== "kanban" || path3.basename(path3.dirname(board2)) !== ".akb") return null;
313
- const linked2 = linkedProject(board2, path3.dirname(path3.dirname(board2)));
314
- return linked2.ok ? linked2.value : null;
313
+ function setBoardRoot(root2, named2 = false) {
314
+ const project2 = path3.resolve(root2);
315
+ return setBoard(path3.join(project2, "docs", "kanban"), project2, named2 ? ` --dir ${project2}` : "");
315
316
  }
316
- function linkedProject(board2, root2) {
317
- const file = path3.join(root2, ".akb", "base.json");
318
- if (!fs2.existsSync(file)) return { ok: true, value: null };
319
- try {
320
- const base = JSON.parse(fs2.readFileSync(file, "utf8"));
321
- 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();
322
- const projects = new Set(Object.keys(base.files ?? {}).flatMap((p) => /^projects\/([^/]+)\//.exec(p)?.[1] ?? []));
323
- if (typeof base.project === "string") projects.add(base.project);
324
- if (projects.size !== 1) throw new Error();
325
- return { ok: true, value: [...projects][0] };
326
- } catch {
327
- return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
328
- }
317
+ function setBoardDir(board2, root2) {
318
+ const folder = path3.resolve(board2);
319
+ return setBoard(folder, root2 ?? projectRootOf(folder), ` --board ${folder}`);
329
320
  }
330
- async function creationProject(board2, root2, task = workspaceTask()) {
331
- const link2 = linkedProject(board2, root2);
332
- if (!link2.ok) return link2;
333
- let project2 = link2.value;
334
- if (task) {
335
- const source = await call("GET", `/v1/tasks/${encodeURIComponent(task)}`);
336
- if (!source.ok) return {
337
- ...source,
338
- 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
339
- };
340
- if (project2 && project2 !== source.value.project) return { ok: false, error: "The source task conflicts with this board\u2019s project link.", code: "invalid-link" };
341
- project2 = source.value.project;
342
- }
343
- if (!project2) return { ok: false, error: "This board is not linked to a Cloud project.", code: "unlinked" };
344
- const checked = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
345
- return checked.ok ? { ok: true, value: project2 } : checked;
321
+ function die(msg, kind) {
322
+ throw new BoardError(msg, typeof kind === "string" ? { kind } : kind);
346
323
  }
347
- async function createProjectTask(project2, said2, key) {
348
- const made = await call("POST", "/v1/tasks", {
349
- title: said2.title,
350
- project: project2,
351
- source: "api",
352
- ...said2.studio ? { studio: cloudStudio(said2.studio) } : {},
353
- ...said2.request?.trim() ? { request: said2.request.trim() } : {},
354
- ...said2.agent ? { source_context: { agent: said2.agent } } : {},
355
- ...said2.triage ? { triage: `tri_${project2.replace(/^prj_/, "")}_${said2.triage}` } : {}
356
- }, key);
357
- if (!made.ok) return made;
358
- const number = numberOf(made.value.key);
359
- if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
360
- return { ok: true, value: { task: made.value, number } };
324
+ function warn2(msg) {
325
+ warn(msg);
361
326
  }
362
- async function approveTask(project2, number) {
363
- const held4 = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
364
- if (!held4.ok) return held4;
365
- const key = `${held4.value.prefix}-${number}`;
366
- const task = await call("GET", `/v1/tasks/${encodeURIComponent(key)}`);
367
- if (!task.ok) return task;
368
- const revision = task.value.review?.revision;
369
- const decided = await call("POST", `/v1/tasks/${encodeURIComponent(key)}/decisions`, {
370
- decision: "approve",
371
- ...revision !== void 0 ? { review_revision: revision } : {}
372
- });
373
- return decided.ok ? { ok: true, value: { key } } : decided;
327
+ function boardPath() {
328
+ return rel(KANBAN).split(path3.sep).join("/");
374
329
  }
375
- var TASK_ENV, numberOf;
376
- var init_tasks = __esm({
377
- "../cli/src/lib/cloud/tasks.ts"() {
330
+ function boardText(text4) {
331
+ const posix = (p) => rel(p).split(path3.sep).join("/");
332
+ const swaps = [
333
+ [ASSETS_PATH_IN_TEXT, posix(ASSETS)],
334
+ [MOCKUPS_PATH_IN_TEXT, posix(MOCKUPS)],
335
+ [BOARD_STATE_IN_TEXT, posix(BOARD_STATE)],
336
+ [BOARD_PATH_IN_TEXT, boardPath()]
337
+ ];
338
+ const swap = (part, i) => i === swaps.length ? part : part.split(swaps[i][0]).map((p) => swap(p, i + 1)).join(swaps[i][1]);
339
+ return swap(text4, 0);
340
+ }
341
+ function useProjectState() {
342
+ ensureAkbDir();
343
+ return ensureProjectState(KANBAN, REPO_ROOT);
344
+ }
345
+ 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;
346
+ var init_paths = __esm({
347
+ "../cli/src/lib/paths.ts"() {
378
348
  "use strict";
379
- init_config();
380
- init_session();
381
- TASK_ENV = "AI4KANBAN_TASK";
382
- numberOf = (key) => Number(/-(\d+)$/.exec(key)?.[1] ?? NaN);
349
+ init_io();
350
+ init_project();
351
+ REPO_ROOT = "";
352
+ KANBAN = "";
353
+ TODO = "";
354
+ ARCHIVE = "";
355
+ REJECTIONS_TO_REVIEW = ".sync";
356
+ ARCHIVE_MD = "";
357
+ README = "";
358
+ MODULES_MD = "";
359
+ CONFIG = "";
360
+ KANBAN_GITIGNORE = "";
361
+ RELEASES = "";
362
+ RELEASE_SUMMARIES = "";
363
+ AGENTS = "";
364
+ STUDIOS = "";
365
+ LEGACY_AGENTS = "";
366
+ ASSETS = "";
367
+ BOARD_STATE = "";
368
+ MOCKUPS = "";
369
+ MEMORY = "";
370
+ AGENT_MEMORY = "";
371
+ PROJECT_MD = "";
372
+ LOCK = "";
373
+ UI_CONFIG = "";
374
+ LEGACY_UI_CONFIG = "";
375
+ LOCAL_CONFIG = "";
376
+ ENV_FILE = "";
377
+ SESSIONS = "";
378
+ SESSIONS_DIR = "";
379
+ SESSIONS_LOCK2 = "";
380
+ INDEX_LOCK2 = "";
381
+ DELIVERIES = "";
382
+ PLANS = "";
383
+ PLANS_ARCHIVE = "";
384
+ RULES = "";
385
+ TRIAGE = "";
386
+ SIGNALS_ARCHIVED = "";
387
+ SIGNALS_DISMISSED = "";
388
+ SIGNALS_FILES = "";
389
+ SIGNALS_OLD_INBOX = "";
390
+ SIGNALS_OLD_HANDLED = "";
391
+ AKB_DIR = "";
392
+ ROOT_GITIGNORE = "";
393
+ AKB_IGNORE_LINE = ".akb/";
394
+ BOARD_FLAG = "";
395
+ setBoardRoot(process.cwd());
396
+ rel = (p) => {
397
+ const from = path3.relative(REPO_ROOT, p);
398
+ if (!from) return p;
399
+ return from.startsWith("..") ? p : from;
400
+ };
401
+ BOARD_PATH_IN_TEXT = "docs/kanban";
402
+ ASSETS_PATH_IN_TEXT = "docs/kanban/.assets";
403
+ MOCKUPS_PATH_IN_TEXT = "docs/kanban/.mockups";
404
+ BOARD_STATE_IN_TEXT = "<board-state>";
383
405
  }
384
406
  });
385
407
 
386
- // ../cli/src/lib/io.ts
387
- function startCollecting() {
388
- sink = { out: [], warnings: [] };
389
- return sink;
390
- }
391
- function stopCollecting() {
392
- sink = null;
393
- }
394
- function quietly(fn) {
395
- const before = sink;
396
- sink = { out: [], warnings: [] };
408
+ // ../cli/src/lib/cloud/reply-approval.ts
409
+ async function approveAfterReply(task, comment) {
410
+ const context = process.env[REPLY_APPROVAL_ENV];
411
+ if (!context) return null;
397
412
  try {
398
- return fn();
399
- } finally {
400
- sink = before;
413
+ const { url, token: token2 } = JSON.parse(context);
414
+ if (!/^http:\/\/127\.0\.0\.1:\d+\/$/.test(url) || !/^[a-f0-9]{64}$/.test(token2)) throw Error("Invalid reply context.");
415
+ const response = await fetch(url, {
416
+ method: "POST",
417
+ headers: { authorization: `Bearer ${token2}`, "content-type": "application/json" },
418
+ body: JSON.stringify({ task, comment }),
419
+ signal: AbortSignal.timeout(12e4)
420
+ });
421
+ const result = await response.json();
422
+ if (!result.ok || !result.value) throw Error(result.error ?? "The request was not accepted.");
423
+ const held4 = result.value;
424
+ if (held4.status === "cancelled") throw Error(held4.reason ?? "The request was cancelled. Ask again in a new reply.");
425
+ say(held4.status === "pending" ? `Approval pending for ${task}; it will be checked after this reply finishes.` : `Approval already committed for ${task}.`);
426
+ return { ...held4, pending: held4.status === "pending" };
427
+ } catch (e) {
428
+ return die(e instanceof Error ? e.message : "Reply approval failed.", { kind: "refused" });
401
429
  }
402
430
  }
403
- async function quietlyAsync(fn) {
404
- const before = sink;
405
- sink = { out: [], warnings: [] };
406
- try {
407
- return await fn();
408
- } finally {
409
- sink = before;
431
+ var REPLY_APPROVAL_ENV;
432
+ var init_reply_approval = __esm({
433
+ "../cli/src/lib/cloud/reply-approval.ts"() {
434
+ "use strict";
435
+ init_io();
436
+ init_paths();
437
+ REPLY_APPROVAL_ENV = "AI4KANBAN_REPLY_APPROVAL";
410
438
  }
439
+ });
440
+
441
+ // ../cli/src/lib/cloud/config.ts
442
+ function cloudEndpoints() {
443
+ return {
444
+ supabaseUrl: trimSlash(process.env.AI4KANBAN_SUPABASE_URL || SUPABASE_URL),
445
+ anonKey: process.env.AI4KANBAN_SUPABASE_ANON_KEY || SUPABASE_ANON_KEY,
446
+ api: trimSlash(process.env.AI4KANBAN_CLOUD_URL || API_URL)
447
+ };
411
448
  }
412
- function say(line = "") {
413
- const text4 = String(line);
414
- if (sink) sink.out.push(...text4.split("\n"));
415
- else console.log(text4);
416
- }
417
- function warn(message) {
418
- if (sink) sink.warnings.push(String(message));
419
- else console.error(`kanban: warning \u2014 ${message}`);
449
+ function cloudConfigured() {
450
+ const { supabaseUrl, anonKey } = cloudEndpoints();
451
+ return !!supabaseUrl && !!anonKey;
420
452
  }
421
- var BoardError, sink;
422
- var init_io = __esm({
423
- "../cli/src/lib/io.ts"() {
424
- "use strict";
425
- BoardError = class extends Error {
426
- // `kind` is the machine-readable name of the refusal (card-not-found, no-board,
427
- // unknown-module, …). It is what a caller reads; the exit code stays 1 for every
428
- // refusal, so nobody has to keep a table of numbers.
429
- kind;
430
- // Only `cloud image` / `cloud tts` set it: 2 for a usage error, as the scripts they replaced did.
431
- exitCode;
432
- // `bare` says the message is already the whole thing a person should see — a usage
433
- // block, say — so the dispatcher prints it without putting the command in front of it.
434
- bare;
435
- details;
436
- constructor(message, { kind = "refused", bare = false, exitCode = 1, ...details } = {}) {
437
- super(message);
438
- this.name = "BoardError";
439
- this.kind = kind;
440
- this.bare = bare;
441
- this.exitCode = exitCode;
442
- this.details = details;
443
- }
444
- };
445
- sink = null;
453
+ var SUPABASE_URL, SUPABASE_ANON_KEY, API_URL, trimSlash, NOT_CONFIGURED;
454
+ var init_config = __esm({
455
+ "../cli/src/lib/cloud/config.ts"() {
456
+ "use strict";
457
+ SUPABASE_URL = "https://yajrbpprmdvtkvjjfpbk.supabase.co";
458
+ SUPABASE_ANON_KEY = "sb_publishable_ioUQ23BTtoj8NKqndp0Jrw_omVR3m4n";
459
+ API_URL = "https://api.ai4kanban.dev";
460
+ trimSlash = (url) => url.replace(/\/+$/, "");
461
+ NOT_CONFIGURED = "This build of WildCrane carries no Cloud project to sign in against.";
446
462
  }
447
463
  });
448
464
 
449
- // ../cli/src/lib/machine/project.ts
450
- import { createHash } from "node:crypto";
465
+ // ../cli/src/lib/cloud/session.ts
451
466
  import fs3 from "node:fs";
452
467
  import path4 from "node:path";
453
- function realPathOf(dir) {
454
- const here = path4.resolve(dir);
455
- const rest = [];
456
- let at = here;
457
- for (; ; ) {
458
- try {
459
- return path4.join(fs3.realpathSync(at), ...rest);
460
- } catch {
461
- const up = path4.dirname(at);
462
- if (up === at) return here;
463
- rest.unshift(path4.basename(at));
464
- at = up;
465
- }
468
+ function readSession() {
469
+ let raw;
470
+ try {
471
+ raw = fs3.readFileSync(sessionFile(), "utf8");
472
+ } catch {
473
+ return null;
466
474
  }
467
- }
468
- function readableName(real2) {
469
- const here = path4.basename(real2);
470
- const up = path4.dirname(real2);
471
- if (here !== "kanban") return slug(here);
472
- return path4.basename(up) === "docs" ? slug(path4.basename(path4.dirname(up))) : slug(`${path4.basename(up)}-kanban`);
473
- }
474
- function legacyProjectStateDir(board2) {
475
- const real2 = realPathOf(board2);
476
- const id = createHash("sha256").update(real2).digest("hex").slice(0, ID_LENGTH);
477
- return path4.join(machineHome(), PROJECTS, `${readableName(real2)}-${id}`);
478
- }
479
- function stateRootOf(board2) {
480
- let dir = realPathOf(board2);
481
- for (; ; ) {
482
- if (fs3.existsSync(path4.join(dir, ".git"))) return dir;
483
- const up = path4.dirname(dir);
484
- if (up === dir) break;
485
- dir = up;
475
+ try {
476
+ const held4 = JSON.parse(raw);
477
+ if (!held4.accessToken || !held4.refreshToken || !held4.subject) return null;
478
+ if (held4.supabaseUrl !== cloudEndpoints().supabaseUrl) return null;
479
+ return { ...held4, version: 1, expiresAt: Number(held4.expiresAt) || 0 };
480
+ } catch {
481
+ return null;
486
482
  }
487
- return rootAbove(realPathOf(board2));
488
483
  }
489
- function rootAbove(board2) {
490
- const parent = path4.dirname(board2);
491
- return ["docs", ".akb"].includes(path4.basename(parent)) ? path4.dirname(parent) : parent;
484
+ function writeSession(session) {
485
+ fs3.mkdirSync(machineHome(), { recursive: true, mode: 448 });
486
+ const tmp = `${sessionFile()}.${process.pid}.tmp`;
487
+ fs3.writeFileSync(tmp, `${JSON.stringify(session, null, 2)}
488
+ `, { mode: 384 });
489
+ fs3.renameSync(tmp, sessionFile());
492
490
  }
493
- function projectStateDir(board2, root2 = stateRootOf(board2)) {
494
- const relative = path4.relative(realPathOf(root2), realPathOf(board2));
495
- if (relative === ".." || relative.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative)) {
496
- throw new Error("The board must be inside its project root.");
491
+ function clearSession() {
492
+ try {
493
+ fs3.rmSync(sessionFile());
494
+ } catch {
497
495
  }
498
- return path4.join(realPathOf(root2), ".akb", "boards", relative || "_root");
499
496
  }
500
- function ensureProjectState(board2, root2 = stateRootOf(board2)) {
501
- const dir = projectStateDir(board2, root2);
502
- if (!fs3.existsSync(dir)) {
503
- const legacy2 = legacyProjectStateDir(board2);
504
- fs3.mkdirSync(path4.dirname(dir), { recursive: true });
505
- const temporary = fs3.mkdtempSync(`${dir}.import-`);
497
+ async function accessToken() {
498
+ const held4 = readSession();
499
+ if (!held4) return { ok: false, reason: "signed-out" };
500
+ if (!expiringSoon(held4)) return { ok: true, token: held4.accessToken, session: held4 };
501
+ return refresh();
502
+ }
503
+ async function refresh() {
504
+ const lock = await takeLock();
505
+ try {
506
+ const now = readSession();
507
+ if (!now) return { ok: false, reason: "signed-out" };
508
+ if (!expiringSoon(now)) return { ok: true, token: now.accessToken, session: now };
509
+ const { api, anonKey } = cloudEndpoints();
510
+ let response;
506
511
  try {
507
- if (fs3.existsSync(legacy2)) fs3.cpSync(legacy2, temporary, {
508
- recursive: true,
509
- filter: (source) => ![".lock", ".answering"].some((suffix) => path4.basename(source).endsWith(suffix))
512
+ response = await fetch(`${api}/auth/v1/token?grant_type=refresh_token`, {
513
+ method: "POST",
514
+ headers: { apikey: anonKey, "content-type": "application/json" },
515
+ body: JSON.stringify({ refresh_token: now.refreshToken })
510
516
  });
511
- try {
512
- fs3.renameSync(temporary, dir);
513
- } catch (err) {
514
- if (!["EEXIST", "ENOTEMPTY"].includes(err.code ?? "")) throw err;
517
+ } catch (e) {
518
+ return { ok: false, reason: "unreachable", error: e instanceof Error ? e.message : String(e) };
519
+ }
520
+ if (!response.ok) {
521
+ const body = await response.json().catch(() => ({}));
522
+ if (response.status >= 500) {
523
+ return { ok: false, reason: "unreachable", error: body.error_description ?? `Cloud answered ${response.status}` };
515
524
  }
516
- } finally {
517
- fs3.rmSync(temporary, { recursive: true, force: true });
525
+ return { ok: false, reason: "expired", error: body.error_description };
518
526
  }
527
+ const fresh = sessionFrom(await response.json(), now);
528
+ if (!fresh) return { ok: false, reason: "expired" };
529
+ const current = readSession();
530
+ if (!current || current.subject !== now.subject) return { ok: false, reason: "expired" };
531
+ if (current.refreshToken !== now.refreshToken) return { ok: true, token: current.accessToken, session: current };
532
+ writeSession(fresh);
533
+ return { ok: true, token: fresh.accessToken, session: fresh };
534
+ } finally {
535
+ lock();
519
536
  }
520
- if (recordedBoard(dir) !== realPathOf(board2)) {
521
- fs3.writeFileSync(path4.join(dir, RECORD), `${JSON.stringify({ board: realPathOf(board2) })}
537
+ }
538
+ function sessionFrom(body, previous) {
539
+ const token2 = body;
540
+ const subject = token2.user?.id ?? previous?.subject;
541
+ if (!token2.access_token || !token2.refresh_token || !subject) return null;
542
+ const expiresAt = token2.expires_at ? token2.expires_at * 1e3 : Date.now() + (token2.expires_in ?? 3600) * 1e3;
543
+ return {
544
+ version: 1,
545
+ supabaseUrl: cloudEndpoints().supabaseUrl,
546
+ accessToken: token2.access_token,
547
+ refreshToken: token2.refresh_token,
548
+ expiresAt,
549
+ subject,
550
+ email: token2.user?.email ?? previous?.email,
551
+ handle: previous?.handle,
552
+ name: previous?.name,
553
+ avatarUrl: previous?.avatarUrl,
554
+ avatar: previous?.avatar
555
+ };
556
+ }
557
+ async function takeLock() {
558
+ const until = Date.now() + LOCK_WAIT_MS;
559
+ for (; ; ) {
560
+ try {
561
+ fs3.mkdirSync(machineHome(), { recursive: true, mode: 448 });
562
+ fs3.mkdirSync(lockDir());
563
+ try {
564
+ fs3.writeFileSync(lockOwner(), `${process.pid}
522
565
  `);
566
+ } catch {
567
+ }
568
+ return () => {
569
+ try {
570
+ fs3.rmSync(lockDir(), { recursive: true, force: true });
571
+ } catch {
572
+ }
573
+ };
574
+ } catch (err) {
575
+ if (err.code !== "EEXIST") throw err;
576
+ if (stale()) {
577
+ fs3.rmSync(lockDir(), { recursive: true, force: true });
578
+ continue;
579
+ }
580
+ if (Date.now() > until) return () => {
581
+ };
582
+ await sleep(LOCK_RETRY_MS);
583
+ }
523
584
  }
524
- return dir;
525
585
  }
526
- function recordedBoard(dir) {
586
+ function stale() {
587
+ let held4;
527
588
  try {
528
- const held4 = JSON.parse(fs3.readFileSync(path4.join(dir, RECORD), "utf8"));
529
- return typeof held4.board === "string" ? held4.board : null;
589
+ const pid = Number(fs3.readFileSync(lockOwner(), "utf8").trim());
590
+ held4 = Number.isInteger(pid) && pid > 0 ? pid : void 0;
530
591
  } catch {
531
- return null;
592
+ held4 = void 0;
593
+ }
594
+ if (held4 !== void 0 && !alive(held4)) return true;
595
+ try {
596
+ return Date.now() - fs3.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
597
+ } catch {
598
+ return false;
532
599
  }
533
600
  }
534
- var PROJECTS, ID_LENGTH, RECORD, SESSIONS_FILE, SESSIONS_FOLDER, ASSETS_FOLDER, MOCKUPS_FOLDER, SESSIONS_LOCK, INDEX_LOCK, UI_CONFIG_FILE, slug;
535
- var init_project = __esm({
536
- "../cli/src/lib/machine/project.ts"() {
601
+ function alive(pid) {
602
+ try {
603
+ process.kill(pid, 0);
604
+ return true;
605
+ } catch (e) {
606
+ return e.code === "EPERM";
607
+ }
608
+ }
609
+ var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep;
610
+ var init_session = __esm({
611
+ "../cli/src/lib/cloud/session.ts"() {
537
612
  "use strict";
538
613
  init_home();
539
- PROJECTS = "projects";
540
- ID_LENGTH = 10;
541
- RECORD = "board.json";
542
- SESSIONS_FILE = "sessions.json";
543
- SESSIONS_FOLDER = "sessions";
544
- ASSETS_FOLDER = "assets";
545
- MOCKUPS_FOLDER = "mockups";
546
- SESSIONS_LOCK = "sessions.lock";
547
- INDEX_LOCK = "index.lock";
548
- UI_CONFIG_FILE = "ui.config.json";
549
- slug = (text4) => text4.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "board";
614
+ init_config();
615
+ REFRESH_MARGIN_MS = 6e4;
616
+ LOCK_STALE_MS = 3e4;
617
+ LOCK_WAIT_MS = 2e4;
618
+ LOCK_RETRY_MS = 50;
619
+ sessionFile = () => path4.join(machineHome(), "session.json");
620
+ lockDir = () => path4.join(machineHome(), "session.lock");
621
+ lockOwner = () => path4.join(lockDir(), "owner");
622
+ expiringSoon = (session) => session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
623
+ sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
550
624
  }
551
625
  });
552
626
 
553
- // ../cli/src/lib/paths.ts
554
- import { spawnSync } from "node:child_process";
627
+ // ../cli/src/lib/cloud/tasks.ts
628
+ import crypto from "node:crypto";
555
629
  import fs4 from "node:fs";
556
630
  import path5 from "node:path";
557
- function boardLockName(kanban, root2) {
558
- const from = path5.relative(root2, kanban);
559
- const name = from && !from.startsWith("..") ? from : path5.basename(kanban);
560
- return `${name.split(path5.sep).join("-")}.lock`;
561
- }
562
- function ensureAkbDir() {
563
- fs4.mkdirSync(AKB_DIR, { recursive: true });
564
- writeRootIgnoreIfMissing();
565
- return AKB_DIR;
631
+ function workspaceTask() {
632
+ const id = process.env[TASK_ENV];
633
+ return id && id.trim() ? id.trim() : null;
566
634
  }
567
- function writeRootIgnoreIfMissing() {
568
- const text4 = fs4.existsSync(ROOT_GITIGNORE) ? fs4.readFileSync(ROOT_GITIGNORE, "utf8") : "";
569
- if (text4.split("\n").some((line) => line.trim() === AKB_IGNORE_LINE)) return false;
570
- const ignored = spawnSync("git", ["-C", REPO_ROOT, "check-ignore", "-q", AKB_IGNORE_LINE], { stdio: "ignore" }).status;
571
- if (ignored === 0 || ignored === 128 && KANBAN.startsWith(AKB_DIR + path5.sep)) return false;
572
- const separator = !text4 || text4.endsWith("\n") ? "" : "\n";
573
- const block = `# Delivery state \u2014 worktrees and the like. Never committed.
574
- ${AKB_IGNORE_LINE}
575
- `;
576
- fs4.writeFileSync(ROOT_GITIGNORE, `${text4}${separator}${block}`);
577
- return true;
635
+ function cloudStudio(name) {
636
+ if (/^wf-/.test(name)) return name.replace("-", "_");
637
+ return `wf_builtin_${name.replace(/-/g, "_")}`;
578
638
  }
579
- function projectRootOf(board2) {
580
- let dir = path5.resolve(board2);
581
- for (; ; ) {
582
- if (fs4.existsSync(path5.join(dir, ".git"))) return dir;
583
- const up = path5.dirname(dir);
584
- if (up === dir) return rootAbove(path5.resolve(board2));
585
- dir = up;
639
+ async function call(method, route2, body, key) {
640
+ if (!cloudConfigured()) return { ok: false, error: NOT_CONFIGURED, code: "bad_request" };
641
+ const token2 = await accessToken();
642
+ if (!token2.ok) {
643
+ 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" };
586
644
  }
645
+ let response;
646
+ try {
647
+ response = await fetch(`${cloudEndpoints().api}${route2}`, {
648
+ method,
649
+ headers: {
650
+ authorization: `Bearer ${token2.token}`,
651
+ ...body ? { "content-type": "application/json" } : {},
652
+ ...key ? { "idempotency-key": key } : {}
653
+ },
654
+ ...body ? { body: JSON.stringify(body) } : {},
655
+ signal: AbortSignal.timeout(2e4)
656
+ });
657
+ } catch (e) {
658
+ return { ok: false, error: `Cloud could not be reached: ${e instanceof Error ? e.message : String(e)}` };
659
+ }
660
+ const parsed = await response.json().catch(() => ({}));
661
+ if (!response.ok) return { ok: false, code: parsed.error?.code ?? "refused", error: parsed.error?.message ?? `Cloud answered ${response.status}.` };
662
+ return { ok: true, value: parsed, replayed: response.headers.get("idempotent-replayed") === "true" };
587
663
  }
588
- function setBoard(kanban, root2, flag) {
589
- REPO_ROOT = path5.resolve(root2);
590
- KANBAN = path5.resolve(kanban);
591
- BOARD_FLAG = flag;
592
- TODO = path5.join(KANBAN, "todo");
593
- ARCHIVE = path5.join(KANBAN, ".archive");
594
- ARCHIVE_MD = path5.join(KANBAN, "archive.md");
595
- README = path5.join(TODO, "README.md");
596
- MODULES_MD = path5.join(KANBAN, "modules.md");
597
- CONFIG = path5.join(KANBAN, "config.md");
598
- KANBAN_GITIGNORE = path5.join(KANBAN, ".gitignore");
599
- RELEASES = path5.join(KANBAN, "releases.md");
600
- RELEASE_SUMMARIES = path5.join(KANBAN, ".release-summaries");
601
- AGENTS = path5.join(KANBAN, "agents");
602
- STUDIOS = path5.join(KANBAN, "studios");
603
- LEGACY_AGENTS = path5.join(KANBAN, "skills");
604
- MEMORY = path5.join(KANBAN, "memory");
605
- AGENT_MEMORY = path5.join(MEMORY, "agents");
606
- PROJECT_MD = path5.join(MEMORY, "project.md");
607
- LEGACY_UI_CONFIG = path5.join(KANBAN, UI_CONFIG_FILE);
608
- LOCAL_CONFIG = path5.join(KANBAN, ".local.json");
609
- ENV_FILE = path5.join(KANBAN, ".env");
610
- const machine = projectStateDir(KANBAN, REPO_ROOT);
611
- BOARD_STATE = machine;
612
- UI_CONFIG = path5.join(machine, UI_CONFIG_FILE);
613
- ASSETS = path5.join(machine, ASSETS_FOLDER);
614
- MOCKUPS = path5.join(machine, MOCKUPS_FOLDER);
615
- SESSIONS = path5.join(machine, SESSIONS_FILE);
616
- SESSIONS_DIR = path5.join(machine, SESSIONS_FOLDER);
617
- SESSIONS_LOCK2 = path5.join(machine, SESSIONS_LOCK);
618
- INDEX_LOCK2 = path5.join(machine, INDEX_LOCK);
619
- DELIVERIES = path5.join(KANBAN, "deliveries");
620
- RULES = path5.join(KANBAN, "rules");
621
- PLANS = path5.join(machine, "plans");
622
- PLANS_ARCHIVE = path5.join(PLANS, "archive");
623
- TRIAGE = path5.join(KANBAN, "triage");
624
- SIGNALS_ARCHIVED = path5.join(TRIAGE, "archived");
625
- SIGNALS_DISMISSED = path5.join(TRIAGE, "dismissed");
626
- SIGNALS_FILES = path5.join(TRIAGE, "files");
627
- SIGNALS_OLD_INBOX = path5.join(TRIAGE, "inbox");
628
- SIGNALS_OLD_HANDLED = path5.join(TRIAGE, "handled.md");
629
- AKB_DIR = path5.join(REPO_ROOT, ".akb");
630
- ROOT_GITIGNORE = path5.join(REPO_ROOT, ".gitignore");
631
- LOCK = path5.join(AKB_DIR, boardLockName(KANBAN, REPO_ROOT));
632
- return REPO_ROOT;
633
- }
634
- function setBoardRoot(root2, named2 = false) {
635
- const project2 = path5.resolve(root2);
636
- return setBoard(path5.join(project2, "docs", "kanban"), project2, named2 ? ` --dir ${project2}` : "");
637
- }
638
- function setBoardDir(board2, root2) {
639
- const folder = path5.resolve(board2);
640
- return setBoard(folder, root2 ?? projectRootOf(folder), ` --board ${folder}`);
664
+ async function createTask(from, said2) {
665
+ const source = await call("GET", `/v1/tasks/${encodeURIComponent(from)}`);
666
+ if (!source.ok) return source;
667
+ const studio = said2.studio ? cloudStudio(said2.studio) : source.value.studio?.id;
668
+ const body = {
669
+ title: said2.title,
670
+ project: source.value.project,
671
+ ...studio ? { studio } : {},
672
+ ...said2.request?.trim() ? { request: said2.request.trim() } : {},
673
+ source: "api",
674
+ source_context: { task: from, ...said2.agent ? { agent: said2.agent } : {} },
675
+ ...said2.run ? { run: true } : {},
676
+ ...said2.metadata && Object.keys(said2.metadata).length ? { metadata: said2.metadata } : {},
677
+ ...said2.triage ? { triage: `tri_${source.value.project.replace(/^prj_/, "")}_${said2.triage}` } : {}
678
+ };
679
+ const key = `akb-${crypto.createHash("sha256").update(`${from}
680
+ ${said2.slug?.trim() || said2.title}`).digest("hex").slice(0, 40)}`;
681
+ const made = await call("POST", "/v1/tasks", body, key);
682
+ if (!made.ok) return made;
683
+ const number = numberOf(made.value.key);
684
+ if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
685
+ return { ok: true, value: { task: made.value, number, from: source.value, replayed: made.replayed === true } };
641
686
  }
642
- function die(msg, kind) {
643
- throw new BoardError(msg, typeof kind === "string" ? { kind } : kind);
687
+ function runnerProject(board2) {
688
+ if (path5.basename(board2) !== "kanban" || path5.basename(path5.dirname(board2)) !== ".akb") return null;
689
+ const linked2 = linkedProject(board2, path5.dirname(path5.dirname(board2)));
690
+ return linked2.ok ? linked2.value : null;
644
691
  }
645
- function warn2(msg) {
646
- warn(msg);
692
+ function linkedProject(board2, root2) {
693
+ const file = path5.join(root2, ".akb", "base.json");
694
+ if (!fs4.existsSync(file)) return { ok: true, value: null };
695
+ try {
696
+ const base = JSON.parse(fs4.readFileSync(file, "utf8"));
697
+ 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();
698
+ const projects = new Set(Object.keys(base.files ?? {}).flatMap((p) => /^projects\/([^/]+)\//.exec(p)?.[1] ?? []));
699
+ if (typeof base.project === "string") projects.add(base.project);
700
+ if (projects.size !== 1) throw new Error();
701
+ return { ok: true, value: [...projects][0] };
702
+ } catch {
703
+ return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
704
+ }
647
705
  }
648
- function boardPath() {
649
- return rel(KANBAN).split(path5.sep).join("/");
706
+ async function creationProject(board2, root2, task = workspaceTask()) {
707
+ const link2 = linkedProject(board2, root2);
708
+ if (!link2.ok) return link2;
709
+ let project2 = link2.value;
710
+ if (task) {
711
+ const source = await call("GET", `/v1/tasks/${encodeURIComponent(task)}`);
712
+ if (!source.ok) return {
713
+ ...source,
714
+ 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
715
+ };
716
+ if (project2 && project2 !== source.value.project) return { ok: false, error: "The source task conflicts with this board\u2019s project link.", code: "invalid-link" };
717
+ project2 = source.value.project;
718
+ }
719
+ if (!project2) return { ok: false, error: "This board is not linked to a Cloud project.", code: "unlinked" };
720
+ const checked = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
721
+ return checked.ok ? { ok: true, value: project2 } : checked;
650
722
  }
651
- function boardText(text4) {
652
- const posix = (p) => rel(p).split(path5.sep).join("/");
653
- const swaps = [
654
- [ASSETS_PATH_IN_TEXT, posix(ASSETS)],
655
- [MOCKUPS_PATH_IN_TEXT, posix(MOCKUPS)],
656
- [BOARD_STATE_IN_TEXT, posix(BOARD_STATE)],
657
- [BOARD_PATH_IN_TEXT, boardPath()]
658
- ];
659
- const swap = (part, i) => i === swaps.length ? part : part.split(swaps[i][0]).map((p) => swap(p, i + 1)).join(swaps[i][1]);
660
- return swap(text4, 0);
723
+ async function createProjectTask(project2, said2, key) {
724
+ const made = await call("POST", "/v1/tasks", {
725
+ title: said2.title,
726
+ project: project2,
727
+ source: "api",
728
+ ...said2.studio ? { studio: cloudStudio(said2.studio) } : {},
729
+ ...said2.request?.trim() ? { request: said2.request.trim() } : {},
730
+ ...said2.agent ? { source_context: { agent: said2.agent } } : {},
731
+ ...said2.triage ? { triage: `tri_${project2.replace(/^prj_/, "")}_${said2.triage}` } : {}
732
+ }, key);
733
+ if (!made.ok) return made;
734
+ const number = numberOf(made.value.key);
735
+ if (!Number.isInteger(number)) return { ok: false, error: `Cloud answered a task with no number: ${made.value.key}`, code: "refused" };
736
+ return { ok: true, value: { task: made.value, number } };
661
737
  }
662
- function useProjectState() {
663
- ensureAkbDir();
664
- return ensureProjectState(KANBAN, REPO_ROOT);
738
+ async function approveTask(project2, number) {
739
+ const held4 = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
740
+ if (!held4.ok) return held4;
741
+ const key = `${held4.value.prefix}-${number}`;
742
+ const task = await call("GET", `/v1/tasks/${encodeURIComponent(key)}`);
743
+ if (!task.ok) return task;
744
+ const revision = task.value.review?.revision;
745
+ const decided = await call("POST", `/v1/tasks/${encodeURIComponent(key)}/decisions`, {
746
+ decision: "approve",
747
+ ...revision !== void 0 ? { review_revision: revision } : {}
748
+ });
749
+ return decided.ok ? { ok: true, value: { key } } : decided;
665
750
  }
666
- 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;
667
- var init_paths = __esm({
668
- "../cli/src/lib/paths.ts"() {
751
+ var TASK_ENV, numberOf;
752
+ var init_tasks = __esm({
753
+ "../cli/src/lib/cloud/tasks.ts"() {
669
754
  "use strict";
670
- init_io();
671
- init_project();
672
- REPO_ROOT = "";
673
- KANBAN = "";
674
- TODO = "";
675
- ARCHIVE = "";
676
- REJECTIONS_TO_REVIEW = ".sync";
677
- ARCHIVE_MD = "";
678
- README = "";
679
- MODULES_MD = "";
680
- CONFIG = "";
681
- KANBAN_GITIGNORE = "";
682
- RELEASES = "";
683
- RELEASE_SUMMARIES = "";
684
- AGENTS = "";
685
- STUDIOS = "";
686
- LEGACY_AGENTS = "";
687
- ASSETS = "";
688
- BOARD_STATE = "";
689
- MOCKUPS = "";
690
- MEMORY = "";
691
- AGENT_MEMORY = "";
692
- PROJECT_MD = "";
693
- LOCK = "";
694
- UI_CONFIG = "";
695
- LEGACY_UI_CONFIG = "";
696
- LOCAL_CONFIG = "";
697
- ENV_FILE = "";
698
- SESSIONS = "";
699
- SESSIONS_DIR = "";
700
- SESSIONS_LOCK2 = "";
701
- INDEX_LOCK2 = "";
702
- DELIVERIES = "";
703
- PLANS = "";
704
- PLANS_ARCHIVE = "";
705
- RULES = "";
706
- TRIAGE = "";
707
- SIGNALS_ARCHIVED = "";
708
- SIGNALS_DISMISSED = "";
709
- SIGNALS_FILES = "";
710
- SIGNALS_OLD_INBOX = "";
711
- SIGNALS_OLD_HANDLED = "";
712
- AKB_DIR = "";
713
- ROOT_GITIGNORE = "";
714
- AKB_IGNORE_LINE = ".akb/";
715
- BOARD_FLAG = "";
716
- setBoardRoot(process.cwd());
717
- rel = (p) => {
718
- const from = path5.relative(REPO_ROOT, p);
719
- if (!from) return p;
720
- return from.startsWith("..") ? p : from;
721
- };
722
- BOARD_PATH_IN_TEXT = "docs/kanban";
723
- ASSETS_PATH_IN_TEXT = "docs/kanban/.assets";
724
- MOCKUPS_PATH_IN_TEXT = "docs/kanban/.mockups";
725
- BOARD_STATE_IN_TEXT = "<board-state>";
755
+ init_config();
756
+ init_session();
757
+ TASK_ENV = "AI4KANBAN_TASK";
758
+ numberOf = (key) => Number(/-(\d+)$/.exec(key)?.[1] ?? NaN);
726
759
  }
727
760
  });
728
761
 
@@ -823,8 +856,8 @@ var init_question_block = __esm({
823
856
  // ../cli/src/lib/view/rules.ts
824
857
  function creationRefusal(id, creation, what, discard = false) {
825
858
  if (!creation || creation.state === "unfinished" && discard) return null;
826
- const run2 = creation.runId.slice(0, 8);
827
- 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.`;
859
+ const run3 = creation.runId.slice(0, 8);
860
+ 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.`;
828
861
  }
829
862
  function hasOptions(q) {
830
863
  return Array.isArray(q.options) && q.options.length > 0;
@@ -1634,6 +1667,8 @@ async function act(id, route2, body, done2) {
1634
1667
  return value;
1635
1668
  }
1636
1669
  async function taskApprove(id, comment) {
1670
+ const deferred = await approveAfterReply(id, comment);
1671
+ if (deferred) return deferred;
1637
1672
  const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id))}`);
1638
1673
  return act(task.key, "decisions", {
1639
1674
  decision: "approve",
@@ -1687,6 +1722,7 @@ var refuse2, enc, WEB, taskUrl, projectLine, taskChat, taskRemove, taskResume, t
1687
1722
  var init_task = __esm({
1688
1723
  "../cli/src/commands/task.ts"() {
1689
1724
  "use strict";
1725
+ init_reply_approval();
1690
1726
  init_config();
1691
1727
  init_session();
1692
1728
  init_tasks();
@@ -2639,11 +2675,11 @@ function checkHarnesses(harnesses) {
2639
2675
  if (providers.length > 1) {
2640
2676
  throw new Error(`harness "${harness.name}": a connector declares one provider list, not ${providers.length}`);
2641
2677
  }
2642
- const list = providers[0];
2643
- if (!list) continue;
2644
- if (!list.providers?.length) throw new Error(`harness "${harness.name}": the provider setting "${list.key}" offers no providers`);
2678
+ const list2 = providers[0];
2679
+ if (!list2) continue;
2680
+ if (!list2.providers?.length) throw new Error(`harness "${harness.name}": the provider setting "${list2.key}" offers no providers`);
2645
2681
  const ids = /* @__PURE__ */ new Set();
2646
- for (const provider of list.providers) {
2682
+ for (const provider of list2.providers) {
2647
2683
  if (ids.has(provider.id)) throw new Error(`harness "${harness.name}": two providers share the id "${provider.id}"`);
2648
2684
  ids.add(provider.id);
2649
2685
  for (const need of [...provider.needs, ...provider.preferWhenSet ?? []]) {
@@ -2656,8 +2692,8 @@ function checkHarnesses(harnesses) {
2656
2692
  if (!provider.needs.includes(key)) throw new Error(`harness "${harness.name}": the provider "${provider.id}" renames the variable of "${key}" without needing it`);
2657
2693
  }
2658
2694
  }
2659
- if (list.defaultProvider && !ids.has(list.defaultProvider)) {
2660
- throw new Error(`harness "${harness.name}": the default provider "${list.defaultProvider}" isn't on the list`);
2695
+ if (list2.defaultProvider && !ids.has(list2.defaultProvider)) {
2696
+ throw new Error(`harness "${harness.name}": the default provider "${list2.defaultProvider}" isn't on the list`);
2661
2697
  }
2662
2698
  }
2663
2699
  }
@@ -2905,9 +2941,9 @@ function copyEnv(file, given = process.env) {
2905
2941
  function probe(file) {
2906
2942
  const key = keyOf(file);
2907
2943
  const start = spawnable(file, ["--version"], { ...probeOptions(file), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
2908
- const run2 = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
2909
- const code = run2.error?.code;
2910
- const answer2 = { key, at: Date.now(), ...judge(code, run2.status, run2.stdout ?? "", run2.stderr ?? "") };
2944
+ const run3 = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
2945
+ const code = run3.error?.code;
2946
+ const answer2 = { key, at: Date.now(), ...judge(code, run3.status, run3.stdout ?? "", run3.stderr ?? "") };
2911
2947
  keep(file, answer2);
2912
2948
  return answer2;
2913
2949
  }
@@ -3061,8 +3097,8 @@ function createEventCollector() {
3061
3097
  case "tool_call_update": {
3062
3098
  const id = str(u.toolCallId);
3063
3099
  if (todoCalls.has(id)) {
3064
- const list = obj(u.rawInput).todos;
3065
- if (Array.isArray(list) && !str(obj(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list) } });
3100
+ const list2 = obj(u.rawInput).todos;
3101
+ if (Array.isArray(list2) && !str(obj(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list2) } });
3066
3102
  return;
3067
3103
  }
3068
3104
  release(id, targetIn(u));
@@ -3242,10 +3278,10 @@ function failedWith(ev) {
3242
3278
  return str(ev.result).trim() || "the agent reported the session failed";
3243
3279
  }
3244
3280
  function denials(ev) {
3245
- const list = Array.isArray(ev.permission_denials) ? ev.permission_denials : [];
3246
- const names3 = [...new Set(list.map((raw) => str(obj(raw).tool_name)).filter(Boolean))];
3281
+ const list2 = Array.isArray(ev.permission_denials) ? ev.permission_denials : [];
3282
+ const names3 = [...new Set(list2.map((raw) => str(obj(raw).tool_name)).filter(Boolean))];
3247
3283
  if (!names3.length) return "";
3248
- return `[refused] ${list.length} tool call${list.length === 1 ? "" : "s"} were not allowed: ${names3.join(", ")}
3284
+ return `[refused] ${list2.length} tool call${list2.length === 1 ? "" : "s"} were not allowed: ${names3.join(", ")}
3249
3285
  `;
3250
3286
  }
3251
3287
  function promptSize(raw) {
@@ -3429,6 +3465,48 @@ var init_claude_stream = __esm({
3429
3465
  }
3430
3466
  });
3431
3467
 
3468
+ // ../cli/src/lib/agent/wire/background.ts
3469
+ function createBackgroundTasks() {
3470
+ const tasks = /* @__PURE__ */ new Map();
3471
+ return {
3472
+ update(id, status, result = "") {
3473
+ if (!id) return false;
3474
+ const previous = tasks.get(id);
3475
+ if (previous?.status === status && previous.result === result) return false;
3476
+ tasks.set(id, { status, result });
3477
+ return true;
3478
+ },
3479
+ results: () => [...tasks].map(([id, task]) => ({ id, ...task })),
3480
+ running: () => [...tasks].filter(([, t]) => t.status === "running").map(([id]) => id),
3481
+ count: () => [...tasks.values()].filter((t) => t.status === "running").length,
3482
+ failure: () => [...tasks].filter(([, t]) => t.status === "failed").map(([id, t]) => t.result || `Background task ${id} failed.`).join("\n") || void 0
3483
+ };
3484
+ }
3485
+ function streamFinished(stream) {
3486
+ if (stream.background?.()) return false;
3487
+ const turns = stream.turns?.();
3488
+ return turns ? !!turns.length && !turns.at(-1).background : stream.result() !== void 0;
3489
+ }
3490
+ function createBackgroundWait(milliseconds, expired) {
3491
+ let timer;
3492
+ return {
3493
+ pending() {
3494
+ if (!timer && milliseconds > 0) timer = setTimeout(expired, milliseconds);
3495
+ },
3496
+ close() {
3497
+ clearTimeout(timer);
3498
+ timer = void 0;
3499
+ }
3500
+ };
3501
+ }
3502
+ var backgroundWaitMessage;
3503
+ var init_background = __esm({
3504
+ "../cli/src/lib/agent/wire/background.ts"() {
3505
+ "use strict";
3506
+ backgroundWaitMessage = (minutes) => `the agent's background tasks did not finish within ${minutes / 60} hours, so the run was ended.`;
3507
+ }
3508
+ });
3509
+
3432
3510
  // ../cli/src/lib/agent/wire/codex-session.ts
3433
3511
  import { readFileSync, readdirSync, statSync } from "node:fs";
3434
3512
  import { homedir } from "node:os";
@@ -3713,6 +3791,31 @@ function createCodexStreamRenderer(carried = false) {
3713
3791
  let lookedAt = 0;
3714
3792
  const events = createEventCollector();
3715
3793
  const started = /* @__PURE__ */ new Set();
3794
+ const background = createBackgroundTasks();
3795
+ const subagents = /* @__PURE__ */ new Set();
3796
+ const collabItems = /* @__PURE__ */ new Set();
3797
+ const collab = (item, done2) => {
3798
+ if (item.type !== "collab_tool_call") return;
3799
+ const key = `${str(item.id)}:${done2}`;
3800
+ if (collabItems.has(key)) return;
3801
+ collabItems.add(key);
3802
+ for (const [id, raw] of Object.entries(obj(item.agents_states))) {
3803
+ const state = obj(raw);
3804
+ const status = str(state.status);
3805
+ if (!["pending_init", "running", "completed", "interrupted", "errored", "shutdown", "not_found"].includes(status)) continue;
3806
+ const previous = background.results().find((t) => t.id === id);
3807
+ if (["shutdown", "not_found"].includes(status) && previous && previous.status !== "running") continue;
3808
+ if (!subagents.has(id)) {
3809
+ subagents.add(id);
3810
+ events.subagent(`agent:${id}`, str(item.prompt) || "Agent");
3811
+ }
3812
+ const running = status === "pending_init" || status === "running";
3813
+ const failed = !running && status !== "completed";
3814
+ if (background.update(id, running ? "running" : failed ? "failed" : "completed", str(state.message)) && !running) {
3815
+ events.toolResult(`agent:${id}`, failed ? "failed" : "completed", str(state.message));
3816
+ }
3817
+ }
3818
+ };
3716
3819
  const look = (now) => {
3717
3820
  if (!threadId) return;
3718
3821
  const at = Date.now();
@@ -3739,6 +3842,7 @@ function createCodexStreamRenderer(carried = false) {
3739
3842
  if (!threadId) threadId = str(ev.thread_id).trim() || void 0;
3740
3843
  return "";
3741
3844
  case "item.started":
3845
+ collab(obj(ev.item), false);
3742
3846
  itemEvents(events, started, obj(ev.item), false);
3743
3847
  return renderStarted(obj(ev.item));
3744
3848
  case "item.updated":
@@ -3746,6 +3850,7 @@ function createCodexStreamRenderer(carried = false) {
3746
3850
  return "";
3747
3851
  case "item.completed": {
3748
3852
  const item = obj(ev.item);
3853
+ collab(item, true);
3749
3854
  if (item.type === "mcp_tool_call" && !/view_image|read_image|open_image/.test(str(item.tool))) {
3750
3855
  const content = obj(item.result).content;
3751
3856
  for (const block of Array.isArray(content) ? content : []) {
@@ -3817,7 +3922,8 @@ function createCodexStreamRenderer(carried = false) {
3817
3922
  // whose rates the board knows.
3818
3923
  costUsd: () => priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own()),
3819
3924
  resumeId: () => threadId,
3820
- failure: () => failure,
3925
+ failure: () => failure ?? background.failure(),
3926
+ background: () => subagents.size ? background.count() : void 0,
3821
3927
  events: events.events
3822
3928
  };
3823
3929
  }
@@ -3825,6 +3931,7 @@ var imageSafeText, CALLS, LOOK_EVERY_MS;
3825
3931
  var init_codex_stream = __esm({
3826
3932
  "../cli/src/lib/agent/wire/codex-stream.ts"() {
3827
3933
  "use strict";
3934
+ init_background();
3828
3935
  init_codex_session();
3829
3936
  init_events();
3830
3937
  init_json();
@@ -4080,6 +4187,27 @@ var init_kimi_stream = __esm({
4080
4187
  }
4081
4188
  });
4082
4189
 
4190
+ // ../cli/src/lib/shared/conversation.ts
4191
+ function bounded(work, ms, reason) {
4192
+ return new Promise((resolve2, reject) => {
4193
+ const timer = setTimeout(() => reject(new Error(reason)), Math.max(0, ms));
4194
+ work.then((value) => {
4195
+ clearTimeout(timer);
4196
+ resolve2(value);
4197
+ }, (error) => {
4198
+ clearTimeout(timer);
4199
+ reject(error);
4200
+ });
4201
+ });
4202
+ }
4203
+ var CONVERSATION_MS;
4204
+ var init_conversation = __esm({
4205
+ "../cli/src/lib/shared/conversation.ts"() {
4206
+ "use strict";
4207
+ CONVERSATION_MS = { send: 15e3, claim: 3e4, prepare: 6e4, start: 15e3, startup: 12e4, quiet: 6e4, stop: 1e4 };
4208
+ }
4209
+ });
4210
+
4083
4211
  // ../cli/src/lib/agent/wire/rpc.ts
4084
4212
  function connect(stdout, stdin, onCall, dialect = {}) {
4085
4213
  let buf = "";
@@ -4138,6 +4266,9 @@ function connect(stdout, stdin, onCall, dialect = {}) {
4138
4266
  send({ id, method, params });
4139
4267
  });
4140
4268
  },
4269
+ notify(method, params = {}) {
4270
+ send({ method, params });
4271
+ },
4141
4272
  /** Answer something the agent asked us. */
4142
4273
  reply(id, result) {
4143
4274
  send({ id, result });
@@ -4223,8 +4354,8 @@ var init_package = __esm({
4223
4354
  "../cli/package.json"() {
4224
4355
  package_default = {
4225
4356
  name: "wildcrane",
4226
- version: "0.11.44",
4227
- akbContract: 11,
4357
+ version: "0.11.45",
4358
+ akbContract: 12,
4228
4359
  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.",
4229
4360
  keywords: [
4230
4361
  "kanban",
@@ -4315,23 +4446,23 @@ function saidBy(update2) {
4315
4446
  function modelOf(answer2) {
4316
4447
  const current = str(obj(answer2.models).currentModelId).trim();
4317
4448
  if (current) return modelsIn(answer2).find((m) => m.modelId === current)?.name ?? current;
4318
- const list = Array.isArray(answer2.configOptions) ? answer2.configOptions : [];
4319
- for (const raw of list) {
4449
+ const list2 = Array.isArray(answer2.configOptions) ? answer2.configOptions : [];
4450
+ for (const raw of list2) {
4320
4451
  const option = obj(raw);
4321
4452
  if (option.id === "model") return str(option.currentValue).trim() || void 0;
4322
4453
  }
4323
4454
  return void 0;
4324
4455
  }
4325
4456
  function modelsIn(answer2) {
4326
- const list = obj(answer2.models).availableModels;
4327
- return (Array.isArray(list) ? list : []).map(obj).flatMap((m) => {
4457
+ const list2 = obj(answer2.models).availableModels;
4458
+ return (Array.isArray(list2) ? list2 : []).map(obj).flatMap((m) => {
4328
4459
  const modelId = str(m.modelId);
4329
4460
  return modelId ? [{ modelId, name: str(m.name) || modelId }] : [];
4330
4461
  });
4331
4462
  }
4332
4463
  function pickedModel(answer2, wanted) {
4333
- const list = modelsIn(answer2);
4334
- return list.find((m) => m.modelId === wanted) ?? list.find((m) => m.name === wanted || m.modelId.split("[")[0] === wanted);
4464
+ const list2 = modelsIn(answer2);
4465
+ return list2.find((m) => m.modelId === wanted) ?? list2.find((m) => m.name === wanted || m.modelId.split("[")[0] === wanted);
4335
4466
  }
4336
4467
  function usageOf2(value, grossInput = false) {
4337
4468
  const usage3 = obj(value);
@@ -4378,6 +4509,11 @@ function createAcpClient(options = {}) {
4378
4509
  }
4379
4510
  async function oneTurn(io, options) {
4380
4511
  const tail = createTail(io.log);
4512
+ const preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
4513
+ const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
4514
+ let started = false;
4515
+ let contentAt = 0;
4516
+ let currentSession = "";
4381
4517
  const events = createEventCollector();
4382
4518
  const emit = () => {
4383
4519
  for (const e of events.events()) io.event?.(e);
@@ -4390,7 +4526,16 @@ async function oneTurn(io, options) {
4390
4526
  io.stdin,
4391
4527
  (msg) => {
4392
4528
  if (msg.method === "session/update") {
4393
- if (live) {
4529
+ if (live && (!obj(msg.params).sessionId || obj(msg.params).sessionId === currentSession)) {
4530
+ const kind = str(obj(obj(msg.params).update).sessionUpdate);
4531
+ if (!started && ["agent_message_chunk", "tool_call", "plan"].includes(kind)) {
4532
+ started = true;
4533
+ phase("started");
4534
+ }
4535
+ if (kind === "agent_message_chunk" && Date.now() - contentAt >= 1e3) {
4536
+ contentAt = Date.now();
4537
+ io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
4538
+ }
4394
4539
  update(obj(msg.params).update, tail, (usd) => costUsd = usd, (window) => context = window);
4395
4540
  events.update(obj(msg.params).update);
4396
4541
  emit();
@@ -4418,20 +4563,22 @@ async function oneTurn(io, options) {
4418
4563
  );
4419
4564
  try {
4420
4565
  const mcpServers = options.mcpConfig ? mcpServersIn(options.mcpConfig) : [];
4421
- await rpc.call("initialize", {
4566
+ phase("preparing");
4567
+ await bounded(rpc.call("initialize", {
4422
4568
  protocolVersion: PROTOCOL_VERSION,
4423
4569
  clientCapabilities: CLIENT_CAPABILITIES,
4424
4570
  clientInfo: { name: "ai4kanban", version: SKILL_VERSION }
4425
- });
4571
+ }), preparingUntil - Date.now(), "ACP initialize timed out.");
4572
+ phase("initialized");
4426
4573
  let sessionId = io.resumeId ?? "";
4427
4574
  let prompt = io.prompt;
4428
4575
  let opened;
4429
4576
  if (sessionId) {
4430
4577
  try {
4431
- opened = await rpc.call("session/load", { sessionId, cwd: io.cwd, mcpServers });
4578
+ opened = await bounded(rpc.call("session/load", { sessionId, cwd: io.cwd, mcpServers }), preparingUntil - Date.now(), "ACP session/load timed out.");
4432
4579
  } catch (e) {
4433
4580
  if (!sessionGone(e) || !io.restartPrompt) throw e;
4434
- const fresh = await newSession(rpc, io.cwd, mcpServers);
4581
+ const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
4435
4582
  opened = fresh.opened;
4436
4583
  sessionId = fresh.sessionId;
4437
4584
  prompt = io.restartPrompt;
@@ -4441,7 +4588,7 @@ async function oneTurn(io, options) {
4441
4588
  emit();
4442
4589
  }
4443
4590
  } else {
4444
- const fresh = await newSession(rpc, io.cwd, mcpServers);
4591
+ const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
4445
4592
  opened = fresh.opened;
4446
4593
  sessionId = fresh.sessionId;
4447
4594
  io.gotResumeId(sessionId);
@@ -4450,11 +4597,15 @@ async function oneTurn(io, options) {
4450
4597
  if (options.model) {
4451
4598
  const listed = obj(opened.models).currentModelId !== void 0;
4452
4599
  const picked = listed ? pickedModel(opened, options.model) : void 0;
4453
- const set = listed ? await rpc.call("session/set_model", { sessionId, modelId: picked?.modelId ?? options.model }) : await rpc.call("session/set_config_option", { sessionId, configId: "model", value: options.model });
4600
+ const set = listed ? await bounded(rpc.call("session/set_model", { sessionId, modelId: picked?.modelId ?? options.model }), preparingUntil - Date.now(), "ACP session/set_model timed out.") : await bounded(rpc.call("session/set_config_option", { sessionId, configId: "model", value: options.model }), preparingUntil - Date.now(), "ACP session/set_config_option timed out.");
4454
4601
  model = picked?.name ?? modelOf(set) ?? options.model;
4455
4602
  }
4456
4603
  if (model) io.gotModel(model);
4604
+ if (Date.now() >= preparingUntil) throw Error("ACP preparation timed out.");
4605
+ phase("ready");
4606
+ currentSession = sessionId;
4457
4607
  live = true;
4608
+ phase("submitted");
4458
4609
  const done2 = await rpc.call("session/prompt", {
4459
4610
  sessionId,
4460
4611
  prompt: [{ type: "text", text: prompt }]
@@ -4535,6 +4686,7 @@ var PROTOCOL_VERSION, CLIENT_CAPABILITIES, INVALID_PARAMS, RESTARTED, TICKS_PER_
4535
4686
  var init_acp = __esm({
4536
4687
  "../cli/src/lib/agent/wire/acp.ts"() {
4537
4688
  "use strict";
4689
+ init_conversation();
4538
4690
  init_events();
4539
4691
  init_json();
4540
4692
  init_rpc();
@@ -4844,6 +4996,370 @@ var init_zcode = __esm({
4844
4996
  }
4845
4997
  });
4846
4998
 
4999
+ // ../cli/src/lib/agent/wire/codex.ts
5000
+ function createCodexConnection(argv) {
5001
+ const execAt = argv.indexOf("exec");
5002
+ if (execAt < 1) return void 0;
5003
+ const server = [argv[0], "app-server"];
5004
+ const options = { images: [] };
5005
+ const roots = [];
5006
+ for (let i = 1; i < argv.length; i++) {
5007
+ if (i === execAt) continue;
5008
+ const arg = argv[i];
5009
+ const [flag, inline] = arg.split(/=(.*)/s);
5010
+ const value = () => inline ?? argv[++i];
5011
+ if (["--json", "--experimental-json", "--skip-git-repo-check"].includes(arg)) continue;
5012
+ if (["-c", "--config", "--enable", "--disable"].includes(flag)) {
5013
+ const v = value();
5014
+ if (!v) return void 0;
5015
+ server.push(flag, v);
5016
+ } else if (["-m", "--model", "-s", "--sandbox"].includes(flag)) {
5017
+ const v = value();
5018
+ if (!v) return void 0;
5019
+ server.push("-c", `${flag === "-m" || flag === "--model" ? "model" : "sandbox_mode"}=${JSON.stringify(v)}`);
5020
+ } else if (arg === "--dangerously-bypass-approvals-and-sandbox") {
5021
+ server.push("-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"');
5022
+ } else if (arg === "--full-auto") {
5023
+ server.push("-c", 'approval_policy="on-request"', "-c", 'sandbox_mode="workspace-write"');
5024
+ } else if (flag === "--add-dir") {
5025
+ const v = value();
5026
+ if (!v) return void 0;
5027
+ roots.push(v);
5028
+ } else if (flag === "-C" || flag === "--cd") {
5029
+ options.cwd = value();
5030
+ if (!options.cwd) return void 0;
5031
+ } else if (flag === "-i" || flag === "--image") {
5032
+ const v = value();
5033
+ if (!v) return void 0;
5034
+ options.images.push(v);
5035
+ } else if (arg === "resume" || arg === "fork") {
5036
+ options.mode = arg;
5037
+ options.threadId = argv[++i];
5038
+ if (!options.threadId || options.threadId.startsWith("-")) return void 0;
5039
+ } else {
5040
+ return void 0;
5041
+ }
5042
+ }
5043
+ if (roots.length) server.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(roots)}`);
5044
+ return { argv: server, client: createCodexClient(options) };
5045
+ }
5046
+ function createCodexClient(options = { images: [] }) {
5047
+ const tasks = createBackgroundTasks();
5048
+ return {
5049
+ structured: true,
5050
+ background: tasks.count,
5051
+ turn: (io) => run(io, options, tasks)
5052
+ };
5053
+ }
5054
+ async function run(io, options, tasks) {
5055
+ const renderer = createCodexStreamRenderer();
5056
+ const preparingUntil = Math.min(io.prepareUntil ?? Infinity, Date.now() + CONVERSATION_MS.prepare);
5057
+ const phase = (phase2) => io.event?.({ kind: "phase", data: { phase: phase2, at: (/* @__PURE__ */ new Date()).toISOString() } });
5058
+ let submitted = false;
5059
+ let started = false;
5060
+ let contentAt = 0;
5061
+ let startupTimer;
5062
+ const began = () => {
5063
+ if (!submitted || started || ended) return;
5064
+ started = true;
5065
+ clearTimeout(startupTimer);
5066
+ phase("started");
5067
+ };
5068
+ const children = /* @__PURE__ */ new Set();
5069
+ const commands = /* @__PURE__ */ new Set();
5070
+ const seenItems = /* @__PURE__ */ new Set();
5071
+ const completedTurns = /* @__PURE__ */ new Set();
5072
+ const historicalTurns = /* @__PURE__ */ new Set();
5073
+ let currentTurn2 = "";
5074
+ let threadId = "";
5075
+ let active2 = true;
5076
+ let waiting = false;
5077
+ let terminalListing = true;
5078
+ let timer;
5079
+ let ended = false;
5080
+ let checking = false;
5081
+ let context;
5082
+ let total;
5083
+ let baseline;
5084
+ let model;
5085
+ let provider;
5086
+ let resolve2;
5087
+ const done2 = new Promise((r) => {
5088
+ resolve2 = r;
5089
+ });
5090
+ const deadline = createBackgroundWait(BACKGROUND_WAIT.minutes * 6e4, () => end2(backgroundWaitMessage(BACKGROUND_WAIT.minutes)));
5091
+ const emit = (type, extra = {}) => {
5092
+ io.log(renderer.push(JSON.stringify({ type, ...extra }) + "\n"));
5093
+ for (const event2 of renderer.events?.() ?? []) io.event?.(event2);
5094
+ };
5095
+ const end2 = (error) => {
5096
+ if (ended) return;
5097
+ ended = true;
5098
+ clearTimeout(timer);
5099
+ clearTimeout(startupTimer);
5100
+ deadline.close();
5101
+ io.stdout.off("close", closed2);
5102
+ io.log(renderer.flush());
5103
+ const usage3 = total && (!options.threadId && !io.resumeId ? total : baseline ? {
5104
+ input: Math.max(0, total.input - baseline.input),
5105
+ cacheRead: Math.max(0, total.cacheRead - baseline.cacheRead),
5106
+ cacheCreation: Math.max(0, total.cacheCreation - baseline.cacheCreation),
5107
+ output: Math.max(0, total.output - baseline.output)
5108
+ } : void 0);
5109
+ const failure = error || tasks.failure();
5110
+ if (failure) io.event?.({ kind: "error", data: { text: failure } });
5111
+ resolve2({ ok: !failure, error: failure, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: usage3, context, costUsd: priceUsd(provider, model, usage3) });
5112
+ };
5113
+ const closed2 = () => end2("Codex closed the connection before all work and results finished.");
5114
+ io.stdout.once("close", closed2);
5115
+ const update2 = (id, state, title = "") => {
5116
+ if (ended) return;
5117
+ const status = str(state.status);
5118
+ if (!status || !id) return;
5119
+ const previous = tasks.results().find((t) => t.id === `agent:${id}`);
5120
+ if (["shutdown", "notFound", "not_found"].includes(status) && previous && previous.status !== "running") return;
5121
+ const running = ["pendingInit", "running", "pending_init"].includes(status);
5122
+ const failed = ["interrupted", "errored", "shutdown", "notFound", "not_found"].includes(status);
5123
+ if (!running && !failed && status !== "completed") return;
5124
+ const known2 = children.has(id);
5125
+ children.add(id);
5126
+ if (!known2) io.event?.({ kind: "tool_call", data: { toolCallId: `agent:${id}`, title: targetOf(title) || "Agent", kind: "other", status: "in_progress", subagent: true } });
5127
+ if (tasks.update(`agent:${id}`, running ? "running" : failed ? "failed" : "completed", str(state.message)) && !running) {
5128
+ io.event?.({ kind: "tool_call_update", data: { toolCallId: `agent:${id}`, status: failed ? "failed" : "completed", result: str(state.message) } });
5129
+ }
5130
+ };
5131
+ const item = (raw, completed, proof = true) => {
5132
+ if (ended) return;
5133
+ const id = str(raw.id);
5134
+ if (raw.type === "collabAgentToolCall") {
5135
+ if (proof) began();
5136
+ const key2 = `${id}:${completed}`;
5137
+ if (seenItems.has(key2)) return;
5138
+ seenItems.add(key2);
5139
+ for (const [child, state] of Object.entries(obj(raw.agentsStates))) update2(child, obj(state), str(raw.prompt));
5140
+ for (const child of Array.isArray(raw.receiverThreadIds) ? raw.receiverThreadIds : []) {
5141
+ if (typeof child === "string" && !children.has(child) && raw.tool === "spawnAgent") update2(child, { status: "running" }, str(raw.prompt));
5142
+ }
5143
+ return;
5144
+ }
5145
+ if (raw.type === "commandExecution") {
5146
+ if (seenItems.has(`${id}:true`)) return;
5147
+ if (raw.status === "inProgress") completed = false;
5148
+ if (!completed) {
5149
+ commands.add(id);
5150
+ if (tasks.results().some((t) => t.id === `command:${id}`)) tasks.update(`command:${id}`, "running");
5151
+ } else {
5152
+ commands.delete(id);
5153
+ const failed = raw.status === "failed" || typeof raw.exitCode === "number" && raw.exitCode !== 0;
5154
+ if (tasks.results().some((t) => t.id === `command:${id}`)) tasks.update(`command:${id}`, failed ? "failed" : "completed", str(raw.aggregatedOutput));
5155
+ }
5156
+ }
5157
+ const key = `${id}:${completed}`;
5158
+ if (seenItems.has(key)) return;
5159
+ seenItems.add(key);
5160
+ const types = { agentMessage: "agent_message", commandExecution: "command_execution", fileChange: "file_change", mcpToolCall: "mcp_tool_call", webSearch: "web_search", imageGeneration: "image_generation" };
5161
+ const type = types[str(raw.type)];
5162
+ if (!type) return;
5163
+ if (proof) began();
5164
+ emit(completed ? "item.completed" : "item.started", { item: {
5165
+ ...raw,
5166
+ type,
5167
+ ...raw.type === "imageGeneration" ? { path: raw.savedPath ?? raw.path } : {},
5168
+ ...raw.type === "fileChange" ? { changes: list(raw.changes).map((c) => ({ ...c, kind: str(obj(c.kind).type) || c.kind })) } : {},
5169
+ aggregated_output: raw.aggregatedOutput,
5170
+ exit_code: raw.exitCode,
5171
+ status: raw.status === "inProgress" ? "in_progress" : raw.status
5172
+ } });
5173
+ };
5174
+ const start = async (text4, images = []) => {
5175
+ active2 = true;
5176
+ waiting = false;
5177
+ submitted = true;
5178
+ currentTurn2 = "";
5179
+ started = false;
5180
+ phase("submitted");
5181
+ startupTimer = setTimeout(() => {
5182
+ if (!started) io.event?.({ kind: "log", data: { text: "[conversation] start_unconfirmed" } });
5183
+ }, CONVERSATION_MS.start);
5184
+ await bounded(rpc.call("turn/start", { threadId, input: [{ type: "text", text: text4 }, ...images.map((path86) => ({ type: "localImage", path: path86 }))] }), CONVERSATION_MS.start, "Codex turn/start timed out; submission outcome is unknown.").catch((error) => {
5185
+ if (!started) throw error;
5186
+ });
5187
+ };
5188
+ const schedule = () => {
5189
+ if (ended || timer) return;
5190
+ timer = setTimeout(() => {
5191
+ timer = void 0;
5192
+ void check();
5193
+ }, 1e3);
5194
+ };
5195
+ const check = async () => {
5196
+ if (ended || checking || active2) return;
5197
+ checking = true;
5198
+ try {
5199
+ for (const key of tasks.running().filter((id) => id.startsWith("agent:"))) {
5200
+ const id = key.slice(6);
5201
+ let thread = obj((await rpc.call("thread/read", { threadId: id, includeTurns: false })).thread);
5202
+ let turns = list(thread.turns);
5203
+ if (thread.historyMode === "paginated") {
5204
+ turns = list((await rpc.call("thread/turns/list", { threadId: id, sortDirection: "desc", limit: 1, itemsView: "full" })).data).reverse();
5205
+ } else if (!turns.length) {
5206
+ thread = obj((await rpc.call("thread/read", { threadId: id, includeTurns: true })).thread);
5207
+ turns = list(thread.turns);
5208
+ }
5209
+ const turn2 = turns.at(-1);
5210
+ const status = str(turn2?.status);
5211
+ if (obj(thread.status).type === "systemError") update2(id, { status: "errored", message: "Codex subagent reported a system error." });
5212
+ else if (obj(thread.status).type !== "active" && turn2 && ["completed", "failed", "interrupted"].includes(status)) {
5213
+ const message = list(turn2.items).filter((i) => i.type === "agentMessage").map((i) => str(i.text)).join("\n\n");
5214
+ update2(id, { status: status === "completed" ? "completed" : "errored", message: str(obj(turn2.error).message) || message });
5215
+ }
5216
+ }
5217
+ if (terminalListing) {
5218
+ try {
5219
+ const running = /* @__PURE__ */ new Set();
5220
+ let cursor = null;
5221
+ const cursors = /* @__PURE__ */ new Set();
5222
+ do {
5223
+ if (cursor && cursors.has(cursor)) throw Error("Codex repeated a background terminal cursor.");
5224
+ cursors.add(cursor);
5225
+ const page = await rpc.call("thread/backgroundTerminals/list", { threadId, ...cursor ? { cursor } : {} });
5226
+ for (const terminal of list(page.data)) {
5227
+ const id = str(terminal.itemId) || str(terminal.processId);
5228
+ if (id) {
5229
+ running.add(id);
5230
+ tasks.update(`command:${id}`, "running");
5231
+ }
5232
+ }
5233
+ cursor = page.nextCursor;
5234
+ } while (cursor && !ended);
5235
+ for (const id of tasks.running().filter((id2) => id2.startsWith("command:"))) if (!running.has(id.slice(8))) {
5236
+ tasks.update(id, "completed");
5237
+ commands.delete(id.slice(8));
5238
+ }
5239
+ } catch (e) {
5240
+ if (!(e instanceof RpcError) || e.code !== -32601) throw e;
5241
+ terminalListing = false;
5242
+ io.log("[Codex] This version does not report background terminals.\n");
5243
+ if (commands.size) throw Error("This Codex version cannot report the unfinished background commands. Update Codex to collect their results.");
5244
+ }
5245
+ }
5246
+ if (ended || active2) return;
5247
+ if (tasks.count()) {
5248
+ waiting = true;
5249
+ deadline.pending();
5250
+ schedule();
5251
+ return;
5252
+ }
5253
+ if (waiting) {
5254
+ 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()));
5255
+ } else end2();
5256
+ } catch (e) {
5257
+ end2(String(e instanceof Error ? e.message : e));
5258
+ } finally {
5259
+ checking = false;
5260
+ }
5261
+ };
5262
+ const rpc = connect(io.stdout, io.stdin, (msg) => {
5263
+ if (ended) return;
5264
+ if (msg.id !== void 0) {
5265
+ rpc.refuse(msg.id, "WildCrane cannot answer interactive requests in an unattended run.");
5266
+ end2(`Codex requested interaction: ${msg.method}`);
5267
+ return;
5268
+ }
5269
+ const p = obj(msg.params);
5270
+ if (str(p.threadId) !== threadId) return;
5271
+ const turnId = str(p.turnId) || str(obj(p.turn).id);
5272
+ if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
5273
+ if (msg.method === "turn/started") {
5274
+ if (!submitted || completedTurns.has(turnId)) return;
5275
+ currentTurn2 = turnId;
5276
+ active2 = true;
5277
+ began();
5278
+ return;
5279
+ }
5280
+ if (submitted && msg.method === "item/agentMessage/delta" && Date.now() - contentAt >= 1e3) {
5281
+ began();
5282
+ contentAt = Date.now();
5283
+ io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
5284
+ }
5285
+ if (msg.method === "item/started" || msg.method === "item/completed") item(obj(p.item), msg.method === "item/completed", !completedTurns.has(turnId));
5286
+ if (msg.method === "thread/tokenUsage/updated") {
5287
+ const token2 = obj(p.tokenUsage);
5288
+ const counts = obj(token2.total);
5289
+ const input = Number(counts.inputTokens) || 0;
5290
+ const read3 = Number(counts.cachedInputTokens) || 0;
5291
+ const write2 = Number(counts.cacheWriteInputTokens) || 0;
5292
+ total = { input: Math.max(0, input - read3 - write2), cacheRead: read3, cacheCreation: write2, output: Number(counts.outputTokens) || 0 };
5293
+ const last = obj(token2.last);
5294
+ context = { used: (Number(last.inputTokens) || 0) + (Number(last.outputTokens) || 0), ...Number(token2.modelContextWindow) > 0 ? { limit: Number(token2.modelContextWindow) } : {} };
5295
+ io.gotContext?.(context);
5296
+ }
5297
+ if (msg.method === "error" && p.willRetry !== true) end2(str(obj(p.error).message) || "Codex failed.");
5298
+ if (msg.method === "turn/completed") {
5299
+ const turn2 = obj(p.turn);
5300
+ const id = str(turn2.id);
5301
+ if (completedTurns.has(id)) return;
5302
+ completedTurns.add(id);
5303
+ for (const raw of list(turn2.items)) item(raw, true);
5304
+ if (turn2.status !== "completed") {
5305
+ end2(str(obj(turn2.error).message) || `Codex turn ${str(turn2.status)}.`);
5306
+ return;
5307
+ }
5308
+ active2 = false;
5309
+ for (const id2 of commands) tasks.update(`command:${id2}`, "running");
5310
+ waiting ||= tasks.count() > 0 || commands.size > 0;
5311
+ deadline.pending();
5312
+ void check();
5313
+ }
5314
+ });
5315
+ try {
5316
+ phase("preparing");
5317
+ await bounded(rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } }), preparingUntil - Date.now(), "Codex initialize timed out.");
5318
+ phase("initialized");
5319
+ rpc.notify("initialized");
5320
+ const mode = options.mode ?? (io.resumeId ? "resume" : void 0);
5321
+ let response;
5322
+ try {
5323
+ response = await bounded(rpc.call(`thread/${mode ?? "start"}`, { cwd: options.cwd ?? io.cwd, ...mode ? { threadId: options.threadId ?? io.resumeId } : {} }), preparingUntil - Date.now(), `Codex thread/${mode ?? "start"} timed out.`);
5324
+ } catch (e) {
5325
+ if (mode && e instanceof RpcError && /no rollout found for thread id/i.test(e.message)) throw Error(`Thread not found: ${e.message}`);
5326
+ throw e;
5327
+ }
5328
+ const thread = obj(response.thread);
5329
+ for (const turn2 of list(thread.turns)) historicalTurns.add(str(turn2.id));
5330
+ threadId = str(thread.id);
5331
+ if (!threadId) throw Error("Codex did not return a thread id.");
5332
+ provider = str(thread.modelProvider) || void 0;
5333
+ model = str(response.model) || str(thread.model) || void 0;
5334
+ if (model) io.gotModel(model);
5335
+ io.gotResumeId(threadId);
5336
+ baseline = readCodexRunFacts(threadId)?.turns?.at(-1)?.total;
5337
+ emit("thread.started", { thread_id: threadId });
5338
+ if (Date.now() >= preparingUntil) throw Error("Codex preparation timed out.");
5339
+ phase("ready");
5340
+ await start(io.prompt, options.images);
5341
+ } catch (e) {
5342
+ end2(e instanceof Error ? e.message : String(e));
5343
+ }
5344
+ return done2;
5345
+ }
5346
+ var list;
5347
+ var init_codex = __esm({
5348
+ "../cli/src/lib/agent/wire/codex.ts"() {
5349
+ "use strict";
5350
+ init_conversation();
5351
+ init_settings();
5352
+ init_background();
5353
+ init_codex_stream();
5354
+ init_codex_session();
5355
+ init_json();
5356
+ init_events();
5357
+ init_rpc();
5358
+ init_prices();
5359
+ list = (value) => Array.isArray(value) ? value.map(obj) : [];
5360
+ }
5361
+ });
5362
+
4847
5363
  // ../cli/src/lib/agent/wire/index.ts
4848
5364
  var init_wire = __esm({
4849
5365
  "../cli/src/lib/agent/wire/index.ts"() {
@@ -4855,6 +5371,8 @@ var init_wire = __esm({
4855
5371
  init_kimi_stream();
4856
5372
  init_acp();
4857
5373
  init_zcode();
5374
+ init_codex();
5375
+ init_background();
4858
5376
  }
4859
5377
  });
4860
5378
 
@@ -4877,8 +5395,8 @@ function str2(value) {
4877
5395
  function num2(value) {
4878
5396
  return typeof value === "number" ? value : Number.MAX_SAFE_INTEGER;
4879
5397
  }
4880
- function uniqueIds(list) {
4881
- return [...new Set(list.map((id) => id.trim()).filter(Boolean))];
5398
+ function uniqueIds(list2) {
5399
+ return [...new Set(list2.map((id) => id.trim()).filter(Boolean))];
4882
5400
  }
4883
5401
  function modelsIn2(file, pick2, salt = "") {
4884
5402
  let stamp4;
@@ -5403,7 +5921,7 @@ function codexInstalls() {
5403
5921
  ];
5404
5922
  }
5405
5923
  var QUIET_CONFIG, ARCHES, CODEX;
5406
- var init_codex = __esm({
5924
+ var init_codex2 = __esm({
5407
5925
  "../cli/src/lib/agent/harnesses/codex.ts"() {
5408
5926
  "use strict";
5409
5927
  init_paths();
@@ -5425,6 +5943,7 @@ var init_codex = __esm({
5425
5943
  "codex exec --json --sandbox workspace-write",
5426
5944
  "codex exec --json --sandbox workspace-write -c sandbox_workspace_write.network_access=true"
5427
5945
  ],
5946
+ connection: createCodexConnection,
5428
5947
  installs: codexInstalls,
5429
5948
  pinned: () => process.env.CODEX_CLI_PATH?.trim() || void 0,
5430
5949
  // Nothing to pin: Codex mints its own thread id and takes none from us, so the generated
@@ -6376,7 +6895,7 @@ var init_harnesses = __esm({
6376
6895
  "use strict";
6377
6896
  init_check();
6378
6897
  init_claude_code();
6379
- init_codex();
6898
+ init_codex2();
6380
6899
  init_cursor();
6381
6900
  init_dsh();
6382
6901
  init_grok();
@@ -6659,8 +7178,8 @@ function settingArgs(harness, held4) {
6659
7178
  const { values } = held4;
6660
7179
  const ignored = held4.ignored ?? [];
6661
7180
  const picked = providerFor(harness, held4);
6662
- const list = providerSetting(harness.settings);
6663
- const byHand = !!list && ignored.includes(list.key);
7181
+ const list2 = providerSetting(harness.settings);
7182
+ const byHand = !!list2 && ignored.includes(list2.key);
6664
7183
  const providerArgs = byHand ? [] : picked?.args ?? [];
6665
7184
  const flags = harness.settings.flatMap((setting) => {
6666
7185
  const value = values[setting.key];
@@ -6690,9 +7209,9 @@ function settingEnv(harness, held4, secrets, cwd) {
6690
7209
  }
6691
7210
  function ownedVars(harness) {
6692
7211
  const names3 = new Set(harness.providerEnv ?? []);
6693
- const list = providerSetting(harness.settings);
6694
- if (!list) return [...names3];
6695
- for (const provider of list.providers ?? []) {
7212
+ const list2 = providerSetting(harness.settings);
7213
+ if (!list2) return [...names3];
7214
+ for (const provider of list2.providers ?? []) {
6696
7215
  for (const name of Object.values(provider.envAs ?? {})) names3.add(name);
6697
7216
  for (const name of Object.keys(provider.env ?? {})) names3.add(name);
6698
7217
  for (const key of provider.needs) {
@@ -7194,17 +7713,17 @@ function noteRefineTried(store, cardId2) {
7194
7713
  }
7195
7714
  function cardsBeingCreated(runs = readRuns()) {
7196
7715
  const newest2 = /* @__PURE__ */ new Map();
7197
- for (const run2 of runs) {
7198
- for (const id of run2.createdCardIds ?? []) {
7199
- if (run2.cardId === id) continue;
7716
+ for (const run3 of runs) {
7717
+ for (const id of run3.createdCardIds ?? []) {
7718
+ if (run3.cardId === id) continue;
7200
7719
  const best = newest2.get(id);
7201
- if (!best || run2.startedAt >= best.startedAt) newest2.set(id, run2);
7720
+ if (!best || run3.startedAt >= best.startedAt) newest2.set(id, run3);
7202
7721
  }
7203
7722
  }
7204
7723
  const out = /* @__PURE__ */ new Map();
7205
- for (const [id, run2] of newest2) {
7206
- if (runIsLive(run2)) out.set(id, { state: "creating", runId: run2.sessionId });
7207
- else if (run2.status !== "done") out.set(id, { state: "unfinished", runId: run2.sessionId });
7724
+ for (const [id, run3] of newest2) {
7725
+ if (runIsLive(run3)) out.set(id, { state: "creating", runId: run3.sessionId });
7726
+ else if (run3.status !== "done") out.set(id, { state: "unfinished", runId: run3.sessionId });
7208
7727
  }
7209
7728
  return out;
7210
7729
  }
@@ -7462,9 +7981,9 @@ function recordCreatedCards(sessionId, ids) {
7462
7981
  const valid = ids.filter((id) => Number.isInteger(id) && id > 0);
7463
7982
  if (!valid.length) return false;
7464
7983
  return withRuns((runs) => {
7465
- const run2 = runs.find((entry) => entry.sessionId === sessionId && entry.status === "running");
7466
- if (!run2) return false;
7467
- run2.createdCardIds = [.../* @__PURE__ */ new Set([...run2.createdCardIds ?? [], ...valid])];
7984
+ const run3 = runs.find((entry) => entry.sessionId === sessionId && entry.status === "running");
7985
+ if (!run3) return false;
7986
+ run3.createdCardIds = [.../* @__PURE__ */ new Set([...run3.createdCardIds ?? [], ...valid])];
7468
7987
  return true;
7469
7988
  });
7470
7989
  }
@@ -7506,7 +8025,7 @@ var init_store = __esm({
7506
8025
  stringRecord = (raw) => raw && typeof raw === "object" && !Array.isArray(raw) && Object.values(raw).every((v) => typeof v === "string") ? raw : void 0;
7507
8026
  readRuns = () => readStore().runs;
7508
8027
  PENDING_MS = 3e4;
7509
- runIsLive = (run2) => run2.status === "running" && (run2.pid ? pidAlive(run2.pid) : Date.now() - run2.startedAt < PENDING_MS);
8028
+ runIsLive = (run3) => run3.status === "running" && (run3.pid ? pidAlive(run3.pid) : Date.now() - run3.startedAt < PENDING_MS);
7510
8029
  creationOf = (runs, cardId2) => cardsBeingCreated(runs).get(cardId2);
7511
8030
  cardCreation = (cardId2, strict = false) => {
7512
8031
  const runs = readRuns();
@@ -7655,9 +8174,9 @@ var init_flows = __esm({
7655
8174
  import fs25 from "node:fs";
7656
8175
  function readRuntimes(cfg = safeConfig()) {
7657
8176
  const saved = Array.isArray(cfg.runtimes) ? cfg.runtimes.map(parseRuntime).filter(isRuntime) : null;
7658
- const list = saved?.length ? dedupe(saved) : fromHarnessBlocks(cfg);
7659
- const global = list.find((r) => r.id === GLOBAL_ID);
7660
- const rest = list.filter((r) => r.id !== GLOBAL_ID);
8177
+ const list2 = saved?.length ? dedupe(saved) : fromHarnessBlocks(cfg);
8178
+ const global = list2.find((r) => r.id === GLOBAL_ID);
8179
+ const rest = list2.filter((r) => r.id !== GLOBAL_ID);
7661
8180
  return [global ?? { id: GLOBAL_ID, name: GLOBAL_NAME, harness: DEFAULT_HARNESS.name, settings: {} }, ...rest];
7662
8181
  }
7663
8182
  function parseRuntime(value) {
@@ -7673,15 +8192,15 @@ function parseRuntime(value) {
7673
8192
  const away = typeof raw.away === "string" && raw.away.trim() ? { away: raw.away.trim() } : {};
7674
8193
  return { id, name: id === GLOBAL_ID ? GLOBAL_NAME : name, harness, settings, ...away };
7675
8194
  }
7676
- function dedupe(list) {
8195
+ function dedupe(list2) {
7677
8196
  const seen = /* @__PURE__ */ new Set();
7678
- return list.filter((r) => !seen.has(r.id) && seen.add(r.id));
8197
+ return list2.filter((r) => !seen.has(r.id) && seen.add(r.id));
7679
8198
  }
7680
8199
  function fromHarnessBlocks(cfg) {
7681
8200
  const asked = typeof cfg.harness === "string" ? cfg.harness.trim() : "";
7682
8201
  const fallback = (harnessByName(asked) ?? DEFAULT_HARNESS).name;
7683
8202
  const blocks = configBlock(cfg.harnessSettings);
7684
- const list = [
8203
+ const list2 = [
7685
8204
  { id: GLOBAL_ID, name: GLOBAL_NAME, harness: asked || fallback, settings: valuesOf(blocks[asked || fallback]) }
7686
8205
  ];
7687
8206
  const taken = /* @__PURE__ */ new Set([GLOBAL_ID]);
@@ -7689,9 +8208,9 @@ function fromHarnessBlocks(cfg) {
7689
8208
  if (harness === (asked || fallback)) continue;
7690
8209
  const id = freeId(harness, taken);
7691
8210
  taken.add(id);
7692
- list.push({ id, name: harnessByName(harness)?.label ?? harness, harness, settings: valuesOf(block) });
8211
+ list2.push({ id, name: harnessByName(harness)?.label ?? harness, harness, settings: valuesOf(block) });
7693
8212
  }
7694
- return list;
8213
+ return list2;
7695
8214
  }
7696
8215
  function valuesOf(block) {
7697
8216
  const out = {};
@@ -7700,15 +8219,15 @@ function valuesOf(block) {
7700
8219
  }
7701
8220
  return out;
7702
8221
  }
7703
- function pickRuntime(list, pin, harness) {
7704
- const rows = harness ? list.filter((r) => r.harness === harness) : list;
8222
+ function pickRuntime(list2, pin, harness) {
8223
+ const rows = harness ? list2.filter((r) => r.harness === harness) : list2;
7705
8224
  const want = pin?.trim();
7706
8225
  const found2 = want && (rows.find((r) => r.id === want) ?? rows.find((r) => r.harness === want));
7707
8226
  if (found2) return found2;
7708
8227
  return rows[0] ?? { id: "", name: harness ?? "", harness: harness ?? DEFAULT_HARNESS.name, settings: {} };
7709
8228
  }
7710
- function runtimeById(id, list = readRuntimes()) {
7711
- return list.find((r) => r.id === id);
8229
+ function runtimeById(id, list2 = readRuntimes()) {
8230
+ return list2.find((r) => r.id === id);
7712
8231
  }
7713
8232
  function secretVar(env2, runtimeId) {
7714
8233
  return `${env2}__${runtimeId.replace(/[^A-Za-z0-9]+/g, "_").toUpperCase()}`;
@@ -7775,23 +8294,23 @@ function setHarness(name) {
7775
8294
  return setRuntimeHarness(GLOBAL_ID, name);
7776
8295
  }
7777
8296
  function change(id, edit) {
7778
- const list = readRuntimes();
7779
- if (!list.some((r) => r.id === id)) return { ok: false, ...noRuntime(id) };
7780
- return save(list.map((r) => r.id === id ? edit(r) : r));
8297
+ const list2 = readRuntimes();
8298
+ if (!list2.some((r) => r.id === id)) return { ok: false, ...noRuntime(id) };
8299
+ return save(list2.map((r) => r.id === id ? edit(r) : r));
7781
8300
  }
7782
- function save(list) {
8301
+ function save(list2) {
7783
8302
  return writeConfig((cfg) => {
7784
8303
  const picks = readAgentRuntime(cfg);
7785
- cfg.runtimes = list;
8304
+ cfg.runtimes = list2;
7786
8305
  delete cfg.harnessSettings;
7787
8306
  delete cfg.harness;
7788
- writePicks(cfg, picks, list);
8307
+ writePicks(cfg, picks, list2);
7789
8308
  });
7790
8309
  }
7791
- function writePicks(cfg, picks, list = readRuntimes(cfg)) {
8310
+ function writePicks(cfg, picks, list2 = readRuntimes(cfg)) {
7792
8311
  const block = {};
7793
8312
  for (const [agent, pin] of Object.entries(picks)) {
7794
- const row = pickRuntime(list, pin);
8313
+ const row = pickRuntime(list2, pin);
7795
8314
  if (keepsPick(row.id)) block[agent] = row.id;
7796
8315
  }
7797
8316
  delete cfg.agentHarness;
@@ -7816,13 +8335,13 @@ function migrateRuntimes(agents, localModels) {
7816
8335
  return null;
7817
8336
  }
7818
8337
  if (Array.isArray(cfg.runtimes) && cfg.runtimes.length) return null;
7819
- const list = fromHarnessBlocks(cfg);
7820
- const taken = new Set(list.map((r) => r.id));
8338
+ const list2 = fromHarnessBlocks(cfg);
8339
+ const taken = new Set(list2.map((r) => r.id));
7821
8340
  const picks = {};
7822
8341
  const bound = configBlock(cfg.agentHarness);
7823
8342
  for (const agent of agents) {
7824
8343
  const named2 = typeof bound[agent] === "string" ? bound[agent].trim() : "";
7825
- const base = pickRuntime(list, named2 || void 0);
8344
+ const base = pickRuntime(list2, named2 || void 0);
7826
8345
  const model = localModels[agent]?.[base.harness] ?? {};
7827
8346
  if (!Object.keys(model).length || sameValues(base.settings, model)) {
7828
8347
  if (named2 && base.id !== GLOBAL_ID) picks[agent] = base.id;
@@ -7830,17 +8349,17 @@ function migrateRuntimes(agents, localModels) {
7830
8349
  }
7831
8350
  const id = freeId(agent, taken);
7832
8351
  taken.add(id);
7833
- list.push({ id, name: agent, harness: base.harness, settings: { ...base.settings, ...model } });
8352
+ list2.push({ id, name: agent, harness: base.harness, settings: { ...base.settings, ...model } });
7834
8353
  picks[agent] = id;
7835
8354
  }
7836
- cfg.runtimes = list;
8355
+ cfg.runtimes = list2;
7837
8356
  if (Object.keys(picks).length) cfg.agentRuntime = picks;
7838
8357
  delete cfg.harness;
7839
8358
  delete cfg.harnessSettings;
7840
8359
  delete cfg.agentHarness;
7841
8360
  fs25.writeFileSync(UI_CONFIG, JSON.stringify(cfg, null, 2) + "\n");
7842
- const minted = list.length - 1;
7843
- 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`;
8361
+ const minted = list2.length - 1;
8362
+ 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`;
7844
8363
  }
7845
8364
  function repairEnvFile() {
7846
8365
  const env2 = readEnvFile();
@@ -7927,11 +8446,11 @@ function readBlock(harness, block, argv, runtimeId) {
7927
8446
  if (value) values[setting.key] = value;
7928
8447
  if (setting.flags?.length && namesFlag(argv, setting.flags)) ignored.push(setting.key);
7929
8448
  }
7930
- const list = providerSetting(harness.settings);
7931
- if (list) {
7932
- const picked = pickedProvider(list, values[list.key] ?? "", isFilled(harness, { values, secretsSet }));
7933
- if (picked) values[list.key] = picked.id;
7934
- else delete values[list.key];
8449
+ const list2 = providerSetting(harness.settings);
8450
+ if (list2) {
8451
+ const picked = pickedProvider(list2, values[list2.key] ?? "", isFilled(harness, { values, secretsSet }));
8452
+ if (picked) values[list2.key] = picked.id;
8453
+ else delete values[list2.key];
7935
8454
  }
7936
8455
  return { values, secretsSet, ignored };
7937
8456
  }
@@ -7950,13 +8469,13 @@ function resolveHarness(ask2 = {}) {
7950
8469
  const cfg = safeConfig();
7951
8470
  const staleCommand = typeof cfg.command === "string" && cfg.command.trim() ? true : void 0;
7952
8471
  const agent = ask2.agent ?? "";
7953
- const list = readRuntimes(cfg);
8472
+ const list2 = readRuntimes(cfg);
7954
8473
  const table = readAgentRuntime(cfg);
7955
8474
  const owner = agent ? runtimeOwner(agent) : "";
7956
8475
  const picked = owner ? runtimeOfAgent(specAgentNames(owner), table) : void 0;
7957
8476
  const asked = ask2.pin ?? picked;
7958
- const runtime = pickRuntime(list, asked, ask2.harness);
7959
- const unknownAgentRuntime = picked && !ask2.pin && !list.some((r) => r.id === picked || r.harness === picked) ? picked : void 0;
8477
+ const runtime = pickRuntime(list2, asked, ask2.harness);
8478
+ const unknownAgentRuntime = picked && !ask2.pin && !list2.some((r) => r.id === picked || r.harness === picked) ? picked : void 0;
7960
8479
  const known2 = harnessByName(runtime.harness);
7961
8480
  const harness = known2 ?? DEFAULT_HARNESS;
7962
8481
  const command = commandOf(runtime.settings, harness);
@@ -7995,13 +8514,13 @@ function agentHarness(agent) {
7995
8514
  function settingSaveError(key, value, ask2 = {}) {
7996
8515
  const resolved2 = resolveHarness(ask2);
7997
8516
  const { harness, values, secretsSet } = resolved2;
7998
- const list = providerSetting(harness.settings);
7999
- if (!list) return null;
8517
+ const list2 = providerSetting(harness.settings);
8518
+ if (!list2) return null;
8000
8519
  const filled = isFilled(harness, { values, secretsSet });
8001
8520
  const label = (k) => harness.settings.find((s) => s.key === k)?.label ?? k;
8002
- if (key === list.key) {
8003
- const provider = list.providers?.find((p) => p.id === value);
8004
- if (!provider) return `"${value}" isn't one of the ${list.label.toLowerCase()} choices`;
8521
+ if (key === list2.key) {
8522
+ const provider = list2.providers?.find((p) => p.id === value);
8523
+ if (!provider) return `"${value}" isn't one of the ${list2.label.toLowerCase()} choices`;
8005
8524
  const missing = missingHere(harness, provider, filled);
8006
8525
  if (missing.length) {
8007
8526
  const names3 = missing.map((k) => `"${label(k)}"`).join(" and ");
@@ -8085,20 +8604,21 @@ function openPlan(plan) {
8085
8604
  const started = [start.binary, ...plan.argv.slice(1)];
8086
8605
  const { argv, env: planned, note } = withSystemLanguage(harness, started, runEnv2(resolved2, plan.cwd ?? REPO_ROOT), runLanguage());
8087
8606
  const env2 = copyEnv(start.binary, planned);
8607
+ const connection = harness.connection?.(argv);
8088
8608
  return {
8089
8609
  ...plan,
8090
- argv,
8610
+ argv: connection?.argv ?? argv,
8091
8611
  ...[start.note, note].some(Boolean) ? { startNote: [start.note, note].filter(Boolean).join("\n") } : {},
8092
8612
  env: env2,
8093
8613
  // The folder and the binary: what a renderer needs to go looking for what the stream
8094
8614
  // left out (agent/harnesses/types.ts). argv's first word is the command's own binary,
8095
8615
  // the same one the spawn resolves and an ENOENT names.
8096
- renderer: harness.renderer?.(plan.cwd ?? REPO_ROOT, argv[0], argv),
8616
+ renderer: connection ? void 0 : harness.renderer?.(plan.cwd ?? REPO_ROOT, argv[0], argv),
8097
8617
  // The client is handed the settings that are actually in effect — the same ones that
8098
8618
  // would have reached the run as flags, minus whatever the picked provider doesn't
8099
8619
  // need — because for a connector that talks, a setting is something the conversation
8100
8620
  // opens with rather than something argv carries.
8101
- client: harness.client?.(effectiveValues2(resolved2)),
8621
+ client: connection?.client ?? harness.client?.(effectiveValues2(resolved2)),
8102
8622
  // Read off the argv, so a plan written before the CLI took its turns on stdin still runs.
8103
8623
  stdinPrompt: harness.stdinPrompt?.(argv),
8104
8624
  quietStderr: harness.quietStderr,
@@ -8127,11 +8647,11 @@ function modelsRun() {
8127
8647
  const ran = /* @__PURE__ */ new Map();
8128
8648
  const { runs } = readStore();
8129
8649
  for (let i = runs.length - 1; i >= 0; i--) {
8130
- const run2 = runs[i];
8131
- if (!run2.harness || !run2.model) continue;
8132
- const seen = ran.get(run2.harness) ?? [];
8133
- if (!seen.includes(run2.model)) seen.push(run2.model);
8134
- ran.set(run2.harness, seen);
8650
+ const run3 = runs[i];
8651
+ if (!run3.harness || !run3.model) continue;
8652
+ const seen = ran.get(run3.harness) ?? [];
8653
+ if (!seen.includes(run3.model)) seen.push(run3.model);
8654
+ ran.set(run3.harness, seen);
8135
8655
  }
8136
8656
  return ran;
8137
8657
  }
@@ -9441,7 +9961,7 @@ var init_yaml2 = __esm({
9441
9961
  });
9442
9962
 
9443
9963
  // ../cli/src/lib/agents/parse.ts
9444
- function parseSpecAgent(text4, from, file, builtIn = false, list = () => []) {
9964
+ function parseSpecAgent(text4, from, file, builtIn = false, list2 = () => []) {
9445
9965
  let named2 = "";
9446
9966
  const bad = (why2, old2) => ({
9447
9967
  problem: `${from}: ${why2}`,
@@ -9503,7 +10023,7 @@ function parseSpecAgent(text4, from, file, builtIn = false, list = () => []) {
9503
10023
  ...declaredSession ? { session: "new" } : {},
9504
10024
  memory: names(akb.memory),
9505
10025
  memoryFiles: { workspace: workspace2 },
9506
- files: list(),
10026
+ files: list2(),
9507
10027
  body: instructions,
9508
10028
  from,
9509
10029
  builtIn,
@@ -9532,12 +10052,12 @@ function memoryPaths(raw, folder = "memory/agents/<name>/") {
9532
10052
  const block = map(raw);
9533
10053
  const extra = block ? Object.keys(block).filter((key) => key !== "workspace") : [];
9534
10054
  if (!block || extra.length) return `\`akb.memoryFiles\` with ${block ? `\`${extra.join("`, `")}\`` : "no `workspace:` list"} \u2014 it holds only \`workspace: [<path>, ...]\``;
9535
- const list = block.workspace;
9536
- if (list === void 0) return [];
9537
- if (!Array.isArray(list) || list.some((v) => typeof v !== "string" || !v.trim())) {
10055
+ const list2 = block.workspace;
10056
+ if (list2 === void 0) return [];
10057
+ if (!Array.isArray(list2) || list2.some((v) => typeof v !== "string" || !v.trim())) {
9538
10058
  return "`akb.memoryFiles.workspace` that is not a list of paths \u2014 write `workspace: [style.md]`";
9539
10059
  }
9540
- const paths = [...new Set(list.map((v) => v.trim()))];
10060
+ const paths = [...new Set(list2.map((v) => v.trim()))];
9541
10061
  const outside = paths.find((p) => p.startsWith("/") || p.includes("\\") || p.split("/").some((part) => part === ".." || part === "."));
9542
10062
  if (outside) return `\`akb.memoryFiles.workspace: ${outside}\`, which is outside its memory folder \u2014 use a path inside \`${folder}\``;
9543
10063
  return paths;
@@ -10046,8 +10566,8 @@ function readFlows() {
10046
10566
  }
10047
10567
  const project2 = boardProject();
10048
10568
  if (!project2 || !readSession()) return [];
10049
- const list = readJson(listFile(project2))?.studios ?? [];
10050
- const flows2 = list.flatMap((w) => {
10569
+ const list2 = readJson(listFile(project2))?.studios ?? [];
10570
+ const flows2 = list2.flatMap((w) => {
10051
10571
  const held4 = readVersion(w.id, w.version);
10052
10572
  return held4 ? flowOf(held4) ?? [] : [];
10053
10573
  });
@@ -10242,8 +10762,8 @@ function readBundled(folder) {
10242
10762
  const file = (relative) => shipped[`${folder}/${relative}`] ?? null;
10243
10763
  const text4 = file("AGENT.md");
10244
10764
  if (text4 === null) return { problem: `${label} has no AGENT.md` };
10245
- const list = () => ownFiles(Object.keys(shipped).filter((k) => k.startsWith(`${folder}/`)).map((k) => k.slice(folder.length + 1)));
10246
- return parseSpecAgent(text4, label, file, official, list);
10765
+ const list2 = () => ownFiles(Object.keys(shipped).filter((k) => k.startsWith(`${folder}/`)).map((k) => k.slice(folder.length + 1)));
10766
+ return parseSpecAgent(text4, label, file, official, list2);
10247
10767
  }
10248
10768
  function projectFolders(root2) {
10249
10769
  let entries;
@@ -10936,8 +11456,8 @@ async function queryPreviews(studio, workspace2) {
10936
11456
  if (externalGoalSession()) return withGoalDiscussion(() => cmdGoalPreviews(studio));
10937
11457
  die("--workspace is required outside a goal discussion.");
10938
11458
  }
10939
- const list = await studios2(workspace2);
10940
- const flow = list.find((w) => w.id === studio || shortStudioId(w.id) === studio);
11459
+ const list2 = await studios2(workspace2);
11460
+ const flow = list2.find((w) => w.id === studio || shortStudioId(w.id) === studio);
10941
11461
  if (!flow) die(`No studio \`${studio}\` here.`);
10942
11462
  if (!flow.previews) die("Preview agents are unavailable; update Runner and try again.");
10943
11463
  const agents = flow.previews.map((p) => ({ name: p.agent, when: p.when || null }));
@@ -15553,23 +16073,23 @@ import path49 from "node:path";
15553
16073
  function writeAudit(delivery, runs) {
15554
16074
  const known2 = new Map(readAudit(delivery.deliveryId)?.sessions.map((s) => [s.sessionId, s]) ?? []);
15555
16075
  const sessions = delivery.sessions.flatMap((id) => {
15556
- const run2 = runs.find((r) => r.sessionId === id);
15557
- if (!run2) {
16076
+ const run3 = runs.find((r) => r.sessionId === id);
16077
+ if (!run3) {
15558
16078
  const before = known2.get(id);
15559
16079
  return before ? [before] : [];
15560
16080
  }
15561
16081
  return [
15562
16082
  {
15563
- sessionId: run2.sessionId,
15564
- action: run2.action,
15565
- status: run2.status,
15566
- startedAt: run2.startedAt,
15567
- endedAt: run2.endedAt,
15568
- harness: run2.harness || void 0,
15569
- model: run2.model,
15570
- costUsd: run2.costUsd,
15571
- resumedFrom: run2.resumedFrom,
15572
- log: rel(run2.logPath)
16083
+ sessionId: run3.sessionId,
16084
+ action: run3.action,
16085
+ status: run3.status,
16086
+ startedAt: run3.startedAt,
16087
+ endedAt: run3.endedAt,
16088
+ harness: run3.harness || void 0,
16089
+ model: run3.model,
16090
+ costUsd: run3.costUsd,
16091
+ resumedFrom: run3.resumedFrom,
16092
+ log: rel(run3.logPath)
15573
16093
  }
15574
16094
  ];
15575
16095
  });
@@ -15647,7 +16167,7 @@ function settleOrphanedDeliveries() {
15647
16167
  const recovered = [];
15648
16168
  withStore((store) => {
15649
16169
  const known2 = new Set(store.deliveries.map((d) => d.deliveryId));
15650
- for (const run2 of store.runs) if (run2.deliveryId) known2.add(run2.deliveryId);
16170
+ for (const run3 of store.runs) if (run3.deliveryId) known2.add(run3.deliveryId);
15651
16171
  for (const audit of audits) {
15652
16172
  if (known2.has(audit.deliveryId) || !localAudit(audit)) continue;
15653
16173
  if (lastSessionRunning(audit)) {
@@ -15858,16 +16378,16 @@ function deliveryFor(req) {
15858
16378
  }
15859
16379
  return req.id === void 0 ? void 0 : activeDelivery(req.id);
15860
16380
  }
15861
- function joinDelivery(store, run2, title, step, start, direct) {
15862
- const cardId2 = run2.cardId;
15863
- let delivery = run2.deliveryId ? store.deliveries.find((d) => d.deliveryId === run2.deliveryId && d.status === "active") : cardId2 === null ? void 0 : activeIn(store, cardId2);
16381
+ function joinDelivery(store, run3, title, step, start, direct) {
16382
+ const cardId2 = run3.cardId;
16383
+ let delivery = run3.deliveryId ? store.deliveries.find((d) => d.deliveryId === run3.deliveryId && d.status === "active") : cardId2 === null ? void 0 : activeIn(store, cardId2);
15864
16384
  if (!delivery) {
15865
16385
  delivery = {
15866
16386
  deliveryId: start?.deliveryId ?? newDeliveryId(store.deliveries),
15867
16387
  cardId: cardId2,
15868
16388
  title,
15869
16389
  status: "active",
15870
- startedAt: run2.startedAt,
16390
+ startedAt: run3.startedAt,
15871
16391
  sessions: [],
15872
16392
  // The one read of the card this delivery will ever make for its requirements — or,
15873
16393
  // with no card, the sentence or the plan's words it was handed, which can never move
@@ -15902,21 +16422,21 @@ function joinDelivery(store, run2, title, step, start, direct) {
15902
16422
  } else if (step === "implement" && delivery.review?.stopped) {
15903
16423
  delivery.review.stopped = void 0;
15904
16424
  }
15905
- delivery.sessions.push(run2.sessionId);
15906
- delivery.steps.push({ step, at: run2.startedAt });
15907
- joinFlow(run2, delivery);
16425
+ delivery.sessions.push(run3.sessionId);
16426
+ delivery.steps.push({ step, at: run3.startedAt });
16427
+ joinFlow(run3, delivery);
15908
16428
  writeAudit(delivery, store.runs);
15909
16429
  return delivery;
15910
16430
  }
15911
16431
  function adoptDirectCard(sessionId, cardId2) {
15912
16432
  return withStore((store) => {
15913
- const run2 = store.runs.find((r) => r.sessionId === sessionId && r.status === "running");
15914
- if (!run2 || run2.action !== "implement" || run2.cardId !== null) return false;
15915
- const delivery = run2.deliveryId ? store.deliveries.find((d) => d.deliveryId === run2.deliveryId && d.status === "active") : void 0;
15916
- if (run2.deliveryId && (!delivery || delivery.cardId !== null)) return false;
16433
+ const run3 = store.runs.find((r) => r.sessionId === sessionId && r.status === "running");
16434
+ if (!run3 || run3.action !== "implement" || run3.cardId !== null) return false;
16435
+ const delivery = run3.deliveryId ? store.deliveries.find((d) => d.deliveryId === run3.deliveryId && d.status === "active") : void 0;
16436
+ if (run3.deliveryId && (!delivery || delivery.cardId !== null)) return false;
15917
16437
  const idle = "ready";
15918
- run2.cardId = cardId2;
15919
- run2.priorStatus = idle;
16438
+ run3.cardId = cardId2;
16439
+ run3.priorStatus = idle;
15920
16440
  if (!delivery) return true;
15921
16441
  delivery.cardId = cardId2;
15922
16442
  delivery.priorStatus = idle;
@@ -15924,21 +16444,21 @@ function adoptDirectCard(sessionId, cardId2) {
15924
16444
  return true;
15925
16445
  });
15926
16446
  }
15927
- function joinActive(store, run2, step, deliveryId) {
15928
- const delivery = deliveryId ? store.deliveries.find((d) => d.status === "active" && d.deliveryId === deliveryId) : run2.cardId === null ? void 0 : activeIn(store, run2.cardId);
16447
+ function joinActive(store, run3, step, deliveryId) {
16448
+ const delivery = deliveryId ? store.deliveries.find((d) => d.status === "active" && d.deliveryId === deliveryId) : run3.cardId === null ? void 0 : activeIn(store, run3.cardId);
15929
16449
  if (!delivery) return void 0;
15930
- delivery.sessions.push(run2.sessionId);
15931
- delivery.steps.push({ step, at: run2.startedAt });
16450
+ delivery.sessions.push(run3.sessionId);
16451
+ delivery.steps.push({ step, at: run3.startedAt });
15932
16452
  if (delivery.review?.stopped) delivery.review.stopped = void 0;
15933
16453
  const now = Date.now();
15934
16454
  for (const answer2 of delivery.answers ?? []) if (!answer2.actedAt) answer2.actedAt = now;
15935
- joinFlow(run2, delivery);
16455
+ joinFlow(run3, delivery);
15936
16456
  writeAudit(delivery, store.runs);
15937
16457
  return delivery;
15938
16458
  }
15939
- function joinFlow(run2, delivery) {
15940
- run2.deliveryId = delivery.deliveryId;
15941
- run2.flowId = delivery.deliveryId;
16459
+ function joinFlow(run3, delivery) {
16460
+ run3.deliveryId = delivery.deliveryId;
16461
+ run3.flowId = delivery.deliveryId;
15942
16462
  }
15943
16463
  function endDelivery(deliveryId, status) {
15944
16464
  const ended = withBoardLock(() => withStore((store) => {
@@ -15953,8 +16473,8 @@ function endDelivery(deliveryId, status) {
15953
16473
  }
15954
16474
  return ended;
15955
16475
  }
15956
- async function settleDelivery(run2) {
15957
- if (run2.deliveryId) syncAudit(run2.deliveryId, run2);
16476
+ async function settleDelivery(run3) {
16477
+ if (run3.deliveryId) syncAudit(run3.deliveryId, run3);
15958
16478
  }
15959
16479
  function deliveryAcceptsAnswers(cardId2) {
15960
16480
  return !!deliveryStateOf(cardId2)?.paused;
@@ -16839,7 +17359,7 @@ var init_prompts = __esm({
16839
17359
  `The session you were continuing is gone, and this one holds nothing of it.`,
16840
17360
  `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.`
16841
17361
  ].join(" ");
16842
- restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
17362
+ restartable = (run3) => (run3.cardId !== null || !!run3.deliveryId) && RESTARTABLE.has(run3.action);
16843
17363
  NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
16844
17364
  BOARD_FOLDER = "<board folder>";
16845
17365
  CARD_FILE = "<card file>";
@@ -16922,16 +17442,16 @@ function signal(pids, sig) {
16922
17442
  }
16923
17443
  }
16924
17444
  }
16925
- function startedUnder(list, root2, since) {
16926
- const self = list.procs.find((p) => p.pid === root2);
17445
+ function startedUnder(list2, root2, since) {
17446
+ const self = list2.procs.find((p) => p.pid === root2);
16927
17447
  const from = since ?? self?.startedAt;
16928
- if (from === void 0 || list.bootedAt > from) return [];
17448
+ if (from === void 0 || list2.bootedAt > from) return [];
16929
17449
  if (self && self.startedAt > from) return [];
16930
17450
  const found2 = self ? [root2] : [];
16931
17451
  const seen = /* @__PURE__ */ new Set([root2]);
16932
17452
  const queue = [{ pid: root2, startedAt: from }];
16933
17453
  for (const parent of queue) {
16934
- for (const p of list.procs) {
17454
+ for (const p of list2.procs) {
16935
17455
  if (p.ppid !== parent.pid || seen.has(p.pid) || p.startedAt < parent.startedAt) continue;
16936
17456
  seen.add(p.pid);
16937
17457
  found2.push(p.pid);
@@ -16962,9 +17482,9 @@ function procsOnWindows() {
16962
17482
  }
16963
17483
  function killUnderOnWindows(pid, since) {
16964
17484
  if (!WINDOWS3 || !pid) return;
16965
- const list = procsOnWindows();
16966
- if (!list) return;
16967
- const pids = startedUnder(list, pid, since).filter((p) => p !== process.pid);
17485
+ const list2 = procsOnWindows();
17486
+ if (!list2) return;
17487
+ const pids = startedUnder(list2, pid, since).filter((p) => p !== process.pid);
16968
17488
  if (!pids.length) return;
16969
17489
  spawnSync4("taskkill", ["/F", ...pids.flatMap((p) => ["/PID", String(p)])], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
16970
17490
  }
@@ -17069,9 +17589,9 @@ function reap(runs, reaped = [], restore = []) {
17069
17589
  }
17070
17590
  return changed;
17071
17591
  }
17072
- function stampDuration(run2, endedAt) {
17592
+ function stampDuration(run3, endedAt) {
17073
17593
  try {
17074
- fs53.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
17594
+ fs53.appendFileSync(run3.logPath, durationLine(endedAt - run3.startedAt));
17075
17595
  } catch {
17076
17596
  }
17077
17597
  }
@@ -17092,19 +17612,19 @@ function cardNow(cardId2) {
17092
17612
  return null;
17093
17613
  }
17094
17614
  }
17095
- function claimCard(run2) {
17096
- const wanted = run2.cardId !== null ? RUN_STATUS[run2.action] : void 0;
17097
- if (run2.cardId === null || !wanted) return void 0;
17098
- const delivery = run2.deliveryId ? activeDelivery(run2.cardId) : void 0;
17099
- run2.priorStatus = (delivery && delivery.deliveryId === run2.deliveryId ? delivery.priorStatus : void 0) ?? cardNow(run2.cardId)?.status ?? "todo";
17100
- return { cardId: run2.cardId, status: wanted };
17615
+ function claimCard(run3) {
17616
+ const wanted = run3.cardId !== null ? RUN_STATUS[run3.action] : void 0;
17617
+ if (run3.cardId === null || !wanted) return void 0;
17618
+ const delivery = run3.deliveryId ? activeDelivery(run3.cardId) : void 0;
17619
+ run3.priorStatus = (delivery && delivery.deliveryId === run3.deliveryId ? delivery.priorStatus : void 0) ?? cardNow(run3.cardId)?.status ?? "todo";
17620
+ return { cardId: run3.cardId, status: wanted };
17101
17621
  }
17102
- async function restoreCardStatus(run2) {
17103
- if (run2.cardId === null || !RUN_STATUS[run2.action]) return;
17104
- if (run2.deliveryId && activeDelivery(run2.cardId)?.deliveryId === run2.deliveryId) return;
17105
- const card = cardNow(run2.cardId);
17622
+ async function restoreCardStatus(run3) {
17623
+ if (run3.cardId === null || !RUN_STATUS[run3.action]) return;
17624
+ if (run3.deliveryId && activeDelivery(run3.cardId)?.deliveryId === run3.deliveryId) return;
17625
+ const card = cardNow(run3.cardId);
17106
17626
  if (!card) return;
17107
- await setCardStatus(run2.cardId, card.questions > 0 ? "todo" : run2.priorStatus ?? "todo");
17627
+ await setCardStatus(run3.cardId, card.questions > 0 ? "todo" : run3.priorStatus ?? "todo");
17108
17628
  }
17109
17629
  async function releaseCard(delivery) {
17110
17630
  if (delivery.cardId === null) return;
@@ -17112,39 +17632,39 @@ async function releaseCard(delivery) {
17112
17632
  if (card?.status !== "implementing") return;
17113
17633
  await setCardStatus(delivery.cardId, card.questions > 0 ? "todo" : delivery.priorStatus ?? "ready");
17114
17634
  }
17115
- function recordPrune(run2) {
17116
- if (run2.action !== "prune-memory" || run2.status !== "done") return;
17635
+ function recordPrune(run3) {
17636
+ if (run3.action !== "prune-memory" || run3.status !== "done") return;
17117
17637
  try {
17118
17638
  stampMemoryPrune();
17119
17639
  } catch {
17120
17640
  }
17121
17641
  }
17122
- function recordMemoryReview(run2) {
17123
- if (run2.action !== "review-memory" || run2.status !== "done") return;
17642
+ function recordMemoryReview(run3) {
17643
+ if (run3.action !== "review-memory" || run3.status !== "done") return;
17124
17644
  try {
17125
- stampMemoryReview(new Date(run2.startedAt));
17645
+ stampMemoryReview(new Date(run3.startedAt));
17126
17646
  } catch {
17127
17647
  }
17128
17648
  }
17129
- function recordReflection(run2) {
17130
- if (run2.action !== "reflect" || run2.status !== "done" || !run2.cards?.length) return;
17649
+ function recordReflection(run3) {
17650
+ if (run3.action !== "reflect" || run3.status !== "done" || !run3.cards?.length) return;
17131
17651
  try {
17132
- dropReflected(run2.cards);
17652
+ dropReflected(run3.cards);
17133
17653
  } catch {
17134
17654
  }
17135
17655
  }
17136
- function recordScheduledRun(run2) {
17137
- if (run2.action !== "scheduled" || run2.status !== "done" || !run2.studio || !run2.specAgent) return;
17656
+ function recordScheduledRun(run3) {
17657
+ if (run3.action !== "scheduled" || run3.status !== "done" || !run3.studio || !run3.specAgent) return;
17138
17658
  try {
17139
- const began = (run2.deliveryId ? findDelivery(run2.deliveryId)?.startedAt : void 0) ?? run2.startedAt;
17140
- stampScheduledRun(run2.studio, run2.specAgent, new Date(began));
17659
+ const began = (run3.deliveryId ? findDelivery(run3.deliveryId)?.startedAt : void 0) ?? run3.startedAt;
17660
+ stampScheduledRun(run3.studio, run3.specAgent, new Date(began));
17141
17661
  } catch {
17142
17662
  }
17143
17663
  }
17144
- function recordProjectDescription(run2) {
17145
- if (run2.action !== "describe-project" || run2.status !== "done") return;
17664
+ function recordProjectDescription(run3) {
17665
+ if (run3.action !== "describe-project" || run3.status !== "done") return;
17146
17666
  try {
17147
- stampProjectDescription(new Date(run2.startedAt));
17667
+ stampProjectDescription(new Date(run3.startedAt));
17148
17668
  } catch {
17149
17669
  }
17150
17670
  }
@@ -17152,8 +17672,8 @@ function resumeIdOf(r) {
17152
17672
  if (adoptsSessionId(r.harness) && !carriesSession(r)) return r.sessionId;
17153
17673
  return r.resumeId;
17154
17674
  }
17155
- function resumeSessionId(run2) {
17156
- return resumesUnder(run2.harness) && !neverStarted(run2) ? resumeIdOf(run2) : void 0;
17675
+ function resumeSessionId(run3) {
17676
+ return resumesUnder(run3.harness) && !neverStarted(run3) ? resumeIdOf(run3) : void 0;
17157
17677
  }
17158
17678
  function endedDeliveryRefusal(r, refusals) {
17159
17679
  if (!r.deliveryId || !canPickUp(r)) return void 0;
@@ -17227,7 +17747,7 @@ function archivedRejected(id) {
17227
17747
  }
17228
17748
  function goneCards(runs) {
17229
17749
  const asking = /* @__PURE__ */ new Set();
17230
- for (const run2 of runs) if (run2.cardId !== null && canPickUp(run2)) asking.add(run2.cardId);
17750
+ for (const run3 of runs) if (run3.cardId !== null && canPickUp(run3)) asking.add(run3.cardId);
17231
17751
  if (asking.size === 0) return asking;
17232
17752
  const onBoard3 = boardCardIds();
17233
17753
  const gone = /* @__PURE__ */ new Set();
@@ -17241,8 +17761,8 @@ async function listRuns() {
17241
17761
  reap(all2, reaped, restore);
17242
17762
  return all2.map((r) => ({ ...r }));
17243
17763
  });
17244
- for (const run2 of restore) await restoreCardStatus(run2);
17245
- for (const run2 of reaped) await settleDelivery(run2);
17764
+ for (const run3 of restore) await restoreCardStatus(run3);
17765
+ for (const run3 of reaped) await settleDelivery(run3);
17246
17766
  for (const sub of runs) {
17247
17767
  if (sub.action !== "sub" || sub.status !== "running" || !sub.parentId) continue;
17248
17768
  if (!runs.some((r) => r.sessionId === sub.parentId && r.status === "running")) await stopRun(sub.sessionId);
@@ -17283,7 +17803,7 @@ async function getRun(id, bytes2) {
17283
17803
  reap(all2, [], restore);
17284
17804
  return all2.map((r) => ({ ...r }));
17285
17805
  });
17286
- for (const run2 of restore) await restoreCardStatus(run2);
17806
+ for (const run3 of restore) await restoreCardStatus(run3);
17287
17807
  const found2 = findRun(runs, id);
17288
17808
  if (!found2) return null;
17289
17809
  const view = toView(found2, goneCards([found2]));
@@ -17506,8 +18026,8 @@ function carriedSession(req) {
17506
18026
  };
17507
18027
  }
17508
18028
  function planningRun(sessionId) {
17509
- const run2 = peekRun(sessionId);
17510
- return run2?.status === "running" && PLANNING.has(run2.action) ? run2 : void 0;
18029
+ const run3 = peekRun(sessionId);
18030
+ return run3?.status === "running" && PLANNING.has(run3.action) ? run3 : void 0;
17511
18031
  }
17512
18032
  function requestOf(record) {
17513
18033
  const id = record.cardId ?? void 0;
@@ -17539,7 +18059,7 @@ async function openResume(id, options) {
17539
18059
  reap(all2, [], restore);
17540
18060
  return all2.map((r) => ({ ...r }));
17541
18061
  });
17542
- for (const run2 of restore) await restoreCardStatus(run2);
18062
+ for (const run3 of restore) await restoreCardStatus(run3);
17543
18063
  const prev = findRun(runs, id);
17544
18064
  if (prev === null) return ambiguousRun(id);
17545
18065
  if (!prev) return unknownRun(id);
@@ -17720,8 +18240,8 @@ function forgetRun(sessionId) {
17720
18240
  }
17721
18241
  }
17722
18242
  function askForSpec(sessionId, ask2) {
17723
- const run2 = peekRun(sessionId);
17724
- if (!run2) return "no-run";
18243
+ const run3 = peekRun(sessionId);
18244
+ if (!run3) return "no-run";
17725
18245
  const file = readAsks(sessionId);
17726
18246
  if (file.asks.some((a) => a.specAgent === ask2.specAgent && a.cardId === ask2.cardId)) return "already";
17727
18247
  file.asks.push(ask2);
@@ -17790,9 +18310,9 @@ function markSpawned(sessionId, pid) {
17790
18310
  }
17791
18311
  function patch(sessionId, change2) {
17792
18312
  return withRuns((runs) => {
17793
- const run2 = runs.find((r) => r.sessionId === sessionId);
17794
- if (run2) change2(run2);
17795
- return run2 ? { ...run2 } : void 0;
18313
+ const run3 = runs.find((r) => r.sessionId === sessionId);
18314
+ if (run3) change2(run3);
18315
+ return run3 ? { ...run3 } : void 0;
17796
18316
  });
17797
18317
  }
17798
18318
  function peekRun(sessionId) {
@@ -17800,18 +18320,18 @@ function peekRun(sessionId) {
17800
18320
  }
17801
18321
  async function closeRun(sessionId, res) {
17802
18322
  const closed2 = withRuns((runs) => {
17803
- const run2 = runs.find((r) => r.sessionId === sessionId);
17804
- if (!run2 || run2.status !== "running") return void 0;
17805
- run2.status = res.status;
17806
- if (res.ok !== void 0) run2.ok = res.ok;
17807
- run2.code = res.code ?? null;
17808
- if (res.error) run2.error = res.error;
17809
- if (res.note) run2.note = res.note;
17810
- if (res.errorWhy?.length) run2.errorWhy = res.errorWhy;
17811
- if (res.noteWhy?.length) run2.noteWhy = res.noteWhy;
17812
- run2.endedAt = res.endedAt ?? Date.now();
17813
- run2.pid = void 0;
17814
- return { ...run2 };
18323
+ const run3 = runs.find((r) => r.sessionId === sessionId);
18324
+ if (!run3 || run3.status !== "running") return void 0;
18325
+ run3.status = res.status;
18326
+ if (res.ok !== void 0) run3.ok = res.ok;
18327
+ run3.code = res.code ?? null;
18328
+ if (res.error) run3.error = res.error;
18329
+ if (res.note) run3.note = res.note;
18330
+ if (res.errorWhy?.length) run3.errorWhy = res.errorWhy;
18331
+ if (res.noteWhy?.length) run3.noteWhy = res.noteWhy;
18332
+ run3.endedAt = res.endedAt ?? Date.now();
18333
+ run3.pid = void 0;
18334
+ return { ...run3 };
17815
18335
  });
17816
18336
  if (!closed2) return;
17817
18337
  if (closed2.status === "done" || closed2.status === "error") {
@@ -17836,14 +18356,14 @@ async function stopRun(id) {
17836
18356
  const restore = [];
17837
18357
  const out = withRuns((runs) => {
17838
18358
  reap(runs, [], restore);
17839
- const run2 = findRun(runs, id);
17840
- if (run2 === null) return { ok: false, ...ambiguousRun(id) };
17841
- if (!run2) return { ok: false, ...unknownRun(id) };
17842
- if (run2.status !== "running") return { ok: true, sessionId: run2.sessionId };
17843
- run2.stopping = true;
17844
- return { ok: true, sessionId: run2.sessionId, pid: run2.pid, live: true };
18359
+ const run3 = findRun(runs, id);
18360
+ if (run3 === null) return { ok: false, ...ambiguousRun(id) };
18361
+ if (!run3) return { ok: false, ...unknownRun(id) };
18362
+ if (run3.status !== "running") return { ok: true, sessionId: run3.sessionId };
18363
+ run3.stopping = true;
18364
+ return { ok: true, sessionId: run3.sessionId, pid: run3.pid, live: true };
17845
18365
  });
17846
- for (const run2 of restore) await restoreCardStatus(run2);
18366
+ for (const run3 of restore) await restoreCardStatus(run3);
17847
18367
  const live = out;
17848
18368
  if (!live.ok || !live.live) {
17849
18369
  return { ok: live.ok, sessionId: live.sessionId, error: live.error, reason: live.reason, args: live.args };
@@ -17889,13 +18409,13 @@ async function cancelDelivery(id) {
17889
18409
  }
17890
18410
  async function stopSubRuns(parentId) {
17891
18411
  const live = liveSubRuns(parentId);
17892
- for (const run2 of live) await stopRun(run2.sessionId);
17893
- await Promise.all(live.map((run2) => runIsDown(run2.sessionId)));
18412
+ for (const run3 of live) await stopRun(run3.sessionId);
18413
+ await Promise.all(live.map((run3) => runIsDown(run3.sessionId)));
17894
18414
  }
17895
18415
  async function runIsDown(sessionId) {
17896
18416
  for (const until = Date.now() + STOP_WAIT_MS; Date.now() < until; ) {
17897
- const run2 = readRuns().find((r) => r.sessionId === sessionId);
17898
- if (!run2 || !runIsLive(run2)) return;
18417
+ const run3 = readRuns().find((r) => r.sessionId === sessionId);
18418
+ if (!run3 || !runIsLive(run3)) return;
17899
18419
  await sleep3(STOP_POLL_MS);
17900
18420
  }
17901
18421
  }
@@ -19387,14 +19907,14 @@ function compareProblem(attrs, id) {
19387
19907
  return { message: `${at} is not valid JSON.` };
19388
19908
  }
19389
19909
  };
19390
- const list = read3(attrs.shots);
19391
- if ("message" in list) return shots(list.message);
19392
- const why2 = Array.isArray(list.data) ? shotsProblem(list.data) : storyboardProblem(list.data);
19910
+ const list2 = read3(attrs.shots);
19911
+ if ("message" in list2) return shots(list2.message);
19912
+ const why2 = Array.isArray(list2.data) ? shotsProblem(list2.data) : storyboardProblem(list2.data);
19393
19913
  if (why2) return shots(`${attrs.shots}: ${why2}`);
19394
19914
  if (!script) return null;
19395
19915
  const bad = storyboardProblem(board2);
19396
19916
  if (bad) return src(`${attrs.b}: ${bad}`);
19397
- const known2 = new Set((Array.isArray(list.data) ? list.data : list.data.shots).map((s) => s.id));
19917
+ const known2 = new Set((Array.isArray(list2.data) ? list2.data : list2.data.shots).map((s) => s.id));
19398
19918
  const extra = board2.shots.find((s) => !known2.has(s.id));
19399
19919
  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;
19400
19920
  }
@@ -19842,8 +20362,8 @@ function cmdUpdateQuestions(id, input) {
19842
20362
  function specRunAgent() {
19843
20363
  const id = insideRun();
19844
20364
  if (!id) return void 0;
19845
- const run2 = readStore().runs.find((r) => r.sessionId === id);
19846
- return run2?.action === "spec" ? run2.specAgent : void 0;
20365
+ const run3 = readStore().runs.find((r) => r.sessionId === id);
20366
+ return run3?.action === "spec" ? run3.specAgent : void 0;
19847
20367
  }
19848
20368
  var TODO_ITEM;
19849
20369
  var init_card = __esm({
@@ -20609,21 +21129,21 @@ function scheduledBusy(pass, store = readStore()) {
20609
21129
  }
20610
21130
  function insideScheduledPass() {
20611
21131
  const sessionId = insideRun();
20612
- const run2 = sessionId ? readStore().runs.find((r) => r.sessionId === sessionId) : void 0;
20613
- return run2?.action === "scheduled" && run2.studio && run2.specAgent ? { studio: run2.studio, agent: run2.specAgent } : null;
21132
+ const run3 = sessionId ? readStore().runs.find((r) => r.sessionId === sessionId) : void 0;
21133
+ return run3?.action === "scheduled" && run3.studio && run3.specAgent ? { studio: run3.studio, agent: run3.specAgent } : null;
20614
21134
  }
20615
21135
  function runAgent() {
20616
21136
  const sessionId = insideRun();
20617
21137
  const runs = sessionId ? readStore().runs : [];
20618
- const run2 = runs.find((r) => r.sessionId === sessionId);
20619
- if (!run2) return null;
20620
- if (run2.action !== "sub") return agentOf(run2);
20621
- const parent = runs.find((r) => r.sessionId === run2.parentId);
20622
- return parent ? agentOf(parent) : run2.specAgent ?? null;
21138
+ const run3 = runs.find((r) => r.sessionId === sessionId);
21139
+ if (!run3) return null;
21140
+ if (run3.action !== "sub") return agentOf(run3);
21141
+ const parent = runs.find((r) => r.sessionId === run3.parentId);
21142
+ return parent ? agentOf(parent) : run3.specAgent ?? null;
20623
21143
  }
20624
- function agentOf(run2) {
20625
- if (run2.action === "scheduled") return run2.specAgent ?? null;
20626
- return flowNodes().find((n) => n.flow === run2.action)?.agent ?? null;
21144
+ function agentOf(run3) {
21145
+ if (run3.action === "scheduled") return run3.specAgent ?? null;
21146
+ return flowNodes().find((n) => n.flow === run3.action)?.agent ?? null;
20627
21147
  }
20628
21148
  var scheduledRequest, isPass, openPasses, stalePasses;
20629
21149
  var init_scheduled = __esm({
@@ -20638,7 +21158,7 @@ var init_scheduled = __esm({
20638
21158
  studio: pass.studio,
20639
21159
  specAgent: pass.agent
20640
21160
  });
20641
- isPass = (run2, pass) => run2.action === "scheduled" && run2.studio === pass.studio && run2.specAgent === pass.agent;
21161
+ isPass = (run3, pass) => run3.action === "scheduled" && run3.studio === pass.studio && run3.specAgent === pass.agent;
20642
21162
  openPasses = (deliveries, pass) => deliveries.filter(
20643
21163
  (d) => d.status === "active" && d.scheduled?.studio === pass.studio && d.scheduled.agent === pass.agent
20644
21164
  );
@@ -21376,16 +21896,16 @@ function removeCard2(id, metric, options) {
21376
21896
  }
21377
21897
  }
21378
21898
  withStore((store) => {
21379
- for (const run2 of store.runs) {
21380
- if (!leaving.some((c) => run2.createdCardIds?.includes(c.id))) continue;
21381
- const marks = new Map((run2.discardedCards ?? []).map((c) => [c.id, c]));
21899
+ for (const run3 of store.runs) {
21900
+ if (!leaving.some((c) => run3.createdCardIds?.includes(c.id))) continue;
21901
+ const marks = new Map((run3.discardedCards ?? []).map((c) => [c.id, c]));
21382
21902
  for (const c of leaving) marks.set(c.id, { id: c.id, path: rel(c.file), pending: true });
21383
- run2.discardedCards = [...marks.values()];
21903
+ run3.discardedCards = [...marks.values()];
21384
21904
  }
21385
21905
  });
21386
21906
  }
21387
21907
  if (options.discard) withStore((store) => {
21388
- for (const run2 of store.runs) for (const card of run2.discardedCards ?? []) {
21908
+ for (const run3 of store.runs) for (const card of run3.discardedCards ?? []) {
21389
21909
  if (leftIds.includes(card.id)) delete card.pending;
21390
21910
  }
21391
21911
  });
@@ -21661,11 +22181,11 @@ function newOpId() {
21661
22181
  opCounter += 1;
21662
22182
  return `${process.pid.toString(36)}-${Date.now().toString(36)}-${opCounter.toString(36)}`;
21663
22183
  }
21664
- async function leaseAnd(provider, target, run2) {
22184
+ async function leaseAnd(provider, target, run3) {
21665
22185
  const got = await provider.lease(target);
21666
22186
  if (!got.ok) return { ok: false, kind: "refused", error: got.error };
21667
22187
  try {
21668
- return await run2(envelope(got.lease.revision, got.lease.id));
22188
+ return await run3(envelope(got.lease.revision, got.lease.id));
21669
22189
  } finally {
21670
22190
  await provider.releaseLease(got.lease.id);
21671
22191
  }
@@ -21793,14 +22313,14 @@ function localBoard() {
21793
22313
  },
21794
22314
  // ---- the named `akb raw` moves ----------------------------------------
21795
22315
  async runMove(move, input, env2) {
21796
- const run2 = MOVES[move];
21797
- if (!run2) return Promise.resolve(opRefused(new Error(`unknown command "${move}".`)));
22316
+ const run3 = MOVES[move];
22317
+ if (!run3) return Promise.resolve(opRefused(new Error(`unknown command "${move}".`)));
21798
22318
  const target = moveTarget(move, input.args);
21799
22319
  try {
21800
22320
  return await withBoardLock(() => {
21801
22321
  const no = checkWrite(target, env2, revisionAt(target));
21802
22322
  if (no) return no;
21803
- const data = run2(input);
22323
+ const data = run3(input);
21804
22324
  if (data instanceof Promise) return data.then((data2) => opOk(revisionAt(target), { data: data2 }));
21805
22325
  return opOk(revisionAt(target), { data: data || {} });
21806
22326
  });
@@ -21809,10 +22329,10 @@ function localBoard() {
21809
22329
  }
21810
22330
  },
21811
22331
  readMove(move, input) {
21812
- const run2 = MOVES[move];
21813
- if (!run2) return Promise.reject(new Error(`unknown command "${move}".`));
22332
+ const run3 = MOVES[move];
22333
+ if (!run3) return Promise.reject(new Error(`unknown command "${move}".`));
21814
22334
  try {
21815
- return Promise.resolve(run2(input) || {});
22335
+ return Promise.resolve(run3(input) || {});
21816
22336
  } catch (e) {
21817
22337
  return Promise.reject(e);
21818
22338
  }
@@ -21864,8 +22384,8 @@ function board() {
21864
22384
  if (!active) active = localBoard();
21865
22385
  return active;
21866
22386
  }
21867
- function withLease(target, run2) {
21868
- return leaseAnd(board(), target, run2);
22387
+ function withLease(target, run3) {
22388
+ return leaseAnd(board(), target, run3);
21869
22389
  }
21870
22390
  var active, setCardStatusOn, cancelBoardDelivery, resumeBoardDelivery;
21871
22391
  var init_board = __esm({
@@ -22167,8 +22687,8 @@ async function dispatch(move, cmd, args, opts, cli) {
22167
22687
  cli.onAnswer?.(data);
22168
22688
  }
22169
22689
  async function cloudCard(task, opts) {
22170
- const run2 = insideRun() ? peekRun(insideRun()) : void 0;
22171
- const triage = typeof opts.triage === "string" ? opts.triage : run2?.triage;
22690
+ const run3 = insideRun() ? peekRun(insideRun()) : void 0;
22691
+ const triage = typeof opts.triage === "string" ? opts.triage : run3?.triage;
22172
22692
  opts = { ...opts, ...triage ? { triage } : {} };
22173
22693
  const sourceFile = triage ? triageFile(triage) : void 0;
22174
22694
  let request2;
@@ -22199,7 +22719,7 @@ async function cloudCard(task, opts) {
22199
22719
  }
22200
22720
  const checked = await creationProject(KANBAN, REPO_ROOT);
22201
22721
  if (!checked.ok) throw new BoardError(creationError(checked.error, triage), { kind: "refused" });
22202
- const requestId = triage ? `triage:${triage}` : run2?.sessionId ?? crypto5.randomUUID();
22722
+ const requestId = triage ? `triage:${triage}` : run3?.sessionId ?? crypto5.randomUUID();
22203
22723
  const slot = triage ? triage : String(opts.slug ?? opts.title);
22204
22724
  const file = creationReceipt(`${checked.value}:${requestId}`, slot);
22205
22725
  const journal = readCreation(file, said2);
@@ -22717,8 +23237,8 @@ function checkSetting(setting, value, ask2) {
22717
23237
  return `"${value}" isn't one of the ${setting.label} choices: ${choices}`;
22718
23238
  }
22719
23239
  if (setting.kind === "provider" && !value) {
22720
- const list = providerSetting(activeSettings(ask2));
22721
- return `a run always goes through a provider, so this one can't be cleared. Pick one: ${list?.providers?.map((p) => p.id).join(", ") ?? ""}`;
23240
+ const list2 = providerSetting(activeSettings(ask2));
23241
+ return `a run always goes through a provider, so this one can't be cleared. Pick one: ${list2?.providers?.map((p) => p.id).join(", ") ?? ""}`;
22722
23242
  }
22723
23243
  return settingSaveError(setting.key, value, ask2);
22724
23244
  }
@@ -23137,7 +23657,7 @@ var init_board3 = __esm({
23137
23657
  var card_chat_default;
23138
23658
  var init_card_chat = __esm({
23139
23659
  "../cli/src/guide/card-chat.md"() {
23140
- 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';
23660
+ 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';
23141
23661
  }
23142
23662
  });
23143
23663
 
@@ -23663,24 +24183,24 @@ function completeDelivery(named2, result = {}) {
23663
24183
  delivery2.completions = durable.completions;
23664
24184
  }
23665
24185
  const receipts = delivery2.completions ??= [];
23666
- const run2 = store.runs.find((r) => r.sessionId === sessionId);
24186
+ const run3 = store.runs.find((r) => r.sessionId === sessionId);
23667
24187
  const current = store.runs.filter((r) => r.deliveryId === delivery2.deliveryId && ["implement", "scheduled"].includes(r.action)).pop();
23668
- if (!run2 || run2.deliveryId !== delivery2.deliveryId) throw new Error("This run does not own the delivery.");
24188
+ if (!run3 || run3.deliveryId !== delivery2.deliveryId) throw new Error("This run does not own the delivery.");
23669
24189
  const pending = receipts[deliveryStep(delivery2)];
23670
24190
  const previous = receipts.find((c) => c.sessionId === sessionId || c.resumedSessions?.includes(sessionId));
23671
24191
  if (previous) {
23672
24192
  if (previous.commit !== commit || previous.branch !== branch) throw new Error("This step already recorded a different result.");
23673
- if (!previous.finished && previous.step === deliveryStep(delivery2) && (delivery2.status !== "active" || run2 !== current || run2.status !== "running")) {
24193
+ if (!previous.finished && previous.step === deliveryStep(delivery2) && (delivery2.status !== "active" || run3 !== current || run3.status !== "running")) {
23674
24194
  throw new Error("Only the current owning run can finish pending completion.");
23675
24195
  }
23676
24196
  return { delivery: delivery2, receipt: previous };
23677
24197
  }
23678
- if (delivery2.status !== "active" || !run2 || run2.status !== "running" || run2 !== current || run2.deliveryId !== delivery2.deliveryId) {
24198
+ if (delivery2.status !== "active" || !run3 || run3.status !== "running" || run3 !== current || run3.deliveryId !== delivery2.deliveryId) {
23679
24199
  throw new Error("Only the current owning run can complete this delivery.");
23680
24200
  }
23681
24201
  if (answerOutcome(delivery2) === "changed") throw new Error("The approved requirements were superseded. Continue with the updated delivery.");
23682
24202
  if (delivery2.cardId !== null && openQuestions(delivery2.cardId)) throw new Error("Answer the open questions before completing.");
23683
- if (pending && run2 === current) {
24203
+ if (pending && run3 === current) {
23684
24204
  if (pending.commit !== commit || pending.branch !== branch) throw new Error("This step already recorded a different result.");
23685
24205
  pending.resumedSessions = [...pending.resumedSessions ?? [], sessionId];
23686
24206
  return { delivery: delivery2, receipt: pending };
@@ -23876,10 +24396,10 @@ function open2(req, sessionId) {
23876
24396
  returnRunPictures(sessionId, req.box);
23877
24397
  return opened;
23878
24398
  }
23879
- const { run: run2 } = opened;
23880
- const pid = spawnWatcher(run2.sessionId);
23881
- markSpawned(run2.sessionId, pid);
23882
- return { run: run2, spawned: pid !== void 0 };
24399
+ const { run: run3 } = opened;
24400
+ const pid = spawnWatcher(run3.sessionId);
24401
+ markSpawned(run3.sessionId, pid);
24402
+ return { run: run3, spawned: pid !== void 0 };
23883
24403
  }
23884
24404
  async function startResume(id, options) {
23885
24405
  const opened = await openResume(id, options);
@@ -24616,7 +25136,7 @@ var init_stage_end = __esm({
24616
25136
  const flow = flowByAction(action);
24617
25137
  return flow ? stageOfFlow(flow.command) : void 0;
24618
25138
  };
24619
- askedFor = (cardId2, agent) => readStore().runs.some((run2) => run2.action === "spec" && run2.cardId === cardId2 && run2.specAgent === agent);
25139
+ askedFor = (cardId2, agent) => readStore().runs.some((run3) => run3.action === "spec" && run3.cardId === cardId2 && run3.specAgent === agent);
24620
25140
  }
24621
25141
  });
24622
25142
 
@@ -24701,26 +25221,26 @@ function stalledLine(cardId2, next) {
24701
25221
  if (!card || refinementStep(card) === "done") return null;
24702
25222
  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.`;
24703
25223
  }
24704
- function planStageEnd(run2) {
24705
- if (run2.cardId === null || stageOfAction(run2.action) !== "plan") return null;
24706
- const card = currentCard(run2.cardId);
25224
+ function planStageEnd(run3) {
25225
+ if (run3.cardId === null || stageOfAction(run3.action) !== "plan") return null;
25226
+ const card = currentCard(run3.cardId);
24707
25227
  if (!card || card.openBlockers.length > 0 || card.questions.length > 0) return null;
24708
25228
  if (refinementStep(card) !== "done") return null;
24709
25229
  return endOfStage(stageContract("plan"), card);
24710
25230
  }
24711
- function refinementRunsAfter(run2, changed, before, waitingForSpec = false, refused = []) {
24712
- const next = waitingForSpec || run2.cardId === null || !["clarify", "resolve", "edit", "approve"].includes(run2.action) ? null : refinementAfter(run2.action, run2.cardId, run2.flowId);
24713
- const starts = refinesAfter(run2.action, changed, before).filter(
24714
- (req) => req.id !== run2.cardId || run2.refineRound === void 0 && run2.action !== "spec"
25231
+ function refinementRunsAfter(run3, changed, before, waitingForSpec = false, refused = []) {
25232
+ const next = waitingForSpec || run3.cardId === null || !["clarify", "resolve", "edit", "approve"].includes(run3.action) ? null : refinementAfter(run3.action, run3.cardId, run3.flowId);
25233
+ const starts = refinesAfter(run3.action, changed, before).filter(
25234
+ (req) => req.id !== run3.cardId || run3.refineRound === void 0 && run3.action !== "spec"
24715
25235
  );
24716
25236
  const refusedNote = waitingForSpec || !refused.length ? "" : `Preview agents not started: ${refused.map((r) => r.error).join(" ")}`;
24717
25237
  const carryOn = next && refusedNote ? { ...next, notes: [next.notes, refusedNote].filter(Boolean).join("\n\n") } : next;
24718
- const end2 = waitingForSpec || carryOn || starts.length ? null : planStageEnd(run2);
25238
+ const end2 = waitingForSpec || carryOn || starts.length ? null : planStageEnd(run3);
24719
25239
  const short2 = end2 && "missing" in end2 ? end2 : null;
24720
- const stalled = (short2 ? shortLine(short2, run2.cardId) : void 0) ?? (waitingForSpec ? void 0 : run2.refineRound !== void 0 && stalledLine(run2.cardId, next) || void 0);
25240
+ const stalled = (short2 ? shortLine(short2, run3.cardId) : void 0) ?? (waitingForSpec ? void 0 : run3.refineRound !== void 0 && stalledLine(run3.cardId, next) || void 0);
24721
25241
  const stalledWhy = [
24722
25242
  ...refusedNote ? [{ kind: "specRefused", refusals: refused }] : [],
24723
- ...!stalled ? [] : short2 ? [{ kind: "stageShort", args: { stage: short2.stage, card: String(run2.cardId), agents: short2.missing.join(", ") } }] : [{ kind: "refineStalled", args: { card: String(run2.cardId) } }]
25243
+ ...!stalled ? [] : short2 ? [{ kind: "stageShort", args: { stage: short2.stage, card: String(run3.cardId), agents: short2.missing.join(", ") } }] : [{ kind: "refineStalled", args: { card: String(run3.cardId) } }]
24724
25244
  ];
24725
25245
  return {
24726
25246
  runs: [...starts, ...carryOn ? [carryOn] : [], ...end2 && "ask" in end2 ? [end2.ask] : []],
@@ -24934,18 +25454,18 @@ import { spawn as spawn3 } from "node:child_process";
24934
25454
  import fs82 from "node:fs";
24935
25455
  async function watchRun(sessionId, resume = startResume) {
24936
25456
  const spec = readSpec(sessionId);
24937
- const run2 = peekRun(sessionId);
24938
- if (!run2 || !spec) {
24939
- if (run2?.status === "running") await closeRun(sessionId, { status: "interrupted", code: null });
25457
+ const run3 = peekRun(sessionId);
25458
+ if (!run3 || !spec) {
25459
+ if (run3?.status === "running") await closeRun(sessionId, { status: "interrupted", code: null });
24940
25460
  return 1;
24941
25461
  }
24942
- if (run2.stopping) {
25462
+ if (run3.stopping) {
24943
25463
  await closeRun(sessionId, { status: "stopped", code: null });
24944
25464
  return 1;
24945
25465
  }
24946
25466
  const stopping = () => peekRun(sessionId)?.status !== "running";
24947
25467
  let releaseIndex = null;
24948
- if (needsIndexLock(run2.action)) {
25468
+ if (needsIndexLock(run3.action)) {
24949
25469
  releaseIndex = await acquireIndexLock(stopping);
24950
25470
  if (!releaseIndex) {
24951
25471
  if (!stopping()) await closeRun(sessionId, { status: "interrupted", code: null });
@@ -24964,7 +25484,7 @@ async function watchRun(sessionId, resume = startResume) {
24964
25484
  const claimed = patch(sessionId, (r) => {
24965
25485
  claim = claimCard(r);
24966
25486
  });
24967
- const record = claimed ?? run2;
25487
+ const record = claimed ?? run3;
24968
25488
  const sub = record.action === "sub";
24969
25489
  if (claim) await setCardStatus(claim.cardId, claim.status);
24970
25490
  fs82.mkdirSync(SESSIONS_DIR, { recursive: true });
@@ -25069,7 +25589,7 @@ async function watchRun(sessionId, resume = startResume) {
25069
25589
  const turns = renderer?.turns?.() ?? [];
25070
25590
  if (turns.length === turnsSeen) return;
25071
25591
  turnsSeen = turns.length;
25072
- if (!turns.at(-1).background) endInput();
25592
+ if (renderer && streamFinished(renderer)) endInput();
25073
25593
  };
25074
25594
  let sawResumeId = !!record.resumeId;
25075
25595
  let sawModel = false;
@@ -25160,7 +25680,7 @@ async function watchRun(sessionId, resume = startResume) {
25160
25680
  if (errRest) log.write(errRest);
25161
25681
  const endedAt = Date.now();
25162
25682
  const blocker = peekRun(sessionId)?.blocker;
25163
- const failure = renderer?.failure?.();
25683
+ const failure = renderer?.failure?.() ?? (renderer?.background?.() ? "The agent exited with unfinished background tasks." : void 0);
25164
25684
  const unfinished = blocker || failure;
25165
25685
  const result = spoken ? spoken.result : renderer?.result();
25166
25686
  const held4 = peekRun(sessionId) ?? record;
@@ -25168,7 +25688,7 @@ async function watchRun(sessionId, resume = startResume) {
25168
25688
  const said2 = failure ?? spoken?.error;
25169
25689
  const offStream = renderer?.offStream?.();
25170
25690
  const quiet = silent && !asked && !blocker && !sub && !!resumeSessionId(held4);
25171
- 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 });
25691
+ 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 });
25172
25692
  const again = blip ? planRetry2(held4.retry, blip, held4.startedAt, Date.now(), Math.random, !quiet) : null;
25173
25693
  if (again) {
25174
25694
  log.write(`
@@ -25294,7 +25814,7 @@ ${result}
25294
25814
  ...spawnWhy ? [spawnWhy] : [],
25295
25815
  ...saidOurs ? [waited ? { kind: "backgroundSilent", args: { n: String(BACKGROUND_WAIT.minutes / 60) } } : { kind: "silent", args: { n: String(silenceFor) } }] : []
25296
25816
  ];
25297
- const quietSaid = waited ? backgroundSaid(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor);
25817
+ const quietSaid = waited ? backgroundWaitMessage(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor);
25298
25818
  if (sub) {
25299
25819
  await closeRun(sessionId, {
25300
25820
  status,
@@ -25381,7 +25901,7 @@ Cannot resume board repair: ${next.error}`;
25381
25901
  touch = () => {
25382
25902
  if (done2 || !silenceMs) return;
25383
25903
  if (idle) clearTimeout(idle);
25384
- const background = renderer?.background?.() ?? 0;
25904
+ const background = client?.background?.() ?? renderer?.background?.() ?? 0;
25385
25905
  idle = setTimeout(() => {
25386
25906
  if (done2 || stopped2 || silent) return;
25387
25907
  if (liveSubRuns(sessionId).length) {
@@ -25396,7 +25916,7 @@ Cannot resume board repair: ${next.error}`;
25396
25916
  silent = true;
25397
25917
  waited = background > 0;
25398
25918
  log.write(`
25399
- [board] ${waited ? backgroundSaid(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor)}
25919
+ [board] ${waited ? backgroundWaitMessage(BACKGROUND_WAIT.minutes) : silenceSaid(silenceFor)}
25400
25920
  `);
25401
25921
  giveUp(false);
25402
25922
  }, background ? BACKGROUND_WAIT.minutes * 6e4 : silenceMs);
@@ -25423,7 +25943,8 @@ Cannot resume board repair: ${next.error}`;
25423
25943
  log: append2,
25424
25944
  gotResumeId: (id, restarted) => gotResumeId(id, restarted),
25425
25945
  gotModel: (model) => gotModel(model),
25426
- event: event2
25946
+ event: event2,
25947
+ gotContext
25427
25948
  }).then((end2) => {
25428
25949
  spoken = end2;
25429
25950
  endChild();
@@ -25437,11 +25958,11 @@ Cannot resume board repair: ${next.error}`;
25437
25958
  child.on("close", (code) => void finish(code, peekRun(sessionId)?.stopping === true || stopped2));
25438
25959
  });
25439
25960
  }
25440
- function settleBoard(run2, changed, before) {
25961
+ function settleBoard(run3, changed, before) {
25441
25962
  try {
25442
- const helpers = specRunsAfter(readSpecAsks(run2.sessionId));
25443
- const waitingForSpec = helpers.some((req) => req.id === run2.cardId);
25444
- return refinementRunsAfter(run2, changed, before, waitingForSpec, readSpecRefusals(run2.sessionId));
25963
+ const helpers = specRunsAfter(readSpecAsks(run3.sessionId));
25964
+ const waitingForSpec = helpers.some((req) => req.id === run3.cardId);
25965
+ return refinementRunsAfter(run3, changed, before, waitingForSpec, readSpecRefusals(run3.sessionId));
25445
25966
  } catch {
25446
25967
  return null;
25447
25968
  }
@@ -25501,7 +26022,7 @@ function catchModel(sessionId, model) {
25501
26022
  });
25502
26023
  return true;
25503
26024
  }
25504
- var STOP_GRACE_MS, STOP_CLOSE_MS, STOP_FINISH_MS, silenceSaid, backgroundSaid, MAX_FORMAT_REPAIRS, joinNotes;
26025
+ var STOP_GRACE_MS, STOP_CLOSE_MS, STOP_FINISH_MS, silenceSaid, MAX_FORMAT_REPAIRS, joinNotes;
25505
26026
  var init_watch = __esm({
25506
26027
  "../cli/src/lib/agent/watch.ts"() {
25507
26028
  "use strict";
@@ -25522,6 +26043,7 @@ var init_watch = __esm({
25522
26043
  init_follow();
25523
26044
  init_propose();
25524
26045
  init_log();
26046
+ init_background();
25525
26047
  init_wire();
25526
26048
  init_prompts();
25527
26049
  init_resolve();
@@ -25534,7 +26056,6 @@ var init_watch = __esm({
25534
26056
  STOP_CLOSE_MS = 2e3;
25535
26057
  STOP_FINISH_MS = 1e4;
25536
26058
  silenceSaid = (minutes) => `the agent said nothing for ${minutes} minute${minutes === 1 ? "" : "s"}, so the run was ended.`;
25537
- backgroundSaid = (minutes) => `the agent's background tasks did not finish within ${minutes / 60} hours, so the run was ended.`;
25538
26059
  MAX_FORMAT_REPAIRS = 3;
25539
26060
  joinNotes = (...parts) => parts.filter(Boolean).join("\n\n") || void 0;
25540
26061
  }
@@ -25545,6 +26066,10 @@ import fs83 from "node:fs";
25545
26066
  import path83 from "node:path";
25546
26067
  async function cmdStartRun(action, args, opts, program2 = "akb") {
25547
26068
  const { req, follow: follow2, print } = readRequest(action, args, opts);
26069
+ if (!print && (action === "approve" || action === "implement")) {
26070
+ const deferred = await approveAfterReply(String(req.id), req.notes);
26071
+ if (deferred) return deferred;
26072
+ }
25548
26073
  if (Number.isInteger(req.id)) {
25549
26074
  const creating = creationRefusal(req.id, cardCreation(req.id, req.discard === true), action, req.discard === true);
25550
26075
  if (creating) die(creating, { kind: "card-being-created", action });
@@ -25587,13 +26112,13 @@ async function cmdStartRun(action, args, opts, program2 = "akb") {
25587
26112
  sayIfHeld(req, program2);
25588
26113
  const started = action === "refine" ? await startRefinement(req) : await startRun(runnable);
25589
26114
  if ("error" in started) die(started.error, { kind: "run-refused", action });
25590
- const { run: run2, spawned } = started;
25591
- if (!spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
25592
- say(`${action} \u2014 run ${run2.sessionId}${run2.deliveryId ? ` in delivery ${run2.deliveryId}` : ""}`);
25593
- say(` follow it: ${program2} raw run log ${short(run2.sessionId)} --follow${BOARD_FLAG}`);
25594
- say(` stop it: ${program2} raw run stop ${short(run2.sessionId)}${BOARD_FLAG}`);
25595
- if (follow2) return await followStarted(run2.sessionId, program2, opts.events === true);
25596
- return { sessionId: run2.sessionId, action, cardId: run2.cardId };
26115
+ const { run: run3, spawned } = started;
26116
+ if (!spawned) die(`couldn't start a process for run ${run3.sessionId}`, { kind: "spawn-failed" });
26117
+ say(`${action} \u2014 run ${run3.sessionId}${run3.deliveryId ? ` in delivery ${run3.deliveryId}` : ""}`);
26118
+ say(` follow it: ${program2} raw run log ${short(run3.sessionId)} --follow${BOARD_FLAG}`);
26119
+ say(` stop it: ${program2} raw run stop ${short(run3.sessionId)}${BOARD_FLAG}`);
26120
+ if (follow2) return await followStarted(run3.sessionId, program2, opts.events === true);
26121
+ return { sessionId: run3.sessionId, action, cardId: run3.cardId };
25597
26122
  }
25598
26123
  async function cmdRunScheduled(studio, agent, opts, program2 = "akb") {
25599
26124
  const id = knownStudio(studio);
@@ -25603,12 +26128,12 @@ async function cmdRunScheduled(studio, agent, opts, program2 = "akb") {
25603
26128
  if (insideRun() || opts.print) return printFlow(req, program2);
25604
26129
  const started = await startRun(req);
25605
26130
  if ("error" in started) die(started.error, { kind: "run-refused", action: "scheduled" });
25606
- const { run: run2, spawned } = started;
25607
- if (!spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
25608
- say(`${one.agent} \u2014 run ${run2.sessionId}${run2.deliveryId ? ` in delivery ${run2.deliveryId}` : ""}`);
25609
- say(` follow it: ${program2} raw run log ${short(run2.sessionId)} --follow${BOARD_FLAG}`);
25610
- if (opts.follow) return await followStarted(run2.sessionId, program2, opts.events === true);
25611
- return { sessionId: run2.sessionId, action: "scheduled" };
26131
+ const { run: run3, spawned } = started;
26132
+ if (!spawned) die(`couldn't start a process for run ${run3.sessionId}`, { kind: "spawn-failed" });
26133
+ say(`${one.agent} \u2014 run ${run3.sessionId}${run3.deliveryId ? ` in delivery ${run3.deliveryId}` : ""}`);
26134
+ say(` follow it: ${program2} raw run log ${short(run3.sessionId)} --follow${BOARD_FLAG}`);
26135
+ if (opts.follow) return await followStarted(run3.sessionId, program2, opts.events === true);
26136
+ return { sessionId: run3.sessionId, action: "scheduled" };
25612
26137
  }
25613
26138
  async function approveInCloud(project2, id) {
25614
26139
  const approved = await approveTask(project2, id);
@@ -25698,12 +26223,12 @@ function readRequest(action, args, opts) {
25698
26223
  async function cmdResume(id, opts) {
25699
26224
  const opened = await startResume(id ?? "last", opts.requireSession);
25700
26225
  if ("error" in opened) die(opened.error, { kind: "run-refused", ..."reason" in opened ? { reason: opened.reason } : {} });
25701
- const { run: run2 } = opened;
25702
- if (!opened.spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
25703
- const within = run2.deliveryId ? ` in delivery ${run2.deliveryId}` : "";
25704
- say(run2.resumedFrom ? `continuing ${short(run2.resumedFrom)} \u2014 run ${run2.sessionId}${within}` : `trying again \u2014 run ${run2.sessionId}${within}`);
25705
- if (opts.follow === true) return await followStarted(run2.sessionId, "akb", opts.events === true);
25706
- return { sessionId: run2.sessionId, resumedFrom: run2.resumedFrom };
26226
+ const { run: run3 } = opened;
26227
+ if (!opened.spawned) die(`couldn't start a process for run ${run3.sessionId}`, { kind: "spawn-failed" });
26228
+ const within = run3.deliveryId ? ` in delivery ${run3.deliveryId}` : "";
26229
+ say(run3.resumedFrom ? `continuing ${short(run3.resumedFrom)} \u2014 run ${run3.sessionId}${within}` : `trying again \u2014 run ${run3.sessionId}${within}`);
26230
+ if (opts.follow === true) return await followStarted(run3.sessionId, "akb", opts.events === true);
26231
+ return { sessionId: run3.sessionId, resumedFrom: run3.resumedFrom };
25707
26232
  }
25708
26233
  async function cmdCancel(named2) {
25709
26234
  const res = await cancelBoardDelivery(named2);
@@ -26058,6 +26583,7 @@ var init_run = __esm({
26058
26583
  init_io();
26059
26584
  init_lock();
26060
26585
  init_paths();
26586
+ init_reply_approval();
26061
26587
  init_tasks();
26062
26588
  init_read();
26063
26589
  init_rules();
@@ -26240,16 +26766,16 @@ async function cmdSpec(opts, program2 = "akb") {
26240
26766
  }
26241
26767
  const started = await startRun(req);
26242
26768
  if ("error" in started) die(started.error, { kind: "run-refused", action: "spec" });
26243
- const { run: run2, spawned } = started;
26244
- if (!spawned) die(`couldn't start a process to run ${run2.sessionId}`, { kind: "spawn-failed" });
26769
+ const { run: run3, spawned } = started;
26770
+ if (!spawned) die(`couldn't start a process to run ${run3.sessionId}`, { kind: "spawn-failed" });
26245
26771
  if (ownRuntime || ownSession) {
26246
26772
  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.`);
26247
26773
  }
26248
- say(`previews ${name} #${id} \u2014 run ${run2.sessionId}`);
26249
- say(` follow it: ${program2} raw run log ${short(run2.sessionId)} --follow${BOARD_FLAG}`);
26250
- say(` stop it: ${program2} raw run stop ${short(run2.sessionId)}${BOARD_FLAG}`);
26251
- if (opts.follow === true) return await followStarted(run2.sessionId, program2);
26252
- return { sessionId: run2.sessionId, action: "spec", specAgent: name, cardId: id };
26774
+ say(`previews ${name} #${id} \u2014 run ${run3.sessionId}`);
26775
+ say(` follow it: ${program2} raw run log ${short(run3.sessionId)} --follow${BOARD_FLAG}`);
26776
+ say(` stop it: ${program2} raw run stop ${short(run3.sessionId)}${BOARD_FLAG}`);
26777
+ if (opts.follow === true) return await followStarted(run3.sessionId, program2);
26778
+ return { sessionId: run3.sessionId, action: "spec", specAgent: name, cardId: id };
26253
26779
  }
26254
26780
  function noteOf(words, flag) {
26255
26781
  const typed = words.join(" ").trim();
@@ -26322,7 +26848,7 @@ var init_telemetry2 = __esm({
26322
26848
 
26323
26849
  // ../cli/src/commands/agent-check.ts
26324
26850
  import { spawnSync as spawnSync5 } from "node:child_process";
26325
- function run(file, args) {
26851
+ function run2(file, args) {
26326
26852
  const start = spawnable(file, args, { env: copyEnv(file), stdio: ["ignore", "pipe", "pipe"], timeout: 1e4 });
26327
26853
  const ran = spawnSync5(start.command, start.args, { ...start.options, encoding: "utf8" });
26328
26854
  return { out: `${ran.stdout ?? ""}${ran.stderr ?? ""}`.trim(), error: ran.error?.message };
@@ -26336,14 +26862,14 @@ function cmdAgentCheck(name) {
26336
26862
  const answer2 = { agent: harness.name, file: copy2?.file ?? null, version: copy2?.version ?? null };
26337
26863
  if (!copy2) die(`${harness.label} not found: no \`${binary}\` on the PATH or in its usual install folders.`, { kind: "agent-missing" });
26338
26864
  if (!copy2.starts) {
26339
- const said2 = run(copy2.file, ["--version"]);
26865
+ const said2 = run2(copy2.file, ["--version"]);
26340
26866
  die(`${harness.label} at ${copy2.file} failed to start: ${said2.error ?? said2.out.split("\n")[0] ?? "no output"}`, { kind: "agent-broken" });
26341
26867
  }
26342
26868
  if (harness.name === "dsh" && !dshFound(copy2.file, binaryOnPath)) {
26343
26869
  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" });
26344
26870
  }
26345
26871
  if (harness.login) {
26346
- const said2 = run(copy2.file, harness.login.args).out;
26872
+ const said2 = run2(copy2.file, harness.login.args).out;
26347
26873
  if (!harness.login.ready(said2) && harness.login.loggedOut(said2)) {
26348
26874
  die(`${harness.label} is signed out: run \`${harness.login.login}\`.`, { kind: "agent-signed-out" });
26349
26875
  }
@@ -26636,8 +27162,8 @@ function declareRuns(program2, cli) {
26636
27162
  if (code !== 0) throw new BoardError(`the watcher for ${sessionId} ended with ${code}`, { kind: "watch-failed" });
26637
27163
  });
26638
27164
  }
26639
- function declareRunning(run2, cli) {
26640
- const verb = (name) => withShared(run2.command(name));
27165
+ function declareRunning(run3, cli) {
27166
+ const verb = (name) => withShared(run3.command(name));
26641
27167
  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() {
26642
27168
  await onBoard2(this, cli, (p) => cmdRuns(this.opts(), p));
26643
27169
  });