wildcrane 0.11.44 → 0.11.46

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