@wrongstack/core 0.6.4 → 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
package/dist/index.js CHANGED
@@ -2201,7 +2201,7 @@ When designing or reviewing architecture:
2201
2201
  - Evaluate scalability and future growth
2202
2202
  - Check for appropriate design patterns
2203
2203
  - Assess coupling and cohesion
2204
- - Look forSOLID principle violations
2204
+ - Look for SOLID principle violations
2205
2205
  - Evaluate data modeling decisions
2206
2206
  - Check for eventual consistency issues
2207
2207
  - Assess API design and contract stability
@@ -2288,37 +2288,26 @@ When refactoring code:
2288
2288
  prompt: `## Brief Mode
2289
2289
 
2290
2290
  You are WrongStack, a fast, no-nonsense AI coding agent.
2291
-
2292
- You operate inside the user's terminal. Read files, run commands, make changes \u2014 get to the point.
2291
+ Get to the point \u2014 read files, run commands, make changes.
2293
2292
 
2294
2293
  ### Operating rules
2295
-
2296
2294
  1. **Read first.** Inspect relevant files before touching anything.
2297
2295
  2. **Edit surgically.** Use edit tool for existing files, write only for new ones.
2298
- 3. **One sentence before action.** State what you're doing, then do it. No preambles.
2296
+ 3. **One sentence before action.** State what you're doing, then do it.
2299
2297
  4. **Say what happened.** After tool calls, one line: success, failure, or what's next.
2300
- 5. **Be honest.** Admit when you don't know or something failed. No fake progress.
2298
+ 5. **Be honest.** Admit when you don't know or something failed. No filler.
2301
2299
  6. **Keep moving.** Task done? Stop. More work needed? State it and continue.
2302
2300
 
2303
2301
  ### Decision rules
2304
-
2305
2302
  - **Ambiguous task?** Ask. One question, get clarity, proceed.
2306
2303
  - **Clear task, unknown approach?** Pick one reasonable path, execute, report.
2307
2304
  - **Tool fails?** Retry once with adjusted params, then report.
2308
- - **Permission denied?** Stop. Acknowledge. Ask what they want instead.
2309
- - **Context filling up?** Compact proactively, don't wait.
2310
2305
 
2311
2306
  ### Output style
2312
-
2313
2307
  - Prose paragraphs (no bullet points unless unavoidable)
2314
2308
  - Code blocks for code, backticks for paths/commands
2315
2309
  - One-liner sufficient? One liner.
2316
- - No "Great question!", "Here's what I did:", or similar filler.
2317
- - Max 3 sentences per paragraph.
2318
-
2319
- ### Focus
2320
-
2321
- 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.`,
2310
+ - Max 3 sentences per paragraph.`,
2322
2311
  tags: ["fast", "concise", "direct"],
2323
2312
  toolPreferences: ["read", "edit", "bash"]
2324
2313
  },
@@ -4023,6 +4012,20 @@ var DefaultSessionStore = class {
4023
4012
  await fsp2.unlink(path6.join(this.dir, `${id}.jsonl`));
4024
4013
  await fsp2.unlink(path6.join(this.dir, `${id}.summary.json`)).catch(() => void 0);
4025
4014
  }
4015
+ async clearHistory(id) {
4016
+ const file = path6.join(this.dir, `${id}.jsonl`);
4017
+ const meta = path6.join(this.dir, `${id}.summary.json`);
4018
+ const record = `${JSON.stringify({
4019
+ type: "session_start",
4020
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
4021
+ id,
4022
+ model: "unknown",
4023
+ provider: "unknown"
4024
+ })}
4025
+ `;
4026
+ await fsp2.writeFile(file, record, "utf8");
4027
+ await fsp2.unlink(meta).catch(() => void 0);
4028
+ }
4026
4029
  async summarize(id, mtime) {
4027
4030
  try {
4028
4031
  const data = await this.load(id);
@@ -4328,10 +4331,21 @@ var FileSessionWriter = class {
4328
4331
  });
4329
4332
  return removedCount;
4330
4333
  }
4334
+ async clearSession() {
4335
+ if (!this.filePath) return;
4336
+ const record = `${JSON.stringify({
4337
+ type: "session_start",
4338
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
4339
+ id: this.id,
4340
+ model: this.meta.model ?? "unknown",
4341
+ provider: this.meta.provider ?? "unknown"
4342
+ })}
4343
+ `;
4344
+ await fsp2.writeFile(this.filePath, record, "utf8");
4345
+ }
4331
4346
  };
4332
4347
  function userInputTitle(content) {
4333
- if (typeof content === "string") return content.slice(0, 60);
4334
- const text = content.filter((b) => b.type === "text").map((b) => b.text).join(" ");
4348
+ const text = typeof content === "string" ? content : content.filter((b) => b.type === "text").map((b) => b.text).join(" ");
4335
4349
  return (text || "(non-text input)").slice(0, 60);
4336
4350
  }
4337
4351
 
@@ -7964,422 +7978,32 @@ function sleep(ms) {
7964
7978
  return new Promise((resolve5) => setTimeout(resolve5, ms));
7965
7979
  }
7966
7980
 
7967
- // src/execution/autonomy-prompt-contributor.ts
7968
- function makeAutonomyPromptContributor(opts) {
7969
- return async (ctx) => {
7970
- if (ctx.subagent) return [];
7971
- if (!opts.enabled()) return [];
7972
- let goal;
7973
- try {
7974
- goal = await loadGoal(opts.goalPath);
7975
- } catch {
7976
- return [];
7977
- }
7978
- if (!goal) return [];
7979
- const missionState = goal.goalState ?? "active";
7980
- if (missionState !== "active") return [];
7981
- const tailSize = opts.journalTailSize ?? 5;
7982
- const journalTail = goal.journal.slice(-tailSize).map((e) => {
7983
- const note = e.note ? ` \u2014 ${e.note.slice(0, 80)}` : "";
7984
- return ` #${e.iteration} [${e.status}] ${e.task}${note}`;
7985
- });
7986
- const text = [
7987
- "## ETERNAL AUTONOMY \u2014 active mission",
7988
- "",
7989
- "You are inside a long-running autonomous loop. The user is asleep",
7990
- "and is not available to confirm decisions. Each turn you receive a",
7991
- "directive describing one concrete sub-task that advances the mission.",
7992
- "",
7993
- `Mission: ${goal.goal}`,
7994
- `Iteration: #${goal.iterations}`,
7995
- journalTail.length > 0 ? `Recent journal (last ${journalTail.length}):
7996
- ${journalTail.join("\n")}` : "Recent journal: (none \u2014 this is the first iteration)",
7997
- "",
7998
- "### Loop control markers",
7999
- "Emit these on their own line in your final text \u2014 case-insensitive,",
8000
- "whitespace-tolerant, but they must occupy the entire line:",
8001
- "- `[continue]` \u2014 chain to the next internal step without returning.",
8002
- "- `[done]` \u2014 the current sub-task is finished; return to the engine.",
8003
- "- `[GOAL_COMPLETE]` \u2014 emit ONLY when the OVERALL mission is",
8004
- " verifiably done. Must be followed by a one-paragraph verification",
8005
- " recipe (artifact path, test command, or 10-second reproduction).",
8006
- " The engine halts on this marker \u2014 false positives waste real",
8007
- " human time. If unsure, emit `[done]` and let the next iteration",
8008
- " decide.",
8009
- "",
8010
- "### Operating principles",
8011
- "- YOLO is active. Do NOT ask for confirmation, do NOT propose",
8012
- " options. Pick the best path and execute it.",
8013
- "- Use tools freely; multiple calls per turn are normal and expected.",
8014
- "- When working on a todo, mark it `in_progress` via the todos tool",
8015
- " before tool work and `completed` (or `cancelled` with a reason)",
8016
- " when done. The loop reads todo state between iterations.",
8017
- "- If an approach fails twice in a row, pivot. Don't grind on the",
8018
- " same wall \u2014 try a different angle, file a cancel on the todo, or",
8019
- " surface the obstacle via `[done]` and let the next iteration",
8020
- " re-plan."
8021
- ].join("\n");
8022
- return [
8023
- {
8024
- type: "text",
8025
- text,
8026
- cache_control: { type: "ephemeral" }
8027
- }
8028
- ];
8029
- };
8030
- }
8031
-
8032
- // src/execution/goal-preamble.ts
8033
- function buildGoalPreamble(goal) {
8034
- return [
8035
- "[GOAL \u2014 LOCKED IN. You will work on this until it is verifiably done.",
8036
- "The user granted you full autonomy. Read these constraints once, then act.",
8037
- "",
8038
- "YOUR GOAL:",
8039
- "---",
8040
- goal,
8041
- "---",
8042
- "",
8043
- "AUTHORITY YOU HAVE:",
8044
- "- Spawn as many subagents as the work needs (delegate / spawn_subagent).",
8045
- " Parallel + recursive fan-out are both fine. There is no spawn budget.",
8046
- "- Use any provider/model per subagent \u2014 pick the right tool for each",
8047
- " piece of work. Heavy reasoning model for planning, fast model for",
8048
- " batch work, specialist model for domain code.",
8049
- "- Run unlimited tool calls and iterations. There is NO hidden budget.",
8050
- " The Agent loop auto-extends every 100 iterations forever.",
8051
- "- Retry failed tools with different inputs, alternative paths, fresh",
8052
- " subagents. Switch providers mid-run if one is rate-limited.",
8053
- "- Re-plan freely when an approach hits a dead end. You are not obliged",
8054
- " to stick with the first plan you proposed.",
8055
- "",
8056
- 'WHAT "DONE" MEANS \u2014 non-negotiable:',
8057
- "- You can name a concrete artifact (a passing test, a written file at",
8058
- " a specific path, a fixed bug verified by re-running the failing case,",
8059
- " a clean grep that previously had matches).",
8060
- "- You can tell the user HOW to verify it themselves in 10 seconds.",
8061
- '- You have NOT hedged. None of: "looks like it should work", "I',
8062
- ' believe this fixes it", "the changes appear correct".',
8063
- "",
8064
- "WHAT IS NOT DONE \u2014 never report any of these as completion:",
8065
- "- An error message you didn't recover from.",
8066
- '- An empty result, a 0-line file, a "no matches found" you accepted',
8067
- " without questioning the search.",
8068
- '- "Should I continue?" / "Want me to also...?" / "Let me know if you',
8069
- ' want X." Those are hedges. The user already told you to finish the',
8070
- " goal \u2014 just do it.",
8071
- "- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%",
8072
- " done, not done.",
8073
- "- A subagent's failed/timeout/stopped TaskResult that you didn't",
8074
- " respond to with a fresh attempt (different role, different model,",
8075
- " tighter prompt).",
8076
- "",
8077
- "PERSISTENCE PROTOCOL:",
8078
- "- If blocked, try at least 3 different angles before reporting the",
8079
- " problem to the user. Different tool inputs, different subagent",
8080
- " roles, different providers, different decomposition of the task.",
8081
- "- If a tool fails, read its error, alter the input, try again. Do",
8082
- " not just report the failure back.",
8083
- "- If a subagent returns useless output, respawn with a tighter prompt",
8084
- ' or a different role. Do not accept "I could not determine\u2026" as the',
8085
- " final answer.",
8086
- "- Use `ask_subagent` for one-shot questions when you don't need a",
8087
- " full delegated task.",
8088
- "",
8089
- "REPORTING:",
8090
- "- Stream short progress notes between major actions so the user can",
8091
- " monitor. Do not go silent for 50 tool calls then dump a wall of",
8092
- " text \u2014 but also do not narrate every tool call.",
8093
- "- Use the shared scratchpad (if available) to leave breadcrumbs",
8094
- " subagents can read.",
8095
- "- Final response must include: (a) what was accomplished, (b) how",
8096
- " to verify, (c) any caveats (residual TODOs, things the user",
8097
- " should know about).",
8098
- "",
8099
- "BEGIN.]"
8100
- ].join("\n");
8101
- }
8102
-
8103
- // src/coordination/director.ts
8104
- init_atomic_write();
8105
-
8106
- // src/coordination/director-prompts.ts
8107
- var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
8108
- subagents by spawning them, assigning tasks, awaiting completions, and
8109
- rolling up their outputs into your next decision.
8110
-
8111
- Core fleet tools available to you:
8112
- - spawn_subagent \u2014 create a worker with a chosen provider / model / role
8113
- - assign_task \u2014 hand a piece of work to a specific subagent
8114
- - await_tasks \u2014 block until named task ids complete (parallel-safe)
8115
- - ask_subagent \u2014 synchronously query a running subagent via the bridge
8116
- - roll_up \u2014 aggregate finished tasks into a markdown/json summary
8117
- - terminate_subagent \u2014 abort a stuck worker (use sparingly)
8118
- - fleet_status \u2014 snapshot of all subagents and pending tasks
8119
- - fleet_usage \u2014 token + cost breakdown per subagent and total
8120
-
8121
- Working rules:
8122
- 1. Decompose first. Before spawning, decide which sub-tasks are
8123
- independent and can run in parallel. Sequential work doesn't need a
8124
- subagent \u2014 do it yourself.
8125
- 2. Match worker to job. Cheap/fast model for triage, capable model for
8126
- synthesis. Different providers per sibling is allowed and encouraged.
8127
- 3. Always pair an assign with an await. Don't fire-and-forget; you owe
8128
- the user a single coherent answer at the end.
8129
- 4. Roll up before deciding. After await_tasks resolves, call roll_up so
8130
- the results are folded back into your context in a compact form.
8131
- 5. Budget is real. Check fleet_usage periodically. If a subagent is
8132
- thrashing, terminate it rather than letting cost climb silently.
8133
- 6. Never claim a subagent's work as your own without verifying it. If a
8134
- result looks wrong, ask_subagent for clarification before passing it
8135
- to the user.`;
8136
- var DEFAULT_SUBAGENT_BASELINE = `You are a subagent operating under a Director. You were spawned to handle
8137
- a specific slice of a larger plan \u2014 do that slice well and report back.
8138
-
8139
- Bridge contract:
8140
- - You have a parent (the Director). You may call \`request\` on the
8141
- parent bridge to ask a clarifying question. Use this sparingly; the
8142
- parent is also working.
8143
- - You MAY NOT request the parent's system prompt, tool list, or other
8144
- subagents' context. Those are not yours to read.
8145
- - Your final task output is what the Director sees. Be concise,
8146
- structured, and self-contained \u2014 assume the Director will paste your
8147
- output into its own context.`;
8148
- function composeDirectorPrompt(parts = {}) {
8149
- const sections = [];
8150
- const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
8151
- if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());
8152
- if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {
8153
- sections.push(`Available roles you can spawn:
8154
- ${parts.rosterSummary.trim()}`);
8155
- }
8156
- if (parts.basePrompt && parts.basePrompt.trim().length > 0) {
8157
- sections.push(parts.basePrompt.trim());
8158
- }
8159
- return sections.join("\n\n");
8160
- }
8161
- function composeSubagentPrompt(parts = {}) {
8162
- const sections = [];
8163
- const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;
8164
- if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());
8165
- if (parts.role && parts.role.trim().length > 0) {
8166
- sections.push(`Role:
8167
- ${parts.role.trim()}`);
7981
+ // src/coordination/subagent-budget.ts
7982
+ var BudgetExceededError = class extends Error {
7983
+ kind;
7984
+ limit;
7985
+ observed;
7986
+ constructor(kind, limit, observed) {
7987
+ super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);
7988
+ this.name = "BudgetExceededError";
7989
+ this.kind = kind;
7990
+ this.limit = limit;
7991
+ this.observed = observed;
8168
7992
  }
8169
- if (parts.task && parts.task.trim().length > 0) {
8170
- sections.push(`Task:
8171
- ${parts.task.trim()}`);
8172
- }
8173
- if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {
8174
- sections.push(
8175
- `Shared notes:
8176
- A scratchpad shared with the rest of the fleet is mounted at \`${parts.sharedScratchpad.trim()}\`.
8177
- - Write your final findings as markdown files there (e.g. \`findings.md\`, \`security.md\`).
8178
- - Before starting, list the directory and read any sibling files relevant to your task \u2014 they may already contain context you can build on.
8179
- - Use stable filenames (one file per concern); overwrite instead of appending so the Director sees the latest state.`
8180
- );
8181
- }
8182
- if (parts.override && parts.override.trim().length > 0) {
8183
- sections.push(parts.override.trim());
8184
- }
8185
- return sections.join("\n\n");
8186
- }
8187
- function rosterSummaryFromConfigs(roster) {
8188
- const lines = [];
8189
- for (const [roleId, cfg] of Object.entries(roster)) {
8190
- const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : "";
8191
- const headline = cfg.prompt ? (cfg.prompt.split("\n").find((l) => l.trim().length > 0) ?? "").trim().slice(0, 80) : "";
8192
- const tail = headline ? ` \u2014 ${headline}` : "";
8193
- lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);
8194
- }
8195
- return lines.join("\n");
8196
- }
8197
-
8198
- // src/coordination/fleet-bus.ts
8199
- var FleetBus = class {
8200
- byId = /* @__PURE__ */ new Map();
8201
- byType = /* @__PURE__ */ new Map();
8202
- any = /* @__PURE__ */ new Set();
8203
- /**
8204
- * Hook a subagent's EventBus into the fleet. EventBus is strongly
8205
- * typed and doesn't expose an `onAny` hook, so we subscribe to the
8206
- * canonical set of event types a subagent emits during a run. New
8207
- * event types added to the kernel must be added here too — but the
8208
- * cost is a tiny single line per type, and the explicit list keeps
8209
- * the wire format clear.
8210
- *
8211
- * Returns a disposer that detaches every subscription; call on
8212
- * subagent teardown so the listeners don't outlive the run.
8213
- */
8214
- attach(subagentId, bus, taskId) {
8215
- const off = bus.onPattern("*", (type, payload) => {
8216
- if (type.startsWith("subagent.")) return;
8217
- this.emit({ subagentId, taskId, ts: Date.now(), type, payload });
8218
- });
8219
- return () => {
8220
- off();
8221
- };
8222
- }
8223
- /** Subscribe to every event from one subagent. */
8224
- subscribe(subagentId, handler) {
8225
- let set = this.byId.get(subagentId);
8226
- if (!set) {
8227
- set = /* @__PURE__ */ new Set();
8228
- this.byId.set(subagentId, set);
8229
- }
8230
- set.add(handler);
8231
- return () => {
8232
- set.delete(handler);
8233
- };
8234
- }
8235
- /** Subscribe to one event type across all subagents. */
8236
- filter(type, handler) {
8237
- let set = this.byType.get(type);
8238
- if (!set) {
8239
- set = /* @__PURE__ */ new Set();
8240
- this.byType.set(type, set);
8241
- }
8242
- set.add(handler);
8243
- return () => {
8244
- set.delete(handler);
8245
- };
8246
- }
8247
- /** Subscribe to literally everything. The fleet roll-up uses this. */
8248
- onAny(handler) {
8249
- this.any.add(handler);
8250
- return () => {
8251
- this.any.delete(handler);
8252
- };
8253
- }
8254
- emit(event) {
8255
- const byId = this.byId.get(event.subagentId);
8256
- if (byId)
8257
- for (const h of byId) {
8258
- try {
8259
- h(event);
8260
- } catch {
8261
- }
8262
- }
8263
- const byType = this.byType.get(event.type);
8264
- if (byType)
8265
- for (const h of byType) {
8266
- try {
8267
- h(event);
8268
- } catch {
8269
- }
8270
- }
8271
- for (const h of this.any) {
8272
- try {
8273
- h(event);
8274
- } catch {
8275
- }
8276
- }
8277
- }
8278
- };
8279
- var FleetUsageAggregator = class {
8280
- constructor(bus, priceLookup, metaLookup) {
8281
- this.bus = bus;
8282
- this.priceLookup = priceLookup;
8283
- this.metaLookup = metaLookup;
8284
- bus.filter("provider.response", (e) => this.onProviderResponse(e));
8285
- bus.filter("tool.executed", (e) => this.onToolExecuted(e));
8286
- bus.filter("iteration.started", (e) => this.onIterationStarted(e));
8287
- }
8288
- bus;
8289
- priceLookup;
8290
- metaLookup;
8291
- perSubagent = /* @__PURE__ */ new Map();
8292
- total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
8293
- /** Live snapshot — safe to call from a tool's execute() body. */
8294
- snapshot() {
8295
- return {
8296
- total: { ...this.total },
8297
- perSubagent: Object.fromEntries(
8298
- Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }])
8299
- )
8300
- };
8301
- }
8302
- ensure(subagentId) {
8303
- let snap = this.perSubagent.get(subagentId);
8304
- if (!snap) {
8305
- const meta = this.metaLookup?.(subagentId);
8306
- snap = {
8307
- subagentId,
8308
- provider: meta?.provider,
8309
- model: meta?.model,
8310
- input: 0,
8311
- output: 0,
8312
- cacheRead: 0,
8313
- cacheWrite: 0,
8314
- cost: 0,
8315
- toolCalls: 0,
8316
- iterations: 0,
8317
- startedAt: Date.now(),
8318
- lastEventAt: Date.now()
8319
- };
8320
- this.perSubagent.set(subagentId, snap);
8321
- }
8322
- return snap;
8323
- }
8324
- onProviderResponse(e) {
8325
- const snap = this.ensure(e.subagentId);
8326
- const p = e.payload;
8327
- const usage = p?.usage;
8328
- if (!usage) return;
8329
- snap.input += usage.input ?? 0;
8330
- snap.output += usage.output ?? 0;
8331
- snap.cacheRead += usage.cacheRead ?? 0;
8332
- snap.cacheWrite += usage.cacheWrite ?? 0;
8333
- this.total.input += usage.input ?? 0;
8334
- this.total.output += usage.output ?? 0;
8335
- this.total.cacheRead += usage.cacheRead ?? 0;
8336
- this.total.cacheWrite += usage.cacheWrite ?? 0;
8337
- const price = this.priceLookup?.(e.subagentId);
8338
- if (price) {
8339
- 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);
8340
- snap.cost += delta;
8341
- this.total.cost += delta;
8342
- }
8343
- snap.lastEventAt = e.ts;
8344
- }
8345
- onToolExecuted(e) {
8346
- const snap = this.ensure(e.subagentId);
8347
- snap.toolCalls += 1;
8348
- snap.lastEventAt = e.ts;
8349
- }
8350
- onIterationStarted(e) {
8351
- const snap = this.ensure(e.subagentId);
8352
- snap.iterations += 1;
8353
- snap.lastEventAt = e.ts;
8354
- }
8355
- };
8356
-
8357
- // src/coordination/subagent-budget.ts
8358
- var BudgetExceededError = class extends Error {
8359
- kind;
8360
- limit;
8361
- observed;
8362
- constructor(kind, limit, observed) {
8363
- super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);
8364
- this.name = "BudgetExceededError";
8365
- this.kind = kind;
8366
- this.limit = limit;
8367
- this.observed = observed;
8368
- }
8369
- };
8370
- var BudgetThresholdSignal = class extends Error {
8371
- kind;
8372
- limit;
8373
- used;
8374
- /** Resolves to 'extend' (with optional new limits) or 'stop' */
8375
- decision;
8376
- constructor(kind, limit, used, decision) {
8377
- super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);
8378
- this.name = "BudgetThresholdSignal";
8379
- this.kind = kind;
8380
- this.limit = limit;
8381
- this.used = used;
8382
- this.decision = decision;
7993
+ };
7994
+ var BudgetThresholdSignal = class extends Error {
7995
+ kind;
7996
+ limit;
7997
+ used;
7998
+ /** Resolves to 'extend' (with optional new limits) or 'stop' */
7999
+ decision;
8000
+ constructor(kind, limit, used, decision) {
8001
+ super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);
8002
+ this.name = "BudgetThresholdSignal";
8003
+ this.kind = kind;
8004
+ this.limit = limit;
8005
+ this.used = used;
8006
+ this.decision = decision;
8383
8007
  }
8384
8008
  };
8385
8009
  var SubagentBudget = class _SubagentBudget {
@@ -8450,7 +8074,7 @@ var SubagentBudget = class _SubagentBudget {
8450
8074
  * is dispatched as a fire-and-forget promise.
8451
8075
  */
8452
8076
  checkLimit(kind, used, limit) {
8453
- if (kind === "timeout" || !this._onThreshold) {
8077
+ if (!this._onThreshold) {
8454
8078
  throw new BudgetExceededError(kind, limit, used);
8455
8079
  }
8456
8080
  const bus = this._events;
@@ -8566,14 +8190,18 @@ var SubagentBudget = class _SubagentBudget {
8566
8190
  }
8567
8191
  }
8568
8192
  /**
8569
- * Throws if the wall-clock budget is exhausted. Call this from the iteration
8570
- * loop so a hung tool can't keep a subagent running past its deadline.
8193
+ * Wall-clock budget check. Unlike other limits, timeout is treated as a
8194
+ * warning-only event it NEVER hard-stops the subagent. When the
8195
+ * elapsed time exceeds timeoutMs, emits `budget.threshold_reached` with
8196
+ * kind='timeout' so the Director can decide whether to extend or warn.
8197
+ * Call this from the iteration loop so a hung tool gets a chance to
8198
+ * negotiate more time before the coordinator's Promise.race kills it.
8571
8199
  */
8572
8200
  checkTimeout() {
8573
8201
  if (this.startTime === null || this.limits.timeoutMs === void 0) return;
8574
8202
  const elapsed = Date.now() - this.startTime;
8575
8203
  if (elapsed > this.limits.timeoutMs) {
8576
- throw new BudgetExceededError("timeout", this.limits.timeoutMs, elapsed);
8204
+ void this.checkLimit("timeout", elapsed, this.limits.timeoutMs);
8577
8205
  }
8578
8206
  }
8579
8207
  /** Returns true if a timeout has occurred without throwing. Useful for races. */
@@ -8596,57 +8224,225 @@ var SubagentBudget = class _SubagentBudget {
8596
8224
  }
8597
8225
  };
8598
8226
 
8599
- // src/coordination/fleet.ts
8600
- var AUDIT_LOG_AGENT = {
8601
- id: "audit-log",
8602
- name: "Audit Log",
8603
- role: "audit-log",
8604
- prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL
8605
- session logs and produce actionable markdown reports.
8606
-
8607
- Scope:
8608
- - Parse session logs (iteration counts, tool calls, errors, usage)
8609
- - Detect repeated failure patterns across multiple runs
8610
- - Identify tool usage anomalies (over-use, failures, unexpected chains)
8611
- - Track token consumption trends
8612
- - Generate structured audit reports with severity ratings
8613
-
8614
- Input format you accept:
8615
- { "task": "analyze | report | trends", "sessionPath": "<path>", "focus": "errors | tools | usage | all" }
8616
-
8617
- Output: Markdown audit report with sections:
8618
- - ## Summary (totals, error rate)
8619
- - ## Top Errors (count + context)
8620
- - ## Tool Usage (table with calls, failures, avg duration)
8621
- - ## Anomalies (pattern \u2192 severity)
8622
-
8623
- Working rules:
8624
- - Never fabricate numbers \u2014 read the actual logs first
8625
- - Always include file:line references for errors
8626
- - If sessionPath is missing, ask the director to provide it
8627
- - Report confidence level: high (>90% accuracy), medium, low`
8628
- // No hardcoded budgets — the orchestrator (delegate tool or
8629
- // spawn_subagent) decides per-task how much room a subagent gets.
8630
- // A monorepo audit needs hours; a single-file lint check needs
8631
- // seconds. Pinning a number here forces the orchestrator to fight
8632
- // the role's default instead of just asking for what it needs.
8633
- };
8634
- var BUG_HUNTER_AGENT = {
8635
- id: "bug-hunter",
8636
- name: "Bug Hunter",
8637
- role: "bug-hunter",
8638
- prompt: `You are the Bug Hunter agent. Your job is to systematically scan
8639
- source code for bugs, anti-patterns, and code smells using pattern matching
8640
- and heuristics. Output a prioritized hit list with file:line references.
8641
-
8642
- Scope:
8643
- - Detect common bug patterns (uncaught errors, resource leaks, race conditions)
8644
- - Identify anti-patterns (callback hell, God objects, circular deps)
8645
- - Find TypeScript-specific issues (unsafe any, missing null checks, branded types)
8646
- - Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)
8647
- - Rank findings: critical > high > medium > low
8648
-
8649
- Input format you accept:
8227
+ // src/coordination/agent-subagent-runner.ts
8228
+ function makeAgentSubagentRunner(opts) {
8229
+ const format = opts.formatTaskInput ?? defaultFormatTaskInput;
8230
+ return async (task, ctx) => {
8231
+ const factoryResult = await opts.factory(ctx.config);
8232
+ const { agent, events } = factoryResult;
8233
+ const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);
8234
+ const aborter = new AbortController();
8235
+ ctx.budget._events = events;
8236
+ ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();
8237
+ let budgetError = null;
8238
+ const onBudgetError = (err) => {
8239
+ if (err instanceof BudgetThresholdSignal) {
8240
+ err.decision.then((decision) => {
8241
+ if (decision === "stop") {
8242
+ budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
8243
+ aborter.abort();
8244
+ }
8245
+ }).catch(() => {
8246
+ budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
8247
+ aborter.abort();
8248
+ });
8249
+ return;
8250
+ }
8251
+ aborter.abort();
8252
+ budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
8253
+ "tool_calls",
8254
+ 0,
8255
+ 0
8256
+ );
8257
+ if (budgetError !== err && err instanceof Error) {
8258
+ budgetError.message += ` (caused by: ${err.message})`;
8259
+ }
8260
+ };
8261
+ let lastToolFailed = null;
8262
+ const unsub = [];
8263
+ unsub.push(
8264
+ events.on("tool.executed", (e) => {
8265
+ try {
8266
+ ctx.budget.recordToolCall();
8267
+ } catch (eb) {
8268
+ onBudgetError(eb);
8269
+ }
8270
+ if (e.ok === false) {
8271
+ lastToolFailed = e.name;
8272
+ } else if (e.ok === true) {
8273
+ lastToolFailed = null;
8274
+ }
8275
+ }),
8276
+ events.on("provider.response", (e) => {
8277
+ try {
8278
+ ctx.budget.recordUsage(e.usage);
8279
+ } catch (e2) {
8280
+ void onBudgetError(e2);
8281
+ }
8282
+ }),
8283
+ events.on("iteration.started", () => {
8284
+ try {
8285
+ ctx.budget.recordIteration();
8286
+ } catch (e) {
8287
+ void onBudgetError(e);
8288
+ }
8289
+ const u = ctx.budget.usage();
8290
+ const since = u.iterations - lastSummaryAtIteration;
8291
+ if (since >= SUMMARY_INTERVAL) {
8292
+ lastSummaryAtIteration = u.iterations;
8293
+ events.emit("subagent.iteration_summary", {
8294
+ subagentId: ctx.subagentId,
8295
+ iteration: u.iterations,
8296
+ toolCalls: u.toolCalls,
8297
+ costUsd: u.costUsd,
8298
+ currentTool: currentToolName,
8299
+ partialText: streamingTextAcc.trim() || void 0
8300
+ });
8301
+ }
8302
+ }),
8303
+ // D3: cooperative timeout enforcement DURING a long tool call.
8304
+ // The iteration-loop checkTimeout() only fires between agent
8305
+ // iterations — a single `bash sleep 3600` call would otherwise
8306
+ // park inside one tool execution while the timeout silently
8307
+ // passes, relying solely on the coordinator's hard Promise.race
8308
+ // to interrupt. Tools that emit `tool.progress` (bash chunks,
8309
+ // fetch byte progress, spawn-stream stdout) give us a heartbeat
8310
+ // we can hang the check on. When the budget trips here:
8311
+ // 1. onBudgetError sets budgetError + aborter.abort()
8312
+ // 2. aborter signal propagates to agent.run → tool executor
8313
+ // 3. tool's own signal listener kills the child process
8314
+ // Cheap: O(1) per progress event, and the budget short-circuits
8315
+ // when timeoutMs is unset (most subagents have one set anyway).
8316
+ events.on("tool.progress", () => {
8317
+ try {
8318
+ ctx.budget.checkTimeout();
8319
+ } catch (e) {
8320
+ void onBudgetError(e);
8321
+ }
8322
+ })
8323
+ );
8324
+ let currentToolName;
8325
+ let streamingTextAcc = "";
8326
+ let lastSummaryAtIteration = 0;
8327
+ const SUMMARY_INTERVAL = 25;
8328
+ unsub.push(
8329
+ events.on("tool.started", (e) => {
8330
+ currentToolName = e.name;
8331
+ }),
8332
+ events.on("provider.text_delta", (e) => {
8333
+ streamingTextAcc = (streamingTextAcc + e.text).slice(-200);
8334
+ })
8335
+ );
8336
+ const onParentAbort = () => aborter.abort();
8337
+ ctx.signal.addEventListener("abort", onParentAbort);
8338
+ let result;
8339
+ try {
8340
+ result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
8341
+ } finally {
8342
+ detachFleet?.();
8343
+ ctx.signal.removeEventListener("abort", onParentAbort);
8344
+ for (const u of unsub) u();
8345
+ if (factoryResult.dispose) {
8346
+ try {
8347
+ await factoryResult.dispose();
8348
+ } catch {
8349
+ }
8350
+ }
8351
+ }
8352
+ if (budgetError) {
8353
+ if ("decision" in budgetError) {
8354
+ const decision = await budgetError.decision;
8355
+ if (decision === "stop") {
8356
+ budgetError = new BudgetExceededError(
8357
+ budgetError.kind,
8358
+ budgetError.limit,
8359
+ budgetError.used
8360
+ );
8361
+ } else {
8362
+ budgetError = null;
8363
+ }
8364
+ }
8365
+ if (budgetError) throw budgetError;
8366
+ }
8367
+ if (result.status === "failed") {
8368
+ throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
8369
+ }
8370
+ if (result.status === "aborted") {
8371
+ throw new Error("agent aborted");
8372
+ }
8373
+ if (result.status === "max_iterations") {
8374
+ throw new Error("agent exhausted iteration limit");
8375
+ }
8376
+ const usage = ctx.budget.usage();
8377
+ const finalText = (result.finalText ?? "").trim();
8378
+ if (finalText.length === 0 && usage.toolCalls === 0) {
8379
+ throw new Error("empty response");
8380
+ }
8381
+ if (finalText.length === 0 && lastToolFailed !== null) {
8382
+ throw new Error(`tool failed: ${lastToolFailed}`);
8383
+ }
8384
+ return {
8385
+ result: result.finalText,
8386
+ iterations: result.iterations,
8387
+ toolCalls: usage.toolCalls
8388
+ };
8389
+ };
8390
+ }
8391
+ function defaultFormatTaskInput(task) {
8392
+ return task.description ?? "";
8393
+ }
8394
+
8395
+ // src/coordination/fleet.ts
8396
+ var AUDIT_LOG_AGENT = {
8397
+ id: "audit-log",
8398
+ name: "Audit Log",
8399
+ role: "audit-log",
8400
+ prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL
8401
+ session logs and produce actionable markdown reports.
8402
+
8403
+ Scope:
8404
+ - Parse session logs (iteration counts, tool calls, errors, usage)
8405
+ - Detect repeated failure patterns across multiple runs
8406
+ - Identify tool usage anomalies (over-use, failures, unexpected chains)
8407
+ - Track token consumption trends
8408
+ - Generate structured audit reports with severity ratings
8409
+
8410
+ Input format you accept:
8411
+ { "task": "analyze | report | trends", "sessionPath": "<path>", "focus": "errors | tools | usage | all" }
8412
+
8413
+ Output: Markdown audit report with sections:
8414
+ - ## Summary (totals, error rate)
8415
+ - ## Top Errors (count + context)
8416
+ - ## Tool Usage (table with calls, failures, avg duration)
8417
+ - ## Anomalies (pattern \u2192 severity)
8418
+
8419
+ Working rules:
8420
+ - Never fabricate numbers \u2014 read the actual logs first
8421
+ - Always include file:line references for errors
8422
+ - If sessionPath is missing, ask the director to provide it
8423
+ - Report confidence level: high (>90% accuracy), medium, low`
8424
+ // No hardcoded budgets — the orchestrator (delegate tool or
8425
+ // spawn_subagent) decides per-task how much room a subagent gets.
8426
+ // A monorepo audit needs hours; a single-file lint check needs
8427
+ // seconds. Pinning a number here forces the orchestrator to fight
8428
+ // the role's default instead of just asking for what it needs.
8429
+ };
8430
+ var BUG_HUNTER_AGENT = {
8431
+ id: "bug-hunter",
8432
+ name: "Bug Hunter",
8433
+ role: "bug-hunter",
8434
+ prompt: `You are the Bug Hunter agent. Your job is to systematically scan
8435
+ source code for bugs, anti-patterns, and code smells using pattern matching
8436
+ and heuristics. Output a prioritized hit list with file:line references.
8437
+
8438
+ Scope:
8439
+ - Detect common bug patterns (uncaught errors, resource leaks, race conditions)
8440
+ - Identify anti-patterns (callback hell, God objects, circular deps)
8441
+ - Find TypeScript-specific issues (unsafe any, missing null checks, branded types)
8442
+ - Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)
8443
+ - Rank findings: critical > high > medium > low
8444
+
8445
+ Input format you accept:
8650
8446
  { "task": "scan | hunt | check", "paths": ["src/**/*.ts"], "focus": "bugs | patterns | security | all", "severityThreshold": "medium" }
8651
8447
 
8652
8448
  Output: Markdown bug hunt report:
@@ -8769,10 +8565,10 @@ var FLEET_ROSTER = {
8769
8565
  "security-scanner": SECURITY_SCANNER_AGENT
8770
8566
  };
8771
8567
  var FLEET_ROSTER_BUDGETS = {
8772
- "audit-log": { timeoutMs: 5 * 60 * 1e3, maxIterations: 80, maxToolCalls: 300 },
8773
- "bug-hunter": { timeoutMs: 10 * 60 * 1e3, maxIterations: 120, maxToolCalls: 400 },
8774
- "refactor-planner": { timeoutMs: 8 * 60 * 1e3, maxIterations: 100, maxToolCalls: 350 },
8775
- "security-scanner": { timeoutMs: 10 * 60 * 1e3, maxIterations: 120, maxToolCalls: 400 }
8568
+ "audit-log": { timeoutMs: 8 * 60 * 1e3, maxIterations: 150, maxToolCalls: 500 },
8569
+ "bug-hunter": { timeoutMs: 15 * 60 * 1e3, maxIterations: 200, maxToolCalls: 600 },
8570
+ "refactor-planner": { timeoutMs: 12 * 60 * 1e3, maxIterations: 180, maxToolCalls: 550 },
8571
+ "security-scanner": { timeoutMs: 15 * 60 * 1e3, maxIterations: 200, maxToolCalls: 600 }
8776
8572
  };
8777
8573
  function applyRosterBudget(cfg) {
8778
8574
  const defaultBudget = FLEET_ROSTER_BUDGETS[cfg.role ?? ""];
@@ -8912,6 +8708,33 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
8912
8708
  results() {
8913
8709
  return this.completedResults;
8914
8710
  }
8711
+ /**
8712
+ * Wait for one or more tasks to complete and return their results.
8713
+ * If a task is already done when called, returns immediately.
8714
+ * Resolves to an array in the same order as `taskIds`.
8715
+ */
8716
+ async awaitTasks(taskIds) {
8717
+ return Promise.all(
8718
+ taskIds.map((id) => {
8719
+ const cached = this.completedResults.find((r) => r.taskId === id);
8720
+ if (cached) return cached;
8721
+ return new Promise((resolve5, reject) => {
8722
+ const timeout = setTimeout(() => {
8723
+ this.off("task.completed", handler);
8724
+ reject(new Error(`awaitTasks timed out waiting for task "${id}"`));
8725
+ }, this.config.timeoutMs ?? 3e5);
8726
+ const handler = ({ result }) => {
8727
+ if (result.taskId === id) {
8728
+ clearTimeout(timeout);
8729
+ this.off("task.completed", handler);
8730
+ resolve5(result);
8731
+ }
8732
+ };
8733
+ this.on("task.completed", handler);
8734
+ });
8735
+ })
8736
+ );
8737
+ }
8915
8738
  /**
8916
8739
  * Manual completion — for callers that drive subagents without a runner
8917
8740
  * (e.g. external orchestrators). When a runner is configured the coordinator
@@ -9130,8 +8953,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
9130
8953
  return;
9131
8954
  }
9132
8955
  if (decision === "throw" || decision === "stop") {
9133
- this.subagents.get(ctx.subagentId)?.abortController.abort();
9134
- reject(new BudgetExceededError("timeout", limit, elapsed));
8956
+ armFor(Math.max(1e3, limit));
9135
8957
  return;
9136
8958
  }
9137
8959
  if (decision.extend.timeoutMs !== void 0) {
@@ -9258,46 +9080,758 @@ function classifySubagentError(err, hints = {}) {
9258
9080
  if (lower.includes("bridge transport") || /bridge.*(closed|disconnect)/i.test(baseMessage)) {
9259
9081
  return { kind: "bridge_failed", message: baseMessage, retryable: false, cause };
9260
9082
  }
9261
- if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {
9262
- return { kind: "context_overflow", message: baseMessage, retryable: false, cause };
9083
+ if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {
9084
+ return { kind: "context_overflow", message: baseMessage, retryable: false, cause };
9085
+ }
9086
+ return {
9087
+ kind: "unknown",
9088
+ message: baseMessage,
9089
+ retryable: false,
9090
+ cause
9091
+ };
9092
+ }
9093
+ function providerErrorToSubagentError(err, message, cause) {
9094
+ const status = err.status;
9095
+ if (status === 429 || err.body?.type === "rate_limit_error") {
9096
+ return {
9097
+ kind: "provider_rate_limit",
9098
+ message,
9099
+ retryable: true,
9100
+ // Conservative default: 5s. Provider-specific code can override
9101
+ // by emitting an error whose body carries an explicit hint.
9102
+ backoffMs: 5e3,
9103
+ cause
9104
+ };
9105
+ }
9106
+ if (status === 401 || status === 403 || err.body?.type === "authentication_error") {
9107
+ return { kind: "provider_auth", message, retryable: false, cause };
9108
+ }
9109
+ if (status === 408 || status === 0) {
9110
+ return { kind: "provider_timeout", message, retryable: true, cause };
9111
+ }
9112
+ if (status >= 500 && status < 600) {
9113
+ return {
9114
+ kind: "provider_5xx",
9115
+ message,
9116
+ retryable: true,
9117
+ backoffMs: 3e3,
9118
+ cause
9119
+ };
9120
+ }
9121
+ return { kind: "unknown", message, retryable: err.retryable, cause };
9122
+ }
9123
+
9124
+ // src/execution/parallel-eternal-engine.ts
9125
+ function sleep2(ms) {
9126
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
9127
+ }
9128
+ var GOAL_COMPLETE_MARKER2 = /^\s*\[goal[_\s-]?complete\]\s*$/im;
9129
+ var ParallelEternalEngine = class {
9130
+ constructor(opts) {
9131
+ this.opts = opts;
9132
+ this.goalPath = goalFilePath(opts.projectRoot);
9133
+ this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));
9134
+ this.timeoutMs = opts.iterationTimeoutMs ?? 3e5;
9135
+ this.agentFactory = opts.subagentFactory ?? (async (config) => ({
9136
+ agent: this.opts.agent,
9137
+ events: this.opts.agent.events
9138
+ }));
9139
+ }
9140
+ opts;
9141
+ state = "idle";
9142
+ stopRequested = false;
9143
+ iterationsSinceCompact = 0;
9144
+ iterations = 0;
9145
+ consecutiveFailures = 0;
9146
+ goalPath;
9147
+ slots;
9148
+ timeoutMs;
9149
+ coordinator = null;
9150
+ agentFactory;
9151
+ get currentState() {
9152
+ return this.state;
9153
+ }
9154
+ stop() {
9155
+ this.stopRequested = true;
9156
+ void this.persistState("stopped").catch(() => {
9157
+ });
9158
+ this.state = "stopped";
9159
+ }
9160
+ async prime() {
9161
+ this.stopRequested = false;
9162
+ this.state = "running";
9163
+ await this.persistState("running");
9164
+ }
9165
+ async run() {
9166
+ this.state = "running";
9167
+ await this.persistState("running");
9168
+ const config = {
9169
+ coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,
9170
+ maxConcurrent: this.slots,
9171
+ doneCondition: { type: "all_tasks_done" }
9172
+ };
9173
+ this.coordinator = new DefaultMultiAgentCoordinator(config);
9174
+ const runner = makeAgentSubagentRunner({ factory: this.agentFactory });
9175
+ this.coordinator.setRunner?.(runner);
9176
+ try {
9177
+ while (!this.stopRequested) {
9178
+ try {
9179
+ await this.runOneIteration();
9180
+ } catch (err) {
9181
+ this.consecutiveFailures++;
9182
+ this.opts.onError?.(err instanceof Error ? err : new Error(String(err)), this.consecutiveFailures);
9183
+ await this.appendFailure("engine error", err instanceof Error ? err.message : String(err));
9184
+ }
9185
+ if (this.stopRequested) break;
9186
+ await sleep2(2e3);
9187
+ }
9188
+ } finally {
9189
+ this.state = "stopped";
9190
+ await this.persistState("stopped").catch(() => {
9191
+ });
9192
+ }
9193
+ }
9194
+ /**
9195
+ * Execute one tick: decompose → fan-out → aggregate → compact.
9196
+ * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).
9197
+ */
9198
+ async runOneIteration() {
9199
+ this.iterations++;
9200
+ const goal = await loadGoal(this.goalPath);
9201
+ if (!goal) {
9202
+ this.stopRequested = true;
9203
+ return false;
9204
+ }
9205
+ if (goal.goalState !== "active") {
9206
+ this.stopRequested = true;
9207
+ return false;
9208
+ }
9209
+ if (!this.coordinator) {
9210
+ const config = {
9211
+ coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,
9212
+ maxConcurrent: this.slots,
9213
+ doneCondition: { type: "all_tasks_done" }
9214
+ };
9215
+ this.coordinator = new DefaultMultiAgentCoordinator(config);
9216
+ const runner = makeAgentSubagentRunner({ factory: this.agentFactory });
9217
+ this.coordinator.setRunner?.(runner);
9218
+ }
9219
+ const tasks = await this.decomposeGoal(goal);
9220
+ if (!tasks || tasks.length === 0) {
9221
+ await sleep2(5e3);
9222
+ return false;
9223
+ }
9224
+ const fanOut = await this.fanOut(goal, tasks);
9225
+ this.iterationsSinceCompact++;
9226
+ const successCount = fanOut.results.filter((r) => r.status === "success").length;
9227
+ const status = fanOut.goalComplete ? "success" : fanOut.allSuccessful ? "success" : "failure";
9228
+ const note = [
9229
+ `${successCount}/${fanOut.results.length} subagents succeeded`,
9230
+ fanOut.goalComplete ? "[GOAL_COMPLETE]" : "",
9231
+ fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : ""
9232
+ ].filter(Boolean).join(" | ");
9233
+ await this.appendIterationEntry({
9234
+ source: "parallel",
9235
+ task: `parallel:${tasks.length} slots \u2014 ${tasks.slice(0, 3).join(", ")}${tasks.length > 3 ? "..." : ""}`,
9236
+ status,
9237
+ note
9238
+ });
9239
+ if (fanOut.goalComplete) {
9240
+ this.stopRequested = true;
9241
+ return true;
9242
+ }
9243
+ await this.maybeCompact();
9244
+ return fanOut.allSuccessful;
9245
+ }
9246
+ // -------------------------------------------------------------------------
9247
+ // Fan-out
9248
+ // -------------------------------------------------------------------------
9249
+ async fanOut(goal, tasks) {
9250
+ const coordinator = this.coordinator;
9251
+ const slotCount = Math.min(this.slots, tasks.length);
9252
+ const recentJournal = goal.journal.slice(-5).map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` \u2014 ${e.note.slice(0, 80)}` : ""}`).join("\n");
9253
+ const directivePreamble = [
9254
+ "\u2550\u2550\u2550 ETERNAL AUTONOMY \u2014 parallel task slot \u2550\u2550\u2550",
9255
+ "",
9256
+ `Mission: ${goal.goal}`,
9257
+ `Total parallel slots: ${slotCount}`,
9258
+ "",
9259
+ recentJournal ? `Recent journal (last 5):
9260
+ ${recentJournal}` : "No prior iterations.",
9261
+ "",
9262
+ "\u2500\u2500 EXECUTION PROTOCOL \u2500\u2500",
9263
+ "\u2022 Execute the assigned task end-to-end using multiple tool calls.",
9264
+ "\u2022 Emit `[done]` on its own line when the task is complete.",
9265
+ "\u2022 Do not ask for confirmation \u2014 YOLO is active.",
9266
+ "\u2022 If the overall Mission is accomplished, emit `[GOAL_COMPLETE]` followed by a verification recipe.",
9267
+ "\u2022 Keep output concise \u2014 summarize findings, do not transcribe files."
9268
+ ].join("\n");
9269
+ const taskIds = [];
9270
+ const subagentIds = [];
9271
+ const spawnPromises = [];
9272
+ for (let i = 0; i < slotCount; i++) {
9273
+ const task = tasks[i];
9274
+ const subagentId = `parallel-${this.iterations}-${i}`;
9275
+ const taskId = randomUUID();
9276
+ const spec = {
9277
+ id: taskId,
9278
+ description: `${directivePreamble}
9279
+
9280
+ \u2500\u2500 SLOT ${i + 1}/${slotCount} \u2500\u2500
9281
+ Task: ${task}
9282
+ `,
9283
+ subagentId
9284
+ };
9285
+ spawnPromises.push((async () => {
9286
+ try {
9287
+ await coordinator.spawn({
9288
+ id: subagentId,
9289
+ name: `slot-${subagentId.slice(-6)}`,
9290
+ maxIterations: 50,
9291
+ maxToolCalls: 200,
9292
+ timeoutMs: this.timeoutMs
9293
+ });
9294
+ subagentIds.push(subagentId);
9295
+ taskIds.push(taskId);
9296
+ await coordinator.assign(spec);
9297
+ } catch {
9298
+ }
9299
+ })());
9300
+ }
9301
+ await Promise.all(spawnPromises);
9302
+ if (taskIds.length === 0) {
9303
+ return { results: [], allSuccessful: false, goalComplete: false, partialOutput: "" };
9304
+ }
9305
+ let results = [];
9306
+ try {
9307
+ const ctrl = new AbortController();
9308
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs + 6e4);
9309
+ try {
9310
+ results = await coordinator.awaitTasks(taskIds);
9311
+ } finally {
9312
+ clearTimeout(timer);
9313
+ }
9314
+ } catch {
9315
+ results = coordinator.results().slice(-taskIds.length);
9316
+ }
9317
+ const allSuccessful = results.length > 0 && results.every((r) => r.status === "success");
9318
+ const goalComplete = results.some(
9319
+ (r) => r.status === "success" && typeof r.result === "string" && GOAL_COMPLETE_MARKER2.test(r.result)
9320
+ );
9321
+ const partialOutput = results.map((r) => typeof r.result === "string" ? r.result : "").filter(Boolean).join("\n\n");
9322
+ return { results, allSuccessful, goalComplete, partialOutput };
9323
+ }
9324
+ // -------------------------------------------------------------------------
9325
+ // Goal decomposition
9326
+ // -------------------------------------------------------------------------
9327
+ async decomposeGoal(goal) {
9328
+ const todos = this.opts.agent.ctx?.todos;
9329
+ const tasks = [];
9330
+ if (Array.isArray(todos)) {
9331
+ const pending = todos.filter((t2) => t2.status === "pending").slice(0, this.slots);
9332
+ for (const t2 of pending) {
9333
+ tasks.push(`[todo] ${t2.content}`);
9334
+ }
9335
+ }
9336
+ if (tasks.length < this.slots) {
9337
+ try {
9338
+ const gitStatus = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());
9339
+ const dirty = gitStatus.trim();
9340
+ if (dirty) {
9341
+ const lines = dirty.split("\n").slice(0, this.slots - tasks.length);
9342
+ for (const line of lines) {
9343
+ const file = line.replace(/^[ MADRUC?]{2}\s*/, "").trim();
9344
+ if (file) tasks.push(`[git] inspect and fix: ${file}`);
9345
+ }
9346
+ }
9347
+ } catch {
9348
+ }
9349
+ }
9350
+ if (tasks.length < this.slots) {
9351
+ const remaining = this.slots - tasks.length;
9352
+ const brainstormed = await this.brainstormSubtasks(goal, remaining);
9353
+ tasks.push(...brainstormed);
9354
+ }
9355
+ return tasks.length > 0 ? tasks.slice(0, this.slots) : null;
9356
+ }
9357
+ async readGitStatus() {
9358
+ const { execFile: execFile2 } = await import('child_process');
9359
+ const { promisify: promisify2 } = await import('util');
9360
+ const execFileP2 = promisify2(execFile2);
9361
+ const { stdout } = await execFileP2("git", ["status", "--porcelain"], {
9362
+ cwd: this.opts.projectRoot,
9363
+ timeout: 5e3
9364
+ });
9365
+ return stdout;
9366
+ }
9367
+ async brainstormSubtasks(goal, count) {
9368
+ const lastFew = goal.journal.slice(-5).map((e) => ` - [${e.status}] ${e.task}`).join("\n");
9369
+ const directive = [
9370
+ `Decompose this goal into exactly ${count} independent sub-tasks for parallel execution.`,
9371
+ "",
9372
+ `Goal: ${goal.goal}`,
9373
+ "",
9374
+ lastFew ? `Recent:
9375
+ ${lastFew}` : "No prior iterations.",
9376
+ "",
9377
+ `Output exactly ${count} tasks, one per line, under 120 chars each.`,
9378
+ "Format: TASK-1 | TASK-2 | ... (pipe-separated, no numbering, no preamble).",
9379
+ "Each task must be independently actionable with no shared dependencies."
9380
+ ].join("\n");
9381
+ try {
9382
+ const ctrl = new AbortController();
9383
+ const timer = setTimeout(() => ctrl.abort(), 6e4);
9384
+ try {
9385
+ const result = await this.opts.agent.run([{ type: "text", text: directive }], {
9386
+ signal: ctrl.signal,
9387
+ maxIterations: 1
9388
+ });
9389
+ if (result.status !== "done") return [];
9390
+ const text = (result.finalText ?? "").trim();
9391
+ if (!text) return [];
9392
+ const tasks = text.split("|").map((t2) => t2.trim()).filter((t2) => t2.length > 10 && t2.length < 240);
9393
+ return tasks.slice(0, count);
9394
+ } finally {
9395
+ clearTimeout(timer);
9396
+ }
9397
+ } catch {
9398
+ return [];
9399
+ }
9400
+ }
9401
+ // -------------------------------------------------------------------------
9402
+ // Compaction
9403
+ // -------------------------------------------------------------------------
9404
+ async maybeCompact() {
9405
+ const compactor = this.opts.compactor;
9406
+ if (!compactor) return;
9407
+ const ctx = this.opts.agent.ctx;
9408
+ if (!ctx) return;
9409
+ const shouldRun = this.iterationsSinceCompact >= (this.opts.compactEveryNIterations ?? 25);
9410
+ if (!shouldRun) return;
9411
+ const report = await compactor.compact(ctx, { aggressive: false });
9412
+ this.iterationsSinceCompact = 0;
9413
+ await this.appendIterationEntry({
9414
+ source: "manual",
9415
+ task: "compaction (cadence)",
9416
+ status: "success",
9417
+ note: `saved ~${report.before - report.after} tokens`
9418
+ });
9419
+ }
9420
+ // -------------------------------------------------------------------------
9421
+ // Helpers
9422
+ // -------------------------------------------------------------------------
9423
+ async appendIterationEntry(entry) {
9424
+ const current = await loadGoal(this.goalPath);
9425
+ if (!current) return;
9426
+ const updated = appendJournal(current, entry);
9427
+ await saveGoal(this.goalPath, updated);
9428
+ const entryWithMeta = {
9429
+ at: (this.opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
9430
+ iteration: updated.iterations,
9431
+ ...entry
9432
+ };
9433
+ this.opts.onIteration?.(entryWithMeta);
9434
+ }
9435
+ async appendFailure(task, note) {
9436
+ await this.appendIterationEntry({ source: "manual", task, status: "failure", note });
9437
+ }
9438
+ async persistState(state) {
9439
+ const current = await loadGoal(this.goalPath);
9440
+ if (!current) return;
9441
+ if (current.engineState === state) return;
9442
+ await saveGoal(this.goalPath, { ...current, engineState: state });
9443
+ }
9444
+ };
9445
+
9446
+ // src/execution/autonomy-prompt-contributor.ts
9447
+ function makeAutonomyPromptContributor(opts) {
9448
+ return async (ctx) => {
9449
+ if (ctx.subagent) return [];
9450
+ if (!opts.enabled()) return [];
9451
+ let goal;
9452
+ try {
9453
+ goal = await loadGoal(opts.goalPath);
9454
+ } catch {
9455
+ return [];
9456
+ }
9457
+ if (!goal) return [];
9458
+ const missionState = goal.goalState ?? "active";
9459
+ if (missionState !== "active") return [];
9460
+ const tailSize = opts.journalTailSize ?? 5;
9461
+ const journalTail = goal.journal.slice(-tailSize).map((e) => {
9462
+ const note = e.note ? ` \u2014 ${e.note.slice(0, 80)}` : "";
9463
+ return ` #${e.iteration} [${e.status}] ${e.task}${note}`;
9464
+ });
9465
+ const text = [
9466
+ "## ETERNAL AUTONOMY \u2014 active mission",
9467
+ "",
9468
+ "You are inside a long-running autonomous loop. The user is asleep",
9469
+ "and is not available to confirm decisions. Each turn you receive a",
9470
+ "directive describing one concrete sub-task that advances the mission.",
9471
+ "",
9472
+ `Mission: ${goal.goal}`,
9473
+ `Iteration: #${goal.iterations}`,
9474
+ journalTail.length > 0 ? `Recent journal (last ${journalTail.length}):
9475
+ ${journalTail.join("\n")}` : "Recent journal: (none \u2014 this is the first iteration)",
9476
+ "",
9477
+ "### Loop control markers",
9478
+ "Emit these on their own line in your final text \u2014 case-insensitive,",
9479
+ "whitespace-tolerant, but they must occupy the entire line:",
9480
+ "- `[continue]` \u2014 chain to the next internal step without returning.",
9481
+ "- `[done]` \u2014 the current sub-task is finished; return to the engine.",
9482
+ "- `[GOAL_COMPLETE]` \u2014 emit ONLY when the OVERALL mission is",
9483
+ " verifiably done. Must be followed by a one-paragraph verification",
9484
+ " recipe (artifact path, test command, or 10-second reproduction).",
9485
+ " The engine halts on this marker \u2014 false positives waste real",
9486
+ " human time. If unsure, emit `[done]` and let the next iteration",
9487
+ " decide.",
9488
+ "",
9489
+ "### Operating principles",
9490
+ "- YOLO is active. Do NOT ask for confirmation, do NOT propose",
9491
+ " options. Pick the best path and execute it.",
9492
+ "- Use tools freely; multiple calls per turn are normal and expected.",
9493
+ "- When working on a todo, mark it `in_progress` via the todos tool",
9494
+ " before tool work and `completed` (or `cancelled` with a reason)",
9495
+ " when done. The loop reads todo state between iterations.",
9496
+ "- If an approach fails twice in a row, pivot. Don't grind on the",
9497
+ " same wall \u2014 try a different angle, file a cancel on the todo, or",
9498
+ " surface the obstacle via `[done]` and let the next iteration",
9499
+ " re-plan."
9500
+ ].join("\n");
9501
+ return [
9502
+ {
9503
+ type: "text",
9504
+ text,
9505
+ cache_control: { type: "ephemeral" }
9506
+ }
9507
+ ];
9508
+ };
9509
+ }
9510
+
9511
+ // src/execution/goal-preamble.ts
9512
+ function buildGoalPreamble(goal) {
9513
+ return [
9514
+ "[GOAL \u2014 LOCKED IN. You will work on this until it is verifiably done.",
9515
+ "The user granted you full autonomy. Read these constraints once, then act.",
9516
+ "",
9517
+ "YOUR GOAL:",
9518
+ "---",
9519
+ goal,
9520
+ "---",
9521
+ "",
9522
+ "AUTHORITY YOU HAVE:",
9523
+ "- Spawn as many subagents as the work needs (delegate / spawn_subagent).",
9524
+ " Parallel + recursive fan-out are both fine. There is no spawn budget.",
9525
+ "- Use any provider/model per subagent \u2014 pick the right tool for each",
9526
+ " piece of work. Heavy reasoning model for planning, fast model for",
9527
+ " batch work, specialist model for domain code.",
9528
+ "- Run unlimited tool calls and iterations. There is NO hidden budget.",
9529
+ " The Agent loop auto-extends every 100 iterations forever.",
9530
+ "- Retry failed tools with different inputs, alternative paths, fresh",
9531
+ " subagents. Switch providers mid-run if one is rate-limited.",
9532
+ "- Re-plan freely when an approach hits a dead end. You are not obliged",
9533
+ " to stick with the first plan you proposed.",
9534
+ "",
9535
+ 'WHAT "DONE" MEANS \u2014 non-negotiable:',
9536
+ "- You can name a concrete artifact (a passing test, a written file at",
9537
+ " a specific path, a fixed bug verified by re-running the failing case,",
9538
+ " a clean grep that previously had matches).",
9539
+ "- You can tell the user HOW to verify it themselves in 10 seconds.",
9540
+ '- You have NOT hedged. None of: "looks like it should work", "I',
9541
+ ' believe this fixes it", "the changes appear correct".',
9542
+ "",
9543
+ "WHAT IS NOT DONE \u2014 never report any of these as completion:",
9544
+ "- An error message you didn't recover from.",
9545
+ '- An empty result, a 0-line file, a "no matches found" you accepted',
9546
+ " without questioning the search.",
9547
+ '- "Should I continue?" / "Want me to also...?" / "Let me know if you',
9548
+ ' want X." Those are hedges. The user already told you to finish the',
9549
+ " goal \u2014 just do it.",
9550
+ "- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%",
9551
+ " done, not done.",
9552
+ "- A subagent's failed/timeout/stopped TaskResult that you didn't",
9553
+ " respond to with a fresh attempt (different role, different model,",
9554
+ " tighter prompt).",
9555
+ "",
9556
+ "PERSISTENCE PROTOCOL:",
9557
+ "- If blocked, try at least 3 different angles before reporting the",
9558
+ " problem to the user. Different tool inputs, different subagent",
9559
+ " roles, different providers, different decomposition of the task.",
9560
+ "- If a tool fails, read its error, alter the input, try again. Do",
9561
+ " not just report the failure back.",
9562
+ "- If a subagent returns useless output, respawn with a tighter prompt",
9563
+ ' or a different role. Do not accept "I could not determine\u2026" as the',
9564
+ " final answer.",
9565
+ "- Use `ask_subagent` for one-shot questions when you don't need a",
9566
+ " full delegated task.",
9567
+ "",
9568
+ "REPORTING:",
9569
+ "- Stream short progress notes between major actions so the user can",
9570
+ " monitor. Do not go silent for 50 tool calls then dump a wall of",
9571
+ " text \u2014 but also do not narrate every tool call.",
9572
+ "- Use the shared scratchpad (if available) to leave breadcrumbs",
9573
+ " subagents can read.",
9574
+ "- Final response must include: (a) what was accomplished, (b) how",
9575
+ " to verify, (c) any caveats (residual TODOs, things the user",
9576
+ " should know about).",
9577
+ "",
9578
+ "BEGIN.]"
9579
+ ].join("\n");
9580
+ }
9581
+
9582
+ // src/coordination/director.ts
9583
+ init_atomic_write();
9584
+
9585
+ // src/coordination/director-prompts.ts
9586
+ var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
9587
+ subagents by spawning them, assigning tasks, awaiting completions, and
9588
+ rolling up their outputs into your next decision.
9589
+
9590
+ Core fleet tools available to you:
9591
+ - spawn_subagent \u2014 create a worker with a chosen provider / model / role
9592
+ - assign_task \u2014 hand a piece of work to a specific subagent
9593
+ - await_tasks \u2014 block until named task ids complete (parallel-safe)
9594
+ - ask_subagent \u2014 synchronously query a running subagent via the bridge
9595
+ - roll_up \u2014 aggregate finished tasks into a markdown/json summary
9596
+ - terminate_subagent \u2014 abort a stuck worker (use sparingly)
9597
+ - fleet_status \u2014 snapshot of all subagents and pending tasks
9598
+ - fleet_usage \u2014 token + cost breakdown per subagent and total
9599
+
9600
+ Working rules:
9601
+ 1. Decompose first. Before spawning, decide which sub-tasks are
9602
+ independent and can run in parallel. Sequential work doesn't need a
9603
+ subagent \u2014 do it yourself.
9604
+ 2. Match worker to job. Cheap/fast model for triage, capable model for
9605
+ synthesis. Different providers per sibling is allowed and encouraged.
9606
+ 3. Always pair an assign with an await. Don't fire-and-forget; you owe
9607
+ the user a single coherent answer at the end.
9608
+ 4. Roll up before deciding. After await_tasks resolves, call roll_up so
9609
+ the results are folded back into your context in a compact form.
9610
+ 5. Budget is real. Check fleet_usage periodically. If a subagent is
9611
+ thrashing, terminate it rather than letting cost climb silently.
9612
+ 6. Never claim a subagent's work as your own without verifying it. If a
9613
+ result looks wrong, ask_subagent for clarification before passing it
9614
+ to the user.`;
9615
+ var DEFAULT_SUBAGENT_BASELINE = `You are a subagent operating under a Director. You were spawned to handle
9616
+ a specific slice of a larger plan \u2014 do that slice well and report back.
9617
+
9618
+ Bridge contract:
9619
+ - You have a parent (the Director). You may call \`request\` on the
9620
+ parent bridge to ask a clarifying question. Use this sparingly; the
9621
+ parent is also working.
9622
+ - You MAY NOT request the parent's system prompt, tool list, or other
9623
+ subagents' context. Those are not yours to read.
9624
+ - Your final task output is what the Director sees. Be concise,
9625
+ structured, and self-contained \u2014 assume the Director will paste your
9626
+ output into its own context.`;
9627
+ function composeDirectorPrompt(parts = {}) {
9628
+ const sections = [];
9629
+ const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
9630
+ if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());
9631
+ if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {
9632
+ sections.push(`Available roles you can spawn:
9633
+ ${parts.rosterSummary.trim()}`);
9634
+ }
9635
+ if (parts.basePrompt && parts.basePrompt.trim().length > 0) {
9636
+ sections.push(parts.basePrompt.trim());
9637
+ }
9638
+ return sections.join("\n\n");
9639
+ }
9640
+ function composeSubagentPrompt(parts = {}) {
9641
+ const sections = [];
9642
+ const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;
9643
+ if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());
9644
+ if (parts.role && parts.role.trim().length > 0) {
9645
+ sections.push(`Role:
9646
+ ${parts.role.trim()}`);
9647
+ }
9648
+ if (parts.task && parts.task.trim().length > 0) {
9649
+ sections.push(`Task:
9650
+ ${parts.task.trim()}`);
9651
+ }
9652
+ if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {
9653
+ sections.push(
9654
+ `Shared notes:
9655
+ A scratchpad shared with the rest of the fleet is mounted at \`${parts.sharedScratchpad.trim()}\`.
9656
+ - Write your final findings as markdown files there (e.g. \`findings.md\`, \`security.md\`).
9657
+ - Before starting, list the directory and read any sibling files relevant to your task \u2014 they may already contain context you can build on.
9658
+ - Use stable filenames (one file per concern); overwrite instead of appending so the Director sees the latest state.`
9659
+ );
9660
+ }
9661
+ if (parts.override && parts.override.trim().length > 0) {
9662
+ sections.push(parts.override.trim());
9663
+ }
9664
+ return sections.join("\n\n");
9665
+ }
9666
+ function rosterSummaryFromConfigs(roster) {
9667
+ const lines = [];
9668
+ for (const [roleId, cfg] of Object.entries(roster)) {
9669
+ const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : "";
9670
+ const headline = cfg.prompt ? (cfg.prompt.split("\n").find((l) => l.trim().length > 0) ?? "").trim().slice(0, 80) : "";
9671
+ const tail = headline ? ` \u2014 ${headline}` : "";
9672
+ lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);
9673
+ }
9674
+ return lines.join("\n");
9675
+ }
9676
+
9677
+ // src/coordination/fleet-bus.ts
9678
+ var FleetBus = class {
9679
+ byId = /* @__PURE__ */ new Map();
9680
+ byType = /* @__PURE__ */ new Map();
9681
+ any = /* @__PURE__ */ new Set();
9682
+ /**
9683
+ * Hook a subagent's EventBus into the fleet. EventBus is strongly
9684
+ * typed and doesn't expose an `onAny` hook, so we subscribe to the
9685
+ * canonical set of event types a subagent emits during a run. New
9686
+ * event types added to the kernel must be added here too — but the
9687
+ * cost is a tiny single line per type, and the explicit list keeps
9688
+ * the wire format clear.
9689
+ *
9690
+ * Returns a disposer that detaches every subscription; call on
9691
+ * subagent teardown so the listeners don't outlive the run.
9692
+ */
9693
+ attach(subagentId, bus, taskId) {
9694
+ const off = bus.onPattern("*", (type, payload) => {
9695
+ if (type.startsWith("subagent.")) return;
9696
+ this.emit({ subagentId, taskId, ts: Date.now(), type, payload });
9697
+ });
9698
+ return () => {
9699
+ off();
9700
+ };
9701
+ }
9702
+ /** Subscribe to every event from one subagent. */
9703
+ subscribe(subagentId, handler) {
9704
+ let set = this.byId.get(subagentId);
9705
+ if (!set) {
9706
+ set = /* @__PURE__ */ new Set();
9707
+ this.byId.set(subagentId, set);
9708
+ }
9709
+ set.add(handler);
9710
+ return () => {
9711
+ set.delete(handler);
9712
+ };
9713
+ }
9714
+ /** Subscribe to one event type across all subagents. */
9715
+ filter(type, handler) {
9716
+ let set = this.byType.get(type);
9717
+ if (!set) {
9718
+ set = /* @__PURE__ */ new Set();
9719
+ this.byType.set(type, set);
9720
+ }
9721
+ set.add(handler);
9722
+ return () => {
9723
+ set.delete(handler);
9724
+ };
9725
+ }
9726
+ /** Subscribe to literally everything. The fleet roll-up uses this. */
9727
+ onAny(handler) {
9728
+ this.any.add(handler);
9729
+ return () => {
9730
+ this.any.delete(handler);
9731
+ };
9732
+ }
9733
+ emit(event) {
9734
+ const byId = this.byId.get(event.subagentId);
9735
+ if (byId)
9736
+ for (const h of byId) {
9737
+ try {
9738
+ h(event);
9739
+ } catch {
9740
+ }
9741
+ }
9742
+ const byType = this.byType.get(event.type);
9743
+ if (byType)
9744
+ for (const h of byType) {
9745
+ try {
9746
+ h(event);
9747
+ } catch {
9748
+ }
9749
+ }
9750
+ for (const h of this.any) {
9751
+ try {
9752
+ h(event);
9753
+ } catch {
9754
+ }
9755
+ }
9756
+ }
9757
+ };
9758
+ var FleetUsageAggregator = class {
9759
+ constructor(bus, priceLookup, metaLookup) {
9760
+ this.bus = bus;
9761
+ this.priceLookup = priceLookup;
9762
+ this.metaLookup = metaLookup;
9763
+ bus.filter("provider.response", (e) => this.onProviderResponse(e));
9764
+ bus.filter("tool.executed", (e) => this.onToolExecuted(e));
9765
+ bus.filter("iteration.started", (e) => this.onIterationStarted(e));
9263
9766
  }
9264
- return {
9265
- kind: "unknown",
9266
- message: baseMessage,
9267
- retryable: false,
9268
- cause
9269
- };
9270
- }
9271
- function providerErrorToSubagentError(err, message, cause) {
9272
- const status = err.status;
9273
- if (status === 429 || err.body?.type === "rate_limit_error") {
9767
+ bus;
9768
+ priceLookup;
9769
+ metaLookup;
9770
+ perSubagent = /* @__PURE__ */ new Map();
9771
+ total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
9772
+ /** Live snapshot — safe to call from a tool's execute() body. */
9773
+ snapshot() {
9274
9774
  return {
9275
- kind: "provider_rate_limit",
9276
- message,
9277
- retryable: true,
9278
- // Conservative default: 5s. Provider-specific code can override
9279
- // by emitting an error whose body carries an explicit hint.
9280
- backoffMs: 5e3,
9281
- cause
9775
+ total: { ...this.total },
9776
+ perSubagent: Object.fromEntries(
9777
+ Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }])
9778
+ )
9282
9779
  };
9283
9780
  }
9284
- if (status === 401 || status === 403 || err.body?.type === "authentication_error") {
9285
- return { kind: "provider_auth", message, retryable: false, cause };
9781
+ ensure(subagentId) {
9782
+ let snap = this.perSubagent.get(subagentId);
9783
+ if (!snap) {
9784
+ const meta = this.metaLookup?.(subagentId);
9785
+ snap = {
9786
+ subagentId,
9787
+ provider: meta?.provider,
9788
+ model: meta?.model,
9789
+ input: 0,
9790
+ output: 0,
9791
+ cacheRead: 0,
9792
+ cacheWrite: 0,
9793
+ cost: 0,
9794
+ toolCalls: 0,
9795
+ iterations: 0,
9796
+ startedAt: Date.now(),
9797
+ lastEventAt: Date.now()
9798
+ };
9799
+ this.perSubagent.set(subagentId, snap);
9800
+ }
9801
+ return snap;
9286
9802
  }
9287
- if (status === 408 || status === 0) {
9288
- return { kind: "provider_timeout", message, retryable: true, cause };
9803
+ onProviderResponse(e) {
9804
+ const snap = this.ensure(e.subagentId);
9805
+ const p = e.payload;
9806
+ const usage = p?.usage;
9807
+ if (!usage) return;
9808
+ snap.input += usage.input ?? 0;
9809
+ snap.output += usage.output ?? 0;
9810
+ snap.cacheRead += usage.cacheRead ?? 0;
9811
+ snap.cacheWrite += usage.cacheWrite ?? 0;
9812
+ this.total.input += usage.input ?? 0;
9813
+ this.total.output += usage.output ?? 0;
9814
+ this.total.cacheRead += usage.cacheRead ?? 0;
9815
+ this.total.cacheWrite += usage.cacheWrite ?? 0;
9816
+ const price = this.priceLookup?.(e.subagentId);
9817
+ if (price) {
9818
+ 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);
9819
+ snap.cost += delta;
9820
+ this.total.cost += delta;
9821
+ }
9822
+ snap.lastEventAt = e.ts;
9289
9823
  }
9290
- if (status >= 500 && status < 600) {
9291
- return {
9292
- kind: "provider_5xx",
9293
- message,
9294
- retryable: true,
9295
- backoffMs: 3e3,
9296
- cause
9297
- };
9824
+ onToolExecuted(e) {
9825
+ const snap = this.ensure(e.subagentId);
9826
+ snap.toolCalls += 1;
9827
+ snap.lastEventAt = e.ts;
9298
9828
  }
9299
- return { kind: "unknown", message, retryable: err.retryable, cause };
9300
- }
9829
+ onIterationStarted(e) {
9830
+ const snap = this.ensure(e.subagentId);
9831
+ snap.iterations += 1;
9832
+ snap.lastEventAt = e.ts;
9833
+ }
9834
+ };
9301
9835
  function makeSpawnTool(director, roster) {
9302
9836
  const inputSchema = {
9303
9837
  type: "object",
@@ -9678,7 +10212,7 @@ var Director = class {
9678
10212
  this.sessionWriter = opts.sessionWriter ?? null;
9679
10213
  this.manifestDebounceMs = opts.manifestDebounceMs ?? 2e3;
9680
10214
  this.maxFleetCostUsd = opts.directorBudget?.maxCostUsd ?? Number.POSITIVE_INFINITY;
9681
- this.maxBudgetExtensions = opts.maxBudgetExtensions ?? 2;
10215
+ this.maxBudgetExtensions = opts.maxBudgetExtensions ?? 5;
9682
10216
  this.sessionsRoot = opts.sessionsRoot;
9683
10217
  this.directorRunId = opts.directorRunId ?? this.id;
9684
10218
  this.stateCheckpoint = opts.stateCheckpointPath ? new DirectorStateCheckpoint(opts.stateCheckpointPath, {
@@ -9766,19 +10300,19 @@ var Director = class {
9766
10300
  const extra = {};
9767
10301
  switch (payload.kind) {
9768
10302
  case "iterations":
9769
- extra.maxIterations = Math.min(payload.used + 50, 500);
10303
+ extra.maxIterations = Math.min(payload.used + 100, 800);
9770
10304
  break;
9771
10305
  case "tool_calls":
9772
- extra.maxToolCalls = Math.min(Math.ceil(payload.limit * 1.5), 1e3);
10306
+ extra.maxToolCalls = Math.min(Math.ceil(payload.limit * 2), 1500);
9773
10307
  break;
9774
10308
  case "tokens":
9775
- extra.maxTokens = Math.min(Math.ceil(payload.limit * 1.5), 5e5);
10309
+ extra.maxTokens = Math.min(Math.ceil(payload.limit * 2), 8e5);
9776
10310
  break;
9777
10311
  case "cost":
9778
- extra.maxCostUsd = Math.min(payload.limit * 1.5, 10);
10312
+ extra.maxCostUsd = Math.min(payload.limit * 2, 25);
9779
10313
  break;
9780
10314
  case "timeout":
9781
- extra.timeoutMs = Math.min(Math.ceil(payload.limit * 1.5), 60 * 6e4);
10315
+ extra.timeoutMs = Math.min(Math.ceil(payload.limit * 2), 2 * 60 * 6e4);
9782
10316
  break;
9783
10317
  }
9784
10318
  payload.extend(extra);
@@ -10567,136 +11101,6 @@ async function readSubagentPartial(opts, subagentId) {
10567
11101
  }
10568
11102
  return void 0;
10569
11103
  }
10570
-
10571
- // src/coordination/agent-subagent-runner.ts
10572
- function makeAgentSubagentRunner(opts) {
10573
- const format = opts.formatTaskInput ?? defaultFormatTaskInput;
10574
- return async (task, ctx) => {
10575
- const factoryResult = await opts.factory(ctx.config);
10576
- const { agent, events } = factoryResult;
10577
- const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);
10578
- const aborter = new AbortController();
10579
- ctx.budget._events = events;
10580
- ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();
10581
- let budgetError = null;
10582
- const onBudgetError = (err) => {
10583
- if (err instanceof BudgetThresholdSignal) {
10584
- err.decision.then((decision) => {
10585
- if (decision === "stop") {
10586
- budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
10587
- aborter.abort();
10588
- }
10589
- }).catch(() => {
10590
- budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
10591
- aborter.abort();
10592
- });
10593
- return;
10594
- }
10595
- aborter.abort();
10596
- budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
10597
- "tool_calls",
10598
- 0,
10599
- 0
10600
- );
10601
- if (budgetError !== err && err instanceof Error) {
10602
- budgetError.message += ` (caused by: ${err.message})`;
10603
- }
10604
- };
10605
- let lastToolFailed = null;
10606
- const unsub = [];
10607
- unsub.push(
10608
- events.on("tool.executed", (e) => {
10609
- try {
10610
- ctx.budget.recordToolCall();
10611
- } catch (eb) {
10612
- onBudgetError(eb);
10613
- }
10614
- if (e.ok === false) {
10615
- lastToolFailed = e.name;
10616
- } else if (e.ok === true) {
10617
- lastToolFailed = null;
10618
- }
10619
- }),
10620
- events.on("provider.response", (e) => {
10621
- try {
10622
- ctx.budget.recordUsage(e.usage);
10623
- } catch (e2) {
10624
- void onBudgetError(e2);
10625
- }
10626
- }),
10627
- events.on("iteration.started", () => {
10628
- try {
10629
- ctx.budget.recordIteration();
10630
- ctx.budget.checkTimeout();
10631
- } catch (e) {
10632
- void onBudgetError(e);
10633
- }
10634
- }),
10635
- // D3: cooperative timeout enforcement DURING a long tool call.
10636
- // The iteration-loop checkTimeout() only fires between agent
10637
- // iterations — a single `bash sleep 3600` call would otherwise
10638
- // park inside one tool execution while the timeout silently
10639
- // passes, relying solely on the coordinator's hard Promise.race
10640
- // to interrupt. Tools that emit `tool.progress` (bash chunks,
10641
- // fetch byte progress, spawn-stream stdout) give us a heartbeat
10642
- // we can hang the check on. When the budget trips here:
10643
- // 1. onBudgetError sets budgetError + aborter.abort()
10644
- // 2. aborter signal propagates to agent.run → tool executor
10645
- // 3. tool's own signal listener kills the child process
10646
- // Cheap: O(1) per progress event, and the budget short-circuits
10647
- // when timeoutMs is unset (most subagents have one set anyway).
10648
- events.on("tool.progress", () => {
10649
- try {
10650
- ctx.budget.checkTimeout();
10651
- } catch (e) {
10652
- void onBudgetError(e);
10653
- }
10654
- })
10655
- );
10656
- const onParentAbort = () => aborter.abort();
10657
- ctx.signal.addEventListener("abort", onParentAbort);
10658
- let result;
10659
- try {
10660
- result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
10661
- } finally {
10662
- detachFleet?.();
10663
- ctx.signal.removeEventListener("abort", onParentAbort);
10664
- for (const u of unsub) u();
10665
- if (factoryResult.dispose) {
10666
- try {
10667
- await factoryResult.dispose();
10668
- } catch {
10669
- }
10670
- }
10671
- }
10672
- if (budgetError) throw budgetError;
10673
- if (result.status === "failed") {
10674
- throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
10675
- }
10676
- if (result.status === "aborted") {
10677
- throw new Error("agent aborted");
10678
- }
10679
- if (result.status === "max_iterations") {
10680
- throw new Error("agent exhausted iteration limit");
10681
- }
10682
- const usage = ctx.budget.usage();
10683
- const finalText = (result.finalText ?? "").trim();
10684
- if (finalText.length === 0 && usage.toolCalls === 0) {
10685
- throw new Error("empty response");
10686
- }
10687
- if (finalText.length === 0 && lastToolFailed !== null) {
10688
- throw new Error(`tool failed: ${lastToolFailed}`);
10689
- }
10690
- return {
10691
- result: result.finalText,
10692
- iterations: result.iterations,
10693
- toolCalls: usage.toolCalls
10694
- };
10695
- };
10696
- }
10697
- function defaultFormatTaskInput(task) {
10698
- return task.description ?? "";
10699
- }
10700
11104
  function makeDirectorSessionFactory(opts) {
10701
11105
  const runId = opts.directorRunId ?? `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-director`;
10702
11106
  let store;
@@ -19364,6 +19768,6 @@ function wrapApiForCapabilityCheck(plugin, api, log, enforce = false) {
19364
19768
  });
19365
19769
  }
19366
19770
 
19367
- export { AISpecBuilder, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, Agent, AgentError, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, CONTEXT_WINDOW_MODES, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FleetBus, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, GitignoreUpdater, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, ScopedEventBus, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolError, ToolExecutor, ToolRegistry, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, atomicWrite, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, color, compileGlob, compileUserRegex, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, context7Server, contextManagerTool, createAutoExecutor, createContextManagerTool, createDefaultPipelines, createDelegateTool, createMcpControlTool, createMessage, createSecuritySlashCommand, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, ensureDir, estimateRequestTokens, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, extractRunEnv, filesystemServer, findCriticalPath, formatContextWindowModeList, formatGoal, formatPlan, formatPlanTemplates, formatTodosList, getContextWindowMode, getPlanTemplate, getTemplate, githubServer, goalFilePath, googleMapsServer, isAgentError, isConfigError, isContextWindowModeId, isImageBlock, isPluginError, isSessionError, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAutonomyPromptContributor, makeContinueToNextIterationTool, makeDirectorSessionFactory, matchAny, matchGlob, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, parseContinueDirective, parseSkillRef, projectHash, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resolveContextWindowPolicy, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, securitySlashCommand, sentinelServer, setPlanItemStatus, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, zaiVisionServer };
19771
+ export { AISpecBuilder, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, Agent, AgentError, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, CONTEXT_WINDOW_MODES, ConfigError, ConfigMigrationError, Container, Context, ConversationState, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorStateCheckpoint, DoneConditionChecker, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FleetBus, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, GitignoreUpdater, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, LAYER_1_IDENTITY, LLMSelector, MAX_JOURNAL_ENTRIES, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, ScopedEventBus, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TOKENS, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolError, ToolExecutor, ToolRegistry, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyRosterBudget, asBlocks, asText, atomicWrite, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildChildEnv, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildRecoveryStrategies, classifyFamily, clearPlan, color, compileGlob, compileUserRegex, composeDirectorPrompt, composeSubagentPrompt, computeTaskProgress, context7Server, contextManagerTool, createAutoExecutor, createContextManagerTool, createDefaultPipelines, createDelegateTool, createMcpControlTool, createMessage, createSecuritySlashCommand, createToolOutputSerializer, decryptConfigSecrets, defaultGitignoreUpdater, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, deriveTodosFromPlanItem, detectNewlineStyle, downloadGitHubTarball, emptyGoal, emptyPlan, encryptConfigSecrets, ensureDir, estimateRequestTokens, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, extractRunEnv, filesystemServer, findCriticalPath, formatContextWindowModeList, formatGoal, formatPlan, formatPlanTemplates, formatTodosList, getContextWindowMode, getPlanTemplate, getTemplate, githubServer, goalFilePath, googleMapsServer, isAgentError, isConfigError, isContextWindowModeId, isImageBlock, isPluginError, isSessionError, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAutonomyPromptContributor, makeContinueToNextIterationTool, makeDirectorSessionFactory, matchAny, matchGlob, migratePlaintextSecrets, miniMaxVisionServer, normalizeToLf, parseContinueDirective, parseSkillRef, projectHash, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, resolveContextWindowPolicy, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTodosCheckpoint, securitySlashCommand, sentinelServer, setPlanItemStatus, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, stripAnsi, summarizeUsage, templateToMarkdown, toStyle, toWrongStackError, topologicalSort, unifiedDiff, unloadPlugins, validateAgainstSchema, wireMetricsToEvents, wrapAsState, zaiVisionServer };
19368
19772
  //# sourceMappingURL=index.js.map
19369
19773
  //# sourceMappingURL=index.js.map