@wrongstack/core 0.6.3 → 0.6.5

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 (63) hide show
  1. package/dist/{agent-bridge-eb7qnNrd.d.ts → agent-bridge-BBXK_ppx.d.ts} +1 -1
  2. package/dist/agent-subagent-runner-DsSm9lKN.d.ts +174 -0
  3. package/dist/{compactor-RIPuTtWK.d.ts → compactor-C8NhpSt5.d.ts} +1 -1
  4. package/dist/{config-BGGuP_Ar.d.ts → config-DfC6g6KV.d.ts} +1 -1
  5. package/dist/{context-CDRyrkKQ.d.ts → context-DN5v-uQX.d.ts} +11 -0
  6. package/dist/coordination/index.d.ts +10 -9
  7. package/dist/coordination/index.js +113 -20
  8. package/dist/coordination/index.js.map +1 -1
  9. package/dist/defaults/index.d.ts +21 -20
  10. package/dist/defaults/index.js +1329 -925
  11. package/dist/defaults/index.js.map +1 -1
  12. package/dist/{events-BHuIHekD.d.ts → events-CJqwQl8G.d.ts} +17 -1
  13. package/dist/execution/index.d.ts +82 -13
  14. package/dist/execution/index.js +1366 -74
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -6
  17. package/dist/{goal-store-DVCfj7Ff.d.ts → goal-store-_Er467ya.d.ts} +2 -2
  18. package/dist/{index-CPcDqvZh.d.ts → index-CXnWsGBp.d.ts} +11 -175
  19. package/dist/{index-BOn9NK7D.d.ts → index-DcnXDPdY.d.ts} +6 -6
  20. package/dist/index.d.ts +28 -27
  21. package/dist/index.js +1068 -664
  22. package/dist/index.js.map +1 -1
  23. package/dist/infrastructure/index.d.ts +6 -6
  24. package/dist/kernel/index.d.ts +9 -9
  25. package/dist/kernel/index.js.map +1 -1
  26. package/dist/{mcp-servers-DBdh3cee.d.ts → mcp-servers-CevFHHM1.d.ts} +3 -3
  27. package/dist/models/index.d.ts +2 -2
  28. package/dist/models/index.js +5 -16
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{multi-agent-CxSb-9dQ.d.ts → multi-agent-D5IbASk_.d.ts} +16 -4
  31. package/dist/observability/index.d.ts +2 -2
  32. package/dist/{path-resolver-CMGNadvq.d.ts → path-resolver-CBx_q1HA.d.ts} +2 -2
  33. package/dist/{plan-templates-BJflQY2i.d.ts → plan-templates-BEOllUJV.d.ts} +5 -4
  34. package/dist/{provider-runner-BFgNXpaP.d.ts → provider-runner-Byh5TcJs.d.ts} +3 -3
  35. package/dist/{retry-policy-LKS8MHsB.d.ts → retry-policy-BZSIMxrJ.d.ts} +1 -1
  36. package/dist/sdd/index.d.ts +3 -3
  37. package/dist/{secret-scrubber-CfMdAJ_l.d.ts → secret-scrubber-CT7wefiO.d.ts} +1 -1
  38. package/dist/{secret-scrubber-BzQR5BiL.d.ts → secret-scrubber-I0QHY_ob.d.ts} +1 -1
  39. package/dist/security/index.d.ts +3 -3
  40. package/dist/{selector-C7HqnZJU.d.ts → selector-DDb_mq9X.d.ts} +1 -1
  41. package/dist/{session-reader-CzfRA6Vk.d.ts → session-reader-B9nVkziM.d.ts} +1 -1
  42. package/dist/storage/index.d.ts +6 -6
  43. package/dist/storage/index.js +27 -2
  44. package/dist/storage/index.js.map +1 -1
  45. package/dist/{system-prompt-Dl2QY1_B.d.ts → system-prompt-gL06H9P4.d.ts} +1 -1
  46. package/dist/{tool-executor-FoxBjULX.d.ts → tool-executor-BF7QfYVE.d.ts} +4 -4
  47. package/dist/types/index.d.ts +15 -15
  48. package/dist/types/index.js +5 -16
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/index.d.ts +1 -1
  51. package/package.json +1 -1
  52. package/skills/audit-log/SKILL.md +57 -28
  53. package/skills/bug-hunter/SKILL.md +85 -61
  54. package/skills/git-flow/SKILL.md +73 -18
  55. package/skills/multi-agent/SKILL.md +69 -40
  56. package/skills/node-modern/SKILL.md +111 -19
  57. package/skills/prompt-engineering/SKILL.md +97 -16
  58. package/skills/react-modern/SKILL.md +104 -18
  59. package/skills/refactor-planner/SKILL.md +73 -43
  60. package/skills/sdd/SKILL.md +54 -112
  61. package/skills/security-scanner/SKILL.md +95 -93
  62. package/skills/skill-creator/SKILL.md +58 -25
  63. package/skills/typescript-strict/SKILL.md +107 -15
@@ -436,6 +436,20 @@ var DefaultSessionStore = class {
436
436
  await fsp.unlink(path3.join(this.dir, `${id}.jsonl`));
437
437
  await fsp.unlink(path3.join(this.dir, `${id}.summary.json`)).catch(() => void 0);
438
438
  }
439
+ async clearHistory(id) {
440
+ const file = path3.join(this.dir, `${id}.jsonl`);
441
+ const meta = path3.join(this.dir, `${id}.summary.json`);
442
+ const record = `${JSON.stringify({
443
+ type: "session_start",
444
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
445
+ id,
446
+ model: "unknown",
447
+ provider: "unknown"
448
+ })}
449
+ `;
450
+ await fsp.writeFile(file, record, "utf8");
451
+ await fsp.unlink(meta).catch(() => void 0);
452
+ }
439
453
  async summarize(id, mtime) {
440
454
  try {
441
455
  const data = await this.load(id);
@@ -741,10 +755,21 @@ var FileSessionWriter = class {
741
755
  });
742
756
  return removedCount;
743
757
  }
758
+ async clearSession() {
759
+ if (!this.filePath) return;
760
+ const record = `${JSON.stringify({
761
+ type: "session_start",
762
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
763
+ id: this.id,
764
+ model: this.meta.model ?? "unknown",
765
+ provider: this.meta.provider ?? "unknown"
766
+ })}
767
+ `;
768
+ await fsp.writeFile(this.filePath, record, "utf8");
769
+ }
744
770
  };
745
771
  function userInputTitle(content) {
746
- if (typeof content === "string") return content.slice(0, 60);
747
- const text = content.filter((b) => b.type === "text").map((b) => b.text).join(" ");
772
+ const text = typeof content === "string" ? content : content.filter((b) => b.type === "text").map((b) => b.text).join(" ");
748
773
  return (text || "(non-text input)").slice(0, 60);
749
774
  }
750
775
 
@@ -5867,644 +5892,108 @@ function sleep(ms) {
5867
5892
  return new Promise((resolve2) => setTimeout(resolve2, ms));
5868
5893
  }
5869
5894
 
5870
- // src/execution/autonomy-prompt-contributor.ts
5871
- function makeAutonomyPromptContributor(opts) {
5872
- return async (ctx) => {
5873
- if (ctx.subagent) return [];
5874
- if (!opts.enabled()) return [];
5875
- let goal;
5876
- try {
5877
- goal = await loadGoal(opts.goalPath);
5878
- } catch {
5879
- return [];
5880
- }
5881
- if (!goal) return [];
5882
- const missionState = goal.goalState ?? "active";
5883
- if (missionState !== "active") return [];
5884
- const tailSize = opts.journalTailSize ?? 5;
5885
- const journalTail = goal.journal.slice(-tailSize).map((e) => {
5886
- const note = e.note ? ` \u2014 ${e.note.slice(0, 80)}` : "";
5887
- return ` #${e.iteration} [${e.status}] ${e.task}${note}`;
5888
- });
5889
- const text = [
5890
- "## ETERNAL AUTONOMY \u2014 active mission",
5891
- "",
5892
- "You are inside a long-running autonomous loop. The user is asleep",
5893
- "and is not available to confirm decisions. Each turn you receive a",
5894
- "directive describing one concrete sub-task that advances the mission.",
5895
- "",
5896
- `Mission: ${goal.goal}`,
5897
- `Iteration: #${goal.iterations}`,
5898
- journalTail.length > 0 ? `Recent journal (last ${journalTail.length}):
5899
- ${journalTail.join("\n")}` : "Recent journal: (none \u2014 this is the first iteration)",
5900
- "",
5901
- "### Loop control markers",
5902
- "Emit these on their own line in your final text \u2014 case-insensitive,",
5903
- "whitespace-tolerant, but they must occupy the entire line:",
5904
- "- `[continue]` \u2014 chain to the next internal step without returning.",
5905
- "- `[done]` \u2014 the current sub-task is finished; return to the engine.",
5906
- "- `[GOAL_COMPLETE]` \u2014 emit ONLY when the OVERALL mission is",
5907
- " verifiably done. Must be followed by a one-paragraph verification",
5908
- " recipe (artifact path, test command, or 10-second reproduction).",
5909
- " The engine halts on this marker \u2014 false positives waste real",
5910
- " human time. If unsure, emit `[done]` and let the next iteration",
5911
- " decide.",
5912
- "",
5913
- "### Operating principles",
5914
- "- YOLO is active. Do NOT ask for confirmation, do NOT propose",
5915
- " options. Pick the best path and execute it.",
5916
- "- Use tools freely; multiple calls per turn are normal and expected.",
5917
- "- When working on a todo, mark it `in_progress` via the todos tool",
5918
- " before tool work and `completed` (or `cancelled` with a reason)",
5919
- " when done. The loop reads todo state between iterations.",
5920
- "- If an approach fails twice in a row, pivot. Don't grind on the",
5921
- " same wall \u2014 try a different angle, file a cancel on the todo, or",
5922
- " surface the obstacle via `[done]` and let the next iteration",
5923
- " re-plan."
5924
- ].join("\n");
5925
- return [
5926
- {
5927
- type: "text",
5928
- text,
5929
- cache_control: { type: "ephemeral" }
5930
- }
5931
- ];
5932
- };
5933
- }
5934
-
5935
- // src/execution/goal-preamble.ts
5936
- function buildGoalPreamble(goal) {
5937
- return [
5938
- "[GOAL \u2014 LOCKED IN. You will work on this until it is verifiably done.",
5939
- "The user granted you full autonomy. Read these constraints once, then act.",
5940
- "",
5941
- "YOUR GOAL:",
5942
- "---",
5943
- goal,
5944
- "---",
5945
- "",
5946
- "AUTHORITY YOU HAVE:",
5947
- "- Spawn as many subagents as the work needs (delegate / spawn_subagent).",
5948
- " Parallel + recursive fan-out are both fine. There is no spawn budget.",
5949
- "- Use any provider/model per subagent \u2014 pick the right tool for each",
5950
- " piece of work. Heavy reasoning model for planning, fast model for",
5951
- " batch work, specialist model for domain code.",
5952
- "- Run unlimited tool calls and iterations. There is NO hidden budget.",
5953
- " The Agent loop auto-extends every 100 iterations forever.",
5954
- "- Retry failed tools with different inputs, alternative paths, fresh",
5955
- " subagents. Switch providers mid-run if one is rate-limited.",
5956
- "- Re-plan freely when an approach hits a dead end. You are not obliged",
5957
- " to stick with the first plan you proposed.",
5958
- "",
5959
- 'WHAT "DONE" MEANS \u2014 non-negotiable:',
5960
- "- You can name a concrete artifact (a passing test, a written file at",
5961
- " a specific path, a fixed bug verified by re-running the failing case,",
5962
- " a clean grep that previously had matches).",
5963
- "- You can tell the user HOW to verify it themselves in 10 seconds.",
5964
- '- You have NOT hedged. None of: "looks like it should work", "I',
5965
- ' believe this fixes it", "the changes appear correct".',
5966
- "",
5967
- "WHAT IS NOT DONE \u2014 never report any of these as completion:",
5968
- "- An error message you didn't recover from.",
5969
- '- An empty result, a 0-line file, a "no matches found" you accepted',
5970
- " without questioning the search.",
5971
- '- "Should I continue?" / "Want me to also...?" / "Let me know if you',
5972
- ' want X." Those are hedges. The user already told you to finish the',
5973
- " goal \u2014 just do it.",
5974
- "- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%",
5975
- " done, not done.",
5976
- "- A subagent's failed/timeout/stopped TaskResult that you didn't",
5977
- " respond to with a fresh attempt (different role, different model,",
5978
- " tighter prompt).",
5979
- "",
5980
- "PERSISTENCE PROTOCOL:",
5981
- "- If blocked, try at least 3 different angles before reporting the",
5982
- " problem to the user. Different tool inputs, different subagent",
5983
- " roles, different providers, different decomposition of the task.",
5984
- "- If a tool fails, read its error, alter the input, try again. Do",
5985
- " not just report the failure back.",
5986
- "- If a subagent returns useless output, respawn with a tighter prompt",
5987
- ' or a different role. Do not accept "I could not determine\u2026" as the',
5988
- " final answer.",
5989
- "- Use `ask_subagent` for one-shot questions when you don't need a",
5990
- " full delegated task.",
5991
- "",
5992
- "REPORTING:",
5993
- "- Stream short progress notes between major actions so the user can",
5994
- " monitor. Do not go silent for 50 tool calls then dump a wall of",
5995
- " text \u2014 but also do not narrate every tool call.",
5996
- "- Use the shared scratchpad (if available) to leave breadcrumbs",
5997
- " subagents can read.",
5998
- "- Final response must include: (a) what was accomplished, (b) how",
5999
- " to verify, (c) any caveats (residual TODOs, things the user",
6000
- " should know about).",
6001
- "",
6002
- "BEGIN.]"
6003
- ].join("\n");
6004
- }
6005
-
6006
- // src/coordination/director.ts
6007
- init_atomic_write();
6008
-
6009
- // src/coordination/in-memory-transport.ts
6010
- var InMemoryBridgeTransport = class {
6011
- subs = /* @__PURE__ */ new Map();
6012
- send(msg, to) {
6013
- if (to === "*") {
6014
- for (const [id, handlers2] of this.subs) {
6015
- if (id === msg.from) continue;
6016
- for (const h of handlers2) {
6017
- try {
6018
- h(msg);
6019
- } catch {
6020
- }
6021
- }
6022
- }
6023
- return Promise.resolve();
6024
- }
6025
- const handlers = this.subs.get(to);
6026
- if (handlers) {
6027
- for (const h of handlers) {
6028
- try {
6029
- h(msg);
6030
- } catch {
6031
- }
6032
- }
6033
- }
6034
- return Promise.resolve();
6035
- }
6036
- subscribe(agentId, handler) {
6037
- if (!this.subs.has(agentId)) this.subs.set(agentId, /* @__PURE__ */ new Set());
6038
- this.subs.get(agentId).add(handler);
6039
- return () => this.subs.get(agentId)?.delete(handler);
6040
- }
6041
- close(agentId) {
6042
- this.subs.delete(agentId);
6043
- return Promise.resolve();
5895
+ // src/coordination/subagent-budget.ts
5896
+ var BudgetExceededError = class extends Error {
5897
+ kind;
5898
+ limit;
5899
+ observed;
5900
+ constructor(kind, limit, observed) {
5901
+ super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);
5902
+ this.name = "BudgetExceededError";
5903
+ this.kind = kind;
5904
+ this.limit = limit;
5905
+ this.observed = observed;
6044
5906
  }
6045
5907
  };
6046
-
6047
- // src/coordination/agent-bridge.ts
6048
- var InMemoryAgentBridge = class {
6049
- agentId;
6050
- coordinatorId;
6051
- transport;
6052
- subscriptions = /* @__PURE__ */ new Set();
6053
- pendingRequests = /* @__PURE__ */ new Map();
6054
- stopped = false;
6055
- timeoutMs;
6056
- /** Guards request() so concurrent calls on the same id can't silently overwrite. */
6057
- inflightGuards = /* @__PURE__ */ new Set();
6058
- constructor(config, transport) {
6059
- this.agentId = config.agentId;
6060
- this.coordinatorId = config.coordinatorId;
6061
- this.transport = transport;
6062
- this.timeoutMs = config.timeoutMs ?? 3e4;
6063
- this.transport.subscribe(this.agentId, (msg) => {
6064
- if (msg.type === "heartbeat") return;
6065
- const pending = this.pendingRequests.get(msg.id);
6066
- if (pending) {
6067
- clearTimeout(pending.timer);
6068
- this.pendingRequests.delete(msg.id);
6069
- this.inflightGuards.delete(msg.id);
6070
- pending.resolve(msg);
6071
- return;
6072
- }
6073
- for (const h of this.subscriptions) {
6074
- try {
6075
- h(msg);
6076
- } catch {
6077
- }
6078
- }
6079
- });
6080
- }
6081
- async send(msg) {
6082
- msg.timestamp = Date.now();
6083
- await this.transport.send(msg, msg.to ?? this.coordinatorId);
6084
- }
6085
- async broadcast(msg) {
6086
- msg.timestamp = Date.now();
6087
- msg.to = "*";
6088
- await this.transport.send(msg, "*");
6089
- }
6090
- subscribe(handler) {
6091
- this.subscriptions.add(handler);
6092
- return () => this.subscriptions.delete(handler);
6093
- }
6094
- async request(msg, timeoutMs) {
6095
- if (this.stopped) throw new Error("Bridge is stopped");
6096
- const timeout = timeoutMs ?? this.timeoutMs;
6097
- const correlationId = msg.id;
6098
- if (this.inflightGuards.has(correlationId)) {
6099
- throw new Error(
6100
- `Bridge request id "${correlationId}" collides with an in-flight request \u2014 caller is reusing message ids`
6101
- );
6102
- }
6103
- this.inflightGuards.add(correlationId);
6104
- return new Promise((resolve2, reject) => {
6105
- const timer = setTimeout(() => {
6106
- this.inflightGuards.delete(correlationId);
6107
- this.pendingRequests.delete(correlationId);
6108
- reject(new Error(`Request ${correlationId} timed out after ${timeout}ms`));
6109
- }, timeout);
6110
- if (this.stopped) {
6111
- clearTimeout(timer);
6112
- this.inflightGuards.delete(correlationId);
6113
- this.pendingRequests.delete(correlationId);
6114
- reject(new Error("Bridge stopped"));
6115
- return;
6116
- }
6117
- this.pendingRequests.set(correlationId, {
6118
- resolve: resolve2,
6119
- reject,
6120
- timer
6121
- });
6122
- msg.timestamp = Date.now();
6123
- this.transport.send(msg, msg.to ?? this.coordinatorId).catch((e) => {
6124
- clearTimeout(timer);
6125
- this.inflightGuards.delete(correlationId);
6126
- this.pendingRequests.delete(correlationId);
6127
- reject(e);
6128
- });
6129
- });
6130
- }
6131
- async stop() {
6132
- this.stopped = true;
6133
- for (const [, p] of this.pendingRequests) {
6134
- clearTimeout(p.timer);
6135
- p.reject(new Error("Bridge stopped"));
6136
- }
6137
- this.pendingRequests.clear();
6138
- this.inflightGuards.clear();
6139
- this.subscriptions.clear();
6140
- await this.transport.close(this.agentId);
5908
+ var BudgetThresholdSignal = class extends Error {
5909
+ kind;
5910
+ limit;
5911
+ used;
5912
+ /** Resolves to 'extend' (with optional new limits) or 'stop' */
5913
+ decision;
5914
+ constructor(kind, limit, used, decision) {
5915
+ super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);
5916
+ this.name = "BudgetThresholdSignal";
5917
+ this.kind = kind;
5918
+ this.limit = limit;
5919
+ this.used = used;
5920
+ this.decision = decision;
6141
5921
  }
6142
5922
  };
6143
- function createMessage(type, from, payload, to) {
6144
- return {
6145
- id: randomUUID(),
6146
- type,
6147
- from,
6148
- to,
6149
- payload,
6150
- timestamp: Date.now(),
6151
- priority: "normal"
6152
- };
6153
- }
6154
-
6155
- // src/coordination/director-prompts.ts
6156
- var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
6157
- subagents by spawning them, assigning tasks, awaiting completions, and
6158
- rolling up their outputs into your next decision.
6159
-
6160
- Core fleet tools available to you:
6161
- - spawn_subagent \u2014 create a worker with a chosen provider / model / role
6162
- - assign_task \u2014 hand a piece of work to a specific subagent
6163
- - await_tasks \u2014 block until named task ids complete (parallel-safe)
6164
- - ask_subagent \u2014 synchronously query a running subagent via the bridge
6165
- - roll_up \u2014 aggregate finished tasks into a markdown/json summary
6166
- - terminate_subagent \u2014 abort a stuck worker (use sparingly)
6167
- - fleet_status \u2014 snapshot of all subagents and pending tasks
6168
- - fleet_usage \u2014 token + cost breakdown per subagent and total
6169
-
6170
- Working rules:
6171
- 1. Decompose first. Before spawning, decide which sub-tasks are
6172
- independent and can run in parallel. Sequential work doesn't need a
6173
- subagent \u2014 do it yourself.
6174
- 2. Match worker to job. Cheap/fast model for triage, capable model for
6175
- synthesis. Different providers per sibling is allowed and encouraged.
6176
- 3. Always pair an assign with an await. Don't fire-and-forget; you owe
6177
- the user a single coherent answer at the end.
6178
- 4. Roll up before deciding. After await_tasks resolves, call roll_up so
6179
- the results are folded back into your context in a compact form.
6180
- 5. Budget is real. Check fleet_usage periodically. If a subagent is
6181
- thrashing, terminate it rather than letting cost climb silently.
6182
- 6. Never claim a subagent's work as your own without verifying it. If a
6183
- result looks wrong, ask_subagent for clarification before passing it
6184
- to the user.`;
6185
- var DEFAULT_SUBAGENT_BASELINE = `You are a subagent operating under a Director. You were spawned to handle
6186
- a specific slice of a larger plan \u2014 do that slice well and report back.
6187
-
6188
- Bridge contract:
6189
- - You have a parent (the Director). You may call \`request\` on the
6190
- parent bridge to ask a clarifying question. Use this sparingly; the
6191
- parent is also working.
6192
- - You MAY NOT request the parent's system prompt, tool list, or other
6193
- subagents' context. Those are not yours to read.
6194
- - Your final task output is what the Director sees. Be concise,
6195
- structured, and self-contained \u2014 assume the Director will paste your
6196
- output into its own context.`;
6197
- function composeDirectorPrompt(parts = {}) {
6198
- const sections = [];
6199
- const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
6200
- if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());
6201
- if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {
6202
- sections.push(`Available roles you can spawn:
6203
- ${parts.rosterSummary.trim()}`);
6204
- }
6205
- if (parts.basePrompt && parts.basePrompt.trim().length > 0) {
6206
- sections.push(parts.basePrompt.trim());
6207
- }
6208
- return sections.join("\n\n");
6209
- }
6210
- function composeSubagentPrompt(parts = {}) {
6211
- const sections = [];
6212
- const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;
6213
- if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());
6214
- if (parts.role && parts.role.trim().length > 0) {
6215
- sections.push(`Role:
6216
- ${parts.role.trim()}`);
5923
+ var SubagentBudget = class _SubagentBudget {
5924
+ limits;
5925
+ iterations = 0;
5926
+ toolCalls = 0;
5927
+ tokenInput = 0;
5928
+ tokenOutput = 0;
5929
+ costUsd = 0;
5930
+ startTime = null;
5931
+ _onThreshold;
5932
+ /**
5933
+ * Tracks which budget kinds currently have an extension request
5934
+ * in flight. While a kind is here, further `checkLimit` calls for the
5935
+ * same kind are no-ops — without this dedup, every `recordIteration`
5936
+ * after the limit is reached spawns a fresh decision Promise (until
5937
+ * the first one lands and patches limits), flooding the FleetBus
5938
+ * with redundant threshold events. Cleared in `checkLimitAsync`'s
5939
+ * `finally`.
5940
+ */
5941
+ pendingExtensions = /* @__PURE__ */ new Set();
5942
+ /**
5943
+ * Hard cap on how long `checkLimitAsync` waits for the coordinator to
5944
+ * respond before defaulting to 'stop'. Without this fallback an absent
5945
+ * or hung listener (Director not built / event filter detached mid-run)
5946
+ * leaves the budget over-limit and never enforces anything, since
5947
+ * `checkLimit` returns synchronously via `void this.checkLimitAsync`.
5948
+ * Hardcoded for now most fleets set their own per-task timeout that
5949
+ * dwarfs this anyway. 30 s matches the existing event-emit timeoutMs.
5950
+ */
5951
+ static DECISION_TIMEOUT_MS = 3e4;
5952
+ /**
5953
+ * Injected by the runner when wiring the budget to its EventBus.
5954
+ * Used by `checkLimitAsync` to emit `budget.threshold_reached` events.
5955
+ */
5956
+ _events;
5957
+ /**
5958
+ * Optional callback for soft-limit handling. When set, the budget will
5959
+ * call this instead of throwing when a limit is first reached. The
5960
+ * handler decides whether to throw, continue, or ask the coordinator.
5961
+ */
5962
+ get onThreshold() {
5963
+ return this._onThreshold;
6217
5964
  }
6218
- if (parts.task && parts.task.trim().length > 0) {
6219
- sections.push(`Task:
6220
- ${parts.task.trim()}`);
5965
+ set onThreshold(fn) {
5966
+ this._onThreshold = fn;
6221
5967
  }
6222
- if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {
6223
- sections.push(
6224
- `Shared notes:
6225
- A scratchpad shared with the rest of the fleet is mounted at \`${parts.sharedScratchpad.trim()}\`.
6226
- - Write your final findings as markdown files there (e.g. \`findings.md\`, \`security.md\`).
6227
- - Before starting, list the directory and read any sibling files relevant to your task \u2014 they may already contain context you can build on.
6228
- - Use stable filenames (one file per concern); overwrite instead of appending so the Director sees the latest state.`
6229
- );
5968
+ constructor(limits = {}) {
5969
+ this.limits = Object.freeze({ ...limits });
6230
5970
  }
6231
- if (parts.override && parts.override.trim().length > 0) {
6232
- sections.push(parts.override.trim());
5971
+ start() {
5972
+ this.startTime = Date.now();
6233
5973
  }
6234
- return sections.join("\n\n");
6235
- }
6236
- function rosterSummaryFromConfigs(roster) {
6237
- const lines = [];
6238
- for (const [roleId, cfg] of Object.entries(roster)) {
6239
- const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : "";
6240
- const headline = cfg.prompt ? (cfg.prompt.split("\n").find((l) => l.trim().length > 0) ?? "").trim().slice(0, 80) : "";
6241
- const tail = headline ? ` \u2014 ${headline}` : "";
6242
- lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);
5974
+ /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */
5975
+ isNearLimit() {
5976
+ const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;
5977
+ if (maxIterations && this.iterations >= maxIterations * 0.9) return true;
5978
+ if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;
5979
+ if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;
5980
+ if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;
5981
+ return false;
6243
5982
  }
6244
- return lines.join("\n");
6245
- }
6246
-
6247
- // src/coordination/fleet-bus.ts
6248
- var FleetBus = class {
6249
- byId = /* @__PURE__ */ new Map();
6250
- byType = /* @__PURE__ */ new Map();
6251
- any = /* @__PURE__ */ new Set();
6252
5983
  /**
6253
- * Hook a subagent's EventBus into the fleet. EventBus is strongly
6254
- * typed and doesn't expose an `onAny` hook, so we subscribe to the
6255
- * canonical set of event types a subagent emits during a run. New
6256
- * event types added to the kernel must be added here too — but the
6257
- * cost is a tiny single line per type, and the explicit list keeps
6258
- * the wire format clear.
6259
- *
6260
- * Returns a disposer that detaches every subscription; call on
6261
- * subagent teardown so the listeners don't outlive the run.
5984
+ * Synchronous budget check always throws synchronously so callers
5985
+ * (especially test event handlers using `expect().toThrow()`) get an
5986
+ * unhandled rejection when the budget is exceeded without a handler.
5987
+ * When `onThreshold` IS configured, the actual async threshold-handling
5988
+ * is dispatched as a fire-and-forget promise.
6262
5989
  */
6263
- attach(subagentId, bus, taskId) {
6264
- const off = bus.onPattern("*", (type, payload) => {
6265
- if (type.startsWith("subagent.")) return;
6266
- this.emit({ subagentId, taskId, ts: Date.now(), type, payload });
6267
- });
6268
- return () => {
6269
- off();
6270
- };
6271
- }
6272
- /** Subscribe to every event from one subagent. */
6273
- subscribe(subagentId, handler) {
6274
- let set = this.byId.get(subagentId);
6275
- if (!set) {
6276
- set = /* @__PURE__ */ new Set();
6277
- this.byId.set(subagentId, set);
5990
+ checkLimit(kind, used, limit) {
5991
+ if (!this._onThreshold) {
5992
+ throw new BudgetExceededError(kind, limit, used);
6278
5993
  }
6279
- set.add(handler);
6280
- return () => {
6281
- set.delete(handler);
6282
- };
6283
- }
6284
- /** Subscribe to one event type across all subagents. */
6285
- filter(type, handler) {
6286
- let set = this.byType.get(type);
6287
- if (!set) {
6288
- set = /* @__PURE__ */ new Set();
6289
- this.byType.set(type, set);
6290
- }
6291
- set.add(handler);
6292
- return () => {
6293
- set.delete(handler);
6294
- };
6295
- }
6296
- /** Subscribe to literally everything. The fleet roll-up uses this. */
6297
- onAny(handler) {
6298
- this.any.add(handler);
6299
- return () => {
6300
- this.any.delete(handler);
6301
- };
6302
- }
6303
- emit(event) {
6304
- const byId = this.byId.get(event.subagentId);
6305
- if (byId)
6306
- for (const h of byId) {
6307
- try {
6308
- h(event);
6309
- } catch {
6310
- }
6311
- }
6312
- const byType = this.byType.get(event.type);
6313
- if (byType)
6314
- for (const h of byType) {
6315
- try {
6316
- h(event);
6317
- } catch {
6318
- }
6319
- }
6320
- for (const h of this.any) {
6321
- try {
6322
- h(event);
6323
- } catch {
6324
- }
6325
- }
6326
- }
6327
- };
6328
- var FleetUsageAggregator = class {
6329
- constructor(bus, priceLookup, metaLookup) {
6330
- this.bus = bus;
6331
- this.priceLookup = priceLookup;
6332
- this.metaLookup = metaLookup;
6333
- bus.filter("provider.response", (e) => this.onProviderResponse(e));
6334
- bus.filter("tool.executed", (e) => this.onToolExecuted(e));
6335
- bus.filter("iteration.started", (e) => this.onIterationStarted(e));
6336
- }
6337
- bus;
6338
- priceLookup;
6339
- metaLookup;
6340
- perSubagent = /* @__PURE__ */ new Map();
6341
- total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
6342
- /** Live snapshot — safe to call from a tool's execute() body. */
6343
- snapshot() {
6344
- return {
6345
- total: { ...this.total },
6346
- perSubagent: Object.fromEntries(
6347
- Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }])
6348
- )
6349
- };
6350
- }
6351
- ensure(subagentId) {
6352
- let snap = this.perSubagent.get(subagentId);
6353
- if (!snap) {
6354
- const meta = this.metaLookup?.(subagentId);
6355
- snap = {
6356
- subagentId,
6357
- provider: meta?.provider,
6358
- model: meta?.model,
6359
- input: 0,
6360
- output: 0,
6361
- cacheRead: 0,
6362
- cacheWrite: 0,
6363
- cost: 0,
6364
- toolCalls: 0,
6365
- iterations: 0,
6366
- startedAt: Date.now(),
6367
- lastEventAt: Date.now()
6368
- };
6369
- this.perSubagent.set(subagentId, snap);
6370
- }
6371
- return snap;
6372
- }
6373
- onProviderResponse(e) {
6374
- const snap = this.ensure(e.subagentId);
6375
- const p = e.payload;
6376
- const usage = p?.usage;
6377
- if (!usage) return;
6378
- snap.input += usage.input ?? 0;
6379
- snap.output += usage.output ?? 0;
6380
- snap.cacheRead += usage.cacheRead ?? 0;
6381
- snap.cacheWrite += usage.cacheWrite ?? 0;
6382
- this.total.input += usage.input ?? 0;
6383
- this.total.output += usage.output ?? 0;
6384
- this.total.cacheRead += usage.cacheRead ?? 0;
6385
- this.total.cacheWrite += usage.cacheWrite ?? 0;
6386
- const price = this.priceLookup?.(e.subagentId);
6387
- if (price) {
6388
- const delta = (usage.input ?? 0) / 1e6 * (price.input ?? 0) + (usage.output ?? 0) / 1e6 * (price.output ?? 0) + (usage.cacheRead ?? 0) / 1e6 * (price.cacheRead ?? 0) + (usage.cacheWrite ?? 0) / 1e6 * (price.cacheWrite ?? 0);
6389
- snap.cost += delta;
6390
- this.total.cost += delta;
6391
- }
6392
- snap.lastEventAt = e.ts;
6393
- }
6394
- onToolExecuted(e) {
6395
- const snap = this.ensure(e.subagentId);
6396
- snap.toolCalls += 1;
6397
- snap.lastEventAt = e.ts;
6398
- }
6399
- onIterationStarted(e) {
6400
- const snap = this.ensure(e.subagentId);
6401
- snap.iterations += 1;
6402
- snap.lastEventAt = e.ts;
6403
- }
6404
- };
6405
-
6406
- // src/coordination/subagent-budget.ts
6407
- var BudgetExceededError = class extends Error {
6408
- kind;
6409
- limit;
6410
- observed;
6411
- constructor(kind, limit, observed) {
6412
- super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);
6413
- this.name = "BudgetExceededError";
6414
- this.kind = kind;
6415
- this.limit = limit;
6416
- this.observed = observed;
6417
- }
6418
- };
6419
- var BudgetThresholdSignal = class extends Error {
6420
- kind;
6421
- limit;
6422
- used;
6423
- /** Resolves to 'extend' (with optional new limits) or 'stop' */
6424
- decision;
6425
- constructor(kind, limit, used, decision) {
6426
- super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);
6427
- this.name = "BudgetThresholdSignal";
6428
- this.kind = kind;
6429
- this.limit = limit;
6430
- this.used = used;
6431
- this.decision = decision;
6432
- }
6433
- };
6434
- var SubagentBudget = class _SubagentBudget {
6435
- limits;
6436
- iterations = 0;
6437
- toolCalls = 0;
6438
- tokenInput = 0;
6439
- tokenOutput = 0;
6440
- costUsd = 0;
6441
- startTime = null;
6442
- _onThreshold;
6443
- /**
6444
- * Tracks which budget kinds currently have an extension request
6445
- * in flight. While a kind is here, further `checkLimit` calls for the
6446
- * same kind are no-ops — without this dedup, every `recordIteration`
6447
- * after the limit is reached spawns a fresh decision Promise (until
6448
- * the first one lands and patches limits), flooding the FleetBus
6449
- * with redundant threshold events. Cleared in `checkLimitAsync`'s
6450
- * `finally`.
6451
- */
6452
- pendingExtensions = /* @__PURE__ */ new Set();
6453
- /**
6454
- * Hard cap on how long `checkLimitAsync` waits for the coordinator to
6455
- * respond before defaulting to 'stop'. Without this fallback an absent
6456
- * or hung listener (Director not built / event filter detached mid-run)
6457
- * leaves the budget over-limit and never enforces anything, since
6458
- * `checkLimit` returns synchronously via `void this.checkLimitAsync`.
6459
- * Hardcoded for now — most fleets set their own per-task timeout that
6460
- * dwarfs this anyway. 30 s matches the existing event-emit timeoutMs.
6461
- */
6462
- static DECISION_TIMEOUT_MS = 3e4;
6463
- /**
6464
- * Injected by the runner when wiring the budget to its EventBus.
6465
- * Used by `checkLimitAsync` to emit `budget.threshold_reached` events.
6466
- */
6467
- _events;
6468
- /**
6469
- * Optional callback for soft-limit handling. When set, the budget will
6470
- * call this instead of throwing when a limit is first reached. The
6471
- * handler decides whether to throw, continue, or ask the coordinator.
6472
- */
6473
- get onThreshold() {
6474
- return this._onThreshold;
6475
- }
6476
- set onThreshold(fn) {
6477
- this._onThreshold = fn;
6478
- }
6479
- constructor(limits = {}) {
6480
- this.limits = Object.freeze({ ...limits });
6481
- }
6482
- start() {
6483
- this.startTime = Date.now();
6484
- }
6485
- /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */
6486
- isNearLimit() {
6487
- const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;
6488
- if (maxIterations && this.iterations >= maxIterations * 0.9) return true;
6489
- if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;
6490
- if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;
6491
- if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;
6492
- return false;
6493
- }
6494
- /**
6495
- * Synchronous budget check — always throws synchronously so callers
6496
- * (especially test event handlers using `expect().toThrow()`) get an
6497
- * unhandled rejection when the budget is exceeded without a handler.
6498
- * When `onThreshold` IS configured, the actual async threshold-handling
6499
- * is dispatched as a fire-and-forget promise.
6500
- */
6501
- checkLimit(kind, used, limit) {
6502
- if (kind === "timeout" || !this._onThreshold) {
6503
- throw new BudgetExceededError(kind, limit, used);
6504
- }
6505
- const bus = this._events;
6506
- if (!bus || bus.listenerCount("budget.threshold_reached") === 0) {
6507
- throw new BudgetExceededError(kind, limit, used);
5994
+ const bus = this._events;
5995
+ if (!bus || bus.listenerCount("budget.threshold_reached") === 0) {
5996
+ throw new BudgetExceededError(kind, limit, used);
6508
5997
  }
6509
5998
  if (this.pendingExtensions.has(kind)) return;
6510
5999
  this.pendingExtensions.add(kind);
@@ -6615,14 +6104,18 @@ var SubagentBudget = class _SubagentBudget {
6615
6104
  }
6616
6105
  }
6617
6106
  /**
6618
- * Throws if the wall-clock budget is exhausted. Call this from the iteration
6619
- * loop so a hung tool can't keep a subagent running past its deadline.
6107
+ * Wall-clock budget check. Unlike other limits, timeout is treated as a
6108
+ * warning-only event it NEVER hard-stops the subagent. When the
6109
+ * elapsed time exceeds timeoutMs, emits `budget.threshold_reached` with
6110
+ * kind='timeout' so the Director can decide whether to extend or warn.
6111
+ * Call this from the iteration loop so a hung tool gets a chance to
6112
+ * negotiate more time before the coordinator's Promise.race kills it.
6620
6113
  */
6621
6114
  checkTimeout() {
6622
6115
  if (this.startTime === null || this.limits.timeoutMs === void 0) return;
6623
6116
  const elapsed = Date.now() - this.startTime;
6624
6117
  if (elapsed > this.limits.timeoutMs) {
6625
- throw new BudgetExceededError("timeout", this.limits.timeoutMs, elapsed);
6118
+ void this.checkLimit("timeout", elapsed, this.limits.timeoutMs);
6626
6119
  }
6627
6120
  }
6628
6121
  /** Returns true if a timeout has occurred without throwing. Useful for races. */
@@ -6645,45 +6138,213 @@ var SubagentBudget = class _SubagentBudget {
6645
6138
  }
6646
6139
  };
6647
6140
 
6648
- // src/coordination/fleet.ts
6649
- var AUDIT_LOG_AGENT = {
6650
- id: "audit-log",
6651
- name: "Audit Log",
6652
- role: "audit-log",
6653
- prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL
6654
- session logs and produce actionable markdown reports.
6655
-
6656
- Scope:
6657
- - Parse session logs (iteration counts, tool calls, errors, usage)
6658
- - Detect repeated failure patterns across multiple runs
6659
- - Identify tool usage anomalies (over-use, failures, unexpected chains)
6660
- - Track token consumption trends
6661
- - Generate structured audit reports with severity ratings
6662
-
6663
- Input format you accept:
6664
- { "task": "analyze | report | trends", "sessionPath": "<path>", "focus": "errors | tools | usage | all" }
6665
-
6666
- Output: Markdown audit report with sections:
6667
- - ## Summary (totals, error rate)
6668
- - ## Top Errors (count + context)
6669
- - ## Tool Usage (table with calls, failures, avg duration)
6670
- - ## Anomalies (pattern \u2192 severity)
6671
-
6672
- Working rules:
6673
- - Never fabricate numbers \u2014 read the actual logs first
6674
- - Always include file:line references for errors
6675
- - If sessionPath is missing, ask the director to provide it
6676
- - Report confidence level: high (>90% accuracy), medium, low`
6677
- // No hardcoded budgets — the orchestrator (delegate tool or
6678
- // spawn_subagent) decides per-task how much room a subagent gets.
6679
- // A monorepo audit needs hours; a single-file lint check needs
6680
- // seconds. Pinning a number here forces the orchestrator to fight
6681
- // the role's default instead of just asking for what it needs.
6682
- };
6683
- var BUG_HUNTER_AGENT = {
6684
- id: "bug-hunter",
6685
- name: "Bug Hunter",
6686
- role: "bug-hunter",
6141
+ // src/coordination/agent-subagent-runner.ts
6142
+ function makeAgentSubagentRunner(opts) {
6143
+ const format = opts.formatTaskInput ?? defaultFormatTaskInput;
6144
+ return async (task, ctx) => {
6145
+ const factoryResult = await opts.factory(ctx.config);
6146
+ const { agent, events } = factoryResult;
6147
+ const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);
6148
+ const aborter = new AbortController();
6149
+ ctx.budget._events = events;
6150
+ ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();
6151
+ let budgetError = null;
6152
+ const onBudgetError = (err) => {
6153
+ if (err instanceof BudgetThresholdSignal) {
6154
+ err.decision.then((decision) => {
6155
+ if (decision === "stop") {
6156
+ budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
6157
+ aborter.abort();
6158
+ }
6159
+ }).catch(() => {
6160
+ budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
6161
+ aborter.abort();
6162
+ });
6163
+ return;
6164
+ }
6165
+ aborter.abort();
6166
+ budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
6167
+ "tool_calls",
6168
+ 0,
6169
+ 0
6170
+ );
6171
+ if (budgetError !== err && err instanceof Error) {
6172
+ budgetError.message += ` (caused by: ${err.message})`;
6173
+ }
6174
+ };
6175
+ let lastToolFailed = null;
6176
+ const unsub = [];
6177
+ unsub.push(
6178
+ events.on("tool.executed", (e) => {
6179
+ try {
6180
+ ctx.budget.recordToolCall();
6181
+ } catch (eb) {
6182
+ onBudgetError(eb);
6183
+ }
6184
+ if (e.ok === false) {
6185
+ lastToolFailed = e.name;
6186
+ } else if (e.ok === true) {
6187
+ lastToolFailed = null;
6188
+ }
6189
+ }),
6190
+ events.on("provider.response", (e) => {
6191
+ try {
6192
+ ctx.budget.recordUsage(e.usage);
6193
+ } catch (e2) {
6194
+ void onBudgetError(e2);
6195
+ }
6196
+ }),
6197
+ events.on("iteration.started", () => {
6198
+ try {
6199
+ ctx.budget.recordIteration();
6200
+ } catch (e) {
6201
+ void onBudgetError(e);
6202
+ }
6203
+ const u = ctx.budget.usage();
6204
+ const since = u.iterations - lastSummaryAtIteration;
6205
+ if (since >= SUMMARY_INTERVAL) {
6206
+ lastSummaryAtIteration = u.iterations;
6207
+ events.emit("subagent.iteration_summary", {
6208
+ subagentId: ctx.subagentId,
6209
+ iteration: u.iterations,
6210
+ toolCalls: u.toolCalls,
6211
+ costUsd: u.costUsd,
6212
+ currentTool: currentToolName,
6213
+ partialText: streamingTextAcc.trim() || void 0
6214
+ });
6215
+ }
6216
+ }),
6217
+ // D3: cooperative timeout enforcement DURING a long tool call.
6218
+ // The iteration-loop checkTimeout() only fires between agent
6219
+ // iterations — a single `bash sleep 3600` call would otherwise
6220
+ // park inside one tool execution while the timeout silently
6221
+ // passes, relying solely on the coordinator's hard Promise.race
6222
+ // to interrupt. Tools that emit `tool.progress` (bash chunks,
6223
+ // fetch byte progress, spawn-stream stdout) give us a heartbeat
6224
+ // we can hang the check on. When the budget trips here:
6225
+ // 1. onBudgetError sets budgetError + aborter.abort()
6226
+ // 2. aborter signal propagates to agent.run → tool executor
6227
+ // 3. tool's own signal listener kills the child process
6228
+ // Cheap: O(1) per progress event, and the budget short-circuits
6229
+ // when timeoutMs is unset (most subagents have one set anyway).
6230
+ events.on("tool.progress", () => {
6231
+ try {
6232
+ ctx.budget.checkTimeout();
6233
+ } catch (e) {
6234
+ void onBudgetError(e);
6235
+ }
6236
+ })
6237
+ );
6238
+ let currentToolName;
6239
+ let streamingTextAcc = "";
6240
+ let lastSummaryAtIteration = 0;
6241
+ const SUMMARY_INTERVAL = 25;
6242
+ unsub.push(
6243
+ events.on("tool.started", (e) => {
6244
+ currentToolName = e.name;
6245
+ }),
6246
+ events.on("provider.text_delta", (e) => {
6247
+ streamingTextAcc = (streamingTextAcc + e.text).slice(-200);
6248
+ })
6249
+ );
6250
+ const onParentAbort = () => aborter.abort();
6251
+ ctx.signal.addEventListener("abort", onParentAbort);
6252
+ let result;
6253
+ try {
6254
+ result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
6255
+ } finally {
6256
+ detachFleet?.();
6257
+ ctx.signal.removeEventListener("abort", onParentAbort);
6258
+ for (const u of unsub) u();
6259
+ if (factoryResult.dispose) {
6260
+ try {
6261
+ await factoryResult.dispose();
6262
+ } catch {
6263
+ }
6264
+ }
6265
+ }
6266
+ if (budgetError) {
6267
+ if ("decision" in budgetError) {
6268
+ const decision = await budgetError.decision;
6269
+ if (decision === "stop") {
6270
+ budgetError = new BudgetExceededError(
6271
+ budgetError.kind,
6272
+ budgetError.limit,
6273
+ budgetError.used
6274
+ );
6275
+ } else {
6276
+ budgetError = null;
6277
+ }
6278
+ }
6279
+ if (budgetError) throw budgetError;
6280
+ }
6281
+ if (result.status === "failed") {
6282
+ throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
6283
+ }
6284
+ if (result.status === "aborted") {
6285
+ throw new Error("agent aborted");
6286
+ }
6287
+ if (result.status === "max_iterations") {
6288
+ throw new Error("agent exhausted iteration limit");
6289
+ }
6290
+ const usage = ctx.budget.usage();
6291
+ const finalText = (result.finalText ?? "").trim();
6292
+ if (finalText.length === 0 && usage.toolCalls === 0) {
6293
+ throw new Error("empty response");
6294
+ }
6295
+ if (finalText.length === 0 && lastToolFailed !== null) {
6296
+ throw new Error(`tool failed: ${lastToolFailed}`);
6297
+ }
6298
+ return {
6299
+ result: result.finalText,
6300
+ iterations: result.iterations,
6301
+ toolCalls: usage.toolCalls
6302
+ };
6303
+ };
6304
+ }
6305
+ function defaultFormatTaskInput(task) {
6306
+ return task.description ?? "";
6307
+ }
6308
+
6309
+ // src/coordination/fleet.ts
6310
+ var AUDIT_LOG_AGENT = {
6311
+ id: "audit-log",
6312
+ name: "Audit Log",
6313
+ role: "audit-log",
6314
+ prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL
6315
+ session logs and produce actionable markdown reports.
6316
+
6317
+ Scope:
6318
+ - Parse session logs (iteration counts, tool calls, errors, usage)
6319
+ - Detect repeated failure patterns across multiple runs
6320
+ - Identify tool usage anomalies (over-use, failures, unexpected chains)
6321
+ - Track token consumption trends
6322
+ - Generate structured audit reports with severity ratings
6323
+
6324
+ Input format you accept:
6325
+ { "task": "analyze | report | trends", "sessionPath": "<path>", "focus": "errors | tools | usage | all" }
6326
+
6327
+ Output: Markdown audit report with sections:
6328
+ - ## Summary (totals, error rate)
6329
+ - ## Top Errors (count + context)
6330
+ - ## Tool Usage (table with calls, failures, avg duration)
6331
+ - ## Anomalies (pattern \u2192 severity)
6332
+
6333
+ Working rules:
6334
+ - Never fabricate numbers \u2014 read the actual logs first
6335
+ - Always include file:line references for errors
6336
+ - If sessionPath is missing, ask the director to provide it
6337
+ - Report confidence level: high (>90% accuracy), medium, low`
6338
+ // No hardcoded budgets — the orchestrator (delegate tool or
6339
+ // spawn_subagent) decides per-task how much room a subagent gets.
6340
+ // A monorepo audit needs hours; a single-file lint check needs
6341
+ // seconds. Pinning a number here forces the orchestrator to fight
6342
+ // the role's default instead of just asking for what it needs.
6343
+ };
6344
+ var BUG_HUNTER_AGENT = {
6345
+ id: "bug-hunter",
6346
+ name: "Bug Hunter",
6347
+ role: "bug-hunter",
6687
6348
  prompt: `You are the Bug Hunter agent. Your job is to systematically scan
6688
6349
  source code for bugs, anti-patterns, and code smells using pattern matching
6689
6350
  and heuristics. Output a prioritized hit list with file:line references.
@@ -6818,10 +6479,10 @@ var FLEET_ROSTER = {
6818
6479
  "security-scanner": SECURITY_SCANNER_AGENT
6819
6480
  };
6820
6481
  var FLEET_ROSTER_BUDGETS = {
6821
- "audit-log": { timeoutMs: 5 * 60 * 1e3, maxIterations: 80, maxToolCalls: 300 },
6822
- "bug-hunter": { timeoutMs: 10 * 60 * 1e3, maxIterations: 120, maxToolCalls: 400 },
6823
- "refactor-planner": { timeoutMs: 8 * 60 * 1e3, maxIterations: 100, maxToolCalls: 350 },
6824
- "security-scanner": { timeoutMs: 10 * 60 * 1e3, maxIterations: 120, maxToolCalls: 400 }
6482
+ "audit-log": { timeoutMs: 8 * 60 * 1e3, maxIterations: 150, maxToolCalls: 500 },
6483
+ "bug-hunter": { timeoutMs: 15 * 60 * 1e3, maxIterations: 200, maxToolCalls: 600 },
6484
+ "refactor-planner": { timeoutMs: 12 * 60 * 1e3, maxIterations: 180, maxToolCalls: 550 },
6485
+ "security-scanner": { timeoutMs: 15 * 60 * 1e3, maxIterations: 200, maxToolCalls: 600 }
6825
6486
  };
6826
6487
  function applyRosterBudget(cfg) {
6827
6488
  const defaultBudget = FLEET_ROSTER_BUDGETS[cfg.role ?? ""];
@@ -6961,6 +6622,33 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6961
6622
  results() {
6962
6623
  return this.completedResults;
6963
6624
  }
6625
+ /**
6626
+ * Wait for one or more tasks to complete and return their results.
6627
+ * If a task is already done when called, returns immediately.
6628
+ * Resolves to an array in the same order as `taskIds`.
6629
+ */
6630
+ async awaitTasks(taskIds) {
6631
+ return Promise.all(
6632
+ taskIds.map((id) => {
6633
+ const cached = this.completedResults.find((r) => r.taskId === id);
6634
+ if (cached) return cached;
6635
+ return new Promise((resolve2, reject) => {
6636
+ const timeout = setTimeout(() => {
6637
+ this.off("task.completed", handler);
6638
+ reject(new Error(`awaitTasks timed out waiting for task "${id}"`));
6639
+ }, this.config.timeoutMs ?? 3e5);
6640
+ const handler = ({ result }) => {
6641
+ if (result.taskId === id) {
6642
+ clearTimeout(timeout);
6643
+ this.off("task.completed", handler);
6644
+ resolve2(result);
6645
+ }
6646
+ };
6647
+ this.on("task.completed", handler);
6648
+ });
6649
+ })
6650
+ );
6651
+ }
6964
6652
  /**
6965
6653
  * Manual completion — for callers that drive subagents without a runner
6966
6654
  * (e.g. external orchestrators). When a runner is configured the coordinator
@@ -7179,8 +6867,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
7179
6867
  return;
7180
6868
  }
7181
6869
  if (decision === "throw" || decision === "stop") {
7182
- this.subagents.get(ctx.subagentId)?.abortController.abort();
7183
- reject(new BudgetExceededError("timeout", limit, elapsed));
6870
+ armFor(Math.max(1e3, limit));
7184
6871
  return;
7185
6872
  }
7186
6873
  if (decision.extend.timeoutMs !== void 0) {
@@ -7230,123 +6917,981 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
7230
6917
  subagent.abortController = new AbortController();
7231
6918
  }
7232
6919
  }
7233
- this.terminating.delete(result.subagentId);
7234
- this.emit("task.completed", {
7235
- task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },
7236
- result
7237
- });
7238
- this.tryDispatchNext();
7239
- if (this.isDone()) {
7240
- this.emit("done", {
7241
- results: this.completedResults,
7242
- totalIterations: this.totalIterations
6920
+ this.terminating.delete(result.subagentId);
6921
+ this.emit("task.completed", {
6922
+ task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },
6923
+ result
6924
+ });
6925
+ this.tryDispatchNext();
6926
+ if (this.isDone()) {
6927
+ this.emit("done", {
6928
+ results: this.completedResults,
6929
+ totalIterations: this.totalIterations
6930
+ });
6931
+ }
6932
+ }
6933
+ isDone() {
6934
+ if (this.config.doneCondition.type === "all_tasks_done") {
6935
+ return this.pendingTasks.length === 0 && this.inFlight === 0;
6936
+ }
6937
+ if (this.config.doneCondition.maxIterations !== void 0 && this.totalIterations >= this.config.doneCondition.maxIterations) {
6938
+ return true;
6939
+ }
6940
+ return false;
6941
+ }
6942
+ };
6943
+ function classifySubagentError(err, hints = {}) {
6944
+ const cause = err instanceof Error ? { name: err.name, message: err.message, stack: err.stack } : void 0;
6945
+ if (err instanceof ProviderError) {
6946
+ const baseMessage2 = err.describe();
6947
+ return providerErrorToSubagentError(err, baseMessage2, cause);
6948
+ }
6949
+ const baseMessage = err instanceof Error ? err.message : String(err);
6950
+ if (err instanceof BudgetExceededError) {
6951
+ const map = {
6952
+ iterations: "budget_iterations",
6953
+ tool_calls: "budget_tool_calls",
6954
+ tokens: "budget_tokens",
6955
+ cost: "budget_cost",
6956
+ timeout: "budget_timeout"
6957
+ };
6958
+ return {
6959
+ kind: map[err.kind],
6960
+ message: baseMessage,
6961
+ // Budgets are user-configured ceilings, not transient failures —
6962
+ // retrying with the same budget will hit the same ceiling. The
6963
+ // orchestrator must raise the budget or narrow the task first.
6964
+ retryable: false,
6965
+ cause
6966
+ };
6967
+ }
6968
+ if (hints.parentAborted) {
6969
+ return {
6970
+ kind: "aborted_by_parent",
6971
+ message: baseMessage,
6972
+ retryable: false,
6973
+ cause
6974
+ };
6975
+ }
6976
+ const lower = baseMessage.toLowerCase();
6977
+ if (/agent aborted$/i.test(baseMessage)) {
6978
+ return {
6979
+ kind: "aborted_by_parent",
6980
+ message: baseMessage,
6981
+ retryable: false,
6982
+ cause
6983
+ };
6984
+ }
6985
+ if (/agent exhausted iteration limit$/i.test(baseMessage)) {
6986
+ return { kind: "budget_iterations", message: baseMessage, retryable: false, cause };
6987
+ }
6988
+ if (/empty response$/i.test(baseMessage)) {
6989
+ return { kind: "empty_response", message: baseMessage, retryable: false, cause };
6990
+ }
6991
+ if (/^tool failed: /i.test(baseMessage)) {
6992
+ return { kind: "tool_failed", message: baseMessage, retryable: false, cause };
6993
+ }
6994
+ if (lower.includes("bridge transport") || /bridge.*(closed|disconnect)/i.test(baseMessage)) {
6995
+ return { kind: "bridge_failed", message: baseMessage, retryable: false, cause };
6996
+ }
6997
+ if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {
6998
+ return { kind: "context_overflow", message: baseMessage, retryable: false, cause };
6999
+ }
7000
+ return {
7001
+ kind: "unknown",
7002
+ message: baseMessage,
7003
+ retryable: false,
7004
+ cause
7005
+ };
7006
+ }
7007
+ function providerErrorToSubagentError(err, message, cause) {
7008
+ const status = err.status;
7009
+ if (status === 429 || err.body?.type === "rate_limit_error") {
7010
+ return {
7011
+ kind: "provider_rate_limit",
7012
+ message,
7013
+ retryable: true,
7014
+ // Conservative default: 5s. Provider-specific code can override
7015
+ // by emitting an error whose body carries an explicit hint.
7016
+ backoffMs: 5e3,
7017
+ cause
7018
+ };
7019
+ }
7020
+ if (status === 401 || status === 403 || err.body?.type === "authentication_error") {
7021
+ return { kind: "provider_auth", message, retryable: false, cause };
7022
+ }
7023
+ if (status === 408 || status === 0) {
7024
+ return { kind: "provider_timeout", message, retryable: true, cause };
7025
+ }
7026
+ if (status >= 500 && status < 600) {
7027
+ return {
7028
+ kind: "provider_5xx",
7029
+ message,
7030
+ retryable: true,
7031
+ backoffMs: 3e3,
7032
+ cause
7033
+ };
7034
+ }
7035
+ return { kind: "unknown", message, retryable: err.retryable, cause };
7036
+ }
7037
+
7038
+ // src/execution/parallel-eternal-engine.ts
7039
+ function sleep2(ms) {
7040
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
7041
+ }
7042
+ var GOAL_COMPLETE_MARKER2 = /^\s*\[goal[_\s-]?complete\]\s*$/im;
7043
+ var ParallelEternalEngine = class {
7044
+ constructor(opts) {
7045
+ this.opts = opts;
7046
+ this.goalPath = goalFilePath(opts.projectRoot);
7047
+ this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));
7048
+ this.timeoutMs = opts.iterationTimeoutMs ?? 3e5;
7049
+ this.agentFactory = opts.subagentFactory ?? (async (config) => ({
7050
+ agent: this.opts.agent,
7051
+ events: this.opts.agent.events
7052
+ }));
7053
+ }
7054
+ opts;
7055
+ state = "idle";
7056
+ stopRequested = false;
7057
+ iterationsSinceCompact = 0;
7058
+ iterations = 0;
7059
+ consecutiveFailures = 0;
7060
+ goalPath;
7061
+ slots;
7062
+ timeoutMs;
7063
+ coordinator = null;
7064
+ agentFactory;
7065
+ get currentState() {
7066
+ return this.state;
7067
+ }
7068
+ stop() {
7069
+ this.stopRequested = true;
7070
+ void this.persistState("stopped").catch(() => {
7071
+ });
7072
+ this.state = "stopped";
7073
+ }
7074
+ async prime() {
7075
+ this.stopRequested = false;
7076
+ this.state = "running";
7077
+ await this.persistState("running");
7078
+ }
7079
+ async run() {
7080
+ this.state = "running";
7081
+ await this.persistState("running");
7082
+ const config = {
7083
+ coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,
7084
+ maxConcurrent: this.slots,
7085
+ doneCondition: { type: "all_tasks_done" }
7086
+ };
7087
+ this.coordinator = new DefaultMultiAgentCoordinator(config);
7088
+ const runner = makeAgentSubagentRunner({ factory: this.agentFactory });
7089
+ this.coordinator.setRunner?.(runner);
7090
+ try {
7091
+ while (!this.stopRequested) {
7092
+ try {
7093
+ await this.runOneIteration();
7094
+ } catch (err) {
7095
+ this.consecutiveFailures++;
7096
+ this.opts.onError?.(err instanceof Error ? err : new Error(String(err)), this.consecutiveFailures);
7097
+ await this.appendFailure("engine error", err instanceof Error ? err.message : String(err));
7098
+ }
7099
+ if (this.stopRequested) break;
7100
+ await sleep2(2e3);
7101
+ }
7102
+ } finally {
7103
+ this.state = "stopped";
7104
+ await this.persistState("stopped").catch(() => {
7105
+ });
7106
+ }
7107
+ }
7108
+ /**
7109
+ * Execute one tick: decompose → fan-out → aggregate → compact.
7110
+ * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).
7111
+ */
7112
+ async runOneIteration() {
7113
+ this.iterations++;
7114
+ const goal = await loadGoal(this.goalPath);
7115
+ if (!goal) {
7116
+ this.stopRequested = true;
7117
+ return false;
7118
+ }
7119
+ if (goal.goalState !== "active") {
7120
+ this.stopRequested = true;
7121
+ return false;
7122
+ }
7123
+ if (!this.coordinator) {
7124
+ const config = {
7125
+ coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,
7126
+ maxConcurrent: this.slots,
7127
+ doneCondition: { type: "all_tasks_done" }
7128
+ };
7129
+ this.coordinator = new DefaultMultiAgentCoordinator(config);
7130
+ const runner = makeAgentSubagentRunner({ factory: this.agentFactory });
7131
+ this.coordinator.setRunner?.(runner);
7132
+ }
7133
+ const tasks = await this.decomposeGoal(goal);
7134
+ if (!tasks || tasks.length === 0) {
7135
+ await sleep2(5e3);
7136
+ return false;
7137
+ }
7138
+ const fanOut = await this.fanOut(goal, tasks);
7139
+ this.iterationsSinceCompact++;
7140
+ const successCount = fanOut.results.filter((r) => r.status === "success").length;
7141
+ const status = fanOut.goalComplete ? "success" : fanOut.allSuccessful ? "success" : "failure";
7142
+ const note = [
7143
+ `${successCount}/${fanOut.results.length} subagents succeeded`,
7144
+ fanOut.goalComplete ? "[GOAL_COMPLETE]" : "",
7145
+ fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : ""
7146
+ ].filter(Boolean).join(" | ");
7147
+ await this.appendIterationEntry({
7148
+ source: "parallel",
7149
+ task: `parallel:${tasks.length} slots \u2014 ${tasks.slice(0, 3).join(", ")}${tasks.length > 3 ? "..." : ""}`,
7150
+ status,
7151
+ note
7152
+ });
7153
+ if (fanOut.goalComplete) {
7154
+ this.stopRequested = true;
7155
+ return true;
7156
+ }
7157
+ await this.maybeCompact();
7158
+ return fanOut.allSuccessful;
7159
+ }
7160
+ // -------------------------------------------------------------------------
7161
+ // Fan-out
7162
+ // -------------------------------------------------------------------------
7163
+ async fanOut(goal, tasks) {
7164
+ const coordinator = this.coordinator;
7165
+ const slotCount = Math.min(this.slots, tasks.length);
7166
+ const recentJournal = goal.journal.slice(-5).map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` \u2014 ${e.note.slice(0, 80)}` : ""}`).join("\n");
7167
+ const directivePreamble = [
7168
+ "\u2550\u2550\u2550 ETERNAL AUTONOMY \u2014 parallel task slot \u2550\u2550\u2550",
7169
+ "",
7170
+ `Mission: ${goal.goal}`,
7171
+ `Total parallel slots: ${slotCount}`,
7172
+ "",
7173
+ recentJournal ? `Recent journal (last 5):
7174
+ ${recentJournal}` : "No prior iterations.",
7175
+ "",
7176
+ "\u2500\u2500 EXECUTION PROTOCOL \u2500\u2500",
7177
+ "\u2022 Execute the assigned task end-to-end using multiple tool calls.",
7178
+ "\u2022 Emit `[done]` on its own line when the task is complete.",
7179
+ "\u2022 Do not ask for confirmation \u2014 YOLO is active.",
7180
+ "\u2022 If the overall Mission is accomplished, emit `[GOAL_COMPLETE]` followed by a verification recipe.",
7181
+ "\u2022 Keep output concise \u2014 summarize findings, do not transcribe files."
7182
+ ].join("\n");
7183
+ const taskIds = [];
7184
+ const subagentIds = [];
7185
+ const spawnPromises = [];
7186
+ for (let i = 0; i < slotCount; i++) {
7187
+ const task = tasks[i];
7188
+ const subagentId = `parallel-${this.iterations}-${i}`;
7189
+ const taskId = randomUUID();
7190
+ const spec = {
7191
+ id: taskId,
7192
+ description: `${directivePreamble}
7193
+
7194
+ \u2500\u2500 SLOT ${i + 1}/${slotCount} \u2500\u2500
7195
+ Task: ${task}
7196
+ `,
7197
+ subagentId
7198
+ };
7199
+ spawnPromises.push((async () => {
7200
+ try {
7201
+ await coordinator.spawn({
7202
+ id: subagentId,
7203
+ name: `slot-${subagentId.slice(-6)}`,
7204
+ maxIterations: 50,
7205
+ maxToolCalls: 200,
7206
+ timeoutMs: this.timeoutMs
7207
+ });
7208
+ subagentIds.push(subagentId);
7209
+ taskIds.push(taskId);
7210
+ await coordinator.assign(spec);
7211
+ } catch {
7212
+ }
7213
+ })());
7214
+ }
7215
+ await Promise.all(spawnPromises);
7216
+ if (taskIds.length === 0) {
7217
+ return { results: [], allSuccessful: false, goalComplete: false, partialOutput: "" };
7218
+ }
7219
+ let results = [];
7220
+ try {
7221
+ const ctrl = new AbortController();
7222
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs + 6e4);
7223
+ try {
7224
+ results = await coordinator.awaitTasks(taskIds);
7225
+ } finally {
7226
+ clearTimeout(timer);
7227
+ }
7228
+ } catch {
7229
+ results = coordinator.results().slice(-taskIds.length);
7230
+ }
7231
+ const allSuccessful = results.length > 0 && results.every((r) => r.status === "success");
7232
+ const goalComplete = results.some(
7233
+ (r) => r.status === "success" && typeof r.result === "string" && GOAL_COMPLETE_MARKER2.test(r.result)
7234
+ );
7235
+ const partialOutput = results.map((r) => typeof r.result === "string" ? r.result : "").filter(Boolean).join("\n\n");
7236
+ return { results, allSuccessful, goalComplete, partialOutput };
7237
+ }
7238
+ // -------------------------------------------------------------------------
7239
+ // Goal decomposition
7240
+ // -------------------------------------------------------------------------
7241
+ async decomposeGoal(goal) {
7242
+ const todos = this.opts.agent.ctx?.todos;
7243
+ const tasks = [];
7244
+ if (Array.isArray(todos)) {
7245
+ const pending = todos.filter((t) => t.status === "pending").slice(0, this.slots);
7246
+ for (const t of pending) {
7247
+ tasks.push(`[todo] ${t.content}`);
7248
+ }
7249
+ }
7250
+ if (tasks.length < this.slots) {
7251
+ try {
7252
+ const gitStatus = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());
7253
+ const dirty = gitStatus.trim();
7254
+ if (dirty) {
7255
+ const lines = dirty.split("\n").slice(0, this.slots - tasks.length);
7256
+ for (const line of lines) {
7257
+ const file = line.replace(/^[ MADRUC?]{2}\s*/, "").trim();
7258
+ if (file) tasks.push(`[git] inspect and fix: ${file}`);
7259
+ }
7260
+ }
7261
+ } catch {
7262
+ }
7263
+ }
7264
+ if (tasks.length < this.slots) {
7265
+ const remaining = this.slots - tasks.length;
7266
+ const brainstormed = await this.brainstormSubtasks(goal, remaining);
7267
+ tasks.push(...brainstormed);
7268
+ }
7269
+ return tasks.length > 0 ? tasks.slice(0, this.slots) : null;
7270
+ }
7271
+ async readGitStatus() {
7272
+ const { execFile: execFile2 } = await import('child_process');
7273
+ const { promisify: promisify2 } = await import('util');
7274
+ const execFileP2 = promisify2(execFile2);
7275
+ const { stdout } = await execFileP2("git", ["status", "--porcelain"], {
7276
+ cwd: this.opts.projectRoot,
7277
+ timeout: 5e3
7278
+ });
7279
+ return stdout;
7280
+ }
7281
+ async brainstormSubtasks(goal, count) {
7282
+ const lastFew = goal.journal.slice(-5).map((e) => ` - [${e.status}] ${e.task}`).join("\n");
7283
+ const directive = [
7284
+ `Decompose this goal into exactly ${count} independent sub-tasks for parallel execution.`,
7285
+ "",
7286
+ `Goal: ${goal.goal}`,
7287
+ "",
7288
+ lastFew ? `Recent:
7289
+ ${lastFew}` : "No prior iterations.",
7290
+ "",
7291
+ `Output exactly ${count} tasks, one per line, under 120 chars each.`,
7292
+ "Format: TASK-1 | TASK-2 | ... (pipe-separated, no numbering, no preamble).",
7293
+ "Each task must be independently actionable with no shared dependencies."
7294
+ ].join("\n");
7295
+ try {
7296
+ const ctrl = new AbortController();
7297
+ const timer = setTimeout(() => ctrl.abort(), 6e4);
7298
+ try {
7299
+ const result = await this.opts.agent.run([{ type: "text", text: directive }], {
7300
+ signal: ctrl.signal,
7301
+ maxIterations: 1
7302
+ });
7303
+ if (result.status !== "done") return [];
7304
+ const text = (result.finalText ?? "").trim();
7305
+ if (!text) return [];
7306
+ const tasks = text.split("|").map((t) => t.trim()).filter((t) => t.length > 10 && t.length < 240);
7307
+ return tasks.slice(0, count);
7308
+ } finally {
7309
+ clearTimeout(timer);
7310
+ }
7311
+ } catch {
7312
+ return [];
7313
+ }
7314
+ }
7315
+ // -------------------------------------------------------------------------
7316
+ // Compaction
7317
+ // -------------------------------------------------------------------------
7318
+ async maybeCompact() {
7319
+ const compactor = this.opts.compactor;
7320
+ if (!compactor) return;
7321
+ const ctx = this.opts.agent.ctx;
7322
+ if (!ctx) return;
7323
+ const shouldRun = this.iterationsSinceCompact >= (this.opts.compactEveryNIterations ?? 25);
7324
+ if (!shouldRun) return;
7325
+ const report = await compactor.compact(ctx, { aggressive: false });
7326
+ this.iterationsSinceCompact = 0;
7327
+ await this.appendIterationEntry({
7328
+ source: "manual",
7329
+ task: "compaction (cadence)",
7330
+ status: "success",
7331
+ note: `saved ~${report.before - report.after} tokens`
7332
+ });
7333
+ }
7334
+ // -------------------------------------------------------------------------
7335
+ // Helpers
7336
+ // -------------------------------------------------------------------------
7337
+ async appendIterationEntry(entry) {
7338
+ const current = await loadGoal(this.goalPath);
7339
+ if (!current) return;
7340
+ const updated = appendJournal(current, entry);
7341
+ await saveGoal(this.goalPath, updated);
7342
+ const entryWithMeta = {
7343
+ at: (this.opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
7344
+ iteration: updated.iterations,
7345
+ ...entry
7346
+ };
7347
+ this.opts.onIteration?.(entryWithMeta);
7348
+ }
7349
+ async appendFailure(task, note) {
7350
+ await this.appendIterationEntry({ source: "manual", task, status: "failure", note });
7351
+ }
7352
+ async persistState(state) {
7353
+ const current = await loadGoal(this.goalPath);
7354
+ if (!current) return;
7355
+ if (current.engineState === state) return;
7356
+ await saveGoal(this.goalPath, { ...current, engineState: state });
7357
+ }
7358
+ };
7359
+
7360
+ // src/execution/autonomy-prompt-contributor.ts
7361
+ function makeAutonomyPromptContributor(opts) {
7362
+ return async (ctx) => {
7363
+ if (ctx.subagent) return [];
7364
+ if (!opts.enabled()) return [];
7365
+ let goal;
7366
+ try {
7367
+ goal = await loadGoal(opts.goalPath);
7368
+ } catch {
7369
+ return [];
7370
+ }
7371
+ if (!goal) return [];
7372
+ const missionState = goal.goalState ?? "active";
7373
+ if (missionState !== "active") return [];
7374
+ const tailSize = opts.journalTailSize ?? 5;
7375
+ const journalTail = goal.journal.slice(-tailSize).map((e) => {
7376
+ const note = e.note ? ` \u2014 ${e.note.slice(0, 80)}` : "";
7377
+ return ` #${e.iteration} [${e.status}] ${e.task}${note}`;
7378
+ });
7379
+ const text = [
7380
+ "## ETERNAL AUTONOMY \u2014 active mission",
7381
+ "",
7382
+ "You are inside a long-running autonomous loop. The user is asleep",
7383
+ "and is not available to confirm decisions. Each turn you receive a",
7384
+ "directive describing one concrete sub-task that advances the mission.",
7385
+ "",
7386
+ `Mission: ${goal.goal}`,
7387
+ `Iteration: #${goal.iterations}`,
7388
+ journalTail.length > 0 ? `Recent journal (last ${journalTail.length}):
7389
+ ${journalTail.join("\n")}` : "Recent journal: (none \u2014 this is the first iteration)",
7390
+ "",
7391
+ "### Loop control markers",
7392
+ "Emit these on their own line in your final text \u2014 case-insensitive,",
7393
+ "whitespace-tolerant, but they must occupy the entire line:",
7394
+ "- `[continue]` \u2014 chain to the next internal step without returning.",
7395
+ "- `[done]` \u2014 the current sub-task is finished; return to the engine.",
7396
+ "- `[GOAL_COMPLETE]` \u2014 emit ONLY when the OVERALL mission is",
7397
+ " verifiably done. Must be followed by a one-paragraph verification",
7398
+ " recipe (artifact path, test command, or 10-second reproduction).",
7399
+ " The engine halts on this marker \u2014 false positives waste real",
7400
+ " human time. If unsure, emit `[done]` and let the next iteration",
7401
+ " decide.",
7402
+ "",
7403
+ "### Operating principles",
7404
+ "- YOLO is active. Do NOT ask for confirmation, do NOT propose",
7405
+ " options. Pick the best path and execute it.",
7406
+ "- Use tools freely; multiple calls per turn are normal and expected.",
7407
+ "- When working on a todo, mark it `in_progress` via the todos tool",
7408
+ " before tool work and `completed` (or `cancelled` with a reason)",
7409
+ " when done. The loop reads todo state between iterations.",
7410
+ "- If an approach fails twice in a row, pivot. Don't grind on the",
7411
+ " same wall \u2014 try a different angle, file a cancel on the todo, or",
7412
+ " surface the obstacle via `[done]` and let the next iteration",
7413
+ " re-plan."
7414
+ ].join("\n");
7415
+ return [
7416
+ {
7417
+ type: "text",
7418
+ text,
7419
+ cache_control: { type: "ephemeral" }
7420
+ }
7421
+ ];
7422
+ };
7423
+ }
7424
+
7425
+ // src/execution/goal-preamble.ts
7426
+ function buildGoalPreamble(goal) {
7427
+ return [
7428
+ "[GOAL \u2014 LOCKED IN. You will work on this until it is verifiably done.",
7429
+ "The user granted you full autonomy. Read these constraints once, then act.",
7430
+ "",
7431
+ "YOUR GOAL:",
7432
+ "---",
7433
+ goal,
7434
+ "---",
7435
+ "",
7436
+ "AUTHORITY YOU HAVE:",
7437
+ "- Spawn as many subagents as the work needs (delegate / spawn_subagent).",
7438
+ " Parallel + recursive fan-out are both fine. There is no spawn budget.",
7439
+ "- Use any provider/model per subagent \u2014 pick the right tool for each",
7440
+ " piece of work. Heavy reasoning model for planning, fast model for",
7441
+ " batch work, specialist model for domain code.",
7442
+ "- Run unlimited tool calls and iterations. There is NO hidden budget.",
7443
+ " The Agent loop auto-extends every 100 iterations forever.",
7444
+ "- Retry failed tools with different inputs, alternative paths, fresh",
7445
+ " subagents. Switch providers mid-run if one is rate-limited.",
7446
+ "- Re-plan freely when an approach hits a dead end. You are not obliged",
7447
+ " to stick with the first plan you proposed.",
7448
+ "",
7449
+ 'WHAT "DONE" MEANS \u2014 non-negotiable:',
7450
+ "- You can name a concrete artifact (a passing test, a written file at",
7451
+ " a specific path, a fixed bug verified by re-running the failing case,",
7452
+ " a clean grep that previously had matches).",
7453
+ "- You can tell the user HOW to verify it themselves in 10 seconds.",
7454
+ '- You have NOT hedged. None of: "looks like it should work", "I',
7455
+ ' believe this fixes it", "the changes appear correct".',
7456
+ "",
7457
+ "WHAT IS NOT DONE \u2014 never report any of these as completion:",
7458
+ "- An error message you didn't recover from.",
7459
+ '- An empty result, a 0-line file, a "no matches found" you accepted',
7460
+ " without questioning the search.",
7461
+ '- "Should I continue?" / "Want me to also...?" / "Let me know if you',
7462
+ ' want X." Those are hedges. The user already told you to finish the',
7463
+ " goal \u2014 just do it.",
7464
+ "- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%",
7465
+ " done, not done.",
7466
+ "- A subagent's failed/timeout/stopped TaskResult that you didn't",
7467
+ " respond to with a fresh attempt (different role, different model,",
7468
+ " tighter prompt).",
7469
+ "",
7470
+ "PERSISTENCE PROTOCOL:",
7471
+ "- If blocked, try at least 3 different angles before reporting the",
7472
+ " problem to the user. Different tool inputs, different subagent",
7473
+ " roles, different providers, different decomposition of the task.",
7474
+ "- If a tool fails, read its error, alter the input, try again. Do",
7475
+ " not just report the failure back.",
7476
+ "- If a subagent returns useless output, respawn with a tighter prompt",
7477
+ ' or a different role. Do not accept "I could not determine\u2026" as the',
7478
+ " final answer.",
7479
+ "- Use `ask_subagent` for one-shot questions when you don't need a",
7480
+ " full delegated task.",
7481
+ "",
7482
+ "REPORTING:",
7483
+ "- Stream short progress notes between major actions so the user can",
7484
+ " monitor. Do not go silent for 50 tool calls then dump a wall of",
7485
+ " text \u2014 but also do not narrate every tool call.",
7486
+ "- Use the shared scratchpad (if available) to leave breadcrumbs",
7487
+ " subagents can read.",
7488
+ "- Final response must include: (a) what was accomplished, (b) how",
7489
+ " to verify, (c) any caveats (residual TODOs, things the user",
7490
+ " should know about).",
7491
+ "",
7492
+ "BEGIN.]"
7493
+ ].join("\n");
7494
+ }
7495
+
7496
+ // src/coordination/director.ts
7497
+ init_atomic_write();
7498
+
7499
+ // src/coordination/in-memory-transport.ts
7500
+ var InMemoryBridgeTransport = class {
7501
+ subs = /* @__PURE__ */ new Map();
7502
+ send(msg, to) {
7503
+ if (to === "*") {
7504
+ for (const [id, handlers2] of this.subs) {
7505
+ if (id === msg.from) continue;
7506
+ for (const h of handlers2) {
7507
+ try {
7508
+ h(msg);
7509
+ } catch {
7510
+ }
7511
+ }
7512
+ }
7513
+ return Promise.resolve();
7514
+ }
7515
+ const handlers = this.subs.get(to);
7516
+ if (handlers) {
7517
+ for (const h of handlers) {
7518
+ try {
7519
+ h(msg);
7520
+ } catch {
7521
+ }
7522
+ }
7523
+ }
7524
+ return Promise.resolve();
7525
+ }
7526
+ subscribe(agentId, handler) {
7527
+ if (!this.subs.has(agentId)) this.subs.set(agentId, /* @__PURE__ */ new Set());
7528
+ this.subs.get(agentId).add(handler);
7529
+ return () => this.subs.get(agentId)?.delete(handler);
7530
+ }
7531
+ close(agentId) {
7532
+ this.subs.delete(agentId);
7533
+ return Promise.resolve();
7534
+ }
7535
+ };
7536
+
7537
+ // src/coordination/agent-bridge.ts
7538
+ var InMemoryAgentBridge = class {
7539
+ agentId;
7540
+ coordinatorId;
7541
+ transport;
7542
+ subscriptions = /* @__PURE__ */ new Set();
7543
+ pendingRequests = /* @__PURE__ */ new Map();
7544
+ stopped = false;
7545
+ timeoutMs;
7546
+ /** Guards request() so concurrent calls on the same id can't silently overwrite. */
7547
+ inflightGuards = /* @__PURE__ */ new Set();
7548
+ constructor(config, transport) {
7549
+ this.agentId = config.agentId;
7550
+ this.coordinatorId = config.coordinatorId;
7551
+ this.transport = transport;
7552
+ this.timeoutMs = config.timeoutMs ?? 3e4;
7553
+ this.transport.subscribe(this.agentId, (msg) => {
7554
+ if (msg.type === "heartbeat") return;
7555
+ const pending = this.pendingRequests.get(msg.id);
7556
+ if (pending) {
7557
+ clearTimeout(pending.timer);
7558
+ this.pendingRequests.delete(msg.id);
7559
+ this.inflightGuards.delete(msg.id);
7560
+ pending.resolve(msg);
7561
+ return;
7562
+ }
7563
+ for (const h of this.subscriptions) {
7564
+ try {
7565
+ h(msg);
7566
+ } catch {
7567
+ }
7568
+ }
7569
+ });
7570
+ }
7571
+ async send(msg) {
7572
+ msg.timestamp = Date.now();
7573
+ await this.transport.send(msg, msg.to ?? this.coordinatorId);
7574
+ }
7575
+ async broadcast(msg) {
7576
+ msg.timestamp = Date.now();
7577
+ msg.to = "*";
7578
+ await this.transport.send(msg, "*");
7579
+ }
7580
+ subscribe(handler) {
7581
+ this.subscriptions.add(handler);
7582
+ return () => this.subscriptions.delete(handler);
7583
+ }
7584
+ async request(msg, timeoutMs) {
7585
+ if (this.stopped) throw new Error("Bridge is stopped");
7586
+ const timeout = timeoutMs ?? this.timeoutMs;
7587
+ const correlationId = msg.id;
7588
+ if (this.inflightGuards.has(correlationId)) {
7589
+ throw new Error(
7590
+ `Bridge request id "${correlationId}" collides with an in-flight request \u2014 caller is reusing message ids`
7591
+ );
7592
+ }
7593
+ this.inflightGuards.add(correlationId);
7594
+ return new Promise((resolve2, reject) => {
7595
+ const timer = setTimeout(() => {
7596
+ this.inflightGuards.delete(correlationId);
7597
+ this.pendingRequests.delete(correlationId);
7598
+ reject(new Error(`Request ${correlationId} timed out after ${timeout}ms`));
7599
+ }, timeout);
7600
+ if (this.stopped) {
7601
+ clearTimeout(timer);
7602
+ this.inflightGuards.delete(correlationId);
7603
+ this.pendingRequests.delete(correlationId);
7604
+ reject(new Error("Bridge stopped"));
7605
+ return;
7606
+ }
7607
+ this.pendingRequests.set(correlationId, {
7608
+ resolve: resolve2,
7609
+ reject,
7610
+ timer
7243
7611
  });
7244
- }
7612
+ msg.timestamp = Date.now();
7613
+ this.transport.send(msg, msg.to ?? this.coordinatorId).catch((e) => {
7614
+ clearTimeout(timer);
7615
+ this.inflightGuards.delete(correlationId);
7616
+ this.pendingRequests.delete(correlationId);
7617
+ reject(e);
7618
+ });
7619
+ });
7245
7620
  }
7246
- isDone() {
7247
- if (this.config.doneCondition.type === "all_tasks_done") {
7248
- return this.pendingTasks.length === 0 && this.inFlight === 0;
7249
- }
7250
- if (this.config.doneCondition.maxIterations !== void 0 && this.totalIterations >= this.config.doneCondition.maxIterations) {
7251
- return true;
7621
+ async stop() {
7622
+ this.stopped = true;
7623
+ for (const [, p] of this.pendingRequests) {
7624
+ clearTimeout(p.timer);
7625
+ p.reject(new Error("Bridge stopped"));
7252
7626
  }
7253
- return false;
7627
+ this.pendingRequests.clear();
7628
+ this.inflightGuards.clear();
7629
+ this.subscriptions.clear();
7630
+ await this.transport.close(this.agentId);
7254
7631
  }
7255
7632
  };
7256
- function classifySubagentError(err, hints = {}) {
7257
- const cause = err instanceof Error ? { name: err.name, message: err.message, stack: err.stack } : void 0;
7258
- if (err instanceof ProviderError) {
7259
- const baseMessage2 = err.describe();
7260
- return providerErrorToSubagentError(err, baseMessage2, cause);
7633
+ function createMessage(type, from, payload, to) {
7634
+ return {
7635
+ id: randomUUID(),
7636
+ type,
7637
+ from,
7638
+ to,
7639
+ payload,
7640
+ timestamp: Date.now(),
7641
+ priority: "normal"
7642
+ };
7643
+ }
7644
+
7645
+ // src/coordination/director-prompts.ts
7646
+ var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
7647
+ subagents by spawning them, assigning tasks, awaiting completions, and
7648
+ rolling up their outputs into your next decision.
7649
+
7650
+ Core fleet tools available to you:
7651
+ - spawn_subagent \u2014 create a worker with a chosen provider / model / role
7652
+ - assign_task \u2014 hand a piece of work to a specific subagent
7653
+ - await_tasks \u2014 block until named task ids complete (parallel-safe)
7654
+ - ask_subagent \u2014 synchronously query a running subagent via the bridge
7655
+ - roll_up \u2014 aggregate finished tasks into a markdown/json summary
7656
+ - terminate_subagent \u2014 abort a stuck worker (use sparingly)
7657
+ - fleet_status \u2014 snapshot of all subagents and pending tasks
7658
+ - fleet_usage \u2014 token + cost breakdown per subagent and total
7659
+
7660
+ Working rules:
7661
+ 1. Decompose first. Before spawning, decide which sub-tasks are
7662
+ independent and can run in parallel. Sequential work doesn't need a
7663
+ subagent \u2014 do it yourself.
7664
+ 2. Match worker to job. Cheap/fast model for triage, capable model for
7665
+ synthesis. Different providers per sibling is allowed and encouraged.
7666
+ 3. Always pair an assign with an await. Don't fire-and-forget; you owe
7667
+ the user a single coherent answer at the end.
7668
+ 4. Roll up before deciding. After await_tasks resolves, call roll_up so
7669
+ the results are folded back into your context in a compact form.
7670
+ 5. Budget is real. Check fleet_usage periodically. If a subagent is
7671
+ thrashing, terminate it rather than letting cost climb silently.
7672
+ 6. Never claim a subagent's work as your own without verifying it. If a
7673
+ result looks wrong, ask_subagent for clarification before passing it
7674
+ to the user.`;
7675
+ var DEFAULT_SUBAGENT_BASELINE = `You are a subagent operating under a Director. You were spawned to handle
7676
+ a specific slice of a larger plan \u2014 do that slice well and report back.
7677
+
7678
+ Bridge contract:
7679
+ - You have a parent (the Director). You may call \`request\` on the
7680
+ parent bridge to ask a clarifying question. Use this sparingly; the
7681
+ parent is also working.
7682
+ - You MAY NOT request the parent's system prompt, tool list, or other
7683
+ subagents' context. Those are not yours to read.
7684
+ - Your final task output is what the Director sees. Be concise,
7685
+ structured, and self-contained \u2014 assume the Director will paste your
7686
+ output into its own context.`;
7687
+ function composeDirectorPrompt(parts = {}) {
7688
+ const sections = [];
7689
+ const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
7690
+ if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());
7691
+ if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {
7692
+ sections.push(`Available roles you can spawn:
7693
+ ${parts.rosterSummary.trim()}`);
7261
7694
  }
7262
- const baseMessage = err instanceof Error ? err.message : String(err);
7263
- if (err instanceof BudgetExceededError) {
7264
- const map = {
7265
- iterations: "budget_iterations",
7266
- tool_calls: "budget_tool_calls",
7267
- tokens: "budget_tokens",
7268
- cost: "budget_cost",
7269
- timeout: "budget_timeout"
7270
- };
7271
- return {
7272
- kind: map[err.kind],
7273
- message: baseMessage,
7274
- // Budgets are user-configured ceilings, not transient failures —
7275
- // retrying with the same budget will hit the same ceiling. The
7276
- // orchestrator must raise the budget or narrow the task first.
7277
- retryable: false,
7278
- cause
7279
- };
7695
+ if (parts.basePrompt && parts.basePrompt.trim().length > 0) {
7696
+ sections.push(parts.basePrompt.trim());
7280
7697
  }
7281
- if (hints.parentAborted) {
7282
- return {
7283
- kind: "aborted_by_parent",
7284
- message: baseMessage,
7285
- retryable: false,
7286
- cause
7287
- };
7698
+ return sections.join("\n\n");
7699
+ }
7700
+ function composeSubagentPrompt(parts = {}) {
7701
+ const sections = [];
7702
+ const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;
7703
+ if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());
7704
+ if (parts.role && parts.role.trim().length > 0) {
7705
+ sections.push(`Role:
7706
+ ${parts.role.trim()}`);
7288
7707
  }
7289
- const lower = baseMessage.toLowerCase();
7290
- if (/agent aborted$/i.test(baseMessage)) {
7291
- return {
7292
- kind: "aborted_by_parent",
7293
- message: baseMessage,
7294
- retryable: false,
7295
- cause
7708
+ if (parts.task && parts.task.trim().length > 0) {
7709
+ sections.push(`Task:
7710
+ ${parts.task.trim()}`);
7711
+ }
7712
+ if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {
7713
+ sections.push(
7714
+ `Shared notes:
7715
+ A scratchpad shared with the rest of the fleet is mounted at \`${parts.sharedScratchpad.trim()}\`.
7716
+ - Write your final findings as markdown files there (e.g. \`findings.md\`, \`security.md\`).
7717
+ - Before starting, list the directory and read any sibling files relevant to your task \u2014 they may already contain context you can build on.
7718
+ - Use stable filenames (one file per concern); overwrite instead of appending so the Director sees the latest state.`
7719
+ );
7720
+ }
7721
+ if (parts.override && parts.override.trim().length > 0) {
7722
+ sections.push(parts.override.trim());
7723
+ }
7724
+ return sections.join("\n\n");
7725
+ }
7726
+ function rosterSummaryFromConfigs(roster) {
7727
+ const lines = [];
7728
+ for (const [roleId, cfg] of Object.entries(roster)) {
7729
+ const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : "";
7730
+ const headline = cfg.prompt ? (cfg.prompt.split("\n").find((l) => l.trim().length > 0) ?? "").trim().slice(0, 80) : "";
7731
+ const tail = headline ? ` \u2014 ${headline}` : "";
7732
+ lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);
7733
+ }
7734
+ return lines.join("\n");
7735
+ }
7736
+
7737
+ // src/coordination/fleet-bus.ts
7738
+ var FleetBus = class {
7739
+ byId = /* @__PURE__ */ new Map();
7740
+ byType = /* @__PURE__ */ new Map();
7741
+ any = /* @__PURE__ */ new Set();
7742
+ /**
7743
+ * Hook a subagent's EventBus into the fleet. EventBus is strongly
7744
+ * typed and doesn't expose an `onAny` hook, so we subscribe to the
7745
+ * canonical set of event types a subagent emits during a run. New
7746
+ * event types added to the kernel must be added here too — but the
7747
+ * cost is a tiny single line per type, and the explicit list keeps
7748
+ * the wire format clear.
7749
+ *
7750
+ * Returns a disposer that detaches every subscription; call on
7751
+ * subagent teardown so the listeners don't outlive the run.
7752
+ */
7753
+ attach(subagentId, bus, taskId) {
7754
+ const off = bus.onPattern("*", (type, payload) => {
7755
+ if (type.startsWith("subagent.")) return;
7756
+ this.emit({ subagentId, taskId, ts: Date.now(), type, payload });
7757
+ });
7758
+ return () => {
7759
+ off();
7296
7760
  };
7297
7761
  }
7298
- if (/agent exhausted iteration limit$/i.test(baseMessage)) {
7299
- return { kind: "budget_iterations", message: baseMessage, retryable: false, cause };
7762
+ /** Subscribe to every event from one subagent. */
7763
+ subscribe(subagentId, handler) {
7764
+ let set = this.byId.get(subagentId);
7765
+ if (!set) {
7766
+ set = /* @__PURE__ */ new Set();
7767
+ this.byId.set(subagentId, set);
7768
+ }
7769
+ set.add(handler);
7770
+ return () => {
7771
+ set.delete(handler);
7772
+ };
7300
7773
  }
7301
- if (/empty response$/i.test(baseMessage)) {
7302
- return { kind: "empty_response", message: baseMessage, retryable: false, cause };
7774
+ /** Subscribe to one event type across all subagents. */
7775
+ filter(type, handler) {
7776
+ let set = this.byType.get(type);
7777
+ if (!set) {
7778
+ set = /* @__PURE__ */ new Set();
7779
+ this.byType.set(type, set);
7780
+ }
7781
+ set.add(handler);
7782
+ return () => {
7783
+ set.delete(handler);
7784
+ };
7303
7785
  }
7304
- if (/^tool failed: /i.test(baseMessage)) {
7305
- return { kind: "tool_failed", message: baseMessage, retryable: false, cause };
7786
+ /** Subscribe to literally everything. The fleet roll-up uses this. */
7787
+ onAny(handler) {
7788
+ this.any.add(handler);
7789
+ return () => {
7790
+ this.any.delete(handler);
7791
+ };
7306
7792
  }
7307
- if (lower.includes("bridge transport") || /bridge.*(closed|disconnect)/i.test(baseMessage)) {
7308
- return { kind: "bridge_failed", message: baseMessage, retryable: false, cause };
7793
+ emit(event) {
7794
+ const byId = this.byId.get(event.subagentId);
7795
+ if (byId)
7796
+ for (const h of byId) {
7797
+ try {
7798
+ h(event);
7799
+ } catch {
7800
+ }
7801
+ }
7802
+ const byType = this.byType.get(event.type);
7803
+ if (byType)
7804
+ for (const h of byType) {
7805
+ try {
7806
+ h(event);
7807
+ } catch {
7808
+ }
7809
+ }
7810
+ for (const h of this.any) {
7811
+ try {
7812
+ h(event);
7813
+ } catch {
7814
+ }
7815
+ }
7309
7816
  }
7310
- if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {
7311
- return { kind: "context_overflow", message: baseMessage, retryable: false, cause };
7817
+ };
7818
+ var FleetUsageAggregator = class {
7819
+ constructor(bus, priceLookup, metaLookup) {
7820
+ this.bus = bus;
7821
+ this.priceLookup = priceLookup;
7822
+ this.metaLookup = metaLookup;
7823
+ bus.filter("provider.response", (e) => this.onProviderResponse(e));
7824
+ bus.filter("tool.executed", (e) => this.onToolExecuted(e));
7825
+ bus.filter("iteration.started", (e) => this.onIterationStarted(e));
7312
7826
  }
7313
- return {
7314
- kind: "unknown",
7315
- message: baseMessage,
7316
- retryable: false,
7317
- cause
7318
- };
7319
- }
7320
- function providerErrorToSubagentError(err, message, cause) {
7321
- const status = err.status;
7322
- if (status === 429 || err.body?.type === "rate_limit_error") {
7827
+ bus;
7828
+ priceLookup;
7829
+ metaLookup;
7830
+ perSubagent = /* @__PURE__ */ new Map();
7831
+ total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
7832
+ /** Live snapshot — safe to call from a tool's execute() body. */
7833
+ snapshot() {
7323
7834
  return {
7324
- kind: "provider_rate_limit",
7325
- message,
7326
- retryable: true,
7327
- // Conservative default: 5s. Provider-specific code can override
7328
- // by emitting an error whose body carries an explicit hint.
7329
- backoffMs: 5e3,
7330
- cause
7835
+ total: { ...this.total },
7836
+ perSubagent: Object.fromEntries(
7837
+ Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }])
7838
+ )
7331
7839
  };
7332
7840
  }
7333
- if (status === 401 || status === 403 || err.body?.type === "authentication_error") {
7334
- return { kind: "provider_auth", message, retryable: false, cause };
7841
+ ensure(subagentId) {
7842
+ let snap = this.perSubagent.get(subagentId);
7843
+ if (!snap) {
7844
+ const meta = this.metaLookup?.(subagentId);
7845
+ snap = {
7846
+ subagentId,
7847
+ provider: meta?.provider,
7848
+ model: meta?.model,
7849
+ input: 0,
7850
+ output: 0,
7851
+ cacheRead: 0,
7852
+ cacheWrite: 0,
7853
+ cost: 0,
7854
+ toolCalls: 0,
7855
+ iterations: 0,
7856
+ startedAt: Date.now(),
7857
+ lastEventAt: Date.now()
7858
+ };
7859
+ this.perSubagent.set(subagentId, snap);
7860
+ }
7861
+ return snap;
7335
7862
  }
7336
- if (status === 408 || status === 0) {
7337
- return { kind: "provider_timeout", message, retryable: true, cause };
7863
+ onProviderResponse(e) {
7864
+ const snap = this.ensure(e.subagentId);
7865
+ const p = e.payload;
7866
+ const usage = p?.usage;
7867
+ if (!usage) return;
7868
+ snap.input += usage.input ?? 0;
7869
+ snap.output += usage.output ?? 0;
7870
+ snap.cacheRead += usage.cacheRead ?? 0;
7871
+ snap.cacheWrite += usage.cacheWrite ?? 0;
7872
+ this.total.input += usage.input ?? 0;
7873
+ this.total.output += usage.output ?? 0;
7874
+ this.total.cacheRead += usage.cacheRead ?? 0;
7875
+ this.total.cacheWrite += usage.cacheWrite ?? 0;
7876
+ const price = this.priceLookup?.(e.subagentId);
7877
+ if (price) {
7878
+ const delta = (usage.input ?? 0) / 1e6 * (price.input ?? 0) + (usage.output ?? 0) / 1e6 * (price.output ?? 0) + (usage.cacheRead ?? 0) / 1e6 * (price.cacheRead ?? 0) + (usage.cacheWrite ?? 0) / 1e6 * (price.cacheWrite ?? 0);
7879
+ snap.cost += delta;
7880
+ this.total.cost += delta;
7881
+ }
7882
+ snap.lastEventAt = e.ts;
7338
7883
  }
7339
- if (status >= 500 && status < 600) {
7340
- return {
7341
- kind: "provider_5xx",
7342
- message,
7343
- retryable: true,
7344
- backoffMs: 3e3,
7345
- cause
7346
- };
7884
+ onToolExecuted(e) {
7885
+ const snap = this.ensure(e.subagentId);
7886
+ snap.toolCalls += 1;
7887
+ snap.lastEventAt = e.ts;
7347
7888
  }
7348
- return { kind: "unknown", message, retryable: err.retryable, cause };
7349
- }
7889
+ onIterationStarted(e) {
7890
+ const snap = this.ensure(e.subagentId);
7891
+ snap.iterations += 1;
7892
+ snap.lastEventAt = e.ts;
7893
+ }
7894
+ };
7350
7895
  function makeSpawnTool(director, roster) {
7351
7896
  const inputSchema = {
7352
7897
  type: "object",
@@ -7727,7 +8272,7 @@ var Director = class {
7727
8272
  this.sessionWriter = opts.sessionWriter ?? null;
7728
8273
  this.manifestDebounceMs = opts.manifestDebounceMs ?? 2e3;
7729
8274
  this.maxFleetCostUsd = opts.directorBudget?.maxCostUsd ?? Number.POSITIVE_INFINITY;
7730
- this.maxBudgetExtensions = opts.maxBudgetExtensions ?? 2;
8275
+ this.maxBudgetExtensions = opts.maxBudgetExtensions ?? 5;
7731
8276
  this.sessionsRoot = opts.sessionsRoot;
7732
8277
  this.directorRunId = opts.directorRunId ?? this.id;
7733
8278
  this.stateCheckpoint = opts.stateCheckpointPath ? new DirectorStateCheckpoint(opts.stateCheckpointPath, {
@@ -7815,19 +8360,19 @@ var Director = class {
7815
8360
  const extra = {};
7816
8361
  switch (payload.kind) {
7817
8362
  case "iterations":
7818
- extra.maxIterations = Math.min(payload.used + 50, 500);
8363
+ extra.maxIterations = Math.min(payload.used + 100, 800);
7819
8364
  break;
7820
8365
  case "tool_calls":
7821
- extra.maxToolCalls = Math.min(Math.ceil(payload.limit * 1.5), 1e3);
8366
+ extra.maxToolCalls = Math.min(Math.ceil(payload.limit * 2), 1500);
7822
8367
  break;
7823
8368
  case "tokens":
7824
- extra.maxTokens = Math.min(Math.ceil(payload.limit * 1.5), 5e5);
8369
+ extra.maxTokens = Math.min(Math.ceil(payload.limit * 2), 8e5);
7825
8370
  break;
7826
8371
  case "cost":
7827
- extra.maxCostUsd = Math.min(payload.limit * 1.5, 10);
8372
+ extra.maxCostUsd = Math.min(payload.limit * 2, 25);
7828
8373
  break;
7829
8374
  case "timeout":
7830
- extra.timeoutMs = Math.min(Math.ceil(payload.limit * 1.5), 60 * 6e4);
8375
+ extra.timeoutMs = Math.min(Math.ceil(payload.limit * 2), 2 * 60 * 6e4);
7831
8376
  break;
7832
8377
  }
7833
8378
  payload.extend(extra);
@@ -8616,136 +9161,6 @@ async function readSubagentPartial(opts, subagentId) {
8616
9161
  }
8617
9162
  return void 0;
8618
9163
  }
8619
-
8620
- // src/coordination/agent-subagent-runner.ts
8621
- function makeAgentSubagentRunner(opts) {
8622
- const format = opts.formatTaskInput ?? defaultFormatTaskInput;
8623
- return async (task, ctx) => {
8624
- const factoryResult = await opts.factory(ctx.config);
8625
- const { agent, events } = factoryResult;
8626
- const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);
8627
- const aborter = new AbortController();
8628
- ctx.budget._events = events;
8629
- ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();
8630
- let budgetError = null;
8631
- const onBudgetError = (err) => {
8632
- if (err instanceof BudgetThresholdSignal) {
8633
- err.decision.then((decision) => {
8634
- if (decision === "stop") {
8635
- budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
8636
- aborter.abort();
8637
- }
8638
- }).catch(() => {
8639
- budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
8640
- aborter.abort();
8641
- });
8642
- return;
8643
- }
8644
- aborter.abort();
8645
- budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
8646
- "tool_calls",
8647
- 0,
8648
- 0
8649
- );
8650
- if (budgetError !== err && err instanceof Error) {
8651
- budgetError.message += ` (caused by: ${err.message})`;
8652
- }
8653
- };
8654
- let lastToolFailed = null;
8655
- const unsub = [];
8656
- unsub.push(
8657
- events.on("tool.executed", (e) => {
8658
- try {
8659
- ctx.budget.recordToolCall();
8660
- } catch (eb) {
8661
- onBudgetError(eb);
8662
- }
8663
- if (e.ok === false) {
8664
- lastToolFailed = e.name;
8665
- } else if (e.ok === true) {
8666
- lastToolFailed = null;
8667
- }
8668
- }),
8669
- events.on("provider.response", (e) => {
8670
- try {
8671
- ctx.budget.recordUsage(e.usage);
8672
- } catch (e2) {
8673
- void onBudgetError(e2);
8674
- }
8675
- }),
8676
- events.on("iteration.started", () => {
8677
- try {
8678
- ctx.budget.recordIteration();
8679
- ctx.budget.checkTimeout();
8680
- } catch (e) {
8681
- void onBudgetError(e);
8682
- }
8683
- }),
8684
- // D3: cooperative timeout enforcement DURING a long tool call.
8685
- // The iteration-loop checkTimeout() only fires between agent
8686
- // iterations — a single `bash sleep 3600` call would otherwise
8687
- // park inside one tool execution while the timeout silently
8688
- // passes, relying solely on the coordinator's hard Promise.race
8689
- // to interrupt. Tools that emit `tool.progress` (bash chunks,
8690
- // fetch byte progress, spawn-stream stdout) give us a heartbeat
8691
- // we can hang the check on. When the budget trips here:
8692
- // 1. onBudgetError sets budgetError + aborter.abort()
8693
- // 2. aborter signal propagates to agent.run → tool executor
8694
- // 3. tool's own signal listener kills the child process
8695
- // Cheap: O(1) per progress event, and the budget short-circuits
8696
- // when timeoutMs is unset (most subagents have one set anyway).
8697
- events.on("tool.progress", () => {
8698
- try {
8699
- ctx.budget.checkTimeout();
8700
- } catch (e) {
8701
- void onBudgetError(e);
8702
- }
8703
- })
8704
- );
8705
- const onParentAbort = () => aborter.abort();
8706
- ctx.signal.addEventListener("abort", onParentAbort);
8707
- let result;
8708
- try {
8709
- result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
8710
- } finally {
8711
- detachFleet?.();
8712
- ctx.signal.removeEventListener("abort", onParentAbort);
8713
- for (const u of unsub) u();
8714
- if (factoryResult.dispose) {
8715
- try {
8716
- await factoryResult.dispose();
8717
- } catch {
8718
- }
8719
- }
8720
- }
8721
- if (budgetError) throw budgetError;
8722
- if (result.status === "failed") {
8723
- throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
8724
- }
8725
- if (result.status === "aborted") {
8726
- throw new Error("agent aborted");
8727
- }
8728
- if (result.status === "max_iterations") {
8729
- throw new Error("agent exhausted iteration limit");
8730
- }
8731
- const usage = ctx.budget.usage();
8732
- const finalText = (result.finalText ?? "").trim();
8733
- if (finalText.length === 0 && usage.toolCalls === 0) {
8734
- throw new Error("empty response");
8735
- }
8736
- if (finalText.length === 0 && lastToolFailed !== null) {
8737
- throw new Error(`tool failed: ${lastToolFailed}`);
8738
- }
8739
- return {
8740
- result: result.finalText,
8741
- iterations: result.iterations,
8742
- toolCalls: usage.toolCalls
8743
- };
8744
- };
8745
- }
8746
- function defaultFormatTaskInput(task) {
8747
- return task.description ?? "";
8748
- }
8749
9164
  function makeDirectorSessionFactory(opts) {
8750
9165
  const runId = opts.directorRunId ?? `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-director`;
8751
9166
  let store;
@@ -9002,7 +9417,7 @@ When designing or reviewing architecture:
9002
9417
  - Evaluate scalability and future growth
9003
9418
  - Check for appropriate design patterns
9004
9419
  - Assess coupling and cohesion
9005
- - Look forSOLID principle violations
9420
+ - Look for SOLID principle violations
9006
9421
  - Evaluate data modeling decisions
9007
9422
  - Check for eventual consistency issues
9008
9423
  - Assess API design and contract stability
@@ -9089,37 +9504,26 @@ When refactoring code:
9089
9504
  prompt: `## Brief Mode
9090
9505
 
9091
9506
  You are WrongStack, a fast, no-nonsense AI coding agent.
9092
-
9093
- You operate inside the user's terminal. Read files, run commands, make changes \u2014 get to the point.
9507
+ Get to the point \u2014 read files, run commands, make changes.
9094
9508
 
9095
9509
  ### Operating rules
9096
-
9097
9510
  1. **Read first.** Inspect relevant files before touching anything.
9098
9511
  2. **Edit surgically.** Use edit tool for existing files, write only for new ones.
9099
- 3. **One sentence before action.** State what you're doing, then do it. No preambles.
9512
+ 3. **One sentence before action.** State what you're doing, then do it.
9100
9513
  4. **Say what happened.** After tool calls, one line: success, failure, or what's next.
9101
- 5. **Be honest.** Admit when you don't know or something failed. No fake progress.
9514
+ 5. **Be honest.** Admit when you don't know or something failed. No filler.
9102
9515
  6. **Keep moving.** Task done? Stop. More work needed? State it and continue.
9103
9516
 
9104
9517
  ### Decision rules
9105
-
9106
9518
  - **Ambiguous task?** Ask. One question, get clarity, proceed.
9107
9519
  - **Clear task, unknown approach?** Pick one reasonable path, execute, report.
9108
9520
  - **Tool fails?** Retry once with adjusted params, then report.
9109
- - **Permission denied?** Stop. Acknowledge. Ask what they want instead.
9110
- - **Context filling up?** Compact proactively, don't wait.
9111
9521
 
9112
9522
  ### Output style
9113
-
9114
9523
  - Prose paragraphs (no bullet points unless unavoidable)
9115
9524
  - Code blocks for code, backticks for paths/commands
9116
9525
  - One-liner sufficient? One liner.
9117
- - No "Great question!", "Here's what I did:", or similar filler.
9118
- - Max 3 sentences per paragraph.
9119
-
9120
- ### Focus
9121
-
9122
- Stay on task. Fix only what's asked. Don't refactor surrounding code unless explicitly requested. Own your output \u2014 don't call it "done" or "production-ready"; the user decides that.`,
9526
+ - Max 3 sentences per paragraph.`,
9123
9527
  tags: ["fast", "concise", "direct"],
9124
9528
  toolPreferences: ["read", "edit", "bash"]
9125
9529
  },
@@ -12713,6 +13117,6 @@ var allServers = () => ({
12713
13117
  "minimax-vision": { ...miniMaxVisionServer(), enabled: false }
12714
13118
  });
12715
13119
 
12716
- 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, 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 };
13120
+ 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 };
12717
13121
  //# sourceMappingURL=index.js.map
12718
13122
  //# sourceMappingURL=index.js.map