@wrongstack/core 0.87.0 → 0.89.1

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.
Files changed (49) hide show
  1. package/dist/{agent-bridge-C9P_HPez.d.ts → agent-bridge-B8F2ORwg.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-2Aq0jOSj.d.ts → agent-subagent-runner-CQaLFNnA.d.ts} +3 -2
  3. package/dist/coordination/index.d.ts +7 -7
  4. package/dist/coordination/index.js +183 -56
  5. package/dist/coordination/index.js.map +1 -1
  6. package/dist/{default-config-DEXI4jsl.d.ts → default-config-CXsDvOmP.d.ts} +3 -1
  7. package/dist/defaults/index.d.ts +10 -10
  8. package/dist/defaults/index.js +268 -68
  9. package/dist/defaults/index.js.map +1 -1
  10. package/dist/{events-DnRqXaZ3.d.ts → events-DzyLtja6.d.ts} +6 -0
  11. package/dist/execution/index.d.ts +5 -5
  12. package/dist/execution/index.js +56 -19
  13. package/dist/execution/index.js.map +1 -1
  14. package/dist/extension/index.d.ts +2 -2
  15. package/dist/{index-BNOLadHw.d.ts → index-Ca_lOmKl.d.ts} +2 -2
  16. package/dist/{index-N0_c4bHQ.d.ts → index-Dx-CnrDN.d.ts} +3 -1
  17. package/dist/index.d.ts +24 -21
  18. package/dist/index.js +448 -179
  19. package/dist/index.js.map +1 -1
  20. package/dist/infrastructure/index.d.ts +2 -2
  21. package/dist/infrastructure/index.js +12 -3
  22. package/dist/infrastructure/index.js.map +1 -1
  23. package/dist/kernel/index.d.ts +3 -3
  24. package/dist/kernel/index.js +17 -0
  25. package/dist/kernel/index.js.map +1 -1
  26. package/dist/models/index.js.map +1 -1
  27. package/dist/{multi-agent-coordinator-DllpCVkF.d.ts → multi-agent-coordinator-Da9nd8Ic.d.ts} +1 -1
  28. package/dist/{null-fleet-bus-BY0AN-sr.d.ts → null-fleet-bus-CHJOXv3t.d.ts} +11 -5
  29. package/dist/observability/index.d.ts +1 -1
  30. package/dist/{parallel-eternal-engine-D402RASp.d.ts → parallel-eternal-engine-DyMCj2Pw.d.ts} +4 -3
  31. package/dist/{path-resolver-UPFTsDyD.d.ts → path-resolver-TjBlRKyH.d.ts} +1 -1
  32. package/dist/{plan-templates-DRvPgkfZ.d.ts → plan-templates-D9UhwoGh.d.ts} +1 -1
  33. package/dist/{provider-runner-COAJM8tC.d.ts → provider-runner-BEPWwkxH.d.ts} +1 -1
  34. package/dist/sdd/index.d.ts +3 -3
  35. package/dist/sdd/index.js +89 -19
  36. package/dist/sdd/index.js.map +1 -1
  37. package/dist/security/index.js +18 -2
  38. package/dist/security/index.js.map +1 -1
  39. package/dist/skills/index.js.map +1 -1
  40. package/dist/storage/index.d.ts +4 -4
  41. package/dist/storage/index.js +149 -90
  42. package/dist/storage/index.js.map +1 -1
  43. package/dist/types/index.d.ts +10 -10
  44. package/dist/types/index.js +44 -7
  45. package/dist/types/index.js.map +1 -1
  46. package/dist/utils/index.d.ts +6 -1
  47. package/dist/utils/index.js +51 -3
  48. package/dist/utils/index.js.map +1 -1
  49. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -33,7 +33,8 @@ var __export = (target, all) => {
33
33
  var atomic_write_exports = {};
34
34
  __export(atomic_write_exports, {
35
35
  atomicWrite: () => atomicWrite,
36
- ensureDir: () => ensureDir
36
+ ensureDir: () => ensureDir,
37
+ withFileLock: () => withFileLock
37
38
  });
38
39
  async function atomicWrite(targetPath, content, opts = {}) {
39
40
  const dir = path6.dirname(targetPath);
@@ -56,8 +57,8 @@ async function atomicWrite(targetPath, content, opts = {}) {
56
57
  }
57
58
  let mode;
58
59
  try {
59
- const stat10 = await fsp3.stat(targetPath);
60
- mode = stat10.mode & 511;
60
+ const stat11 = await fsp3.stat(targetPath);
61
+ mode = stat11.mode & 511;
61
62
  } catch {
62
63
  mode = opts.mode;
63
64
  }
@@ -76,6 +77,49 @@ async function atomicWrite(targetPath, content, opts = {}) {
76
77
  async function ensureDir(dir) {
77
78
  await fsp3.mkdir(dir, { recursive: true });
78
79
  }
80
+ async function withFileLock(targetPath, fn, opts = {}) {
81
+ const dir = path6.dirname(targetPath);
82
+ await fsp3.mkdir(dir, { recursive: true });
83
+ const lockPath = path6.join(dir, `.${path6.basename(targetPath)}.lock`);
84
+ const timeoutMs = opts.timeoutMs ?? 5e3;
85
+ const staleMs = opts.staleMs ?? 3e4;
86
+ const started = Date.now();
87
+ let handle;
88
+ for (; ; ) {
89
+ try {
90
+ handle = await fsp3.open(lockPath, "wx");
91
+ await handle.writeFile(`${process.pid}:${Date.now()}`);
92
+ break;
93
+ } catch (err) {
94
+ if (err.code !== "EEXIST") throw err;
95
+ try {
96
+ const stat11 = await fsp3.stat(lockPath);
97
+ if (Date.now() - stat11.mtimeMs > staleMs) {
98
+ await fsp3.unlink(lockPath);
99
+ continue;
100
+ }
101
+ } catch {
102
+ continue;
103
+ }
104
+ if (Date.now() - started >= timeoutMs) {
105
+ throw new Error(`Timed out waiting for file lock: ${targetPath}`);
106
+ }
107
+ await new Promise((resolve13) => setTimeout(resolve13, 25));
108
+ }
109
+ }
110
+ try {
111
+ return await fn();
112
+ } finally {
113
+ try {
114
+ await handle?.close();
115
+ } catch {
116
+ }
117
+ try {
118
+ await fsp3.unlink(lockPath);
119
+ } catch {
120
+ }
121
+ }
122
+ }
79
123
  async function renameWithRetry(from, to) {
80
124
  if (process.platform !== "win32") {
81
125
  await fsp3.rename(from, to);
@@ -703,6 +747,23 @@ var EventBus = class {
703
747
  }
704
748
  }
705
749
  }
750
+ /**
751
+ * Emit a plugin-defined event that is intentionally outside EventMap.
752
+ * Custom events are delivered to wildcard/pattern listeners only; typed
753
+ * listeners remain reserved for core EventMap keys.
754
+ */
755
+ emitCustom(event, payload) {
756
+ if (this.wildcards.length === 0) return;
757
+ const snapshot = this.wildcards.slice();
758
+ for (const { match, fn } of snapshot) {
759
+ if (!match(event)) continue;
760
+ try {
761
+ fn(event, payload);
762
+ } catch (err) {
763
+ this.logger?.error(`EventBus wildcard listener for "${event}" threw`, err);
764
+ }
765
+ }
766
+ }
706
767
  clear() {
707
768
  this.listeners.clear();
708
769
  this.wildcards.length = 0;
@@ -1093,6 +1154,7 @@ var DEFAULT_SESSION_LOGGING_CONFIG = Object.freeze({
1093
1154
  }
1094
1155
  }
1095
1156
  });
1157
+ var DEFAULT_SESSION_PRUNE_DAYS = 30;
1096
1158
 
1097
1159
  // src/types/secret-vault.ts
1098
1160
  var ENCRYPTED_PREFIX = "enc:v1:";
@@ -1254,9 +1316,18 @@ async function restrictFilePermissions(filePath, opts) {
1254
1316
  const { execFile: execFile2 } = await import('child_process');
1255
1317
  const { promisify: promisify2 } = await import('util');
1256
1318
  const execFileAsync = promisify2(execFile2);
1257
- await execFileAsync("icacls", [filePath, "/inheritance:r", "/grant:r", `${process.env.USERNAME}:(F)`]);
1319
+ const user = windowsAccountName();
1320
+ if (!user) {
1321
+ warn(
1322
+ `[secret-vault] Could not determine the current Windows user for ${filePath}; skipping icacls hardening.`
1323
+ );
1324
+ return;
1325
+ }
1326
+ await execFileAsync("icacls", [filePath, "/inheritance:r", "/grant:r", `${user}:(F)`]);
1258
1327
  } catch {
1259
- warn(`[secret-vault] Could not restrict permissions on ${filePath} \u2014 config file may be readable by other users on this system.`);
1328
+ warn(
1329
+ `[secret-vault] Could not restrict permissions on ${filePath} \u2014 config file may be readable by other users on this system.`
1330
+ );
1260
1331
  }
1261
1332
  } else {
1262
1333
  try {
@@ -1265,6 +1336,13 @@ async function restrictFilePermissions(filePath, opts) {
1265
1336
  }
1266
1337
  }
1267
1338
  }
1339
+ function windowsAccountName() {
1340
+ const username = process.env.USERNAME || process.env.USER;
1341
+ if (!username || username.includes("\0")) return void 0;
1342
+ const domain = process.env.USERDOMAIN;
1343
+ if (domain && !domain.includes("\0")) return `${domain}\\${username}`;
1344
+ return username;
1345
+ }
1268
1346
  function walkCount(node, vault, counter) {
1269
1347
  if (node === null || node === void 0) return node;
1270
1348
  if (typeof node !== "object") return node;
@@ -1371,10 +1449,15 @@ function writeErr(s, stream = process.stderr) {
1371
1449
 
1372
1450
  // src/utils/color.ts
1373
1451
  var isColorTty = () => {
1374
- if (process.env.NO_COLOR) return false;
1375
- if (process.env.FORCE_COLOR) return true;
1452
+ if (envFlag(process.env.NO_COLOR)) return false;
1453
+ if (envFlag(process.env.FORCE_COLOR)) return true;
1376
1454
  return isStdoutTTY();
1377
1455
  };
1456
+ function envFlag(value) {
1457
+ if (value === void 0) return false;
1458
+ if (value.trim() === "") return false;
1459
+ return !/^(0|false|no|off)$/i.test(value.trim());
1460
+ }
1378
1461
  var COLOR = isColorTty();
1379
1462
  var wrap = (open5, close) => (s) => COLOR ? `\x1B[${open5}m${s}\x1B[${close}m` : s;
1380
1463
  var color = {
@@ -1418,6 +1501,7 @@ var COLORS = {
1418
1501
  debug: color.gray,
1419
1502
  trace: color.dim
1420
1503
  };
1504
+ var LOG_LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "debug", "trace"]);
1421
1505
  var DefaultLogger = class _DefaultLogger {
1422
1506
  level;
1423
1507
  file;
@@ -1425,7 +1509,7 @@ var DefaultLogger = class _DefaultLogger {
1425
1509
  pretty;
1426
1510
  stderr;
1427
1511
  constructor(opts = {}) {
1428
- this.level = opts.level ?? process.env.WRONGSTACK_LOG_LEVEL ?? "info";
1512
+ this.level = opts.level ?? parseLogLevel(process.env.WRONGSTACK_LOG_LEVEL);
1429
1513
  this.file = opts.file;
1430
1514
  this.bindings = opts.bindings ?? {};
1431
1515
  this.pretty = opts.pretty ?? true;
@@ -1490,6 +1574,9 @@ var DefaultLogger = class _DefaultLogger {
1490
1574
  }
1491
1575
  }
1492
1576
  };
1577
+ function parseLogLevel(raw) {
1578
+ return raw && LOG_LEVELS.has(raw) ? raw : "info";
1579
+ }
1493
1580
  function formatCtx(ctx) {
1494
1581
  if (ctx instanceof Error) return color.dim(ctx.message);
1495
1582
  if (typeof ctx === "string") return color.dim(ctx);
@@ -3490,6 +3577,7 @@ var ToolExecutor = class {
3490
3577
  this.registry = registry;
3491
3578
  this.opts = opts;
3492
3579
  this.iterationTimeoutMs = opts.iterationTimeoutMs ?? 3e5;
3580
+ this.maxToolTimeoutMs = opts.maxToolTimeoutMs ?? 3e5;
3493
3581
  this.serializer = createToolOutputSerializer({
3494
3582
  perIterationOutputCapBytes: opts.perIterationOutputCapBytes ?? 1e5
3495
3583
  });
@@ -3498,6 +3586,7 @@ var ToolExecutor = class {
3498
3586
  opts;
3499
3587
  serializer;
3500
3588
  iterationTimeoutMs;
3589
+ maxToolTimeoutMs;
3501
3590
  /**
3502
3591
  * Clear the interactive confirm awaiter so the executor returns
3503
3592
  * `ToolConfirmPendingResult` instead of blocking on stdin. Used by
@@ -3735,7 +3824,10 @@ ${post.additionalContext}` };
3735
3824
  if (parentSignal.reason instanceof Error) throw parentSignal.reason;
3736
3825
  throw new Error(typeof parentSignal.reason === "string" ? parentSignal.reason : "aborted");
3737
3826
  }
3738
- const timeoutMs = tool.timeoutMs ?? this.iterationTimeoutMs;
3827
+ const timeoutMs = clampTimeoutMs(
3828
+ tool.timeoutMs ?? this.iterationTimeoutMs,
3829
+ this.maxToolTimeoutMs
3830
+ );
3739
3831
  const ctrl = new AbortController();
3740
3832
  const timer = setTimeout(() => ctrl.abort(new Error("tool timeout")), timeoutMs);
3741
3833
  const combined = AbortSignal.any([parentSignal, ctrl.signal]);
@@ -3870,6 +3962,12 @@ ${excerpt}`;
3870
3962
  return void 0;
3871
3963
  }
3872
3964
  };
3965
+ function clampTimeoutMs(timeoutMs, maxTimeoutMs) {
3966
+ const fallback = 3e5;
3967
+ const finiteTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : fallback;
3968
+ const finiteMax = Number.isFinite(maxTimeoutMs) && maxTimeoutMs > 0 ? maxTimeoutMs : fallback;
3969
+ return Math.max(1, Math.min(finiteTimeout, finiteMax));
3970
+ }
3873
3971
  var MALFORMED_ARG_MARKERS = ["__raw", "__raw_arguments", "_raw"];
3874
3972
  function hasMalformedArguments(input) {
3875
3973
  if (!input || typeof input !== "object" || Array.isArray(input)) return false;
@@ -4840,8 +4938,8 @@ async function expandGlob(pattern) {
4840
4938
  for (const e of entries) {
4841
4939
  const full = `${dir}${SEP}${e}`;
4842
4940
  try {
4843
- const stat10 = await fsp3.stat(full);
4844
- if (stat10.isDirectory()) await walk4(full, rest);
4941
+ const stat11 = await fsp3.stat(full);
4942
+ if (stat11.isDirectory()) await walk4(full, rest);
4845
4943
  } catch {
4846
4944
  }
4847
4945
  }
@@ -4858,8 +4956,8 @@ async function expandGlob(pattern) {
4858
4956
  if (entries.includes(seg)) {
4859
4957
  const full = `${dir}${SEP}${seg}`;
4860
4958
  try {
4861
- const stat10 = await fsp3.stat(full);
4862
- if (stat10.isDirectory()) await walk4(full, rest);
4959
+ const stat11 = await fsp3.stat(full);
4960
+ if (stat11.isDirectory()) await walk4(full, rest);
4863
4961
  } catch {
4864
4962
  }
4865
4963
  }
@@ -5254,8 +5352,8 @@ var DefaultSessionStore = class _DefaultSessionStore {
5254
5352
  return JSON.parse(raw);
5255
5353
  } catch {
5256
5354
  const full = this.sessionPath(id, ".jsonl");
5257
- const stat10 = await fsp3.stat(full);
5258
- const summary = await this.summarize(id, stat10.mtime.toISOString());
5355
+ const stat11 = await fsp3.stat(full);
5356
+ const summary = await this.summarize(id, stat11.mtime.toISOString());
5259
5357
  await atomicWrite(manifest, JSON.stringify(summary), { mode: 384 }).catch((err) => {
5260
5358
  console.warn(
5261
5359
  `[session-store] Failed to write manifest for "${id}":`,
@@ -5303,8 +5401,8 @@ var DefaultSessionStore = class _DefaultSessionStore {
5303
5401
  if (!file.isFile() || !file.name.endsWith(".jsonl")) continue;
5304
5402
  const jsonlPath = path6.join(dateDir, file.name);
5305
5403
  try {
5306
- const stat10 = await fsp3.stat(jsonlPath);
5307
- if (stat10.mtimeMs >= cutoff) continue;
5404
+ const stat11 = await fsp3.stat(jsonlPath);
5405
+ if (stat11.mtimeMs >= cutoff) continue;
5308
5406
  } catch {
5309
5407
  continue;
5310
5408
  }
@@ -6321,6 +6419,13 @@ var BEHAVIOR_DEFAULTS = {
6321
6419
  function envBool(v) {
6322
6420
  return !/^(0|false|no|off)$/i.test(v.trim());
6323
6421
  }
6422
+ function envBoolOptional(v) {
6423
+ return v !== void 0 && envBool(v);
6424
+ }
6425
+ var LOG_LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info", "debug", "trace"]);
6426
+ function envLogLevel(v) {
6427
+ return LOG_LEVELS2.has(v) ? v : "info";
6428
+ }
6324
6429
  var ENV_MAP = {
6325
6430
  WRONGSTACK_PROVIDER: (c, v) => {
6326
6431
  c.provider = v;
@@ -6344,7 +6449,7 @@ var ENV_MAP = {
6344
6449
  },
6345
6450
  WRONGSTACK_LOG_LEVEL: (c, v) => {
6346
6451
  if (!c.log) c.log = { level: "info" };
6347
- c.log.level = v;
6452
+ c.log.level = envLogLevel(v);
6348
6453
  },
6349
6454
  WRONGSTACK_INDEX_ON_START: (c, v) => {
6350
6455
  c.indexing = { ...defaultIndexing, ...c.indexing, onSessionStart: envBool(v) };
@@ -6386,7 +6491,7 @@ function deepMerge2(base, patch) {
6386
6491
  out[k] = [.../* @__PURE__ */ new Set([...existing, ...v])];
6387
6492
  } else {
6388
6493
  out[k] = v;
6389
- if (process.env.WRONGSTACK_DEBUG_CONFIG) {
6494
+ if (envBoolOptional(process.env.WRONGSTACK_DEBUG_CONFIG)) {
6390
6495
  console.warn(
6391
6496
  `[config] Non-primitive array for "${k}" replaced (global + local config merge). Global entries: ${existing?.length ?? 0}, local entries: ${v.length}.`
6392
6497
  );
@@ -7954,6 +8059,7 @@ function parseDescription(raw) {
7954
8059
  }
7955
8060
  return { trigger, scope };
7956
8061
  }
8062
+ var STREAM_DRAIN_TIMEOUT_MS = 500;
7957
8063
  function buildResponse(state) {
7958
8064
  const content = [];
7959
8065
  for (const b of state.blockOrder) {
@@ -8166,7 +8272,7 @@ async function streamProviderToResponse(provider, req, signal, ctx, events) {
8166
8272
  await Promise.race([
8167
8273
  Promise.resolve(iter.return?.()),
8168
8274
  new Promise((resolve13) => {
8169
- drainTimer = setTimeout(resolve13, 500);
8275
+ drainTimer = setTimeout(resolve13, STREAM_DRAIN_TIMEOUT_MS);
8170
8276
  })
8171
8277
  ]);
8172
8278
  } finally {
@@ -9928,6 +10034,7 @@ ${recentJournal}` : "No prior iterations.",
9928
10034
  };
9929
10035
 
9930
10036
  // src/coordination/subagent-budget.ts
10037
+ var TIMEOUT_PREEMPT_FRACTION = 0.85;
9931
10038
  var BudgetExceededError = class extends Error {
9932
10039
  kind;
9933
10040
  limit;
@@ -12729,16 +12836,17 @@ Do not add prose, markdown, or code fences.`;
12729
12836
  const raw = (await complete(prompt)).trim();
12730
12837
  const match = raw.match(/\{[\s\S]*\}/);
12731
12838
  if (!match) return null;
12732
- try {
12733
- const parsed = JSON.parse(match[0]);
12734
- if (typeof parsed.role !== "string") return null;
12735
- const role = parsed.role.trim();
12736
- const valid = candidates.some((c) => c.role === role);
12737
- if (!valid) return null;
12738
- return { role, reason: typeof parsed.reason === "string" ? parsed.reason : void 0 };
12739
- } catch {
12740
- return null;
12741
- }
12839
+ const parsed = safeParse(
12840
+ match[0]
12841
+ );
12842
+ if (!parsed.ok || !parsed.value || typeof parsed.value.role !== "string") return null;
12843
+ const role = parsed.value.role.trim();
12844
+ const valid = candidates.some((c) => c.role === role);
12845
+ if (!valid) return null;
12846
+ return {
12847
+ role,
12848
+ reason: typeof parsed.value.reason === "string" ? parsed.value.reason : void 0
12849
+ };
12742
12850
  };
12743
12851
  }
12744
12852
 
@@ -13693,15 +13801,38 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
13693
13801
  }
13694
13802
  const start = Date.now();
13695
13803
  let timer = null;
13804
+ let preemptedForLimit = null;
13696
13805
  const timeoutPromise = new Promise((_, reject) => {
13697
13806
  const armFor = (ms) => {
13698
13807
  if (timer) clearTimeout(timer);
13699
13808
  timer = setTimeout(onTick, Math.max(0, ms));
13700
13809
  };
13701
13810
  const scheduleNext = () => {
13702
- const wallRemaining = initialTimeoutMs === void 0 ? Number.POSITIVE_INFINITY : (budget.limits.timeoutMs ?? initialTimeoutMs) - (Date.now() - start);
13811
+ const wallLimit = budget.limits.timeoutMs ?? initialTimeoutMs;
13812
+ const wallRemaining = initialTimeoutMs === void 0 ? Number.POSITIVE_INFINITY : wallLimit - (Date.now() - start);
13703
13813
  const idleRemaining = idleLimitMs === void 0 ? Number.POSITIVE_INFINITY : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();
13704
- armFor(Math.max(25, Math.min(wallRemaining, idleRemaining)));
13814
+ const preemptRemaining = initialTimeoutMs === void 0 || preemptedForLimit === wallLimit ? Number.POSITIVE_INFINITY : wallLimit * TIMEOUT_PREEMPT_FRACTION - (Date.now() - start);
13815
+ armFor(Math.max(25, Math.min(wallRemaining, idleRemaining, preemptRemaining)));
13816
+ };
13817
+ const negotiateTimeout = async (used, limit) => {
13818
+ const handler = budget.onThreshold;
13819
+ if (!handler) return "stop";
13820
+ const result = handler({
13821
+ kind: "timeout",
13822
+ used,
13823
+ limit,
13824
+ requestDecision: () => new Promise((resolveDecision) => {
13825
+ budget._events?.emit("budget.threshold_reached", {
13826
+ kind: "timeout",
13827
+ used,
13828
+ limit,
13829
+ timeoutMs: 6e4,
13830
+ extend: (extra) => resolveDecision({ extend: extra }),
13831
+ deny: () => resolveDecision("stop")
13832
+ });
13833
+ })
13834
+ });
13835
+ return typeof result === "string" ? result : await result;
13705
13836
  };
13706
13837
  const onTick = async () => {
13707
13838
  const elapsed = Date.now() - start;
@@ -13714,6 +13845,21 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
13714
13845
  reject(new BudgetExceededError("timeout", idleLimit ?? 0, budget.idleMs()));
13715
13846
  return;
13716
13847
  }
13848
+ if (wallLimit !== void 0 && !wallExceeded && budget.onThreshold && preemptedForLimit !== wallLimit && elapsed >= wallLimit * TIMEOUT_PREEMPT_FRACTION) {
13849
+ try {
13850
+ const decision = await negotiateTimeout(elapsed, wallLimit);
13851
+ if (typeof decision !== "string" && decision.extend.timeoutMs !== void 0) {
13852
+ budget.limits.timeoutMs = decision.extend.timeoutMs;
13853
+ preemptedForLimit = null;
13854
+ } else {
13855
+ preemptedForLimit = wallLimit;
13856
+ }
13857
+ } catch {
13858
+ preemptedForLimit = wallLimit;
13859
+ }
13860
+ scheduleNext();
13861
+ return;
13862
+ }
13717
13863
  if (!wallExceeded) {
13718
13864
  scheduleNext();
13719
13865
  return;
@@ -13725,28 +13871,15 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
13725
13871
  return;
13726
13872
  }
13727
13873
  try {
13728
- const result = budget.onThreshold({
13729
- kind: "timeout",
13730
- used: elapsed,
13731
- limit,
13732
- requestDecision: () => new Promise((resolveDecision) => {
13733
- budget._events?.emit("budget.threshold_reached", {
13734
- kind: "timeout",
13735
- used: elapsed,
13736
- limit,
13737
- timeoutMs: 6e4,
13738
- extend: (extra) => resolveDecision({ extend: extra }),
13739
- deny: () => resolveDecision("stop")
13740
- });
13741
- })
13742
- });
13743
- const decision = typeof result === "string" ? result : await result;
13874
+ const decision = await negotiateTimeout(elapsed, limit);
13744
13875
  if (decision === "continue" || decision === "throw" || decision === "stop") {
13876
+ preemptedForLimit = null;
13745
13877
  armFor(Math.max(1e3, limit));
13746
13878
  return;
13747
13879
  }
13748
13880
  if (decision.extend.timeoutMs !== void 0) {
13749
13881
  budget.limits.timeoutMs = decision.extend.timeoutMs;
13882
+ preemptedForLimit = null;
13750
13883
  scheduleNext();
13751
13884
  return;
13752
13885
  }
@@ -14430,6 +14563,7 @@ var CollabSession = class extends EventEmitter {
14430
14563
  timeoutMs;
14431
14564
  cancelled = false;
14432
14565
  alerts = [];
14566
+ snapshotWarnings = [];
14433
14567
  /** Tracks tool call counts per subagent for progress-based timeout decisions. */
14434
14568
  progressBySubagent = /* @__PURE__ */ new Map();
14435
14569
  /** Last tool call count when a timeout warning was handled. */
@@ -14499,10 +14633,19 @@ var CollabSession = class extends EventEmitter {
14499
14633
  }
14500
14634
  for (const filePath of allFiles) {
14501
14635
  try {
14502
- const content = await fsp3.readFile(filePath, "utf8");
14636
+ const [content, stat11] = await Promise.all([
14637
+ fsp3.readFile(filePath, "utf8"),
14638
+ fsp3.stat(filePath)
14639
+ ]);
14503
14640
  const ext = filePath.split(".").pop() ?? "";
14504
14641
  const language = ext === "ts" || ext === "tsx" ? "typescript" : ext === "js" || ext === "jsx" ? "javascript" : ext === "md" ? "markdown" : ext === "json" ? "json" : void 0;
14505
- this.snapshot.files.push({ path: filePath, content, language });
14642
+ this.snapshot.files.push({
14643
+ path: filePath,
14644
+ content,
14645
+ language,
14646
+ snapshotMtimeMs: stat11.mtimeMs,
14647
+ snapshotSizeBytes: stat11.size
14648
+ });
14506
14649
  } catch {
14507
14650
  this.snapshot.files.push({ path: filePath, content: "", language: void 0 });
14508
14651
  }
@@ -14525,7 +14668,11 @@ var CollabSession = class extends EventEmitter {
14525
14668
  subagentId: this.director.id,
14526
14669
  ts: Date.now(),
14527
14670
  type: "director.cancel_collab",
14528
- payload: { sessionId: this.sessionId, reason, cancelledAt: (/* @__PURE__ */ new Date()).toISOString() }
14671
+ payload: {
14672
+ sessionId: this.sessionId,
14673
+ reason,
14674
+ cancelledAt: (/* @__PURE__ */ new Date()).toISOString()
14675
+ }
14529
14676
  });
14530
14677
  this.fleetBus.emit({
14531
14678
  subagentId: this.director.id,
@@ -14576,6 +14723,7 @@ var CollabSession = class extends EventEmitter {
14576
14723
  for (const result of results?.flat() ?? []) {
14577
14724
  await this.parseAndEmit(result);
14578
14725
  }
14726
+ this.snapshotWarnings = await this.checkSnapshotFreshness();
14579
14727
  const report = this.assembleReport();
14580
14728
  this.cleanup();
14581
14729
  this.emit("session.done", report);
@@ -14639,7 +14787,7 @@ var CollabSession = class extends EventEmitter {
14639
14787
  const defaults = {
14640
14788
  "bug-hunter": { maxIterations: 2e3, maxToolCalls: 5e3, timeoutMs: 10 * 60 * 1e3 },
14641
14789
  "refactor-planner": { maxIterations: 1500, maxToolCalls: 4e3, timeoutMs: 8 * 60 * 1e3 },
14642
- "critic": { maxIterations: 1e3, maxToolCalls: 3e3, timeoutMs: 6 * 60 * 1e3 }
14790
+ critic: { maxIterations: 1e3, maxToolCalls: 3e3, timeoutMs: 6 * 60 * 1e3 }
14643
14791
  };
14644
14792
  return defaults[role] ?? { maxIterations: 1500, maxToolCalls: 4e3, timeoutMs: 8 * 60 * 1e3 };
14645
14793
  }
@@ -14719,7 +14867,10 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
14719
14867
  }
14720
14868
  wireFleetBus() {
14721
14869
  const dTool = this.fleetBus.filter("tool.executed", (e) => {
14722
- this.progressBySubagent.set(e.subagentId, (this.progressBySubagent.get(e.subagentId) ?? 0) + 1);
14870
+ this.progressBySubagent.set(
14871
+ e.subagentId,
14872
+ (this.progressBySubagent.get(e.subagentId) ?? 0) + 1
14873
+ );
14723
14874
  });
14724
14875
  this.disposers.push(dTool);
14725
14876
  const dBudget = this.fleetBus.filter("budget.threshold_reached", (e) => {
@@ -14758,7 +14909,10 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
14758
14909
  return;
14759
14910
  }
14760
14911
  this.lastTimeoutProgress.set(e.subagentId, progress);
14761
- const newLimit = Math.min(Math.ceil((payload.timeoutMs ?? payload.limit) * 2), 24 * 60 * 6e4);
14912
+ const newLimit = Math.min(
14913
+ Math.ceil((payload.timeoutMs ?? payload.limit) * 2),
14914
+ 24 * 60 * 6e4
14915
+ );
14762
14916
  setImmediate(() => {
14763
14917
  payload.extend({ timeoutMs: newLimit });
14764
14918
  });
@@ -14868,15 +15022,18 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
14868
15022
  needs_revision: 1,
14869
15023
  reject: 2
14870
15024
  };
14871
- const overallVerdict = evalList.reduce(
14872
- (worst, eval_) => {
14873
- const w = verdictOrder[worst];
14874
- const c = verdictOrder[eval_.verdict];
14875
- return c > w ? eval_.verdict : worst;
14876
- },
14877
- "approve"
15025
+ const overallVerdict = evalList.reduce((worst, eval_) => {
15026
+ const w = verdictOrder[worst];
15027
+ const c = verdictOrder[eval_.verdict];
15028
+ return c > w ? eval_.verdict : worst;
15029
+ }, "approve");
15030
+ const summary = this.buildMarkdownSummary(
15031
+ bugList,
15032
+ planList,
15033
+ evalList,
15034
+ overallVerdict,
15035
+ disposition
14878
15036
  );
14879
- const summary = this.buildMarkdownSummary(bugList, planList, evalList, overallVerdict, disposition);
14880
15037
  return {
14881
15038
  sessionId: this.sessionId,
14882
15039
  startedAt: this.snapshot.createdAt,
@@ -14887,10 +15044,28 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
14887
15044
  refactorPlans: planList,
14888
15045
  evaluations: evalList,
14889
15046
  alerts: [...this.alerts],
15047
+ ...this.snapshotWarnings.length > 0 ? { snapshotWarnings: this.snapshotWarnings } : {},
14890
15048
  overallVerdict,
14891
15049
  summary
14892
15050
  };
14893
15051
  }
15052
+ async checkSnapshotFreshness() {
15053
+ const warnings = [];
15054
+ for (const file of this.snapshot.files) {
15055
+ if (file.snapshotMtimeMs === void 0 && file.snapshotSizeBytes === void 0) continue;
15056
+ try {
15057
+ const stat11 = await fsp3.stat(file.path);
15058
+ const mtimeChanged = file.snapshotMtimeMs !== void 0 && stat11.mtimeMs > file.snapshotMtimeMs + 1;
15059
+ const sizeChanged = file.snapshotSizeBytes !== void 0 && stat11.size !== file.snapshotSizeBytes;
15060
+ if (mtimeChanged || sizeChanged) {
15061
+ warnings.push(`${file.path} changed after the collab snapshot was captured.`);
15062
+ }
15063
+ } catch {
15064
+ warnings.push(`${file.path} could not be checked after the collab snapshot was captured.`);
15065
+ }
15066
+ }
15067
+ return warnings;
15068
+ }
14894
15069
  buildMarkdownSummary(bugs, plans, evals, overallVerdict, disposition) {
14895
15070
  const lines = [
14896
15071
  `## Collaborative Debugging Report \u2014 ${this.sessionId}`,
@@ -14907,10 +15082,19 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
14907
15082
  }
14908
15083
  lines.push("");
14909
15084
  }
15085
+ if (this.snapshotWarnings.length > 0) {
15086
+ lines.push("### Snapshot Warnings", "");
15087
+ for (const warning of this.snapshotWarnings) {
15088
+ lines.push(`- ${warning}`);
15089
+ }
15090
+ lines.push("");
15091
+ }
14910
15092
  if (bugs.length > 0) {
14911
15093
  lines.push("### Bugs Found", "");
14912
15094
  for (const b of bugs) {
14913
- lines.push(`- **[${b.severity.toUpperCase()}]** \`${b.location.file}:${b.location.line}\` \u2014 ${b.description}`);
15095
+ lines.push(
15096
+ `- **[${b.severity.toUpperCase()}]** \`${b.location.file}:${b.location.line}\` \u2014 ${b.description}`
15097
+ );
14914
15098
  }
14915
15099
  lines.push("");
14916
15100
  }
@@ -15513,6 +15697,7 @@ var FleetBus = class {
15513
15697
  set.add(handler);
15514
15698
  return () => {
15515
15699
  set.delete(handler);
15700
+ if (set.size === 0) this.byId.delete(subagentId);
15516
15701
  };
15517
15702
  }
15518
15703
  /** Subscribe to one event type across all subagents. */
@@ -15525,6 +15710,7 @@ var FleetBus = class {
15525
15710
  set.add(handler);
15526
15711
  return () => {
15527
15712
  set.delete(handler);
15713
+ if (set.size === 0) this.byType.delete(type);
15528
15714
  };
15529
15715
  }
15530
15716
  /** Subscribe to literally everything. The fleet roll-up uses this. */
@@ -15558,6 +15744,11 @@ var FleetBus = class {
15558
15744
  }
15559
15745
  }
15560
15746
  }
15747
+ clear() {
15748
+ this.byId.clear();
15749
+ this.byType.clear();
15750
+ this.any.clear();
15751
+ }
15561
15752
  };
15562
15753
  var FleetUsageAggregator = class {
15563
15754
  constructor(bus, priceLookup, metaLookup) {
@@ -16802,7 +16993,9 @@ var Director = class _Director {
16802
16993
  let toolUses = 0;
16803
16994
  for (const line of targetLines) {
16804
16995
  try {
16805
- const ev = JSON.parse(line);
16996
+ const parsed = safeParse(line);
16997
+ if (!parsed.ok || !parsed.value) continue;
16998
+ const ev = parsed.value;
16806
16999
  if (ev.type === "assistant" && typeof ev.text === "string") {
16807
17000
  lastAssistantText = ev.text;
16808
17001
  } else if (ev.type === "stop" && ev.stopReason) {
@@ -17116,7 +17309,7 @@ function createDelegateTool(opts) {
17116
17309
  const offIter = dir.fleet.filter("iteration.started", bump);
17117
17310
  const offProgress = dir.fleet.filter("tool.progress", bump);
17118
17311
  arm();
17119
- dir.awaitTasks([taskId]).then((r) => finish(r[0] ?? { __timeout: true })).catch(() => finish({ __timeout: true }));
17312
+ dir.awaitTasks([taskId]).then((r) => finish(r[0] ?? { __emptyResult: true })).catch(() => finish({ __timeout: true }));
17120
17313
  });
17121
17314
  if ("__timeout" in result) {
17122
17315
  const partial2 = await readSubagentPartial(opts, subagentId);
@@ -17141,6 +17334,29 @@ function createDelegateTool(opts) {
17141
17334
  partial: partial2
17142
17335
  };
17143
17336
  }
17337
+ if ("__emptyResult" in result) {
17338
+ const partial2 = await readSubagentPartial(opts, subagentId);
17339
+ opts.events?.emit("delegate.completed", {
17340
+ target,
17341
+ task: i.task,
17342
+ ok: false,
17343
+ status: "empty_result",
17344
+ summary: `[${target}] completed without a task result`,
17345
+ durationMs: 0,
17346
+ iterations: partial2?.events ?? 0,
17347
+ toolCalls: partial2?.toolUsesObserved ?? 0,
17348
+ subagentId
17349
+ });
17350
+ return {
17351
+ ok: false,
17352
+ stopReason: "error",
17353
+ error: "Director returned no task result for the delegated task.",
17354
+ hint: "Check fleet state with /fleet status, then retry or reassign the task.",
17355
+ subagentId,
17356
+ taskId,
17357
+ partial: partial2
17358
+ };
17359
+ }
17144
17360
  const baseStopReason = result.status === "success" ? "end_turn" : result.status === "timeout" ? "subagent_timeout" : result.status === "stopped" ? "aborted" : "budget_exhausted";
17145
17361
  const partial = result.status === "success" ? void 0 : await readSubagentPartial(opts, subagentId);
17146
17362
  const errorKind = result.error?.kind;
@@ -17313,7 +17529,9 @@ async function readSubagentPartial(opts, subagentId) {
17313
17529
  let toolUses = 0;
17314
17530
  for (const line of lines) {
17315
17531
  try {
17316
- const ev = JSON.parse(line);
17532
+ const parsed = safeParse(line);
17533
+ if (!parsed.ok || !parsed.value) continue;
17534
+ const ev = parsed.value;
17317
17535
  if (ev.type === "tool_use") toolUses += 1;
17318
17536
  if (ev.type === "llm_response") {
17319
17537
  if (typeof ev.stopReason === "string") lastStopReason = ev.stopReason;
@@ -17501,8 +17719,8 @@ async function loadProjectModes(modesDir) {
17501
17719
  for (const entry of entries) {
17502
17720
  if (!entry.endsWith(".md") && !entry.endsWith(".txt")) continue;
17503
17721
  const filePath = path6.join(modesDir, entry);
17504
- const stat10 = await fsp3.stat(filePath);
17505
- if (!stat10.isFile()) continue;
17722
+ const stat11 = await fsp3.stat(filePath);
17723
+ if (!stat11.isFile()) continue;
17506
17724
  const content = await fsp3.readFile(filePath, "utf8");
17507
17725
  const id = path6.basename(entry, path6.extname(entry));
17508
17726
  modes.push({
@@ -21464,10 +21682,10 @@ var SkillInstaller = class {
21464
21682
  if (!resolved.startsWith(path6.resolve(destDir))) {
21465
21683
  throw new Error(`Path traversal detected in skill file: ${file}`);
21466
21684
  }
21467
- const stat10 = await fsp3.stat(srcPath);
21468
- if (stat10.size > MAX_SKILL_FILE_SIZE) {
21685
+ const stat11 = await fsp3.stat(srcPath);
21686
+ if (stat11.size > MAX_SKILL_FILE_SIZE) {
21469
21687
  throw new Error(
21470
- `Skill file "${file}" is too large (${(stat10.size / 1024).toFixed(1)}KB). Max: ${MAX_SKILL_FILE_SIZE / 1024}KB`
21688
+ `Skill file "${file}" is too large (${(stat11.size / 1024).toFixed(1)}KB). Max: ${MAX_SKILL_FILE_SIZE / 1024}KB`
21471
21689
  );
21472
21690
  }
21473
21691
  await fsp3.mkdir(path6.dirname(destPath), { recursive: true });
@@ -21760,9 +21978,7 @@ var AnnotationsStore = class {
21760
21978
  throw new Error("Annotation text must be non-empty");
21761
21979
  }
21762
21980
  if (text.length > MAX_TEXT_LENGTH) {
21763
- throw new Error(
21764
- `Annotation text exceeds ${MAX_TEXT_LENGTH} chars (got ${text.length})`
21765
- );
21981
+ throw new Error(`Annotation text exceeds ${MAX_TEXT_LENGTH} chars (got ${text.length})`);
21766
21982
  }
21767
21983
  if (!Number.isInteger(input.atEventIndex) || input.atEventIndex < 0) {
21768
21984
  throw new Error("atEventIndex must be a non-negative integer");
@@ -21778,20 +21994,22 @@ var AnnotationsStore = class {
21778
21994
  resolved: false
21779
21995
  };
21780
21996
  await this.enqueue(input.sessionId, async () => {
21781
- const all = await this.list(input.sessionId);
21782
- all.push(annotation);
21783
- if (all.length > MAX_ANNOTATIONS) {
21784
- const sorted = all.map((a, i) => ({ a, i })).sort((x, y) => {
21785
- if (x.a.resolved !== y.a.resolved) return x.a.resolved ? 1 : -1;
21786
- return x.a.createdAt.localeCompare(y.a.createdAt);
21787
- });
21788
- const evictCount = all.length - MAX_ANNOTATIONS;
21789
- const toEvict = new Set(sorted.slice(0, evictCount).map((s) => s.a.id));
21790
- const kept = all.filter((a) => !toEvict.has(a.id));
21791
- await this.writeFile(input.sessionId, { version: FILE_VERSION, annotations: kept });
21792
- } else {
21793
- await this.writeFile(input.sessionId, { version: FILE_VERSION, annotations: all });
21794
- }
21997
+ await withFileLock(this.filePath(input.sessionId), async () => {
21998
+ const all = await this.list(input.sessionId);
21999
+ all.push(annotation);
22000
+ if (all.length > MAX_ANNOTATIONS) {
22001
+ const sorted = all.map((a, i) => ({ a, i })).sort((x, y) => {
22002
+ if (x.a.resolved !== y.a.resolved) return x.a.resolved ? 1 : -1;
22003
+ return x.a.createdAt.localeCompare(y.a.createdAt);
22004
+ });
22005
+ const evictCount = all.length - MAX_ANNOTATIONS;
22006
+ const toEvict = new Set(sorted.slice(0, evictCount).map((s) => s.a.id));
22007
+ const kept = all.filter((a) => !toEvict.has(a.id));
22008
+ await this.writeFile(input.sessionId, { version: FILE_VERSION, annotations: kept });
22009
+ } else {
22010
+ await this.writeFile(input.sessionId, { version: FILE_VERSION, annotations: all });
22011
+ }
22012
+ });
21795
22013
  });
21796
22014
  return annotation;
21797
22015
  }
@@ -21804,21 +22022,23 @@ var AnnotationsStore = class {
21804
22022
  async resolve(input) {
21805
22023
  let updated = null;
21806
22024
  await this.enqueue(input.sessionId, async () => {
21807
- const all = await this.list(input.sessionId);
21808
- const idx = all.findIndex((a) => a.id === input.annotationId);
21809
- if (idx === -1) {
21810
- updated = null;
21811
- return;
21812
- }
21813
- const next = {
21814
- ...expectDefined18(all[idx]),
21815
- resolved: true,
21816
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
21817
- resolvedBy: input.resolvedBy
21818
- };
21819
- all[idx] = next;
21820
- await this.writeFile(input.sessionId, { version: FILE_VERSION, annotations: all });
21821
- updated = next;
22025
+ await withFileLock(this.filePath(input.sessionId), async () => {
22026
+ const all = await this.list(input.sessionId);
22027
+ const idx = all.findIndex((a) => a.id === input.annotationId);
22028
+ if (idx === -1) {
22029
+ updated = null;
22030
+ return;
22031
+ }
22032
+ const next = {
22033
+ ...expectDefined18(all[idx]),
22034
+ resolved: true,
22035
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
22036
+ resolvedBy: input.resolvedBy
22037
+ };
22038
+ all[idx] = next;
22039
+ await this.writeFile(input.sessionId, { version: FILE_VERSION, annotations: all });
22040
+ updated = next;
22041
+ });
21822
22042
  });
21823
22043
  return updated;
21824
22044
  }
@@ -21919,22 +22139,22 @@ var ReplayLogStore = class {
21919
22139
  async record(input) {
21920
22140
  const hash = hashRequest(input.request);
21921
22141
  await this.enqueue(input.sessionId, async () => {
21922
- const cache = await this.ensureCache(input.sessionId);
21923
- if (cache.has(hash)) return;
21924
- const entry = {
21925
- hash,
21926
- ts: (/* @__PURE__ */ new Date()).toISOString(),
21927
- request: input.request,
21928
- response: input.response
21929
- };
21930
- cache.set(hash, entry);
21931
- const count = (this.diskCount.get(input.sessionId) ?? 0) + 1;
21932
- if (count > this.maxEntries) {
21933
- await this.compact(input.sessionId, cache);
21934
- } else {
21935
- await fsp3.appendFile(this.filePath(input.sessionId), JSON.stringify(entry) + "\n", "utf8");
21936
- this.diskCount.set(input.sessionId, count);
21937
- }
22142
+ await withFileLock(this.filePath(input.sessionId), async () => {
22143
+ const entries = await this.readAll(input.sessionId);
22144
+ if (entries.some((entry2) => entry2.hash === hash)) return;
22145
+ const entry = {
22146
+ hash,
22147
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
22148
+ request: input.request,
22149
+ response: input.response
22150
+ };
22151
+ entries.push(entry);
22152
+ const keep = entries.slice(-this.maxEntries);
22153
+ const cache = /* @__PURE__ */ new Map();
22154
+ for (const e of keep) cache.set(e.hash, e);
22155
+ this.cache.set(input.sessionId, cache);
22156
+ await this.rewriteCache(input.sessionId, cache);
22157
+ });
21938
22158
  });
21939
22159
  return hash;
21940
22160
  }
@@ -21943,7 +22163,7 @@ var ReplayLogStore = class {
21943
22163
  * Called when entry count exceeds the cap. Rewrites the entire file
21944
22164
  * but only happens O(n / maxEntries) times per session.
21945
22165
  */
21946
- async compact(sessionId, cache) {
22166
+ async rewriteCache(sessionId, cache) {
21947
22167
  const all = [...cache.values()];
21948
22168
  const keep = all.slice(-this.maxEntries);
21949
22169
  await this.writeAll(sessionId, keep);
@@ -22007,11 +22227,12 @@ var ReplayLogStore = class {
22007
22227
  for (const line of raw.split("\n")) {
22008
22228
  if (!line.trim()) continue;
22009
22229
  try {
22010
- const parsed = JSON.parse(line);
22011
- if ("entry" in parsed && parsed.entry) {
22012
- out.push(parsed.entry);
22230
+ const parsed = safeParse(line);
22231
+ if (!parsed.ok || !parsed.value) continue;
22232
+ if ("entry" in parsed.value && parsed.value.entry) {
22233
+ out.push(parsed.value.entry);
22013
22234
  } else {
22014
- out.push(parsed);
22235
+ out.push(parsed.value);
22015
22236
  }
22016
22237
  } catch {
22017
22238
  }
@@ -22071,15 +22292,15 @@ var SessionRecovery = class {
22071
22292
  async detectStale(sessionId) {
22072
22293
  const fp = this.filePath(sessionId);
22073
22294
  const TAIL_SIZE = 8192;
22074
- let stat10;
22295
+ let stat11;
22075
22296
  try {
22076
- stat10 = await fsp3.stat(fp);
22297
+ stat11 = await fsp3.stat(fp);
22077
22298
  } catch (err) {
22078
22299
  if (err.code === "ENOENT") return null;
22079
22300
  return null;
22080
22301
  }
22081
- if (stat10.size === 0) return null;
22082
- const position = Math.max(0, stat10.size - TAIL_SIZE);
22302
+ if (stat11.size === 0) return null;
22303
+ const position = Math.max(0, stat11.size - TAIL_SIZE);
22083
22304
  const buf = Buffer.alloc(TAIL_SIZE);
22084
22305
  let fh;
22085
22306
  try {
@@ -22194,6 +22415,9 @@ var SessionRecovery = class {
22194
22415
  return path6.join(this.dir, `${sessionId}.jsonl`);
22195
22416
  }
22196
22417
  };
22418
+
22419
+ // src/storage/tool-audit-log.ts
22420
+ init_atomic_write();
22197
22421
  function expectDefined20(value) {
22198
22422
  if (value === null || value === void 0) {
22199
22423
  throw new Error("Expected value to be defined");
@@ -22225,37 +22449,42 @@ var ToolAuditLog = class {
22225
22449
  async record(input) {
22226
22450
  let entry = null;
22227
22451
  await this.enqueue(input.sessionId, async () => {
22228
- const prevHash = this.tailHash.get(input.sessionId) ?? GENESIS_PREV;
22229
- const index = this.tailIndex.get(input.sessionId) ?? 0;
22230
- const id = randomUUID();
22231
- const ts = (/* @__PURE__ */ new Date()).toISOString();
22232
- const content = {
22233
- id,
22234
- ts,
22235
- prevHash,
22236
- toolName: input.toolName,
22237
- toolUseId: input.toolUseId,
22238
- input: input.input,
22239
- output: input.output,
22240
- isError: input.isError,
22241
- index
22242
- };
22243
- const hash = createHash("sha256").update(stableStringify2(content), "utf8").digest("hex");
22244
- entry = {
22245
- id,
22246
- ts,
22247
- prevHash,
22248
- hash,
22249
- toolName: input.toolName,
22250
- toolUseId: input.toolUseId,
22251
- input: input.input,
22252
- output: input.output,
22253
- isError: input.isError,
22254
- index
22255
- };
22256
- await this.appendLine(input.sessionId, entry);
22257
- this.tailHash.set(input.sessionId, hash);
22258
- this.tailIndex.set(input.sessionId, index + 1);
22452
+ await withFileLock(this.filePath(input.sessionId), async () => {
22453
+ const entries = await this.readAll(input.sessionId);
22454
+ const prev = entries.at(-1);
22455
+ const prevHash = prev?.hash ?? GENESIS_PREV;
22456
+ const index = prev ? prev.index + 1 : 0;
22457
+ const id = randomUUID();
22458
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
22459
+ const content = {
22460
+ id,
22461
+ ts,
22462
+ prevHash,
22463
+ toolName: input.toolName,
22464
+ toolUseId: input.toolUseId,
22465
+ input: input.input,
22466
+ output: input.output,
22467
+ isError: input.isError,
22468
+ index
22469
+ };
22470
+ const hash = createHash("sha256").update(stableStringify2(content), "utf8").digest("hex");
22471
+ entry = {
22472
+ id,
22473
+ ts,
22474
+ prevHash,
22475
+ hash,
22476
+ toolName: input.toolName,
22477
+ toolUseId: input.toolUseId,
22478
+ input: input.input,
22479
+ output: input.output,
22480
+ isError: input.isError,
22481
+ index
22482
+ };
22483
+ entries.push(entry);
22484
+ await this.writeAll(input.sessionId, entries);
22485
+ this.tailHash.set(input.sessionId, hash);
22486
+ this.tailIndex.set(input.sessionId, index + 1);
22487
+ });
22259
22488
  });
22260
22489
  return entry;
22261
22490
  }
@@ -22325,7 +22554,8 @@ var ToolAuditLog = class {
22325
22554
  for (const line of raw.split("\n")) {
22326
22555
  if (!line.trim()) continue;
22327
22556
  try {
22328
- out.push(JSON.parse(line));
22557
+ const parsed = safeParse(line);
22558
+ if (parsed.ok && parsed.value) out.push(parsed.value);
22329
22559
  } catch {
22330
22560
  }
22331
22561
  }
@@ -22335,10 +22565,10 @@ var ToolAuditLog = class {
22335
22565
  return [];
22336
22566
  }
22337
22567
  }
22338
- async appendLine(sessionId, entry) {
22568
+ async writeAll(sessionId, entries) {
22339
22569
  const fp = this.filePath(sessionId);
22340
- const line = JSON.stringify(entry) + "\n";
22341
- await fsp3.appendFile(fp, line, "utf8");
22570
+ const line = entries.map((e) => JSON.stringify(e)).join("\n") + (entries.length ? "\n" : "");
22571
+ await atomicWrite(fp, line, { mode: 384 });
22342
22572
  const count = (this.unSyncedWrites.get(sessionId) ?? 0) + 1;
22343
22573
  this.unSyncedWrites.set(sessionId, count);
22344
22574
  if (this.fsyncEvery !== Number.POSITIVE_INFINITY && count % this.fsyncEvery === 0) {
@@ -22855,8 +23085,8 @@ var CloudSync = class {
22855
23085
  const localPath = this.categoryToPath(cat);
22856
23086
  if (!localPath) continue;
22857
23087
  try {
22858
- const stat10 = await fsp3.stat(localPath);
22859
- if (stat10.isDirectory()) {
23088
+ const stat11 = await fsp3.stat(localPath);
23089
+ if (stat11.isDirectory()) {
22860
23090
  const files = await this.walkDir(localPath, localPath);
22861
23091
  for (const file of files) {
22862
23092
  const content = await fsp3.readFile(file, "utf8");
@@ -22881,8 +23111,8 @@ var CloudSync = class {
22881
23111
  const localPath = this.categoryToPath(cat);
22882
23112
  if (!localPath) continue;
22883
23113
  try {
22884
- const stat10 = await fsp3.stat(localPath);
22885
- if (stat10.isDirectory()) {
23114
+ const stat11 = await fsp3.stat(localPath);
23115
+ if (stat11.isDirectory()) {
22886
23116
  const files = await this.walkDir(localPath, localPath);
22887
23117
  for (const file of files) {
22888
23118
  const content = await fsp3.readFile(file);
@@ -27470,8 +27700,8 @@ ${this.skillBodyCache}`);
27470
27700
  }
27471
27701
  async dirExists(p) {
27472
27702
  try {
27473
- const stat10 = await fsp3.stat(p);
27474
- return stat10.isDirectory();
27703
+ const stat11 = await fsp3.stat(p);
27704
+ return stat11.isDirectory();
27475
27705
  } catch {
27476
27706
  return false;
27477
27707
  }
@@ -27967,7 +28197,7 @@ var DefaultPluginAPI = class {
27967
28197
  return off;
27968
28198
  }
27969
28199
  emitCustom(event, payload) {
27970
- this.events.emit(event, payload);
28200
+ this.events.emitCustom(event, payload);
27971
28201
  }
27972
28202
  onConfigChange(handler) {
27973
28203
  if (!this.configStore) return () => {
@@ -29189,6 +29419,7 @@ var AutoPhaseRunner = class {
29189
29419
  orchestrator = null;
29190
29420
  opts;
29191
29421
  progressInterval = null;
29422
+ maxRunTimer = null;
29192
29423
  graphCompletedHandler = (payload) => {
29193
29424
  const p = payload;
29194
29425
  if (this.graph && p.graphId === this.graph.id) {
@@ -29256,6 +29487,11 @@ var AutoPhaseRunner = class {
29256
29487
  if (progress) this.opts.onProgress?.(progress);
29257
29488
  }, 2e3);
29258
29489
  }
29490
+ this.maxRunTimer = setTimeout(
29491
+ () => this.stop(),
29492
+ this.opts.maxRunDurationMs ?? 24 * 60 * 6e4
29493
+ );
29494
+ this.maxRunTimer.unref?.();
29259
29495
  if (this.opts.events) {
29260
29496
  const events = this.opts.events;
29261
29497
  const onUntyped = events.on;
@@ -29298,6 +29534,10 @@ var AutoPhaseRunner = class {
29298
29534
  clearInterval(this.progressInterval);
29299
29535
  this.progressInterval = null;
29300
29536
  }
29537
+ if (this.maxRunTimer) {
29538
+ clearTimeout(this.maxRunTimer);
29539
+ this.maxRunTimer = null;
29540
+ }
29301
29541
  this.unsubscribeCompleted?.();
29302
29542
  this.unsubscribeCompleted = null;
29303
29543
  this.unsubscribeFailed?.();
@@ -31003,6 +31243,21 @@ function buildCommitCommand() {
31003
31243
  }
31004
31244
  const dryRun = args.includes("--dry-run") || args.includes("-n");
31005
31245
  const noLlm = args.includes("--no-llm");
31246
+ let worktreeWarning = "";
31247
+ try {
31248
+ const wtResult = await runGit(["worktree", "list", "--porcelain"], cwd);
31249
+ const worktrees = wtResult.stdout.split("\n\n").filter((b) => b.trim().startsWith("worktree "));
31250
+ if (worktrees.length > 1) {
31251
+ const branches = worktrees.map((b) => {
31252
+ const branchLine = b.split("\n").find((l) => l.startsWith("branch "));
31253
+ return branchLine ? branchLine.slice(7).replace("refs/heads/", "") : "?";
31254
+ }).filter(Boolean);
31255
+ worktreeWarning = `
31256
+ ${color.yellow("\u26A0")} ${color.dim("Simultaneous edits:")} ${worktrees.length} worktrees active (${branches.join(", ")}). ${color.dim("Changes from other agents may be captured. Review the diff below.")}
31257
+ `;
31258
+ }
31259
+ } catch {
31260
+ }
31006
31261
  let message = null;
31007
31262
  const provider = noLlm ? null : asLLMProvider(ctx?.provider);
31008
31263
  if (provider && ctx?.model) {
@@ -31011,26 +31266,40 @@ function buildCommitCommand() {
31011
31266
  }
31012
31267
  if (!message) message = await generateCommitMessageHeuristics(cwd);
31013
31268
  if (dryRun) {
31269
+ const diffStat2 = (await runGit(["diff", "--stat"], cwd)).stdout || "(no changes)";
31014
31270
  return {
31015
- message: `Would commit:
31016
-
31017
- ${color.green(message)}
31018
-
31019
- ${color.dim("(dry-run \u2014 no actual commit)")}`
31271
+ message: [
31272
+ worktreeWarning,
31273
+ `${color.dim("Would commit:")}`,
31274
+ ` ${color.green(message)}`,
31275
+ "",
31276
+ `${color.dim(diffStat2)}`,
31277
+ `${color.dim("(dry-run \u2014 no actual commit)")}`
31278
+ ].filter(Boolean).join("\n")
31020
31279
  };
31021
31280
  }
31022
31281
  const stageResult = await runGit(["add", "."], cwd);
31023
31282
  if (stageResult.code !== 0) return { message: `Stage failed: ${stageResult.stderr}` };
31283
+ const diffStat = (await runGit(["diff", "--cached", "--stat"], cwd)).stdout || "";
31284
+ const fullDiff = (await runGit(["diff", "--cached"], cwd)).stdout || "";
31285
+ const diffPreview = fullDiff.length > 8e3 ? fullDiff.slice(0, 8e3) + "\n\n... (diff truncated, showing first 8KB)" : fullDiff;
31024
31286
  const commitResult = await runGit(["commit", "-m", message], cwd);
31025
31287
  if (commitResult.code !== 0) return { message: `Commit failed: ${commitResult.stderr}` };
31026
31288
  const hash = (await runGit(["rev-parse", "--short", "HEAD"], cwd)).stdout.trim();
31027
31289
  const hasRemote = (await runGit(["remote"], cwd)).stdout.trim().length > 0;
31028
31290
  const pushMsg = hasRemote ? `
31029
-
31030
31291
  ${color.dim("Tip: Run /push to push to remote")}` : "";
31031
31292
  return {
31032
- message: `${color.green("\u2713")} Committed: ${color.bold(message)}
31033
- ${color.dim(hash)}${pushMsg}`
31293
+ message: [
31294
+ worktreeWarning,
31295
+ `${color.green("\u2713")} Committed: ${color.bold(message)}`,
31296
+ ` ${color.dim(hash)}`,
31297
+ "",
31298
+ color.dim("\u2500\u2500\u2500 Staged diff \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),
31299
+ color.dim(diffStat),
31300
+ diffPreview ? color.dim(diffPreview) : "",
31301
+ pushMsg
31302
+ ].filter(Boolean).join("\n")
31034
31303
  };
31035
31304
  }
31036
31305
  };
@@ -31574,6 +31843,6 @@ ${formatPlan(updated)}`
31574
31843
  };
31575
31844
  }
31576
31845
 
31577
- 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, BrainDecisionQueue, 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, DefaultBrainArbiter, 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, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, 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, bootConfig, 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, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expectDefined7 as expectDefined, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hashRequest, hookMatcherMatches, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isPluginError, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, 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, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, normalizedEqual, onResize, parseContinueDirective, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setOutputLineGuard, setPlanItemStatus, setRawMode, shouldEnhance, slackServer, sleep, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
31846
+ 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, BrainDecisionQueue, 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_SESSION_PRUNE_DAYS, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultBrainArbiter, 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, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, HookRegistry, HookRunner, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, 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, bootConfig, 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, enhanceUserPrompt, ensureDir, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expectDefined7 as expectDefined, extractRunEnv, filesystemServer, findCriticalPath, flagsToConfigPatch, formatContextWindowModeList, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getPlanTemplate, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hashRequest, hookMatcherMatches, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isPluginError, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, 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, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, normalizedEqual, onResize, parseContinueDirective, parseSkillRef, pendingBtwCount, phaseForRole, projectHash, projectSlug, recentTextTurns, recordActualUsage, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resetCalibration, resolveAuditLevel, resolveContextWindowPolicy, resolveModelMatrix, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, scoreAgents, securitySlashCommand, sentinelServer, setBtwNote, setOutputLineGuard, setPlanItemStatus, setRawMode, shouldEnhance, slackServer, sleep, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, withFileLock, wrapAsState, writeErr, writeOut, zaiVisionServer };
31578
31847
  //# sourceMappingURL=index.js.map
31579
31848
  //# sourceMappingURL=index.js.map