wildcrane-runner 0.6.44 → 0.6.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runner.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.44 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.46 — 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;
@@ -111406,9 +111406,9 @@ function status(line) {
111406
111406
  }
111407
111407
 
111408
111408
  // src/protocol.ts
111409
- var VERSION = true ? "0.6.44" : "0.0.0";
111410
- var AKB_VERSION = true ? "0.11.38" : "0.0.0";
111411
- var AKB_CONTRACT = true ? 9 : 0;
111409
+ var VERSION = true ? "0.6.46" : "0.0.0";
111410
+ var AKB_VERSION = true ? "0.11.40" : "0.0.0";
111411
+ var AKB_CONTRACT = true ? 11 : 0;
111412
111412
  var EXIT_REFUSED = 10;
111413
111413
  var EXIT_OUTDATED = 11;
111414
111414
  var EXIT_UPDATE = 12;
@@ -111423,8 +111423,8 @@ import path16 from "node:path";
111423
111423
  // ../cli/src/lib/agent/language.ts
111424
111424
  var LANGUAGE_ENV = "AI4KANBAN_LANGUAGE";
111425
111425
  var LANGUAGE_LINE_ENV = "AI4KANBAN_LANGUAGE_LINE";
111426
- var SYSTEM_LANGUAGE_ZH = "\u7528\u4E2D\u6587\u56DE\u590D\u3002\u7ED9\u4EFB\u52A1\u521B\u5EFA\u8005\u770B\u7684\u7528\u4E2D\u6587\uFF0C\u5DE5\u4F5C\u6D41\u7684\u6700\u7EC8\u4EA7\u7269\u6CBF\u7528\u9879\u76EE\u8BED\u8A00\u3002";
111427
- var SYSTEM_LANGUAGE_EN = "Reply in English. Write for the task creator in English; the workflow's final artifacts follow the project's language.";
111426
+ var SYSTEM_LANGUAGE_ZH = "\u7528\u4E2D\u6587\u56DE\u590D\u3002\u7ED9\u4EFB\u52A1\u521B\u5EFA\u8005\u770B\u7684\u7528\u4E2D\u6587\uFF0C\u5DE5\u4F5C\u53F0\u7684\u6700\u7EC8\u4EA7\u7269\u6CBF\u7528\u9879\u76EE\u8BED\u8A00\u3002";
111427
+ var SYSTEM_LANGUAGE_EN = "Reply in English. Write for the task creator in English; the studio's final artifacts follow the project's language.";
111428
111428
  var systemLanguages = /* @__PURE__ */ new Set([
111429
111429
  SYSTEM_LANGUAGE_ZH,
111430
111430
  SYSTEM_LANGUAGE_EN,
@@ -113053,8 +113053,8 @@ function createTail(log) {
113053
113053
  // ../cli/package.json
113054
113054
  var package_default = {
113055
113055
  name: "wildcrane",
113056
- version: "0.11.38",
113057
- akbContract: 9,
113056
+ version: "0.11.40",
113057
+ akbContract: 11,
113058
113058
  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.",
113059
113059
  keywords: [
113060
113060
  "kanban",
@@ -114085,7 +114085,7 @@ var KANBAN_GITIGNORE = "";
114085
114085
  var RELEASES = "";
114086
114086
  var RELEASE_SUMMARIES = "";
114087
114087
  var AGENTS = "";
114088
- var WORKFLOWS = "";
114088
+ var STUDIOS = "";
114089
114089
  var LEGACY_AGENTS = "";
114090
114090
  var ASSETS = "";
114091
114091
  var BOARD_STATE = "";
@@ -114134,7 +114134,7 @@ function setBoard(kanban, root2, flag) {
114134
114134
  RELEASES = path10.join(KANBAN, "releases.md");
114135
114135
  RELEASE_SUMMARIES = path10.join(KANBAN, ".release-summaries");
114136
114136
  AGENTS = path10.join(KANBAN, "agents");
114137
- WORKFLOWS = path10.join(KANBAN, "workflows");
114137
+ STUDIOS = path10.join(KANBAN, "studios");
114138
114138
  LEGACY_AGENTS = path10.join(KANBAN, "skills");
114139
114139
  MEMORY = path10.join(KANBAN, "memory");
114140
114140
  AGENT_MEMORY = path10.join(MEMORY, "agents");
@@ -115360,7 +115360,7 @@ __export(api_exports, {
115360
115360
  listFolders: () => listFolders,
115361
115361
  listJobs: () => listJobs,
115362
115362
  listMachineTasks: () => listMachineTasks,
115363
- listWorkflows: () => listWorkflows,
115363
+ listStudios: () => listStudios,
115364
115364
  markReviewed: () => markReviewed,
115365
115365
  openDiscussion: () => openDiscussion,
115366
115366
  openLog: () => openLog,
@@ -115375,10 +115375,10 @@ __export(api_exports, {
115375
115375
  readProject: () => readProject,
115376
115376
  readRejections: () => readRejections,
115377
115377
  readRunner: () => readRunner,
115378
+ readStudio: () => readStudio,
115378
115379
  readTask: () => readTask,
115379
- readTaskWorkflow: () => readTaskWorkflow,
115380
+ readTaskStudio: () => readTaskStudio,
115380
115381
  readVersion: () => readVersion,
115381
- readWorkflow: () => readWorkflow,
115382
115382
  register: () => register,
115383
115383
  release: () => release,
115384
115384
  removeFolder: () => removeFolder,
@@ -115386,8 +115386,8 @@ __export(api_exports, {
115386
115386
  request: () => request,
115387
115387
  requestAgent: () => requestAgent,
115388
115388
  saveDraft: () => saveDraft,
115389
- setGoalWorkflow: () => setGoalWorkflow,
115390
- setIdeaWorkflow: () => setGoalWorkflow,
115389
+ setGoalStudio: () => setGoalStudio,
115390
+ setIdeaStudio: () => setGoalStudio,
115391
115391
  startGoal: () => startGoal,
115392
115392
  startIdea: () => startGoal,
115393
115393
  stopTask: () => stopTask,
@@ -115412,17 +115412,17 @@ async function writeGoals(job, list) {
115412
115412
  } catch (e2) {
115413
115413
  return { error: String(e2) };
115414
115414
  }
115415
- const workflows = [];
115415
+ const studios = [];
115416
115416
  let after = null;
115417
115417
  do {
115418
115418
  const page = await list(job.discussion.workspace, after);
115419
115419
  if (!page.ok) return { error: page.error };
115420
- for (const w2 of page.value.data) workflows.push({ ...w2, id: w2.id, name: w2.names ? `${w2.names.en} / ${w2.names.zh}` : w2.name, ...w2.description ? { description: w2.description } : {} });
115420
+ for (const w2 of page.value.data) studios.push({ ...w2, id: w2.id, name: w2.names ? `${w2.names.en} / ${w2.names.zh}` : w2.name, ...w2.description ? { description: w2.description } : {} });
115421
115421
  after = page.value.next;
115422
115422
  } while (after);
115423
115423
  const file3 = goalsFileOf(job);
115424
115424
  fs10.mkdirSync(path14.dirname(file3), { recursive: true });
115425
- fs10.writeFileSync(file3, `${JSON.stringify({ workspace: job.discussion.workspace, workflows, ideas: goals }, null, 2)}
115425
+ fs10.writeFileSync(file3, `${JSON.stringify({ workspace: job.discussion.workspace, studios, ideas: goals }, null, 2)}
115426
115426
  `);
115427
115427
  return { file: file3 };
115428
115428
  }
@@ -115468,7 +115468,7 @@ var secretsSet = () => Object.fromEntries(Object.entries(readAll()).map(([id, ke
115468
115468
 
115469
115469
  // src/api.ts
115470
115470
  var RUNTIMES = ["claude-code", "codex", "cursor", "opencode", "kimi", "dsh", "zcode", "grok"];
115471
- var PROTOCOL = 17;
115471
+ var PROTOCOL = 18;
115472
115472
  var TIMEOUT_MS = 2e4;
115473
115473
  async function send(method, route, body, signedIn, ms, type, extra = {}) {
115474
115474
  const headers = { accept: "application/json", ...extra };
@@ -115548,7 +115548,7 @@ var readChat = (task) => request("GET", `/v1/tasks/${encodeURIComponent(task)}/c
115548
115548
  var readDecisions = (task, after) => request("GET", `/v1/tasks/${q(task)}/decisions?limit=100${after ? `&after=${q(after)}` : ""}`);
115549
115549
  var dispatchReview = (machineId2, project, tasks, runtime, model) => request("POST", "/v1/runner/reviews", { machineId: machineId2, project, tasks, runtime, model });
115550
115550
  var readAgents = (machineId2, project) => request("GET", `/v1/runner/agents?machine=${encodeURIComponent(machineId2)}&project=${encodeURIComponent(project)}`);
115551
- var requestAgent = (machineId2, project, agent, workflow, seen) => request("POST", "/v1/runner/jobs", { machineId: machineId2, project, agent, workflow, seen });
115551
+ var requestAgent = (machineId2, project, agent, studio, seen) => request("POST", "/v1/runner/jobs", { machineId: machineId2, project, agent, studio, seen });
115552
115552
  var targetVersion = (machineId2) => request("GET", `/v1/runner/version?machine=${encodeURIComponent(machineId2)}`, void 0, false);
115553
115553
  var q = encodeURIComponent;
115554
115554
  var listFolders = (machineId2) => request("GET", `/v1/runner/folders?machine=${q(machineId2)}`);
@@ -115569,10 +115569,10 @@ async function commitBoard(project, job, machine, files) {
115569
115569
  const answer = await sent.value.json().catch(() => null);
115570
115570
  return { ok: false, error: answer?.error?.message ?? "Cloud answered 409", code: answer?.error?.code ?? "refused", ...answer?.files ? { files: answer.files } : {} };
115571
115571
  }
115572
- var readTaskWorkflow = (task) => request("GET", `/v1/tasks/${q(task)}/workflow`);
115573
- var listWorkflows = (workspace, after) => request("GET", `/v1/workflows?workspace=${q(workspace)}&limit=100${after ? `&after=${q(after)}` : ""}`);
115572
+ var readTaskStudio = (task) => request("GET", `/v1/tasks/${q(task)}/studio`);
115573
+ var listStudios = (workspace, after) => request("GET", `/v1/studios?workspace=${q(workspace)}&limit=100${after ? `&after=${q(after)}` : ""}`);
115574
115574
  var readTask = (task) => request("GET", `/v1/tasks/${q(task)}`);
115575
- var readWorkflow = (id) => request("GET", `/v1/workflows/${q(id)}`);
115575
+ var readStudio = (id) => request("GET", `/v1/studios/${q(id)}`);
115576
115576
  var readProject = (project) => request("GET", `/v1/projects/${q(project)}`);
115577
115577
  var readArtifact = (artifact) => request("GET", `/v1/artifacts/${q(artifact)}`);
115578
115578
  var readVersion = (artifact, version) => request("GET", `/v1/artifacts/${q(artifact)}/versions/${version}`);
@@ -115609,7 +115609,7 @@ async function saveDraft(id, expectedVersion, goals) {
115609
115609
  }
115610
115610
  return { ok: false, error: answer?.error?.message ?? "Cloud answered 409", code: answer?.error?.code ?? "refused", ...answer?.discussion ? { discussion: answer.discussion } : {} };
115611
115611
  }
115612
- var setGoalWorkflow = (id, idea, workflow) => request("PATCH", `/v1/discussions/${q(id)}/${goalDiscussions.has(id) ? "goals" : "ideas"}/${q(idea)}`, { workflow });
115612
+ var setGoalStudio = (id, idea, studio) => request("PATCH", `/v1/discussions/${q(id)}/${goalDiscussions.has(id) ? "goals" : "ideas"}/${q(idea)}`, { studio });
115613
115613
  var dropGoal = (id, idea) => request("DELETE", `/v1/discussions/${q(id)}/${goalDiscussions.has(id) ? "goals" : "ideas"}/${q(idea)}`);
115614
115614
  var startGoal = (id, idea, expectedVersion, project) => request("POST", `/v1/discussions/${q(id)}/${goalDiscussions.has(id) ? "goals" : "ideas"}/${q(idea)}/start`, { expectedVersion, ...project ? { project } : {} });
115615
115615
 
@@ -116265,7 +116265,7 @@ async function askDueAgents(machineId2, now = Date.now()) {
116265
116265
  const read4 = await readAgents(machineId2, project);
116266
116266
  if (!read4.ok) continue;
116267
116267
  for (const agent of read4.value.agents.filter((a2) => agentDue(a2, now))) {
116268
- const asked = await requestAgent(machineId2, project, agent.name, agent.workflow ?? null, agent.lastSuccess);
116268
+ const asked = await requestAgent(machineId2, project, agent.name, agent.studio ?? null, agent.lastSuccess);
116269
116269
  if (!asked.ok) console.error(`runner: ${agent.name} was not started on ${project}: ${asked.error}`);
116270
116270
  else if (asked.value.job) started = true;
116271
116271
  }
@@ -116275,8 +116275,8 @@ async function askDueAgents(machineId2, now = Date.now()) {
116275
116275
 
116276
116276
  // src/akb-version.ts
116277
116277
  import { execFile } from "node:child_process";
116278
- import fs18 from "node:fs";
116279
- import path22 from "node:path";
116278
+ import fs23 from "node:fs";
116279
+ import path27 from "node:path";
116280
116280
 
116281
116281
  // src/akb.ts
116282
116282
  import { spawn as spawn3 } from "node:child_process";
@@ -116374,545 +116374,24 @@ function answerOf2(ran) {
116374
116374
  }
116375
116375
 
116376
116376
  // src/cache.ts
116377
- import crypto2 from "node:crypto";
116378
- import fs16 from "node:fs";
116379
- import path20 from "node:path";
116380
- var IDLE_MS = 7 * 24 * 60 * 6e4;
116381
- var SWEEP_MS = 24 * 60 * 6e4;
116382
- var PROJECT_ID = /^[\w-]{1,100}$/;
116383
- var cacheRoot = () => path20.join(runnerHome(), "cache");
116384
- function cacheDir(project) {
116385
- if (!PROJECT_ID.test(project)) throw new Error("This job names no project.");
116386
- return path20.join(cacheRoot(), project);
116387
- }
116388
- var akbDir = (dir) => path20.join(dir, ".akb");
116389
- var usedFile = (dir) => path20.join(akbDir(dir), "used.json");
116390
- var unsentFile = (dir) => path20.join(akbDir(dir), "unsent");
116391
- function markUsed(dir, at2 = Date.now()) {
116392
- fs16.mkdirSync(akbDir(dir), { recursive: true });
116393
- fs16.writeFileSync(usedFile(dir), `${JSON.stringify({ at: at2 })}
116394
- `);
116395
- }
116396
- function usedAt(dir) {
116397
- try {
116398
- const at2 = JSON.parse(fs16.readFileSync(usedFile(dir), "utf8")).at;
116399
- return typeof at2 === "number" ? at2 : null;
116400
- } catch {
116401
- return null;
116402
- }
116403
- }
116404
- var unsent = (dir) => fs16.existsSync(unsentFile(dir));
116405
- function markUnsent(dir, unsent2) {
116406
- if (!unsent2) return void fs16.rmSync(unsentFile(dir), { force: true });
116407
- fs16.mkdirSync(akbDir(dir), { recursive: true });
116408
- fs16.writeFileSync(unsentFile(dir), "");
116409
- }
116410
- var holds = /* @__PURE__ */ new Map();
116411
- var holdsDir = () => path20.join(runnerHome(), "holds");
116412
- var holdFile = (dir) => path20.join(holdsDir(), `${crypto2.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
116413
- function hold(dir) {
116414
- fs16.mkdirSync(holdsDir(), { recursive: true, mode: 448 });
116415
- fs16.writeFileSync(holdFile(dir), "", { mode: 384 });
116416
- holds.set(dir, (holds.get(dir) ?? 0) + 1);
116417
- let held4 = true;
116418
- return () => {
116419
- if (!held4) return;
116420
- held4 = false;
116421
- const left = holds.get(dir) - 1;
116422
- if (left) holds.set(dir, left);
116423
- else {
116424
- holds.delete(dir);
116425
- fs16.rmSync(holdFile(dir), { force: true });
116426
- }
116427
- };
116428
- }
116429
- function paused(dir) {
116430
- try {
116431
- const file3 = path20.join(projectStateDir(path20.join(akbDir(dir), "kanban")), SESSIONS_FILE);
116432
- const held4 = JSON.parse(fs16.readFileSync(file3, "utf8"));
116433
- return (held4.deliveries ?? []).some((d2) => d2.status === "active");
116434
- } catch {
116435
- return false;
116436
- }
116437
- }
116438
- function busy(dir) {
116439
- if (holds.has(dir)) return true;
116440
- const prefix = path20.basename(holdFile(dir)).split(".")[0] + ".";
116441
- try {
116442
- return fs16.readdirSync(holdsDir()).filter((file3) => file3.startsWith(prefix)).some((file3) => {
116443
- try {
116444
- process.kill(Number(file3.split(".")[1]), 0);
116445
- return true;
116446
- } catch {
116447
- fs16.rmSync(path20.join(holdsDir(), file3), { force: true });
116448
- return false;
116449
- }
116450
- });
116451
- } catch {
116452
- return false;
116453
- }
116454
- }
116455
- var kept2 = (dir) => busy(dir) || unsent(dir) || paused(dir);
116456
- function clearAkb(dir) {
116457
- dir = realpath2(dir);
116458
- if (kept2(dir) || fs16.existsSync(path20.join(akbDir(dir), "worktrees")) || fs16.existsSync(path20.join(akbDir(dir), "handoffs"))) return false;
116459
- let entries;
116460
- try {
116461
- entries = fs16.readdirSync(akbDir(dir));
116462
- } catch {
116463
- return true;
116464
- }
116465
- for (const name of entries) fs16.rmSync(path20.join(akbDir(dir), name), { recursive: true, force: true });
116466
- return true;
116467
- }
116468
- async function readAccess(machineId2) {
116469
- if (!readSession()) return null;
116470
- const [folders2, elsewhere] = await Promise.all([listFolders(machineId2), listElsewhere(machineId2)]);
116471
- if (!folders2.ok || !elsewhere.ok) return null;
116472
- return {
116473
- projects: /* @__PURE__ */ new Set([...folders2.value.folders.map((f2) => f2.project), ...elsewhere.value.projects.map((p2) => p2.project)]),
116474
- folders: new Set(folders2.value.folders.map((f2) => realpath2(f2.path)))
116475
- };
116476
- }
116477
- function realpath2(p2) {
116478
- try {
116479
- return fs16.realpathSync(p2);
116480
- } catch {
116481
- return p2;
116482
- }
116483
- }
116484
- function idle(dir, now) {
116485
- const at2 = usedAt(dir);
116486
- if (at2 === null) markUsed(dir, now);
116487
- return at2 !== null && now - at2 > IDLE_MS;
116488
- }
116489
- async function sweepCache(machineId2, now = Date.now()) {
116490
- const access = await readAccess(machineId2);
116491
- const swept = [];
116492
- let cached2 = [];
116493
- try {
116494
- cached2 = fs16.readdirSync(cacheRoot(), { withFileTypes: true });
116495
- } catch {
116496
- }
116497
- for (const e2 of cached2) {
116498
- const dir = path20.join(cacheRoot(), e2.name);
116499
- if (!e2.isDirectory() || kept2(dir) || fs16.existsSync(path20.join(dir, ".git"))) continue;
116500
- const gone = access && !access.projects.has(e2.name);
116501
- if ((idle(dir, now) || gone) && !fs16.existsSync(path20.join(akbDir(dir), "worktrees")) && !fs16.existsSync(path20.join(akbDir(dir), "handoffs"))) {
116502
- fs16.rmSync(dir, { recursive: true, force: true });
116503
- swept.push(dir);
116504
- }
116505
- }
116506
- for (const dir of allowedProjects()) {
116507
- let held4 = [];
116508
- try {
116509
- held4 = fs16.readdirSync(akbDir(dir));
116510
- } catch {
116511
- }
116512
- if (!held4.length) continue;
116513
- const gone = access && !access.folders.has(dir);
116514
- if ((idle(dir, now) || gone) && clearAkb(dir)) swept.push(dir);
116515
- }
116516
- return swept;
116517
- }
116518
- function removeLegacy() {
116519
- const home4 = runnerHome();
116520
- for (const name of ["boards", "akb-bin"]) fs16.rmSync(path20.join(home4, name), { recursive: true, force: true });
116521
- let entries = [];
116522
- try {
116523
- entries = fs16.readdirSync(home4, { withFileTypes: true });
116524
- } catch {
116525
- return;
116526
- }
116527
- for (const e2 of entries) {
116528
- const account = path20.join(home4, e2.name);
116529
- if (!e2.isDirectory() || !fs16.existsSync(path20.join(account, "unfiled"))) continue;
116530
- fs16.rmSync(path20.join(account, "unfiled"), { recursive: true, force: true });
116531
- if (!fs16.readdirSync(account).length) fs16.rmdirSync(account);
116532
- }
116533
- }
116534
-
116535
- // src/update.ts
116536
116377
  import crypto3 from "node:crypto";
116537
- import fs17 from "node:fs";
116538
- import path21 from "node:path";
116539
- import zlib from "node:zlib";
116540
- var TIMEOUT_MS2 = 6e4;
116541
- var versionsDir = () => path21.join(runnerHome(), "bin", "runner");
116542
- var versionDir = (version) => path21.join(versionsDir(), version);
116543
- var entryOf = (dir) => path21.join(dir, "dist", "runner.mjs");
116544
- var registry = () => (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
116545
- async function installPackage(pkg, version, nodeVersion = process.versions.node) {
116546
- const dir = pkg.dirOf(version);
116547
- if (fs17.existsSync(pkg.entryOf(dir))) return { ok: true, dir };
116548
- let meta;
116549
- let tarball;
116550
- try {
116551
- const answer = await fetch(`${registry()}/${pkg.name}/${encodeURIComponent(version)}`, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
116552
- if (!answer.ok) return { ok: false, why: "unreachable", detail: `registry answered ${answer.status}` };
116553
- meta = await answer.json();
116554
- const range = meta.engines?.node;
116555
- if (range && !satisfies(nodeVersion, range)) return { ok: false, why: "node", detail: range };
116556
- if (!meta.dist?.tarball) return { ok: false, why: "unreachable", detail: "no tarball" };
116557
- const download2 = await fetch(meta.dist.tarball, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
116558
- if (!download2.ok) return { ok: false, why: "unreachable", detail: `download answered ${download2.status}` };
116559
- tarball = Buffer.from(await download2.arrayBuffer());
116560
- } catch (e2) {
116561
- return { ok: false, why: "unreachable", detail: e2 instanceof Error ? e2.message : String(e2) };
116562
- }
116563
- const expected = /^sha512-(.+)$/.exec(meta.dist.integrity ?? "")?.[1];
116564
- const actual = crypto3.createHash("sha512").update(tarball).digest("base64");
116565
- if (!expected || expected !== actual) return { ok: false, why: "integrity", detail: "sha512 mismatch" };
116566
- const staging = `${dir}.${process.pid}.tmp`;
116567
- try {
116568
- fs17.rmSync(staging, { recursive: true, force: true });
116569
- extract(zlib.gunzipSync(tarball), staging);
116570
- if (!fs17.existsSync(pkg.entryOf(staging))) throw new Error(`the package carries no ${path21.relative(staging, pkg.entryOf(staging))}`);
116571
- fs17.rmSync(dir, { recursive: true, force: true });
116572
- fs17.renameSync(staging, dir);
116573
- } catch (e2) {
116574
- fs17.rmSync(staging, { recursive: true, force: true });
116575
- return { ok: false, why: "integrity", detail: e2 instanceof Error ? e2.message : String(e2) };
116576
- }
116577
- return { ok: true, dir };
116578
- }
116579
- function extract(tar, into) {
116580
- let offset = 0;
116581
- let longName = null;
116582
- while (offset + 512 <= tar.length) {
116583
- const header = tar.subarray(offset, offset + 512);
116584
- if (header.every((b2) => b2 === 0)) break;
116585
- const field = (start, length) => header.subarray(start, start + length).toString("utf8").replace(/\0.*$/s, "");
116586
- const size = parseInt(field(124, 12).trim() || "0", 8);
116587
- const type = field(156, 1) || "0";
116588
- const body = tar.subarray(offset + 512, offset + 512 + size);
116589
- offset += 512 + Math.ceil(size / 512) * 512;
116590
- if (type === "x") {
116591
- longName = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(body.toString("utf8"))?.[1] ?? null;
116592
- continue;
116593
- }
116594
- if (type === "L") {
116595
- longName = body.toString("utf8").replace(/\0.*$/s, "");
116596
- continue;
116597
- }
116598
- const prefix = field(345, 155);
116599
- const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
116600
- longName = null;
116601
- if (type !== "0" && type !== "5") continue;
116602
- const relative = name.replace(/^[^/]+\//, "");
116603
- if (!relative) continue;
116604
- const target = path21.resolve(into, relative);
116605
- if (!target.startsWith(path21.resolve(into) + path21.sep)) throw new Error(`refusing ${name}`);
116606
- if (type === "5") fs17.mkdirSync(target, { recursive: true });
116607
- else {
116608
- fs17.mkdirSync(path21.dirname(target), { recursive: true });
116609
- fs17.writeFileSync(target, body);
116610
- }
116611
- }
116612
- }
116613
- var parse = (v) => {
116614
- const m = /^v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(v.trim());
116615
- return m ? [Number(m[1]), Number(m[2]) || 0, Number(m[3]) || 0] : null;
116616
- };
116617
- function compare(a2, b2) {
116618
- const [x2, y2] = [parse(a2) ?? [0, 0, 0], parse(b2) ?? [0, 0, 0]];
116619
- for (let i = 0; i < 3; i++) if (x2[i] !== y2[i]) return x2[i] - y2[i];
116620
- const pre = (v) => /^v?\d+\.\d+\.\d+-([^+]+)/.exec(v)?.[1]?.split(".");
116621
- const ap = pre(a2), bp = pre(b2);
116622
- if (!ap || !bp) return ap ? -1 : bp ? 1 : 0;
116623
- for (let i = 0; i < Math.max(ap.length, bp.length); i++) {
116624
- const av = ap[i], bv = bp[i];
116625
- if (av === bv) continue;
116626
- if (av === void 0) return -1;
116627
- if (bv === void 0) return 1;
116628
- const an2 = /^\d+$/.test(av), bn2 = /^\d+$/.test(bv);
116629
- if (an2 && bn2) return Number(av) - Number(bv);
116630
- if (an2 !== bn2) return an2 ? -1 : 1;
116631
- return av < bv ? -1 : 1;
116632
- }
116633
- return 0;
116634
- }
116635
- function satisfies(version, range) {
116636
- return range.split("||").some((alternative) => {
116637
- const parts = alternative.trim().split(/\s+/).filter(Boolean);
116638
- return parts.length > 0 && parts.every((part) => meets(version, part));
116639
- });
116640
- }
116641
- function meets(version, comparator) {
116642
- const m = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/.exec(comparator);
116643
- const bound = m && parse(m[2]);
116644
- if (!m || !bound) return false;
116645
- const v = parse(version);
116646
- const c2 = compare(version, m[2]);
116647
- switch (m[1]) {
116648
- case ">=":
116649
- return c2 >= 0;
116650
- case ">":
116651
- return c2 > 0;
116652
- case "<=":
116653
- return c2 <= 0;
116654
- case "<":
116655
- return c2 < 0;
116656
- case "^":
116657
- return c2 >= 0 && v[0] === bound[0];
116658
- case "~":
116659
- return c2 >= 0 && v[0] === bound[0] && v[1] === bound[1];
116660
- default: {
116661
- const given = m[2].split(".").filter((p2) => /^\d+$/.test(p2)).length;
116662
- return [0, 1, 2].slice(0, given).every((i) => v[i] === bound[i]);
116663
- }
116664
- }
116665
- }
116666
-
116667
- // src/akb-version.ts
116668
- var CHECK_MS2 = 1e4;
116669
- var VERSION2 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
116670
- var stateFile = () => path22.join(akbHome(), "state.json");
116671
- var akbVersionDir = (version) => path22.join(akbHome(), version);
116672
- var entryOf2 = (dir) => path22.join(dir, "bin", "ai4kanban.mjs");
116673
- var AKB = { name: "wildcrane", dirOf: akbVersionDir, entryOf: entryOf2 };
116674
- function readAkbState() {
116675
- try {
116676
- const held4 = JSON.parse(fs18.readFileSync(stateFile(), "utf8"));
116677
- return { current: held4.current ?? null, bad: held4.bad ?? [] };
116678
- } catch {
116679
- return { current: null, bad: [] };
116680
- }
116681
- }
116682
- function writeAkbState(state) {
116683
- fs18.mkdirSync(akbHome(), { recursive: true });
116684
- const staging = `${stateFile()}.${process.pid}.tmp`;
116685
- fs18.writeFileSync(staging, `${JSON.stringify(state, null, 2)}
116686
- `);
116687
- fs18.renameSync(staging, stateFile());
116688
- }
116689
- function contractOf(dir) {
116690
- try {
116691
- return JSON.parse(fs18.readFileSync(path22.join(dir, "package.json"), "utf8")).akbContract ?? null;
116692
- } catch {
116693
- return null;
116694
- }
116695
- }
116696
- var usable = (dir) => fs18.existsSync(entryOf2(dir)) && contractOf(dir) === AKB_CONTRACT;
116697
- function currentAkb() {
116698
- const { current: current2 } = readAkbState();
116699
- if (!current2) return bundledAkb();
116700
- const dir = akbVersionDir(current2);
116701
- if (!usable(dir)) return bundledAkb();
116702
- try {
116703
- const now = /* @__PURE__ */ new Date();
116704
- fs18.utimesSync(dir, now, now);
116705
- } catch {
116706
- }
116707
- return { command: process.execPath, args: akbArgs(entryOf2(dir)), version: current2, shim: path22.join(dir, "shim") };
116708
- }
116709
- var answers2 = (dir, version) => new Promise((resolve2) => {
116710
- execFile(process.execPath, [entryOf2(dir), "--version"], { timeout: CHECK_MS2, killSignal: "SIGKILL" }, (error, stdout) => resolve2(!error && stdout.trim().split(/\s+/).at(-1) === version));
116711
- });
116712
- var wanted = null;
116713
- var fetching = false;
116714
- function useVersion(current2) {
116715
- const state = readAkbState();
116716
- if (state.current !== current2) writeAkbState({ ...state, current: current2 });
116717
- }
116718
- async function fetchVersion(version) {
116719
- const got = await installPackage(AKB, version);
116720
- if (!got.ok) return console.error(`runner: akb ${version} was not fetched: ${got.detail}`);
116721
- if (contractOf(got.dir) !== AKB_CONTRACT || !await answers2(got.dir, version)) {
116722
- console.error(`runner: akb ${version} failed its check and will not be used`);
116723
- const state = readAkbState();
116724
- return writeAkbState({ ...state, bad: [.../* @__PURE__ */ new Set([...state.bad, version])] });
116725
- }
116726
- if (wanted === version) useVersion(version);
116727
- }
116728
- async function followAkb(named2) {
116729
- if (!named2) return;
116730
- const { version } = named2;
116731
- try {
116732
- if (version !== null && !VERSION2.test(version)) return;
116733
- wanted = version;
116734
- if (version === null || version === AKB_VERSION) return useVersion(null);
116735
- const state = readAkbState();
116736
- if (fetching || state.bad.includes(version) || state.current === version && usable(akbVersionDir(version))) return;
116737
- fetching = true;
116738
- await fetchVersion(version).finally(() => fetching = false);
116739
- } catch (e2) {
116740
- console.error(`runner: the akb version was not followed: ${e2 instanceof Error ? e2.message : String(e2)}`);
116741
- }
116742
- }
116743
- function sweepAkb(now = Date.now()) {
116744
- const { current: current2 } = readAkbState();
116745
- let entries = [];
116746
- try {
116747
- entries = fs18.readdirSync(akbHome(), { withFileTypes: true });
116748
- } catch {
116749
- return;
116750
- }
116751
- for (const e2 of entries) {
116752
- if (!e2.isDirectory() || e2.name === current2 || e2.name === BUNDLED_SHIM) continue;
116753
- const dir = path22.join(akbHome(), e2.name);
116754
- if (now - fs18.statSync(dir).mtimeMs > IDLE_MS) fs18.rmSync(dir, { recursive: true, force: true });
116755
- }
116756
- }
116378
+ import fs21 from "node:fs";
116379
+ import path25 from "node:path";
116757
116380
 
116758
- // src/chats.ts
116381
+ // ../cli/src/lib/agent/cloud-studios.ts
116759
116382
  import fs20 from "node:fs";
116760
116383
  import path24 from "node:path";
116761
116384
 
116762
- // ../cli/src/lib/shared/chats.ts
116763
- var CHAT_KEEP_DAYS = 30;
116764
-
116765
- // ../cli/src/lib/agent/task-chats.ts
116766
- import fs19 from "node:fs";
116767
- import path23 from "node:path";
116768
- var TASK = /^[\w-]{1,100}$/;
116769
- var taskChatsDir = (home4 = machineHome()) => path23.join(home4, "chats");
116770
- function taskChatFile(task, home4) {
116771
- if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
116772
- return path23.join(taskChatsDir(home4), `${task}.jsonl`);
116773
- }
116774
- function readTaskChat(task, home4) {
116775
- let text3;
116776
- try {
116777
- text3 = fs19.readFileSync(taskChatFile(task, home4), "utf8");
116778
- } catch {
116779
- return [];
116780
- }
116781
- const lines = [];
116782
- for (const raw of text3.split("\n")) {
116783
- if (!raw.trim()) continue;
116784
- try {
116785
- const line = JSON.parse(raw);
116786
- if (typeof line.id === "string" && (line.role === "user" || line.role === "agent") && typeof line.text === "string") lines.push(line);
116787
- } catch {
116788
- }
116789
- }
116790
- return lines;
116791
- }
116792
-
116793
- // src/chats.ts
116794
- var DAY_MS = 24 * 60 * 6e4;
116795
- var REVIEW_EVERY_MS = DAY_MS;
116796
- var KEEP_MS2 = CHAT_KEEP_DAYS * DAY_MS;
116797
- var home3 = () => runnerHome();
116798
- var reviewedFile = () => path24.join(taskChatsDir(home3()), "reviewed.json");
116799
- function readReviewed() {
116800
- try {
116801
- const held4 = JSON.parse(fs20.readFileSync(reviewedFile(), "utf8"));
116802
- return { checkedAt: Number(held4.checkedAt) || 0, tasks: held4.tasks ?? {} };
116803
- } catch {
116804
- return { checkedAt: 0, tasks: {} };
116805
- }
116806
- }
116807
- function writeReviewed(reviewed) {
116808
- fs20.mkdirSync(path24.dirname(reviewedFile()), { recursive: true });
116809
- fs20.writeFileSync(reviewedFile(), `${JSON.stringify(reviewed, null, 2)}
116810
- `);
116811
- }
116812
- function keepChat(job, reply, at2 = Date.now()) {
116813
- if (!job.task || !job.chat || !reply?.trim()) return;
116814
- const lines = [
116815
- { id: job.chat.message, role: "user", text: job.chat.body, at: at2 },
116816
- { id: job.id, role: "agent", text: reply, at: at2, runtime: job.runtime, model: job.model ?? null }
116817
- ];
116818
- const file3 = taskChatFile(job.task, home3());
116819
- fs20.mkdirSync(path24.dirname(file3), { recursive: true });
116820
- fs20.appendFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
116821
- `).join(""));
116822
- }
116823
- function keepCloudChat(task, messages) {
116824
- const file3 = taskChatFile(task, home3());
116825
- if (!messages.length) return fs20.rmSync(file3, { force: true });
116826
- const lines = messages.map((m) => ({ id: m.id, role: m.role, text: m.body, at: Date.parse(m.created_at) || Date.now() }));
116827
- fs20.mkdirSync(path24.dirname(file3), { recursive: true });
116828
- fs20.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
116829
- `).join(""));
116830
- }
116831
- async function keepDecisions(task, read4) {
116832
- const comments = [];
116833
- let after = null;
116834
- do {
116835
- const page = await read4(task, after);
116836
- if (!page.ok) return;
116837
- for (const d2 of page.value.data) {
116838
- if (d2.comment.trim()) comments.push({ id: d2.id, role: "user", text: d2.comment, at: Date.parse(d2.created_at) || Date.now() });
116839
- }
116840
- after = page.value.next;
116841
- } while (after);
116842
- if (!comments.length) return;
116843
- const ids = new Set(comments.map((c2) => c2.id));
116844
- const lines = [...readTaskChat(task, home3()).filter((l2) => !ids.has(l2.id)), ...comments].sort((a2, b2) => a2.at - b2.at);
116845
- const file3 = taskChatFile(task, home3());
116846
- fs20.mkdirSync(path24.dirname(file3), { recursive: true });
116847
- fs20.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
116848
- `).join(""));
116849
- }
116850
- var tasksKept = () => {
116851
- try {
116852
- return fs20.readdirSync(taskChatsDir(home3())).map((n) => /^([\w-]{1,100})\.jsonl$/.exec(n)?.[1]).filter((t2) => !!t2);
116853
- } catch {
116854
- return [];
116855
- }
116856
- };
116857
- function pruneChats(now = Date.now()) {
116858
- for (const task of tasksKept()) {
116859
- const lines = readTaskChat(task, home3());
116860
- const kept4 = lines.filter((l2) => now - l2.at < KEEP_MS2);
116861
- if (kept4.length === lines.length) continue;
116862
- const file3 = taskChatFile(task, home3());
116863
- if (kept4.length) fs20.writeFileSync(file3, kept4.map((l2) => `${JSON.stringify(l2)}
116864
- `).join(""));
116865
- else fs20.rmSync(file3, { force: true });
116866
- }
116867
- }
116868
- var lastOf = (task) => readTaskChat(task, home3()).at(-1);
116869
- var reviewMarks = (tasks) => Object.fromEntries(tasks.map(({ task, archivedAt }) => {
116870
- const last2 = lastOf(task);
116871
- return [task, last2 ? { archivedAt, message: last2.id } : { archivedAt }];
116872
- }));
116873
- function markReviewed2(marks) {
116874
- const reviewed = readReviewed();
116875
- writeReviewed({ ...reviewed, tasks: { ...reviewed.tasks, ...marks } });
116876
- }
116877
- async function reviewChats(machineId2, runtimes, now = Date.now()) {
116878
- const reviewed = readReviewed();
116879
- if (now - reviewed.checkedAt < REVIEW_EVERY_MS) return;
116880
- pruneChats(now);
116881
- const owned = await listChats(machineId2);
116882
- if (!owned.ok) return;
116883
- const byProject = /* @__PURE__ */ new Map();
116884
- for (const { task, project, archivedAt } of owned.value.chats) {
116885
- const mark = reviewed.tasks[task];
116886
- const last2 = lastOf(task);
116887
- if (mark?.archivedAt === archivedAt && (!last2 || last2.id === mark.message)) continue;
116888
- byProject.set(project, [...byProject.get(project) ?? [], task]);
116889
- }
116890
- const signedIn = runtimes.find((r2) => r2.installed && r2.loggedIn !== false)?.name;
116891
- for (const [project, tasks] of [...byProject].map(([p2, t2]) => [p2, t2.slice(0, 100)])) {
116892
- const replied = tasks.flatMap((t2) => readTaskChat(t2, home3())).filter((l2) => l2.runtime).sort((a2, b2) => a2.at - b2.at).at(-1);
116893
- const runtime = replied?.runtime ?? signedIn ?? "claude-code";
116894
- const sent = await dispatchReview(machineId2, project, tasks, runtime, replied?.model ?? null);
116895
- if (!sent.ok) console.error(`runner: the chats of ${project} were not sent for review: ${sent.error}`);
116896
- }
116897
- const listed2 = new Set(owned.value.chats.map((c2) => c2.task));
116898
- const held4 = readReviewed();
116899
- writeReviewed({ checkedAt: now, tasks: Object.fromEntries(Object.entries(held4.tasks).filter(([t2]) => listed2.has(t2))) });
116900
- }
116901
-
116902
- // src/board-watch.ts
116903
- import fs31 from "node:fs";
116904
- import path35 from "node:path";
116905
-
116906
116385
  // ../cli/src/lib/shared/board-files.ts
116907
- var ROOTS = ["todo/", ".archive/", "memory/", "workflows/", "triage/", "assets/", "rules/"];
116386
+ var ROOTS = ["todo/", ".archive/", "memory/", "studios/", "triage/", "assets/", "rules/"];
116908
116387
  var SETTINGS = ["modules.md", "config.md"];
116909
- var isSettingsPath = (path51) => SETTINGS.includes(path51) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path51);
116388
+ var isSettingsPath = (path51) => SETTINGS.includes(path51) || /^rules\/(?:studios\/)?[^/]+\.md$/.test(path51);
116910
116389
  var BOARD_FILE_LIMIT = 256 * 1024;
116911
116390
  function isBoardPath(path51) {
116912
116391
  if (!path51 || path51.length > 500 || path51.startsWith("/") || path51.includes("\\") || path51.includes("\0")) return false;
116913
116392
  if (path51.split("/").some((part) => !part || part === "." || part === "..")) return false;
116914
116393
  if (path51 === "todo/README.md" || path51.split("/").includes(".sync")) return false;
116915
- if (path51.startsWith("workflows/")) return true;
116394
+ if (path51.startsWith("studios/")) return true;
116916
116395
  if (SETTINGS.includes(path51)) return true;
116917
116396
  if (path51.startsWith("rules/")) return isSettingsPath(path51);
116918
116397
  if (path51.startsWith("assets/")) return path51.endsWith(".json");
@@ -116926,9 +116405,9 @@ function numberOfCard(path51) {
116926
116405
  }
116927
116406
  var cardSlug = (task) => task.toLowerCase().replace(/_/g, "-");
116928
116407
  var assetsFile = (task) => `assets/${task}.json`;
116929
- var workflowFolder = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
116930
- var workflowName = (id) => id.startsWith("wf_builtin_") ? id.slice("wf_builtin_".length).replace(/_/g, "-") : workflowFolder(id);
116931
- var BUILDER = "wf_builtin_workflow_builder";
116408
+ var studioFolder = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
116409
+ var studioName = (id) => id.startsWith("wf_builtin_") ? id.slice("wf_builtin_".length).replace(/_/g, "-") : studioFolder(id);
116410
+ var BUILDER = "wf_builtin_studio_builder";
116932
116411
  var draftFolder = (task) => cardSlug(task);
116933
116412
  var unquote = (value) => value.trim().replace(/^(["'])(.*)\1$/, "$2");
116934
116413
  function cardFront(body) {
@@ -116951,819 +116430,217 @@ function cardFront(body) {
116951
116430
  return out;
116952
116431
  }
116953
116432
 
116954
- // ../artifact-sdk/src/builtin/compare.json
116955
- var compare_default = '{\n "name": "compare",\n "title": { "en": "Compare", "zh": "\u5BF9\u6BD4" },\n "types": ["compare"],\n "schema": {\n "type": "object",\n "required": ["a", "b"],\n "properties": { "a": { "type": "string" }, "b": { "type": "string" } }\n },\n "references": [\n { "json": "/a", "types": ["storyboard", "compare", "spritesheet", "workflow"] },\n { "json": "/b", "types": ["storyboard", "compare", "spritesheet", "workflow"] },\n { "json": "/shots", "types": ["storyboard", "compare", "spritesheet", "workflow"] }\n ]\n}\n';
116956
-
116957
- // ../artifact-sdk/src/builtin/html.json
116958
- var html_default = `{
116959
- "name": "html",
116960
- "title": { "en": "Page", "zh": "\u9875\u9762" },
116961
- "types": ["html"],
116962
- "references": [
116963
- { "text": "<[a-z][^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
116964
- { "text": "<[a-z][^<>]*?\\\\sposter\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
116965
- { "text": "<[a-z][^<>]*?\\\\ssrcset\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']", "list": "," },
116966
- { "text": "<link\\\\b[^<>]*?\\\\shref\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
116967
- { "text": "url\\\\(\\\\s*[\\"']?([^\\"')]+?)[\\"']?\\\\s*\\\\)" }
116968
- ],
116969
- "skip": ["(?<=<script\\\\b[^<>]*>)[\\\\s\\\\S]*?(?=</script\\\\s*>|$)"]
116970
- }
116971
- `;
116972
-
116973
- // ../artifact-sdk/src/builtin/image.json
116974
- var image_default = '{ "name": "image", "title": { "en": "Image", "zh": "\u56FE\u7247" }, "types": ["image"] }\n';
116975
-
116976
- // ../artifact-sdk/src/builtin/markdown.json
116977
- var markdown_default = `{
116978
- "name": "markdown",
116979
- "title": { "en": "Document", "zh": "\u6587\u6863" },
116980
- "types": ["markdown"],
116981
- "references": [
116982
- { "text": "!\\\\[[^\\\\]\\\\n]*\\\\]\\\\(\\\\s*<?([^\\\\s)>]+)>?(?:\\\\s+[\\"'][^\\"'\\\\n]*[\\"'])?\\\\s*\\\\)" },
116983
- { "text": "<img\\\\b[^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" }
116984
- ]
116985
- }
116986
- `;
116987
-
116988
- // ../artifact-sdk/src/builtin/spritesheet.json
116989
- var spritesheet_default = '{\n "name": "spritesheet",\n "title": { "en": "Sprite animation", "zh": "\u7CBE\u7075\u52A8\u753B" },\n "types": ["spritesheet"],\n "schema": {\n "type": "object",\n "required": ["frames", "meta"],\n "properties": {\n "frames": {\n "anyOf": [\n { "type": "array", "minItems": 1, "items": { "type": "object", "required": ["frame"] } },\n { "type": "object", "additionalProperties": { "type": "object", "required": ["frame"] } }\n ]\n },\n "meta": {\n "type": "object",\n "required": ["app", "image"],\n "properties": { "app": { "type": "string", "pattern": "codeandweb\\\\.com/texturepacker" }, "image": { "type": "string" } }\n }\n }\n },\n "references": [{ "json": "/meta/image" }]\n}\n';
116990
-
116991
- // ../artifact-sdk/src/builtin/storyboard.json
116992
- var storyboard_default = '{\n "name": "storyboard",\n "title": { "en": "Storyboard", "zh": "\u5206\u955C" },\n "types": ["storyboard"],\n "schema": {\n "type": "object",\n "anyOf": [{ "required": ["shots"] }, { "required": ["slides"] }],\n "properties": {\n "shots": {\n "type": "array",\n "items": {\n "type": "object",\n "properties": { "frames": { "type": "array", "items": { "type": "object", "properties": { "src": { "type": "string" } } } } }\n }\n },\n "slides": {\n "type": "array",\n "items": {\n "type": "object",\n "properties": {\n "preview": { "type": "object", "properties": { "src": { "type": "string" } } },\n "assets": { "type": "array", "items": { "type": "string" } }\n }\n }\n }\n }\n },\n "references": [\n { "json": "/shots/*/frames/*/src", "types": ["storyboard", "compare", "spritesheet", "workflow"] },\n { "json": "/slides/*/preview/src", "types": ["storyboard", "compare", "spritesheet", "workflow"] },\n { "json": "/slides/*/assets/*" }\n ]\n}\n';
116993
-
116994
- // ../artifact-sdk/src/builtin/tiled.json
116995
- var tiled_default = `{
116996
- "name": "tiled",
116997
- "title": { "en": "Tiled map", "zh": "Tiled \u5730\u56FE" },
116998
- "types": ["tiled"],
116999
- "references": [
117000
- { "text": "<tileset\\\\b[^<>]*?\\\\ssource\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']", "types": ["tiled"] },
117001
- { "text": "<image\\\\b[^<>]*?\\\\ssource\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117002
- { "text": "\\"source\\"\\\\s*:\\\\s*\\"([^\\"]+)\\"", "types": ["tiled"] },
117003
- { "text": "\\"image\\"\\\\s*:\\\\s*\\"([^\\"]+)\\"" }
117004
- ]
117005
- }
117006
- `;
117007
-
117008
- // ../artifact-sdk/src/builtin/video.json
117009
- var video_default = '{ "name": "video", "title": { "en": "Video", "zh": "\u89C6\u9891" }, "types": ["video"] }\n';
117010
-
117011
- // ../artifact-sdk/src/builtin/workflow.json
117012
- var workflow_default = '{\n "name": "workflow",\n "title": { "en": "Workflow", "zh": "\u5DE5\u4F5C\u6D41" },\n "types": ["workflow"],\n "schema": {\n "type": "object",\n "required": ["rounds", "land", "scheduled"],\n "properties": {\n "rounds": {\n "type": "array",\n "items": {\n "type": "array",\n "minItems": 1,\n "items": { "type": "object", "required": ["agent", "title"], "properties": { "agent": { "type": "string" }, "title": { "type": "object", "required": ["en"] } } }\n }\n },\n "land": { "type": "array", "items": { "type": "object", "required": ["agent", "title"] } },\n "scheduled": { "type": "array", "items": { "type": "object", "required": ["agent", "title"] } }\n }\n }\n}\n';
117013
-
117014
- // ../artifact-sdk/src/builtin/index.ts
117015
- var read = (m) => typeof m === "string" ? JSON.parse(m) : m;
117016
- var builtin_default = [html_default, image_default, video_default, markdown_default, storyboard_default, compare_default, workflow_default, tiled_default, spritesheet_default].map(read);
116433
+ // ../official/pack.ts
116434
+ import crypto2 from "node:crypto";
116435
+ import fs17 from "node:fs";
116436
+ import path21 from "node:path";
116437
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
117017
116438
 
117018
- // ../artifact-sdk/src/internal/schema.ts
117019
- var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117020
- function typeOk(type, v) {
117021
- const types = Array.isArray(type) ? type : [type];
117022
- return types.some(
117023
- (t2) => t2 === "null" ? v === null : t2 === "array" ? Array.isArray(v) : t2 === "object" ? isObj(v) : t2 === "integer" ? Number.isInteger(v) : t2 === "number" ? typeof v === "number" && Number.isFinite(v) : typeof v === t2
117024
- );
117025
- }
117026
- function schemaProblem(schema, value, at2 = "") {
117027
- if (!isObj(schema)) return null;
117028
- const s = schema;
117029
- const here2 = at2 || "/";
117030
- if (s.type !== void 0 && !typeOk(s.type, value)) return here2;
117031
- if (Array.isArray(s.enum) && !s.enum.some((e2) => JSON.stringify(e2) === JSON.stringify(value))) return here2;
117032
- if (s.const !== void 0 && JSON.stringify(s.const) !== JSON.stringify(value)) return here2;
117033
- if (Array.isArray(s.anyOf) && !s.anyOf.some((x2) => !schemaProblem(x2, value, at2))) return here2;
117034
- if (typeof value === "string") {
117035
- if (typeof s.minLength === "number" && value.length < s.minLength) return here2;
117036
- if (typeof s.maxLength === "number" && value.length > s.maxLength) return here2;
117037
- if (typeof s.pattern === "string") {
117038
- try {
117039
- if (!new RegExp(s.pattern, "u").test(value)) return here2;
117040
- } catch {
117041
- }
117042
- }
117043
- }
117044
- if (typeof value === "number") {
117045
- if (typeof s.minimum === "number" && value < s.minimum) return here2;
117046
- if (typeof s.maximum === "number" && value > s.maximum) return here2;
117047
- }
117048
- if (Array.isArray(value)) {
117049
- if (typeof s.minItems === "number" && value.length < s.minItems) return here2;
117050
- if (typeof s.maxItems === "number" && value.length > s.maxItems) return here2;
117051
- if (isObj(s.items)) {
117052
- for (let i = 0; i < value.length; i++) {
117053
- const bad = schemaProblem(s.items, value[i], `${at2}/${i}`);
117054
- if (bad) return bad;
117055
- }
116439
+ // ../cli/src/lib/agents/icon.ts
116440
+ var ICON_NAMES = [
116441
+ "file",
116442
+ "text",
116443
+ "article",
116444
+ "outline",
116445
+ "script",
116446
+ "prompt",
116447
+ "email",
116448
+ "image",
116449
+ "post-image",
116450
+ "social-image",
116451
+ "cover",
116452
+ "carousel",
116453
+ "carousel-outline",
116454
+ "slides",
116455
+ "wireframe",
116456
+ "screen",
116457
+ "video",
116458
+ "storyboard",
116459
+ "template",
116460
+ "shots",
116461
+ "api",
116462
+ "schema",
116463
+ "compare",
116464
+ "stack",
116465
+ "studio",
116466
+ "code",
116467
+ "checklist",
116468
+ "card",
116469
+ "plan",
116470
+ "proposal",
116471
+ "dismissed",
116472
+ "inbox",
116473
+ "notebook",
116474
+ "squeeze",
116475
+ "folder",
116476
+ "reply",
116477
+ "feedback",
116478
+ "software",
116479
+ "product-video",
116480
+ "social-post",
116481
+ "blog",
116482
+ "deck",
116483
+ "video-clone",
116484
+ "studio-kit"
116485
+ ];
116486
+ var ICON_COLORS = ["k", "w", "c", "g", "o", "p", "s", "m", "l", "r", "y"];
116487
+ var PATH = /^[MmLlHhVvCcSsQqTtAaZz0-9.,\s-]+$/;
116488
+ var isColor = (v) => ICON_COLORS.includes(v);
116489
+ function readIcon(raw) {
116490
+ if (raw === void 0 || raw === "") return void 0;
116491
+ if (typeof raw === "string") return ICON_NAMES.includes(raw.trim()) ? raw.trim() : { problem: `"${raw}" is not a glyph name` };
116492
+ if (!Array.isArray(raw) || !raw.length || raw.length > 12) return { problem: "the value is neither a glyph name nor a list of 1 to 12 parts" };
116493
+ const parts = [];
116494
+ for (const [i, item] of raw.entries()) {
116495
+ const at2 = `part ${i + 1}`;
116496
+ if (!item || typeof item !== "object" || Array.isArray(item)) return { problem: `${at2} is not a map of \`d\`, \`f\`, \`o\`, \`s\`, \`w\`` };
116497
+ const { d: d2, f: f2, o: o3, s, w: w2, ...extra } = item;
116498
+ if (Object.keys(extra).length) return { problem: `${at2} has \`${Object.keys(extra).join("`, `")}\`` };
116499
+ if (typeof d2 !== "string" || !PATH.test(d2)) return { problem: `${at2} has no \`d\` of SVG path commands and numbers` };
116500
+ const part = { d: d2.trim() };
116501
+ for (const [key, value] of [["f", f2], ["s", s]]) {
116502
+ if (value === void 0) continue;
116503
+ if (typeof value !== "string" || !isColor(value)) return { problem: `${at2} colours \`${key}\` with "${String(value)}"` };
116504
+ part[key] = value;
117056
116505
  }
117057
- }
117058
- if (isObj(value)) {
117059
- const props = isObj(s.properties) ? s.properties : {};
117060
- if (Array.isArray(s.required)) {
117061
- for (const k2 of s.required) if (typeof k2 === "string" && !(k2 in value)) return `${at2}/${k2}`;
116506
+ if (o3 !== void 0) {
116507
+ if (o3 !== "true") return { problem: `${at2} has \`o: ${String(o3)}\`, not \`true\`` };
116508
+ part.o = true;
117062
116509
  }
117063
- for (const [k2, v] of Object.entries(value)) {
117064
- if (k2 in props) {
117065
- const bad = schemaProblem(props[k2], v, `${at2}/${k2}`);
117066
- if (bad) return bad;
117067
- } else if (s.additionalProperties === false) return `${at2}/${k2}`;
117068
- else if (isObj(s.additionalProperties)) {
117069
- const bad = schemaProblem(s.additionalProperties, v, `${at2}/${k2}`);
117070
- if (bad) return bad;
117071
- }
116510
+ if (w2 !== void 0) {
116511
+ const width = typeof w2 === "string" ? Number(w2) : NaN;
116512
+ if (!(width > 0 && width <= 3)) return { problem: `${at2} has \`w: ${String(w2)}\`, not above 0 and up to 3` };
116513
+ part.w = width;
117072
116514
  }
116515
+ parts.push(part);
117073
116516
  }
117074
- return null;
116517
+ return parts;
117075
116518
  }
117076
116519
 
117077
- // ../artifact-sdk/src/internal/manifest.ts
117078
- var BUILTINS = builtin_default;
117079
- var manifestOf = (type) => BUILTINS.find((m) => m.types.includes(type));
117080
- function typeOf(data, types) {
117081
- for (const type of types) if (!schemaProblem(manifestOf(type)?.schema, data)) return { type };
117082
- if (types.length !== 1) return { type: null };
117083
- return { type: types[0], problem: `does not match ${types[0]} at ${schemaProblem(manifestOf(types[0])?.schema, data)}` };
117084
- }
117085
- var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117086
- var remote = (src) => !src || /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src);
117087
- function mapJson(node, keys, at2, visit) {
117088
- if (!keys.length) return typeof node === "string" && node ? visit(node, at2) : node;
117089
- const [key, ...rest] = keys;
117090
- if (Array.isArray(node)) {
117091
- if (key === "*") return node.map((x2, i2) => mapJson(x2, rest, `${at2}/${i2}`, visit));
117092
- const i = Number(key);
117093
- return Number.isInteger(i) && i in node ? node.map((x2, j2) => j2 === i ? mapJson(x2, rest, `${at2}/${j2}`, visit) : x2) : node;
116520
+ // ../cli/src/lib/yaml.ts
116521
+ function yamlScalar(s) {
116522
+ const text3 = String(s);
116523
+ if (text3 === "") return '""';
116524
+ if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(text3) || /:\s/.test(text3) || /[\n"]/.test(text3) || /^\s|\s$/.test(text3)) {
116525
+ return JSON.stringify(text3);
117094
116526
  }
117095
- if (!isObject(node)) return node;
117096
- const out = { ...node };
117097
- for (const k2 of key === "*" ? Object.keys(node) : key in node ? [key] : []) out[k2] = mapJson(node[k2], rest, `${at2}/${k2}`, visit);
117098
- return out;
116527
+ return text3;
117099
116528
  }
117100
- function mapText(text3, rule, skipped, visit) {
117101
- let out = "";
117102
- let last2 = 0;
117103
- for (const m of text3.matchAll(new RegExp(rule.text, "gid"))) {
117104
- const span = m.indices?.[1];
117105
- if (!span || m[1] === void 0 || skipped.some(([a2, b2]) => span[0] >= a2 && span[0] < b2)) continue;
117106
- const line = text3.slice(0, span[0]).split("\n").length;
117107
- const one = (src) => remote(src) ? src : visit(src, line);
117108
- const value = rule.list ? m[1].split(rule.list).map((part) => part.replace(/^(\s*)(\S+)/, (_2, space, src) => space + one(src))).join(rule.list) : one(m[1]);
117109
- out += text3.slice(last2, span[0]) + value;
117110
- last2 = span[1];
116529
+ function unquote2(v) {
116530
+ const text3 = String(v).trim();
116531
+ if (text3.startsWith('"') && text3.endsWith('"')) {
116532
+ try {
116533
+ return JSON.parse(text3);
116534
+ } catch {
116535
+ return text3.slice(1, -1);
116536
+ }
117111
116537
  }
117112
- return out + text3.slice(last2);
116538
+ if (text3.startsWith("'") && text3.endsWith("'")) return text3.slice(1, -1);
116539
+ return text3;
117113
116540
  }
117114
- function mapReferences(manifest, content, map2) {
117115
- const skipped = (text3) => (manifest?.skip ?? []).flatMap((re3) => [...text3.matchAll(new RegExp(re3, "gi"))].map((m) => [m.index, m.index + m[0].length]));
117116
- for (const rule of manifest?.references ?? []) {
117117
- const types = rule.types ?? [];
117118
- if ("json" in rule) {
117119
- if (typeof content !== "string") content = mapJson(content, rule.json.split("/").filter(Boolean), "", (src, at2) => map2(src, { src, types, text: false, at: at2 || "/" }));
117120
- } else if (typeof content === "string") {
117121
- content = mapText(content, rule, skipped(content), (src, line) => map2(src, { src, types, text: true, line }));
116541
+
116542
+ // ../cli/src/lib/agents/yaml.ts
116543
+ function stripComment(value) {
116544
+ let from = 0;
116545
+ const quote2 = value[0];
116546
+ if (quote2 === '"' || quote2 === "'") {
116547
+ let i = 1;
116548
+ while (i < value.length) {
116549
+ if (quote2 === '"' && value[i] === "\\") i += 2;
116550
+ else if (value[i] === quote2 && quote2 === "'" && value[i + 1] === "'") i += 2;
116551
+ else if (value[i] === quote2) break;
116552
+ else i++;
117122
116553
  }
116554
+ from = i + 1;
117123
116555
  }
117124
- return content;
116556
+ const hash = value.slice(from).search(/(^|[ \t])#/);
116557
+ return hash < 0 ? value : value.slice(0, from + hash).trim();
117125
116558
  }
117126
- function referencesOf(manifest, content) {
117127
- const found = [];
117128
- mapReferences(manifest, content, (src, ref) => (found.push(ref), src));
117129
- return found;
116559
+ var readLines = (text3) => text3.split("\n").map((raw) => ({ indent: raw.match(/^[ \t]*/)[0].length, text: raw.trim() })).filter((line) => line.text && !line.text.startsWith("#"));
116560
+ function parseYamlBlock(text3) {
116561
+ const [map2] = readMap(readLines(text3), 0, 0);
116562
+ return map2;
117130
116563
  }
117131
-
117132
- // ../artifact-sdk/src/internal/references.ts
117133
- var STORYBOARD = ["storyboard"];
117134
- var WORKFLOW = ["workflow"];
117135
- var ARRANGED = ["storyboard", "compare", "spritesheet", "workflow"];
117136
- var ASSET = ["spritesheet", "asset"];
117137
- var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117138
- function bodyReferences(body) {
117139
- const lines = body.replace(/<!--[^]*?-->/g, "").split(/\r?\n/);
117140
- let fence = "";
117141
- let inTag = false;
117142
- const out = [];
117143
- const visible = [];
117144
- for (const line of lines) {
117145
- const delimiter = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
117146
- if (fence) {
117147
- if (delimiter && delimiter[0] === fence[0] && delimiter.length >= fence.length) fence = "";
117148
- visible.push("");
116564
+ function readMap(lines, start, indent) {
116565
+ const out = {};
116566
+ let i = start;
116567
+ while (i < lines.length && lines[i].indent >= indent) {
116568
+ const line = lines[i];
116569
+ if (line.indent > indent) {
116570
+ i++;
117149
116571
  continue;
117150
116572
  }
117151
- if (delimiter) {
117152
- fence = delimiter;
117153
- visible.push("");
116573
+ if (line.text.startsWith("-")) break;
116574
+ const match = line.text.match(/^([^:]+):\s*(.*)$/);
116575
+ if (!match) {
116576
+ i++;
117154
116577
  continue;
117155
116578
  }
117156
- const kept4 = inTag || !/^(?: {4}|\t)/.test(line);
117157
- visible.push(kept4 ? line : "");
117158
- if (kept4 && /^ {0,3}<(?:Asset|Mockup|Compare|Storyboard|Workflow)\b/.test(line)) inTag = true;
117159
- if (line.includes("/>")) inTag = false;
117160
- }
117161
- const text3 = visible.join("\n").replace(/(`+)[^]*?\1/g, "");
117162
- const tag = /<(Asset|Mockup|Compare|Storyboard|Workflow)\b([^<>]*?)\/>/g;
117163
- const blocks = text3.matchAll(/^ {0,3}(?:<(?:Asset|Mockup|Compare|Storyboard|Workflow)\b[^<>]*?\/>[ \t]*(?:\n[ \t]*)?)+$/gm);
117164
- for (const block of blocks) {
117165
- const tags = [...block[0].matchAll(tag)];
117166
- for (const m of tags) {
117167
- const a2 = {};
117168
- for (const p2 of m[2].matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) a2[p2[1]] = p2[2] ?? p2[3];
117169
- if (m[1] === "Compare") {
117170
- if (!a2.a || !a2.b) continue;
117171
- for (const k2 of ["a", "b", "shots"]) if (a2[k2]) out.push({ src: a2[k2], types: ARRANGED });
117172
- } else if (a2.src) {
117173
- out.push({ src: a2.src, types: m[1] === "Storyboard" ? STORYBOARD : m[1] === "Workflow" ? WORKFLOW : m[1] === "Asset" ? ASSET : [] });
117174
- if (a2.variants) {
117175
- try {
117176
- const v = JSON.parse(a2.variants);
117177
- if (isObject2(v)) {
117178
- for (const src of Object.values(v)) if (typeof src === "string" && src) out.push({ src, types: m[1] === "Asset" ? ASSET : [] });
117179
- }
117180
- } catch {
117181
- }
117182
- }
117183
- }
116579
+ const key = match[1].trim();
116580
+ const inline = stripComment(match[2].trim());
116581
+ i++;
116582
+ if (inline) {
116583
+ out[key] = readScalar(inline);
116584
+ continue;
117184
116585
  }
116586
+ const [value, next] = readBlock(lines, i, indent);
116587
+ out[key] = value;
116588
+ i = next;
117185
116589
  }
117186
- for (const m of text3.replace(tag, "").matchAll(/\]\(\s*<?([^\s)>]+)>?(?:\s+["'][^]*?["'])?\s*\)/g)) out.push({ src: m[1], types: [] });
117187
- return out;
116590
+ return [out, i];
117188
116591
  }
117189
- var TYPES = {
117190
- ".png": "image/png",
117191
- ".jpg": "image/jpeg",
117192
- ".jpeg": "image/jpeg",
117193
- ".gif": "image/gif",
117194
- ".webp": "image/webp",
117195
- ".svg": "image/svg+xml",
117196
- ".mp4": "video/mp4",
117197
- ".webm": "video/webm",
117198
- ".mp3": "audio/mpeg",
117199
- ".pdf": "application/pdf",
117200
- ".html": "text/html",
117201
- ".md": "text/markdown",
117202
- ".mdx": "text/markdown",
117203
- ".mov": "video/quicktime",
117204
- ".wav": "audio/wav",
117205
- ".m4a": "audio/mp4",
117206
- ".json": "application/json",
117207
- ".txt": "text/plain",
117208
- ".otf": "font/otf",
117209
- ".ttf": "font/ttf",
117210
- ".woff": "font/woff",
117211
- ".woff2": "font/woff2",
117212
- ".css": "text/css",
117213
- ".tmx": "application/xml",
117214
- ".tmj": "application/json",
117215
- ".tsj": "application/json"
117216
- };
117217
- function kindOf2(ext) {
117218
- if (ext === ".tsx" || ext === ".html") return "html";
117219
- if (ext === ".md" || ext === ".mdx") return "markdown";
117220
- if (ext === ".tmx" || ext === ".tmj" || ext === ".tsj") return "tiled";
117221
- const type = TYPES[ext] ?? "";
117222
- if (type.startsWith("image/")) return "image";
117223
- return type.startsWith("video/") || type.startsWith("audio/") ? "video" : "asset";
116592
+ function readScalar(value) {
116593
+ const flow = value.match(/^\[(.*)\]$/);
116594
+ if (!flow) return unquote2(value);
116595
+ return flow[1].split(",").map((item) => unquote2(item.trim())).filter(Boolean);
117224
116596
  }
117225
-
117226
- // ../artifact-sdk/src/internal/collect.ts
117227
- var extOf = (file3) => /\.[^./\\]+$/.exec(file3)?.[0].toLowerCase() ?? "";
117228
- var why = (error) => error instanceof Error ? error.message : String(error);
117229
- var textKind = (ext, types) => types.find((t2) => {
117230
- const m = manifestOf(t2);
117231
- return m && !m.schema;
117232
- }) ?? kindOf2(ext);
117233
- var kindAt = (src, types) => extOf(src) === ".json" ? types.includes("asset") ? "asset" : types[0] ?? "asset" : textKind(extOf(src), types);
117234
- function collect(body, card, host) {
117235
- const nodes = /* @__PURE__ */ new Map();
117236
- const active = /* @__PURE__ */ new Set();
116597
+ function readBlock(lines, start, parentIndent) {
116598
+ if (start >= lines.length || lines[start].indent <= parentIndent) return ["", start];
116599
+ const indent = lines[start].indent;
116600
+ if (lines[start].text.startsWith("-")) return readList(lines, start, indent);
116601
+ return readMap(lines, start, indent);
116602
+ }
116603
+ function readList(lines, start, indent) {
117237
116604
  const out = [];
117238
- const visit = (src, types, owner) => {
117239
- const path51 = src.replace(/[?#].*$/, "");
117240
- let resolved;
117241
- try {
117242
- resolved = host.resolve(path51, owner);
117243
- } catch (error) {
117244
- if (owner !== card) return { key: null, error: why(error) };
117245
- if (!nodes.has(src)) {
117246
- const node2 = { key: src, file: null, kind: kindAt(path51, types), error: why(error), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
117247
- nodes.set(src, node2);
117248
- out.push(node2);
117249
- }
117250
- return { key: src, error: nodes.get(src).error };
117251
- }
117252
- if (!resolved) return { key: null };
117253
- const { key, file: file3 } = resolved;
117254
- if (active.has(key)) throw new Error(`${owner}: ${src}: \u8D44\u6E90\u4F9D\u8D56\u5FAA\u73AF`);
117255
- const json = !!file3 && extOf(file3) === ".json";
117256
- const held4 = nodes.get(key);
117257
- if (held4) {
117258
- if (owner === card) held4.aliases.add(src);
117259
- if (held4.error || !json || !types.length || held4.kind !== "asset") return { key, error: held4.error };
117260
- out.splice(out.indexOf(held4), 1);
117261
- }
117262
- const node = { key, file: file3, kind: "asset", problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: held4?.aliases ?? /* @__PURE__ */ new Set([key]) };
117263
- if (owner === card) node.aliases.add(src);
117264
- nodes.set(key, node);
117265
- active.add(key);
117266
- const child = (ref, from) => {
117267
- const found = visit(ref.src, ref.types, from);
117268
- if (found.key) node.dependencies.set(ref.src, found.key);
117269
- else if (found.error) node.problems.push({ src: ref.src, ..."line" in ref ? { line: ref.line } : {}, ..."at" in ref ? { at: ref.at } : {}, message: found.error });
117270
- node.error ??= found.error;
117271
- };
117272
- if (file3) {
117273
- if (json) {
117274
- try {
117275
- node.data = JSON.parse(host.read(file3));
117276
- const typed = typeOf(node.data, types);
117277
- node.kind = typed.type ?? "asset";
117278
- if (typed.problem) node.problems.push({ src: file3, message: `${typed.problem}: ${file3}` });
117279
- } catch {
117280
- node.problems.push({ src: file3, message: `not valid JSON: ${file3}` });
117281
- }
117282
- } else {
117283
- node.kind = textKind(extOf(file3), types);
117284
- try {
117285
- if (manifestOf(node.kind)?.references) node.data = host.read(file3);
117286
- } catch (error) {
117287
- node.problems.push({ src: file3, message: why(error) });
117288
- }
117289
- }
117290
- node.error = node.problems[0]?.message;
117291
- if (!node.error) for (const ref of referencesOf(manifestOf(node.kind), node.data)) child(ref, file3);
117292
- } else {
117293
- for (const ref of host.retained(key)) child(ref, card);
117294
- }
117295
- active.delete(key);
117296
- out.push(node);
117297
- return { key, error: node.error };
117298
- };
117299
- for (const ref of bodyReferences(body)) visit(ref.src, ref.types, card);
117300
- const sorted = [];
117301
- const done = /* @__PURE__ */ new Set();
117302
- const order = (node) => {
117303
- if (done.has(node.key)) return;
117304
- done.add(node.key);
117305
- for (const key of node.dependencies.values()) {
117306
- const child = nodes.get(key);
117307
- if (child) order(child);
116605
+ let i = start;
116606
+ while (i < lines.length && lines[i].indent === indent && lines[i].text.startsWith("-")) {
116607
+ const line = lines[i];
116608
+ const rest = line.text.replace(/^-\s*/, "");
116609
+ const keyIndent = indent + (line.text.length - rest.length);
116610
+ i++;
116611
+ if (!stripComment(rest)) {
116612
+ const [value, next2] = readBlock(lines, i, indent);
116613
+ out.push(value);
116614
+ i = next2;
116615
+ continue;
117308
116616
  }
117309
- sorted.push(node);
117310
- };
117311
- for (const node of out) order(node);
117312
- return sorted;
117313
- }
117314
-
117315
- // src/task-folder.ts
117316
- import crypto5 from "node:crypto";
117317
- import fs30 from "node:fs";
117318
- import path34 from "node:path";
117319
-
117320
- // node_modules/node-diff3/dist/diff3.mjs
117321
- function LCS(buffer1, buffer2) {
117322
- let equivalenceClasses = /* @__PURE__ */ Object.create(null);
117323
- for (let j2 = 0; j2 < buffer2.length; j2++) {
117324
- const item = buffer2[j2];
117325
- if (equivalenceClasses[item]) {
117326
- equivalenceClasses[item].push(j2);
117327
- } else {
117328
- equivalenceClasses[item] = [j2];
116617
+ const match = rest.match(/^([^:]+):\s*(.*)$/);
116618
+ if (!match || /^\[.*\]$/.test(stripComment(rest))) {
116619
+ out.push(readScalar(stripComment(rest)));
116620
+ continue;
117329
116621
  }
117330
- }
117331
- const NULLRESULT = { buffer1index: -1, buffer2index: -1, chain: null };
117332
- let candidates = [NULLRESULT];
117333
- for (let i = 0; i < buffer1.length; i++) {
117334
- const item = buffer1[i];
117335
- const buffer2indices = equivalenceClasses[item] || [];
117336
- let r2 = 0;
117337
- let c2 = candidates[0];
117338
- for (const j2 of buffer2indices) {
117339
- let s;
117340
- for (s = r2; s < candidates.length; s++) {
117341
- if (candidates[s].buffer2index < j2 && (s === candidates.length - 1 || candidates[s + 1].buffer2index > j2)) {
117342
- break;
117343
- }
117344
- }
117345
- if (s < candidates.length) {
117346
- const newCandidate = { buffer1index: i, buffer2index: j2, chain: candidates[s] };
117347
- if (r2 === candidates.length) {
117348
- candidates.push(c2);
117349
- } else {
117350
- candidates[r2] = c2;
117351
- }
117352
- r2 = s + 1;
117353
- c2 = newCandidate;
117354
- if (r2 === candidates.length) {
117355
- break;
117356
- }
117357
- }
116622
+ const item = {};
116623
+ const inline = stripComment(match[2].trim());
116624
+ if (inline) item[match[1].trim()] = unquote2(inline);
116625
+ else {
116626
+ const [value, next2] = readBlock(lines, i, keyIndent);
116627
+ item[match[1].trim()] = value;
116628
+ i = next2;
117358
116629
  }
117359
- candidates[r2] = c2;
116630
+ const [rest_, next] = readMap(lines, i, keyIndent);
116631
+ Object.assign(item, rest_);
116632
+ i = next;
116633
+ out.push(item);
117360
116634
  }
117361
- return candidates[candidates.length - 1];
116635
+ return [out, i];
117362
116636
  }
117363
- function diffIndices(buffer1, buffer2) {
117364
- const lcs = LCS(buffer1, buffer2);
117365
- let result = [];
117366
- let tail1 = buffer1.length;
117367
- let tail2 = buffer2.length;
117368
- for (let candidate = lcs; candidate !== null; candidate = candidate.chain) {
117369
- const mismatchLength1 = tail1 - candidate.buffer1index - 1;
117370
- const mismatchLength2 = tail2 - candidate.buffer2index - 1;
117371
- tail1 = candidate.buffer1index;
117372
- tail2 = candidate.buffer2index;
117373
- if (mismatchLength1 || mismatchLength2) {
117374
- result.push({
117375
- buffer1: [tail1 + 1, mismatchLength1],
117376
- buffer1Content: buffer1.slice(tail1 + 1, tail1 + 1 + mismatchLength1),
117377
- buffer2: [tail2 + 1, mismatchLength2],
117378
- buffer2Content: buffer2.slice(tail2 + 1, tail2 + 1 + mismatchLength2)
117379
- });
117380
- }
117381
- }
117382
- result.reverse();
117383
- return result;
117384
- }
117385
- function diff3MergeRegions(a2, o3, b2) {
117386
- let hunks = [];
117387
- function addHunk(h3, ab) {
117388
- hunks.push({
117389
- ab,
117390
- oStart: h3.buffer1[0],
117391
- oLength: h3.buffer1[1],
117392
- abStart: h3.buffer2[0],
117393
- abLength: h3.buffer2[1]
117394
- });
117395
- }
117396
- diffIndices(o3, a2).forEach((item) => addHunk(item, "a"));
117397
- diffIndices(o3, b2).forEach((item) => addHunk(item, "b"));
117398
- hunks.sort((x2, y2) => x2.oStart - y2.oStart);
117399
- let results = [];
117400
- let currOffset = 0;
117401
- function advanceTo(endOffset) {
117402
- if (endOffset > currOffset) {
117403
- results.push({
117404
- stable: true,
117405
- buffer: "o",
117406
- bufferStart: currOffset,
117407
- bufferLength: endOffset - currOffset,
117408
- bufferContent: o3.slice(currOffset, endOffset)
117409
- });
117410
- currOffset = endOffset;
117411
- }
117412
- }
117413
- while (hunks.length) {
117414
- let hunk = hunks.shift();
117415
- let regionStart = hunk.oStart;
117416
- let regionEnd = hunk.oStart + hunk.oLength;
117417
- let regionHunks = [hunk];
117418
- advanceTo(regionStart);
117419
- while (hunks.length) {
117420
- const nextHunk = hunks[0];
117421
- const nextHunkStart = nextHunk.oStart;
117422
- if (nextHunkStart > regionEnd)
117423
- break;
117424
- regionEnd = Math.max(regionEnd, nextHunkStart + nextHunk.oLength);
117425
- regionHunks.push(hunks.shift());
117426
- }
117427
- if (regionHunks.length === 1) {
117428
- if (hunk.abLength > 0) {
117429
- const buffer = hunk.ab === "a" ? a2 : b2;
117430
- results.push({
117431
- stable: true,
117432
- buffer: hunk.ab,
117433
- bufferStart: hunk.abStart,
117434
- bufferLength: hunk.abLength,
117435
- bufferContent: buffer.slice(hunk.abStart, hunk.abStart + hunk.abLength)
117436
- });
117437
- }
117438
- } else {
117439
- let bounds = {
117440
- a: [a2.length, -1, o3.length, -1],
117441
- b: [b2.length, -1, o3.length, -1]
117442
- };
117443
- while (regionHunks.length) {
117444
- hunk = regionHunks.shift();
117445
- const oStart = hunk.oStart;
117446
- const oEnd = oStart + hunk.oLength;
117447
- const abStart = hunk.abStart;
117448
- const abEnd = abStart + hunk.abLength;
117449
- let b22 = bounds[hunk.ab];
117450
- b22[0] = Math.min(abStart, b22[0]);
117451
- b22[1] = Math.max(abEnd, b22[1]);
117452
- b22[2] = Math.min(oStart, b22[2]);
117453
- b22[3] = Math.max(oEnd, b22[3]);
117454
- }
117455
- const aStart = bounds.a[0] + (regionStart - bounds.a[2]);
117456
- const aEnd = bounds.a[1] + (regionEnd - bounds.a[3]);
117457
- const bStart = bounds.b[0] + (regionStart - bounds.b[2]);
117458
- const bEnd = bounds.b[1] + (regionEnd - bounds.b[3]);
117459
- let result = {
117460
- stable: false,
117461
- aStart,
117462
- aLength: aEnd - aStart,
117463
- aContent: a2.slice(aStart, aEnd),
117464
- oStart: regionStart,
117465
- oLength: regionEnd - regionStart,
117466
- oContent: o3.slice(regionStart, regionEnd),
117467
- bStart,
117468
- bLength: bEnd - bStart,
117469
- bContent: b2.slice(bStart, bEnd)
117470
- };
117471
- results.push(result);
117472
- }
117473
- currOffset = regionEnd;
117474
- }
117475
- advanceTo(o3.length);
117476
- return results;
117477
- }
117478
- function diff3Merge(a2, o3, b2, options) {
117479
- let defaults = {
117480
- excludeFalseConflicts: true,
117481
- stringSeparator: /\s+/
117482
- };
117483
- options = Object.assign(defaults, options);
117484
- if (typeof a2 === "string")
117485
- a2 = a2.split(options.stringSeparator);
117486
- if (typeof o3 === "string")
117487
- o3 = o3.split(options.stringSeparator);
117488
- if (typeof b2 === "string")
117489
- b2 = b2.split(options.stringSeparator);
117490
- let results = [];
117491
- const regions = diff3MergeRegions(a2, o3, b2);
117492
- let okBuffer = [];
117493
- function flushOk() {
117494
- if (okBuffer.length) {
117495
- results.push({ ok: okBuffer });
117496
- }
117497
- okBuffer = [];
117498
- }
117499
- function isFalseConflict(a22, b22) {
117500
- if (a22.length !== b22.length)
117501
- return false;
117502
- for (let i = 0; i < a22.length; i++) {
117503
- if (a22[i] !== b22[i])
117504
- return false;
117505
- }
117506
- return true;
117507
- }
117508
- regions.forEach((region) => {
117509
- if (region.stable) {
117510
- okBuffer.push(...region.bufferContent);
117511
- } else {
117512
- if (options.excludeFalseConflicts && isFalseConflict(region.aContent, region.bContent)) {
117513
- okBuffer.push(...region.aContent);
117514
- } else {
117515
- flushOk();
117516
- results.push({
117517
- conflict: {
117518
- a: region.aContent,
117519
- aIndex: region.aStart,
117520
- o: region.oContent,
117521
- oIndex: region.oStart,
117522
- b: region.bContent,
117523
- bIndex: region.bStart
117524
- }
117525
- });
117526
- }
117527
- }
117528
- });
117529
- flushOk();
117530
- return results;
117531
- }
117532
-
117533
- // ../cli/src/lib/yaml.ts
117534
- function yamlScalar(s) {
117535
- const text3 = String(s);
117536
- if (text3 === "") return '""';
117537
- if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(text3) || /:\s/.test(text3) || /[\n"]/.test(text3) || /^\s|\s$/.test(text3)) {
117538
- return JSON.stringify(text3);
117539
- }
117540
- return text3;
117541
- }
117542
- function unquote2(v) {
117543
- const text3 = String(v).trim();
117544
- if (text3.startsWith('"') && text3.endsWith('"')) {
117545
- try {
117546
- return JSON.parse(text3);
117547
- } catch {
117548
- return text3.slice(1, -1);
117549
- }
117550
- }
117551
- if (text3.startsWith("'") && text3.endsWith("'")) return text3.slice(1, -1);
117552
- return text3;
117553
- }
117554
-
117555
- // ../cli/src/lib/shared/triage-files.ts
117556
- var ITEM = /^triage\/(?:(dismissed|archived)\/)?([^/]+)\.md$/;
117557
- function itemAt(path51) {
117558
- const m = ITEM.exec(path51);
117559
- if (!m) return null;
117560
- return { state: m[1] === "dismissed" ? "dismissed" : m[1] === "archived" ? "carded" : "open", name: m[2] };
117561
- }
117562
- function stampItem(content, fields) {
117563
- const lines = content.split("\n");
117564
- const close = lines.indexOf("---", 1);
117565
- if (close < 0) return content;
117566
- const kept4 = lines.slice(1, close).filter((line) => {
117567
- const key = /^([a-z_]+):/.exec(line);
117568
- return !key || fields[key[1]] === void 0;
117569
- });
117570
- const added = Object.entries(fields).flatMap(([k2, v]) => v === null ? [] : [`${k2}: ${yamlScalar(v)}`]);
117571
- return ["---", ...kept4, ...added, ...lines.slice(close)].join("\n");
117572
- }
117573
-
117574
- // ../cli/src/lib/agent/cloud-workflows.ts
117575
- import fs25 from "node:fs";
117576
- import path29 from "node:path";
117577
-
117578
- // ../official/pack.ts
117579
- import crypto4 from "node:crypto";
117580
- import fs22 from "node:fs";
117581
- import path26 from "node:path";
117582
- import { fileURLToPath as fileURLToPath2 } from "node:url";
117583
-
117584
- // ../cli/src/lib/agents/icon.ts
117585
- var ICON_NAMES = [
117586
- "file",
117587
- "text",
117588
- "article",
117589
- "outline",
117590
- "script",
117591
- "prompt",
117592
- "email",
117593
- "image",
117594
- "post-image",
117595
- "social-image",
117596
- "cover",
117597
- "carousel",
117598
- "carousel-outline",
117599
- "slides",
117600
- "wireframe",
117601
- "screen",
117602
- "video",
117603
- "storyboard",
117604
- "template",
117605
- "shots",
117606
- "api",
117607
- "schema",
117608
- "compare",
117609
- "stack",
117610
- "workflow",
117611
- "code",
117612
- "checklist",
117613
- "card",
117614
- "plan",
117615
- "proposal",
117616
- "dismissed",
117617
- "inbox",
117618
- "notebook",
117619
- "squeeze",
117620
- "folder",
117621
- "reply",
117622
- "feedback",
117623
- "software",
117624
- "product-video",
117625
- "social-post",
117626
- "blog",
117627
- "deck",
117628
- "video-clone",
117629
- "workflow-kit"
117630
- ];
117631
- var ICON_COLORS = ["k", "w", "c", "g", "o", "p", "s", "m", "l", "r", "y"];
117632
- var PATH = /^[MmLlHhVvCcSsQqTtAaZz0-9.,\s-]+$/;
117633
- var isColor = (v) => ICON_COLORS.includes(v);
117634
- function readIcon(raw) {
117635
- if (raw === void 0 || raw === "") return void 0;
117636
- if (typeof raw === "string") return ICON_NAMES.includes(raw.trim()) ? raw.trim() : { problem: `"${raw}" is not a glyph name` };
117637
- if (!Array.isArray(raw) || !raw.length || raw.length > 12) return { problem: "the value is neither a glyph name nor a list of 1 to 12 parts" };
117638
- const parts = [];
117639
- for (const [i, item] of raw.entries()) {
117640
- const at2 = `part ${i + 1}`;
117641
- if (!item || typeof item !== "object" || Array.isArray(item)) return { problem: `${at2} is not a map of \`d\`, \`f\`, \`o\`, \`s\`, \`w\`` };
117642
- const { d: d2, f: f2, o: o3, s, w: w2, ...extra } = item;
117643
- if (Object.keys(extra).length) return { problem: `${at2} has \`${Object.keys(extra).join("`, `")}\`` };
117644
- if (typeof d2 !== "string" || !PATH.test(d2)) return { problem: `${at2} has no \`d\` of SVG path commands and numbers` };
117645
- const part = { d: d2.trim() };
117646
- for (const [key, value] of [["f", f2], ["s", s]]) {
117647
- if (value === void 0) continue;
117648
- if (typeof value !== "string" || !isColor(value)) return { problem: `${at2} colours \`${key}\` with "${String(value)}"` };
117649
- part[key] = value;
117650
- }
117651
- if (o3 !== void 0) {
117652
- if (o3 !== "true") return { problem: `${at2} has \`o: ${String(o3)}\`, not \`true\`` };
117653
- part.o = true;
117654
- }
117655
- if (w2 !== void 0) {
117656
- const width = typeof w2 === "string" ? Number(w2) : NaN;
117657
- if (!(width > 0 && width <= 3)) return { problem: `${at2} has \`w: ${String(w2)}\`, not above 0 and up to 3` };
117658
- part.w = width;
117659
- }
117660
- parts.push(part);
117661
- }
117662
- return parts;
117663
- }
117664
-
117665
- // ../cli/src/lib/agents/yaml.ts
117666
- function stripComment(value) {
117667
- let from = 0;
117668
- const quote2 = value[0];
117669
- if (quote2 === '"' || quote2 === "'") {
117670
- let i = 1;
117671
- while (i < value.length) {
117672
- if (quote2 === '"' && value[i] === "\\") i += 2;
117673
- else if (value[i] === quote2 && quote2 === "'" && value[i + 1] === "'") i += 2;
117674
- else if (value[i] === quote2) break;
117675
- else i++;
117676
- }
117677
- from = i + 1;
117678
- }
117679
- const hash = value.slice(from).search(/(^|[ \t])#/);
117680
- return hash < 0 ? value : value.slice(0, from + hash).trim();
117681
- }
117682
- var readLines = (text3) => text3.split("\n").map((raw) => ({ indent: raw.match(/^[ \t]*/)[0].length, text: raw.trim() })).filter((line) => line.text && !line.text.startsWith("#"));
117683
- function parseYamlBlock(text3) {
117684
- const [map2] = readMap(readLines(text3), 0, 0);
117685
- return map2;
117686
- }
117687
- function readMap(lines, start, indent) {
117688
- const out = {};
117689
- let i = start;
117690
- while (i < lines.length && lines[i].indent >= indent) {
117691
- const line = lines[i];
117692
- if (line.indent > indent) {
117693
- i++;
117694
- continue;
117695
- }
117696
- if (line.text.startsWith("-")) break;
117697
- const match = line.text.match(/^([^:]+):\s*(.*)$/);
117698
- if (!match) {
117699
- i++;
117700
- continue;
117701
- }
117702
- const key = match[1].trim();
117703
- const inline = stripComment(match[2].trim());
117704
- i++;
117705
- if (inline) {
117706
- out[key] = readScalar(inline);
117707
- continue;
117708
- }
117709
- const [value, next] = readBlock(lines, i, indent);
117710
- out[key] = value;
117711
- i = next;
117712
- }
117713
- return [out, i];
117714
- }
117715
- function readScalar(value) {
117716
- const flow = value.match(/^\[(.*)\]$/);
117717
- if (!flow) return unquote2(value);
117718
- return flow[1].split(",").map((item) => unquote2(item.trim())).filter(Boolean);
117719
- }
117720
- function readBlock(lines, start, parentIndent) {
117721
- if (start >= lines.length || lines[start].indent <= parentIndent) return ["", start];
117722
- const indent = lines[start].indent;
117723
- if (lines[start].text.startsWith("-")) return readList(lines, start, indent);
117724
- return readMap(lines, start, indent);
117725
- }
117726
- function readList(lines, start, indent) {
117727
- const out = [];
117728
- let i = start;
117729
- while (i < lines.length && lines[i].indent === indent && lines[i].text.startsWith("-")) {
117730
- const line = lines[i];
117731
- const rest = line.text.replace(/^-\s*/, "");
117732
- const keyIndent = indent + (line.text.length - rest.length);
117733
- i++;
117734
- if (!stripComment(rest)) {
117735
- const [value, next2] = readBlock(lines, i, indent);
117736
- out.push(value);
117737
- i = next2;
117738
- continue;
117739
- }
117740
- const match = rest.match(/^([^:]+):\s*(.*)$/);
117741
- if (!match || /^\[.*\]$/.test(stripComment(rest))) {
117742
- out.push(readScalar(stripComment(rest)));
117743
- continue;
117744
- }
117745
- const item = {};
117746
- const inline = stripComment(match[2].trim());
117747
- if (inline) item[match[1].trim()] = unquote2(inline);
117748
- else {
117749
- const [value, next2] = readBlock(lines, i, keyIndent);
117750
- item[match[1].trim()] = value;
117751
- i = next2;
117752
- }
117753
- const [rest_, next] = readMap(lines, i, keyIndent);
117754
- Object.assign(item, rest_);
117755
- i = next;
117756
- out.push(item);
117757
- }
117758
- return [out, i];
117759
- }
117760
- function splitFrontmatter(text3) {
117761
- const lines = text3.replace(/^/, "").split("\n");
117762
- if (lines[0]?.trim() !== "---") return { meta: null, body: text3 };
117763
- let i = 1;
117764
- while (i < lines.length && lines[i].trim() !== "---") i++;
117765
- if (i >= lines.length) return { meta: null, body: text3 };
117766
- return { meta: lines.slice(1, i).join("\n"), body: lines.slice(i + 1).join("\n") };
116637
+ function splitFrontmatter(text3) {
116638
+ const lines = text3.replace(/^/, "").split("\n");
116639
+ if (lines[0]?.trim() !== "---") return { meta: null, body: text3 };
116640
+ let i = 1;
116641
+ while (i < lines.length && lines[i].trim() !== "---") i++;
116642
+ if (i >= lines.length) return { meta: null, body: text3 };
116643
+ return { meta: lines.slice(1, i).join("\n"), body: lines.slice(i + 1).join("\n") };
117767
116644
  }
117768
116645
 
117769
116646
  // ../cli/src/lib/agents/parse.ts
@@ -117791,7 +116668,7 @@ function parseSpecAgent(text3, from, file3, builtIn = false, list = () => []) {
117791
116668
  const old = OLD_ROLE_KEYS.filter((key) => akb[key] !== void 0);
117792
116669
  if (old.length) {
117793
116670
  return bad(
117794
- `\`${name}\` declares ${old.map((key) => `\`akb.${key}\``).join(", ")}, which the board no longer reads \u2014 remove ${old.length > 1 ? "them" : "it"}, and list the agent in its workflow's \`WORKFLOW.md\` under \`previews\`, \`land\` or \`scheduled\` (\`akb guide write-agent\`), or ask the Workflow builder to rewrite it`,
116671
+ `\`${name}\` declares ${old.map((key) => `\`akb.${key}\``).join(", ")}, which the board no longer reads \u2014 remove ${old.length > 1 ? "them" : "it"}, and list the agent in its studio's \`STUDIO.md\` under \`previews\`, \`land\` or \`scheduled\` (\`akb guide write-agent\`), or ask the Studio builder to rewrite it`,
117795
116672
  { keys: old }
117796
116673
  );
117797
116674
  }
@@ -117857,7 +116734,7 @@ function readTranslations(raw) {
117857
116734
  }
117858
116735
  return out;
117859
116736
  }
117860
- function memoryPaths(raw) {
116737
+ function memoryPaths(raw, folder = "memory/agents/<name>/") {
117861
116738
  if (raw === void 0) return [];
117862
116739
  const block = map(raw);
117863
116740
  const extra = block ? Object.keys(block).filter((key) => key !== "workspace") : [];
@@ -117869,7 +116746,7 @@ function memoryPaths(raw) {
117869
116746
  }
117870
116747
  const paths = [...new Set(list.map((v) => v.trim()))];
117871
116748
  const outside = paths.find((p2) => p2.startsWith("/") || p2.includes("\\") || p2.split("/").some((part) => part === ".." || part === "."));
117872
- if (outside) return `\`akb.memoryFiles.workspace: ${outside}\`, which is outside its memory folder \u2014 use a path inside \`memory/agents/<name>/\``;
116749
+ if (outside) return `\`akb.memoryFiles.workspace: ${outside}\`, which is outside its memory folder \u2014 use a path inside \`${folder}\``;
117873
116750
  return paths;
117874
116751
  }
117875
116752
  var names = (value) => [...new Set((Array.isArray(value) ? value : [value]).map((v) => str3(v)).filter(Boolean))];
@@ -117894,8 +116771,8 @@ var canonicalSpecAgent = (name) => {
117894
116771
  return LEGACY_SPEC_AGENT_NAMES[asked] ?? asked;
117895
116772
  };
117896
116773
 
117897
- // ../cli/src/lib/agent/workflow-def.ts
117898
- var WORKFLOW_ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
116774
+ // ../cli/src/lib/agent/studio-def.ts
116775
+ var STUDIO_ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
117899
116776
  var OLD_KEYS = ["stages", "delivers", "helpers", "every"];
117900
116777
  var box = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
117901
116778
  var text2 = (value) => typeof value === "string" ? value.trim() : "";
@@ -117914,8 +116791,8 @@ function readPreviews(value) {
117914
116791
  }
117915
116792
  return readGroup(value);
117916
116793
  }
117917
- function parseWorkflowFile(id, source, from) {
117918
- if (!WORKFLOW_ID.test(id)) return { problem: `${from}: \`${id}\` is not a workflow id \u2014 use lowercase letters, digits and dashes` };
116794
+ function parseStudioFile(id, source, from) {
116795
+ if (!STUDIO_ID.test(id)) return { problem: `${from}: \`${id}\` is not a studio id \u2014 use lowercase letters, digits and dashes` };
117919
116796
  const { meta, body } = splitFrontmatter(source);
117920
116797
  if (meta === null) return { problem: `${from}: no \`---\` frontmatter` };
117921
116798
  const raw = parseYamlBlock(meta);
@@ -117924,7 +116801,7 @@ function parseWorkflowFile(id, source, from) {
117924
116801
  const old = OLD_KEYS.filter((key) => key in raw);
117925
116802
  if (old.length) {
117926
116803
  return {
117927
- problem: `${from}: \`${old.join("`, `")}\` ${old.length > 1 ? "are" : "is"} no longer read \u2014 list the agents under \`previews\`, \`land\` and \`scheduled\` instead (\`akb guide write-agent\`), or ask the Workflow builder to rewrite it`
116804
+ problem: `${from}: \`${old.join("`, `")}\` ${old.length > 1 ? "are" : "is"} no longer read \u2014 list the agents under \`previews\`, \`land\` and \`scheduled\` instead (\`akb guide write-agent\`), or ask the Studio builder to rewrite it`
117928
116805
  };
117929
116806
  }
117930
116807
  const icon = readIcon(raw.icon);
@@ -117948,6 +116825,8 @@ function parseWorkflowFile(id, source, from) {
117948
116825
  if (!agent || scheduled.some((s) => s.agent === agent)) continue;
117949
116826
  scheduled.push({ agent, ...text2(row.cadence) ? { cadence: text2(row.cadence) } : {} });
117950
116827
  }
116828
+ const workspace = memoryPaths(raw.memoryFiles, `memory/studios/${id}/`);
116829
+ if (typeof workspace === "string") return { problem: `${from}: declares ${workspace}` };
117951
116830
  const names2 = Object.fromEntries(Object.entries(box(raw.names)).map(([lang, said]) => [lang, text2(said)]).filter(([, said]) => said));
117952
116831
  return {
117953
116832
  def: {
@@ -117961,371 +116840,1539 @@ function parseWorkflowFile(id, source, from) {
117961
116840
  previews,
117962
116841
  land,
117963
116842
  scheduled,
116843
+ ...workspace.length ? { memoryFiles: { workspace } } : {},
117964
116844
  rules: body.trim()
117965
116845
  }
117966
116846
  };
117967
116847
  }
117968
116848
 
117969
- // ../cli/src/lib/agent/workflow-folder.ts
117970
- import fs21 from "node:fs";
117971
- import path25 from "node:path";
116849
+ // ../cli/src/lib/agent/studio-folder.ts
116850
+ import fs16 from "node:fs";
116851
+ import path20 from "node:path";
116852
+
116853
+ // ../cli/src/lib/shared/studio-files.ts
116854
+ var STUDIO_FILE = "STUDIO.md";
116855
+ var MCP_FILE = "mcp.json";
116856
+ var CARD_TEMPLATE_FILE = "CARD.md";
116857
+ var SHARED_DIR = "shared/";
116858
+ var VERSION_FILE = "version.json";
116859
+ var KB = 1024;
116860
+ var FILE_LIMITS = { file: 2 * KB * KB, total: 2 * KB * KB, count: 500, path: 512 };
116861
+ var officialId = (folder) => `wf_builtin_${folder.replace(/-/g, "_")}`;
116862
+ var hashInput = (files) => JSON.stringify(Object.entries(files).sort(([a2], [b2]) => a2 < b2 ? -1 : 1));
116863
+ var landsOf = (def) => ({ lands: def.land.some((h3) => !h3.off) });
116864
+ var SEGMENT = /^[\w.-]+$/;
116865
+ var isAboutFile = (file3) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file3) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file3);
116866
+ var bytes = (text3) => new TextEncoder().encode(text3).length;
116867
+ var isSharedFile = (file3) => {
116868
+ const parts = file3.split("/");
116869
+ return parts.length > 1 && parts[0] === "shared" && parts.slice(1).every((p2) => SEGMENT.test(p2) && p2 !== "." && p2 !== "..");
116870
+ };
116871
+ function folderPath(file3, top) {
116872
+ const parts = file3.split("/");
116873
+ if (parts.length < 3 || parts[0] !== top || !AGENT_NAME.test(parts[1])) return null;
116874
+ if (parts.slice(2).some((p2) => !SEGMENT.test(p2) || p2 === "." || p2 === "..")) return null;
116875
+ return [parts[1], parts.slice(2).join("/")];
116876
+ }
116877
+ function mcpProblem(text3) {
116878
+ let read4;
116879
+ try {
116880
+ read4 = JSON.parse(text3);
116881
+ } catch {
116882
+ return "is not JSON";
116883
+ }
116884
+ const servers = read4?.mcpServers;
116885
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "must hold `mcpServers`, an object of name \u2192 server";
116886
+ for (const [name, server] of Object.entries(servers)) {
116887
+ const { command, args, ...rest } = server ?? {};
116888
+ if (!AGENT_NAME.test(name)) return `names a server \`${name}\`; use lowercase letters, digits and dashes`;
116889
+ if (typeof command !== "string" || !command) return `server \`${name}\` needs a \`command\``;
116890
+ if (args !== void 0 && !(Array.isArray(args) && args.every((a2) => typeof a2 === "string"))) return `server \`${name}\`: \`args\` must be a list of strings`;
116891
+ if (Object.keys(rest).length) return `server \`${name}\` takes only \`command\` and \`args\``;
116892
+ }
116893
+ return null;
116894
+ }
116895
+ function checkStudioFiles(value, official = false) {
116896
+ const read4 = inspect(value, official);
116897
+ const first = read4.problems[0];
116898
+ return first ? { ok: false, ...first } : { ok: true, def: read4.def, files: read4.files };
116899
+ }
116900
+ function inspect(value, official) {
116901
+ const problems = [];
116902
+ const fail = (file3, reason, tooLarge = false) => {
116903
+ problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
116904
+ return { problems };
116905
+ };
116906
+ if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
116907
+ const files = Object.fromEntries(Object.entries(value).filter(([file3]) => file3 !== VERSION_FILE));
116908
+ const entries = Object.entries(files);
116909
+ if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
116910
+ let total = 0;
116911
+ const folders2 = /* @__PURE__ */ new Map();
116912
+ const skills = /* @__PURE__ */ new Set();
116913
+ for (const [file3, text3] of entries) {
116914
+ if (typeof text3 !== "string" || text3.includes("\0")) {
116915
+ fail(file3, "is not a text file");
116916
+ continue;
116917
+ }
116918
+ if (file3.length > FILE_LIMITS.path) {
116919
+ fail(file3, `the path is longer than ${FILE_LIMITS.path} characters`);
116920
+ continue;
116921
+ }
116922
+ const size = bytes(text3);
116923
+ if (size > FILE_LIMITS.file) return fail(file3, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
116924
+ total += size;
116925
+ if (total > FILE_LIMITS.total) return fail("files", `are larger than ${FILE_LIMITS.total / KB / KB} MB together`, true);
116926
+ if (file3 === STUDIO_FILE || file3 === CARD_TEMPLATE_FILE) continue;
116927
+ if (official && file3 === MCP_FILE) {
116928
+ const problem = mcpProblem(text3);
116929
+ if (problem) fail(file3, problem);
116930
+ continue;
116931
+ }
116932
+ if (official && isAboutFile(file3)) continue;
116933
+ if (official && file3.startsWith("skills/")) {
116934
+ if (!folderPath(file3, "skills")) fail(file3, "is not inside skills/<name>/");
116935
+ else skills.add(file3.split("/")[1]);
116936
+ continue;
116937
+ }
116938
+ if (isSharedFile(file3)) continue;
116939
+ const at2 = folderPath(file3, "agents");
116940
+ if (!at2) {
116941
+ fail(file3, `is neither ${STUDIO_FILE}, ${CARD_TEMPLATE_FILE}, shared/ nor inside agents/<name>/`);
116942
+ continue;
116943
+ }
116944
+ if (!folders2.has(at2[0])) folders2.set(at2[0], /* @__PURE__ */ new Map());
116945
+ folders2.get(at2[0]).set(at2[1], text3);
116946
+ }
116947
+ for (const name of skills) {
116948
+ if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
116949
+ }
116950
+ const source = files[STUDIO_FILE];
116951
+ const read4 = typeof source === "string" ? parseStudioFile("studio", source, STUDIO_FILE) : null;
116952
+ if (!read4) fail(STUDIO_FILE, "is missing");
116953
+ else if ("problem" in read4) fail(STUDIO_FILE, read4.problem.replace(`${STUDIO_FILE}: `, ""));
116954
+ const agents = /* @__PURE__ */ new Map();
116955
+ for (const [name, own2] of folders2) {
116956
+ const from = `agents/${name}/AGENT.md`;
116957
+ const text3 = own2.get("AGENT.md");
116958
+ if (text3 === void 0) {
116959
+ fail(from, "is missing");
116960
+ continue;
116961
+ }
116962
+ const parsed = parseSpecAgent(text3, from, (p2) => own2.get(p2) ?? null, false, () => [...own2.keys()].filter((p2) => p2 !== "AGENT.md"));
116963
+ if ("problem" in parsed) fail(from, parsed.problem.replace(`${from}: `, ""));
116964
+ else if (parsed.agent.name !== name) fail(from, `calls itself \`${parsed.agent.name}\`; it must match its folder`);
116965
+ else agents.set(name, parsed.agent);
116966
+ }
116967
+ if (!read4 || "problem" in read4) return { problems };
116968
+ const def = read4.def;
116969
+ const named2 = [
116970
+ ...def.previews.map((h3) => [h3.agent, "it previews with"]),
116971
+ ...def.land.map((h3) => [h3.agent, "it lands with"]),
116972
+ ...def.scheduled.map((s) => [s.agent, "it schedules"])
116973
+ ];
116974
+ for (const [name, why2] of named2) {
116975
+ if (!agents.has(name) && !folders2.has(name)) fail(STUDIO_FILE, `${why2} \`${name}\`, which has no agents/${name}/AGENT.md`);
116976
+ }
116977
+ return { problems, def, files };
116978
+ }
116979
+
116980
+ // ../cli/src/lib/agent/studio-folder.ts
116981
+ var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
116982
+ function filesOf(dir, base = dir) {
116983
+ return fs16.readdirSync(dir, { withFileTypes: true }).filter((e2) => !e2.name.startsWith(".")).flatMap((e2) => {
116984
+ const full = path20.join(dir, e2.name);
116985
+ return e2.isDirectory() ? filesOf(full, base) : [path20.relative(base, full).split(path20.sep).join("/")];
116986
+ });
116987
+ }
116988
+ function readStudioFile(dir, file3) {
116989
+ const full = path20.join(dir, file3);
116990
+ return isAboutFile(file3) && !file3.endsWith(".md") ? `data:${MIME[path20.extname(file3)]};base64,${fs16.readFileSync(full).toString("base64")}` : fs16.readFileSync(full, "utf8");
116991
+ }
116992
+ var readStudioFolder = (dir) => Object.fromEntries(filesOf(dir).sort().map((f2) => [f2, readStudioFile(dir, f2)]));
116993
+
116994
+ // ../official/pack.ts
116995
+ var OFFICIAL = path21.dirname(fileURLToPath2(import.meta.url));
116996
+ var dirs = (dir) => fs17.readdirSync(dir, { withFileTypes: true }).filter((e2) => e2.isDirectory()).map((e2) => e2.name).sort();
116997
+ var hashOf = (files) => crypto2.createHash("sha256").update(hashInput(files)).digest("hex");
116998
+ function packOfficial(root2 = OFFICIAL, loose = false) {
116999
+ const agentsDir = path21.join(root2, "agents");
117000
+ const agentFiles = Object.fromEntries(dirs(agentsDir).map((name) => {
117001
+ const dir = path21.join(agentsDir, name);
117002
+ return [name, readStudioFolder(dir)];
117003
+ }));
117004
+ for (const [name, own2] of Object.entries(loose ? {} : agentFiles)) {
117005
+ const read4 = parseSpecAgent(own2["AGENT.md"] ?? "", `official/agents/${name}/AGENT.md`, (p2) => own2[p2] ?? null, true);
117006
+ if ("problem" in read4) throw new Error(read4.problem);
117007
+ }
117008
+ const studiosDir = path21.join(root2, "studios");
117009
+ return dirs(studiosDir).map((folder) => {
117010
+ const dir = path21.join(studiosDir, folder);
117011
+ const files = {};
117012
+ for (const f2 of filesOf(dir).sort()) {
117013
+ if (f2 === STUDIO_FILE || f2 === CARD_TEMPLATE_FILE || f2 === MCP_FILE || f2.startsWith("skills/") || f2.startsWith(SHARED_DIR) || isAboutFile(f2)) files[f2] = readStudioFile(dir, f2);
117014
+ }
117015
+ const read4 = checkStudioFiles({ [STUDIO_FILE]: files[STUDIO_FILE], ...Object.fromEntries(
117016
+ Object.entries(agentFiles).flatMap(([name, own2]) => Object.entries(own2).map(([f2, t2]) => [`agents/${name}/${f2}`, t2]))
117017
+ ) });
117018
+ if (!read4.ok && !loose) throw new Error(`official/studios/${folder}: ${read4.file}: ${read4.reason}`);
117019
+ const parsed = parseStudioFile(folder, files[STUDIO_FILE] ?? "", STUDIO_FILE);
117020
+ if ("problem" in parsed) throw new Error(parsed.problem);
117021
+ const def = parsed.def;
117022
+ for (const name of [...new Set([...def.previews, ...def.land, ...def.scheduled].map((h3) => h3.agent))].sort()) {
117023
+ for (const [f2, text3] of Object.entries(agentFiles[name] ?? {})) files[`agents/${name}/${f2}`] = text3;
117024
+ }
117025
+ const checked = loose ? { ok: true } : checkStudioFiles(files, true);
117026
+ if (!checked.ok) throw new Error(`official/studios/${folder}: ${checked.file}: ${checked.reason}`);
117027
+ if (!def.names?.zh && !loose) throw new Error(`official/studios/${folder}/${STUDIO_FILE}: add its Chinese name under \`names: zh\``);
117028
+ return {
117029
+ id: officialId(folder),
117030
+ name: def.name,
117031
+ names: { en: def.name, ...def.names },
117032
+ description: def.description,
117033
+ when: def.when,
117034
+ ...landsOf(def),
117035
+ hash: hashOf(files),
117036
+ files
117037
+ };
117038
+ });
117039
+ }
117040
+
117041
+ // ../cli/src/lib/cloud/tasks.ts
117042
+ import fs18 from "node:fs";
117043
+ import path22 from "node:path";
117044
+ var TASK_ENV = "AI4KANBAN_TASK";
117045
+ function workspaceTask() {
117046
+ const id = process.env[TASK_ENV];
117047
+ return id && id.trim() ? id.trim() : null;
117048
+ }
117049
+ function runnerProject(board) {
117050
+ if (path22.basename(board) !== "kanban" || path22.basename(path22.dirname(board)) !== ".akb") return null;
117051
+ const linked = linkedProject(board, path22.dirname(path22.dirname(board)));
117052
+ return linked.ok ? linked.value : null;
117053
+ }
117054
+ function linkedProject(board, root2) {
117055
+ const file3 = path22.join(root2, ".akb", "base.json");
117056
+ if (!fs18.existsSync(file3)) return { ok: true, value: null };
117057
+ try {
117058
+ const base = JSON.parse(fs18.readFileSync(file3, "utf8"));
117059
+ 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();
117060
+ const projects = new Set(Object.keys(base.files ?? {}).flatMap((p2) => /^projects\/([^/]+)\//.exec(p2)?.[1] ?? []));
117061
+ if (typeof base.project === "string") projects.add(base.project);
117062
+ if (projects.size !== 1) throw new Error();
117063
+ return { ok: true, value: [...projects][0] };
117064
+ } catch {
117065
+ return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
117066
+ }
117067
+ }
117068
+
117069
+ // ../cli/src/lib/file-memo.ts
117070
+ import fs19 from "node:fs";
117071
+ import path23 from "node:path";
117072
+ function stamp(paths) {
117073
+ const parts = [];
117074
+ const visit = (p2) => {
117075
+ let st2;
117076
+ try {
117077
+ st2 = fs19.statSync(p2, { bigint: true });
117078
+ } catch {
117079
+ parts.push(`${p2}:-`);
117080
+ return;
117081
+ }
117082
+ if (!st2.isDirectory()) {
117083
+ parts.push(`${p2}:${st2.mtimeNs}:${st2.size}`);
117084
+ return;
117085
+ }
117086
+ parts.push(`${p2}/`);
117087
+ let names2;
117088
+ try {
117089
+ names2 = fs19.readdirSync(p2).sort();
117090
+ } catch {
117091
+ return;
117092
+ }
117093
+ for (const name of names2) if (name !== "node_modules" && name !== ".git") visit(path23.join(p2, name));
117094
+ };
117095
+ for (const p2 of paths) visit(p2);
117096
+ return parts.join("\n");
117097
+ }
117098
+ function copy(v) {
117099
+ if (Array.isArray(v)) return v.map(copy);
117100
+ if (v instanceof Map) return new Map([...v].map(([k2, x2]) => [k2, copy(x2)]));
117101
+ if (v instanceof Set) return new Set([...v].map(copy));
117102
+ if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
117103
+ return Object.fromEntries(Object.entries(v).map(([k2, x2]) => [k2, copy(x2)]));
117104
+ }
117105
+ return v;
117106
+ }
117107
+ var perTurn = false;
117108
+ var turn = 0;
117109
+ var turnEnding = false;
117110
+ function currentTurn() {
117111
+ if (!perTurn) return ++turn;
117112
+ if (!turnEnding) {
117113
+ turnEnding = true;
117114
+ setImmediate(() => {
117115
+ turn++;
117116
+ turnEnding = false;
117117
+ }).unref();
117118
+ }
117119
+ return turn;
117120
+ }
117121
+ function memoByFiles(paths, read4) {
117122
+ let last2 = null;
117123
+ return () => {
117124
+ const now = currentTurn();
117125
+ if (last2?.turn !== now) {
117126
+ const seen = stamp(paths());
117127
+ if (last2?.stamp === seen) last2.turn = now;
117128
+ else last2 = { stamp: seen, turn: now, value: read4() };
117129
+ }
117130
+ return copy(last2.value);
117131
+ };
117132
+ }
117133
+
117134
+ // ../cli/src/lib/agent/cloud-studios.ts
117135
+ var DEV = "AI4KANBAN_STUDIOS";
117136
+ var root = () => path24.join(machineHome(), "studios");
117137
+ var safe = (name) => name.replace(/[^\w.@-]/g, "_");
117138
+ var versionFile = (id, version) => path24.join(root(), "versions", `${safe(id)}@${version}.json`);
117139
+ var listFile = (project) => path24.join(root(), "lists", `${safe(project)}.json`);
117140
+ var pinFile = (task) => path24.join(root(), "tasks", `${safe(task)}.json`);
117141
+ function readJson(file3) {
117142
+ try {
117143
+ return JSON.parse(fs20.readFileSync(file3, "utf8"));
117144
+ } catch {
117145
+ return null;
117146
+ }
117147
+ }
117148
+ function writeJson(file3, value) {
117149
+ fs20.mkdirSync(path24.dirname(file3), { recursive: true });
117150
+ const tmp = `${file3}.${process.pid}.tmp`;
117151
+ fs20.writeFileSync(tmp, `${JSON.stringify(value)}
117152
+ `);
117153
+ fs20.renameSync(tmp, file3);
117154
+ }
117155
+ var readVersion2 = (id, version) => readJson(versionFile(id, version));
117156
+ function saveVersion(held4) {
117157
+ const file3 = versionFile(held4.id, held4.version);
117158
+ if (!fs20.existsSync(file3)) writeJson(file3, { id: held4.id, version: held4.version, name: held4.name, names: held4.names, files: held4.files });
117159
+ }
117160
+ function savePin(task, held4) {
117161
+ saveVersion(held4);
117162
+ writeJson(pinFile(task), { studio: held4.id, version: held4.version });
117163
+ }
117164
+ var readPin = (task) => readJson(pinFile(task));
117165
+ var jsonIn = (dir) => {
117166
+ try {
117167
+ return fs20.readdirSync(path24.join(root(), dir)).filter((f2) => f2.endsWith(".json"));
117168
+ } catch {
117169
+ return [];
117170
+ }
117171
+ };
117172
+ async function sweepVersions(ended2) {
117173
+ const keep2 = /* @__PURE__ */ new Set();
117174
+ const held4 = (id, version) => keep2.add(path24.basename(versionFile(id, version)));
117175
+ for (const file3 of jsonIn("tasks")) {
117176
+ const at2 = path24.join(root(), "tasks", file3);
117177
+ const pin = readJson(at2);
117178
+ if (!pin || await ended2(file3.slice(0, -".json".length))) fs20.rmSync(at2, { force: true });
117179
+ else held4(pin.studio, pin.version);
117180
+ }
117181
+ for (const file3 of jsonIn("lists")) {
117182
+ for (const w2 of readJson(path24.join(root(), "lists", file3))?.studios ?? []) held4(w2.id, w2.version);
117183
+ }
117184
+ const versions = jsonIn("versions");
117185
+ const newest2 = /* @__PURE__ */ new Map();
117186
+ const parts = (file3) => ({ id: file3.slice(0, file3.lastIndexOf("@")), version: Number(file3.slice(file3.lastIndexOf("@") + 1, -".json".length)) });
117187
+ for (const file3 of versions) {
117188
+ const { id, version } = parts(file3);
117189
+ if (version > (newest2.get(id) ?? -1)) newest2.set(id, version);
117190
+ }
117191
+ const gone = versions.filter((file3) => !keep2.has(file3) && newest2.get(parts(file3).id) !== parts(file3).version);
117192
+ for (const file3 of gone) fs20.rmSync(path24.join(root(), "versions", file3), { force: true });
117193
+ return gone;
117194
+ }
117195
+ var boardProject = () => KANBAN ? runnerProject(KANBAN) : null;
117196
+ var devFolder = () => process.env[DEV]?.trim() || "";
117197
+ var flowOf = (held4) => {
117198
+ const id = studioName(held4.id);
117199
+ const read4 = parseStudioFile(id, held4.files["STUDIO.md"] ?? "", `the \`${id}\` studio`);
117200
+ if ("problem" in read4) return null;
117201
+ return { def: read4.def, cloudId: held4.id, version: held4.version, builtIn: held4.id.startsWith("wf_builtin_"), files: held4.files };
117202
+ };
117203
+ function readFlows() {
117204
+ const dev = devFolder();
117205
+ if (dev) {
117206
+ return packOfficial(dev, true).flatMap((w2) => flowOf({ id: w2.id, version: 1, name: w2.name, names: w2.names, files: w2.files }) ?? []);
117207
+ }
117208
+ const project = boardProject();
117209
+ if (!project || !readSession()) return [];
117210
+ const list = readJson(listFile(project))?.studios ?? [];
117211
+ const flows2 = list.flatMap((w2) => {
117212
+ const held4 = readVersion2(w2.id, w2.version);
117213
+ return held4 ? flowOf(held4) ?? [] : [];
117214
+ });
117215
+ const task = workspaceTask();
117216
+ const pin = task ? readPin(task) : null;
117217
+ const pinned = pin && readVersion2(pin.studio, pin.version);
117218
+ const mine = pinned && flowOf(pinned);
117219
+ if (!mine) return flows2;
117220
+ return [mine, ...flows2.filter((f2) => f2.cloudId !== mine.cloudId)];
117221
+ }
117222
+ var sources = () => {
117223
+ if (devFolder()) return [devFolder()];
117224
+ const project = boardProject();
117225
+ const task = workspaceTask();
117226
+ return [sessionFile(), ...project ? [listFile(project)] : [], ...task ? [pinFile(task)] : []];
117227
+ };
117228
+ var flows = memoByFiles(sources, readFlows);
117229
+ var cloudFlows = () => flows();
117230
+ function cloudAgentFiles() {
117231
+ const files = {};
117232
+ const official = /* @__PURE__ */ new Set();
117233
+ const owner = /* @__PURE__ */ new Map();
117234
+ for (const flow of cloudFlows()) {
117235
+ for (const [name, text3] of Object.entries(flow.files)) {
117236
+ const at2 = /^agents\/([^/]+)\/(.+)$/.exec(name);
117237
+ if (!at2) continue;
117238
+ const [, agent, rest] = at2;
117239
+ if (owner.has(agent) && owner.get(agent) !== flow.cloudId) continue;
117240
+ owner.set(agent, flow.cloudId);
117241
+ if (flow.builtIn) official.add(agent);
117242
+ files[`${agent}/${rest}`] = text3;
117243
+ }
117244
+ }
117245
+ return { files, official };
117246
+ }
117247
+
117248
+ // src/cache.ts
117249
+ var IDLE_MS = 7 * 24 * 60 * 6e4;
117250
+ var SWEEP_MS = 24 * 60 * 6e4;
117251
+ var PROJECT_ID = /^[\w-]{1,100}$/;
117252
+ var cacheRoot = () => path25.join(runnerHome(), "cache");
117253
+ function cacheDir(project) {
117254
+ if (!PROJECT_ID.test(project)) throw new Error("This job names no project.");
117255
+ return path25.join(cacheRoot(), project);
117256
+ }
117257
+ var akbDir = (dir) => path25.join(dir, ".akb");
117258
+ var usedFile = (dir) => path25.join(akbDir(dir), "used.json");
117259
+ var unsentFile = (dir) => path25.join(akbDir(dir), "unsent");
117260
+ function markUsed(dir, at2 = Date.now()) {
117261
+ fs21.mkdirSync(akbDir(dir), { recursive: true });
117262
+ fs21.writeFileSync(usedFile(dir), `${JSON.stringify({ at: at2 })}
117263
+ `);
117264
+ }
117265
+ function usedAt(dir) {
117266
+ try {
117267
+ const at2 = JSON.parse(fs21.readFileSync(usedFile(dir), "utf8")).at;
117268
+ return typeof at2 === "number" ? at2 : null;
117269
+ } catch {
117270
+ return null;
117271
+ }
117272
+ }
117273
+ var unsent = (dir) => fs21.existsSync(unsentFile(dir));
117274
+ function markUnsent(dir, unsent2) {
117275
+ if (!unsent2) return void fs21.rmSync(unsentFile(dir), { force: true });
117276
+ fs21.mkdirSync(akbDir(dir), { recursive: true });
117277
+ fs21.writeFileSync(unsentFile(dir), "");
117278
+ }
117279
+ var holds = /* @__PURE__ */ new Map();
117280
+ var holdsDir = () => path25.join(runnerHome(), "holds");
117281
+ var holdFile = (dir) => path25.join(holdsDir(), `${crypto3.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
117282
+ function hold(dir) {
117283
+ fs21.mkdirSync(holdsDir(), { recursive: true, mode: 448 });
117284
+ fs21.writeFileSync(holdFile(dir), "", { mode: 384 });
117285
+ holds.set(dir, (holds.get(dir) ?? 0) + 1);
117286
+ let held4 = true;
117287
+ return () => {
117288
+ if (!held4) return;
117289
+ held4 = false;
117290
+ const left = holds.get(dir) - 1;
117291
+ if (left) holds.set(dir, left);
117292
+ else {
117293
+ holds.delete(dir);
117294
+ fs21.rmSync(holdFile(dir), { force: true });
117295
+ }
117296
+ };
117297
+ }
117298
+ function paused(dir) {
117299
+ try {
117300
+ const file3 = path25.join(projectStateDir(path25.join(akbDir(dir), "kanban")), SESSIONS_FILE);
117301
+ const held4 = JSON.parse(fs21.readFileSync(file3, "utf8"));
117302
+ return (held4.deliveries ?? []).some((d2) => d2.status === "active");
117303
+ } catch {
117304
+ return false;
117305
+ }
117306
+ }
117307
+ function busy(dir) {
117308
+ if (holds.has(dir)) return true;
117309
+ const prefix = path25.basename(holdFile(dir)).split(".")[0] + ".";
117310
+ try {
117311
+ return fs21.readdirSync(holdsDir()).filter((file3) => file3.startsWith(prefix)).some((file3) => {
117312
+ try {
117313
+ process.kill(Number(file3.split(".")[1]), 0);
117314
+ return true;
117315
+ } catch {
117316
+ fs21.rmSync(path25.join(holdsDir(), file3), { force: true });
117317
+ return false;
117318
+ }
117319
+ });
117320
+ } catch {
117321
+ return false;
117322
+ }
117323
+ }
117324
+ var kept2 = (dir) => busy(dir) || unsent(dir) || paused(dir);
117325
+ function clearAkb(dir) {
117326
+ dir = realpath2(dir);
117327
+ if (kept2(dir) || fs21.existsSync(path25.join(akbDir(dir), "worktrees")) || fs21.existsSync(path25.join(akbDir(dir), "handoffs"))) return false;
117328
+ let entries;
117329
+ try {
117330
+ entries = fs21.readdirSync(akbDir(dir));
117331
+ } catch {
117332
+ return true;
117333
+ }
117334
+ for (const name of entries) fs21.rmSync(path25.join(akbDir(dir), name), { recursive: true, force: true });
117335
+ return true;
117336
+ }
117337
+ async function readAccess(machineId2) {
117338
+ if (!readSession()) return null;
117339
+ const [folders2, elsewhere] = await Promise.all([listFolders(machineId2), listElsewhere(machineId2)]);
117340
+ if (!folders2.ok || !elsewhere.ok) return null;
117341
+ return {
117342
+ projects: /* @__PURE__ */ new Set([...folders2.value.folders.map((f2) => f2.project), ...elsewhere.value.projects.map((p2) => p2.project)]),
117343
+ folders: new Set(folders2.value.folders.map((f2) => realpath2(f2.path)))
117344
+ };
117345
+ }
117346
+ function realpath2(p2) {
117347
+ try {
117348
+ return fs21.realpathSync(p2);
117349
+ } catch {
117350
+ return p2;
117351
+ }
117352
+ }
117353
+ function idle(dir, now) {
117354
+ const at2 = usedAt(dir);
117355
+ if (at2 === null) markUsed(dir, now);
117356
+ return at2 !== null && now - at2 > IDLE_MS;
117357
+ }
117358
+ async function sweepCache(machineId2, now = Date.now()) {
117359
+ const access = await readAccess(machineId2);
117360
+ const swept = [];
117361
+ let cached2 = [];
117362
+ try {
117363
+ cached2 = fs21.readdirSync(cacheRoot(), { withFileTypes: true });
117364
+ } catch {
117365
+ }
117366
+ for (const e2 of cached2) {
117367
+ const dir = path25.join(cacheRoot(), e2.name);
117368
+ if (!e2.isDirectory() || kept2(dir) || fs21.existsSync(path25.join(dir, ".git"))) continue;
117369
+ const gone = access && !access.projects.has(e2.name);
117370
+ if ((idle(dir, now) || gone) && !fs21.existsSync(path25.join(akbDir(dir), "worktrees")) && !fs21.existsSync(path25.join(akbDir(dir), "handoffs"))) {
117371
+ fs21.rmSync(dir, { recursive: true, force: true });
117372
+ swept.push(dir);
117373
+ }
117374
+ }
117375
+ for (const dir of allowedProjects()) {
117376
+ let held4 = [];
117377
+ try {
117378
+ held4 = fs21.readdirSync(akbDir(dir));
117379
+ } catch {
117380
+ }
117381
+ if (!held4.length) continue;
117382
+ const gone = access && !access.folders.has(dir);
117383
+ if ((idle(dir, now) || gone) && clearAkb(dir)) swept.push(dir);
117384
+ }
117385
+ return swept;
117386
+ }
117387
+ var sweepStudios = () => sweepVersions(async (task) => {
117388
+ const read4 = await readTask(task);
117389
+ if (read4.ok) return read4.value.status === "done" || read4.value.status === "cancelled";
117390
+ return read4.code === "not_found" ? true : null;
117391
+ });
117392
+ function removeLegacy() {
117393
+ const home4 = runnerHome();
117394
+ for (const name of ["boards", "akb-bin"]) fs21.rmSync(path25.join(home4, name), { recursive: true, force: true });
117395
+ let entries = [];
117396
+ try {
117397
+ entries = fs21.readdirSync(home4, { withFileTypes: true });
117398
+ } catch {
117399
+ return;
117400
+ }
117401
+ for (const e2 of entries) {
117402
+ const account = path25.join(home4, e2.name);
117403
+ if (!e2.isDirectory() || !fs21.existsSync(path25.join(account, "unfiled"))) continue;
117404
+ fs21.rmSync(path25.join(account, "unfiled"), { recursive: true, force: true });
117405
+ if (!fs21.readdirSync(account).length) fs21.rmdirSync(account);
117406
+ }
117407
+ }
117408
+
117409
+ // src/update.ts
117410
+ import crypto4 from "node:crypto";
117411
+ import fs22 from "node:fs";
117412
+ import path26 from "node:path";
117413
+ import zlib from "node:zlib";
117414
+ var TIMEOUT_MS2 = 6e4;
117415
+ var versionsDir = () => path26.join(runnerHome(), "bin", "runner");
117416
+ var versionDir = (version) => path26.join(versionsDir(), version);
117417
+ var entryOf = (dir) => path26.join(dir, "dist", "runner.mjs");
117418
+ var registry = () => (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
117419
+ async function installPackage(pkg, version, nodeVersion = process.versions.node) {
117420
+ const dir = pkg.dirOf(version);
117421
+ if (fs22.existsSync(pkg.entryOf(dir))) return { ok: true, dir };
117422
+ let meta;
117423
+ let tarball;
117424
+ try {
117425
+ const answer = await fetch(`${registry()}/${pkg.name}/${encodeURIComponent(version)}`, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
117426
+ if (!answer.ok) return { ok: false, why: "unreachable", detail: `registry answered ${answer.status}` };
117427
+ meta = await answer.json();
117428
+ const range = meta.engines?.node;
117429
+ if (range && !satisfies(nodeVersion, range)) return { ok: false, why: "node", detail: range };
117430
+ if (!meta.dist?.tarball) return { ok: false, why: "unreachable", detail: "no tarball" };
117431
+ const download2 = await fetch(meta.dist.tarball, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
117432
+ if (!download2.ok) return { ok: false, why: "unreachable", detail: `download answered ${download2.status}` };
117433
+ tarball = Buffer.from(await download2.arrayBuffer());
117434
+ } catch (e2) {
117435
+ return { ok: false, why: "unreachable", detail: e2 instanceof Error ? e2.message : String(e2) };
117436
+ }
117437
+ const expected = /^sha512-(.+)$/.exec(meta.dist.integrity ?? "")?.[1];
117438
+ const actual = crypto4.createHash("sha512").update(tarball).digest("base64");
117439
+ if (!expected || expected !== actual) return { ok: false, why: "integrity", detail: "sha512 mismatch" };
117440
+ const staging = `${dir}.${process.pid}.tmp`;
117441
+ try {
117442
+ fs22.rmSync(staging, { recursive: true, force: true });
117443
+ extract(zlib.gunzipSync(tarball), staging);
117444
+ if (!fs22.existsSync(pkg.entryOf(staging))) throw new Error(`the package carries no ${path26.relative(staging, pkg.entryOf(staging))}`);
117445
+ fs22.rmSync(dir, { recursive: true, force: true });
117446
+ fs22.renameSync(staging, dir);
117447
+ } catch (e2) {
117448
+ fs22.rmSync(staging, { recursive: true, force: true });
117449
+ return { ok: false, why: "integrity", detail: e2 instanceof Error ? e2.message : String(e2) };
117450
+ }
117451
+ return { ok: true, dir };
117452
+ }
117453
+ function extract(tar, into) {
117454
+ let offset = 0;
117455
+ let longName = null;
117456
+ while (offset + 512 <= tar.length) {
117457
+ const header = tar.subarray(offset, offset + 512);
117458
+ if (header.every((b2) => b2 === 0)) break;
117459
+ const field = (start, length) => header.subarray(start, start + length).toString("utf8").replace(/\0.*$/s, "");
117460
+ const size = parseInt(field(124, 12).trim() || "0", 8);
117461
+ const type = field(156, 1) || "0";
117462
+ const body = tar.subarray(offset + 512, offset + 512 + size);
117463
+ offset += 512 + Math.ceil(size / 512) * 512;
117464
+ if (type === "x") {
117465
+ longName = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(body.toString("utf8"))?.[1] ?? null;
117466
+ continue;
117467
+ }
117468
+ if (type === "L") {
117469
+ longName = body.toString("utf8").replace(/\0.*$/s, "");
117470
+ continue;
117471
+ }
117472
+ const prefix = field(345, 155);
117473
+ const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
117474
+ longName = null;
117475
+ if (type !== "0" && type !== "5") continue;
117476
+ const relative = name.replace(/^[^/]+\//, "");
117477
+ if (!relative) continue;
117478
+ const target = path26.resolve(into, relative);
117479
+ if (!target.startsWith(path26.resolve(into) + path26.sep)) throw new Error(`refusing ${name}`);
117480
+ if (type === "5") fs22.mkdirSync(target, { recursive: true });
117481
+ else {
117482
+ fs22.mkdirSync(path26.dirname(target), { recursive: true });
117483
+ fs22.writeFileSync(target, body);
117484
+ }
117485
+ }
117486
+ }
117487
+ var parse = (v) => {
117488
+ const m = /^v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(v.trim());
117489
+ return m ? [Number(m[1]), Number(m[2]) || 0, Number(m[3]) || 0] : null;
117490
+ };
117491
+ function compare(a2, b2) {
117492
+ const [x2, y2] = [parse(a2) ?? [0, 0, 0], parse(b2) ?? [0, 0, 0]];
117493
+ for (let i = 0; i < 3; i++) if (x2[i] !== y2[i]) return x2[i] - y2[i];
117494
+ const pre = (v) => /^v?\d+\.\d+\.\d+-([^+]+)/.exec(v)?.[1]?.split(".");
117495
+ const ap = pre(a2), bp = pre(b2);
117496
+ if (!ap || !bp) return ap ? -1 : bp ? 1 : 0;
117497
+ for (let i = 0; i < Math.max(ap.length, bp.length); i++) {
117498
+ const av = ap[i], bv = bp[i];
117499
+ if (av === bv) continue;
117500
+ if (av === void 0) return -1;
117501
+ if (bv === void 0) return 1;
117502
+ const an2 = /^\d+$/.test(av), bn2 = /^\d+$/.test(bv);
117503
+ if (an2 && bn2) return Number(av) - Number(bv);
117504
+ if (an2 !== bn2) return an2 ? -1 : 1;
117505
+ return av < bv ? -1 : 1;
117506
+ }
117507
+ return 0;
117508
+ }
117509
+ function satisfies(version, range) {
117510
+ return range.split("||").some((alternative) => {
117511
+ const parts = alternative.trim().split(/\s+/).filter(Boolean);
117512
+ return parts.length > 0 && parts.every((part) => meets(version, part));
117513
+ });
117514
+ }
117515
+ function meets(version, comparator) {
117516
+ const m = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/.exec(comparator);
117517
+ const bound = m && parse(m[2]);
117518
+ if (!m || !bound) return false;
117519
+ const v = parse(version);
117520
+ const c2 = compare(version, m[2]);
117521
+ switch (m[1]) {
117522
+ case ">=":
117523
+ return c2 >= 0;
117524
+ case ">":
117525
+ return c2 > 0;
117526
+ case "<=":
117527
+ return c2 <= 0;
117528
+ case "<":
117529
+ return c2 < 0;
117530
+ case "^":
117531
+ return c2 >= 0 && v[0] === bound[0];
117532
+ case "~":
117533
+ return c2 >= 0 && v[0] === bound[0] && v[1] === bound[1];
117534
+ default: {
117535
+ const given = m[2].split(".").filter((p2) => /^\d+$/.test(p2)).length;
117536
+ return [0, 1, 2].slice(0, given).every((i) => v[i] === bound[i]);
117537
+ }
117538
+ }
117539
+ }
117540
+
117541
+ // src/akb-version.ts
117542
+ var CHECK_MS2 = 1e4;
117543
+ var VERSION2 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
117544
+ var stateFile = () => path27.join(akbHome(), "state.json");
117545
+ var akbVersionDir = (version) => path27.join(akbHome(), version);
117546
+ var entryOf2 = (dir) => path27.join(dir, "bin", "ai4kanban.mjs");
117547
+ var AKB = { name: "wildcrane", dirOf: akbVersionDir, entryOf: entryOf2 };
117548
+ function readAkbState() {
117549
+ try {
117550
+ const held4 = JSON.parse(fs23.readFileSync(stateFile(), "utf8"));
117551
+ return { current: held4.current ?? null, bad: held4.bad ?? [] };
117552
+ } catch {
117553
+ return { current: null, bad: [] };
117554
+ }
117555
+ }
117556
+ function writeAkbState(state) {
117557
+ fs23.mkdirSync(akbHome(), { recursive: true });
117558
+ const staging = `${stateFile()}.${process.pid}.tmp`;
117559
+ fs23.writeFileSync(staging, `${JSON.stringify(state, null, 2)}
117560
+ `);
117561
+ fs23.renameSync(staging, stateFile());
117562
+ }
117563
+ function contractOf(dir) {
117564
+ try {
117565
+ return JSON.parse(fs23.readFileSync(path27.join(dir, "package.json"), "utf8")).akbContract ?? null;
117566
+ } catch {
117567
+ return null;
117568
+ }
117569
+ }
117570
+ var usable = (dir) => fs23.existsSync(entryOf2(dir)) && contractOf(dir) === AKB_CONTRACT;
117571
+ function currentAkb() {
117572
+ const { current: current2 } = readAkbState();
117573
+ if (!current2) return bundledAkb();
117574
+ const dir = akbVersionDir(current2);
117575
+ if (!usable(dir)) return bundledAkb();
117576
+ try {
117577
+ const now = /* @__PURE__ */ new Date();
117578
+ fs23.utimesSync(dir, now, now);
117579
+ } catch {
117580
+ }
117581
+ return { command: process.execPath, args: akbArgs(entryOf2(dir)), version: current2, shim: path27.join(dir, "shim") };
117582
+ }
117583
+ var answers2 = (dir, version) => new Promise((resolve2) => {
117584
+ execFile(process.execPath, [entryOf2(dir), "--version"], { timeout: CHECK_MS2, killSignal: "SIGKILL" }, (error, stdout) => resolve2(!error && stdout.trim().split(/\s+/).at(-1) === version));
117585
+ });
117586
+ var wanted = null;
117587
+ var fetching = false;
117588
+ function useVersion(current2) {
117589
+ const state = readAkbState();
117590
+ if (state.current !== current2) writeAkbState({ ...state, current: current2 });
117591
+ }
117592
+ async function fetchVersion(version) {
117593
+ const got = await installPackage(AKB, version);
117594
+ if (!got.ok) return console.error(`runner: akb ${version} was not fetched: ${got.detail}`);
117595
+ if (contractOf(got.dir) !== AKB_CONTRACT || !await answers2(got.dir, version)) {
117596
+ console.error(`runner: akb ${version} failed its check and will not be used`);
117597
+ const state = readAkbState();
117598
+ return writeAkbState({ ...state, bad: [.../* @__PURE__ */ new Set([...state.bad, version])] });
117599
+ }
117600
+ if (wanted === version) useVersion(version);
117601
+ }
117602
+ async function followAkb(named2) {
117603
+ if (!named2) return;
117604
+ const { version } = named2;
117605
+ try {
117606
+ if (version !== null && !VERSION2.test(version)) return;
117607
+ wanted = version;
117608
+ if (version === null || version === AKB_VERSION) return useVersion(null);
117609
+ const state = readAkbState();
117610
+ if (fetching || state.bad.includes(version) || state.current === version && usable(akbVersionDir(version))) return;
117611
+ fetching = true;
117612
+ await fetchVersion(version).finally(() => fetching = false);
117613
+ } catch (e2) {
117614
+ console.error(`runner: the akb version was not followed: ${e2 instanceof Error ? e2.message : String(e2)}`);
117615
+ }
117616
+ }
117617
+ function sweepAkb(now = Date.now()) {
117618
+ const { current: current2 } = readAkbState();
117619
+ let entries = [];
117620
+ try {
117621
+ entries = fs23.readdirSync(akbHome(), { withFileTypes: true });
117622
+ } catch {
117623
+ return;
117624
+ }
117625
+ for (const e2 of entries) {
117626
+ if (!e2.isDirectory() || e2.name === current2 || e2.name === BUNDLED_SHIM) continue;
117627
+ const dir = path27.join(akbHome(), e2.name);
117628
+ if (now - fs23.statSync(dir).mtimeMs > IDLE_MS) fs23.rmSync(dir, { recursive: true, force: true });
117629
+ }
117630
+ }
117631
+
117632
+ // src/chats.ts
117633
+ import fs25 from "node:fs";
117634
+ import path29 from "node:path";
117635
+
117636
+ // ../cli/src/lib/shared/chats.ts
117637
+ var CHAT_KEEP_DAYS = 30;
117638
+
117639
+ // ../cli/src/lib/agent/task-chats.ts
117640
+ import fs24 from "node:fs";
117641
+ import path28 from "node:path";
117642
+ var TASK = /^[\w-]{1,100}$/;
117643
+ var taskChatsDir = (home4 = machineHome()) => path28.join(home4, "chats");
117644
+ function taskChatFile(task, home4) {
117645
+ if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
117646
+ return path28.join(taskChatsDir(home4), `${task}.jsonl`);
117647
+ }
117648
+ function readTaskChat(task, home4) {
117649
+ let text3;
117650
+ try {
117651
+ text3 = fs24.readFileSync(taskChatFile(task, home4), "utf8");
117652
+ } catch {
117653
+ return [];
117654
+ }
117655
+ const lines = [];
117656
+ for (const raw of text3.split("\n")) {
117657
+ if (!raw.trim()) continue;
117658
+ try {
117659
+ const line = JSON.parse(raw);
117660
+ if (typeof line.id === "string" && (line.role === "user" || line.role === "agent") && typeof line.text === "string") lines.push(line);
117661
+ } catch {
117662
+ }
117663
+ }
117664
+ return lines;
117665
+ }
117666
+
117667
+ // src/chats.ts
117668
+ var DAY_MS = 24 * 60 * 6e4;
117669
+ var REVIEW_EVERY_MS = DAY_MS;
117670
+ var KEEP_MS2 = CHAT_KEEP_DAYS * DAY_MS;
117671
+ var home3 = () => runnerHome();
117672
+ var reviewedFile = () => path29.join(taskChatsDir(home3()), "reviewed.json");
117673
+ function readReviewed() {
117674
+ try {
117675
+ const held4 = JSON.parse(fs25.readFileSync(reviewedFile(), "utf8"));
117676
+ return { checkedAt: Number(held4.checkedAt) || 0, tasks: held4.tasks ?? {} };
117677
+ } catch {
117678
+ return { checkedAt: 0, tasks: {} };
117679
+ }
117680
+ }
117681
+ function writeReviewed(reviewed) {
117682
+ fs25.mkdirSync(path29.dirname(reviewedFile()), { recursive: true });
117683
+ fs25.writeFileSync(reviewedFile(), `${JSON.stringify(reviewed, null, 2)}
117684
+ `);
117685
+ }
117686
+ function keepChat(job, reply, at2 = Date.now()) {
117687
+ if (!job.task || !job.chat || !reply?.trim()) return;
117688
+ const lines = [
117689
+ { id: job.chat.message, role: "user", text: job.chat.body, at: at2 },
117690
+ { id: job.id, role: "agent", text: reply, at: at2, runtime: job.runtime, model: job.model ?? null }
117691
+ ];
117692
+ const file3 = taskChatFile(job.task, home3());
117693
+ fs25.mkdirSync(path29.dirname(file3), { recursive: true });
117694
+ fs25.appendFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
117695
+ `).join(""));
117696
+ }
117697
+ function keepCloudChat(task, messages) {
117698
+ const file3 = taskChatFile(task, home3());
117699
+ if (!messages.length) return fs25.rmSync(file3, { force: true });
117700
+ const lines = messages.map((m) => ({ id: m.id, role: m.role, text: m.body, at: Date.parse(m.created_at) || Date.now() }));
117701
+ fs25.mkdirSync(path29.dirname(file3), { recursive: true });
117702
+ fs25.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
117703
+ `).join(""));
117704
+ }
117705
+ async function keepDecisions(task, read4) {
117706
+ const comments = [];
117707
+ let after = null;
117708
+ do {
117709
+ const page = await read4(task, after);
117710
+ if (!page.ok) return;
117711
+ for (const d2 of page.value.data) {
117712
+ if (d2.comment.trim()) comments.push({ id: d2.id, role: "user", text: d2.comment, at: Date.parse(d2.created_at) || Date.now() });
117713
+ }
117714
+ after = page.value.next;
117715
+ } while (after);
117716
+ if (!comments.length) return;
117717
+ const ids = new Set(comments.map((c2) => c2.id));
117718
+ const lines = [...readTaskChat(task, home3()).filter((l2) => !ids.has(l2.id)), ...comments].sort((a2, b2) => a2.at - b2.at);
117719
+ const file3 = taskChatFile(task, home3());
117720
+ fs25.mkdirSync(path29.dirname(file3), { recursive: true });
117721
+ fs25.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
117722
+ `).join(""));
117723
+ }
117724
+ var tasksKept = () => {
117725
+ try {
117726
+ return fs25.readdirSync(taskChatsDir(home3())).map((n) => /^([\w-]{1,100})\.jsonl$/.exec(n)?.[1]).filter((t2) => !!t2);
117727
+ } catch {
117728
+ return [];
117729
+ }
117730
+ };
117731
+ function pruneChats(now = Date.now()) {
117732
+ for (const task of tasksKept()) {
117733
+ const lines = readTaskChat(task, home3());
117734
+ const kept4 = lines.filter((l2) => now - l2.at < KEEP_MS2);
117735
+ if (kept4.length === lines.length) continue;
117736
+ const file3 = taskChatFile(task, home3());
117737
+ if (kept4.length) fs25.writeFileSync(file3, kept4.map((l2) => `${JSON.stringify(l2)}
117738
+ `).join(""));
117739
+ else fs25.rmSync(file3, { force: true });
117740
+ }
117741
+ }
117742
+ var lastOf = (task) => readTaskChat(task, home3()).at(-1);
117743
+ var reviewMarks = (tasks) => Object.fromEntries(tasks.map(({ task, archivedAt }) => {
117744
+ const last2 = lastOf(task);
117745
+ return [task, last2 ? { archivedAt, message: last2.id } : { archivedAt }];
117746
+ }));
117747
+ function markReviewed2(marks) {
117748
+ const reviewed = readReviewed();
117749
+ writeReviewed({ ...reviewed, tasks: { ...reviewed.tasks, ...marks } });
117750
+ }
117751
+ async function reviewChats(machineId2, runtimes, now = Date.now()) {
117752
+ const reviewed = readReviewed();
117753
+ if (now - reviewed.checkedAt < REVIEW_EVERY_MS) return;
117754
+ pruneChats(now);
117755
+ const owned = await listChats(machineId2);
117756
+ if (!owned.ok) return;
117757
+ const byProject = /* @__PURE__ */ new Map();
117758
+ for (const { task, project, archivedAt } of owned.value.chats) {
117759
+ const mark = reviewed.tasks[task];
117760
+ const last2 = lastOf(task);
117761
+ if (mark?.archivedAt === archivedAt && (!last2 || last2.id === mark.message)) continue;
117762
+ byProject.set(project, [...byProject.get(project) ?? [], task]);
117763
+ }
117764
+ const signedIn = runtimes.find((r2) => r2.installed && r2.loggedIn !== false)?.name;
117765
+ for (const [project, tasks] of [...byProject].map(([p2, t2]) => [p2, t2.slice(0, 100)])) {
117766
+ const replied = tasks.flatMap((t2) => readTaskChat(t2, home3())).filter((l2) => l2.runtime).sort((a2, b2) => a2.at - b2.at).at(-1);
117767
+ const runtime = replied?.runtime ?? signedIn ?? "claude-code";
117768
+ const sent = await dispatchReview(machineId2, project, tasks, runtime, replied?.model ?? null);
117769
+ if (!sent.ok) console.error(`runner: the chats of ${project} were not sent for review: ${sent.error}`);
117770
+ }
117771
+ const listed2 = new Set(owned.value.chats.map((c2) => c2.task));
117772
+ const held4 = readReviewed();
117773
+ writeReviewed({ checkedAt: now, tasks: Object.fromEntries(Object.entries(held4.tasks).filter(([t2]) => listed2.has(t2))) });
117774
+ }
117775
+
117776
+ // src/board-watch.ts
117777
+ import fs31 from "node:fs";
117778
+ import path35 from "node:path";
117779
+
117780
+ // ../artifact-sdk/src/builtin/compare.json
117781
+ var compare_default = '{\n "name": "compare",\n "title": { "en": "Compare", "zh": "\u5BF9\u6BD4" },\n "types": ["compare"],\n "schema": {\n "type": "object",\n "required": ["a", "b"],\n "properties": { "a": { "type": "string" }, "b": { "type": "string" } }\n },\n "references": [\n { "json": "/a", "types": ["storyboard", "compare", "spritesheet", "studio"] },\n { "json": "/b", "types": ["storyboard", "compare", "spritesheet", "studio"] },\n { "json": "/shots", "types": ["storyboard", "compare", "spritesheet", "studio"] }\n ]\n}\n';
117782
+
117783
+ // ../artifact-sdk/src/builtin/html.json
117784
+ var html_default = `{
117785
+ "name": "html",
117786
+ "title": { "en": "Page", "zh": "\u9875\u9762" },
117787
+ "types": ["html"],
117788
+ "references": [
117789
+ { "text": "<[a-z][^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117790
+ { "text": "<[a-z][^<>]*?\\\\sposter\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117791
+ { "text": "<[a-z][^<>]*?\\\\ssrcset\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']", "list": "," },
117792
+ { "text": "<link\\\\b[^<>]*?\\\\shref\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117793
+ { "text": "url\\\\(\\\\s*[\\"']?([^\\"')]+?)[\\"']?\\\\s*\\\\)" }
117794
+ ],
117795
+ "skip": ["(?<=<script\\\\b[^<>]*>)[\\\\s\\\\S]*?(?=</script\\\\s*>|$)"]
117796
+ }
117797
+ `;
117798
+
117799
+ // ../artifact-sdk/src/builtin/image.json
117800
+ var image_default = '{ "name": "image", "title": { "en": "Image", "zh": "\u56FE\u7247" }, "types": ["image"] }\n';
117801
+
117802
+ // ../artifact-sdk/src/builtin/markdown.json
117803
+ var markdown_default = `{
117804
+ "name": "markdown",
117805
+ "title": { "en": "Document", "zh": "\u6587\u6863" },
117806
+ "types": ["markdown"],
117807
+ "references": [
117808
+ { "text": "!\\\\[[^\\\\]\\\\n]*\\\\]\\\\(\\\\s*<?([^\\\\s)>]+)>?(?:\\\\s+[\\"'][^\\"'\\\\n]*[\\"'])?\\\\s*\\\\)" },
117809
+ { "text": "<img\\\\b[^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" }
117810
+ ]
117811
+ }
117812
+ `;
117813
+
117814
+ // ../artifact-sdk/src/builtin/spritesheet.json
117815
+ var spritesheet_default = '{\n "name": "spritesheet",\n "title": { "en": "Sprite animation", "zh": "\u7CBE\u7075\u52A8\u753B" },\n "types": ["spritesheet"],\n "schema": {\n "type": "object",\n "required": ["frames", "meta"],\n "properties": {\n "frames": {\n "anyOf": [\n { "type": "array", "minItems": 1, "items": { "type": "object", "required": ["frame"] } },\n { "type": "object", "additionalProperties": { "type": "object", "required": ["frame"] } }\n ]\n },\n "meta": {\n "type": "object",\n "required": ["app", "image"],\n "properties": { "app": { "type": "string", "pattern": "codeandweb\\\\.com/texturepacker" }, "image": { "type": "string" } }\n }\n }\n },\n "references": [{ "json": "/meta/image" }]\n}\n';
117816
+
117817
+ // ../artifact-sdk/src/builtin/storyboard.json
117818
+ var storyboard_default = '{\n "name": "storyboard",\n "title": { "en": "Storyboard", "zh": "\u5206\u955C" },\n "types": ["storyboard"],\n "schema": {\n "type": "object",\n "anyOf": [{ "required": ["shots"] }, { "required": ["slides"] }],\n "properties": {\n "shots": {\n "type": "array",\n "items": {\n "type": "object",\n "properties": { "frames": { "type": "array", "items": { "type": "object", "properties": { "src": { "type": "string" } } } } }\n }\n },\n "slides": {\n "type": "array",\n "items": {\n "type": "object",\n "properties": {\n "preview": { "type": "object", "properties": { "src": { "type": "string" } } },\n "assets": { "type": "array", "items": { "type": "string" } }\n }\n }\n }\n }\n },\n "references": [\n { "json": "/shots/*/frames/*/src", "types": ["storyboard", "compare", "spritesheet", "studio"] },\n { "json": "/slides/*/preview/src", "types": ["storyboard", "compare", "spritesheet", "studio"] },\n { "json": "/slides/*/assets/*" }\n ]\n}\n';
117819
+
117820
+ // ../artifact-sdk/src/builtin/tiled.json
117821
+ var tiled_default = `{
117822
+ "name": "tiled",
117823
+ "title": { "en": "Tiled map", "zh": "Tiled \u5730\u56FE" },
117824
+ "types": ["tiled"],
117825
+ "references": [
117826
+ { "text": "<tileset\\\\b[^<>]*?\\\\ssource\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']", "types": ["tiled"] },
117827
+ { "text": "<image\\\\b[^<>]*?\\\\ssource\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117828
+ { "text": "\\"source\\"\\\\s*:\\\\s*\\"([^\\"]+)\\"", "types": ["tiled"] },
117829
+ { "text": "\\"image\\"\\\\s*:\\\\s*\\"([^\\"]+)\\"" }
117830
+ ]
117831
+ }
117832
+ `;
117833
+
117834
+ // ../artifact-sdk/src/builtin/video.json
117835
+ var video_default = '{ "name": "video", "title": { "en": "Video", "zh": "\u89C6\u9891" }, "types": ["video"] }\n';
117836
+
117837
+ // ../artifact-sdk/src/builtin/studio.json
117838
+ var studio_default = '{\n "name": "studio",\n "title": { "en": "Studio", "zh": "\u5DE5\u4F5C\u53F0" },\n "types": ["studio"],\n "schema": {\n "type": "object",\n "required": ["rounds", "land", "scheduled"],\n "properties": {\n "rounds": {\n "type": "array",\n "items": {\n "type": "array",\n "minItems": 1,\n "items": { "type": "object", "required": ["agent", "title"], "properties": { "agent": { "type": "string" }, "title": { "type": "object", "required": ["en"] } } }\n }\n },\n "land": { "type": "array", "items": { "type": "object", "required": ["agent", "title"] } },\n "scheduled": { "type": "array", "items": { "type": "object", "required": ["agent", "title"] } }\n }\n }\n}\n';
117839
+
117840
+ // ../artifact-sdk/src/builtin/index.ts
117841
+ var read = (m) => typeof m === "string" ? JSON.parse(m) : m;
117842
+ var builtin_default = [html_default, image_default, video_default, markdown_default, storyboard_default, compare_default, studio_default, tiled_default, spritesheet_default].map(read);
117843
+
117844
+ // ../artifact-sdk/src/internal/schema.ts
117845
+ var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117846
+ function typeOk(type, v) {
117847
+ const types = Array.isArray(type) ? type : [type];
117848
+ return types.some(
117849
+ (t2) => t2 === "null" ? v === null : t2 === "array" ? Array.isArray(v) : t2 === "object" ? isObj(v) : t2 === "integer" ? Number.isInteger(v) : t2 === "number" ? typeof v === "number" && Number.isFinite(v) : typeof v === t2
117850
+ );
117851
+ }
117852
+ function schemaProblem(schema, value, at2 = "") {
117853
+ if (!isObj(schema)) return null;
117854
+ const s = schema;
117855
+ const here2 = at2 || "/";
117856
+ if (s.type !== void 0 && !typeOk(s.type, value)) return here2;
117857
+ if (Array.isArray(s.enum) && !s.enum.some((e2) => JSON.stringify(e2) === JSON.stringify(value))) return here2;
117858
+ if (s.const !== void 0 && JSON.stringify(s.const) !== JSON.stringify(value)) return here2;
117859
+ if (Array.isArray(s.anyOf) && !s.anyOf.some((x2) => !schemaProblem(x2, value, at2))) return here2;
117860
+ if (typeof value === "string") {
117861
+ if (typeof s.minLength === "number" && value.length < s.minLength) return here2;
117862
+ if (typeof s.maxLength === "number" && value.length > s.maxLength) return here2;
117863
+ if (typeof s.pattern === "string") {
117864
+ try {
117865
+ if (!new RegExp(s.pattern, "u").test(value)) return here2;
117866
+ } catch {
117867
+ }
117868
+ }
117869
+ }
117870
+ if (typeof value === "number") {
117871
+ if (typeof s.minimum === "number" && value < s.minimum) return here2;
117872
+ if (typeof s.maximum === "number" && value > s.maximum) return here2;
117873
+ }
117874
+ if (Array.isArray(value)) {
117875
+ if (typeof s.minItems === "number" && value.length < s.minItems) return here2;
117876
+ if (typeof s.maxItems === "number" && value.length > s.maxItems) return here2;
117877
+ if (isObj(s.items)) {
117878
+ for (let i = 0; i < value.length; i++) {
117879
+ const bad = schemaProblem(s.items, value[i], `${at2}/${i}`);
117880
+ if (bad) return bad;
117881
+ }
117882
+ }
117883
+ }
117884
+ if (isObj(value)) {
117885
+ const props = isObj(s.properties) ? s.properties : {};
117886
+ if (Array.isArray(s.required)) {
117887
+ for (const k2 of s.required) if (typeof k2 === "string" && !(k2 in value)) return `${at2}/${k2}`;
117888
+ }
117889
+ for (const [k2, v] of Object.entries(value)) {
117890
+ if (k2 in props) {
117891
+ const bad = schemaProblem(props[k2], v, `${at2}/${k2}`);
117892
+ if (bad) return bad;
117893
+ } else if (s.additionalProperties === false) return `${at2}/${k2}`;
117894
+ else if (isObj(s.additionalProperties)) {
117895
+ const bad = schemaProblem(s.additionalProperties, v, `${at2}/${k2}`);
117896
+ if (bad) return bad;
117897
+ }
117898
+ }
117899
+ }
117900
+ return null;
117901
+ }
117902
+
117903
+ // ../artifact-sdk/src/internal/manifest.ts
117904
+ var BUILTINS = builtin_default;
117905
+ var manifestOf = (type) => BUILTINS.find((m) => m.types.includes(type));
117906
+ function typeOf(data, types) {
117907
+ for (const type of types) if (!schemaProblem(manifestOf(type)?.schema, data)) return { type };
117908
+ if (types.length !== 1) return { type: null };
117909
+ return { type: types[0], problem: `does not match ${types[0]} at ${schemaProblem(manifestOf(types[0])?.schema, data)}` };
117910
+ }
117911
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117912
+ var remote = (src) => !src || /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src);
117913
+ function mapJson(node, keys, at2, visit) {
117914
+ if (!keys.length) return typeof node === "string" && node ? visit(node, at2) : node;
117915
+ const [key, ...rest] = keys;
117916
+ if (Array.isArray(node)) {
117917
+ if (key === "*") return node.map((x2, i2) => mapJson(x2, rest, `${at2}/${i2}`, visit));
117918
+ const i = Number(key);
117919
+ return Number.isInteger(i) && i in node ? node.map((x2, j2) => j2 === i ? mapJson(x2, rest, `${at2}/${j2}`, visit) : x2) : node;
117920
+ }
117921
+ if (!isObject(node)) return node;
117922
+ const out = { ...node };
117923
+ for (const k2 of key === "*" ? Object.keys(node) : key in node ? [key] : []) out[k2] = mapJson(node[k2], rest, `${at2}/${k2}`, visit);
117924
+ return out;
117925
+ }
117926
+ function mapText(text3, rule, skipped, visit) {
117927
+ let out = "";
117928
+ let last2 = 0;
117929
+ for (const m of text3.matchAll(new RegExp(rule.text, "gid"))) {
117930
+ const span = m.indices?.[1];
117931
+ if (!span || m[1] === void 0 || skipped.some(([a2, b2]) => span[0] >= a2 && span[0] < b2)) continue;
117932
+ const line = text3.slice(0, span[0]).split("\n").length;
117933
+ const one = (src) => remote(src) ? src : visit(src, line);
117934
+ const value = rule.list ? m[1].split(rule.list).map((part) => part.replace(/^(\s*)(\S+)/, (_2, space, src) => space + one(src))).join(rule.list) : one(m[1]);
117935
+ out += text3.slice(last2, span[0]) + value;
117936
+ last2 = span[1];
117937
+ }
117938
+ return out + text3.slice(last2);
117939
+ }
117940
+ function mapReferences(manifest, content, map2) {
117941
+ const skipped = (text3) => (manifest?.skip ?? []).flatMap((re3) => [...text3.matchAll(new RegExp(re3, "gi"))].map((m) => [m.index, m.index + m[0].length]));
117942
+ for (const rule of manifest?.references ?? []) {
117943
+ const types = rule.types ?? [];
117944
+ if ("json" in rule) {
117945
+ if (typeof content !== "string") content = mapJson(content, rule.json.split("/").filter(Boolean), "", (src, at2) => map2(src, { src, types, text: false, at: at2 || "/" }));
117946
+ } else if (typeof content === "string") {
117947
+ content = mapText(content, rule, skipped(content), (src, line) => map2(src, { src, types, text: true, line }));
117948
+ }
117949
+ }
117950
+ return content;
117951
+ }
117952
+ function referencesOf(manifest, content) {
117953
+ const found = [];
117954
+ mapReferences(manifest, content, (src, ref) => (found.push(ref), src));
117955
+ return found;
117956
+ }
117957
+
117958
+ // ../artifact-sdk/src/internal/references.ts
117959
+ var STORYBOARD = ["storyboard"];
117960
+ var STUDIO = ["studio"];
117961
+ var ARRANGED = ["storyboard", "compare", "spritesheet", "studio"];
117962
+ var ASSET = ["spritesheet", "asset"];
117963
+ var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117964
+ function bodyReferences(body) {
117965
+ const lines = body.replace(/<!--[^]*?-->/g, "").split(/\r?\n/);
117966
+ let fence = "";
117967
+ let inTag = false;
117968
+ const out = [];
117969
+ const visible = [];
117970
+ for (const line of lines) {
117971
+ const delimiter = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
117972
+ if (fence) {
117973
+ if (delimiter && delimiter[0] === fence[0] && delimiter.length >= fence.length) fence = "";
117974
+ visible.push("");
117975
+ continue;
117976
+ }
117977
+ if (delimiter) {
117978
+ fence = delimiter;
117979
+ visible.push("");
117980
+ continue;
117981
+ }
117982
+ const kept4 = inTag || !/^(?: {4}|\t)/.test(line);
117983
+ visible.push(kept4 ? line : "");
117984
+ if (kept4 && /^ {0,3}<(?:Asset|Mockup|Compare|Storyboard|Studio)\b/.test(line)) inTag = true;
117985
+ if (line.includes("/>")) inTag = false;
117986
+ }
117987
+ const text3 = visible.join("\n").replace(/(`+)[^]*?\1/g, "");
117988
+ const tag = /<(Asset|Mockup|Compare|Storyboard|Studio)\b([^<>]*?)\/>/g;
117989
+ const blocks = text3.matchAll(/^ {0,3}(?:<(?:Asset|Mockup|Compare|Storyboard|Studio)\b[^<>]*?\/>[ \t]*(?:\n[ \t]*)?)+$/gm);
117990
+ for (const block of blocks) {
117991
+ const tags = [...block[0].matchAll(tag)];
117992
+ for (const m of tags) {
117993
+ const a2 = {};
117994
+ for (const p2 of m[2].matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) a2[p2[1]] = p2[2] ?? p2[3];
117995
+ if (m[1] === "Compare") {
117996
+ if (!a2.a || !a2.b) continue;
117997
+ for (const k2 of ["a", "b", "shots"]) if (a2[k2]) out.push({ src: a2[k2], types: ARRANGED });
117998
+ } else if (a2.src) {
117999
+ out.push({ src: a2.src, types: m[1] === "Storyboard" ? STORYBOARD : m[1] === "Studio" ? STUDIO : m[1] === "Asset" ? ASSET : [] });
118000
+ if (a2.variants) {
118001
+ try {
118002
+ const v = JSON.parse(a2.variants);
118003
+ if (isObject2(v)) {
118004
+ for (const src of Object.values(v)) if (typeof src === "string" && src) out.push({ src, types: m[1] === "Asset" ? ASSET : [] });
118005
+ }
118006
+ } catch {
118007
+ }
118008
+ }
118009
+ }
118010
+ }
118011
+ }
118012
+ for (const m of text3.replace(tag, "").matchAll(/\]\(\s*<?([^\s)>]+)>?(?:\s+["'][^]*?["'])?\s*\)/g)) out.push({ src: m[1], types: [] });
118013
+ return out;
118014
+ }
118015
+ var TYPES = {
118016
+ ".png": "image/png",
118017
+ ".jpg": "image/jpeg",
118018
+ ".jpeg": "image/jpeg",
118019
+ ".gif": "image/gif",
118020
+ ".webp": "image/webp",
118021
+ ".svg": "image/svg+xml",
118022
+ ".mp4": "video/mp4",
118023
+ ".webm": "video/webm",
118024
+ ".mp3": "audio/mpeg",
118025
+ ".pdf": "application/pdf",
118026
+ ".html": "text/html",
118027
+ ".md": "text/markdown",
118028
+ ".mdx": "text/markdown",
118029
+ ".mov": "video/quicktime",
118030
+ ".wav": "audio/wav",
118031
+ ".m4a": "audio/mp4",
118032
+ ".json": "application/json",
118033
+ ".txt": "text/plain",
118034
+ ".otf": "font/otf",
118035
+ ".ttf": "font/ttf",
118036
+ ".woff": "font/woff",
118037
+ ".woff2": "font/woff2",
118038
+ ".css": "text/css",
118039
+ ".tmx": "application/xml",
118040
+ ".tmj": "application/json",
118041
+ ".tsj": "application/json"
118042
+ };
118043
+ function kindOf2(ext) {
118044
+ if (ext === ".tsx" || ext === ".html") return "html";
118045
+ if (ext === ".md" || ext === ".mdx") return "markdown";
118046
+ if (ext === ".tmx" || ext === ".tmj" || ext === ".tsj") return "tiled";
118047
+ const type = TYPES[ext] ?? "";
118048
+ if (type.startsWith("image/")) return "image";
118049
+ return type.startsWith("video/") || type.startsWith("audio/") ? "video" : "asset";
118050
+ }
118051
+
118052
+ // ../artifact-sdk/src/internal/collect.ts
118053
+ var extOf = (file3) => /\.[^./\\]+$/.exec(file3)?.[0].toLowerCase() ?? "";
118054
+ var why = (error) => error instanceof Error ? error.message : String(error);
118055
+ var textKind = (ext, types) => types.find((t2) => {
118056
+ const m = manifestOf(t2);
118057
+ return m && !m.schema;
118058
+ }) ?? kindOf2(ext);
118059
+ var kindAt = (src, types) => extOf(src) === ".json" ? types.includes("asset") ? "asset" : types[0] ?? "asset" : textKind(extOf(src), types);
118060
+ function collect(body, card, host) {
118061
+ const nodes = /* @__PURE__ */ new Map();
118062
+ const active = /* @__PURE__ */ new Set();
118063
+ const out = [];
118064
+ const visit = (src, types, owner) => {
118065
+ const path51 = src.replace(/[?#].*$/, "");
118066
+ let resolved;
118067
+ try {
118068
+ resolved = host.resolve(path51, owner);
118069
+ } catch (error) {
118070
+ if (owner !== card) return { key: null, error: why(error) };
118071
+ if (!nodes.has(src)) {
118072
+ const node2 = { key: src, file: null, kind: kindAt(path51, types), error: why(error), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
118073
+ nodes.set(src, node2);
118074
+ out.push(node2);
118075
+ }
118076
+ return { key: src, error: nodes.get(src).error };
118077
+ }
118078
+ if (!resolved) return { key: null };
118079
+ const { key, file: file3 } = resolved;
118080
+ if (active.has(key)) throw new Error(`${owner}: ${src}: \u8D44\u6E90\u4F9D\u8D56\u5FAA\u73AF`);
118081
+ const json = !!file3 && extOf(file3) === ".json";
118082
+ const held4 = nodes.get(key);
118083
+ if (held4) {
118084
+ if (owner === card) held4.aliases.add(src);
118085
+ if (held4.error || !json || !types.length || held4.kind !== "asset") return { key, error: held4.error };
118086
+ out.splice(out.indexOf(held4), 1);
118087
+ }
118088
+ const node = { key, file: file3, kind: "asset", problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: held4?.aliases ?? /* @__PURE__ */ new Set([key]) };
118089
+ if (owner === card) node.aliases.add(src);
118090
+ nodes.set(key, node);
118091
+ active.add(key);
118092
+ const child = (ref, from) => {
118093
+ const found = visit(ref.src, ref.types, from);
118094
+ if (found.key) node.dependencies.set(ref.src, found.key);
118095
+ else if (found.error) node.problems.push({ src: ref.src, ..."line" in ref ? { line: ref.line } : {}, ..."at" in ref ? { at: ref.at } : {}, message: found.error });
118096
+ node.error ??= found.error;
118097
+ };
118098
+ if (file3) {
118099
+ if (json) {
118100
+ try {
118101
+ node.data = JSON.parse(host.read(file3));
118102
+ const typed = typeOf(node.data, types);
118103
+ node.kind = typed.type ?? "asset";
118104
+ if (typed.problem) node.problems.push({ src: file3, message: `${typed.problem}: ${file3}` });
118105
+ } catch {
118106
+ node.problems.push({ src: file3, message: `not valid JSON: ${file3}` });
118107
+ }
118108
+ } else {
118109
+ node.kind = textKind(extOf(file3), types);
118110
+ try {
118111
+ if (manifestOf(node.kind)?.references) node.data = host.read(file3);
118112
+ } catch (error) {
118113
+ node.problems.push({ src: file3, message: why(error) });
118114
+ }
118115
+ }
118116
+ node.error = node.problems[0]?.message;
118117
+ if (!node.error) for (const ref of referencesOf(manifestOf(node.kind), node.data)) child(ref, file3);
118118
+ } else {
118119
+ for (const ref of host.retained(key)) child(ref, card);
118120
+ }
118121
+ active.delete(key);
118122
+ out.push(node);
118123
+ return { key, error: node.error };
118124
+ };
118125
+ for (const ref of bodyReferences(body)) visit(ref.src, ref.types, card);
118126
+ const sorted = [];
118127
+ const done = /* @__PURE__ */ new Set();
118128
+ const order = (node) => {
118129
+ if (done.has(node.key)) return;
118130
+ done.add(node.key);
118131
+ for (const key of node.dependencies.values()) {
118132
+ const child = nodes.get(key);
118133
+ if (child) order(child);
118134
+ }
118135
+ sorted.push(node);
118136
+ };
118137
+ for (const node of out) order(node);
118138
+ return sorted;
118139
+ }
118140
+
118141
+ // src/task-folder.ts
118142
+ import crypto5 from "node:crypto";
118143
+ import fs30 from "node:fs";
118144
+ import path34 from "node:path";
117972
118145
 
117973
- // ../cli/src/lib/shared/workflow-files.ts
117974
- var WORKFLOW_FILE = "WORKFLOW.md";
117975
- var MCP_FILE = "mcp.json";
117976
- var VERSION_FILE = "version.json";
117977
- var KB = 1024;
117978
- var FILE_LIMITS = { file: 2 * KB * KB, total: 2 * KB * KB, count: 500, path: 512 };
117979
- var officialId = (folder) => `wf_builtin_${folder.replace(/-/g, "_")}`;
117980
- var hashInput = (files) => JSON.stringify(Object.entries(files).sort(([a2], [b2]) => a2 < b2 ? -1 : 1));
117981
- var landsOf = (def) => ({ lands: def.land.some((h3) => !h3.off) });
117982
- var SEGMENT = /^[\w.-]+$/;
117983
- var isAboutFile = (file3) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file3) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file3);
117984
- var bytes = (text3) => new TextEncoder().encode(text3).length;
117985
- function folderPath(file3, top) {
117986
- const parts = file3.split("/");
117987
- if (parts.length < 3 || parts[0] !== top || !AGENT_NAME.test(parts[1])) return null;
117988
- if (parts.slice(2).some((p2) => !SEGMENT.test(p2) || p2 === "." || p2 === "..")) return null;
117989
- return [parts[1], parts.slice(2).join("/")];
117990
- }
117991
- function mcpProblem(text3) {
117992
- let read4;
117993
- try {
117994
- read4 = JSON.parse(text3);
117995
- } catch {
117996
- return "is not JSON";
118146
+ // node_modules/node-diff3/dist/diff3.mjs
118147
+ function LCS(buffer1, buffer2) {
118148
+ let equivalenceClasses = /* @__PURE__ */ Object.create(null);
118149
+ for (let j2 = 0; j2 < buffer2.length; j2++) {
118150
+ const item = buffer2[j2];
118151
+ if (equivalenceClasses[item]) {
118152
+ equivalenceClasses[item].push(j2);
118153
+ } else {
118154
+ equivalenceClasses[item] = [j2];
118155
+ }
117997
118156
  }
117998
- const servers = read4?.mcpServers;
117999
- if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "must hold `mcpServers`, an object of name \u2192 server";
118000
- for (const [name, server] of Object.entries(servers)) {
118001
- const { command, args, ...rest } = server ?? {};
118002
- if (!AGENT_NAME.test(name)) return `names a server \`${name}\`; use lowercase letters, digits and dashes`;
118003
- if (typeof command !== "string" || !command) return `server \`${name}\` needs a \`command\``;
118004
- if (args !== void 0 && !(Array.isArray(args) && args.every((a2) => typeof a2 === "string"))) return `server \`${name}\`: \`args\` must be a list of strings`;
118005
- if (Object.keys(rest).length) return `server \`${name}\` takes only \`command\` and \`args\``;
118157
+ const NULLRESULT = { buffer1index: -1, buffer2index: -1, chain: null };
118158
+ let candidates = [NULLRESULT];
118159
+ for (let i = 0; i < buffer1.length; i++) {
118160
+ const item = buffer1[i];
118161
+ const buffer2indices = equivalenceClasses[item] || [];
118162
+ let r2 = 0;
118163
+ let c2 = candidates[0];
118164
+ for (const j2 of buffer2indices) {
118165
+ let s;
118166
+ for (s = r2; s < candidates.length; s++) {
118167
+ if (candidates[s].buffer2index < j2 && (s === candidates.length - 1 || candidates[s + 1].buffer2index > j2)) {
118168
+ break;
118169
+ }
118170
+ }
118171
+ if (s < candidates.length) {
118172
+ const newCandidate = { buffer1index: i, buffer2index: j2, chain: candidates[s] };
118173
+ if (r2 === candidates.length) {
118174
+ candidates.push(c2);
118175
+ } else {
118176
+ candidates[r2] = c2;
118177
+ }
118178
+ r2 = s + 1;
118179
+ c2 = newCandidate;
118180
+ if (r2 === candidates.length) {
118181
+ break;
118182
+ }
118183
+ }
118184
+ }
118185
+ candidates[r2] = c2;
118006
118186
  }
118007
- return null;
118008
- }
118009
- function checkWorkflowFiles(value, official = false) {
118010
- const read4 = inspect(value, official);
118011
- const first = read4.problems[0];
118012
- return first ? { ok: false, ...first } : { ok: true, def: read4.def, files: read4.files };
118187
+ return candidates[candidates.length - 1];
118013
118188
  }
118014
- function inspect(value, official) {
118015
- const problems = [];
118016
- const fail = (file3, reason, tooLarge = false) => {
118017
- problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
118018
- return { problems };
118019
- };
118020
- if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
118021
- const files = Object.fromEntries(Object.entries(value).filter(([file3]) => file3 !== VERSION_FILE));
118022
- const entries = Object.entries(files);
118023
- if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
118024
- let total = 0;
118025
- const folders2 = /* @__PURE__ */ new Map();
118026
- const skills = /* @__PURE__ */ new Set();
118027
- for (const [file3, text3] of entries) {
118028
- if (typeof text3 !== "string" || text3.includes("\0")) {
118029
- fail(file3, "is not a text file");
118030
- continue;
118031
- }
118032
- if (file3.length > FILE_LIMITS.path) {
118033
- fail(file3, `the path is longer than ${FILE_LIMITS.path} characters`);
118034
- continue;
118035
- }
118036
- const size = bytes(text3);
118037
- if (size > FILE_LIMITS.file) return fail(file3, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
118038
- total += size;
118039
- if (total > FILE_LIMITS.total) return fail("files", `are larger than ${FILE_LIMITS.total / KB / KB} MB together`, true);
118040
- if (file3 === WORKFLOW_FILE) continue;
118041
- if (official && file3 === MCP_FILE) {
118042
- const problem = mcpProblem(text3);
118043
- if (problem) fail(file3, problem);
118044
- continue;
118045
- }
118046
- if (official && isAboutFile(file3)) continue;
118047
- if (official && file3.startsWith("skills/")) {
118048
- if (!folderPath(file3, "skills")) fail(file3, "is not inside skills/<name>/");
118049
- else skills.add(file3.split("/")[1]);
118050
- continue;
118051
- }
118052
- const at2 = folderPath(file3, "agents");
118053
- if (!at2) {
118054
- fail(file3, `is neither ${WORKFLOW_FILE} nor inside agents/<name>/`);
118055
- continue;
118189
+ function diffIndices(buffer1, buffer2) {
118190
+ const lcs = LCS(buffer1, buffer2);
118191
+ let result = [];
118192
+ let tail1 = buffer1.length;
118193
+ let tail2 = buffer2.length;
118194
+ for (let candidate = lcs; candidate !== null; candidate = candidate.chain) {
118195
+ const mismatchLength1 = tail1 - candidate.buffer1index - 1;
118196
+ const mismatchLength2 = tail2 - candidate.buffer2index - 1;
118197
+ tail1 = candidate.buffer1index;
118198
+ tail2 = candidate.buffer2index;
118199
+ if (mismatchLength1 || mismatchLength2) {
118200
+ result.push({
118201
+ buffer1: [tail1 + 1, mismatchLength1],
118202
+ buffer1Content: buffer1.slice(tail1 + 1, tail1 + 1 + mismatchLength1),
118203
+ buffer2: [tail2 + 1, mismatchLength2],
118204
+ buffer2Content: buffer2.slice(tail2 + 1, tail2 + 1 + mismatchLength2)
118205
+ });
118056
118206
  }
118057
- if (!folders2.has(at2[0])) folders2.set(at2[0], /* @__PURE__ */ new Map());
118058
- folders2.get(at2[0]).set(at2[1], text3);
118059
118207
  }
118060
- for (const name of skills) {
118061
- if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
118208
+ result.reverse();
118209
+ return result;
118210
+ }
118211
+ function diff3MergeRegions(a2, o3, b2) {
118212
+ let hunks = [];
118213
+ function addHunk(h3, ab) {
118214
+ hunks.push({
118215
+ ab,
118216
+ oStart: h3.buffer1[0],
118217
+ oLength: h3.buffer1[1],
118218
+ abStart: h3.buffer2[0],
118219
+ abLength: h3.buffer2[1]
118220
+ });
118062
118221
  }
118063
- const source = files[WORKFLOW_FILE];
118064
- const read4 = typeof source === "string" ? parseWorkflowFile("workflow", source, WORKFLOW_FILE) : null;
118065
- if (!read4) fail(WORKFLOW_FILE, "is missing");
118066
- else if ("problem" in read4) fail(WORKFLOW_FILE, read4.problem.replace(`${WORKFLOW_FILE}: `, ""));
118067
- const agents = /* @__PURE__ */ new Map();
118068
- for (const [name, own2] of folders2) {
118069
- const from = `agents/${name}/AGENT.md`;
118070
- const text3 = own2.get("AGENT.md");
118071
- if (text3 === void 0) {
118072
- fail(from, "is missing");
118073
- continue;
118222
+ diffIndices(o3, a2).forEach((item) => addHunk(item, "a"));
118223
+ diffIndices(o3, b2).forEach((item) => addHunk(item, "b"));
118224
+ hunks.sort((x2, y2) => x2.oStart - y2.oStart);
118225
+ let results = [];
118226
+ let currOffset = 0;
118227
+ function advanceTo(endOffset) {
118228
+ if (endOffset > currOffset) {
118229
+ results.push({
118230
+ stable: true,
118231
+ buffer: "o",
118232
+ bufferStart: currOffset,
118233
+ bufferLength: endOffset - currOffset,
118234
+ bufferContent: o3.slice(currOffset, endOffset)
118235
+ });
118236
+ currOffset = endOffset;
118074
118237
  }
118075
- const parsed = parseSpecAgent(text3, from, (p2) => own2.get(p2) ?? null, false, () => [...own2.keys()].filter((p2) => p2 !== "AGENT.md"));
118076
- if ("problem" in parsed) fail(from, parsed.problem.replace(`${from}: `, ""));
118077
- else if (parsed.agent.name !== name) fail(from, `calls itself \`${parsed.agent.name}\`; it must match its folder`);
118078
- else agents.set(name, parsed.agent);
118079
- }
118080
- if (!read4 || "problem" in read4) return { problems };
118081
- const def = read4.def;
118082
- const named2 = [
118083
- ...def.previews.map((h3) => [h3.agent, "it previews with"]),
118084
- ...def.land.map((h3) => [h3.agent, "it lands with"]),
118085
- ...def.scheduled.map((s) => [s.agent, "it schedules"])
118086
- ];
118087
- for (const [name, why2] of named2) {
118088
- if (!agents.has(name) && !folders2.has(name)) fail(WORKFLOW_FILE, `${why2} \`${name}\`, which has no agents/${name}/AGENT.md`);
118089
- }
118090
- return { problems, def, files };
118091
- }
118092
-
118093
- // ../cli/src/lib/agent/workflow-folder.ts
118094
- var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
118095
- function filesOf(dir, base = dir) {
118096
- return fs21.readdirSync(dir, { withFileTypes: true }).filter((e2) => !e2.name.startsWith(".")).flatMap((e2) => {
118097
- const full = path25.join(dir, e2.name);
118098
- return e2.isDirectory() ? filesOf(full, base) : [path25.relative(base, full).split(path25.sep).join("/")];
118099
- });
118100
- }
118101
- function readWorkflowFile(dir, file3) {
118102
- const full = path25.join(dir, file3);
118103
- return isAboutFile(file3) && !file3.endsWith(".md") ? `data:${MIME[path25.extname(file3)]};base64,${fs21.readFileSync(full).toString("base64")}` : fs21.readFileSync(full, "utf8");
118104
- }
118105
- var readWorkflowFolder = (dir) => Object.fromEntries(filesOf(dir).sort().map((f2) => [f2, readWorkflowFile(dir, f2)]));
118106
-
118107
- // ../official/pack.ts
118108
- var OFFICIAL = path26.dirname(fileURLToPath2(import.meta.url));
118109
- var dirs = (dir) => fs22.readdirSync(dir, { withFileTypes: true }).filter((e2) => e2.isDirectory()).map((e2) => e2.name).sort();
118110
- var hashOf = (files) => crypto4.createHash("sha256").update(hashInput(files)).digest("hex");
118111
- function packOfficial(root2 = OFFICIAL, loose = false) {
118112
- const agentsDir = path26.join(root2, "agents");
118113
- const agentFiles = Object.fromEntries(dirs(agentsDir).map((name) => {
118114
- const dir = path26.join(agentsDir, name);
118115
- return [name, readWorkflowFolder(dir)];
118116
- }));
118117
- for (const [name, own2] of Object.entries(loose ? {} : agentFiles)) {
118118
- const read4 = parseSpecAgent(own2["AGENT.md"] ?? "", `official/agents/${name}/AGENT.md`, (p2) => own2[p2] ?? null, true);
118119
- if ("problem" in read4) throw new Error(read4.problem);
118120
118238
  }
118121
- const workflowsDir = path26.join(root2, "workflows");
118122
- return dirs(workflowsDir).map((folder) => {
118123
- const dir = path26.join(workflowsDir, folder);
118124
- const files = {};
118125
- for (const f2 of filesOf(dir).sort()) {
118126
- if (f2 === WORKFLOW_FILE || f2 === MCP_FILE || f2.startsWith("skills/") || isAboutFile(f2)) files[f2] = readWorkflowFile(dir, f2);
118239
+ while (hunks.length) {
118240
+ let hunk = hunks.shift();
118241
+ let regionStart = hunk.oStart;
118242
+ let regionEnd = hunk.oStart + hunk.oLength;
118243
+ let regionHunks = [hunk];
118244
+ advanceTo(regionStart);
118245
+ while (hunks.length) {
118246
+ const nextHunk = hunks[0];
118247
+ const nextHunkStart = nextHunk.oStart;
118248
+ if (nextHunkStart > regionEnd)
118249
+ break;
118250
+ regionEnd = Math.max(regionEnd, nextHunkStart + nextHunk.oLength);
118251
+ regionHunks.push(hunks.shift());
118127
118252
  }
118128
- const read4 = checkWorkflowFiles({ [WORKFLOW_FILE]: files[WORKFLOW_FILE], ...Object.fromEntries(
118129
- Object.entries(agentFiles).flatMap(([name, own2]) => Object.entries(own2).map(([f2, t2]) => [`agents/${name}/${f2}`, t2]))
118130
- ) });
118131
- if (!read4.ok && !loose) throw new Error(`official/workflows/${folder}: ${read4.file}: ${read4.reason}`);
118132
- const parsed = parseWorkflowFile(folder, files[WORKFLOW_FILE] ?? "", WORKFLOW_FILE);
118133
- if ("problem" in parsed) throw new Error(parsed.problem);
118134
- const def = parsed.def;
118135
- for (const name of [...new Set([...def.previews, ...def.land, ...def.scheduled].map((h3) => h3.agent))].sort()) {
118136
- for (const [f2, text3] of Object.entries(agentFiles[name] ?? {})) files[`agents/${name}/${f2}`] = text3;
118253
+ if (regionHunks.length === 1) {
118254
+ if (hunk.abLength > 0) {
118255
+ const buffer = hunk.ab === "a" ? a2 : b2;
118256
+ results.push({
118257
+ stable: true,
118258
+ buffer: hunk.ab,
118259
+ bufferStart: hunk.abStart,
118260
+ bufferLength: hunk.abLength,
118261
+ bufferContent: buffer.slice(hunk.abStart, hunk.abStart + hunk.abLength)
118262
+ });
118263
+ }
118264
+ } else {
118265
+ let bounds = {
118266
+ a: [a2.length, -1, o3.length, -1],
118267
+ b: [b2.length, -1, o3.length, -1]
118268
+ };
118269
+ while (regionHunks.length) {
118270
+ hunk = regionHunks.shift();
118271
+ const oStart = hunk.oStart;
118272
+ const oEnd = oStart + hunk.oLength;
118273
+ const abStart = hunk.abStart;
118274
+ const abEnd = abStart + hunk.abLength;
118275
+ let b22 = bounds[hunk.ab];
118276
+ b22[0] = Math.min(abStart, b22[0]);
118277
+ b22[1] = Math.max(abEnd, b22[1]);
118278
+ b22[2] = Math.min(oStart, b22[2]);
118279
+ b22[3] = Math.max(oEnd, b22[3]);
118280
+ }
118281
+ const aStart = bounds.a[0] + (regionStart - bounds.a[2]);
118282
+ const aEnd = bounds.a[1] + (regionEnd - bounds.a[3]);
118283
+ const bStart = bounds.b[0] + (regionStart - bounds.b[2]);
118284
+ const bEnd = bounds.b[1] + (regionEnd - bounds.b[3]);
118285
+ let result = {
118286
+ stable: false,
118287
+ aStart,
118288
+ aLength: aEnd - aStart,
118289
+ aContent: a2.slice(aStart, aEnd),
118290
+ oStart: regionStart,
118291
+ oLength: regionEnd - regionStart,
118292
+ oContent: o3.slice(regionStart, regionEnd),
118293
+ bStart,
118294
+ bLength: bEnd - bStart,
118295
+ bContent: b2.slice(bStart, bEnd)
118296
+ };
118297
+ results.push(result);
118137
118298
  }
118138
- const checked = loose ? { ok: true } : checkWorkflowFiles(files, true);
118139
- if (!checked.ok) throw new Error(`official/workflows/${folder}: ${checked.file}: ${checked.reason}`);
118140
- if (!def.names?.zh && !loose) throw new Error(`official/workflows/${folder}/${WORKFLOW_FILE}: add its Chinese name under \`names: zh\``);
118141
- return {
118142
- id: officialId(folder),
118143
- name: def.name,
118144
- names: { en: def.name, ...def.names },
118145
- description: def.description,
118146
- when: def.when,
118147
- ...landsOf(def),
118148
- hash: hashOf(files),
118149
- files
118150
- };
118151
- });
118152
- }
118153
-
118154
- // ../cli/src/lib/cloud/tasks.ts
118155
- import fs23 from "node:fs";
118156
- import path27 from "node:path";
118157
- var TASK_ENV = "AI4KANBAN_TASK";
118158
- function workspaceTask() {
118159
- const id = process.env[TASK_ENV];
118160
- return id && id.trim() ? id.trim() : null;
118161
- }
118162
- function runnerProject(board) {
118163
- if (path27.basename(board) !== "kanban" || path27.basename(path27.dirname(board)) !== ".akb") return null;
118164
- const linked = linkedProject(board, path27.dirname(path27.dirname(board)));
118165
- return linked.ok ? linked.value : null;
118166
- }
118167
- function linkedProject(board, root2) {
118168
- const file3 = path27.join(root2, ".akb", "base.json");
118169
- if (!fs23.existsSync(file3)) return { ok: true, value: null };
118170
- try {
118171
- const base = JSON.parse(fs23.readFileSync(file3, "utf8"));
118172
- 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();
118173
- const projects = new Set(Object.keys(base.files ?? {}).flatMap((p2) => /^projects\/([^/]+)\//.exec(p2)?.[1] ?? []));
118174
- if (typeof base.project === "string") projects.add(base.project);
118175
- if (projects.size !== 1) throw new Error();
118176
- return { ok: true, value: [...projects][0] };
118177
- } catch {
118178
- return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
118299
+ currOffset = regionEnd;
118179
118300
  }
118301
+ advanceTo(o3.length);
118302
+ return results;
118180
118303
  }
118181
-
118182
- // ../cli/src/lib/file-memo.ts
118183
- import fs24 from "node:fs";
118184
- import path28 from "node:path";
118185
- function stamp(paths) {
118186
- const parts = [];
118187
- const visit = (p2) => {
118188
- let st2;
118189
- try {
118190
- st2 = fs24.statSync(p2, { bigint: true });
118191
- } catch {
118192
- parts.push(`${p2}:-`);
118193
- return;
118194
- }
118195
- if (!st2.isDirectory()) {
118196
- parts.push(`${p2}:${st2.mtimeNs}:${st2.size}`);
118197
- return;
118198
- }
118199
- parts.push(`${p2}/`);
118200
- let names2;
118201
- try {
118202
- names2 = fs24.readdirSync(p2).sort();
118203
- } catch {
118204
- return;
118205
- }
118206
- for (const name of names2) if (name !== "node_modules" && name !== ".git") visit(path28.join(p2, name));
118304
+ function diff3Merge(a2, o3, b2, options) {
118305
+ let defaults = {
118306
+ excludeFalseConflicts: true,
118307
+ stringSeparator: /\s+/
118207
118308
  };
118208
- for (const p2 of paths) visit(p2);
118209
- return parts.join("\n");
118210
- }
118211
- function copy(v) {
118212
- if (Array.isArray(v)) return v.map(copy);
118213
- if (v instanceof Map) return new Map([...v].map(([k2, x2]) => [k2, copy(x2)]));
118214
- if (v instanceof Set) return new Set([...v].map(copy));
118215
- if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
118216
- return Object.fromEntries(Object.entries(v).map(([k2, x2]) => [k2, copy(x2)]));
118309
+ options = Object.assign(defaults, options);
118310
+ if (typeof a2 === "string")
118311
+ a2 = a2.split(options.stringSeparator);
118312
+ if (typeof o3 === "string")
118313
+ o3 = o3.split(options.stringSeparator);
118314
+ if (typeof b2 === "string")
118315
+ b2 = b2.split(options.stringSeparator);
118316
+ let results = [];
118317
+ const regions = diff3MergeRegions(a2, o3, b2);
118318
+ let okBuffer = [];
118319
+ function flushOk() {
118320
+ if (okBuffer.length) {
118321
+ results.push({ ok: okBuffer });
118322
+ }
118323
+ okBuffer = [];
118217
118324
  }
118218
- return v;
118219
- }
118220
- var perTurn = false;
118221
- var turn = 0;
118222
- var turnEnding = false;
118223
- function currentTurn() {
118224
- if (!perTurn) return ++turn;
118225
- if (!turnEnding) {
118226
- turnEnding = true;
118227
- setImmediate(() => {
118228
- turn++;
118229
- turnEnding = false;
118230
- }).unref();
118325
+ function isFalseConflict(a22, b22) {
118326
+ if (a22.length !== b22.length)
118327
+ return false;
118328
+ for (let i = 0; i < a22.length; i++) {
118329
+ if (a22[i] !== b22[i])
118330
+ return false;
118331
+ }
118332
+ return true;
118231
118333
  }
118232
- return turn;
118233
- }
118234
- function memoByFiles(paths, read4) {
118235
- let last2 = null;
118236
- return () => {
118237
- const now = currentTurn();
118238
- if (last2?.turn !== now) {
118239
- const seen = stamp(paths());
118240
- if (last2?.stamp === seen) last2.turn = now;
118241
- else last2 = { stamp: seen, turn: now, value: read4() };
118334
+ regions.forEach((region) => {
118335
+ if (region.stable) {
118336
+ okBuffer.push(...region.bufferContent);
118337
+ } else {
118338
+ if (options.excludeFalseConflicts && isFalseConflict(region.aContent, region.bContent)) {
118339
+ okBuffer.push(...region.aContent);
118340
+ } else {
118341
+ flushOk();
118342
+ results.push({
118343
+ conflict: {
118344
+ a: region.aContent,
118345
+ aIndex: region.aStart,
118346
+ o: region.oContent,
118347
+ oIndex: region.oStart,
118348
+ b: region.bContent,
118349
+ bIndex: region.bStart
118350
+ }
118351
+ });
118352
+ }
118242
118353
  }
118243
- return copy(last2.value);
118244
- };
118354
+ });
118355
+ flushOk();
118356
+ return results;
118245
118357
  }
118246
118358
 
118247
- // ../cli/src/lib/agent/cloud-workflows.ts
118248
- var DEV = "AI4KANBAN_WORKFLOWS";
118249
- var root = () => path29.join(machineHome(), "workflows");
118250
- var safe = (name) => name.replace(/[^\w.@-]/g, "_");
118251
- var versionFile = (id, version) => path29.join(root(), "versions", `${safe(id)}@${version}.json`);
118252
- var listFile = (project) => path29.join(root(), "lists", `${safe(project)}.json`);
118253
- var pinFile = (task) => path29.join(root(), "tasks", `${safe(task)}.json`);
118254
- function readJson(file3) {
118255
- try {
118256
- return JSON.parse(fs25.readFileSync(file3, "utf8"));
118257
- } catch {
118258
- return null;
118259
- }
118260
- }
118261
- function writeJson(file3, value) {
118262
- fs25.mkdirSync(path29.dirname(file3), { recursive: true });
118263
- const tmp = `${file3}.${process.pid}.tmp`;
118264
- fs25.writeFileSync(tmp, `${JSON.stringify(value)}
118265
- `);
118266
- fs25.renameSync(tmp, file3);
118267
- }
118268
- var readVersion2 = (id, version) => readJson(versionFile(id, version));
118269
- function saveVersion(held4) {
118270
- const file3 = versionFile(held4.id, held4.version);
118271
- if (!fs25.existsSync(file3)) writeJson(file3, { id: held4.id, version: held4.version, name: held4.name, names: held4.names, files: held4.files });
118272
- }
118273
- function savePin(task, held4) {
118274
- saveVersion(held4);
118275
- writeJson(pinFile(task), { workflow: held4.id, version: held4.version });
118359
+ // ../cli/src/lib/shared/triage-files.ts
118360
+ var ITEM = /^triage\/(?:(dismissed|archived)\/)?([^/]+)\.md$/;
118361
+ function itemAt(path51) {
118362
+ const m = ITEM.exec(path51);
118363
+ if (!m) return null;
118364
+ return { state: m[1] === "dismissed" ? "dismissed" : m[1] === "archived" ? "carded" : "open", name: m[2] };
118276
118365
  }
118277
- var readPin = (task) => readJson(pinFile(task));
118278
- var boardProject = () => KANBAN ? runnerProject(KANBAN) : null;
118279
- var devFolder = () => process.env[DEV]?.trim() || "";
118280
- var flowOf = (held4) => {
118281
- const id = workflowName(held4.id);
118282
- const read4 = parseWorkflowFile(id, held4.files["WORKFLOW.md"] ?? "", `the \`${id}\` workflow`);
118283
- if ("problem" in read4) return null;
118284
- return { def: read4.def, cloudId: held4.id, version: held4.version, builtIn: held4.id.startsWith("wf_builtin_"), files: held4.files };
118285
- };
118286
- function readFlows() {
118287
- const dev = devFolder();
118288
- if (dev) {
118289
- return packOfficial(dev, true).flatMap((w2) => flowOf({ id: w2.id, version: 1, name: w2.name, names: w2.names, files: w2.files }) ?? []);
118290
- }
118291
- const project = boardProject();
118292
- if (!project || !readSession()) return [];
118293
- const list = readJson(listFile(project))?.workflows ?? [];
118294
- const flows2 = list.flatMap((w2) => {
118295
- const held4 = readVersion2(w2.id, w2.version);
118296
- return held4 ? flowOf(held4) ?? [] : [];
118366
+ function stampItem(content, fields) {
118367
+ const lines = content.split("\n");
118368
+ const close = lines.indexOf("---", 1);
118369
+ if (close < 0) return content;
118370
+ const kept4 = lines.slice(1, close).filter((line) => {
118371
+ const key = /^([a-z_]+):/.exec(line);
118372
+ return !key || fields[key[1]] === void 0;
118297
118373
  });
118298
- const task = workspaceTask();
118299
- const pin = task ? readPin(task) : null;
118300
- const pinned = pin && readVersion2(pin.workflow, pin.version);
118301
- const mine = pinned && flowOf(pinned);
118302
- if (!mine) return flows2;
118303
- return [mine, ...flows2.filter((f2) => f2.cloudId !== mine.cloudId)];
118304
- }
118305
- var sources = () => {
118306
- if (devFolder()) return [devFolder()];
118307
- const project = boardProject();
118308
- const task = workspaceTask();
118309
- return [sessionFile(), ...project ? [listFile(project)] : [], ...task ? [pinFile(task)] : []];
118310
- };
118311
- var flows = memoByFiles(sources, readFlows);
118312
- var cloudFlows = () => flows();
118313
- function cloudAgentFiles() {
118314
- const files = {};
118315
- const official = /* @__PURE__ */ new Set();
118316
- const owner = /* @__PURE__ */ new Map();
118317
- for (const flow of cloudFlows()) {
118318
- for (const [name, text3] of Object.entries(flow.files)) {
118319
- const at2 = /^agents\/([^/]+)\/(.+)$/.exec(name);
118320
- if (!at2) continue;
118321
- const [, agent, rest] = at2;
118322
- if (owner.has(agent) && owner.get(agent) !== flow.cloudId) continue;
118323
- owner.set(agent, flow.cloudId);
118324
- if (flow.builtIn) official.add(agent);
118325
- files[`${agent}/${rest}`] = text3;
118326
- }
118327
- }
118328
- return { files, official };
118374
+ const added = Object.entries(fields).flatMap(([k2, v]) => v === null ? [] : [`${k2}: ${yamlScalar(v)}`]);
118375
+ return ["---", ...kept4, ...added, ...lines.slice(close)].join("\n");
118329
118376
  }
118330
118377
 
118331
118378
  // ../cli/src/lib/preview-validation.ts
@@ -118437,7 +118484,10 @@ function sharedMemory(board) {
118437
118484
  }
118438
118485
  take(folder, text3, false);
118439
118486
  }
118440
- const matches = [...declared].flatMap(([agent, paths]) => paths.map((p2) => matcher(`agents/${agent}/${p2}`)));
118487
+ const matches = [
118488
+ ...[...declared].flatMap(([agent, paths]) => paths.map((p2) => matcher(`agents/${agent}/${p2}`))),
118489
+ ...cloudFlows().flatMap((f2) => (f2.def.memoryFiles?.workspace ?? []).map((p2) => matcher(`studios/${f2.def.id}/${p2}`)))
118490
+ ];
118441
118491
  return (name) => matches.some((m) => m(name));
118442
118492
  }
118443
118493
  function matcher(entry) {
@@ -118459,7 +118509,7 @@ function openTaskFolder(job, projectDir2) {
118459
118509
  markUsed(projectDir2);
118460
118510
  const board = path34.join(projectDir2, ".akb", "kanban");
118461
118511
  fs30.mkdirSync(board, { recursive: true });
118462
- return { task, cloudTask: task, board, cwd: projectDir2, project: job.project, number: job.number ?? null, workflow: job.workflow ?? job.flow?.workflow ?? null };
118512
+ return { task, cloudTask: task, board, cwd: projectDir2, project: job.project, number: job.number ?? null, studio: job.studio ?? job.flow?.studio ?? null };
118463
118513
  }
118464
118514
  function openAgentFolder(job, projectDir2) {
118465
118515
  if (!job.project || !job.agent) throw new Error("This job names no project.");
@@ -118468,13 +118518,13 @@ function openAgentFolder(job, projectDir2) {
118468
118518
  const board = path34.join(projectDir2, ".akb", "kanban");
118469
118519
  fs30.mkdirSync(board, { recursive: true });
118470
118520
  return {
118471
- task: `agent-${safe2(job.agent.workflow ? `${job.agent.workflow}-${job.agent.name}` : job.agent.name)}`,
118521
+ task: `agent-${safe2(job.agent.studio ? `${job.agent.studio}-${job.agent.name}` : job.agent.name)}`,
118472
118522
  cloudTask: job.agent.tasks?.[0]?.id ?? null,
118473
118523
  board,
118474
118524
  cwd: projectDir2,
118475
118525
  project: job.project,
118476
118526
  number: null,
118477
- workflow: job.agent.workflow ?? null
118527
+ studio: job.agent.studio ?? null
118478
118528
  };
118479
118529
  }
118480
118530
  function openDiscussionFolder(job, projectDir2) {
@@ -118483,9 +118533,9 @@ function openDiscussionFolder(job, projectDir2) {
118483
118533
  markUsed(projectDir2);
118484
118534
  const board = path34.join(projectDir2, ".akb", "kanban");
118485
118535
  fs30.mkdirSync(board, { recursive: true });
118486
- return { task: "discussion", cloudTask: null, board, cwd: projectDir2, project: job.project, number: null, workflow: null };
118536
+ return { task: "discussion", cloudTask: null, board, cwd: projectDir2, project: job.project, number: null, studio: null };
118487
118537
  }
118488
- var boardFolder = (ws) => ({ task: "board", cloudTask: null, board: ws.board, cwd: ws.cwd, project: ws.project, number: null, workflow: null });
118538
+ var boardFolder = (ws) => ({ task: "board", cloudTask: null, board: ws.board, cwd: ws.cwd, project: ws.project, number: null, studio: null });
118489
118539
  function keptBoard(cwd) {
118490
118540
  const board = path34.join(cwd, ".akb", "kanban");
118491
118541
  const base = readBase({ cwd });
@@ -118652,26 +118702,26 @@ function pullTools(ws, record, files) {
118652
118702
  record.tools = { skills, mcp };
118653
118703
  }
118654
118704
  var mcpServersOf = (ws) => readRecord(ws).tools?.mcp ?? {};
118655
- async function workflowFiles(ws) {
118656
- const workflow = ws.workflow;
118705
+ async function studioFiles(ws) {
118706
+ const studio = ws.studio;
118657
118707
  if (ws.cloudTask && ws.cloudTask === ws.task) {
118658
118708
  const pin = readPin(ws.cloudTask);
118659
- const held4 = pin && readVersion2(pin.workflow, pin.version);
118709
+ const held4 = pin && readVersion2(pin.studio, pin.version);
118660
118710
  if (held4) return { ok: true, value: held4.files };
118661
- const read5 = await readTaskWorkflow(ws.cloudTask);
118711
+ const read5 = await readTaskStudio(ws.cloudTask);
118662
118712
  if (!read5.ok) return read5;
118663
- savePin(ws.cloudTask, { id: read5.value.workflow, version: read5.value.version, name: read5.value.name ?? read5.value.workflow, files: read5.value.files });
118713
+ savePin(ws.cloudTask, { id: read5.value.studio, version: read5.value.version, name: read5.value.name ?? read5.value.studio, files: read5.value.files });
118664
118714
  return { ok: true, value: read5.value.files };
118665
118715
  }
118666
- const read4 = await readWorkflow(workflow);
118716
+ const read4 = await readStudio(studio);
118667
118717
  if (!read4.ok) return read4;
118668
- saveVersion({ id: workflow, version: read4.value.version, name: read4.value.name ?? workflow, files: read4.value.files });
118718
+ saveVersion({ id: studio, version: read4.value.version, name: read4.value.name ?? studio, files: read4.value.files });
118669
118719
  return { ok: true, value: read4.value.files };
118670
118720
  }
118671
- async function pullWorkflow(ws, record) {
118672
- if (ws.workflow) {
118673
- record.builtin = ws.workflow.startsWith("wf_builtin_");
118674
- const files = await workflowFiles(ws);
118721
+ async function pullStudio(ws, record) {
118722
+ if (ws.studio) {
118723
+ record.builtin = ws.studio.startsWith("wf_builtin_");
118724
+ const files = await studioFiles(ws);
118675
118725
  if (!files.ok && files.code !== "not_found") return files;
118676
118726
  if (files.ok) pullTools(ws, record, files.value);
118677
118727
  }
@@ -118694,8 +118744,8 @@ function dropPlacedAgents(ws) {
118694
118744
  fs30.rmSync(agentsRecord(ws), { force: true });
118695
118745
  }
118696
118746
  function pullDraftAgents(ws, record) {
118697
- if (ws.workflow !== BUILDER) return;
118698
- const root2 = path34.join(ws.board, "workflows", draftFolder(ws.task), "agents");
118747
+ if (ws.studio !== BUILDER) return;
118748
+ const root2 = path34.join(ws.board, "studios", draftFolder(ws.task), "agents");
118699
118749
  record.agents ??= {};
118700
118750
  for (const name of filesUnder(root2)) {
118701
118751
  const text3 = fs30.readFileSync(path34.join(root2, name));
@@ -118815,8 +118865,8 @@ async function readCloud(ws) {
118815
118865
  for (const p2 of localFiles(ws, base)) if (!keepDraft.has(p2) && !view.has(p2) && !first(p2)) fs30.rmSync(path34.join(ws.board, p2), { force: true });
118816
118866
  reset(view);
118817
118867
  const record = readRecord(ws);
118818
- const workflow = await pullWorkflow(ws, record);
118819
- if (!workflow.ok) return workflow;
118868
+ const studio = await pullStudio(ws, record);
118869
+ if (!studio.ok) return studio;
118820
118870
  pullDraftAgents(ws, record);
118821
118871
  reset(viewOf(ws, base, sharedMemory(ws.board)));
118822
118872
  const assets = await pullAssets(ws, record, assetsOf(assetsListOf(ws, base)));
@@ -119135,7 +119185,7 @@ function proposeItems(ws, base) {
119135
119185
  const said = (key) => new RegExp(`^${key}:`, "m").test(content.split(/\n---/)[0] ?? "");
119136
119186
  const fields = {
119137
119187
  ...ws.cloudTask && !said("source_task") ? { source_task: ws.cloudTask } : {},
119138
- ...ws.workflow && !said("workflow") ? { workflow: workflowName(ws.workflow) } : {}
119188
+ ...ws.studio && !said("studio") ? { studio: studioName(ws.studio) } : {}
119139
119189
  };
119140
119190
  const stamped = Object.keys(fields).length ? stampItem(content, fields) : content;
119141
119191
  if (stamped !== content) write(file3, stamped);
@@ -119733,7 +119783,7 @@ function parseFrontmatter(text3) {
119733
119783
  delete meta.release;
119734
119784
  delete meta.schedule;
119735
119785
  delete meta.roi;
119736
- meta.workflow = typeof meta.workflow === "string" && meta.workflow.trim() ? meta.workflow.trim() : "";
119786
+ meta.studio = typeof meta.studio === "string" && meta.studio.trim() ? meta.studio.trim() : "";
119737
119787
  meta.triage = typeof meta.triage === "string" ? meta.triage.trim() : "";
119738
119788
  meta.source = (Array.isArray(meta.source) ? meta.source : typeof meta.source === "string" ? [meta.source] : []).map((ref) => String(ref).trim()).filter(Boolean);
119739
119789
  delete meta.phases;
@@ -119807,7 +119857,7 @@ ${item.text.trim()}
119807
119857
  function writeItem(dir, item, fields = {}) {
119808
119858
  fs34.mkdirSync(dir, { recursive: true });
119809
119859
  const name = freeName(dir, item.title);
119810
- fs34.writeFileSync(path37.join(dir, name), itemText(item, item.workflow ? { workflow: workflowName(item.workflow), ...fields } : fields));
119860
+ fs34.writeFileSync(path37.join(dir, name), itemText(item, item.studio ? { studio: studioName(item.studio), ...fields } : fields));
119811
119861
  return name;
119812
119862
  }
119813
119863
  function layOut(board, rejections) {
@@ -119875,19 +119925,19 @@ function installCommitHook(root2, _board) {
119875
119925
  // src/built.ts
119876
119926
  import fs36 from "node:fs";
119877
119927
  import path39 from "node:path";
119878
- var isBuilder = (ws) => ws.workflow === BUILDER;
119879
- var draftDir = (ws) => path39.join(ws.board, "workflows", draftFolder(ws.task));
119880
- var draftLine = (ws) => `<!-- workflow folder: ${path39.relative(ws.cwd, draftDir(ws)).split(path39.sep).join("/")}/ -->`;
119928
+ var isBuilder = (ws) => ws.studio === BUILDER;
119929
+ var draftDir = (ws) => path39.join(ws.board, "studios", draftFolder(ws.task));
119930
+ var draftLine = (ws) => `<!-- studio folder: ${path39.relative(ws.cwd, draftDir(ws)).split(path39.sep).join("/")}/ -->`;
119881
119931
  var skeleton = (name) => ["---", `name: ${/\s#/.test(name) ? JSON.stringify(name) : yamlScalar(name)}`, "needsArtifact: false", "---", ""].join("\n");
119882
119932
  async function placeDraft(ws, read4) {
119883
119933
  const dir = draftDir(ws);
119884
- if (fs36.existsSync(path39.join(dir, WORKFLOW_FILE))) return { ok: true, value: void 0 };
119934
+ if (fs36.existsSync(path39.join(dir, STUDIO_FILE))) return { ok: true, value: void 0 };
119885
119935
  const task = await read4.readTask(ws.task);
119886
119936
  if (!task.ok) return task;
119887
- let files = { [WORKFLOW_FILE]: skeleton(task.value.title.trim() || "Untitled") };
119888
- const changes = task.value.context?.workflow;
119937
+ let files = { [STUDIO_FILE]: skeleton(task.value.title.trim() || "Untitled") };
119938
+ const changes = task.value.context?.studio;
119889
119939
  if (changes) {
119890
- const held4 = await read4.readWorkflow(changes);
119940
+ const held4 = await read4.readStudio(changes);
119891
119941
  if (!held4.ok) return held4;
119892
119942
  files = held4.value.files;
119893
119943
  }
@@ -119908,16 +119958,16 @@ function draftBase(ws) {
119908
119958
  }
119909
119959
  }
119910
119960
  var named = (def) => [...new Set([...def.previews, ...def.land, ...def.scheduled].map((h3) => h3.agent))];
119911
- async function builtWorkflow(ws, akb) {
119961
+ async function builtStudio(ws, akb) {
119912
119962
  if (!isBuilder(ws)) return null;
119913
119963
  const id = draftFolder(ws.task);
119914
119964
  const dir = draftDir(ws);
119915
119965
  let source = "";
119916
119966
  try {
119917
- source = fs36.readFileSync(path39.join(dir, WORKFLOW_FILE), "utf8");
119967
+ source = fs36.readFileSync(path39.join(dir, STUDIO_FILE), "utf8");
119918
119968
  } catch {
119919
119969
  }
119920
- const read4 = parseWorkflowFile(id, source, `workflows/${id}/${WORKFLOW_FILE}`);
119970
+ const read4 = parseStudioFile(id, source, `studios/${id}/${STUDIO_FILE}`);
119921
119971
  const names2 = "def" in read4 ? named(read4.def) : [];
119922
119972
  const agents = path39.join(dir, "agents");
119923
119973
  if ("def" in read4) {
@@ -120237,24 +120287,24 @@ async function scheduledEnv(ws, deps) {
120237
120287
  console.error(`runner: scheduled agents not read: ${read4.error}`);
120238
120288
  return {};
120239
120289
  }
120240
- const names2 = read4.value.agents.filter((a2) => a2.workflow).map((a2) => a2.name);
120290
+ const names2 = read4.value.agents.filter((a2) => a2.studio).map((a2) => a2.name);
120241
120291
  return { [SCHEDULED_AGENTS_ENV]: [...new Set(names2)].join(",") };
120242
120292
  }
120243
120293
  async function runAgent(job, ws, deps, io) {
120244
120294
  const since = Date.now();
120245
120295
  const failed = await setUp(job, ws, deps, io);
120246
120296
  if (failed) return { ok: false, reason: failed };
120247
- const { name, workflow, tasks } = job.agent;
120297
+ const { name, studio, tasks } = job.agent;
120248
120298
  if (name === "review-dismissals") {
120249
120299
  const { runs: runs2, failure: failure2 } = await reviewRejections(job, ws, deps, io);
120250
120300
  if (io.lost()) return { ok: false, reason: "" };
120251
120301
  return failure2 ? { ok: false, reason: failure2 } : { ok: true, report: spentBy(runs2, job) };
120252
120302
  }
120253
120303
  if (name === "reflect" && !tasks?.length) return { ok: true, report: {} };
120254
- const args = workflow ? ["raw", "agent", "run", workflowName(workflow), name] : name === "reflect" ? ["raw", "reflect", "--cards", ...tasks.map((t2) => String(t2.number))] : ["raw", ...name === "prune-memory" ? ["memory", "prune"] : [name]];
120304
+ const args = studio ? ["raw", "agent", "run", studioName(studio), name] : name === "reflect" ? ["raw", "reflect", "--cards", ...tasks.map((t2) => String(t2.number))] : ["raw", ...name === "prune-memory" ? ["memory", "prune"] : [name]];
120255
120305
  const akb = boardAkb(job, ws, deps, io, ws.cloudTask ?? void 0);
120256
120306
  await akb(["raw", "run", "list", "--all", "--json"]);
120257
- const env2 = name === "reflect" && !workflow ? await scheduledEnv(ws, deps) : void 0;
120307
+ const env2 = name === "reflect" && !studio ? await scheduledEnv(ws, deps) : void 0;
120258
120308
  const ran = await akb([...args, "--follow", "--events", "--json"], true, env2);
120259
120309
  if (io.lost()) return { ok: false, reason: "" };
120260
120310
  const answer = answerOf2(ran);
@@ -120328,8 +120378,8 @@ ${draftLine(ws)}
120328
120378
  "create",
120329
120379
  "--title",
120330
120380
  title,
120331
- "--workflow",
120332
- workflowName(flow.workflow),
120381
+ "--studio",
120382
+ studioName(flow.studio),
120333
120383
  "--body-file",
120334
120384
  body,
120335
120385
  "--id",
@@ -121435,7 +121485,7 @@ async function runClaimed(job, deps, track, keep2, lease, replyStream) {
121435
121485
  discussed = board.board;
121436
121486
  }
121437
121487
  if (job.discussion) {
121438
- const wrote = recovering && fs42.existsSync(goalsFileOf(job)) ? { file: goalsFileOf(job) } : await writeGoals({ ...job, discussion: job.discussion }, deps.api.listWorkflows);
121488
+ const wrote = recovering && fs42.existsSync(goalsFileOf(job)) ? { file: goalsFileOf(job) } : await writeGoals({ ...job, discussion: job.discussion }, deps.api.listStudios);
121439
121489
  if ("error" in wrote) throw new Error(wrote.error);
121440
121490
  goalFile = wrote.file;
121441
121491
  }
@@ -121848,8 +121898,8 @@ async function finish(deps, id, lease, outcome, reason = "", report2) {
121848
121898
  }
121849
121899
  async function sendBack(deps, id, lease, ws, said, landed = () => {
121850
121900
  }) {
121851
- const built = await builtWorkflow(ws, deps.akb);
121852
- const report2 = built ? { ...said, workflow: { files: built, base: draftBase(ws) } } : said;
121901
+ const built = await builtStudio(ws, deps.akb);
121902
+ const report2 = built ? { ...said, studio: { files: built, base: draftBase(ws) } } : said;
121853
121903
  const pushed = await whileOffline(deps, id, lease, () => push(ws, { id, machineId: deps.machineId }));
121854
121904
  if (!pushed) return;
121855
121905
  if (pushed.ok) {
@@ -122117,6 +122167,7 @@ function startRunner(options) {
122117
122167
  try {
122118
122168
  sweepAkb();
122119
122169
  await sweepCache(registration.machineId);
122170
+ await sweepStudios();
122120
122171
  } catch (e2) {
122121
122172
  console.error(`runner: the cache was not cleaned: ${e2 instanceof Error ? e2.message : String(e2)}`);
122122
122173
  } finally {