@kernlang/agon 0.1.2 → 0.1.4

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.
@@ -380,6 +380,7 @@ var DEFAULT_AGON_CONFIG = {
380
380
  allowedCommands: [],
381
381
  toolPermissions: {},
382
382
  hiddenEngines: [],
383
+ removedEngines: [],
383
384
  engineModels: {},
384
385
  engineEfforts: {},
385
386
  engineIsolation: "workspace-pure",
@@ -396,6 +397,7 @@ var DEFAULT_AGON_CONFIG = {
396
397
  var DEFAULT_CONFIG = DEFAULT_AGON_CONFIG;
397
398
 
398
399
  // ../core/src/generated/models/errors.ts
400
+ var AGON_MODE_NAMES = ["forge", "brainstorm", "tribunal", "campfire", "council", "synthesis", "conquer", "goal", "agent", "pipeline", "review", "nero", "think"];
399
401
  var AgonError = class extends Error {
400
402
  constructor(message) {
401
403
  super(message);
@@ -404,7 +406,8 @@ var AgonError = class extends Error {
404
406
  };
405
407
  var EngineNotFoundError = class extends AgonError {
406
408
  constructor(engineId, installHint) {
407
- const hint = installHint ? `. Install: ${installHint}` : "";
409
+ const modeId = engineId.toLowerCase();
410
+ const hint = AGON_MODE_NAMES.includes(modeId) ? `. "${engineId}" is an Agon mode (a command), not an engine \u2014 run /${modeId} instead. Engines are backends like codex, claude, or agy.` : installHint ? `. Install: ${installHint}` : "";
408
411
  super(`Engine "${engineId}" not found${hint}`);
409
412
  this.engineId = engineId;
410
413
  this.installHint = installHint;
@@ -504,6 +507,7 @@ function loadConfig(cwd) {
504
507
  const merged = { ...DEFAULT_AGON_CONFIG, ...global, ...local, ...localPrivate };
505
508
  if (!Array.isArray(merged.forgeEnabledEngines)) merged.forgeEnabledEngines = [];
506
509
  if (!Array.isArray(merged.hiddenEngines)) merged.hiddenEngines = [];
510
+ if (!Array.isArray(merged.removedEngines)) merged.removedEngines = [];
507
511
  if (!["auto", "explicit"].includes(String(merged.engineActivationMode))) merged.engineActivationMode = "auto";
508
512
  if (!merged.hooks || typeof merged.hooks === "string") merged.hooks = {};
509
513
  if (!merged.allowedCommands || typeof merged.allowedCommands === "string") merged.allowedCommands = [];
@@ -1703,7 +1707,7 @@ async function spawnWithTimeout(opts) {
1703
1707
  if (opts.signal?.aborted) {
1704
1708
  return { exitCode: 130, stdout: "", stderr: "Aborted", durationMs: 0, timedOut: false };
1705
1709
  }
1706
- return new Promise((resolve27) => {
1710
+ return new Promise((resolve28) => {
1707
1711
  const startTime = Date.now();
1708
1712
  let timedOut = false;
1709
1713
  let aborted2 = false;
@@ -1719,7 +1723,7 @@ async function spawnWithTimeout(opts) {
1719
1723
  if (forceKillTimer) clearTimeout(forceKillTimer);
1720
1724
  if (forceFinishTimer) clearTimeout(forceFinishTimer);
1721
1725
  if (opts.signal) opts.signal.removeEventListener("abort", onAbort);
1722
- resolve27(result);
1726
+ resolve28(result);
1723
1727
  }
1724
1728
  const child = spawn(opts.command, opts.args, {
1725
1729
  cwd: opts.cwd,
@@ -16361,8 +16365,8 @@ var EngineRegistry = class {
16361
16365
  return this.availableEngines().map((e) => e.id);
16362
16366
  }
16363
16367
  activeEngines(config2) {
16364
- const hidden = new Set(config2?.hiddenEngines ?? []);
16365
- const available = this.availableEngines().filter((e) => !hidden.has(e.id));
16368
+ const excluded = /* @__PURE__ */ new Set([...config2?.hiddenEngines ?? [], ...config2?.removedEngines ?? []]);
16369
+ const available = this.availableEngines().filter((e) => !excluded.has(e.id));
16366
16370
  if (!config2 || config2.engineActivationMode !== "explicit") {
16367
16371
  return available;
16368
16372
  }
@@ -16372,6 +16376,24 @@ var EngineRegistry = class {
16372
16376
  activeIds(config2) {
16373
16377
  return this.activeEngines(config2).map((e) => e.id);
16374
16378
  }
16379
+ partitionRoster(requested, config2) {
16380
+ if (!requested) {
16381
+ return { active: this.activeIds(config2), removed: [] };
16382
+ }
16383
+ const removedSet = new Set(config2?.removedEngines ?? []);
16384
+ const active = [];
16385
+ const removed = [];
16386
+ for (const raw of requested) {
16387
+ const id = this.resolveId(String(raw ?? "").trim());
16388
+ if (id && removedSet.has(id) && !removed.includes(id)) {
16389
+ removed.push(id);
16390
+ }
16391
+ if (id && !removedSet.has(id) && !active.includes(id)) {
16392
+ active.push(id);
16393
+ }
16394
+ }
16395
+ return { active, removed };
16396
+ }
16375
16397
  pickStarter(available, strategy, preferred) {
16376
16398
  if (available.length === 0) {
16377
16399
  throw new EngineNotFoundError("(any)", "No engines available");
@@ -16408,6 +16430,25 @@ var EngineRegistry = class {
16408
16430
  // ../core/src/generated/blocks/context-scanner.ts
16409
16431
  import { readFileSync as readFileSync8, readdirSync as readdirSync6, statSync as statSync6, existsSync as existsSync6 } from "fs";
16410
16432
  import { join as join9, basename } from "path";
16433
+ var PROJECT_BRIEF_FILES = [".agon/project.md", "AGON.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
16434
+ var MAX_PROJECT_BRIEF_BYTES = 512 * 1024;
16435
+ function projectBriefCap(file2) {
16436
+ return file2 === ".agon/project.md" || file2 === "AGON.md" ? 4e3 : 2e3;
16437
+ }
16438
+ function hasProjectBrief(cwd) {
16439
+ for (const file2 of PROJECT_BRIEF_FILES) {
16440
+ try {
16441
+ const path = join9(cwd, file2);
16442
+ const st = existsSync6(path) ? statSync6(path) : null;
16443
+ if (st && st.isFile() && st.size > 0) {
16444
+ if (st.size > MAX_PROJECT_BRIEF_BYTES) return true;
16445
+ if (readFileSync8(path, "utf-8").trim().length > 0) return true;
16446
+ }
16447
+ } catch {
16448
+ }
16449
+ }
16450
+ return false;
16451
+ }
16411
16452
  function isKernProject(cwd) {
16412
16453
  if (existsSync6(join9(cwd, "kern.config.ts"))) return true;
16413
16454
  try {
@@ -16519,14 +16560,15 @@ ${tree}`);
16519
16560
  ${diff}`);
16520
16561
  }
16521
16562
  }
16522
- const instructionFiles = ["AGON.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
16523
- for (const file2 of instructionFiles) {
16563
+ for (const file2 of PROJECT_BRIEF_FILES) {
16524
16564
  try {
16525
16565
  const path = join9(cwd, file2);
16526
16566
  if (existsSync6(path)) {
16527
16567
  const content = readFileSync8(path, "utf-8").trim();
16528
16568
  if (content) {
16529
- const capped = content.length > 2e3 ? content.slice(0, 2e3) + "\n... (truncated)" : content;
16569
+ const cap = projectBriefCap(file2);
16570
+ const capped = content.length > cap ? content.slice(0, cap) + `
16571
+ ... (truncated at ${cap} chars)` : content;
16530
16572
  sections.push(`Project instructions (${file2}):
16531
16573
  ${capped}`);
16532
16574
  break;
@@ -16551,20 +16593,235 @@ ${result}
16551
16593
  return result;
16552
16594
  }
16553
16595
 
16596
+ // ../core/src/generated/blocks/codebase-map.ts
16597
+ import { readFileSync as readFileSync9, readdirSync as readdirSync7, statSync as statSync7, lstatSync as lstatSync2, writeFileSync as writeFileSync7, mkdirSync as mkdirSync7, existsSync as existsSync7, rmSync as rmSync4 } from "fs";
16598
+ import { join as join10, relative as relative2 } from "path";
16599
+ import { createHash as createHash2 } from "crypto";
16600
+ var MAP_IGNORE_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "dist-tsc", ".next", ".cache", ".turbo", "__pycache__", ".venv", "venv", "coverage", ".kern-gaps", ".agon", ".claude", "worktrees", "build", "out", ".idea", ".vscode"]);
16601
+ var MAP_SOURCE_EXT = [".kern", ".ts", ".tsx", ".py", ".js", ".jsx"];
16602
+ var MAP_MAX_FILES_WALKED = 6e3;
16603
+ var MAP_MAX_FILES_READ = 600;
16604
+ var MAP_MAX_FILE_BYTES = 262144;
16605
+ var MAP_MEMO = /* @__PURE__ */ new Map();
16606
+ var MAP_LOCKFILES = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb"];
16607
+ var MAP_CACHE_TTL_MS = 6 * 60 * 60 * 1e3;
16608
+ function mapSourceExt(path) {
16609
+ const dot = path.lastIndexOf(".");
16610
+ if (dot < 0) return null;
16611
+ const ext = path.slice(dot);
16612
+ return MAP_SOURCE_EXT.includes(ext) ? ext : null;
16613
+ }
16614
+ function collectSourceFiles(root) {
16615
+ const out = [];
16616
+ const stack = [root];
16617
+ while (stack.length > 0 && out.length < MAP_MAX_FILES_WALKED) {
16618
+ const dir = stack.pop();
16619
+ let entries;
16620
+ try {
16621
+ entries = readdirSync7(dir);
16622
+ } catch {
16623
+ continue;
16624
+ }
16625
+ for (const entry of entries) {
16626
+ if (entry.startsWith(".DS_")) continue;
16627
+ const full = join10(dir, entry);
16628
+ let st;
16629
+ try {
16630
+ st = lstatSync2(full);
16631
+ } catch {
16632
+ continue;
16633
+ }
16634
+ if (st.isSymbolicLink()) continue;
16635
+ if (st.isDirectory()) {
16636
+ if (!MAP_IGNORE_DIRS.has(entry)) stack.push(full);
16637
+ continue;
16638
+ }
16639
+ if (mapSourceExt(entry)) out.push(relative2(root, full));
16640
+ if (out.length >= MAP_MAX_FILES_WALKED) break;
16641
+ }
16642
+ }
16643
+ out.sort();
16644
+ return out;
16645
+ }
16646
+ function extractSymbols(relPath, content) {
16647
+ const ext = mapSourceExt(relPath);
16648
+ const names = [];
16649
+ const push = (n) => {
16650
+ if (n && !names.includes(n)) names.push(n);
16651
+ };
16652
+ if (ext === ".kern") {
16653
+ const re = /\b(?:fn|service|union|interface|const|screen|machine|event|type)\s+name=([A-Za-z0-9_$]+)/g;
16654
+ let m;
16655
+ while ((m = re.exec(content)) !== null) push(m[1]);
16656
+ } else if (ext === ".py") {
16657
+ const re = /^\s*(?:async\s+)?(?:def|class)\s+([A-Za-z0-9_]+)/gm;
16658
+ let m;
16659
+ while ((m = re.exec(content)) !== null) push(m[1]);
16660
+ } else {
16661
+ const re = /^\s*export\s+(?:default\s+)?(?:async\s+)?(?:function|const|let|var|class|interface|type|enum)\s+([A-Za-z0-9_$]+)/gm;
16662
+ let m;
16663
+ while ((m = re.exec(content)) !== null) push(m[1]);
16664
+ }
16665
+ return names.slice(0, 12);
16666
+ }
16667
+ function topLevelGroup(relPath) {
16668
+ const parts = relPath.split("/");
16669
+ if (parts[0] === "packages" && parts.length > 1) return `packages/${parts[1]}`;
16670
+ if (parts.length > 1) return parts[0];
16671
+ return "(root)";
16672
+ }
16673
+ function mapCacheDir() {
16674
+ return agonPath("cache", "codebase-map");
16675
+ }
16676
+ function mapCacheKey(cwd) {
16677
+ return createHash2("sha1").update(cwd).digest("hex").slice(0, 16);
16678
+ }
16679
+ function mapCacheFile(cwd) {
16680
+ return join10(mapCacheDir(), `${mapCacheKey(cwd)}.json`);
16681
+ }
16682
+ function mapCacheSignature(cwd) {
16683
+ let head = "nogit";
16684
+ try {
16685
+ head = headSha(cwd);
16686
+ } catch {
16687
+ }
16688
+ let lockMtime = "0";
16689
+ for (const lf of MAP_LOCKFILES) {
16690
+ try {
16691
+ lockMtime = String(Math.round(statSync7(join10(cwd, lf)).mtimeMs));
16692
+ break;
16693
+ } catch {
16694
+ }
16695
+ }
16696
+ return `${head}:${lockMtime}`;
16697
+ }
16698
+ function readMapDiskCache(cwd, sig) {
16699
+ try {
16700
+ const path = mapCacheFile(cwd);
16701
+ if (!existsSync7(path)) return null;
16702
+ const raw = JSON.parse(readFileSync9(path, "utf-8"));
16703
+ if (raw.sig !== sig) return null;
16704
+ if (typeof raw.builtAt === "number" && Date.now() - raw.builtAt > MAP_CACHE_TTL_MS) return null;
16705
+ return typeof raw.brief === "string" ? raw.brief : null;
16706
+ } catch {
16707
+ return null;
16708
+ }
16709
+ }
16710
+ function writeMapDiskCache(cwd, sig, brief) {
16711
+ try {
16712
+ mkdirSync7(mapCacheDir(), { recursive: true });
16713
+ writeFileSync7(mapCacheFile(cwd), JSON.stringify({ sig, brief, builtAt: Date.now() }));
16714
+ } catch {
16715
+ }
16716
+ }
16717
+ function composeBrief(cwd, cap) {
16718
+ const files = collectSourceFiles(cwd);
16719
+ if (files.length === 0) return "";
16720
+ const generatedCount = files.filter((f) => f.includes("/generated/")).length;
16721
+ const kernCount = files.filter((f) => f.endsWith(".kern")).length;
16722
+ const groups = /* @__PURE__ */ new Map();
16723
+ for (const f of files) {
16724
+ const g = topLevelGroup(f);
16725
+ const arr = groups.get(g) ?? [];
16726
+ arr.push(f);
16727
+ groups.set(g, arr);
16728
+ }
16729
+ let filesRead = 0;
16730
+ const lines = [];
16731
+ let totalLen = 0;
16732
+ const addLine = (s) => {
16733
+ lines.push(s);
16734
+ totalLen += s.length + 1;
16735
+ };
16736
+ addLine("## CODEBASE BRIEF (where things live \u2014 prefer this over searching)");
16737
+ if (kernCount > 0 && generatedCount > 0) {
16738
+ addLine(`KERN project: ${kernCount} .kern sources compile to generated/ TS mirrors \u2014 EDIT THE .kern, not generated/.`);
16739
+ }
16740
+ const groupNames = Array.from(groups.keys()).sort();
16741
+ const perGroupBudget = Math.min(cap, Math.max(300, Math.floor(cap / Math.max(1, groupNames.length))));
16742
+ for (const g of groupNames) {
16743
+ if (totalLen > cap) break;
16744
+ const groupFiles = (groups.get(g) ?? []).filter((f) => !f.includes("/generated/"));
16745
+ if (groupFiles.length === 0) continue;
16746
+ groupFiles.sort((a, b) => {
16747
+ const ak = a.endsWith(".kern") ? 0 : 1;
16748
+ const bk = b.endsWith(".kern") ? 0 : 1;
16749
+ if (ak !== bk) return ak - bk;
16750
+ return a < b ? -1 : a > b ? 1 : 0;
16751
+ });
16752
+ const groupStart = totalLen;
16753
+ addLine(`
16754
+ ### ${g} (${groupFiles.length} files)`);
16755
+ let shown = 0;
16756
+ for (const f of groupFiles.slice(0, 12)) {
16757
+ if (totalLen > cap) break;
16758
+ if (shown > 0 && totalLen - groupStart > perGroupBudget) break;
16759
+ let syms = [];
16760
+ if (filesRead < MAP_MAX_FILES_READ) {
16761
+ try {
16762
+ const st = statSync7(join10(cwd, f));
16763
+ if (st.size <= MAP_MAX_FILE_BYTES) {
16764
+ syms = extractSymbols(f, readFileSync9(join10(cwd, f), "utf-8"));
16765
+ filesRead++;
16766
+ }
16767
+ } catch {
16768
+ }
16769
+ }
16770
+ addLine(syms.length > 0 ? `- ${f}: ${syms.join(", ")}` : `- ${f}`);
16771
+ shown++;
16772
+ }
16773
+ const extra = groupFiles.length - shown;
16774
+ if (extra > 0) addLine(` (+${extra} more files in ${g})`);
16775
+ }
16776
+ let brief = lines.join("\n");
16777
+ if (brief.length > cap) brief = brief.slice(0, cap) + "\n... (brief truncated)";
16778
+ return brief;
16779
+ }
16780
+ function buildCodebaseMap(cwd, maxChars) {
16781
+ if (maxChars !== void 0) return composeBrief(cwd, Math.max(1, maxChars));
16782
+ const sig = mapCacheSignature(cwd);
16783
+ const cached2 = MAP_MEMO.get(cwd);
16784
+ if (cached2 !== void 0 && cached2.sig === sig) return cached2.brief;
16785
+ const fromDisk = readMapDiskCache(cwd, sig);
16786
+ if (fromDisk !== null) {
16787
+ MAP_MEMO.set(cwd, { sig, brief: fromDisk });
16788
+ return fromDisk;
16789
+ }
16790
+ const brief = composeBrief(cwd, 3500);
16791
+ writeMapDiskCache(cwd, sig, brief);
16792
+ MAP_MEMO.set(cwd, { sig, brief });
16793
+ return brief;
16794
+ }
16795
+ function clearCodebaseMapCache(cwd) {
16796
+ if (cwd) {
16797
+ MAP_MEMO.delete(cwd);
16798
+ try {
16799
+ rmSync4(mapCacheFile(cwd), { force: true });
16800
+ } catch {
16801
+ }
16802
+ } else {
16803
+ MAP_MEMO.clear();
16804
+ try {
16805
+ rmSync4(mapCacheDir(), { recursive: true, force: true });
16806
+ } catch {
16807
+ }
16808
+ }
16809
+ }
16810
+
16554
16811
  // ../core/src/generated/blocks/workspace.ts
16555
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync7, renameSync as renameSync6 } from "fs";
16556
- import { join as join10, resolve as resolve5, basename as basename2 } from "path";
16812
+ import { readFileSync as readFileSync10, writeFileSync as writeFileSync8, renameSync as renameSync6 } from "fs";
16813
+ import { join as join11, resolve as resolve5, basename as basename2 } from "path";
16557
16814
  import { homedir as homedir4 } from "os";
16558
16815
  function getWorkspacesPath() {
16559
16816
  const override = process.env.AGON_HOME?.trim();
16560
- const home = override ? resolve5(override) : join10(homedir4(), ".agon");
16561
- return join10(home, "workspaces.json");
16817
+ const home = override ? resolve5(override) : join11(homedir4(), ".agon");
16818
+ return join11(home, "workspaces.json");
16562
16819
  }
16563
16820
  function loadState() {
16564
16821
  const WORKSPACES_PATH = getWorkspacesPath();
16565
16822
  ensureAgonHome();
16566
16823
  try {
16567
- return JSON.parse(readFileSync9(WORKSPACES_PATH, "utf-8"));
16824
+ return JSON.parse(readFileSync10(WORKSPACES_PATH, "utf-8"));
16568
16825
  } catch (err) {
16569
16826
  if (err.code !== "ENOENT") {
16570
16827
  console.warn(`[agon] workspace state corrupted, resetting to defaults: ${err instanceof Error ? err.message : String(err)}`);
@@ -16575,7 +16832,7 @@ function loadState() {
16575
16832
  function saveState(state) {
16576
16833
  const WORKSPACES_PATH = getWorkspacesPath();
16577
16834
  const tmpPath = WORKSPACES_PATH + ".tmp";
16578
- writeFileSync7(tmpPath, JSON.stringify(state, null, 2) + "\n");
16835
+ writeFileSync8(tmpPath, JSON.stringify(state, null, 2) + "\n");
16579
16836
  renameSync6(tmpPath, WORKSPACES_PATH);
16580
16837
  }
16581
16838
  function addWorkspace(rawPath) {
@@ -16862,17 +17119,17 @@ function resetStepForRetry(plan, stepId) {
16862
17119
  }
16863
17120
 
16864
17121
  // ../core/src/generated/signals/plan-store.ts
16865
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync8, mkdirSync as mkdirSync7, readdirSync as readdirSync7, unlinkSync as unlinkSync3, renameSync as renameSync7 } from "fs";
16866
- import { join as join11, resolve as resolve6 } from "path";
17122
+ import { readFileSync as readFileSync11, writeFileSync as writeFileSync9, mkdirSync as mkdirSync8, readdirSync as readdirSync8, unlinkSync as unlinkSync3, renameSync as renameSync7 } from "fs";
17123
+ import { join as join12, resolve as resolve6 } from "path";
16867
17124
  import { homedir as homedir5 } from "os";
16868
17125
  function getPlansDir() {
16869
17126
  const override = process.env.AGON_HOME?.trim();
16870
- const home = override ? resolve6(override) : join11(homedir5(), ".agon");
16871
- return join11(home, "plans");
17127
+ const home = override ? resolve6(override) : join12(homedir5(), ".agon");
17128
+ return join12(home, "plans");
16872
17129
  }
16873
17130
  function ensurePlansDir() {
16874
17131
  ensureAgonHome();
16875
- mkdirSync7(getPlansDir(), { recursive: true });
17132
+ mkdirSync8(getPlansDir(), { recursive: true });
16876
17133
  }
16877
17134
  function safePlanPath(id) {
16878
17135
  const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, "");
@@ -16887,12 +17144,12 @@ function savePlan(plan) {
16887
17144
  ensurePlansDir();
16888
17145
  const target = safePlanPath(plan.id);
16889
17146
  const tmpPath = target + ".tmp";
16890
- writeFileSync8(tmpPath, JSON.stringify(plan, null, 2) + "\n");
17147
+ writeFileSync9(tmpPath, JSON.stringify(plan, null, 2) + "\n");
16891
17148
  renameSync7(tmpPath, target);
16892
17149
  }
16893
17150
  function loadPlan(id) {
16894
17151
  try {
16895
- return JSON.parse(readFileSync10(safePlanPath(id), "utf-8"));
17152
+ return JSON.parse(readFileSync11(safePlanPath(id), "utf-8"));
16896
17153
  } catch (err) {
16897
17154
  if (err.code !== "ENOENT") {
16898
17155
  console.warn(`[agon] failed to load plan ${id}: ${err instanceof Error ? err.message : String(err)}`);
@@ -16904,8 +17161,8 @@ function listPlans(limit) {
16904
17161
  ensurePlansDir();
16905
17162
  try {
16906
17163
  const plansDir = getPlansDir();
16907
- const files = readdirSync7(plansDir).filter((f) => f.endsWith(".json"));
16908
- return files.map((f) => JSON.parse(readFileSync10(join11(plansDir, f), "utf-8"))).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, limit ?? 20);
17164
+ const files = readdirSync8(plansDir).filter((f) => f.endsWith(".json"));
17165
+ return files.map((f) => JSON.parse(readFileSync11(join12(plansDir, f), "utf-8"))).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, limit ?? 20);
16909
17166
  } catch (err) {
16910
17167
  console.warn(`[agon] failed to list plans: ${err instanceof Error ? err.message : String(err)}`);
16911
17168
  return [];
@@ -16947,6 +17204,389 @@ function wordWrap(text, width) {
16947
17204
  return result;
16948
17205
  }
16949
17206
 
17207
+ // ../core/src/generated/blocks/stack-trace.ts
17208
+ import { existsSync as existsSync9, readFileSync as readFileSync12 } from "fs";
17209
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute2, normalize, resolve as resolve7 } from "path";
17210
+ import { fileURLToPath as fileURLToPath2 } from "url";
17211
+ import { createRequire as createRequire2 } from "module";
17212
+ import { Buffer as Buffer2 } from "buffer";
17213
+ function setBoundedCacheEntry(cache, key, value) {
17214
+ if (!cache || typeof cache.set !== "function") return;
17215
+ const limit = 256;
17216
+ if (cache.has(key)) {
17217
+ cache.delete(key);
17218
+ } else if (cache.size >= limit) {
17219
+ const oldest = cache.keys().next().value;
17220
+ if (oldest !== void 0) cache.delete(oldest);
17221
+ }
17222
+ cache.set(key, value);
17223
+ }
17224
+ function normalizeStackFilePath(rawPath) {
17225
+ let filePath = String(rawPath ?? "");
17226
+ if (!filePath) return "";
17227
+ if (filePath.startsWith("file://")) {
17228
+ try {
17229
+ filePath = fileURLToPath2(filePath);
17230
+ } catch {
17231
+ return normalize(filePath);
17232
+ }
17233
+ }
17234
+ return normalize(filePath);
17235
+ }
17236
+ function readTextFileCached(filePath) {
17237
+ const normalized = normalizeStackFilePath(filePath);
17238
+ if (!normalized) return null;
17239
+ const cache = stackTraceMapperState().sourceTextCache;
17240
+ if (cache.has(normalized)) return cache.get(normalized) ?? null;
17241
+ let content = null;
17242
+ try {
17243
+ if (existsSync9(normalized)) content = readFileSync12(normalized, "utf8");
17244
+ } catch {
17245
+ content = null;
17246
+ }
17247
+ if (content !== null) setBoundedCacheEntry(cache, normalized, content);
17248
+ return content;
17249
+ }
17250
+ function nodeModuleApi() {
17251
+ try {
17252
+ return createRequire2(import.meta.url)("node:module");
17253
+ } catch {
17254
+ return {};
17255
+ }
17256
+ }
17257
+ function sourceMappingUrlFromContent(content) {
17258
+ const text = String(content ?? "");
17259
+ const lineMatches = [...text.matchAll(/\/\/\s*[#@]\s*sourceMappingURL\s*=\s*([^\s]+)/g)];
17260
+ const blockMatches = [...text.matchAll(/\/\*\s*[#@]\s*sourceMappingURL\s*=\s*([\s\S]*?)\s*\*\//g)];
17261
+ const matches = [...lineMatches, ...blockMatches].sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
17262
+ const last = matches[matches.length - 1];
17263
+ return last?.[1]?.trim() || null;
17264
+ }
17265
+ function loadSourceMapForFile(filePath) {
17266
+ const normalized = normalizeStackFilePath(filePath);
17267
+ if (!normalized) return null;
17268
+ const mod = nodeModuleApi();
17269
+ try {
17270
+ if (typeof mod.findSourceMap === "function") {
17271
+ const found = mod.findSourceMap(normalized);
17272
+ if (found) return found;
17273
+ }
17274
+ } catch {
17275
+ }
17276
+ const cache = stackTraceMapperState().sourceMapCache;
17277
+ if (cache.has(normalized)) return cache.get(normalized) ?? null;
17278
+ let loaded = null;
17279
+ try {
17280
+ const content = readTextFileCached(normalized);
17281
+ const mappingUrl = content ? sourceMappingUrlFromContent(content) : null;
17282
+ if (mappingUrl) {
17283
+ let payload = null;
17284
+ if (mappingUrl.startsWith("data:")) {
17285
+ const base643 = mappingUrl.match(/^data:application\/json(?:;charset=[^;,]+)?;base64,(.+)$/i)?.[1];
17286
+ if (base643) payload = JSON.parse(Buffer2.from(base643, "base64").toString("utf8"));
17287
+ } else {
17288
+ const mapPath = resolve7(dirname5(normalized), decodeURIComponent(mappingUrl));
17289
+ if (existsSync9(mapPath)) payload = JSON.parse(readFileSync12(mapPath, "utf8"));
17290
+ }
17291
+ if (payload && typeof mod.SourceMap === "function") {
17292
+ loaded = new mod.SourceMap(payload);
17293
+ }
17294
+ }
17295
+ } catch {
17296
+ loaded = null;
17297
+ }
17298
+ setBoundedCacheEntry(cache, normalized, loaded);
17299
+ return loaded;
17300
+ }
17301
+ function sourceContentForOrigin(sourceMap, originFileName) {
17302
+ const payload = sourceMap?.payload;
17303
+ const sources = Array.isArray(payload?.sources) ? payload.sources : [];
17304
+ const contents = Array.isArray(payload?.sourcesContent) ? payload.sourcesContent : [];
17305
+ let index = sources.indexOf(originFileName);
17306
+ if (index < 0) {
17307
+ const normalizedOrigin = String(originFileName ?? "").replace(/\\/g, "/");
17308
+ index = sources.findIndex((source) => String(source ?? "").replace(/\\/g, "/") === normalizedOrigin);
17309
+ }
17310
+ if (index < 0) return null;
17311
+ const content = contents[index];
17312
+ return typeof content === "string" ? content : null;
17313
+ }
17314
+ function resolveSourceMapSourcePath(mapFilePath, sourceMap, originFileName) {
17315
+ let sourceRef = String(originFileName ?? "");
17316
+ if (!sourceRef) return "";
17317
+ if (sourceRef.startsWith("file://")) {
17318
+ try {
17319
+ return normalize(fileURLToPath2(sourceRef));
17320
+ } catch {
17321
+ return sourceRef;
17322
+ }
17323
+ }
17324
+ if (isAbsolute2(sourceRef)) return normalize(sourceRef);
17325
+ const sourceRoot = String(sourceMap?.payload?.sourceRoot ?? "");
17326
+ if (sourceRoot.startsWith("file://")) {
17327
+ try {
17328
+ return normalize(resolve7(fileURLToPath2(sourceRoot), sourceRef));
17329
+ } catch {
17330
+ return normalize(sourceRef);
17331
+ }
17332
+ }
17333
+ return normalize(resolve7(dirname5(normalizeStackFilePath(mapFilePath)), sourceRoot, sourceRef));
17334
+ }
17335
+ function sourceMapOriginForLocation(sourceMap, lineNumber, columnNumber) {
17336
+ if (!sourceMap) return null;
17337
+ if (typeof sourceMap.findOrigin === "function") {
17338
+ try {
17339
+ const origin = sourceMap.findOrigin(lineNumber, columnNumber);
17340
+ if (origin?.fileName && Number.isFinite(Number(origin.lineNumber))) {
17341
+ return {
17342
+ fileName: String(origin.fileName),
17343
+ lineNumber: Math.max(1, Math.floor(Number(origin.lineNumber) || 1))
17344
+ };
17345
+ }
17346
+ } catch {
17347
+ }
17348
+ }
17349
+ if (typeof sourceMap.findEntry === "function") {
17350
+ try {
17351
+ const entry = sourceMap.findEntry(Math.max(0, lineNumber - 1), Math.max(0, columnNumber - 1));
17352
+ const fileName = entry?.originalSource ?? entry?.sourceURL ?? entry?.fileName;
17353
+ const rawLine = entry?.originalLine ?? entry?.line ?? entry?.lineNumber;
17354
+ if (fileName && Number.isFinite(Number(rawLine))) {
17355
+ return {
17356
+ fileName: String(fileName),
17357
+ lineNumber: Math.max(1, Math.floor(Number(rawLine)) + 1)
17358
+ };
17359
+ }
17360
+ } catch {
17361
+ }
17362
+ }
17363
+ return null;
17364
+ }
17365
+ function generatedSourceTextForLocation(filePath, lineNumber, columnNumber) {
17366
+ const normalized = normalizeStackFilePath(filePath);
17367
+ if (!normalized) return null;
17368
+ const safeLine = Math.max(1, Math.floor(Number(lineNumber) || 1));
17369
+ const rawColumn = Number(columnNumber);
17370
+ const safeColumn = Number.isFinite(rawColumn) ? Math.max(0, Math.floor(rawColumn)) : 1;
17371
+ const sourceMap = loadSourceMapForFile(normalized);
17372
+ if (sourceMap) {
17373
+ try {
17374
+ const origin = sourceMapOriginForLocation(sourceMap, safeLine, safeColumn);
17375
+ if (origin) {
17376
+ const originPath = resolveSourceMapSourcePath(normalized, sourceMap, origin.fileName);
17377
+ const content = readTextFileCached(originPath) ?? sourceContentForOrigin(sourceMap, origin.fileName);
17378
+ if (content) {
17379
+ return {
17380
+ content,
17381
+ filePath: originPath,
17382
+ lineNumber: origin.lineNumber,
17383
+ generatedFile: normalized,
17384
+ generatedLine: safeLine
17385
+ };
17386
+ }
17387
+ }
17388
+ } catch {
17389
+ }
17390
+ }
17391
+ const directContent = readTextFileCached(normalized);
17392
+ if (!directContent) return null;
17393
+ return {
17394
+ content: directContent,
17395
+ filePath: normalized,
17396
+ lineNumber: safeLine,
17397
+ generatedFile: normalized,
17398
+ generatedLine: safeLine
17399
+ };
17400
+ }
17401
+ function findNearestKernTrace(content, lineNumber) {
17402
+ const lines = String(content ?? "").split(/\r?\n/);
17403
+ const start = Math.max(0, Math.min(lines.length - 1, Math.floor(Number(lineNumber) || 1) - 1));
17404
+ for (let index = start; index >= 0; index -= 1) {
17405
+ const match = lines[index].match(/^\s*\/\/ @kern-source: (.+):(\d+)\s*$/);
17406
+ if (!match) continue;
17407
+ return { sourceName: match[1], line: Math.max(1, Math.floor(Number(match[2]) || 1)) };
17408
+ }
17409
+ return null;
17410
+ }
17411
+ function generatedHeaderSource(content) {
17412
+ const match = String(content ?? "").match(/^\/\/\s*@generated\s+by\s+kern\b[\s\S]*?\bSource:\s*(.+?)\s*$/m);
17413
+ return match?.[1]?.trim() || null;
17414
+ }
17415
+ function packageRootForGeneratedPath(generatedFile) {
17416
+ const normalized = normalizeStackFilePath(generatedFile);
17417
+ const slashPath = normalized.replace(/\\/g, "/");
17418
+ const srcMarker = "/src/generated/";
17419
+ const srcIndex = slashPath.indexOf(srcMarker);
17420
+ if (srcIndex >= 0) return normalized.slice(0, srcIndex);
17421
+ const generatedMarker = "/generated/";
17422
+ const generatedIndex = slashPath.indexOf(generatedMarker);
17423
+ if (generatedIndex >= 0) return normalized.slice(0, generatedIndex);
17424
+ return null;
17425
+ }
17426
+ function resolveKernSourceFile(generatedFile, content, sourceName) {
17427
+ const header = generatedHeaderSource(content);
17428
+ const candidates = [];
17429
+ const root = packageRootForGeneratedPath(generatedFile);
17430
+ if (header) {
17431
+ if (isAbsolute2(header)) candidates.push(normalize(header));
17432
+ if (root) candidates.push(normalize(resolve7(root, header)));
17433
+ candidates.push(normalize(resolve7(dirname5(normalizeStackFilePath(generatedFile)), header)));
17434
+ try {
17435
+ candidates.push(normalize(resolve7(process.cwd(), header)));
17436
+ } catch {
17437
+ }
17438
+ }
17439
+ if (root) {
17440
+ candidates.push(normalize(resolve7(root, "src", "kern", `${sourceName}.kern`)));
17441
+ candidates.push(normalize(resolve7(root, "kern", `${sourceName}.kern`)));
17442
+ }
17443
+ const sourceBase = `${sourceName}.kern`;
17444
+ const matchingHeader = candidates.find((candidate) => basename3(candidate) === sourceBase);
17445
+ const matchingHeaderExists = matchingHeader ? (() => {
17446
+ try {
17447
+ return existsSync9(matchingHeader);
17448
+ } catch {
17449
+ return false;
17450
+ }
17451
+ })() : false;
17452
+ const existing = candidates.find((candidate) => {
17453
+ try {
17454
+ return existsSync9(candidate);
17455
+ } catch {
17456
+ return false;
17457
+ }
17458
+ });
17459
+ return (matchingHeaderExists ? matchingHeader : null) ?? matchingHeader ?? existing ?? candidates[0] ?? sourceBase;
17460
+ }
17461
+ function resolveKernSourceLocation(filePath, lineNumber, columnNumber) {
17462
+ const normalized = normalizeStackFilePath(filePath);
17463
+ const cache = stackTraceMapperState().locationCache;
17464
+ const cacheKey = `${normalized || String(filePath ?? "")}:${Number(lineNumber) || 0}:${Number(columnNumber) || 0}`;
17465
+ if (cache.has(cacheKey)) return cache.get(cacheKey) ?? null;
17466
+ const source = generatedSourceTextForLocation(filePath, lineNumber, columnNumber);
17467
+ if (!source?.content) {
17468
+ setBoundedCacheEntry(cache, cacheKey, null);
17469
+ return null;
17470
+ }
17471
+ const trace = findNearestKernTrace(source.content, source.lineNumber);
17472
+ if (!trace) {
17473
+ setBoundedCacheEntry(cache, cacheKey, null);
17474
+ return null;
17475
+ }
17476
+ const kernFile = resolveKernSourceFile(source.filePath, source.content, trace.sourceName);
17477
+ const result = {
17478
+ file: kernFile,
17479
+ line: trace.line,
17480
+ sourceName: trace.sourceName,
17481
+ generatedFile: source.filePath,
17482
+ generatedLine: source.lineNumber
17483
+ };
17484
+ setBoundedCacheEntry(cache, cacheKey, result);
17485
+ return result;
17486
+ }
17487
+ function stackLineLocation(line) {
17488
+ const match = String(line ?? "").match(/((?:file:\/\/\/[A-Za-z]:[\\/].+?|[A-Za-z]:[\\/].+?|file:\/\/\/.+?|\/.+?|\\\\.+?)\.(?:mjs|cjs|js|jsx|ts|tsx|mts|cts|vue|py|json)):(\d+):(\d+)(\)?)(\s*)$/);
17489
+ if (!match || match.index == null) return null;
17490
+ const locationText = `${match[1]}:${match[2]}:${match[3]}`;
17491
+ return {
17492
+ rawFile: match[1],
17493
+ rawLine: match[2],
17494
+ rawColumn: match[3],
17495
+ start: match.index,
17496
+ end: match.index + locationText.length
17497
+ };
17498
+ }
17499
+ function mapKernStackTrace(stack) {
17500
+ const text = String(stack ?? "");
17501
+ if (!text) return text;
17502
+ return text.split("\n").map((line) => {
17503
+ if (line.includes("[kern: ")) return line;
17504
+ const frame = stackLineLocation(line);
17505
+ if (!frame) return line;
17506
+ const loc = resolveKernSourceLocation(frame.rawFile, Number(frame.rawLine), Number(frame.rawColumn));
17507
+ if (!loc) return line;
17508
+ return `${line.slice(0, frame.end)} [kern: ${loc.file}:${loc.line}]${line.slice(frame.end)}`;
17509
+ }).join("\n");
17510
+ }
17511
+ function formatDefaultStackTrace(error48, frames) {
17512
+ const name = error48?.name ? String(error48.name) : "Error";
17513
+ const message = error48?.message ? `${name}: ${String(error48.message)}` : name;
17514
+ const lines = [message];
17515
+ for (const frame of frames ?? []) {
17516
+ lines.push(` at ${String(frame)}`);
17517
+ }
17518
+ return lines.join("\n");
17519
+ }
17520
+ function stackTraceMapperDisabled() {
17521
+ return !!process.env.AGON_NO_STACK_TRACE_MAPPER;
17522
+ }
17523
+ function stackTraceMapperState() {
17524
+ const holder = stackTraceMapperState;
17525
+ if (!holder.state) {
17526
+ holder.state = {
17527
+ installed: false,
17528
+ previous: null,
17529
+ wrapper: null,
17530
+ sourceTextCache: /* @__PURE__ */ new Map(),
17531
+ sourceMapCache: /* @__PURE__ */ new Map(),
17532
+ locationCache: /* @__PURE__ */ new Map()
17533
+ };
17534
+ }
17535
+ return holder.state;
17536
+ }
17537
+ function installKernStackTraceMapper() {
17538
+ if (stackTraceMapperDisabled()) return;
17539
+ const state = stackTraceMapperState();
17540
+ if (state.installed && Error.prepareStackTrace === state.wrapper) return;
17541
+ if (state.installed) {
17542
+ state.installed = false;
17543
+ state.previous = null;
17544
+ state.wrapper = null;
17545
+ }
17546
+ const mod = nodeModuleApi();
17547
+ try {
17548
+ if (typeof mod.setSourceMapsSupport === "function") {
17549
+ mod.setSourceMapsSupport(true, { nodeModules: false, generatedCode: true });
17550
+ }
17551
+ } catch {
17552
+ }
17553
+ const previous = Error.prepareStackTrace;
17554
+ if (state.wrapper && previous === state.wrapper) {
17555
+ state.installed = true;
17556
+ return;
17557
+ }
17558
+ const wrapper = (error48, frames) => {
17559
+ if (typeof previous === "function") {
17560
+ const rendered = previous(error48, frames);
17561
+ return typeof rendered === "string" ? mapKernStackTrace(rendered) : rendered;
17562
+ }
17563
+ return mapKernStackTrace(formatDefaultStackTrace(error48, frames));
17564
+ };
17565
+ try {
17566
+ Error.prepareStackTrace = wrapper;
17567
+ } catch {
17568
+ return;
17569
+ }
17570
+ state.previous = previous;
17571
+ state.wrapper = wrapper;
17572
+ state.installed = true;
17573
+ }
17574
+ function uninstallKernStackTraceMapper() {
17575
+ const state = stackTraceMapperState();
17576
+ if (state.installed && Error.prepareStackTrace === state.wrapper) {
17577
+ try {
17578
+ Error.prepareStackTrace = state.previous;
17579
+ } catch {
17580
+ }
17581
+ }
17582
+ state.installed = false;
17583
+ state.previous = null;
17584
+ state.wrapper = null;
17585
+ state.sourceTextCache?.clear?.();
17586
+ state.sourceMapCache?.clear?.();
17587
+ state.locationCache?.clear?.();
17588
+ }
17589
+
16950
17590
  // ../core/src/generated/signals/output-manager.ts
16951
17591
  function formatSpinnerFrame(frames, index, text) {
16952
17592
  return ` \x1B[38;5;214m${frames[index % frames.length]}\x1B[0m \x1B[2m${text}\x1B[0m`;
@@ -17114,15 +17754,15 @@ async function discoverEngines(registry2, adapter) {
17114
17754
  }
17115
17755
 
17116
17756
  // ../core/src/generated/blocks/patch-apply.ts
17117
- import { readFileSync as readFileSync11, writeFileSync as writeFileSync9, mkdirSync as mkdirSync8, renameSync as renameSync8 } from "fs";
17118
- import { join as join13 } from "path";
17757
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, renameSync as renameSync8 } from "fs";
17758
+ import { join as join14 } from "path";
17119
17759
  import { execSync } from "child_process";
17120
17760
 
17121
17761
  // ../core/src/generated/utils/paths.ts
17122
- import { join as join12, resolve as resolve7 } from "path";
17762
+ import { join as join13, resolve as resolve8 } from "path";
17123
17763
  import { homedir as homedir6 } from "os";
17124
17764
  function runtimeAgonPath(...parts) {
17125
- return join12(resolve7(process.env.AGON_HOME?.trim() || join12(homedir6(), ".agon")), ...parts);
17765
+ return join13(resolve8(process.env.AGON_HOME?.trim() || join13(homedir6(), ".agon")), ...parts);
17126
17766
  }
17127
17767
  function getCacheDir() {
17128
17768
  return runtimeAgonPath("cache");
@@ -17215,12 +17855,12 @@ function invertPatch(content) {
17215
17855
  // ../core/src/generated/blocks/patch-apply.ts
17216
17856
  function readPatchFromManifest(manifestPath) {
17217
17857
  try {
17218
- const raw = readFileSync11(manifestPath, "utf-8");
17858
+ const raw = readFileSync13(manifestPath, "utf-8");
17219
17859
  const manifest = JSON.parse(raw);
17220
17860
  if (!manifest.winner) return null;
17221
17861
  const patchPath = manifest.patches[manifest.winner];
17222
17862
  if (!patchPath) return null;
17223
- const content = normalizePatchContent(readFileSync11(patchPath, "utf-8"));
17863
+ const content = normalizePatchContent(readFileSync13(patchPath, "utf-8"));
17224
17864
  const lineCount = content.split("\n").filter(
17225
17865
  (l) => l.startsWith("+") && !l.startsWith("+++") || l.startsWith("-") && !l.startsWith("---")
17226
17866
  ).length;
@@ -17232,7 +17872,7 @@ function readPatchFromManifest(manifestPath) {
17232
17872
  }
17233
17873
  function readPatchFromPath(patchPath) {
17234
17874
  try {
17235
- const content = normalizePatchContent(readFileSync11(patchPath, "utf-8"));
17875
+ const content = normalizePatchContent(readFileSync13(patchPath, "utf-8"));
17236
17876
  if (!content.trim()) return null;
17237
17877
  const lineCount = content.split("\n").filter(
17238
17878
  (l) => l.startsWith("+") && !l.startsWith("+++") || l.startsWith("-") && !l.startsWith("---")
@@ -17292,7 +17932,7 @@ function preflightApply(cwd, patchPath, manifestPath) {
17292
17932
  }
17293
17933
  function applyPatchWithUndo(cwd, patchContent) {
17294
17934
  const undoDir = getUndoDir();
17295
- mkdirSync8(undoDir, { recursive: true });
17935
+ mkdirSync9(undoDir, { recursive: true });
17296
17936
  const inverse = invertPatch(patchContent);
17297
17937
  const token = `undo-${Date.now()}`;
17298
17938
  try {
@@ -17301,18 +17941,18 @@ function applyPatchWithUndo(cwd, patchContent) {
17301
17941
  const msg = err instanceof Error ? err.stderr || err.message : String(err);
17302
17942
  return { ok: false, error: msg };
17303
17943
  }
17304
- const inversePath = join13(undoDir, `${token}.patch`);
17305
- const tmpPath = join13(undoDir, `${token}.patch.tmp`);
17306
- writeFileSync9(tmpPath, inverse);
17944
+ const inversePath = join14(undoDir, `${token}.patch`);
17945
+ const tmpPath = join14(undoDir, `${token}.patch.tmp`);
17946
+ writeFileSync10(tmpPath, inverse);
17307
17947
  renameSync8(tmpPath, inversePath);
17308
17948
  return { ok: true, undoToken: token };
17309
17949
  }
17310
17950
  function undoPatch(cwd, undoToken) {
17311
17951
  const undoDir = getUndoDir();
17312
- const inversePath = join13(undoDir, `${undoToken}.patch`);
17952
+ const inversePath = join14(undoDir, `${undoToken}.patch`);
17313
17953
  let inverse;
17314
17954
  try {
17315
- inverse = readFileSync11(inversePath, "utf-8");
17955
+ inverse = readFileSync13(inversePath, "utf-8");
17316
17956
  } catch {
17317
17957
  return { ok: false, error: `Undo token not found: ${undoToken}` };
17318
17958
  }
@@ -17326,28 +17966,28 @@ function undoPatch(cwd, undoToken) {
17326
17966
  }
17327
17967
 
17328
17968
  // ../core/src/generated/blocks/file-history.ts
17329
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, existsSync as existsSync8, readdirSync as readdirSync8, unlinkSync as unlinkSync4 } from "fs";
17330
- import { join as join14, dirname as dirname5, resolve as resolve8 } from "path";
17969
+ import { readFileSync as readFileSync14, writeFileSync as writeFileSync11, mkdirSync as mkdirSync10, existsSync as existsSync10, readdirSync as readdirSync9, unlinkSync as unlinkSync4 } from "fs";
17970
+ import { join as join15, dirname as dirname6, resolve as resolve9 } from "path";
17331
17971
  import { randomUUID as randomUUID2 } from "crypto";
17332
17972
  import { homedir as homedir7 } from "os";
17333
17973
  function snapshotsDir() {
17334
17974
  const override = process.env.AGON_HOME?.trim();
17335
- const home = override ? resolve8(override) : join14(homedir7(), ".agon");
17336
- return join14(home, "snapshots");
17975
+ const home = override ? resolve9(override) : join15(homedir7(), ".agon");
17976
+ return join15(home, "snapshots");
17337
17977
  }
17338
17978
  var MAX_SNAPSHOTS = 50;
17339
17979
  function ensureSnapshotsDir() {
17340
17980
  ensureAgonHome();
17341
- mkdirSync9(snapshotsDir(), { recursive: true });
17981
+ mkdirSync10(snapshotsDir(), { recursive: true });
17342
17982
  }
17343
17983
  function takeSnapshot(label, cwd, filePaths) {
17344
17984
  ensureSnapshotsDir();
17345
17985
  const files = [];
17346
17986
  for (const fp of filePaths) {
17347
- const fullPath = resolve8(cwd, fp);
17348
- if (existsSync8(fullPath)) {
17987
+ const fullPath = resolve9(cwd, fp);
17988
+ if (existsSync10(fullPath)) {
17349
17989
  try {
17350
- const content = readFileSync12(fullPath, "utf-8");
17990
+ const content = readFileSync14(fullPath, "utf-8");
17351
17991
  files.push({ path: fp, content, timestamp: Date.now(), existed: true });
17352
17992
  } catch (err) {
17353
17993
  console.warn(`[agon] snapshot: could not read ${fp}: ${err instanceof Error ? err.message : String(err)}`);
@@ -17363,36 +18003,36 @@ function takeSnapshot(label, cwd, filePaths) {
17363
18003
  files,
17364
18004
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
17365
18005
  };
17366
- const entryPath = join14(snapshotsDir(), `${entry.id}.json`);
17367
- writeFileSync10(entryPath, JSON.stringify(entry, null, 2) + "\n");
18006
+ const entryPath = join15(snapshotsDir(), `${entry.id}.json`);
18007
+ writeFileSync11(entryPath, JSON.stringify(entry, null, 2) + "\n");
17368
18008
  pruneSnapshots();
17369
18009
  return entry;
17370
18010
  }
17371
18011
  function revertSnapshot(id) {
17372
18012
  ensureSnapshotsDir();
17373
- const entryPath = join14(snapshotsDir(), `${id}.json`);
17374
- if (!existsSync8(entryPath)) {
18013
+ const entryPath = join15(snapshotsDir(), `${id}.json`);
18014
+ if (!existsSync10(entryPath)) {
17375
18015
  return { ok: false, error: `Snapshot ${id} not found`, filesReverted: 0 };
17376
18016
  }
17377
18017
  let entry;
17378
18018
  try {
17379
- entry = JSON.parse(readFileSync12(entryPath, "utf-8"));
18019
+ entry = JSON.parse(readFileSync14(entryPath, "utf-8"));
17380
18020
  } catch (err) {
17381
18021
  return { ok: false, error: `Corrupt snapshot: ${err instanceof Error ? err.message : String(err)}`, filesReverted: 0 };
17382
18022
  }
17383
18023
  let reverted = 0;
17384
18024
  for (const snap of entry.files) {
17385
- const fullPath = resolve8(entry.cwd, snap.path);
18025
+ const fullPath = resolve9(entry.cwd, snap.path);
17386
18026
  try {
17387
18027
  const existedBefore = typeof snap.existed === "boolean" ? snap.existed : snap.content !== "";
17388
18028
  if (!existedBefore) {
17389
- if (existsSync8(fullPath)) {
18029
+ if (existsSync10(fullPath)) {
17390
18030
  unlinkSync4(fullPath);
17391
18031
  reverted++;
17392
18032
  }
17393
18033
  } else {
17394
- mkdirSync9(dirname5(fullPath), { recursive: true });
17395
- writeFileSync10(fullPath, snap.content);
18034
+ mkdirSync10(dirname6(fullPath), { recursive: true });
18035
+ writeFileSync11(fullPath, snap.content);
17396
18036
  reverted++;
17397
18037
  }
17398
18038
  } catch (err) {
@@ -17409,10 +18049,10 @@ function revertSnapshot(id) {
17409
18049
  function listSnapshots() {
17410
18050
  ensureSnapshotsDir();
17411
18051
  try {
17412
- const files = readdirSync8(snapshotsDir()).filter((f) => f.endsWith(".json"));
18052
+ const files = readdirSync9(snapshotsDir()).filter((f) => f.endsWith(".json"));
17413
18053
  const entries = files.map((f) => {
17414
18054
  try {
17415
- return JSON.parse(readFileSync12(join14(snapshotsDir(), f), "utf-8"));
18055
+ return JSON.parse(readFileSync14(join15(snapshotsDir(), f), "utf-8"));
17416
18056
  } catch {
17417
18057
  return null;
17418
18058
  }
@@ -17429,11 +18069,11 @@ function listSnapshots() {
17429
18069
  }
17430
18070
  function pruneSnapshots() {
17431
18071
  try {
17432
- const files = readdirSync8(snapshotsDir()).filter((f) => f.endsWith(".json"));
18072
+ const files = readdirSync9(snapshotsDir()).filter((f) => f.endsWith(".json"));
17433
18073
  if (files.length > MAX_SNAPSHOTS) {
17434
18074
  const byAge = files.map((f) => {
17435
18075
  try {
17436
- const entry = JSON.parse(readFileSync12(join14(snapshotsDir(), f), "utf-8"));
18076
+ const entry = JSON.parse(readFileSync14(join15(snapshotsDir(), f), "utf-8"));
17437
18077
  return { file: f, ts: Date.parse(entry.createdAt ?? "") || 0 };
17438
18078
  } catch {
17439
18079
  return { file: f, ts: 0 };
@@ -17442,7 +18082,7 @@ function pruneSnapshots() {
17442
18082
  const toDelete = byAge.slice(0, files.length - MAX_SNAPSHOTS);
17443
18083
  for (const item of toDelete) {
17444
18084
  try {
17445
- unlinkSync4(join14(snapshotsDir(), item.file));
18085
+ unlinkSync4(join15(snapshotsDir(), item.file));
17446
18086
  } catch {
17447
18087
  }
17448
18088
  }
@@ -17533,38 +18173,38 @@ function copyToClipboard(text) {
17533
18173
  }
17534
18174
 
17535
18175
  // ../core/src/generated/signals/paste-store.ts
17536
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync11, mkdirSync as mkdirSync10, existsSync as existsSync9, readdirSync as readdirSync9, unlinkSync as unlinkSync5, statSync as statSync8 } from "fs";
17537
- import { join as join15, resolve as resolve9 } from "path";
17538
- import { createHash as createHash2 } from "crypto";
18176
+ import { readFileSync as readFileSync15, writeFileSync as writeFileSync12, mkdirSync as mkdirSync11, existsSync as existsSync11, readdirSync as readdirSync10, unlinkSync as unlinkSync5, statSync as statSync9 } from "fs";
18177
+ import { join as join16, resolve as resolve10 } from "path";
18178
+ import { createHash as createHash3 } from "crypto";
17539
18179
  import { homedir as homedir8 } from "os";
17540
18180
  function getPasteStoreDir() {
17541
18181
  const override = process.env.AGON_HOME?.trim();
17542
- const home = override ? resolve9(override) : join15(homedir8(), ".agon");
17543
- return join15(home, "paste-cache");
18182
+ const home = override ? resolve10(override) : join16(homedir8(), ".agon");
18183
+ return join16(home, "paste-cache");
17544
18184
  }
17545
18185
  var PASTE_MAX_AGE = 7 * 24 * 60 * 60 * 1e3;
17546
18186
  function ensurePasteDir() {
17547
18187
  ensureAgonHome();
17548
- mkdirSync10(getPasteStoreDir(), { recursive: true });
18188
+ mkdirSync11(getPasteStoreDir(), { recursive: true });
17549
18189
  }
17550
18190
  var PasteStore = class {
17551
18191
  store(text) {
17552
18192
  ensurePasteDir();
17553
- const hash2 = createHash2("sha256").update(text).digest("hex");
17554
- const filePath = join15(getPasteStoreDir(), `${hash2}.txt`);
17555
- if (!existsSync9(filePath)) {
17556
- writeFileSync11(filePath, text);
18193
+ const hash2 = createHash3("sha256").update(text).digest("hex");
18194
+ const filePath = join16(getPasteStoreDir(), `${hash2}.txt`);
18195
+ if (!existsSync11(filePath)) {
18196
+ writeFileSync12(filePath, text);
17557
18197
  }
17558
18198
  const lines = text.split("\n");
17559
18199
  const preview = text.slice(0, 200).replace(/\n/g, " ").trim();
17560
18200
  return { hash: hash2, preview, lineCount: lines.length };
17561
18201
  }
17562
18202
  retrieve(hash2) {
17563
- const filePath = join15(getPasteStoreDir(), `${hash2}.txt`);
17564
- if (!existsSync9(filePath)) {
18203
+ const filePath = join16(getPasteStoreDir(), `${hash2}.txt`);
18204
+ if (!existsSync11(filePath)) {
17565
18205
  return null;
17566
18206
  }
17567
- return readFileSync13(filePath, "utf-8");
18207
+ return readFileSync15(filePath, "utf-8");
17568
18208
  }
17569
18209
  cleanup(maxAge) {
17570
18210
  const age = maxAge ?? PASTE_MAX_AGE;
@@ -17573,11 +18213,11 @@ var PasteStore = class {
17573
18213
  ensurePasteDir();
17574
18214
  try {
17575
18215
  const pasteStoreDir = getPasteStoreDir();
17576
- const files = readdirSync9(pasteStoreDir).filter((f) => f.endsWith(".txt"));
18216
+ const files = readdirSync10(pasteStoreDir).filter((f) => f.endsWith(".txt"));
17577
18217
  for (const f of files) {
17578
- const fp = join15(pasteStoreDir, f);
18218
+ const fp = join16(pasteStoreDir, f);
17579
18219
  try {
17580
- const stat = statSync8(fp);
18220
+ const stat = statSync9(fp);
17581
18221
  if (now - stat.mtimeMs > age) {
17582
18222
  unlinkSync5(fp);
17583
18223
  deleted++;
@@ -17597,27 +18237,27 @@ var PasteStore = class {
17597
18237
  var pasteStore = new PasteStore();
17598
18238
 
17599
18239
  // ../core/src/generated/signals/session-store.ts
17600
- import { writeFileSync as writeFileSync12, readFileSync as readFileSync14, existsSync as existsSync10, mkdirSync as mkdirSync11, unlinkSync as unlinkSync6, readdirSync as readdirSync10, rmdirSync, renameSync as renameSync9 } from "fs";
17601
- import { join as join16 } from "path";
17602
- import { createHash as createHash3 } from "crypto";
18240
+ import { writeFileSync as writeFileSync13, readFileSync as readFileSync16, existsSync as existsSync12, mkdirSync as mkdirSync12, unlinkSync as unlinkSync6, readdirSync as readdirSync11, rmdirSync, renameSync as renameSync9 } from "fs";
18241
+ import { join as join17 } from "path";
18242
+ import { createHash as createHash4 } from "crypto";
17603
18243
  var SESSION_SCHEMA_VERSION = 2;
17604
18244
  var SESSION_MAX_MESSAGES = 80;
17605
18245
  var SESSION_TTL_MS = 36e5;
17606
18246
  function sessionStorePath(engineId) {
17607
- const cwdHash = createHash3("md5").update(process.cwd()).digest("hex").slice(0, 8);
18247
+ const cwdHash = createHash4("md5").update(process.cwd()).digest("hex").slice(0, 8);
17608
18248
  return runtimeAgonPath("sessions", `${engineId}-${cwdHash}.json`);
17609
18249
  }
17610
18250
  function sessionCacheDir(engineId) {
17611
- const cwdHash = createHash3("md5").update(process.cwd()).digest("hex").slice(0, 8);
18251
+ const cwdHash = createHash4("md5").update(process.cwd()).digest("hex").slice(0, 8);
17612
18252
  return runtimeAgonPath("sessions", `${engineId}-${cwdHash}-cache`);
17613
18253
  }
17614
18254
  function saveToolResultToDisk(engineId, toolCallId, toolName, content) {
17615
18255
  try {
17616
18256
  const cacheDir = sessionCacheDir(engineId);
17617
- mkdirSync11(cacheDir, { recursive: true });
17618
- const filePath = join16(cacheDir, `${toolCallId}.txt`);
18257
+ mkdirSync12(cacheDir, { recursive: true });
18258
+ const filePath = join17(cacheDir, `${toolCallId}.txt`);
17619
18259
  const tmpFilePath = filePath + ".tmp";
17620
- writeFileSync12(tmpFilePath, content, "utf-8");
18260
+ writeFileSync13(tmpFilePath, content, "utf-8");
17621
18261
  renameSync9(tmpFilePath, filePath);
17622
18262
  return {
17623
18263
  toolCallId,
@@ -17634,11 +18274,11 @@ function saveToolResultToDisk(engineId, toolCallId, toolName, content) {
17634
18274
  function loadToolResultFromDisk(engineId, toolCallId) {
17635
18275
  try {
17636
18276
  const cacheDir = sessionCacheDir(engineId);
17637
- const filePath = join16(cacheDir, `${toolCallId}.txt`);
17638
- if (!existsSync10(filePath)) {
18277
+ const filePath = join17(cacheDir, `${toolCallId}.txt`);
18278
+ if (!existsSync12(filePath)) {
17639
18279
  return null;
17640
18280
  }
17641
- return readFileSync14(filePath, "utf-8");
18281
+ return readFileSync16(filePath, "utf-8");
17642
18282
  } catch (e) {
17643
18283
  return null;
17644
18284
  }
@@ -17646,13 +18286,13 @@ function loadToolResultFromDisk(engineId, toolCallId) {
17646
18286
  function pruneToolCache(engineId, keepIds) {
17647
18287
  try {
17648
18288
  const cacheDir = sessionCacheDir(engineId);
17649
- if (!existsSync10(cacheDir)) return;
17650
- const files = readdirSync10(cacheDir);
18289
+ if (!existsSync12(cacheDir)) return;
18290
+ const files = readdirSync11(cacheDir);
17651
18291
  for (const f of files) {
17652
18292
  const id = f.replace(/\.txt$/, "");
17653
18293
  if (!keepIds.has(id)) {
17654
18294
  try {
17655
- unlinkSync6(join16(cacheDir, f));
18295
+ unlinkSync6(join17(cacheDir, f));
17656
18296
  } catch {
17657
18297
  }
17658
18298
  }
@@ -17662,21 +18302,21 @@ function pruneToolCache(engineId, keepIds) {
17662
18302
  }
17663
18303
  function saveSessionState(engineId, state) {
17664
18304
  const dir = runtimeAgonPath("sessions");
17665
- mkdirSync11(dir, { recursive: true });
18305
+ mkdirSync12(dir, { recursive: true });
17666
18306
  const path = sessionStorePath(engineId);
17667
18307
  const trimmed = state.messageHistory.slice(-SESSION_MAX_MESSAGES);
17668
18308
  const data = { schemaVersion: SESSION_SCHEMA_VERSION, messageHistory: trimmed, compactionSummary: state.compactionSummary ?? null, toolCacheManifest: state.toolCacheManifest ?? [], confidence: state.confidence, savedAt: Date.now() };
17669
18309
  const tmpPath = path + ".tmp";
17670
- writeFileSync12(tmpPath, JSON.stringify(data), "utf-8");
18310
+ writeFileSync13(tmpPath, JSON.stringify(data), "utf-8");
17671
18311
  renameSync9(tmpPath, path);
17672
18312
  }
17673
18313
  function loadSessionState(engineId) {
17674
18314
  const path = sessionStorePath(engineId);
17675
- if (!existsSync10(path)) {
18315
+ if (!existsSync12(path)) {
17676
18316
  return null;
17677
18317
  }
17678
18318
  try {
17679
- const raw = readFileSync14(path, "utf-8");
18319
+ const raw = readFileSync16(path, "utf-8");
17680
18320
  const data = JSON.parse(raw);
17681
18321
  if (data.savedAt && Date.now() - data.savedAt > SESSION_TTL_MS) {
17682
18322
  return null;
@@ -17695,16 +18335,16 @@ function loadSessionState(engineId) {
17695
18335
  function clearSessionState(engineId) {
17696
18336
  const path = sessionStorePath(engineId);
17697
18337
  try {
17698
- if (existsSync10(path)) unlinkSync6(path);
18338
+ if (existsSync12(path)) unlinkSync6(path);
17699
18339
  } catch {
17700
18340
  }
17701
18341
  try {
17702
18342
  const cacheDir = sessionCacheDir(engineId);
17703
- if (existsSync10(cacheDir)) {
17704
- const files = readdirSync10(cacheDir);
18343
+ if (existsSync12(cacheDir)) {
18344
+ const files = readdirSync11(cacheDir);
17705
18345
  for (const f of files) {
17706
18346
  try {
17707
- unlinkSync6(join16(cacheDir, f));
18347
+ unlinkSync6(join17(cacheDir, f));
17708
18348
  } catch {
17709
18349
  }
17710
18350
  }
@@ -17715,7 +18355,7 @@ function clearSessionState(engineId) {
17715
18355
  }
17716
18356
  var CONVERSATION_SCHEMA_VERSION = 1;
17717
18357
  function conversationStorePath() {
17718
- const cwdHash = createHash3("md5").update(process.cwd()).digest("hex").slice(0, 8);
18358
+ const cwdHash = createHash4("md5").update(process.cwd()).digest("hex").slice(0, 8);
17719
18359
  return runtimeAgonPath("sessions", `conversation-${cwdHash}.json`);
17720
18360
  }
17721
18361
  function stripEngineArtifacts(messages) {
@@ -17764,22 +18404,22 @@ ${marker}` : marker;
17764
18404
  }
17765
18405
  function saveConversation(messages, sourceEngineId) {
17766
18406
  const dir = runtimeAgonPath("sessions");
17767
- mkdirSync11(dir, { recursive: true });
18407
+ mkdirSync12(dir, { recursive: true });
17768
18408
  const path = conversationStorePath();
17769
18409
  const trimmed = messages.slice(-SESSION_MAX_MESSAGES);
17770
18410
  const clean = stripEngineArtifacts(trimmed);
17771
18411
  const data = { schemaVersion: CONVERSATION_SCHEMA_VERSION, messageHistory: clean, savedAt: Date.now(), sourceEngine: sourceEngineId };
17772
18412
  const tmpPath = path + ".tmp";
17773
- writeFileSync12(tmpPath, JSON.stringify(data), "utf-8");
18413
+ writeFileSync13(tmpPath, JSON.stringify(data), "utf-8");
17774
18414
  renameSync9(tmpPath, path);
17775
18415
  }
17776
18416
  function loadConversation() {
17777
18417
  const path = conversationStorePath();
17778
- if (!existsSync10(path)) {
18418
+ if (!existsSync12(path)) {
17779
18419
  return null;
17780
18420
  }
17781
18421
  try {
17782
- const raw = readFileSync14(path, "utf-8");
18422
+ const raw = readFileSync16(path, "utf-8");
17783
18423
  const data = JSON.parse(raw);
17784
18424
  if (data.savedAt && Date.now() - data.savedAt > SESSION_TTL_MS) {
17785
18425
  return null;
@@ -17795,7 +18435,7 @@ function loadConversation() {
17795
18435
  function clearConversation() {
17796
18436
  const path = conversationStorePath();
17797
18437
  try {
17798
- if (existsSync10(path)) unlinkSync6(path);
18438
+ if (existsSync12(path)) unlinkSync6(path);
17799
18439
  } catch {
17800
18440
  }
17801
18441
  }
@@ -17998,7 +18638,7 @@ var Semaphore = class {
17998
18638
  this.permits -= 1;
17999
18639
  return;
18000
18640
  }
18001
- return new Promise((resolve27, reject) => {
18641
+ return new Promise((resolve28, reject) => {
18002
18642
  const entry = {
18003
18643
  resolve: () => {
18004
18644
  if (entry.onAbort && entry.signal) {
@@ -18007,7 +18647,7 @@ var Semaphore = class {
18007
18647
  } catch {
18008
18648
  }
18009
18649
  }
18010
- resolve27();
18650
+ resolve28();
18011
18651
  },
18012
18652
  reject: (err) => {
18013
18653
  if (entry.onAbort && entry.signal) {
@@ -18624,8 +19264,8 @@ async function runToolLoop(sendMessage, initialResponse, ctx, registry2, callbac
18624
19264
  }
18625
19265
 
18626
19266
  // ../core/src/generated/tools/tool-read.ts
18627
- import { readFileSync as readFileSync15, statSync as statSync10, existsSync as existsSync11 } from "fs";
18628
- import { resolve as resolve10, relative as relative3 } from "path";
19267
+ import { readFileSync as readFileSync17, statSync as statSync11, existsSync as existsSync13 } from "fs";
19268
+ import { resolve as resolve11, relative as relative4 } from "path";
18629
19269
  function formatWithLineNumbers(text, startLine) {
18630
19270
  const lines = text.split("\n");
18631
19271
  return lines.map((line, i) => {
@@ -18663,9 +19303,9 @@ function createReadTool() {
18663
19303
  return null;
18664
19304
  };
18665
19305
  const checkPermission = (input, ctx) => {
18666
- const filePath = resolve10(ctx.cwd, input.file_path);
18667
- const rel = relative3(ctx.cwd, filePath);
18668
- if (rel.startsWith("..") || resolve10(ctx.cwd, rel) !== filePath) {
19306
+ const filePath = resolve11(ctx.cwd, input.file_path);
19307
+ const rel = relative4(ctx.cwd, filePath);
19308
+ if (rel.startsWith("..") || resolve11(ctx.cwd, rel) !== filePath) {
18669
19309
  return {
18670
19310
  behavior: "deny",
18671
19311
  message: `Read denied: ${filePath} is outside the working directory`,
@@ -18675,7 +19315,7 @@ function createReadTool() {
18675
19315
  return { behavior: "allow" };
18676
19316
  };
18677
19317
  const execute = async (input, ctx) => {
18678
- const filePath = resolve10(ctx.cwd, input.file_path);
19318
+ const filePath = resolve11(ctx.cwd, input.file_path);
18679
19319
  if (ctx.virtualFs) {
18680
19320
  const vfsContent = ctx.virtualFs.read(filePath);
18681
19321
  if (vfsContent === null) {
@@ -18687,12 +19327,12 @@ function createReadTool() {
18687
19327
  const sliced2 = limit2 !== void 0 ? lines2.slice(offset2, offset2 + limit2) : lines2.slice(offset2);
18688
19328
  return { ok: true, content: sliced2.join("\n") };
18689
19329
  }
18690
- if (!existsSync11(filePath)) {
19330
+ if (!existsSync13(filePath)) {
18691
19331
  return { ok: false, content: "", error: `File not found: ${filePath}` };
18692
19332
  }
18693
19333
  let mtime;
18694
19334
  try {
18695
- const stat = statSync10(filePath);
19335
+ const stat = statSync11(filePath);
18696
19336
  mtime = stat.mtimeMs;
18697
19337
  } catch (err) {
18698
19338
  return { ok: false, content: "", error: `Cannot stat file: ${err instanceof Error ? err.message : String(err)}` };
@@ -18708,7 +19348,7 @@ function createReadTool() {
18708
19348
  }
18709
19349
  let fullContent;
18710
19350
  try {
18711
- fullContent = readFileSync15(filePath, "utf-8");
19351
+ fullContent = readFileSync17(filePath, "utf-8");
18712
19352
  } catch (err) {
18713
19353
  return { ok: false, content: "", error: `Cannot read file: ${err instanceof Error ? err.message : String(err)}` };
18714
19354
  }
@@ -18739,8 +19379,8 @@ function createReadTool() {
18739
19379
  }
18740
19380
 
18741
19381
  // ../core/src/generated/tools/tool-edit.ts
18742
- import { readFileSync as readFileSync16, writeFileSync as writeFileSync13, statSync as statSync11, existsSync as existsSync12 } from "fs";
18743
- import { resolve as resolve11, relative as relative4 } from "path";
19382
+ import { readFileSync as readFileSync18, writeFileSync as writeFileSync14, statSync as statSync12, existsSync as existsSync14 } from "fs";
19383
+ import { resolve as resolve12, relative as relative5 } from "path";
18744
19384
  function normalizeCurlyQuotes(text) {
18745
19385
  return text.replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"');
18746
19386
  }
@@ -18796,9 +19436,9 @@ function createEditTool() {
18796
19436
  reason: "exploration-mode"
18797
19437
  };
18798
19438
  }
18799
- const filePath = resolve11(ctx.cwd, input.file_path);
18800
- const rel = relative4(ctx.cwd, filePath);
18801
- if (rel.startsWith("..") || resolve11(ctx.cwd, rel) !== filePath) {
19439
+ const filePath = resolve12(ctx.cwd, input.file_path);
19440
+ const rel = relative5(ctx.cwd, filePath);
19441
+ if (rel.startsWith("..") || resolve12(ctx.cwd, rel) !== filePath) {
18802
19442
  return {
18803
19443
  behavior: "deny",
18804
19444
  message: `Edit denied: ${filePath} is outside the working directory`,
@@ -18808,7 +19448,7 @@ function createEditTool() {
18808
19448
  return { behavior: "allow" };
18809
19449
  };
18810
19450
  const execute = async (input, ctx) => {
18811
- const filePath = resolve11(ctx.cwd, input.file_path);
19451
+ const filePath = resolve12(ctx.cwd, input.file_path);
18812
19452
  const oldString = input.old_string;
18813
19453
  const newString = input.new_string;
18814
19454
  const replaceAll = input.replace_all ?? false;
@@ -18824,7 +19464,7 @@ function createEditTool() {
18824
19464
  ctx.virtualFs.write(filePath, updated);
18825
19465
  return { ok: true, content: `Edited ${filePath} in VirtualFS` };
18826
19466
  }
18827
- if (!existsSync12(filePath)) {
19467
+ if (!existsSync14(filePath)) {
18828
19468
  return { ok: false, content: "", error: `File not found: ${filePath}` };
18829
19469
  }
18830
19470
  const cache = ctx.readFileState;
@@ -18837,7 +19477,7 @@ function createEditTool() {
18837
19477
  }
18838
19478
  let mtime;
18839
19479
  try {
18840
- const stat = statSync11(filePath);
19480
+ const stat = statSync12(filePath);
18841
19481
  mtime = stat.mtimeMs;
18842
19482
  } catch (err) {
18843
19483
  return { ok: false, content: "", error: `Cannot stat file: ${err instanceof Error ? err.message : String(err)}` };
@@ -18852,7 +19492,7 @@ function createEditTool() {
18852
19492
  }
18853
19493
  let content;
18854
19494
  try {
18855
- content = readFileSync16(filePath, "utf-8");
19495
+ content = readFileSync18(filePath, "utf-8");
18856
19496
  } catch (err) {
18857
19497
  return { ok: false, content: "", error: `Cannot read file: ${err instanceof Error ? err.message : String(err)}` };
18858
19498
  }
@@ -18885,15 +19525,15 @@ function createEditTool() {
18885
19525
  };
18886
19526
  }
18887
19527
  }
18888
- const relPath = relative4(ctx.cwd, filePath);
19528
+ const relPath = relative5(ctx.cwd, filePath);
18889
19529
  const snapshot = takeSnapshot(`Edit: ${relPath}`, ctx.cwd, [relPath]);
18890
19530
  const newContent = replaceAll ? content.split(searchString).join(newString) : content.replace(searchString, newString);
18891
19531
  try {
18892
- writeFileSync13(filePath, newContent, "utf-8");
19532
+ writeFileSync14(filePath, newContent, "utf-8");
18893
19533
  } catch (err) {
18894
19534
  return { ok: false, content: "", error: `Failed to write file: ${err instanceof Error ? err.message : String(err)}` };
18895
19535
  }
18896
- const newMtime = statSync11(filePath).mtimeMs;
19536
+ const newMtime = statSync12(filePath).mtimeMs;
18897
19537
  cache.set(filePath, {
18898
19538
  content: newContent,
18899
19539
  timestamp: newMtime,
@@ -18912,8 +19552,8 @@ function createEditTool() {
18912
19552
  }
18913
19553
 
18914
19554
  // ../core/src/generated/tools/tool-write.ts
18915
- import { writeFileSync as writeFileSync14, statSync as statSync12, existsSync as existsSync13, mkdirSync as mkdirSync13 } from "fs";
18916
- import { resolve as resolve12, dirname as dirname8, relative as relative5 } from "path";
19555
+ import { writeFileSync as writeFileSync15, statSync as statSync13, existsSync as existsSync15, mkdirSync as mkdirSync14 } from "fs";
19556
+ import { resolve as resolve13, dirname as dirname9, relative as relative6 } from "path";
18917
19557
  function createWriteTool() {
18918
19558
  const definition = {
18919
19559
  name: "Write",
@@ -18947,9 +19587,9 @@ function createWriteTool() {
18947
19587
  reason: "exploration-mode"
18948
19588
  };
18949
19589
  }
18950
- const filePath = resolve12(ctx.cwd, input.file_path);
18951
- const rel = relative5(ctx.cwd, filePath);
18952
- if (rel.startsWith("..") || resolve12(ctx.cwd, rel) !== filePath) {
19590
+ const filePath = resolve13(ctx.cwd, input.file_path);
19591
+ const rel = relative6(ctx.cwd, filePath);
19592
+ if (rel.startsWith("..") || resolve13(ctx.cwd, rel) !== filePath) {
18953
19593
  return {
18954
19594
  behavior: "deny",
18955
19595
  message: `Write denied: ${filePath} is outside the working directory`,
@@ -18959,15 +19599,15 @@ function createWriteTool() {
18959
19599
  return { behavior: "allow" };
18960
19600
  };
18961
19601
  const execute = async (input, ctx) => {
18962
- const filePath = resolve12(ctx.cwd, input.file_path);
19602
+ const filePath = resolve13(ctx.cwd, input.file_path);
18963
19603
  const content = input.content;
18964
- const relPath = relative5(ctx.cwd, filePath);
19604
+ const relPath = relative6(ctx.cwd, filePath);
18965
19605
  const cache = ctx.readFileState;
18966
19606
  if (ctx.virtualFs) {
18967
19607
  ctx.virtualFs.write(filePath, content);
18968
19608
  return { ok: true, content: `Wrote ${filePath} in VirtualFS (${content.split("\n").length} lines)` };
18969
19609
  }
18970
- const fileExists = existsSync13(filePath);
19610
+ const fileExists = existsSync15(filePath);
18971
19611
  let snapshot = null;
18972
19612
  if (fileExists) {
18973
19613
  if (!cache.has(filePath)) {
@@ -18979,7 +19619,7 @@ function createWriteTool() {
18979
19619
  }
18980
19620
  let mtime;
18981
19621
  try {
18982
- const stat = statSync12(filePath);
19622
+ const stat = statSync13(filePath);
18983
19623
  mtime = stat.mtimeMs;
18984
19624
  } catch (err) {
18985
19625
  return { ok: false, content: "", error: `Cannot stat file: ${err instanceof Error ? err.message : String(err)}` };
@@ -18996,20 +19636,20 @@ function createWriteTool() {
18996
19636
  } else {
18997
19637
  snapshot = takeSnapshot(`Write (new): ${relPath}`, ctx.cwd, [relPath]);
18998
19638
  }
18999
- const parentDir = dirname8(filePath);
19000
- if (!existsSync13(parentDir)) {
19639
+ const parentDir = dirname9(filePath);
19640
+ if (!existsSync15(parentDir)) {
19001
19641
  try {
19002
- mkdirSync13(parentDir, { recursive: true });
19642
+ mkdirSync14(parentDir, { recursive: true });
19003
19643
  } catch (err) {
19004
19644
  return { ok: false, content: "", error: `Failed to create directory: ${err instanceof Error ? err.message : String(err)}` };
19005
19645
  }
19006
19646
  }
19007
19647
  try {
19008
- writeFileSync14(filePath, content, "utf-8");
19648
+ writeFileSync15(filePath, content, "utf-8");
19009
19649
  } catch (err) {
19010
19650
  return { ok: false, content: "", error: `Failed to write file: ${err instanceof Error ? err.message : String(err)}` };
19011
19651
  }
19012
- const newMtime = statSync12(filePath).mtimeMs;
19652
+ const newMtime = statSync13(filePath).mtimeMs;
19013
19653
  cache.set(filePath, {
19014
19654
  content,
19015
19655
  timestamp: newMtime,
@@ -19044,6 +19684,13 @@ function extractBaseCommand(command) {
19044
19684
  }
19045
19685
  return cmd;
19046
19686
  }
19687
+ function guiUnavailableHint(command, stderr) {
19688
+ const cmd = (command ?? "").trim();
19689
+ const launchesGui = /(^|\s)electron(\s|$)/i.test(cmd) || /(^|\s)(pnpm|npm|yarn|bun)\s+(run\s+)?(studio|gui)(\s|$)/i.test(cmd);
19690
+ const displayFailure = /(DISPLAY\s+not\s+set|cannot\s+open\s+display|Missing X server)/i.test(stderr ?? "");
19691
+ if (!launchesGui && !displayFailure) return null;
19692
+ return "This looks like a GUI/desktop app, which cannot run in this headless shell. Use a headless equivalent (a build/test/CLI script, or a --headless flag), or run the GUI on your own machine.";
19693
+ }
19047
19694
  function createBashTool() {
19048
19695
  const definition = {
19049
19696
  name: "Bash",
@@ -19112,10 +19759,10 @@ function createBashTool() {
19112
19759
  const readRedirect = tryRedirectToRead(command);
19113
19760
  if (readRedirect) {
19114
19761
  try {
19115
- const { readFileSync: readFileSync31 } = await import("fs");
19116
- const { resolve: resolve27 } = await import("path");
19117
- const filePath = resolve27(ctx.cwd, readRedirect.file);
19118
- const content = readFileSync31(filePath, "utf-8");
19762
+ const { readFileSync: readFileSync33 } = await import("fs");
19763
+ const { resolve: resolve28 } = await import("path");
19764
+ const filePath = resolve28(ctx.cwd, readRedirect.file);
19765
+ const content = readFileSync33(filePath, "utf-8");
19119
19766
  const lines = content.split("\n");
19120
19767
  const offset = readRedirect.offset ?? 0;
19121
19768
  const limit = readRedirect.limit ?? lines.length;
@@ -19160,19 +19807,23 @@ function createBashTool() {
19160
19807
  }
19161
19808
  const durationMs = Date.now() - start;
19162
19809
  const exitCode = closeResult?.exitCode ?? 1;
19810
+ const guiHint = guiUnavailableHint(command, stderr);
19163
19811
  if (closeResult?.timedOut) {
19164
19812
  return {
19165
19813
  ok: false,
19166
19814
  content: stdout,
19167
- error: `Command timed out after ${timeout}ms`,
19815
+ error: `Command timed out after ${timeout}ms` + (guiHint ? `
19816
+ ${guiHint}` : ""),
19168
19817
  metadata: { exitCode: 124, durationMs, timedOut: true }
19169
19818
  };
19170
19819
  }
19171
19820
  if (exitCode !== 0) {
19821
+ const baseErr = stderr || `Process exited with code ${exitCode}`;
19172
19822
  return {
19173
19823
  ok: false,
19174
19824
  content: stdout,
19175
- error: stderr || `Process exited with code ${exitCode}`,
19825
+ error: guiHint ? `${baseErr}
19826
+ ${guiHint}` : baseErr,
19176
19827
  metadata: { exitCode, durationMs, timedOut: false }
19177
19828
  };
19178
19829
  }
@@ -19415,7 +20066,7 @@ import { randomUUID as randomUUID3 } from "crypto";
19415
20066
 
19416
20067
  // ../core/src/generated/blocks/file-state-cache.ts
19417
20068
  import { execFileSync as execFileSync3 } from "child_process";
19418
- import { resolve as resolve13 } from "path";
20069
+ import { resolve as resolve14 } from "path";
19419
20070
  var MAX_CACHE_ENTRIES = 100;
19420
20071
  var MAX_CACHE_BYTES = 25 * 1024 * 1024;
19421
20072
  function createTrackedFileStateMap(owner) {
@@ -19520,7 +20171,7 @@ var _projectCaches = /* @__PURE__ */ new Map();
19520
20171
  var _projectFingerprintCache = /* @__PURE__ */ new Map();
19521
20172
  var PROJECT_FINGERPRINT_TTL_MS = 1e3;
19522
20173
  function projectCacheFingerprint(cwd) {
19523
- const absCwd = resolve13(cwd || process.cwd());
20174
+ const absCwd = resolve14(cwd || process.cwd());
19524
20175
  const now = Date.now();
19525
20176
  const cached2 = _projectFingerprintCache.get(absCwd);
19526
20177
  if (cached2 && cached2.expires > now) return cached2.value;
@@ -19895,21 +20546,21 @@ function createTodoWriteTool() {
19895
20546
  }
19896
20547
 
19897
20548
  // ../core/src/generated/signals/auth-store.ts
19898
- import { readFileSync as readFileSync17, writeFileSync as writeFileSync15, mkdirSync as mkdirSync14, existsSync as existsSync14, chmodSync } from "fs";
19899
- import { join as join17, dirname as dirname9, resolve as resolve14 } from "path";
20549
+ import { readFileSync as readFileSync19, writeFileSync as writeFileSync16, mkdirSync as mkdirSync15, existsSync as existsSync16, chmodSync } from "fs";
20550
+ import { join as join18, dirname as dirname10, resolve as resolve15 } from "path";
19900
20551
  import { homedir as homedir9 } from "os";
19901
20552
  function getAuthFile() {
19902
20553
  const override = process.env.AGON_HOME?.trim();
19903
- const home = override ? resolve14(override) : join17(homedir9(), ".agon");
19904
- return join17(home, "auth.json");
20554
+ const home = override ? resolve15(override) : join18(homedir9(), ".agon");
20555
+ return join18(home, "auth.json");
19905
20556
  }
19906
20557
  function loadAuthStore() {
19907
20558
  const authFile = getAuthFile();
19908
- if (!existsSync14(authFile)) {
20559
+ if (!existsSync16(authFile)) {
19909
20560
  return { entries: {} };
19910
20561
  }
19911
20562
  try {
19912
- const data = JSON.parse(readFileSync17(authFile, "utf-8"));
20563
+ const data = JSON.parse(readFileSync19(authFile, "utf-8"));
19913
20564
  return { entries: data ?? {} };
19914
20565
  } catch (e) {
19915
20566
  return { entries: {} };
@@ -19917,9 +20568,9 @@ function loadAuthStore() {
19917
20568
  }
19918
20569
  function saveAuthStore(store) {
19919
20570
  const authFile = getAuthFile();
19920
- const dir = dirname9(authFile);
19921
- mkdirSync14(dir, { recursive: true });
19922
- writeFileSync15(authFile, JSON.stringify(store.entries, null, 2) + "\n", { mode: 384 });
20571
+ const dir = dirname10(authFile);
20572
+ mkdirSync15(dir, { recursive: true });
20573
+ writeFileSync16(authFile, JSON.stringify(store.entries, null, 2) + "\n", { mode: 384 });
19923
20574
  try {
19924
20575
  chmodSync(authFile, 384);
19925
20576
  } catch (_e) {
@@ -20469,7 +21120,7 @@ function planEngineIsolation(engine, mode, opts) {
20469
21120
  var fileStateCache = new FileStateCache();
20470
21121
 
20471
21122
  // ../core/src/generated/tools/tool-permissions.ts
20472
- import { resolve as resolve15, relative as relative6, isAbsolute as isAbsolute2 } from "path";
21123
+ import { resolve as resolve16, relative as relative7, isAbsolute as isAbsolute3 } from "path";
20473
21124
  import { realpathSync as realpathSync3 } from "fs";
20474
21125
  import { execSync as execSync3 } from "child_process";
20475
21126
  var DANGEROUS_COMMANDS = ["rm -rf /", "rm -rf ~", "rm -rf *", "dd if" + String.fromCharCode(61), "mkfs.", "> /dev/sd", "> /dev/nv", "chmod 777 /", ":(){:|:&}\\x3b:"];
@@ -20524,7 +21175,7 @@ function checkBashPermission(command, ctx) {
20524
21175
  return isDangerousCommand(command) ? { behavior: "deny", message: `Dangerous command blocked: ${command.slice(0, 50)}`, reason: "dangerous_pattern" } : ctx.permissionMode === "deny-all" ? { behavior: "deny", message: "All tool execution is denied" } : ctx.toolPermissions?.["Bash"] === "allow" ? { behavior: "allow" } : ctx.toolPermissions?.["Bash"] === "deny" ? { behavior: "deny", message: "Bash denied in settings" } : isReadOnlyCommand(command) ? { behavior: "allow" } : ctx.allowedCommands?.some((ac) => command.startsWith(ac) || command.trim().split(/\s+/)[0] === ac) ? { behavior: "allow" } : ctx.permissionMode === "smart" ? isSessionAllowed(command, ctx) || ctx.source === "orchestrator" ? { behavior: "allow" } : { behavior: "ask", message: `This command requires approval`, reason: "bash_mutating" } : ctx.permissionMode === "auto" ? { behavior: "allow" } : { behavior: "ask", message: `This command requires approval`, reason: "bash_mutating" };
20525
21176
  }
20526
21177
  function isPathUnderCwd(filePath, cwd) {
20527
- const resolved = isAbsolute2(filePath) ? filePath : resolve15(cwd, filePath);
21178
+ const resolved = isAbsolute3(filePath) ? filePath : resolve16(cwd, filePath);
20528
21179
  let realPath;
20529
21180
  let realCwd;
20530
21181
  try {
@@ -20537,7 +21188,7 @@ function isPathUnderCwd(filePath, cwd) {
20537
21188
  } catch {
20538
21189
  realCwd = cwd;
20539
21190
  }
20540
- const rel = relative6(realCwd, realPath);
21191
+ const rel = relative7(realCwd, realPath);
20541
21192
  return !rel.startsWith("..");
20542
21193
  }
20543
21194
  function checkFileReadPermission(filePath, ctx) {
@@ -20547,7 +21198,7 @@ function checkFileReadPermission(filePath, ctx) {
20547
21198
  if (ctx.toolPermissions?.["Read"] === "deny") {
20548
21199
  return { behavior: "deny", message: "Read denied in settings" };
20549
21200
  }
20550
- const readResolved = isAbsolute2(filePath) ? filePath : resolve15(ctx.cwd, filePath);
21201
+ const readResolved = isAbsolute3(filePath) ? filePath : resolve16(ctx.cwd, filePath);
20551
21202
  if (isPathUnderCwd(readResolved, ctx.cwd)) {
20552
21203
  return { behavior: "allow" };
20553
21204
  }
@@ -20572,11 +21223,11 @@ function checkFileWritePermission(filePath, ctx) {
20572
21223
  return { behavior: "ask", message: `Edit requires approval: ${filePath}` };
20573
21224
  }
20574
21225
  }
20575
- const writeResolved = isAbsolute2(filePath) ? filePath : resolve15(ctx.cwd, filePath);
20576
- const basename6 = writeResolved.split("/").pop() ?? "";
21226
+ const writeResolved = isAbsolute3(filePath) ? filePath : resolve16(ctx.cwd, filePath);
21227
+ const basename7 = writeResolved.split("/").pop() ?? "";
20577
21228
  const sensitivePatterns = [".env", "credentials", "secrets", ".pem", ".key", "id_rsa"];
20578
- if (sensitivePatterns.some((pat) => basename6.includes(pat))) {
20579
- return { behavior: "ask", message: `Write to sensitive file: ${basename6}` };
21229
+ if (sensitivePatterns.some((pat) => basename7.includes(pat))) {
21230
+ return { behavior: "ask", message: `Write to sensitive file: ${basename7}` };
20580
21231
  }
20581
21232
  if (isPathUnderCwd(writeResolved, ctx.cwd)) {
20582
21233
  return { behavior: "allow" };
@@ -20936,6 +21587,39 @@ function createGoalTool() {
20936
21587
  };
20937
21588
  return { definition, validate, checkPermission, execute };
20938
21589
  }
21590
+ function createConquerTool() {
21591
+ const definition = {
21592
+ name: "Conquer",
21593
+ description: "Delegate to the supervised-autonomous conquer controller \u2014 Cesar drives an external builder CLI (--builder codex|claude|agy, default codex) as the user, unattended, until an OPEN-ENDED build is done, then STOPS at a human merge gate (changes left in the tree or pushed to a branch; NEVER auto-merged). The gate command IS the done-spec \u2014 make it discriminating. Fire ONLY when the user explicitly asks to conquer / build unattended; it is a long multi-hour run. After calling, STOP and wait \u2014 runs in the background; track with /jobs or /focus.",
21594
+ inputSchema: {
21595
+ type: "object",
21596
+ properties: {
21597
+ task: { type: "string", description: "Open-ended build task to drive to completion (seeds the run + branch)." },
21598
+ gate: { type: "string", description: 'The done-spec: a discriminating test/verify command that proves the build is complete (e.g. "pnpm test"). Required \u2014 frozen at start.' },
21599
+ builder: { type: "string", description: "External builder CLI Cesar drives as the user: codex | claude | agy. Default codex." },
21600
+ engines: { type: "array", items: { type: "string" }, description: "Optional consult roster for fork escalations (nero/tribunal/council). Omit for active roster." },
21601
+ maxTurns: { type: "number", description: "Optional cap on builder turns (0/omit = controller default)." }
21602
+ },
21603
+ required: ["task", "gate"]
21604
+ },
21605
+ maxResultSizeChars: 500,
21606
+ isReadOnly: false,
21607
+ isConcurrencySafe: false
21608
+ };
21609
+ const validate = (input, _ctx) => {
21610
+ if (!input.task || typeof input.task !== "string" || !input.task.trim()) return "Missing required parameter: task";
21611
+ if (!input.gate || typeof input.gate !== "string" || !input.gate.trim()) return "Missing required parameter: gate (the done-spec test/verify command). Ask the user for the command that proves the build is done.";
21612
+ if (input.engines !== void 0 && (!Array.isArray(input.engines) || !input.engines.every((e) => typeof e === "string" && e.trim().length > 0))) return "engines must be an array of non-empty engine ID strings";
21613
+ return null;
21614
+ };
21615
+ const checkPermission = (_input, _ctx) => {
21616
+ return { behavior: "allow" };
21617
+ };
21618
+ const execute = async (_input, _ctx) => {
21619
+ return { ok: true, content: "Delegation accepted. STOP responding now. The orchestrator will handle the rest." };
21620
+ };
21621
+ return { definition, validate, checkPermission, execute };
21622
+ }
20939
21623
  function createPipelineTool() {
20940
21624
  const definition = {
20941
21625
  name: "Pipeline",
@@ -21094,8 +21778,8 @@ function createExitPlanModeTool() {
21094
21778
  }
21095
21779
 
21096
21780
  // ../core/src/generated/cesar/plan.ts
21097
- import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync16, readFileSync as readFileSync18, readdirSync as readdirSync11, renameSync as renameSync10, unlinkSync as unlinkSync7, existsSync as existsSync15 } from "fs";
21098
- import { join as join18, resolve as resolve16 } from "path";
21781
+ import { mkdirSync as mkdirSync16, writeFileSync as writeFileSync17, readFileSync as readFileSync20, readdirSync as readdirSync12, renameSync as renameSync10, unlinkSync as unlinkSync7, existsSync as existsSync17 } from "fs";
21782
+ import { join as join19, resolve as resolve17 } from "path";
21099
21783
  function getCesarPlansDir() {
21100
21784
  return runtimeAgonPath("plans");
21101
21785
  }
@@ -21108,16 +21792,16 @@ function safeCesarPlanId(planId) {
21108
21792
  }
21109
21793
  function cesarPlanJsonPath(planId) {
21110
21794
  const plansDir = getCesarPlansDir();
21111
- const full = resolve16(plansDir, `${safeCesarPlanId(planId)}.json`);
21112
- if (!full.startsWith(resolve16(plansDir))) {
21795
+ const full = resolve17(plansDir, `${safeCesarPlanId(planId)}.json`);
21796
+ if (!full.startsWith(resolve17(plansDir))) {
21113
21797
  throw new Error(`Invalid plan ID: ${planId}`);
21114
21798
  }
21115
21799
  return full;
21116
21800
  }
21117
21801
  function cesarPlanMarkdownPath(planId) {
21118
21802
  const plansDir = getCesarPlansDir();
21119
- const full = resolve16(plansDir, `${safeCesarPlanId(planId)}.md`);
21120
- if (!full.startsWith(resolve16(plansDir))) {
21803
+ const full = resolve17(plansDir, `${safeCesarPlanId(planId)}.md`);
21804
+ if (!full.startsWith(resolve17(plansDir))) {
21121
21805
  throw new Error(`Invalid plan ID: ${planId}`);
21122
21806
  }
21123
21807
  return full;
@@ -21202,7 +21886,7 @@ function exitCesarPlan(plan, reason) {
21202
21886
  }
21203
21887
  function saveCesarPlan(plan) {
21204
21888
  const dir = getCesarPlansDir();
21205
- mkdirSync15(dir, { recursive: true });
21889
+ mkdirSync16(dir, { recursive: true });
21206
21890
  const finalPath = cesarPlanJsonPath(plan.id);
21207
21891
  const persistedPlan = {
21208
21892
  ...plan,
@@ -21210,7 +21894,7 @@ function saveCesarPlan(plan) {
21210
21894
  };
21211
21895
  const tmpPath = `${finalPath}.${process.pid}.${Date.now()}.tmp`;
21212
21896
  try {
21213
- writeFileSync16(tmpPath, JSON.stringify(persistedPlan, null, 2));
21897
+ writeFileSync17(tmpPath, JSON.stringify(persistedPlan, null, 2));
21214
21898
  renameSync10(tmpPath, finalPath);
21215
21899
  } catch (err) {
21216
21900
  try {
@@ -21230,9 +21914,9 @@ function loadCesarPlan(planId) {
21230
21914
  const paths = [{ filePath: cesarPlanJsonPath(safeId), canonical: true }, { filePath: runtimeAgonPath("runs", `${safeId}.json`), canonical: false }];
21231
21915
  for (const entry of paths) {
21232
21916
  try {
21233
- const plan = JSON.parse(readFileSync18(entry.filePath, "utf-8"));
21917
+ const plan = JSON.parse(readFileSync20(entry.filePath, "utf-8"));
21234
21918
  const fallbackMarkdownPath = cesarPlanMarkdownPath(plan.id);
21235
- const hasFallback = entry.canonical || existsSync15(fallbackMarkdownPath);
21919
+ const hasFallback = entry.canonical || existsSync17(fallbackMarkdownPath);
21236
21920
  const fallbackPath = hasFallback ? fallbackMarkdownPath : void 0;
21237
21921
  const planFilePath = plan.planFilePath ?? fallbackPath;
21238
21922
  return planFilePath ? { ...plan, planFilePath } : plan;
@@ -21246,16 +21930,16 @@ function listCesarPlans() {
21246
21930
  const readFromDir = (dir, canonical) => {
21247
21931
  let files = [];
21248
21932
  try {
21249
- files = readdirSync11(dir).filter((f) => f.startsWith("cplan-") && f.endsWith(".json"));
21933
+ files = readdirSync12(dir).filter((f) => f.startsWith("cplan-") && f.endsWith(".json"));
21250
21934
  } catch {
21251
21935
  return;
21252
21936
  }
21253
21937
  for (const f of files) {
21254
21938
  try {
21255
- const plan = JSON.parse(readFileSync18(join18(dir, f), "utf-8"));
21939
+ const plan = JSON.parse(readFileSync20(join19(dir, f), "utf-8"));
21256
21940
  if (!plan?.id || byId.has(plan.id)) continue;
21257
21941
  const fallbackMarkdownPath = cesarPlanMarkdownPath(plan.id);
21258
- const planFilePath = plan.planFilePath ?? (canonical || existsSync15(fallbackMarkdownPath) ? fallbackMarkdownPath : void 0);
21942
+ const planFilePath = plan.planFilePath ?? (canonical || existsSync17(fallbackMarkdownPath) ? fallbackMarkdownPath : void 0);
21259
21943
  byId.set(plan.id, planFilePath ? { ...plan, planFilePath } : plan);
21260
21944
  } catch {
21261
21945
  }
@@ -21404,15 +22088,15 @@ function formatCesarPlanMarkdown(plan) {
21404
22088
  }
21405
22089
 
21406
22090
  // ../core/src/generated/tools/mcp-discovery.ts
21407
- import { readFileSync as readFileSync19, existsSync as existsSync16, statSync as statSync13 } from "fs";
21408
- import { join as join19 } from "path";
22091
+ import { readFileSync as readFileSync21, existsSync as existsSync18, statSync as statSync14 } from "fs";
22092
+ import { join as join20 } from "path";
21409
22093
  import { homedir as homedir10 } from "os";
21410
22094
  function _readJsonSafe(path) {
21411
22095
  try {
21412
- if (!existsSync16(path)) {
22096
+ if (!existsSync18(path)) {
21413
22097
  return null;
21414
22098
  }
21415
- return JSON.parse(readFileSync19(path, "utf-8"));
22099
+ return JSON.parse(readFileSync21(path, "utf-8"));
21416
22100
  } catch (e) {
21417
22101
  return null;
21418
22102
  }
@@ -21445,31 +22129,31 @@ function _extractMcpServers(data) {
21445
22129
  function discoverMcpServers(cwd) {
21446
22130
  const home = homedir10();
21447
22131
  const servers = /* @__PURE__ */ new Map();
21448
- const claudeSettings = _readJsonSafe(join19(home, ".claude", "settings.json"));
22132
+ const claudeSettings = _readJsonSafe(join20(home, ".claude", "settings.json"));
21449
22133
  if (claudeSettings) {
21450
22134
  for (const s of _extractMcpServers(claudeSettings)) {
21451
22135
  servers.set(s.name, s);
21452
22136
  }
21453
22137
  }
21454
- const claudeLocal = _readJsonSafe(join19(home, ".claude", "settings.local.json"));
22138
+ const claudeLocal = _readJsonSafe(join20(home, ".claude", "settings.local.json"));
21455
22139
  if (claudeLocal) {
21456
22140
  for (const s of _extractMcpServers(claudeLocal)) {
21457
22141
  servers.set(s.name, s);
21458
22142
  }
21459
22143
  }
21460
- const vscodeMcp = _readJsonSafe(join19(cwd, ".vscode", "mcp.json"));
22144
+ const vscodeMcp = _readJsonSafe(join20(cwd, ".vscode", "mcp.json"));
21461
22145
  if (vscodeMcp) {
21462
22146
  for (const s of _extractMcpServers(vscodeMcp)) {
21463
22147
  servers.set(s.name, s);
21464
22148
  }
21465
22149
  }
21466
- const cursorMcp = _readJsonSafe(join19(cwd, ".cursor", "mcp.json"));
22150
+ const cursorMcp = _readJsonSafe(join20(cwd, ".cursor", "mcp.json"));
21467
22151
  if (cursorMcp) {
21468
22152
  for (const s of _extractMcpServers(cursorMcp)) {
21469
22153
  servers.set(s.name, s);
21470
22154
  }
21471
22155
  }
21472
- const agonProject = _readJsonSafe(join19(cwd, ".agon.json"));
22156
+ const agonProject = _readJsonSafe(join20(cwd, ".agon.json"));
21473
22157
  if (agonProject) {
21474
22158
  for (const s of _extractMcpServers(agonProject)) {
21475
22159
  servers.set(s.name, s);
@@ -21479,12 +22163,12 @@ function discoverMcpServers(cwd) {
21479
22163
  }
21480
22164
  function mcpDiscoveryFingerprint(cwd) {
21481
22165
  const home = homedir10();
21482
- const paths = [join19(home, ".claude", "settings.json"), join19(home, ".claude", "settings.local.json"), join19(cwd, ".vscode", "mcp.json"), join19(cwd, ".cursor", "mcp.json"), join19(cwd, ".agon.json")];
22166
+ const paths = [join20(home, ".claude", "settings.json"), join20(home, ".claude", "settings.local.json"), join20(cwd, ".vscode", "mcp.json"), join20(cwd, ".cursor", "mcp.json"), join20(cwd, ".agon.json")];
21483
22167
  const parts = [];
21484
22168
  for (const p of paths) {
21485
22169
  try {
21486
- if (existsSync16(p)) {
21487
- parts.push(`${p}:${statSync13(p).mtimeMs}`);
22170
+ if (existsSync18(p)) {
22171
+ parts.push(`${p}:${statSync14(p).mtimeMs}`);
21488
22172
  }
21489
22173
  } catch (e) {
21490
22174
  }
@@ -21502,13 +22186,13 @@ function mcpServersToWireFormat(servers) {
21502
22186
  }
21503
22187
 
21504
22188
  // ../core/src/generated/signals/chat-store.ts
21505
- import { mkdirSync as mkdirSync16, appendFileSync, readFileSync as readFileSync20, readdirSync as readdirSync12, statSync as statSync14, unlinkSync as unlinkSync8 } from "fs";
21506
- import { join as join20 } from "path";
22189
+ import { mkdirSync as mkdirSync17, appendFileSync, readFileSync as readFileSync22, readdirSync as readdirSync13, statSync as statSync15, unlinkSync as unlinkSync8 } from "fs";
22190
+ import { join as join21 } from "path";
21507
22191
  function chatsDir() {
21508
22192
  return runtimeAgonPath("chats");
21509
22193
  }
21510
22194
  function ensureChatsDir() {
21511
- mkdirSync16(chatsDir(), { recursive: true });
22195
+ mkdirSync17(chatsDir(), { recursive: true });
21512
22196
  }
21513
22197
  var CHAT_RETENTION = 50;
21514
22198
  var CHAT_SUMMARY_TAIL_MESSAGES = 12;
@@ -21517,7 +22201,7 @@ var CHAT_SUMMARY_ENTRY_CHARS = 320;
21517
22201
  function pruneChats() {
21518
22202
  try {
21519
22203
  const dir = chatsDir();
21520
- const files = readdirSync12(dir).filter((f) => f.endsWith(".ndjson")).map((f) => {
22204
+ const files = readdirSync13(dir).filter((f) => f.endsWith(".ndjson")).map((f) => {
21521
22205
  const ts = parseInt(f.replace("chat-", "").replace(".ndjson", ""), 10);
21522
22206
  return { name: f, ts: isNaN(ts) ? 0 : ts };
21523
22207
  }).sort((a, b) => b.ts - a.ts);
@@ -21525,7 +22209,7 @@ function pruneChats() {
21525
22209
  const toRemove = files.slice(CHAT_RETENTION);
21526
22210
  for (const f of toRemove) {
21527
22211
  try {
21528
- unlinkSync8(join20(dir, f.name));
22212
+ unlinkSync8(join21(dir, f.name));
21529
22213
  } catch {
21530
22214
  }
21531
22215
  }
@@ -21537,7 +22221,7 @@ function startChatSession(opts) {
21537
22221
  pruneChats();
21538
22222
  const id = `chat-${Date.now()}`;
21539
22223
  const session = { id, startedAt: (/* @__PURE__ */ new Date()).toISOString(), messages: [], cwd: opts?.cwd, branch: opts?.branch, engineIds: opts?.engineIds };
21540
- const filePath = join20(chatsDir(), `${id}.ndjson`);
22224
+ const filePath = join21(chatsDir(), `${id}.ndjson`);
21541
22225
  const header = { _type: "header", id, startedAt: session.startedAt };
21542
22226
  if (opts?.cwd) {
21543
22227
  header.cwd = opts.cwd;
@@ -21553,7 +22237,7 @@ function startChatSession(opts) {
21553
22237
  }
21554
22238
  function appendMessage(session, msg) {
21555
22239
  session.messages.push(msg);
21556
- const filePath = join20(chatsDir(), `${session.id}.ndjson`);
22240
+ const filePath = join21(chatsDir(), `${session.id}.ndjson`);
21557
22241
  appendFileSync(filePath, JSON.stringify(msg) + "\n");
21558
22242
  if (updateChatSummary(session)) {
21559
22243
  appendSummaryRecord(session);
@@ -21573,7 +22257,7 @@ function appendUserTurnIfAbsent(session, input) {
21573
22257
  }
21574
22258
  const msg = { role: "user", content: input, timestamp: (/* @__PURE__ */ new Date()).toISOString() };
21575
22259
  session.messages.push(msg);
21576
- const filePath = join20(chatsDir(), `${session.id}.ndjson`);
22260
+ const filePath = join21(chatsDir(), `${session.id}.ndjson`);
21577
22261
  appendFileSync(filePath, JSON.stringify(msg) + "\n");
21578
22262
  if (updateChatSummary(session)) {
21579
22263
  appendSummaryRecord(session);
@@ -21608,7 +22292,7 @@ function trimChatSummary(summary) {
21608
22292
  return text.slice(0, head).trimEnd() + marker + text.slice(text.length - tail).trimStart();
21609
22293
  }
21610
22294
  function appendSummaryRecord(session) {
21611
- const filePath = join20(chatsDir(), `${session.id}.ndjson`);
22295
+ const filePath = join21(chatsDir(), `${session.id}.ndjson`);
21612
22296
  appendFileSync(filePath, JSON.stringify({ _type: "summary", summary: session.summary ?? "", summarizedMessageCount: session.summarizedMessageCount ?? 0, timestamp: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
21613
22297
  }
21614
22298
  function freeSummarizedMessageBodies(messages, from, to) {
@@ -21719,8 +22403,8 @@ function buildHistoryPrimedPrompt(session, input, maxTurns) {
21719
22403
  }
21720
22404
  function loadChatSession(id) {
21721
22405
  try {
21722
- const filePath = join20(chatsDir(), `${id}.ndjson`);
21723
- const raw = readFileSync20(filePath, "utf-8");
22406
+ const filePath = join21(chatsDir(), `${id}.ndjson`);
22407
+ const raw = readFileSync22(filePath, "utf-8");
21724
22408
  const lines = raw.trim().split("\n").filter(Boolean);
21725
22409
  if (lines.length === 0) return null;
21726
22410
  const header = JSON.parse(lines[0]);
@@ -21761,9 +22445,9 @@ function listChatSessions(limit) {
21761
22445
  ensureChatsDir();
21762
22446
  try {
21763
22447
  const dir = chatsDir();
21764
- const files = readdirSync12(dir).filter((f) => f.endsWith(".ndjson")).map((f) => ({
22448
+ const files = readdirSync13(dir).filter((f) => f.endsWith(".ndjson")).map((f) => ({
21765
22449
  name: f,
21766
- mtime: statSync14(join20(dir, f)).mtimeMs
22450
+ mtime: statSync15(join21(dir, f)).mtimeMs
21767
22451
  })).sort((a, b) => b.mtime - a.mtime).slice(0, limit);
21768
22452
  return files.map((f) => {
21769
22453
  const id = f.name.replace(".ndjson", "");
@@ -21780,8 +22464,8 @@ function latestChatSession() {
21780
22464
  }
21781
22465
 
21782
22466
  // ../core/src/generated/blocks/image.ts
21783
- import { existsSync as existsSync17 } from "fs";
21784
- import { resolve as resolve18, basename as basename3, extname as extname2 } from "path";
22467
+ import { existsSync as existsSync19 } from "fs";
22468
+ import { resolve as resolve19, basename as basename4, extname as extname2 } from "path";
21785
22469
  import { homedir as homedir11 } from "os";
21786
22470
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp"]);
21787
22471
  var MIME_MAP = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml", ".bmp": "image/bmp" };
@@ -21798,20 +22482,20 @@ function mimeFromExt(filePath) {
21798
22482
  function resolveImagePath(rawPath, cwd) {
21799
22483
  let resolved;
21800
22484
  if (rawPath.startsWith("~/")) {
21801
- resolved = resolve18(homedir11(), rawPath.slice(2));
22485
+ resolved = resolve19(homedir11(), rawPath.slice(2));
21802
22486
  } else if (rawPath.startsWith("/")) {
21803
- resolved = resolve18(rawPath);
22487
+ resolved = resolve19(rawPath);
21804
22488
  } else {
21805
- resolved = resolve18(cwd, rawPath);
22489
+ resolved = resolve19(cwd, rawPath);
21806
22490
  }
21807
- return existsSync17(resolved) ? resolved : null;
22491
+ return existsSync19(resolved) ? resolved : null;
21808
22492
  }
21809
22493
  function buildImageAttachment(rawPath, cwd) {
21810
22494
  const resolved = resolveImagePath(rawPath.trim(), cwd);
21811
22495
  if (!resolved) {
21812
22496
  return null;
21813
22497
  }
21814
- return { path: resolved, filename: basename3(resolved), mimeType: mimeFromExt(resolved) };
22498
+ return { path: resolved, filename: basename4(resolved), mimeType: mimeFromExt(resolved) };
21815
22499
  }
21816
22500
  function extractImagesFromInput(input, cwd) {
21817
22501
  const images = [];
@@ -21841,31 +22525,31 @@ function extractImagesFromInput(input, cwd) {
21841
22525
  }
21842
22526
 
21843
22527
  // ../core/src/generated/signals/flow.ts
21844
- import { readFileSync as readFileSync21, writeFileSync as writeFileSync18, mkdirSync as mkdirSync17, readdirSync as readdirSync13 } from "fs";
21845
- import { join as join21, resolve as resolve19 } from "path";
22528
+ import { readFileSync as readFileSync23, writeFileSync as writeFileSync19, mkdirSync as mkdirSync18, readdirSync as readdirSync14 } from "fs";
22529
+ import { join as join22, resolve as resolve20 } from "path";
21846
22530
  import { homedir as homedir12 } from "os";
21847
22531
  function getFlowsDir() {
21848
22532
  const override = process.env.AGON_HOME?.trim();
21849
- const home = override ? resolve19(override) : join21(homedir12(), ".agon");
21850
- return join21(home, "flows");
22533
+ const home = override ? resolve20(override) : join22(homedir12(), ".agon");
22534
+ return join22(home, "flows");
21851
22535
  }
21852
22536
  var FLOWS_DIR = getFlowsDir();
21853
22537
  var FRICTION_TAGS = ["slow", "wrong-mode", "engine-error", "unclear-output", "timeout", "context-lost", "other"];
21854
22538
  function ensureFlowsDir() {
21855
- mkdirSync17(getFlowsDir(), { recursive: true });
22539
+ mkdirSync18(getFlowsDir(), { recursive: true });
21856
22540
  }
21857
22541
  function logFlow(record2) {
21858
22542
  ensureFlowsDir();
21859
22543
  const filename = `flow-${record2.id}.json`;
21860
- const filepath = join21(getFlowsDir(), filename);
21861
- writeFileSync18(filepath, JSON.stringify(record2, null, 2));
22544
+ const filepath = join22(getFlowsDir(), filename);
22545
+ writeFileSync19(filepath, JSON.stringify(record2, null, 2));
21862
22546
  return filepath;
21863
22547
  }
21864
22548
  function readFlows(limit) {
21865
22549
  ensureFlowsDir();
21866
22550
  let files;
21867
22551
  try {
21868
- files = readdirSync13(getFlowsDir()).filter((f) => f.startsWith("flow-") && f.endsWith(".json")).sort().reverse();
22552
+ files = readdirSync14(getFlowsDir()).filter((f) => f.startsWith("flow-") && f.endsWith(".json")).sort().reverse();
21869
22553
  } catch (err) {
21870
22554
  console.warn(`[agon] failed to read flows directory: ${err instanceof Error ? err.message : String(err)}`);
21871
22555
  return [];
@@ -21874,7 +22558,7 @@ function readFlows(limit) {
21874
22558
  const records = [];
21875
22559
  for (const file2 of files) {
21876
22560
  try {
21877
- const data = JSON.parse(readFileSync21(join21(getFlowsDir(), file2), "utf-8"));
22561
+ const data = JSON.parse(readFileSync23(join22(getFlowsDir(), file2), "utf-8"));
21878
22562
  records.push(data);
21879
22563
  } catch (err) {
21880
22564
  console.warn(`[agon] skipping malformed flow record ${file2}: ${err instanceof Error ? err.message : String(err)}`);
@@ -21939,13 +22623,13 @@ async function companionDispatch(opts) {
21939
22623
  const startTime = Date.now();
21940
22624
  if (!isAcp && !isStreamJson) {
21941
22625
  const checkAvailable = () => {
21942
- return new Promise((resolve27) => {
22626
+ return new Promise((resolve28) => {
21943
22627
  const check2 = spawn2(opts.binaryPath, ["app-server", "--help"], {
21944
22628
  stdio: "pipe",
21945
22629
  timeout: 5e3
21946
22630
  });
21947
- check2.on("close", (code) => resolve27(code === 0));
21948
- check2.on("error", () => resolve27(false));
22631
+ check2.on("close", (code) => resolve28(code === 0));
22632
+ check2.on("error", () => resolve28(false));
21949
22633
  });
21950
22634
  };
21951
22635
  const available = await checkAvailable();
@@ -21963,10 +22647,10 @@ async function companionDispatch(opts) {
21963
22647
  detached: true
21964
22648
  });
21965
22649
  let procClosed = false;
21966
- const procClosedPromise = new Promise((resolve27) => {
22650
+ const procClosedPromise = new Promise((resolve28) => {
21967
22651
  proc.once("close", () => {
21968
22652
  procClosed = true;
21969
- resolve27();
22653
+ resolve28();
21970
22654
  });
21971
22655
  });
21972
22656
  let nextId = 1;
@@ -21994,7 +22678,7 @@ async function companionDispatch(opts) {
21994
22678
  return normalized;
21995
22679
  }
21996
22680
  function writeStdin(line) {
21997
- return new Promise((resolve27, reject) => {
22681
+ return new Promise((resolve28, reject) => {
21998
22682
  if (stdinError) {
21999
22683
  reject(stdinError);
22000
22684
  return;
@@ -22006,7 +22690,7 @@ async function companionDispatch(opts) {
22006
22690
  }
22007
22691
  stdin.write(line, (err) => {
22008
22692
  if (err) reject(setStdinError(err));
22009
- else resolve27();
22693
+ else resolve28();
22010
22694
  });
22011
22695
  });
22012
22696
  }
@@ -22141,12 +22825,12 @@ async function companionDispatch(opts) {
22141
22825
  function send(method, params) {
22142
22826
  const id = nextId++;
22143
22827
  const timeoutMs = method === "initialize" ? 8e3 : opts.timeout * 1e3;
22144
- return new Promise((resolve27, reject) => {
22828
+ return new Promise((resolve28, reject) => {
22145
22829
  const timer = setTimeout(() => {
22146
22830
  pending.delete(id);
22147
22831
  reject(new Error(`Timeout waiting for ${method}`));
22148
22832
  }, timeoutMs);
22149
- pending.set(id, { resolve: resolve27, reject, timer });
22833
+ pending.set(id, { resolve: resolve28, reject, timer });
22150
22834
  void writeStdin(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n").catch((err) => {
22151
22835
  pending.delete(id);
22152
22836
  clearTimeout(timer);
@@ -22158,7 +22842,7 @@ async function companionDispatch(opts) {
22158
22842
  fireWriteStdin(JSON.stringify({ jsonrpc: "2.0", method }) + "\n");
22159
22843
  }
22160
22844
  function sleep(ms) {
22161
- return new Promise((resolve27) => setTimeout(resolve27, ms));
22845
+ return new Promise((resolve28) => setTimeout(resolve28, ms));
22162
22846
  }
22163
22847
  function killProc(signal = "SIGTERM") {
22164
22848
  if (procClosed) return;
@@ -22186,10 +22870,10 @@ async function companionDispatch(opts) {
22186
22870
  }
22187
22871
  function waitForTurnComplete() {
22188
22872
  const deadline = Date.now() + opts.timeout * 1e3;
22189
- return new Promise((resolve27, reject) => {
22873
+ return new Promise((resolve28, reject) => {
22190
22874
  const check2 = () => {
22191
22875
  if (turnCompleted) {
22192
- resolve27();
22876
+ resolve28();
22193
22877
  return;
22194
22878
  }
22195
22879
  if (turnError) {
@@ -22303,19 +22987,19 @@ async function companionDispatch(opts) {
22303
22987
  }
22304
22988
 
22305
22989
  // ../core/src/generated/signals/models-registry.ts
22306
- import { readFileSync as readFileSync22, writeFileSync as writeFileSync19, mkdirSync as mkdirSync18, existsSync as existsSync18, statSync as statSync15 } from "fs";
22307
- import { join as join22 } from "path";
22990
+ import { readFileSync as readFileSync24, writeFileSync as writeFileSync20, mkdirSync as mkdirSync19, existsSync as existsSync20, statSync as statSync16 } from "fs";
22991
+ import { join as join23 } from "path";
22308
22992
  var CACHE_TTL_MS = 36e5;
22309
22993
  var MODELS_DEV_URL = "https://models.dev/api.json";
22310
22994
  async function fetchModelsRegistry() {
22311
22995
  const cacheDir = getCacheDir();
22312
- const cacheFile = join22(cacheDir, "models-dev.json");
22313
- if (existsSync18(cacheFile)) {
22996
+ const cacheFile = join23(cacheDir, "models-dev.json");
22997
+ if (existsSync20(cacheFile)) {
22314
22998
  try {
22315
- const stat = statSync15(cacheFile);
22999
+ const stat = statSync16(cacheFile);
22316
23000
  const age = Date.now() - stat.mtimeMs;
22317
23001
  if (age < CACHE_TTL_MS) {
22318
- return JSON.parse(readFileSync22(cacheFile, "utf-8"));
23002
+ return JSON.parse(readFileSync24(cacheFile, "utf-8"));
22319
23003
  }
22320
23004
  } catch (_e) {
22321
23005
  console.warn(`[agon] models-registry: cache read failed, refetching: ${_e instanceof Error ? _e.message : String(_e)}`);
@@ -22323,14 +23007,14 @@ async function fetchModelsRegistry() {
22323
23007
  }
22324
23008
  const response = await fetch(MODELS_DEV_URL);
22325
23009
  if (!response.ok) {
22326
- if (existsSync18(cacheFile)) {
22327
- return JSON.parse(readFileSync22(cacheFile, "utf-8"));
23010
+ if (existsSync20(cacheFile)) {
23011
+ return JSON.parse(readFileSync24(cacheFile, "utf-8"));
22328
23012
  }
22329
23013
  throw new Error(`Failed to fetch models registry: ${response.status}`);
22330
23014
  }
22331
23015
  const data = await response.json();
22332
- mkdirSync18(cacheDir, { recursive: true });
22333
- writeFileSync19(cacheFile, JSON.stringify(data));
23016
+ mkdirSync19(cacheDir, { recursive: true });
23017
+ writeFileSync20(cacheFile, JSON.stringify(data));
22334
23018
  return data;
22335
23019
  }
22336
23020
  function resolveModelFormat(providerNpm, model) {
@@ -22432,7 +23116,8 @@ function searchModels(entries, query) {
22432
23116
  });
22433
23117
  return scored.map((s) => s.entry);
22434
23118
  }
22435
- function normalizeBaseUrl(url2) {
23119
+ function normalizeBaseUrl(url2, format) {
23120
+ if (format === "anthropic") return url2;
22436
23121
  try {
22437
23122
  const parsed = new URL(url2);
22438
23123
  if (parsed.pathname.startsWith("/anthropic/") || parsed.pathname === "/anthropic") {
@@ -22445,29 +23130,29 @@ function normalizeBaseUrl(url2) {
22445
23130
  }
22446
23131
  }
22447
23132
  function modelEntryToEngineDef(entry) {
22448
- return { schemaVersion: 3, id: `${entry.providerId}-${entry.modelId}`.replace(/[^a-zA-Z0-9._-]/g, "-").toLowerCase(), displayName: `${entry.providerName} \u2014 ${entry.modelName}`, isLocal: false, tier: "user", timeout: 180, exec: { args: [] }, review: { args: [] }, api: { baseUrl: normalizeBaseUrl(entry.baseUrl), apiKeyEnv: entry.apiKeyEnv, model: entry.modelId, maxTokens: Math.min(entry.contextWindow ? Math.floor(entry.contextWindow / 4) : 4096, 16384), format: entry.format ?? "openai" } };
23133
+ return { schemaVersion: 3, id: `${entry.providerId}-${entry.modelId}`.replace(/[^a-zA-Z0-9._-]/g, "-").toLowerCase(), displayName: `${entry.providerName} \u2014 ${entry.modelName}`, isLocal: false, tier: "user", timeout: 180, exec: { args: [] }, review: { args: [] }, api: { baseUrl: normalizeBaseUrl(entry.baseUrl, entry.format ?? "openai"), apiKeyEnv: entry.apiKeyEnv, model: entry.modelId, maxTokens: Math.min(entry.contextWindow ? Math.floor(entry.contextWindow / 4) : 4096, 16384), format: entry.format ?? "openai" } };
22449
23134
  }
22450
23135
 
22451
23136
  // ../core/src/generated/signals/cli-models-registry.ts
22452
23137
  import { execSync as execSync4 } from "child_process";
22453
- import { readFileSync as readFileSync23, writeFileSync as writeFileSync20, mkdirSync as mkdirSync19, existsSync as existsSync19, statSync as statSync16 } from "fs";
22454
- import { join as join23 } from "path";
23138
+ import { readFileSync as readFileSync25, writeFileSync as writeFileSync21, mkdirSync as mkdirSync20, existsSync as existsSync21, statSync as statSync17 } from "fs";
23139
+ import { join as join24 } from "path";
22455
23140
  import { homedir as homedir13 } from "os";
22456
- import { createRequire as createRequire2 } from "module";
23141
+ import { createRequire as createRequire3 } from "module";
22457
23142
  var ENGINE_PROVIDER_MAP = { anthropic: { providerId: "anthropic", engineId: "claude", engineBinary: "claude", versionCmd: ["--version"], listCmd: ["__pty:/model"], effortLevels: ["low", "medium", "high", "xhigh", "max"] }, openai: { providerId: "openai", engineId: "codex", engineBinary: "codex", versionCmd: ["--version"], listCmd: ["__pty:/model"], effortLevels: ["low", "medium", "high", "xhigh"] }, google: { providerId: "google", engineId: "agy", engineBinary: "agy", versionCmd: ["--version"], listCmd: ["__pty:/model"] }, opencode: { providerId: "opencode", engineId: "opencode", engineBinary: "opencode", versionCmd: ["--version"], listCmd: ["models"] }, mistral: { providerId: "mistral", engineId: "mistral", engineBinary: "mistral", versionCmd: ["--version"] }, openrouter: { providerId: "openrouter", engineId: "openrouter", engineBinary: "openrouter", versionCmd: [] } };
22458
23143
  var ENGINE_DISPLAY_NAMES = { claude: "Claude", codex: "Codex", agy: "Antigravity", opencode: "OpenCode", mistral: "Mistral", openrouter: "OpenRouter" };
22459
23144
  var FALLBACK_MODELS = { anthropic: [{ id: "claude-sonnet-4-5-20250929", name: "Claude Sonnet 4.5", contextWindow: 2e5, toolCall: true, reasoning: true }, { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", contextWindow: 2e5, toolCall: true, reasoning: true }], openai: [{ id: "gpt-4o", name: "GPT-4o", contextWindow: 128e3, toolCall: true, reasoning: false }, { id: "o4-mini", name: "o4-mini", contextWindow: 2e5, toolCall: true, reasoning: true }], google: [{ id: "gemini-3.5-flash", name: "Gemini 3.5 Flash", contextWindow: 1048576, toolCall: true, reasoning: true }, { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro", contextWindow: 1048576, toolCall: true, reasoning: true }, { id: "gemini-3-flash-preview", name: "Gemini 3 Flash", contextWindow: 1048576, toolCall: true, reasoning: true }], mistral: [{ id: "mistral-large-latest", name: "Mistral Large", contextWindow: 128e3, toolCall: true, reasoning: false }, { id: "codestral-latest", name: "Codestral", contextWindow: 256e3, toolCall: true, reasoning: false }], openrouter: [{ id: "auto", name: "Auto (best for task)", toolCall: true, reasoning: false }], opencode: [{ id: "anthropic/claude-sonnet-4", name: "anthropic/claude-sonnet-4", toolCall: true, reasoning: false }, { id: "openai/gpt-5.3-codex", name: "openai/gpt-5.3-codex", toolCall: true, reasoning: false }] };
22460
23145
  var PROBE_TTL_MS = 864e5;
22461
23146
  function probedModelsCacheFile(engineId) {
22462
- return join23(getCacheDir(), `cli-models-${engineId.replace(/[^a-zA-Z0-9_-]/g, "-")}.json`);
23147
+ return join24(getCacheDir(), `cli-models-${engineId.replace(/[^a-zA-Z0-9_-]/g, "-")}.json`);
22463
23148
  }
22464
23149
  function readProbedCliModels(engineId, ttlMs) {
22465
23150
  try {
22466
23151
  const file2 = probedModelsCacheFile(engineId);
22467
- if (!existsSync19(file2)) return null;
22468
- const age = Date.now() - statSync16(file2).mtimeMs;
23152
+ if (!existsSync21(file2)) return null;
23153
+ const age = Date.now() - statSync17(file2).mtimeMs;
22469
23154
  if (age > (ttlMs ?? PROBE_TTL_MS)) return null;
22470
- const data = JSON.parse(readFileSync23(file2, "utf-8"));
23155
+ const data = JSON.parse(readFileSync25(file2, "utf-8"));
22471
23156
  const raw = Array.isArray(data?.models) ? data.models : [];
22472
23157
  const models = raw.map((m) => ({ id: String(m.id ?? ""), name: String(m.name ?? m.id ?? ""), current: !!m.current })).filter((m) => m.name);
22473
23158
  return models.length > 0 ? models : null;
@@ -22477,7 +23162,7 @@ function readProbedCliModels(engineId, ttlMs) {
22477
23162
  }
22478
23163
  function resolveModelProbeScript() {
22479
23164
  try {
22480
- const req = createRequire2(import.meta.url);
23165
+ const req = createRequire3(import.meta.url);
22481
23166
  const anchor = req.resolve("@kernlang/agon-engines/cli/claude.js");
22482
23167
  const candidates = [
22483
23168
  // Canonical: the package ships the probe at py/kern_engines/cli/ (see
@@ -22485,16 +23170,16 @@ function resolveModelProbeScript() {
22485
23170
  // to the package root, then into py/. This is the path that actually
22486
23171
  // exists — the dist/cli & root/cli guesses below never matched, so the
22487
23172
  // probe silently never ran and every engine fell back to its static list.
22488
- join23(anchor, "..", "..", "..", "py", "kern_engines", "cli", "model_probe.py"),
23173
+ join24(anchor, "..", "..", "..", "py", "kern_engines", "cli", "model_probe.py"),
22489
23174
  // dist/cli → root → py/kern_engines/cli
22490
- join23(anchor, "..", "..", "py", "kern_engines", "cli", "model_probe.py"),
23175
+ join24(anchor, "..", "..", "py", "kern_engines", "cli", "model_probe.py"),
22491
23176
  // (alt layout: cli/claude.js → root)
22492
- join23(anchor, "..", "..", "..", "cli", "model_probe.py"),
22493
- join23(anchor, "..", "..", "cli", "model_probe.py"),
22494
- join23(anchor, "..", "model_probe.py")
23177
+ join24(anchor, "..", "..", "..", "cli", "model_probe.py"),
23178
+ join24(anchor, "..", "..", "cli", "model_probe.py"),
23179
+ join24(anchor, "..", "model_probe.py")
22495
23180
  ];
22496
23181
  for (const c of candidates) {
22497
- if (existsSync19(c)) return c;
23182
+ if (existsSync21(c)) return c;
22498
23183
  }
22499
23184
  return null;
22500
23185
  } catch {
@@ -22564,8 +23249,8 @@ async function refreshProbedCliModels(engineId, binary, listCmd, pythonBin) {
22564
23249
  return false;
22565
23250
  }
22566
23251
  const dir = getCacheDir();
22567
- mkdirSync19(dir, { recursive: true });
22568
- writeFileSync20(probedModelsCacheFile(engineId), JSON.stringify({ ts: Date.now(), engineId, models }));
23252
+ mkdirSync20(dir, { recursive: true });
23253
+ writeFileSync21(probedModelsCacheFile(engineId), JSON.stringify({ ts: Date.now(), engineId, models }));
22569
23254
  return true;
22570
23255
  } catch (e) {
22571
23256
  dbg(`probe threw: ${e?.message ?? e}`);
@@ -22581,10 +23266,10 @@ function findBinary(binary) {
22581
23266
  } catch (e) {
22582
23267
  }
22583
23268
  const home = homedir13();
22584
- const searchPaths = [join23(home, ".local", "bin"), join23(home, ".npm-global", "bin"), "/usr/local/bin"];
23269
+ const searchPaths = [join24(home, ".local", "bin"), join24(home, ".npm-global", "bin"), "/usr/local/bin"];
22585
23270
  for (const dir of searchPaths) {
22586
- const fullPath = join23(dir, binary);
22587
- if (existsSync19(fullPath)) {
23271
+ const fullPath = join24(dir, binary);
23272
+ if (existsSync21(fullPath)) {
22588
23273
  return fullPath;
22589
23274
  }
22590
23275
  }
@@ -22601,6 +23286,29 @@ function getBinaryVersion(binary, versionCmd) {
22601
23286
  return null;
22602
23287
  }
22603
23288
  }
23289
+ var VERSION_CACHE = /* @__PURE__ */ new Map();
23290
+ async function getBinaryVersionAsync(engineId, binary, versionCmd) {
23291
+ if (!versionCmd.length) return null;
23292
+ const cached2 = VERSION_CACHE.get(engineId);
23293
+ if (cached2) return cached2;
23294
+ try {
23295
+ const result = await spawnWithTimeout({ command: binary, args: versionCmd, cwd: process.cwd(), timeout: 5e3 });
23296
+ if (result.timedOut || result.exitCode !== 0) return null;
23297
+ const v = (result.stdout ?? "").trim() || null;
23298
+ if (v) VERSION_CACHE.set(engineId, v);
23299
+ return v;
23300
+ } catch {
23301
+ return null;
23302
+ }
23303
+ }
23304
+ async function refreshCliGroupVersion(engineId) {
23305
+ const entry = Object.entries(ENGINE_PROVIDER_MAP).find(([, e]) => e.engineId === engineId);
23306
+ if (!entry) return null;
23307
+ const [, eng] = entry;
23308
+ const binaryPath = findBinary(eng.engineBinary);
23309
+ if (!binaryPath) return null;
23310
+ return getBinaryVersionAsync(eng.engineId, binaryPath, eng.versionCmd);
23311
+ }
22604
23312
  function buildCliModelGroups() {
22605
23313
  const groups = [];
22606
23314
  for (const [key, eng] of Object.entries(ENGINE_PROVIDER_MAP)) {
@@ -22626,7 +23334,7 @@ async function buildCliModelGroupsAsync() {
22626
23334
  for (const [key, eng] of Object.entries(ENGINE_PROVIDER_MAP)) {
22627
23335
  const binaryPath = findBinary(eng.engineBinary);
22628
23336
  const installed = binaryPath !== null;
22629
- const version2 = installed ? getBinaryVersion(eng.engineBinary, eng.versionCmd) : null;
23337
+ const version2 = installed ? await getBinaryVersionAsync(eng.engineId, binaryPath, eng.versionCmd) : null;
22630
23338
  const displayName = ENGINE_DISPLAY_NAMES[eng.engineId] ?? eng.engineId.charAt(0).toUpperCase() + eng.engineId.slice(1);
22631
23339
  const probed = readProbedCliModels(eng.engineId);
22632
23340
  const models = probed && probed.length > 0 ? probed.map((m) => Object.assign({}, { id: m.id, name: m.name, providerId: eng.providerId, providerName: displayName, engineId: eng.engineId, engineBinary: eng.engineBinary, toolCall: true, reasoning: true })) : (FALLBACK_MODELS[key] ?? []).map((m) => Object.assign({}, { id: m.id, name: m.name, providerId: eng.providerId, providerName: displayName, engineId: eng.engineId, engineBinary: eng.engineBinary, contextWindow: m.contextWindow, toolCall: m.toolCall, reasoning: m.reasoning }));
@@ -22639,7 +23347,7 @@ function buildCliGroupsImmediate() {
22639
23347
  for (const [key, eng] of Object.entries(ENGINE_PROVIDER_MAP)) {
22640
23348
  const binaryPath = findBinary(eng.engineBinary);
22641
23349
  const installed = binaryPath !== null;
22642
- const version2 = installed ? getBinaryVersion(eng.engineBinary, eng.versionCmd) : null;
23350
+ const version2 = installed ? VERSION_CACHE.get(eng.engineId) ?? null : null;
22643
23351
  const displayName = ENGINE_DISPLAY_NAMES[eng.engineId] ?? eng.engineId.charAt(0).toUpperCase() + eng.engineId.slice(1);
22644
23352
  const probed = readProbedCliModels(eng.engineId);
22645
23353
  const probeCapable = Array.isArray(eng.listCmd) && eng.listCmd.length > 0;
@@ -22658,7 +23366,7 @@ async function refreshCliGroup(engineId) {
22658
23366
  const probeCapable = Array.isArray(eng.listCmd) && eng.listCmd.length > 0;
22659
23367
  if (!installed || !probeCapable) return null;
22660
23368
  const displayName = ENGINE_DISPLAY_NAMES[eng.engineId] ?? eng.engineId.charAt(0).toUpperCase() + eng.engineId.slice(1);
22661
- const version2 = getBinaryVersion(eng.engineBinary, eng.versionCmd);
23369
+ const version2 = await getBinaryVersionAsync(eng.engineId, binaryPath, eng.versionCmd);
22662
23370
  try {
22663
23371
  await refreshProbedCliModels(eng.engineId, binaryPath, eng.listCmd);
22664
23372
  } catch {
@@ -22705,12 +23413,12 @@ function createCompanionSession(config2) {
22705
23413
  function sendRpc(method, params) {
22706
23414
  const id = nextRpcId++;
22707
23415
  const timeoutMs = method === "initialize" ? 8e3 : 9e4;
22708
- return new Promise((resolve27, reject) => {
23416
+ return new Promise((resolve28, reject) => {
22709
23417
  const timer = setTimeout(() => {
22710
23418
  pending.delete(id);
22711
23419
  reject(new Error(`Timeout waiting for ${method}`));
22712
23420
  }, timeoutMs);
22713
- pending.set(id, { resolve: resolve27, reject, timer });
23421
+ pending.set(id, { resolve: resolve28, reject, timer });
22714
23422
  proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
22715
23423
  });
22716
23424
  }
@@ -23035,12 +23743,12 @@ function createAcpSession(config2) {
23035
23743
  function sendRpc(method, params) {
23036
23744
  const id = nextRpcId++;
23037
23745
  const timeoutMs = method === "initialize" ? 8e3 : 9e4;
23038
- return new Promise((resolve27, reject) => {
23746
+ return new Promise((resolve28, reject) => {
23039
23747
  const timer = setTimeout(() => {
23040
23748
  pending.delete(id);
23041
23749
  reject(new Error(`ACP timeout: ${method}`));
23042
23750
  }, timeoutMs);
23043
- pending.set(id, { resolve: resolve27, reject, timer });
23751
+ pending.set(id, { resolve: resolve28, reject, timer });
23044
23752
  proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
23045
23753
  });
23046
23754
  }
@@ -23486,16 +24194,16 @@ function createStreamJsonSession(config2) {
23486
24194
  alive = false;
23487
24195
  proc = null;
23488
24196
  });
23489
- const startOk = await new Promise((resolve27) => {
23490
- const timeout = setTimeout(() => resolve27(true), 5e3);
24197
+ const startOk = await new Promise((resolve28) => {
24198
+ const timeout = setTimeout(() => resolve28(true), 5e3);
23491
24199
  rl.once("line", () => {
23492
24200
  clearTimeout(timeout);
23493
- resolve27(true);
24201
+ resolve28(true);
23494
24202
  });
23495
24203
  proc.once("close", (code) => {
23496
24204
  clearTimeout(timeout);
23497
24205
  console.error(`[cesar:claude] process died during start, code=${code}`);
23498
- resolve27(false);
24206
+ resolve28(false);
23499
24207
  });
23500
24208
  });
23501
24209
  if (!startOk || !proc) {
@@ -24656,33 +25364,33 @@ function createStreamBridge(dispatch, opts) {
24656
25364
  }
24657
25365
 
24658
25366
  // ../core/src/generated/forge/virtual-fs.ts
24659
- import { readFileSync as readFileSync24, existsSync as existsSync20, readdirSync as readdirSync14, statSync as statSync17 } from "fs";
24660
- import { join as join24, resolve as resolve20, relative as relative7, dirname as dirname10 } from "path";
24661
- import { createHash as createHash4 } from "crypto";
25367
+ import { readFileSync as readFileSync26, existsSync as existsSync22, readdirSync as readdirSync15, statSync as statSync18 } from "fs";
25368
+ import { join as join25, resolve as resolve21, relative as relative8, dirname as dirname11 } from "path";
25369
+ import { createHash as createHash5 } from "crypto";
24662
25370
  function createFileSnapshot(rootDir) {
24663
- const snapshotId = createHash4("sha256").update(rootDir + Date.now().toString()).digest("hex").slice(0, 12);
25371
+ const snapshotId = createHash5("sha256").update(rootDir + Date.now().toString()).digest("hex").slice(0, 12);
24664
25372
  return {
24665
25373
  snapshotId,
24666
- rootDir: resolve20(rootDir),
25374
+ rootDir: resolve21(rootDir),
24667
25375
  cache: /* @__PURE__ */ new Map()
24668
25376
  };
24669
25377
  }
24670
25378
  function snapshotRead(snap, absPath) {
24671
- const key = resolve20(absPath);
25379
+ const key = resolve21(absPath);
24672
25380
  if (snap.cache.has(key)) {
24673
25381
  return snap.cache.get(key) ?? null;
24674
25382
  }
24675
25383
  try {
24676
- if (!existsSync20(key)) {
25384
+ if (!existsSync22(key)) {
24677
25385
  snap.cache.set(key, null);
24678
25386
  return null;
24679
25387
  }
24680
- const st = statSync17(key);
25388
+ const st = statSync18(key);
24681
25389
  if (!st.isFile()) {
24682
25390
  snap.cache.set(key, null);
24683
25391
  return null;
24684
25392
  }
24685
- const content = readFileSync24(key, "utf-8");
25393
+ const content = readFileSync26(key, "utf-8");
24686
25394
  snap.cache.set(key, content);
24687
25395
  return content;
24688
25396
  } catch (e) {
@@ -24691,15 +25399,15 @@ function snapshotRead(snap, absPath) {
24691
25399
  }
24692
25400
  }
24693
25401
  function snapshotList(snap, absDir) {
24694
- const dir = resolve20(absDir);
25402
+ const dir = resolve21(absDir);
24695
25403
  try {
24696
- return readdirSync14(dir).filter((f) => {
25404
+ return readdirSync15(dir).filter((f) => {
24697
25405
  try {
24698
- return statSync17(join24(dir, f)).isFile();
25406
+ return statSync18(join25(dir, f)).isFile();
24699
25407
  } catch {
24700
25408
  return false;
24701
25409
  }
24702
- }).map((f) => join24(dir, f));
25410
+ }).map((f) => join25(dir, f));
24703
25411
  } catch {
24704
25412
  return [];
24705
25413
  }
@@ -24725,19 +25433,19 @@ var VirtualFS = class {
24725
25433
  notifyChange(absPath) {
24726
25434
  if (!this.onChange) return;
24727
25435
  try {
24728
- this.onChange(resolve20(absPath));
25436
+ this.onChange(resolve21(absPath));
24729
25437
  } catch {
24730
25438
  }
24731
25439
  }
24732
25440
  read(absPath) {
24733
- const key = resolve20(absPath);
25441
+ const key = resolve21(absPath);
24734
25442
  if (this.overlay.has(key)) {
24735
25443
  return this.overlay.get(key) ?? null;
24736
25444
  }
24737
25445
  return snapshotRead(this.snapshot, key);
24738
25446
  }
24739
25447
  write(absPath, content) {
24740
- const key = resolve20(absPath);
25448
+ const key = resolve21(absPath);
24741
25449
  const previous = this.overlay.has(key) ? this.overlay.get(key) ?? null : snapshotRead(this.snapshot, key);
24742
25450
  this.overlay.set(key, content);
24743
25451
  if (previous !== content) {
@@ -24745,7 +25453,7 @@ var VirtualFS = class {
24745
25453
  }
24746
25454
  }
24747
25455
  delete(absPath) {
24748
- const key = resolve20(absPath);
25456
+ const key = resolve21(absPath);
24749
25457
  const previous = this.overlay.has(key) ? this.overlay.get(key) ?? null : snapshotRead(this.snapshot, key);
24750
25458
  this.overlay.set(key, null);
24751
25459
  if (previous !== null) {
@@ -24753,19 +25461,19 @@ var VirtualFS = class {
24753
25461
  }
24754
25462
  }
24755
25463
  exists(absPath) {
24756
- const key = resolve20(absPath);
25464
+ const key = resolve21(absPath);
24757
25465
  if (this.overlay.has(key)) {
24758
25466
  return this.overlay.get(key) !== null;
24759
25467
  }
24760
25468
  return snapshotRead(this.snapshot, key) !== null;
24761
25469
  }
24762
25470
  list(absDir) {
24763
- const dir = resolve20(absDir);
25471
+ const dir = resolve21(absDir);
24764
25472
  const base = snapshotList(this.snapshot, dir);
24765
25473
  const overlayWritten = [];
24766
25474
  const overlayDeleted = /* @__PURE__ */ new Set();
24767
25475
  for (const [path, content] of this.overlay.entries()) {
24768
- if (dirname10(path) === dir) {
25476
+ if (dirname11(path) === dir) {
24769
25477
  if (content === null) {
24770
25478
  overlayDeleted.add(path);
24771
25479
  } else {
@@ -24822,9 +25530,9 @@ function applyEffectPackage(pkg, targetDir) {
24822
25530
  const import_fs = __require("fs");
24823
25531
  const modified = [];
24824
25532
  for (const effect of pkg.effects) {
24825
- const absPath = resolve20(targetDir, effect.kind === "rename" ? effect.from : effect.path);
25533
+ const absPath = resolve21(targetDir, effect.kind === "rename" ? effect.from : effect.path);
24826
25534
  if (effect.kind === "write") {
24827
- const dir = dirname10(absPath);
25535
+ const dir = dirname11(absPath);
24828
25536
  import_fs.mkdirSync(dir, { recursive: true });
24829
25537
  import_fs.writeFileSync(absPath, effect.content, "utf-8");
24830
25538
  modified.push(absPath);
@@ -24835,8 +25543,8 @@ function applyEffectPackage(pkg, targetDir) {
24835
25543
  }
24836
25544
  modified.push(absPath);
24837
25545
  } else if (effect.kind === "rename") {
24838
- const dest = resolve20(targetDir, effect.to);
24839
- import_fs.mkdirSync(dirname10(dest), { recursive: true });
25546
+ const dest = resolve21(targetDir, effect.to);
25547
+ import_fs.mkdirSync(dirname11(dest), { recursive: true });
24840
25548
  import_fs.renameSync(absPath, dest);
24841
25549
  modified.push(absPath);
24842
25550
  modified.push(dest);
@@ -24845,13 +25553,13 @@ function applyEffectPackage(pkg, targetDir) {
24845
25553
  return modified;
24846
25554
  }
24847
25555
  function relocateEffectPackage(pkg, fromDir, toDir) {
24848
- const fromRoot = resolve20(fromDir);
24849
- const toRoot = resolve20(toDir);
25556
+ const fromRoot = resolve21(fromDir);
25557
+ const toRoot = resolve21(toDir);
24850
25558
  const relocatePath = (path) => {
24851
- const abs = resolve20(path);
24852
- const rel = relative7(fromRoot, abs);
24853
- if (rel.startsWith("..") || resolve20(fromRoot, rel) !== abs) return abs;
24854
- return resolve20(toRoot, rel);
25559
+ const abs = resolve21(path);
25560
+ const rel = relative8(fromRoot, abs);
25561
+ if (rel.startsWith("..") || resolve21(fromRoot, rel) !== abs) return abs;
25562
+ return resolve21(toRoot, rel);
24855
25563
  };
24856
25564
  const effects = pkg.effects.map((effect) => {
24857
25565
  if (effect.kind === "write") {
@@ -24914,7 +25622,7 @@ function scoreEffectPackage(pkg, taskKeywords) {
24914
25622
 
24915
25623
  // ../core/src/generated/cesar/speculator.ts
24916
25624
  import { randomUUID as randomUUID4 } from "crypto";
24917
- import { resolve as resolve21, join as join25 } from "path";
25625
+ import { resolve as resolve22, join as join26 } from "path";
24918
25626
  var Speculator = class {
24919
25627
  runId;
24920
25628
  snapshot;
@@ -24923,7 +25631,7 @@ var Speculator = class {
24923
25631
  this.snapshot = null;
24924
25632
  }
24925
25633
  async run(opts) {
24926
- const cwd = resolve21(opts.cwd);
25634
+ const cwd = resolve22(opts.cwd);
24927
25635
  const isolate = opts.isolate !== false;
24928
25636
  const root = isolate ? repoRoot(cwd) : cwd;
24929
25637
  this.snapshot = createFileSnapshot(cwd);
@@ -24936,7 +25644,7 @@ var Speculator = class {
24936
25644
  if (isolate) {
24937
25645
  const baseSha = stashSnapshot(root);
24938
25646
  for (const member of opts.members) {
24939
- const wtPath = join25(root, `.agon/speculate-worktrees/${this.runId}/${member.engineId}`);
25647
+ const wtPath = join26(root, `.agon/speculate-worktrees/${this.runId}/${member.engineId}`);
24940
25648
  try {
24941
25649
  await worktreeCreate(root, wtPath, baseSha);
24942
25650
  worktreesByEngine[member.engineId] = wtPath;
@@ -25109,26 +25817,26 @@ ${sessionLines.join("\n")}`);
25109
25817
  }
25110
25818
 
25111
25819
  // ../core/src/generated/cesar/context-thread.ts
25112
- import { readFileSync as readFileSync25, writeFileSync as writeFileSync21, mkdirSync as mkdirSync20, renameSync as renameSync11, existsSync as existsSync21, readdirSync as readdirSync15, unlinkSync as unlinkSync9, statSync as statSync18, chmodSync as chmodSync2, openSync, fsyncSync, closeSync, appendFileSync as appendFileSync2 } from "fs";
25113
- import { join as join26, resolve as resolve22, basename as basename5 } from "path";
25114
- import { randomUUID as randomUUID5, createHash as createHash5 } from "crypto";
25820
+ import { readFileSync as readFileSync27, writeFileSync as writeFileSync22, mkdirSync as mkdirSync21, renameSync as renameSync11, existsSync as existsSync23, readdirSync as readdirSync16, unlinkSync as unlinkSync9, statSync as statSync19, chmodSync as chmodSync2, openSync, fsyncSync, closeSync, appendFileSync as appendFileSync2 } from "fs";
25821
+ import { join as join27, resolve as resolve23, basename as basename6 } from "path";
25822
+ import { randomUUID as randomUUID5, createHash as createHash6 } from "crypto";
25115
25823
  import { homedir as homedir14 } from "os";
25116
25824
  function threadsDir() {
25117
25825
  const override = process.env.AGON_HOME?.trim();
25118
- const home = override ? resolve22(override) : join26(homedir14(), ".agon");
25119
- return join26(home, "threads");
25826
+ const home = override ? resolve23(override) : join27(homedir14(), ".agon");
25827
+ return join27(home, "threads");
25120
25828
  }
25121
25829
  function activePointerPath() {
25122
- return join26(threadsDir(), "active.json");
25830
+ return join27(threadsDir(), "active.json");
25123
25831
  }
25124
25832
  function projectHash16(projectPath) {
25125
- return createHash5("sha256").update(projectPath).digest("hex").slice(0, 16);
25833
+ return createHash6("sha256").update(projectPath).digest("hex").slice(0, 16);
25126
25834
  }
25127
25835
  function projectSha8(projectPath) {
25128
25836
  return projectHash16(projectPath);
25129
25837
  }
25130
25838
  function threadDirFor(projectPath) {
25131
- return join26(threadsDir(), projectHash16(projectPath));
25839
+ return join27(threadsDir(), projectHash16(projectPath));
25132
25840
  }
25133
25841
  var THREAD_ID_RE = /^(thread_\d{10,16}_[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
25134
25842
  function threadJournalPath(projectPath, threadId) {
@@ -25139,9 +25847,9 @@ function threadFilePath(projectPath, threadId) {
25139
25847
  throw new Error(`Invalid threadId: ${threadId}`);
25140
25848
  }
25141
25849
  const dir = threadDirFor(projectPath);
25142
- const full = resolve22(dir, `${threadId}.json`);
25143
- const resolvedDir = resolve22(dir);
25144
- const nativeSep = join26("a", "b")[1];
25850
+ const full = resolve23(dir, `${threadId}.json`);
25851
+ const resolvedDir = resolve23(dir);
25852
+ const nativeSep = join27("a", "b")[1];
25145
25853
  const isContained = full === resolvedDir || full.startsWith(resolvedDir + "/") || full.startsWith(resolvedDir + nativeSep);
25146
25854
  if (!isContained) {
25147
25855
  throw new Error(`Invalid thread path (traversal attempt): ${threadId}`);
@@ -25150,7 +25858,7 @@ function threadFilePath(projectPath, threadId) {
25150
25858
  }
25151
25859
  function ensureThreadDir(projectPath) {
25152
25860
  ensureAgonHome();
25153
- mkdirSync20(threadDirFor(projectPath), { recursive: true });
25861
+ mkdirSync21(threadDirFor(projectPath), { recursive: true });
25154
25862
  }
25155
25863
  var LOCK_MAX_RETRIES = 8;
25156
25864
  var LOCK_BASE_DELAY_MS = 20;
@@ -25161,7 +25869,7 @@ async function acquireLock(lockPath) {
25161
25869
  for (let attempt = 0; attempt < LOCK_MAX_RETRIES; attempt++) {
25162
25870
  try {
25163
25871
  const fd = openSync(lockPath, "wx", 384);
25164
- writeFileSync21(fd, String(process.pid));
25872
+ writeFileSync22(fd, String(process.pid));
25165
25873
  closeSync(fd);
25166
25874
  return attempt;
25167
25875
  } catch (err) {
@@ -25210,7 +25918,7 @@ var SECRET_PATTERNS = [
25210
25918
  var SECRET_PATH_BLOCKLIST = [".env", ".env.local", ".env.production", ".env.staging", ".env.development", "credentials.json", "secrets.json", "auth.json", ".ssh/id_rsa", ".ssh/id_ed25519", ".ssh/id_ecdsa", ".aws/credentials", ".docker/config.json", ".netrc", ".pgpass", ".my.cnf"];
25211
25919
  function isSecretPath(path) {
25212
25920
  const lower = path.toLowerCase();
25213
- const name = basename5(lower);
25921
+ const name = basename6(lower);
25214
25922
  for (const needle of SECRET_PATH_BLOCKLIST) {
25215
25923
  if (name === needle || lower.endsWith("/" + needle) || lower.endsWith("\\" + needle)) {
25216
25924
  return true;
@@ -25334,14 +26042,14 @@ var ContextThread = class {
25334
26042
  const now = Date.now();
25335
26043
  if (config2.threadId) {
25336
26044
  const candidatePath = threadFilePath(this.projectPath, config2.threadId);
25337
- if (existsSync21(candidatePath)) {
26045
+ if (existsSync23(candidatePath)) {
25338
26046
  try {
25339
- const stat = statSync18(candidatePath);
26047
+ const stat = statSync19(candidatePath);
25340
26048
  if (stat.size > MAX_THREAD_FILE_BYTES) {
25341
26049
  console.warn(`[agon] context-thread: ${candidatePath} is ${stat.size} bytes (> ${MAX_THREAD_FILE_BYTES}), refusing to load. Run /thread compact or /thread fork.`);
25342
26050
  throw new Error("thread file too large");
25343
26051
  }
25344
- const raw = readFileSync25(candidatePath, "utf-8");
26052
+ const raw = readFileSync27(candidatePath, "utf-8");
25345
26053
  const snap = JSON.parse(raw);
25346
26054
  if (snap && typeof snap === "object" && Array.isArray(snap.messages)) {
25347
26055
  const filteredMessages = (snap.messages ?? []).filter((m) => m && m.role !== "system");
@@ -25359,9 +26067,9 @@ var ContextThread = class {
25359
26067
  this.fileTouches = snap.fileTouches ?? {};
25360
26068
  this.hydrated = true;
25361
26069
  const jPathOnLoad = threadFilePath(this.projectPath, this.threadId).replace(/\.json$/, ".journal.jsonl");
25362
- if (existsSync21(jPathOnLoad)) {
26070
+ if (existsSync23(jPathOnLoad)) {
25363
26071
  try {
25364
- const journalLines = readFileSync25(jPathOnLoad, "utf-8").split("\n").filter(Boolean);
26072
+ const journalLines = readFileSync27(jPathOnLoad, "utf-8").split("\n").filter(Boolean);
25365
26073
  const knownOnLoad = new Set(this.messages.map((m) => m.id));
25366
26074
  let merged = false;
25367
26075
  for (const line of journalLines) {
@@ -25631,8 +26339,8 @@ ${msg.content}` };
25631
26339
  let bytes = 0;
25632
26340
  try {
25633
26341
  const path = threadFilePath(this.projectPath, this.threadId);
25634
- if (existsSync21(path)) {
25635
- bytes = readFileSync25(path, "utf-8").length;
26342
+ if (existsSync23(path)) {
26343
+ bytes = readFileSync27(path, "utf-8").length;
25636
26344
  }
25637
26345
  } catch {
25638
26346
  }
@@ -25665,7 +26373,7 @@ ${msg.content}` };
25665
26373
  let fd = -1;
25666
26374
  try {
25667
26375
  fd = openSync(tmpPath, "w", 384);
25668
- writeFileSync21(fd, body, "utf-8");
26376
+ writeFileSync22(fd, body, "utf-8");
25669
26377
  fsyncSync(fd);
25670
26378
  } finally {
25671
26379
  if (fd >= 0) try {
@@ -25681,7 +26389,7 @@ ${msg.content}` };
25681
26389
  this.dirty = false;
25682
26390
  this.hydrated = true;
25683
26391
  const jPath = threadJournalPath(this.projectPath, this.threadId);
25684
- if (existsSync21(jPath)) unlinkSync9(jPath);
26392
+ if (existsSync23(jPath)) unlinkSync9(jPath);
25685
26393
  this.journaledIds.clear();
25686
26394
  } catch {
25687
26395
  }
@@ -25713,9 +26421,9 @@ ${msg.content}` };
25713
26421
  }
25714
26422
  try {
25715
26423
  const jPath = threadJournalPath(this.projectPath, this.threadId);
25716
- if (existsSync21(jPath)) {
26424
+ if (existsSync23(jPath)) {
25717
26425
  try {
25718
- const journalLines = readFileSync25(jPath, "utf-8").split("\n").filter(Boolean);
26426
+ const journalLines = readFileSync27(jPath, "utf-8").split("\n").filter(Boolean);
25719
26427
  const known = new Set(this.messages.map((m) => m.id));
25720
26428
  for (const line of journalLines) {
25721
26429
  try {
@@ -25734,11 +26442,11 @@ ${msg.content}` };
25734
26442
  console.warn(`[agon] context-thread: journal merge failed (will overwrite): ${err instanceof Error ? err.message : String(err)}`);
25735
26443
  }
25736
26444
  }
25737
- if (existsSync21(target)) {
26445
+ if (existsSync23(target)) {
25738
26446
  try {
25739
- const stat = statSync18(target);
26447
+ const stat = statSync19(target);
25740
26448
  if (stat.size <= MAX_THREAD_FILE_BYTES) {
25741
- const raw = readFileSync25(target, "utf-8");
26449
+ const raw = readFileSync27(target, "utf-8");
25742
26450
  const onDisk = JSON.parse(raw);
25743
26451
  if (onDisk && Array.isArray(onDisk.messages)) {
25744
26452
  const known = new Set(this.messages.map((m) => m.id));
@@ -25777,7 +26485,7 @@ ${msg.content}` };
25777
26485
  let fd = -1;
25778
26486
  try {
25779
26487
  fd = openSync(tmpPath, "w", 384);
25780
- writeFileSync21(fd, body, "utf-8");
26488
+ writeFileSync22(fd, body, "utf-8");
25781
26489
  fsyncSync(fd);
25782
26490
  } finally {
25783
26491
  if (fd >= 0) {
@@ -25796,7 +26504,7 @@ ${msg.content}` };
25796
26504
  this.dirty = false;
25797
26505
  this.hydrated = true;
25798
26506
  try {
25799
- if (existsSync21(jPath)) unlinkSync9(jPath);
26507
+ if (existsSync23(jPath)) unlinkSync9(jPath);
25800
26508
  this.journaledIds.clear();
25801
26509
  } catch {
25802
26510
  }
@@ -25817,8 +26525,8 @@ ${msg.content}` };
25817
26525
  function loadActivePointer() {
25818
26526
  try {
25819
26527
  const path = activePointerPath();
25820
- if (existsSync21(path)) {
25821
- const raw = readFileSync25(path, "utf-8");
26528
+ if (existsSync23(path)) {
26529
+ const raw = readFileSync27(path, "utf-8");
25822
26530
  const parsed = JSON.parse(raw);
25823
26531
  if (parsed && typeof parsed === "object" && parsed.byProject) {
25824
26532
  return parsed;
@@ -25832,9 +26540,9 @@ function loadActivePointer() {
25832
26540
  function saveActivePointer(pointer) {
25833
26541
  ensureAgonHome();
25834
26542
  const path = activePointerPath();
25835
- mkdirSync20(threadsDir(), { recursive: true });
26543
+ mkdirSync21(threadsDir(), { recursive: true });
25836
26544
  const tmpPath = path + ".tmp";
25837
- writeFileSync21(tmpPath, JSON.stringify(pointer, null, 2) + "\n", "utf-8");
26545
+ writeFileSync22(tmpPath, JSON.stringify(pointer, null, 2) + "\n", "utf-8");
25838
26546
  renameSync11(tmpPath, path);
25839
26547
  }
25840
26548
  var _WeakRefCtor = globalThis.WeakRef;
@@ -25890,9 +26598,9 @@ async function forkActiveThread(projectPath, systemPrompt) {
25890
26598
  }
25891
26599
  function listThreadsForProject(projectPath) {
25892
26600
  const dir = threadDirFor(projectPath);
25893
- if (!existsSync21(dir)) return [];
26601
+ if (!existsSync23(dir)) return [];
25894
26602
  try {
25895
- return readdirSync15(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5));
26603
+ return readdirSync16(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5));
25896
26604
  } catch (err) {
25897
26605
  console.warn(`[agon] context-thread: failed to list threads: ${err instanceof Error ? err.message : String(err)}`);
25898
26606
  return [];
@@ -26432,7 +27140,7 @@ var AgentSession = class {
26432
27140
  };
26433
27141
 
26434
27142
  // ../core/src/generated/cesar/agent-team.ts
26435
- import { join as join27 } from "path";
27143
+ import { join as join28 } from "path";
26436
27144
  import { randomBytes as randomBytes2 } from "crypto";
26437
27145
  function makeAgentTeamError(message, cause) {
26438
27146
  const err = new Error(`AgentTeam: ${message}`);
@@ -26515,7 +27223,7 @@ var AgentTeam = class {
26515
27223
  if (!this.config.isolate) {
26516
27224
  return { m, wt: null };
26517
27225
  }
26518
- const wt = join27(this.config.cwd, ".agon", "agent-worktrees", this.runId, m.engineId);
27226
+ const wt = join28(this.config.cwd, ".agon", "agent-worktrees", this.runId, m.engineId);
26519
27227
  worktreeCreate(root, wt, this.baseSha);
26520
27228
  return { m, wt };
26521
27229
  });
@@ -27341,10 +28049,10 @@ function hooksOutput(results) {
27341
28049
  }
27342
28050
 
27343
28051
  // ../core/src/generated/blocks/skill-loader.ts
27344
- import { readFileSync as readFileSync26, readdirSync as readdirSync16, existsSync as existsSync22 } from "fs";
27345
- import { join as join28, dirname as dirname11, resolve as resolve23 } from "path";
28052
+ import { readFileSync as readFileSync28, readdirSync as readdirSync17, existsSync as existsSync24 } from "fs";
28053
+ import { join as join29, dirname as dirname12, resolve as resolve24 } from "path";
27346
28054
  import { homedir as homedir15 } from "os";
27347
- import { fileURLToPath as fileURLToPath2 } from "url";
28055
+ import { fileURLToPath as fileURLToPath3 } from "url";
27348
28056
  function parseFrontmatter(content) {
27349
28057
  const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);
27350
28058
  if (!match) {
@@ -27363,7 +28071,7 @@ function parseFrontmatter(content) {
27363
28071
  }
27364
28072
  function loadSkillFile(filePath) {
27365
28073
  try {
27366
- const content = readFileSync26(filePath, "utf-8");
28074
+ const content = readFileSync28(filePath, "utf-8");
27367
28075
  const { meta: meta3, body } = parseFrontmatter(content);
27368
28076
  if (!meta3.name || !meta3.trigger) return null;
27369
28077
  return {
@@ -27381,11 +28089,11 @@ function loadSkillFile(filePath) {
27381
28089
  }
27382
28090
  function loadSkillsFromDir(dir, source) {
27383
28091
  const skills = [];
27384
- if (!existsSync22(dir)) return skills;
28092
+ if (!existsSync24(dir)) return skills;
27385
28093
  try {
27386
- const files = readdirSync16(dir).filter((f) => f.endsWith(".md"));
28094
+ const files = readdirSync17(dir).filter((f) => f.endsWith(".md"));
27387
28095
  for (const file2 of files) {
27388
- const skill = loadSkillFile(join28(dir, file2));
28096
+ const skill = loadSkillFile(join29(dir, file2));
27389
28097
  if (skill) {
27390
28098
  skill.source = source;
27391
28099
  skills.push(skill);
@@ -27399,12 +28107,12 @@ function loadSkillsFromDir(dir, source) {
27399
28107
  function loadSkills(cwd) {
27400
28108
  const skills = [];
27401
28109
  const override = process.env.AGON_HOME?.trim();
27402
- const home = override ? resolve23(override) : join28(homedir15(), ".agon");
27403
- const builtinDir = join28(dirname11(fileURLToPath2(import.meta.url)), "../../skills");
28110
+ const home = override ? resolve24(override) : join29(homedir15(), ".agon");
28111
+ const builtinDir = join29(dirname12(fileURLToPath3(import.meta.url)), "../../skills");
27404
28112
  skills.push(...loadSkillsFromDir(builtinDir, "builtin"));
27405
- skills.push(...loadSkillsFromDir(join28(home, "skills"), "global"));
28113
+ skills.push(...loadSkillsFromDir(join29(home, "skills"), "global"));
27406
28114
  if (cwd) {
27407
- skills.push(...loadSkillsFromDir(join28(cwd, ".agon", "skills"), "project"));
28115
+ skills.push(...loadSkillsFromDir(join29(cwd, ".agon", "skills"), "project"));
27408
28116
  }
27409
28117
  const seen = /* @__PURE__ */ new Map();
27410
28118
  for (const skill of skills) {
@@ -27421,17 +28129,17 @@ function renderSkillPrompt(skill, input) {
27421
28129
  }
27422
28130
 
27423
28131
  // ../core/src/generated/blocks/engine-memory.ts
27424
- import { readFileSync as readFileSync27, writeFileSync as writeFileSync22, mkdirSync as mkdirSync21, renameSync as renameSync12 } from "fs";
27425
- import { join as join29, resolve as resolve24 } from "path";
28132
+ import { readFileSync as readFileSync29, writeFileSync as writeFileSync23, mkdirSync as mkdirSync22, renameSync as renameSync12 } from "fs";
28133
+ import { join as join30, resolve as resolve25 } from "path";
27426
28134
  import { homedir as homedir16 } from "os";
27427
28135
  function memoryPath() {
27428
28136
  const override = process.env.AGON_HOME?.trim();
27429
- const home = override ? resolve24(override) : join29(homedir16(), ".agon");
27430
- return join29(home, "engine-memory.json");
28137
+ const home = override ? resolve25(override) : join30(homedir16(), ".agon");
28138
+ return join30(home, "engine-memory.json");
27431
28139
  }
27432
28140
  function loadEngineMemory() {
27433
28141
  try {
27434
- return JSON.parse(readFileSync27(memoryPath(), "utf-8"));
28142
+ return JSON.parse(readFileSync29(memoryPath(), "utf-8"));
27435
28143
  } catch (err) {
27436
28144
  if (err.code !== "ENOENT") {
27437
28145
  console.warn(`[agon] failed to load engine memory: ${err instanceof Error ? err.message : String(err)}`);
@@ -27441,12 +28149,12 @@ function loadEngineMemory() {
27441
28149
  }
27442
28150
  function saveEngineMemory(record2) {
27443
28151
  const override = process.env.AGON_HOME?.trim();
27444
- const home = override ? resolve24(override) : join29(homedir16(), ".agon");
27445
- mkdirSync21(home, { recursive: true });
28152
+ const home = override ? resolve25(override) : join30(homedir16(), ".agon");
28153
+ mkdirSync22(home, { recursive: true });
27446
28154
  record2.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
27447
28155
  const path = memoryPath();
27448
28156
  const tmpPath = path + ".tmp";
27449
- writeFileSync22(tmpPath, JSON.stringify(record2, null, 2) + "\n");
28157
+ writeFileSync23(tmpPath, JSON.stringify(record2, null, 2) + "\n");
27450
28158
  renameSync12(tmpPath, path);
27451
28159
  }
27452
28160
  function ensureProfile(record2, engineId) {
@@ -27674,13 +28382,13 @@ function assignForgeRoles(engineIds, taskClass) {
27674
28382
  }
27675
28383
 
27676
28384
  // ../core/src/generated/blocks/sidechain-logger.ts
27677
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync22 } from "fs";
27678
- import { join as join30 } from "path";
28385
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync23 } from "fs";
28386
+ import { join as join31 } from "path";
27679
28387
  function createSidechainLogger(opts) {
27680
28388
  const suffix = opts.parentId ? `_sidechain_${opts.parentId}` : "";
27681
28389
  const filename = `${opts.sessionType}_${opts.sessionId}${suffix}.jsonl`;
27682
- const logPath = join30(opts.outputDir, filename);
27683
- mkdirSync22(opts.outputDir, { recursive: true });
28390
+ const logPath = join31(opts.outputDir, filename);
28391
+ mkdirSync23(opts.outputDir, { recursive: true });
27684
28392
  function log(type, engineId, data) {
27685
28393
  const event = {
27686
28394
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -27709,12 +28417,12 @@ function createSidechainLogger(opts) {
27709
28417
  }
27710
28418
 
27711
28419
  // ../core/src/generated/blocks/provenance.ts
27712
- import { readFileSync as readFileSync28, writeFileSync as writeFileSync23, mkdirSync as mkdirSync23 } from "fs";
27713
- import { join as join31, resolve as resolve25 } from "path";
27714
- import { createHash as createHash6 } from "crypto";
28420
+ import { readFileSync as readFileSync30, writeFileSync as writeFileSync24, mkdirSync as mkdirSync24 } from "fs";
28421
+ import { join as join32, resolve as resolve26 } from "path";
28422
+ import { createHash as createHash7 } from "crypto";
27715
28423
  function sha256OfFile(path) {
27716
28424
  try {
27717
- return "sha256:" + createHash6("sha256").update(readFileSync28(path)).digest("hex");
28425
+ return "sha256:" + createHash7("sha256").update(readFileSync30(path)).digest("hex");
27718
28426
  } catch (e) {
27719
28427
  console.warn(`[agon] provenance: could not hash ${path}: ${e instanceof Error ? e.message : String(e)}`);
27720
28428
  return "unavailable";
@@ -27874,18 +28582,18 @@ function renderProvenanceMarkdown(led) {
27874
28582
  function writeProvenanceReport(manifest, manifestPath, outDir, format) {
27875
28583
  const fmt = format ?? "md";
27876
28584
  const ledger = buildForgeProvenance(manifest, manifestPath);
27877
- mkdirSync23(outDir, { recursive: true });
28585
+ mkdirSync24(outDir, { recursive: true });
27878
28586
  if (fmt === "md" || fmt === "both") {
27879
- const mdPath = resolve25(join31(outDir, "provenance.md"));
27880
- writeFileSync23(mdPath, renderProvenanceMarkdown(ledger), "utf-8");
28587
+ const mdPath = resolve26(join32(outDir, "provenance.md"));
28588
+ writeFileSync24(mdPath, renderProvenanceMarkdown(ledger), "utf-8");
27881
28589
  if (fmt === "md") return mdPath;
27882
28590
  }
27883
28591
  if (fmt === "json" || fmt === "both") {
27884
- const jsonPath = resolve25(join31(outDir, "provenance.json"));
27885
- writeFileSync23(jsonPath, renderProvenanceJson(ledger), "utf-8");
28592
+ const jsonPath = resolve26(join32(outDir, "provenance.json"));
28593
+ writeFileSync24(jsonPath, renderProvenanceJson(ledger), "utf-8");
27886
28594
  if (fmt === "json") return jsonPath;
27887
28595
  }
27888
- return resolve25(join31(outDir, "provenance.md"));
28596
+ return resolve26(join32(outDir, "provenance.md"));
27889
28597
  }
27890
28598
 
27891
28599
  // ../core/src/generated/models/extension-manifest.ts
@@ -27991,8 +28699,8 @@ var CommandRegistry = class {
27991
28699
  };
27992
28700
 
27993
28701
  // ../core/src/generated/blocks/extension-loader.ts
27994
- import { join as join32, resolve as resolve26 } from "path";
27995
- import { readdirSync as readdirSync17, readFileSync as readFileSync29, existsSync as existsSync23 } from "fs";
28702
+ import { join as join33, resolve as resolve27 } from "path";
28703
+ import { readdirSync as readdirSync18, readFileSync as readFileSync31, existsSync as existsSync25 } from "fs";
27996
28704
  import { homedir as homedir17 } from "os";
27997
28705
 
27998
28706
  // ../core/src/generated/signals/event-bus.ts
@@ -28083,31 +28791,31 @@ function bridgeShellHooks(bus, hooks) {
28083
28791
  function discoverExtensionDirs(cwd) {
28084
28792
  const results = [];
28085
28793
  const override = process.env.AGON_HOME?.trim();
28086
- const home = override ? resolve26(override) : join32(homedir17(), ".agon");
28087
- const userDir = join32(home, "extensions");
28088
- if (existsSync23(userDir)) {
28794
+ const home = override ? resolve27(override) : join33(homedir17(), ".agon");
28795
+ const userDir = join33(home, "extensions");
28796
+ if (existsSync25(userDir)) {
28089
28797
  try {
28090
- const entries = readdirSync17(userDir, { withFileTypes: true });
28798
+ const entries = readdirSync18(userDir, { withFileTypes: true });
28091
28799
  for (const entry of entries) {
28092
28800
  if (entry.isDirectory()) {
28093
- const manifestPath = join32(userDir, entry.name, "manifest.json");
28094
- if (existsSync23(manifestPath)) {
28095
- results.push({ dir: join32(userDir, entry.name), source: "user" });
28801
+ const manifestPath = join33(userDir, entry.name, "manifest.json");
28802
+ if (existsSync25(manifestPath)) {
28803
+ results.push({ dir: join33(userDir, entry.name), source: "user" });
28096
28804
  }
28097
28805
  }
28098
28806
  }
28099
28807
  } catch {
28100
28808
  }
28101
28809
  }
28102
- const repoDir = join32(cwd, ".agon", "extensions");
28103
- if (existsSync23(repoDir)) {
28810
+ const repoDir = join33(cwd, ".agon", "extensions");
28811
+ if (existsSync25(repoDir)) {
28104
28812
  try {
28105
- const entries = readdirSync17(repoDir, { withFileTypes: true });
28813
+ const entries = readdirSync18(repoDir, { withFileTypes: true });
28106
28814
  for (const entry of entries) {
28107
28815
  if (entry.isDirectory()) {
28108
- const manifestPath = join32(repoDir, entry.name, "manifest.json");
28109
- if (existsSync23(manifestPath)) {
28110
- results.push({ dir: join32(repoDir, entry.name), source: "repo" });
28816
+ const manifestPath = join33(repoDir, entry.name, "manifest.json");
28817
+ if (existsSync25(manifestPath)) {
28818
+ results.push({ dir: join33(repoDir, entry.name), source: "repo" });
28111
28819
  }
28112
28820
  }
28113
28821
  }
@@ -28117,9 +28825,9 @@ function discoverExtensionDirs(cwd) {
28117
28825
  return results;
28118
28826
  }
28119
28827
  function loadExtensionManifest(dir, source) {
28120
- const manifestPath = join32(dir, "manifest.json");
28828
+ const manifestPath = join33(dir, "manifest.json");
28121
28829
  try {
28122
- const raw = JSON.parse(readFileSync29(manifestPath, "utf-8"));
28830
+ const raw = JSON.parse(readFileSync31(manifestPath, "utf-8"));
28123
28831
  const result = validateManifest(raw, manifestPath);
28124
28832
  if (!result.ok || !result.data) {
28125
28833
  console.warn(`[agon] skipping extension ${dir}: ${result.error}`);
@@ -28151,7 +28859,7 @@ async function registerExtensionCommands(ext, commandRegistry) {
28151
28859
  if (!commands || commands.length === 0) return registered;
28152
28860
  for (const cmd of commands) {
28153
28861
  try {
28154
- const handlerPath = resolve26(ext.dir, cmd.handler);
28862
+ const handlerPath = resolve27(ext.dir, cmd.handler);
28155
28863
  const mod = await import(handlerPath);
28156
28864
  if (typeof mod.execute !== "function") {
28157
28865
  console.warn(`[agon] extension '${ext.manifest.id}' command '${cmd.name}': handler missing execute() export`);
@@ -28187,8 +28895,8 @@ function registerExtensionEngines(ext, engineRegistry) {
28187
28895
  }
28188
28896
  for (const enginePath of enginePaths) {
28189
28897
  try {
28190
- const fullPath = resolve26(ext.dir, enginePath);
28191
- const raw = JSON.parse(readFileSync29(fullPath, "utf-8"));
28898
+ const fullPath = resolve27(ext.dir, enginePath);
28899
+ const raw = JSON.parse(readFileSync31(fullPath, "utf-8"));
28192
28900
  if (raw.id) {
28193
28901
  engineRegistry.register(raw);
28194
28902
  registered.push(raw.id);
@@ -28209,12 +28917,12 @@ function registerExtensionSkills(ext) {
28209
28917
  trigger: sc.trigger.startsWith("/") ? sc.trigger : "/" + sc.trigger,
28210
28918
  description: sc.description || "",
28211
28919
  prompt: sc.prompt || "",
28212
- source: resolve26(ext.dir, "manifest.json"),
28920
+ source: resolve27(ext.dir, "manifest.json"),
28213
28921
  tools: sc.tools
28214
28922
  };
28215
28923
  if (sc.handler) {
28216
28924
  try {
28217
- const handlerPath = resolve26(ext.dir, sc.handler);
28925
+ const handlerPath = resolve27(ext.dir, sc.handler);
28218
28926
  skill._handlerPath = handlerPath;
28219
28927
  skill.handler = async (args, ctx) => {
28220
28928
  const mod = await import(handlerPath);
@@ -28238,7 +28946,7 @@ async function registerExtensionHooks(ext, eventBus) {
28238
28946
  if (!hookContribs || hookContribs.length === 0) return registered;
28239
28947
  for (const hook of hookContribs) {
28240
28948
  try {
28241
- const handlerPath = resolve26(ext.dir, hook.handler);
28949
+ const handlerPath = resolve27(ext.dir, hook.handler);
28242
28950
  const mod = await import(handlerPath);
28243
28951
  if (typeof mod.handler !== "function" && typeof mod.default !== "function") {
28244
28952
  console.warn(`[agon] extension '${ext.manifest.id}' hook '${hook.event}': handler missing handler() or default() export`);
@@ -28345,12 +29053,14 @@ function registerBuiltinCommands(registry2) {
28345
29053
  { name: "chats", desc: "[id|resume <id>] \u2014 chat history or resume session", category: "info" },
28346
29054
  { name: "jobs", desc: " \u2014 list running/completed jobs", category: "info" },
28347
29055
  { name: "focus", desc: "<id> \u2014 switch to background job output", category: "info" },
29056
+ { name: "update", desc: "[version] [--check] \u2014 self-update from npm (also runs from the in-app banner)", category: "info" },
28348
29057
  // Session
28349
29058
  { name: "mcp", desc: "connect <name|url> | disconnect | list \u2014 manage session MCP servers", category: "session" },
28350
29059
  { name: "explore", desc: " \u2014 toggle exploration mode (read-only)", category: "session" },
28351
29060
  { name: "nero", desc: " \u2014 toggle Nero mode (adversarial)", category: "session" },
28352
29061
  { name: "btw", desc: "<question> \u2014 ask something while engines work", category: "session" },
28353
- { name: "clear", desc: " \u2014 reset session", category: "session", aliases: ["clean"] },
29062
+ { name: "compact", desc: " \u2014 shrink Cesar context without clearing transcript", category: "session" },
29063
+ { name: "clear", desc: " \u2014 reset session (saves chat, clears brain)", category: "session", aliases: ["clean"] },
28354
29064
  // Utility
28355
29065
  { name: "worktree", desc: "new|list|rm|prune|rehydrate <branch> \u2014 isolated per-session git worktrees", category: "utility", aliases: ["wt"] },
28356
29066
  { name: "create-skill", desc: "<name> \u2014 scaffold a new skill (.agon/skills/)", category: "utility" },
@@ -28601,8 +29311,8 @@ function computeContributionWeights(team, trace) {
28601
29311
  }
28602
29312
 
28603
29313
  // ../core/src/generated/teams/team-elo.ts
28604
- import { readFileSync as readFileSync30, writeFileSync as writeFileSync24, mkdirSync as mkdirSync24, renameSync as renameSync13 } from "fs";
28605
- import { dirname as dirname12 } from "path";
29314
+ import { readFileSync as readFileSync32, writeFileSync as writeFileSync25, mkdirSync as mkdirSync25, renameSync as renameSync13 } from "fs";
29315
+ import { dirname as dirname13 } from "path";
28606
29316
  function defaultCompositionRating(lineupKey2) {
28607
29317
  return { lineupKey: lineupKey2, rating: 1500, wins: 0, losses: 0, draws: 0, matches: 0 };
28608
29318
  }
@@ -28611,7 +29321,7 @@ function defaultRoleRating(engineId, role) {
28611
29321
  }
28612
29322
  function loadTeamElo() {
28613
29323
  try {
28614
- return JSON.parse(readFileSync30(TEAM_ELO_PATH, "utf-8"));
29324
+ return JSON.parse(readFileSync32(TEAM_ELO_PATH, "utf-8"));
28615
29325
  } catch (err) {
28616
29326
  if (err.code !== "ENOENT") {
28617
29327
  console.warn(`[agon] failed to load team ELO: ${err instanceof Error ? err.message : String(err)}`);
@@ -28620,10 +29330,10 @@ function loadTeamElo() {
28620
29330
  }
28621
29331
  }
28622
29332
  function saveTeamElo(record2) {
28623
- mkdirSync24(dirname12(TEAM_ELO_PATH), { recursive: true });
29333
+ mkdirSync25(dirname13(TEAM_ELO_PATH), { recursive: true });
28624
29334
  record2.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
28625
29335
  const tmpPath = TEAM_ELO_PATH + ".tmp";
28626
- writeFileSync24(tmpPath, JSON.stringify(record2, null, 2) + "\n");
29336
+ writeFileSync25(tmpPath, JSON.stringify(record2, null, 2) + "\n");
28627
29337
  renameSync13(tmpPath, TEAM_ELO_PATH);
28628
29338
  }
28629
29339
  function expectedScore(rA, rB) {
@@ -28710,6 +29420,7 @@ function updateTeamElo(match, kFactor) {
28710
29420
  export {
28711
29421
  DEFAULT_AGON_CONFIG,
28712
29422
  DEFAULT_CONFIG,
29423
+ AGON_MODE_NAMES,
28713
29424
  AgonError,
28714
29425
  EngineNotFoundError,
28715
29426
  EngineTimeoutError,
@@ -28814,8 +29525,13 @@ export {
28814
29525
  validateEngineConfig,
28815
29526
  validateEngineDir,
28816
29527
  EngineRegistry,
29528
+ hasProjectBrief,
28817
29529
  isKernProject,
28818
29530
  scanProjectContext,
29531
+ collectSourceFiles,
29532
+ extractSymbols,
29533
+ buildCodebaseMap,
29534
+ clearCodebaseMapCache,
28819
29535
  addWorkspace,
28820
29536
  removeWorkspace,
28821
29537
  listWorkspaces,
@@ -28842,6 +29558,10 @@ export {
28842
29558
  listPlans,
28843
29559
  deletePlan,
28844
29560
  wordWrap,
29561
+ resolveKernSourceLocation,
29562
+ mapKernStackTrace,
29563
+ installKernStackTraceMapper,
29564
+ uninstallKernStackTraceMapper,
28845
29565
  formatSpinnerFrame,
28846
29566
  formatEngineBlock,
28847
29567
  formatStatusLine,
@@ -28940,6 +29660,7 @@ export {
28940
29660
  createAgentTool,
28941
29661
  createQuickNeroTool,
28942
29662
  createGoalTool,
29663
+ createConquerTool,
28943
29664
  createPipelineTool,
28944
29665
  createProposePlanTool,
28945
29666
  createExitPlanModeTool,
@@ -28990,6 +29711,8 @@ export {
28990
29711
  refreshProbedCliModels,
28991
29712
  findBinary,
28992
29713
  getBinaryVersion,
29714
+ getBinaryVersionAsync,
29715
+ refreshCliGroupVersion,
28993
29716
  buildCliModelGroups,
28994
29717
  buildCliModelGroupsAsync,
28995
29718
  buildCliGroupsImmediate,
@@ -29106,4 +29829,4 @@ export {
29106
29829
  predictTeamRating,
29107
29830
  updateTeamElo
29108
29831
  };
29109
- //# sourceMappingURL=chunk-7PMMOQZ7.js.map
29832
+ //# sourceMappingURL=chunk-C22VTCS6.js.map