wildcrane-runner 0.6.105 → 0.6.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/settings.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.105 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.106 — built by runner/scripts/build.mjs. Do not edit.
2
2
  import { createRequire as __ai4kanbanRequire } from 'node:module'
3
3
  const require = __ai4kanbanRequire(import.meta.url)
4
4
  var __create = Object.create;
@@ -61045,2004 +61045,963 @@ function cloudProblem(response, body) {
61045
61045
  }
61046
61046
 
61047
61047
  // src/protocol.ts
61048
- var VERSION = true ? "0.6.105" : "0.0.0";
61049
- var AKB_VERSION = true ? "0.11.85" : "0.0.0";
61048
+ var VERSION = true ? "0.6.106" : "0.0.0";
61049
+ var AKB_VERSION = true ? "0.11.86" : "0.0.0";
61050
61050
 
61051
- // src/api.ts
61052
- var RUNTIMES = ["claude-code", "codex", "cursor", "opencode", "kimi", "dsh", "zcode", "grok", "antigravity"];
61053
- var TIMEOUT_MS = 2e4;
61054
- async function send(method, route, body, signedIn, ms, type, extra = {}) {
61055
- const headers = { accept: "application/json", ...extra };
61056
- if (signedIn) {
61057
- const token = await accessToken();
61058
- if (!token.ok) {
61059
- return token.reason === "unreachable" ? { ok: false, error: token.error } : { ok: false, error: "Sign in again.", code: "unauthenticated" };
61060
- }
61061
- headers.authorization = `Bearer ${token.token}`;
61062
- }
61063
- const raw = body instanceof Uint8Array;
61064
- if (body !== void 0) headers["content-type"] = raw ? type ?? "application/octet-stream" : "application/json";
61065
- try {
61066
- const response = await fetch(`${cloudEndpoints().api}${route}`, {
61067
- method,
61068
- headers,
61069
- body: body === void 0 ? void 0 : raw ? body : JSON.stringify(body),
61070
- signal: AbortSignal.timeout(ms)
61071
- });
61072
- return { ok: true, value: response };
61073
- } catch (e) {
61074
- return { ok: false, error: e instanceof Error ? e.message : String(e) };
61075
- }
61076
- }
61077
- async function answerOf(response) {
61078
- const answer = await readCloudJson(response);
61079
- const problem = cloudProblem(response, answer) ?? (answer === void 0 ? invalidResponse("valid JSON") : null);
61080
- if (!problem) return { ok: true, value: answer };
61081
- const error62 = isRecord(answer) && isRecord(answer.error) ? answer.error : null;
61082
- return {
61083
- ok: false,
61084
- error: problem.message,
61085
- code: problem.code,
61086
- status: problem.status,
61087
- ...typeof error62?.project === "string" ? { project: error62.project } : {}
61088
- };
61089
- }
61090
- async function request(method, route, body, signedIn = true) {
61091
- const sent = await send(method, route, body, signedIn, TIMEOUT_MS);
61092
- return sent.ok ? answerOf(sent.value) : sent;
61093
- }
61094
- var FILE_TIMEOUT_MS = 10 * 6e4;
61095
- var readRunner = () => request("GET", "/v1/runner");
61096
- var q = encodeURIComponent;
61097
- var listFolders = (machineId2) => request("GET", `/v1/runner/folders?machine=${q(machineId2)}`);
61098
- var addFolder = (machineId2, name, path36, project) => request("POST", "/v1/runner/folders", { machineId: machineId2, name, path: path36, ...project ? { project } : {} });
61099
- async function createProject(name, workspace, key) {
61100
- const sent = await send("POST", "/v1/projects", { name, workspace }, true, TIMEOUT_MS, void 0, { "idempotency-key": key });
61101
- return sent.ok ? answerOf(sent.value) : sent;
61102
- }
61103
- var removeFolder = (machineId2, project) => request("POST", `/v1/runner/folders/${q(project)}/remove`, { machineId: machineId2 });
61104
-
61105
- // ../cli/src/lib/shared/board-conflicts.ts
61106
- var import_yaml7 = __toESM(require_dist(), 1);
61107
-
61108
- // ../cli/src/lib/agent/cloud-studios.ts
61109
- import fs8 from "node:fs";
61110
- import path10 from "node:path";
61111
-
61112
- // ../cli/src/lib/shared/file-limits.ts
61113
- var BOARD_FILE_LIMIT = 10 * 1024 * 1024;
61114
- var ASSET_FILE_LIMIT = 100 * 1024 * 1024;
61115
-
61116
- // ../cli/src/lib/shared/board-files.ts
61117
- var ROOTS = ["todo/", ".archive/", "memory/", "studios/", "triage/", "assets/", "rules/"];
61118
- var SETTINGS = ["modules.md", "config.md"];
61119
- var isSettingsPath = (path36) => SETTINGS.includes(path36) || /^rules\/(?:studios\/[^/]+|proposer|project-writer|dismissal-reviewer|memory-pruner)\.md$/.test(path36);
61120
- function isBoardPath(path36) {
61121
- if (!path36 || path36.length > 500 || path36.startsWith("/") || path36.includes("\\") || path36.includes("\0")) return false;
61122
- if (path36.split("/").some((part) => !part || part === "." || part === "..")) return false;
61123
- if (path36 === "todo/README.md" || path36.split("/").includes(".sync")) return false;
61124
- if (path36.startsWith("studios/")) return true;
61125
- if (SETTINGS.includes(path36)) return true;
61126
- if (path36.startsWith("rules/")) return isSettingsPath(path36);
61127
- if (path36.startsWith("assets/")) return taskOfAssets(path36) !== null;
61128
- return ROOTS.some((root2) => path36.startsWith(root2)) && path36.endsWith(".md");
61129
- }
61130
- var taskOfAssets = (path36) => /^assets\/(task_[0-9a-f]+)\.json$/.exec(path36)?.[1] ?? null;
61131
- var studioFolder = (id2) => id2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
61132
- var studioName = (id2) => id2.startsWith("wf_builtin_") ? id2.slice("wf_builtin_".length).replace(/_/g, "-") : studioFolder(id2);
61051
+ // ../cli/src/lib/agent/harnesses/antigravity.ts
61052
+ import fs7 from "node:fs";
61053
+ import path9 from "node:path";
61054
+ import { createHash as createHash3 } from "node:crypto";
61055
+ import { spawnSync as spawnSync2 } from "node:child_process";
61133
61056
 
61134
- // ../official/pack.ts
61135
- import crypto2 from "node:crypto";
61057
+ // ../cli/src/lib/agent/locate.ts
61058
+ import { spawn, spawnSync } from "node:child_process";
61136
61059
  import fs4 from "node:fs";
61060
+ import os4 from "node:os";
61137
61061
  import path5 from "node:path";
61138
- import { fileURLToPath } from "node:url";
61139
-
61140
- // ../cli/src/lib/agent/studio-def.ts
61141
- var import_ajv = __toESM(require_ajv(), 1);
61142
- var import_yaml = __toESM(require_dist(), 1);
61143
-
61144
- // ../cli/src/lib/agents/icon.ts
61145
- var ICON_NAMES = [
61146
- "file",
61147
- "text",
61148
- "article",
61149
- "outline",
61150
- "script",
61151
- "prompt",
61152
- "email",
61153
- "image",
61154
- "post-image",
61155
- "social-image",
61156
- "cover",
61157
- "carousel",
61158
- "carousel-outline",
61159
- "slides",
61160
- "wireframe",
61161
- "screen",
61162
- "video",
61163
- "storyboard",
61164
- "template",
61165
- "shots",
61166
- "api",
61167
- "schema",
61168
- "compare",
61169
- "stack",
61170
- "studio",
61171
- "code",
61172
- "checklist",
61173
- "card",
61174
- "plan",
61175
- "proposal",
61176
- "dismissed",
61177
- "inbox",
61178
- "notebook",
61179
- "squeeze",
61180
- "folder",
61181
- "reply",
61182
- "feedback",
61183
- "software",
61184
- "product-video",
61185
- "social-post",
61186
- "blog",
61187
- "deck",
61188
- "video-clone",
61189
- "studio-kit"
61190
- ];
61191
- var ICON_COLORS = ["k", "w", "c", "g", "o", "p", "s", "m", "l", "r", "y"];
61192
61062
 
61193
- // ../cli/src/lib/shared/preview-blocks.ts
61194
- var PREVIEW_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
61195
- function sourcePosition(source, offset) {
61196
- const before = source.slice(0, offset);
61197
- return { line: before.split("\n").length, column: offset - before.lastIndexOf("\n") };
61198
- }
61199
- function withoutCode(source) {
61200
- const blank = (s) => s.replace(/[^\n\r]/g, " ");
61201
- let fence;
61202
- let indented = false, afterBlank = true, inList = false;
61203
- return source.split(/(?<=\n)/).map((line) => {
61204
- const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
61205
- if (fence) {
61206
- if (marker && marker[1][0] === fence.char && marker[1].length >= fence.length && !marker[2].trim()) fence = void 0;
61207
- return blank(line);
61208
- }
61209
- if (marker) {
61210
- fence = { char: marker[1][0], length: marker[1].length };
61211
- return blank(line);
61212
- }
61213
- if (!line.trim()) {
61214
- afterBlank = true;
61215
- return line;
61216
- }
61217
- const hasIndent = /^(?: {4}|\t)/.test(line);
61218
- if (!hasIndent) indented = false;
61219
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s/.test(line)) inList = true;
61220
- else if (/^\S/.test(line)) inList = false;
61221
- if (hasIndent && (indented || afterBlank && !inList)) {
61222
- indented = true;
61223
- return blank(line);
61063
+ // ../cli/src/lib/agent/argv.ts
61064
+ function splitCommand(command) {
61065
+ const argv = [];
61066
+ let word = "";
61067
+ let started = false;
61068
+ let quote2 = "";
61069
+ for (const ch of command) {
61070
+ if (quote2) {
61071
+ if (ch === quote2) quote2 = "";
61072
+ else word += ch;
61073
+ continue;
61224
61074
  }
61225
- afterBlank = false;
61226
- return line;
61227
- }).join("").replace(/(`+)([^]*?)\1(?!`)/g, blank);
61228
- }
61229
- function parsePreviewBlocks(source, file3 = "STUDIO.md") {
61230
- const blocks = [], problems = [];
61231
- const masked = withoutCode(source);
61232
- let open2;
61233
- const seen = /* @__PURE__ */ new Set();
61234
- const fail = (offset, id2, code, message, hint2) => problems.push({ file: file3, ...sourcePosition(source, offset), path: id2 ? `previews.${id2}` : "previews", code, message, hint: hint2 });
61235
- for (const tag of masked.matchAll(/<\/?Preview\b[^>]*(?:>|$)/g)) {
61236
- const offset = tag.index, text2 = tag[0];
61237
- const closing = /^<\/Preview\s*>$/.test(text2);
61238
- if (closing) {
61239
- if (!open2) fail(offset, "", "preview-unexpected-close", "Preview has no opening tag", "Remove it or restore its opening tag.");
61240
- else {
61241
- const instructions = source.slice(open2.content, offset).trim();
61242
- if (!instructions) fail(open2.start, open2.id, "preview-empty", `Preview ${open2.id} is empty`, "Describe the requested output inside the block.");
61243
- blocks.push({ id: open2.id, instructions, start: open2.start, end: offset + text2.length });
61244
- open2 = void 0;
61245
- }
61075
+ if (ch === '"' || ch === "'") {
61076
+ quote2 = ch;
61077
+ started = true;
61246
61078
  continue;
61247
61079
  }
61248
- const opening = /^<Preview\s+id=(?:"([^"]*)"|'([^']*)')\s*>$/.exec(text2);
61249
- if (!opening || open2) {
61250
- fail(offset, open2?.id ?? "", "preview-tag", "Malformed or nested Preview tag", 'Use one non-nested <Preview id="stable-id"> block with only id.');
61080
+ if (/\s/.test(ch)) {
61081
+ if (started) argv.push(word);
61082
+ word = "";
61083
+ started = false;
61251
61084
  continue;
61252
61085
  }
61253
- const id2 = opening[1] ?? opening[2];
61254
- if (!PREVIEW_ID.test(id2) || seen.has(id2)) fail(offset, id2, "preview-id", `Invalid or repeated Preview ID ${id2}`, "Use a unique lowercase ID with digits and dashes.");
61255
- seen.add(id2);
61256
- open2 = { id: id2, start: offset, content: offset + text2.length };
61086
+ word += ch;
61087
+ started = true;
61257
61088
  }
61258
- if (open2) fail(open2.start, open2.id, "preview-unclosed", `Preview ${open2.id} is not closed`, "Add </Preview> after this block.");
61259
- return { blocks, problems };
61089
+ if (started) argv.push(word);
61090
+ return argv;
61260
61091
  }
61261
61092
 
61262
- // ../cli/src/lib/agent/studio-def.ts
61263
- var STUDIO_ID = PREVIEW_ID;
61264
- var titles = { type: "object", minProperties: 1, propertyNames: { pattern: "^[a-z]{2,3}(?:-[A-Za-z0-9]+)*$" }, additionalProperties: { type: "string", minLength: 1, pattern: "\\S" } };
61265
- var icon = { anyOf: [
61266
- { type: "string", enum: ICON_NAMES },
61267
- { type: "array", minItems: 1, maxItems: 12, items: { type: "object", required: ["d"], additionalProperties: false, properties: {
61268
- d: { type: "string", minLength: 1, pattern: "^[MmLlHhVvCcSsQqTtAaZz0-9.,\\s-]+$" },
61269
- f: { enum: ICON_COLORS },
61270
- o: { const: true },
61271
- s: { enum: ICON_COLORS },
61272
- w: { type: "number", exclusiveMinimum: 0, maximum: 3 }
61273
- } } }
61274
- ] };
61275
- var STUDIO_SCHEMA = {
61276
- type: "object",
61277
- required: ["name"],
61278
- additionalProperties: false,
61279
- properties: {
61280
- name: { type: "string", minLength: 1, pattern: "\\S" },
61281
- names: titles,
61282
- description: { type: "string" },
61283
- needsArtifact: { type: "boolean" },
61284
- icon,
61285
- previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
61286
- type: "object",
61287
- additionalProperties: false,
61288
- properties: { title: titles, description: titles, icon }
61289
- } }
61290
- }
61291
- };
61292
- var validate2 = new import_ajv.Ajv({ allErrors: true, meta: false, validateSchema: false }).compile(STUDIO_SCHEMA);
61293
- function landSections(body, previews) {
61294
- const blank = (text2) => text2.replace(/[^\r\n]/g, " ");
61295
- let visible = "", at = 0;
61296
- for (const { start, end } of previews) {
61297
- visible += body.slice(at, start) + blank(body.slice(start, end));
61298
- at = end;
61299
- }
61300
- visible += body.slice(at);
61301
- const comments = /<!--[^]*?(?:-->|$)/g;
61302
- const markdown = withoutCode(visible).replace(comments, blank);
61303
- const headings = [...markdown.matchAll(/^ {0,3}#{1,2}(?=[ \t\r\n]|$)[^\r\n]*/gm)];
61304
- return headings.flatMap((heading, index) => {
61305
- const start = heading.index;
61306
- const end = start + heading[0].length;
61307
- if (!/^ {0,3}##[ \t]+Land(?:[ \t]+#+)?[ \t]*$/.test(visible.slice(start, end))) return [];
61308
- return [{
61309
- offset: start + heading[0].indexOf("#"),
61310
- empty: !visible.slice(end, headings[index + 1]?.index).replace(comments, "").trim()
61311
- }];
61312
- });
61093
+ // ../cli/src/lib/agent/installed.ts
61094
+ var WINDOWS = process.platform === "win32";
61095
+ function commandBinary(command) {
61096
+ return splitCommand(command)[0] ?? "";
61313
61097
  }
61314
- function parseStudioFile(id2, source, from, { requirePreviewCopy = false, requireLand = false } = {}) {
61315
- const problems = [];
61316
- const fail = (offset, path36, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source, offset), path: path36, code, message, hint: hint2 });
61317
- const result = () => ({ problem: problems.map((p) => `${p.file}:${p.line}:${p.column} ${p.path}: ${p.code} \u2014 ${p.message}. ${p.hint}`).join("\n"), problems });
61318
- if (!STUDIO_ID.test(id2)) fail(0, "id", "studio-schema", `Invalid Studio ID ${id2}`, "Use lowercase letters, digits and dashes.");
61319
- const front = /^---\r?\n([^]*?)\r?\n---(?:\r?\n|$)/.exec(source);
61320
- if (!front) {
61321
- fail(0, "", "yaml-syntax", "Missing YAML frontmatter", "Enclose metadata between --- lines.");
61322
- return result();
61098
+
61099
+ // ../cli/src/lib/agent/spawnable.ts
61100
+ import fs3 from "node:fs";
61101
+ import path4 from "node:path";
61102
+ var META = /([()\][%!^"`<>&|;, *?])/g;
61103
+ function cmdArg(arg) {
61104
+ const quoted = `"${arg.replace(/\r?\n|\r/g, " ").replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
61105
+ return quoted.replace(META, "^$1").replace(META, "^$1");
61106
+ }
61107
+ function cmdLine(file3, args2) {
61108
+ return `"${[file3.replace(META, "^$1"), ...args2.map(cmdArg)].join(" ")}"`;
61109
+ }
61110
+ function shimTarget(text2, file3) {
61111
+ const dir = path4.win32.dirname(file3);
61112
+ const found = /"%(?:~dp0|dp0%)\\?([^"%]+)"\s+%\*/i.exec(text2);
61113
+ if (!found || !/\\node\.exe"/i.test(text2)) return null;
61114
+ const script = path4.win32.resolve(dir, found[1].replace(/\//g, "\\"));
61115
+ const local = path4.win32.join(dir, "node.exe");
61116
+ const nodePath = /SET "NODE_PATH=([^"]*)"/i.exec(text2)?.[1];
61117
+ return { script, node: fs3.existsSync(local) ? local : "node", env: nodePath ? { NODE_PATH: nodePath } : {} };
61118
+ }
61119
+ function onWindowsPath(name, env2) {
61120
+ const exts = (env2.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
61121
+ const key = Object.keys(env2).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
61122
+ for (const dir of (env2[key] ?? "").split(";").filter(Boolean)) {
61123
+ for (const ext of exts) {
61124
+ const file3 = path4.win32.join(dir, `${name}${ext.toLowerCase()}`);
61125
+ if (fs3.existsSync(file3)) return file3;
61126
+ }
61323
61127
  }
61324
- const metaOffset = source.indexOf("\n") + 1, bodyOffset = front[0].length;
61325
- const counter = new import_yaml.LineCounter();
61326
- const document = (0, import_yaml.parseDocument)(front[1], { lineCounter: counter, uniqueKeys: true, strict: true });
61327
- for (const error62 of document.errors) fail(metaOffset + (error62.pos[0] ?? 0), "", error62.code === "DUPLICATE_KEY" ? "yaml-duplicate-key" : "yaml-syntax", error62.message.split("\n")[0], "Correct the indicated YAML location.");
61328
- if (problems.length) return result();
61329
- let raw;
61128
+ return void 0;
61129
+ }
61130
+ function spawnable(command, args2, options = {}, platform = process.platform) {
61131
+ if (platform !== "win32") return { command, args: args2, options };
61132
+ const env2 = options.env ?? process.env;
61133
+ const file3 = path4.extname(command) || /[\\/]/.test(command) ? command : onWindowsPath(command, env2) ?? command;
61134
+ const ext = path4.extname(file3).toLowerCase();
61135
+ const hidden = { ...options, windowsHide: true, shell: false };
61136
+ if (ext !== ".cmd" && ext !== ".bat") return { command: file3, args: args2, options: hidden };
61137
+ let text2 = "";
61330
61138
  try {
61331
- raw = document.toJS({ maxAliasCount: 0 });
61139
+ text2 = fs3.readFileSync(file3, "utf8");
61332
61140
  } catch {
61333
- fail(metaOffset, "", "yaml-syntax", "YAML aliases are not supported", "Write metadata explicitly.");
61334
- return result();
61335
61141
  }
61336
- if (!validate2(raw)) {
61337
- for (const error62 of validate2.errors ?? []) {
61338
- const parts = error62.instancePath.split("/").slice(1);
61339
- const key = error62.params.additionalProperty ?? error62.params.missingProperty;
61340
- if (key) parts.push(String(key));
61341
- const node2 = parts.length ? document.getIn(parts, true) : document.contents;
61342
- fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
61343
- }
61142
+ const shim = shimTarget(text2, file3);
61143
+ if (shim) {
61144
+ return { command: shim.node, args: [shim.script, ...args2], options: { ...hidden, env: { ...env2, ...shim.env } } };
61344
61145
  }
61345
- const body = source.slice(bodyOffset);
61346
- const parsed = parsePreviewBlocks(body, from);
61347
- problems.push(...parsed.problems.map((p) => ({ ...p, line: p.line + source.slice(0, bodyOffset).split("\n").length - 1 })));
61348
- if (problems.length) return result();
61349
- const map2 = raw.previews ?? {};
61350
- for (const block of parsed.blocks) if (!Object.hasOwn(map2, block.id)) fail(bodyOffset + block.start, `previews.${block.id}`, "preview-metadata-missing", `Preview ${block.id} has no metadata entry`, "Add the ID under previews, using {} if needed.");
61351
- for (const key of Object.keys(map2)) if (!parsed.blocks.some((b) => b.id === key)) fail(metaOffset + (document.getIn(["previews", key], true)?.range?.[0] ?? 0), `previews.${key}`, "preview-body-missing", `Preview ${key} has no body`, "Add its block or remove unused metadata.");
61352
- if (requirePreviewCopy) for (const block of parsed.blocks) {
61353
- const metadata = Object.hasOwn(map2, block.id) ? map2[block.id] : void 0;
61354
- if (!metadata) continue;
61355
- for (const field of ["title", "description"]) for (const lang of ["en", "zh"]) {
61356
- if (metadata[field]?.[lang]) continue;
61357
- fail(
61358
- bodyOffset + block.start,
61359
- `previews.${block.id}.${field}.${lang}`,
61360
- "preview-display-missing",
61361
- `Preview ${block.id} needs a ${lang} ${field}`,
61362
- "Add non-blank en and zh display text in the Preview metadata."
61363
- );
61364
- }
61146
+ return {
61147
+ command: env2.ComSpec || process.env.ComSpec || "cmd.exe",
61148
+ args: ["/d", "/s", "/c", cmdLine(file3, args2)],
61149
+ options: { ...hidden, windowsVerbatimArguments: true }
61150
+ };
61151
+ }
61152
+
61153
+ // ../cli/src/lib/agent/locate.ts
61154
+ var WINDOWS2 = process.platform === "win32";
61155
+ var PROBE_MS = 3e3;
61156
+ var KEEP_MS = 60 * 6e4;
61157
+ var SPAWN_MS = 5 * 6e4;
61158
+ function versionIn(output3) {
61159
+ const plain = output3.replace(/\x1b\[[0-9;]*m/g, "");
61160
+ return /(?<![\w.-])v?(\d+(?:\.\d+)+(?:-[0-9A-Za-z.-]+)?)/.exec(plain)?.[1] ?? null;
61161
+ }
61162
+ var RELEASE_STAGE = /^(alpha|beta|canary|dev|next|nightly|pre|preview|rc)[.-]?(\d*)$/i;
61163
+ function compareVersions(a, b) {
61164
+ const [numberA = "", ...restA] = a.split("-");
61165
+ const [numberB = "", ...restB] = b.split("-");
61166
+ const [x, y] = [numberA.split(".").map(Number), numberB.split(".").map(Number)];
61167
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
61168
+ const step = (x[i] ?? 0) - (y[i] ?? 0);
61169
+ if (step) return step;
61365
61170
  }
61366
- if (requireLand) {
61367
- const sections = landSections(body, parsed.blocks);
61368
- if (!sections.length) fail(bodyOffset, "Land", "studio-land-missing", "Missing ## Land section", "Add ## Land to the Studio body and describe delivery, checks and what to record.");
61369
- for (const [index, { offset, empty }] of sections.entries()) {
61370
- if (index) fail(bodyOffset + offset, "Land", "studio-land-duplicate", "Repeated ## Land section", "Combine delivery instructions under one ## Land heading.");
61371
- if (empty) fail(bodyOffset + offset, "Land", "studio-land-empty", "The ## Land section is empty", "Describe delivery, checks and what to record under ## Land.");
61372
- }
61171
+ const [tagA, tagB] = [restA.join("-"), restB.join("-")];
61172
+ if (tagA === tagB) return 0;
61173
+ if (/^\d+$/.test(tagA) && /^\d+$/.test(tagB)) return Number(tagA) - Number(tagB);
61174
+ const [stageA, stageB] = [RELEASE_STAGE.exec(tagA), RELEASE_STAGE.exec(tagB)];
61175
+ if (!tagA && stageB) return 1;
61176
+ if (stageA && !tagB) return -1;
61177
+ if (stageA && stageB && stageA[1].toLowerCase() === stageB[1].toLowerCase()) {
61178
+ return Number(stageA[2] || 0) - Number(stageB[2] || 0);
61373
61179
  }
61374
- if (problems.length) return result();
61375
- let rules = "", at = 0;
61376
- for (const block of parsed.blocks) {
61377
- rules += body.slice(at, block.start);
61378
- at = block.end;
61180
+ return null;
61181
+ }
61182
+ function newest(copies) {
61183
+ let best = copies[0] ?? null;
61184
+ for (const copy2 of copies) {
61185
+ if (!copy2.version) return null;
61186
+ for (const other of copies) {
61187
+ if (!other.version || compareVersions(copy2.version, other.version) === null) return null;
61188
+ }
61189
+ if (compareVersions(copy2.version, best.version) > 0) best = copy2;
61379
61190
  }
61380
- rules += body.slice(at);
61381
- return { def: {
61382
- id: id2,
61383
- name: raw.name.trim(),
61384
- ...raw.names ? { names: raw.names } : {},
61385
- description: raw.description ?? "",
61386
- needsArtifact: raw.needsArtifact ?? false,
61387
- ...raw.icon ? { icon: raw.icon } : {},
61388
- previews: parsed.blocks.map((b) => ({ id: b.id, instructions: b.instructions, ...map2[b.id] })),
61389
- rules: rules.trim()
61390
- } };
61191
+ return best;
61391
61192
  }
61392
-
61393
- // ../cli/src/lib/agent/studio-folder.ts
61394
- import fs3 from "node:fs";
61395
- import path4 from "node:path";
61396
-
61397
- // ../cli/src/lib/shared/guide-topics.ts
61398
- var GUIDE_TOPICS = ["board", "writing", "add-task", "follow-up", "discuss-goal", "troubleshoot", "card-chat", "update-studio", "implement", "settle-background", "archive", "update-questions", "refine", "revise", "resolve", "prune-memory", "review-memory", "describe-project", "review-rejections", "reflect", "write-agent", "write-prompt", "module-map"];
61399
-
61400
- // ../cli/src/lib/shared/studio-files.ts
61401
- var STUDIO_FILE = "STUDIO.md";
61402
- var MCP_FILE = "mcp.json";
61403
- var CARD_TEMPLATE_FILE = "CARD.md";
61404
- var VERSION_FILE = "version.json";
61405
- var KB = 1024;
61406
- var FILE_LIMITS = { file: 2 * KB * KB, total: 2 * KB * KB, count: 500, path: 512 };
61407
- var officialId = (folder2) => `wf_builtin_${folder2.replace(/-/g, "_")}`;
61408
- var hashInput = (files) => JSON.stringify(Object.entries(files).sort(([a], [b]) => a < b ? -1 : 1));
61409
- var landsOf = (_def) => ({ lands: true });
61410
- var SEGMENT = /^[\w.-]+$/;
61411
- var isAboutFile = (file3) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file3) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file3);
61412
- var bytes = (text2) => new TextEncoder().encode(text2).length;
61413
- var isSharedFile = (file3) => {
61414
- const parts = file3.split("/");
61415
- return parts.length > 1 && parts[0] === "shared" && parts.slice(1).every((p) => SEGMENT.test(p) && p !== "." && p !== "..");
61416
- };
61417
- function folderPath(file3, top) {
61418
- const parts = file3.split("/");
61419
- if (parts.length < 3 || parts[0] !== top || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(parts[1])) return null;
61420
- if (parts.slice(2).some((p) => !SEGMENT.test(p) || p === "." || p === "..")) return null;
61421
- return [parts[1], parts.slice(2).join("/")];
61193
+ function pick2(copies) {
61194
+ const live = copies.filter((copy2) => copy2.starts);
61195
+ if (!live.length) return copies.find((copy2) => copy2.entry) ?? copies[0] ?? null;
61196
+ const entry = live.find((copy2) => copy2.entry);
61197
+ const best = newest(live);
61198
+ if (best) return entry && compareVersions(entry.version, best.version) === 0 ? entry : best;
61199
+ return entry ?? newest(live.filter((copy2) => copy2.version)) ?? live[0];
61422
61200
  }
61423
- function mcpProblem(text2) {
61424
- let read3;
61201
+ function folders(parent) {
61425
61202
  try {
61426
- read3 = JSON.parse(text2);
61203
+ return fs4.readdirSync(parent, { withFileTypes: true }).filter((one) => one.isDirectory()).map((one) => one.name);
61427
61204
  } catch {
61428
- return "is not JSON";
61429
- }
61430
- const servers = read3?.mcpServers;
61431
- if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "must hold `mcpServers`, an object of name \u2192 server";
61432
- for (const [name, server] of Object.entries(servers)) {
61433
- const { command, args: args2, ...rest } = server ?? {};
61434
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return `names a server \`${name}\`; use lowercase letters, digits and dashes`;
61435
- if (typeof command !== "string" || !command) return `server \`${name}\` needs a \`command\``;
61436
- if (args2 !== void 0 && !(Array.isArray(args2) && args2.every((a) => typeof a === "string"))) return `server \`${name}\`: \`args\` must be a list of strings`;
61437
- if (Object.keys(rest).length) return `server \`${name}\` takes only \`command\` and \`args\``;
61205
+ return [];
61438
61206
  }
61439
- return null;
61440
61207
  }
61441
- function formatStudioProblem({ file: file3, line, column, reason, hint: hint2 }) {
61442
- const location = line === void 0 ? file3 : `${file3}:${line}:${column ?? 1}`;
61443
- return `${location}: ${reason}${hint2 ? `. ${hint2}` : ""}`;
61208
+ function byVersion(names) {
61209
+ const numbers = (name) => /(\d+(?:\.\d+)+)/.exec(name)?.[1]?.split(".").map(Number) ?? [];
61210
+ return [...names].sort((a, b) => {
61211
+ const [x, y] = [numbers(a), numbers(b)];
61212
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
61213
+ const step = (y[i] ?? -1) - (x[i] ?? -1);
61214
+ if (step) return step;
61215
+ }
61216
+ return a < b ? -1 : a > b ? 1 : 0;
61217
+ });
61444
61218
  }
61445
- function checkStudioFiles(value, official = false, checks = {}) {
61446
- const read3 = inspect(value, official, checks);
61447
- const first = read3.problems[0];
61448
- return first ? { ok: false, ...first, problems: read3.problems } : { ok: true, def: read3.def, files: read3.files };
61219
+ function latestIn(parent, tail = "") {
61220
+ let names;
61221
+ try {
61222
+ names = fs4.readdirSync(parent);
61223
+ } catch {
61224
+ return [];
61225
+ }
61226
+ return byVersion(names.filter((name) => !name.startsWith("."))).slice(0, 2).map((name) => path5.join(parent, name, tail));
61449
61227
  }
61450
- function inspect(value, official, { allowLegacyPreviewCopy, allowLegacyLand } = {}) {
61451
- const problems = [];
61452
- const fail = (file3, reason, tooLarge = false) => {
61453
- problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
61454
- return { problems };
61455
- };
61456
- if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
61457
- const files = Object.fromEntries(Object.entries(value).filter(([file3]) => file3 !== VERSION_FILE));
61458
- const entries = Object.entries(files);
61459
- if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
61460
- let total = 0;
61461
- const skills = /* @__PURE__ */ new Set();
61462
- for (const [file3, text2] of entries) {
61463
- if (typeof text2 !== "string" || text2.includes("\0")) {
61464
- fail(file3, "is not a text file");
61465
- continue;
61466
- }
61467
- if (file3.length > FILE_LIMITS.path) {
61468
- fail(file3, `the path is longer than ${FILE_LIMITS.path} characters`);
61469
- continue;
61470
- }
61471
- const size = bytes(text2);
61472
- if (size > FILE_LIMITS.file) return fail(file3, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
61473
- total += size;
61474
- if (total > FILE_LIMITS.total) return fail("files", `are larger than ${FILE_LIMITS.total / KB / KB} MB together`, true);
61475
- if (file3 === STUDIO_FILE || file3 === CARD_TEMPLATE_FILE) continue;
61476
- if (official && file3 === MCP_FILE) {
61477
- const problem = mcpProblem(text2);
61478
- if (problem) fail(file3, problem);
61479
- continue;
61480
- }
61481
- if (official && isAboutFile(file3)) continue;
61482
- if (official && file3.startsWith("skills/")) {
61483
- if (!folderPath(file3, "skills")) fail(file3, "is not inside skills/<name>/");
61484
- else skills.add(file3.split("/")[1]);
61485
- continue;
61486
- }
61487
- if (isSharedFile(file3)) continue;
61488
- if (/^(?:references|scripts)\//.test(file3) && file3.split("/").every((p) => SEGMENT.test(p) && p !== "." && p !== "..")) continue;
61489
- fail(file3, `use ${STUDIO_FILE}, ${CARD_TEMPLATE_FILE}, references/, scripts/ or shared/`);
61490
- }
61491
- for (const name of skills) {
61492
- if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
61493
- }
61494
- const source = files[STUDIO_FILE];
61495
- const read3 = typeof source === "string" ? parseStudioFile("studio", source, STUDIO_FILE, { requirePreviewCopy: !official && !allowLegacyPreviewCopy, requireLand: !allowLegacyLand }) : null;
61496
- if (!read3) fail(STUDIO_FILE, "is missing");
61497
- else if ("problem" in read3) for (const problem of read3.problems) problems.push({ ...problem, reason: problem.message });
61498
- if (!read3 || "problem" in read3) return { problems };
61499
- const def = read3.def;
61500
- for (const [file3, text2] of Object.entries(files)) {
61501
- if (typeof text2 !== "string" || !file3.endsWith(".md")) continue;
61502
- const masked = withoutCode(text2);
61503
- const reference = (offset, link, message) => problems.push({ file: file3, ...sourcePosition(text2, offset), path: link, code: "studio-reference", message, reason: message, hint: "Use an existing safe relative resource or a shipped AKB Guide." });
61504
- for (const match of masked.matchAll(/!?\[[^\]]*\]\(([^\s)]+)(?:\s+[^)]*)?\)/g)) {
61505
- const link = match[1].replace(/^<|>$/g, "");
61506
- if (/^(?:https?:|mailto:|#)/i.test(link)) continue;
61507
- let decoded;
61508
- try {
61509
- decoded = decodeURIComponent(link.split(/[?#]/)[0]);
61510
- } catch {
61511
- reference(match.index, link, "Invalid resource URL");
61512
- continue;
61513
- }
61514
- if (/^(?:[a-z][\w+.-]*:|[/\\])|\\/i.test(decoded) || decoded.split("/").includes("..")) {
61515
- reference(match.index, link, "Unsafe resource path");
61516
- continue;
61517
- }
61518
- const target = [...file3.split("/").slice(0, -1), ...decoded.split("/").filter((p) => p !== ".")].join("/");
61519
- if (!Object.hasOwn(files, target)) reference(match.index, link, `Missing resource ${target}`);
61520
- }
61521
- for (const match of text2.matchAll(/akb guide ([a-z][a-z-]*)/g)) if (!GUIDE_TOPICS.includes(match[1])) reference(match.index, match[1], `Unknown AKB Guide ${match[1]}`);
61228
+ var env = (name) => process.env[name]?.trim() ?? "";
61229
+ function commonDirs() {
61230
+ const home3 = os4.homedir();
61231
+ const under = (...parts) => path5.join(home3, ...parts);
61232
+ const nodes = (root2, tail = []) => root2 ? folders(root2).map((version2) => path5.join(root2, version2, ...tail)) : [];
61233
+ if (WINDOWS2) {
61234
+ const [app, local, data, programs] = [env("APPDATA"), env("LOCALAPPDATA"), env("ProgramData"), env("ProgramFiles")];
61235
+ return [
61236
+ under(".local", "bin"),
61237
+ under(".bun", "bin"),
61238
+ under("scoop", "shims"),
61239
+ ...app ? [path5.join(app, "npm")] : [],
61240
+ ...local ? [path5.join(local, "pnpm"), path5.join(local, "Volta", "bin"), path5.join(local, "Microsoft", "WinGet", "Links")] : [],
61241
+ ...data ? [path5.join(data, "chocolatey", "bin")] : [],
61242
+ ...programs ? [path5.join(programs, "nodejs")] : [],
61243
+ ...nodes(env("NVM_HOME")),
61244
+ ...app ? nodes(path5.join(app, "fnm", "node-versions"), ["installation"]) : []
61245
+ ];
61522
61246
  }
61523
- return { problems, def, files };
61524
- }
61525
-
61526
- // ../cli/src/lib/agent/studio-folder.ts
61527
- var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
61528
- function filesOf(dir, base = dir) {
61529
- return fs3.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".")).flatMap((e) => {
61530
- const full = path4.join(dir, e.name);
61531
- if (e.isSymbolicLink()) throw new Error(`${full}: symbolic links are not allowed`);
61532
- return e.isDirectory() ? filesOf(full, base) : [path4.relative(base, full).split(path4.sep).join("/")];
61533
- });
61247
+ const support = process.platform === "darwin" ? under("Library", "Application Support") : under(".local", "share");
61248
+ return [
61249
+ under(".local", "bin"),
61250
+ under("bin"),
61251
+ "/usr/local/bin",
61252
+ "/usr/bin",
61253
+ // Not on macOS, where a stat under /home waits on the automounter.
61254
+ process.platform === "darwin" ? "/opt/homebrew/bin" : "/home/linuxbrew/.linuxbrew/bin",
61255
+ under(".npm-global", "bin"),
61256
+ under(".yarn", "bin"),
61257
+ under(".bun", "bin"),
61258
+ ...env("PNPM_HOME") ? [env("PNPM_HOME")] : [],
61259
+ under("Library", "pnpm"),
61260
+ under(".local", "share", "pnpm"),
61261
+ path5.join(env("VOLTA_HOME") || under(".volta"), "bin"),
61262
+ ...nodes(path5.join(env("NVM_DIR") || under(".nvm"), "versions", "node"), ["bin"]),
61263
+ ...nodes(path5.join(env("FNM_DIR") || path5.join(support, "fnm"), "node-versions"), ["installation", "bin"]),
61264
+ ...nodes(path5.join(env("ASDF_DATA_DIR") || under(".asdf"), "installs", "nodejs"), ["bin"]),
61265
+ ...nodes(under(".local", "share", "mise", "installs", "node"), ["bin"]),
61266
+ ...nodes(under(".nodenv", "versions"), ["bin"]),
61267
+ ...nodes("/usr/local/n/versions/node", ["bin"])
61268
+ ];
61534
61269
  }
61535
- function readStudioFile(dir, file3) {
61536
- const full = path4.join(dir, file3);
61537
- return isAboutFile(file3) && !file3.endsWith(".md") ? `data:${MIME[path4.extname(file3)]};base64,${fs3.readFileSync(full).toString("base64")}` : fs3.readFileSync(full, "utf8");
61270
+ function onPath(binary) {
61271
+ const names = WINDOWS2 ? (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((ext) => `${binary}${ext.toLowerCase()}`) : [binary];
61272
+ return (process.env.PATH ?? "").split(path5.delimiter).filter(Boolean).flatMap((dir) => names.map((name) => path5.join(dir, name)));
61538
61273
  }
61539
- var readStudioFolder = (dir) => Object.fromEntries(filesOf(dir).sort().map((f) => [f, readStudioFile(dir, f)]));
61540
-
61541
- // ../official/pack.ts
61542
- var OFFICIAL = path5.dirname(fileURLToPath(import.meta.url));
61543
- var dirs = (dir) => fs4.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
61544
- var hashOf = (files) => crypto2.createHash("sha256").update(hashInput(files)).digest("hex");
61545
- function packOfficial(root2 = OFFICIAL, loose = false) {
61546
- const studiosDir = path5.join(root2, "studios");
61547
- return dirs(studiosDir).map((folder2) => {
61548
- const files = readStudioFolder(path5.join(studiosDir, folder2));
61549
- const parsed = parseStudioFile(folder2, files[STUDIO_FILE] ?? "", STUDIO_FILE);
61550
- if ("problem" in parsed) throw new Error(parsed.problem);
61551
- const def = parsed.def;
61552
- const checked = loose ? { ok: true } : checkStudioFiles(files, true);
61553
- if (!checked.ok) throw new Error(`official/studios/${folder2}: ${formatStudioProblem(checked)}`);
61554
- if (!def.names?.zh && !loose) throw new Error(`official/studios/${folder2}/${STUDIO_FILE}: add its Chinese name under \`names: zh\``);
61555
- return {
61556
- id: officialId(folder2),
61557
- name: def.name,
61558
- names: { en: def.name, ...def.names },
61559
- description: def.description,
61560
- when: def.description,
61561
- ...landsOf(def),
61562
- hash: hashOf(files),
61563
- files
61564
- };
61274
+ var isFile = (file3) => {
61275
+ try {
61276
+ return fs4.statSync(file3).isFile();
61277
+ } catch {
61278
+ return false;
61279
+ }
61280
+ };
61281
+ function copyFiles(harness) {
61282
+ const pinned = harness.pinned?.();
61283
+ if (pinned && isFile(pinned)) return [{ file: pinned, entry: false }];
61284
+ const binary = commandBinary(harness.command);
61285
+ const exe = (file3) => WINDOWS2 && !path5.extname(file3) ? [`${file3}.exe`, `${file3}.cmd`] : [file3];
61286
+ const path_ = onPath(binary).filter(isFile);
61287
+ const elsewhere = process.env.AI4KANBAN_PATH_ONLY ? [] : [...harness.installs?.() ?? [], ...commonDirs().map((dir) => path5.join(dir, binary))];
61288
+ const others = elsewhere.flatMap(exe).filter(isFile);
61289
+ const seen = /* @__PURE__ */ new Set();
61290
+ return [...path_, ...others].flatMap((file3, i) => {
61291
+ const real = fs4.realpathSync.native(file3);
61292
+ if (seen.has(real)) return [];
61293
+ seen.add(real);
61294
+ return [{ file: file3, entry: i === 0 && path_.length > 0 }];
61565
61295
  });
61566
61296
  }
61567
-
61568
- // ../cli/src/lib/cloud/tasks.ts
61569
- import fs5 from "node:fs";
61570
- import path6 from "node:path";
61571
- var TASK_ENV = "AI4KANBAN_TASK";
61572
- function workspaceTask() {
61573
- const id2 = process.env[TASK_ENV];
61574
- return id2 && id2.trim() ? id2.trim() : null;
61575
- }
61576
- function runnerProject(board) {
61577
- if (path6.basename(board) !== "kanban" || path6.basename(path6.dirname(board)) !== ".akb") return null;
61578
- const linked = linkedProject(board, path6.dirname(path6.dirname(board)));
61579
- return linked.ok ? linked.value : null;
61297
+ var answers;
61298
+ var answersFile = () => path5.join(machineHome(), "agent-copies.json");
61299
+ function kept() {
61300
+ if (answers) return answers;
61301
+ try {
61302
+ answers = JSON.parse(fs4.readFileSync(answersFile(), "utf8"));
61303
+ } catch {
61304
+ answers = {};
61305
+ }
61306
+ return answers;
61580
61307
  }
61581
- function linkedProject(board, root2) {
61582
- const file3 = path6.join(root2, ".akb", "base.json");
61583
- if (!fs5.existsSync(file3)) return { ok: true, value: null };
61308
+ function keep(file3, answer) {
61309
+ kept()[file3] = answer;
61584
61310
  try {
61585
- const base = JSON.parse(fs5.readFileSync(file3, "utf8"));
61586
- 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();
61587
- const projects = new Set(Object.keys(base.files ?? {}).flatMap((p) => /^projects\/([^/]+)\//.exec(p)?.[1] ?? []));
61588
- if (typeof base.project === "string") projects.add(base.project);
61589
- if (projects.size !== 1) throw new Error();
61590
- return { ok: true, value: [...projects][0] };
61311
+ fs4.mkdirSync(machineHome(), { recursive: true });
61312
+ const staged = `${answersFile()}.${process.pid}`;
61313
+ fs4.writeFileSync(staged, JSON.stringify(answers));
61314
+ fs4.renameSync(staged, answersFile());
61591
61315
  } catch {
61592
- return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
61593
61316
  }
61594
61317
  }
61595
-
61596
- // ../cli/src/lib/file-memo.ts
61597
- import fs6 from "node:fs";
61598
- import path7 from "node:path";
61599
- function stamp(paths) {
61600
- const parts = [];
61601
- const visit2 = (p) => {
61602
- let st;
61603
- try {
61604
- st = fs6.statSync(p, { bigint: true });
61605
- } catch {
61606
- parts.push(`${p}:-`);
61607
- return;
61608
- }
61609
- if (!st.isDirectory()) {
61610
- parts.push(`${p}:${st.mtimeNs}:${st.size}`);
61611
- return;
61612
- }
61613
- parts.push(`${p}/`);
61614
- let names;
61615
- try {
61616
- names = fs6.readdirSync(p).sort();
61617
- } catch {
61618
- return;
61619
- }
61620
- for (const name of names) if (name !== "node_modules" && name !== ".git") visit2(path7.join(p, name));
61621
- };
61622
- for (const p of paths) visit2(p);
61623
- return parts.join("\n");
61318
+ function keyOf(file3) {
61319
+ const real = fs4.realpathSync.native(file3);
61320
+ const stat = fs4.statSync(real);
61321
+ return `${real}|${stat.size}|${stat.mtimeMs}`;
61624
61322
  }
61625
- function copy(v) {
61626
- if (Array.isArray(v)) return v.map(copy);
61627
- if (v instanceof Map) return new Map([...v].map(([k, x]) => [k, copy(x)]));
61628
- if (v instanceof Set) return new Set([...v].map(copy));
61629
- if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
61630
- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, copy(x)]));
61631
- }
61632
- return v;
61323
+ function known(file3, maxAge) {
61324
+ const answer = kept()[file3];
61325
+ return answer && answer.key === keyOf(file3) && Date.now() - answer.at < maxAge ? answer : void 0;
61633
61326
  }
61634
- var perTurn = false;
61635
- var turn = 0;
61636
- var turnEnding = false;
61637
- function currentTurn() {
61638
- if (!perTurn) return ++turn;
61639
- if (!turnEnding) {
61640
- turnEnding = true;
61641
- setImmediate(() => {
61642
- turn++;
61643
- turnEnding = false;
61644
- }).unref();
61645
- }
61646
- return turn;
61327
+ function judge(code, status2, stdout, stderr) {
61328
+ if (code && ["ENOENT", "EACCES", "EPERM", "ENOEXEC", "EINVAL"].includes(code)) return { starts: false, version: null };
61329
+ if ((status2 === 126 || status2 === 127) && !stdout.trim()) return { starts: false, version: null };
61330
+ return { starts: true, version: status2 === 0 ? versionIn(stdout) ?? versionIn(stderr) : null };
61647
61331
  }
61648
- function memoByFiles(paths, read3) {
61649
- let last2 = null;
61650
- return () => {
61651
- const now = currentTurn();
61652
- if (last2?.turn !== now) {
61653
- const seen = stamp(paths());
61654
- if (last2?.stamp === seen) last2.turn = now;
61655
- else last2 = { stamp: seen, turn: now, value: read3() };
61656
- }
61657
- return copy(last2.value);
61658
- };
61332
+ function copyEnv(file3, given = process.env) {
61333
+ if (!path5.isAbsolute(file3)) return given;
61334
+ return { ...given, PATH: [path5.dirname(file3), given.PATH].filter(Boolean).join(path5.delimiter) };
61659
61335
  }
61660
-
61661
- // ../cli/src/lib/paths.ts
61662
- import path9 from "node:path";
61663
-
61664
- // ../cli/src/lib/machine/project.ts
61665
- import fs7 from "node:fs";
61666
- import path8 from "node:path";
61667
- var SESSIONS_FILE = "sessions.json";
61668
- var SESSIONS_FOLDER = "sessions";
61669
- var ASSETS_FOLDER = "assets";
61670
- var SESSIONS_LOCK = "sessions.lock";
61671
- var INDEX_LOCK = "index.lock";
61672
- var UI_CONFIG_FILE = "ui.config.json";
61673
- function realPathOf(dir) {
61674
- const here2 = path8.resolve(dir);
61675
- const rest = [];
61676
- let at = here2;
61677
- for (; ; ) {
61678
- try {
61679
- return path8.join(fs7.realpathSync(at), ...rest);
61680
- } catch {
61681
- const up = path8.dirname(at);
61682
- if (up === at) return here2;
61683
- rest.unshift(path8.basename(at));
61684
- at = up;
61685
- }
61686
- }
61336
+ var probeOptions = (file3) => ({ cwd: os4.tmpdir(), env: copyEnv(file3), windowsHide: true, shell: false });
61337
+ function probe(file3) {
61338
+ const key = keyOf(file3);
61339
+ const start = spawnable(file3, ["--version"], { ...probeOptions(file3), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
61340
+ const run2 = spawnSync(start.command, start.args, { ...start.options, encoding: "utf8" });
61341
+ const code = run2.error?.code;
61342
+ const answer = { key, at: Date.now(), ...judge(code, run2.status, run2.stdout ?? "", run2.stderr ?? "") };
61343
+ keep(file3, answer);
61344
+ return answer;
61687
61345
  }
61688
- function stateRootOf(board) {
61689
- let dir = realPathOf(board);
61690
- for (; ; ) {
61691
- if (fs7.existsSync(path8.join(dir, ".git"))) return dir;
61692
- const up = path8.dirname(dir);
61693
- if (up === dir) break;
61694
- dir = up;
61695
- }
61696
- return rootAbove(realPathOf(board));
61346
+ function probeAsync(file3) {
61347
+ const key = keyOf(file3);
61348
+ return new Promise((resolve2) => {
61349
+ let [stdout, stderr] = ["", ""];
61350
+ const start = spawnable(file3, ["--version"], { ...probeOptions(file3), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
61351
+ const child = spawn(start.command, start.args, start.options);
61352
+ const done = (code, status2) => {
61353
+ keep(file3, { key, at: Date.now(), ...judge(code, status2, stdout, stderr) });
61354
+ resolve2();
61355
+ };
61356
+ child.stdout.on("data", (d) => stdout += d);
61357
+ child.stderr.on("data", (d) => stderr += d);
61358
+ child.on("error", (e) => done(e.code, null));
61359
+ child.on("close", (status2) => done(void 0, status2));
61360
+ });
61697
61361
  }
61698
- function rootAbove(board) {
61699
- const parent = path8.dirname(board);
61700
- return ["docs", ".akb"].includes(path8.basename(parent)) ? path8.dirname(parent) : parent;
61362
+ async function warm(harness) {
61363
+ await Promise.all(copyFiles(harness).filter(({ file: file3 }) => !known(file3, KEEP_MS)).map(({ file: file3 }) => probeAsync(file3)));
61701
61364
  }
61702
- function projectStateDir(board, root2 = stateRootOf(board)) {
61703
- const relative = path8.relative(realPathOf(root2), realPathOf(board));
61704
- if (relative === ".." || relative.startsWith(`..${path8.sep}`) || path8.isAbsolute(relative)) {
61705
- throw new Error("The board must be inside its project root.");
61365
+ function locate(harness, maxAge = KEEP_MS) {
61366
+ const files = copyFiles(harness);
61367
+ const copies = files.map(({ file: file3, entry }) => {
61368
+ const { starts, version: version2 } = known(file3, KEEP_MS) ?? probe(file3);
61369
+ return { file: file3, entry, starts, version: version2 };
61370
+ });
61371
+ for (; ; ) {
61372
+ const best = pick2(copies);
61373
+ if (!best?.starts || known(best.file, maxAge)) return best;
61374
+ const { starts, version: version2 } = probe(best.file);
61375
+ Object.assign(best, { starts, version: version2 });
61376
+ if (starts) return pick2(copies);
61706
61377
  }
61707
- return path8.join(realPathOf(root2), ".akb", "boards", relative || "_root");
61708
61378
  }
61379
+ function chooseCopy(harness, maxAge = KEEP_MS) {
61380
+ const files = copyFiles(harness);
61381
+ return files.length === 1 ? { ...files[0], starts: true, version: null } : locate(harness, maxAge);
61382
+ }
61383
+ var spawnName = (copy2, binary) => copy2 && (!copy2.entry || /\.(cmd|bat)$/i.test(copy2.file)) ? copy2.file : binary;
61709
61384
 
61710
- // ../cli/src/lib/paths.ts
61711
- var REPO_ROOT = "";
61712
- var KANBAN = "";
61713
- var TODO = "";
61714
- var ARCHIVE = "";
61715
- var ARCHIVE_MD = "";
61716
- var README = "";
61717
- var MODULES_MD = "";
61718
- var CONFIG = "";
61719
- var KANBAN_GITIGNORE = "";
61720
- var RELEASES = "";
61721
- var RELEASE_SUMMARIES = "";
61722
- var AGENTS = "";
61723
- var STUDIOS = "";
61724
- var ASSETS = "";
61725
- var BOARD_STATE = "";
61726
- var MEMORY = "";
61727
- var AGENT_MEMORY = "";
61728
- var PROJECT_MD = "";
61729
- var LOCK = "";
61730
- var UI_CONFIG = "";
61731
- var ENV_FILE = "";
61732
- var SESSIONS = "";
61733
- var SESSIONS_DIR = "";
61734
- var SESSIONS_LOCK2 = "";
61735
- var INDEX_LOCK2 = "";
61736
- var DELIVERIES = "";
61737
- var PLANS = "";
61738
- var PLANS_ARCHIVE = "";
61739
- var RULES = "";
61740
- var TRIAGE = "";
61741
- var SIGNALS_ARCHIVED = "";
61742
- var SIGNALS_DISMISSED = "";
61743
- var SIGNALS_FILES = "";
61744
- var SIGNALS_OLD_INBOX = "";
61745
- var SIGNALS_OLD_HANDLED = "";
61746
- var AKB_DIR = "";
61747
- var ROOT_GITIGNORE = "";
61748
- function boardLockName(kanban, root2) {
61749
- const from = path9.relative(root2, kanban);
61750
- const name = from && !from.startsWith("..") ? from : path9.basename(kanban);
61751
- return `${name.split(path9.sep).join("-")}.lock`;
61385
+ // ../cli/src/lib/agent/harnesses/models.ts
61386
+ import { readFileSync, statSync } from "node:fs";
61387
+ import { homedir } from "node:os";
61388
+ import { join } from "node:path";
61389
+ function home(...parts) {
61390
+ return join(homedir(), ...parts);
61752
61391
  }
61753
- var BOARD_FLAG = "";
61754
- function setBoard(kanban, root2, flag) {
61755
- REPO_ROOT = path9.resolve(root2);
61756
- KANBAN = path9.resolve(kanban);
61757
- BOARD_FLAG = flag;
61758
- TODO = path9.join(KANBAN, "todo");
61759
- ARCHIVE = path9.join(KANBAN, ".archive");
61760
- ARCHIVE_MD = path9.join(KANBAN, "archive.md");
61761
- README = path9.join(TODO, "README.md");
61762
- MODULES_MD = path9.join(KANBAN, "modules.md");
61763
- CONFIG = path9.join(KANBAN, "config.md");
61764
- KANBAN_GITIGNORE = path9.join(KANBAN, ".gitignore");
61765
- RELEASES = path9.join(KANBAN, "releases.md");
61766
- RELEASE_SUMMARIES = path9.join(KANBAN, ".release-summaries");
61767
- AGENTS = path9.join(KANBAN, "agents");
61768
- STUDIOS = path9.join(KANBAN, "studios");
61769
- MEMORY = path9.join(KANBAN, "memory");
61770
- AGENT_MEMORY = path9.join(MEMORY, "agents");
61771
- PROJECT_MD = path9.join(MEMORY, "project.md");
61772
- ENV_FILE = path9.join(KANBAN, ".env");
61773
- const machine = projectStateDir(KANBAN, REPO_ROOT);
61774
- BOARD_STATE = machine;
61775
- UI_CONFIG = path9.join(machine, UI_CONFIG_FILE);
61776
- ASSETS = path9.join(machine, ASSETS_FOLDER);
61777
- SESSIONS = path9.join(machine, SESSIONS_FILE);
61778
- SESSIONS_DIR = path9.join(machine, SESSIONS_FOLDER);
61779
- SESSIONS_LOCK2 = path9.join(machine, SESSIONS_LOCK);
61780
- INDEX_LOCK2 = path9.join(machine, INDEX_LOCK);
61781
- DELIVERIES = path9.join(KANBAN, "deliveries");
61782
- RULES = path9.join(KANBAN, "rules");
61783
- PLANS = path9.join(machine, "plans");
61784
- PLANS_ARCHIVE = path9.join(PLANS, "archive");
61785
- TRIAGE = path9.join(KANBAN, "triage");
61786
- SIGNALS_ARCHIVED = path9.join(TRIAGE, "archived");
61787
- SIGNALS_DISMISSED = path9.join(TRIAGE, "dismissed");
61788
- SIGNALS_FILES = path9.join(TRIAGE, "files");
61789
- SIGNALS_OLD_INBOX = path9.join(TRIAGE, "inbox");
61790
- SIGNALS_OLD_HANDLED = path9.join(TRIAGE, "handled.md");
61791
- AKB_DIR = path9.join(REPO_ROOT, ".akb");
61792
- ROOT_GITIGNORE = path9.join(REPO_ROOT, ".gitignore");
61793
- LOCK = path9.join(AKB_DIR, boardLockName(KANBAN, REPO_ROOT));
61794
- return REPO_ROOT;
61392
+ function obj(value) {
61393
+ return value && typeof value === "object" ? value : {};
61795
61394
  }
61796
- function setBoardRoot(root2, named = false) {
61797
- const project = path9.resolve(root2);
61798
- return setBoard(path9.join(project, "docs", "kanban"), project, named ? ` --dir ${project}` : "");
61395
+ function arr(value) {
61396
+ return Array.isArray(value) ? value : [];
61799
61397
  }
61800
- setBoardRoot(process.cwd());
61801
-
61802
- // ../cli/src/lib/agent/cloud-studios.ts
61803
- var DEV = "AI4KANBAN_STUDIOS";
61804
- var root = () => path10.join(machineHome(), "studios");
61805
- var safe = (name) => name.replace(/[^\w.@-]/g, "_");
61806
- var versionFile = (id2, version2) => path10.join(root(), "versions", `${safe(id2)}@${version2}.json`);
61807
- var listFile = (project) => path10.join(root(), "lists", `${safe(project)}.json`);
61808
- var pinFile = (task) => path10.join(root(), "tasks", `${safe(task)}.json`);
61809
- function readJson(file3) {
61398
+ function str(value) {
61399
+ return typeof value === "string" ? value : "";
61400
+ }
61401
+ function num(value) {
61402
+ return typeof value === "number" ? value : Number.MAX_SAFE_INTEGER;
61403
+ }
61404
+ function uniqueIds(list3) {
61405
+ return [...new Set(list3.map((id2) => id2.trim()).filter(Boolean))];
61406
+ }
61407
+ var cached2 = /* @__PURE__ */ new Map();
61408
+ function modelsIn(file3, pick3, salt = "") {
61409
+ let stamp2;
61810
61410
  try {
61811
- return JSON.parse(fs8.readFileSync(file3, "utf8"));
61411
+ const stat = statSync(file3);
61412
+ stamp2 = `${stat.mtimeMs}:${stat.size}:${salt}`;
61812
61413
  } catch {
61813
- return null;
61414
+ return cached2.get(file3)?.found ?? [];
61415
+ }
61416
+ const hit = cached2.get(file3);
61417
+ if (hit?.stamp === stamp2) return hit.found;
61418
+ let found = [];
61419
+ try {
61420
+ found = uniqueIds(pick3(JSON.parse(readFileSync(file3, "utf8"))));
61421
+ } catch {
61422
+ found = [];
61814
61423
  }
61424
+ if (found.length) cached2.set(file3, { stamp: stamp2, found });
61425
+ return found.length ? found : hit?.found ?? [];
61815
61426
  }
61816
- var readVersion = (id2, version2) => readJson(versionFile(id2, version2));
61817
- var readPin = (task) => readJson(pinFile(task));
61818
- var boardProject = () => KANBAN ? runnerProject(KANBAN) : null;
61819
- var devFolder = () => process.env[DEV]?.trim() || "";
61820
- var flowOf = (held2) => {
61821
- const id2 = studioName(held2.id);
61822
- const read3 = parseStudioFile(id2, held2.files["STUDIO.md"] ?? "", `the \`${id2}\` studio`);
61823
- if ("problem" in read3) return null;
61824
- return { def: read3.def, cloudId: held2.id, version: held2.version, builtIn: held2.id.startsWith("wf_builtin_"), files: held2.files };
61427
+
61428
+ // ../cli/src/lib/agent/harnesses/types.ts
61429
+ import { createHash as createHash2 } from "node:crypto";
61430
+ import fs5 from "node:fs";
61431
+ import path6 from "node:path";
61432
+ function namesFlag(argv, flags) {
61433
+ return argv.some((tok) => flags.some((flag) => tok === flag || tok.startsWith(`${flag}=`)));
61434
+ }
61435
+ var RAW_ARGS_KEY = "args";
61436
+ var MODEL_KEY = "model";
61437
+ var RAW_ARGS = {
61438
+ key: RAW_ARGS_KEY,
61439
+ label: "Extra arguments",
61440
+ kind: "text",
61441
+ placeholder: "--max-budget-usd 5",
61442
+ help: "Appended to the command as written, for whatever the settings above don't cover. Split on spaces; a bad one fails the run and the log says why."
61825
61443
  };
61826
- function readFlows() {
61827
- const dev = devFolder();
61828
- if (dev) {
61829
- return packOfficial(dev, true).flatMap((w) => flowOf({ id: w.id, version: 1, name: w.name, names: w.names, files: w.files }) ?? []);
61444
+ var MCP_CONFIG = {
61445
+ key: "mcpConfig",
61446
+ label: "MCP config file",
61447
+ kind: "text",
61448
+ placeholder: "/path/to/mcp.json",
61449
+ help: "A JSON file of `mcpServers`, as Claude Code's --mcp-config takes. Empty opens no servers."
61450
+ };
61451
+ function machineFile(name, text2) {
61452
+ const suffix = createHash2("sha256").update(text2).digest("hex").slice(0, 16);
61453
+ const file3 = path6.join(machineHome(), "prompts", `${path6.parse(name).name}-${suffix}${path6.extname(name)}`);
61454
+ try {
61455
+ if (fs5.readFileSync(file3, "utf8") === text2) return file3;
61456
+ } catch {
61830
61457
  }
61831
- const project = boardProject();
61832
- if (!project || !readSession()) return [];
61833
- const list3 = readJson(listFile(project))?.studios ?? [];
61834
- const flows2 = list3.flatMap((w) => {
61835
- const held2 = readVersion(w.id, w.version);
61836
- return held2 ? flowOf(held2) ?? [] : [];
61837
- });
61838
- const task = workspaceTask();
61839
- const pin = task ? readPin(task) : null;
61840
- const pinned = pin && readVersion(pin.studio, pin.version);
61841
- const mine = pinned && flowOf(pinned);
61842
- if (!mine) return flows2;
61843
- return [mine, ...flows2.filter((f) => f.cloudId !== mine.cloudId)];
61458
+ fs5.mkdirSync(path6.dirname(file3), { recursive: true });
61459
+ fs5.writeFileSync(file3, text2);
61460
+ return file3;
61844
61461
  }
61845
- var sources = () => {
61846
- if (devFolder()) return [devFolder()];
61847
- const project = boardProject();
61848
- const task = workspaceTask();
61849
- return [sessionFile(), ...project ? [listFile(project)] : [], ...task ? [pinFile(task)] : []];
61850
- };
61851
- var flows = memoByFiles(sources, readFlows);
61852
61462
 
61853
- // ../cli/src/lib/shared/board-conflicts.ts
61854
- import fs9 from "node:fs";
61855
- import path11 from "node:path";
61463
+ // ../cli/src/lib/machine/settings.ts
61464
+ import fs6 from "node:fs";
61465
+ import path7 from "node:path";
61856
61466
 
61857
- // ../cli/src/lib/lock.ts
61858
- function pidAlive(pid) {
61859
- if (!pid) return false;
61860
- try {
61861
- process.kill(pid, 0);
61862
- return true;
61863
- } catch (e) {
61864
- return e.code === "EPERM";
61865
- }
61467
+ // ../cli/src/lib/machine/types.ts
61468
+ var LANGUAGES = ["en", "zh"];
61469
+ var DEFAULT_LANGUAGE = "en";
61470
+ function isLanguage(value) {
61471
+ return typeof value === "string" && LANGUAGES.includes(value);
61866
61472
  }
61867
61473
 
61868
- // ../cli/src/lib/shared/board-conflicts.ts
61869
- var folder = (board) => path11.join(projectStateDir(board), "conflicts");
61870
- var fileOf = (board, id2) => {
61871
- if (!/^c_[a-f0-9]{32}$/.test(id2)) throw new BoardError("Unknown board conflict.", { kind: "conflict-not-found", id: id2 });
61872
- return path11.join(folder(board), `${id2}.json`);
61873
- };
61874
- function read(board, id2) {
61875
- const file3 = fileOf(board, id2);
61876
- if (!fs9.existsSync(file3)) throw new BoardError("Unknown board conflict.", { kind: "conflict-not-found", id: id2 });
61474
+ // ../cli/src/lib/machine/settings.ts
61475
+ var settingsFile = () => path7.join(machineHome(), "settings.json");
61476
+ function heldSettings() {
61477
+ let text2;
61877
61478
  try {
61878
- const r = JSON.parse(fs9.readFileSync(file3, "utf8"));
61879
- if (r.id !== id2 || !r.project || !["open", "unconfirmed", "resolved"].includes(r.state) || !Array.isArray(r.files) || !r.files.length) throw Error();
61880
- const names = /* @__PURE__ */ new Set();
61881
- for (const f of r.files) {
61882
- if (!isBoardPath(f.path) || names.has(f.path) || f.remotePath !== `projects/${r.project}/${f.path}` && !(f.path.startsWith("memory/") && f.remotePath === f.path)) throw Error();
61883
- names.add(f.path);
61884
- if (typeof f.conflicted !== "boolean" || !f.local || !(f.local.content === null || typeof f.local.content === "string")) throw Error();
61885
- if (f.automatic && !(f.automatic.content === null || typeof f.automatic.content === "string")) throw Error();
61886
- for (const v of [f.base, f.remote]) if (!v || !Number.isSafeInteger(v.seq) || v.seq < 0 || !(v.content === null || typeof v.content === "string")) throw Error();
61887
- }
61888
- if (r.state !== "open" && (!r.draft || !Array.isArray(r.draft.writes) || r.draft.writes.length !== r.files.length || !Array.isArray(r.draft.working) || r.draft.working.length !== r.files.length)) throw Error();
61889
- if (r.state !== "open" && (!r.draft.writes.every((w) => w && r.files.some((f) => f.remotePath === w.path) && Number.isSafeInteger(w.base_seq) && w.base_seq >= 0 && (w.content === null || typeof w.content === "string")) || new Set(r.draft.writes.map((w) => w.path)).size !== r.files.length || r.draft.working.some((c) => c !== null && typeof c !== "string") || !Array.isArray(r.draft.files) || typeof r.draft.revision !== "string")) throw Error();
61890
- if (r.receipt && (!Number.isSafeInteger(r.receipt.head_seq) || !Array.isArray(r.receipt.files) || !r.files.every((f) => r.receipt.files.some((v) => v.path === f.remotePath && Number.isSafeInteger(v.seq) && v.seq >= 0)))) throw Error();
61891
- if (r.state === "resolved" && !r.receipt) throw Error();
61892
- return r;
61479
+ text2 = fs6.readFileSync(settingsFile(), "utf8");
61480
+ } catch (err) {
61481
+ if (err.code === "ENOENT") return { unreadable: false, values: {} };
61482
+ return { unreadable: true, values: {} };
61483
+ }
61484
+ try {
61485
+ const parsed = JSON.parse(text2);
61486
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { unreadable: true, values: {} };
61487
+ return { unreadable: false, values: parsed };
61893
61488
  } catch {
61894
- throw new BoardError(`Cannot read board conflict ${id2}. Preserve its record for recovery.`, { kind: "cloud-refused", id: id2 });
61489
+ return { unreadable: true, values: {} };
61895
61490
  }
61896
61491
  }
61897
- function conflictRecords(board) {
61898
- let names;
61899
- try {
61900
- names = fs9.readdirSync(folder(board));
61901
- } catch (e) {
61902
- if (e.code === "ENOENT") return [];
61903
- throw e;
61904
- }
61905
- return names.filter((n) => n.endsWith(".json")).sort().map((n) => read(board, n.slice(0, -5)));
61492
+ var held = () => heldSettings().values;
61493
+ function readLanguage() {
61494
+ const value = held().language;
61495
+ return isLanguage(value) ? value : DEFAULT_LANGUAGE;
61906
61496
  }
61907
- var pendingConflicts = (board) => conflictRecords(board).filter((r) => r.state !== "resolved");
61908
-
61909
- // src/cache.ts
61910
- import crypto3 from "node:crypto";
61911
- import fs11 from "node:fs";
61912
- import path13 from "node:path";
61913
61497
 
61914
- // src/folders.ts
61915
- import fs10 from "node:fs";
61916
- import os4 from "node:os";
61917
- import path12 from "node:path";
61918
- var projectsFile = () => path12.join(runnerHome(), "projects.json");
61919
- function realpath(p) {
61920
- try {
61921
- return fs10.realpathSync(p);
61922
- } catch {
61923
- return null;
61924
- }
61498
+ // ../cli/src/lib/agent/language.ts
61499
+ var LANGUAGE_ENV = "AI4KANBAN_LANGUAGE";
61500
+ var languageCode = (value) => value === "zh" || value === "en" ? value : null;
61501
+ function runLanguage() {
61502
+ if (process.env[LANGUAGE_ENV] !== void 0) return languageCode(process.env[LANGUAGE_ENV]);
61503
+ return readLanguage();
61925
61504
  }
61926
- function readGrants() {
61927
- try {
61928
- const held2 = JSON.parse(fs10.readFileSync(projectsFile(), "utf8"));
61929
- if (!Array.isArray(held2.projects)) throw new Error("invalid_projects");
61930
- return held2;
61931
- } catch (error62) {
61932
- if (error62.code === "ENOENT") return { projects: [] };
61933
- throw error62;
61934
- }
61505
+ var translating = () => runLanguage() === "zh";
61506
+
61507
+ // ../cli/src/lib/agent/wire/antigravity.ts
61508
+ import path8 from "node:path";
61509
+
61510
+ // ../cli/src/lib/agent/retry.ts
61511
+ var MAX_RETRY_ATTEMPTS = 4;
61512
+ var MAX_SUMMARY_CHARS = 300;
61513
+ var MAX_DETAIL_CHARS = 4e3;
61514
+ var SOURCES = /* @__PURE__ */ new Set(["runtime", "runner", "sync", "validation"]);
61515
+ function clipSummary(text2) {
61516
+ const clean = text2.replace(/\s+/g, " ").trim();
61517
+ return clean.length > MAX_SUMMARY_CHARS ? `${clean.slice(0, MAX_SUMMARY_CHARS - 1)}\u2026` : clean;
61518
+ }
61519
+ function clipDetail(text2) {
61520
+ if (!text2) return void 0;
61521
+ const trimmed = text2.trim();
61522
+ if (!trimmed) return void 0;
61523
+ return trimmed.length > MAX_DETAIL_CHARS ? `${trimmed.slice(0, MAX_DETAIL_CHARS - 1)}\u2026` : trimmed;
61524
+ }
61525
+ function makeFailure(source, rawSummary, options) {
61526
+ const summary2 = clipSummary(rawSummary) || "Execution failed.";
61527
+ const rawDetail = options?.detail?.trim() || (rawSummary.trim().length > summary2.length || rawSummary.includes("\n") ? rawSummary.trim() : void 0);
61528
+ const detail = clipDetail(rawDetail);
61529
+ return {
61530
+ ...options?.code ? { code: options.code } : {},
61531
+ source,
61532
+ summary: summary2,
61533
+ ...detail && detail !== summary2 ? { detail } : {},
61534
+ ...typeof options?.retryAfterMs === "number" && Number.isFinite(options.retryAfterMs) && options.retryAfterMs >= 0 ? { retryAfterMs: options.retryAfterMs } : {}
61535
+ };
61935
61536
  }
61936
- function listOf(held2) {
61937
- const subject = readSession()?.subject;
61938
- if (!held2.accounts) return held2.projects;
61939
- return subject ? held2.accounts[subject] ?? [] : [];
61537
+ var SESSION_MISSING_RE = /no rollout found for thread id|no conversation found with session id|session[_\s-]*not[_\s-]*found|session[_\s-]*mismatch|(?:session|thread|conversation)\s+\S+\s+not\s+found|unknown\s+(?:session|thread)|did not resume the requested conversation|did not return the requested session/i;
61538
+ function isSessionMissingText(text2) {
61539
+ return !!text2 && SESSION_MISSING_RE.test(text2);
61940
61540
  }
61941
- function update(change) {
61942
- fs10.mkdirSync(runnerHome(), { recursive: true, mode: 448 });
61943
- const lock = `${projectsFile()}.lock`;
61944
- let fd;
61945
- const until = Date.now() + 2e3;
61946
- for (; ; ) {
61947
- try {
61948
- fd = fs10.openSync(lock, "wx", 384);
61949
- fs10.writeFileSync(fd, String(process.pid));
61950
- break;
61951
- } catch {
61952
- try {
61953
- const pid = Number(fs10.readFileSync(lock, "utf8"));
61954
- if (pid > 0) {
61955
- try {
61956
- process.kill(pid, 0);
61957
- } catch {
61958
- fs10.rmSync(lock, { force: true });
61959
- }
61960
- }
61961
- } catch {
61962
- }
61963
- if (Date.now() > until) throw new Error("authorization_busy");
61964
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
61965
- }
61966
- }
61967
- try {
61968
- const held2 = readGrants();
61969
- const subject = readSession()?.subject;
61970
- const before = listOf(held2);
61971
- const after = [...new Set(change(before))];
61972
- if (subject) {
61973
- if (!held2.accounts) {
61974
- held2.accounts = { [subject]: held2.projects };
61975
- held2.legacyOwner = subject;
61976
- }
61977
- held2.accounts[subject] = after;
61978
- held2.projects = after;
61979
- } else held2.projects = after;
61980
- const tmp = `${projectsFile()}.${process.pid}.tmp`;
61981
- fs10.writeFileSync(tmp, `${JSON.stringify(held2, null, 2)}
61982
- `, { mode: 384 });
61983
- fs10.renameSync(tmp, projectsFile());
61984
- return before.filter((p) => !after.includes(p));
61985
- } finally {
61986
- fs10.closeSync(fd);
61987
- fs10.rmSync(lock, { force: true });
61988
- }
61541
+ function normalizeSource(raw) {
61542
+ if (SOURCES.has(raw)) return raw;
61543
+ if (raw === "provider" || raw === "harness") return "runtime";
61544
+ if (raw === "invariant") return "runner";
61545
+ return "runtime";
61989
61546
  }
61990
- function adoptLegacy() {
61991
- if (readSession() && !readGrants().accounts) update((list3) => list3);
61547
+ function readFailure(raw) {
61548
+ if (!raw || typeof raw !== "object") return;
61549
+ const r = raw;
61550
+ const rawSummary = typeof r.summary === "string" && r.summary.trim() ? r.summary : typeof r.reason === "string" && r.reason.trim() ? r.reason : "";
61551
+ if (!rawSummary) return;
61552
+ const code = typeof r.code === "string" && r.code.trim() ? r.code.trim() : void 0;
61553
+ const detail = typeof r.detail === "string" ? clipDetail(r.detail) : void 0;
61554
+ const retryAfterMs2 = typeof r.retryAfterMs === "number" && Number.isFinite(r.retryAfterMs) && r.retryAfterMs >= 0 ? r.retryAfterMs : void 0;
61555
+ return {
61556
+ ...code ? { code } : {},
61557
+ source: normalizeSource(r.source),
61558
+ summary: clipSummary(rawSummary),
61559
+ ...detail && detail !== clipSummary(rawSummary) ? { detail } : {},
61560
+ ...retryAfterMs2 !== void 0 ? { retryAfterMs: retryAfterMs2 } : {}
61561
+ };
61992
61562
  }
61993
- var allow = (dir) => {
61994
- update((list3) => [...list3, dir]);
61563
+
61564
+ // ../cli/src/lib/agent/prices.ts
61565
+ var OPENAI = {
61566
+ "gpt-6.2-astra": { input: 8, cachedInput: 0.4, output: 40 },
61567
+ "gpt-6.2-sol": { input: 2, cachedInput: 0.1, output: 10 },
61568
+ "gpt-6.1-sol": { input: 2, cachedInput: 0.1, output: 10 },
61569
+ "gpt-6-astra": { input: 10, cachedInput: 1, output: 50 },
61570
+ "gpt-6-sol": { input: 2, cachedInput: 0.2, output: 10 },
61571
+ "gpt-6-luna": { input: 0.1, cachedInput: 0.01, output: 0.5 },
61572
+ "gpt-5.6-sol": { input: 4, cachedInput: 0.4, output: 20 },
61573
+ "gpt-5.6-terra": { input: 2, cachedInput: 0.2, output: 12 },
61574
+ "gpt-5.6-luna": { input: 0.2, cachedInput: 0.02, output: 1.2 },
61575
+ "gpt-5.5": { input: 5, cachedInput: 0.5, output: 30 },
61576
+ "gpt-5.5-pro": { input: 30, cachedInput: 30, output: 180 },
61577
+ "gpt-5.4": { input: 2.5, cachedInput: 0.25, output: 15 },
61578
+ "gpt-5.4-mini": { input: 0.75, cachedInput: 0.075, output: 4.5 },
61579
+ "gpt-5.4-nano": { input: 0.2, cachedInput: 0.02, output: 1.25 },
61580
+ "gpt-5.4-pro": { input: 30, cachedInput: 30, output: 180 },
61581
+ "gpt-5.3-codex": { input: 1.75, cachedInput: 0.175, output: 14 },
61582
+ "gpt-5.2": { input: 1.75, cachedInput: 0.175, output: 14 },
61583
+ "gpt-5.2-pro": { input: 21, cachedInput: 21, output: 168 },
61584
+ "gpt-5.1": { input: 1.25, cachedInput: 0.125, output: 10 },
61585
+ "gpt-5": { input: 1.25, cachedInput: 0.125, output: 10 },
61586
+ "gpt-5-mini": { input: 0.25, cachedInput: 0.025, output: 2 },
61587
+ "gpt-5-nano": { input: 0.05, cachedInput: 5e-3, output: 0.4 },
61588
+ "gpt-5-pro": { input: 15, cachedInput: 15, output: 120 }
61995
61589
  };
61996
- var disallow = (dir) => update((list3) => list3.filter((p) => p !== dir));
61997
- var SYSTEM_MAC = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/etc", "/var", "/private", "/opt", "/cores", "/dev"];
61998
- var SYSTEM_WIN = ["Windows", "Program Files", "Program Files (x86)", "ProgramData"];
61999
- var here = () => ({ platform: process.platform, home: os4.homedir(), resolve: realpath });
62000
- function refusal(picked, where = here()) {
62001
- const win = where.platform === "win32";
62002
- const p = win ? path12.win32 : path12.posix;
62003
- const real = where.resolve(picked);
62004
- if (!real || !p.isAbsolute(real) || where.resolve === realpath && !fs10.statSync(real).isDirectory()) return "missing";
62005
- const norm = (d) => {
62006
- const n = p.normalize(d).replace(/[\\/]+$/, "") || p.sep;
62007
- return win ? n.toLowerCase() : n;
62008
- };
62009
- const within = (dir, root2) => {
62010
- const [d, r] = [norm(dir), norm(root2)];
62011
- return d === r || d.startsWith(r.endsWith(p.sep) ? r : r + p.sep);
61590
+ function antigravityPrices(at) {
61591
+ const pro = at < Date.parse("2026-12-01T00:00:00Z") ? 2 : 4;
61592
+ const flash = at < Date.parse("2027-01-01T00:00:00Z") ? 0.75 : 1.5;
61593
+ return {
61594
+ "gemini-4-carbon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
61595
+ "gemini-4-argon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
61596
+ "gemini-4-neon": { input: 3, cachedInput: 0.15, output: 15 },
61597
+ "gemini-4-hydrogen": { input: 1.5, cachedInput: 0.075, output: 7.5 },
61598
+ "gemini-3.8-flash": { input: flash, cachedInput: flash / 10, output: flash * 5 }
62012
61599
  };
62013
- const forms = [picked, real];
62014
- if (forms.some((f) => norm(f) === norm(where.home))) return "home";
62015
- if (forms.some((f) => norm(f) === norm(p.parse(f).root)) || !win && forms.some((f) => /^\/Volumes(\/[^/]+)?\/?$/.test(f))) {
62016
- return "disk";
62017
- }
62018
- if (forms.some((f) => within(where.home, f))) return "home";
62019
- if (forms.some((f) => within(f, runnerHome()))) return "system";
62020
- const system = win ? SYSTEM_WIN.map((s) => p.join(p.parse(real).root, s)) : SYSTEM_MAC;
62021
- return forms.some((f) => system.some((s) => within(f, s))) ? "system" : null;
61600
+ }
61601
+ var PRICES = { openai: OPENAI, "openai-api": OPENAI };
61602
+ function lookUp(table, model) {
61603
+ const id2 = model.trim().toLowerCase().replace(/^[^/]+\//, "");
61604
+ return table[id2] ?? table[id2.replace(/-\d{4}-\d{2}-\d{2}$/, "")];
61605
+ }
61606
+ function priceUsd(provider, model, usage, at = Date.now()) {
61607
+ if (!provider || !model || !usage) return void 0;
61608
+ const agy = provider.trim().toLowerCase() === "antigravity";
61609
+ const table = agy ? antigravityPrices(at) : PRICES[provider.trim().toLowerCase()];
61610
+ const price = table && (agy ? table[model.trim().toLowerCase().replace(/-(?:low|medium|high|xhigh|max)$/, "")] : lookUp(table, model));
61611
+ if (!price) return void 0;
61612
+ const usd = ((usage.input + usage.cacheCreation) * price.input + usage.cacheRead * price.cachedInput + usage.output * price.output) / 1e6;
61613
+ return Number.isFinite(usd) && usd >= 0 ? usd : void 0;
62022
61614
  }
62023
61615
 
62024
- // src/cache.ts
62025
- var IDLE_MS = 7 * 24 * 60 * 6e4;
62026
- var SWEEP_MS = 24 * 60 * 6e4;
62027
- var akbDir = (dir) => path13.join(dir, ".akb");
62028
- var unsentFile = (dir) => path13.join(akbDir(dir), "unsent");
62029
- var unsent = (dir) => fs11.existsSync(unsentFile(dir));
62030
- var holds = /* @__PURE__ */ new Map();
62031
- var holdsDir = () => path13.join(runnerHome(), "holds");
62032
- var holdFile = (dir) => path13.join(holdsDir(), `${crypto3.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
62033
- function paused(dir) {
62034
- try {
62035
- const file3 = path13.join(projectStateDir(path13.join(akbDir(dir), "kanban")), SESSIONS_FILE);
62036
- const held2 = JSON.parse(fs11.readFileSync(file3, "utf8"));
62037
- return (held2.deliveries ?? []).some((d) => d.status === "active");
62038
- } catch {
62039
- return false;
62040
- }
61616
+ // ../cli/src/lib/agent/wire/json.ts
61617
+ function obj2(value) {
61618
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
62041
61619
  }
62042
- function busy(dir) {
62043
- if (holds.has(dir)) return true;
62044
- const prefix = path13.basename(holdFile(dir)).split(".")[0] + ".";
62045
- try {
62046
- return fs11.readdirSync(holdsDir()).filter((file3) => file3.startsWith(prefix)).some((file3) => {
62047
- try {
62048
- process.kill(Number(file3.split(".")[1]), 0);
62049
- return true;
62050
- } catch {
62051
- fs11.rmSync(path13.join(holdsDir(), file3), { force: true });
62052
- return false;
62053
- }
62054
- });
62055
- } catch {
62056
- return false;
62057
- }
61620
+ function str2(value) {
61621
+ return typeof value === "string" ? value : "";
62058
61622
  }
62059
- function conflicted(dir) {
62060
- try {
62061
- return pendingConflicts(path13.join(dir, ".akb", "kanban")).length > 0;
62062
- } catch {
62063
- return true;
62064
- }
61623
+ function num2(value) {
61624
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
62065
61625
  }
62066
- var kept = (dir) => busy(dir) || unsent(dir) || paused(dir) || conflicted(dir);
62067
- function clearAkb(dir) {
62068
- dir = realpath2(dir);
62069
- if (kept(dir) || fs11.existsSync(path13.join(akbDir(dir), "worktrees")) || fs11.existsSync(path13.join(akbDir(dir), "handoffs"))) return false;
62070
- let entries;
62071
- try {
62072
- entries = fs11.readdirSync(akbDir(dir));
62073
- } catch {
62074
- return true;
62075
- }
62076
- for (const name of entries) fs11.rmSync(path13.join(akbDir(dir), name), { recursive: true, force: true });
62077
- return true;
61626
+ function hint(raw) {
61627
+ const line = raw.split("\n")[0].trim();
61628
+ if (!line) return "";
61629
+ return `(${line.length > 96 ? `${line.slice(0, 93)}\u2026` : line})`;
62078
61630
  }
62079
- function realpath2(p) {
62080
- try {
62081
- return fs11.realpathSync(p);
62082
- } catch {
62083
- return p;
61631
+ function argHint(input2, keys) {
61632
+ const args2 = obj2(input2);
61633
+ for (const key of keys) {
61634
+ const value = str2(args2[key]);
61635
+ if (value.trim()) return hint(value);
62084
61636
  }
61637
+ return "";
62085
61638
  }
62086
61639
 
62087
- // src/kanban-skill.ts
62088
- import { spawnSync } from "node:child_process";
62089
- import fs12 from "node:fs";
62090
- import path14 from "node:path";
62091
- var SKILL_FOLDERS = [".claude/skills/kanban", ".agents/skills/kanban"];
62092
- var MANAGED = /^<!-- ai4kanban \S+ -->$/m;
62093
- function removeLegacyKanbanSkill(root2) {
62094
- for (const folder2 of SKILL_FOLDERS) {
62095
- try {
62096
- let at = root2;
62097
- if (!fs12.lstatSync(at, { throwIfNoEntry: false })?.isDirectory()) continue;
62098
- let safe2 = true;
62099
- const parts = `${folder2}/SKILL.md`.split("/");
62100
- for (const [i, name] of parts.entries()) {
62101
- at = path14.join(at, name);
62102
- const stat = fs12.lstatSync(at, { throwIfNoEntry: false });
62103
- if (!stat || stat.isSymbolicLink() || (i < parts.length - 1 ? !stat.isDirectory() : !stat.isFile())) {
62104
- safe2 = false;
62105
- break;
61640
+ // ../cli/src/lib/agent/wire/events.ts
61641
+ var TOOL_KINDS = ["read", "edit", "delete", "move", "search", "execute", "fetch", "other"];
61642
+ var toolKind = (v) => TOOL_KINDS.includes(str2(v)) ? v : "other";
61643
+ function targetOf(raw) {
61644
+ const line = raw.split("\n")[0].trim();
61645
+ if (!line) return void 0;
61646
+ return line.length > 160 ? `${line.slice(0, 159)}\u2026` : line;
61647
+ }
61648
+ function contentText(raw) {
61649
+ const parts = Array.isArray(raw) ? raw : [];
61650
+ return parts.map((p) => {
61651
+ const part = obj2(p);
61652
+ if (part.type === "diff") return str2(part.path);
61653
+ return str2(obj2(part.content).text) || str2(part.text);
61654
+ }).filter((t2) => t2.trim()).join("\n");
61655
+ }
61656
+ function statusOf(raw) {
61657
+ const s = str2(raw).toLowerCase();
61658
+ if (s.includes("progress")) return "in_progress";
61659
+ if (/complete|done|cancel/.test(s)) return "completed";
61660
+ return "pending";
61661
+ }
61662
+ function entriesOf(raw) {
61663
+ return (Array.isArray(raw) ? raw : []).map(obj2).flatMap((e) => {
61664
+ const content = str2(e.content).trim();
61665
+ if (!content) return [];
61666
+ return [{ content, status: statusOf(e.status), ...str2(e.priority) ? { priority: str2(e.priority) } : {} }];
61667
+ });
61668
+ }
61669
+ var isTodoCall = (u) => str2(u.title) === "todowrite" || str2(obj2(u.rawInput)._toolName) === "updateTodos";
61670
+ var inputTarget = (input2) => str2(input2.command) || str2(input2.path) || str2(input2.filePath);
61671
+ var targetIn = (u) => {
61672
+ const locations = Array.isArray(u.locations) ? u.locations : [];
61673
+ return targetOf(inputTarget(obj2(u.rawInput)) || str2(obj2(locations[0]).path) || "");
61674
+ };
61675
+ function createEventCollector() {
61676
+ let queue = [];
61677
+ let said = "";
61678
+ let activity = 0;
61679
+ const todoCalls = /* @__PURE__ */ new Set();
61680
+ const held2 = /* @__PURE__ */ new Map();
61681
+ let todos = [];
61682
+ const close = () => {
61683
+ if (said.trim()) queue.push({ kind: "message", data: { text: said.trim() } });
61684
+ said = "";
61685
+ };
61686
+ const release = (id2, target) => {
61687
+ const call2 = held2.get(id2);
61688
+ if (!call2) return;
61689
+ held2.delete(id2);
61690
+ queue.push({ kind: "tool_call", data: { ...call2, ...target ? { target } : {} } });
61691
+ };
61692
+ return {
61693
+ activity: () => activity,
61694
+ progress: () => {
61695
+ activity++;
61696
+ },
61697
+ /** One ACP `session/update`'s `update`. Thoughts and housekeeping updates yield nothing. */
61698
+ update(raw) {
61699
+ const u = obj2(raw);
61700
+ if (u.sessionUpdate === "agent_message_chunk") {
61701
+ const chunk = str2(obj2(u.content).text);
61702
+ if (chunk) activity++;
61703
+ said += chunk;
61704
+ return;
61705
+ }
61706
+ if (!["tool_call", "tool_call_update", "plan"].includes(str2(u.sessionUpdate))) return;
61707
+ close();
61708
+ switch (u.sessionUpdate) {
61709
+ case "tool_call": {
61710
+ const id2 = str2(u.toolCallId);
61711
+ if (isTodoCall(u)) {
61712
+ todoCalls.add(id2);
61713
+ return;
61714
+ }
61715
+ const target = targetIn(u);
61716
+ const subagent = /^(?:Task|Agent|delegate_task|spawn_agent)$/i.test(str2(u.title)) || !!obj2(u.rawInput).subagent_type;
61717
+ const data = { toolCallId: id2, title: str2(u.title) || "tool", kind: toolKind(u.kind), status: str2(u.status) || "pending", ...subagent ? { subagent: true } : {}, ...target ? { target } : {} };
61718
+ if (data.kind !== "execute" && !subagent && u.rawInput !== void 0 && !inputTarget(obj2(u.rawInput))) held2.set(id2, data);
61719
+ else queue.push({ kind: "tool_call", data });
61720
+ return;
61721
+ }
61722
+ case "tool_call_update": {
61723
+ const id2 = str2(u.toolCallId);
61724
+ if (todoCalls.has(id2)) {
61725
+ const list3 = obj2(u.rawInput).todos;
61726
+ if (Array.isArray(list3) && !str2(obj2(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list3) } });
61727
+ return;
61728
+ }
61729
+ release(id2, targetIn(u));
61730
+ const result = contentText(u.content);
61731
+ if (!u.status && !result) return;
61732
+ queue.push({
61733
+ kind: "tool_call_update",
61734
+ data: { toolCallId: str2(u.toolCallId), status: str2(u.status) || "in_progress", ...result ? { result } : {} }
61735
+ });
61736
+ return;
62106
61737
  }
61738
+ case "plan":
61739
+ queue.push({ kind: "plan", data: { entries: entriesOf(u.entries) } });
61740
+ return;
62107
61741
  }
62108
- if (!safe2 || !MANAGED.test(fs12.readFileSync(at, "utf8"))) continue;
62109
- fs12.unlinkSync(at);
62110
- const dir = path14.dirname(at);
62111
- if (fs12.readdirSync(dir).length === 0) fs12.rmdirSync(dir);
62112
- } catch (e) {
62113
- process.stderr.write(`wildcrane: \u65E0\u6CD5\u6E05\u7406 ${folder2}\uFF1A${e instanceof Error ? e.message : String(e)}
62114
- `);
61742
+ },
61743
+ /** A whole message, for a source that never sends one in pieces. */
61744
+ message(text2) {
61745
+ close();
61746
+ if (text2.trim()) queue.push({ kind: "message", data: { text: text2.trim() } });
61747
+ },
61748
+ toolCall(toolCallId, title, kind, target) {
61749
+ close();
61750
+ const t2 = target ? targetOf(target) : void 0;
61751
+ queue.push({ kind: "tool_call", data: { toolCallId, title, kind, status: "in_progress", ...t2 ? { target: t2 } : {} } });
61752
+ },
61753
+ /** A subagent the agent started, titled by its task; it ends with its call's `toolResult`. */
61754
+ subagent(toolCallId, title) {
61755
+ close();
61756
+ queue.push({ kind: "tool_call", data: { toolCallId, title: targetOf(title) ?? "subagent", kind: "other", status: "in_progress", subagent: true } });
61757
+ },
61758
+ toolResult(toolCallId, status2, result) {
61759
+ close();
61760
+ queue.push({ kind: "tool_call_update", data: { toolCallId, status: status2, ...result.trim() ? { result: result.trim() } : {} } });
61761
+ },
61762
+ plan(entries) {
61763
+ close();
61764
+ queue.push({ kind: "plan", data: { entries: entriesOf(entries) } });
61765
+ },
61766
+ /** Cursor's `cursor/update_todos`: the whole list, or under `merge` only what changed, by id. */
61767
+ todos(raw, merge2) {
61768
+ close();
61769
+ const items = (Array.isArray(raw) ? raw : []).map(obj2).flatMap((e) => {
61770
+ const [entry] = entriesOf([e]);
61771
+ return entry ? [{ ...entry, id: str2(e.id) }] : [];
61772
+ });
61773
+ const next = merge2 ? [...todos] : [];
61774
+ for (const item of items) {
61775
+ const at = item.id ? next.findIndex((t2) => t2.id === item.id) : -1;
61776
+ if (at >= 0) next[at] = item;
61777
+ else next.push(item);
61778
+ }
61779
+ todos = next;
61780
+ queue.push({ kind: "plan", data: { entries: todos.map(({ id: _, ...e }) => e) } });
61781
+ },
61782
+ log(text2) {
61783
+ close();
61784
+ if (text2.trim()) queue.push({ kind: "log", data: { text: text2 } });
61785
+ },
61786
+ error(text2) {
61787
+ close();
61788
+ if (text2.trim()) queue.push({ kind: "error", data: { text: text2.trim() } });
61789
+ },
61790
+ /** The turn is over: a half-held message is finished off. */
61791
+ end() {
61792
+ close();
61793
+ for (const id2 of [...held2.keys()]) release(id2);
61794
+ },
61795
+ /** What arrived since the last call. */
61796
+ events() {
61797
+ const out = queue;
61798
+ queue = [];
61799
+ return out;
62115
61800
  }
62116
- }
61801
+ };
62117
61802
  }
62118
- function keepOutOfGit(dir, folders2 = SKILL_FOLDERS) {
62119
- const git2 = (...args2) => spawnSync("git", ["-C", dir, ...args2], { encoding: "utf8" });
62120
- const inside = git2("rev-parse", "--git-path", "info/exclude");
62121
- if (inside.status !== 0) return;
62122
- const missing = [".akb/", ...folders2.map((f) => `${f}/`)].filter((p) => git2("check-ignore", "-q", p).status !== 0);
62123
- if (!missing.length) return;
62124
- const exclude = path14.resolve(dir, inside.stdout.trim());
62125
- fs12.mkdirSync(path14.dirname(exclude), { recursive: true });
62126
- const held2 = fs12.existsSync(exclude) ? fs12.readFileSync(exclude, "utf8") : "";
62127
- fs12.writeFileSync(exclude, `${held2}${held2 && !held2.endsWith("\n") ? "\n" : ""}${missing.join("\n")}
62128
- `);
61803
+
61804
+ // ../cli/src/lib/agent/wire/stream.ts
61805
+ function createLineReader(renderLine) {
61806
+ let buf = "";
61807
+ return {
61808
+ push(chunk) {
61809
+ buf += chunk;
61810
+ const lines = buf.split("\n");
61811
+ buf = lines.pop() ?? "";
61812
+ return lines.map(renderLine).join("");
61813
+ },
61814
+ flush() {
61815
+ const rest = buf;
61816
+ buf = "";
61817
+ return rest ? renderLine(rest) : "";
61818
+ }
61819
+ };
62129
61820
  }
62130
- function retireKanbanSkill(dir) {
61821
+ function frame(line) {
62131
61822
  try {
62132
- keepOutOfGit(dir);
62133
- removeLegacyKanbanSkill(dir);
62134
- } catch (e) {
62135
- process.stderr.write(`wildcrane: ${e instanceof Error ? e.message : String(e)}
62136
- `);
61823
+ const parsed = JSON.parse(line);
61824
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
61825
+ return parsed;
61826
+ } catch {
61827
+ return void 0;
62137
61828
  }
62138
61829
  }
62139
61830
 
62140
- // src/runtimes.ts
62141
- import { spawn as spawn2 } from "node:child_process";
62142
- import fs22 from "node:fs";
62143
- import os6 from "node:os";
62144
- import path26 from "node:path";
62145
-
62146
- // ../cli/src/lib/agent/harnesses/antigravity.ts
62147
- import fs17 from "node:fs";
62148
- import path20 from "node:path";
62149
- import { createHash as createHash3 } from "node:crypto";
62150
- import { spawnSync as spawnSync3 } from "node:child_process";
62151
-
62152
- // ../cli/src/lib/agent/locate.ts
62153
- import { spawn, spawnSync as spawnSync2 } from "node:child_process";
62154
- import fs14 from "node:fs";
62155
- import os5 from "node:os";
62156
- import path16 from "node:path";
62157
-
62158
- // ../cli/src/lib/agent/argv.ts
62159
- function splitCommand(command) {
62160
- const argv = [];
62161
- let word = "";
62162
- let started = false;
62163
- let quote2 = "";
62164
- for (const ch of command) {
62165
- if (quote2) {
62166
- if (ch === quote2) quote2 = "";
62167
- else word += ch;
62168
- continue;
62169
- }
62170
- if (ch === '"' || ch === "'") {
62171
- quote2 = ch;
62172
- started = true;
62173
- continue;
62174
- }
62175
- if (/\s/.test(ch)) {
62176
- if (started) argv.push(word);
62177
- word = "";
62178
- started = false;
61831
+ // ../cli/src/lib/agent/wire/antigravity-session.ts
61832
+ import { existsSync } from "node:fs";
61833
+ function antigravityConversationFile(session) {
61834
+ if (/^[a-f0-9-]{36}$/i.test(session)) return home(".gemini", "antigravity-cli", "conversations", `${session}.db`);
61835
+ }
61836
+ function varint(bytes2, offset) {
61837
+ let value = 0;
61838
+ for (let shift = 0; shift < 70 && offset.value < bytes2.length; shift += 7) {
61839
+ const byte = bytes2[offset.value++];
61840
+ value += (byte & 127) * 2 ** shift;
61841
+ if (byte < 128) return value;
61842
+ }
61843
+ throw new Error("Invalid Antigravity conversation metadata");
61844
+ }
61845
+ function* fields(bytes2) {
61846
+ const offset = { value: 0 };
61847
+ while (offset.value < bytes2.length) {
61848
+ const tag = varint(bytes2, offset);
61849
+ const number4 = Math.floor(tag / 8);
61850
+ const wire = tag % 8;
61851
+ if (number4 < 1 || number4 >= 2 ** 29) throw new Error("Invalid Antigravity conversation metadata");
61852
+ if (wire === 0) {
61853
+ yield [number4, varint(bytes2, offset)];
62179
61854
  continue;
62180
61855
  }
62181
- word += ch;
62182
- started = true;
61856
+ const size = wire === 2 ? varint(bytes2, offset) : wire === 1 ? 8 : wire === 5 ? 4 : -1;
61857
+ const end = offset.value + size;
61858
+ if (size < 0 || end > bytes2.length) throw new Error("Invalid Antigravity conversation metadata");
61859
+ if (wire === 2) yield [number4, bytes2.subarray(offset.value, end)];
61860
+ offset.value = end;
62183
61861
  }
62184
- if (started) argv.push(word);
62185
- return argv;
62186
- }
62187
-
62188
- // ../cli/src/lib/agent/installed.ts
62189
- var WINDOWS = process.platform === "win32";
62190
- function commandBinary(command) {
62191
- return splitCommand(command)[0] ?? "";
62192
61862
  }
62193
-
62194
- // ../cli/src/lib/agent/spawnable.ts
62195
- import fs13 from "node:fs";
62196
- import path15 from "node:path";
62197
- var META = /([()\][%!^"`<>&|;, *?])/g;
62198
- function cmdArg(arg) {
62199
- const quoted = `"${arg.replace(/\r?\n|\r/g, " ").replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
62200
- return quoted.replace(META, "^$1").replace(META, "^$1");
62201
- }
62202
- function cmdLine(file3, args2) {
62203
- return `"${[file3.replace(META, "^$1"), ...args2.map(cmdArg)].join(" ")}"`;
62204
- }
62205
- function shimTarget(text2, file3) {
62206
- const dir = path15.win32.dirname(file3);
62207
- const found = /"%(?:~dp0|dp0%)\\?([^"%]+)"\s+%\*/i.exec(text2);
62208
- if (!found || !/\\node\.exe"/i.test(text2)) return null;
62209
- const script = path15.win32.resolve(dir, found[1].replace(/\//g, "\\"));
62210
- const local = path15.win32.join(dir, "node.exe");
62211
- const nodePath = /SET "NODE_PATH=([^"]*)"/i.exec(text2)?.[1];
62212
- return { script, node: fs13.existsSync(local) ? local : "node", env: nodePath ? { NODE_PATH: nodePath } : {} };
62213
- }
62214
- function onWindowsPath(name, env2) {
62215
- const exts = (env2.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
62216
- const key = Object.keys(env2).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
62217
- for (const dir of (env2[key] ?? "").split(";").filter(Boolean)) {
62218
- for (const ext of exts) {
62219
- const file3 = path15.win32.join(dir, `${name}${ext.toLowerCase()}`);
62220
- if (fs13.existsSync(file3)) return file3;
62221
- }
62222
- }
62223
- return void 0;
62224
- }
62225
- function spawnable(command, args2, options = {}, platform = process.platform) {
62226
- if (platform !== "win32") return { command, args: args2, options };
62227
- const env2 = options.env ?? process.env;
62228
- const file3 = path15.extname(command) || /[\\/]/.test(command) ? command : onWindowsPath(command, env2) ?? command;
62229
- const ext = path15.extname(file3).toLowerCase();
62230
- const hidden = { ...options, windowsHide: true, shell: false };
62231
- if (ext !== ".cmd" && ext !== ".bat") return { command: file3, args: args2, options: hidden };
62232
- let text2 = "";
62233
- try {
62234
- text2 = fs13.readFileSync(file3, "utf8");
62235
- } catch {
62236
- }
62237
- const shim = shimTarget(text2, file3);
62238
- if (shim) {
62239
- return { command: shim.node, args: [shim.script, ...args2], options: { ...hidden, env: { ...env2, ...shim.env } } };
62240
- }
62241
- return {
62242
- command: env2.ComSpec || process.env.ComSpec || "cmd.exe",
62243
- args: ["/d", "/s", "/c", cmdLine(file3, args2)],
62244
- options: { ...hidden, windowsVerbatimArguments: true }
62245
- };
62246
- }
62247
-
62248
- // ../cli/src/lib/agent/locate.ts
62249
- var WINDOWS2 = process.platform === "win32";
62250
- var PROBE_MS = 3e3;
62251
- var KEEP_MS = 60 * 6e4;
62252
- var SPAWN_MS = 5 * 6e4;
62253
- function versionIn(output3) {
62254
- const plain = output3.replace(/\x1b\[[0-9;]*m/g, "");
62255
- return /(?<![\w.-])v?(\d+(?:\.\d+)+(?:-[0-9A-Za-z.-]+)?)/.exec(plain)?.[1] ?? null;
62256
- }
62257
- var RELEASE_STAGE = /^(alpha|beta|canary|dev|next|nightly|pre|preview|rc)[.-]?(\d*)$/i;
62258
- function compareVersions(a, b) {
62259
- const [numberA = "", ...restA] = a.split("-");
62260
- const [numberB = "", ...restB] = b.split("-");
62261
- const [x, y] = [numberA.split(".").map(Number), numberB.split(".").map(Number)];
62262
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
62263
- const step = (x[i] ?? 0) - (y[i] ?? 0);
62264
- if (step) return step;
62265
- }
62266
- const [tagA, tagB] = [restA.join("-"), restB.join("-")];
62267
- if (tagA === tagB) return 0;
62268
- if (/^\d+$/.test(tagA) && /^\d+$/.test(tagB)) return Number(tagA) - Number(tagB);
62269
- const [stageA, stageB] = [RELEASE_STAGE.exec(tagA), RELEASE_STAGE.exec(tagB)];
62270
- if (!tagA && stageB) return 1;
62271
- if (stageA && !tagB) return -1;
62272
- if (stageA && stageB && stageA[1].toLowerCase() === stageB[1].toLowerCase()) {
62273
- return Number(stageA[2] || 0) - Number(stageB[2] || 0);
62274
- }
62275
- return null;
62276
- }
62277
- function newest(copies) {
62278
- let best = copies[0] ?? null;
62279
- for (const copy2 of copies) {
62280
- if (!copy2.version) return null;
62281
- for (const other of copies) {
62282
- if (!other.version || compareVersions(copy2.version, other.version) === null) return null;
62283
- }
62284
- if (compareVersions(copy2.version, best.version) > 0) best = copy2;
61863
+ function bytesField(data, field) {
61864
+ if (!(data instanceof Uint8Array)) return;
61865
+ for (const [number4, value] of fields(data)) {
61866
+ if (number4 === field && value instanceof Uint8Array) return value;
62285
61867
  }
62286
- return best;
62287
- }
62288
- function pick2(copies) {
62289
- const live = copies.filter((copy2) => copy2.starts);
62290
- if (!live.length) return copies.find((copy2) => copy2.entry) ?? copies[0] ?? null;
62291
- const entry = live.find((copy2) => copy2.entry);
62292
- const best = newest(live);
62293
- if (best) return entry && compareVersions(entry.version, best.version) === 0 ? entry : best;
62294
- return entry ?? newest(live.filter((copy2) => copy2.version)) ?? live[0];
62295
61868
  }
62296
- function folders(parent) {
62297
- try {
62298
- return fs14.readdirSync(parent, { withFileTypes: true }).filter((one) => one.isDirectory()).map((one) => one.name);
62299
- } catch {
62300
- return [];
61869
+ function varintField(data, field) {
61870
+ if (!(data instanceof Uint8Array)) return;
61871
+ for (const [number4, value] of fields(data)) {
61872
+ if (number4 === field && typeof value === "number") return value;
62301
61873
  }
62302
61874
  }
62303
- function byVersion(names) {
62304
- const numbers = (name) => /(\d+(?:\.\d+)+)/.exec(name)?.[1]?.split(".").map(Number) ?? [];
62305
- return [...names].sort((a, b) => {
62306
- const [x, y] = [numbers(a), numbers(b)];
62307
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
62308
- const step = (y[i] ?? -1) - (x[i] ?? -1);
62309
- if (step) return step;
61875
+ function stepIndices(data) {
61876
+ const out = [];
61877
+ for (const [field, value] of fields(data)) {
61878
+ if (field !== 2) continue;
61879
+ if (typeof value === "number") out.push(value);
61880
+ else {
61881
+ const offset = { value: 0 };
61882
+ while (offset.value < value.length) out.push(varint(value, offset));
62310
61883
  }
62311
- return a < b ? -1 : a > b ? 1 : 0;
62312
- });
62313
- }
62314
- function latestIn(parent, tail = "") {
62315
- let names;
62316
- try {
62317
- names = fs14.readdirSync(parent);
62318
- } catch {
62319
- return [];
62320
- }
62321
- return byVersion(names.filter((name) => !name.startsWith("."))).slice(0, 2).map((name) => path16.join(parent, name, tail));
62322
- }
62323
- var env = (name) => process.env[name]?.trim() ?? "";
62324
- function commonDirs() {
62325
- const home3 = os5.homedir();
62326
- const under = (...parts) => path16.join(home3, ...parts);
62327
- const nodes = (root2, tail = []) => root2 ? folders(root2).map((version2) => path16.join(root2, version2, ...tail)) : [];
62328
- if (WINDOWS2) {
62329
- const [app, local, data, programs] = [env("APPDATA"), env("LOCALAPPDATA"), env("ProgramData"), env("ProgramFiles")];
62330
- return [
62331
- under(".local", "bin"),
62332
- under(".bun", "bin"),
62333
- under("scoop", "shims"),
62334
- ...app ? [path16.join(app, "npm")] : [],
62335
- ...local ? [path16.join(local, "pnpm"), path16.join(local, "Volta", "bin"), path16.join(local, "Microsoft", "WinGet", "Links")] : [],
62336
- ...data ? [path16.join(data, "chocolatey", "bin")] : [],
62337
- ...programs ? [path16.join(programs, "nodejs")] : [],
62338
- ...nodes(env("NVM_HOME")),
62339
- ...app ? nodes(path16.join(app, "fnm", "node-versions"), ["installation"]) : []
62340
- ];
62341
- }
62342
- const support = process.platform === "darwin" ? under("Library", "Application Support") : under(".local", "share");
62343
- return [
62344
- under(".local", "bin"),
62345
- under("bin"),
62346
- "/usr/local/bin",
62347
- "/usr/bin",
62348
- // Not on macOS, where a stat under /home waits on the automounter.
62349
- process.platform === "darwin" ? "/opt/homebrew/bin" : "/home/linuxbrew/.linuxbrew/bin",
62350
- under(".npm-global", "bin"),
62351
- under(".yarn", "bin"),
62352
- under(".bun", "bin"),
62353
- ...env("PNPM_HOME") ? [env("PNPM_HOME")] : [],
62354
- under("Library", "pnpm"),
62355
- under(".local", "share", "pnpm"),
62356
- path16.join(env("VOLTA_HOME") || under(".volta"), "bin"),
62357
- ...nodes(path16.join(env("NVM_DIR") || under(".nvm"), "versions", "node"), ["bin"]),
62358
- ...nodes(path16.join(env("FNM_DIR") || path16.join(support, "fnm"), "node-versions"), ["installation", "bin"]),
62359
- ...nodes(path16.join(env("ASDF_DATA_DIR") || under(".asdf"), "installs", "nodejs"), ["bin"]),
62360
- ...nodes(under(".local", "share", "mise", "installs", "node"), ["bin"]),
62361
- ...nodes(under(".nodenv", "versions"), ["bin"]),
62362
- ...nodes("/usr/local/n/versions/node", ["bin"])
62363
- ];
62364
- }
62365
- function onPath(binary) {
62366
- const names = WINDOWS2 ? (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((ext) => `${binary}${ext.toLowerCase()}`) : [binary];
62367
- return (process.env.PATH ?? "").split(path16.delimiter).filter(Boolean).flatMap((dir) => names.map((name) => path16.join(dir, name)));
62368
- }
62369
- var isFile = (file3) => {
62370
- try {
62371
- return fs14.statSync(file3).isFile();
62372
- } catch {
62373
- return false;
62374
- }
62375
- };
62376
- function copyFiles(harness) {
62377
- const pinned = harness.pinned?.();
62378
- if (pinned && isFile(pinned)) return [{ file: pinned, entry: false }];
62379
- const binary = commandBinary(harness.command);
62380
- const exe = (file3) => WINDOWS2 && !path16.extname(file3) ? [`${file3}.exe`, `${file3}.cmd`] : [file3];
62381
- const path_ = onPath(binary).filter(isFile);
62382
- const elsewhere = process.env.AI4KANBAN_PATH_ONLY ? [] : [...harness.installs?.() ?? [], ...commonDirs().map((dir) => path16.join(dir, binary))];
62383
- const others = elsewhere.flatMap(exe).filter(isFile);
62384
- const seen = /* @__PURE__ */ new Set();
62385
- return [...path_, ...others].flatMap((file3, i) => {
62386
- const real = fs14.realpathSync.native(file3);
62387
- if (seen.has(real)) return [];
62388
- seen.add(real);
62389
- return [{ file: file3, entry: i === 0 && path_.length > 0 }];
62390
- });
62391
- }
62392
- var answers;
62393
- var answersFile = () => path16.join(machineHome(), "agent-copies.json");
62394
- function kept2() {
62395
- if (answers) return answers;
62396
- try {
62397
- answers = JSON.parse(fs14.readFileSync(answersFile(), "utf8"));
62398
- } catch {
62399
- answers = {};
62400
- }
62401
- return answers;
62402
- }
62403
- function keep(file3, answer) {
62404
- kept2()[file3] = answer;
62405
- try {
62406
- fs14.mkdirSync(machineHome(), { recursive: true });
62407
- const staged = `${answersFile()}.${process.pid}`;
62408
- fs14.writeFileSync(staged, JSON.stringify(answers));
62409
- fs14.renameSync(staged, answersFile());
62410
- } catch {
62411
61884
  }
61885
+ return out;
62412
61886
  }
62413
- function keyOf(file3) {
62414
- const real = fs14.realpathSync.native(file3);
62415
- const stat = fs14.statSync(real);
62416
- return `${real}|${stat.size}|${stat.mtimeMs}`;
62417
- }
62418
- function known(file3, maxAge) {
62419
- const answer = kept2()[file3];
62420
- return answer && answer.key === keyOf(file3) && Date.now() - answer.at < maxAge ? answer : void 0;
62421
- }
62422
- function judge(code, status2, stdout, stderr) {
62423
- if (code && ["ENOENT", "EACCES", "EPERM", "ENOEXEC", "EINVAL"].includes(code)) return { starts: false, version: null };
62424
- if ((status2 === 126 || status2 === 127) && !stdout.trim()) return { starts: false, version: null };
62425
- return { starts: true, version: status2 === 0 ? versionIn(stdout) ?? versionIn(stderr) : null };
62426
- }
62427
- function copyEnv(file3, given = process.env) {
62428
- if (!path16.isAbsolute(file3)) return given;
62429
- return { ...given, PATH: [path16.dirname(file3), given.PATH].filter(Boolean).join(path16.delimiter) };
62430
- }
62431
- var probeOptions = (file3) => ({ cwd: os5.tmpdir(), env: copyEnv(file3), windowsHide: true, shell: false });
62432
- function probe(file3) {
62433
- const key = keyOf(file3);
62434
- const start = spawnable(file3, ["--version"], { ...probeOptions(file3), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
62435
- const run2 = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
62436
- const code = run2.error?.code;
62437
- const answer = { key, at: Date.now(), ...judge(code, run2.status, run2.stdout ?? "", run2.stderr ?? "") };
62438
- keep(file3, answer);
62439
- return answer;
62440
- }
62441
- function probeAsync(file3) {
62442
- const key = keyOf(file3);
62443
- return new Promise((resolve2) => {
62444
- let [stdout, stderr] = ["", ""];
62445
- const start = spawnable(file3, ["--version"], { ...probeOptions(file3), stdio: ["ignore", "pipe", "pipe"], timeout: PROBE_MS });
62446
- const child = spawn(start.command, start.args, start.options);
62447
- const done = (code, status2) => {
62448
- keep(file3, { key, at: Date.now(), ...judge(code, status2, stdout, stderr) });
62449
- resolve2();
62450
- };
62451
- child.stdout.on("data", (d) => stdout += d);
62452
- child.stderr.on("data", (d) => stderr += d);
62453
- child.on("error", (e) => done(e.code, null));
62454
- child.on("close", (status2) => done(void 0, status2));
62455
- });
62456
- }
62457
- async function warm(harness) {
62458
- await Promise.all(copyFiles(harness).filter(({ file: file3 }) => !known(file3, KEEP_MS)).map(({ file: file3 }) => probeAsync(file3)));
62459
- }
62460
- function locate(harness, maxAge = KEEP_MS) {
62461
- const files = copyFiles(harness);
62462
- const copies = files.map(({ file: file3, entry }) => {
62463
- const { starts, version: version2 } = known(file3, KEEP_MS) ?? probe(file3);
62464
- return { file: file3, entry, starts, version: version2 };
62465
- });
62466
- for (; ; ) {
62467
- const best = pick2(copies);
62468
- if (!best?.starts || known(best.file, maxAge)) return best;
62469
- const { starts, version: version2 } = probe(best.file);
62470
- Object.assign(best, { starts, version: version2 });
62471
- if (starts) return pick2(copies);
62472
- }
62473
- }
62474
- function chooseCopy(harness, maxAge = KEEP_MS) {
62475
- const files = copyFiles(harness);
62476
- return files.length === 1 ? { ...files[0], starts: true, version: null } : locate(harness, maxAge);
62477
- }
62478
- var spawnName = (copy2, binary) => copy2 && (!copy2.entry || /\.(cmd|bat)$/i.test(copy2.file)) ? copy2.file : binary;
62479
-
62480
- // ../cli/src/lib/agent/harnesses/models.ts
62481
- import { readFileSync, statSync } from "node:fs";
62482
- import { homedir } from "node:os";
62483
- import { join } from "node:path";
62484
- function home(...parts) {
62485
- return join(homedir(), ...parts);
62486
- }
62487
- function obj(value) {
62488
- return value && typeof value === "object" ? value : {};
62489
- }
62490
- function arr(value) {
62491
- return Array.isArray(value) ? value : [];
62492
- }
62493
- function str(value) {
62494
- return typeof value === "string" ? value : "";
62495
- }
62496
- function num(value) {
62497
- return typeof value === "number" ? value : Number.MAX_SAFE_INTEGER;
62498
- }
62499
- function uniqueIds(list3) {
62500
- return [...new Set(list3.map((id2) => id2.trim()).filter(Boolean))];
62501
- }
62502
- var cached2 = /* @__PURE__ */ new Map();
62503
- function modelsIn(file3, pick3, salt = "") {
62504
- let stamp2;
62505
- try {
62506
- const stat = statSync(file3);
62507
- stamp2 = `${stat.mtimeMs}:${stat.size}:${salt}`;
62508
- } catch {
62509
- return cached2.get(file3)?.found ?? [];
62510
- }
62511
- const hit = cached2.get(file3);
62512
- if (hit?.stamp === stamp2) return hit.found;
62513
- let found = [];
62514
- try {
62515
- found = uniqueIds(pick3(JSON.parse(readFileSync(file3, "utf8"))));
62516
- } catch {
62517
- found = [];
62518
- }
62519
- if (found.length) cached2.set(file3, { stamp: stamp2, found });
62520
- return found.length ? found : hit?.found ?? [];
61887
+ function recordedContextLimit(data) {
61888
+ const limit = varintField(bytesField(bytesField(bytesField(data, 1), 9), 10), 4);
61889
+ return limit !== void 0 && Number.isSafeInteger(limit) && limit > 0 ? limit : void 0;
62521
61890
  }
62522
-
62523
- // ../cli/src/lib/agent/harnesses/types.ts
62524
- import { createHash as createHash2 } from "node:crypto";
62525
- import fs15 from "node:fs";
62526
- import path17 from "node:path";
62527
- function namesFlag(argv, flags) {
62528
- return argv.some((tok) => flags.some((flag) => tok === flag || tok.startsWith(`${flag}=`)));
61891
+ var utf8 = (bytes2) => bytes2 && Buffer.from(bytes2).toString("utf8");
61892
+ function stepUuid(stepRow, index) {
61893
+ if (!Number.isSafeInteger(index) || index < 0) return;
61894
+ const id2 = bytesField(stepRow.get(index)?.metadata, 12);
61895
+ return id2?.length === 36 ? id2 : void 0;
62529
61896
  }
62530
- var RAW_ARGS_KEY = "args";
62531
- var MODEL_KEY = "model";
62532
- var RAW_ARGS = {
62533
- key: RAW_ARGS_KEY,
62534
- label: "Extra arguments",
62535
- kind: "text",
62536
- placeholder: "--max-budget-usd 5",
62537
- help: "Appended to the command as written, for whatever the settings above don't cover. Split on spaces; a bad one fails the run and the log says why."
62538
- };
62539
- var MCP_CONFIG = {
62540
- key: "mcpConfig",
62541
- label: "MCP config file",
62542
- kind: "text",
62543
- placeholder: "/path/to/mcp.json",
62544
- help: "A JSON file of `mcpServers`, as Claude Code's --mcp-config takes. Empty opens no servers."
62545
- };
62546
- function machineFile(name, text2) {
62547
- const suffix = createHash2("sha256").update(text2).digest("hex").slice(0, 16);
62548
- const file3 = path17.join(machineHome(), "prompts", `${path17.parse(name).name}-${suffix}${path17.extname(name)}`);
61897
+ function antigravityRecordedModels(session, steps) {
61898
+ const found = /* @__PURE__ */ new Map();
61899
+ if (!steps.size) return found;
61900
+ const file3 = antigravityConversationFile(session);
61901
+ if (!file3 || !existsSync(file3)) return found;
62549
61902
  try {
62550
- if (fs15.readFileSync(file3, "utf8") === text2) return file3;
61903
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
61904
+ if (!sqlite) return found;
61905
+ const db = new sqlite.DatabaseSync(file3, { readOnly: true });
61906
+ try {
61907
+ const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
61908
+ const promptIds = /* @__PURE__ */ new Map();
61909
+ const promptUuid = (prompt) => {
61910
+ if (!promptIds.has(prompt)) promptIds.set(prompt, stepUuid(stepRow, prompt));
61911
+ return promptIds.get(prompt);
61912
+ };
61913
+ const groups = /* @__PURE__ */ new Map();
61914
+ for (const [index, { prompt }] of steps) {
61915
+ if (!Number.isSafeInteger(index) || index < 0) continue;
61916
+ const id2 = stepUuid(stepRow, index) ?? promptUuid(prompt);
61917
+ if (!id2) continue;
61918
+ const uuid3 = utf8(id2);
61919
+ let group = groups.get(uuid3);
61920
+ if (!group) groups.set(uuid3, group = { id: id2, steps: /* @__PURE__ */ new Set() });
61921
+ group.steps.add(index);
61922
+ }
61923
+ const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
61924
+ for (const [uuid3, { id: id2, steps: groupSteps }] of groups) {
61925
+ const key = Buffer.concat([Buffer.from([34, 36]), id2]);
61926
+ for (const { data } of generations.iterate(key)) {
61927
+ if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== uuid3) continue;
61928
+ const model = utf8(bytesField(bytesField(data, 1), 19)) || void 0;
61929
+ for (const step of stepIndices(data)) {
61930
+ if (!groupSteps.has(step)) continue;
61931
+ found.set(step, found.has(step) && found.get(step) !== model ? void 0 : model);
61932
+ }
61933
+ }
61934
+ }
61935
+ } finally {
61936
+ db.close();
61937
+ }
61938
+ return found;
62551
61939
  } catch {
61940
+ return /* @__PURE__ */ new Map();
62552
61941
  }
62553
- fs15.mkdirSync(path17.dirname(file3), { recursive: true });
62554
- fs15.writeFileSync(file3, text2);
62555
- return file3;
62556
- }
62557
-
62558
- // ../cli/src/lib/machine/settings.ts
62559
- import fs16 from "node:fs";
62560
- import path18 from "node:path";
62561
-
62562
- // ../cli/src/lib/machine/types.ts
62563
- var LANGUAGES = ["en", "zh"];
62564
- var DEFAULT_LANGUAGE = "en";
62565
- function isLanguage(value) {
62566
- return typeof value === "string" && LANGUAGES.includes(value);
62567
61942
  }
62568
-
62569
- // ../cli/src/lib/machine/settings.ts
62570
- var settingsFile = () => path18.join(machineHome(), "settings.json");
62571
- function heldSettings() {
62572
- let text2;
62573
- try {
62574
- text2 = fs16.readFileSync(settingsFile(), "utf8");
62575
- } catch (err) {
62576
- if (err.code === "ENOENT") return { unreadable: false, values: {} };
62577
- return { unreadable: true, values: {} };
62578
- }
61943
+ function antigravityRecordedContextLimit(session, step, prompt) {
61944
+ if (!Number.isSafeInteger(step) || step < 0) return;
61945
+ const file3 = antigravityConversationFile(session);
61946
+ if (!file3 || !existsSync(file3)) return;
62579
61947
  try {
62580
- const parsed = JSON.parse(text2);
62581
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { unreadable: true, values: {} };
62582
- return { unreadable: false, values: parsed };
61948
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
61949
+ if (!sqlite) return;
61950
+ const db = new sqlite.DatabaseSync(file3, { readOnly: true });
61951
+ try {
61952
+ const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
61953
+ const id2 = stepUuid(stepRow, step) ?? stepUuid(stepRow, prompt);
61954
+ if (!id2) return;
61955
+ const key = Buffer.concat([Buffer.from([34, 36]), id2]);
61956
+ const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
61957
+ let found;
61958
+ let matched = false;
61959
+ for (const { data } of generations.iterate(key)) {
61960
+ if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== utf8(id2)) continue;
61961
+ if (!stepIndices(data).includes(step)) continue;
61962
+ const limit = recordedContextLimit(data);
61963
+ if (matched && found !== limit) return;
61964
+ found = limit;
61965
+ matched = true;
61966
+ }
61967
+ return found;
61968
+ } finally {
61969
+ db.close();
61970
+ }
62583
61971
  } catch {
62584
- return { unreadable: true, values: {} };
61972
+ return;
62585
61973
  }
62586
61974
  }
62587
- var held = () => heldSettings().values;
62588
- function readLanguage() {
62589
- const value = held().language;
62590
- return isLanguage(value) ? value : DEFAULT_LANGUAGE;
62591
- }
62592
-
62593
- // ../cli/src/lib/agent/language.ts
62594
- var LANGUAGE_ENV = "AI4KANBAN_LANGUAGE";
62595
- var languageCode = (value) => value === "zh" || value === "en" ? value : null;
62596
- function runLanguage() {
62597
- if (process.env[LANGUAGE_ENV] !== void 0) return languageCode(process.env[LANGUAGE_ENV]);
62598
- return readLanguage();
62599
- }
62600
- var translating = () => runLanguage() === "zh";
62601
61975
 
62602
61976
  // ../cli/src/lib/agent/wire/antigravity.ts
62603
- import path19 from "node:path";
62604
-
62605
- // ../cli/src/lib/agent/prices.ts
62606
- var OPENAI = {
62607
- "gpt-6.2-astra": { input: 8, cachedInput: 0.4, output: 40 },
62608
- "gpt-6.2-sol": { input: 2, cachedInput: 0.1, output: 10 },
62609
- "gpt-6.1-sol": { input: 2, cachedInput: 0.1, output: 10 },
62610
- "gpt-6-astra": { input: 10, cachedInput: 1, output: 50 },
62611
- "gpt-6-sol": { input: 2, cachedInput: 0.2, output: 10 },
62612
- "gpt-6-luna": { input: 0.1, cachedInput: 0.01, output: 0.5 },
62613
- "gpt-5.6-sol": { input: 4, cachedInput: 0.4, output: 20 },
62614
- "gpt-5.6-terra": { input: 2, cachedInput: 0.2, output: 12 },
62615
- "gpt-5.6-luna": { input: 0.2, cachedInput: 0.02, output: 1.2 },
62616
- "gpt-5.5": { input: 5, cachedInput: 0.5, output: 30 },
62617
- "gpt-5.5-pro": { input: 30, cachedInput: 30, output: 180 },
62618
- "gpt-5.4": { input: 2.5, cachedInput: 0.25, output: 15 },
62619
- "gpt-5.4-mini": { input: 0.75, cachedInput: 0.075, output: 4.5 },
62620
- "gpt-5.4-nano": { input: 0.2, cachedInput: 0.02, output: 1.25 },
62621
- "gpt-5.4-pro": { input: 30, cachedInput: 30, output: 180 },
62622
- "gpt-5.3-codex": { input: 1.75, cachedInput: 0.175, output: 14 },
62623
- "gpt-5.2": { input: 1.75, cachedInput: 0.175, output: 14 },
62624
- "gpt-5.2-pro": { input: 21, cachedInput: 21, output: 168 },
62625
- "gpt-5.1": { input: 1.25, cachedInput: 0.125, output: 10 },
62626
- "gpt-5": { input: 1.25, cachedInput: 0.125, output: 10 },
62627
- "gpt-5-mini": { input: 0.25, cachedInput: 0.025, output: 2 },
62628
- "gpt-5-nano": { input: 0.05, cachedInput: 5e-3, output: 0.4 },
62629
- "gpt-5-pro": { input: 15, cachedInput: 15, output: 120 }
61977
+ var CONTEXT_LOOK_EVERY_MS = 250;
61978
+ var KINDS = {
61979
+ run_command: "execute",
61980
+ command_status: "execute",
61981
+ send_command_input: "execute",
61982
+ read_file: "read",
61983
+ view_file: "read",
61984
+ list_dir: "read",
61985
+ grep_search: "search",
61986
+ find_by_name: "search",
61987
+ write_file: "edit",
61988
+ write_to_file: "edit",
61989
+ replace_file_content: "edit",
61990
+ multi_replace_file_content: "edit",
61991
+ read_url_content: "fetch",
61992
+ search_web: "fetch"
62630
61993
  };
62631
- function antigravityPrices(at) {
62632
- const pro = at < Date.parse("2026-12-01T00:00:00Z") ? 2 : 4;
62633
- const flash = at < Date.parse("2027-01-01T00:00:00Z") ? 0.75 : 1.5;
62634
- return {
62635
- "gemini-4-carbon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
62636
- "gemini-4-argon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
62637
- "gemini-4-neon": { input: 3, cachedInput: 0.15, output: 15 },
62638
- "gemini-4-hydrogen": { input: 1.5, cachedInput: 0.075, output: 7.5 },
62639
- "gemini-3.8-flash": { input: flash, cachedInput: flash / 10, output: flash * 5 }
62640
- };
62641
- }
62642
- var PRICES = { openai: OPENAI, "openai-api": OPENAI };
62643
- function lookUp(table, model) {
62644
- const id2 = model.trim().toLowerCase().replace(/^[^/]+\//, "");
62645
- return table[id2] ?? table[id2.replace(/-\d{4}-\d{2}-\d{2}$/, "")];
62646
- }
62647
- function priceUsd(provider, model, usage, at = Date.now()) {
62648
- if (!provider || !model || !usage) return void 0;
62649
- const agy = provider.trim().toLowerCase() === "antigravity";
62650
- const table = agy ? antigravityPrices(at) : PRICES[provider.trim().toLowerCase()];
62651
- const price = table && (agy ? table[model.trim().toLowerCase().replace(/-(?:low|medium|high|xhigh|max)$/, "")] : lookUp(table, model));
62652
- if (!price) return void 0;
62653
- const usd = ((usage.input + usage.cacheCreation) * price.input + usage.cacheRead * price.cachedInput + usage.output * price.output) / 1e6;
62654
- return Number.isFinite(usd) && usd >= 0 ? usd : void 0;
62655
- }
62656
-
62657
- // ../cli/src/lib/agent/wire/json.ts
62658
- function obj2(value) {
62659
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
62660
- }
62661
- function str2(value) {
62662
- return typeof value === "string" ? value : "";
62663
- }
62664
- function num2(value) {
62665
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
62666
- }
62667
- function hint(raw) {
62668
- const line = raw.split("\n")[0].trim();
62669
- if (!line) return "";
62670
- return `(${line.length > 96 ? `${line.slice(0, 93)}\u2026` : line})`;
62671
- }
62672
- function argHint(input2, keys) {
62673
- const args2 = obj2(input2);
62674
- for (const key of keys) {
62675
- const value = str2(args2[key]);
62676
- if (value.trim()) return hint(value);
62677
- }
62678
- return "";
62679
- }
62680
-
62681
- // ../cli/src/lib/agent/wire/events.ts
62682
- var TOOL_KINDS = ["read", "edit", "delete", "move", "search", "execute", "fetch", "other"];
62683
- var toolKind = (v) => TOOL_KINDS.includes(str2(v)) ? v : "other";
62684
- function targetOf(raw) {
62685
- const line = raw.split("\n")[0].trim();
62686
- if (!line) return void 0;
62687
- return line.length > 160 ? `${line.slice(0, 159)}\u2026` : line;
62688
- }
62689
- function contentText(raw) {
62690
- const parts = Array.isArray(raw) ? raw : [];
62691
- return parts.map((p) => {
62692
- const part = obj2(p);
62693
- if (part.type === "diff") return str2(part.path);
62694
- return str2(obj2(part.content).text) || str2(part.text);
62695
- }).filter((t2) => t2.trim()).join("\n");
62696
- }
62697
- function statusOf(raw) {
62698
- const s = str2(raw).toLowerCase();
62699
- if (s.includes("progress")) return "in_progress";
62700
- if (/complete|done|cancel/.test(s)) return "completed";
62701
- return "pending";
62702
- }
62703
- function entriesOf(raw) {
62704
- return (Array.isArray(raw) ? raw : []).map(obj2).flatMap((e) => {
62705
- const content = str2(e.content).trim();
62706
- if (!content) return [];
62707
- return [{ content, status: statusOf(e.status), ...str2(e.priority) ? { priority: str2(e.priority) } : {} }];
62708
- });
62709
- }
62710
- var isTodoCall = (u) => str2(u.title) === "todowrite" || str2(obj2(u.rawInput)._toolName) === "updateTodos";
62711
- var inputTarget = (input2) => str2(input2.command) || str2(input2.path) || str2(input2.filePath);
62712
- var targetIn = (u) => {
62713
- const locations = Array.isArray(u.locations) ? u.locations : [];
62714
- return targetOf(inputTarget(obj2(u.rawInput)) || str2(obj2(locations[0]).path) || "");
62715
- };
62716
- function createEventCollector() {
62717
- let queue = [];
62718
- let said = "";
62719
- let activity = 0;
62720
- const todoCalls = /* @__PURE__ */ new Set();
62721
- const held2 = /* @__PURE__ */ new Map();
62722
- let todos = [];
62723
- const close = () => {
62724
- if (said.trim()) queue.push({ kind: "message", data: { text: said.trim() } });
62725
- said = "";
62726
- };
62727
- const release = (id2, target) => {
62728
- const call2 = held2.get(id2);
62729
- if (!call2) return;
62730
- held2.delete(id2);
62731
- queue.push({ kind: "tool_call", data: { ...call2, ...target ? { target } : {} } });
62732
- };
62733
- return {
62734
- activity: () => activity,
62735
- progress: () => {
62736
- activity++;
62737
- },
62738
- /** One ACP `session/update`'s `update`. Thoughts and housekeeping updates yield nothing. */
62739
- update(raw) {
62740
- const u = obj2(raw);
62741
- if (u.sessionUpdate === "agent_message_chunk") {
62742
- const chunk = str2(obj2(u.content).text);
62743
- if (chunk) activity++;
62744
- said += chunk;
62745
- return;
62746
- }
62747
- if (!["tool_call", "tool_call_update", "plan"].includes(str2(u.sessionUpdate))) return;
62748
- close();
62749
- switch (u.sessionUpdate) {
62750
- case "tool_call": {
62751
- const id2 = str2(u.toolCallId);
62752
- if (isTodoCall(u)) {
62753
- todoCalls.add(id2);
62754
- return;
62755
- }
62756
- const target = targetIn(u);
62757
- const subagent = /^(?:Task|Agent|delegate_task|spawn_agent)$/i.test(str2(u.title)) || !!obj2(u.rawInput).subagent_type;
62758
- const data = { toolCallId: id2, title: str2(u.title) || "tool", kind: toolKind(u.kind), status: str2(u.status) || "pending", ...subagent ? { subagent: true } : {}, ...target ? { target } : {} };
62759
- if (data.kind !== "execute" && !subagent && u.rawInput !== void 0 && !inputTarget(obj2(u.rawInput))) held2.set(id2, data);
62760
- else queue.push({ kind: "tool_call", data });
62761
- return;
62762
- }
62763
- case "tool_call_update": {
62764
- const id2 = str2(u.toolCallId);
62765
- if (todoCalls.has(id2)) {
62766
- const list3 = obj2(u.rawInput).todos;
62767
- if (Array.isArray(list3) && !str2(obj2(u.rawInput)._toolName)) queue.push({ kind: "plan", data: { entries: entriesOf(list3) } });
62768
- return;
62769
- }
62770
- release(id2, targetIn(u));
62771
- const result = contentText(u.content);
62772
- if (!u.status && !result) return;
62773
- queue.push({
62774
- kind: "tool_call_update",
62775
- data: { toolCallId: str2(u.toolCallId), status: str2(u.status) || "in_progress", ...result ? { result } : {} }
62776
- });
62777
- return;
62778
- }
62779
- case "plan":
62780
- queue.push({ kind: "plan", data: { entries: entriesOf(u.entries) } });
62781
- return;
62782
- }
62783
- },
62784
- /** A whole message, for a source that never sends one in pieces. */
62785
- message(text2) {
62786
- close();
62787
- if (text2.trim()) queue.push({ kind: "message", data: { text: text2.trim() } });
62788
- },
62789
- toolCall(toolCallId, title, kind, target) {
62790
- close();
62791
- const t2 = target ? targetOf(target) : void 0;
62792
- queue.push({ kind: "tool_call", data: { toolCallId, title, kind, status: "in_progress", ...t2 ? { target: t2 } : {} } });
62793
- },
62794
- /** A subagent the agent started, titled by its task; it ends with its call's `toolResult`. */
62795
- subagent(toolCallId, title) {
62796
- close();
62797
- queue.push({ kind: "tool_call", data: { toolCallId, title: targetOf(title) ?? "subagent", kind: "other", status: "in_progress", subagent: true } });
62798
- },
62799
- toolResult(toolCallId, status2, result) {
62800
- close();
62801
- queue.push({ kind: "tool_call_update", data: { toolCallId, status: status2, ...result.trim() ? { result: result.trim() } : {} } });
62802
- },
62803
- plan(entries) {
62804
- close();
62805
- queue.push({ kind: "plan", data: { entries: entriesOf(entries) } });
62806
- },
62807
- /** Cursor's `cursor/update_todos`: the whole list, or under `merge` only what changed, by id. */
62808
- todos(raw, merge2) {
62809
- close();
62810
- const items = (Array.isArray(raw) ? raw : []).map(obj2).flatMap((e) => {
62811
- const [entry] = entriesOf([e]);
62812
- return entry ? [{ ...entry, id: str2(e.id) }] : [];
62813
- });
62814
- const next = merge2 ? [...todos] : [];
62815
- for (const item of items) {
62816
- const at = item.id ? next.findIndex((t2) => t2.id === item.id) : -1;
62817
- if (at >= 0) next[at] = item;
62818
- else next.push(item);
62819
- }
62820
- todos = next;
62821
- queue.push({ kind: "plan", data: { entries: todos.map(({ id: _, ...e }) => e) } });
62822
- },
62823
- log(text2) {
62824
- close();
62825
- if (text2.trim()) queue.push({ kind: "log", data: { text: text2 } });
62826
- },
62827
- error(text2) {
62828
- close();
62829
- if (text2.trim()) queue.push({ kind: "error", data: { text: text2.trim() } });
62830
- },
62831
- /** The turn is over: a half-held message is finished off. */
62832
- end() {
62833
- close();
62834
- for (const id2 of [...held2.keys()]) release(id2);
62835
- },
62836
- /** What arrived since the last call. */
62837
- events() {
62838
- const out = queue;
62839
- queue = [];
62840
- return out;
62841
- }
62842
- };
62843
- }
62844
-
62845
- // ../cli/src/lib/agent/wire/stream.ts
62846
- function createLineReader(renderLine) {
62847
- let buf = "";
62848
- return {
62849
- push(chunk) {
62850
- buf += chunk;
62851
- const lines = buf.split("\n");
62852
- buf = lines.pop() ?? "";
62853
- return lines.map(renderLine).join("");
62854
- },
62855
- flush() {
62856
- const rest = buf;
62857
- buf = "";
62858
- return rest ? renderLine(rest) : "";
62859
- }
62860
- };
62861
- }
62862
- function frame(line) {
62863
- try {
62864
- const parsed = JSON.parse(line);
62865
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
62866
- return parsed;
62867
- } catch {
62868
- return void 0;
62869
- }
62870
- }
62871
-
62872
- // ../cli/src/lib/agent/wire/antigravity-session.ts
62873
- import { existsSync } from "node:fs";
62874
- function antigravityConversationFile(session) {
62875
- if (/^[a-f0-9-]{36}$/i.test(session)) return home(".gemini", "antigravity-cli", "conversations", `${session}.db`);
62876
- }
62877
- function varint(bytes2, offset) {
62878
- let value = 0;
62879
- for (let shift = 0; shift < 70 && offset.value < bytes2.length; shift += 7) {
62880
- const byte = bytes2[offset.value++];
62881
- value += (byte & 127) * 2 ** shift;
62882
- if (byte < 128) return value;
62883
- }
62884
- throw new Error("Invalid Antigravity conversation metadata");
62885
- }
62886
- function* fields(bytes2) {
62887
- const offset = { value: 0 };
62888
- while (offset.value < bytes2.length) {
62889
- const tag = varint(bytes2, offset);
62890
- const number4 = Math.floor(tag / 8);
62891
- const wire = tag % 8;
62892
- if (number4 < 1 || number4 >= 2 ** 29) throw new Error("Invalid Antigravity conversation metadata");
62893
- if (wire === 0) {
62894
- yield [number4, varint(bytes2, offset)];
62895
- continue;
62896
- }
62897
- const size = wire === 2 ? varint(bytes2, offset) : wire === 1 ? 8 : wire === 5 ? 4 : -1;
62898
- const end = offset.value + size;
62899
- if (size < 0 || end > bytes2.length) throw new Error("Invalid Antigravity conversation metadata");
62900
- if (wire === 2) yield [number4, bytes2.subarray(offset.value, end)];
62901
- offset.value = end;
62902
- }
62903
- }
62904
- function bytesField(data, field) {
62905
- if (!(data instanceof Uint8Array)) return;
62906
- for (const [number4, value] of fields(data)) {
62907
- if (number4 === field && value instanceof Uint8Array) return value;
62908
- }
62909
- }
62910
- function varintField(data, field) {
62911
- if (!(data instanceof Uint8Array)) return;
62912
- for (const [number4, value] of fields(data)) {
62913
- if (number4 === field && typeof value === "number") return value;
62914
- }
62915
- }
62916
- function stepIndices(data) {
62917
- const out = [];
62918
- for (const [field, value] of fields(data)) {
62919
- if (field !== 2) continue;
62920
- if (typeof value === "number") out.push(value);
62921
- else {
62922
- const offset = { value: 0 };
62923
- while (offset.value < value.length) out.push(varint(value, offset));
62924
- }
62925
- }
62926
- return out;
62927
- }
62928
- function recordedContextLimit(data) {
62929
- const limit = varintField(bytesField(bytesField(bytesField(data, 1), 9), 10), 4);
62930
- return limit !== void 0 && Number.isSafeInteger(limit) && limit > 0 ? limit : void 0;
62931
- }
62932
- var utf8 = (bytes2) => bytes2 && Buffer.from(bytes2).toString("utf8");
62933
- function stepUuid(stepRow, index) {
62934
- if (!Number.isSafeInteger(index) || index < 0) return;
62935
- const id2 = bytesField(stepRow.get(index)?.metadata, 12);
62936
- return id2?.length === 36 ? id2 : void 0;
62937
- }
62938
- function antigravityRecordedModels(session, steps) {
62939
- const found = /* @__PURE__ */ new Map();
62940
- if (!steps.size) return found;
62941
- const file3 = antigravityConversationFile(session);
62942
- if (!file3 || !existsSync(file3)) return found;
62943
- try {
62944
- const sqlite = process.getBuiltinModule?.("node:sqlite");
62945
- if (!sqlite) return found;
62946
- const db = new sqlite.DatabaseSync(file3, { readOnly: true });
62947
- try {
62948
- const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
62949
- const promptIds = /* @__PURE__ */ new Map();
62950
- const promptUuid = (prompt) => {
62951
- if (!promptIds.has(prompt)) promptIds.set(prompt, stepUuid(stepRow, prompt));
62952
- return promptIds.get(prompt);
62953
- };
62954
- const groups = /* @__PURE__ */ new Map();
62955
- for (const [index, { prompt }] of steps) {
62956
- if (!Number.isSafeInteger(index) || index < 0) continue;
62957
- const id2 = stepUuid(stepRow, index) ?? promptUuid(prompt);
62958
- if (!id2) continue;
62959
- const uuid3 = utf8(id2);
62960
- let group = groups.get(uuid3);
62961
- if (!group) groups.set(uuid3, group = { id: id2, steps: /* @__PURE__ */ new Set() });
62962
- group.steps.add(index);
62963
- }
62964
- const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
62965
- for (const [uuid3, { id: id2, steps: groupSteps }] of groups) {
62966
- const key = Buffer.concat([Buffer.from([34, 36]), id2]);
62967
- for (const { data } of generations.iterate(key)) {
62968
- if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== uuid3) continue;
62969
- const model = utf8(bytesField(bytesField(data, 1), 19)) || void 0;
62970
- for (const step of stepIndices(data)) {
62971
- if (!groupSteps.has(step)) continue;
62972
- found.set(step, found.has(step) && found.get(step) !== model ? void 0 : model);
62973
- }
62974
- }
62975
- }
62976
- } finally {
62977
- db.close();
62978
- }
62979
- return found;
62980
- } catch {
62981
- return /* @__PURE__ */ new Map();
62982
- }
62983
- }
62984
- function antigravityRecordedContextLimit(session, step, prompt) {
62985
- if (!Number.isSafeInteger(step) || step < 0) return;
62986
- const file3 = antigravityConversationFile(session);
62987
- if (!file3 || !existsSync(file3)) return;
62988
- try {
62989
- const sqlite = process.getBuiltinModule?.("node:sqlite");
62990
- if (!sqlite) return;
62991
- const db = new sqlite.DatabaseSync(file3, { readOnly: true });
62992
- try {
62993
- const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
62994
- const id2 = stepUuid(stepRow, step) ?? stepUuid(stepRow, prompt);
62995
- if (!id2) return;
62996
- const key = Buffer.concat([Buffer.from([34, 36]), id2]);
62997
- const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
62998
- let found;
62999
- let matched = false;
63000
- for (const { data } of generations.iterate(key)) {
63001
- if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== utf8(id2)) continue;
63002
- if (!stepIndices(data).includes(step)) continue;
63003
- const limit = recordedContextLimit(data);
63004
- if (matched && found !== limit) return;
63005
- found = limit;
63006
- matched = true;
63007
- }
63008
- return found;
63009
- } finally {
63010
- db.close();
63011
- }
63012
- } catch {
63013
- return;
63014
- }
63015
- }
63016
-
63017
- // ../cli/src/lib/agent/wire/antigravity.ts
63018
- var CONTEXT_LOOK_EVERY_MS = 250;
63019
- var KINDS = {
63020
- run_command: "execute",
63021
- command_status: "execute",
63022
- send_command_input: "execute",
63023
- read_file: "read",
63024
- view_file: "read",
63025
- list_dir: "read",
63026
- grep_search: "search",
63027
- find_by_name: "search",
63028
- write_file: "edit",
63029
- write_to_file: "edit",
63030
- replace_file_content: "edit",
63031
- multi_replace_file_content: "edit",
63032
- read_url_content: "fetch",
63033
- search_web: "fetch"
63034
- };
63035
- var zero = () => ({ input: 0, cacheCreation: 0, cacheRead: 0, output: 0 });
63036
- var usageOf = (raw) => {
63037
- const u = obj2(raw);
63038
- return { input: num2(u.input_tokens), output: num2(u.output_tokens), cacheRead: num2(u.cache_read_tokens), cacheCreation: 0 };
63039
- };
63040
- var add = (a, b) => ({ input: a.input + b.input, output: a.output + b.output, cacheRead: a.cacheRead + b.cacheRead, cacheCreation: 0 });
63041
- function failureHint(reason) {
63042
- const zh = translating();
63043
- const hint2 = /authentication (?:required|failed)|not (?:logged|signed) in|unauthenticated|unauthorized|invalid credentials/i.test(reason) ? zh ? "\u8BF7\u5728\u672C\u673A\u8FD0\u884C agy \u767B\u5F55\u540E\u91CD\u8BD5\u3002" : "Run agy on this computer to sign in, then retry." : /invalid model|model.*(?:unavailable|not found|not recognized)/i.test(reason) ? zh ? "\u8BF7\u8FD0\u884C agy models\uFF0C\u9009\u62E9\u53EF\u7528\u6A21\u578B\u540E\u91CD\u8BD5\u3002" : "Run agy models and choose an available model, then retry." : /quota|rate.?limit|resource.exhausted|credits|429/i.test(reason) ? zh ? "\u8BF7\u7B49\u5F85\u989D\u5EA6\u6062\u590D\uFF0C\u6216\u68C0\u67E5 Antigravity \u8D26\u53F7\u989D\u5EA6\u540E\u91CD\u8BD5\u3002" : "Wait for the limit to reset or check your Antigravity credits, then retry." : /network|connection|unavailable|deadline|timeout|timed out|dial tcp|DNS|502|503/i.test(reason) ? zh ? "\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002" : "Check the network connection, then retry." : /permission|denied|soft.den/i.test(reason) ? zh ? "\u8BF7\u68C0\u67E5 Antigravity \u7684\u6743\u9650\u89C4\u5219\u540E\u91CD\u8BD5\u3002" : "Check Antigravity permission rules, then retry." : "";
63044
- return hint2 ? `${reason}
63045
- ${hint2}` : reason;
61994
+ var zero = () => ({ input: 0, cacheCreation: 0, cacheRead: 0, output: 0 });
61995
+ var usageOf = (raw) => {
61996
+ const u = obj2(raw);
61997
+ return { input: num2(u.input_tokens), output: num2(u.output_tokens), cacheRead: num2(u.cache_read_tokens), cacheCreation: 0 };
61998
+ };
61999
+ var add = (a, b) => ({ input: a.input + b.input, output: a.output + b.output, cacheRead: a.cacheRead + b.cacheRead, cacheCreation: 0 });
62000
+ function failureHint(reason) {
62001
+ const zh = translating();
62002
+ const hint2 = /authentication (?:required|failed)|not (?:logged|signed) in|unauthenticated|unauthorized|invalid credentials/i.test(reason) ? zh ? "\u8BF7\u5728\u672C\u673A\u8FD0\u884C agy \u767B\u5F55\u540E\u91CD\u8BD5\u3002" : "Run agy on this computer to sign in, then retry." : /invalid model|model.*(?:unavailable|not found|not recognized)/i.test(reason) ? zh ? "\u8BF7\u8FD0\u884C agy models\uFF0C\u9009\u62E9\u53EF\u7528\u6A21\u578B\u540E\u91CD\u8BD5\u3002" : "Run agy models and choose an available model, then retry." : /quota|rate.?limit|resource.exhausted|credits|429/i.test(reason) ? zh ? "\u8BF7\u7B49\u5F85\u989D\u5EA6\u6062\u590D\uFF0C\u6216\u68C0\u67E5 Antigravity \u8D26\u53F7\u989D\u5EA6\u540E\u91CD\u8BD5\u3002" : "Wait for the limit to reset or check your Antigravity credits, then retry." : /network|connection|unavailable|deadline|timeout|timed out|dial tcp|DNS|502|503/i.test(reason) ? zh ? "\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002" : "Check the network connection, then retry." : /permission|denied|soft.den/i.test(reason) ? zh ? "\u8BF7\u68C0\u67E5 Antigravity \u7684\u6743\u9650\u89C4\u5219\u540E\u91CD\u8BD5\u3002" : "Check Antigravity permission rules, then retry." : "";
62003
+ return hint2 ? `${reason}
62004
+ ${hint2}` : reason;
63046
62005
  }
63047
62006
  var imagePath = (target) => /\.(?:png|jpe?g|gif|webp|bmp|tiff?|svg)$/i.test(target);
63048
62007
  function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
@@ -63106,7 +62065,7 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
63106
62065
  const events = createEventCollector();
63107
62066
  const fail = (reason, code = "provider_failed") => {
63108
62067
  failure3 = failureHint(reason);
63109
- classified = { code, level: 3, reason: failure3 };
62068
+ classified = makeFailure("runtime", failure3, { code, detail: reason });
63110
62069
  events.error(failure3);
63111
62070
  };
63112
62071
  const reader = createLineReader((line) => {
@@ -63175,7 +62134,7 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
63175
62134
  closed.add(id2);
63176
62135
  const failed = !!reason || step.state !== "DONE";
63177
62136
  if (["read_file", "view_file"].includes(name) && imagePath(target)) {
63178
- const file3 = path19.resolve(cwd, target);
62137
+ const file3 = path8.resolve(cwd, target);
63179
62138
  if (failed) {
63180
62139
  imageErrors.set(file3, reason || str2(step.state));
63181
62140
  out += `
@@ -63228,7 +62187,7 @@ ${imageError(target, reason || str2(step.state))}
63228
62187
  return {
63229
62188
  push: reader.push,
63230
62189
  setRequiredImages(files) {
63231
- requiredImages = files.filter(imagePath).map((file3) => path19.resolve(cwd, file3));
62190
+ requiredImages = files.filter(imagePath).map((file3) => path8.resolve(cwd, file3));
63232
62191
  },
63233
62192
  flush() {
63234
62193
  const text2 = reader.flush();
@@ -63261,7 +62220,7 @@ ${imageError(target, reason || str2(step.state))}
63261
62220
  },
63262
62221
  failure: () => failure3 || imageFailure,
63263
62222
  terminalFailure: () => terminal && !!classified,
63264
- executionFailure: () => classified ?? (imageFailure ? { code: "image_read_failed", level: 3, reason: imageFailure } : void 0),
62223
+ executionFailure: () => classified ?? (imageFailure ? makeFailure("runtime", imageFailure, { code: "image_read_failed", detail: imageFailure }) : void 0),
63265
62224
  events: events.events,
63266
62225
  activity: events.activity
63267
62226
  };
@@ -63288,7 +62247,7 @@ function args(argv, resume) {
63288
62247
  if (namesFlag(argv, ["--continue", "-c", "--conversation", "--remote-agent"])) throw new Error(translating() ? "\u8BF7\u901A\u8FC7 WildCrane \u9009\u62E9 Antigravity \u4F1A\u8BDD\uFF0C\u4E0D\u8981\u5728\u989D\u5916\u53C2\u6570\u4E2D\u6307\u5B9A\u4F1A\u8BDD\u6216\u8FDC\u7A0B\u6267\u884C\u3002" : "Antigravity: select a session through WildCrane, not extra arguments.");
63289
62248
  if (resume) {
63290
62249
  const file3 = antigravityConversationFile(resume);
63291
- if (!file3 || !fs17.existsSync(file3)) throw new Error(translating() ? "Antigravity \u4F1A\u8BDD\u4E0D\u5B58\u5728\u3002\u8BF7\u5728\u672C\u673A\u6062\u590D\u539F\u4F1A\u8BDD\u540E\u7EED\u63A5\u3002" : "Antigravity session not found. Restore the original conversation on this computer before resuming.");
62250
+ if (!file3 || !fs7.existsSync(file3)) throw new Error(translating() ? "Antigravity \u4F1A\u8BDD\u4E0D\u5B58\u5728\u3002\u8BF7\u5728\u672C\u673A\u6062\u590D\u539F\u4F1A\u8BDD\u540E\u7EED\u63A5\u3002" : "Antigravity session not found. Restore the original conversation on this computer before resuming.");
63292
62251
  }
63293
62252
  const extra = resume ? ["--conversation", resume] : [];
63294
62253
  if (!namesFlag(argv, ["--output-format"])) extra.push("--output-format", "stream-json");
@@ -63333,7 +62292,7 @@ var ANTIGRAVITY = {
63333
62292
  const copy2 = locate(ANTIGRAVITY);
63334
62293
  if (!copy2) return [];
63335
62294
  const start = spawnable(copy2.file, ["models"], { env: copyEnv(copy2.file), stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 });
63336
- const result = spawnSync3(start.command, start.args, { ...start.options, encoding: "utf8" });
62295
+ const result = spawnSync2(start.command, start.args, { ...start.options, encoding: "utf8" });
63337
62296
  return result.status === 0 ? antigravityModels(result.stdout ?? "").map((m) => m.id) : [];
63338
62297
  },
63339
62298
  env: () => ({ ...process.env }),
@@ -63347,10 +62306,10 @@ var ANTIGRAVITY = {
63347
62306
 
63348
62307
  The task working directory is ${env2.PWD ?? process.cwd()}. Use it as the base for project files and commands. This additional workspace contains only language rules; do not write task output here.`;
63349
62308
  const hash2 = createHash3("sha256").update(rule).digest("hex").slice(0, 16);
63350
- const root2 = path20.join(machineHome(), "prompts", `antigravity-${hash2}`);
63351
- const file3 = path20.join(root2, ".agents", "rules", "language.md");
63352
- fs17.mkdirSync(path20.dirname(file3), { recursive: true });
63353
- fs17.writeFileSync(file3, `---
62309
+ const root2 = path9.join(machineHome(), "prompts", `antigravity-${hash2}`);
62310
+ const file3 = path9.join(root2, ".agents", "rules", "language.md");
62311
+ fs7.mkdirSync(path9.dirname(file3), { recursive: true });
62312
+ fs7.writeFileSync(file3, `---
63354
62313
  trigger: always_on
63355
62314
  ---
63356
62315
 
@@ -63452,20 +62411,12 @@ function checkHarnesses(harnesses) {
63452
62411
  }
63453
62412
 
63454
62413
  // ../cli/src/lib/agent/harnesses/claude-code.ts
63455
- import path23 from "node:path";
63456
-
63457
- // ../cli/src/lib/agent/retry.ts
63458
- function readFailure(raw) {
63459
- if (!raw || typeof raw !== "object") return;
63460
- const { code, level, reason, source, retryAfterMs: retryAfterMs2 } = raw;
63461
- if (typeof code !== "string" || !code || typeof reason !== "string" || level !== 1 && level !== 2 && level !== 3) return;
63462
- return { code, level, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source) ? { source } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
63463
- }
62414
+ import path12 from "node:path";
63464
62415
 
63465
62416
  // ../cli/src/lib/agent/wire/failures.ts
63466
62417
  var ExecutionError = class extends Error {
63467
62418
  constructor(failure3) {
63468
- super(failure3.reason);
62419
+ super(failure3.summary);
63469
62420
  this.failure = failure3;
63470
62421
  }
63471
62422
  failure;
@@ -63475,13 +62426,9 @@ var TEMPORARY_HTTP = /* @__PURE__ */ new Set([502, 503, 504, 529]);
63475
62426
  function executionFailure(error62) {
63476
62427
  if (error62 instanceof ExecutionError) return error62.failure;
63477
62428
  const code = str2(obj2(error62).code);
63478
- const reason = error62 instanceof Error ? error62.message : String(error62);
63479
- return {
63480
- code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
63481
- level: NETWORK.has(code) ? 2 : 3,
63482
- source: "harness",
63483
- reason
63484
- };
62429
+ const raw = error62 instanceof Error ? error62.message : String(error62);
62430
+ const resolvedCode = isSessionMissingText(raw) ? "session_not_found" : NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed";
62431
+ return makeFailure("runner", raw, { code: resolvedCode, detail: raw });
63485
62432
  }
63486
62433
  function retryAfterMs(value, now = Date.now()) {
63487
62434
  if (typeof value !== "string") return;
@@ -63491,37 +62438,48 @@ function retryAfterMs(value, now = Date.now()) {
63491
62438
  const date5 = Date.parse(header);
63492
62439
  if (Number.isFinite(date5)) return Math.max(0, date5 - now);
63493
62440
  }
63494
- function providerFailure(error62, reason) {
62441
+ function providerFailure(error62, reason, detail) {
63495
62442
  const info = obj2(error62);
63496
62443
  const status2 = typeof info.status === "number" ? info.status : void 0;
63497
62444
  const headers = obj2(info.headers);
63498
62445
  const wait = retryAfterMs(headers["retry-after"] ?? headers["Retry-After"]);
63499
- const code = info.code ?? info.type;
63500
- if (code === "session_not_found") return { code, source: "provider", level: 3, reason };
63501
- if (status2 === 401 || status2 === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str2(code))) {
63502
- return { code: "provider_refused", source: "provider", level: 3, reason };
62446
+ const rawCode = info.code ?? info.type;
62447
+ const fullDetail = detail || reason;
62448
+ if (rawCode === "session_not_found" || isSessionMissingText(reason) || isSessionMissingText(fullDetail)) {
62449
+ return makeFailure("runtime", reason, { code: "session_not_found", detail: fullDetail });
62450
+ }
62451
+ if (status2 === 401 || status2 === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str2(rawCode))) {
62452
+ return makeFailure("runtime", reason, { code: "provider_refused", detail: fullDetail });
62453
+ }
62454
+ if (status2 === 429 || rawCode === "rate_limit_error") {
62455
+ return makeFailure("runtime", reason, { code: "rate_limited", detail: fullDetail, retryAfterMs: wait });
62456
+ }
62457
+ if (TEMPORARY_HTTP.has(status2 ?? 0) || rawCode === "overloaded_error") {
62458
+ return makeFailure("runtime", reason, { code: "service_overloaded", detail: fullDetail, retryAfterMs: wait });
62459
+ }
62460
+ if (NETWORK.has(str2(rawCode))) {
62461
+ return makeFailure("runtime", reason, { code: "connection_lost", detail: fullDetail, retryAfterMs: wait });
63503
62462
  }
63504
- if (code === "rate_limit_error") return { code: "rate_limited", source: "provider", level: 2, reason, retryAfterMs: wait };
63505
- if (TEMPORARY_HTTP.has(status2 ?? 0) || code === "overloaded_error") return { code: "service_overloaded", source: "provider", level: 2, reason, retryAfterMs: wait };
63506
- if (NETWORK.has(str2(code))) return { code: "connection_lost", source: "provider", level: 2, reason, retryAfterMs: wait };
63507
- return { code: "provider_failed", source: "provider", level: 3, reason };
62463
+ return makeFailure("runtime", reason, { code: "provider_failed", detail: fullDetail, retryAfterMs: wait });
63508
62464
  }
63509
62465
  function codexFailure(raw, fallback) {
63510
62466
  const error62 = obj2(raw);
63511
62467
  const failure3 = readFailure(error62.wildcraneFailure);
63512
- if (failure3?.source === "harness" || failure3?.source === "invariant") return failure3;
62468
+ if (failure3) return failure3;
63513
62469
  const reason = str2(error62.message) || fallback;
62470
+ const additional = str2(error62.additionalDetails);
62471
+ const detail = [reason, additional].filter(Boolean).join("\n");
63514
62472
  const info = error62.codexErrorInfo;
63515
- if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason);
63516
- if (info === "rateLimitExceeded") return providerFailure({ ...error62, type: "rate_limit_error" }, reason);
62473
+ if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason, detail);
62474
+ if (info === "rateLimitExceeded") return providerFailure({ ...error62, type: "rate_limit_error" }, reason, detail);
63517
62475
  const types = obj2(info);
63518
62476
  for (const kind of ["httpConnectionFailed", "responseStreamConnectionFailed", "responseStreamDisconnected", "responseTooManyFailedAttempts"]) {
63519
62477
  if (!(kind in types)) continue;
63520
62478
  const status2 = obj2(types[kind]).httpStatusCode;
63521
- if (typeof status2 === "number") return providerFailure({ ...error62, status: status2 }, reason);
63522
- if (kind !== "responseTooManyFailedAttempts") return providerFailure({ ...error62, code: "ECONNRESET" }, reason);
62479
+ if (typeof status2 === "number") return providerFailure({ ...error62, status: status2 }, reason, detail);
62480
+ if (kind !== "responseTooManyFailedAttempts") return providerFailure({ ...error62, code: "ECONNRESET" }, reason, detail);
63523
62481
  }
63524
- return providerFailure(error62, reason);
62482
+ return providerFailure(error62, reason, detail);
63525
62483
  }
63526
62484
 
63527
62485
  // ../cli/src/lib/agent/wire/claude-stream.ts
@@ -63678,7 +62636,12 @@ function createStreamRenderer() {
63678
62636
  const turnUsage = usageOf2(ev.usage);
63679
62637
  if (turnUsage) usage = usage ? addUsage(usage, turnUsage) : turnUsage;
63680
62638
  failure3 = ev.is_error === true ? whyItFailed(ev) : void 0;
63681
- classified = failure3 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, source: "validation", reason: failure3 } : { ...apiFailure ?? providerFailure(ev.error, failure3), reason: failure3 } : void 0;
62639
+ classified = failure3 ? ev.subtype === "error_max_structured_output_retries" ? makeFailure("validation", failure3, { code: "validation_failed", detail: failure3 }) : (() => {
62640
+ const base = apiFailure ?? providerFailure(ev.error, failure3, failure3);
62641
+ const summary2 = clipSummary(failure3);
62642
+ const detail = clipDetail(failure3);
62643
+ return { ...base, summary: summary2, ...detail && detail !== summary2 ? { detail } : {} };
62644
+ })() : void 0;
63682
62645
  apiFailure = void 0;
63683
62646
  if (failure3) events.error(failure3);
63684
62647
  turns.push({
@@ -64122,7 +63085,7 @@ function createCodexStreamRenderer(carried = false) {
64122
63085
  return "";
64123
63086
  // 最终失败保留;连接提示只在没有后续成功完成时才作为失败。
64124
63087
  case "turn.failed": {
64125
- const said = str2(obj2(ev.error).message) || failure3?.reason || "Codex execution failed.";
63088
+ const said = str2(obj2(ev.error).message) || failure3?.summary || "Codex execution failed.";
64126
63089
  failure3 = codexFailure(ev.error, said);
64127
63090
  events.error(said);
64128
63091
  return `[error] ${said}
@@ -64177,7 +63140,7 @@ function createCodexStreamRenderer(carried = false) {
64177
63140
  },
64178
63141
  costIncomplete: () => childSpend(subagents, since).costIncomplete || childSpend(subagents, since).costUsd !== void 0 && priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own3()) === void 0 || void 0,
64179
63142
  resumeId: () => threadId,
64180
- failure: () => failure3?.reason ?? background.failure(),
63143
+ failure: () => failure3?.summary ?? background.failure(),
64181
63144
  executionFailure: () => failure3,
64182
63145
  background: () => subagents.size ? background.count() : void 0,
64183
63146
  events: events.events,
@@ -64428,16 +63391,16 @@ function createKimiStreamRenderer(cwd, resumeId) {
64428
63391
  }
64429
63392
 
64430
63393
  // ../cli/src/lib/agent/wire/acp-cost.ts
64431
- import fs18 from "node:fs";
64432
- import path21 from "node:path";
63394
+ import fs8 from "node:fs";
63395
+ import path10 from "node:path";
64433
63396
  import { createHash as createHash4 } from "node:crypto";
64434
63397
  function acpCostFile(tool, cwd, session) {
64435
63398
  const key = createHash4("sha256").update(JSON.stringify([tool, cwd, session])).digest("hex");
64436
- return path21.join(machineHome(), "usage", "acp", `${key}.json`);
63399
+ return path10.join(machineHome(), "usage", "acp", `${key}.json`);
64437
63400
  }
64438
63401
  function readAcpCost(file3) {
64439
63402
  try {
64440
- const n = JSON.parse(fs18.readFileSync(file3, "utf8"));
63403
+ const n = JSON.parse(fs8.readFileSync(file3, "utf8"));
64441
63404
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : void 0;
64442
63405
  } catch {
64443
63406
  return void 0;
@@ -64446,10 +63409,10 @@ function readAcpCost(file3) {
64446
63409
  function saveAcpCost(file3, cost) {
64447
63410
  if (cost === void 0) return;
64448
63411
  try {
64449
- fs18.mkdirSync(path21.dirname(file3), { recursive: true, mode: 448 });
63412
+ fs8.mkdirSync(path10.dirname(file3), { recursive: true, mode: 448 });
64450
63413
  const tmp = `${file3}.${process.pid}.tmp`;
64451
- fs18.writeFileSync(tmp, JSON.stringify(cost), { mode: 384 });
64452
- fs18.renameSync(tmp, file3);
63414
+ fs8.writeFileSync(tmp, JSON.stringify(cost), { mode: 384 });
63415
+ fs8.renameSync(tmp, file3);
64453
63416
  } catch {
64454
63417
  }
64455
63418
  }
@@ -64470,7 +63433,7 @@ function bounded(work, ms, reason) {
64470
63433
  }
64471
63434
 
64472
63435
  // ../cli/src/lib/agent/wire/acp.ts
64473
- import fs19 from "node:fs";
63436
+ import fs9 from "node:fs";
64474
63437
 
64475
63438
  // ../cli/src/lib/agent/wire/rpc.ts
64476
63439
  var RpcError = class extends Error {
@@ -64528,7 +63491,7 @@ function connect(stdout, stdin, onCall, dialect = {}) {
64528
63491
  } else pending.ok(obj2(msg.result));
64529
63492
  }
64530
63493
  });
64531
- stdout.on("close", () => closed(new ExecutionError({ code: "connection_lost", level: 2, reason: "The agent closed the connection." })));
63494
+ stdout.on("close", () => closed(new ExecutionError({ code: "connection_lost", source: "runtime", summary: "The agent closed the connection." })));
64532
63495
  stdout.on("error", (err) => closed(new ExecutionError(executionFailure(err))));
64533
63496
  stdin.on("error", (err) => closed(new ExecutionError(executionFailure(err))));
64534
63497
  return {
@@ -64606,8 +63569,8 @@ function createTail(log) {
64606
63569
  // ../cli/package.json
64607
63570
  var package_default = {
64608
63571
  name: "wildcrane",
64609
- version: "0.11.85",
64610
- akbContract: 28,
63572
+ version: "0.11.86",
63573
+ akbContract: 29,
64611
63574
  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.",
64612
63575
  keywords: [
64613
63576
  "kanban",
@@ -64750,7 +63713,7 @@ var STOPPED = {
64750
63713
  cancelled: "the turn was cancelled"
64751
63714
  };
64752
63715
  function mcpServersIn(file3) {
64753
- const servers = obj2(obj2(JSON.parse(fs19.readFileSync(file3, "utf8"))).mcpServers);
63716
+ const servers = obj2(obj2(JSON.parse(fs9.readFileSync(file3, "utf8"))).mcpServers);
64754
63717
  return Object.entries(servers).map(([name, raw]) => {
64755
63718
  const s = obj2(raw);
64756
63719
  return {
@@ -64793,7 +63756,7 @@ async function oneTurn(io, options) {
64793
63756
  if (msg.method === "session/update") {
64794
63757
  const params = obj2(msg.params);
64795
63758
  if (!live && (!params.sessionId || params.sessionId === io.resumeId)) {
64796
- update2(params.update, createTail(() => {
63759
+ update(params.update, createTail(() => {
64797
63760
  }), (usd) => {
64798
63761
  costBefore = usd;
64799
63762
  }, () => {
@@ -64823,7 +63786,7 @@ async function oneTurn(io, options) {
64823
63786
  contentAt = Date.now();
64824
63787
  io.event?.({ kind: "phase", data: { phase: "started", at: (/* @__PURE__ */ new Date()).toISOString(), contentAt: new Date(contentAt).toISOString() } });
64825
63788
  }
64826
- update2(obj2(msg.params).update, tail, (usd) => costUsd = usd, (window) => context = window);
63789
+ update(obj2(msg.params).update, tail, (usd) => costUsd = usd, (window) => context = window);
64827
63790
  events.update(obj2(msg.params).update);
64828
63791
  emit();
64829
63792
  }
@@ -64866,7 +63829,7 @@ async function oneTurn(io, options) {
64866
63829
  } catch (e) {
64867
63830
  const reason = e instanceof Error ? e.message : String(e);
64868
63831
  const failure3 = e instanceof RpcError ? providerFailure(e.data, reason) : executionFailure(e);
64869
- if (failure3.code !== "session_not_found") throw e;
63832
+ if (!(e instanceof RpcError) || obj2(e.data).code !== "session_not_found") throw e;
64870
63833
  if (!io.restartPrompt) throw new ExecutionError(failure3);
64871
63834
  const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
64872
63835
  opened = fresh.opened;
@@ -64914,7 +63877,7 @@ async function oneTurn(io, options) {
64914
63877
  `);
64915
63878
  events.error(why);
64916
63879
  emit();
64917
- return { ok: false, result, error: why, failure: { code: stopReason, level: 3, reason: why }, usage, context, costUsd };
63880
+ return { ok: false, result, error: why, failure: makeFailure("runtime", why, { code: stopReason }), usage, context, costUsd };
64918
63881
  }
64919
63882
  emit();
64920
63883
  return { ok: true, result, usage, context, costUsd };
@@ -64932,7 +63895,7 @@ async function oneTurn(io, options) {
64932
63895
  io.signal?.removeEventListener("abort", cancelled);
64933
63896
  }
64934
63897
  }
64935
- function update2(raw, tail, gotCost, gotContext) {
63898
+ function update(raw, tail, gotCost, gotContext) {
64936
63899
  const change = obj2(raw);
64937
63900
  switch (change.sessionUpdate) {
64938
63901
  case "agent_message_chunk":
@@ -64980,7 +63943,7 @@ function decide(params, tail, events) {
64980
63943
  }
64981
63944
 
64982
63945
  // ../cli/src/lib/agent/wire/zcode.ts
64983
- import path22 from "node:path";
63946
+ import path11 from "node:path";
64984
63947
  function whereHint2(input2, title) {
64985
63948
  const named = obj2(input2);
64986
63949
  for (const key of ["command", "file_path", "path", "url", "pattern"]) {
@@ -65173,7 +64136,7 @@ async function oneTurn2(io, options) {
65173
64136
  { stringIds: true }
65174
64137
  );
65175
64138
  try {
65176
- const workspacePath = path22.resolve(io.cwd);
64139
+ const workspacePath = path11.resolve(io.cwd);
65177
64140
  const workspace = { workspacePath, workspaceKey: workspacePath };
65178
64141
  let opened;
65179
64142
  if (io.resumeId) {
@@ -65274,7 +64237,7 @@ function event(envelope, parts, tail, live, ended) {
65274
64237
  case "turn.failed": {
65275
64238
  const error62 = obj2(payload.error);
65276
64239
  const failure3 = providerFailure(error62, str2(error62.message) || "the turn failed");
65277
- return ended({ ok: false, error: failure3.reason, failure: failure3 });
64240
+ return ended({ ok: false, error: failure3.summary, failure: failure3 });
65278
64241
  }
65279
64242
  case "session.closed":
65280
64243
  return ended({ ok: false, error: str2(payload.reason) || "the agent closed the session" });
@@ -65289,9 +64252,9 @@ function decide2(params, tail) {
65289
64252
  }
65290
64253
 
65291
64254
  // ../cli/src/lib/agent/idle.ts
65292
- var IDLE_MS2 = 5 * 6e4;
64255
+ var IDLE_MS = 5 * 6e4;
65293
64256
  var IDLE_ERROR = "No response for 5 minutes (idle timeout).";
65294
- var IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
64257
+ var IDLE_FAILURE = { code: "idle_timeout", source: "runtime", summary: IDLE_ERROR };
65295
64258
  var PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
65296
64259
 
65297
64260
  // ../cli/src/lib/agent/wire/codex.ts
@@ -65632,12 +64595,12 @@ async function run(io, options, count2) {
65632
64595
  const costUsd = cost === void 0 ? child.costUsd : cost + (child.costUsd ?? 0);
65633
64596
  const failure3 = error62 || (cleanup.status === "unconfirmed" ? cleanup.detail : void 0) || work.work().filter((w) => !w.intentionalStop && ["failed", "interrupted"].includes(w.status)).map((w) => w.result || `Background work ${w.id} ${w.status}.`).join("\n") || void 0;
65634
64597
  if (failure3) io.event?.({ kind: "error", data: { text: failure3 } });
65635
- resolve2({ ok: !failure3, error: failure3, failure: failure3 ? classified ?? { code: "execution_failed", level: 3, reason: failure3 } : void 0, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
64598
+ resolve2({ ok: !failure3, error: failure3, failure: failure3 ? classified ?? makeFailure("runtime", failure3, { code: "execution_failed", detail: failure3 }) : void 0, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
65636
64599
  };
65637
64600
  const closed = () => {
65638
64601
  const reason = "Codex connection closed before all work and results finished.";
65639
64602
  if (work.work().some((w) => ["running", "unknown"].includes(w.status))) note("Connection lost; managed cleanup is unconfirmed.");
65640
- end(reason, { code: "connection_lost", level: 2, reason });
64603
+ end(reason, makeFailure("runtime", reason, { code: "connection_lost", detail: reason }));
65641
64604
  };
65642
64605
  const inputFailed = (e) => {
65643
64606
  if (work.work().some((w) => ["running", "unknown"].includes(w.status))) note("Connection input failed; managed cleanup is unconfirmed.");
@@ -65676,7 +64639,7 @@ async function run(io, options, count2) {
65676
64639
  } catch (error62) {
65677
64640
  if (!ended) note(error62 instanceof Error ? error62.message : String(error62));
65678
64641
  }
65679
- if (!ended) end(IDLE_FAILURE.reason, IDLE_FAILURE);
64642
+ if (!ended) end(IDLE_FAILURE.summary, IDLE_FAILURE);
65680
64643
  };
65681
64644
  io.idleSignal?.addEventListener("abort", idle, { once: true });
65682
64645
  const childUpdates = () => {
@@ -65936,10 +64899,24 @@ async function run(io, options, count2) {
65936
64899
  const failure3 = codexFailure(p.error, "Codex failed.");
65937
64900
  if (p.willRetry === true && submitted && active && !idling) {
65938
64901
  status2 = "retrying";
65939
- io.log(`[Codex recovery] ${failure3.code}: ${failure3.reason}
64902
+ io.log(`[Codex recovery] ${failure3.code ?? "error"}: ${failure3.summary}
65940
64903
  `);
65941
64904
  io.event?.({ kind: "status", data: { state: "retrying", source: "codex", code: failure3.code } });
65942
- } else if (p.willRetry !== true) end(failure3.reason, failure3);
64905
+ io.event?.({
64906
+ kind: "retry",
64907
+ data: {
64908
+ state: "retrying",
64909
+ source: "runtime",
64910
+ runtime: { connector: "codex", name: null, model: model ?? null },
64911
+ attempt: 1,
64912
+ maxAttempts: MAX_RETRY_ATTEMPTS,
64913
+ summary: failure3.summary,
64914
+ ...failure3.detail ? { detail: failure3.detail } : {},
64915
+ ...failure3.code ? { code: failure3.code } : {},
64916
+ at: (/* @__PURE__ */ new Date()).toISOString()
64917
+ }
64918
+ });
64919
+ } else if (p.willRetry !== true) end(failure3.summary, failure3);
65943
64920
  }
65944
64921
  if (msg.method === "turn/completed") {
65945
64922
  const turn2 = obj2(p.turn);
@@ -65953,7 +64930,7 @@ async function run(io, options, count2) {
65953
64930
  if (idling) return;
65954
64931
  if (turn2.status !== "completed") {
65955
64932
  const reason = str2(obj2(turn2.error).message) || `Codex turn ${str2(turn2.status)}.`;
65956
- const failure3 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : { code: "turn_stopped", level: 3, reason };
64933
+ const failure3 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : makeFailure("runtime", reason, { code: "turn_stopped", detail: reason });
65957
64934
  end(reason, failure3);
65958
64935
  return;
65959
64936
  }
@@ -65990,11 +64967,15 @@ async function run(io, options, count2) {
65990
64967
  try {
65991
64968
  response = await bounded(rpc.call(method, params), preparingUntil - Date.now(), `Codex ${method} timed out.`);
65992
64969
  } catch (error62) {
64970
+ if (mode === "fork" && error62 instanceof RpcError && error62.code === -32600 && error62.message === `no rollout found for thread id ${params.threadId}`) {
64971
+ end(error62.message, { code: "codex_fork_source_missing", source: "runtime", summary: error62.message, detail: error62.message });
64972
+ return done;
64973
+ }
65993
64974
  const failure3 = error62 instanceof RpcError ? codexFailure(error62.data, error62.message) : void 0;
65994
- if (mode !== "fork" || failure3?.source !== "harness" || failure3.code !== "codex_source_busy") throw error62;
64975
+ if (mode !== "fork" || failure3?.code !== "codex_source_busy") throw error62;
65995
64976
  if (!waiting) {
65996
64977
  waiting = true;
65997
- io.event?.({ kind: "log", data: { text: failure3.reason } });
64978
+ io.event?.({ kind: "log", data: { text: failure3.summary } });
65998
64979
  }
65999
64980
  io.activity?.();
66000
64981
  await delay(500, void 0, { signal: io.signal });
@@ -66020,7 +65001,7 @@ async function run(io, options, count2) {
66020
65001
  await start(io.prompt, options.images);
66021
65002
  } catch (e) {
66022
65003
  const failure3 = e instanceof RpcError ? codexFailure(e.data, e.message) : executionFailure(e);
66023
- end(failure3.reason, failure3);
65004
+ end(failure3.summary, failure3);
66024
65005
  }
66025
65006
  return done;
66026
65007
  }
@@ -66036,15 +65017,15 @@ var userMessage = (prompt) => `${JSON.stringify({ type: "user", message: { role:
66036
65017
  `;
66037
65018
  function claudeOnWindows() {
66038
65019
  const [local, roaming] = [process.env.LOCALAPPDATA?.trim(), process.env.APPDATA?.trim()];
66039
- const packages = local ? path23.join(local, "Packages") : "";
65020
+ const packages = local ? path12.join(local, "Packages") : "";
66040
65021
  const data = [
66041
- ...folders(packages).filter((name) => /^(\w+\.)?Claude_/i.test(name)).sort().map((name) => path23.join(packages, name, "LocalCache", "Roaming", "Claude")),
66042
- ...roaming ? [path23.join(roaming, "Claude")] : []
65022
+ ...folders(packages).filter((name) => /^(\w+\.)?Claude_/i.test(name)).sort().map((name) => path12.join(packages, name, "LocalCache", "Roaming", "Claude")),
65023
+ ...roaming ? [path12.join(roaming, "Claude")] : []
66043
65024
  ];
66044
65025
  return data.flatMap(
66045
- (dir) => latestIn(path23.join(dir, "claude-code")).flatMap((version2) => [
66046
- path23.join(version2, "claude.exe"),
66047
- ...folders(version2).map((build) => path23.join(version2, build, "claude.exe"))
65026
+ (dir) => latestIn(path12.join(dir, "claude-code")).flatMap((version2) => [
65027
+ path12.join(version2, "claude.exe"),
65028
+ ...folders(version2).map((build) => path12.join(version2, build, "claude.exe"))
66048
65029
  ])
66049
65030
  );
66050
65031
  }
@@ -66288,24 +65269,165 @@ var CLAUDE_CODE = {
66288
65269
  ...latestIn(home(".local", "share", "claude", "versions")),
66289
65270
  // The copy Claude Desktop carries.
66290
65271
  ...process.platform === "win32" ? claudeOnWindows() : latestIn(home("Library", "Application Support", "Claude", "claude-code")).flatMap(
66291
- (version2) => folders(version2).map((build) => path23.join(version2, build, "claude.app", "Contents", "MacOS", "claude"))
65272
+ (version2) => folders(version2).map((build) => path12.join(version2, build, "claude.app", "Contents", "MacOS", "claude"))
66292
65273
  )
66293
65274
  ],
66294
65275
  install: "npm install -g @anthropic-ai/claude-code"
66295
65276
  };
66296
65277
 
66297
65278
  // ../cli/src/lib/agent/harnesses/codex.ts
66298
- import fs20 from "node:fs";
66299
- import path24 from "node:path";
65279
+ import fs11 from "node:fs";
65280
+ import path15 from "node:path";
65281
+
65282
+ // ../cli/src/lib/paths.ts
65283
+ import path14 from "node:path";
65284
+
65285
+ // ../cli/src/lib/machine/project.ts
65286
+ import fs10 from "node:fs";
65287
+ import path13 from "node:path";
65288
+ var SESSIONS_FILE = "sessions.json";
65289
+ var SESSIONS_FOLDER = "sessions";
65290
+ var ASSETS_FOLDER = "assets";
65291
+ var SESSIONS_LOCK = "sessions.lock";
65292
+ var INDEX_LOCK = "index.lock";
65293
+ var UI_CONFIG_FILE = "ui.config.json";
65294
+ function realPathOf(dir) {
65295
+ const here2 = path13.resolve(dir);
65296
+ const rest = [];
65297
+ let at = here2;
65298
+ for (; ; ) {
65299
+ try {
65300
+ return path13.join(fs10.realpathSync(at), ...rest);
65301
+ } catch {
65302
+ const up = path13.dirname(at);
65303
+ if (up === at) return here2;
65304
+ rest.unshift(path13.basename(at));
65305
+ at = up;
65306
+ }
65307
+ }
65308
+ }
65309
+ function stateRootOf(board) {
65310
+ let dir = realPathOf(board);
65311
+ for (; ; ) {
65312
+ if (fs10.existsSync(path13.join(dir, ".git"))) return dir;
65313
+ const up = path13.dirname(dir);
65314
+ if (up === dir) break;
65315
+ dir = up;
65316
+ }
65317
+ return rootAbove(realPathOf(board));
65318
+ }
65319
+ function rootAbove(board) {
65320
+ const parent = path13.dirname(board);
65321
+ return ["docs", ".akb"].includes(path13.basename(parent)) ? path13.dirname(parent) : parent;
65322
+ }
65323
+ function projectStateDir(board, root2 = stateRootOf(board)) {
65324
+ const relative = path13.relative(realPathOf(root2), realPathOf(board));
65325
+ if (relative === ".." || relative.startsWith(`..${path13.sep}`) || path13.isAbsolute(relative)) {
65326
+ throw new Error("The board must be inside its project root.");
65327
+ }
65328
+ return path13.join(realPathOf(root2), ".akb", "boards", relative || "_root");
65329
+ }
65330
+
65331
+ // ../cli/src/lib/paths.ts
65332
+ var REPO_ROOT = "";
65333
+ var KANBAN = "";
65334
+ var TODO = "";
65335
+ var ARCHIVE = "";
65336
+ var ARCHIVE_MD = "";
65337
+ var README = "";
65338
+ var MODULES_MD = "";
65339
+ var CONFIG = "";
65340
+ var KANBAN_GITIGNORE = "";
65341
+ var RELEASES = "";
65342
+ var RELEASE_SUMMARIES = "";
65343
+ var AGENTS = "";
65344
+ var STUDIOS = "";
65345
+ var ASSETS = "";
65346
+ var BOARD_STATE = "";
65347
+ var MEMORY = "";
65348
+ var AGENT_MEMORY = "";
65349
+ var PROJECT_MD = "";
65350
+ var LOCK = "";
65351
+ var UI_CONFIG = "";
65352
+ var ENV_FILE = "";
65353
+ var SESSIONS = "";
65354
+ var SESSIONS_DIR = "";
65355
+ var SESSIONS_LOCK2 = "";
65356
+ var INDEX_LOCK2 = "";
65357
+ var DELIVERIES = "";
65358
+ var PLANS = "";
65359
+ var PLANS_ARCHIVE = "";
65360
+ var RULES = "";
65361
+ var TRIAGE = "";
65362
+ var SIGNALS_ARCHIVED = "";
65363
+ var SIGNALS_DISMISSED = "";
65364
+ var SIGNALS_FILES = "";
65365
+ var SIGNALS_OLD_INBOX = "";
65366
+ var SIGNALS_OLD_HANDLED = "";
65367
+ var AKB_DIR = "";
65368
+ var ROOT_GITIGNORE = "";
65369
+ function boardLockName(kanban, root2) {
65370
+ const from = path14.relative(root2, kanban);
65371
+ const name = from && !from.startsWith("..") ? from : path14.basename(kanban);
65372
+ return `${name.split(path14.sep).join("-")}.lock`;
65373
+ }
65374
+ var BOARD_FLAG = "";
65375
+ function setBoard(kanban, root2, flag) {
65376
+ REPO_ROOT = path14.resolve(root2);
65377
+ KANBAN = path14.resolve(kanban);
65378
+ BOARD_FLAG = flag;
65379
+ TODO = path14.join(KANBAN, "todo");
65380
+ ARCHIVE = path14.join(KANBAN, ".archive");
65381
+ ARCHIVE_MD = path14.join(KANBAN, "archive.md");
65382
+ README = path14.join(TODO, "README.md");
65383
+ MODULES_MD = path14.join(KANBAN, "modules.md");
65384
+ CONFIG = path14.join(KANBAN, "config.md");
65385
+ KANBAN_GITIGNORE = path14.join(KANBAN, ".gitignore");
65386
+ RELEASES = path14.join(KANBAN, "releases.md");
65387
+ RELEASE_SUMMARIES = path14.join(KANBAN, ".release-summaries");
65388
+ AGENTS = path14.join(KANBAN, "agents");
65389
+ STUDIOS = path14.join(KANBAN, "studios");
65390
+ MEMORY = path14.join(KANBAN, "memory");
65391
+ AGENT_MEMORY = path14.join(MEMORY, "agents");
65392
+ PROJECT_MD = path14.join(MEMORY, "project.md");
65393
+ ENV_FILE = path14.join(KANBAN, ".env");
65394
+ const machine = projectStateDir(KANBAN, REPO_ROOT);
65395
+ BOARD_STATE = machine;
65396
+ UI_CONFIG = path14.join(machine, UI_CONFIG_FILE);
65397
+ ASSETS = path14.join(machine, ASSETS_FOLDER);
65398
+ SESSIONS = path14.join(machine, SESSIONS_FILE);
65399
+ SESSIONS_DIR = path14.join(machine, SESSIONS_FOLDER);
65400
+ SESSIONS_LOCK2 = path14.join(machine, SESSIONS_LOCK);
65401
+ INDEX_LOCK2 = path14.join(machine, INDEX_LOCK);
65402
+ DELIVERIES = path14.join(KANBAN, "deliveries");
65403
+ RULES = path14.join(KANBAN, "rules");
65404
+ PLANS = path14.join(machine, "plans");
65405
+ PLANS_ARCHIVE = path14.join(PLANS, "archive");
65406
+ TRIAGE = path14.join(KANBAN, "triage");
65407
+ SIGNALS_ARCHIVED = path14.join(TRIAGE, "archived");
65408
+ SIGNALS_DISMISSED = path14.join(TRIAGE, "dismissed");
65409
+ SIGNALS_FILES = path14.join(TRIAGE, "files");
65410
+ SIGNALS_OLD_INBOX = path14.join(TRIAGE, "inbox");
65411
+ SIGNALS_OLD_HANDLED = path14.join(TRIAGE, "handled.md");
65412
+ AKB_DIR = path14.join(REPO_ROOT, ".akb");
65413
+ ROOT_GITIGNORE = path14.join(REPO_ROOT, ".gitignore");
65414
+ LOCK = path14.join(AKB_DIR, boardLockName(KANBAN, REPO_ROOT));
65415
+ return REPO_ROOT;
65416
+ }
65417
+ function setBoardRoot(root2, named = false) {
65418
+ const project = path14.resolve(root2);
65419
+ return setBoard(path14.join(project, "docs", "kanban"), project, named ? ` --dir ${project}` : "");
65420
+ }
65421
+ setBoardRoot(process.cwd());
66300
65422
 
66301
65423
  // ../cli/src/lib/agent/worktree.ts
66302
- import { spawnSync as spawnSync4 } from "node:child_process";
65424
+ import { spawnSync as spawnSync3 } from "node:child_process";
66303
65425
  var MAX_OUTPUT = 64 * 1024 * 1024;
66304
65426
  var gitLimits = { timeoutMs: 3e4 };
66305
65427
  var GitTimeoutError = class extends Error {
66306
65428
  };
66307
65429
  function spawnGit(args2, options) {
66308
- const out = spawnSync4("git", args2, {
65430
+ const out = spawnSync3("git", args2, {
66309
65431
  ...options,
66310
65432
  encoding: "utf8",
66311
65433
  stdio: ["ignore", "pipe", "pipe"],
@@ -66343,10 +65465,10 @@ function codexExtraArgs(argv, cwd = REPO_ROOT) {
66343
65465
  }
66344
65466
  const flags = [...argv, ...extra];
66345
65467
  const workspaceWrite = flags.some((arg, i) => arg === "--full-auto" || arg === "--sandbox=workspace-write" || (arg === "--sandbox" || arg === "-s") && flags[i + 1] === "workspace-write");
66346
- if (workspaceWrite && path24.resolve(cwd) !== path24.resolve(REPO_ROOT)) {
65468
+ if (workspaceWrite && path15.resolve(cwd) !== path15.resolve(REPO_ROOT)) {
66347
65469
  for (const dir of [KANBAN, AKB_DIR]) {
66348
- const relative = path24.relative(cwd, dir);
66349
- if (relative === ".." || relative.startsWith(`..${path24.sep}`) || path24.isAbsolute(relative)) {
65470
+ const relative = path15.relative(cwd, dir);
65471
+ if (relative === ".." || relative.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative)) {
66350
65472
  extra.push("--add-dir", dir);
66351
65473
  }
66352
65474
  }
@@ -66369,7 +65491,7 @@ function envRoot(name) {
66369
65491
  }
66370
65492
  function modified(file3) {
66371
65493
  try {
66372
- return fs20.statSync(file3).mtimeMs;
65494
+ return fs11.statSync(file3).mtimeMs;
66373
65495
  } catch {
66374
65496
  return 0;
66375
65497
  }
@@ -66395,28 +65517,28 @@ function codexOnWindows() {
66395
65517
  const local = envRoot("LOCALAPPDATA");
66396
65518
  const profile = envRoot("USERPROFILE");
66397
65519
  const programs = envRoot("ProgramFiles");
66398
- const cache = local ? path24.join(local, "OpenAI", "Codex", "bin") : "";
66399
- const releases = profile ? path24.join(profile, ".codex", "packages", "standalone", "releases") : "";
66400
- const packages = programs ? path24.join(programs, "WindowsApps") : "";
65520
+ const cache = local ? path15.join(local, "OpenAI", "Codex", "bin") : "";
65521
+ const releases = profile ? path15.join(profile, ".codex", "packages", "standalone", "releases") : "";
65522
+ const packages = programs ? path15.join(programs, "WindowsApps") : "";
66401
65523
  return [
66402
65524
  // Desktop's relocated CLI cache: a folder per build hash, newest file first.
66403
- ...byNewest(folders(cache).map((name) => path24.join(cache, name, "codex.exe"))),
65525
+ ...byNewest(folders(cache).map((name) => path15.join(cache, name, "codex.exe"))),
66404
65526
  // The separate standalone launcher, at a path with nothing variable in it.
66405
- ...local ? [path24.join(local, "Programs", "OpenAI", "Codex", "bin", "codex.exe")] : [],
65527
+ ...local ? [path15.join(local, "Programs", "OpenAI", "Codex", "bin", "codex.exe")] : [],
66406
65528
  // That launcher's release payload: a folder per version and target.
66407
65529
  ...byVersion(folders(releases).filter(ourArch)).map(
66408
- (name) => path24.join(releases, name, "bin", "codex.exe")
65530
+ (name) => path15.join(releases, name, "bin", "codex.exe")
66409
65531
  ),
66410
65532
  // Desktop's own MSIX package.
66411
65533
  ...byVersion(folders(packages).filter((name) => name.startsWith("OpenAI.Codex_")).filter(ourArch)).map(
66412
- (name) => path24.join(packages, name, "app", "resources", "codex.exe")
65534
+ (name) => path15.join(packages, name, "app", "resources", "codex.exe")
66413
65535
  )
66414
65536
  ];
66415
65537
  }
66416
65538
  function codexInstalls() {
66417
65539
  const chosen = process.env.CODEX_INSTALL_DIR?.trim();
66418
65540
  return [
66419
- ...chosen ? [path24.join(chosen, "codex")] : [],
65541
+ ...chosen ? [path15.join(chosen, "codex")] : [],
66420
65542
  ...process.platform === "win32" ? codexOnWindows() : [
66421
65543
  // macOS, where Codex now lives in the merged app — `codex-cli/bin/` since 26.928…
66422
65544
  "/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex",
@@ -66462,7 +65584,7 @@ var CODEX = {
66462
65584
  systemPrompt(text2, argv) {
66463
65585
  if (namesFlag(argv, ["developer_instructions", "model_instructions_file"])) return {};
66464
65586
  try {
66465
- const config2 = fs20.readFileSync(path24.join(process.env.CODEX_HOME || home(".codex"), "config.toml"), "utf8");
65587
+ const config2 = fs11.readFileSync(path15.join(process.env.CODEX_HOME || home(".codex"), "config.toml"), "utf8");
66466
65588
  if (/^\s*(?:developer_instructions|model_instructions_file)\s*=/m.test(config2)) return {};
66467
65589
  } catch {
66468
65590
  }
@@ -66702,24 +65824,24 @@ var CURSOR = {
66702
65824
  };
66703
65825
 
66704
65826
  // ../cli/src/lib/agent/harnesses/dsh.ts
66705
- import fs21 from "node:fs";
66706
- import path25 from "node:path";
65827
+ import fs12 from "node:fs";
65828
+ import path16 from "node:path";
66707
65829
  function dshHome(argv) {
66708
65830
  const binary = argv[0];
66709
65831
  if (!binary) return void 0;
66710
- const names = process.platform === "win32" && !path25.extname(binary) ? [".exe", ".cmd"].map((ext) => binary + ext) : [binary];
66711
- const candidates = binary.includes("/") || binary.includes("\\") ? names : (process.env.PATH ?? "").split(path25.delimiter).filter(Boolean).flatMap((dir2) => names.map((name) => path25.join(dir2, name)));
65832
+ const names = process.platform === "win32" && !path16.extname(binary) ? [".exe", ".cmd"].map((ext) => binary + ext) : [binary];
65833
+ const candidates = binary.includes("/") || binary.includes("\\") ? names : (process.env.PATH ?? "").split(path16.delimiter).filter(Boolean).flatMap((dir2) => names.map((name) => path16.join(dir2, name)));
66712
65834
  let dir;
66713
65835
  try {
66714
- const found = candidates.find((candidate) => fs21.existsSync(candidate));
65836
+ const found = candidates.find((candidate) => fs12.existsSync(candidate));
66715
65837
  if (!found) return void 0;
66716
- const script = /\.cmd$/i.test(found) ? shimTarget(fs21.readFileSync(found, "utf8"), found)?.script : void 0;
66717
- dir = path25.dirname(fs21.realpathSync(script ?? found));
65838
+ const script = /\.cmd$/i.test(found) ? shimTarget(fs12.readFileSync(found, "utf8"), found)?.script : void 0;
65839
+ dir = path16.dirname(fs12.realpathSync(script ?? found));
66718
65840
  } catch {
66719
65841
  return void 0;
66720
65842
  }
66721
- for (let up = path25.dirname(dir); dir !== up; up = path25.dirname(dir)) {
66722
- if (fs21.existsSync(path25.join(dir, "package.json"))) return dir;
65843
+ for (let up = path16.dirname(dir); dir !== up; up = path16.dirname(dir)) {
65844
+ if (fs12.existsSync(path16.join(dir, "package.json"))) return dir;
66723
65845
  dir = up;
66724
65846
  }
66725
65847
  return void 0;
@@ -67306,6 +66428,960 @@ var HARNESSES = [CLAUDE_CODE, CODEX, CURSOR, OPENCODE, KIMI, DSH, ZCODE, GROK, A
67306
66428
  var DEFAULT_HARNESS = HARNESSES[0];
67307
66429
  checkHarnesses(HARNESSES);
67308
66430
 
66431
+ // ../cli/src/lib/file-memo.ts
66432
+ import fs13 from "node:fs";
66433
+ import path17 from "node:path";
66434
+ function stamp(paths) {
66435
+ const parts = [];
66436
+ const visit2 = (p) => {
66437
+ let st;
66438
+ try {
66439
+ st = fs13.statSync(p, { bigint: true });
66440
+ } catch {
66441
+ parts.push(`${p}:-`);
66442
+ return;
66443
+ }
66444
+ if (!st.isDirectory()) {
66445
+ parts.push(`${p}:${st.mtimeNs}:${st.size}`);
66446
+ return;
66447
+ }
66448
+ parts.push(`${p}/`);
66449
+ let names;
66450
+ try {
66451
+ names = fs13.readdirSync(p).sort();
66452
+ } catch {
66453
+ return;
66454
+ }
66455
+ for (const name of names) if (name !== "node_modules" && name !== ".git") visit2(path17.join(p, name));
66456
+ };
66457
+ for (const p of paths) visit2(p);
66458
+ return parts.join("\n");
66459
+ }
66460
+ function copy(v) {
66461
+ if (Array.isArray(v)) return v.map(copy);
66462
+ if (v instanceof Map) return new Map([...v].map(([k, x]) => [k, copy(x)]));
66463
+ if (v instanceof Set) return new Set([...v].map(copy));
66464
+ if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
66465
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, copy(x)]));
66466
+ }
66467
+ return v;
66468
+ }
66469
+ var perTurn = false;
66470
+ var turn = 0;
66471
+ var turnEnding = false;
66472
+ function currentTurn() {
66473
+ if (!perTurn) return ++turn;
66474
+ if (!turnEnding) {
66475
+ turnEnding = true;
66476
+ setImmediate(() => {
66477
+ turn++;
66478
+ turnEnding = false;
66479
+ }).unref();
66480
+ }
66481
+ return turn;
66482
+ }
66483
+ function memoByFiles(paths, read3) {
66484
+ let last2 = null;
66485
+ return () => {
66486
+ const now = currentTurn();
66487
+ if (last2?.turn !== now) {
66488
+ const seen = stamp(paths());
66489
+ if (last2?.stamp === seen) last2.turn = now;
66490
+ else last2 = { stamp: seen, turn: now, value: read3() };
66491
+ }
66492
+ return copy(last2.value);
66493
+ };
66494
+ }
66495
+
66496
+ // src/api.ts
66497
+ var RUNTIMES = ["claude-code", "codex", "cursor", "opencode", "kimi", "dsh", "zcode", "grok", "antigravity"];
66498
+ var TIMEOUT_MS = 2e4;
66499
+ async function send(method, route, body, signedIn, ms, type, extra = {}) {
66500
+ const headers = { accept: "application/json", ...extra };
66501
+ if (signedIn) {
66502
+ const token = await accessToken();
66503
+ if (!token.ok) {
66504
+ return token.reason === "unreachable" ? { ok: false, error: token.error } : { ok: false, error: "Sign in again.", code: "unauthenticated" };
66505
+ }
66506
+ headers.authorization = `Bearer ${token.token}`;
66507
+ }
66508
+ const raw = body instanceof Uint8Array;
66509
+ if (body !== void 0) headers["content-type"] = raw ? type ?? "application/octet-stream" : "application/json";
66510
+ try {
66511
+ const response = await fetch(`${cloudEndpoints().api}${route}`, {
66512
+ method,
66513
+ headers,
66514
+ body: body === void 0 ? void 0 : raw ? body : JSON.stringify(body),
66515
+ signal: AbortSignal.timeout(ms)
66516
+ });
66517
+ return { ok: true, value: response };
66518
+ } catch (e) {
66519
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
66520
+ }
66521
+ }
66522
+ async function answerOf(response) {
66523
+ const answer = await readCloudJson(response);
66524
+ const problem = cloudProblem(response, answer) ?? (answer === void 0 ? invalidResponse("valid JSON") : null);
66525
+ if (!problem) return { ok: true, value: answer };
66526
+ const error62 = isRecord(answer) && isRecord(answer.error) ? answer.error : null;
66527
+ return {
66528
+ ok: false,
66529
+ error: problem.message,
66530
+ code: problem.code,
66531
+ status: problem.status,
66532
+ ...typeof error62?.project === "string" ? { project: error62.project } : {}
66533
+ };
66534
+ }
66535
+ async function request(method, route, body, signedIn = true) {
66536
+ const sent = await send(method, route, body, signedIn, TIMEOUT_MS);
66537
+ return sent.ok ? answerOf(sent.value) : sent;
66538
+ }
66539
+ var FILE_TIMEOUT_MS = 10 * 6e4;
66540
+ var readRunner = () => request("GET", "/v1/runner");
66541
+ var q = encodeURIComponent;
66542
+ var listFolders = (machineId2) => request("GET", `/v1/runner/folders?machine=${q(machineId2)}`);
66543
+ var addFolder = (machineId2, name, path36, project) => request("POST", "/v1/runner/folders", { machineId: machineId2, name, path: path36, ...project ? { project } : {} });
66544
+ async function createProject(name, workspace, key) {
66545
+ const sent = await send("POST", "/v1/projects", { name, workspace }, true, TIMEOUT_MS, void 0, { "idempotency-key": key });
66546
+ return sent.ok ? answerOf(sent.value) : sent;
66547
+ }
66548
+ var removeFolder = (machineId2, project) => request("POST", `/v1/runner/folders/${q(project)}/remove`, { machineId: machineId2 });
66549
+
66550
+ // ../cli/src/lib/shared/board-conflicts.ts
66551
+ var import_yaml7 = __toESM(require_dist(), 1);
66552
+
66553
+ // ../cli/src/lib/agent/cloud-studios.ts
66554
+ import fs17 from "node:fs";
66555
+ import path21 from "node:path";
66556
+
66557
+ // ../cli/src/lib/shared/file-limits.ts
66558
+ var BOARD_FILE_LIMIT = 10 * 1024 * 1024;
66559
+ var ASSET_FILE_LIMIT = 100 * 1024 * 1024;
66560
+
66561
+ // ../cli/src/lib/shared/board-files.ts
66562
+ var ROOTS = ["todo/", ".archive/", "memory/", "studios/", "triage/", "assets/", "rules/"];
66563
+ var SETTINGS = ["modules.md", "config.md"];
66564
+ var isSettingsPath = (path36) => SETTINGS.includes(path36) || /^rules\/(?:studios\/[^/]+|proposer|project-writer|dismissal-reviewer|memory-pruner)\.md$/.test(path36);
66565
+ function isBoardPath(path36) {
66566
+ if (!path36 || path36.length > 500 || path36.startsWith("/") || path36.includes("\\") || path36.includes("\0")) return false;
66567
+ if (path36.split("/").some((part) => !part || part === "." || part === "..")) return false;
66568
+ if (path36 === "todo/README.md" || path36.split("/").includes(".sync")) return false;
66569
+ if (path36.startsWith("studios/")) return true;
66570
+ if (SETTINGS.includes(path36)) return true;
66571
+ if (path36.startsWith("rules/")) return isSettingsPath(path36);
66572
+ if (path36.startsWith("assets/")) return taskOfAssets(path36) !== null;
66573
+ return ROOTS.some((root2) => path36.startsWith(root2)) && path36.endsWith(".md");
66574
+ }
66575
+ var taskOfAssets = (path36) => /^assets\/(task_[0-9a-f]+)\.json$/.exec(path36)?.[1] ?? null;
66576
+ var studioFolder = (id2) => id2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
66577
+ var studioName = (id2) => id2.startsWith("wf_builtin_") ? id2.slice("wf_builtin_".length).replace(/_/g, "-") : studioFolder(id2);
66578
+
66579
+ // ../official/pack.ts
66580
+ import crypto2 from "node:crypto";
66581
+ import fs15 from "node:fs";
66582
+ import path19 from "node:path";
66583
+ import { fileURLToPath } from "node:url";
66584
+
66585
+ // ../cli/src/lib/agent/studio-def.ts
66586
+ var import_ajv = __toESM(require_ajv(), 1);
66587
+ var import_yaml = __toESM(require_dist(), 1);
66588
+
66589
+ // ../cli/src/lib/agents/icon.ts
66590
+ var ICON_NAMES = [
66591
+ "file",
66592
+ "text",
66593
+ "article",
66594
+ "outline",
66595
+ "script",
66596
+ "prompt",
66597
+ "email",
66598
+ "image",
66599
+ "post-image",
66600
+ "social-image",
66601
+ "cover",
66602
+ "carousel",
66603
+ "carousel-outline",
66604
+ "slides",
66605
+ "wireframe",
66606
+ "screen",
66607
+ "video",
66608
+ "storyboard",
66609
+ "template",
66610
+ "shots",
66611
+ "api",
66612
+ "schema",
66613
+ "compare",
66614
+ "stack",
66615
+ "studio",
66616
+ "code",
66617
+ "checklist",
66618
+ "card",
66619
+ "plan",
66620
+ "proposal",
66621
+ "dismissed",
66622
+ "inbox",
66623
+ "notebook",
66624
+ "squeeze",
66625
+ "folder",
66626
+ "reply",
66627
+ "feedback",
66628
+ "software",
66629
+ "product-video",
66630
+ "social-post",
66631
+ "blog",
66632
+ "deck",
66633
+ "video-clone",
66634
+ "studio-kit"
66635
+ ];
66636
+ var ICON_COLORS = ["k", "w", "c", "g", "o", "p", "s", "m", "l", "r", "y"];
66637
+
66638
+ // ../cli/src/lib/shared/preview-blocks.ts
66639
+ var PREVIEW_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
66640
+ function sourcePosition(source, offset) {
66641
+ const before = source.slice(0, offset);
66642
+ return { line: before.split("\n").length, column: offset - before.lastIndexOf("\n") };
66643
+ }
66644
+ function withoutCode(source) {
66645
+ const blank = (s) => s.replace(/[^\n\r]/g, " ");
66646
+ let fence;
66647
+ let indented = false, afterBlank = true, inList = false;
66648
+ return source.split(/(?<=\n)/).map((line) => {
66649
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
66650
+ if (fence) {
66651
+ if (marker && marker[1][0] === fence.char && marker[1].length >= fence.length && !marker[2].trim()) fence = void 0;
66652
+ return blank(line);
66653
+ }
66654
+ if (marker) {
66655
+ fence = { char: marker[1][0], length: marker[1].length };
66656
+ return blank(line);
66657
+ }
66658
+ if (!line.trim()) {
66659
+ afterBlank = true;
66660
+ return line;
66661
+ }
66662
+ const hasIndent = /^(?: {4}|\t)/.test(line);
66663
+ if (!hasIndent) indented = false;
66664
+ if (/^ {0,3}(?:[-+*]|\d+[.)])\s/.test(line)) inList = true;
66665
+ else if (/^\S/.test(line)) inList = false;
66666
+ if (hasIndent && (indented || afterBlank && !inList)) {
66667
+ indented = true;
66668
+ return blank(line);
66669
+ }
66670
+ afterBlank = false;
66671
+ return line;
66672
+ }).join("").replace(/(`+)([^]*?)\1(?!`)/g, blank);
66673
+ }
66674
+ function parsePreviewBlocks(source, file3 = "STUDIO.md") {
66675
+ const blocks = [], problems = [];
66676
+ const masked = withoutCode(source);
66677
+ let open2;
66678
+ const seen = /* @__PURE__ */ new Set();
66679
+ const fail = (offset, id2, code, message, hint2) => problems.push({ file: file3, ...sourcePosition(source, offset), path: id2 ? `previews.${id2}` : "previews", code, message, hint: hint2 });
66680
+ for (const tag of masked.matchAll(/<\/?Preview\b[^>]*(?:>|$)/g)) {
66681
+ const offset = tag.index, text2 = tag[0];
66682
+ const closing = /^<\/Preview\s*>$/.test(text2);
66683
+ if (closing) {
66684
+ if (!open2) fail(offset, "", "preview-unexpected-close", "Preview has no opening tag", "Remove it or restore its opening tag.");
66685
+ else {
66686
+ const instructions = source.slice(open2.content, offset).trim();
66687
+ if (!instructions) fail(open2.start, open2.id, "preview-empty", `Preview ${open2.id} is empty`, "Describe the requested output inside the block.");
66688
+ blocks.push({ id: open2.id, instructions, start: open2.start, end: offset + text2.length });
66689
+ open2 = void 0;
66690
+ }
66691
+ continue;
66692
+ }
66693
+ const opening = /^<Preview\s+id=(?:"([^"]*)"|'([^']*)')\s*>$/.exec(text2);
66694
+ if (!opening || open2) {
66695
+ fail(offset, open2?.id ?? "", "preview-tag", "Malformed or nested Preview tag", 'Use one non-nested <Preview id="stable-id"> block with only id.');
66696
+ continue;
66697
+ }
66698
+ const id2 = opening[1] ?? opening[2];
66699
+ if (!PREVIEW_ID.test(id2) || seen.has(id2)) fail(offset, id2, "preview-id", `Invalid or repeated Preview ID ${id2}`, "Use a unique lowercase ID with digits and dashes.");
66700
+ seen.add(id2);
66701
+ open2 = { id: id2, start: offset, content: offset + text2.length };
66702
+ }
66703
+ if (open2) fail(open2.start, open2.id, "preview-unclosed", `Preview ${open2.id} is not closed`, "Add </Preview> after this block.");
66704
+ return { blocks, problems };
66705
+ }
66706
+
66707
+ // ../cli/src/lib/agent/studio-def.ts
66708
+ var STUDIO_ID = PREVIEW_ID;
66709
+ var titles = { type: "object", minProperties: 1, propertyNames: { pattern: "^[a-z]{2,3}(?:-[A-Za-z0-9]+)*$" }, additionalProperties: { type: "string", minLength: 1, pattern: "\\S" } };
66710
+ var icon = { anyOf: [
66711
+ { type: "string", enum: ICON_NAMES },
66712
+ { type: "array", minItems: 1, maxItems: 12, items: { type: "object", required: ["d"], additionalProperties: false, properties: {
66713
+ d: { type: "string", minLength: 1, pattern: "^[MmLlHhVvCcSsQqTtAaZz0-9.,\\s-]+$" },
66714
+ f: { enum: ICON_COLORS },
66715
+ o: { const: true },
66716
+ s: { enum: ICON_COLORS },
66717
+ w: { type: "number", exclusiveMinimum: 0, maximum: 3 }
66718
+ } } }
66719
+ ] };
66720
+ var STUDIO_SCHEMA = {
66721
+ type: "object",
66722
+ required: ["name"],
66723
+ additionalProperties: false,
66724
+ properties: {
66725
+ name: { type: "string", minLength: 1, pattern: "\\S" },
66726
+ names: titles,
66727
+ description: { type: "string" },
66728
+ needsArtifact: { type: "boolean" },
66729
+ icon,
66730
+ previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
66731
+ type: "object",
66732
+ additionalProperties: false,
66733
+ properties: { title: titles, description: titles, icon }
66734
+ } }
66735
+ }
66736
+ };
66737
+ var validate2 = new import_ajv.Ajv({ allErrors: true, meta: false, validateSchema: false }).compile(STUDIO_SCHEMA);
66738
+ function landSections(body, previews) {
66739
+ const blank = (text2) => text2.replace(/[^\r\n]/g, " ");
66740
+ let visible = "", at = 0;
66741
+ for (const { start, end } of previews) {
66742
+ visible += body.slice(at, start) + blank(body.slice(start, end));
66743
+ at = end;
66744
+ }
66745
+ visible += body.slice(at);
66746
+ const comments = /<!--[^]*?(?:-->|$)/g;
66747
+ const markdown = withoutCode(visible).replace(comments, blank);
66748
+ const headings = [...markdown.matchAll(/^ {0,3}#{1,2}(?=[ \t\r\n]|$)[^\r\n]*/gm)];
66749
+ return headings.flatMap((heading, index) => {
66750
+ const start = heading.index;
66751
+ const end = start + heading[0].length;
66752
+ if (!/^ {0,3}##[ \t]+Land(?:[ \t]+#+)?[ \t]*$/.test(visible.slice(start, end))) return [];
66753
+ return [{
66754
+ offset: start + heading[0].indexOf("#"),
66755
+ empty: !visible.slice(end, headings[index + 1]?.index).replace(comments, "").trim()
66756
+ }];
66757
+ });
66758
+ }
66759
+ function parseStudioFile(id2, source, from, { requirePreviewCopy = false, requireLand = false } = {}) {
66760
+ const problems = [];
66761
+ const fail = (offset, path36, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source, offset), path: path36, code, message, hint: hint2 });
66762
+ const result = () => ({ problem: problems.map((p) => `${p.file}:${p.line}:${p.column} ${p.path}: ${p.code} \u2014 ${p.message}. ${p.hint}`).join("\n"), problems });
66763
+ if (!STUDIO_ID.test(id2)) fail(0, "id", "studio-schema", `Invalid Studio ID ${id2}`, "Use lowercase letters, digits and dashes.");
66764
+ const front = /^---\r?\n([^]*?)\r?\n---(?:\r?\n|$)/.exec(source);
66765
+ if (!front) {
66766
+ fail(0, "", "yaml-syntax", "Missing YAML frontmatter", "Enclose metadata between --- lines.");
66767
+ return result();
66768
+ }
66769
+ const metaOffset = source.indexOf("\n") + 1, bodyOffset = front[0].length;
66770
+ const counter = new import_yaml.LineCounter();
66771
+ const document = (0, import_yaml.parseDocument)(front[1], { lineCounter: counter, uniqueKeys: true, strict: true });
66772
+ for (const error62 of document.errors) fail(metaOffset + (error62.pos[0] ?? 0), "", error62.code === "DUPLICATE_KEY" ? "yaml-duplicate-key" : "yaml-syntax", error62.message.split("\n")[0], "Correct the indicated YAML location.");
66773
+ if (problems.length) return result();
66774
+ let raw;
66775
+ try {
66776
+ raw = document.toJS({ maxAliasCount: 0 });
66777
+ } catch {
66778
+ fail(metaOffset, "", "yaml-syntax", "YAML aliases are not supported", "Write metadata explicitly.");
66779
+ return result();
66780
+ }
66781
+ if (!validate2(raw)) {
66782
+ for (const error62 of validate2.errors ?? []) {
66783
+ const parts = error62.instancePath.split("/").slice(1);
66784
+ const key = error62.params.additionalProperty ?? error62.params.missingProperty;
66785
+ if (key) parts.push(String(key));
66786
+ const node2 = parts.length ? document.getIn(parts, true) : document.contents;
66787
+ fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
66788
+ }
66789
+ }
66790
+ const body = source.slice(bodyOffset);
66791
+ const parsed = parsePreviewBlocks(body, from);
66792
+ problems.push(...parsed.problems.map((p) => ({ ...p, line: p.line + source.slice(0, bodyOffset).split("\n").length - 1 })));
66793
+ if (problems.length) return result();
66794
+ const map2 = raw.previews ?? {};
66795
+ for (const block of parsed.blocks) if (!Object.hasOwn(map2, block.id)) fail(bodyOffset + block.start, `previews.${block.id}`, "preview-metadata-missing", `Preview ${block.id} has no metadata entry`, "Add the ID under previews, using {} if needed.");
66796
+ for (const key of Object.keys(map2)) if (!parsed.blocks.some((b) => b.id === key)) fail(metaOffset + (document.getIn(["previews", key], true)?.range?.[0] ?? 0), `previews.${key}`, "preview-body-missing", `Preview ${key} has no body`, "Add its block or remove unused metadata.");
66797
+ if (requirePreviewCopy) for (const block of parsed.blocks) {
66798
+ const metadata = Object.hasOwn(map2, block.id) ? map2[block.id] : void 0;
66799
+ if (!metadata) continue;
66800
+ for (const field of ["title", "description"]) for (const lang of ["en", "zh"]) {
66801
+ if (metadata[field]?.[lang]) continue;
66802
+ fail(
66803
+ bodyOffset + block.start,
66804
+ `previews.${block.id}.${field}.${lang}`,
66805
+ "preview-display-missing",
66806
+ `Preview ${block.id} needs a ${lang} ${field}`,
66807
+ "Add non-blank en and zh display text in the Preview metadata."
66808
+ );
66809
+ }
66810
+ }
66811
+ if (requireLand) {
66812
+ const sections = landSections(body, parsed.blocks);
66813
+ if (!sections.length) fail(bodyOffset, "Land", "studio-land-missing", "Missing ## Land section", "Add ## Land to the Studio body and describe delivery, checks and what to record.");
66814
+ for (const [index, { offset, empty }] of sections.entries()) {
66815
+ if (index) fail(bodyOffset + offset, "Land", "studio-land-duplicate", "Repeated ## Land section", "Combine delivery instructions under one ## Land heading.");
66816
+ if (empty) fail(bodyOffset + offset, "Land", "studio-land-empty", "The ## Land section is empty", "Describe delivery, checks and what to record under ## Land.");
66817
+ }
66818
+ }
66819
+ if (problems.length) return result();
66820
+ let rules = "", at = 0;
66821
+ for (const block of parsed.blocks) {
66822
+ rules += body.slice(at, block.start);
66823
+ at = block.end;
66824
+ }
66825
+ rules += body.slice(at);
66826
+ return { def: {
66827
+ id: id2,
66828
+ name: raw.name.trim(),
66829
+ ...raw.names ? { names: raw.names } : {},
66830
+ description: raw.description ?? "",
66831
+ needsArtifact: raw.needsArtifact ?? false,
66832
+ ...raw.icon ? { icon: raw.icon } : {},
66833
+ previews: parsed.blocks.map((b) => ({ id: b.id, instructions: b.instructions, ...map2[b.id] })),
66834
+ rules: rules.trim()
66835
+ } };
66836
+ }
66837
+
66838
+ // ../cli/src/lib/agent/studio-folder.ts
66839
+ import fs14 from "node:fs";
66840
+ import path18 from "node:path";
66841
+
66842
+ // ../cli/src/lib/shared/guide-topics.ts
66843
+ var GUIDE_TOPICS = ["board", "writing", "add-task", "follow-up", "discuss-goal", "troubleshoot", "card-chat", "update-studio", "implement", "settle-background", "archive", "update-questions", "refine", "revise", "resolve", "prune-memory", "review-memory", "describe-project", "review-rejections", "reflect", "write-agent", "write-prompt", "module-map"];
66844
+
66845
+ // ../cli/src/lib/shared/studio-files.ts
66846
+ var STUDIO_FILE = "STUDIO.md";
66847
+ var MCP_FILE = "mcp.json";
66848
+ var CARD_TEMPLATE_FILE = "CARD.md";
66849
+ var VERSION_FILE = "version.json";
66850
+ var KB = 1024;
66851
+ var FILE_LIMITS = { file: 2 * KB * KB, total: 2 * KB * KB, count: 500, path: 512 };
66852
+ var officialId = (folder2) => `wf_builtin_${folder2.replace(/-/g, "_")}`;
66853
+ var hashInput = (files) => JSON.stringify(Object.entries(files).sort(([a], [b]) => a < b ? -1 : 1));
66854
+ var landsOf = (_def) => ({ lands: true });
66855
+ var SEGMENT = /^[\w.-]+$/;
66856
+ var isAboutFile = (file3) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file3) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file3);
66857
+ var bytes = (text2) => new TextEncoder().encode(text2).length;
66858
+ var isSharedFile = (file3) => {
66859
+ const parts = file3.split("/");
66860
+ return parts.length > 1 && parts[0] === "shared" && parts.slice(1).every((p) => SEGMENT.test(p) && p !== "." && p !== "..");
66861
+ };
66862
+ function folderPath(file3, top) {
66863
+ const parts = file3.split("/");
66864
+ if (parts.length < 3 || parts[0] !== top || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(parts[1])) return null;
66865
+ if (parts.slice(2).some((p) => !SEGMENT.test(p) || p === "." || p === "..")) return null;
66866
+ return [parts[1], parts.slice(2).join("/")];
66867
+ }
66868
+ function mcpProblem(text2) {
66869
+ let read3;
66870
+ try {
66871
+ read3 = JSON.parse(text2);
66872
+ } catch {
66873
+ return "is not JSON";
66874
+ }
66875
+ const servers = read3?.mcpServers;
66876
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "must hold `mcpServers`, an object of name \u2192 server";
66877
+ for (const [name, server] of Object.entries(servers)) {
66878
+ const { command, args: args2, ...rest } = server ?? {};
66879
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return `names a server \`${name}\`; use lowercase letters, digits and dashes`;
66880
+ if (typeof command !== "string" || !command) return `server \`${name}\` needs a \`command\``;
66881
+ if (args2 !== void 0 && !(Array.isArray(args2) && args2.every((a) => typeof a === "string"))) return `server \`${name}\`: \`args\` must be a list of strings`;
66882
+ if (Object.keys(rest).length) return `server \`${name}\` takes only \`command\` and \`args\``;
66883
+ }
66884
+ return null;
66885
+ }
66886
+ function formatStudioProblem({ file: file3, line, column, reason, hint: hint2 }) {
66887
+ const location = line === void 0 ? file3 : `${file3}:${line}:${column ?? 1}`;
66888
+ return `${location}: ${reason}${hint2 ? `. ${hint2}` : ""}`;
66889
+ }
66890
+ function checkStudioFiles(value, official = false, checks = {}) {
66891
+ const read3 = inspect(value, official, checks);
66892
+ const first = read3.problems[0];
66893
+ return first ? { ok: false, ...first, problems: read3.problems } : { ok: true, def: read3.def, files: read3.files };
66894
+ }
66895
+ function inspect(value, official, { allowLegacyPreviewCopy, allowLegacyLand } = {}) {
66896
+ const problems = [];
66897
+ const fail = (file3, reason, tooLarge = false) => {
66898
+ problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
66899
+ return { problems };
66900
+ };
66901
+ if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
66902
+ const files = Object.fromEntries(Object.entries(value).filter(([file3]) => file3 !== VERSION_FILE));
66903
+ const entries = Object.entries(files);
66904
+ if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
66905
+ let total = 0;
66906
+ const skills = /* @__PURE__ */ new Set();
66907
+ for (const [file3, text2] of entries) {
66908
+ if (typeof text2 !== "string" || text2.includes("\0")) {
66909
+ fail(file3, "is not a text file");
66910
+ continue;
66911
+ }
66912
+ if (file3.length > FILE_LIMITS.path) {
66913
+ fail(file3, `the path is longer than ${FILE_LIMITS.path} characters`);
66914
+ continue;
66915
+ }
66916
+ const size = bytes(text2);
66917
+ if (size > FILE_LIMITS.file) return fail(file3, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
66918
+ total += size;
66919
+ if (total > FILE_LIMITS.total) return fail("files", `are larger than ${FILE_LIMITS.total / KB / KB} MB together`, true);
66920
+ if (file3 === STUDIO_FILE || file3 === CARD_TEMPLATE_FILE) continue;
66921
+ if (official && file3 === MCP_FILE) {
66922
+ const problem = mcpProblem(text2);
66923
+ if (problem) fail(file3, problem);
66924
+ continue;
66925
+ }
66926
+ if (official && isAboutFile(file3)) continue;
66927
+ if (official && file3.startsWith("skills/")) {
66928
+ if (!folderPath(file3, "skills")) fail(file3, "is not inside skills/<name>/");
66929
+ else skills.add(file3.split("/")[1]);
66930
+ continue;
66931
+ }
66932
+ if (isSharedFile(file3)) continue;
66933
+ if (/^(?:references|scripts)\//.test(file3) && file3.split("/").every((p) => SEGMENT.test(p) && p !== "." && p !== "..")) continue;
66934
+ fail(file3, `use ${STUDIO_FILE}, ${CARD_TEMPLATE_FILE}, references/, scripts/ or shared/`);
66935
+ }
66936
+ for (const name of skills) {
66937
+ if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
66938
+ }
66939
+ const source = files[STUDIO_FILE];
66940
+ const read3 = typeof source === "string" ? parseStudioFile("studio", source, STUDIO_FILE, { requirePreviewCopy: !official && !allowLegacyPreviewCopy, requireLand: !allowLegacyLand }) : null;
66941
+ if (!read3) fail(STUDIO_FILE, "is missing");
66942
+ else if ("problem" in read3) for (const problem of read3.problems) problems.push({ ...problem, reason: problem.message });
66943
+ if (!read3 || "problem" in read3) return { problems };
66944
+ const def = read3.def;
66945
+ for (const [file3, text2] of Object.entries(files)) {
66946
+ if (typeof text2 !== "string" || !file3.endsWith(".md")) continue;
66947
+ const masked = withoutCode(text2);
66948
+ const reference = (offset, link, message) => problems.push({ file: file3, ...sourcePosition(text2, offset), path: link, code: "studio-reference", message, reason: message, hint: "Use an existing safe relative resource or a shipped AKB Guide." });
66949
+ for (const match of masked.matchAll(/!?\[[^\]]*\]\(([^\s)]+)(?:\s+[^)]*)?\)/g)) {
66950
+ const link = match[1].replace(/^<|>$/g, "");
66951
+ if (/^(?:https?:|mailto:|#)/i.test(link)) continue;
66952
+ let decoded;
66953
+ try {
66954
+ decoded = decodeURIComponent(link.split(/[?#]/)[0]);
66955
+ } catch {
66956
+ reference(match.index, link, "Invalid resource URL");
66957
+ continue;
66958
+ }
66959
+ if (/^(?:[a-z][\w+.-]*:|[/\\])|\\/i.test(decoded) || decoded.split("/").includes("..")) {
66960
+ reference(match.index, link, "Unsafe resource path");
66961
+ continue;
66962
+ }
66963
+ const target = [...file3.split("/").slice(0, -1), ...decoded.split("/").filter((p) => p !== ".")].join("/");
66964
+ if (!Object.hasOwn(files, target)) reference(match.index, link, `Missing resource ${target}`);
66965
+ }
66966
+ for (const match of text2.matchAll(/akb guide ([a-z][a-z-]*)/g)) if (!GUIDE_TOPICS.includes(match[1])) reference(match.index, match[1], `Unknown AKB Guide ${match[1]}`);
66967
+ }
66968
+ return { problems, def, files };
66969
+ }
66970
+
66971
+ // ../cli/src/lib/agent/studio-folder.ts
66972
+ var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
66973
+ function filesOf(dir, base = dir) {
66974
+ return fs14.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".")).flatMap((e) => {
66975
+ const full = path18.join(dir, e.name);
66976
+ if (e.isSymbolicLink()) throw new Error(`${full}: symbolic links are not allowed`);
66977
+ return e.isDirectory() ? filesOf(full, base) : [path18.relative(base, full).split(path18.sep).join("/")];
66978
+ });
66979
+ }
66980
+ function readStudioFile(dir, file3) {
66981
+ const full = path18.join(dir, file3);
66982
+ return isAboutFile(file3) && !file3.endsWith(".md") ? `data:${MIME[path18.extname(file3)]};base64,${fs14.readFileSync(full).toString("base64")}` : fs14.readFileSync(full, "utf8");
66983
+ }
66984
+ var readStudioFolder = (dir) => Object.fromEntries(filesOf(dir).sort().map((f) => [f, readStudioFile(dir, f)]));
66985
+
66986
+ // ../official/pack.ts
66987
+ var OFFICIAL = path19.dirname(fileURLToPath(import.meta.url));
66988
+ var dirs = (dir) => fs15.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
66989
+ var hashOf = (files) => crypto2.createHash("sha256").update(hashInput(files)).digest("hex");
66990
+ function packOfficial(root2 = OFFICIAL, loose = false) {
66991
+ const studiosDir = path19.join(root2, "studios");
66992
+ return dirs(studiosDir).map((folder2) => {
66993
+ const files = readStudioFolder(path19.join(studiosDir, folder2));
66994
+ const parsed = parseStudioFile(folder2, files[STUDIO_FILE] ?? "", STUDIO_FILE);
66995
+ if ("problem" in parsed) throw new Error(parsed.problem);
66996
+ const def = parsed.def;
66997
+ const checked = loose ? { ok: true } : checkStudioFiles(files, true);
66998
+ if (!checked.ok) throw new Error(`official/studios/${folder2}: ${formatStudioProblem(checked)}`);
66999
+ if (!def.names?.zh && !loose) throw new Error(`official/studios/${folder2}/${STUDIO_FILE}: add its Chinese name under \`names: zh\``);
67000
+ return {
67001
+ id: officialId(folder2),
67002
+ name: def.name,
67003
+ names: { en: def.name, ...def.names },
67004
+ description: def.description,
67005
+ when: def.description,
67006
+ ...landsOf(def),
67007
+ hash: hashOf(files),
67008
+ files
67009
+ };
67010
+ });
67011
+ }
67012
+
67013
+ // ../cli/src/lib/cloud/tasks.ts
67014
+ import fs16 from "node:fs";
67015
+ import path20 from "node:path";
67016
+ var TASK_ENV = "AI4KANBAN_TASK";
67017
+ function workspaceTask() {
67018
+ const id2 = process.env[TASK_ENV];
67019
+ return id2 && id2.trim() ? id2.trim() : null;
67020
+ }
67021
+ function runnerProject(board) {
67022
+ if (path20.basename(board) !== "kanban" || path20.basename(path20.dirname(board)) !== ".akb") return null;
67023
+ const linked = linkedProject(board, path20.dirname(path20.dirname(board)));
67024
+ return linked.ok ? linked.value : null;
67025
+ }
67026
+ function linkedProject(board, root2) {
67027
+ const file3 = path20.join(root2, ".akb", "base.json");
67028
+ if (!fs16.existsSync(file3)) return { ok: true, value: null };
67029
+ try {
67030
+ const base = JSON.parse(fs16.readFileSync(file3, "utf8"));
67031
+ 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();
67032
+ const projects = new Set(Object.keys(base.files ?? {}).flatMap((p) => /^projects\/([^/]+)\//.exec(p)?.[1] ?? []));
67033
+ if (typeof base.project === "string") projects.add(base.project);
67034
+ if (projects.size !== 1) throw new Error();
67035
+ return { ok: true, value: [...projects][0] };
67036
+ } catch {
67037
+ return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
67038
+ }
67039
+ }
67040
+
67041
+ // ../cli/src/lib/agent/cloud-studios.ts
67042
+ var DEV = "AI4KANBAN_STUDIOS";
67043
+ var root = () => path21.join(machineHome(), "studios");
67044
+ var safe = (name) => name.replace(/[^\w.@-]/g, "_");
67045
+ var versionFile = (id2, version2) => path21.join(root(), "versions", `${safe(id2)}@${version2}.json`);
67046
+ var listFile = (project) => path21.join(root(), "lists", `${safe(project)}.json`);
67047
+ var pinFile = (task) => path21.join(root(), "tasks", `${safe(task)}.json`);
67048
+ function readJson(file3) {
67049
+ try {
67050
+ return JSON.parse(fs17.readFileSync(file3, "utf8"));
67051
+ } catch {
67052
+ return null;
67053
+ }
67054
+ }
67055
+ var readVersion = (id2, version2) => readJson(versionFile(id2, version2));
67056
+ var readPin = (task) => readJson(pinFile(task));
67057
+ var boardProject = () => KANBAN ? runnerProject(KANBAN) : null;
67058
+ var devFolder = () => process.env[DEV]?.trim() || "";
67059
+ var flowOf = (held2) => {
67060
+ const id2 = studioName(held2.id);
67061
+ const read3 = parseStudioFile(id2, held2.files["STUDIO.md"] ?? "", `the \`${id2}\` studio`);
67062
+ if ("problem" in read3) return null;
67063
+ return { def: read3.def, cloudId: held2.id, version: held2.version, builtIn: held2.id.startsWith("wf_builtin_"), files: held2.files };
67064
+ };
67065
+ function readFlows() {
67066
+ const dev = devFolder();
67067
+ if (dev) {
67068
+ return packOfficial(dev, true).flatMap((w) => flowOf({ id: w.id, version: 1, name: w.name, names: w.names, files: w.files }) ?? []);
67069
+ }
67070
+ const project = boardProject();
67071
+ if (!project || !readSession()) return [];
67072
+ const list3 = readJson(listFile(project))?.studios ?? [];
67073
+ const flows2 = list3.flatMap((w) => {
67074
+ const held2 = readVersion(w.id, w.version);
67075
+ return held2 ? flowOf(held2) ?? [] : [];
67076
+ });
67077
+ const task = workspaceTask();
67078
+ const pin = task ? readPin(task) : null;
67079
+ const pinned = pin && readVersion(pin.studio, pin.version);
67080
+ const mine = pinned && flowOf(pinned);
67081
+ if (!mine) return flows2;
67082
+ return [mine, ...flows2.filter((f) => f.cloudId !== mine.cloudId)];
67083
+ }
67084
+ var sources = () => {
67085
+ if (devFolder()) return [devFolder()];
67086
+ const project = boardProject();
67087
+ const task = workspaceTask();
67088
+ return [sessionFile(), ...project ? [listFile(project)] : [], ...task ? [pinFile(task)] : []];
67089
+ };
67090
+ var flows = memoByFiles(sources, readFlows);
67091
+
67092
+ // ../cli/src/lib/shared/board-conflicts.ts
67093
+ import fs18 from "node:fs";
67094
+ import path22 from "node:path";
67095
+
67096
+ // ../cli/src/lib/lock.ts
67097
+ function pidAlive(pid) {
67098
+ if (!pid) return false;
67099
+ try {
67100
+ process.kill(pid, 0);
67101
+ return true;
67102
+ } catch (e) {
67103
+ return e.code === "EPERM";
67104
+ }
67105
+ }
67106
+
67107
+ // ../cli/src/lib/shared/board-conflicts.ts
67108
+ var folder = (board) => path22.join(projectStateDir(board), "conflicts");
67109
+ var fileOf = (board, id2) => {
67110
+ if (!/^c_[a-f0-9]{32}$/.test(id2)) throw new BoardError("Unknown board conflict.", { kind: "conflict-not-found", id: id2 });
67111
+ return path22.join(folder(board), `${id2}.json`);
67112
+ };
67113
+ function read(board, id2) {
67114
+ const file3 = fileOf(board, id2);
67115
+ if (!fs18.existsSync(file3)) throw new BoardError("Unknown board conflict.", { kind: "conflict-not-found", id: id2 });
67116
+ try {
67117
+ const r = JSON.parse(fs18.readFileSync(file3, "utf8"));
67118
+ if (r.id !== id2 || !r.project || !["open", "unconfirmed", "resolved"].includes(r.state) || !Array.isArray(r.files) || !r.files.length) throw Error();
67119
+ const names = /* @__PURE__ */ new Set();
67120
+ for (const f of r.files) {
67121
+ if (!isBoardPath(f.path) || names.has(f.path) || f.remotePath !== `projects/${r.project}/${f.path}` && !(f.path.startsWith("memory/") && f.remotePath === f.path)) throw Error();
67122
+ names.add(f.path);
67123
+ if (typeof f.conflicted !== "boolean" || !f.local || !(f.local.content === null || typeof f.local.content === "string")) throw Error();
67124
+ if (f.automatic && !(f.automatic.content === null || typeof f.automatic.content === "string")) throw Error();
67125
+ for (const v of [f.base, f.remote]) if (!v || !Number.isSafeInteger(v.seq) || v.seq < 0 || !(v.content === null || typeof v.content === "string")) throw Error();
67126
+ }
67127
+ if (r.state !== "open" && (!r.draft || !Array.isArray(r.draft.writes) || r.draft.writes.length !== r.files.length || !Array.isArray(r.draft.working) || r.draft.working.length !== r.files.length)) throw Error();
67128
+ if (r.state !== "open" && (!r.draft.writes.every((w) => w && r.files.some((f) => f.remotePath === w.path) && Number.isSafeInteger(w.base_seq) && w.base_seq >= 0 && (w.content === null || typeof w.content === "string")) || new Set(r.draft.writes.map((w) => w.path)).size !== r.files.length || r.draft.working.some((c) => c !== null && typeof c !== "string") || !Array.isArray(r.draft.files) || typeof r.draft.revision !== "string")) throw Error();
67129
+ if (r.receipt && (!Number.isSafeInteger(r.receipt.head_seq) || !Array.isArray(r.receipt.files) || !r.files.every((f) => r.receipt.files.some((v) => v.path === f.remotePath && Number.isSafeInteger(v.seq) && v.seq >= 0)))) throw Error();
67130
+ if (r.state === "resolved" && !r.receipt) throw Error();
67131
+ return r;
67132
+ } catch {
67133
+ throw new BoardError(`Cannot read board conflict ${id2}. Preserve its record for recovery.`, { kind: "cloud-refused", id: id2 });
67134
+ }
67135
+ }
67136
+ function conflictRecords(board) {
67137
+ let names;
67138
+ try {
67139
+ names = fs18.readdirSync(folder(board));
67140
+ } catch (e) {
67141
+ if (e.code === "ENOENT") return [];
67142
+ throw e;
67143
+ }
67144
+ return names.filter((n) => n.endsWith(".json")).sort().map((n) => read(board, n.slice(0, -5)));
67145
+ }
67146
+ var pendingConflicts = (board) => conflictRecords(board).filter((r) => r.state !== "resolved");
67147
+
67148
+ // src/cache.ts
67149
+ import crypto3 from "node:crypto";
67150
+ import fs20 from "node:fs";
67151
+ import path24 from "node:path";
67152
+
67153
+ // src/folders.ts
67154
+ import fs19 from "node:fs";
67155
+ import os5 from "node:os";
67156
+ import path23 from "node:path";
67157
+ var projectsFile = () => path23.join(runnerHome(), "projects.json");
67158
+ function realpath(p) {
67159
+ try {
67160
+ return fs19.realpathSync(p);
67161
+ } catch {
67162
+ return null;
67163
+ }
67164
+ }
67165
+ function readGrants() {
67166
+ try {
67167
+ const held2 = JSON.parse(fs19.readFileSync(projectsFile(), "utf8"));
67168
+ if (!Array.isArray(held2.projects)) throw new Error("invalid_projects");
67169
+ return held2;
67170
+ } catch (error62) {
67171
+ if (error62.code === "ENOENT") return { projects: [] };
67172
+ throw error62;
67173
+ }
67174
+ }
67175
+ function listOf(held2) {
67176
+ const subject = readSession()?.subject;
67177
+ if (!held2.accounts) return held2.projects;
67178
+ return subject ? held2.accounts[subject] ?? [] : [];
67179
+ }
67180
+ function update2(change) {
67181
+ fs19.mkdirSync(runnerHome(), { recursive: true, mode: 448 });
67182
+ const lock = `${projectsFile()}.lock`;
67183
+ let fd;
67184
+ const until = Date.now() + 2e3;
67185
+ for (; ; ) {
67186
+ try {
67187
+ fd = fs19.openSync(lock, "wx", 384);
67188
+ fs19.writeFileSync(fd, String(process.pid));
67189
+ break;
67190
+ } catch {
67191
+ try {
67192
+ const pid = Number(fs19.readFileSync(lock, "utf8"));
67193
+ if (pid > 0) {
67194
+ try {
67195
+ process.kill(pid, 0);
67196
+ } catch {
67197
+ fs19.rmSync(lock, { force: true });
67198
+ }
67199
+ }
67200
+ } catch {
67201
+ }
67202
+ if (Date.now() > until) throw new Error("authorization_busy");
67203
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
67204
+ }
67205
+ }
67206
+ try {
67207
+ const held2 = readGrants();
67208
+ const subject = readSession()?.subject;
67209
+ const before = listOf(held2);
67210
+ const after = [...new Set(change(before))];
67211
+ if (subject) {
67212
+ if (!held2.accounts) {
67213
+ held2.accounts = { [subject]: held2.projects };
67214
+ held2.legacyOwner = subject;
67215
+ }
67216
+ held2.accounts[subject] = after;
67217
+ held2.projects = after;
67218
+ } else held2.projects = after;
67219
+ const tmp = `${projectsFile()}.${process.pid}.tmp`;
67220
+ fs19.writeFileSync(tmp, `${JSON.stringify(held2, null, 2)}
67221
+ `, { mode: 384 });
67222
+ fs19.renameSync(tmp, projectsFile());
67223
+ return before.filter((p) => !after.includes(p));
67224
+ } finally {
67225
+ fs19.closeSync(fd);
67226
+ fs19.rmSync(lock, { force: true });
67227
+ }
67228
+ }
67229
+ function adoptLegacy() {
67230
+ if (readSession() && !readGrants().accounts) update2((list3) => list3);
67231
+ }
67232
+ var allow = (dir) => {
67233
+ update2((list3) => [...list3, dir]);
67234
+ };
67235
+ var disallow = (dir) => update2((list3) => list3.filter((p) => p !== dir));
67236
+ var SYSTEM_MAC = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/etc", "/var", "/private", "/opt", "/cores", "/dev"];
67237
+ var SYSTEM_WIN = ["Windows", "Program Files", "Program Files (x86)", "ProgramData"];
67238
+ var here = () => ({ platform: process.platform, home: os5.homedir(), resolve: realpath });
67239
+ function refusal2(picked, where = here()) {
67240
+ const win = where.platform === "win32";
67241
+ const p = win ? path23.win32 : path23.posix;
67242
+ const real = where.resolve(picked);
67243
+ if (!real || !p.isAbsolute(real) || where.resolve === realpath && !fs19.statSync(real).isDirectory()) return "missing";
67244
+ const norm = (d) => {
67245
+ const n = p.normalize(d).replace(/[\\/]+$/, "") || p.sep;
67246
+ return win ? n.toLowerCase() : n;
67247
+ };
67248
+ const within = (dir, root2) => {
67249
+ const [d, r] = [norm(dir), norm(root2)];
67250
+ return d === r || d.startsWith(r.endsWith(p.sep) ? r : r + p.sep);
67251
+ };
67252
+ const forms = [picked, real];
67253
+ if (forms.some((f) => norm(f) === norm(where.home))) return "home";
67254
+ if (forms.some((f) => norm(f) === norm(p.parse(f).root)) || !win && forms.some((f) => /^\/Volumes(\/[^/]+)?\/?$/.test(f))) {
67255
+ return "disk";
67256
+ }
67257
+ if (forms.some((f) => within(where.home, f))) return "home";
67258
+ if (forms.some((f) => within(f, runnerHome()))) return "system";
67259
+ const system = win ? SYSTEM_WIN.map((s) => p.join(p.parse(real).root, s)) : SYSTEM_MAC;
67260
+ return forms.some((f) => system.some((s) => within(f, s))) ? "system" : null;
67261
+ }
67262
+
67263
+ // src/cache.ts
67264
+ var IDLE_MS2 = 7 * 24 * 60 * 6e4;
67265
+ var SWEEP_MS = 24 * 60 * 6e4;
67266
+ var akbDir = (dir) => path24.join(dir, ".akb");
67267
+ var unsentFile = (dir) => path24.join(akbDir(dir), "unsent");
67268
+ var unsent = (dir) => fs20.existsSync(unsentFile(dir));
67269
+ var holds = /* @__PURE__ */ new Map();
67270
+ var holdsDir = () => path24.join(runnerHome(), "holds");
67271
+ var holdFile = (dir) => path24.join(holdsDir(), `${crypto3.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
67272
+ function paused(dir) {
67273
+ try {
67274
+ const file3 = path24.join(projectStateDir(path24.join(akbDir(dir), "kanban")), SESSIONS_FILE);
67275
+ const held2 = JSON.parse(fs20.readFileSync(file3, "utf8"));
67276
+ return (held2.deliveries ?? []).some((d) => d.status === "active");
67277
+ } catch {
67278
+ return false;
67279
+ }
67280
+ }
67281
+ function busy(dir) {
67282
+ if (holds.has(dir)) return true;
67283
+ const prefix = path24.basename(holdFile(dir)).split(".")[0] + ".";
67284
+ try {
67285
+ return fs20.readdirSync(holdsDir()).filter((file3) => file3.startsWith(prefix)).some((file3) => {
67286
+ try {
67287
+ process.kill(Number(file3.split(".")[1]), 0);
67288
+ return true;
67289
+ } catch {
67290
+ fs20.rmSync(path24.join(holdsDir(), file3), { force: true });
67291
+ return false;
67292
+ }
67293
+ });
67294
+ } catch {
67295
+ return false;
67296
+ }
67297
+ }
67298
+ function conflicted(dir) {
67299
+ try {
67300
+ return pendingConflicts(path24.join(dir, ".akb", "kanban")).length > 0;
67301
+ } catch {
67302
+ return true;
67303
+ }
67304
+ }
67305
+ var kept2 = (dir) => busy(dir) || unsent(dir) || paused(dir) || conflicted(dir);
67306
+ function clearAkb(dir) {
67307
+ dir = realpath2(dir);
67308
+ if (kept2(dir) || fs20.existsSync(path24.join(akbDir(dir), "worktrees")) || fs20.existsSync(path24.join(akbDir(dir), "handoffs"))) return false;
67309
+ let entries;
67310
+ try {
67311
+ entries = fs20.readdirSync(akbDir(dir));
67312
+ } catch {
67313
+ return true;
67314
+ }
67315
+ for (const name of entries) fs20.rmSync(path24.join(akbDir(dir), name), { recursive: true, force: true });
67316
+ return true;
67317
+ }
67318
+ function realpath2(p) {
67319
+ try {
67320
+ return fs20.realpathSync(p);
67321
+ } catch {
67322
+ return p;
67323
+ }
67324
+ }
67325
+
67326
+ // src/kanban-skill.ts
67327
+ import { spawnSync as spawnSync4 } from "node:child_process";
67328
+ import fs21 from "node:fs";
67329
+ import path25 from "node:path";
67330
+ var SKILL_FOLDERS = [".claude/skills/kanban", ".agents/skills/kanban"];
67331
+ var MANAGED = /^<!-- ai4kanban \S+ -->$/m;
67332
+ function removeLegacyKanbanSkill(root2) {
67333
+ for (const folder2 of SKILL_FOLDERS) {
67334
+ try {
67335
+ let at = root2;
67336
+ if (!fs21.lstatSync(at, { throwIfNoEntry: false })?.isDirectory()) continue;
67337
+ let safe2 = true;
67338
+ const parts = `${folder2}/SKILL.md`.split("/");
67339
+ for (const [i, name] of parts.entries()) {
67340
+ at = path25.join(at, name);
67341
+ const stat = fs21.lstatSync(at, { throwIfNoEntry: false });
67342
+ if (!stat || stat.isSymbolicLink() || (i < parts.length - 1 ? !stat.isDirectory() : !stat.isFile())) {
67343
+ safe2 = false;
67344
+ break;
67345
+ }
67346
+ }
67347
+ if (!safe2 || !MANAGED.test(fs21.readFileSync(at, "utf8"))) continue;
67348
+ fs21.unlinkSync(at);
67349
+ const dir = path25.dirname(at);
67350
+ if (fs21.readdirSync(dir).length === 0) fs21.rmdirSync(dir);
67351
+ } catch (e) {
67352
+ process.stderr.write(`wildcrane: \u65E0\u6CD5\u6E05\u7406 ${folder2}\uFF1A${e instanceof Error ? e.message : String(e)}
67353
+ `);
67354
+ }
67355
+ }
67356
+ }
67357
+ function keepOutOfGit(dir, folders2 = SKILL_FOLDERS) {
67358
+ const git2 = (...args2) => spawnSync4("git", ["-C", dir, ...args2], { encoding: "utf8" });
67359
+ const inside = git2("rev-parse", "--git-path", "info/exclude");
67360
+ if (inside.status !== 0) return;
67361
+ const missing = [".akb/", ...folders2.map((f) => `${f}/`)].filter((p) => git2("check-ignore", "-q", p).status !== 0);
67362
+ if (!missing.length) return;
67363
+ const exclude = path25.resolve(dir, inside.stdout.trim());
67364
+ fs21.mkdirSync(path25.dirname(exclude), { recursive: true });
67365
+ const held2 = fs21.existsSync(exclude) ? fs21.readFileSync(exclude, "utf8") : "";
67366
+ fs21.writeFileSync(exclude, `${held2}${held2 && !held2.endsWith("\n") ? "\n" : ""}${missing.join("\n")}
67367
+ `);
67368
+ }
67369
+ function retireKanbanSkill(dir) {
67370
+ try {
67371
+ keepOutOfGit(dir);
67372
+ removeLegacyKanbanSkill(dir);
67373
+ } catch (e) {
67374
+ process.stderr.write(`wildcrane: ${e instanceof Error ? e.message : String(e)}
67375
+ `);
67376
+ }
67377
+ }
67378
+
67379
+ // src/runtimes.ts
67380
+ import { spawn as spawn2 } from "node:child_process";
67381
+ import fs22 from "node:fs";
67382
+ import os6 from "node:os";
67383
+ import path26 from "node:path";
67384
+
67309
67385
  // src/model-list.ts
67310
67386
  var MODEL_REFRESH_MS = 3e4;
67311
67387
  var MODEL_TIMEOUT_MS = 15e3;
@@ -67936,7 +68012,7 @@ var authCall = (path36, body) => {
67936
68012
  signal: AbortSignal.timeout(2e4)
67937
68013
  });
67938
68014
  };
67939
- var refusal2 = (status2) => ({ ok: false, error: status2 === 429 ? "too_many" : status2 === 400 || status2 === 401 || status2 === 403 ? "bad_code" : "failed" });
68015
+ var refusal3 = (status2) => ({ ok: false, error: status2 === 429 ? "too_many" : status2 === 400 || status2 === 401 || status2 === 403 ? "bad_code" : "failed" });
67940
68016
  async function sendCode(email3, lang) {
67941
68017
  try {
67942
68018
  const response = await authCall("otp", { email: email3.trim(), create_user: true, data: { lang } });
@@ -67952,7 +68028,7 @@ async function verifyCode(email3, code, generation, signal) {
67952
68028
  } catch {
67953
68029
  return { ok: false, error: "failed" };
67954
68030
  }
67955
- if (!response.ok) return refusal2(response.status);
68031
+ if (!response.ok) return refusal3(response.status);
67956
68032
  const session = sessionFrom(await response.json().catch(() => ({})));
67957
68033
  if (!session) return { ok: false, error: "failed" };
67958
68034
  if (signal?.aborted || accountGeneration() !== generation) return { ok: false, error: "failed" };
@@ -68092,7 +68168,7 @@ async function addFolder2(dir, bind, strict = false) {
68092
68168
  if (!readSession()) return { error: "signed_out" };
68093
68169
  adoptLegacy();
68094
68170
  const subject = readSession().subject;
68095
- const why = refusal(dir);
68171
+ const why = refusal2(dir);
68096
68172
  if (why) return { error: why };
68097
68173
  const real = fs27.realpathSync(dir);
68098
68174
  const found = await folderOf(real);
@@ -68121,7 +68197,7 @@ async function removeFolder2(project) {
68121
68197
  if ("error" in found) return found;
68122
68198
  const held2 = found.folders.find((f) => f.project === project);
68123
68199
  if (!held2) return { error: "not_found" };
68124
- if (kept(held2.path)) return { error: "busy" };
68200
+ if (kept2(held2.path)) return { error: "busy" };
68125
68201
  const removed = await removeFolder(machineId(), project);
68126
68202
  if (!removed.ok) return failure2(removed);
68127
68203
  if (readSession()?.subject !== subject) return { error: "signed_out" };
@@ -68187,7 +68263,7 @@ async function settingsState(context, retryTransport = false) {
68187
68263
  account,
68188
68264
  connected: runner.ok && runner.value.runner?.connected,
68189
68265
  workspaces: workspaces.value,
68190
- projects: folders2.value.folders.map((f) => ({ ...f, ...metadata(f.project), busy: kept(f.path), missing: !fs27.existsSync(f.path) })),
68266
+ projects: folders2.value.folders.map((f) => ({ ...f, ...metadata(f.project), busy: kept2(f.path), missing: !fs27.existsSync(f.path) })),
68191
68267
  elsewhere: projects.filter((p) => !p.general && !folders2.value.folders.some((f) => f.project === p.id)).map((p) => ({ project: p.id, name: p.name, ...metadata(p.id) })),
68192
68268
  ...context.project && !projects.some((p) => p.id === context.project) ? { error: "not_found" } : {}
68193
68269
  };
@@ -68217,7 +68293,7 @@ async function settingsAction(action, body, context) {
68217
68293
  const dir = body.current === true ? context.path : await pickFolder();
68218
68294
  if (readSession()?.subject !== subject) return { error: "signed_out" };
68219
68295
  if (!dir) return { cancelled: true };
68220
- const why = refusal(dir);
68296
+ const why = refusal2(dir);
68221
68297
  if (why) return { error: why };
68222
68298
  const real = fs27.realpathSync(dir);
68223
68299
  selected.set(context, { path: real, subject: readSession().subject });
@@ -68240,7 +68316,7 @@ async function settingsAction(action, body, context) {
68240
68316
  if (!project) {
68241
68317
  const name = typeof body.name === "string" ? body.name.trim() : "";
68242
68318
  if (!name || typeof body.workspace !== "string") return { error: "bad_request" };
68243
- if (refusal(dir)) return { error: "missing" };
68319
+ if (refusal2(dir)) return { error: "missing" };
68244
68320
  const spaces = await all("/v1/workspaces");
68245
68321
  if (!spaces.ok) return failure2(spaces);
68246
68322
  if (!spaces.value.some((ws) => ws.id === body.workspace && ws.role !== "viewer")) return { error: "forbidden" };