@wrongstack/core 0.77.0 → 0.82.6

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 (79) hide show
  1. package/dist/{agent-bridge-EWdqs8v6.d.ts → agent-bridge-C9P_HPez.d.ts} +2 -2
  2. package/dist/{agent-subagent-runner-D8qW8OSC.d.ts → agent-subagent-runner-2Aq0jOSj.d.ts} +107 -102
  3. package/dist/{compactor-D_ExJajC.d.ts → compactor-CJq7LQev.d.ts} +3 -3
  4. package/dist/{config-Dy0CK_o6.d.ts → config-_DZ7dN-T.d.ts} +77 -75
  5. package/dist/{context-y87Jc5ei.d.ts → context-ToHAp4-U.d.ts} +119 -90
  6. package/dist/coordination/index.d.ts +16 -16
  7. package/dist/coordination/index.js +318 -37
  8. package/dist/coordination/index.js.map +1 -1
  9. package/dist/defaults/index.d.ts +31 -31
  10. package/dist/defaults/index.js +419 -67
  11. package/dist/defaults/index.js.map +1 -1
  12. package/dist/{director-state-BmYi3DGA.d.ts → director-state-CgIc30qi.d.ts} +19 -19
  13. package/dist/{events-CYaoLN5_.d.ts → events-DnRqXaZ3.d.ts} +43 -42
  14. package/dist/execution/index.d.ts +53 -53
  15. package/dist/execution/index.js +67 -23
  16. package/dist/execution/index.js.map +1 -1
  17. package/dist/extension/index.d.ts +9 -9
  18. package/dist/extension/index.js +8 -1
  19. package/dist/extension/index.js.map +1 -1
  20. package/dist/{goal-store-C7jcumEh.d.ts → goal-store-DvWLNu52.d.ts} +4 -4
  21. package/dist/{index-DIxjTOga.d.ts → index-BNOLadHw.d.ts} +28 -28
  22. package/dist/{index-Dsda0uCn.d.ts → index-N0_c4bHQ.d.ts} +45 -45
  23. package/dist/index.d.ts +165 -165
  24. package/dist/index.js +593 -137
  25. package/dist/index.js.map +1 -1
  26. package/dist/infrastructure/index.d.ts +9 -9
  27. package/dist/infrastructure/index.js +13 -5
  28. package/dist/infrastructure/index.js.map +1 -1
  29. package/dist/kernel/index.d.ts +14 -14
  30. package/dist/kernel/index.js +7 -0
  31. package/dist/kernel/index.js.map +1 -1
  32. package/dist/logger-B72yyPc6.d.ts +12 -0
  33. package/dist/{logger-BppKxDqZ.d.ts → logger-C_27pj9i.d.ts} +6 -7
  34. package/dist/{mcp-servers-T0O6UN_w.d.ts → mcp-servers-Dck3T85_.d.ts} +20 -20
  35. package/dist/{mode-BO4SEUIv.d.ts → mode-CHo2XtHs.d.ts} +4 -4
  36. package/dist/models/index.d.ts +10 -10
  37. package/dist/models/index.js +8 -2
  38. package/dist/models/index.js.map +1 -1
  39. package/dist/{models-registry-BcYJDKLm.d.ts → models-registry-Be3osGt5.d.ts} +28 -28
  40. package/dist/{models-registry-Cuq1C8V9.d.ts → models-registry-Boz639EI.d.ts} +12 -12
  41. package/dist/{multi-agent-coordinator-DpbG3wiy.d.ts → multi-agent-coordinator-DllpCVkF.d.ts} +12 -12
  42. package/dist/{null-fleet-bus-u5ys3lW_.d.ts → null-fleet-bus-BY0AN-sr.d.ts} +121 -121
  43. package/dist/observability/index.d.ts +41 -41
  44. package/dist/observability/index.js.map +1 -1
  45. package/dist/{observability-BhnVLBLS.d.ts → observability-CoSNZdhX.d.ts} +4 -4
  46. package/dist/{parallel-eternal-engine-Dn0P8Pbj.d.ts → parallel-eternal-engine-D402RASp.d.ts} +49 -49
  47. package/dist/{path-resolver-B32v2JIq.d.ts → path-resolver-UPFTsDyD.d.ts} +6 -6
  48. package/dist/{permission-V5BLOrY6.d.ts → permission-14CChMmO.d.ts} +10 -8
  49. package/dist/{permission-policy-CBVx-d-8.d.ts → permission-policy-gW5htOo1.d.ts} +7 -7
  50. package/dist/{plan-templates-BcUwLlMQ.d.ts → plan-templates-DRvPgkfZ.d.ts} +65 -32
  51. package/dist/{provider-runner-CSi_7l0h.d.ts → provider-runner-COAJM8tC.d.ts} +6 -6
  52. package/dist/{retry-policy-CG3qvH_e.d.ts → retry-policy-DSu6O6rD.d.ts} +4 -4
  53. package/dist/sdd/index.d.ts +47 -47
  54. package/dist/sdd/index.js +47 -22
  55. package/dist/sdd/index.js.map +1 -1
  56. package/dist/security/index.d.ts +6 -6
  57. package/dist/security/index.js +7 -1
  58. package/dist/security/index.js.map +1 -1
  59. package/dist/{selector-RvBR_YRW.d.ts → selector-11-fm95U.d.ts} +2 -2
  60. package/dist/{session-event-bridge-CDHxcmQU.d.ts → session-event-bridge-D0u-x576.d.ts} +7 -7
  61. package/dist/{session-reader-BIpwM60D.d.ts → session-reader-BQU-toaN.d.ts} +23 -23
  62. package/dist/{skill-CxuWrsKK.d.ts → skill-BJeF2DwY.d.ts} +1 -1
  63. package/dist/skills/index.d.ts +9 -9
  64. package/dist/skills/index.js +15 -3
  65. package/dist/skills/index.js.map +1 -1
  66. package/dist/storage/index.d.ts +15 -15
  67. package/dist/storage/index.js +378 -76
  68. package/dist/storage/index.js.map +1 -1
  69. package/dist/{system-prompt-CA11g6Jo.d.ts → system-prompt-C0rLCeyn.d.ts} +16 -11
  70. package/dist/{task-graph-D1YQbpxF.d.ts → task-graph-CikNdRTG.d.ts} +22 -22
  71. package/dist/types/index.d.ts +25 -25
  72. package/dist/types/index.js +45 -10
  73. package/dist/types/index.js.map +1 -1
  74. package/dist/utils/index.d.ts +46 -45
  75. package/dist/utils/index.js +53 -12
  76. package/dist/utils/index.js.map +1 -1
  77. package/dist/{wstack-paths-D7evAFWM.d.ts → wstack-paths-BQMvEllz.d.ts} +2 -2
  78. package/package.json +1 -1
  79. package/dist/logger-DDd5C--Z.d.ts +0 -12
package/dist/index.js CHANGED
@@ -419,6 +419,13 @@ var Container = class {
419
419
  has(token) {
420
420
  return this.entries.has(token);
421
421
  }
422
+ /**
423
+ * Resolve a token if it is bound, otherwise return undefined.
424
+ * Unlike resolve(), this does not throw if the token is unbound.
425
+ */
426
+ safeResolve(token) {
427
+ return this.has(token) ? this.resolve(token) : void 0;
428
+ }
422
429
  ownerOf(token) {
423
430
  return this.entries.get(token)?.owner;
424
431
  }
@@ -1338,9 +1345,20 @@ function setRawMode(input, mode) {
1338
1345
  input.setRawMode(mode);
1339
1346
  return true;
1340
1347
  }
1348
+ var activeOutputGuard = null;
1349
+ function setOutputLineGuard(guard) {
1350
+ activeOutputGuard = guard;
1351
+ }
1341
1352
  function writeTo(s, stream) {
1342
1353
  if (!stream || typeof stream.write !== "function") return false;
1354
+ const guard = activeOutputGuard;
1355
+ if (!guard) {
1356
+ stream.write(s);
1357
+ return true;
1358
+ }
1359
+ guard.suspend();
1343
1360
  stream.write(s);
1361
+ guard.resume();
1344
1362
  return true;
1345
1363
  }
1346
1364
  function writeOut(s, stream = process.stdout) {
@@ -1515,7 +1533,7 @@ var DefaultTokenCounter = class {
1515
1533
  } else if (this.registry && this.providerId && model) {
1516
1534
  if (this.priceCache.size >= PRICE_CACHE_MAX_SIZE) {
1517
1535
  const keys = [...this.priceCache.keys()];
1518
- this.priceCache.delete(keys[0]);
1536
+ this.priceCache.delete(keys[0] ?? "");
1519
1537
  }
1520
1538
  void this.registry.getModel(this.providerId, model).then((m) => {
1521
1539
  if (m) {
@@ -1540,7 +1558,7 @@ var DefaultTokenCounter = class {
1540
1558
  const price = priceFromModel(resolved);
1541
1559
  if (this.priceCache.size >= PRICE_CACHE_MAX_SIZE) {
1542
1560
  const keys = [...this.priceCache.keys()];
1543
- this.priceCache.delete(keys[0]);
1561
+ this.priceCache.delete(keys[0] ?? "");
1544
1562
  }
1545
1563
  this.priceCache.set(resolved.modelId, price);
1546
1564
  this.applyPrice(usage, price);
@@ -1608,6 +1626,12 @@ function round4(n) {
1608
1626
  }
1609
1627
 
1610
1628
  // src/utils/token-estimate.ts
1629
+ function expectDefined(value) {
1630
+ if (value === null || value === void 0) {
1631
+ throw new Error("Expected value to be defined");
1632
+ }
1633
+ return value;
1634
+ }
1611
1635
  var RoughTokenEstimate = (text, charsPerToken = 3.5) => Math.max(1, Math.ceil(text.length / charsPerToken));
1612
1636
  var _cal = {
1613
1637
  ratio: 1,
@@ -1628,7 +1652,7 @@ function getCachedEstimate(key, compute) {
1628
1652
  if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {
1629
1653
  const keys = [...ESTIMATE_CACHE.keys()];
1630
1654
  for (let i = 0; i < Math.floor(ESTIMATE_CACHE_MAX_SIZE / 4); i++) {
1631
- ESTIMATE_CACHE.delete(keys[i]);
1655
+ ESTIMATE_CACHE.delete(expectDefined(keys[i]));
1632
1656
  }
1633
1657
  }
1634
1658
  const estimate = compute();
@@ -1741,6 +1765,12 @@ function resetCalibration() {
1741
1765
  }
1742
1766
 
1743
1767
  // src/utils/message-invariants.ts
1768
+ function expectDefined2(value) {
1769
+ if (value === null || value === void 0) {
1770
+ throw new Error("Expected value to be defined");
1771
+ }
1772
+ return value;
1773
+ }
1744
1774
  function repairToolUseAdjacency(messages) {
1745
1775
  const removedToolUses = [];
1746
1776
  const removedToolResults = [];
@@ -1748,7 +1778,7 @@ function repairToolUseAdjacency(messages) {
1748
1778
  let changed = false;
1749
1779
  const out = [];
1750
1780
  for (let i = 0; i < messages.length; i++) {
1751
- const original = messages[i];
1781
+ const original = expectDefined2(messages[i]);
1752
1782
  let msg = original;
1753
1783
  if (hasToolUse(msg)) {
1754
1784
  const nextIds = toolResultIds(messages[i + 1]);
@@ -2906,6 +2936,12 @@ Remember: your job is to make the user a better developer, not just to complete
2906
2936
  ];
2907
2937
 
2908
2938
  // src/types/context-window.ts
2939
+ function expectDefined3(value) {
2940
+ if (value === null || value === void 0) {
2941
+ throw new Error("Expected value to be defined");
2942
+ }
2943
+ return value;
2944
+ }
2909
2945
  var DEFAULT_CONTEXT_WINDOW_MODE_ID = "balanced";
2910
2946
  var CONTEXT_WINDOW_MODES = Object.freeze([
2911
2947
  {
@@ -2962,7 +2998,7 @@ function isContextWindowModeId(id) {
2962
2998
  }
2963
2999
  function resolveContextWindowPolicy(config = {}, overrideMode) {
2964
3000
  const requested = overrideMode ?? config.mode ?? DEFAULT_CONTEXT_WINDOW_MODE_ID;
2965
- const mode = getContextWindowMode(requested) ?? getContextWindowMode(DEFAULT_CONTEXT_WINDOW_MODE_ID);
3001
+ const mode = getContextWindowMode(requested) ?? expectDefined3(getContextWindowMode(DEFAULT_CONTEXT_WINDOW_MODE_ID));
2966
3002
  if (mode.id !== DEFAULT_CONTEXT_WINDOW_MODE_ID) {
2967
3003
  return mode;
2968
3004
  }
@@ -3013,7 +3049,7 @@ var InMemoryBridgeTransport = class {
3013
3049
  }
3014
3050
  subscribe(agentId, handler) {
3015
3051
  if (!this.subs.has(agentId)) this.subs.set(agentId, /* @__PURE__ */ new Set());
3016
- this.subs.get(agentId).add(handler);
3052
+ this.subs.get(agentId)?.add(handler);
3017
3053
  return () => this.subs.get(agentId)?.delete(handler);
3018
3054
  }
3019
3055
  close(agentId) {
@@ -3442,6 +3478,12 @@ function sizeSignals(toolName, content) {
3442
3478
  }
3443
3479
 
3444
3480
  // src/execution/tool-executor.ts
3481
+ function expectDefined4(value) {
3482
+ if (value === null || value === void 0) {
3483
+ throw new Error("Expected value to be defined");
3484
+ }
3485
+ return value;
3486
+ }
3445
3487
  var ToolExecutor = class {
3446
3488
  constructor(registry, opts) {
3447
3489
  this.registry = registry;
@@ -3730,6 +3772,9 @@ ${post.additionalContext}` };
3730
3772
  async runStreamedTool(tool, input, ctx, signal, toolUseId) {
3731
3773
  let finalOutput;
3732
3774
  let sawFinal = false;
3775
+ if (!tool.executeStream) {
3776
+ throw new Error(`Tool "${tool.name}" does not support streaming execution`);
3777
+ }
3733
3778
  const stream = tool.executeStream(input, ctx, { signal });
3734
3779
  for await (const ev of stream) {
3735
3780
  if (ev.type === "final") {
@@ -3834,7 +3879,7 @@ function hasMalformedArguments(input) {
3834
3879
  function extractMalformedRaw(input) {
3835
3880
  if (!hasMalformedArguments(input)) return void 0;
3836
3881
  const obj = input;
3837
- const value = obj[Object.keys(obj)[0]];
3882
+ const value = obj[expectDefined4(Object.keys(obj)[0])];
3838
3883
  if (value === void 0 || value === null) return void 0;
3839
3884
  if (typeof value === "string") return value;
3840
3885
  try {
@@ -3881,6 +3926,12 @@ function compileUserRegex(pattern, flags) {
3881
3926
  }
3882
3927
 
3883
3928
  // src/storage/session-reader.ts
3929
+ function expectDefined5(value) {
3930
+ if (value === null || value === void 0) {
3931
+ throw new Error("Expected value to be defined");
3932
+ }
3933
+ return value;
3934
+ }
3884
3935
  var DefaultSessionReader = class {
3885
3936
  store;
3886
3937
  constructor(opts) {
@@ -3942,7 +3993,7 @@ var DefaultSessionReader = class {
3942
3993
  continue;
3943
3994
  }
3944
3995
  for (let i = 0; i < data.events.length; i++) {
3945
- const ev = data.events[i];
3996
+ const ev = expectDefined5(data.events[i]);
3946
3997
  if (allowedTypes && !allowedTypes.has(ev.type)) continue;
3947
3998
  const text = eventText(ev);
3948
3999
  if (text === null) continue;
@@ -4210,7 +4261,7 @@ function escapeControlCharsInStrings(s) {
4210
4261
  let inString = false;
4211
4262
  let out = "";
4212
4263
  for (let i = 0; i < s.length; i++) {
4213
- const c = s[i];
4264
+ const c = s.charAt(i);
4214
4265
  if (c === '"' && (i === 0 || s[i - 1] !== "\\")) {
4215
4266
  inString = !inString;
4216
4267
  out += c;
@@ -4248,12 +4299,12 @@ function stripSingleLineComments(s) {
4248
4299
  const chars = [];
4249
4300
  let i = 0;
4250
4301
  while (i < s.length) {
4251
- const c = s[i];
4252
- if (c === '"' && (i === 0 || s[i - 1] !== "\\")) {
4302
+ const c = s.charAt(i);
4303
+ if (c === '"' && (i === 0 || s.charAt(i - 1) !== "\\")) {
4253
4304
  inString = !inString;
4254
4305
  chars.push(c);
4255
- } else if (c === "/" && s[i + 1] === "/" && !inString) {
4256
- while (i < s.length && s[i] !== "\n") i++;
4306
+ } else if (c === "/" && s.charAt(i + 1) === "/" && !inString) {
4307
+ while (i < s.length && s.charAt(i) !== "\n") i++;
4257
4308
  } else {
4258
4309
  chars.push(c);
4259
4310
  }
@@ -4310,6 +4361,12 @@ function formatTodosList(todos) {
4310
4361
  }
4311
4362
 
4312
4363
  // src/utils/glob-match.ts
4364
+ function expectDefined6(value) {
4365
+ if (value === null || value === void 0) {
4366
+ throw new Error("Expected value to be defined");
4367
+ }
4368
+ return value;
4369
+ }
4313
4370
  function escapeRegex(s) {
4314
4371
  return s.replace(/[.+^${}()|\\]/g, "\\$&");
4315
4372
  }
@@ -4321,7 +4378,7 @@ function getCachedGlob(pattern) {
4321
4378
  if (COMPILED_GLOB_CACHE.size >= CACHE_MAX_SIZE) {
4322
4379
  const keys = [...COMPILED_GLOB_CACHE.keys()];
4323
4380
  for (let i = 0; i < Math.floor(CACHE_MAX_SIZE / 4); i++) {
4324
- COMPILED_GLOB_CACHE.delete(keys[i]);
4381
+ COMPILED_GLOB_CACHE.delete(expectDefined6(keys[i]));
4325
4382
  }
4326
4383
  }
4327
4384
  const re = compileGlob(pattern);
@@ -4676,6 +4733,12 @@ function buildChildEnv(optsOrSessionId) {
4676
4733
  if (opts.sessionId) out["WRONGSTACK_SESSION_ID"] = opts.sessionId;
4677
4734
  return out;
4678
4735
  }
4736
+ function expectDefined7(value) {
4737
+ if (value === null || value === void 0) {
4738
+ throw new Error("Expected value to be defined");
4739
+ }
4740
+ return value;
4741
+ }
4679
4742
  var GLOB_CHARS = /* @__PURE__ */ new Set(["*", "?", "["]);
4680
4743
  var IS_WINDOWS = process.platform === "win32";
4681
4744
  var SEP = IS_WINDOWS ? "\\" : "/";
@@ -4689,7 +4752,7 @@ function globToRegex(pat) {
4689
4752
  let i = 0;
4690
4753
  let re = "^";
4691
4754
  while (i < pat.length) {
4692
- const c = pat[i];
4755
+ const c = expectDefined7(pat[i]);
4693
4756
  if (c === "*") {
4694
4757
  if (pat[i + 1] === "*") {
4695
4758
  re += ".*";
@@ -4728,7 +4791,7 @@ function globToRegex(pat) {
4728
4791
  }
4729
4792
  function baseDir(pat) {
4730
4793
  let i = pat.length - 1;
4731
- while (i >= 0 && !GLOB_CHARS.has(pat[i]) && pat[i] !== SEP && pat[i] !== "/") i--;
4794
+ while (i >= 0 && !GLOB_CHARS.has(expectDefined7(pat[i])) && pat[i] !== SEP && pat[i] !== "/") i--;
4732
4795
  const cut = i >= 0 ? pat.lastIndexOf(SEP, i) : pat.lastIndexOf("/", i);
4733
4796
  return cut < 0 ? "." : pat.slice(0, cut);
4734
4797
  }
@@ -4793,6 +4856,12 @@ async function expandGlob(pattern) {
4793
4856
  }
4794
4857
 
4795
4858
  // src/utils/json-repair.ts
4859
+ function expectDefined8(value) {
4860
+ if (value === null || value === void 0) {
4861
+ throw new Error("Expected value to be defined");
4862
+ }
4863
+ return value;
4864
+ }
4796
4865
  function completePartialObject(s) {
4797
4866
  if (!s.trim().startsWith("{")) return s;
4798
4867
  if (tryParse(s).ok) return s;
@@ -4804,7 +4873,7 @@ function completePartialObject(s) {
4804
4873
  let contentEnd = 0;
4805
4874
  let stringBraceDepth = 0;
4806
4875
  for (let i = 0; i < s.length; i++) {
4807
- const ch = s[i];
4876
+ const ch = expectDefined8(s[i]);
4808
4877
  if (inString) {
4809
4878
  contentEnd = i + 1;
4810
4879
  if (escaped) {
@@ -4900,6 +4969,12 @@ function mergeCustomModelDefs(providerCustomModels, configModels) {
4900
4969
 
4901
4970
  // src/storage/session-store.ts
4902
4971
  init_atomic_write();
4972
+ function expectDefined9(value) {
4973
+ if (value === null || value === void 0) {
4974
+ throw new Error("Expected value to be defined");
4975
+ }
4976
+ return value;
4977
+ }
4903
4978
  function sanitizeModel(model) {
4904
4979
  return model.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
4905
4980
  }
@@ -4910,7 +4985,7 @@ function generateSessionId(startedAt, model) {
4910
4985
  const modelPart = model ? `_${sanitizeModel(model)}` : "";
4911
4986
  return `${date}/${time}Z${modelPart}_${suffix}`;
4912
4987
  }
4913
- var DefaultSessionStore = class {
4988
+ var DefaultSessionStore = class _DefaultSessionStore {
4914
4989
  dir;
4915
4990
  events;
4916
4991
  secretScrubber;
@@ -4919,6 +4994,10 @@ var DefaultSessionStore = class {
4919
4994
  this.events = opts.events;
4920
4995
  this.secretScrubber = opts.secretScrubber;
4921
4996
  }
4997
+ /** Absolute path to the session index file. */
4998
+ get indexFile() {
4999
+ return path6.join(this.dir, "_index.jsonl");
5000
+ }
4922
5001
  /** Join session ID to its absolute path within the store directory. */
4923
5002
  sessionPath(id, ext) {
4924
5003
  return path6.join(this.dir, `${id}${ext}`);
@@ -4951,7 +5030,8 @@ var DefaultSessionStore = class {
4951
5030
  return new FileSessionWriter(id, handle, startedAt, meta, this.events, {
4952
5031
  dir: shardDir,
4953
5032
  filePath: file,
4954
- secretScrubber: this.secretScrubber
5033
+ secretScrubber: this.secretScrubber,
5034
+ onClose: (s) => this.appendToIndex(s)
4955
5035
  });
4956
5036
  } catch (err) {
4957
5037
  await handle.close().catch(() => {
@@ -4982,7 +5062,7 @@ var DefaultSessionStore = class {
4982
5062
  provider: data.metadata.provider
4983
5063
  },
4984
5064
  this.events,
4985
- { resumed: true, dir: this.dir, filePath: file, secretScrubber: this.secretScrubber }
5065
+ { resumed: true, dir: this.dir, filePath: file, secretScrubber: this.secretScrubber, onClose: (s) => this.appendToIndex(s) }
4986
5066
  );
4987
5067
  return { writer, data };
4988
5068
  } catch (err) {
@@ -5012,6 +5092,15 @@ var DefaultSessionStore = class {
5012
5092
  async list(limit = 20) {
5013
5093
  try {
5014
5094
  await ensureDir(this.dir);
5095
+ const indexed = await this.readIndex();
5096
+ if (indexed.length > 0) {
5097
+ indexed.sort((a, b) => {
5098
+ if (a.startedAt < b.startedAt) return 1;
5099
+ if (a.startedAt > b.startedAt) return -1;
5100
+ return a.id.localeCompare(b.id);
5101
+ });
5102
+ return indexed.slice(0, limit);
5103
+ }
5015
5104
  const ids = await this.collectSessionIds(this.dir);
5016
5105
  const sessions = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));
5017
5106
  const out = sessions.filter((s) => s !== null);
@@ -5025,16 +5114,121 @@ var DefaultSessionStore = class {
5025
5114
  return [];
5026
5115
  }
5027
5116
  }
5028
- /** Recursively collect all session IDs from shard subdirectories. */
5029
- async collectSessionIds(dir) {
5117
+ // ── Session index (_index.jsonl) ─────────────────────────────────────────
5118
+ //
5119
+ // One JSON line per closed session, appended atomically on close().
5120
+ // When a session is deleted, a tombstone {action:"delete",id:"..."} is
5121
+ // appended. On read, tombstones filter out matching session entries.
5122
+ // This keeps listing O(lines-in-index) instead of O(files-on-disk).
5123
+ //
5124
+ // The index auto-compacts every N appends to prevent unbounded growth
5125
+ // from tombstones and duplicate entries (resume cycles).
5126
+ indexAppendCount = 0;
5127
+ static COMPACT_EVERY = 30;
5128
+ /** Append a session summary to the index. */
5129
+ async appendToIndex(summary) {
5130
+ try {
5131
+ await ensureDir(this.dir);
5132
+ const line = JSON.stringify(summary) + "\n";
5133
+ await fsp3.appendFile(this.indexFile, line, "utf8");
5134
+ this.indexAppendCount++;
5135
+ if (this.indexAppendCount >= _DefaultSessionStore.COMPACT_EVERY) {
5136
+ await this.compactIndex();
5137
+ this.indexAppendCount = 0;
5138
+ }
5139
+ } catch {
5140
+ }
5141
+ }
5142
+ /** Append a tombstone entry for a deleted session. */
5143
+ async writeTombstone(id) {
5144
+ try {
5145
+ await ensureDir(this.dir);
5146
+ const line = JSON.stringify({ action: "delete", id }) + "\n";
5147
+ await fsp3.appendFile(this.indexFile, line, "utf8");
5148
+ this.indexAppendCount++;
5149
+ } catch {
5150
+ }
5151
+ }
5152
+ /**
5153
+ * Compact the index: read all entries, drop tombstones, deduplicate
5154
+ * (keep latest per session), and rewrite. Atomic via temp+rename.
5155
+ */
5156
+ async compactIndex() {
5157
+ const entries = await this.readIndex();
5158
+ if (entries.length === 0) return;
5159
+ const tmp = `${this.indexFile}.compact.tmp`;
5160
+ const lines = entries.map((s) => JSON.stringify(s)).join("\n") + "\n";
5161
+ await fsp3.writeFile(tmp, lines, "utf8");
5162
+ await fsp3.rename(tmp, this.indexFile);
5163
+ }
5164
+ /**
5165
+ * Read the index file and return deduplicated session summaries.
5166
+ * Entries with a matching tombstone are filtered out.
5167
+ * Returns empty array when the index doesn't exist or is corrupt.
5168
+ */
5169
+ async readIndex() {
5170
+ let raw;
5171
+ try {
5172
+ raw = await fsp3.readFile(this.indexFile, "utf8");
5173
+ } catch {
5174
+ return [];
5175
+ }
5176
+ const deleted = /* @__PURE__ */ new Set();
5177
+ const seen = /* @__PURE__ */ new Map();
5178
+ for (const line of raw.split("\n")) {
5179
+ if (!line.trim()) continue;
5180
+ try {
5181
+ const entry = JSON.parse(line);
5182
+ if (entry.action === "delete" && entry.id) {
5183
+ deleted.add(entry.id);
5184
+ seen.delete(entry.id);
5185
+ continue;
5186
+ }
5187
+ if (entry.id && !deleted.has(entry.id)) {
5188
+ seen.set(entry.id, entry);
5189
+ }
5190
+ } catch {
5191
+ }
5192
+ }
5193
+ return Array.from(seen.values());
5194
+ }
5195
+ /**
5196
+ * Rebuild the index from disk by scanning all sessions and writing a
5197
+ * fresh _index.jsonl. Useful after manual cleanup or index corruption.
5198
+ */
5199
+ async rebuildIndex() {
5200
+ const ids = await this.collectSessionIds(this.dir);
5201
+ const summaries = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));
5202
+ const valid = summaries.filter((s) => s !== null);
5203
+ const tmp = `${this.indexFile}.tmp`;
5204
+ const lines = valid.map((s) => JSON.stringify(s)).join("\n") + "\n";
5205
+ await fsp3.writeFile(tmp, lines, "utf8");
5206
+ await fsp3.rename(tmp, this.indexFile);
5207
+ return valid.length;
5208
+ }
5209
+ /** Recursively collect session IDs from date-shard subdirectories.
5210
+ * IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_…").
5211
+ * Skips `.jsonl`/`.summary.json` root files, dot-files, and
5212
+ * sub-directories that belong to fleet/subagent sessions. */
5213
+ async collectSessionIds(dir, prefix = "", depth = 0) {
5030
5214
  const ids = [];
5031
- const entries = await fsp3.readdir(dir, { withFileTypes: true });
5215
+ let entries;
5216
+ try {
5217
+ entries = await fsp3.readdir(dir, { withFileTypes: true });
5218
+ } catch {
5219
+ return ids;
5220
+ }
5032
5221
  for (const entry of entries) {
5033
- const full = path6.join(dir, entry.name);
5222
+ if (entry.name.startsWith(".") && entry.name !== ".wrongstack") continue;
5223
+ if (entry.name === "shared" || entry.name === "subagents" || entry.name === "attachments")
5224
+ continue;
5034
5225
  if (entry.isDirectory()) {
5035
- ids.push(...await this.collectSessionIds(full));
5226
+ const childPrefix = depth === 0 ? entry.name : `${prefix}/${entry.name}`;
5227
+ ids.push(...await this.collectSessionIds(path6.join(dir, entry.name), childPrefix, depth + 1));
5036
5228
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
5037
- ids.push(entry.name.replace(/\.jsonl$/, ""));
5229
+ if (entry.name === "_index.jsonl") continue;
5230
+ const base = entry.name.replace(/\.jsonl$/, "");
5231
+ ids.push(prefix ? `${prefix}/${base}` : base);
5038
5232
  }
5039
5233
  }
5040
5234
  return ids;
@@ -5057,9 +5251,70 @@ var DefaultSessionStore = class {
5057
5251
  return summary;
5058
5252
  }
5059
5253
  }
5060
- async delete(id) {
5061
- await fsp3.unlink(this.sessionPath(id, ".jsonl"));
5254
+ /**
5255
+ * Delete a session and all associated files: JSONL, summary, plan/todos
5256
+ * sidecars, and the session directory (fleet.json, shared/, subagents/).
5257
+ */
5258
+ async deleteSession(id) {
5259
+ await fsp3.unlink(this.sessionPath(id, ".jsonl")).catch(() => void 0);
5062
5260
  await fsp3.unlink(this.sessionPath(id, ".summary.json")).catch(() => void 0);
5261
+ const shardDir = path6.dirname(path6.join(this.dir, id));
5262
+ const base = path6.basename(id);
5263
+ for (const ext of [".plan.json", ".todos.json"]) {
5264
+ await fsp3.unlink(path6.join(shardDir, `${base}${ext}`)).catch(() => void 0);
5265
+ }
5266
+ const sessDir = path6.join(shardDir, base);
5267
+ await fsp3.rm(sessDir, { recursive: true, force: true }).catch(() => void 0);
5268
+ await this.writeTombstone(id);
5269
+ }
5270
+ async delete(id) {
5271
+ await this.deleteSession(id);
5272
+ }
5273
+ async prune(maxAgeDays = 30) {
5274
+ const cutoff = Date.now() - maxAgeDays * 864e5;
5275
+ let deleted = 0;
5276
+ let activeSessionId = null;
5277
+ try {
5278
+ const raw = await fsp3.readFile(path6.join(this.dir, "active.json"), "utf8");
5279
+ const active = JSON.parse(raw);
5280
+ activeSessionId = active.sessionId ?? null;
5281
+ } catch {
5282
+ }
5283
+ const entries = await fsp3.readdir(this.dir, { withFileTypes: true }).catch(() => []);
5284
+ for (const entry of entries) {
5285
+ if (!entry.isDirectory()) continue;
5286
+ const dateDir = path6.join(this.dir, entry.name);
5287
+ const files = await fsp3.readdir(dateDir, { withFileTypes: true }).catch(() => []);
5288
+ for (const file of files) {
5289
+ if (!file.isFile() || !file.name.endsWith(".jsonl")) continue;
5290
+ const jsonlPath = path6.join(dateDir, file.name);
5291
+ try {
5292
+ const stat10 = await fsp3.stat(jsonlPath);
5293
+ if (stat10.mtimeMs >= cutoff) continue;
5294
+ } catch {
5295
+ continue;
5296
+ }
5297
+ const id = `${entry.name}/${file.name.replace(/\.jsonl$/, "")}`;
5298
+ if (activeSessionId && id === activeSessionId) continue;
5299
+ await this.deleteSession(id);
5300
+ deleted++;
5301
+ }
5302
+ }
5303
+ if (deleted > 0) {
5304
+ await this.compactIndex().catch(() => void 0);
5305
+ }
5306
+ for (const entry of entries) {
5307
+ if (!entry.isDirectory()) continue;
5308
+ const dateDir = path6.join(this.dir, entry.name);
5309
+ try {
5310
+ const remaining = await fsp3.readdir(dateDir);
5311
+ if (remaining.length === 0) {
5312
+ await fsp3.rmdir(dateDir).catch(() => void 0);
5313
+ }
5314
+ } catch {
5315
+ }
5316
+ }
5317
+ return deleted;
5063
5318
  }
5064
5319
  async clearHistory(id) {
5065
5320
  await this.ensureShardDir(id);
@@ -5081,13 +5336,42 @@ var DefaultSessionStore = class {
5081
5336
  const data = await this.load(id);
5082
5337
  const firstUser = data.events.find((e) => e.type === "user_input");
5083
5338
  const title = firstUser && firstUser.type === "user_input" ? userInputTitle(firstUser.content) : "(empty session)";
5339
+ let iterationCount = 0;
5340
+ let toolCallCount = 0;
5341
+ let toolErrorCount = 0;
5342
+ let fileChangeCount = 0;
5343
+ const toolBreakdown = {};
5344
+ let outcome = void 0;
5345
+ const lastEvent = data.events[data.events.length - 1];
5346
+ for (const e of data.events) {
5347
+ if (e.type === "in_flight_start") iterationCount++;
5348
+ else if (e.type === "tool_call_start") {
5349
+ toolCallCount++;
5350
+ toolBreakdown[e.name] = (toolBreakdown[e.name] ?? 0) + 1;
5351
+ } else if (e.type === "tool_result" && e.isError) toolErrorCount++;
5352
+ else if (e.type === "file_snapshot") fileChangeCount += e.files.length;
5353
+ }
5354
+ if (lastEvent?.type === "session_end") {
5355
+ outcome = "completed";
5356
+ } else if (lastEvent?.type === "in_flight_start") {
5357
+ outcome = "aborted";
5358
+ } else if (data.events.some((e) => e.type === "error")) {
5359
+ outcome = "error";
5360
+ }
5084
5361
  return {
5085
5362
  id,
5086
5363
  title,
5087
5364
  startedAt: data.metadata.startedAt,
5365
+ endedAt: data.metadata.endedAt,
5088
5366
  model: data.metadata.model ?? "unknown",
5089
5367
  provider: data.metadata.provider ?? "unknown",
5090
- tokenTotal: data.usage.input + data.usage.output
5368
+ tokenTotal: data.usage.input + data.usage.output,
5369
+ iterationCount: iterationCount > 0 ? iterationCount : void 0,
5370
+ toolCallCount: toolCallCount > 0 ? toolCallCount : void 0,
5371
+ toolErrorCount: toolErrorCount > 0 ? toolErrorCount : void 0,
5372
+ fileChangeCount: fileChangeCount > 0 ? fileChangeCount : void 0,
5373
+ toolBreakdown: Object.keys(toolBreakdown).length > 0 ? toolBreakdown : {},
5374
+ outcome
5091
5375
  };
5092
5376
  } catch {
5093
5377
  return {
@@ -5186,9 +5470,10 @@ var FileSessionWriter = class {
5186
5470
  this.meta = meta;
5187
5471
  this.events = events;
5188
5472
  this.resumed = opts.resumed ?? false;
5189
- this.manifestFile = opts.dir ? path6.join(opts.dir, `${id}.summary.json`) : "";
5473
+ this.manifestFile = opts.dir ? path6.join(opts.dir, `${path6.basename(id)}.summary.json`) : "";
5190
5474
  this.filePath = opts.filePath ?? "";
5191
5475
  this.secretScrubber = opts.secretScrubber;
5476
+ this.onCloseCb = opts.onClose;
5192
5477
  this.summary = {
5193
5478
  id,
5194
5479
  title: "(empty session)",
@@ -5218,6 +5503,15 @@ var FileSessionWriter = class {
5218
5503
  appendFailCount = 0;
5219
5504
  lastAppendWarnAt = 0;
5220
5505
  secretScrubber;
5506
+ onCloseCb;
5507
+ // ── Enriched summary tracking ──────────────────────────────────────────
5508
+ iterationCount = 0;
5509
+ toolCallCount = 0;
5510
+ toolErrorCount = 0;
5511
+ toolBreakdown = {};
5512
+ fileChangeCount = 0;
5513
+ compactionCount = 0;
5514
+ outcome = void 0;
5221
5515
  /**
5222
5516
  * Scrub secrets out of conversation-turn events before they are observed
5223
5517
  * for the summary, written to the JSONL log, or surfaced on resume. Only
@@ -5295,8 +5589,22 @@ var FileSessionWriter = class {
5295
5589
  observeForSummary(event) {
5296
5590
  if (event.type === "tool_use") {
5297
5591
  this.openToolUses.add(event.id);
5592
+ } else if (event.type === "tool_call_start") {
5593
+ this.toolCallCount++;
5594
+ this.toolBreakdown[event.name] = (this.toolBreakdown[event.name] ?? 0) + 1;
5298
5595
  } else if (event.type === "tool_result") {
5299
5596
  this.openToolUses.delete(event.id);
5597
+ if (event.isError) {
5598
+ this.toolErrorCount++;
5599
+ this.outcome = "error";
5600
+ }
5601
+ } else if (event.type === "file_snapshot") {
5602
+ this.fileChangeCount += event.files.length;
5603
+ } else if (event.type === "compaction") {
5604
+ this.compactionCount++;
5605
+ }
5606
+ if (event.type === "error" || event.type === "provider_error") {
5607
+ this.outcome = "error";
5300
5608
  }
5301
5609
  if (event.type === "user_input" && this.summary.title === "(empty session)") {
5302
5610
  this.summary = { ...this.summary, title: userInputTitle(event.content) };
@@ -5307,18 +5615,35 @@ var FileSessionWriter = class {
5307
5615
  } else if (event.type === "session_end") {
5308
5616
  const total = event.usage.input + event.usage.output;
5309
5617
  if (total > 0) this.summary = { ...this.summary, tokenTotal: total };
5618
+ } else if (event.type === "in_flight_start") {
5619
+ this.iterationCount++;
5310
5620
  }
5311
5621
  }
5312
5622
  async close() {
5313
5623
  if (this.closing) return;
5314
5624
  this.closing = true;
5315
5625
  this.closed = true;
5626
+ this.summary = {
5627
+ ...this.summary,
5628
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
5629
+ iterationCount: this.iterationCount,
5630
+ toolCallCount: this.toolCallCount,
5631
+ toolErrorCount: this.toolErrorCount,
5632
+ fileChangeCount: this.fileChangeCount,
5633
+ compactionCount: this.compactionCount > 0 ? this.compactionCount : void 0,
5634
+ toolBreakdown: { ...this.toolBreakdown },
5635
+ outcome: this.outcome ?? "completed"
5636
+ };
5316
5637
  if (this.manifestFile) {
5317
5638
  try {
5318
5639
  await atomicWrite(this.manifestFile, JSON.stringify(this.summary), { mode: 384 });
5319
5640
  } catch {
5320
5641
  }
5321
5642
  }
5643
+ try {
5644
+ await this.onCloseCb?.(this.summary);
5645
+ } catch {
5646
+ }
5322
5647
  try {
5323
5648
  await this.handle.close();
5324
5649
  } catch {
@@ -5360,7 +5685,7 @@ var FileSessionWriter = class {
5360
5685
  let targetCheckpointLine = -1;
5361
5686
  let afterTarget = false;
5362
5687
  for (let i = 0; i < lines.length; i++) {
5363
- const line = lines[i];
5688
+ const line = expectDefined9(lines[i]);
5364
5689
  if (!line.trim()) continue;
5365
5690
  let event;
5366
5691
  try {
@@ -6497,8 +6822,11 @@ var SessionAnalyzer = class {
6497
6822
  }
6498
6823
  calcDuration(events) {
6499
6824
  if (events.length < 2) return 0;
6500
- const first = new Date(events[0].ts).getTime();
6501
- const last = new Date(events[events.length - 1].ts).getTime();
6825
+ const firstEvent = events[0];
6826
+ const lastEvent = events[events.length - 1];
6827
+ if (!firstEvent || !lastEvent) return 0;
6828
+ const first = new Date(firstEvent.ts).getTime();
6829
+ const last = new Date(lastEvent.ts).getTime();
6502
6830
  return last - first;
6503
6831
  }
6504
6832
  };
@@ -7607,7 +7935,7 @@ function parseDescription(raw) {
7607
7935
  const scope = [];
7608
7936
  const coversMatch = /(?:covers|for|including)\s+([^.]+)/i.exec(desc);
7609
7937
  if (coversMatch) {
7610
- const items = coversMatch[1].replace(/[·•]/g, ",").split(",").map((s) => s.trim()).filter(Boolean);
7938
+ const items = coversMatch[1] ?? "".replace(/[·•]/g, ",").split(",").map((s) => s.trim()).filter(Boolean);
7611
7939
  scope.push(...items);
7612
7940
  }
7613
7941
  return { trigger, scope };
@@ -8062,7 +8390,7 @@ var IntelligentCompactor = class {
8062
8390
  maxTokens: 1024
8063
8391
  };
8064
8392
  const ac = ctx.signal ? void 0 : new AbortController();
8065
- const signal = ctx.signal ?? ac.signal;
8393
+ const signal = ctx.signal ?? ac?.signal;
8066
8394
  const res = await this.provider.complete(req, { signal });
8067
8395
  const textBlocks = res.content.filter(isTextBlock);
8068
8396
  return textBlocks.map((b) => b.text).join("\n").trim() || "(empty summary)";
@@ -8165,6 +8493,12 @@ var IntelligentCompactor = class {
8165
8493
  };
8166
8494
 
8167
8495
  // src/models/llm-selector.ts
8496
+ function expectDefined10(value) {
8497
+ if (value === null || value === void 0) {
8498
+ throw new Error("Expected value to be defined");
8499
+ }
8500
+ return value;
8501
+ }
8168
8502
  var DEFAULT_SYSTEM_PROMPT = `You are a context pruning assistant. Given a conversation history and a token budget, decide which message ranges are worth keeping verbatim and which should be collapsed into summaries.
8169
8503
 
8170
8504
  Output a JSON object with this structure:
@@ -8205,7 +8539,7 @@ function formatMessages(messages, maxChars = 8e3) {
8205
8539
  const lines = [];
8206
8540
  let used = 0;
8207
8541
  for (let i = 0; i < messages.length; i++) {
8208
- const m = messages[i];
8542
+ const m = expectDefined10(messages[i]);
8209
8543
  const role = m.role.padEnd(10, " ");
8210
8544
  let text;
8211
8545
  if (typeof m.content === "string") {
@@ -8270,7 +8604,7 @@ IMPORTANT: Total conversation (${totalTokens} tokens) exceeds budget (${effectiv
8270
8604
  let tokenCount = 0;
8271
8605
  let startIdx = 0;
8272
8606
  for (let i = messages.length - 1; i >= 0; i--) {
8273
- const m = messages[i];
8607
+ const m = expectDefined10(messages[i]);
8274
8608
  const cost = typeof m.content === "string" ? Math.ceil(m.content.length / 4) : m.content.reduce(
8275
8609
  (acc, b) => acc + (b.type === "text" ? Math.ceil(b.text.length / 4) : Math.ceil(JSON.stringify(b).length / 4)),
8276
8610
  0
@@ -8481,6 +8815,7 @@ Summarize the following message range:`;
8481
8815
  let boundary = preserveIdx;
8482
8816
  for (let i = preserveIdx; i < messages.length && i < preserveIdx + 6; i++) {
8483
8817
  const m = messages[i];
8818
+ if (!m) continue;
8484
8819
  if (m.role === "user" && this.hasTextContent(m)) {
8485
8820
  boundary = i;
8486
8821
  break;
@@ -9745,16 +10080,16 @@ var SubagentBudget = class _SubagentBudget {
9745
10080
  }
9746
10081
  if (exceeded.length === 0) return [];
9747
10082
  if (!this._onThreshold) {
9748
- const first2 = exceeded[0];
10083
+ const first2 = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
9749
10084
  throw new BudgetExceededError(first2.kind, first2.limit, first2.used);
9750
10085
  }
9751
10086
  if (this._mode === "sync") {
9752
- const first2 = exceeded[0];
10087
+ const first2 = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
9753
10088
  throw new BudgetExceededError(first2.kind, first2.limit, first2.used);
9754
10089
  }
9755
10090
  const bus = this._events;
9756
10091
  if (!bus || !bus.hasListenerFor("budget.threshold_reached")) {
9757
- const first2 = exceeded[0];
10092
+ const first2 = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
9758
10093
  throw new BudgetExceededError(first2.kind, first2.limit, first2.used);
9759
10094
  }
9760
10095
  for (const entry of exceeded) {
@@ -9762,8 +10097,9 @@ var SubagentBudget = class _SubagentBudget {
9762
10097
  const decision2 = this._negotiateExtension(entry.kind, exceeded);
9763
10098
  this._pendingNegotiations.set(entry.kind, decision2);
9764
10099
  }
9765
- const first = exceeded[0];
10100
+ const first = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
9766
10101
  const decision = this._pendingNegotiations.get(first.kind);
10102
+ if (!decision) throw new Error(`No pending negotiation for ${first.kind}`);
9767
10103
  throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);
9768
10104
  }
9769
10105
  /**
@@ -9785,8 +10121,11 @@ var SubagentBudget = class _SubagentBudget {
9785
10121
  * a fresh signal.
9786
10122
  */
9787
10123
  async _negotiateExtension(kind, exceeded) {
10124
+ if (!this._onThreshold) {
10125
+ return "stop";
10126
+ }
9788
10127
  try {
9789
- const first = exceeded[0];
10128
+ const first = exceeded[0] ?? { kind: "iterations", limit: 0, used: 0 };
9790
10129
  const result = this._onThreshold({
9791
10130
  kind: first.kind,
9792
10131
  used: first.used,
@@ -12269,6 +12608,11 @@ function getAgentDefinition(role) {
12269
12608
 
12270
12609
  // src/coordination/dispatcher.ts
12271
12610
  var DEFAULT_DISPATCH_ROLE = "executor";
12611
+ var FALLBACK_DEFINITION = {
12612
+ config: { role: "unknown", name: "Unknown Agent" },
12613
+ budget: {},
12614
+ capability: { phase: "meta", summary: "", keywords: [] }
12615
+ };
12272
12616
  function normalize2(text) {
12273
12617
  return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
12274
12618
  }
@@ -12296,7 +12640,7 @@ function scoreAgents(task, catalog = AGENT_CATALOG) {
12296
12640
  }
12297
12641
  function heuristicConfidence(candidates) {
12298
12642
  if (candidates.length === 0) return 0;
12299
- const top = candidates[0].score;
12643
+ const top = candidates[0]?.score ?? 0;
12300
12644
  const second = candidates[1]?.score ?? 0;
12301
12645
  const strength = Math.min(1, top / 3);
12302
12646
  const margin = (top - second + 1) / (top + 1);
@@ -12312,7 +12656,7 @@ async function dispatchAgent(task, opts = {}) {
12312
12656
  if (top && confidence >= threshold) {
12313
12657
  return {
12314
12658
  role: top.role,
12315
- definition: catalog[top.role],
12659
+ definition: catalog[top.role] ?? FALLBACK_DEFINITION,
12316
12660
  confidence,
12317
12661
  method: "heuristic",
12318
12662
  reason: `Matched keywords: ${top.matched.slice(0, 4).join(", ")}`,
@@ -12320,7 +12664,7 @@ async function dispatchAgent(task, opts = {}) {
12320
12664
  };
12321
12665
  }
12322
12666
  if (opts.classifier) {
12323
- const pool = (candidates.length > 0 ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]) : ALL_AGENT_DEFINITIONS).map((d) => ({
12667
+ const pool = (candidates.length > 0 ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role] ?? FALLBACK_DEFINITION) : ALL_AGENT_DEFINITIONS).map((d) => ({
12324
12668
  role: d.config.role,
12325
12669
  name: d.config.name,
12326
12670
  summary: d.capability.summary
@@ -12330,7 +12674,7 @@ async function dispatchAgent(task, opts = {}) {
12330
12674
  if (choice && catalog[choice.role]) {
12331
12675
  return {
12332
12676
  role: choice.role,
12333
- definition: catalog[choice.role],
12677
+ definition: catalog[choice.role] ?? FALLBACK_DEFINITION,
12334
12678
  confidence: 1,
12335
12679
  method: "llm",
12336
12680
  reason: choice.reason ?? "Selected by LLM classifier",
@@ -12343,17 +12687,17 @@ async function dispatchAgent(task, opts = {}) {
12343
12687
  if (top) {
12344
12688
  return {
12345
12689
  role: top.role,
12346
- definition: catalog[top.role],
12690
+ definition: catalog[top.role] ?? FALLBACK_DEFINITION,
12347
12691
  confidence,
12348
12692
  method: "heuristic",
12349
12693
  reason: `Weak match (${top.matched.slice(0, 3).join(", ") || "low signal"})`,
12350
12694
  alternatives: candidates.slice(1, maxCandidates)
12351
12695
  };
12352
12696
  }
12353
- const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE] ? DEFAULT_DISPATCH_ROLE : Object.keys(catalog)[0];
12697
+ const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE] ? DEFAULT_DISPATCH_ROLE : Object.keys(catalog)[0] ?? DEFAULT_DISPATCH_ROLE;
12354
12698
  return {
12355
12699
  role: fallbackRole,
12356
- definition: catalog[fallbackRole],
12700
+ definition: catalog[fallbackRole] ?? FALLBACK_DEFINITION,
12357
12701
  confidence: 0,
12358
12702
  method: "fallback",
12359
12703
  reason: "No keyword signal; defaulting to the generalist Executor",
@@ -13166,6 +13510,7 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
13166
13510
  takeNextDispatchableTask() {
13167
13511
  for (let i = 0; i < this.pendingTasks.length; i++) {
13168
13512
  const task = this.pendingTasks[i];
13513
+ if (!task) continue;
13169
13514
  const subagentId = task.subagentId ? this.isIdleSubagent(task.subagentId) ? task.subagentId : null : this.findIdleSubagent();
13170
13515
  if (!subagentId) continue;
13171
13516
  this.pendingTasks.splice(i, 1);
@@ -13357,14 +13702,14 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
13357
13702
  const idleExceeded = idleLimit !== void 0 && budget.idleMs() >= idleLimit;
13358
13703
  if (idleExceeded && !wallExceeded) {
13359
13704
  this.subagents.get(ctx.subagentId)?.abortController.abort();
13360
- reject(new BudgetExceededError("timeout", idleLimit, budget.idleMs()));
13705
+ reject(new BudgetExceededError("timeout", idleLimit ?? 0, budget.idleMs()));
13361
13706
  return;
13362
13707
  }
13363
13708
  if (!wallExceeded) {
13364
13709
  scheduleNext();
13365
13710
  return;
13366
13711
  }
13367
- const limit = wallLimit;
13712
+ const limit = wallLimit ?? 0;
13368
13713
  if (!budget.onThreshold) {
13369
13714
  this.subagents.get(ctx.subagentId)?.abortController.abort();
13370
13715
  reject(new BudgetExceededError("timeout", limit, elapsed));
@@ -13523,6 +13868,12 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
13523
13868
  };
13524
13869
 
13525
13870
  // src/execution/parallel-eternal-engine.ts
13871
+ function expectDefined11(value) {
13872
+ if (value === null || value === void 0) {
13873
+ throw new Error("Expected value to be defined");
13874
+ }
13875
+ return value;
13876
+ }
13526
13877
  function sleep2(ms) {
13527
13878
  return new Promise((resolve13) => setTimeout(resolve13, ms));
13528
13879
  }
@@ -13681,7 +14032,7 @@ var ParallelEternalEngine = class {
13681
14032
  // Fan-out
13682
14033
  // -------------------------------------------------------------------------
13683
14034
  async fanOut(goal, tasks) {
13684
- const coordinator = this.coordinator;
14035
+ const coordinator = expectDefined11(this.coordinator);
13685
14036
  const slotCount = Math.min(this.slots, tasks.length);
13686
14037
  const routes = this.dispatchEnabled ? await Promise.all(
13687
14038
  tasks.slice(0, slotCount).map(
@@ -13713,7 +14064,7 @@ ${recentJournal}` : "No prior iterations.",
13713
14064
  const routeInfo = [];
13714
14065
  const spawnPromises = [];
13715
14066
  for (let i = 0; i < slotCount; i++) {
13716
- const task = tasks[i];
14067
+ const task = expectDefined11(tasks[i]);
13717
14068
  const route = routes[i] ?? null;
13718
14069
  const subagentId = `parallel-${this.iterations}-${i}`;
13719
14070
  const taskId = randomUUID();
@@ -14216,7 +14567,7 @@ var CollabSession = class extends EventEmitter {
14216
14567
  this.emit("session.error", error);
14217
14568
  throw error;
14218
14569
  }
14219
- for (const result of results.flat()) {
14570
+ for (const result of results?.flat() ?? []) {
14220
14571
  await this.parseAndEmit(result);
14221
14572
  }
14222
14573
  const report = this.assembleReport();
@@ -14277,7 +14628,7 @@ var CollabSession = class extends EventEmitter {
14277
14628
  }
14278
14629
  budgetForRole(role) {
14279
14630
  if (this.options.budgetOverrides?.[role]) {
14280
- return this.options.budgetOverrides[role];
14631
+ return this.options.budgetOverrides[role] ?? { maxIterations: 0, maxToolCalls: 0, timeoutMs: 0 };
14281
14632
  }
14282
14633
  const defaults = {
14283
14634
  "bug-hunter": { maxIterations: 2e3, maxToolCalls: 5e3, timeoutMs: 10 * 60 * 1e3 },
@@ -14730,7 +15081,7 @@ function makeSpawnTool(director, roster) {
14730
15081
  });
14731
15082
  const dispatchRole = dispatchResult.role;
14732
15083
  if (roster?.[dispatchRole]) {
14733
- cfg = instantiateRosterConfig(dispatchRole, roster[dispatchRole]);
15084
+ cfg = instantiateRosterConfig(dispatchRole, roster[dispatchRole] ?? {});
14734
15085
  } else {
14735
15086
  const def = dispatchResult.definition;
14736
15087
  cfg = {
@@ -17039,7 +17390,10 @@ function attachAutoExtend(events, policy = {}) {
17039
17390
  if (kind === "timeout" || kind === "idle_timeout") {
17040
17391
  if (progress > lastTimeoutProgress) {
17041
17392
  lastTimeoutProgress = progress;
17042
- const next2 = Math.min(Math.ceil(limit * (1 + factor)), ceiling.timeoutMs);
17393
+ const next2 = Math.min(
17394
+ Math.ceil(limit * (1 + factor)),
17395
+ ceiling.timeoutMs ?? DEFAULT_CEILING.timeoutMs
17396
+ );
17043
17397
  extend({ timeoutMs: next2 });
17044
17398
  } else {
17045
17399
  deny();
@@ -17053,7 +17407,7 @@ function attachAutoExtend(events, policy = {}) {
17053
17407
  }
17054
17408
  extendCounts.set(kind, count + 1);
17055
17409
  const field = FIELD_BY_KIND[kind];
17056
- const cap = ceiling[field];
17410
+ const cap = ceiling[field] ?? DEFAULT_CEILING[field];
17057
17411
  const next = Math.min(Math.ceil(limit * (1 + factor)), cap);
17058
17412
  extend({ [field]: next });
17059
17413
  })
@@ -17698,7 +18052,7 @@ var TaskTracker = class {
17698
18052
  if (filter.type?.length && !filter.type.includes(n.type)) return false;
17699
18053
  if (filter.assignee?.length && n.assignee && !filter.assignee.includes(n.assignee))
17700
18054
  return false;
17701
- if (filter.tags?.length && n.tags && !n.tags.some((t2) => filter.tags.includes(t2)))
18055
+ if (filter.tags?.length && n.tags && !n.tags.some((t2) => filter.tags?.includes(t2)))
17702
18056
  return false;
17703
18057
  if (filter.specRequirementId && n.specRequirementId !== filter.specRequirementId)
17704
18058
  return false;
@@ -18212,6 +18566,12 @@ var TaskGraphStore = class {
18212
18566
  };
18213
18567
 
18214
18568
  // src/sdd/spec-builder.ts
18569
+ function expectDefined12(value) {
18570
+ if (value === null || value === void 0) {
18571
+ throw new Error("Expected value to be defined");
18572
+ }
18573
+ return value;
18574
+ }
18215
18575
  function buildQuestioningPrompt(session, min, max) {
18216
18576
  const answered = session.answers.length;
18217
18577
  const remaining = Math.max(0, min - answered);
@@ -18257,7 +18617,7 @@ function buildQuestioningPrompt(session, min, max) {
18257
18617
  if (answered > 0) {
18258
18618
  lines.push("", "**Conversation so far:**");
18259
18619
  for (let i = 0; i < answered; i++) {
18260
- const a = session.answers[i];
18620
+ const a = expectDefined12(session.answers[i]);
18261
18621
  lines.push(``, `Q${i + 1}: ${a.question}`, `A${i + 1}: ${a.answer}`);
18262
18622
  }
18263
18623
  }
@@ -18999,6 +19359,12 @@ function truncate2(str, maxLen) {
18999
19359
  }
19000
19360
 
19001
19361
  // src/sdd/critical-path.ts
19362
+ function expectDefined13(value) {
19363
+ if (value === null || value === void 0) {
19364
+ throw new Error("Expected value to be defined");
19365
+ }
19366
+ return value;
19367
+ }
19002
19368
  function analyzeCriticalPath(graph) {
19003
19369
  const nodes = Array.from(graph.nodes.values());
19004
19370
  const topoOrder = topologicalSort(graph);
@@ -19007,9 +19373,9 @@ function analyzeCriticalPath(graph) {
19007
19373
  for (const edge of graph.edges) {
19008
19374
  if (edge.type === "depends_on") {
19009
19375
  if (!blockedByMap.has(edge.from)) blockedByMap.set(edge.from, /* @__PURE__ */ new Set());
19010
- blockedByMap.get(edge.from).add(edge.to);
19376
+ blockedByMap.get(edge.from)?.add(edge.to);
19011
19377
  if (!blocksMap.has(edge.to)) blocksMap.set(edge.to, /* @__PURE__ */ new Set());
19012
- blocksMap.get(edge.to).add(edge.from);
19378
+ blocksMap.get(edge.to)?.add(edge.from);
19013
19379
  }
19014
19380
  }
19015
19381
  const readyTasks = [];
@@ -19074,7 +19440,7 @@ function getTransitiveBlocked(_graph, taskId, blocksMap) {
19074
19440
  const visited = /* @__PURE__ */ new Set();
19075
19441
  const queue = [taskId];
19076
19442
  while (queue.length > 0) {
19077
- const current = queue.shift();
19443
+ const current = expectDefined13(queue.shift());
19078
19444
  const blocked = blocksMap.get(current);
19079
19445
  if (!blocked) continue;
19080
19446
  for (const id of blocked) {
@@ -19099,7 +19465,7 @@ function computeCriticalPath(graph, _topoOrder, blockedByMap) {
19099
19465
  for (const [taskId, blockers] of blockedByMap) {
19100
19466
  for (const blockerId of blockers) {
19101
19467
  if (!blocksMap.has(blockerId)) blocksMap.set(blockerId, /* @__PURE__ */ new Set());
19102
- blocksMap.get(blockerId).add(taskId);
19468
+ blocksMap.get(blockerId)?.add(taskId);
19103
19469
  }
19104
19470
  }
19105
19471
  const n = allIds.length;
@@ -19120,7 +19486,7 @@ function computeCriticalPath(graph, _topoOrder, blockedByMap) {
19120
19486
  if (!changed) break;
19121
19487
  }
19122
19488
  let maxDist = 0;
19123
- let maxId = allIds[0];
19489
+ let maxId = expectDefined13(allIds[0]);
19124
19490
  for (const id of allIds) {
19125
19491
  const d = dist.get(id) ?? 0;
19126
19492
  if (d > maxDist) {
@@ -19589,6 +19955,12 @@ var SddTaskDecomposer = class {
19589
19955
  return nodes.some((n) => n.status === "blocked");
19590
19956
  }
19591
19957
  };
19958
+ function expectDefined14(value) {
19959
+ if (value === null || value === void 0) {
19960
+ throw new Error("Expected value to be defined");
19961
+ }
19962
+ return value;
19963
+ }
19592
19964
  var SddParallelRun = class {
19593
19965
  constructor(opts) {
19594
19966
  this.opts = opts;
@@ -19689,8 +20061,10 @@ var SddParallelRun = class {
19689
20061
  "\u2022 Do not ask before routine in-project tool use; if a permission gate appears, wait for that flow.",
19690
20062
  "\u2022 Keep output concise \u2014 summarize changes, do not transcribe files."
19691
20063
  ].join("\n");
20064
+ if (!this.coordinator) throw new Error("SDD parallel runner requires a coordinator");
20065
+ const coordinator = this.coordinator;
19692
20066
  const spawns = subagentIds.map(
19693
- (subagentId) => this.coordinator.spawn({
20067
+ (subagentId) => coordinator.spawn({
19694
20068
  id: subagentId,
19695
20069
  name: subagentId,
19696
20070
  role: "executor",
@@ -19698,12 +20072,12 @@ var SddParallelRun = class {
19698
20072
  })
19699
20073
  );
19700
20074
  const spawnResults = await Promise.all(spawns);
19701
- if (!spawnResults.every((r) => r.subagentId)) {
20075
+ if (!spawnResults.every((r) => Boolean(r.subagentId))) {
19702
20076
  throw new Error("One or more subagent spawns failed");
19703
20077
  }
19704
20078
  const assignPromises = tasks.map((task, i) => {
19705
20079
  const spec = {
19706
- id: taskIds[i],
20080
+ id: taskIds[i] ?? task.id,
19707
20081
  description: [
19708
20082
  directivePreamble,
19709
20083
  "",
@@ -19712,15 +20086,15 @@ var SddParallelRun = class {
19712
20086
  "",
19713
20087
  task.description
19714
20088
  ].join("\n"),
19715
- subagentId: subagentIds[i],
20089
+ subagentId: subagentIds[i] ?? spawnResults[i]?.subagentId ?? task.id,
19716
20090
  timeoutMs: this.timeoutMs
19717
20091
  };
19718
- return this.coordinator.assign(spec);
20092
+ return this.coordinator?.assign(spec);
19719
20093
  });
19720
20094
  await Promise.all(assignPromises);
19721
20095
  let results;
19722
20096
  try {
19723
- results = await this.coordinator.awaitTasks(taskIds);
20097
+ results = await coordinator.awaitTasks(taskIds);
19724
20098
  } catch (err) {
19725
20099
  results = taskIds.map((id) => ({
19726
20100
  subagentId: "",
@@ -19735,8 +20109,8 @@ var SddParallelRun = class {
19735
20109
  const successCount = results.filter((r) => r.status === "success").length;
19736
20110
  const failCount = results.length - successCount;
19737
20111
  for (let i = 0; i < results.length; i++) {
19738
- const result = results[i];
19739
- const taskId = taskIds[i];
20112
+ const result = expectDefined14(results[i]);
20113
+ const taskId = expectDefined14(taskIds[i]);
19740
20114
  if (result.status === "success") {
19741
20115
  this.opts.tracker.updateNodeStatus(taskId, "completed");
19742
20116
  } else {
@@ -20843,6 +21217,12 @@ var allServers = () => ({
20843
21217
  "zai-vision": { ...zaiVisionServer(), enabled: false },
20844
21218
  "minimax-vision": { ...miniMaxVisionServer(), enabled: false }
20845
21219
  });
21220
+ function expectDefined15(value) {
21221
+ if (value === null || value === void 0) {
21222
+ throw new Error("Expected value to be defined");
21223
+ }
21224
+ return value;
21225
+ }
20846
21226
  function parseSkillRef(input) {
20847
21227
  const trimmed = input.trim().replace(/^https?:\/\/github\.com\//, "").replace(/\.git$/, "");
20848
21228
  const atIdx = trimmed.indexOf("@");
@@ -20859,7 +21239,7 @@ function parseSkillRef(input) {
20859
21239
  if (parts.length < 2) {
20860
21240
  throw new Error(`Invalid skill reference "${input}". Expected format: user/repo or user/repo@ref`);
20861
21241
  }
20862
- return { owner: parts[0], repo: parts[1], ref };
21242
+ return { owner: expectDefined15(parts[0]), repo: expectDefined15(parts[1]), ref };
20863
21243
  }
20864
21244
  var MAX_TARBALL_SIZE = 50 * 1024 * 1024;
20865
21245
  async function downloadGitHubTarball(parsed) {
@@ -21028,6 +21408,12 @@ var SkillManifestStore = class {
21028
21408
  };
21029
21409
 
21030
21410
  // src/skills/skill-installer.ts
21411
+ function expectDefined16(value) {
21412
+ if (value === null || value === void 0) {
21413
+ throw new Error("Expected value to be defined");
21414
+ }
21415
+ return value;
21416
+ }
21031
21417
  var MAX_SKILL_FILE_SIZE = 100 * 1024;
21032
21418
  var SkillInstaller = class {
21033
21419
  opts;
@@ -21149,10 +21535,10 @@ var SkillInstaller = class {
21149
21535
  for (const entry of targets) {
21150
21536
  const key = `${entry.source}@${entry.ref}`;
21151
21537
  if (!bySource.has(key)) bySource.set(key, []);
21152
- bySource.get(key).push(entry);
21538
+ bySource.get(key)?.push(entry);
21153
21539
  }
21154
21540
  for (const [, entries] of bySource) {
21155
- const first = entries[0];
21541
+ const first = expectDefined16(entries[0]);
21156
21542
  const scope = first.scope;
21157
21543
  const isGlobal = scope === "user";
21158
21544
  try {
@@ -21322,6 +21708,12 @@ async function collectFiles(dir, baseDir2) {
21322
21708
 
21323
21709
  // src/storage/annotations-store.ts
21324
21710
  init_atomic_write();
21711
+ function expectDefined17(value) {
21712
+ if (value === null || value === void 0) {
21713
+ throw new Error("Expected value to be defined");
21714
+ }
21715
+ return value;
21716
+ }
21325
21717
  var FILE_VERSION = 1;
21326
21718
  var MAX_TEXT_LENGTH = 2e3;
21327
21719
  var MAX_ANNOTATIONS = 1e3;
@@ -21413,7 +21805,7 @@ var AnnotationsStore = class {
21413
21805
  return;
21414
21806
  }
21415
21807
  const next = {
21416
- ...all[idx],
21808
+ ...expectDefined17(all[idx]),
21417
21809
  resolved: true,
21418
21810
  resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
21419
21811
  resolvedBy: input.resolvedBy
@@ -21649,6 +22041,12 @@ var ReplayLogStore = class {
21649
22041
  return next;
21650
22042
  }
21651
22043
  };
22044
+ function expectDefined18(value) {
22045
+ if (value === null || value === void 0) {
22046
+ throw new Error("Expected value to be defined");
22047
+ }
22048
+ return value;
22049
+ }
21652
22050
  var SessionRecovery = class {
21653
22051
  constructor(dir) {
21654
22052
  this.dir = dir;
@@ -21689,7 +22087,7 @@ var SessionRecovery = class {
21689
22087
  const lines = raw.split("\n").filter((l) => l.trim());
21690
22088
  for (let i = lines.length - 1; i >= 0; i--) {
21691
22089
  try {
21692
- const ev = JSON.parse(lines[i]);
22090
+ const ev = JSON.parse(expectDefined18(lines[i]));
21693
22091
  if (ev.type === "in_flight_start") {
21694
22092
  return {
21695
22093
  sessionId,
@@ -21741,13 +22139,13 @@ var SessionRecovery = class {
21741
22139
  let lastCheckpoint = null;
21742
22140
  let lastCheckpointIdx = -1;
21743
22141
  for (let i = 0; i < events.length; i++) {
21744
- if (events[i].type === "checkpoint") {
21745
- lastCheckpoint = events[i];
22142
+ if (events[i]?.type === "checkpoint") {
22143
+ lastCheckpoint = expectDefined18(events[i]);
21746
22144
  lastCheckpointIdx = i;
21747
22145
  }
21748
22146
  }
21749
22147
  const pendingEvents = lastCheckpointIdx >= 0 ? events.slice(lastCheckpointIdx + 1) : events;
21750
- const lastEv = events[events.length - 1];
22148
+ const lastEv = expectDefined18(events[events.length - 1]);
21751
22149
  const inFlightStart = lastEv.type === "in_flight_start" ? lastEv : null;
21752
22150
  const context = inFlightStart && inFlightStart.type === "in_flight_start" ? inFlightStart.context : null;
21753
22151
  return {
@@ -21790,6 +22188,12 @@ var SessionRecovery = class {
21790
22188
  return path6.join(this.dir, `${sessionId}.jsonl`);
21791
22189
  }
21792
22190
  };
22191
+ function expectDefined19(value) {
22192
+ if (value === null || value === void 0) {
22193
+ throw new Error("Expected value to be defined");
22194
+ }
22195
+ return value;
22196
+ }
21793
22197
  var GENESIS_PREV = "0".repeat(64);
21794
22198
  var DEFAULT_FSYNC_EVERY = 100;
21795
22199
  var ToolAuditLog = class {
@@ -21856,7 +22260,7 @@ var ToolAuditLog = class {
21856
22260
  async verify(sessionId) {
21857
22261
  const entries = await this.readAll(sessionId);
21858
22262
  if (entries.length === 0) return { ok: true, entries: 0 };
21859
- if (entries[0].prevHash !== GENESIS_PREV) {
22263
+ if (entries[0]?.prevHash !== GENESIS_PREV) {
21860
22264
  return {
21861
22265
  ok: false,
21862
22266
  brokenAt: 0,
@@ -21865,7 +22269,7 @@ var ToolAuditLog = class {
21865
22269
  }
21866
22270
  let prevHash = GENESIS_PREV;
21867
22271
  for (let i = 0; i < entries.length; i++) {
21868
- const e = entries[i];
22272
+ const e = expectDefined19(entries[i]);
21869
22273
  if (e.prevHash !== prevHash) {
21870
22274
  return {
21871
22275
  ok: false,
@@ -21984,6 +22388,12 @@ function sortKeys2(value) {
21984
22388
 
21985
22389
  // src/storage/session-rewinder.ts
21986
22390
  init_atomic_write();
22391
+ function expectDefined20(value) {
22392
+ if (value === null || value === void 0) {
22393
+ throw new Error("Expected value to be defined");
22394
+ }
22395
+ return value;
22396
+ }
21987
22397
  var DefaultSessionRewinder = class {
21988
22398
  constructor(sessionsDir, projectRoot) {
21989
22399
  this.sessionsDir = sessionsDir;
@@ -22022,7 +22432,7 @@ var DefaultSessionRewinder = class {
22022
22432
  const events = parseEvents(raw);
22023
22433
  let targetIdx = -1;
22024
22434
  for (let i = 0; i < events.length; i++) {
22025
- const event = events[i];
22435
+ const event = expectDefined20(events[i]);
22026
22436
  if (event.type === "checkpoint") {
22027
22437
  const checkpointEvent = event;
22028
22438
  if (checkpointEvent.promptIndex === checkpointIndex) {
@@ -22036,7 +22446,7 @@ var DefaultSessionRewinder = class {
22036
22446
  }
22037
22447
  const snapshotsToRevert = [];
22038
22448
  for (let i = targetIdx + 1; i < events.length; i++) {
22039
- const event = events[i];
22449
+ const event = expectDefined20(events[i]);
22040
22450
  if (event.type === "checkpoint") {
22041
22451
  break;
22042
22452
  }
@@ -22218,6 +22628,12 @@ var DefaultPromptStore = class {
22218
22628
  };
22219
22629
  }
22220
22630
  };
22631
+ function expectDefined21(value) {
22632
+ if (value === null || value === void 0) {
22633
+ throw new Error("Expected value to be defined");
22634
+ }
22635
+ return value;
22636
+ }
22221
22637
  var ALL_SYNC_CATEGORIES = ["settings", "skills", "prompts", "memory", "history"];
22222
22638
  var CloudSync = class {
22223
22639
  constructor(paths, getConfig, setConfig) {
@@ -22260,8 +22676,8 @@ var CloudSync = class {
22260
22676
  const cfg = this.getConfig();
22261
22677
  if (!cfg?.enabled) return { ok: false, action: "push", categories: [], message: "Not enabled." };
22262
22678
  const parts = cfg.repo.split("/");
22263
- const owner = parts[0];
22264
- const repoName = parts[1];
22679
+ const owner = expectDefined21(parts[0]);
22680
+ const repoName = expectDefined21(parts[1]);
22265
22681
  const branch = "main";
22266
22682
  const baseTreeSha = this.state?.sha;
22267
22683
  const { treeEntries, rev } = await this.buildLocalTree(cfg.categories);
@@ -22313,8 +22729,8 @@ var CloudSync = class {
22313
22729
  const cfg = this.getConfig();
22314
22730
  if (!cfg?.enabled) return { ok: false, action: "pull", categories: [], message: "Not enabled." };
22315
22731
  const pullParts = cfg.repo.split("/");
22316
- const owner = pullParts[0];
22317
- const repoName = pullParts[1];
22732
+ const owner = expectDefined21(pullParts[0]);
22733
+ const repoName = expectDefined21(pullParts[1]);
22318
22734
  const branchData = await this.getRef(token, owner, repoName, "main");
22319
22735
  const currentSha = branchData.object.sha;
22320
22736
  const commitData = await this.getCommit(token, owner, repoName, currentSha);
@@ -22369,7 +22785,7 @@ var CloudSync = class {
22369
22785
  // ── GitHub API helpers ──────────────────────────────────────────────
22370
22786
  async githubFetch(token, owner, repo, method, pathSegment, body) {
22371
22787
  const url = `https://api.github.com/repos/${owner}/${repo}${pathSegment}`;
22372
- const res = await fetch(url, {
22788
+ const init = {
22373
22789
  signal: AbortSignal.timeout(15e3),
22374
22790
  method,
22375
22791
  headers: {
@@ -22377,9 +22793,10 @@ var CloudSync = class {
22377
22793
  Accept: "application/vnd.github+json",
22378
22794
  "X-GitHub-Api-Version": "2022-11-28",
22379
22795
  "Content-Type": "application/json"
22380
- },
22381
- body: body !== void 0 ? JSON.stringify(body) : void 0
22382
- });
22796
+ }
22797
+ };
22798
+ if (body !== void 0) init.body = JSON.stringify(body);
22799
+ const res = await fetch(url, init);
22383
22800
  if (!res.ok) {
22384
22801
  const errText = await res.text();
22385
22802
  throw new Error(`GitHub API ${method} ${pathSegment} failed (${res.status}): ${errText}`);
@@ -23514,7 +23931,7 @@ var ReportGenerator = class {
23514
23931
  if (groups[finding.category] === void 0) {
23515
23932
  groups[finding.category] = [];
23516
23933
  }
23517
- groups[finding.category].push(finding);
23934
+ groups[finding.category]?.push(finding);
23518
23935
  }
23519
23936
  return groups;
23520
23937
  }
@@ -23659,6 +24076,12 @@ var defaultGitignoreUpdater = new GitignoreUpdater();
23659
24076
 
23660
24077
  // src/security-scanner/orchestrator.ts
23661
24078
  init_atomic_write();
24079
+ function expectDefined22(value) {
24080
+ if (value === null || value === void 0) {
24081
+ throw new Error("Expected value to be defined");
24082
+ }
24083
+ return value;
24084
+ }
23662
24085
  var SecurityScannerOrchestrator = class {
23663
24086
  constructor(retryPolicy, errorHandler) {
23664
24087
  this.retryPolicy = retryPolicy;
@@ -23708,7 +24131,7 @@ var SecurityScannerOrchestrator = class {
23708
24131
  if (detectionResult.detectedStacks.length === 0) {
23709
24132
  throw new Error(`No supported tech stack detected in ${projectRoot}`);
23710
24133
  }
23711
- const techStack = detectionResult.detectedStacks[0];
24134
+ const techStack = expectDefined22(detectionResult.detectedStacks[0]);
23712
24135
  const generatedSkill = await this.generateSkillLLM(provider, model, projectRoot, techStack);
23713
24136
  const scanResult = await this.scanWithLLM(provider, model, projectRoot, generatedSkill, techStack, options);
23714
24137
  const synthesizedReport = await this.synthesizeReportLLM(provider, model, projectRoot, techStack, scanResult);
@@ -23789,7 +24212,7 @@ Return ONLY the JSON object, no markdown, no explanation.`;
23789
24212
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
23790
24213
  const jsonMatch = text.match(/\{[\s\S]*\}/);
23791
24214
  if (jsonMatch) {
23792
- const sanitized = sanitizeJsonString(jsonMatch[0]) || jsonMatch[0];
24215
+ const sanitized = sanitizeJsonString(expectDefined22(jsonMatch[0])) || expectDefined22(jsonMatch[0]);
23793
24216
  const skillData = JSON.parse(sanitized);
23794
24217
  return {
23795
24218
  name: skillData.name || `security-scanner-${techStack.stack}`,
@@ -23909,7 +24332,7 @@ Return ONLY the JSON array. If no issues found, return [].`;
23909
24332
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
23910
24333
  const jsonMatch = text.match(/\[[\s\S]*\]/);
23911
24334
  if (jsonMatch) {
23912
- const sanitized = sanitizeJsonString(jsonMatch[0]) || jsonMatch[0];
24335
+ const sanitized = sanitizeJsonString(expectDefined22(jsonMatch[0])) || expectDefined22(jsonMatch[0]);
23913
24336
  const parsed = JSON.parse(sanitized);
23914
24337
  return parsed.map((item, idx) => ({
23915
24338
  id: `llm-finding-${idx}-${Date.now()}`,
@@ -24149,7 +24572,7 @@ ${dirs.join(", ")}`);
24149
24572
  if (detectionResult.detectedStacks.length === 0) {
24150
24573
  throw new Error(`No supported tech stack detected in ${projectRoot}`);
24151
24574
  }
24152
- const techStack = detectionResult.detectedStacks[0];
24575
+ const techStack = expectDefined22(detectionResult.detectedStacks[0]);
24153
24576
  return {
24154
24577
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
24155
24578
  projectRoot,
@@ -24757,6 +25180,12 @@ var FleetManager = class {
24757
25180
  this.usage.dispose();
24758
25181
  }
24759
25182
  };
25183
+ function expectDefined23(value) {
25184
+ if (value === null || value === void 0) {
25185
+ throw new Error("Expected value to be defined");
25186
+ }
25187
+ return value;
25188
+ }
24760
25189
  function createMcpControlTool(opts) {
24761
25190
  const { getConfig, configPath, registry } = opts;
24762
25191
  const inputSchema = {
@@ -24802,11 +25231,11 @@ async function mcpControlDispatch(input, deps) {
24802
25231
  case "search":
24803
25232
  return renderSearch(query ?? "", deps);
24804
25233
  case "enable":
24805
- return runEnable(server, deps);
25234
+ return server ? runEnable(server, deps) : "`server` is required for enable.";
24806
25235
  case "disable":
24807
- return runDisable(server, deps);
25236
+ return server ? runDisable(server, deps) : "`server` is required for disable.";
24808
25237
  case "restart":
24809
- return runRestart(server, deps);
25238
+ return server ? runRestart(server, deps) : "`server` is required for restart.";
24810
25239
  default:
24811
25240
  return `Unknown action "${action}". Use one of: list, search, enable, disable, restart.`;
24812
25241
  }
@@ -24908,7 +25337,7 @@ async function runDisable(name, deps) {
24908
25337
  const mcpServers = {
24909
25338
  ...full.mcpServers ?? {}
24910
25339
  };
24911
- const existing = mcpServers[name];
25340
+ const existing = expectDefined23(mcpServers[name]);
24912
25341
  mcpServers[name] = { ...existing, enabled: false };
24913
25342
  full.mcpServers = mcpServers;
24914
25343
  await writeConfig(deps.configPath, full);
@@ -24979,6 +25408,12 @@ function badge(state) {
24979
25408
  }
24980
25409
 
24981
25410
  // src/extension/registry.ts
25411
+ function expectDefined24(value) {
25412
+ if (value === null || value === void 0) {
25413
+ throw new Error("Expected value to be defined");
25414
+ }
25415
+ return value;
25416
+ }
24982
25417
  var ExtensionRegistry = class {
24983
25418
  extensions = [];
24984
25419
  promptContributors = [];
@@ -25144,11 +25579,12 @@ var ExtensionRegistry = class {
25144
25579
  * default runner, each subsequent wrapper wraps the previous.
25145
25580
  */
25146
25581
  wrapProviderRunner(inner) {
25147
- const wrappers = this.extensions.filter((e) => e.wrapProviderRunner).map((e) => ({ name: e.name, wrap: e.wrapProviderRunner }));
25582
+ const wrappers = this.extensions.filter((e) => e.wrapProviderRunner).map((e) => ({ name: e.name, wrap: expectDefined24(e.wrapProviderRunner) }));
25148
25583
  if (wrappers.length === 0) return inner;
25149
25584
  let composed = inner;
25150
25585
  for (let i = wrappers.length - 1; i >= 0; i--) {
25151
25586
  const wrapper = wrappers[i];
25587
+ if (!wrapper) continue;
25152
25588
  const next = composed;
25153
25589
  composed = async (ctx, req) => {
25154
25590
  try {
@@ -25247,7 +25683,7 @@ function createAgentToolHandler(a) {
25247
25683
  const useById = new Map(selectedToolUses.map((u) => [u.id, u]));
25248
25684
  const resultsForMessage = [];
25249
25685
  for (const { result, tool, durationMs } of outputs) {
25250
- if (result.type === "tool_confirm_pending") {
25686
+ if (result.type === "tool_confirm_pending" && tool) {
25251
25687
  const decision = await waitForConfirm({
25252
25688
  tool,
25253
25689
  input: result.input,
@@ -25309,6 +25745,7 @@ function createAgentToolHandler(a) {
25309
25745
  resultsForMessage.push(reRunResult.result);
25310
25746
  continue;
25311
25747
  }
25748
+ if (result.type !== "tool_result") continue;
25312
25749
  resultsForMessage.push(result);
25313
25750
  const use = useById.get(result.tool_use_id);
25314
25751
  if (!use) continue;
@@ -25824,13 +26261,12 @@ var Agent = class {
25824
26261
  return this.container.resolve(TOKENS.PermissionPolicy);
25825
26262
  }
25826
26263
  get renderer() {
25827
- return this.container.has(TOKENS.Renderer) ? this.container.resolve(TOKENS.Renderer) : void 0;
26264
+ return this.container.safeResolve(TOKENS.Renderer);
25828
26265
  }
25829
26266
  disableInteractiveConfirmation() {
25830
26267
  this.toolExecutor.clearConfirmAwaiter();
25831
- const policy = this.permission;
25832
- if (typeof policy.setPromptDelegate === "function") {
25833
- policy.setPromptDelegate(void 0);
26268
+ if (typeof this.permission.setPromptDelegate === "function") {
26269
+ this.permission.setPromptDelegate(void 0);
25834
26270
  }
25835
26271
  }
25836
26272
  register(tool) {
@@ -25860,6 +26296,7 @@ var Agent = class {
25860
26296
  const signal = controller.signal;
25861
26297
  this.ctx.signal = signal;
25862
26298
  controller.onAbort(() => this.ctx.drainAbortHooks());
26299
+ this.ctx.tools = this.tools.list();
25863
26300
  const span = this.tracer?.startSpan("agent.run", {
25864
26301
  "agent.model": opts.model ?? this.ctx.model,
25865
26302
  "agent.executionStrategy": opts.executionStrategy ?? this.executionStrategy
@@ -25876,7 +26313,8 @@ var Agent = class {
25876
26313
  return result;
25877
26314
  } catch (err) {
25878
26315
  const wse = err instanceof AgentError ? err : toWrongStackError(err);
25879
- this.events.emit("error", { err: err instanceof Error ? err : new Error(String(err)), phase: "agent" });
26316
+ const safeError = err instanceof Error ? new Error(err.message) : new Error(String(err));
26317
+ this.events.emit("error", { err: safeError, phase: "agent", _original: err instanceof Error ? err : void 0 });
25880
26318
  if (err instanceof Error) span?.recordError(err);
25881
26319
  span?.setAttribute("agent.status", "failed");
25882
26320
  const result = {
@@ -27907,7 +28345,7 @@ function buildRefinerInput(text, history) {
27907
28345
  }
27908
28346
  async function enhanceUserPrompt(opts) {
27909
28347
  const { provider, model, text } = opts;
27910
- const timeoutMs = opts.timeoutMs ?? 25e3;
28348
+ const timeoutMs = opts.timeoutMs ?? 9e4;
27911
28349
  const maxTokens = opts.maxTokens ?? 2048;
27912
28350
  const req = {
27913
28351
  model,
@@ -27972,7 +28410,7 @@ var PhaseGraphBuilder = class _PhaseGraphBuilder {
27972
28410
  const phases = /* @__PURE__ */ new Map();
27973
28411
  const phaseIds = [];
27974
28412
  for (let i = 0; i < this.opts.phases.length; i++) {
27975
- const tmpl = this.opts.phases[i];
28413
+ const tmpl = this.opts.phases[i] ?? { name: "", description: "", taskTemplates: [], parallelizable: false, priority: "medium", estimateHours: 0 };
27976
28414
  const phaseId = crypto.randomUUID();
27977
28415
  phaseIds.push(phaseId);
27978
28416
  const store = this.opts.externalTaskStore ?? new DefaultTaskStore();
@@ -27997,8 +28435,8 @@ var PhaseGraphBuilder = class _PhaseGraphBuilder {
27997
28435
  description: tmpl.description,
27998
28436
  status: "pending",
27999
28437
  taskGraph,
28000
- dependsOn: i > 0 ? [phaseIds[i - 1]] : [],
28001
- nextPhases: i < this.opts.phases.length - 1 ? [phaseIds[i + 1]] : [],
28438
+ dependsOn: i > 0 ? [phaseIds[i - 1] ?? ""] : [],
28439
+ nextPhases: i < this.opts.phases.length - 1 ? [phaseIds[i + 1] ?? ""] : [],
28002
28440
  parallelizable: tmpl.parallelizable,
28003
28441
  priority: tmpl.priority,
28004
28442
  estimateHours: tmpl.estimateHours,
@@ -28011,15 +28449,16 @@ var PhaseGraphBuilder = class _PhaseGraphBuilder {
28011
28449
  const phaseArray = Array.from(phases.values());
28012
28450
  for (let i = 0; i < phaseArray.length; i++) {
28013
28451
  const phase = phaseArray[i];
28014
- phase.nextPhases = i < phaseArray.length - 1 ? [phaseArray[i + 1].id] : [];
28015
- phase.dependsOn = i > 0 ? [phaseArray[i - 1].id] : [];
28452
+ if (!phase) continue;
28453
+ phase.nextPhases = i < phaseArray.length - 1 ? [phaseArray[i + 1]?.id ?? ""] : [];
28454
+ phase.dependsOn = i > 0 ? [phaseArray[i - 1]?.id ?? ""] : [];
28016
28455
  }
28017
28456
  const graph = {
28018
28457
  id: graphId,
28019
28458
  title: this.opts.title,
28020
28459
  description: this.opts.description ?? "",
28021
28460
  phases,
28022
- rootPhaseIds: phaseIds.length > 0 ? [phaseIds[0]] : [],
28461
+ rootPhaseIds: phaseIds.length > 0 ? [phaseIds[0] ?? ""] : [],
28023
28462
  activePhaseIds: [],
28024
28463
  completedPhaseIds: [],
28025
28464
  failedPhaseIds: [],
@@ -28201,7 +28640,7 @@ var PhaseOrchestrator = class {
28201
28640
  return;
28202
28641
  }
28203
28642
  if (this.opts.stopOnFailure && this.graph.failedPhaseIds.length > 0) {
28204
- const failedPhase = this.graph.phases.get(this.graph.failedPhaseIds[0]);
28643
+ const failedPhase = this.graph.phases.get(this.graph.failedPhaseIds[0] ?? "");
28205
28644
  if (failedPhase) {
28206
28645
  this.onGraphFailed(failedPhase);
28207
28646
  }
@@ -28377,9 +28816,14 @@ var PhaseOrchestrator = class {
28377
28816
  name: phase.name,
28378
28817
  files: info.conflictFiles
28379
28818
  });
28380
- return this.ctx.resolveConflict(phase, info);
28819
+ const resolved = await this.ctx.resolveConflict?.(phase, info);
28820
+ return resolved ?? false;
28381
28821
  } : void 0;
28382
- const result = await this.worktrees.merge(handle, { squash: true, resolve: resolve13 });
28822
+ const mergeOpts = {
28823
+ squash: true
28824
+ };
28825
+ if (resolve13 !== void 0) mergeOpts.resolve = resolve13;
28826
+ const result = await this.worktrees.merge(handle, mergeOpts);
28383
28827
  if (result.resolved) {
28384
28828
  this.emit("phase.conflictResolved", { phaseId: phase.id, name: phase.name });
28385
28829
  }
@@ -28773,9 +29217,6 @@ var AutoPhaseRunner = class {
28773
29217
  this.graph = await builder.build();
28774
29218
  const ctx = {
28775
29219
  executeTask: this.opts.executeTask,
28776
- verifyPhase: this.opts.verifyPhase,
28777
- repairPhase: this.opts.repairPhase,
28778
- resolveConflict: this.opts.resolveConflict,
28779
29220
  brain: this.opts.brain,
28780
29221
  onPhaseComplete: (phase) => {
28781
29222
  this.opts.onPhaseComplete?.(phase);
@@ -28787,6 +29228,9 @@ var AutoPhaseRunner = class {
28787
29228
  this.opts.onTick?.(tickCtx);
28788
29229
  }
28789
29230
  };
29231
+ if (this.opts.verifyPhase !== void 0) ctx.verifyPhase = this.opts.verifyPhase;
29232
+ if (this.opts.repairPhase !== void 0) ctx.repairPhase = this.opts.repairPhase;
29233
+ if (this.opts.resolveConflict !== void 0) ctx.resolveConflict = this.opts.resolveConflict;
28790
29234
  this.orchestrator = new PhaseOrchestrator({
28791
29235
  graph: this.graph,
28792
29236
  ctx,
@@ -28802,8 +29246,8 @@ var AutoPhaseRunner = class {
28802
29246
  });
28803
29247
  if (this.opts.onProgress) {
28804
29248
  this.progressInterval = setInterval(() => {
28805
- const progress = this.orchestrator.getProgress();
28806
- this.opts.onProgress(progress);
29249
+ const progress = this.orchestrator?.getProgress();
29250
+ if (progress) this.opts.onProgress?.(progress);
28807
29251
  }, 2e3);
28808
29252
  }
28809
29253
  if (this.opts.events) {
@@ -29023,7 +29467,7 @@ function firstBalancedArray(text) {
29023
29467
  let inString = false;
29024
29468
  let escaped = false;
29025
29469
  for (let i = start; i < text.length; i++) {
29026
- const ch = text[i];
29470
+ const ch = text[i] ?? "";
29027
29471
  if (inString) {
29028
29472
  if (escaped) {
29029
29473
  escaped = false;
@@ -29533,7 +29977,7 @@ ${merged.stderr}`);
29533
29977
  async tryResolveConflict(handle, conflictFiles, opts) {
29534
29978
  let resolved = false;
29535
29979
  try {
29536
- resolved = await opts.resolve({ conflictFiles, cwd: this.projectRoot });
29980
+ resolved = opts.resolve ? await opts.resolve({ conflictFiles, cwd: this.projectRoot }) : false;
29537
29981
  } catch {
29538
29982
  resolved = false;
29539
29983
  }
@@ -30056,6 +30500,12 @@ var ReplayProviderRunner = class {
30056
30500
  };
30057
30501
 
30058
30502
  // src/plugins/prompts-plugin.ts
30503
+ function expectDefined25(value) {
30504
+ if (value === null || value === void 0) {
30505
+ throw new Error("Expected value to be defined");
30506
+ }
30507
+ return value;
30508
+ }
30059
30509
  function createPromptsPlugin(opts) {
30060
30510
  let store = null;
30061
30511
  return {
@@ -30109,7 +30559,7 @@ ${lines.join("\n")}
30109
30559
  if (!restJoined) return { message: "Usage: /prompts view <title>" };
30110
30560
  const matches = await store.find(restJoined);
30111
30561
  if (matches.length === 0) return { message: `No prompt matching "${restJoined}".` };
30112
- const entry = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? matches[0];
30562
+ const entry = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? expectDefined25(matches[0]);
30113
30563
  const tags = entry.tags.length > 0 ? ` [${entry.tags.join(", ")}]` : "";
30114
30564
  return {
30115
30565
  message: `# ${entry.title}${tags}
@@ -30132,7 +30582,7 @@ ${dim2(`id: ${entry.id} | created: ${entry.createdAt}`)}`
30132
30582
  if (!restJoined) return { message: "Usage: /prompts delete <title>" };
30133
30583
  const matches = await store.find(restJoined);
30134
30584
  if (matches.length === 0) return { message: `No prompt matching "${restJoined}".` };
30135
- const exact = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? matches[0];
30585
+ const exact = matches.find((m) => m.title.toLowerCase() === restJoined.toLowerCase()) ?? expectDefined25(matches[0]);
30136
30586
  const deleted = await store.delete(exact.id);
30137
30587
  return { message: deleted ? `Deleted "${exact.title}".` : "Delete failed." };
30138
30588
  }
@@ -30142,7 +30592,7 @@ ${dim2(`id: ${entry.id} | created: ${entry.createdAt}`)}`
30142
30592
  if (!parsed.title) return { message: 'Usage: /prompts edit "title" "new content"' };
30143
30593
  const matches = await store.find(parsed.title);
30144
30594
  if (matches.length === 0) return { message: `No prompt matching "${parsed.title}".` };
30145
- const exact = matches.find((m) => m.title.toLowerCase() === parsed.title.toLowerCase()) ?? matches[0];
30595
+ const exact = matches.find((m) => m.title.toLowerCase() === parsed.title?.toLowerCase()) ?? expectDefined25(matches[0]);
30146
30596
  exact.content = parsed.content;
30147
30597
  exact.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
30148
30598
  await store.save(exact);
@@ -30154,7 +30604,7 @@ ${dim2(`id: ${entry.id} | created: ${entry.createdAt}`)}`
30154
30604
  if (!parsed.title) return { message: 'Usage: /prompts extend "title" <instructions>' };
30155
30605
  const matches = await store.find(parsed.title);
30156
30606
  if (matches.length === 0) return { message: `No prompt matching "${parsed.title}".` };
30157
- const exact = matches.find((m) => m.title.toLowerCase() === parsed.title.toLowerCase()) ?? matches[0];
30607
+ const exact = matches.find((m) => m.title.toLowerCase() === parsed.title?.toLowerCase()) ?? expectDefined25(matches[0]);
30158
30608
  const prov = ctx.provider;
30159
30609
  if (!prov?.complete) return { message: "LLM not available. Configure a provider first." };
30160
30610
  const enhanced = await prov.complete(ctx.model, [
@@ -30189,9 +30639,9 @@ function parseTitleContent(args) {
30189
30639
  const trimmed = args.trim();
30190
30640
  if (!trimmed) return { title: "", content: "" };
30191
30641
  const doubleMatch = /^"([^"]+)"\s+"([^"]+)"$/.exec(trimmed) || /^'([^']+)'\s+'([^']+)'$/.exec(trimmed);
30192
- if (doubleMatch) return { title: doubleMatch[1], content: doubleMatch[2] };
30642
+ if (doubleMatch) return { title: expectDefined25(doubleMatch[1]), content: expectDefined25(doubleMatch[2]) };
30193
30643
  const singleMatch = /^'([^']+)'\s+(.+)$/.exec(trimmed);
30194
- if (singleMatch) return { title: singleMatch[1], content: singleMatch[2] };
30644
+ if (singleMatch) return { title: expectDefined25(singleMatch[1]), content: expectDefined25(singleMatch[2]) };
30195
30645
  const firstSpace = trimmed.indexOf(" ");
30196
30646
  if (firstSpace === -1) return { title: trimmed, content: "" };
30197
30647
  return { title: trimmed.slice(0, firstSpace), content: trimmed.slice(firstSpace + 1) };
@@ -30202,6 +30652,12 @@ function dim2(s) {
30202
30652
 
30203
30653
  // src/plugins/sync-plugin.ts
30204
30654
  init_atomic_write();
30655
+ function expectDefined26(value) {
30656
+ if (value === null || value === void 0) {
30657
+ throw new Error("Expected value to be defined");
30658
+ }
30659
+ return value;
30660
+ }
30205
30661
  function createSyncPlugin(opts) {
30206
30662
  let cloud = null;
30207
30663
  let configStore;
@@ -30227,11 +30683,11 @@ function createSyncPlugin(opts) {
30227
30683
  cloud = new CloudSync(
30228
30684
  paths,
30229
30685
  () => {
30230
- const cfg = configStore.get();
30686
+ const cfg = configStore?.get();
30231
30687
  return cfg.sync;
30232
30688
  },
30233
30689
  async (cfg) => {
30234
- configStore.update({ sync: cfg });
30690
+ configStore?.update({ sync: cfg });
30235
30691
  }
30236
30692
  );
30237
30693
  void cloud.loadState();
@@ -30275,7 +30731,7 @@ function buildSyncCommand(cloud, configStore, vault, syncConfigPath) {
30275
30731
  if (!repo || !repo.includes("/")) {
30276
30732
  return { message: 'Invalid repo format. Expected "owner/repo".' };
30277
30733
  }
30278
- const storedToken = vault ? vault.encrypt(token) : token;
30734
+ const storedToken = vault ? vault.encrypt(expectDefined26(token)) : expectDefined26(token);
30279
30735
  const syncConfig = {
30280
30736
  enabled: true,
30281
30737
  repo,
@@ -30515,7 +30971,7 @@ async function generateCommitMessageHeuristics(cwd) {
30515
30971
  const commitType = detectCommitType(statsResult.stdout);
30516
30972
  let scope = "";
30517
30973
  if (files.length > 0) {
30518
- const primary = files[0].split("/")[0];
30974
+ const primary = files[0]?.split("/")[0];
30519
30975
  if (primary && primary !== "packages" && primary !== "apps" && primary !== "node_modules") {
30520
30976
  scope = `(${primary})`;
30521
30977
  }
@@ -31112,6 +31568,6 @@ ${formatPlan(updated)}`
31112
31568
  };
31113
31569
  }
31114
31570
 
31115
- 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, 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, setPlanItemStatus, setRawMode, shouldEnhance, slackServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
31571
+ 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, 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, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, writeErr, writeOut, zaiVisionServer };
31116
31572
  //# sourceMappingURL=index.js.map
31117
31573
  //# sourceMappingURL=index.js.map