@wrongstack/core 0.280.1 → 0.281.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/{agent-subagent-runner-PoqNKiR4.d.ts → agent-subagent-runner-DyOSK2Wy.d.ts} +39 -8
  2. package/dist/{compactor-U3agvUIG.d.ts → compactor-BxddyCFu.d.ts} +1 -1
  3. package/dist/{config-Cr3312zc.d.ts → config-CN-vdDEI.d.ts} +82 -2
  4. package/dist/coordination/index.d.ts +203 -20
  5. package/dist/coordination/index.js +981 -52
  6. package/dist/coordination/index.js.map +1 -1
  7. package/dist/defaults/index.d.ts +26 -30
  8. package/dist/defaults/index.js +382 -30
  9. package/dist/defaults/index.js.map +1 -1
  10. package/dist/{events-Bs2fmldo.d.ts → events-C5hLU0AT.d.ts} +38 -2
  11. package/dist/execution/index.d.ts +16 -16
  12. package/dist/execution/index.js +161 -18
  13. package/dist/execution/index.js.map +1 -1
  14. package/dist/execution/prompt-enhancer.d.ts +1 -1
  15. package/dist/execution/prompt-enhancer.js +12 -3
  16. package/dist/execution/prompt-enhancer.js.map +1 -1
  17. package/dist/extension/index.d.ts +6 -6
  18. package/dist/{global-mailbox-Ct7IorLJ.d.ts → global-mailbox-CHM1QkCi.d.ts} +5 -2
  19. package/dist/{goal-store-C4F6DjC0.d.ts → goal-store-BLGZq16t.d.ts} +1 -1
  20. package/dist/hq/index.d.ts +6 -6
  21. package/dist/hq/index.js +35 -13
  22. package/dist/hq/index.js.map +1 -1
  23. package/dist/{index-nP09-oP2.d.ts → index-BEFWNZYs.d.ts} +1 -2
  24. package/dist/{index-kidebiDh.d.ts → index-C1E-_71T.d.ts} +6 -6
  25. package/dist/index.d.ts +44 -48
  26. package/dist/index.js +14855 -13944
  27. package/dist/index.js.map +1 -1
  28. package/dist/infrastructure/index.d.ts +60 -8
  29. package/dist/infrastructure/index.js.map +1 -1
  30. package/dist/kernel/index.d.ts +11 -11
  31. package/dist/kernel/index.js.map +1 -1
  32. package/dist/{mcp-servers-D910X5_r.d.ts → mcp-servers-EKRAcJDi.d.ts} +97 -4
  33. package/dist/models/index.d.ts +4 -5
  34. package/dist/models/index.js +22 -5
  35. package/dist/models/index.js.map +1 -1
  36. package/dist/{multi-agent-coordinator-CieyUoEL.d.ts → multi-agent-coordinator-IpHCuHUa.d.ts} +29 -1
  37. package/dist/{null-fleet-bus-DkdmZJ_W.d.ts → null-fleet-bus-ZBkKGR9j.d.ts} +105 -7
  38. package/dist/observability/index.d.ts +3 -3
  39. package/dist/{tool-executor-SiE1wlZo.d.ts → parallel-eternal-engine-Cc2CNgmv.d.ts} +6 -202
  40. package/dist/path-resolver-CMS5307d.d.ts +13 -0
  41. package/dist/{permission-Dx6dIqS2.d.ts → permission-B6YAtNFz.d.ts} +1 -1
  42. package/dist/{pipeline-BwAP21_4.d.ts → pipeline-E7_jqGyV.d.ts} +2 -2
  43. package/dist/{provider-model-resolve-CwQNZWt_.d.ts → provider-model-resolve-KgIdiEQ6.d.ts} +118 -5
  44. package/dist/{provider-runner-CYHFImzV.d.ts → provider-runner-DxWXNHL1.d.ts} +3 -3
  45. package/dist/{retry-policy-D4feSLk3.d.ts → retry-policy-V67lBOJz.d.ts} +2 -2
  46. package/dist/sdd/index.d.ts +9 -9
  47. package/dist/sdd/index.js +94 -10
  48. package/dist/sdd/index.js.map +1 -1
  49. package/dist/{permission-policy-C8vJcnX5.d.ts → secret-vault-D7jeyXUQ.d.ts} +119 -3
  50. package/dist/security/index.d.ts +5 -6
  51. package/dist/security/index.js +4 -1
  52. package/dist/security/index.js.map +1 -1
  53. package/dist/{selector-Dy-MzKp1.d.ts → selector-Bx2HgUkU.d.ts} +1 -1
  54. package/dist/{session-event-bridge-CqdiGnfU.d.ts → session-event-bridge-vA2fLV58.d.ts} +1 -1
  55. package/dist/{session-reader-Hk0WbNm9.d.ts → session-reader-B-Fi9L6I.d.ts} +1 -1
  56. package/dist/session-registry-Dvg7i_IA.d.ts +129 -0
  57. package/dist/storage/index.d.ts +71 -142
  58. package/dist/storage/index.js +161 -13
  59. package/dist/storage/index.js.map +1 -1
  60. package/dist/{todos-checkpoint-Bk2uP7Ex.d.ts → todos-checkpoint-B1QVkoa8.d.ts} +23 -5
  61. package/dist/{tool-BkOgs_KL.d.ts → tool-LVSLiE1s.d.ts} +18 -4
  62. package/dist/{strategy-compactor-CQwhbErd.d.ts → tool-executor-BWtYwuPI.d.ts} +210 -12
  63. package/dist/tools/index.d.ts +2 -2
  64. package/dist/tools/index.js.map +1 -1
  65. package/dist/types/index.d.ts +17 -41
  66. package/dist/types/index.js +182 -5085
  67. package/dist/types/index.js.map +1 -1
  68. package/dist/utils/index.d.ts +3 -3
  69. package/dist/utils/index.js +6 -1
  70. package/dist/utils/index.js.map +1 -1
  71. package/dist/{worktree-manager-BjOFF6bt.d.ts → worktree-manager-C6CIilTT.d.ts} +1 -1
  72. package/dist/{wstack-paths-CMl_cYgq.d.ts → wstack-paths-C3K40Qst.d.ts} +2 -0
  73. package/instructions/agents/shadow-agent.md +23 -84
  74. package/instructions/coordination/director-preamble.md +12 -3
  75. package/instructions/coordination/subagent-baseline.md +39 -46
  76. package/instructions/leader-after-task.md +10 -28
  77. package/instructions/llm/llm-selector.md +1 -2
  78. package/instructions/modes/brief-system.md +7 -33
  79. package/instructions/modes/brief.md +5 -20
  80. package/instructions/modes/teach-system.md +12 -72
  81. package/instructions/modes/teach.md +12 -49
  82. package/instructions/sections/tool/commit-hygiene.md +5 -5
  83. package/instructions/sections/tool/context-management-full.md +6 -6
  84. package/instructions/sections/tool/delegation-compact.md +1 -1
  85. package/instructions/sections/tool/delegation-full.md +19 -23
  86. package/instructions/sections/tool/mailbox-full.md +11 -31
  87. package/instructions/sections/tool/mcp-full-control.md +5 -7
  88. package/instructions/sections/tool/mcp-full-use.md +7 -7
  89. package/instructions/system.md +22 -38
  90. package/package.json +1 -29
  91. package/dist/agent-bridge-DXC6QDJ4.d.ts +0 -35
  92. package/dist/logger-D3lV0cUZ.d.ts +0 -101
  93. package/dist/models-registry-CLkoOcHk.d.ts +0 -108
  94. package/dist/path-resolver-XfZ9eLxG.d.ts +0 -67
  95. package/dist/secret-vault-CImt2XrR.d.ts +0 -118
@@ -1,5 +1,5 @@
1
- import { U as Usage, C as Context, l as ToolErrorCategory, m as ToolProgressEvent, T as Tool, n as RiskTier, o as ToolOutputMetadata } from './tool-BkOgs_KL.js';
2
- import { a as PermissionDecision } from './permission-Dx6dIqS2.js';
1
+ import { U as Usage, d as Context, l as ToolErrorCategory, m as ToolProgressEvent, g as Tool, n as RiskTier, o as ToolOutputMetadata } from './tool-LVSLiE1s.js';
2
+ import { a as PermissionDecision } from './permission-B6YAtNFz.js';
3
3
 
4
4
  /**
5
5
  * Brain coordination primitives.
@@ -992,6 +992,42 @@ interface EventMap {
992
992
  tokens: number;
993
993
  maxContext: number;
994
994
  };
995
+ /**
996
+ * A supervision rule detected a condition worth engaging on (starvation,
997
+ * overload, backlog, stuck agent, failure streak). Fires even when the
998
+ * subsequent decision is "do nothing" — the signal trail is the audit log.
999
+ */
1000
+ 'fleet.supervisor.signal': {
1001
+ sessionId?: string | undefined;
1002
+ /** Rule kind, e.g. 'pinned_starvation' | 'overloaded_worker' | 'backlog' | 'stuck_agent' | 'failure_streak' | 'idle_with_work'. */
1003
+ kind: string;
1004
+ subagentId?: string | undefined;
1005
+ taskId?: string | undefined;
1006
+ detail: string;
1007
+ };
1008
+ /**
1009
+ * The supervisor consulted its decision path for a signal. `via:'rule'`
1010
+ * means the deterministic policy answered without an LLM; `via:'brain'`
1011
+ * means the tiered BrainArbiter was engaged. `outcome:'escalated'` =
1012
+ * unresolved ask_human, no action taken.
1013
+ */
1014
+ 'fleet.supervisor.decision': {
1015
+ sessionId?: string | undefined;
1016
+ kind: string;
1017
+ proposedAction: string;
1018
+ via: 'rule' | 'brain';
1019
+ outcome: 'approved' | 'denied' | 'escalated' | 'skipped';
1020
+ rationale?: string | undefined;
1021
+ };
1022
+ /** The supervisor executed (or failed to execute) an approved action. */
1023
+ 'fleet.supervisor.action': {
1024
+ sessionId?: string | undefined;
1025
+ action: 'retarget' | 'spawn_helper' | 'steer' | 'notify_leader' | 'terminate';
1026
+ subagentId?: string | undefined;
1027
+ taskId?: string | undefined;
1028
+ ok: boolean;
1029
+ detail?: string | undefined;
1030
+ };
995
1031
  /** A parallel SDD run started. */
996
1032
  'sdd.run.started': {
997
1033
  sessionId?: string | undefined;
@@ -1,25 +1,25 @@
1
- export { A as AutoCompactionMiddleware, a as AutonomousRunner, b as AutonomousRunnerOptions, c as AutonomyPromptContributorOptions, C as CompactorStrategy, U as ContextWindowBudgetSnapshot, D as DefaultDesignKitLoader, d as DefaultPromptLoader, e as DefaultSkillLoader, f as DesignKitLoaderOptions, h as DoneCheckResult, i as DoneConditionChecker, I as IntelligentCompactor, j as IntelligentCompactorOptions, P as PersistedActiveKit, k as PromptLoaderOptions, S as SelectiveCompactor, l as SelectiveCompactorOptions, m as SkillLoaderOptions, n as StrategyCompactorOptions, _ as _resetDesignKitLoaderMemo, o as _resetDesignRulesCache, p as activateDesign, r as buildGoalPreamble, s as clearActiveKit, t as clearPersistedActiveKit, u as createStrategyCompactor, v as designProjectDir, w as detectFrontendFile, x as detectFrontendIntent, y as getDesignKitLoader, z as getDesignState, B as installDesignStudioMiddleware, E as loadActiveKit, F as loadProjectDesignRules, G as makeAutonomyPromptContributor, H as makeDesignDetectToolCallMiddleware, J as makeDesignDetectUserInputMiddleware, K as makeDesignStudioRequestMiddleware, M as recordKitChoice, O as renderPrompt, Q as resolveBundledDesignKitsDir, R as setActiveKit } from '../strategy-compactor-CQwhbErd.js';
2
- import { P as Provider, a as ReasoningConfig, r as Capabilities, c as Request } from '../tool-BkOgs_KL.js';
3
- import { e as BrainDecision, h as BrainDecisionRequest, B as BrainArbiter } from '../events-Bs2fmldo.js';
4
- export { C as CompactorOptions, h as DefaultErrorHandler, i as DefaultRetryPolicy, E as EternalAutonomyEngine, k as EternalAutonomyOptions, l as EternalEngineState, H as HybridCompactor, I as IterationStage, P as ParallelEngineState, m as ParallelEternalEngine, n as ParallelEternalOptions, o as ParallelIterationStage, T as ToolExecutor } from '../tool-executor-SiE1wlZo.js';
5
- import { h as ModelRuntimeConfig } from '../config-Cr3312zc.js';
6
- import '../pipeline-BwAP21_4.js';
1
+ export { A as AutoCompactionMiddleware, a as AutonomousRunner, b as AutonomousRunnerOptions, c as AutonomyPromptContributorOptions, C as CompactorOptions, d as CompactorStrategy, Z as ContextWindowBudgetSnapshot, $ as DEFAULT_RECOVERY_STRATEGIES, D as DefaultDesignKitLoader, e as DefaultErrorHandler, f as DefaultPromptLoader, g as DefaultRetryPolicy, h as DefaultSkillLoader, i as DesignKitLoaderOptions, k as DoneCheckResult, l as DoneConditionChecker, H as HybridCompactor, I as IntelligentCompactor, m as IntelligentCompactorOptions, P as PersistedActiveKit, n as PromptLoaderOptions, a0 as RecoveryStrategy, S as SelectiveCompactor, o as SelectiveCompactorOptions, p as SkillLoaderOptions, q as StrategyCompactorOptions, T as ToolExecutor, _ as _resetDesignKitLoaderMemo, r as _resetDesignRulesCache, s as activateDesign, u as buildGoalPreamble, a1 as buildRecoveryStrategies, v as clearActiveKit, w as clearPersistedActiveKit, x as createStrategyCompactor, y as designProjectDir, z as detectFrontendFile, B as detectFrontendIntent, E as getDesignKitLoader, F as getDesignState, G as installDesignStudioMiddleware, J as loadActiveKit, K as loadProjectDesignRules, L as makeAutonomyPromptContributor, M as makeDesignDetectToolCallMiddleware, N as makeDesignDetectUserInputMiddleware, O as makeDesignStudioRequestMiddleware, R as recordKitChoice, V as renderPrompt, W as resolveBundledDesignKitsDir, X as setActiveKit } from '../tool-executor-BWtYwuPI.js';
2
+ import { P as Provider, a as ReasoningConfig, r as Capabilities, c as Request } from '../tool-LVSLiE1s.js';
3
+ import { e as BrainDecision, h as BrainDecisionRequest, B as BrainArbiter } from '../events-C5hLU0AT.js';
4
+ export { E as EternalAutonomyEngine, h as EternalAutonomyOptions, i as EternalEngineState, I as IterationStage, P as ParallelEngineState, j as ParallelEternalEngine, k as ParallelEternalOptions, l as ParallelIterationStage } from '../parallel-eternal-engine-Cc2CNgmv.js';
5
+ import { h as ModelRuntimeConfig } from '../config-CN-vdDEI.js';
6
+ import '../pipeline-E7_jqGyV.js';
7
7
  import '../mailbox-types-BGZWrYTJ.js';
8
- import '../session-event-bridge-CqdiGnfU.js';
9
- import '../compactor-U3agvUIG.js';
10
- import '../agent-subagent-runner-PoqNKiR4.js';
11
- import '../index-kidebiDh.js';
8
+ import '../session-event-bridge-vA2fLV58.js';
9
+ import '../compactor-BxddyCFu.js';
10
+ import '../agent-subagent-runner-DyOSK2Wy.js';
11
+ import '../index-C1E-_71T.js';
12
12
  import '../logger-B63L5bTg.js';
13
- import '../permission-Dx6dIqS2.js';
13
+ import '../permission-B6YAtNFz.js';
14
14
  import '../observability-D-HZN_mF.js';
15
15
  import '../secret-scrubber-3MHDDAtm.js';
16
- import '../retry-policy-D4feSLk3.js';
17
- import '../selector-Dy-MzKp1.js';
16
+ import '../retry-policy-V67lBOJz.js';
17
+ import '../selector-Bx2HgUkU.js';
18
18
  import '../skill-DHniprNl.js';
19
- import '../wstack-paths-CMl_cYgq.js';
19
+ import '../wstack-paths-C3K40Qst.js';
20
20
  import '../prompt-DLd35n4Q.js';
21
- import '../goal-store-C4F6DjC0.js';
22
- import '../multi-agent-coordinator-CieyUoEL.js';
21
+ import '../goal-store-BLGZq16t.js';
22
+ import '../multi-agent-coordinator-IpHCuHUa.js';
23
23
  import 'node:events';
24
24
 
25
25
  /**
@@ -1,4 +1,4 @@
1
- import { randomUUID, createHash, randomBytes } from 'crypto';
1
+ import { randomUUID, randomInt, createHash, randomBytes } from 'crypto';
2
2
  import * as fs from 'fs/promises';
3
3
  import * as path3 from 'path';
4
4
  import * as os from 'os';
@@ -193,7 +193,7 @@ function walk(value, schema, path12, errors, depth) {
193
193
  return;
194
194
  }
195
195
  if (schema.enum !== void 0) {
196
- if (!schema.enum.some((e) => deepEqual(e, value))) {
196
+ if (!enumIncludes(schema.enum, value)) {
197
197
  errors.push({
198
198
  path: path12 || "<root>",
199
199
  message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`
@@ -263,6 +263,10 @@ function joinPath(parent, key) {
263
263
  if (!parent) return key;
264
264
  return `${parent}.${key}`;
265
265
  }
266
+ function enumIncludes(values, value) {
267
+ if (value === null || typeof value !== "object") return values.includes(value);
268
+ return values.some((candidate) => deepEqual(candidate, value));
269
+ }
266
270
  function deepEqual(a, b) {
267
271
  if (a === b) return true;
268
272
  if (typeof a !== typeof b) return false;
@@ -1457,6 +1461,7 @@ function resolveWstackPaths(opts) {
1457
1461
  projectHash: hash,
1458
1462
  projectSlug: slug,
1459
1463
  projectGoal: path3.join(projectDir, "goal.json"),
1464
+ projectInputHistory: path3.join(projectDir, "input-history.json"),
1460
1465
  projectSpecs: path3.join(projectDir, "specs"),
1461
1466
  projectTaskGraphs: path3.join(projectDir, "task-graphs"),
1462
1467
  projectSddSession: path3.join(projectDir, "sdd-session.json"),
@@ -2137,14 +2142,21 @@ var AutonomousRunner = class {
2137
2142
  this.stopped = true;
2138
2143
  }
2139
2144
  };
2145
+ var textCache = /* @__PURE__ */ new Map();
2146
+ var rootCandidates;
2140
2147
  function readBundledInstructionText(relativePath) {
2148
+ const cached = textCache.get(relativePath);
2149
+ if (cached !== void 0) return cached;
2150
+ let resolved = "";
2141
2151
  for (const root of instructionRootCandidates()) {
2142
2152
  try {
2143
- return readFileSync(path3.join(root, relativePath), "utf8").trimEnd();
2153
+ resolved = readFileSync(path3.join(root, relativePath), "utf8").trimEnd();
2154
+ break;
2144
2155
  } catch {
2145
2156
  }
2146
2157
  }
2147
- return "";
2158
+ textCache.set(relativePath, resolved);
2159
+ return resolved;
2148
2160
  }
2149
2161
  function renderInstructionTemplate(template, values) {
2150
2162
  return template.replace(
@@ -2153,13 +2165,15 @@ function renderInstructionTemplate(template, values) {
2153
2165
  );
2154
2166
  }
2155
2167
  function instructionRootCandidates() {
2168
+ if (rootCandidates !== void 0) return rootCandidates;
2156
2169
  const here = path3.dirname(fileURLToPath(import.meta.url));
2157
2170
  const candidates = [
2158
2171
  path3.resolve(here, "../../instructions"),
2159
2172
  path3.resolve(here, "../instructions"),
2160
2173
  path3.resolve(here, "instructions")
2161
2174
  ];
2162
- return candidates.sort((a, b) => Number(!isDirectory(a)) - Number(!isDirectory(b)));
2175
+ rootCandidates = candidates.sort((a, b) => Number(!isDirectory(a)) - Number(!isDirectory(b)));
2176
+ return rootCandidates;
2163
2177
  }
2164
2178
  function isDirectory(candidate) {
2165
2179
  try {
@@ -3915,7 +3929,38 @@ function buildRecoveryStrategies(opts) {
3915
3929
  async attempt(err, ctx) {
3916
3930
  if (!(err instanceof ProviderError)) return null;
3917
3931
  if (err.status !== 529 && err.status < 500) return null;
3918
- return null;
3932
+ const registry = opts?.modelsRegistry;
3933
+ if (!registry) return null;
3934
+ try {
3935
+ const providerId = ctx.provider?.id;
3936
+ if (!providerId) return null;
3937
+ const provider = await registry.getProvider(providerId);
3938
+ if (!provider) return null;
3939
+ const currentModel = await registry.getModel(providerId, ctx.model);
3940
+ if (!currentModel) return null;
3941
+ const visibleModels = opts?.getConfig?.().providers?.[providerId]?.models;
3942
+ const candidates = provider.models.filter((m) => {
3943
+ if (visibleModels !== void 0 && !visibleModels.includes(m.id)) return false;
3944
+ const modelCost = m.cost?.input ?? Number.POSITIVE_INFINITY;
3945
+ const currentCost = currentModel.cost?.input ?? Number.POSITIVE_INFINITY;
3946
+ if (modelCost >= currentCost) return false;
3947
+ if (currentModel.capabilities.tools && !m.tool_call) return false;
3948
+ if (currentModel.capabilities.vision && !m.modalities?.input?.includes("image"))
3949
+ return false;
3950
+ return true;
3951
+ });
3952
+ if (candidates.length === 0) return null;
3953
+ const fallback = candidates.reduce(
3954
+ (prev, curr) => (curr.cost?.input ?? Number.POSITIVE_INFINITY) < (prev.cost?.input ?? Number.POSITIVE_INFINITY) ? curr : prev
3955
+ );
3956
+ return {
3957
+ action: "retry",
3958
+ reason: "model_downgrade",
3959
+ model: fallback.id
3960
+ };
3961
+ } catch {
3962
+ return null;
3963
+ }
3919
3964
  }
3920
3965
  }
3921
3966
  ];
@@ -5625,20 +5670,32 @@ var TOOLS = {
5625
5670
  /** Web research. */
5626
5671
  research: ["read", "grep", "glob", "search", "fetch", "mailbox"]
5627
5672
  };
5673
+ var promptCache = /* @__PURE__ */ new Map();
5674
+ var candidateCache = /* @__PURE__ */ new Map();
5628
5675
  function agentPrompt(id) {
5676
+ const envDir = process.env["WRONGSTACK_AGENT_INSTRUCTIONS_DIR"] ?? "";
5677
+ const cacheKey = `${envDir}\0${id}`;
5678
+ const cached = promptCache.get(cacheKey);
5679
+ if (cached !== void 0) return cached;
5629
5680
  const fileName = `${id}.md`;
5630
- for (const dir of agentPromptDirCandidates()) {
5681
+ let resolved = "";
5682
+ for (const dir of agentPromptDirCandidates(envDir)) {
5631
5683
  try {
5632
- return readFileSync(path3.join(dir, fileName), "utf8").trimEnd();
5684
+ resolved = readFileSync(path3.join(dir, fileName), "utf8").trimEnd();
5685
+ break;
5633
5686
  } catch {
5634
5687
  }
5635
5688
  }
5636
- return "";
5689
+ promptCache.set(cacheKey, resolved);
5690
+ return resolved;
5637
5691
  }
5638
- function agentPromptDirCandidates() {
5639
- const here = path3.dirname(fileURLToPath(import.meta.url));
5640
- const explicitDir = process.env["WRONGSTACK_AGENT_INSTRUCTIONS_DIR"];
5692
+ function agentPromptDirCandidates(envDir) {
5641
5693
  const globalRoot = process.env["WRONGSTACK_HOME"] || path3.join(os.homedir(), ".wrongstack");
5694
+ const candKey = `${envDir}\0${globalRoot}`;
5695
+ const cached = candidateCache.get(candKey);
5696
+ if (cached !== void 0) return cached;
5697
+ const here = path3.dirname(fileURLToPath(import.meta.url));
5698
+ const explicitDir = envDir || void 0;
5642
5699
  const candidates = [
5643
5700
  ...explicitDir ? [path3.resolve(explicitDir)] : [],
5644
5701
  path3.join(globalRoot, "instructions", "agents"),
@@ -5648,7 +5705,9 @@ function agentPromptDirCandidates() {
5648
5705
  path3.resolve(here, "../instructions/agents"),
5649
5706
  path3.resolve(here, "instructions/agents")
5650
5707
  ];
5651
- return candidates.sort((a, b) => Number(!isDirectory2(a)) - Number(!isDirectory2(b)));
5708
+ const ordered = candidates.sort((a, b) => Number(!isDirectory2(a)) - Number(!isDirectory2(b)));
5709
+ candidateCache.set(candKey, ordered);
5710
+ return ordered;
5652
5711
  }
5653
5712
  function isDirectory2(candidate) {
5654
5713
  try {
@@ -7710,6 +7769,30 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
7710
7769
  results() {
7711
7770
  return this.completedResults;
7712
7771
  }
7772
+ /** Defensive snapshot of the still-queued (not yet dispatched) tasks. */
7773
+ listPendingTasks() {
7774
+ return this.pendingTasks.map((t) => ({ ...t }));
7775
+ }
7776
+ /**
7777
+ * Re-pin a still-PENDING task to a different subagent (`undefined` =
7778
+ * unpin, any idle worker may take it), then try to dispatch. Returns
7779
+ * `false` when the task is not in the pending queue — already
7780
+ * dispatched, completed, or unknown. Running tasks can never be pulled;
7781
+ * they can only be steered or terminated. The mutation is synchronous
7782
+ * (same tick as the check), so it cannot race a concurrent dispatch:
7783
+ * `tryDispatchNext` runs on this same call stack or a later one.
7784
+ *
7785
+ * The task keeps its id, so waiters, the report-back notifier, and
7786
+ * checkpoint bookkeeping resolve unchanged when it eventually completes.
7787
+ */
7788
+ retargetPendingTask(taskId, subagentId) {
7789
+ const task = this.pendingTasks.find((t) => t.id === taskId);
7790
+ if (!task) return false;
7791
+ if (subagentId !== void 0 && !this.subagents.has(subagentId)) return false;
7792
+ task.subagentId = subagentId;
7793
+ this.tryDispatchNext();
7794
+ return true;
7795
+ }
7713
7796
  /**
7714
7797
  * Wait for one or more tasks to complete and return their results.
7715
7798
  * If a task is already done when called, returns immediately.
@@ -7737,6 +7820,43 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
7737
7820
  })
7738
7821
  );
7739
7822
  }
7823
+ /**
7824
+ * Wait until AT LEAST ONE of the named tasks completes. Returns every
7825
+ * requested result already available at that moment (drain-what's-done)
7826
+ * plus the ids still outstanding, so callers can loop "handle finishers,
7827
+ * re-await the remainder" instead of blocking on the whole batch.
7828
+ *
7829
+ * Unlike `awaitTasks`, this never rejects and deliberately does NOT
7830
+ * inherit `config.timeoutMs` — a "return whatever is done" call has no
7831
+ * business timing out unless the caller asks for a window explicitly.
7832
+ */
7833
+ async awaitTasksAny(taskIds, opts) {
7834
+ const ids = new Set(taskIds);
7835
+ const completed = this.completedResults.filter((r) => ids.has(r.taskId));
7836
+ if (completed.length > 0 || ids.size === 0) {
7837
+ const done = new Set(completed.map((r) => r.taskId));
7838
+ return { completed, pending: taskIds.filter((id) => !done.has(id)) };
7839
+ }
7840
+ return new Promise((resolve5) => {
7841
+ let timer;
7842
+ const handler = ({ result }) => {
7843
+ if (!ids.has(result.taskId)) return;
7844
+ if (timer) clearTimeout(timer);
7845
+ this.off("task.completed", handler);
7846
+ resolve5({
7847
+ completed: [result],
7848
+ pending: taskIds.filter((id) => id !== result.taskId)
7849
+ });
7850
+ };
7851
+ if (opts?.timeoutMs !== void 0) {
7852
+ timer = setTimeout(() => {
7853
+ this.off("task.completed", handler);
7854
+ resolve5({ completed: [], pending: [...taskIds], timedOut: true });
7855
+ }, opts.timeoutMs);
7856
+ }
7857
+ this.on("task.completed", handler);
7858
+ });
7859
+ }
7740
7860
  /**
7741
7861
  * Manual completion — for callers that drive subagents without a runner
7742
7862
  * (e.g. external orchestrators). When a runner is configured the coordinator
@@ -8679,8 +8799,7 @@ ${lastFew}` : "No prior iterations.",
8679
8799
  await saveGoal(this.goalPath, { ...current, engineState: state }, this.opts.events);
8680
8800
  }
8681
8801
  };
8682
-
8683
- // src/execution/retry-policy.ts
8802
+ var MAX_RETRY_AFTER_MS = 6e4;
8684
8803
  var DefaultRetryPolicy = class {
8685
8804
  shouldRetry(err, attempt) {
8686
8805
  if (err instanceof ProviderError) {
@@ -8702,13 +8821,37 @@ var DefaultRetryPolicy = class {
8702
8821
  }
8703
8822
  return 2;
8704
8823
  }
8705
- delayMs(attempt) {
8824
+ /**
8825
+ * Compute the retry delay.
8826
+ *
8827
+ * Precedence:
8828
+ * 1. If `err` is a `ProviderError` with a populated
8829
+ * `body.retryAfterMs`, honour it — clamped into
8830
+ * [0, MAX_RETRY_AFTER_MS]. The provider told us exactly when
8831
+ * to come back; we should listen.
8832
+ * 2. Otherwise fall through to the exponential-with-jitter
8833
+ * schedule (`1000 * 2^attempt + jitter`, capped at 30s).
8834
+ *
8835
+ * `err` is optional for back-compat with the existing interface;
8836
+ * callers should pass it whenever available.
8837
+ */
8838
+ delayMs(attempt, err) {
8839
+ const hint = retryAfterMsFromError(err);
8840
+ if (hint !== void 0) {
8841
+ return Math.max(0, Math.min(hint, MAX_RETRY_AFTER_MS));
8842
+ }
8706
8843
  const base = 1e3;
8707
8844
  const exp = base * 2 ** attempt;
8708
- const jitter = Math.random() * base;
8845
+ const jitter = randomInt(0, base);
8709
8846
  return Math.min(3e4, exp + jitter);
8710
8847
  }
8711
8848
  };
8849
+ function retryAfterMsFromError(err) {
8850
+ if (!err || !(err instanceof ProviderError)) return void 0;
8851
+ const ms = err.body?.retryAfterMs;
8852
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms <= 0) return void 0;
8853
+ return ms;
8854
+ }
8712
8855
 
8713
8856
  // src/models/llm-selector.ts
8714
8857
  var DEFAULT_SYSTEM_PROMPT = readBundledInstructionText("llm/llm-selector.md");
@@ -10621,6 +10764,6 @@ async function maybePersistLargeToolOutput(toolName, content, budget) {
10621
10764
  }
10622
10765
  }
10623
10766
 
10624
- export { AutoCompactionMiddleware, AutonomousRunner, DefaultDesignKitLoader, DefaultErrorHandler, DefaultPromptLoader, DefaultRetryPolicy, DefaultSkillLoader, DoneConditionChecker, EternalAutonomyEngine, HybridCompactor, IntelligentCompactor, ParallelEternalEngine, SelectiveCompactor, ToolExecutor, _resetDesignKitLoaderMemo, _resetDesignRulesCache, activateDesign, applyModelRuntime, buildGoalPreamble, clearActiveKit, clearPersistedActiveKit, createAutonomyBrain, createStrategyCompactor, createTieredBrainArbiter, designProjectDir, detectFrontendFile, detectFrontendIntent, formatDecisionSummary, getDesignKitLoader, getDesignState, installDesignStudioMiddleware, loadActiveKit, loadProjectDesignRules, makeAutonomyPromptContributor, makeDesignDetectToolCallMiddleware, makeDesignDetectUserInputMiddleware, makeDesignStudioRequestMiddleware, mergeModelRuntime, recordKitChoice, renderPrompt, resolveBundledDesignKitsDir, resolveCacheForRequest, resolveModelRuntime, resolveReasoningForRequest, setActiveKit };
10767
+ export { AutoCompactionMiddleware, AutonomousRunner, DEFAULT_RECOVERY_STRATEGIES, DefaultDesignKitLoader, DefaultErrorHandler, DefaultPromptLoader, DefaultRetryPolicy, DefaultSkillLoader, DoneConditionChecker, EternalAutonomyEngine, HybridCompactor, IntelligentCompactor, ParallelEternalEngine, SelectiveCompactor, ToolExecutor, _resetDesignKitLoaderMemo, _resetDesignRulesCache, activateDesign, applyModelRuntime, buildGoalPreamble, buildRecoveryStrategies, clearActiveKit, clearPersistedActiveKit, createAutonomyBrain, createStrategyCompactor, createTieredBrainArbiter, designProjectDir, detectFrontendFile, detectFrontendIntent, formatDecisionSummary, getDesignKitLoader, getDesignState, installDesignStudioMiddleware, loadActiveKit, loadProjectDesignRules, makeAutonomyPromptContributor, makeDesignDetectToolCallMiddleware, makeDesignDetectUserInputMiddleware, makeDesignStudioRequestMiddleware, mergeModelRuntime, recordKitChoice, renderPrompt, resolveBundledDesignKitsDir, resolveCacheForRequest, resolveModelRuntime, resolveReasoningForRequest, setActiveKit };
10625
10768
  //# sourceMappingURL=index.js.map
10626
10769
  //# sourceMappingURL=index.js.map