wildcrane-runner 0.6.43 → 0.6.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runner.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.43 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.45 — 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;
@@ -111129,10 +111129,10 @@ async function refresh() {
111129
111129
  const now = readSession();
111130
111130
  if (!now) return { ok: false, reason: "signed-out" };
111131
111131
  if (!expiringSoon(now)) return { ok: true, token: now.accessToken, session: now };
111132
- const { supabaseUrl, anonKey } = cloudEndpoints();
111132
+ const { api, anonKey } = cloudEndpoints();
111133
111133
  let response;
111134
111134
  try {
111135
- response = await fetch(`${supabaseUrl}/auth/v1/token?grant_type=refresh_token`, {
111135
+ response = await fetch(`${api}/auth/v1/token?grant_type=refresh_token`, {
111136
111136
  method: "POST",
111137
111137
  headers: { apikey: anonKey, "content-type": "application/json" },
111138
111138
  body: JSON.stringify({ refresh_token: now.refreshToken })
@@ -111406,9 +111406,9 @@ function status(line) {
111406
111406
  }
111407
111407
 
111408
111408
  // src/protocol.ts
111409
- var VERSION = true ? "0.6.43" : "0.0.0";
111410
- var AKB_VERSION = true ? "0.11.37" : "0.0.0";
111411
- var AKB_CONTRACT = true ? 9 : 0;
111409
+ var VERSION = true ? "0.6.45" : "0.0.0";
111410
+ var AKB_VERSION = true ? "0.11.39" : "0.0.0";
111411
+ var AKB_CONTRACT = true ? 10 : 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.37",
113057
- akbContract: 9,
113056
+ version: "0.11.39",
113057
+ akbContract: 10,
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
 
@@ -115882,8 +115882,8 @@ function connectCloudLive(handlers) {
115882
115882
  if (!cloudConfigured() || !session || !handlers.topic) return null;
115883
115883
  const Socket = globalThis.WebSocket;
115884
115884
  if (!Socket) return null;
115885
- const { supabaseUrl, anonKey } = cloudEndpoints();
115886
- const url = `${supabaseUrl.replace(/^http/, "ws")}/realtime/v1/websocket?apikey=${encodeURIComponent(anonKey)}&vsn=${VSN}`;
115885
+ const { api, anonKey } = cloudEndpoints();
115886
+ const url = `${api.replace(/^http/, "ws")}/realtime/v1/websocket?apikey=${encodeURIComponent(anonKey)}&vsn=${VSN}`;
115887
115887
  const topic = `realtime:${handlers.topic}`;
115888
115888
  let socket = null;
115889
115889
  let heartbeat = null;
@@ -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';
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";
117013
116438
 
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);
117017
-
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
  }
@@ -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);
@@ -117966,12 +116843,12 @@ function parseWorkflowFile(id, source, from) {
117966
116843
  };
117967
116844
  }
117968
116845
 
117969
- // ../cli/src/lib/agent/workflow-folder.ts
117970
- import fs21 from "node:fs";
117971
- import path25 from "node:path";
116846
+ // ../cli/src/lib/agent/studio-folder.ts
116847
+ import fs16 from "node:fs";
116848
+ import path20 from "node:path";
117972
116849
 
117973
- // ../cli/src/lib/shared/workflow-files.ts
117974
- var WORKFLOW_FILE = "WORKFLOW.md";
116850
+ // ../cli/src/lib/shared/studio-files.ts
116851
+ var STUDIO_FILE = "STUDIO.md";
117975
116852
  var MCP_FILE = "mcp.json";
117976
116853
  var VERSION_FILE = "version.json";
117977
116854
  var KB = 1024;
@@ -118006,7 +116883,7 @@ function mcpProblem(text3) {
118006
116883
  }
118007
116884
  return null;
118008
116885
  }
118009
- function checkWorkflowFiles(value, official = false) {
116886
+ function checkStudioFiles(value, official = false) {
118010
116887
  const read4 = inspect(value, official);
118011
116888
  const first = read4.problems[0];
118012
116889
  return first ? { ok: false, ...first } : { ok: true, def: read4.def, files: read4.files };
@@ -118037,7 +116914,7 @@ function inspect(value, official) {
118037
116914
  if (size > FILE_LIMITS.file) return fail(file3, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
118038
116915
  total += size;
118039
116916
  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;
116917
+ if (file3 === STUDIO_FILE) continue;
118041
116918
  if (official && file3 === MCP_FILE) {
118042
116919
  const problem = mcpProblem(text3);
118043
116920
  if (problem) fail(file3, problem);
@@ -118049,283 +116926,1443 @@ function inspect(value, official) {
118049
116926
  else skills.add(file3.split("/")[1]);
118050
116927
  continue;
118051
116928
  }
118052
- const at2 = folderPath(file3, "agents");
118053
- if (!at2) {
118054
- fail(file3, `is neither ${WORKFLOW_FILE} nor inside agents/<name>/`);
118055
- continue;
116929
+ const at2 = folderPath(file3, "agents");
116930
+ if (!at2) {
116931
+ fail(file3, `is neither ${STUDIO_FILE} nor inside agents/<name>/`);
116932
+ continue;
116933
+ }
116934
+ if (!folders2.has(at2[0])) folders2.set(at2[0], /* @__PURE__ */ new Map());
116935
+ folders2.get(at2[0]).set(at2[1], text3);
116936
+ }
116937
+ for (const name of skills) {
116938
+ if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
116939
+ }
116940
+ const source = files[STUDIO_FILE];
116941
+ const read4 = typeof source === "string" ? parseStudioFile("studio", source, STUDIO_FILE) : null;
116942
+ if (!read4) fail(STUDIO_FILE, "is missing");
116943
+ else if ("problem" in read4) fail(STUDIO_FILE, read4.problem.replace(`${STUDIO_FILE}: `, ""));
116944
+ const agents = /* @__PURE__ */ new Map();
116945
+ for (const [name, own2] of folders2) {
116946
+ const from = `agents/${name}/AGENT.md`;
116947
+ const text3 = own2.get("AGENT.md");
116948
+ if (text3 === void 0) {
116949
+ fail(from, "is missing");
116950
+ continue;
116951
+ }
116952
+ const parsed = parseSpecAgent(text3, from, (p2) => own2.get(p2) ?? null, false, () => [...own2.keys()].filter((p2) => p2 !== "AGENT.md"));
116953
+ if ("problem" in parsed) fail(from, parsed.problem.replace(`${from}: `, ""));
116954
+ else if (parsed.agent.name !== name) fail(from, `calls itself \`${parsed.agent.name}\`; it must match its folder`);
116955
+ else agents.set(name, parsed.agent);
116956
+ }
116957
+ if (!read4 || "problem" in read4) return { problems };
116958
+ const def = read4.def;
116959
+ const named2 = [
116960
+ ...def.previews.map((h3) => [h3.agent, "it previews with"]),
116961
+ ...def.land.map((h3) => [h3.agent, "it lands with"]),
116962
+ ...def.scheduled.map((s) => [s.agent, "it schedules"])
116963
+ ];
116964
+ for (const [name, why2] of named2) {
116965
+ if (!agents.has(name) && !folders2.has(name)) fail(STUDIO_FILE, `${why2} \`${name}\`, which has no agents/${name}/AGENT.md`);
116966
+ }
116967
+ return { problems, def, files };
116968
+ }
116969
+
116970
+ // ../cli/src/lib/agent/studio-folder.ts
116971
+ var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
116972
+ function filesOf(dir, base = dir) {
116973
+ return fs16.readdirSync(dir, { withFileTypes: true }).filter((e2) => !e2.name.startsWith(".")).flatMap((e2) => {
116974
+ const full = path20.join(dir, e2.name);
116975
+ return e2.isDirectory() ? filesOf(full, base) : [path20.relative(base, full).split(path20.sep).join("/")];
116976
+ });
116977
+ }
116978
+ function readStudioFile(dir, file3) {
116979
+ const full = path20.join(dir, file3);
116980
+ return isAboutFile(file3) && !file3.endsWith(".md") ? `data:${MIME[path20.extname(file3)]};base64,${fs16.readFileSync(full).toString("base64")}` : fs16.readFileSync(full, "utf8");
116981
+ }
116982
+ var readStudioFolder = (dir) => Object.fromEntries(filesOf(dir).sort().map((f2) => [f2, readStudioFile(dir, f2)]));
116983
+
116984
+ // ../official/pack.ts
116985
+ var OFFICIAL = path21.dirname(fileURLToPath2(import.meta.url));
116986
+ var dirs = (dir) => fs17.readdirSync(dir, { withFileTypes: true }).filter((e2) => e2.isDirectory()).map((e2) => e2.name).sort();
116987
+ var hashOf = (files) => crypto2.createHash("sha256").update(hashInput(files)).digest("hex");
116988
+ function packOfficial(root2 = OFFICIAL, loose = false) {
116989
+ const agentsDir = path21.join(root2, "agents");
116990
+ const agentFiles = Object.fromEntries(dirs(agentsDir).map((name) => {
116991
+ const dir = path21.join(agentsDir, name);
116992
+ return [name, readStudioFolder(dir)];
116993
+ }));
116994
+ for (const [name, own2] of Object.entries(loose ? {} : agentFiles)) {
116995
+ const read4 = parseSpecAgent(own2["AGENT.md"] ?? "", `official/agents/${name}/AGENT.md`, (p2) => own2[p2] ?? null, true);
116996
+ if ("problem" in read4) throw new Error(read4.problem);
116997
+ }
116998
+ const studiosDir = path21.join(root2, "studios");
116999
+ return dirs(studiosDir).map((folder) => {
117000
+ const dir = path21.join(studiosDir, folder);
117001
+ const files = {};
117002
+ for (const f2 of filesOf(dir).sort()) {
117003
+ if (f2 === STUDIO_FILE || f2 === MCP_FILE || f2.startsWith("skills/") || isAboutFile(f2)) files[f2] = readStudioFile(dir, f2);
117004
+ }
117005
+ const read4 = checkStudioFiles({ [STUDIO_FILE]: files[STUDIO_FILE], ...Object.fromEntries(
117006
+ Object.entries(agentFiles).flatMap(([name, own2]) => Object.entries(own2).map(([f2, t2]) => [`agents/${name}/${f2}`, t2]))
117007
+ ) });
117008
+ if (!read4.ok && !loose) throw new Error(`official/studios/${folder}: ${read4.file}: ${read4.reason}`);
117009
+ const parsed = parseStudioFile(folder, files[STUDIO_FILE] ?? "", STUDIO_FILE);
117010
+ if ("problem" in parsed) throw new Error(parsed.problem);
117011
+ const def = parsed.def;
117012
+ for (const name of [...new Set([...def.previews, ...def.land, ...def.scheduled].map((h3) => h3.agent))].sort()) {
117013
+ for (const [f2, text3] of Object.entries(agentFiles[name] ?? {})) files[`agents/${name}/${f2}`] = text3;
117014
+ }
117015
+ const checked = loose ? { ok: true } : checkStudioFiles(files, true);
117016
+ if (!checked.ok) throw new Error(`official/studios/${folder}: ${checked.file}: ${checked.reason}`);
117017
+ if (!def.names?.zh && !loose) throw new Error(`official/studios/${folder}/${STUDIO_FILE}: add its Chinese name under \`names: zh\``);
117018
+ return {
117019
+ id: officialId(folder),
117020
+ name: def.name,
117021
+ names: { en: def.name, ...def.names },
117022
+ description: def.description,
117023
+ when: def.when,
117024
+ ...landsOf(def),
117025
+ hash: hashOf(files),
117026
+ files
117027
+ };
117028
+ });
117029
+ }
117030
+
117031
+ // ../cli/src/lib/cloud/tasks.ts
117032
+ import fs18 from "node:fs";
117033
+ import path22 from "node:path";
117034
+ var TASK_ENV = "AI4KANBAN_TASK";
117035
+ function workspaceTask() {
117036
+ const id = process.env[TASK_ENV];
117037
+ return id && id.trim() ? id.trim() : null;
117038
+ }
117039
+ function runnerProject(board) {
117040
+ if (path22.basename(board) !== "kanban" || path22.basename(path22.dirname(board)) !== ".akb") return null;
117041
+ const linked = linkedProject(board, path22.dirname(path22.dirname(board)));
117042
+ return linked.ok ? linked.value : null;
117043
+ }
117044
+ function linkedProject(board, root2) {
117045
+ const file3 = path22.join(root2, ".akb", "base.json");
117046
+ if (!fs18.existsSync(file3)) return { ok: true, value: null };
117047
+ try {
117048
+ const base = JSON.parse(fs18.readFileSync(file3, "utf8"));
117049
+ 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();
117050
+ const projects = new Set(Object.keys(base.files ?? {}).flatMap((p2) => /^projects\/([^/]+)\//.exec(p2)?.[1] ?? []));
117051
+ if (typeof base.project === "string") projects.add(base.project);
117052
+ if (projects.size !== 1) throw new Error();
117053
+ return { ok: true, value: [...projects][0] };
117054
+ } catch {
117055
+ return { ok: false, error: "The project link is invalid or names multiple projects.", code: "invalid-link" };
117056
+ }
117057
+ }
117058
+
117059
+ // ../cli/src/lib/file-memo.ts
117060
+ import fs19 from "node:fs";
117061
+ import path23 from "node:path";
117062
+ function stamp(paths) {
117063
+ const parts = [];
117064
+ const visit = (p2) => {
117065
+ let st2;
117066
+ try {
117067
+ st2 = fs19.statSync(p2, { bigint: true });
117068
+ } catch {
117069
+ parts.push(`${p2}:-`);
117070
+ return;
117071
+ }
117072
+ if (!st2.isDirectory()) {
117073
+ parts.push(`${p2}:${st2.mtimeNs}:${st2.size}`);
117074
+ return;
117075
+ }
117076
+ parts.push(`${p2}/`);
117077
+ let names2;
117078
+ try {
117079
+ names2 = fs19.readdirSync(p2).sort();
117080
+ } catch {
117081
+ return;
117082
+ }
117083
+ for (const name of names2) if (name !== "node_modules" && name !== ".git") visit(path23.join(p2, name));
117084
+ };
117085
+ for (const p2 of paths) visit(p2);
117086
+ return parts.join("\n");
117087
+ }
117088
+ function copy(v) {
117089
+ if (Array.isArray(v)) return v.map(copy);
117090
+ if (v instanceof Map) return new Map([...v].map(([k2, x2]) => [k2, copy(x2)]));
117091
+ if (v instanceof Set) return new Set([...v].map(copy));
117092
+ if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
117093
+ return Object.fromEntries(Object.entries(v).map(([k2, x2]) => [k2, copy(x2)]));
117094
+ }
117095
+ return v;
117096
+ }
117097
+ var perTurn = false;
117098
+ var turn = 0;
117099
+ var turnEnding = false;
117100
+ function currentTurn() {
117101
+ if (!perTurn) return ++turn;
117102
+ if (!turnEnding) {
117103
+ turnEnding = true;
117104
+ setImmediate(() => {
117105
+ turn++;
117106
+ turnEnding = false;
117107
+ }).unref();
117108
+ }
117109
+ return turn;
117110
+ }
117111
+ function memoByFiles(paths, read4) {
117112
+ let last2 = null;
117113
+ return () => {
117114
+ const now = currentTurn();
117115
+ if (last2?.turn !== now) {
117116
+ const seen = stamp(paths());
117117
+ if (last2?.stamp === seen) last2.turn = now;
117118
+ else last2 = { stamp: seen, turn: now, value: read4() };
117119
+ }
117120
+ return copy(last2.value);
117121
+ };
117122
+ }
117123
+
117124
+ // ../cli/src/lib/agent/cloud-studios.ts
117125
+ var DEV = "AI4KANBAN_STUDIOS";
117126
+ var root = () => path24.join(machineHome(), "studios");
117127
+ var safe = (name) => name.replace(/[^\w.@-]/g, "_");
117128
+ var versionFile = (id, version) => path24.join(root(), "versions", `${safe(id)}@${version}.json`);
117129
+ var listFile = (project) => path24.join(root(), "lists", `${safe(project)}.json`);
117130
+ var pinFile = (task) => path24.join(root(), "tasks", `${safe(task)}.json`);
117131
+ function readJson(file3) {
117132
+ try {
117133
+ return JSON.parse(fs20.readFileSync(file3, "utf8"));
117134
+ } catch {
117135
+ return null;
117136
+ }
117137
+ }
117138
+ function writeJson(file3, value) {
117139
+ fs20.mkdirSync(path24.dirname(file3), { recursive: true });
117140
+ const tmp = `${file3}.${process.pid}.tmp`;
117141
+ fs20.writeFileSync(tmp, `${JSON.stringify(value)}
117142
+ `);
117143
+ fs20.renameSync(tmp, file3);
117144
+ }
117145
+ var readVersion2 = (id, version) => readJson(versionFile(id, version));
117146
+ function saveVersion(held4) {
117147
+ const file3 = versionFile(held4.id, held4.version);
117148
+ if (!fs20.existsSync(file3)) writeJson(file3, { id: held4.id, version: held4.version, name: held4.name, names: held4.names, files: held4.files });
117149
+ }
117150
+ function savePin(task, held4) {
117151
+ saveVersion(held4);
117152
+ writeJson(pinFile(task), { studio: held4.id, version: held4.version });
117153
+ }
117154
+ var readPin = (task) => readJson(pinFile(task));
117155
+ var jsonIn = (dir) => {
117156
+ try {
117157
+ return fs20.readdirSync(path24.join(root(), dir)).filter((f2) => f2.endsWith(".json"));
117158
+ } catch {
117159
+ return [];
117160
+ }
117161
+ };
117162
+ async function sweepVersions(ended2) {
117163
+ const keep2 = /* @__PURE__ */ new Set();
117164
+ const held4 = (id, version) => keep2.add(path24.basename(versionFile(id, version)));
117165
+ for (const file3 of jsonIn("tasks")) {
117166
+ const at2 = path24.join(root(), "tasks", file3);
117167
+ const pin = readJson(at2);
117168
+ if (!pin || await ended2(file3.slice(0, -".json".length))) fs20.rmSync(at2, { force: true });
117169
+ else held4(pin.studio, pin.version);
117170
+ }
117171
+ for (const file3 of jsonIn("lists")) {
117172
+ for (const w2 of readJson(path24.join(root(), "lists", file3))?.studios ?? []) held4(w2.id, w2.version);
117173
+ }
117174
+ const versions = jsonIn("versions");
117175
+ const newest2 = /* @__PURE__ */ new Map();
117176
+ const parts = (file3) => ({ id: file3.slice(0, file3.lastIndexOf("@")), version: Number(file3.slice(file3.lastIndexOf("@") + 1, -".json".length)) });
117177
+ for (const file3 of versions) {
117178
+ const { id, version } = parts(file3);
117179
+ if (version > (newest2.get(id) ?? -1)) newest2.set(id, version);
117180
+ }
117181
+ const gone = versions.filter((file3) => !keep2.has(file3) && newest2.get(parts(file3).id) !== parts(file3).version);
117182
+ for (const file3 of gone) fs20.rmSync(path24.join(root(), "versions", file3), { force: true });
117183
+ return gone;
117184
+ }
117185
+ var boardProject = () => KANBAN ? runnerProject(KANBAN) : null;
117186
+ var devFolder = () => process.env[DEV]?.trim() || "";
117187
+ var flowOf = (held4) => {
117188
+ const id = studioName(held4.id);
117189
+ const read4 = parseStudioFile(id, held4.files["STUDIO.md"] ?? "", `the \`${id}\` studio`);
117190
+ if ("problem" in read4) return null;
117191
+ return { def: read4.def, cloudId: held4.id, version: held4.version, builtIn: held4.id.startsWith("wf_builtin_"), files: held4.files };
117192
+ };
117193
+ function readFlows() {
117194
+ const dev = devFolder();
117195
+ if (dev) {
117196
+ return packOfficial(dev, true).flatMap((w2) => flowOf({ id: w2.id, version: 1, name: w2.name, names: w2.names, files: w2.files }) ?? []);
117197
+ }
117198
+ const project = boardProject();
117199
+ if (!project || !readSession()) return [];
117200
+ const list = readJson(listFile(project))?.studios ?? [];
117201
+ const flows2 = list.flatMap((w2) => {
117202
+ const held4 = readVersion2(w2.id, w2.version);
117203
+ return held4 ? flowOf(held4) ?? [] : [];
117204
+ });
117205
+ const task = workspaceTask();
117206
+ const pin = task ? readPin(task) : null;
117207
+ const pinned = pin && readVersion2(pin.studio, pin.version);
117208
+ const mine = pinned && flowOf(pinned);
117209
+ if (!mine) return flows2;
117210
+ return [mine, ...flows2.filter((f2) => f2.cloudId !== mine.cloudId)];
117211
+ }
117212
+ var sources = () => {
117213
+ if (devFolder()) return [devFolder()];
117214
+ const project = boardProject();
117215
+ const task = workspaceTask();
117216
+ return [sessionFile(), ...project ? [listFile(project)] : [], ...task ? [pinFile(task)] : []];
117217
+ };
117218
+ var flows = memoByFiles(sources, readFlows);
117219
+ var cloudFlows = () => flows();
117220
+ function cloudAgentFiles() {
117221
+ const files = {};
117222
+ const official = /* @__PURE__ */ new Set();
117223
+ const owner = /* @__PURE__ */ new Map();
117224
+ for (const flow of cloudFlows()) {
117225
+ for (const [name, text3] of Object.entries(flow.files)) {
117226
+ const at2 = /^agents\/([^/]+)\/(.+)$/.exec(name);
117227
+ if (!at2) continue;
117228
+ const [, agent, rest] = at2;
117229
+ if (owner.has(agent) && owner.get(agent) !== flow.cloudId) continue;
117230
+ owner.set(agent, flow.cloudId);
117231
+ if (flow.builtIn) official.add(agent);
117232
+ files[`${agent}/${rest}`] = text3;
117233
+ }
117234
+ }
117235
+ return { files, official };
117236
+ }
117237
+
117238
+ // src/cache.ts
117239
+ var IDLE_MS = 7 * 24 * 60 * 6e4;
117240
+ var SWEEP_MS = 24 * 60 * 6e4;
117241
+ var PROJECT_ID = /^[\w-]{1,100}$/;
117242
+ var cacheRoot = () => path25.join(runnerHome(), "cache");
117243
+ function cacheDir(project) {
117244
+ if (!PROJECT_ID.test(project)) throw new Error("This job names no project.");
117245
+ return path25.join(cacheRoot(), project);
117246
+ }
117247
+ var akbDir = (dir) => path25.join(dir, ".akb");
117248
+ var usedFile = (dir) => path25.join(akbDir(dir), "used.json");
117249
+ var unsentFile = (dir) => path25.join(akbDir(dir), "unsent");
117250
+ function markUsed(dir, at2 = Date.now()) {
117251
+ fs21.mkdirSync(akbDir(dir), { recursive: true });
117252
+ fs21.writeFileSync(usedFile(dir), `${JSON.stringify({ at: at2 })}
117253
+ `);
117254
+ }
117255
+ function usedAt(dir) {
117256
+ try {
117257
+ const at2 = JSON.parse(fs21.readFileSync(usedFile(dir), "utf8")).at;
117258
+ return typeof at2 === "number" ? at2 : null;
117259
+ } catch {
117260
+ return null;
117261
+ }
117262
+ }
117263
+ var unsent = (dir) => fs21.existsSync(unsentFile(dir));
117264
+ function markUnsent(dir, unsent2) {
117265
+ if (!unsent2) return void fs21.rmSync(unsentFile(dir), { force: true });
117266
+ fs21.mkdirSync(akbDir(dir), { recursive: true });
117267
+ fs21.writeFileSync(unsentFile(dir), "");
117268
+ }
117269
+ var holds = /* @__PURE__ */ new Map();
117270
+ var holdsDir = () => path25.join(runnerHome(), "holds");
117271
+ var holdFile = (dir) => path25.join(holdsDir(), `${crypto3.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
117272
+ function hold(dir) {
117273
+ fs21.mkdirSync(holdsDir(), { recursive: true, mode: 448 });
117274
+ fs21.writeFileSync(holdFile(dir), "", { mode: 384 });
117275
+ holds.set(dir, (holds.get(dir) ?? 0) + 1);
117276
+ let held4 = true;
117277
+ return () => {
117278
+ if (!held4) return;
117279
+ held4 = false;
117280
+ const left = holds.get(dir) - 1;
117281
+ if (left) holds.set(dir, left);
117282
+ else {
117283
+ holds.delete(dir);
117284
+ fs21.rmSync(holdFile(dir), { force: true });
117285
+ }
117286
+ };
117287
+ }
117288
+ function paused(dir) {
117289
+ try {
117290
+ const file3 = path25.join(projectStateDir(path25.join(akbDir(dir), "kanban")), SESSIONS_FILE);
117291
+ const held4 = JSON.parse(fs21.readFileSync(file3, "utf8"));
117292
+ return (held4.deliveries ?? []).some((d2) => d2.status === "active");
117293
+ } catch {
117294
+ return false;
117295
+ }
117296
+ }
117297
+ function busy(dir) {
117298
+ if (holds.has(dir)) return true;
117299
+ const prefix = path25.basename(holdFile(dir)).split(".")[0] + ".";
117300
+ try {
117301
+ return fs21.readdirSync(holdsDir()).filter((file3) => file3.startsWith(prefix)).some((file3) => {
117302
+ try {
117303
+ process.kill(Number(file3.split(".")[1]), 0);
117304
+ return true;
117305
+ } catch {
117306
+ fs21.rmSync(path25.join(holdsDir(), file3), { force: true });
117307
+ return false;
117308
+ }
117309
+ });
117310
+ } catch {
117311
+ return false;
117312
+ }
117313
+ }
117314
+ var kept2 = (dir) => busy(dir) || unsent(dir) || paused(dir);
117315
+ function clearAkb(dir) {
117316
+ dir = realpath2(dir);
117317
+ if (kept2(dir) || fs21.existsSync(path25.join(akbDir(dir), "worktrees")) || fs21.existsSync(path25.join(akbDir(dir), "handoffs"))) return false;
117318
+ let entries;
117319
+ try {
117320
+ entries = fs21.readdirSync(akbDir(dir));
117321
+ } catch {
117322
+ return true;
117323
+ }
117324
+ for (const name of entries) fs21.rmSync(path25.join(akbDir(dir), name), { recursive: true, force: true });
117325
+ return true;
117326
+ }
117327
+ async function readAccess(machineId2) {
117328
+ if (!readSession()) return null;
117329
+ const [folders2, elsewhere] = await Promise.all([listFolders(machineId2), listElsewhere(machineId2)]);
117330
+ if (!folders2.ok || !elsewhere.ok) return null;
117331
+ return {
117332
+ projects: /* @__PURE__ */ new Set([...folders2.value.folders.map((f2) => f2.project), ...elsewhere.value.projects.map((p2) => p2.project)]),
117333
+ folders: new Set(folders2.value.folders.map((f2) => realpath2(f2.path)))
117334
+ };
117335
+ }
117336
+ function realpath2(p2) {
117337
+ try {
117338
+ return fs21.realpathSync(p2);
117339
+ } catch {
117340
+ return p2;
117341
+ }
117342
+ }
117343
+ function idle(dir, now) {
117344
+ const at2 = usedAt(dir);
117345
+ if (at2 === null) markUsed(dir, now);
117346
+ return at2 !== null && now - at2 > IDLE_MS;
117347
+ }
117348
+ async function sweepCache(machineId2, now = Date.now()) {
117349
+ const access = await readAccess(machineId2);
117350
+ const swept = [];
117351
+ let cached2 = [];
117352
+ try {
117353
+ cached2 = fs21.readdirSync(cacheRoot(), { withFileTypes: true });
117354
+ } catch {
117355
+ }
117356
+ for (const e2 of cached2) {
117357
+ const dir = path25.join(cacheRoot(), e2.name);
117358
+ if (!e2.isDirectory() || kept2(dir) || fs21.existsSync(path25.join(dir, ".git"))) continue;
117359
+ const gone = access && !access.projects.has(e2.name);
117360
+ if ((idle(dir, now) || gone) && !fs21.existsSync(path25.join(akbDir(dir), "worktrees")) && !fs21.existsSync(path25.join(akbDir(dir), "handoffs"))) {
117361
+ fs21.rmSync(dir, { recursive: true, force: true });
117362
+ swept.push(dir);
117363
+ }
117364
+ }
117365
+ for (const dir of allowedProjects()) {
117366
+ let held4 = [];
117367
+ try {
117368
+ held4 = fs21.readdirSync(akbDir(dir));
117369
+ } catch {
117370
+ }
117371
+ if (!held4.length) continue;
117372
+ const gone = access && !access.folders.has(dir);
117373
+ if ((idle(dir, now) || gone) && clearAkb(dir)) swept.push(dir);
117374
+ }
117375
+ return swept;
117376
+ }
117377
+ var sweepStudios = () => sweepVersions(async (task) => {
117378
+ const read4 = await readTask(task);
117379
+ if (read4.ok) return read4.value.status === "done" || read4.value.status === "cancelled";
117380
+ return read4.code === "not_found" ? true : null;
117381
+ });
117382
+ function removeLegacy() {
117383
+ const home4 = runnerHome();
117384
+ for (const name of ["boards", "akb-bin"]) fs21.rmSync(path25.join(home4, name), { recursive: true, force: true });
117385
+ let entries = [];
117386
+ try {
117387
+ entries = fs21.readdirSync(home4, { withFileTypes: true });
117388
+ } catch {
117389
+ return;
117390
+ }
117391
+ for (const e2 of entries) {
117392
+ const account = path25.join(home4, e2.name);
117393
+ if (!e2.isDirectory() || !fs21.existsSync(path25.join(account, "unfiled"))) continue;
117394
+ fs21.rmSync(path25.join(account, "unfiled"), { recursive: true, force: true });
117395
+ if (!fs21.readdirSync(account).length) fs21.rmdirSync(account);
117396
+ }
117397
+ }
117398
+
117399
+ // src/update.ts
117400
+ import crypto4 from "node:crypto";
117401
+ import fs22 from "node:fs";
117402
+ import path26 from "node:path";
117403
+ import zlib from "node:zlib";
117404
+ var TIMEOUT_MS2 = 6e4;
117405
+ var versionsDir = () => path26.join(runnerHome(), "bin", "runner");
117406
+ var versionDir = (version) => path26.join(versionsDir(), version);
117407
+ var entryOf = (dir) => path26.join(dir, "dist", "runner.mjs");
117408
+ var registry = () => (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
117409
+ async function installPackage(pkg, version, nodeVersion = process.versions.node) {
117410
+ const dir = pkg.dirOf(version);
117411
+ if (fs22.existsSync(pkg.entryOf(dir))) return { ok: true, dir };
117412
+ let meta;
117413
+ let tarball;
117414
+ try {
117415
+ const answer = await fetch(`${registry()}/${pkg.name}/${encodeURIComponent(version)}`, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
117416
+ if (!answer.ok) return { ok: false, why: "unreachable", detail: `registry answered ${answer.status}` };
117417
+ meta = await answer.json();
117418
+ const range = meta.engines?.node;
117419
+ if (range && !satisfies(nodeVersion, range)) return { ok: false, why: "node", detail: range };
117420
+ if (!meta.dist?.tarball) return { ok: false, why: "unreachable", detail: "no tarball" };
117421
+ const download2 = await fetch(meta.dist.tarball, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
117422
+ if (!download2.ok) return { ok: false, why: "unreachable", detail: `download answered ${download2.status}` };
117423
+ tarball = Buffer.from(await download2.arrayBuffer());
117424
+ } catch (e2) {
117425
+ return { ok: false, why: "unreachable", detail: e2 instanceof Error ? e2.message : String(e2) };
117426
+ }
117427
+ const expected = /^sha512-(.+)$/.exec(meta.dist.integrity ?? "")?.[1];
117428
+ const actual = crypto4.createHash("sha512").update(tarball).digest("base64");
117429
+ if (!expected || expected !== actual) return { ok: false, why: "integrity", detail: "sha512 mismatch" };
117430
+ const staging = `${dir}.${process.pid}.tmp`;
117431
+ try {
117432
+ fs22.rmSync(staging, { recursive: true, force: true });
117433
+ extract(zlib.gunzipSync(tarball), staging);
117434
+ if (!fs22.existsSync(pkg.entryOf(staging))) throw new Error(`the package carries no ${path26.relative(staging, pkg.entryOf(staging))}`);
117435
+ fs22.rmSync(dir, { recursive: true, force: true });
117436
+ fs22.renameSync(staging, dir);
117437
+ } catch (e2) {
117438
+ fs22.rmSync(staging, { recursive: true, force: true });
117439
+ return { ok: false, why: "integrity", detail: e2 instanceof Error ? e2.message : String(e2) };
117440
+ }
117441
+ return { ok: true, dir };
117442
+ }
117443
+ function extract(tar, into) {
117444
+ let offset = 0;
117445
+ let longName = null;
117446
+ while (offset + 512 <= tar.length) {
117447
+ const header = tar.subarray(offset, offset + 512);
117448
+ if (header.every((b2) => b2 === 0)) break;
117449
+ const field = (start, length) => header.subarray(start, start + length).toString("utf8").replace(/\0.*$/s, "");
117450
+ const size = parseInt(field(124, 12).trim() || "0", 8);
117451
+ const type = field(156, 1) || "0";
117452
+ const body = tar.subarray(offset + 512, offset + 512 + size);
117453
+ offset += 512 + Math.ceil(size / 512) * 512;
117454
+ if (type === "x") {
117455
+ longName = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(body.toString("utf8"))?.[1] ?? null;
117456
+ continue;
117457
+ }
117458
+ if (type === "L") {
117459
+ longName = body.toString("utf8").replace(/\0.*$/s, "");
117460
+ continue;
117461
+ }
117462
+ const prefix = field(345, 155);
117463
+ const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
117464
+ longName = null;
117465
+ if (type !== "0" && type !== "5") continue;
117466
+ const relative = name.replace(/^[^/]+\//, "");
117467
+ if (!relative) continue;
117468
+ const target = path26.resolve(into, relative);
117469
+ if (!target.startsWith(path26.resolve(into) + path26.sep)) throw new Error(`refusing ${name}`);
117470
+ if (type === "5") fs22.mkdirSync(target, { recursive: true });
117471
+ else {
117472
+ fs22.mkdirSync(path26.dirname(target), { recursive: true });
117473
+ fs22.writeFileSync(target, body);
117474
+ }
117475
+ }
117476
+ }
117477
+ var parse = (v) => {
117478
+ const m = /^v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(v.trim());
117479
+ return m ? [Number(m[1]), Number(m[2]) || 0, Number(m[3]) || 0] : null;
117480
+ };
117481
+ function compare(a2, b2) {
117482
+ const [x2, y2] = [parse(a2) ?? [0, 0, 0], parse(b2) ?? [0, 0, 0]];
117483
+ for (let i = 0; i < 3; i++) if (x2[i] !== y2[i]) return x2[i] - y2[i];
117484
+ const pre = (v) => /^v?\d+\.\d+\.\d+-([^+]+)/.exec(v)?.[1]?.split(".");
117485
+ const ap = pre(a2), bp = pre(b2);
117486
+ if (!ap || !bp) return ap ? -1 : bp ? 1 : 0;
117487
+ for (let i = 0; i < Math.max(ap.length, bp.length); i++) {
117488
+ const av = ap[i], bv = bp[i];
117489
+ if (av === bv) continue;
117490
+ if (av === void 0) return -1;
117491
+ if (bv === void 0) return 1;
117492
+ const an2 = /^\d+$/.test(av), bn2 = /^\d+$/.test(bv);
117493
+ if (an2 && bn2) return Number(av) - Number(bv);
117494
+ if (an2 !== bn2) return an2 ? -1 : 1;
117495
+ return av < bv ? -1 : 1;
117496
+ }
117497
+ return 0;
117498
+ }
117499
+ function satisfies(version, range) {
117500
+ return range.split("||").some((alternative) => {
117501
+ const parts = alternative.trim().split(/\s+/).filter(Boolean);
117502
+ return parts.length > 0 && parts.every((part) => meets(version, part));
117503
+ });
117504
+ }
117505
+ function meets(version, comparator) {
117506
+ const m = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/.exec(comparator);
117507
+ const bound = m && parse(m[2]);
117508
+ if (!m || !bound) return false;
117509
+ const v = parse(version);
117510
+ const c2 = compare(version, m[2]);
117511
+ switch (m[1]) {
117512
+ case ">=":
117513
+ return c2 >= 0;
117514
+ case ">":
117515
+ return c2 > 0;
117516
+ case "<=":
117517
+ return c2 <= 0;
117518
+ case "<":
117519
+ return c2 < 0;
117520
+ case "^":
117521
+ return c2 >= 0 && v[0] === bound[0];
117522
+ case "~":
117523
+ return c2 >= 0 && v[0] === bound[0] && v[1] === bound[1];
117524
+ default: {
117525
+ const given = m[2].split(".").filter((p2) => /^\d+$/.test(p2)).length;
117526
+ return [0, 1, 2].slice(0, given).every((i) => v[i] === bound[i]);
117527
+ }
117528
+ }
117529
+ }
117530
+
117531
+ // src/akb-version.ts
117532
+ var CHECK_MS2 = 1e4;
117533
+ var VERSION2 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
117534
+ var stateFile = () => path27.join(akbHome(), "state.json");
117535
+ var akbVersionDir = (version) => path27.join(akbHome(), version);
117536
+ var entryOf2 = (dir) => path27.join(dir, "bin", "ai4kanban.mjs");
117537
+ var AKB = { name: "wildcrane", dirOf: akbVersionDir, entryOf: entryOf2 };
117538
+ function readAkbState() {
117539
+ try {
117540
+ const held4 = JSON.parse(fs23.readFileSync(stateFile(), "utf8"));
117541
+ return { current: held4.current ?? null, bad: held4.bad ?? [] };
117542
+ } catch {
117543
+ return { current: null, bad: [] };
117544
+ }
117545
+ }
117546
+ function writeAkbState(state) {
117547
+ fs23.mkdirSync(akbHome(), { recursive: true });
117548
+ const staging = `${stateFile()}.${process.pid}.tmp`;
117549
+ fs23.writeFileSync(staging, `${JSON.stringify(state, null, 2)}
117550
+ `);
117551
+ fs23.renameSync(staging, stateFile());
117552
+ }
117553
+ function contractOf(dir) {
117554
+ try {
117555
+ return JSON.parse(fs23.readFileSync(path27.join(dir, "package.json"), "utf8")).akbContract ?? null;
117556
+ } catch {
117557
+ return null;
117558
+ }
117559
+ }
117560
+ var usable = (dir) => fs23.existsSync(entryOf2(dir)) && contractOf(dir) === AKB_CONTRACT;
117561
+ function currentAkb() {
117562
+ const { current: current2 } = readAkbState();
117563
+ if (!current2) return bundledAkb();
117564
+ const dir = akbVersionDir(current2);
117565
+ if (!usable(dir)) return bundledAkb();
117566
+ try {
117567
+ const now = /* @__PURE__ */ new Date();
117568
+ fs23.utimesSync(dir, now, now);
117569
+ } catch {
117570
+ }
117571
+ return { command: process.execPath, args: akbArgs(entryOf2(dir)), version: current2, shim: path27.join(dir, "shim") };
117572
+ }
117573
+ var answers2 = (dir, version) => new Promise((resolve2) => {
117574
+ execFile(process.execPath, [entryOf2(dir), "--version"], { timeout: CHECK_MS2, killSignal: "SIGKILL" }, (error, stdout) => resolve2(!error && stdout.trim().split(/\s+/).at(-1) === version));
117575
+ });
117576
+ var wanted = null;
117577
+ var fetching = false;
117578
+ function useVersion(current2) {
117579
+ const state = readAkbState();
117580
+ if (state.current !== current2) writeAkbState({ ...state, current: current2 });
117581
+ }
117582
+ async function fetchVersion(version) {
117583
+ const got = await installPackage(AKB, version);
117584
+ if (!got.ok) return console.error(`runner: akb ${version} was not fetched: ${got.detail}`);
117585
+ if (contractOf(got.dir) !== AKB_CONTRACT || !await answers2(got.dir, version)) {
117586
+ console.error(`runner: akb ${version} failed its check and will not be used`);
117587
+ const state = readAkbState();
117588
+ return writeAkbState({ ...state, bad: [.../* @__PURE__ */ new Set([...state.bad, version])] });
117589
+ }
117590
+ if (wanted === version) useVersion(version);
117591
+ }
117592
+ async function followAkb(named2) {
117593
+ if (!named2) return;
117594
+ const { version } = named2;
117595
+ try {
117596
+ if (version !== null && !VERSION2.test(version)) return;
117597
+ wanted = version;
117598
+ if (version === null || version === AKB_VERSION) return useVersion(null);
117599
+ const state = readAkbState();
117600
+ if (fetching || state.bad.includes(version) || state.current === version && usable(akbVersionDir(version))) return;
117601
+ fetching = true;
117602
+ await fetchVersion(version).finally(() => fetching = false);
117603
+ } catch (e2) {
117604
+ console.error(`runner: the akb version was not followed: ${e2 instanceof Error ? e2.message : String(e2)}`);
117605
+ }
117606
+ }
117607
+ function sweepAkb(now = Date.now()) {
117608
+ const { current: current2 } = readAkbState();
117609
+ let entries = [];
117610
+ try {
117611
+ entries = fs23.readdirSync(akbHome(), { withFileTypes: true });
117612
+ } catch {
117613
+ return;
117614
+ }
117615
+ for (const e2 of entries) {
117616
+ if (!e2.isDirectory() || e2.name === current2 || e2.name === BUNDLED_SHIM) continue;
117617
+ const dir = path27.join(akbHome(), e2.name);
117618
+ if (now - fs23.statSync(dir).mtimeMs > IDLE_MS) fs23.rmSync(dir, { recursive: true, force: true });
117619
+ }
117620
+ }
117621
+
117622
+ // src/chats.ts
117623
+ import fs25 from "node:fs";
117624
+ import path29 from "node:path";
117625
+
117626
+ // ../cli/src/lib/shared/chats.ts
117627
+ var CHAT_KEEP_DAYS = 30;
117628
+
117629
+ // ../cli/src/lib/agent/task-chats.ts
117630
+ import fs24 from "node:fs";
117631
+ import path28 from "node:path";
117632
+ var TASK = /^[\w-]{1,100}$/;
117633
+ var taskChatsDir = (home4 = machineHome()) => path28.join(home4, "chats");
117634
+ function taskChatFile(task, home4) {
117635
+ if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
117636
+ return path28.join(taskChatsDir(home4), `${task}.jsonl`);
117637
+ }
117638
+ function readTaskChat(task, home4) {
117639
+ let text3;
117640
+ try {
117641
+ text3 = fs24.readFileSync(taskChatFile(task, home4), "utf8");
117642
+ } catch {
117643
+ return [];
117644
+ }
117645
+ const lines = [];
117646
+ for (const raw of text3.split("\n")) {
117647
+ if (!raw.trim()) continue;
117648
+ try {
117649
+ const line = JSON.parse(raw);
117650
+ if (typeof line.id === "string" && (line.role === "user" || line.role === "agent") && typeof line.text === "string") lines.push(line);
117651
+ } catch {
117652
+ }
117653
+ }
117654
+ return lines;
117655
+ }
117656
+
117657
+ // src/chats.ts
117658
+ var DAY_MS = 24 * 60 * 6e4;
117659
+ var REVIEW_EVERY_MS = DAY_MS;
117660
+ var KEEP_MS2 = CHAT_KEEP_DAYS * DAY_MS;
117661
+ var home3 = () => runnerHome();
117662
+ var reviewedFile = () => path29.join(taskChatsDir(home3()), "reviewed.json");
117663
+ function readReviewed() {
117664
+ try {
117665
+ const held4 = JSON.parse(fs25.readFileSync(reviewedFile(), "utf8"));
117666
+ return { checkedAt: Number(held4.checkedAt) || 0, tasks: held4.tasks ?? {} };
117667
+ } catch {
117668
+ return { checkedAt: 0, tasks: {} };
117669
+ }
117670
+ }
117671
+ function writeReviewed(reviewed) {
117672
+ fs25.mkdirSync(path29.dirname(reviewedFile()), { recursive: true });
117673
+ fs25.writeFileSync(reviewedFile(), `${JSON.stringify(reviewed, null, 2)}
117674
+ `);
117675
+ }
117676
+ function keepChat(job, reply, at2 = Date.now()) {
117677
+ if (!job.task || !job.chat || !reply?.trim()) return;
117678
+ const lines = [
117679
+ { id: job.chat.message, role: "user", text: job.chat.body, at: at2 },
117680
+ { id: job.id, role: "agent", text: reply, at: at2, runtime: job.runtime, model: job.model ?? null }
117681
+ ];
117682
+ const file3 = taskChatFile(job.task, home3());
117683
+ fs25.mkdirSync(path29.dirname(file3), { recursive: true });
117684
+ fs25.appendFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
117685
+ `).join(""));
117686
+ }
117687
+ function keepCloudChat(task, messages) {
117688
+ const file3 = taskChatFile(task, home3());
117689
+ if (!messages.length) return fs25.rmSync(file3, { force: true });
117690
+ const lines = messages.map((m) => ({ id: m.id, role: m.role, text: m.body, at: Date.parse(m.created_at) || Date.now() }));
117691
+ fs25.mkdirSync(path29.dirname(file3), { recursive: true });
117692
+ fs25.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
117693
+ `).join(""));
117694
+ }
117695
+ async function keepDecisions(task, read4) {
117696
+ const comments = [];
117697
+ let after = null;
117698
+ do {
117699
+ const page = await read4(task, after);
117700
+ if (!page.ok) return;
117701
+ for (const d2 of page.value.data) {
117702
+ if (d2.comment.trim()) comments.push({ id: d2.id, role: "user", text: d2.comment, at: Date.parse(d2.created_at) || Date.now() });
117703
+ }
117704
+ after = page.value.next;
117705
+ } while (after);
117706
+ if (!comments.length) return;
117707
+ const ids = new Set(comments.map((c2) => c2.id));
117708
+ const lines = [...readTaskChat(task, home3()).filter((l2) => !ids.has(l2.id)), ...comments].sort((a2, b2) => a2.at - b2.at);
117709
+ const file3 = taskChatFile(task, home3());
117710
+ fs25.mkdirSync(path29.dirname(file3), { recursive: true });
117711
+ fs25.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
117712
+ `).join(""));
117713
+ }
117714
+ var tasksKept = () => {
117715
+ try {
117716
+ return fs25.readdirSync(taskChatsDir(home3())).map((n) => /^([\w-]{1,100})\.jsonl$/.exec(n)?.[1]).filter((t2) => !!t2);
117717
+ } catch {
117718
+ return [];
117719
+ }
117720
+ };
117721
+ function pruneChats(now = Date.now()) {
117722
+ for (const task of tasksKept()) {
117723
+ const lines = readTaskChat(task, home3());
117724
+ const kept4 = lines.filter((l2) => now - l2.at < KEEP_MS2);
117725
+ if (kept4.length === lines.length) continue;
117726
+ const file3 = taskChatFile(task, home3());
117727
+ if (kept4.length) fs25.writeFileSync(file3, kept4.map((l2) => `${JSON.stringify(l2)}
117728
+ `).join(""));
117729
+ else fs25.rmSync(file3, { force: true });
117730
+ }
117731
+ }
117732
+ var lastOf = (task) => readTaskChat(task, home3()).at(-1);
117733
+ var reviewMarks = (tasks) => Object.fromEntries(tasks.map(({ task, archivedAt }) => {
117734
+ const last2 = lastOf(task);
117735
+ return [task, last2 ? { archivedAt, message: last2.id } : { archivedAt }];
117736
+ }));
117737
+ function markReviewed2(marks) {
117738
+ const reviewed = readReviewed();
117739
+ writeReviewed({ ...reviewed, tasks: { ...reviewed.tasks, ...marks } });
117740
+ }
117741
+ async function reviewChats(machineId2, runtimes, now = Date.now()) {
117742
+ const reviewed = readReviewed();
117743
+ if (now - reviewed.checkedAt < REVIEW_EVERY_MS) return;
117744
+ pruneChats(now);
117745
+ const owned = await listChats(machineId2);
117746
+ if (!owned.ok) return;
117747
+ const byProject = /* @__PURE__ */ new Map();
117748
+ for (const { task, project, archivedAt } of owned.value.chats) {
117749
+ const mark = reviewed.tasks[task];
117750
+ const last2 = lastOf(task);
117751
+ if (mark?.archivedAt === archivedAt && (!last2 || last2.id === mark.message)) continue;
117752
+ byProject.set(project, [...byProject.get(project) ?? [], task]);
117753
+ }
117754
+ const signedIn = runtimes.find((r2) => r2.installed && r2.loggedIn !== false)?.name;
117755
+ for (const [project, tasks] of [...byProject].map(([p2, t2]) => [p2, t2.slice(0, 100)])) {
117756
+ const replied = tasks.flatMap((t2) => readTaskChat(t2, home3())).filter((l2) => l2.runtime).sort((a2, b2) => a2.at - b2.at).at(-1);
117757
+ const runtime = replied?.runtime ?? signedIn ?? "claude-code";
117758
+ const sent = await dispatchReview(machineId2, project, tasks, runtime, replied?.model ?? null);
117759
+ if (!sent.ok) console.error(`runner: the chats of ${project} were not sent for review: ${sent.error}`);
117760
+ }
117761
+ const listed2 = new Set(owned.value.chats.map((c2) => c2.task));
117762
+ const held4 = readReviewed();
117763
+ writeReviewed({ checkedAt: now, tasks: Object.fromEntries(Object.entries(held4.tasks).filter(([t2]) => listed2.has(t2))) });
117764
+ }
117765
+
117766
+ // src/board-watch.ts
117767
+ import fs31 from "node:fs";
117768
+ import path35 from "node:path";
117769
+
117770
+ // ../artifact-sdk/src/builtin/compare.json
117771
+ 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';
117772
+
117773
+ // ../artifact-sdk/src/builtin/html.json
117774
+ var html_default = `{
117775
+ "name": "html",
117776
+ "title": { "en": "Page", "zh": "\u9875\u9762" },
117777
+ "types": ["html"],
117778
+ "references": [
117779
+ { "text": "<[a-z][^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117780
+ { "text": "<[a-z][^<>]*?\\\\sposter\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117781
+ { "text": "<[a-z][^<>]*?\\\\ssrcset\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']", "list": "," },
117782
+ { "text": "<link\\\\b[^<>]*?\\\\shref\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117783
+ { "text": "url\\\\(\\\\s*[\\"']?([^\\"')]+?)[\\"']?\\\\s*\\\\)" }
117784
+ ],
117785
+ "skip": ["(?<=<script\\\\b[^<>]*>)[\\\\s\\\\S]*?(?=</script\\\\s*>|$)"]
117786
+ }
117787
+ `;
117788
+
117789
+ // ../artifact-sdk/src/builtin/image.json
117790
+ var image_default = '{ "name": "image", "title": { "en": "Image", "zh": "\u56FE\u7247" }, "types": ["image"] }\n';
117791
+
117792
+ // ../artifact-sdk/src/builtin/markdown.json
117793
+ var markdown_default = `{
117794
+ "name": "markdown",
117795
+ "title": { "en": "Document", "zh": "\u6587\u6863" },
117796
+ "types": ["markdown"],
117797
+ "references": [
117798
+ { "text": "!\\\\[[^\\\\]\\\\n]*\\\\]\\\\(\\\\s*<?([^\\\\s)>]+)>?(?:\\\\s+[\\"'][^\\"'\\\\n]*[\\"'])?\\\\s*\\\\)" },
117799
+ { "text": "<img\\\\b[^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" }
117800
+ ]
117801
+ }
117802
+ `;
117803
+
117804
+ // ../artifact-sdk/src/builtin/spritesheet.json
117805
+ 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';
117806
+
117807
+ // ../artifact-sdk/src/builtin/storyboard.json
117808
+ 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';
117809
+
117810
+ // ../artifact-sdk/src/builtin/tiled.json
117811
+ var tiled_default = `{
117812
+ "name": "tiled",
117813
+ "title": { "en": "Tiled map", "zh": "Tiled \u5730\u56FE" },
117814
+ "types": ["tiled"],
117815
+ "references": [
117816
+ { "text": "<tileset\\\\b[^<>]*?\\\\ssource\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']", "types": ["tiled"] },
117817
+ { "text": "<image\\\\b[^<>]*?\\\\ssource\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" },
117818
+ { "text": "\\"source\\"\\\\s*:\\\\s*\\"([^\\"]+)\\"", "types": ["tiled"] },
117819
+ { "text": "\\"image\\"\\\\s*:\\\\s*\\"([^\\"]+)\\"" }
117820
+ ]
117821
+ }
117822
+ `;
117823
+
117824
+ // ../artifact-sdk/src/builtin/video.json
117825
+ var video_default = '{ "name": "video", "title": { "en": "Video", "zh": "\u89C6\u9891" }, "types": ["video"] }\n';
117826
+
117827
+ // ../artifact-sdk/src/builtin/studio.json
117828
+ 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';
117829
+
117830
+ // ../artifact-sdk/src/builtin/index.ts
117831
+ var read = (m) => typeof m === "string" ? JSON.parse(m) : m;
117832
+ var builtin_default = [html_default, image_default, video_default, markdown_default, storyboard_default, compare_default, studio_default, tiled_default, spritesheet_default].map(read);
117833
+
117834
+ // ../artifact-sdk/src/internal/schema.ts
117835
+ var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117836
+ function typeOk(type, v) {
117837
+ const types = Array.isArray(type) ? type : [type];
117838
+ return types.some(
117839
+ (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
117840
+ );
117841
+ }
117842
+ function schemaProblem(schema, value, at2 = "") {
117843
+ if (!isObj(schema)) return null;
117844
+ const s = schema;
117845
+ const here2 = at2 || "/";
117846
+ if (s.type !== void 0 && !typeOk(s.type, value)) return here2;
117847
+ if (Array.isArray(s.enum) && !s.enum.some((e2) => JSON.stringify(e2) === JSON.stringify(value))) return here2;
117848
+ if (s.const !== void 0 && JSON.stringify(s.const) !== JSON.stringify(value)) return here2;
117849
+ if (Array.isArray(s.anyOf) && !s.anyOf.some((x2) => !schemaProblem(x2, value, at2))) return here2;
117850
+ if (typeof value === "string") {
117851
+ if (typeof s.minLength === "number" && value.length < s.minLength) return here2;
117852
+ if (typeof s.maxLength === "number" && value.length > s.maxLength) return here2;
117853
+ if (typeof s.pattern === "string") {
117854
+ try {
117855
+ if (!new RegExp(s.pattern, "u").test(value)) return here2;
117856
+ } catch {
117857
+ }
117858
+ }
117859
+ }
117860
+ if (typeof value === "number") {
117861
+ if (typeof s.minimum === "number" && value < s.minimum) return here2;
117862
+ if (typeof s.maximum === "number" && value > s.maximum) return here2;
117863
+ }
117864
+ if (Array.isArray(value)) {
117865
+ if (typeof s.minItems === "number" && value.length < s.minItems) return here2;
117866
+ if (typeof s.maxItems === "number" && value.length > s.maxItems) return here2;
117867
+ if (isObj(s.items)) {
117868
+ for (let i = 0; i < value.length; i++) {
117869
+ const bad = schemaProblem(s.items, value[i], `${at2}/${i}`);
117870
+ if (bad) return bad;
117871
+ }
117872
+ }
117873
+ }
117874
+ if (isObj(value)) {
117875
+ const props = isObj(s.properties) ? s.properties : {};
117876
+ if (Array.isArray(s.required)) {
117877
+ for (const k2 of s.required) if (typeof k2 === "string" && !(k2 in value)) return `${at2}/${k2}`;
117878
+ }
117879
+ for (const [k2, v] of Object.entries(value)) {
117880
+ if (k2 in props) {
117881
+ const bad = schemaProblem(props[k2], v, `${at2}/${k2}`);
117882
+ if (bad) return bad;
117883
+ } else if (s.additionalProperties === false) return `${at2}/${k2}`;
117884
+ else if (isObj(s.additionalProperties)) {
117885
+ const bad = schemaProblem(s.additionalProperties, v, `${at2}/${k2}`);
117886
+ if (bad) return bad;
117887
+ }
117888
+ }
117889
+ }
117890
+ return null;
117891
+ }
117892
+
117893
+ // ../artifact-sdk/src/internal/manifest.ts
117894
+ var BUILTINS = builtin_default;
117895
+ var manifestOf = (type) => BUILTINS.find((m) => m.types.includes(type));
117896
+ function typeOf(data, types) {
117897
+ for (const type of types) if (!schemaProblem(manifestOf(type)?.schema, data)) return { type };
117898
+ if (types.length !== 1) return { type: null };
117899
+ return { type: types[0], problem: `does not match ${types[0]} at ${schemaProblem(manifestOf(types[0])?.schema, data)}` };
117900
+ }
117901
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117902
+ var remote = (src) => !src || /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src);
117903
+ function mapJson(node, keys, at2, visit) {
117904
+ if (!keys.length) return typeof node === "string" && node ? visit(node, at2) : node;
117905
+ const [key, ...rest] = keys;
117906
+ if (Array.isArray(node)) {
117907
+ if (key === "*") return node.map((x2, i2) => mapJson(x2, rest, `${at2}/${i2}`, visit));
117908
+ const i = Number(key);
117909
+ return Number.isInteger(i) && i in node ? node.map((x2, j2) => j2 === i ? mapJson(x2, rest, `${at2}/${j2}`, visit) : x2) : node;
117910
+ }
117911
+ if (!isObject(node)) return node;
117912
+ const out = { ...node };
117913
+ for (const k2 of key === "*" ? Object.keys(node) : key in node ? [key] : []) out[k2] = mapJson(node[k2], rest, `${at2}/${k2}`, visit);
117914
+ return out;
117915
+ }
117916
+ function mapText(text3, rule, skipped, visit) {
117917
+ let out = "";
117918
+ let last2 = 0;
117919
+ for (const m of text3.matchAll(new RegExp(rule.text, "gid"))) {
117920
+ const span = m.indices?.[1];
117921
+ if (!span || m[1] === void 0 || skipped.some(([a2, b2]) => span[0] >= a2 && span[0] < b2)) continue;
117922
+ const line = text3.slice(0, span[0]).split("\n").length;
117923
+ const one = (src) => remote(src) ? src : visit(src, line);
117924
+ 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]);
117925
+ out += text3.slice(last2, span[0]) + value;
117926
+ last2 = span[1];
117927
+ }
117928
+ return out + text3.slice(last2);
117929
+ }
117930
+ function mapReferences(manifest, content, map2) {
117931
+ const skipped = (text3) => (manifest?.skip ?? []).flatMap((re3) => [...text3.matchAll(new RegExp(re3, "gi"))].map((m) => [m.index, m.index + m[0].length]));
117932
+ for (const rule of manifest?.references ?? []) {
117933
+ const types = rule.types ?? [];
117934
+ if ("json" in rule) {
117935
+ if (typeof content !== "string") content = mapJson(content, rule.json.split("/").filter(Boolean), "", (src, at2) => map2(src, { src, types, text: false, at: at2 || "/" }));
117936
+ } else if (typeof content === "string") {
117937
+ content = mapText(content, rule, skipped(content), (src, line) => map2(src, { src, types, text: true, line }));
117938
+ }
117939
+ }
117940
+ return content;
117941
+ }
117942
+ function referencesOf(manifest, content) {
117943
+ const found = [];
117944
+ mapReferences(manifest, content, (src, ref) => (found.push(ref), src));
117945
+ return found;
117946
+ }
117947
+
117948
+ // ../artifact-sdk/src/internal/references.ts
117949
+ var STORYBOARD = ["storyboard"];
117950
+ var STUDIO = ["studio"];
117951
+ var ARRANGED = ["storyboard", "compare", "spritesheet", "studio"];
117952
+ var ASSET = ["spritesheet", "asset"];
117953
+ var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
117954
+ function bodyReferences(body) {
117955
+ const lines = body.replace(/<!--[^]*?-->/g, "").split(/\r?\n/);
117956
+ let fence = "";
117957
+ let inTag = false;
117958
+ const out = [];
117959
+ const visible = [];
117960
+ for (const line of lines) {
117961
+ const delimiter = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
117962
+ if (fence) {
117963
+ if (delimiter && delimiter[0] === fence[0] && delimiter.length >= fence.length) fence = "";
117964
+ visible.push("");
117965
+ continue;
117966
+ }
117967
+ if (delimiter) {
117968
+ fence = delimiter;
117969
+ visible.push("");
117970
+ continue;
117971
+ }
117972
+ const kept4 = inTag || !/^(?: {4}|\t)/.test(line);
117973
+ visible.push(kept4 ? line : "");
117974
+ if (kept4 && /^ {0,3}<(?:Asset|Mockup|Compare|Storyboard|Studio)\b/.test(line)) inTag = true;
117975
+ if (line.includes("/>")) inTag = false;
117976
+ }
117977
+ const text3 = visible.join("\n").replace(/(`+)[^]*?\1/g, "");
117978
+ const tag = /<(Asset|Mockup|Compare|Storyboard|Studio)\b([^<>]*?)\/>/g;
117979
+ const blocks = text3.matchAll(/^ {0,3}(?:<(?:Asset|Mockup|Compare|Storyboard|Studio)\b[^<>]*?\/>[ \t]*(?:\n[ \t]*)?)+$/gm);
117980
+ for (const block of blocks) {
117981
+ const tags = [...block[0].matchAll(tag)];
117982
+ for (const m of tags) {
117983
+ const a2 = {};
117984
+ for (const p2 of m[2].matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) a2[p2[1]] = p2[2] ?? p2[3];
117985
+ if (m[1] === "Compare") {
117986
+ if (!a2.a || !a2.b) continue;
117987
+ for (const k2 of ["a", "b", "shots"]) if (a2[k2]) out.push({ src: a2[k2], types: ARRANGED });
117988
+ } else if (a2.src) {
117989
+ out.push({ src: a2.src, types: m[1] === "Storyboard" ? STORYBOARD : m[1] === "Studio" ? STUDIO : m[1] === "Asset" ? ASSET : [] });
117990
+ if (a2.variants) {
117991
+ try {
117992
+ const v = JSON.parse(a2.variants);
117993
+ if (isObject2(v)) {
117994
+ for (const src of Object.values(v)) if (typeof src === "string" && src) out.push({ src, types: m[1] === "Asset" ? ASSET : [] });
117995
+ }
117996
+ } catch {
117997
+ }
117998
+ }
117999
+ }
118000
+ }
118001
+ }
118002
+ for (const m of text3.replace(tag, "").matchAll(/\]\(\s*<?([^\s)>]+)>?(?:\s+["'][^]*?["'])?\s*\)/g)) out.push({ src: m[1], types: [] });
118003
+ return out;
118004
+ }
118005
+ var TYPES = {
118006
+ ".png": "image/png",
118007
+ ".jpg": "image/jpeg",
118008
+ ".jpeg": "image/jpeg",
118009
+ ".gif": "image/gif",
118010
+ ".webp": "image/webp",
118011
+ ".svg": "image/svg+xml",
118012
+ ".mp4": "video/mp4",
118013
+ ".webm": "video/webm",
118014
+ ".mp3": "audio/mpeg",
118015
+ ".pdf": "application/pdf",
118016
+ ".html": "text/html",
118017
+ ".md": "text/markdown",
118018
+ ".mdx": "text/markdown",
118019
+ ".mov": "video/quicktime",
118020
+ ".wav": "audio/wav",
118021
+ ".m4a": "audio/mp4",
118022
+ ".json": "application/json",
118023
+ ".txt": "text/plain",
118024
+ ".otf": "font/otf",
118025
+ ".ttf": "font/ttf",
118026
+ ".woff": "font/woff",
118027
+ ".woff2": "font/woff2",
118028
+ ".css": "text/css",
118029
+ ".tmx": "application/xml",
118030
+ ".tmj": "application/json",
118031
+ ".tsj": "application/json"
118032
+ };
118033
+ function kindOf2(ext) {
118034
+ if (ext === ".tsx" || ext === ".html") return "html";
118035
+ if (ext === ".md" || ext === ".mdx") return "markdown";
118036
+ if (ext === ".tmx" || ext === ".tmj" || ext === ".tsj") return "tiled";
118037
+ const type = TYPES[ext] ?? "";
118038
+ if (type.startsWith("image/")) return "image";
118039
+ return type.startsWith("video/") || type.startsWith("audio/") ? "video" : "asset";
118040
+ }
118041
+
118042
+ // ../artifact-sdk/src/internal/collect.ts
118043
+ var extOf = (file3) => /\.[^./\\]+$/.exec(file3)?.[0].toLowerCase() ?? "";
118044
+ var why = (error) => error instanceof Error ? error.message : String(error);
118045
+ var textKind = (ext, types) => types.find((t2) => {
118046
+ const m = manifestOf(t2);
118047
+ return m && !m.schema;
118048
+ }) ?? kindOf2(ext);
118049
+ var kindAt = (src, types) => extOf(src) === ".json" ? types.includes("asset") ? "asset" : types[0] ?? "asset" : textKind(extOf(src), types);
118050
+ function collect(body, card, host) {
118051
+ const nodes = /* @__PURE__ */ new Map();
118052
+ const active = /* @__PURE__ */ new Set();
118053
+ const out = [];
118054
+ const visit = (src, types, owner) => {
118055
+ const path51 = src.replace(/[?#].*$/, "");
118056
+ let resolved;
118057
+ try {
118058
+ resolved = host.resolve(path51, owner);
118059
+ } catch (error) {
118060
+ if (owner !== card) return { key: null, error: why(error) };
118061
+ if (!nodes.has(src)) {
118062
+ const node2 = { key: src, file: null, kind: kindAt(path51, types), error: why(error), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
118063
+ nodes.set(src, node2);
118064
+ out.push(node2);
118065
+ }
118066
+ return { key: src, error: nodes.get(src).error };
118067
+ }
118068
+ if (!resolved) return { key: null };
118069
+ const { key, file: file3 } = resolved;
118070
+ if (active.has(key)) throw new Error(`${owner}: ${src}: \u8D44\u6E90\u4F9D\u8D56\u5FAA\u73AF`);
118071
+ const json = !!file3 && extOf(file3) === ".json";
118072
+ const held4 = nodes.get(key);
118073
+ if (held4) {
118074
+ if (owner === card) held4.aliases.add(src);
118075
+ if (held4.error || !json || !types.length || held4.kind !== "asset") return { key, error: held4.error };
118076
+ out.splice(out.indexOf(held4), 1);
118056
118077
  }
118057
- if (!folders2.has(at2[0])) folders2.set(at2[0], /* @__PURE__ */ new Map());
118058
- folders2.get(at2[0]).set(at2[1], text3);
118059
- }
118060
- for (const name of skills) {
118061
- if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
118062
- }
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;
118078
+ const node = { key, file: file3, kind: "asset", problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: held4?.aliases ?? /* @__PURE__ */ new Set([key]) };
118079
+ if (owner === card) node.aliases.add(src);
118080
+ nodes.set(key, node);
118081
+ active.add(key);
118082
+ const child = (ref, from) => {
118083
+ const found = visit(ref.src, ref.types, from);
118084
+ if (found.key) node.dependencies.set(ref.src, found.key);
118085
+ 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 });
118086
+ node.error ??= found.error;
118087
+ };
118088
+ if (file3) {
118089
+ if (json) {
118090
+ try {
118091
+ node.data = JSON.parse(host.read(file3));
118092
+ const typed = typeOf(node.data, types);
118093
+ node.kind = typed.type ?? "asset";
118094
+ if (typed.problem) node.problems.push({ src: file3, message: `${typed.problem}: ${file3}` });
118095
+ } catch {
118096
+ node.problems.push({ src: file3, message: `not valid JSON: ${file3}` });
118097
+ }
118098
+ } else {
118099
+ node.kind = textKind(extOf(file3), types);
118100
+ try {
118101
+ if (manifestOf(node.kind)?.references) node.data = host.read(file3);
118102
+ } catch (error) {
118103
+ node.problems.push({ src: file3, message: why(error) });
118104
+ }
118105
+ }
118106
+ node.error = node.problems[0]?.message;
118107
+ if (!node.error) for (const ref of referencesOf(manifestOf(node.kind), node.data)) child(ref, file3);
118108
+ } else {
118109
+ for (const ref of host.retained(key)) child(ref, card);
118074
118110
  }
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 };
118111
+ active.delete(key);
118112
+ out.push(node);
118113
+ return { key, error: node.error };
118114
+ };
118115
+ for (const ref of bodyReferences(body)) visit(ref.src, ref.types, card);
118116
+ const sorted = [];
118117
+ const done = /* @__PURE__ */ new Set();
118118
+ const order = (node) => {
118119
+ if (done.has(node.key)) return;
118120
+ done.add(node.key);
118121
+ for (const key of node.dependencies.values()) {
118122
+ const child = nodes.get(key);
118123
+ if (child) order(child);
118124
+ }
118125
+ sorted.push(node);
118126
+ };
118127
+ for (const node of out) order(node);
118128
+ return sorted;
118091
118129
  }
118092
118130
 
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)]));
118131
+ // src/task-folder.ts
118132
+ import crypto5 from "node:crypto";
118133
+ import fs30 from "node:fs";
118134
+ import path34 from "node:path";
118106
118135
 
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
- }
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);
118136
+ // node_modules/node-diff3/dist/diff3.mjs
118137
+ function LCS(buffer1, buffer2) {
118138
+ let equivalenceClasses = /* @__PURE__ */ Object.create(null);
118139
+ for (let j2 = 0; j2 < buffer2.length; j2++) {
118140
+ const item = buffer2[j2];
118141
+ if (equivalenceClasses[item]) {
118142
+ equivalenceClasses[item].push(j2);
118143
+ } else {
118144
+ equivalenceClasses[item] = [j2];
118127
118145
  }
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;
118146
+ }
118147
+ const NULLRESULT = { buffer1index: -1, buffer2index: -1, chain: null };
118148
+ let candidates = [NULLRESULT];
118149
+ for (let i = 0; i < buffer1.length; i++) {
118150
+ const item = buffer1[i];
118151
+ const buffer2indices = equivalenceClasses[item] || [];
118152
+ let r2 = 0;
118153
+ let c2 = candidates[0];
118154
+ for (const j2 of buffer2indices) {
118155
+ let s;
118156
+ for (s = r2; s < candidates.length; s++) {
118157
+ if (candidates[s].buffer2index < j2 && (s === candidates.length - 1 || candidates[s + 1].buffer2index > j2)) {
118158
+ break;
118159
+ }
118160
+ }
118161
+ if (s < candidates.length) {
118162
+ const newCandidate = { buffer1index: i, buffer2index: j2, chain: candidates[s] };
118163
+ if (r2 === candidates.length) {
118164
+ candidates.push(c2);
118165
+ } else {
118166
+ candidates[r2] = c2;
118167
+ }
118168
+ r2 = s + 1;
118169
+ c2 = newCandidate;
118170
+ if (r2 === candidates.length) {
118171
+ break;
118172
+ }
118173
+ }
118137
118174
  }
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;
118175
+ candidates[r2] = c2;
118176
+ }
118177
+ return candidates[candidates.length - 1];
118166
118178
  }
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" };
118179
+ function diffIndices(buffer1, buffer2) {
118180
+ const lcs = LCS(buffer1, buffer2);
118181
+ let result = [];
118182
+ let tail1 = buffer1.length;
118183
+ let tail2 = buffer2.length;
118184
+ for (let candidate = lcs; candidate !== null; candidate = candidate.chain) {
118185
+ const mismatchLength1 = tail1 - candidate.buffer1index - 1;
118186
+ const mismatchLength2 = tail2 - candidate.buffer2index - 1;
118187
+ tail1 = candidate.buffer1index;
118188
+ tail2 = candidate.buffer2index;
118189
+ if (mismatchLength1 || mismatchLength2) {
118190
+ result.push({
118191
+ buffer1: [tail1 + 1, mismatchLength1],
118192
+ buffer1Content: buffer1.slice(tail1 + 1, tail1 + 1 + mismatchLength1),
118193
+ buffer2: [tail2 + 1, mismatchLength2],
118194
+ buffer2Content: buffer2.slice(tail2 + 1, tail2 + 1 + mismatchLength2)
118195
+ });
118196
+ }
118179
118197
  }
118198
+ result.reverse();
118199
+ return result;
118180
118200
  }
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;
118201
+ function diff3MergeRegions(a2, o3, b2) {
118202
+ let hunks = [];
118203
+ function addHunk(h3, ab) {
118204
+ hunks.push({
118205
+ ab,
118206
+ oStart: h3.buffer1[0],
118207
+ oLength: h3.buffer1[1],
118208
+ abStart: h3.buffer2[0],
118209
+ abLength: h3.buffer2[1]
118210
+ });
118211
+ }
118212
+ diffIndices(o3, a2).forEach((item) => addHunk(item, "a"));
118213
+ diffIndices(o3, b2).forEach((item) => addHunk(item, "b"));
118214
+ hunks.sort((x2, y2) => x2.oStart - y2.oStart);
118215
+ let results = [];
118216
+ let currOffset = 0;
118217
+ function advanceTo(endOffset) {
118218
+ if (endOffset > currOffset) {
118219
+ results.push({
118220
+ stable: true,
118221
+ buffer: "o",
118222
+ bufferStart: currOffset,
118223
+ bufferLength: endOffset - currOffset,
118224
+ bufferContent: o3.slice(currOffset, endOffset)
118225
+ });
118226
+ currOffset = endOffset;
118194
118227
  }
118195
- if (!st2.isDirectory()) {
118196
- parts.push(`${p2}:${st2.mtimeNs}:${st2.size}`);
118197
- return;
118228
+ }
118229
+ while (hunks.length) {
118230
+ let hunk = hunks.shift();
118231
+ let regionStart = hunk.oStart;
118232
+ let regionEnd = hunk.oStart + hunk.oLength;
118233
+ let regionHunks = [hunk];
118234
+ advanceTo(regionStart);
118235
+ while (hunks.length) {
118236
+ const nextHunk = hunks[0];
118237
+ const nextHunkStart = nextHunk.oStart;
118238
+ if (nextHunkStart > regionEnd)
118239
+ break;
118240
+ regionEnd = Math.max(regionEnd, nextHunkStart + nextHunk.oLength);
118241
+ regionHunks.push(hunks.shift());
118198
118242
  }
118199
- parts.push(`${p2}/`);
118200
- let names2;
118201
- try {
118202
- names2 = fs24.readdirSync(p2).sort();
118203
- } catch {
118204
- return;
118243
+ if (regionHunks.length === 1) {
118244
+ if (hunk.abLength > 0) {
118245
+ const buffer = hunk.ab === "a" ? a2 : b2;
118246
+ results.push({
118247
+ stable: true,
118248
+ buffer: hunk.ab,
118249
+ bufferStart: hunk.abStart,
118250
+ bufferLength: hunk.abLength,
118251
+ bufferContent: buffer.slice(hunk.abStart, hunk.abStart + hunk.abLength)
118252
+ });
118253
+ }
118254
+ } else {
118255
+ let bounds = {
118256
+ a: [a2.length, -1, o3.length, -1],
118257
+ b: [b2.length, -1, o3.length, -1]
118258
+ };
118259
+ while (regionHunks.length) {
118260
+ hunk = regionHunks.shift();
118261
+ const oStart = hunk.oStart;
118262
+ const oEnd = oStart + hunk.oLength;
118263
+ const abStart = hunk.abStart;
118264
+ const abEnd = abStart + hunk.abLength;
118265
+ let b22 = bounds[hunk.ab];
118266
+ b22[0] = Math.min(abStart, b22[0]);
118267
+ b22[1] = Math.max(abEnd, b22[1]);
118268
+ b22[2] = Math.min(oStart, b22[2]);
118269
+ b22[3] = Math.max(oEnd, b22[3]);
118270
+ }
118271
+ const aStart = bounds.a[0] + (regionStart - bounds.a[2]);
118272
+ const aEnd = bounds.a[1] + (regionEnd - bounds.a[3]);
118273
+ const bStart = bounds.b[0] + (regionStart - bounds.b[2]);
118274
+ const bEnd = bounds.b[1] + (regionEnd - bounds.b[3]);
118275
+ let result = {
118276
+ stable: false,
118277
+ aStart,
118278
+ aLength: aEnd - aStart,
118279
+ aContent: a2.slice(aStart, aEnd),
118280
+ oStart: regionStart,
118281
+ oLength: regionEnd - regionStart,
118282
+ oContent: o3.slice(regionStart, regionEnd),
118283
+ bStart,
118284
+ bLength: bEnd - bStart,
118285
+ bContent: b2.slice(bStart, bEnd)
118286
+ };
118287
+ results.push(result);
118205
118288
  }
118206
- for (const name of names2) if (name !== "node_modules" && name !== ".git") visit(path28.join(p2, name));
118207
- };
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)]));
118289
+ currOffset = regionEnd;
118217
118290
  }
118218
- return v;
118291
+ advanceTo(o3.length);
118292
+ return results;
118219
118293
  }
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();
118294
+ function diff3Merge(a2, o3, b2, options) {
118295
+ let defaults = {
118296
+ excludeFalseConflicts: true,
118297
+ stringSeparator: /\s+/
118298
+ };
118299
+ options = Object.assign(defaults, options);
118300
+ if (typeof a2 === "string")
118301
+ a2 = a2.split(options.stringSeparator);
118302
+ if (typeof o3 === "string")
118303
+ o3 = o3.split(options.stringSeparator);
118304
+ if (typeof b2 === "string")
118305
+ b2 = b2.split(options.stringSeparator);
118306
+ let results = [];
118307
+ const regions = diff3MergeRegions(a2, o3, b2);
118308
+ let okBuffer = [];
118309
+ function flushOk() {
118310
+ if (okBuffer.length) {
118311
+ results.push({ ok: okBuffer });
118312
+ }
118313
+ okBuffer = [];
118231
118314
  }
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() };
118315
+ function isFalseConflict(a22, b22) {
118316
+ if (a22.length !== b22.length)
118317
+ return false;
118318
+ for (let i = 0; i < a22.length; i++) {
118319
+ if (a22[i] !== b22[i])
118320
+ return false;
118242
118321
  }
118243
- return copy(last2.value);
118244
- };
118245
- }
118246
-
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;
118322
+ return true;
118259
118323
  }
118324
+ regions.forEach((region) => {
118325
+ if (region.stable) {
118326
+ okBuffer.push(...region.bufferContent);
118327
+ } else {
118328
+ if (options.excludeFalseConflicts && isFalseConflict(region.aContent, region.bContent)) {
118329
+ okBuffer.push(...region.aContent);
118330
+ } else {
118331
+ flushOk();
118332
+ results.push({
118333
+ conflict: {
118334
+ a: region.aContent,
118335
+ aIndex: region.aStart,
118336
+ o: region.oContent,
118337
+ oIndex: region.oStart,
118338
+ b: region.bContent,
118339
+ bIndex: region.bStart
118340
+ }
118341
+ });
118342
+ }
118343
+ }
118344
+ });
118345
+ flushOk();
118346
+ return results;
118260
118347
  }
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 });
118348
+
118349
+ // ../cli/src/lib/shared/triage-files.ts
118350
+ var ITEM = /^triage\/(?:(dismissed|archived)\/)?([^/]+)\.md$/;
118351
+ function itemAt(path51) {
118352
+ const m = ITEM.exec(path51);
118353
+ if (!m) return null;
118354
+ return { state: m[1] === "dismissed" ? "dismissed" : m[1] === "archived" ? "carded" : "open", name: m[2] };
118276
118355
  }
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) ?? [] : [];
118356
+ function stampItem(content, fields) {
118357
+ const lines = content.split("\n");
118358
+ const close = lines.indexOf("---", 1);
118359
+ if (close < 0) return content;
118360
+ const kept4 = lines.slice(1, close).filter((line) => {
118361
+ const key = /^([a-z_]+):/.exec(line);
118362
+ return !key || fields[key[1]] === void 0;
118297
118363
  });
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 };
118364
+ const added = Object.entries(fields).flatMap(([k2, v]) => v === null ? [] : [`${k2}: ${yamlScalar(v)}`]);
118365
+ return ["---", ...kept4, ...added, ...lines.slice(close)].join("\n");
118329
118366
  }
118330
118367
 
118331
118368
  // ../cli/src/lib/preview-validation.ts
@@ -118459,7 +118496,7 @@ function openTaskFolder(job, projectDir2) {
118459
118496
  markUsed(projectDir2);
118460
118497
  const board = path34.join(projectDir2, ".akb", "kanban");
118461
118498
  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 };
118499
+ return { task, cloudTask: task, board, cwd: projectDir2, project: job.project, number: job.number ?? null, studio: job.studio ?? job.flow?.studio ?? null };
118463
118500
  }
118464
118501
  function openAgentFolder(job, projectDir2) {
118465
118502
  if (!job.project || !job.agent) throw new Error("This job names no project.");
@@ -118468,13 +118505,13 @@ function openAgentFolder(job, projectDir2) {
118468
118505
  const board = path34.join(projectDir2, ".akb", "kanban");
118469
118506
  fs30.mkdirSync(board, { recursive: true });
118470
118507
  return {
118471
- task: `agent-${safe2(job.agent.workflow ? `${job.agent.workflow}-${job.agent.name}` : job.agent.name)}`,
118508
+ task: `agent-${safe2(job.agent.studio ? `${job.agent.studio}-${job.agent.name}` : job.agent.name)}`,
118472
118509
  cloudTask: job.agent.tasks?.[0]?.id ?? null,
118473
118510
  board,
118474
118511
  cwd: projectDir2,
118475
118512
  project: job.project,
118476
118513
  number: null,
118477
- workflow: job.agent.workflow ?? null
118514
+ studio: job.agent.studio ?? null
118478
118515
  };
118479
118516
  }
118480
118517
  function openDiscussionFolder(job, projectDir2) {
@@ -118483,9 +118520,9 @@ function openDiscussionFolder(job, projectDir2) {
118483
118520
  markUsed(projectDir2);
118484
118521
  const board = path34.join(projectDir2, ".akb", "kanban");
118485
118522
  fs30.mkdirSync(board, { recursive: true });
118486
- return { task: "discussion", cloudTask: null, board, cwd: projectDir2, project: job.project, number: null, workflow: null };
118523
+ return { task: "discussion", cloudTask: null, board, cwd: projectDir2, project: job.project, number: null, studio: null };
118487
118524
  }
118488
- var boardFolder = (ws) => ({ task: "board", cloudTask: null, board: ws.board, cwd: ws.cwd, project: ws.project, number: null, workflow: null });
118525
+ var boardFolder = (ws) => ({ task: "board", cloudTask: null, board: ws.board, cwd: ws.cwd, project: ws.project, number: null, studio: null });
118489
118526
  function keptBoard(cwd) {
118490
118527
  const board = path34.join(cwd, ".akb", "kanban");
118491
118528
  const base = readBase({ cwd });
@@ -118652,26 +118689,26 @@ function pullTools(ws, record, files) {
118652
118689
  record.tools = { skills, mcp };
118653
118690
  }
118654
118691
  var mcpServersOf = (ws) => readRecord(ws).tools?.mcp ?? {};
118655
- async function workflowFiles(ws) {
118656
- const workflow = ws.workflow;
118692
+ async function studioFiles(ws) {
118693
+ const studio = ws.studio;
118657
118694
  if (ws.cloudTask && ws.cloudTask === ws.task) {
118658
118695
  const pin = readPin(ws.cloudTask);
118659
- const held4 = pin && readVersion2(pin.workflow, pin.version);
118696
+ const held4 = pin && readVersion2(pin.studio, pin.version);
118660
118697
  if (held4) return { ok: true, value: held4.files };
118661
- const read5 = await readTaskWorkflow(ws.cloudTask);
118698
+ const read5 = await readTaskStudio(ws.cloudTask);
118662
118699
  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 });
118700
+ savePin(ws.cloudTask, { id: read5.value.studio, version: read5.value.version, name: read5.value.name ?? read5.value.studio, files: read5.value.files });
118664
118701
  return { ok: true, value: read5.value.files };
118665
118702
  }
118666
- const read4 = await readWorkflow(workflow);
118703
+ const read4 = await readStudio(studio);
118667
118704
  if (!read4.ok) return read4;
118668
- saveVersion({ id: workflow, version: read4.value.version, name: read4.value.name ?? workflow, files: read4.value.files });
118705
+ saveVersion({ id: studio, version: read4.value.version, name: read4.value.name ?? studio, files: read4.value.files });
118669
118706
  return { ok: true, value: read4.value.files };
118670
118707
  }
118671
- async function pullWorkflow(ws, record) {
118672
- if (ws.workflow) {
118673
- record.builtin = ws.workflow.startsWith("wf_builtin_");
118674
- const files = await workflowFiles(ws);
118708
+ async function pullStudio(ws, record) {
118709
+ if (ws.studio) {
118710
+ record.builtin = ws.studio.startsWith("wf_builtin_");
118711
+ const files = await studioFiles(ws);
118675
118712
  if (!files.ok && files.code !== "not_found") return files;
118676
118713
  if (files.ok) pullTools(ws, record, files.value);
118677
118714
  }
@@ -118694,8 +118731,8 @@ function dropPlacedAgents(ws) {
118694
118731
  fs30.rmSync(agentsRecord(ws), { force: true });
118695
118732
  }
118696
118733
  function pullDraftAgents(ws, record) {
118697
- if (ws.workflow !== BUILDER) return;
118698
- const root2 = path34.join(ws.board, "workflows", draftFolder(ws.task), "agents");
118734
+ if (ws.studio !== BUILDER) return;
118735
+ const root2 = path34.join(ws.board, "studios", draftFolder(ws.task), "agents");
118699
118736
  record.agents ??= {};
118700
118737
  for (const name of filesUnder(root2)) {
118701
118738
  const text3 = fs30.readFileSync(path34.join(root2, name));
@@ -118815,8 +118852,8 @@ async function readCloud(ws) {
118815
118852
  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
118853
  reset(view);
118817
118854
  const record = readRecord(ws);
118818
- const workflow = await pullWorkflow(ws, record);
118819
- if (!workflow.ok) return workflow;
118855
+ const studio = await pullStudio(ws, record);
118856
+ if (!studio.ok) return studio;
118820
118857
  pullDraftAgents(ws, record);
118821
118858
  reset(viewOf(ws, base, sharedMemory(ws.board)));
118822
118859
  const assets = await pullAssets(ws, record, assetsOf(assetsListOf(ws, base)));
@@ -119135,7 +119172,7 @@ function proposeItems(ws, base) {
119135
119172
  const said = (key) => new RegExp(`^${key}:`, "m").test(content.split(/\n---/)[0] ?? "");
119136
119173
  const fields = {
119137
119174
  ...ws.cloudTask && !said("source_task") ? { source_task: ws.cloudTask } : {},
119138
- ...ws.workflow && !said("workflow") ? { workflow: workflowName(ws.workflow) } : {}
119175
+ ...ws.studio && !said("studio") ? { studio: studioName(ws.studio) } : {}
119139
119176
  };
119140
119177
  const stamped = Object.keys(fields).length ? stampItem(content, fields) : content;
119141
119178
  if (stamped !== content) write(file3, stamped);
@@ -119733,7 +119770,7 @@ function parseFrontmatter(text3) {
119733
119770
  delete meta.release;
119734
119771
  delete meta.schedule;
119735
119772
  delete meta.roi;
119736
- meta.workflow = typeof meta.workflow === "string" && meta.workflow.trim() ? meta.workflow.trim() : "";
119773
+ meta.studio = typeof meta.studio === "string" && meta.studio.trim() ? meta.studio.trim() : "";
119737
119774
  meta.triage = typeof meta.triage === "string" ? meta.triage.trim() : "";
119738
119775
  meta.source = (Array.isArray(meta.source) ? meta.source : typeof meta.source === "string" ? [meta.source] : []).map((ref) => String(ref).trim()).filter(Boolean);
119739
119776
  delete meta.phases;
@@ -119807,7 +119844,7 @@ ${item.text.trim()}
119807
119844
  function writeItem(dir, item, fields = {}) {
119808
119845
  fs34.mkdirSync(dir, { recursive: true });
119809
119846
  const name = freeName(dir, item.title);
119810
- fs34.writeFileSync(path37.join(dir, name), itemText(item, item.workflow ? { workflow: workflowName(item.workflow), ...fields } : fields));
119847
+ fs34.writeFileSync(path37.join(dir, name), itemText(item, item.studio ? { studio: studioName(item.studio), ...fields } : fields));
119811
119848
  return name;
119812
119849
  }
119813
119850
  function layOut(board, rejections) {
@@ -119875,19 +119912,19 @@ function installCommitHook(root2, _board) {
119875
119912
  // src/built.ts
119876
119913
  import fs36 from "node:fs";
119877
119914
  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("/")}/ -->`;
119915
+ var isBuilder = (ws) => ws.studio === BUILDER;
119916
+ var draftDir = (ws) => path39.join(ws.board, "studios", draftFolder(ws.task));
119917
+ var draftLine = (ws) => `<!-- studio folder: ${path39.relative(ws.cwd, draftDir(ws)).split(path39.sep).join("/")}/ -->`;
119881
119918
  var skeleton = (name) => ["---", `name: ${/\s#/.test(name) ? JSON.stringify(name) : yamlScalar(name)}`, "needsArtifact: false", "---", ""].join("\n");
119882
119919
  async function placeDraft(ws, read4) {
119883
119920
  const dir = draftDir(ws);
119884
- if (fs36.existsSync(path39.join(dir, WORKFLOW_FILE))) return { ok: true, value: void 0 };
119921
+ if (fs36.existsSync(path39.join(dir, STUDIO_FILE))) return { ok: true, value: void 0 };
119885
119922
  const task = await read4.readTask(ws.task);
119886
119923
  if (!task.ok) return task;
119887
- let files = { [WORKFLOW_FILE]: skeleton(task.value.title.trim() || "Untitled") };
119888
- const changes = task.value.context?.workflow;
119924
+ let files = { [STUDIO_FILE]: skeleton(task.value.title.trim() || "Untitled") };
119925
+ const changes = task.value.context?.studio;
119889
119926
  if (changes) {
119890
- const held4 = await read4.readWorkflow(changes);
119927
+ const held4 = await read4.readStudio(changes);
119891
119928
  if (!held4.ok) return held4;
119892
119929
  files = held4.value.files;
119893
119930
  }
@@ -119899,17 +119936,25 @@ async function placeDraft(ws, read4) {
119899
119936
  }
119900
119937
  return { ok: true, value: void 0 };
119901
119938
  }
119939
+ function draftBase(ws) {
119940
+ try {
119941
+ const version = JSON.parse(fs36.readFileSync(path39.join(draftDir(ws), VERSION_FILE), "utf8")).version;
119942
+ return Number.isInteger(version) ? version : void 0;
119943
+ } catch {
119944
+ return void 0;
119945
+ }
119946
+ }
119902
119947
  var named = (def) => [...new Set([...def.previews, ...def.land, ...def.scheduled].map((h3) => h3.agent))];
119903
- async function builtWorkflow(ws, akb) {
119948
+ async function builtStudio(ws, akb) {
119904
119949
  if (!isBuilder(ws)) return null;
119905
119950
  const id = draftFolder(ws.task);
119906
119951
  const dir = draftDir(ws);
119907
119952
  let source = "";
119908
119953
  try {
119909
- source = fs36.readFileSync(path39.join(dir, WORKFLOW_FILE), "utf8");
119954
+ source = fs36.readFileSync(path39.join(dir, STUDIO_FILE), "utf8");
119910
119955
  } catch {
119911
119956
  }
119912
- const read4 = parseWorkflowFile(id, source, `workflows/${id}/${WORKFLOW_FILE}`);
119957
+ const read4 = parseStudioFile(id, source, `studios/${id}/${STUDIO_FILE}`);
119913
119958
  const names2 = "def" in read4 ? named(read4.def) : [];
119914
119959
  const agents = path39.join(dir, "agents");
119915
119960
  if ("def" in read4) {
@@ -120229,24 +120274,24 @@ async function scheduledEnv(ws, deps) {
120229
120274
  console.error(`runner: scheduled agents not read: ${read4.error}`);
120230
120275
  return {};
120231
120276
  }
120232
- const names2 = read4.value.agents.filter((a2) => a2.workflow).map((a2) => a2.name);
120277
+ const names2 = read4.value.agents.filter((a2) => a2.studio).map((a2) => a2.name);
120233
120278
  return { [SCHEDULED_AGENTS_ENV]: [...new Set(names2)].join(",") };
120234
120279
  }
120235
120280
  async function runAgent(job, ws, deps, io) {
120236
120281
  const since = Date.now();
120237
120282
  const failed = await setUp(job, ws, deps, io);
120238
120283
  if (failed) return { ok: false, reason: failed };
120239
- const { name, workflow, tasks } = job.agent;
120284
+ const { name, studio, tasks } = job.agent;
120240
120285
  if (name === "review-dismissals") {
120241
120286
  const { runs: runs2, failure: failure2 } = await reviewRejections(job, ws, deps, io);
120242
120287
  if (io.lost()) return { ok: false, reason: "" };
120243
120288
  return failure2 ? { ok: false, reason: failure2 } : { ok: true, report: spentBy(runs2, job) };
120244
120289
  }
120245
120290
  if (name === "reflect" && !tasks?.length) return { ok: true, report: {} };
120246
- 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]];
120291
+ 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]];
120247
120292
  const akb = boardAkb(job, ws, deps, io, ws.cloudTask ?? void 0);
120248
120293
  await akb(["raw", "run", "list", "--all", "--json"]);
120249
- const env2 = name === "reflect" && !workflow ? await scheduledEnv(ws, deps) : void 0;
120294
+ const env2 = name === "reflect" && !studio ? await scheduledEnv(ws, deps) : void 0;
120250
120295
  const ran = await akb([...args, "--follow", "--events", "--json"], true, env2);
120251
120296
  if (io.lost()) return { ok: false, reason: "" };
120252
120297
  const answer = answerOf2(ran);
@@ -120320,8 +120365,8 @@ ${draftLine(ws)}
120320
120365
  "create",
120321
120366
  "--title",
120322
120367
  title,
120323
- "--workflow",
120324
- workflowName(flow.workflow),
120368
+ "--studio",
120369
+ studioName(flow.studio),
120325
120370
  "--body-file",
120326
120371
  body,
120327
120372
  "--id",
@@ -121427,7 +121472,7 @@ async function runClaimed(job, deps, track, keep2, lease, replyStream) {
121427
121472
  discussed = board.board;
121428
121473
  }
121429
121474
  if (job.discussion) {
121430
- const wrote = recovering && fs42.existsSync(goalsFileOf(job)) ? { file: goalsFileOf(job) } : await writeGoals({ ...job, discussion: job.discussion }, deps.api.listWorkflows);
121475
+ const wrote = recovering && fs42.existsSync(goalsFileOf(job)) ? { file: goalsFileOf(job) } : await writeGoals({ ...job, discussion: job.discussion }, deps.api.listStudios);
121431
121476
  if ("error" in wrote) throw new Error(wrote.error);
121432
121477
  goalFile = wrote.file;
121433
121478
  }
@@ -121840,8 +121885,8 @@ async function finish(deps, id, lease, outcome, reason = "", report2) {
121840
121885
  }
121841
121886
  async function sendBack(deps, id, lease, ws, said, landed = () => {
121842
121887
  }) {
121843
- const built = await builtWorkflow(ws, deps.akb);
121844
- const report2 = built ? { ...said, workflow: { files: built } } : said;
121888
+ const built = await builtStudio(ws, deps.akb);
121889
+ const report2 = built ? { ...said, studio: { files: built, base: draftBase(ws) } } : said;
121845
121890
  const pushed = await whileOffline(deps, id, lease, () => push(ws, { id, machineId: deps.machineId }));
121846
121891
  if (!pushed) return;
121847
121892
  if (pushed.ok) {
@@ -122109,6 +122154,7 @@ function startRunner(options) {
122109
122154
  try {
122110
122155
  sweepAkb();
122111
122156
  await sweepCache(registration.machineId);
122157
+ await sweepStudios();
122112
122158
  } catch (e2) {
122113
122159
  console.error(`runner: the cache was not cleaned: ${e2 instanceof Error ? e2.message : String(e2)}`);
122114
122160
  } finally {
@@ -122358,6 +122404,19 @@ var CREST = "M44.97 27.45C44.61 26.89 46.57 25.76 47.87 25.76C48.72 25.76 50.6 2
122358
122404
  var COPY = {
122359
122405
  zh: {
122360
122406
  choose: ["\u767B\u5F55 WildCrane", "\u9009\u62E9\u767B\u5F55\u65B9\u5F0F\uFF0C\u5B8C\u6210\u540E\u56DE\u5230 WildCrane\u3002"],
122407
+ email: "name@company.com",
122408
+ send: "\u53D1\u9001\u9A8C\u8BC1\u7801",
122409
+ sending: "\u6B63\u5728\u53D1\u9001\u2026",
122410
+ or: "\u6216",
122411
+ sent: "\u9A8C\u8BC1\u7801\u5DF2\u53D1\u9001\u81F3 ",
122412
+ code: "6 \u4F4D\u9A8C\u8BC1\u7801",
122413
+ submit: "\u767B\u5F55",
122414
+ verifying: "\u6B63\u5728\u767B\u5F55\u2026",
122415
+ change: "\u6362\u4E2A\u90AE\u7BB1",
122416
+ badEmail: "\u8BF7\u8F93\u5165\u6709\u6548\u7684\u90AE\u7BB1\u3002",
122417
+ badCode: "\u9A8C\u8BC1\u7801\u9519\u8BEF\u6216\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u6216\u91CD\u65B0\u53D1\u9001\u3002",
122418
+ tooMany: "\u8BF7\u6C42\u592A\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002",
122419
+ error: "\u767B\u5F55\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u3002",
122361
122420
  github: "\u7528 GitHub \u767B\u5F55",
122362
122421
  google: "\u7528 Google \u767B\u5F55",
122363
122422
  ok: ["\u5DF2\u767B\u5F55 WildCrane", "\u53EF\u4EE5\u5173\u95ED\u6B64\u9875\u9762\uFF0C\u56DE\u5230 WildCrane \u7EE7\u7EED\u3002"],
@@ -122366,6 +122425,19 @@ var COPY = {
122366
122425
  },
122367
122426
  en: {
122368
122427
  choose: ["Sign in to WildCrane", "Choose how to sign in, then return to WildCrane."],
122428
+ email: "name@company.com",
122429
+ send: "Send code",
122430
+ sending: "Sending\u2026",
122431
+ or: "or",
122432
+ sent: "We sent a code to ",
122433
+ code: "6-digit code",
122434
+ submit: "Sign in",
122435
+ verifying: "Signing in\u2026",
122436
+ change: "Use a different email",
122437
+ badEmail: "Enter a valid email.",
122438
+ badCode: "That code is wrong or has expired. Try again or resend it.",
122439
+ tooMany: "Too many attempts. Try again in a moment.",
122440
+ error: "Sign-in didn't finish. Try again.",
122369
122441
  github: "Sign in with GitHub",
122370
122442
  google: "Sign in with Google",
122371
122443
  ok: ["Signed in to WildCrane", "You can close this page and return to WildCrane."],
@@ -122376,13 +122448,24 @@ var COPY = {
122376
122448
  var langOf = (accept) => /^\s*zh\b/i.test(accept ?? "") ? "zh" : "en";
122377
122449
  var GITHUB_ICON = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/></svg>';
122378
122450
  var GOOGLE_ICON = '<svg viewBox="0 0 48 48" width="17" height="17" aria-hidden="true"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/></svg>';
122451
+ var EMAIL_SCRIPT = (c2) => `(()=>{const t=${JSON.stringify({
122452
+ send: c2.send,
122453
+ sending: c2.sending,
122454
+ sent: c2.sent,
122455
+ submit: c2.submit,
122456
+ verifying: c2.verifying,
122457
+ badEmail: c2.badEmail,
122458
+ badCode: c2.badCode,
122459
+ tooMany: c2.tooMany,
122460
+ error: c2.error
122461
+ }).replace(/</g, "\\u003c")};const $=(i)=>document.getElementById(i),f=$('f'),e=$('e'),c=$('c'),b=$('b'),m=$('m'),x=$('x');let to='';const say=(s,bad)=>{m.textContent=s;m.className=bad?'bad':''};const step=(code)=>{to=code?e.value.trim():'';e.hidden=!!code;c.hidden=!code;x.hidden=!code;b.textContent=code?t.submit:t.send;if(code){say(t.sent+to);c.value='';c.focus()}else{say('');e.focus()}};x.onclick=()=>step(false);f.onsubmit=async(ev)=>{ev.preventDefault();const verify=!!to;if(!verify&&!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(e.value.trim()))return say(t.badEmail,true);b.disabled=true;b.textContent=verify?t.verifying:t.sending;let r={error:'failed'};try{r=await (await fetch(verify?'/verify':'/send',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(verify?{email:to,code:c.value.trim()}:{email:e.value.trim()})})).json()}catch{}b.disabled=false;if(r.ok){if(!verify)return step(true);document.open();document.write(r.page);return document.close()}b.textContent=verify?t.submit:t.send;say(r.error==='bad_code'?t.badCode:r.error==='too_many'?t.tooMany:t.error,true)}})()`;
122379
122462
  var PAGE = (outcome, lang, links) => {
122380
122463
  const c2 = COPY[lang];
122381
122464
  const [title, body] = c2[outcome];
122382
122465
  const ok = outcome === "ok";
122383
122466
  const icon = ok ? '<polyline points="20 6 9 17 4 12"/>' : '<path d="M18 6 6 18M6 6l12 12"/>';
122384
- const top = links ? `<h1>${title}</h1><p>${body}</p><nav><a class="dark" href="${links.github}">${GITHUB_ICON}${c2.github}</a><a href="${links.google}">${GOOGLE_ICON}${c2.google}</a></nav>` : `<span class="icon"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${icon}</svg></span><h1 class="below">${title}</h1><p>${body}</p>`;
122385
- return `<!doctype html><html lang="${lang === "zh" ? "zh-CN" : "en"}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} \xB7 WildCrane</title><style>*{margin:0;box-sizing:border-box}body{display:flex;flex-direction:column;min-height:100dvh;background:#fff;color:#24231f;font-family:ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}header{padding:16px 36px 0}main{flex:1;display:flex;align-items:center;justify-content:center;padding:0 36px 64px;text-align:center}.icon{display:flex;margin:0 auto;width:44px;height:44px;border-radius:50%;align-items:center;justify-content:center;background:${ok ? "#e4f3ea" : "#f7ddce"};color:${ok ? "#2f6b46" : "#b83a12"}}h1{font-size:24px;font-weight:850;line-height:1.25;letter-spacing:-0.02em}h1.below{margin-top:16px}p{margin:8px auto 0;max-width:38ch;font-size:13px;line-height:19px;color:#565550}main>div.choose{width:100%;max-width:320px}nav{margin-top:28px;display:flex;flex-direction:column;gap:12px}nav a{display:flex;height:44px;align-items:center;justify-content:center;gap:8px;border-radius:10px;font-size:14.5px;font-weight:600;color:#24231f;text-decoration:none;background:#fff;border:1px solid rgba(36,35,31,0.14)}nav a.dark{background:#24231f;color:#fff;border-color:#24231f}</style><header><svg viewBox="2 4 56 52" width="23.7" height="22" aria-hidden="true"><path d="${CRANE}" fill="#24231f"/><path d="${CREST}" fill="#dd4f1e"/></svg></header><main><div${links ? ' class="choose"' : ""}>${top}</div></main></html>`;
122467
+ const top = links ? `<h1>${title}</h1><p>${body}</p><form id="f" novalidate><input id="e" type="email" autocomplete="email" placeholder="${c2.email}" required><input id="c" inputmode="numeric" autocomplete="one-time-code" maxlength="10" placeholder="${c2.code}" hidden><button id="b" class="dark">${c2.send}</button><small id="m"></small><button id="x" type="button" class="link" hidden>${c2.change}</button></form><div class="or">${c2.or}</div><nav><a href="${links.github}">${GITHUB_ICON}${c2.github}</a><a href="${links.google}">${GOOGLE_ICON}${c2.google}</a></nav><script>${EMAIL_SCRIPT(c2)}</script>` : `<span class="icon"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${icon}</svg></span><h1 class="below">${title}</h1><p>${body}</p>`;
122468
+ return `<!doctype html><html lang="${lang === "zh" ? "zh-CN" : "en"}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} \xB7 WildCrane</title><style>*{margin:0;box-sizing:border-box}body{display:flex;flex-direction:column;min-height:100dvh;background:#fff;color:#24231f;font-family:ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}header{padding:16px 36px 0}main{flex:1;display:flex;align-items:center;justify-content:center;padding:0 36px 64px;text-align:center}.icon{display:flex;margin:0 auto;width:44px;height:44px;border-radius:50%;align-items:center;justify-content:center;background:${ok ? "#e4f3ea" : "#f7ddce"};color:${ok ? "#2f6b46" : "#b83a12"}}h1{font-size:24px;font-weight:850;line-height:1.25;letter-spacing:-0.02em}h1.below{margin-top:16px}p{margin:8px auto 0;max-width:38ch;font-size:13px;line-height:19px;color:#565550}main>div.choose{width:100%;max-width:320px}nav{margin-top:28px;display:flex;flex-direction:column;gap:12px}nav a{display:flex;height:44px;align-items:center;justify-content:center;gap:8px;border-radius:10px;font-size:14.5px;font-weight:600;color:#24231f;text-decoration:none;background:#fff;border:1px solid rgba(36,35,31,0.14)}nav a.dark{background:#24231f;color:#fff;border-color:#24231f}form{margin-top:28px;display:flex;flex-direction:column;gap:12px}input{height:44px;padding:0 14px;border-radius:10px;border:1px solid rgba(36,35,31,0.14);font:inherit;font-size:14.5px}button{height:44px;border-radius:10px;border:0;font:inherit;font-size:14.5px;font-weight:600;cursor:pointer}button.dark{background:#24231f;color:#fff}button:disabled{opacity:.6}button.link{height:auto;background:none;color:#565550;font-size:13px;font-weight:500}small{font-size:13px;line-height:19px;color:#565550}small.bad{color:#b83a12}small:empty{display:none}.or{margin-top:20px;display:flex;align-items:center;gap:12px;font-size:13px;color:#8a8984}.or::before,.or::after{content:"";flex:1;height:1px;background:rgba(36,35,31,0.12)}.or+nav{margin-top:20px}</style><header><svg viewBox="2 4 56 52" width="23.7" height="22" aria-hidden="true"><path d="${CRANE}" fill="#24231f"/><path d="${CREST}" fill="#dd4f1e"/></svg></header><main><div${links ? ' class="choose"' : ""}>${top}</div></main></html>`;
122386
122469
  };
122387
122470
  async function signIn(options = {}) {
122388
122471
  const generation = accountGeneration();
@@ -122400,6 +122483,18 @@ async function signIn(options = {}) {
122400
122483
  res.end(PAGE("choose", lang, { github: authorize("github"), google: authorize("google") }));
122401
122484
  return;
122402
122485
  }
122486
+ if (req.method === "POST" && (asked.pathname === "/send" || asked.pathname === "/verify") && !answering) {
122487
+ const asks2 = await readJson2(req);
122488
+ const answer = asked.pathname === "/send" ? await sendCode(asks2.email ?? "", lang) : await verifyCode(asks2.email ?? "", asks2.code ?? "", generation, options.signal);
122489
+ const done = answer.ok && asked.pathname === "/verify";
122490
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
122491
+ res.end(JSON.stringify(done ? { ...answer, page: PAGE("ok", lang) } : answer));
122492
+ if (done) {
122493
+ answering = true;
122494
+ finish2(null);
122495
+ }
122496
+ return;
122497
+ }
122403
122498
  if (asked.pathname !== "/signed-in" || answering) {
122404
122499
  res.writeHead(404).end();
122405
122500
  return;
@@ -122443,14 +122538,9 @@ async function signIn(options = {}) {
122443
122538
  return failure2;
122444
122539
  }
122445
122540
  async function exchange(code, verifier, generation, signal2) {
122446
- const { supabaseUrl, anonKey } = cloudEndpoints();
122447
122541
  let response;
122448
122542
  try {
122449
- response = await fetch(`${supabaseUrl}/auth/v1/token?grant_type=pkce`, {
122450
- method: "POST",
122451
- headers: { apikey: anonKey, "content-type": "application/json" },
122452
- body: JSON.stringify({ auth_code: code, code_verifier: verifier })
122453
- });
122543
+ response = await authCall("token?grant_type=pkce", { auth_code: code, code_verifier: verifier });
122454
122544
  } catch (e2) {
122455
122545
  return { why: "unreachable", detail: e2 instanceof Error ? e2.message : String(e2) };
122456
122546
  }
@@ -122460,6 +122550,50 @@ async function exchange(code, verifier, generation, signal2) {
122460
122550
  writeSession(session);
122461
122551
  return null;
122462
122552
  }
122553
+ var authCall = (path51, body) => {
122554
+ const { api, anonKey } = cloudEndpoints();
122555
+ return fetch(`${api}/auth/v1/${path51}`, {
122556
+ method: "POST",
122557
+ headers: { apikey: anonKey, "content-type": "application/json" },
122558
+ body: JSON.stringify(body),
122559
+ signal: AbortSignal.timeout(2e4)
122560
+ });
122561
+ };
122562
+ var refusal3 = (status2) => ({ ok: false, error: status2 === 429 ? "too_many" : status2 === 400 || status2 === 401 || status2 === 403 ? "bad_code" : "failed" });
122563
+ async function sendCode(email, lang) {
122564
+ try {
122565
+ const response = await authCall("otp", { email: email.trim(), create_user: true, data: { lang } });
122566
+ return response.ok ? { ok: true } : { ok: false, error: response.status === 429 ? "too_many" : "failed" };
122567
+ } catch {
122568
+ return { ok: false, error: "failed" };
122569
+ }
122570
+ }
122571
+ async function verifyCode(email, code, generation, signal2) {
122572
+ let response;
122573
+ try {
122574
+ response = await authCall("verify", { type: "email", email: email.trim(), token: code.trim() });
122575
+ } catch {
122576
+ return { ok: false, error: "failed" };
122577
+ }
122578
+ if (!response.ok) return refusal3(response.status);
122579
+ const session = sessionFrom(await response.json().catch(() => ({})));
122580
+ if (!session) return { ok: false, error: "failed" };
122581
+ if (signal2?.aborted || accountGeneration() !== generation) return { ok: false, error: "failed" };
122582
+ writeSession(session);
122583
+ return { ok: true };
122584
+ }
122585
+ async function readJson2(req) {
122586
+ let text3 = "";
122587
+ for await (const chunk of req) {
122588
+ text3 += chunk;
122589
+ if (text3.length > 1e4) break;
122590
+ }
122591
+ try {
122592
+ return JSON.parse(text3);
122593
+ } catch {
122594
+ return {};
122595
+ }
122596
+ }
122463
122597
  function openBrowser(url) {
122464
122598
  const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
122465
122599
  try {