@wrongstack/core 0.6.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/{agent-bridge-BBXK_ppx.d.ts → agent-bridge-CrQpYjM7.d.ts} +1 -1
  2. package/dist/{compactor-C8NhpSt5.d.ts → compactor-CWV1u-IU.d.ts} +1 -1
  3. package/dist/{config-DfC6g6KV.d.ts → config-C34JRwl4.d.ts} +1 -1
  4. package/dist/{context-DN5v-uQX.d.ts → context-bmR0YgBm.d.ts} +74 -8
  5. package/dist/coordination/index.d.ts +11 -11
  6. package/dist/coordination/index.js +115 -39
  7. package/dist/coordination/index.js.map +1 -1
  8. package/dist/default-config-DvRSTELf.d.ts +20 -0
  9. package/dist/defaults/index.d.ts +20 -19
  10. package/dist/defaults/index.js +224 -64
  11. package/dist/defaults/index.js.map +1 -1
  12. package/dist/{events-CJqwQl8G.d.ts → events-CEKFTmIY.d.ts} +10 -1
  13. package/dist/execution/index.d.ts +27 -13
  14. package/dist/execution/index.js +153 -40
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -6
  17. package/dist/extension/index.js +3 -1
  18. package/dist/extension/index.js.map +1 -1
  19. package/dist/{index-DcnXDPdY.d.ts → index-BJIFLGII.d.ts} +20 -5
  20. package/dist/{index-CXnWsGBp.d.ts → index-CZR0HjxM.d.ts} +14 -110
  21. package/dist/index.d.ts +27 -26
  22. package/dist/index.js +396 -180
  23. package/dist/index.js.map +1 -1
  24. package/dist/infrastructure/index.d.ts +6 -6
  25. package/dist/kernel/index.d.ts +9 -9
  26. package/dist/kernel/index.js +8 -4
  27. package/dist/kernel/index.js.map +1 -1
  28. package/dist/{mcp-servers-CevFHHM1.d.ts → mcp-servers-BRJicm5o.d.ts} +3 -3
  29. package/dist/models/index.d.ts +2 -2
  30. package/dist/{multi-agent-D5IbASk_.d.ts → multi-agent-Cm1wYSrw.d.ts} +9 -4
  31. package/dist/{agent-subagent-runner-DsSm9lKN.d.ts → multi-agent-coordinator-CCupVFqv.d.ts} +117 -4
  32. package/dist/observability/index.d.ts +2 -2
  33. package/dist/{path-resolver-CBx_q1HA.d.ts → path-resolver-CfT7e_HT.d.ts} +2 -2
  34. package/dist/{plan-templates-BEOllUJV.d.ts → plan-templates-Q78an-GJ.d.ts} +4 -4
  35. package/dist/{provider-runner-Byh5TcJs.d.ts → provider-runner-WDj28o7J.d.ts} +3 -3
  36. package/dist/{retry-policy-BZSIMxrJ.d.ts → retry-policy-Dpxp4SET.d.ts} +1 -1
  37. package/dist/sdd/index.d.ts +3 -3
  38. package/dist/{secret-scrubber-CT7wefiO.d.ts → secret-scrubber-C2YCYtkn.d.ts} +1 -1
  39. package/dist/{secret-scrubber-I0QHY_ob.d.ts → secret-scrubber-CowtdEF8.d.ts} +1 -1
  40. package/dist/security/index.d.ts +3 -3
  41. package/dist/{selector-DDb_mq9X.d.ts → selector-CP39HhCe.d.ts} +1 -1
  42. package/dist/{session-reader-B9nVkziM.d.ts → session-reader-Dwjn4WZR.d.ts} +1 -1
  43. package/dist/storage/index.d.ts +5 -5
  44. package/dist/storage/index.js +94 -11
  45. package/dist/storage/index.js.map +1 -1
  46. package/dist/{system-prompt-gL06H9P4.d.ts → system-prompt-CfgXqyv2.d.ts} +1 -1
  47. package/dist/{tool-executor-BF7QfYVE.d.ts → tool-executor-D5NFi_LV.d.ts} +5 -5
  48. package/dist/types/index.d.ts +16 -15
  49. package/dist/types/index.js +102 -23
  50. package/dist/types/index.js.map +1 -1
  51. package/dist/utils/index.d.ts +1 -1
  52. package/package.json +1 -1
@@ -348,8 +348,16 @@ var DefaultSessionStore = class {
348
348
  }
349
349
  }
350
350
  async resume(id) {
351
- const data = await this.load(id);
352
351
  const file = path3.join(this.dir, `${id}.jsonl`);
352
+ try {
353
+ await fsp.access(file, fsp.constants.R_OK);
354
+ } catch {
355
+ throw new Error(
356
+ `Session "${id}" not found \u2014 the session file does not exist or was deleted.`,
357
+ { cause: new Error("ENOENT") }
358
+ );
359
+ }
360
+ const data = await this.load(id);
353
361
  let handle;
354
362
  try {
355
363
  handle = await fsp.open(file, "a", 384);
@@ -1303,6 +1311,20 @@ function safeParse(input, maxBytes = 5e6) {
1303
1311
  }
1304
1312
  }
1305
1313
 
1314
+ // src/types/default-config.ts
1315
+ var DEFAULT_TOOLS_CONFIG = Object.freeze({
1316
+ defaultExecutionStrategy: "smart",
1317
+ maxIterations: 100,
1318
+ iterationTimeoutMs: 3e5,
1319
+ sessionTimeoutMs: 18e5,
1320
+ perIterationOutputCapBytes: 1e5,
1321
+ autoExtendLimit: true
1322
+ });
1323
+ var DEFAULT_CONTEXT_CONFIG = Object.freeze({
1324
+ preserveK: 10,
1325
+ eliseThreshold: 2e3
1326
+ });
1327
+
1306
1328
  // src/storage/config-loader.ts
1307
1329
  var BEHAVIOR_DEFAULTS = {
1308
1330
  version: 1,
@@ -1312,16 +1334,16 @@ var BEHAVIOR_DEFAULTS = {
1312
1334
  softThreshold: 0.75,
1313
1335
  hardThreshold: 0.9,
1314
1336
  autoCompact: true,
1315
- preserveK: 10,
1316
- eliseThreshold: 2e3
1337
+ preserveK: DEFAULT_CONTEXT_CONFIG.preserveK,
1338
+ eliseThreshold: DEFAULT_CONTEXT_CONFIG.eliseThreshold
1317
1339
  },
1318
1340
  tools: {
1319
- defaultExecutionStrategy: "smart",
1320
- maxIterations: 100,
1321
- iterationTimeoutMs: 3e5,
1322
- sessionTimeoutMs: 18e5,
1323
- perIterationOutputCapBytes: 1e5,
1324
- autoExtendLimit: true
1341
+ defaultExecutionStrategy: DEFAULT_TOOLS_CONFIG.defaultExecutionStrategy,
1342
+ maxIterations: DEFAULT_TOOLS_CONFIG.maxIterations,
1343
+ iterationTimeoutMs: DEFAULT_TOOLS_CONFIG.iterationTimeoutMs,
1344
+ sessionTimeoutMs: DEFAULT_TOOLS_CONFIG.sessionTimeoutMs,
1345
+ perIterationOutputCapBytes: DEFAULT_TOOLS_CONFIG.perIterationOutputCapBytes,
1346
+ autoExtendLimit: DEFAULT_TOOLS_CONFIG.autoExtendLimit
1325
1347
  },
1326
1348
  log: { level: "info" },
1327
1349
  features: {
@@ -2531,7 +2553,7 @@ var DirectorStateCheckpoint = class {
2531
2553
  this.timer = null;
2532
2554
  }
2533
2555
  await this.persist();
2534
- if (this.rewriteRequested) {
2556
+ while (this.rewriteRequested) {
2535
2557
  this.rewriteRequested = false;
2536
2558
  await this.persist();
2537
2559
  }
@@ -3192,6 +3214,22 @@ var AutoApprovePermissionPolicy = class {
3192
3214
  };
3193
3215
 
3194
3216
  // src/types/errors.ts
3217
+ var ERROR_CODES = {
3218
+ // Provider
3219
+ PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
3220
+ PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
3221
+ PROVIDER_OVERLOADED: "PROVIDER_OVERLOADED",
3222
+ PROVIDER_INVALID_REQUEST: "PROVIDER_INVALID_REQUEST",
3223
+ PROVIDER_SERVER_ERROR: "PROVIDER_SERVER_ERROR",
3224
+ PROVIDER_NETWORK_ERROR: "PROVIDER_NETWORK_ERROR",
3225
+ // Agent
3226
+ AGENT_ITERATION_LIMIT: "AGENT_ITERATION_LIMIT",
3227
+ AGENT_CONTEXT_OVERFLOW: "AGENT_CONTEXT_OVERFLOW",
3228
+ AGENT_ABORTED: "AGENT_ABORTED",
3229
+ AGENT_RUN_FAILED: "AGENT_RUN_FAILED",
3230
+ // File system
3231
+ FS_READ_FAILED: "FS_READ_FAILED",
3232
+ FS_ATOMIC_WRITE_FAILED: "FS_ATOMIC_WRITE_FAILED"};
3195
3233
  var WrongStackError = class extends Error {
3196
3234
  code;
3197
3235
  subsystem;
@@ -3226,23 +3264,39 @@ var AgentError = class extends WrongStackError {
3226
3264
  message: opts.message,
3227
3265
  code: opts.code,
3228
3266
  subsystem: "agent",
3229
- severity: opts.code === "AGENT_ABORTED" ? "warning" : "error",
3230
- recoverable: opts.recoverable ?? opts.code === "AGENT_ITERATION_LIMIT",
3267
+ severity: opts.code === ERROR_CODES.AGENT_ABORTED ? "warning" : "error",
3268
+ recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,
3231
3269
  context: opts.context,
3232
3270
  cause: opts.cause
3233
3271
  });
3234
3272
  this.name = "AgentError";
3235
3273
  }
3236
3274
  };
3237
- function toWrongStackError(err, code = "AGENT_RUN_FAILED") {
3275
+ function toWrongStackError(err, code = ERROR_CODES.AGENT_RUN_FAILED) {
3238
3276
  if (err instanceof WrongStackError) return err;
3239
3277
  const message = err instanceof Error ? err.message : String(err);
3240
3278
  return new AgentError({
3241
3279
  message,
3242
- code: code === "UNKNOWN" ? "AGENT_RUN_FAILED" : code,
3280
+ code: code === "UNKNOWN" ? ERROR_CODES.AGENT_RUN_FAILED : code,
3243
3281
  cause: err
3244
3282
  });
3245
3283
  }
3284
+ var FsError = class extends WrongStackError {
3285
+ path;
3286
+ constructor(opts) {
3287
+ super({
3288
+ message: opts.message,
3289
+ code: opts.code,
3290
+ subsystem: "fs",
3291
+ severity: "error",
3292
+ recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,
3293
+ context: { path: opts.path, ...opts.context },
3294
+ cause: opts.cause
3295
+ });
3296
+ this.name = "FsError";
3297
+ this.path = opts.path;
3298
+ }
3299
+ };
3246
3300
 
3247
3301
  // src/types/provider.ts
3248
3302
  var ProviderError = class extends WrongStackError {
@@ -3306,26 +3360,28 @@ function truncate(s, n) {
3306
3360
  return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
3307
3361
  }
3308
3362
  function providerStatusToCode(status, type) {
3309
- if (status === 0) return "PROVIDER_NETWORK_ERROR";
3310
- if (type === "rate_limit_error" || status === 429) return "PROVIDER_RATE_LIMITED";
3311
- if (type === "authentication_error" || status === 401) return "PROVIDER_AUTH_FAILED";
3312
- if (type === "overloaded_error" || status === 529) return "PROVIDER_OVERLOADED";
3313
- if (type === "invalid_request_error" || status === 400) return "PROVIDER_INVALID_REQUEST";
3314
- if (status === 408) return "PROVIDER_NETWORK_ERROR";
3315
- if (status >= 500) return "PROVIDER_SERVER_ERROR";
3316
- return "PROVIDER_INVALID_REQUEST";
3363
+ if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;
3364
+ if (type === "rate_limit_error" || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;
3365
+ if (type === "authentication_error" || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;
3366
+ if (type === "overloaded_error" || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;
3367
+ if (type === "invalid_request_error" || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;
3368
+ if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;
3369
+ if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;
3370
+ return ERROR_CODES.PROVIDER_INVALID_REQUEST;
3317
3371
  }
3318
3372
 
3373
+ // src/execution/regex-patterns.ts
3374
+ var NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;
3375
+
3319
3376
  // src/execution/retry-policy.ts
3320
- var DefaultRetryPolicy = class _DefaultRetryPolicy {
3321
- static NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;
3377
+ var DefaultRetryPolicy = class {
3322
3378
  shouldRetry(err, attempt) {
3323
3379
  if (err instanceof ProviderError) {
3324
3380
  if (!err.retryable) return false;
3325
3381
  return attempt < this.maxAttempts(err);
3326
3382
  }
3327
3383
  const msg = err.message ?? "";
3328
- const isNetwork = _DefaultRetryPolicy.NETWORK_ERR_RE.test(msg);
3384
+ const isNetwork = NETWORK_ERR_RE.test(msg);
3329
3385
  if (isNetwork) return attempt < 2;
3330
3386
  return false;
3331
3387
  }
@@ -3348,7 +3404,6 @@ var DefaultRetryPolicy = class _DefaultRetryPolicy {
3348
3404
 
3349
3405
  // src/execution/error-handler.ts
3350
3406
  var CONTEXT_OVERFLOW_RE = /context|too long|tokens/i;
3351
- var NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;
3352
3407
  function buildRecoveryStrategies(opts) {
3353
3408
  return [
3354
3409
  {
@@ -4815,7 +4870,7 @@ var AutoCompactionMiddleware = class {
4815
4870
  if (fatal) {
4816
4871
  throw new AgentError({
4817
4872
  message: `Auto-compaction failed at ${pressure.level} threshold`,
4818
- code: "AGENT_CONTEXT_OVERFLOW",
4873
+ code: ERROR_CODES.AGENT_CONTEXT_OVERFLOW,
4819
4874
  recoverable: true,
4820
4875
  context: {
4821
4876
  level: pressure.level,
@@ -5348,7 +5403,16 @@ async function loadGoal(filePath) {
5348
5403
  }
5349
5404
  }
5350
5405
  async function saveGoal(filePath, goal) {
5351
- await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 384 });
5406
+ try {
5407
+ await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 384 });
5408
+ } catch (err) {
5409
+ throw new FsError({
5410
+ message: err instanceof Error ? err.message : String(err),
5411
+ code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,
5412
+ path: filePath,
5413
+ cause: err
5414
+ });
5415
+ }
5352
5416
  }
5353
5417
  function appendJournal(goal, entry) {
5354
5418
  const iteration = goal.iterations + 1;
@@ -5367,7 +5431,8 @@ function appendJournal(goal, entry) {
5367
5431
  // src/execution/eternal-autonomy.ts
5368
5432
  var execFileP = promisify(execFile);
5369
5433
  var BRAINSTORM_DONE = /* @__PURE__ */ Symbol("brainstorm-done");
5370
- var GOAL_COMPLETE_MARKER = /^\s*\[goal[_\s-]?complete\]\s*$/im;
5434
+ var GOAL_COMPLETE_MARKER = /^\s*\[goal[_\s-]*complete\]\s*$/im;
5435
+ var GOAL_CLEAR_MARKER = /^\s*\[\/?goal\s*clear\]\s*$/im;
5371
5436
  var EternalAutonomyEngine = class {
5372
5437
  constructor(opts) {
5373
5438
  this.opts = opts;
@@ -5505,7 +5570,7 @@ var EternalAutonomyEngine = class {
5505
5570
  // Cap the inner loop so a runaway agent.run can't burn through
5506
5571
  // the iteration timeout — the engine's own outer loop is the
5507
5572
  // long-running thing, each tick should be bounded.
5508
- maxIterations: this.opts.iterationMaxAgentSteps ?? 50
5573
+ maxIterations: this.opts.iterationMaxAgentSteps ?? 500
5509
5574
  }
5510
5575
  );
5511
5576
  if (result.status === "aborted") {
@@ -5593,7 +5658,12 @@ var EternalAutonomyEngine = class {
5593
5658
  emit({ phase: "sleep", ms: cycleGapMs });
5594
5659
  await sleep(cycleGapMs);
5595
5660
  if (GOAL_COMPLETE_MARKER.test(finalText)) {
5596
- await this.markGoalCompleted(action, finalText);
5661
+ await this.clearGoalManually(finalText);
5662
+ this.stopRequested = true;
5663
+ return true;
5664
+ }
5665
+ if (GOAL_CLEAR_MARKER.test(finalText)) {
5666
+ await this.clearGoalManually(finalText);
5597
5667
  this.stopRequested = true;
5598
5668
  return true;
5599
5669
  }
@@ -5893,6 +5963,30 @@ ${recentJournal}` : "No prior iterations.",
5893
5963
  });
5894
5964
  await saveGoal(this.goalPath, withEntry);
5895
5965
  }
5966
+ /**
5967
+ * Manually clear the goal — equivalent to `/goal clear` typed by the user.
5968
+ * Sets goalState to `abandoned`, removes the goal file, and fires
5969
+ * `onEternalStop` so the REPL returns to normal mode.
5970
+ */
5971
+ async clearGoalManually(note) {
5972
+ const current = await loadGoal(this.goalPath);
5973
+ if (current) {
5974
+ const abandoned = { ...current, goalState: "abandoned" };
5975
+ await saveGoal(this.goalPath, abandoned);
5976
+ }
5977
+ try {
5978
+ const { unlink: unlink9 } = await import('fs/promises');
5979
+ await unlink9(this.goalPath);
5980
+ } catch {
5981
+ }
5982
+ this.opts.onEternalStop?.();
5983
+ void this.appendIterationEntry({
5984
+ source: "manual",
5985
+ task: "goal cleared",
5986
+ status: "success",
5987
+ note: note.slice(0, 240)
5988
+ });
5989
+ }
5896
5990
  async appendFailure(task, note) {
5897
5991
  await this.appendIterationEntry({ source: "manual", task, status: "failure", note });
5898
5992
  }
@@ -5960,10 +6054,10 @@ var SubagentBudget = class _SubagentBudget {
5960
6054
  * or hung listener (Director not built / event filter detached mid-run)
5961
6055
  * leaves the budget over-limit and never enforces anything, since
5962
6056
  * `checkLimit` returns synchronously via `void this.checkLimitAsync`.
5963
- * Hardcoded for now most fleets set their own per-task timeout that
5964
- * dwarfs this anyway. 30 s matches the existing event-emit timeoutMs.
6057
+ * Raised from 30s to 60s to give subagents more headroom before
6058
+ * the threshold negotiation times out and triggers a hard stop.
5965
6059
  */
5966
- static DECISION_TIMEOUT_MS = 3e4;
6060
+ static DECISION_TIMEOUT_MS = 6e4;
5967
6061
  /**
5968
6062
  * Injected by the runner when wiring the budget to its EventBus.
5969
6063
  * Used by `checkLimitAsync` to emit `budget.threshold_reached` events.
@@ -6494,13 +6588,19 @@ var FLEET_ROSTER = {
6494
6588
  "security-scanner": SECURITY_SCANNER_AGENT
6495
6589
  };
6496
6590
  var FLEET_ROSTER_BUDGETS = {
6497
- "audit-log": { timeoutMs: 8 * 60 * 1e3, maxIterations: 150, maxToolCalls: 500 },
6498
- "bug-hunter": { timeoutMs: 15 * 60 * 1e3, maxIterations: 200, maxToolCalls: 600 },
6499
- "refactor-planner": { timeoutMs: 12 * 60 * 1e3, maxIterations: 180, maxToolCalls: 550 },
6500
- "security-scanner": { timeoutMs: 15 * 60 * 1e3, maxIterations: 200, maxToolCalls: 600 }
6591
+ "audit-log": { timeoutMs: 7.5 * 60 * 60 * 1e3, maxIterations: 5e3, maxToolCalls: 15e3 },
6592
+ "bug-hunter": { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 },
6593
+ "refactor-planner": { timeoutMs: 7.5 * 60 * 60 * 1e3, maxIterations: 6e3, maxToolCalls: 18e3 },
6594
+ "security-scanner": { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 }
6595
+ };
6596
+ var GENERIC_SUBAGENT_BUDGET = {
6597
+ timeoutMs: 3 * 60 * 60 * 1e3,
6598
+ maxIterations: 5e3,
6599
+ maxToolCalls: 15e3
6501
6600
  };
6502
6601
  function applyRosterBudget(cfg) {
6503
- const defaultBudget = FLEET_ROSTER_BUDGETS[cfg.role ?? ""];
6602
+ const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : void 0;
6603
+ const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : void 0);
6504
6604
  if (!defaultBudget) return cfg;
6505
6605
  return {
6506
6606
  ...cfg,
@@ -6572,7 +6672,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6572
6672
  // hasParentBridge() — the type now reflects this.
6573
6673
  parentBridge: null,
6574
6674
  doneCondition: this.config.doneCondition,
6575
- maxConcurrent: this.config.maxConcurrent ?? 4
6675
+ maxConcurrent: this.config.maxConcurrent ?? 16
6576
6676
  };
6577
6677
  this.subagents.set(id, {
6578
6678
  config: { ...subagent, id },
@@ -6618,6 +6718,30 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6618
6718
  this.drainPendingAsAborted("Coordinator stopAll() drained the pending queue");
6619
6719
  await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));
6620
6720
  }
6721
+ async remove(subagentId) {
6722
+ await this.stop(subagentId);
6723
+ this.subagents.delete(subagentId);
6724
+ }
6725
+ /**
6726
+ * Get current coordinator stats for monitoring/debugging.
6727
+ */
6728
+ getStats() {
6729
+ let running = 0, idle = 0, stopped = 0;
6730
+ for (const [, entry] of this.subagents) {
6731
+ if (entry.status === "running") running++;
6732
+ else if (entry.status === "idle") idle++;
6733
+ else stopped++;
6734
+ }
6735
+ return {
6736
+ total: this.subagents.size,
6737
+ running,
6738
+ idle,
6739
+ stopped,
6740
+ inFlight: this.inFlight,
6741
+ pending: this.pendingTasks.length,
6742
+ completed: this.completedResults.length
6743
+ };
6744
+ }
6621
6745
  getStatus() {
6622
6746
  return {
6623
6747
  coordinatorId: this.coordinatorId,
@@ -6699,7 +6823,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6699
6823
  }
6700
6824
  }
6701
6825
  canDispatch() {
6702
- const max = this.config.maxConcurrent ?? 4;
6826
+ const max = this.config.maxConcurrent ?? 16;
6703
6827
  return this.inFlight < max && this.pendingTasks.length > 0;
6704
6828
  }
6705
6829
  takeNextDispatchableTask() {
@@ -6793,13 +6917,18 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6793
6917
  task.subagentId = subagentId;
6794
6918
  subagent.context.tasks.push(task);
6795
6919
  this.emit("task.assigned", { task, subagentId });
6920
+ const rawMaxIterations = subagent.config.maxIterations;
6921
+ const rawMaxToolCalls = subagent.config.maxToolCalls;
6922
+ const rawMaxTokens = subagent.config.maxTokens;
6923
+ const rawMaxCostUsd = subagent.config.maxCostUsd;
6924
+ const rawTimeoutMs = subagent.config.timeoutMs;
6796
6925
  const configWithRosterDefaults = applyRosterBudget(subagent.config);
6797
6926
  const budget = new SubagentBudget({
6798
- maxIterations: configWithRosterDefaults.maxIterations ?? this.config.defaultBudget?.maxIterations,
6799
- maxToolCalls: task.maxToolCalls ?? configWithRosterDefaults.maxToolCalls ?? this.config.defaultBudget?.maxToolCalls,
6800
- maxTokens: configWithRosterDefaults.maxTokens ?? this.config.defaultBudget?.maxTokens,
6801
- maxCostUsd: configWithRosterDefaults.maxCostUsd ?? this.config.defaultBudget?.maxCostUsd,
6802
- timeoutMs: task.timeoutMs ?? configWithRosterDefaults.timeoutMs ?? this.config.defaultBudget?.timeoutMs
6927
+ maxIterations: rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,
6928
+ maxToolCalls: rawMaxToolCalls ?? this.config.defaultBudget?.maxToolCalls ?? configWithRosterDefaults.maxToolCalls,
6929
+ maxTokens: rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,
6930
+ maxCostUsd: rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,
6931
+ timeoutMs: rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs
6803
6932
  });
6804
6933
  subagent.activeBudget = budget;
6805
6934
  if (!this.runner) {
@@ -6870,7 +6999,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6870
6999
  kind: "timeout",
6871
7000
  used: elapsed,
6872
7001
  limit,
6873
- timeoutMs: 3e4,
7002
+ timeoutMs: 6e4,
6874
7003
  extend: (extra) => resolveDecision({ extend: extra }),
6875
7004
  deny: () => resolveDecision("stop")
6876
7005
  });
@@ -7080,6 +7209,12 @@ var ParallelEternalEngine = class {
7080
7209
  get currentState() {
7081
7210
  return this.state;
7082
7211
  }
7212
+ /**
7213
+ * Get the underlying coordinator for stats/monitoring.
7214
+ */
7215
+ getCoordinator() {
7216
+ return this.coordinator;
7217
+ }
7083
7218
  stop() {
7084
7219
  this.stopRequested = true;
7085
7220
  void this.persistState("stopped").catch(() => {
@@ -7216,8 +7351,8 @@ Task: ${task}
7216
7351
  await coordinator.spawn({
7217
7352
  id: subagentId,
7218
7353
  name: `slot-${subagentId.slice(-6)}`,
7219
- maxIterations: 50,
7220
- maxToolCalls: 200,
7354
+ // Let the coordinator apply its default budget (from roster or generic).
7355
+ // Hardcoding low limits here defeats the x10 budget improvement.
7221
7356
  timeoutMs: this.timeoutMs
7222
7357
  });
7223
7358
  subagentIds.push(subagentId);
@@ -7234,7 +7369,7 @@ Task: ${task}
7234
7369
  let results = [];
7235
7370
  try {
7236
7371
  const ctrl = new AbortController();
7237
- const timer = setTimeout(() => ctrl.abort(), this.timeoutMs + 6e4);
7372
+ const timer = setTimeout(() => ctrl.abort(), Math.max(this.timeoutMs * 2, 72e5));
7238
7373
  try {
7239
7374
  results = await coordinator.awaitTasks(taskIds);
7240
7375
  } finally {
@@ -7612,10 +7747,8 @@ var InMemoryAgentBridge = class {
7612
7747
  this.pendingRequests.delete(correlationId);
7613
7748
  reject(new Error(`Request ${correlationId} timed out after ${timeout}ms`));
7614
7749
  }, timeout);
7615
- if (this.stopped) {
7750
+ if (!this.inflightGuards.has(correlationId)) {
7616
7751
  clearTimeout(timer);
7617
- this.inflightGuards.delete(correlationId);
7618
- this.pendingRequests.delete(correlationId);
7619
7752
  reject(new Error("Bridge stopped"));
7620
7753
  return;
7621
7754
  }
@@ -8446,7 +8579,12 @@ var Director = class {
8446
8579
  }
8447
8580
  }
8448
8581
  }
8449
- const result = await this.coordinator.spawn(config);
8582
+ let result;
8583
+ try {
8584
+ result = await this.coordinator.spawn(config);
8585
+ } catch (err) {
8586
+ throw err;
8587
+ }
8450
8588
  if (this.fleetManager) {
8451
8589
  this.fleetManager.recordSpawn(result.subagentId, config, priceLookup);
8452
8590
  } else {
@@ -8714,6 +8852,9 @@ var Director = class {
8714
8852
  async terminateAll() {
8715
8853
  await this.coordinator.stopAll();
8716
8854
  }
8855
+ async remove(subagentId) {
8856
+ await this.coordinator.remove(subagentId);
8857
+ }
8717
8858
  status() {
8718
8859
  return this.coordinator.getStatus();
8719
8860
  }
@@ -8894,7 +9035,7 @@ var Director = class {
8894
9035
  }
8895
9036
  };
8896
9037
  function createDelegateTool(opts) {
8897
- const defaultTimeoutMs = opts.defaultTimeoutMs ?? 4 * 60 * 60 * 1e3;
9038
+ const defaultTimeoutMs = opts.defaultTimeoutMs ?? 30 * 60 * 1e3;
8898
9039
  const rosterIds = opts.roster ? Object.keys(opts.roster) : [];
8899
9040
  const inputSchema = {
8900
9041
  type: "object",
@@ -8910,7 +9051,7 @@ function createDelegateTool(opts) {
8910
9051
  },
8911
9052
  name: {
8912
9053
  type: "string",
8913
- description: "Display name for the subagent when not using a roster role. Required when `role` is omitted."
9054
+ description: "Display name for free-form subagents (not using a roster role). The subagent gets a large default budget (3h, 5000 iter, 15000 tool calls). Required when `role` is omitted."
8914
9055
  },
8915
9056
  provider: {
8916
9057
  type: "string",
@@ -8941,8 +9082,8 @@ function createDelegateTool(opts) {
8941
9082
  };
8942
9083
  return {
8943
9084
  name: "delegate",
8944
- description: "Hand a discrete piece of work to a dedicated subagent and wait for its result. The subagent has its own context, its own LLM call, and its own budget \u2014 use this when a task is self-contained, would otherwise blow up your context, or benefits from a specialized role (bug-hunter, security-scanner, refactor-planner, audit-log). YOU decide how big the budget is: pass `timeoutMs`, `maxIterations`, and `maxToolCalls` sized to the actual work. There is no hidden cap forcing a 3-minute / 80-iteration limit \u2014 if a monorepo audit needs 2 hours and 500 tool calls, ask for that. Call multiple delegates in parallel through the provider's parallel-tool-call surface to fan work out across roles.",
8945
- usageHint: "Set `task` to a complete instruction. Either pick `role` from the roster or pass `name` + `provider` + `model`. For non-trivial work, also pass `timeoutMs` (the wall-clock budget you actually need), `maxIterations`, and `maxToolCalls` \u2014 defaults are intentionally generous (4 hours) but the right values depend on scope. Returns the subagent's `TaskResult` \u2014 including the textual `result`, iteration count, tool count, and duration. Auto-promotes the host into director mode on first call.",
9085
+ description: "Hand a discrete piece of work to a dedicated subagent and wait for its result. The subagent has its own context, its own LLM call, and its own budget \u2014 use this when a task is self-contained, would otherwise blow up your context, or benefits from a specialized role (bug-hunter, security-scanner, refactor-planner, audit-log). For free-form coding tasks (not tied to a pre-defined role), pass `name` + `task` \u2014 the subagent runs as a general-purpose coding agent with a large default budget. YOU decide how big the budget is: pass `timeoutMs`, `maxIterations`, and `maxToolCalls` sized to the actual work. There is no hidden cap forcing a 3-minute / 80-iteration limit \u2014 if a monorepo audit needs 2 hours and 500 tool calls, ask for that. Call multiple delegates in parallel through the provider's parallel-tool-call surface to fan work out across roles.",
9086
+ usageHint: "Set `task` to a complete instruction. Either pick `role` from the roster (audit-log, bug-hunter, refactor-planner, security-scanner) or pass `name` to run a free-form coding agent. For non-trivial work, also pass `timeoutMs`, `maxIterations`, and `maxToolCalls`. Returns the subagent's `TaskResult` \u2014 including the textual `result`, iteration count, tool count, and duration. Auto-promotes the host into director mode on first call.",
8946
9087
  permission: "auto",
8947
9088
  mutating: false,
8948
9089
  inputSchema,
@@ -8990,6 +9131,7 @@ function createDelegateTool(opts) {
8990
9131
  model: i.model,
8991
9132
  systemPromptOverride: i.systemPromptOverride
8992
9133
  };
9134
+ cfg = applyRosterBudget({ ...cfg, name: i.name });
8993
9135
  }
8994
9136
  if (typeof i.maxIterations === "number" && i.maxIterations > 0) {
8995
9137
  cfg.maxIterations = i.maxIterations;
@@ -8997,7 +9139,7 @@ function createDelegateTool(opts) {
8997
9139
  if (typeof i.maxToolCalls === "number" && i.maxToolCalls > 0) {
8998
9140
  cfg.maxToolCalls = i.maxToolCalls;
8999
9141
  }
9000
- const SUBAGENT_TIMEOUT_BUFFER_MS = opts.subagentTimeoutBufferMs ?? 3e4;
9142
+ const SUBAGENT_TIMEOUT_BUFFER_MS = opts.subagentTimeoutBufferMs ?? 6e4;
9001
9143
  const desiredSubTimeout = Math.max(3e4, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);
9002
9144
  if (!cfg.timeoutMs || cfg.timeoutMs > desiredSubTimeout) {
9003
9145
  cfg.timeoutMs = desiredSubTimeout;
@@ -9034,6 +9176,7 @@ function createDelegateTool(opts) {
9034
9176
  const errorKind = result.error?.kind;
9035
9177
  const retryable = result.error?.retryable;
9036
9178
  const backoffMs = result.error?.backoffMs;
9179
+ const summary = buildDelegateSummary(i.role, result);
9037
9180
  return {
9038
9181
  ok: result.status === "success",
9039
9182
  status: result.status,
@@ -9049,7 +9192,10 @@ function createDelegateTool(opts) {
9049
9192
  toolCalls: result.toolCalls,
9050
9193
  durationMs: result.durationMs,
9051
9194
  ...partial ? { partial } : {},
9052
- ...hintForKind(errorKind, retryable, backoffMs, partial) ? { hint: hintForKind(errorKind, retryable, backoffMs, partial) } : {}
9195
+ ...hintForKind(errorKind, retryable, backoffMs, partial) ? { hint: hintForKind(errorKind, retryable, backoffMs, partial) } : {},
9196
+ // Summary is included so callers (TUI, CLI renderer) can surface
9197
+ // it as a chat history line — the LLM also sees it for continuity.
9198
+ summary
9053
9199
  };
9054
9200
  } catch (err) {
9055
9201
  return {
@@ -9062,10 +9208,11 @@ function createDelegateTool(opts) {
9062
9208
  };
9063
9209
  }
9064
9210
  function instantiateRosterConfig2(role, base) {
9211
+ const withBudget = applyRosterBudget({ ...base, role });
9065
9212
  return {
9066
- ...base,
9067
- // Roster entries are templates. Give each spawn a fresh id so
9068
- // parallel or repeated delegates can use the same role safely.
9213
+ ...withBudget,
9214
+ // Give each spawn a fresh id so parallel or repeated delegates
9215
+ // can use the same role safely.
9069
9216
  id: `${role}-${randomUUID().slice(0, 8)}`
9070
9217
  };
9071
9218
  }
@@ -9125,6 +9272,18 @@ ${partial.lastAssistantText}`;
9125
9272
  return retryable ? "Failure classified as retryable. Try again with the same input." : void 0;
9126
9273
  }
9127
9274
  }
9275
+ function buildDelegateSummary(role, result) {
9276
+ const roleLabel = role ?? "subagent";
9277
+ const ms = result.durationMs;
9278
+ const duration = ms < 6e4 ? `${Math.round(ms / 1e3)}s` : ms < 36e5 ? `${Math.round(ms / 6e4)}m` : `${(ms / 36e5).toFixed(1)}h`;
9279
+ if (result.status === "success") {
9280
+ const preview = typeof result.result === "string" ? result.result.trim().slice(0, 120).replace(/\n+/g, " ") : null;
9281
+ const tail = preview ? ` \u2014 ${preview}` : "";
9282
+ return `[${roleLabel}] done in ${duration} (${result.iterations} iter, ${result.toolCalls} tools)${tail}`;
9283
+ }
9284
+ const errLabel = result.error?.kind ?? result.status;
9285
+ return `[${roleLabel}] ${result.status} after ${duration} (${result.iterations} iter, ${result.toolCalls} tools) \u2014 ${errLabel}`;
9286
+ }
9128
9287
  async function readSubagentPartial(opts, subagentId) {
9129
9288
  if (!opts.sessionsRoot) return void 0;
9130
9289
  const candidates = [];
@@ -9165,6 +9324,7 @@ async function readSubagentPartial(opts, subagentId) {
9165
9324
  }
9166
9325
  }
9167
9326
  } catch {
9327
+ continue;
9168
9328
  }
9169
9329
  }
9170
9330
  return {
@@ -13153,6 +13313,6 @@ var allServers = () => ({
13153
13313
  "minimax-vision": { ...miniMaxVisionServer(), enabled: false }
13154
13314
  });
13155
13315
 
13156
- export { AISpecBuilder, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, ConfigMigrationError, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPermissionPolicy, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, Director, DirectorStateCheckpoint, DoneConditionChecker, EternalAutonomyEngine, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FleetBus, FleetSpawnBudgetError, FleetUsageAggregator, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, LLMSelector, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, SelectiveCompactor, SessionAnalyzer, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, ToolExecutor, addPlanItem, allServers, analyzeCriticalPath, applyRosterBudget, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, clearPlan, composeDirectorPrompt, composeSubagentPrompt, context7Server, contextManagerTool, createAutoExecutor, createContextManagerTool, createDelegateTool, createMessage, decryptConfigSecrets2 as decryptConfigSecrets, deriveTodosFromPlanItem, emptyPlan, encryptConfigSecrets, everArtServer, filesystemServer, formatPlan, formatPlanTemplates, getPlanTemplate, getTemplate, githubServer, googleMapsServer, listPlanTemplates, listTemplates, loadDirectorState, loadPlan, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAutonomyPromptContributor, makeDirectorSessionFactory, migratePlaintextSecrets, miniMaxVisionServer, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, savePlan, saveTodosCheckpoint, sentinelServer, setPlanItemStatus, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, templateToMarkdown, wireMetricsToEvents, zaiVisionServer };
13316
+ export { AISpecBuilder, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, ConfigMigrationError, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPermissionPolicy, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, Director, DirectorStateCheckpoint, DoneConditionChecker, EternalAutonomyEngine, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FleetBus, FleetSpawnBudgetError, FleetUsageAggregator, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, LLMSelector, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, SelectiveCompactor, SessionAnalyzer, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, ToolExecutor, addPlanItem, allServers, analyzeCriticalPath, applyRosterBudget, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, clearPlan, composeDirectorPrompt, composeSubagentPrompt, context7Server, contextManagerTool, createAutoExecutor, createContextManagerTool, createDelegateTool, createMessage, decryptConfigSecrets2 as decryptConfigSecrets, deriveTodosFromPlanItem, emptyPlan, encryptConfigSecrets, everArtServer, filesystemServer, formatPlan, formatPlanTemplates, getPlanTemplate, getTemplate, githubServer, googleMapsServer, listPlanTemplates, listTemplates, loadDirectorState, loadPlan, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAutonomyPromptContributor, makeDirectorSessionFactory, migratePlaintextSecrets, miniMaxVisionServer, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, savePlan, saveTodosCheckpoint, sentinelServer, setPlanItemStatus, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, templateToMarkdown, wireMetricsToEvents, zaiVisionServer };
13157
13317
  //# sourceMappingURL=index.js.map
13158
13318
  //# sourceMappingURL=index.js.map