@wrongstack/core 0.24.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as crypto2 from 'crypto';
2
2
  import { randomBytes, createCipheriv, createDecipheriv, randomUUID, createHash } from 'crypto';
3
- import * as fsp2 from 'fs/promises';
3
+ import * as fsp3 from 'fs/promises';
4
4
  import { readFile, readdir, stat, mkdir } from 'fs/promises';
5
5
  import * as path6 from 'path';
6
- import { join, extname, relative, resolve, sep } from 'path';
6
+ import { join, extname, relative, isAbsolute, resolve, sep } from 'path';
7
7
  import * as fs2 from 'fs';
8
8
  import * as os5 from 'os';
9
9
  import { execFile, spawn } from 'child_process';
@@ -37,16 +37,16 @@ __export(atomic_write_exports, {
37
37
  });
38
38
  async function atomicWrite(targetPath, content, opts = {}) {
39
39
  const dir = path6.dirname(targetPath);
40
- await fsp2.mkdir(dir, { recursive: true });
40
+ await fsp3.mkdir(dir, { recursive: true });
41
41
  const tmp = path6.join(dir, `.${path6.basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
42
42
  try {
43
43
  if (typeof content === "string") {
44
- await fsp2.writeFile(tmp, content, { flag: "wx", encoding: opts.encoding ?? "utf8" });
44
+ await fsp3.writeFile(tmp, content, { flag: "wx", encoding: opts.encoding ?? "utf8" });
45
45
  } else {
46
- await fsp2.writeFile(tmp, content, { flag: "wx" });
46
+ await fsp3.writeFile(tmp, content, { flag: "wx" });
47
47
  }
48
48
  try {
49
- const fh = await fsp2.open(tmp, "r+");
49
+ const fh = await fsp3.open(tmp, "r+");
50
50
  try {
51
51
  await fh.sync();
52
52
  } finally {
@@ -56,36 +56,36 @@ async function atomicWrite(targetPath, content, opts = {}) {
56
56
  }
57
57
  let mode;
58
58
  try {
59
- const stat9 = await fsp2.stat(targetPath);
60
- mode = stat9.mode & 511;
59
+ const stat10 = await fsp3.stat(targetPath);
60
+ mode = stat10.mode & 511;
61
61
  } catch {
62
62
  mode = opts.mode;
63
63
  }
64
64
  if (mode !== void 0) {
65
- await fsp2.chmod(tmp, mode);
65
+ await fsp3.chmod(tmp, mode);
66
66
  }
67
67
  await renameWithRetry(tmp, targetPath);
68
68
  } catch (err) {
69
69
  try {
70
- await fsp2.unlink(tmp);
70
+ await fsp3.unlink(tmp);
71
71
  } catch {
72
72
  }
73
73
  throw err;
74
74
  }
75
75
  }
76
76
  async function ensureDir(dir) {
77
- await fsp2.mkdir(dir, { recursive: true });
77
+ await fsp3.mkdir(dir, { recursive: true });
78
78
  }
79
79
  async function renameWithRetry(from, to) {
80
80
  if (process.platform !== "win32") {
81
- await fsp2.rename(from, to);
81
+ await fsp3.rename(from, to);
82
82
  return;
83
83
  }
84
84
  const delays = [10, 25, 60, 120, 250];
85
85
  let lastErr;
86
86
  for (let i = 0; i <= delays.length; i++) {
87
87
  try {
88
- await fsp2.rename(from, to);
88
+ await fsp3.rename(from, to);
89
89
  return;
90
90
  } catch (err) {
91
91
  lastErr = err;
@@ -93,7 +93,7 @@ async function renameWithRetry(from, to) {
93
93
  if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {
94
94
  throw err;
95
95
  }
96
- await new Promise((resolve9) => setTimeout(resolve9, delays[i]));
96
+ await new Promise((resolve10) => setTimeout(resolve10, delays[i]));
97
97
  }
98
98
  }
99
99
  throw lastErr;
@@ -1206,20 +1206,20 @@ function isSecretField(name) {
1206
1206
  async function rewriteConfigEncrypted(configPath, vault, patch) {
1207
1207
  let current = {};
1208
1208
  try {
1209
- const raw = await fsp2.readFile(configPath, "utf8");
1209
+ const raw = await fsp3.readFile(configPath, "utf8");
1210
1210
  current = JSON.parse(raw);
1211
1211
  } catch {
1212
1212
  }
1213
1213
  const merged = deepMerge(current, patch ?? {});
1214
1214
  const encrypted = encryptConfigSecrets(merged, vault);
1215
- await fsp2.mkdir(path6.dirname(configPath), { recursive: true });
1215
+ await fsp3.mkdir(path6.dirname(configPath), { recursive: true });
1216
1216
  await atomicWrite(configPath, JSON.stringify(encrypted, null, 2), { mode: 384 });
1217
1217
  await restrictFilePermissions(configPath);
1218
1218
  }
1219
1219
  async function migratePlaintextSecrets(configPath, vault) {
1220
1220
  let raw;
1221
1221
  try {
1222
- raw = await fsp2.readFile(configPath, "utf8");
1222
+ raw = await fsp3.readFile(configPath, "utf8");
1223
1223
  } catch {
1224
1224
  return { migrated: 0, file: configPath };
1225
1225
  }
@@ -1248,7 +1248,7 @@ async function restrictFilePermissions(filePath) {
1248
1248
  }
1249
1249
  } else {
1250
1250
  try {
1251
- await fsp2.chmod(filePath, 384);
1251
+ await fsp3.chmod(filePath, 384);
1252
1252
  } catch {
1253
1253
  }
1254
1254
  }
@@ -1550,6 +1550,17 @@ function round4(n) {
1550
1550
 
1551
1551
  // src/utils/token-estimate.ts
1552
1552
  var RoughTokenEstimate = (text, charsPerToken = 3.5) => Math.max(1, Math.ceil(text.length / charsPerToken));
1553
+ var _cal = {
1554
+ ratio: 1,
1555
+ // current calibration multiplier (actual / estimated)
1556
+ count: 0,
1557
+ // number of samples recorded
1558
+ prevEst: 0,
1559
+ // estimated tokens from the most recent estimateRequestTokens call
1560
+ /** EWM α — higher = faster adaptation, more volatile */
1561
+ alpha: 0.3
1562
+ };
1563
+ var MIN_SAMPLES_FOR_CALIBRATION = 3;
1553
1564
  var ESTIMATE_CACHE = /* @__PURE__ */ new Map();
1554
1565
  var ESTIMATE_CACHE_MAX_SIZE = 1e4;
1555
1566
  function getCachedEstimate(key, compute) {
@@ -1622,13 +1633,53 @@ function estimateRequestTokens(messages, systemPrompt, tools) {
1622
1633
  for (const t2 of tools) {
1623
1634
  toolsTokens += estimateToolDefTokens(t2);
1624
1635
  }
1636
+ const total = messagesTokens + systemTokens + toolsTokens;
1637
+ _cal.prevEst = total;
1625
1638
  return {
1626
1639
  messages: messagesTokens,
1627
1640
  systemPrompt: systemTokens,
1628
1641
  tools: toolsTokens,
1629
- total: messagesTokens + systemTokens + toolsTokens
1642
+ total
1630
1643
  };
1631
1644
  }
1645
+ function recordActualUsage(actualInputTokens, estimatedInputTokens) {
1646
+ if (actualInputTokens <= 0) return;
1647
+ const est = estimatedInputTokens ?? _cal.prevEst;
1648
+ if (est <= 0) return;
1649
+ const sampleRatio = actualInputTokens / est;
1650
+ if (_cal.count === 0) {
1651
+ _cal.ratio = sampleRatio;
1652
+ } else {
1653
+ _cal.ratio = _cal.alpha * sampleRatio + (1 - _cal.alpha) * _cal.ratio;
1654
+ }
1655
+ _cal.ratio = Math.min(1.5, Math.max(0.5, _cal.ratio));
1656
+ _cal.count++;
1657
+ }
1658
+ function getCalibrationState() {
1659
+ return {
1660
+ ratio: _cal.ratio,
1661
+ count: _cal.count,
1662
+ calibrated: _cal.count >= MIN_SAMPLES_FOR_CALIBRATION
1663
+ };
1664
+ }
1665
+ function estimateRequestTokensCalibrated(messages, systemPrompt, tools) {
1666
+ const result = estimateRequestTokens(messages, systemPrompt, tools);
1667
+ if (_cal.count >= MIN_SAMPLES_FOR_CALIBRATION) {
1668
+ const safeRatio = Math.min(1.5, Math.max(0.5, _cal.ratio));
1669
+ return {
1670
+ messages: Math.round(result.messages * safeRatio),
1671
+ systemPrompt: Math.round(result.systemPrompt * safeRatio),
1672
+ tools: Math.round(result.tools * safeRatio),
1673
+ total: Math.round(result.total * safeRatio)
1674
+ };
1675
+ }
1676
+ return result;
1677
+ }
1678
+ function resetCalibration() {
1679
+ _cal.ratio = 1;
1680
+ _cal.count = 0;
1681
+ _cal.prevEst = 0;
1682
+ }
1632
1683
 
1633
1684
  // src/utils/message-invariants.ts
1634
1685
  function repairToolUseAdjacency(messages) {
@@ -2431,7 +2482,7 @@ var DefaultModelsRegistry = class {
2431
2482
  async readOverlayFile() {
2432
2483
  if (!this.overlayFile) return void 0;
2433
2484
  try {
2434
- const raw = await fsp2.readFile(this.overlayFile, "utf8");
2485
+ const raw = await fsp3.readFile(this.overlayFile, "utf8");
2435
2486
  return JSON.parse(raw);
2436
2487
  } catch {
2437
2488
  return void 0;
@@ -2509,7 +2560,7 @@ var DefaultModelsRegistry = class {
2509
2560
  }
2510
2561
  async readCacheAt(file) {
2511
2562
  try {
2512
- const raw = await fsp2.readFile(file, "utf8");
2563
+ const raw = await fsp3.readFile(file, "utf8");
2513
2564
  return JSON.parse(raw);
2514
2565
  } catch {
2515
2566
  return void 0;
@@ -2927,7 +2978,7 @@ var InMemoryAgentBridge = class {
2927
2978
  );
2928
2979
  }
2929
2980
  this.inflightGuards.add(correlationId);
2930
- return new Promise((resolve9, reject) => {
2981
+ return new Promise((resolve10, reject) => {
2931
2982
  const timer = setTimeout(() => {
2932
2983
  this.inflightGuards.delete(correlationId);
2933
2984
  this.pendingRequests.delete(correlationId);
@@ -2939,7 +2990,7 @@ var InMemoryAgentBridge = class {
2939
2990
  return;
2940
2991
  }
2941
2992
  this.pendingRequests.set(correlationId, {
2942
- resolve: resolve9,
2993
+ resolve: resolve10,
2943
2994
  reject,
2944
2995
  timer
2945
2996
  });
@@ -4441,6 +4492,120 @@ function buildChildEnv(optsOrSessionId) {
4441
4492
  if (opts.sessionId) out["WRONGSTACK_SESSION_ID"] = opts.sessionId;
4442
4493
  return out;
4443
4494
  }
4495
+ var GLOB_CHARS = /* @__PURE__ */ new Set(["*", "?", "["]);
4496
+ var IS_WINDOWS = process.platform === "win32";
4497
+ var SEP = IS_WINDOWS ? "\\" : "/";
4498
+ function isGlob(p) {
4499
+ for (const c of p) {
4500
+ if (GLOB_CHARS.has(c)) return true;
4501
+ }
4502
+ return false;
4503
+ }
4504
+ function globToRegex(pat) {
4505
+ let i = 0, re = "^";
4506
+ while (i < pat.length) {
4507
+ const c = pat[i];
4508
+ if (c === "*") {
4509
+ if (pat[i + 1] === "*") {
4510
+ re += ".*";
4511
+ i += 2;
4512
+ if (pat[i] === "/") i++;
4513
+ } else {
4514
+ re += "[^/\\\\]*";
4515
+ i++;
4516
+ }
4517
+ } else if (c === "?") {
4518
+ re += "[^/\\\\]";
4519
+ i++;
4520
+ } else if (c === "[") {
4521
+ let cls = "[";
4522
+ i++;
4523
+ if (pat[i] === "!" || pat[i] === "^") {
4524
+ cls += "^";
4525
+ i++;
4526
+ }
4527
+ while (i < pat.length && pat[i] !== "]") {
4528
+ const ch = pat[i] ?? "";
4529
+ if (ch === "\\") cls += "\\\\";
4530
+ else if (ch === "]" || ch === "^") cls += `\\${ch}`;
4531
+ else cls += ch;
4532
+ i++;
4533
+ }
4534
+ cls += "]";
4535
+ re += cls;
4536
+ i++;
4537
+ } else {
4538
+ re += c.replace(/[.+^${}()|\\]/g, "\\$&");
4539
+ i++;
4540
+ }
4541
+ }
4542
+ return new RegExp(re + "$");
4543
+ }
4544
+ function baseDir(pat) {
4545
+ let i = pat.length - 1;
4546
+ while (i >= 0 && !GLOB_CHARS.has(pat[i]) && pat[i] !== SEP && pat[i] !== "/") i--;
4547
+ const cut = i >= 0 ? pat.lastIndexOf(SEP, i) : pat.lastIndexOf("/", i);
4548
+ return cut < 0 ? "." : pat.slice(0, cut);
4549
+ }
4550
+ async function expandGlob(pattern) {
4551
+ if (!isGlob(pattern)) return [pattern];
4552
+ const results = /* @__PURE__ */ new Set();
4553
+ const abs = isAbsolute(pattern);
4554
+ const base = abs ? baseDir(pattern) : baseDir(pattern);
4555
+ const relPat = base === "." ? pattern : pattern.slice(base.length + 1);
4556
+ async function walk4(dir, pat) {
4557
+ let entries;
4558
+ try {
4559
+ entries = await fsp3.readdir(dir);
4560
+ } catch {
4561
+ return;
4562
+ }
4563
+ const firstGlob = pat.search(/[*?[\[]/);
4564
+ if (firstGlob < 0) {
4565
+ const re = globToRegex(pat);
4566
+ for (const e of entries) {
4567
+ if (re.test(e)) {
4568
+ const full = `${dir}${SEP}${e}`;
4569
+ results.add(abs ? resolve(full) : full);
4570
+ }
4571
+ }
4572
+ return;
4573
+ }
4574
+ const before = pat.slice(0, firstGlob);
4575
+ const rest = pat.slice(firstGlob);
4576
+ if (before.endsWith("**")) {
4577
+ await walk4(dir, rest);
4578
+ for (const e of entries) {
4579
+ const full = `${dir}${SEP}${e}`;
4580
+ try {
4581
+ const stat10 = await fsp3.stat(full);
4582
+ if (stat10.isDirectory()) await walk4(full, rest);
4583
+ } catch {
4584
+ }
4585
+ }
4586
+ } else if (before === "") {
4587
+ const re = globToRegex(rest);
4588
+ for (const e of entries) {
4589
+ if (re.test(e)) {
4590
+ const full = `${dir}${SEP}${e}`;
4591
+ results.add(abs ? resolve(full) : full);
4592
+ }
4593
+ }
4594
+ } else {
4595
+ const seg = before.replace(/[*?[\]]/g, "").replace(/\/$/, "");
4596
+ if (entries.includes(seg)) {
4597
+ const full = `${dir}${SEP}${seg}`;
4598
+ try {
4599
+ const stat10 = await fsp3.stat(full);
4600
+ if (stat10.isDirectory()) await walk4(full, rest);
4601
+ } catch {
4602
+ }
4603
+ }
4604
+ }
4605
+ }
4606
+ await walk4(base === "." ? "." : base, relPat);
4607
+ return [...results];
4608
+ }
4444
4609
 
4445
4610
  // src/utils/json-repair.ts
4446
4611
  function completePartialObject(s) {
@@ -4557,7 +4722,7 @@ var DefaultSessionStore = class {
4557
4722
  const file = path6.join(shardDir, `${id}.jsonl`);
4558
4723
  let handle;
4559
4724
  try {
4560
- handle = await fsp2.open(file, "a", 384);
4725
+ handle = await fsp3.open(file, "a", 384);
4561
4726
  } catch (err) {
4562
4727
  throw new Error(
4563
4728
  `Failed to open session file: ${err instanceof Error ? err.message : String(err)}`,
@@ -4581,7 +4746,7 @@ var DefaultSessionStore = class {
4581
4746
  const data = await this.load(id);
4582
4747
  let handle;
4583
4748
  try {
4584
- handle = await fsp2.open(file, "a", 384);
4749
+ handle = await fsp3.open(file, "a", 384);
4585
4750
  } catch (err) {
4586
4751
  throw new Error(
4587
4752
  `Failed to open session "${id}" for append: ${err instanceof Error ? err.message : String(err)}`,
@@ -4610,7 +4775,7 @@ var DefaultSessionStore = class {
4610
4775
  }
4611
4776
  async load(id) {
4612
4777
  const file = this.sessionPath(id, ".jsonl");
4613
- const raw = await fsp2.readFile(file, "utf8");
4778
+ const raw = await fsp3.readFile(file, "utf8");
4614
4779
  const lines = raw.split("\n").filter((l) => l.trim());
4615
4780
  const events = [];
4616
4781
  for (const line of lines) {
@@ -4645,7 +4810,7 @@ var DefaultSessionStore = class {
4645
4810
  /** Recursively collect all session IDs from shard subdirectories. */
4646
4811
  async collectSessionIds(dir) {
4647
4812
  const ids = [];
4648
- const entries = await fsp2.readdir(dir, { withFileTypes: true });
4813
+ const entries = await fsp3.readdir(dir, { withFileTypes: true });
4649
4814
  for (const entry of entries) {
4650
4815
  const full = path6.join(dir, entry.name);
4651
4816
  if (entry.isDirectory()) {
@@ -4659,12 +4824,12 @@ var DefaultSessionStore = class {
4659
4824
  async summaryFor(id) {
4660
4825
  const manifest = this.sessionPath(id, ".summary.json");
4661
4826
  try {
4662
- const raw = await fsp2.readFile(manifest, "utf8");
4827
+ const raw = await fsp3.readFile(manifest, "utf8");
4663
4828
  return JSON.parse(raw);
4664
4829
  } catch {
4665
4830
  const full = this.sessionPath(id, ".jsonl");
4666
- const stat9 = await fsp2.stat(full);
4667
- const summary = await this.summarize(id, stat9.mtime.toISOString());
4831
+ const stat10 = await fsp3.stat(full);
4832
+ const summary = await this.summarize(id, stat10.mtime.toISOString());
4668
4833
  await atomicWrite(manifest, JSON.stringify(summary), { mode: 384 }).catch((err) => {
4669
4834
  console.warn(
4670
4835
  `[session-store] Failed to write manifest for "${id}":`,
@@ -4675,8 +4840,8 @@ var DefaultSessionStore = class {
4675
4840
  }
4676
4841
  }
4677
4842
  async delete(id) {
4678
- await fsp2.unlink(this.sessionPath(id, ".jsonl"));
4679
- await fsp2.unlink(this.sessionPath(id, ".summary.json")).catch(() => void 0);
4843
+ await fsp3.unlink(this.sessionPath(id, ".jsonl"));
4844
+ await fsp3.unlink(this.sessionPath(id, ".summary.json")).catch(() => void 0);
4680
4845
  }
4681
4846
  async clearHistory(id) {
4682
4847
  await this.ensureShardDir(id);
@@ -4690,8 +4855,8 @@ var DefaultSessionStore = class {
4690
4855
  provider: "unknown"
4691
4856
  })}
4692
4857
  `;
4693
- await fsp2.writeFile(file, record, "utf8");
4694
- await fsp2.unlink(meta).catch(() => void 0);
4858
+ await fsp3.writeFile(file, record, "utf8");
4859
+ await fsp3.unlink(meta).catch(() => void 0);
4695
4860
  }
4696
4861
  async summarize(id, mtime) {
4697
4862
  try {
@@ -4877,7 +5042,7 @@ var FileSessionWriter = class {
4877
5042
  `;
4878
5043
  try {
4879
5044
  if (this.filePath) {
4880
- await fsp2.writeFile(this.filePath, record, { flag: "a", mode: 384 });
5045
+ await fsp3.writeFile(this.filePath, record, { flag: "a", mode: 384 });
4881
5046
  }
4882
5047
  } catch {
4883
5048
  }
@@ -4970,7 +5135,7 @@ var FileSessionWriter = class {
4970
5135
  }
4971
5136
  async truncateToCheckpoint(targetPromptIndex) {
4972
5137
  if (!this.filePath) return 0;
4973
- const raw = await fsp2.readFile(this.filePath, "utf8");
5138
+ const raw = await fsp3.readFile(this.filePath, "utf8");
4974
5139
  const lines = raw.split("\n");
4975
5140
  const kept = [];
4976
5141
  let removedCount = 0;
@@ -5008,13 +5173,13 @@ var FileSessionWriter = class {
5008
5173
  }
5009
5174
  const truncated = kept.join("\n");
5010
5175
  const tmpPath = `${this.filePath}.rewind.tmp`;
5011
- await fsp2.writeFile(tmpPath, truncated + "\n", "utf8");
5176
+ await fsp3.writeFile(tmpPath, truncated + "\n", "utf8");
5012
5177
  try {
5013
5178
  await this.handle.close();
5014
- await fsp2.rename(tmpPath, this.filePath);
5015
- this.handle = await fsp2.open(this.filePath, "a", 384);
5179
+ await fsp3.rename(tmpPath, this.filePath);
5180
+ this.handle = await fsp3.open(this.filePath, "a", 384);
5016
5181
  } catch (err) {
5017
- await fsp2.unlink(tmpPath).catch(() => void 0);
5182
+ await fsp3.unlink(tmpPath).catch(() => void 0);
5018
5183
  throw err;
5019
5184
  }
5020
5185
  await this.append({
@@ -5040,7 +5205,7 @@ var FileSessionWriter = class {
5040
5205
  provider: this.meta.provider ?? "unknown"
5041
5206
  })}
5042
5207
  `;
5043
- await fsp2.writeFile(this.filePath, record, "utf8");
5208
+ await fsp3.writeFile(this.filePath, record, "utf8");
5044
5209
  }
5045
5210
  /**
5046
5211
  * Idea #1 — write an in-flight marker. The agent loop should call
@@ -5097,7 +5262,7 @@ var QueueStore = class {
5097
5262
  async read() {
5098
5263
  let raw;
5099
5264
  try {
5100
- raw = await fsp2.readFile(this.file, "utf8");
5265
+ raw = await fsp3.readFile(this.file, "utf8");
5101
5266
  } catch (err) {
5102
5267
  const code = err.code;
5103
5268
  if (code === "ENOENT") return [];
@@ -5119,7 +5284,7 @@ var QueueStore = class {
5119
5284
  }
5120
5285
  async clear() {
5121
5286
  try {
5122
- await fsp2.unlink(this.file);
5287
+ await fsp3.unlink(this.file);
5123
5288
  } catch (err) {
5124
5289
  const code = err.code;
5125
5290
  if (code === "ENOENT") return;
@@ -5154,7 +5319,7 @@ var DefaultAttachmentStore = class {
5154
5319
  let spooledPath;
5155
5320
  let data = input.data;
5156
5321
  if (this.spoolDir && bytes >= this.spoolThreshold) {
5157
- await fsp2.mkdir(this.spoolDir, { recursive: true });
5322
+ await fsp3.mkdir(this.spoolDir, { recursive: true });
5158
5323
  spooledPath = path6.join(this.spoolDir, `${id}.bin`);
5159
5324
  await atomicWrite(spooledPath, input.data, {
5160
5325
  encoding: input.kind === "image" ? "base64" : "utf8"
@@ -5217,7 +5382,7 @@ var DefaultAttachmentStore = class {
5217
5382
  for (const att of this.items.values()) {
5218
5383
  if (att.path) toDelete.push(att.path);
5219
5384
  }
5220
- await Promise.all(toDelete.map((p) => fsp2.unlink(p).catch(() => void 0)));
5385
+ await Promise.all(toDelete.map((p) => fsp3.unlink(p).catch(() => void 0)));
5221
5386
  }
5222
5387
  this.items.clear();
5223
5388
  this.refs.length = 0;
@@ -5225,7 +5390,7 @@ var DefaultAttachmentStore = class {
5225
5390
  }
5226
5391
  async toBlock(att) {
5227
5392
  if (att.kind === "image") {
5228
- const data = att.data ?? (att.path ? await fsp2.readFile(att.path, { encoding: "base64" }) : "");
5393
+ const data = att.data ?? (att.path ? await fsp3.readFile(att.path, { encoding: "base64" }) : "");
5229
5394
  return {
5230
5395
  type: "image",
5231
5396
  source: {
@@ -5235,7 +5400,7 @@ var DefaultAttachmentStore = class {
5235
5400
  }
5236
5401
  };
5237
5402
  }
5238
- const raw = att.data ?? (att.path ? await fsp2.readFile(att.path, "utf8") : "");
5403
+ const raw = att.data ?? (att.path ? await fsp3.readFile(att.path, "utf8") : "");
5239
5404
  const label = att.meta.filename ? `<file path="${att.meta.filename}">` : "<pasted>";
5240
5405
  const close = att.meta.filename ? "</file>" : "</pasted>";
5241
5406
  return { type: "text", text: `${label}
@@ -5335,7 +5500,7 @@ ${body.trim()}`);
5335
5500
  }
5336
5501
  async read(scope) {
5337
5502
  try {
5338
- return await fsp2.readFile(this.files[scope], "utf8");
5503
+ return await fsp3.readFile(this.files[scope], "utf8");
5339
5504
  } catch {
5340
5505
  return "";
5341
5506
  }
@@ -5346,7 +5511,7 @@ ${body.trim()}`);
5346
5511
  await ensureDir(path6.dirname(file));
5347
5512
  let existing = "";
5348
5513
  try {
5349
- existing = await fsp2.readFile(file, "utf8");
5514
+ existing = await fsp3.readFile(file, "utf8");
5350
5515
  } catch {
5351
5516
  }
5352
5517
  const ts = (/* @__PURE__ */ new Date()).toISOString();
@@ -5370,7 +5535,7 @@ ${entry}`;
5370
5535
  const file = this.files[scope];
5371
5536
  let existing;
5372
5537
  try {
5373
- existing = await fsp2.readFile(file, "utf8");
5538
+ existing = await fsp3.readFile(file, "utf8");
5374
5539
  } catch {
5375
5540
  return 0;
5376
5541
  }
@@ -5409,7 +5574,7 @@ ${entry}`;
5409
5574
  const file = this.files[scope];
5410
5575
  let existing;
5411
5576
  try {
5412
- existing = await fsp2.readFile(file, "utf8");
5577
+ existing = await fsp3.readFile(file, "utf8");
5413
5578
  } catch {
5414
5579
  return;
5415
5580
  }
@@ -5425,7 +5590,7 @@ ${entry}`;
5425
5590
  const next = lines.join("\n");
5426
5591
  const backup = `${file}.bak.${Date.now()}`;
5427
5592
  try {
5428
- await fsp2.copyFile(file, backup);
5593
+ await fsp3.copyFile(file, backup);
5429
5594
  } catch {
5430
5595
  }
5431
5596
  try {
@@ -5742,7 +5907,7 @@ var DefaultConfigLoader = class {
5742
5907
  */
5743
5908
  async loadSyncConfig() {
5744
5909
  try {
5745
- const raw = await fsp2.readFile(this.paths.syncConfig, "utf8");
5910
+ const raw = await fsp3.readFile(this.paths.syncConfig, "utf8");
5746
5911
  const parsed = safeParse(raw);
5747
5912
  if (!parsed.ok || !parsed.value) return null;
5748
5913
  if (this.vault) {
@@ -5759,7 +5924,7 @@ var DefaultConfigLoader = class {
5759
5924
  async readJson(file) {
5760
5925
  let raw;
5761
5926
  try {
5762
- raw = await fsp2.readFile(file, "utf8");
5927
+ raw = await fsp3.readFile(file, "utf8");
5763
5928
  } catch (err) {
5764
5929
  if (err.code !== "ENOENT") {
5765
5930
  console.warn(`[config] Failed to read "${file}":`, err);
@@ -5941,7 +6106,7 @@ var RecoveryLock = class {
5941
6106
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
5942
6107
  };
5943
6108
  try {
5944
- await fsp2.writeFile(this.file, JSON.stringify(lock), { flag: "wx", mode: 384 });
6109
+ await fsp3.writeFile(this.file, JSON.stringify(lock), { flag: "wx", mode: 384 });
5945
6110
  } catch (err) {
5946
6111
  const code = err.code;
5947
6112
  if (code === "EEXIST") {
@@ -5957,7 +6122,7 @@ var RecoveryLock = class {
5957
6122
  */
5958
6123
  async clear() {
5959
6124
  try {
5960
- await fsp2.unlink(this.file);
6125
+ await fsp3.unlink(this.file);
5961
6126
  } catch (err) {
5962
6127
  const code = err.code;
5963
6128
  if (code === "ENOENT") return;
@@ -5967,7 +6132,7 @@ var RecoveryLock = class {
5967
6132
  async readLock() {
5968
6133
  let raw;
5969
6134
  try {
5970
- raw = await fsp2.readFile(this.file, "utf8");
6135
+ raw = await fsp3.readFile(this.file, "utf8");
5971
6136
  } catch (err) {
5972
6137
  const code = err.code;
5973
6138
  if (code === "ENOENT") return null;
@@ -6196,7 +6361,7 @@ init_atomic_write();
6196
6361
  async function loadTodosCheckpoint(filePath) {
6197
6362
  let raw;
6198
6363
  try {
6199
- raw = await fsp2.readFile(filePath, "utf8");
6364
+ raw = await fsp3.readFile(filePath, "utf8");
6200
6365
  } catch {
6201
6366
  return null;
6202
6367
  }
@@ -6267,7 +6432,7 @@ init_atomic_write();
6267
6432
  async function loadPlan(filePath) {
6268
6433
  let raw;
6269
6434
  try {
6270
- raw = await fsp2.readFile(filePath, "utf8");
6435
+ raw = await fsp3.readFile(filePath, "utf8");
6271
6436
  } catch {
6272
6437
  return null;
6273
6438
  }
@@ -6504,7 +6669,7 @@ init_atomic_write();
6504
6669
  async function loadDirectorState(filePath) {
6505
6670
  let raw;
6506
6671
  try {
6507
- raw = await fsp2.readFile(filePath, "utf8");
6672
+ raw = await fsp3.readFile(filePath, "utf8");
6508
6673
  } catch {
6509
6674
  return null;
6510
6675
  }
@@ -6519,7 +6684,7 @@ async function loadDirectorState(filePath) {
6519
6684
  async function acquireDirectorStateLock(lockPath, processId = process.pid) {
6520
6685
  let existing;
6521
6686
  try {
6522
- existing = await fsp2.readFile(lockPath, "utf8");
6687
+ existing = await fsp3.readFile(lockPath, "utf8");
6523
6688
  } catch {
6524
6689
  }
6525
6690
  if (existing) {
@@ -6543,7 +6708,7 @@ async function acquireDirectorStateLock(lockPath, processId = process.pid) {
6543
6708
  }
6544
6709
  async function releaseDirectorStateLock(lockPath) {
6545
6710
  try {
6546
- await fsp2.unlink(lockPath);
6711
+ await fsp3.unlink(lockPath);
6547
6712
  } catch {
6548
6713
  }
6549
6714
  }
@@ -6748,7 +6913,7 @@ var DefaultPermissionPolicy = class {
6748
6913
  }
6749
6914
  async reload() {
6750
6915
  try {
6751
- const raw = await fsp2.readFile(this.trustFile, "utf8");
6916
+ const raw = await fsp3.readFile(this.trustFile, "utf8");
6752
6917
  const parsed = safeParse(raw);
6753
6918
  if (parsed.ok && parsed.value) this.policy = parsed.value;
6754
6919
  } catch {
@@ -6987,12 +7152,12 @@ var DefaultSkillLoader = class {
6987
7152
  const seen = /* @__PURE__ */ new Set();
6988
7153
  for (const { dir, source } of this.dirs) {
6989
7154
  try {
6990
- const entries = await fsp2.readdir(dir, { withFileTypes: true });
7155
+ const entries = await fsp3.readdir(dir, { withFileTypes: true });
6991
7156
  for (const e of entries) {
6992
7157
  if (!e.isDirectory()) continue;
6993
7158
  const skillFile = path6.join(dir, e.name, "SKILL.md");
6994
7159
  try {
6995
- const raw = await fsp2.readFile(skillFile, "utf8");
7160
+ const raw = await fsp3.readFile(skillFile, "utf8");
6996
7161
  const meta = parseFrontmatter(raw);
6997
7162
  if (!meta.name || !meta.description) continue;
6998
7163
  if (seen.has(meta.name)) continue;
@@ -7034,7 +7199,7 @@ var DefaultSkillLoader = class {
7034
7199
  const entries = [];
7035
7200
  for (const s of skills) {
7036
7201
  try {
7037
- const raw = await fsp2.readFile(s.path, "utf8");
7202
+ const raw = await fsp3.readFile(s.path, "utf8");
7038
7203
  const { trigger, scope } = parseDescription(raw);
7039
7204
  entries.push({ name: s.name, trigger, scope, source: s.source, path: s.path });
7040
7205
  } catch {
@@ -7048,7 +7213,7 @@ var DefaultSkillLoader = class {
7048
7213
  async readBody(name) {
7049
7214
  const m = await this.find(name);
7050
7215
  if (!m) throw new Error(`Skill "${name}" not found`);
7051
- return fsp2.readFile(m.path, "utf8");
7216
+ return fsp3.readFile(m.path, "utf8");
7052
7217
  }
7053
7218
  };
7054
7219
  function parseFrontmatter(raw) {
@@ -7313,8 +7478,8 @@ async function streamProviderToResponse(provider, req, signal, ctx, events) {
7313
7478
  try {
7314
7479
  await Promise.race([
7315
7480
  Promise.resolve(iter.return?.()),
7316
- new Promise((resolve9) => {
7317
- drainTimer = setTimeout(resolve9, 500);
7481
+ new Promise((resolve10) => {
7482
+ drainTimer = setTimeout(resolve10, 500);
7318
7483
  })
7319
7484
  ]);
7320
7485
  } finally {
@@ -7375,7 +7540,7 @@ async function runProviderWithRetry(opts) {
7375
7540
  description
7376
7541
  });
7377
7542
  }
7378
- await new Promise((resolve9, reject) => {
7543
+ await new Promise((resolve10, reject) => {
7379
7544
  let settled = false;
7380
7545
  const onAbort = () => {
7381
7546
  if (settled) return;
@@ -7388,7 +7553,7 @@ async function runProviderWithRetry(opts) {
7388
7553
  settled = true;
7389
7554
  clearTimeout(t2);
7390
7555
  signal.removeEventListener("abort", onAbort);
7391
- resolve9();
7556
+ resolve10();
7392
7557
  }, delay);
7393
7558
  if (signal.aborted) {
7394
7559
  onAbort();
@@ -8131,7 +8296,7 @@ var AutoCompactionMiddleware = class _AutoCompactionMiddleware {
8131
8296
  }
8132
8297
  handler() {
8133
8298
  return async (ctx, next) => {
8134
- const tokens = this._estimator ? this._estimator(ctx) : estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;
8299
+ const tokens = this._estimator ? this._estimator(ctx) : estimateRequestTokensCalibrated(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;
8135
8300
  const load = tokens / this._maxContext;
8136
8301
  const policy = this.policyProvider?.(ctx);
8137
8302
  const thresholds = policy?.thresholds ?? {
@@ -8400,7 +8565,7 @@ function goalFilePath(projectRoot) {
8400
8565
  async function loadGoal(filePath) {
8401
8566
  let raw;
8402
8567
  try {
8403
- raw = await fsp2.readFile(filePath, "utf8");
8568
+ raw = await fsp3.readFile(filePath, "utf8");
8404
8569
  } catch {
8405
8570
  return null;
8406
8571
  }
@@ -9067,7 +9232,7 @@ ${recentJournal}` : "No prior iterations.",
9067
9232
  }
9068
9233
  };
9069
9234
  function sleep(ms) {
9070
- return new Promise((resolve9) => setTimeout(resolve9, ms));
9235
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
9071
9236
  }
9072
9237
 
9073
9238
  // src/coordination/subagent-budget.ts
@@ -9283,12 +9448,12 @@ var SubagentBudget = class _SubagentBudget {
9283
9448
  if (!bus || !bus.hasListenerFor("budget.threshold_reached")) {
9284
9449
  return Promise.resolve("stop");
9285
9450
  }
9286
- return new Promise((resolve9) => {
9451
+ return new Promise((resolve10) => {
9287
9452
  let resolved = false;
9288
9453
  const respond = (d) => {
9289
9454
  if (resolved) return;
9290
9455
  resolved = true;
9291
- resolve9(d);
9456
+ resolve10(d);
9292
9457
  };
9293
9458
  const fallback = setTimeout(
9294
9459
  () => respond("stop"),
@@ -12225,6 +12390,10 @@ var NICKNAME_POOL = {
12225
12390
  "pasteur": { name: "Pasteur", domain: "biology" },
12226
12391
  "hawking": { name: "Hawking", domain: "cosmology" },
12227
12392
  "sagan": { name: "Sagan", domain: "cosmology" },
12393
+ // Exploration & navigation
12394
+ "columbus": { name: "Columbus", domain: "exploration" },
12395
+ "polo": { name: "Polo", domain: "exploration" },
12396
+ "magellan": { name: "Magellan", domain: "exploration" },
12228
12397
  // Chemistry / materials
12229
12398
  "lavoisier": { name: "Lavoisier", domain: "chemistry" },
12230
12399
  "mendeleev": { name: "Mendeleev", domain: "chemistry" }
@@ -12279,7 +12448,7 @@ function formatRole(role) {
12279
12448
  }
12280
12449
 
12281
12450
  // src/coordination/multi-agent-coordinator.ts
12282
- var DefaultMultiAgentCoordinator = class extends EventEmitter {
12451
+ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends EventEmitter {
12283
12452
  coordinatorId;
12284
12453
  config;
12285
12454
  runner;
@@ -12294,8 +12463,12 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12294
12463
  * names) to memorable ones here — that's what surfaces in the fleet monitor.
12295
12464
  */
12296
12465
  usedNicknames = /* @__PURE__ */ new Set();
12466
+ /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */
12467
+ subagentNicknames = /* @__PURE__ */ new Map();
12297
12468
  pendingTasks = [];
12298
12469
  completedResults = [];
12470
+ /** Prevents completedResults from growing unbounded in long-running coordinators. */
12471
+ static MAX_COMPLETED_RESULTS = 1e4;
12299
12472
  totalIterations = 0;
12300
12473
  inFlight = 0;
12301
12474
  /**
@@ -12350,7 +12523,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12350
12523
  * Explicit, human-chosen names — including nicknames already assigned by
12351
12524
  * `Director.spawn()` — are left untouched, so this never double-assigns.
12352
12525
  */
12353
- withNickname(subagent) {
12526
+ withNickname(subagent, subagentId) {
12354
12527
  const role = subagent.role ?? "subagent";
12355
12528
  const name = subagent.name?.trim() ?? "";
12356
12529
  const isPlaceholder = name === "" || name.toLowerCase() === role.toLowerCase() || name === "subagent" || name === "adhoc" || name === "generic" || /^slot-/.test(name);
@@ -12358,11 +12531,12 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12358
12531
  const nickname = assignNickname(role, this.usedNicknames);
12359
12532
  const baseKey = nickname.split(" ")[0].toLowerCase().replace(/[^a-z0-9-]/g, "-");
12360
12533
  this.usedNicknames.add(baseKey);
12534
+ this.subagentNicknames.set(subagentId, baseKey);
12361
12535
  return { ...subagent, name: nickname };
12362
12536
  }
12363
12537
  async spawn(subagent) {
12364
- subagent = this.withNickname(subagent);
12365
12538
  const id = subagent.id || randomUUID();
12539
+ subagent = this.withNickname(subagent, id);
12366
12540
  if (this.subagents.has(id)) {
12367
12541
  throw new Error(`Subagent id "${id}" already exists \u2014 refusing to overwrite`);
12368
12542
  }
@@ -12506,7 +12680,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12506
12680
  taskIds.map((id) => {
12507
12681
  const cached = this.completedResults.find((r) => r.taskId === id);
12508
12682
  if (cached) return cached;
12509
- return new Promise((resolve9, reject) => {
12683
+ return new Promise((resolve10, reject) => {
12510
12684
  const timeout = setTimeout(() => {
12511
12685
  this.off("task.completed", handler);
12512
12686
  reject(new Error(`awaitTasks timed out waiting for task "${id}"`));
@@ -12515,7 +12689,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12515
12689
  if (result.taskId === id) {
12516
12690
  clearTimeout(timeout);
12517
12691
  this.off("task.completed", handler);
12518
- resolve9(result);
12692
+ resolve10(result);
12519
12693
  }
12520
12694
  };
12521
12695
  this.on("task.completed", handler);
@@ -12804,6 +12978,12 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12804
12978
  }
12805
12979
  recordCompletion(result) {
12806
12980
  this.completedResults.push(result);
12981
+ if (this.completedResults.length > _DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {
12982
+ this.completedResults.splice(
12983
+ 0,
12984
+ this.completedResults.length - _DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS
12985
+ );
12986
+ }
12807
12987
  this.totalIterations += result.iterations;
12808
12988
  if (this.inFlight > 0) {
12809
12989
  this.inFlight--;
@@ -12873,7 +13053,29 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
12873
13053
  }
12874
13054
  this.subagents.delete(subagentId);
12875
13055
  this.terminating.delete(subagentId);
13056
+ const nicknameKey = this.subagentNicknames.get(subagentId);
13057
+ if (nicknameKey) {
13058
+ this.usedNicknames.delete(nicknameKey);
13059
+ this.subagentNicknames.delete(subagentId);
13060
+ }
13061
+ const orphaned = this.pendingTasks.filter((t2) => t2.subagentId === subagentId);
12876
13062
  this.pendingTasks = this.pendingTasks.filter((t2) => t2.subagentId !== subagentId);
13063
+ for (const t2 of orphaned) {
13064
+ const synthetic = {
13065
+ subagentId,
13066
+ taskId: t2.id,
13067
+ status: "stopped",
13068
+ error: {
13069
+ kind: "aborted_by_parent",
13070
+ message: `Subagent "${subagentId}" was removed while task "${t2.id}" was pending`,
13071
+ retryable: false
13072
+ },
13073
+ iterations: 0,
13074
+ toolCalls: 0,
13075
+ durationMs: 0
13076
+ };
13077
+ this.recordCompletion(synthetic);
13078
+ }
12877
13079
  this.fleetBus?.emit({
12878
13080
  subagentId,
12879
13081
  ts: Date.now(),
@@ -12990,7 +13192,7 @@ function providerErrorToSubagentError(err, message, cause) {
12990
13192
 
12991
13193
  // src/execution/parallel-eternal-engine.ts
12992
13194
  function sleep2(ms) {
12993
- return new Promise((resolve9) => setTimeout(resolve9, ms));
13195
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
12994
13196
  }
12995
13197
  var GOAL_COMPLETE_MARKER2 = /^\s*\[goal[_\s-]?complete\]\s*$/im;
12996
13198
  var ParallelEternalEngine = class {
@@ -13488,6 +13690,80 @@ function buildGoalPreamble(goal) {
13488
13690
  // src/coordination/director.ts
13489
13691
  init_atomic_write();
13490
13692
 
13693
+ // src/coordination/large-answer-store.ts
13694
+ var LargeAnswerStore = class {
13695
+ /**
13696
+ * Responses above this size (in characters) are stored out-of-context.
13697
+ * Below this, the full answer is returned inline (no overhead).
13698
+ * Default: 2000 chars ≈ 400-600 tokens.
13699
+ */
13700
+ sizeThreshold;
13701
+ store = /* @__PURE__ */ new Map();
13702
+ constructor(sizeThreshold = 2e3) {
13703
+ this.sizeThreshold = sizeThreshold;
13704
+ }
13705
+ /**
13706
+ * Store a value, returning a summary + key for inline use.
13707
+ * If the value is below sizeThreshold, returns it as-is (no store entry).
13708
+ */
13709
+ storeAnswer(value) {
13710
+ if (value === void 0 || value === null) {
13711
+ return { summary: String(value), inline: true };
13712
+ }
13713
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
13714
+ const size = serialized.length;
13715
+ if (size <= this.sizeThreshold) {
13716
+ return { summary: serialized.slice(0, 500), inline: true };
13717
+ }
13718
+ const key = `a-${hashStr(serialized)}`;
13719
+ this.store.set(key, {
13720
+ key,
13721
+ value,
13722
+ size,
13723
+ storedAt: Date.now()
13724
+ });
13725
+ return {
13726
+ key,
13727
+ summary: `[stored: ${size} chars \u2014 use roll_up or ask_result tool to retrieve, key=${key}]`,
13728
+ inline: false
13729
+ };
13730
+ }
13731
+ /**
13732
+ * Retrieve a previously stored answer by its key.
13733
+ * Returns undefined if the key is unknown or the store was cleared.
13734
+ */
13735
+ retrieveAnswer(key) {
13736
+ return this.store.get(key)?.value;
13737
+ }
13738
+ /**
13739
+ * Check if a key exists in the store.
13740
+ */
13741
+ hasAnswer(key) {
13742
+ return this.store.has(key);
13743
+ }
13744
+ /** Number of stored entries. */
13745
+ get size() {
13746
+ return this.store.size;
13747
+ }
13748
+ /** Total characters stored. */
13749
+ get totalChars() {
13750
+ let total = 0;
13751
+ for (const e of this.store.values()) total += e.size;
13752
+ return total;
13753
+ }
13754
+ /** Clear all stored entries. Call at the end of a director run. */
13755
+ clear() {
13756
+ this.store.clear();
13757
+ }
13758
+ };
13759
+ function hashStr(s) {
13760
+ let h = 5381;
13761
+ for (let i = 0; i < s.length; i++) {
13762
+ h = h * 33 ^ s.charCodeAt(i);
13763
+ }
13764
+ return (h >>> 0).toString(36);
13765
+ }
13766
+
13491
13767
  // src/coordination/director-prompts.ts
13492
13768
  var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
13493
13769
  subagents by spawning them, assigning tasks, awaiting completions, and
@@ -13771,9 +14047,12 @@ function makeSpawnTool(director, roster) {
13771
14047
  provider: { type: "string", description: 'Provider id (e.g. "anthropic", "openai"). Defaults to the leader provider when omitted.' },
13772
14048
  model: { type: "string", description: "Model id within the provider. Defaults to the leader model when omitted." },
13773
14049
  systemPromptOverride: { type: "string", description: "Extra prompt text appended after the role-base prompt." },
13774
- maxIterations: { type: "number" },
13775
- maxToolCalls: { type: "number" },
13776
- maxCostUsd: { type: "number" }
14050
+ maxIterations: { type: "number", minimum: 1 },
14051
+ maxToolCalls: { type: "number", minimum: 1 },
14052
+ maxCostUsd: { type: "number", minimum: 0 },
14053
+ timeoutMs: { type: "number", minimum: 1, description: "Hard wall-clock cap in milliseconds. Defaults to none (idle timeout is the default reaper)." },
14054
+ idleTimeoutMs: { type: "number", minimum: 1, description: "Idle timeout in ms: reap the subagent after this long with no activity. Resets on every iteration/tool call. Default is role/coordinator-specific." },
14055
+ maxTokens: { type: "number", minimum: 1, description: "Maximum total tokens (input + output) the subagent may use." }
13777
14056
  },
13778
14057
  required: []
13779
14058
  };
@@ -13819,6 +14098,9 @@ function makeSpawnTool(director, roster) {
13819
14098
  if (typeof i.maxIterations === "number") cfg.maxIterations = i.maxIterations;
13820
14099
  if (typeof i.maxToolCalls === "number") cfg.maxToolCalls = i.maxToolCalls;
13821
14100
  if (typeof i.maxCostUsd === "number") cfg.maxCostUsd = i.maxCostUsd;
14101
+ if (typeof i.timeoutMs === "number") cfg.timeoutMs = i.timeoutMs;
14102
+ if (typeof i.idleTimeoutMs === "number") cfg.idleTimeoutMs = i.idleTimeoutMs;
14103
+ if (typeof i.maxTokens === "number") cfg.maxTokens = i.maxTokens;
13822
14104
  try {
13823
14105
  const subagentId = await director.spawn(cfg);
13824
14106
  return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name, role: cfg.role };
@@ -13846,10 +14128,10 @@ function makeAssignTool(director) {
13846
14128
  const inputSchema = {
13847
14129
  type: "object",
13848
14130
  properties: {
13849
- subagentId: { type: "string", description: "Target subagent id. Required." },
13850
- description: { type: "string", description: "The task in natural language \u2014 what you want this subagent to do." },
13851
- maxToolCalls: { type: "number", description: "Optional per-task tool-call budget override." },
13852
- timeoutMs: { type: "number", description: "Optional per-task timeout in ms." }
14131
+ subagentId: { type: "string", minLength: 1, description: "Target subagent id. Required." },
14132
+ description: { type: "string", minLength: 1, description: "The task in natural language \u2014 what you want this subagent to do." },
14133
+ maxToolCalls: { type: "number", minimum: 1, description: "Optional per-task tool-call budget override." },
14134
+ timeoutMs: { type: "number", minimum: 1, description: "Optional per-task timeout in ms." }
13853
14135
  },
13854
14136
  required: ["subagentId", "description"]
13855
14137
  };
@@ -13890,9 +14172,9 @@ function makeAskTool(director) {
13890
14172
  inputSchema: {
13891
14173
  type: "object",
13892
14174
  properties: {
13893
- subagentId: { type: "string", description: "Subagent to ask. Must be a previously spawned id." },
13894
- question: { type: "string", description: "The question or instruction." },
13895
- timeoutMs: { type: "number", description: "Optional timeout in ms (default 30s)." }
14175
+ subagentId: { type: "string", minLength: 1, description: "Subagent to ask. Must be a previously spawned id." },
14176
+ question: { type: "string", minLength: 1, description: "The question or instruction." },
14177
+ timeoutMs: { type: "number", minimum: 1, description: "Optional timeout in ms (default 30s)." }
13896
14178
  },
13897
14179
  required: ["subagentId", "question"]
13898
14180
  },
@@ -13900,13 +14182,49 @@ function makeAskTool(director) {
13900
14182
  const i = input;
13901
14183
  try {
13902
14184
  const answer = await director.ask(i.subagentId, { question: i.question }, i.timeoutMs);
13903
- return { ok: true, answer };
14185
+ const stored = director.largeAnswerStore.storeAnswer(answer);
14186
+ if (stored.inline) {
14187
+ return { ok: true, answer: stored.summary };
14188
+ }
14189
+ return {
14190
+ ok: true,
14191
+ answer: stored.summary,
14192
+ _answerKey: stored.key,
14193
+ _hint: "Response was large and stored. Use ask_result with the key to retrieve it."
14194
+ };
13904
14195
  } catch (err) {
13905
14196
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
13906
14197
  }
13907
14198
  }
13908
14199
  };
13909
14200
  }
14201
+ function makeAskResultTool(director) {
14202
+ return {
14203
+ name: "ask_result",
14204
+ description: "Retrieve a large `ask_subagent` response that was stored out-of-context (>2K chars). Returns the full stored value.",
14205
+ permission: "auto",
14206
+ mutating: false,
14207
+ inputSchema: {
14208
+ type: "object",
14209
+ properties: {
14210
+ key: {
14211
+ type: "string",
14212
+ minLength: 1,
14213
+ description: "The `_answerKey` returned by `ask_subagent` for a large response."
14214
+ }
14215
+ },
14216
+ required: ["key"]
14217
+ },
14218
+ async execute(input) {
14219
+ const i = input;
14220
+ const value = director.largeAnswerStore.retrieveAnswer(i.key);
14221
+ if (value === void 0) {
14222
+ return { ok: false, error: `No stored answer found for key "${i.key}" \u2014 it may have been cleared or the key is invalid.` };
14223
+ }
14224
+ return { ok: true, value };
14225
+ }
14226
+ };
14227
+ }
13910
14228
  function makeRollUpTool(director) {
13911
14229
  return {
13912
14230
  name: "roll_up",
@@ -14060,7 +14378,18 @@ function makeCollabDebugTool(director) {
14060
14378
  },
14061
14379
  timeoutMs: {
14062
14380
  type: "number",
14381
+ minimum: 1,
14063
14382
  description: "Timeout in ms. Default: 600000 (10 minutes)."
14383
+ },
14384
+ maxTargetFiles: {
14385
+ type: "number",
14386
+ minimum: 1,
14387
+ description: "Maximum number of files to include in the snapshot. If not set, the limit is computed dynamically from contextWindow or falls back to the default (30)."
14388
+ },
14389
+ contextWindow: {
14390
+ type: "number",
14391
+ minimum: 1,
14392
+ description: "Context window size (tokens) of the model. When provided and maxTargetFiles is not set, the file limit is computed dynamically as floor((contextWindow * 0.4) / 2000)."
14064
14393
  }
14065
14394
  },
14066
14395
  required: ["targetPaths"]
@@ -14072,7 +14401,9 @@ function makeCollabDebugTool(director) {
14072
14401
  }
14073
14402
  const options = {
14074
14403
  targetPaths: i.targetPaths,
14075
- timeoutMs: i.timeoutMs
14404
+ timeoutMs: i.timeoutMs,
14405
+ maxTargetFiles: i.maxTargetFiles,
14406
+ contextWindow: i.contextWindow
14076
14407
  };
14077
14408
  try {
14078
14409
  const report = await director.spawnCollab(options);
@@ -14139,6 +14470,7 @@ function makeWorkCompleteTool(director) {
14139
14470
  }
14140
14471
  };
14141
14472
  }
14473
+ var DEFAULT_MAX_TARGET_FILES = 30;
14142
14474
  var CollabSession = class extends EventEmitter {
14143
14475
  sessionId;
14144
14476
  options;
@@ -14195,11 +14527,36 @@ var CollabSession = class extends EventEmitter {
14195
14527
  getSubagentIds() {
14196
14528
  return new Map(this.subagentIds);
14197
14529
  }
14530
+ /**
14531
+ * Returns the effective file limit for this session.
14532
+ * Priority: explicit `maxTargetFiles` > dynamic from `contextWindow` > `DEFAULT_MAX_TARGET_FILES`.
14533
+ */
14534
+ effectiveFileLimit() {
14535
+ if (this.options.maxTargetFiles !== void 0) {
14536
+ return this.options.maxTargetFiles;
14537
+ }
14538
+ if (this.options.contextWindow !== void 0) {
14539
+ return Math.max(5, Math.floor(this.options.contextWindow * 0.4 / 2e3));
14540
+ }
14541
+ return DEFAULT_MAX_TARGET_FILES;
14542
+ }
14198
14543
  async buildSnapshot() {
14199
14544
  if (this.snapshot.files.length > 0) return this.snapshot;
14200
- for (const filePath of this.options.targetPaths) {
14545
+ const allFiles = [];
14546
+ for (const pattern of this.options.targetPaths) {
14547
+ const expanded = await expandGlob(pattern);
14548
+ allFiles.push(...expanded);
14549
+ }
14550
+ const limit = this.effectiveFileLimit();
14551
+ if (allFiles.length > limit) {
14552
+ const hint = this.options.contextWindow ? `contextWindow=${this.options.contextWindow} \u2192 calculated limit=${limit}` : `default limit=${DEFAULT_MAX_TARGET_FILES}`;
14553
+ throw new Error(
14554
+ `[collab_debug] Target has ${allFiles.length} files, which exceeds the limit (${hint}). Narrow the target or pass maxTargetFiles / contextWindow to override. For large codebases, run package-by-package or module-by-module sessions instead of targeting the entire repo.`
14555
+ );
14556
+ }
14557
+ for (const filePath of allFiles) {
14201
14558
  try {
14202
- const content = await fsp2.readFile(filePath, "utf8");
14559
+ const content = await fsp3.readFile(filePath, "utf8");
14203
14560
  const ext = filePath.split(".").pop() ?? "";
14204
14561
  const language = ext === "ts" || ext === "tsx" ? "typescript" : ext === "js" || ext === "jsx" ? "javascript" : ext === "md" ? "markdown" : ext === "json" ? "json" : void 0;
14205
14562
  this.snapshot.files.push({ path: filePath, content, language });
@@ -14253,7 +14610,7 @@ var CollabSession = class extends EventEmitter {
14253
14610
  reject(new Error(`CollabSession timed out after ${this.timeoutMs}ms`));
14254
14611
  }, this.timeoutMs);
14255
14612
  });
14256
- let results;
14613
+ let results = null;
14257
14614
  try {
14258
14615
  results = await Promise.race([
14259
14616
  Promise.all([
@@ -14684,7 +15041,7 @@ var FleetContextOverflowError = class extends Error {
14684
15041
  this.observed = observed;
14685
15042
  }
14686
15043
  };
14687
- var Director = class {
15044
+ var Director = class _Director {
14688
15045
  /** Alias for the ICoordinator contract. `id` is retained for backward compatibility. */
14689
15046
  get coordinatorId() {
14690
15047
  return this.id;
@@ -14742,6 +15099,8 @@ var Director = class {
14742
15099
  * coordinator already fired the event — `awaitTasks(['t-1'])` after
14743
15100
  * t-1 finished should resolve immediately, not hang. */
14744
15101
  completed = /* @__PURE__ */ new Map();
15102
+ /** Prevents the completed Map from growing unbounded in long-running directors. */
15103
+ static MAX_COMPLETED = 1e4;
14745
15104
  /** Per-subagent provider/model metadata, captured at spawn time so the
14746
15105
  * FleetUsageAggregator's metaLookup can surface readable rows. */
14747
15106
  subagentMeta = /* @__PURE__ */ new Map();
@@ -14821,6 +15180,8 @@ var Director = class {
14821
15180
  _leaderBtwNotes = [];
14822
15181
  /** Active collab sessions tracked by sessionId (see spawnCollab). */
14823
15182
  _activeCollabSessions = /* @__PURE__ */ new Map();
15183
+ /** Prevents large `ask_subagent` answers from bloating the leader's context window. */
15184
+ largeAnswerStore;
14824
15185
  constructor(opts) {
14825
15186
  this.id = opts.config.coordinatorId || randomUUID();
14826
15187
  this.manifestPath = opts.manifestPath;
@@ -14849,7 +15210,7 @@ var Director = class {
14849
15210
  }, opts.checkpointDebounceMs ?? 250) : null;
14850
15211
  this.fleetManager = opts.fleetManager;
14851
15212
  if (this.sharedScratchpadPath) {
14852
- void fsp2.mkdir(this.sharedScratchpadPath, { recursive: true }).catch(
15213
+ void fsp3.mkdir(this.sharedScratchpadPath, { recursive: true }).catch(
14853
15214
  (err) => this.logShutdownError("shared_scratchpad_mkdir", err)
14854
15215
  );
14855
15216
  }
@@ -14881,6 +15242,11 @@ var Director = class {
14881
15242
  this.taskCompletedListener = (payload) => {
14882
15243
  const r = payload.result;
14883
15244
  this.completed.set(r.taskId, r);
15245
+ if (this.completed.size > _Director.MAX_COMPLETED) {
15246
+ const toDelete = this.completed.size - _Director.MAX_COMPLETED;
15247
+ const keys = [...this.completed.keys()].slice(0, toDelete);
15248
+ for (const k of keys) this.completed.delete(k);
15249
+ }
14884
15250
  const waiter = this.taskWaiters.get(r.taskId);
14885
15251
  if (waiter) {
14886
15252
  waiter.resolve(r);
@@ -14987,6 +15353,7 @@ var Director = class {
14987
15353
  payload.extend(extra);
14988
15354
  });
14989
15355
  });
15356
+ this.largeAnswerStore = new LargeAnswerStore(2e3);
14990
15357
  }
14991
15358
  /**
14992
15359
  * Record a granted budget extension and broadcast it on the FleetBus so
@@ -15213,6 +15580,20 @@ var Director = class {
15213
15580
  );
15214
15581
  this.coordinator.setSubagentBridge(result.subagentId, subagentBridge);
15215
15582
  this.subagentBridges.set(result.subagentId, subagentBridge);
15583
+ this.fleet.emit({
15584
+ subagentId: result.subagentId,
15585
+ ts: Date.now(),
15586
+ type: "subagent.spawned",
15587
+ payload: {
15588
+ subagentId: result.subagentId,
15589
+ taskId: "",
15590
+ // taskId will be set when assign() is called
15591
+ name: config.name,
15592
+ role: config.role,
15593
+ provider: config.provider,
15594
+ model: config.model
15595
+ }
15596
+ });
15216
15597
  if (!this.fleetManager) {
15217
15598
  this.manifestEntries.set(result.subagentId, {
15218
15599
  subagentId: result.subagentId,
@@ -15352,7 +15733,7 @@ var Director = class {
15352
15733
  })),
15353
15734
  usage: this.usage.snapshot()
15354
15735
  };
15355
- await fsp2.mkdir(path6.dirname(this.manifestPath), { recursive: true });
15736
+ await fsp3.mkdir(path6.dirname(this.manifestPath), { recursive: true });
15356
15737
  await atomicWrite(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 384 });
15357
15738
  return this.manifestPath;
15358
15739
  }
@@ -15467,11 +15848,11 @@ var Director = class {
15467
15848
  if (cached) return cached;
15468
15849
  const existing = this.taskWaiters.get(id);
15469
15850
  if (existing) return existing.promise;
15470
- let resolve9;
15851
+ let resolve10;
15471
15852
  const promise = new Promise((res) => {
15472
- resolve9 = res;
15853
+ resolve10 = res;
15473
15854
  });
15474
- this.taskWaiters.set(id, { promise, resolve: resolve9 });
15855
+ this.taskWaiters.set(id, { promise, resolve: resolve10 });
15475
15856
  return promise;
15476
15857
  })
15477
15858
  );
@@ -15484,7 +15865,24 @@ var Director = class {
15484
15865
  }
15485
15866
  async remove(subagentId) {
15486
15867
  await this.coordinator.remove(subagentId);
15868
+ const bridge = this.subagentBridges.get(subagentId);
15869
+ if (bridge) {
15870
+ await bridge.stop();
15871
+ this.subagentBridges.delete(subagentId);
15872
+ }
15487
15873
  this.usage.removeSubagent(subagentId);
15874
+ if (this.fleetManager) {
15875
+ this.fleetManager.removeSubagent(subagentId);
15876
+ } else {
15877
+ const entry = this.manifestEntries.get(subagentId);
15878
+ if (entry?.name) {
15879
+ const nicknameKey = entry.name.split(" ")[0].toLowerCase().replace(/[^a-z0-9-]/g, "-");
15880
+ this._usedNicknames.delete(nicknameKey);
15881
+ }
15882
+ }
15883
+ this.manifestEntries.delete(subagentId);
15884
+ this.taskOwners.delete(subagentId);
15885
+ this.taskDescriptions.delete(subagentId);
15488
15886
  }
15489
15887
  status() {
15490
15888
  const base = this.coordinator.getStatus();
@@ -15540,7 +15938,7 @@ var Director = class {
15540
15938
  const filePath = path6.join(this.sessionsRoot, this.directorRunId, `${subagentId}.jsonl`);
15541
15939
  let raw;
15542
15940
  try {
15543
- raw = await fsp2.readFile(filePath, "utf8");
15941
+ raw = await fsp3.readFile(filePath, "utf8");
15544
15942
  } catch {
15545
15943
  return null;
15546
15944
  }
@@ -15646,6 +16044,7 @@ var Director = class {
15646
16044
  makeAssignTool(this),
15647
16045
  makeAwaitTasksTool(this),
15648
16046
  makeAskTool(this),
16047
+ makeAskResultTool(this),
15649
16048
  makeRollUpTool(this),
15650
16049
  makeTerminateTool(this),
15651
16050
  makeTerminateAllTool(this),
@@ -15728,15 +16127,33 @@ function createDelegateTool(opts) {
15728
16127
  },
15729
16128
  timeoutMs: {
15730
16129
  type: "number",
16130
+ minimum: 1,
15731
16131
  description: `Wall-clock budget for this delegate in milliseconds. No hard cap \u2014 set as high as the task realistically needs (a monorepo audit can take hours, a single-file lint takes seconds). Default ${Math.round(defaultTimeoutMs / 1e3 / 60)} minutes.`
15732
16132
  },
15733
16133
  maxIterations: {
15734
16134
  type: "number",
16135
+ minimum: 1,
15735
16136
  description: "Maximum LLM iterations the subagent may take. Unset = use the role/coordinator default. Raise this for tasks with many tool-think-tool cycles (deep code analysis, multi-file refactors)."
15736
16137
  },
15737
16138
  maxToolCalls: {
15738
16139
  type: "number",
16140
+ minimum: 1,
15739
16141
  description: "Maximum number of tool invocations the subagent may make. Unset = use the role/coordinator default. Raise this for tasks that touch many files (large grep + read + report)."
16142
+ },
16143
+ idleTimeoutMs: {
16144
+ type: "number",
16145
+ minimum: 1,
16146
+ description: "Idle timeout in ms: reap the subagent after this long with no activity. Resets on every iteration/tool call. Unset = use the role/coordinator default."
16147
+ },
16148
+ maxTokens: {
16149
+ type: "number",
16150
+ minimum: 1,
16151
+ description: "Maximum total tokens (input + output) the subagent may use. Unset = use the role/coordinator default."
16152
+ },
16153
+ maxCostUsd: {
16154
+ type: "number",
16155
+ minimum: 0,
16156
+ description: "Maximum estimated USD cost the subagent may incur. Unset = use the role/coordinator default."
15740
16157
  }
15741
16158
  },
15742
16159
  required: ["task"]
@@ -15794,12 +16211,21 @@ function createDelegateTool(opts) {
15794
16211
  };
15795
16212
  cfg = applyRosterBudget({ ...cfg, name: i.name });
15796
16213
  }
15797
- if (typeof i.maxIterations === "number" && i.maxIterations > 0) {
16214
+ if (typeof i.maxIterations === "number") {
15798
16215
  cfg.maxIterations = i.maxIterations;
15799
16216
  }
15800
- if (typeof i.maxToolCalls === "number" && i.maxToolCalls > 0) {
16217
+ if (typeof i.maxToolCalls === "number") {
15801
16218
  cfg.maxToolCalls = i.maxToolCalls;
15802
16219
  }
16220
+ if (typeof i.idleTimeoutMs === "number") {
16221
+ cfg.idleTimeoutMs = i.idleTimeoutMs;
16222
+ }
16223
+ if (typeof i.maxTokens === "number") {
16224
+ cfg.maxTokens = i.maxTokens;
16225
+ }
16226
+ if (typeof i.maxCostUsd === "number") {
16227
+ cfg.maxCostUsd = i.maxCostUsd;
16228
+ }
15803
16229
  const SUBAGENT_TIMEOUT_BUFFER_MS = opts.subagentTimeoutBufferMs ?? 6e4;
15804
16230
  if (!cfg.timeoutMs) {
15805
16231
  cfg.timeoutMs = Math.max(3e4, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);
@@ -15811,7 +16237,7 @@ function createDelegateTool(opts) {
15811
16237
  subagentId
15812
16238
  });
15813
16239
  const dir = director;
15814
- const result = await new Promise((resolve9) => {
16240
+ const result = await new Promise((resolve10) => {
15815
16241
  let settled = false;
15816
16242
  let timer;
15817
16243
  const finish = (value) => {
@@ -15821,7 +16247,7 @@ function createDelegateTool(opts) {
15821
16247
  offTool();
15822
16248
  offIter();
15823
16249
  offProgress();
15824
- resolve9(value);
16250
+ resolve10(value);
15825
16251
  };
15826
16252
  const arm = () => {
15827
16253
  if (timer) clearTimeout(timer);
@@ -15968,7 +16394,7 @@ async function readSubagentPartial(opts, subagentId) {
15968
16394
  candidates.push(path6.join(opts.sessionsRoot, opts.directorRunId, `${subagentId}.jsonl`));
15969
16395
  } else {
15970
16396
  try {
15971
- const entries = await fsp2.readdir(opts.sessionsRoot, { withFileTypes: true });
16397
+ const entries = await fsp3.readdir(opts.sessionsRoot, { withFileTypes: true });
15972
16398
  for (const entry of entries) {
15973
16399
  if (entry.isDirectory()) {
15974
16400
  candidates.push(path6.join(opts.sessionsRoot, entry.name, `${subagentId}.jsonl`));
@@ -15981,7 +16407,7 @@ async function readSubagentPartial(opts, subagentId) {
15981
16407
  for (const file of candidates) {
15982
16408
  let raw;
15983
16409
  try {
15984
- raw = await fsp2.readFile(file, "utf8");
16410
+ raw = await fsp3.readFile(file, "utf8");
15985
16411
  } catch {
15986
16412
  continue;
15987
16413
  }
@@ -16150,7 +16576,7 @@ var DefaultModeStore = class {
16150
16576
  async loadActiveMode() {
16151
16577
  try {
16152
16578
  const configPath = path6.join(this.configDir, "mode.json");
16153
- const content = await fsp2.readFile(configPath, "utf8");
16579
+ const content = await fsp3.readFile(configPath, "utf8");
16154
16580
  const data = JSON.parse(content);
16155
16581
  this.activeModeId = data.activeMode ?? null;
16156
16582
  } catch {
@@ -16159,7 +16585,7 @@ var DefaultModeStore = class {
16159
16585
  }
16160
16586
  async saveActiveMode() {
16161
16587
  try {
16162
- await fsp2.mkdir(this.configDir, { recursive: true });
16588
+ await fsp3.mkdir(this.configDir, { recursive: true });
16163
16589
  const configPath = path6.join(this.configDir, "mode.json");
16164
16590
  await atomicWrite(
16165
16591
  configPath,
@@ -16172,13 +16598,13 @@ var DefaultModeStore = class {
16172
16598
  async function loadProjectModes(modesDir) {
16173
16599
  const modes = [];
16174
16600
  try {
16175
- const entries = await fsp2.readdir(modesDir);
16601
+ const entries = await fsp3.readdir(modesDir);
16176
16602
  for (const entry of entries) {
16177
16603
  if (!entry.endsWith(".md") && !entry.endsWith(".txt")) continue;
16178
16604
  const filePath = path6.join(modesDir, entry);
16179
- const stat9 = await fsp2.stat(filePath);
16180
- if (!stat9.isFile()) continue;
16181
- const content = await fsp2.readFile(filePath, "utf8");
16605
+ const stat10 = await fsp3.stat(filePath);
16606
+ if (!stat10.isFile()) continue;
16607
+ const content = await fsp3.readFile(filePath, "utf8");
16182
16608
  const id = path6.basename(entry, path6.extname(entry));
16183
16609
  modes.push({
16184
16610
  id,
@@ -16196,7 +16622,7 @@ async function loadUserModes(modesDir) {
16196
16622
  const modes = [];
16197
16623
  try {
16198
16624
  const manifestPath = path6.join(modesDir, "modes.json");
16199
- const content = await fsp2.readFile(manifestPath, "utf8");
16625
+ const content = await fsp3.readFile(manifestPath, "utf8");
16200
16626
  const manifest = JSON.parse(content);
16201
16627
  for (const mode of manifest.modes) {
16202
16628
  modes.push(mode);
@@ -17052,7 +17478,7 @@ var SpecStore = class {
17052
17478
  }
17053
17479
  async load(id) {
17054
17480
  try {
17055
- const raw = await fsp2.readFile(this.filePath(id), "utf8");
17481
+ const raw = await fsp3.readFile(this.filePath(id), "utf8");
17056
17482
  return JSON.parse(raw);
17057
17483
  } catch {
17058
17484
  return null;
@@ -17064,7 +17490,7 @@ var SpecStore = class {
17064
17490
  }
17065
17491
  async delete(id) {
17066
17492
  try {
17067
- await fsp2.unlink(this.filePath(id));
17493
+ await fsp3.unlink(this.filePath(id));
17068
17494
  await this.removeFromIndex(id);
17069
17495
  return true;
17070
17496
  } catch {
@@ -17073,7 +17499,7 @@ var SpecStore = class {
17073
17499
  }
17074
17500
  async exists(id) {
17075
17501
  try {
17076
- await fsp2.access(this.filePath(id));
17502
+ await fsp3.access(this.filePath(id));
17077
17503
  return true;
17078
17504
  } catch {
17079
17505
  return false;
@@ -17115,7 +17541,7 @@ var SpecStore = class {
17115
17541
  }
17116
17542
  async readIndex() {
17117
17543
  try {
17118
- const raw = await fsp2.readFile(this.indexPath, "utf8");
17544
+ const raw = await fsp3.readFile(this.indexPath, "utf8");
17119
17545
  const parsed = JSON.parse(raw);
17120
17546
  if (parsed?.version === 1) return parsed;
17121
17547
  } catch {
@@ -17178,7 +17604,7 @@ var TaskGraphStore = class {
17178
17604
  }
17179
17605
  async load(id) {
17180
17606
  try {
17181
- const raw = await fsp2.readFile(this.filePath(id), "utf8");
17607
+ const raw = await fsp3.readFile(this.filePath(id), "utf8");
17182
17608
  return graphFromJSON(raw);
17183
17609
  } catch {
17184
17610
  return null;
@@ -17190,7 +17616,7 @@ var TaskGraphStore = class {
17190
17616
  }
17191
17617
  async delete(id) {
17192
17618
  try {
17193
- await fsp2.unlink(this.filePath(id));
17619
+ await fsp3.unlink(this.filePath(id));
17194
17620
  await this.removeFromIndex(id);
17195
17621
  return true;
17196
17622
  } catch {
@@ -17199,7 +17625,7 @@ var TaskGraphStore = class {
17199
17625
  }
17200
17626
  async exists(id) {
17201
17627
  try {
17202
- await fsp2.access(this.filePath(id));
17628
+ await fsp3.access(this.filePath(id));
17203
17629
  return true;
17204
17630
  } catch {
17205
17631
  return false;
@@ -17210,7 +17636,7 @@ var TaskGraphStore = class {
17210
17636
  }
17211
17637
  async readIndex() {
17212
17638
  try {
17213
- const raw = await fsp2.readFile(this.indexPath, "utf8");
17639
+ const raw = await fsp3.readFile(this.indexPath, "utf8");
17214
17640
  const parsed = JSON.parse(raw);
17215
17641
  if (parsed?.version === 1) return parsed;
17216
17642
  } catch {
@@ -17450,10 +17876,10 @@ var AISpecBuilder = class {
17450
17876
  async saveSession() {
17451
17877
  if (!this.sessionPath) return;
17452
17878
  try {
17453
- const fsp19 = await import('fs/promises');
17879
+ const fsp20 = await import('fs/promises');
17454
17880
  const path35 = await import('path');
17455
17881
  const { atomicWrite: atomicWrite2 } = await Promise.resolve().then(() => (init_atomic_write(), atomic_write_exports));
17456
- await fsp19.mkdir(path35.dirname(this.sessionPath), { recursive: true });
17882
+ await fsp20.mkdir(path35.dirname(this.sessionPath), { recursive: true });
17457
17883
  await atomicWrite2(this.sessionPath, JSON.stringify(this.session, null, 2));
17458
17884
  } catch {
17459
17885
  }
@@ -17462,8 +17888,8 @@ var AISpecBuilder = class {
17462
17888
  async loadSession() {
17463
17889
  if (!this.sessionPath) return false;
17464
17890
  try {
17465
- const fsp19 = await import('fs/promises');
17466
- const raw = await fsp19.readFile(this.sessionPath, "utf8");
17891
+ const fsp20 = await import('fs/promises');
17892
+ const raw = await fsp20.readFile(this.sessionPath, "utf8");
17467
17893
  const loaded = JSON.parse(raw);
17468
17894
  if (loaded?.id && loaded?.phase && loaded?.title) {
17469
17895
  this.session = loaded;
@@ -17477,8 +17903,8 @@ var AISpecBuilder = class {
17477
17903
  async deleteSession() {
17478
17904
  if (!this.sessionPath) return;
17479
17905
  try {
17480
- const fsp19 = await import('fs/promises');
17481
- await fsp19.unlink(this.sessionPath);
17906
+ const fsp20 = await import('fs/promises');
17907
+ await fsp20.unlink(this.sessionPath);
17482
17908
  } catch {
17483
17909
  }
17484
17910
  }
@@ -18964,9 +19390,9 @@ var DefaultHealthRegistry = class {
18964
19390
  }
18965
19391
  async runOne(check) {
18966
19392
  let timer = null;
18967
- const timeout = new Promise((resolve9) => {
19393
+ const timeout = new Promise((resolve10) => {
18968
19394
  timer = setTimeout(
18969
- () => resolve9({ status: "unhealthy", detail: `timeout after ${this.timeoutMs}ms` }),
19395
+ () => resolve10({ status: "unhealthy", detail: `timeout after ${this.timeoutMs}ms` }),
18970
19396
  this.timeoutMs
18971
19397
  );
18972
19398
  });
@@ -19205,14 +19631,14 @@ async function startMetricsServer(opts) {
19205
19631
  const { createServer } = await import('http');
19206
19632
  server = createServer(listener);
19207
19633
  }
19208
- await new Promise((resolve9, reject) => {
19634
+ await new Promise((resolve10, reject) => {
19209
19635
  const onError = (err) => {
19210
19636
  server.off("listening", onListening);
19211
19637
  reject(err);
19212
19638
  };
19213
19639
  const onListening = () => {
19214
19640
  server.off("error", onError);
19215
- resolve9();
19641
+ resolve10();
19216
19642
  };
19217
19643
  server.once("error", onError);
19218
19644
  server.once("listening", onListening);
@@ -19224,8 +19650,8 @@ async function startMetricsServer(opts) {
19224
19650
  return {
19225
19651
  port: boundPort,
19226
19652
  url: `${protocol}://${host}:${boundPort}${path35}`,
19227
- close: () => new Promise((resolve9, reject) => {
19228
- server.close((err) => err ? reject(err) : resolve9());
19653
+ close: () => new Promise((resolve10, reject) => {
19654
+ server.close((err) => err ? reject(err) : resolve10());
19229
19655
  })
19230
19656
  };
19231
19657
  }
@@ -19925,7 +20351,7 @@ async function downloadGitHubTarball(parsed) {
19925
20351
  `Tarball too large (${(Number.parseInt(contentLength, 10) / 1024 / 1024).toFixed(1)}MB). Max: ${MAX_TARBALL_SIZE / 1024 / 1024}MB`
19926
20352
  );
19927
20353
  }
19928
- const tempDir = await fsp2.mkdtemp(path6.join(os5.tmpdir(), "wskill-"));
20354
+ const tempDir = await fsp3.mkdtemp(path6.join(os5.tmpdir(), "wskill-"));
19929
20355
  try {
19930
20356
  if (!response.body) {
19931
20357
  throw new Error("Empty response body from GitHub API");
@@ -19942,7 +20368,7 @@ async function downloadGitHubTarball(parsed) {
19942
20368
  await extractTar(tarBuf, tempDir);
19943
20369
  return { tempDir };
19944
20370
  } catch (err) {
19945
- await fsp2.rm(tempDir, { recursive: true, force: true }).catch(() => {
20371
+ await fsp3.rm(tempDir, { recursive: true, force: true }).catch(() => {
19946
20372
  });
19947
20373
  throw err;
19948
20374
  }
@@ -19968,16 +20394,16 @@ async function extractTar(buf, destDir) {
19968
20394
  }
19969
20395
  if (typeflag === 53 || typeflag === 0) {
19970
20396
  if (relPath.endsWith("/") || typeflag === 53) {
19971
- await fsp2.mkdir(destPath, { recursive: true });
20397
+ await fsp3.mkdir(destPath, { recursive: true });
19972
20398
  }
19973
20399
  }
19974
20400
  if ((typeflag === 48 || typeflag === 0 || typeflag === 0) && size > 0) {
19975
20401
  const dir = path6.dirname(destPath);
19976
- await fsp2.mkdir(dir, { recursive: true });
20402
+ await fsp3.mkdir(dir, { recursive: true });
19977
20403
  const dataStart = offset + 512;
19978
20404
  const dataEnd = dataStart + size;
19979
20405
  if (dataEnd > buf.length) break;
19980
- await fsp2.writeFile(destPath, buf.subarray(dataStart, dataEnd));
20406
+ await fsp3.writeFile(destPath, buf.subarray(dataStart, dataEnd));
19981
20407
  }
19982
20408
  }
19983
20409
  offset += 512 + Math.ceil(size / 512) * 512;
@@ -20007,7 +20433,7 @@ var SkillManifestStore = class {
20007
20433
  async read() {
20008
20434
  if (this.cache) return this.cache;
20009
20435
  try {
20010
- const raw = await fsp2.readFile(this.manifestPath, "utf8");
20436
+ const raw = await fsp3.readFile(this.manifestPath, "utf8");
20011
20437
  const data = JSON.parse(raw);
20012
20438
  if (!Array.isArray(data.skills)) {
20013
20439
  this.cache = { skills: [] };
@@ -20021,7 +20447,7 @@ var SkillManifestStore = class {
20021
20447
  }
20022
20448
  async write(data) {
20023
20449
  const dir = path6.dirname(this.manifestPath);
20024
- await fsp2.mkdir(dir, { recursive: true });
20450
+ await fsp3.mkdir(dir, { recursive: true });
20025
20451
  await atomicWrite(this.manifestPath, JSON.stringify(data, null, 2) + "\n");
20026
20452
  this.cache = data;
20027
20453
  }
@@ -20097,7 +20523,7 @@ var SkillInstaller = class {
20097
20523
  await this.removeSkillFiles(skill.name, scope);
20098
20524
  }
20099
20525
  const destDir = path6.join(targetDir, skill.name);
20100
- await fsp2.mkdir(destDir, { recursive: true });
20526
+ await fsp3.mkdir(destDir, { recursive: true });
20101
20527
  const copiedFiles = [];
20102
20528
  for (const file of skill.files) {
20103
20529
  const srcPath = path6.join(skill.baseDir, file);
@@ -20106,14 +20532,14 @@ var SkillInstaller = class {
20106
20532
  if (!resolved.startsWith(path6.resolve(destDir))) {
20107
20533
  throw new Error(`Path traversal detected in skill file: ${file}`);
20108
20534
  }
20109
- const stat9 = await fsp2.stat(srcPath);
20110
- if (stat9.size > MAX_SKILL_FILE_SIZE) {
20535
+ const stat10 = await fsp3.stat(srcPath);
20536
+ if (stat10.size > MAX_SKILL_FILE_SIZE) {
20111
20537
  throw new Error(
20112
- `Skill file "${file}" is too large (${(stat9.size / 1024).toFixed(1)}KB). Max: ${MAX_SKILL_FILE_SIZE / 1024}KB`
20538
+ `Skill file "${file}" is too large (${(stat10.size / 1024).toFixed(1)}KB). Max: ${MAX_SKILL_FILE_SIZE / 1024}KB`
20113
20539
  );
20114
20540
  }
20115
- await fsp2.mkdir(path6.dirname(destPath), { recursive: true });
20116
- await fsp2.copyFile(srcPath, destPath);
20541
+ await fsp3.mkdir(path6.dirname(destPath), { recursive: true });
20542
+ await fsp3.copyFile(srcPath, destPath);
20117
20543
  copiedFiles.push(file);
20118
20544
  }
20119
20545
  const entry = {
@@ -20138,7 +20564,7 @@ var SkillInstaller = class {
20138
20564
  this.invalidateLoaderCache();
20139
20565
  return results;
20140
20566
  } finally {
20141
- await fsp2.rm(tempDir, { recursive: true, force: true }).catch(() => {
20567
+ await fsp3.rm(tempDir, { recursive: true, force: true }).catch(() => {
20142
20568
  });
20143
20569
  }
20144
20570
  }
@@ -20242,31 +20668,31 @@ var SkillInstaller = class {
20242
20668
  * Detect skills in an extracted repository.
20243
20669
  * Returns an array of detected skills with their files.
20244
20670
  */
20245
- async detectSkills(baseDir) {
20671
+ async detectSkills(baseDir2) {
20246
20672
  const results = [];
20247
- const rootSkillMd = path6.join(baseDir, "SKILL.md");
20673
+ const rootSkillMd = path6.join(baseDir2, "SKILL.md");
20248
20674
  try {
20249
- await fsp2.access(rootSkillMd);
20250
- const content = await fsp2.readFile(rootSkillMd, "utf8");
20675
+ await fsp3.access(rootSkillMd);
20676
+ const content = await fsp3.readFile(rootSkillMd, "utf8");
20251
20677
  const meta = parseFrontmatter2(content);
20252
20678
  if (meta.name && meta.description) {
20253
20679
  results.push({
20254
20680
  name: meta.name,
20255
- baseDir,
20681
+ baseDir: baseDir2,
20256
20682
  files: ["SKILL.md"]
20257
20683
  });
20258
20684
  return results;
20259
20685
  }
20260
20686
  } catch {
20261
20687
  }
20262
- const skillsDir = path6.join(baseDir, "skills");
20688
+ const skillsDir = path6.join(baseDir2, "skills");
20263
20689
  try {
20264
- const entries = await fsp2.readdir(skillsDir, { withFileTypes: true });
20690
+ const entries = await fsp3.readdir(skillsDir, { withFileTypes: true });
20265
20691
  for (const entry of entries) {
20266
20692
  if (!entry.isDirectory()) continue;
20267
20693
  const skillFile = path6.join(skillsDir, entry.name, "SKILL.md");
20268
20694
  try {
20269
- const content = await fsp2.readFile(skillFile, "utf8");
20695
+ const content = await fsp3.readFile(skillFile, "utf8");
20270
20696
  const meta = parseFrontmatter2(content);
20271
20697
  if (meta.name && meta.description) {
20272
20698
  const skillDir = path6.join(skillsDir, entry.name);
@@ -20290,7 +20716,7 @@ var SkillInstaller = class {
20290
20716
  async removeSkillFiles(name, scope) {
20291
20717
  const targetDir = scope === "project" ? this.opts.projectSkillsDir : this.opts.globalSkillsDir;
20292
20718
  const skillDir = path6.join(targetDir, name);
20293
- await fsp2.rm(skillDir, { recursive: true, force: true });
20719
+ await fsp3.rm(skillDir, { recursive: true, force: true });
20294
20720
  }
20295
20721
  /**
20296
20722
  * Invalidate the skill loader's cache so newly installed skills appear.
@@ -20338,15 +20764,15 @@ function parseFrontmatter2(raw) {
20338
20764
  flush();
20339
20765
  return out;
20340
20766
  }
20341
- async function collectFiles(dir, baseDir) {
20767
+ async function collectFiles(dir, baseDir2) {
20342
20768
  const results = [];
20343
- const entries = await fsp2.readdir(dir, { withFileTypes: true });
20769
+ const entries = await fsp3.readdir(dir, { withFileTypes: true });
20344
20770
  for (const entry of entries) {
20345
20771
  const fullPath = path6.join(dir, entry.name);
20346
- const relPath = path6.relative(baseDir, fullPath);
20772
+ const relPath = path6.relative(baseDir2, fullPath);
20347
20773
  if (entry.isDirectory()) {
20348
20774
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
20349
- results.push(...await collectFiles(fullPath, baseDir));
20775
+ results.push(...await collectFiles(fullPath, baseDir2));
20350
20776
  } else {
20351
20777
  results.push(relPath);
20352
20778
  }
@@ -20468,7 +20894,7 @@ var AnnotationsStore = class {
20468
20894
  async readFile(sessionId) {
20469
20895
  const fp = this.filePath(sessionId);
20470
20896
  try {
20471
- const raw = await fsp2.readFile(fp, "utf8");
20897
+ const raw = await fsp3.readFile(fp, "utf8");
20472
20898
  const parsed = JSON.parse(raw);
20473
20899
  if (parsed.version !== FILE_VERSION) {
20474
20900
  return { version: FILE_VERSION, annotations: [] };
@@ -20568,7 +20994,7 @@ var ReplayLogStore = class {
20568
20994
  if (count > this.maxEntries) {
20569
20995
  await this.compact(input.sessionId, cache);
20570
20996
  } else {
20571
- await fsp2.appendFile(this.filePath(input.sessionId), JSON.stringify(entry) + "\n", "utf8");
20997
+ await fsp3.appendFile(this.filePath(input.sessionId), JSON.stringify(entry) + "\n", "utf8");
20572
20998
  this.diskCount.set(input.sessionId, count);
20573
20999
  }
20574
21000
  });
@@ -20610,7 +21036,7 @@ var ReplayLogStore = class {
20610
21036
  async list() {
20611
21037
  let entries;
20612
21038
  try {
20613
- entries = await fsp2.readdir(this.dir);
21039
+ entries = await fsp3.readdir(this.dir);
20614
21040
  } catch (err) {
20615
21041
  if (err.code === "ENOENT") return [];
20616
21042
  return [];
@@ -20638,7 +21064,7 @@ var ReplayLogStore = class {
20638
21064
  async readAll(sessionId) {
20639
21065
  const fp = this.filePath(sessionId);
20640
21066
  try {
20641
- const raw = await fsp2.readFile(fp, "utf8");
21067
+ const raw = await fsp3.readFile(fp, "utf8");
20642
21068
  const out = [];
20643
21069
  for (const line of raw.split("\n")) {
20644
21070
  if (!line.trim()) continue;
@@ -20701,19 +21127,19 @@ var SessionRecovery = class {
20701
21127
  async detectStale(sessionId) {
20702
21128
  const fp = this.filePath(sessionId);
20703
21129
  const TAIL_SIZE = 8192;
20704
- let stat9;
21130
+ let stat10;
20705
21131
  try {
20706
- stat9 = await fsp2.stat(fp);
21132
+ stat10 = await fsp3.stat(fp);
20707
21133
  } catch (err) {
20708
21134
  if (err.code === "ENOENT") return null;
20709
21135
  return null;
20710
21136
  }
20711
- if (stat9.size === 0) return null;
20712
- const position = Math.max(0, stat9.size - TAIL_SIZE);
21137
+ if (stat10.size === 0) return null;
21138
+ const position = Math.max(0, stat10.size - TAIL_SIZE);
20713
21139
  const buf = Buffer.alloc(TAIL_SIZE);
20714
21140
  let fh;
20715
21141
  try {
20716
- fh = await fsp2.open(fp, "r");
21142
+ fh = await fsp3.open(fp, "r");
20717
21143
  const { bytesRead } = await fh.read(buf, 0, TAIL_SIZE, position);
20718
21144
  let eventCount = 0;
20719
21145
  const raw = buf.subarray(0, bytesRead).toString("utf8");
@@ -20759,7 +21185,7 @@ var SessionRecovery = class {
20759
21185
  const fp = this.filePath(sessionId);
20760
21186
  let raw;
20761
21187
  try {
20762
- raw = await fsp2.readFile(fp, "utf8");
21188
+ raw = await fsp3.readFile(fp, "utf8");
20763
21189
  } catch (err) {
20764
21190
  if (err.code === "ENOENT") return null;
20765
21191
  return null;
@@ -20802,7 +21228,7 @@ var SessionRecovery = class {
20802
21228
  async listResumable() {
20803
21229
  let entries;
20804
21230
  try {
20805
- entries = await fsp2.readdir(this.dir);
21231
+ entries = await fsp3.readdir(this.dir);
20806
21232
  } catch (err) {
20807
21233
  if (err.code === "ENOENT") return [];
20808
21234
  return [];
@@ -20945,7 +21371,7 @@ var ToolAuditLog = class {
20945
21371
  async readAll(sessionId) {
20946
21372
  const fp = this.filePath(sessionId);
20947
21373
  try {
20948
- const raw = await fsp2.readFile(fp, "utf8");
21374
+ const raw = await fsp3.readFile(fp, "utf8");
20949
21375
  const out = [];
20950
21376
  for (const line of raw.split("\n")) {
20951
21377
  if (!line.trim()) continue;
@@ -20963,7 +21389,7 @@ var ToolAuditLog = class {
20963
21389
  async appendLine(sessionId, entry) {
20964
21390
  const fp = this.filePath(sessionId);
20965
21391
  const line = JSON.stringify(entry) + "\n";
20966
- await fsp2.appendFile(fp, line, "utf8");
21392
+ await fsp3.appendFile(fp, line, "utf8");
20967
21393
  const count = (this.unSyncedWrites.get(sessionId) ?? 0) + 1;
20968
21394
  this.unSyncedWrites.set(sessionId, count);
20969
21395
  if (this.fsyncEvery !== Infinity && count % this.fsyncEvery === 0) {
@@ -20980,7 +21406,7 @@ var ToolAuditLog = class {
20980
21406
  }
20981
21407
  async sync(sessionId, fp) {
20982
21408
  try {
20983
- const fh = await fsp2.open(fp, "r+");
21409
+ const fh = await fsp3.open(fp, "r+");
20984
21410
  try {
20985
21411
  await fh.sync();
20986
21412
  } finally {
@@ -21028,7 +21454,7 @@ var DefaultSessionRewinder = class {
21028
21454
  projectRoot;
21029
21455
  async listCheckpoints(sessionId) {
21030
21456
  const file = path6.join(this.sessionsDir, `${sessionId}.jsonl`);
21031
- const raw = await fsp2.readFile(file, "utf8");
21457
+ const raw = await fsp3.readFile(file, "utf8");
21032
21458
  const events = parseEvents(raw);
21033
21459
  const fileCountMap = /* @__PURE__ */ new Map();
21034
21460
  for (const event of events) {
@@ -21053,7 +21479,7 @@ var DefaultSessionRewinder = class {
21053
21479
  }
21054
21480
  async rewindToCheckpoint(sessionId, checkpointIndex) {
21055
21481
  const file = path6.join(this.sessionsDir, `${sessionId}.jsonl`);
21056
- const raw = await fsp2.readFile(file, "utf8");
21482
+ const raw = await fsp3.readFile(file, "utf8");
21057
21483
  const events = parseEvents(raw);
21058
21484
  let targetIdx = -1;
21059
21485
  for (let i = 0; i < events.length; i++) {
@@ -21088,7 +21514,7 @@ var DefaultSessionRewinder = class {
21088
21514
  }
21089
21515
  async rewindLastN(sessionId, n) {
21090
21516
  const file = path6.join(this.sessionsDir, `${sessionId}.jsonl`);
21091
- const raw = await fsp2.readFile(file, "utf8");
21517
+ const raw = await fsp3.readFile(file, "utf8");
21092
21518
  const events = parseEvents(raw);
21093
21519
  const checkpoints = [];
21094
21520
  for (const event of events) {
@@ -21117,7 +21543,7 @@ var DefaultSessionRewinder = class {
21117
21543
  }
21118
21544
  async rewindToStart(sessionId) {
21119
21545
  const file = path6.join(this.sessionsDir, `${sessionId}.jsonl`);
21120
- const raw = await fsp2.readFile(file, "utf8");
21546
+ const raw = await fsp3.readFile(file, "utf8");
21121
21547
  const events = parseEvents(raw);
21122
21548
  const allSnapshots = [];
21123
21549
  for (const event of events) {
@@ -21165,7 +21591,7 @@ async function revertSnapshots(snapshots, projectRoot) {
21165
21591
  revertedFiles.push(file.path);
21166
21592
  }
21167
21593
  } else if (file.action === "created") {
21168
- await fsp2.unlink(file.path);
21594
+ await fsp3.unlink(file.path);
21169
21595
  revertedFiles.push(file.path);
21170
21596
  } else if (file.action === "modified") {
21171
21597
  if (file.before !== null) {
@@ -21192,12 +21618,12 @@ var DefaultPromptStore = class {
21192
21618
  await ensureDir(this.dir);
21193
21619
  const entries = [];
21194
21620
  try {
21195
- const files = await fsp2.readdir(this.dir);
21621
+ const files = await fsp3.readdir(this.dir);
21196
21622
  for (const file of files) {
21197
21623
  if (!file.endsWith(".json")) continue;
21198
21624
  try {
21199
21625
  const raw = JSON.parse(
21200
- await fsp2.readFile(path6.join(this.dir, file), "utf8")
21626
+ await fsp3.readFile(path6.join(this.dir, file), "utf8")
21201
21627
  );
21202
21628
  entries.push(raw.entry);
21203
21629
  } catch {
@@ -21212,7 +21638,7 @@ var DefaultPromptStore = class {
21212
21638
  async get(id) {
21213
21639
  const file = path6.join(this.dir, `${id}.json`);
21214
21640
  try {
21215
- const raw = JSON.parse(await fsp2.readFile(file, "utf8"));
21641
+ const raw = JSON.parse(await fsp3.readFile(file, "utf8"));
21216
21642
  return raw.entry;
21217
21643
  } catch {
21218
21644
  return null;
@@ -21227,7 +21653,7 @@ var DefaultPromptStore = class {
21227
21653
  async delete(id) {
21228
21654
  const file = path6.join(this.dir, `${id}.json`);
21229
21655
  try {
21230
- await fsp2.unlink(file);
21656
+ await fsp3.unlink(file);
21231
21657
  return true;
21232
21658
  } catch {
21233
21659
  return false;
@@ -21334,7 +21760,7 @@ var CloudSync = class {
21334
21760
  lastSyncedAt: (/* @__PURE__ */ new Date()).toISOString(),
21335
21761
  localRev: rev
21336
21762
  };
21337
- await fsp2.writeFile(this.statePath, JSON.stringify(syncState, null, 2), "utf8");
21763
+ await fsp3.writeFile(this.statePath, JSON.stringify(syncState, null, 2), "utf8");
21338
21764
  this.state = syncState;
21339
21765
  return {
21340
21766
  ok: true,
@@ -21366,8 +21792,8 @@ var CloudSync = class {
21366
21792
  const rel = segments.slice(2).join("/");
21367
21793
  const destPath = rel ? path6.join(localPath, rel) : localPath;
21368
21794
  const blobData = await this.getBlob(token, owner, repoName, entry.sha);
21369
- await fsp2.mkdir(path6.dirname(destPath), { recursive: true });
21370
- await fsp2.writeFile(destPath, Buffer.from(blobData, "base64"));
21795
+ await fsp3.mkdir(path6.dirname(destPath), { recursive: true });
21796
+ await fsp3.writeFile(destPath, Buffer.from(blobData, "base64"));
21371
21797
  }
21372
21798
  const localRev = await this.hashLocalCategories(cfg.categories);
21373
21799
  const syncState = {
@@ -21376,7 +21802,7 @@ var CloudSync = class {
21376
21802
  lastSyncedAt: (/* @__PURE__ */ new Date()).toISOString(),
21377
21803
  localRev
21378
21804
  };
21379
- await fsp2.writeFile(this.statePath, JSON.stringify(syncState, null, 2), "utf8");
21805
+ await fsp3.writeFile(this.statePath, JSON.stringify(syncState, null, 2), "utf8");
21380
21806
  this.state = syncState;
21381
21807
  return {
21382
21808
  ok: true,
@@ -21395,7 +21821,7 @@ var CloudSync = class {
21395
21821
  }
21396
21822
  async loadState() {
21397
21823
  try {
21398
- const raw = await fsp2.readFile(this.statePath, "utf8");
21824
+ const raw = await fsp3.readFile(this.statePath, "utf8");
21399
21825
  this.state = JSON.parse(raw);
21400
21826
  } catch {
21401
21827
  this.state = null;
@@ -21466,17 +21892,17 @@ var CloudSync = class {
21466
21892
  const localPath = this.categoryToPath(cat);
21467
21893
  if (!localPath) continue;
21468
21894
  try {
21469
- const stat9 = await fsp2.stat(localPath);
21470
- if (stat9.isDirectory()) {
21895
+ const stat10 = await fsp3.stat(localPath);
21896
+ if (stat10.isDirectory()) {
21471
21897
  const files = await this.walkDir(localPath, localPath);
21472
21898
  for (const file of files) {
21473
- const content = await fsp2.readFile(file, "utf8");
21899
+ const content = await fsp3.readFile(file, "utf8");
21474
21900
  const rel = path6.relative(localPath, file).replace(/\\/g, "/");
21475
21901
  entries.push({ path: `data/${cat}/${rel}`, content, mode: "100644" });
21476
21902
  hashes.push(content);
21477
21903
  }
21478
21904
  } else {
21479
- const content = await fsp2.readFile(localPath, "utf8");
21905
+ const content = await fsp3.readFile(localPath, "utf8");
21480
21906
  entries.push({ path: `data/${cat}`, content, mode: "100644" });
21481
21907
  hashes.push(content);
21482
21908
  }
@@ -21492,15 +21918,15 @@ var CloudSync = class {
21492
21918
  const localPath = this.categoryToPath(cat);
21493
21919
  if (!localPath) continue;
21494
21920
  try {
21495
- const stat9 = await fsp2.stat(localPath);
21496
- if (stat9.isDirectory()) {
21921
+ const stat10 = await fsp3.stat(localPath);
21922
+ if (stat10.isDirectory()) {
21497
21923
  const files = await this.walkDir(localPath, localPath);
21498
21924
  for (const file of files) {
21499
- const content = await fsp2.readFile(file);
21925
+ const content = await fsp3.readFile(file);
21500
21926
  hashes.push(content.toString("base64") + file);
21501
21927
  }
21502
21928
  } else {
21503
- const content = await fsp2.readFile(localPath);
21929
+ const content = await fsp3.readFile(localPath);
21504
21930
  hashes.push(content.toString("base64") + localPath);
21505
21931
  }
21506
21932
  } catch {
@@ -21526,7 +21952,7 @@ var CloudSync = class {
21526
21952
  }
21527
21953
  async walkDir(dir, base) {
21528
21954
  const results = [];
21529
- const entries = await fsp2.readdir(dir, { withFileTypes: true });
21955
+ const entries = await fsp3.readdir(dir, { withFileTypes: true });
21530
21956
  for (const entry of entries) {
21531
21957
  const full = path6.join(dir, entry.name);
21532
21958
  if (entry.isDirectory()) {
@@ -22701,7 +23127,7 @@ var SecurityScannerOrchestrator = class {
22701
23127
  const delay = Math.round(policy.delayMs(attempt));
22702
23128
  const status = isProviderErr ? err.status : 0;
22703
23129
  console.warn(`[SecurityScanner] retry ${attempt + 1} after ${delay}ms (status=${status}) \u2014 ${errAsErr.message}`);
22704
- await new Promise((resolve9) => setTimeout(resolve9, delay));
23130
+ await new Promise((resolve10) => setTimeout(resolve10, delay));
22705
23131
  return this.completeWithRetry(provider, request, abortController, attempt + 1);
22706
23132
  }
22707
23133
  }
@@ -23626,7 +24052,7 @@ var FleetManager = class {
23626
24052
  })),
23627
24053
  usage: this.usage.snapshot()
23628
24054
  };
23629
- await fsp2.mkdir(path6.dirname(this.manifestPath), { recursive: true });
24055
+ await fsp3.mkdir(path6.dirname(this.manifestPath), { recursive: true });
23630
24056
  await atomicWrite(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 384 });
23631
24057
  return this.manifestPath;
23632
24058
  }
@@ -23736,6 +24162,23 @@ var FleetManager = class {
23736
24162
  }));
23737
24163
  return { pending, live: [] };
23738
24164
  }
24165
+ /**
24166
+ * Clean up all fleet-manager state associated with a removed subagent:
24167
+ * - Frees the nickname slot so the same name can be reused
24168
+ * - Removes any pending tasks for this subagent
24169
+ */
24170
+ removeSubagent(subagentId) {
24171
+ const entry = this.manifestEntries.get(subagentId);
24172
+ if (entry?.name) {
24173
+ const nicknameKey = entry.name.split(" ")[0].toLowerCase().replace(/[^a-z0-9-]/g, "-");
24174
+ this._usedNicknames.delete(nicknameKey);
24175
+ }
24176
+ for (const [taskId, task] of this.pendingTasks) {
24177
+ if (task.subagentId === subagentId) {
24178
+ this.pendingTasks.delete(taskId);
24179
+ }
24180
+ }
24181
+ }
23739
24182
  /** Release all resources: clear the manifest debounce timer and dispose the usage aggregator. */
23740
24183
  dispose() {
23741
24184
  if (this.manifestTimer) {
@@ -23923,7 +24366,7 @@ async function runRestart(name, deps) {
23923
24366
  }
23924
24367
  async function readConfig(p) {
23925
24368
  try {
23926
- return JSON.parse(await fsp2.readFile(p, "utf8"));
24369
+ return JSON.parse(await fsp3.readFile(p, "utf8"));
23927
24370
  } catch {
23928
24371
  return {};
23929
24372
  }
@@ -23931,8 +24374,8 @@ async function readConfig(p) {
23931
24374
  async function writeConfig(p, cfg) {
23932
24375
  const raw = JSON.stringify(cfg, null, 2);
23933
24376
  const tmp = p + ".tmp";
23934
- await fsp2.writeFile(tmp, raw, "utf8");
23935
- await fsp2.rename(tmp, p);
24377
+ await fsp3.writeFile(tmp, raw, "utf8");
24378
+ await fsp3.rename(tmp, p);
23936
24379
  }
23937
24380
  function bold(s) {
23938
24381
  return `\x1B[1m${s}\x1B[0m`;
@@ -24255,12 +24698,12 @@ function makeContinueToNextIterationTool() {
24255
24698
  // src/core/iteration-limit.ts
24256
24699
  function requestLimitExtension(opts) {
24257
24700
  const { events, currentIterations, currentLimit, autoExtend, timeoutMs = 3e4 } = opts;
24258
- return new Promise((resolve9) => {
24701
+ return new Promise((resolve10) => {
24259
24702
  let resolved = false;
24260
24703
  const timerFired = () => {
24261
24704
  if (!resolved) {
24262
24705
  resolved = true;
24263
- resolve9(0);
24706
+ resolve10(0);
24264
24707
  }
24265
24708
  };
24266
24709
  const timer = setTimeout(timerFired, timeoutMs);
@@ -24269,14 +24712,14 @@ function requestLimitExtension(opts) {
24269
24712
  if (!resolved) {
24270
24713
  resolved = true;
24271
24714
  clearTimeout(timer);
24272
- resolve9(0);
24715
+ resolve10(0);
24273
24716
  }
24274
24717
  };
24275
24718
  const grant = (extra) => {
24276
24719
  if (!resolved) {
24277
24720
  resolved = true;
24278
24721
  clearTimeout(timer);
24279
- resolve9(Math.max(0, extra));
24722
+ resolve10(Math.max(0, extra));
24280
24723
  }
24281
24724
  };
24282
24725
  events.emit("iteration.limit_reached", {
@@ -24290,7 +24733,7 @@ function requestLimitExtension(opts) {
24290
24733
  if (!resolved) {
24291
24734
  resolved = true;
24292
24735
  clearTimeout(timer);
24293
- resolve9(100);
24736
+ resolve10(100);
24294
24737
  }
24295
24738
  });
24296
24739
  }
@@ -24526,6 +24969,8 @@ var Agent = class {
24526
24969
  let res;
24527
24970
  try {
24528
24971
  res = await customRunner(this.ctx, req);
24972
+ const calibratedEstimate = estimateRequestTokensCalibrated(req.messages, req.system, req.tools ?? []).total;
24973
+ recordActualUsage(res.usage.input, calibratedEstimate);
24529
24974
  recoveryRetries = 0;
24530
24975
  } catch (err) {
24531
24976
  if (controller.signal.aborted) {
@@ -24880,13 +25325,13 @@ var Agent = class {
24880
25325
  }
24881
25326
  }
24882
25327
  waitForConfirm(info) {
24883
- return new Promise((resolve9) => {
25328
+ return new Promise((resolve10) => {
24884
25329
  this.events.emit("tool.confirm_needed", {
24885
25330
  tool: info.tool,
24886
25331
  input: info.input,
24887
25332
  toolUseId: info.toolUseId,
24888
25333
  suggestedPattern: info.suggestedPattern,
24889
- resolve: resolve9
25334
+ resolve: resolve10
24890
25335
  });
24891
25336
  });
24892
25337
  }
@@ -25425,7 +25870,7 @@ var DefaultSystemPromptBuilder = class {
25425
25870
  if (!planPath) return "";
25426
25871
  let raw;
25427
25872
  try {
25428
- raw = await fsp2.readFile(planPath, "utf8");
25873
+ raw = await fsp3.readFile(planPath, "utf8");
25429
25874
  } catch {
25430
25875
  return "";
25431
25876
  }
@@ -25653,19 +26098,19 @@ ${mem}`);
25653
26098
  }
25654
26099
  async dirExists(p) {
25655
26100
  try {
25656
- const stat9 = await fsp2.stat(p);
25657
- return stat9.isDirectory();
26101
+ const stat10 = await fsp3.stat(p);
26102
+ return stat10.isDirectory();
25658
26103
  } catch {
25659
26104
  return false;
25660
26105
  }
25661
26106
  }
25662
26107
  async gitStatus(root) {
25663
- return new Promise((resolve9) => {
26108
+ return new Promise((resolve10) => {
25664
26109
  let settled = false;
25665
26110
  const finish = (s) => {
25666
26111
  if (settled) return;
25667
26112
  settled = true;
25668
- resolve9(s);
26113
+ resolve10(s);
25669
26114
  };
25670
26115
  let proc;
25671
26116
  const timer = setTimeout(() => {
@@ -25720,7 +26165,7 @@ ${mem}`);
25720
26165
  const hits = await Promise.all(
25721
26166
  checks.map(async ([marker, lang]) => {
25722
26167
  try {
25723
- await fsp2.access(path6.join(root, marker));
26168
+ await fsp3.access(path6.join(root, marker));
25724
26169
  return lang;
25725
26170
  } catch {
25726
26171
  return null;
@@ -27069,7 +27514,7 @@ var PhaseOrchestrator = class {
27069
27514
  };
27070
27515
  }
27071
27516
  delay(ms) {
27072
- return new Promise((resolve9) => setTimeout(resolve9, ms));
27517
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
27073
27518
  }
27074
27519
  };
27075
27520
 
@@ -27388,14 +27833,14 @@ var PhaseStore = class {
27388
27833
  }
27389
27834
  async save(graph) {
27390
27835
  const filePath = this.getFilePath(graph.id);
27391
- await fsp2.mkdir(path6.dirname(filePath), { recursive: true });
27836
+ await fsp3.mkdir(path6.dirname(filePath), { recursive: true });
27392
27837
  const serialized = this.serializeGraph(graph);
27393
- await fsp2.writeFile(filePath, JSON.stringify(serialized, null, 2), "utf8");
27838
+ await fsp3.writeFile(filePath, JSON.stringify(serialized, null, 2), "utf8");
27394
27839
  }
27395
27840
  async load(graphId) {
27396
27841
  const filePath = this.getFilePath(graphId);
27397
27842
  try {
27398
- const raw = await fsp2.readFile(filePath, "utf8");
27843
+ const raw = await fsp3.readFile(filePath, "utf8");
27399
27844
  const serialized = JSON.parse(raw);
27400
27845
  return this.deserializeGraph(serialized);
27401
27846
  } catch {
@@ -27405,18 +27850,18 @@ var PhaseStore = class {
27405
27850
  async delete(graphId) {
27406
27851
  const filePath = this.getFilePath(graphId);
27407
27852
  try {
27408
- await fsp2.unlink(filePath);
27853
+ await fsp3.unlink(filePath);
27409
27854
  } catch {
27410
27855
  }
27411
27856
  }
27412
27857
  async list() {
27413
27858
  try {
27414
- const entries = await fsp2.readdir(this.baseDir, { withFileTypes: true });
27859
+ const entries = await fsp3.readdir(this.baseDir, { withFileTypes: true });
27415
27860
  const graphs = [];
27416
27861
  for (const entry of entries) {
27417
27862
  if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
27418
27863
  try {
27419
- const raw = await fsp2.readFile(path6.join(this.baseDir, entry.name), "utf8");
27864
+ const raw = await fsp3.readFile(path6.join(this.baseDir, entry.name), "utf8");
27420
27865
  const serialized = JSON.parse(raw);
27421
27866
  const done = serialized.completedPhaseIds.length;
27422
27867
  const total = serialized.phases.length;
@@ -27562,7 +28007,7 @@ var CheckpointManager = class {
27562
28007
  this.baseDir = opts.baseDir ?? path6.join(opts.store.baseDir, ".checkpoints");
27563
28008
  }
27564
28009
  async initialize() {
27565
- await fsp2.mkdir(this.baseDir, { recursive: true });
28010
+ await fsp3.mkdir(this.baseDir, { recursive: true });
27566
28011
  await this.loadFromDisk();
27567
28012
  }
27568
28013
  async saveCheckpoint(graph, label) {
@@ -27625,14 +28070,14 @@ var CheckpointManager = class {
27625
28070
  return true;
27626
28071
  }
27627
28072
  async saveToDisk(checkpoint) {
27628
- await fsp2.mkdir(this.baseDir, { recursive: true });
28073
+ await fsp3.mkdir(this.baseDir, { recursive: true });
27629
28074
  const filePath = path6.join(this.baseDir, `${checkpoint.graphId}.json`);
27630
28075
  const serialized = {
27631
28076
  ...checkpoint
27632
28077
  };
27633
28078
  let existing = [];
27634
28079
  try {
27635
- const raw = await fsp2.readFile(filePath, "utf8");
28080
+ const raw = await fsp3.readFile(filePath, "utf8");
27636
28081
  const parsed = JSON.parse(raw);
27637
28082
  if (Array.isArray(parsed)) {
27638
28083
  existing = parsed;
@@ -27640,12 +28085,12 @@ var CheckpointManager = class {
27640
28085
  } catch {
27641
28086
  }
27642
28087
  existing.push(serialized);
27643
- await fsp2.writeFile(filePath, JSON.stringify(existing, null, 2), "utf8");
28088
+ await fsp3.writeFile(filePath, JSON.stringify(existing, null, 2), "utf8");
27644
28089
  }
27645
28090
  async deleteFromDisk(checkpointId) {
27646
28091
  let entries;
27647
28092
  try {
27648
- entries = await fsp2.readdir(this.baseDir);
28093
+ entries = await fsp3.readdir(this.baseDir);
27649
28094
  } catch {
27650
28095
  return;
27651
28096
  }
@@ -27653,16 +28098,16 @@ var CheckpointManager = class {
27653
28098
  if (!filename.endsWith(".json")) continue;
27654
28099
  const filePath = path6.join(this.baseDir, filename);
27655
28100
  try {
27656
- const raw = await fsp2.readFile(filePath, "utf8");
28101
+ const raw = await fsp3.readFile(filePath, "utf8");
27657
28102
  const parsed = JSON.parse(raw);
27658
28103
  if (!Array.isArray(parsed)) continue;
27659
28104
  const existing = parsed;
27660
28105
  const filtered = existing.filter((c) => c.id !== checkpointId);
27661
28106
  if (filtered.length !== existing.length) {
27662
28107
  if (filtered.length === 0) {
27663
- await fsp2.unlink(filePath);
28108
+ await fsp3.unlink(filePath);
27664
28109
  } else {
27665
- await fsp2.writeFile(filePath, JSON.stringify(filtered, null, 2), "utf8");
28110
+ await fsp3.writeFile(filePath, JSON.stringify(filtered, null, 2), "utf8");
27666
28111
  }
27667
28112
  }
27668
28113
  } catch {
@@ -27672,7 +28117,7 @@ var CheckpointManager = class {
27672
28117
  async loadFromDisk() {
27673
28118
  let entries;
27674
28119
  try {
27675
- entries = await fsp2.readdir(this.baseDir);
28120
+ entries = await fsp3.readdir(this.baseDir);
27676
28121
  } catch {
27677
28122
  return;
27678
28123
  }
@@ -27680,7 +28125,7 @@ var CheckpointManager = class {
27680
28125
  if (!filename.endsWith(".json")) continue;
27681
28126
  const filePath = path6.join(this.baseDir, filename);
27682
28127
  try {
27683
- const raw = await fsp2.readFile(filePath, "utf8");
28128
+ const raw = await fsp3.readFile(filePath, "utf8");
27684
28129
  const parsed = JSON.parse(raw);
27685
28130
  if (!Array.isArray(parsed)) continue;
27686
28131
  const checkpoints = parsed;
@@ -28029,8 +28474,8 @@ var CollaborationBus = class {
28029
28474
  if (this.isPaused()) return false;
28030
28475
  this.pausedAtMs = Date.now();
28031
28476
  this.pausedBy = byParticipant;
28032
- this.pausePromise = new Promise((resolve9) => {
28033
- this.pauseResolve = resolve9;
28477
+ this.pausePromise = new Promise((resolve10) => {
28478
+ this.pauseResolve = resolve10;
28034
28479
  });
28035
28480
  return true;
28036
28481
  }
@@ -28066,8 +28511,8 @@ var CollaborationBus = class {
28066
28511
  return true;
28067
28512
  }
28068
28513
  let timer;
28069
- const timeoutPromise = new Promise((resolve9) => {
28070
- timer = setTimeout(() => resolve9("timeout"), timeoutMs);
28514
+ const timeoutPromise = new Promise((resolve10) => {
28515
+ timer = setTimeout(() => resolve10("timeout"), timeoutMs);
28071
28516
  });
28072
28517
  const resumedPromise = this.pausePromise.then(() => "resumed");
28073
28518
  const winner = await Promise.race([resumedPromise, timeoutPromise]);
@@ -28558,7 +29003,7 @@ function createGitPlugin() {
28558
29003
  }
28559
29004
  async function runGit(args, cwd) {
28560
29005
  try {
28561
- return await new Promise((resolve9, reject) => {
29006
+ return await new Promise((resolve10, reject) => {
28562
29007
  const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
28563
29008
  let stdout = "";
28564
29009
  let stderr = "";
@@ -28579,7 +29024,7 @@ async function runGit(args, cwd) {
28579
29024
  })
28580
29025
  );
28581
29026
  });
28582
- child.on("close", (code) => resolve9({ stdout, stderr, code: code ?? 0 }));
29027
+ child.on("close", (code) => resolve10({ stdout, stderr, code: code ?? 0 }));
28583
29028
  });
28584
29029
  } catch (err) {
28585
29030
  if (err instanceof WrongStackError) throw err;
@@ -29255,6 +29700,6 @@ ${formatPlan(updated)}`
29255
29700
  };
29256
29701
  }
29257
29702
 
29258
- export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, CheckpointManager, CloudSync, CollaborationBus, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolError, ToolExecutor, ToolRegistry, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, assertSafePath, atomicWrite, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildBtwBlock, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, consumeBtwNotes, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createMcpControlTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createSyncPlugin, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, dispatchAgent, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, ensureDir, estimateRequestTokens, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, extractRunEnv, filesystemServer, findCriticalPath, formatContextWindowModeList, formatGoal, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getContextWindowMode, getPlanTemplate, getTemplate, githubServer, goalFilePath, googleMapsServer, hashRequest, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isPluginError, isSessionError, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeRollUpTool, makeSpawnTool, makeTerminateTool, matchAny, matchGlob, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, parseContinueDirective, parseSkillRef, pendingBtwCount, projectHash, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resolveAuditLevel, resolveContextWindowPolicy, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setPlanItemStatus, slackServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, zaiVisionServer };
29703
+ export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, CheckpointManager, CloudSync, CollaborationBus, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionRecovery, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolError, ToolExecutor, ToolRegistry, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, assertSafePath, atomicWrite, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildBtwBlock, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, consumeBtwNotes, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createMcpControlTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createSyncPlugin, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, dispatchAgent, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, extractRunEnv, filesystemServer, findCriticalPath, formatContextWindowModeList, formatGoal, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, githubServer, goalFilePath, googleMapsServer, hashRequest, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isPluginError, isSessionError, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeRollUpTool, makeSpawnTool, makeTerminateTool, matchAny, matchGlob, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, parseContinueDirective, parseSkillRef, pendingBtwCount, projectHash, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setPlanItemStatus, slackServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, zaiVisionServer };
29259
29704
  //# sourceMappingURL=index.js.map
29260
29705
  //# sourceMappingURL=index.js.map