@wrongstack/core 0.1.8 → 0.1.10

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 (73) hide show
  1. package/dist/agent-bridge-6KPqsFx6.d.ts +33 -0
  2. package/dist/compactor-B4mQZXf2.d.ts +17 -0
  3. package/dist/config-BU9f_5yH.d.ts +193 -0
  4. package/dist/{provider-txgB0Oq9.d.ts → context-BmM2xGUZ.d.ts} +532 -472
  5. package/dist/coordination/index.d.ts +694 -0
  6. package/dist/coordination/index.js +1995 -0
  7. package/dist/coordination/index.js.map +1 -0
  8. package/dist/defaults/index.d.ts +34 -2206
  9. package/dist/defaults/index.js +4116 -3790
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/events-BMNaEFZl.d.ts +218 -0
  12. package/dist/execution/index.d.ts +260 -0
  13. package/dist/execution/index.js +1625 -0
  14. package/dist/execution/index.js.map +1 -0
  15. package/dist/index.d.ts +50 -12
  16. package/dist/index.js +6669 -5909
  17. package/dist/index.js.map +1 -1
  18. package/dist/infrastructure/index.d.ts +10 -0
  19. package/dist/infrastructure/index.js +575 -0
  20. package/dist/infrastructure/index.js.map +1 -0
  21. package/dist/input-reader-E-ffP2ee.d.ts +12 -0
  22. package/dist/kernel/index.d.ts +15 -4
  23. package/dist/kernel/index.js.map +1 -1
  24. package/dist/logger-BH6AE0W9.d.ts +24 -0
  25. package/dist/logger-BMQgxvdy.d.ts +12 -0
  26. package/dist/mcp-servers-Dzgg4x1w.d.ts +100 -0
  27. package/dist/memory-CEXuo7sz.d.ts +16 -0
  28. package/dist/mode-CV077NjV.d.ts +27 -0
  29. package/dist/models/index.d.ts +60 -0
  30. package/dist/models/index.js +621 -0
  31. package/dist/models/index.js.map +1 -0
  32. package/dist/models-registry-DqzwpBQy.d.ts +46 -0
  33. package/dist/models-registry-Y2xbog0E.d.ts +95 -0
  34. package/dist/multi-agent-fmkRHtof.d.ts +283 -0
  35. package/dist/observability/index.d.ts +353 -0
  36. package/dist/observability/index.js +691 -0
  37. package/dist/observability/index.js.map +1 -0
  38. package/dist/observability-BhnVLBLS.d.ts +67 -0
  39. package/dist/path-resolver-CPRj4bFY.d.ts +10 -0
  40. package/dist/path-resolver-DBjaoXFq.d.ts +54 -0
  41. package/dist/plugin-DJk6LL8B.d.ts +434 -0
  42. package/dist/renderer-rk_1Swwc.d.ts +158 -0
  43. package/dist/sdd/index.d.ts +206 -0
  44. package/dist/sdd/index.js +864 -0
  45. package/dist/sdd/index.js.map +1 -0
  46. package/dist/secret-scrubber-CicHLN4G.d.ts +31 -0
  47. package/dist/secret-scrubber-DF88luOe.d.ts +54 -0
  48. package/dist/secret-vault-DoISxaKO.d.ts +19 -0
  49. package/dist/security/index.d.ts +30 -0
  50. package/dist/security/index.js +524 -0
  51. package/dist/security/index.js.map +1 -0
  52. package/dist/selector-BbJqiEP4.d.ts +51 -0
  53. package/dist/session-reader-Drq8RvJu.d.ts +150 -0
  54. package/dist/skill-DhfSizKv.d.ts +72 -0
  55. package/dist/storage/index.d.ts +382 -0
  56. package/dist/storage/index.js +1530 -0
  57. package/dist/storage/index.js.map +1 -0
  58. package/dist/{system-prompt-vAB0F54-.d.ts → system-prompt-BC_8ypCG.d.ts} +1 -1
  59. package/dist/task-graph-BITvWt4t.d.ts +160 -0
  60. package/dist/tool-executor-CpuJPYm9.d.ts +97 -0
  61. package/dist/types/index.d.ts +26 -4
  62. package/dist/types/index.js +1787 -4
  63. package/dist/types/index.js.map +1 -1
  64. package/dist/utils/index.d.ts +49 -2
  65. package/dist/utils/index.js +100 -2
  66. package/dist/utils/index.js.map +1 -1
  67. package/package.json +34 -2
  68. package/skills/audit-log/SKILL.md +67 -0
  69. package/skills/bug-hunter/SKILL.md +87 -0
  70. package/skills/refactor-planner/SKILL.md +94 -0
  71. package/skills/security-scanner/SKILL.md +117 -0
  72. package/dist/mode-Pjt5vMS6.d.ts +0 -815
  73. package/dist/session-reader-9sOTgmeC.d.ts +0 -1087
@@ -0,0 +1,1995 @@
1
+ import { randomUUID, randomBytes } from 'crypto';
2
+ import * as fsp2 from 'fs/promises';
3
+ import * as path3 from 'path';
4
+ import { EventEmitter } from 'events';
5
+
6
+ // src/coordination/director.ts
7
+
8
+ // src/coordination/in-memory-transport.ts
9
+ var InMemoryBridgeTransport = class {
10
+ subs = /* @__PURE__ */ new Map();
11
+ send(msg, to) {
12
+ if (to === "*") {
13
+ for (const [id, handlers2] of this.subs) {
14
+ if (id === msg.from) continue;
15
+ for (const h of handlers2) {
16
+ try {
17
+ h(msg);
18
+ } catch {
19
+ }
20
+ }
21
+ }
22
+ return Promise.resolve();
23
+ }
24
+ const handlers = this.subs.get(to);
25
+ if (handlers) {
26
+ for (const h of handlers) {
27
+ try {
28
+ h(msg);
29
+ } catch {
30
+ }
31
+ }
32
+ }
33
+ return Promise.resolve();
34
+ }
35
+ subscribe(agentId, handler) {
36
+ if (!this.subs.has(agentId)) this.subs.set(agentId, /* @__PURE__ */ new Set());
37
+ this.subs.get(agentId).add(handler);
38
+ return () => this.subs.get(agentId)?.delete(handler);
39
+ }
40
+ close(agentId) {
41
+ this.subs.delete(agentId);
42
+ return Promise.resolve();
43
+ }
44
+ };
45
+
46
+ // src/coordination/agent-bridge.ts
47
+ var InMemoryAgentBridge = class {
48
+ agentId;
49
+ coordinatorId;
50
+ transport;
51
+ subscriptions = /* @__PURE__ */ new Set();
52
+ pendingRequests = /* @__PURE__ */ new Map();
53
+ stopped = false;
54
+ timeoutMs;
55
+ /** Guards request() so concurrent calls on the same id can't silently overwrite. */
56
+ inflightGuards = /* @__PURE__ */ new Set();
57
+ constructor(config, transport) {
58
+ this.agentId = config.agentId;
59
+ this.coordinatorId = config.coordinatorId;
60
+ this.transport = transport;
61
+ this.timeoutMs = config.timeoutMs ?? 3e4;
62
+ this.transport.subscribe(this.agentId, (msg) => {
63
+ if (msg.type === "heartbeat") return;
64
+ const pending = this.pendingRequests.get(msg.id);
65
+ if (pending) {
66
+ clearTimeout(pending.timer);
67
+ this.pendingRequests.delete(msg.id);
68
+ this.inflightGuards.delete(msg.id);
69
+ pending.resolve(msg);
70
+ return;
71
+ }
72
+ for (const h of this.subscriptions) {
73
+ try {
74
+ h(msg);
75
+ } catch {
76
+ }
77
+ }
78
+ });
79
+ }
80
+ async send(msg) {
81
+ msg.timestamp = Date.now();
82
+ await this.transport.send(msg, msg.to ?? this.coordinatorId);
83
+ }
84
+ async broadcast(msg) {
85
+ msg.timestamp = Date.now();
86
+ msg.to = "*";
87
+ await this.transport.send(msg, "*");
88
+ }
89
+ subscribe(handler) {
90
+ this.subscriptions.add(handler);
91
+ return () => this.subscriptions.delete(handler);
92
+ }
93
+ async request(msg, timeoutMs) {
94
+ if (this.stopped) throw new Error("Bridge is stopped");
95
+ const timeout = timeoutMs ?? this.timeoutMs;
96
+ const correlationId = msg.id;
97
+ if (this.inflightGuards.has(correlationId)) {
98
+ throw new Error(
99
+ `Bridge request id "${correlationId}" collides with an in-flight request \u2014 caller is reusing message ids`
100
+ );
101
+ }
102
+ this.inflightGuards.add(correlationId);
103
+ return new Promise((resolve, reject) => {
104
+ const timer = setTimeout(() => {
105
+ this.inflightGuards.delete(correlationId);
106
+ this.pendingRequests.delete(correlationId);
107
+ reject(new Error(`Request ${correlationId} timed out after ${timeout}ms`));
108
+ }, timeout);
109
+ this.pendingRequests.set(correlationId, {
110
+ resolve,
111
+ reject,
112
+ timer
113
+ });
114
+ msg.timestamp = Date.now();
115
+ this.transport.send(msg, msg.to ?? this.coordinatorId).catch((e) => {
116
+ clearTimeout(timer);
117
+ this.inflightGuards.delete(correlationId);
118
+ this.pendingRequests.delete(correlationId);
119
+ reject(e);
120
+ });
121
+ });
122
+ }
123
+ async stop() {
124
+ this.stopped = true;
125
+ for (const [, p] of this.pendingRequests) {
126
+ clearTimeout(p.timer);
127
+ }
128
+ this.pendingRequests.clear();
129
+ this.inflightGuards.clear();
130
+ this.subscriptions.clear();
131
+ await this.transport.close(this.agentId);
132
+ }
133
+ };
134
+ function createMessage(type, from, payload, to) {
135
+ return {
136
+ id: randomUUID(),
137
+ type,
138
+ from,
139
+ to,
140
+ payload,
141
+ timestamp: Date.now(),
142
+ priority: "normal"
143
+ };
144
+ }
145
+
146
+ // src/coordination/director-prompts.ts
147
+ var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
148
+ subagents by spawning them, assigning tasks, awaiting completions, and
149
+ rolling up their outputs into your next decision.
150
+
151
+ Core fleet tools available to you:
152
+ - spawn_subagent \u2014 create a worker with a chosen provider / model / role
153
+ - assign_task \u2014 hand a piece of work to a specific subagent
154
+ - await_tasks \u2014 block until named task ids complete (parallel-safe)
155
+ - ask_subagent \u2014 synchronously query a running subagent via the bridge
156
+ - roll_up \u2014 aggregate finished tasks into a markdown/json summary
157
+ - terminate_subagent \u2014 abort a stuck worker (use sparingly)
158
+ - fleet_status \u2014 snapshot of all subagents and pending tasks
159
+ - fleet_usage \u2014 token + cost breakdown per subagent and total
160
+
161
+ Working rules:
162
+ 1. Decompose first. Before spawning, decide which sub-tasks are
163
+ independent and can run in parallel. Sequential work doesn't need a
164
+ subagent \u2014 do it yourself.
165
+ 2. Match worker to job. Cheap/fast model for triage, capable model for
166
+ synthesis. Different providers per sibling is allowed and encouraged.
167
+ 3. Always pair an assign with an await. Don't fire-and-forget; you owe
168
+ the user a single coherent answer at the end.
169
+ 4. Roll up before deciding. After await_tasks resolves, call roll_up so
170
+ the results are folded back into your context in a compact form.
171
+ 5. Budget is real. Check fleet_usage periodically. If a subagent is
172
+ thrashing, terminate it rather than letting cost climb silently.
173
+ 6. Never claim a subagent's work as your own without verifying it. If a
174
+ result looks wrong, ask_subagent for clarification before passing it
175
+ to the user.`;
176
+ var DEFAULT_SUBAGENT_BASELINE = `You are a subagent operating under a Director. You were spawned to handle
177
+ a specific slice of a larger plan \u2014 do that slice well and report back.
178
+
179
+ Bridge contract:
180
+ - You have a parent (the Director). You may call \`request\` on the
181
+ parent bridge to ask a clarifying question. Use this sparingly; the
182
+ parent is also working.
183
+ - You MAY NOT request the parent's system prompt, tool list, or other
184
+ subagents' context. Those are not yours to read.
185
+ - Your final task output is what the Director sees. Be concise,
186
+ structured, and self-contained \u2014 assume the Director will paste your
187
+ output into its own context.`;
188
+ function composeDirectorPrompt(parts = {}) {
189
+ const sections = [];
190
+ const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
191
+ if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());
192
+ if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {
193
+ sections.push(`Available roles you can spawn:
194
+ ${parts.rosterSummary.trim()}`);
195
+ }
196
+ if (parts.basePrompt && parts.basePrompt.trim().length > 0) {
197
+ sections.push(parts.basePrompt.trim());
198
+ }
199
+ return sections.join("\n\n");
200
+ }
201
+ function composeSubagentPrompt(parts = {}) {
202
+ const sections = [];
203
+ const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;
204
+ if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());
205
+ if (parts.role && parts.role.trim().length > 0) {
206
+ sections.push(`Role:
207
+ ${parts.role.trim()}`);
208
+ }
209
+ if (parts.task && parts.task.trim().length > 0) {
210
+ sections.push(`Task:
211
+ ${parts.task.trim()}`);
212
+ }
213
+ if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {
214
+ sections.push(
215
+ `Shared notes:
216
+ A scratchpad shared with the rest of the fleet is mounted at \`${parts.sharedScratchpad.trim()}\`.
217
+ - Write your final findings as markdown files there (e.g. \`findings.md\`, \`security.md\`).
218
+ - Before starting, list the directory and read any sibling files relevant to your task \u2014 they may already contain context you can build on.
219
+ - Use stable filenames (one file per concern); overwrite instead of appending so the Director sees the latest state.`
220
+ );
221
+ }
222
+ if (parts.override && parts.override.trim().length > 0) {
223
+ sections.push(parts.override.trim());
224
+ }
225
+ return sections.join("\n\n");
226
+ }
227
+ function rosterSummaryFromConfigs(roster) {
228
+ const lines = [];
229
+ for (const [roleId, cfg] of Object.entries(roster)) {
230
+ const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : "";
231
+ const headline = cfg.prompt ? (cfg.prompt.split("\n").find((l) => l.trim().length > 0) ?? "").trim().slice(0, 80) : "";
232
+ const tail = headline ? ` \u2014 ${headline}` : "";
233
+ lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);
234
+ }
235
+ return lines.join("\n");
236
+ }
237
+
238
+ // src/coordination/fleet-bus.ts
239
+ var FleetBus = class {
240
+ byId = /* @__PURE__ */ new Map();
241
+ byType = /* @__PURE__ */ new Map();
242
+ any = /* @__PURE__ */ new Set();
243
+ /**
244
+ * Hook a subagent's EventBus into the fleet. EventBus is strongly
245
+ * typed and doesn't expose an `onAny` hook, so we subscribe to the
246
+ * canonical set of event types a subagent emits during a run. New
247
+ * event types added to the kernel must be added here too — but the
248
+ * cost is a tiny single line per type, and the explicit list keeps
249
+ * the wire format clear.
250
+ *
251
+ * Returns a disposer that detaches every subscription; call on
252
+ * subagent teardown so the listeners don't outlive the run.
253
+ */
254
+ attach(subagentId, bus, taskId) {
255
+ const FORWARDED_TYPES = [
256
+ "tool.started",
257
+ "tool.executed",
258
+ "tool.progress",
259
+ "tool.confirm_needed",
260
+ "iteration.started",
261
+ "iteration.completed",
262
+ "provider.text_delta",
263
+ "provider.response",
264
+ "provider.retry",
265
+ "provider.error",
266
+ "session.started",
267
+ "session.ended",
268
+ "session.damaged",
269
+ "compaction.fired",
270
+ "compaction.failed",
271
+ "token.threshold"
272
+ ];
273
+ const offs = [];
274
+ for (const t of FORWARDED_TYPES) {
275
+ offs.push(
276
+ bus.on(t, (payload) => {
277
+ this.emit({ subagentId, taskId, ts: Date.now(), type: t, payload });
278
+ })
279
+ );
280
+ }
281
+ return () => {
282
+ for (const off of offs) off();
283
+ };
284
+ }
285
+ /** Subscribe to every event from one subagent. */
286
+ subscribe(subagentId, handler) {
287
+ let set = this.byId.get(subagentId);
288
+ if (!set) {
289
+ set = /* @__PURE__ */ new Set();
290
+ this.byId.set(subagentId, set);
291
+ }
292
+ set.add(handler);
293
+ return () => {
294
+ set.delete(handler);
295
+ };
296
+ }
297
+ /** Subscribe to one event type across all subagents. */
298
+ filter(type, handler) {
299
+ let set = this.byType.get(type);
300
+ if (!set) {
301
+ set = /* @__PURE__ */ new Set();
302
+ this.byType.set(type, set);
303
+ }
304
+ set.add(handler);
305
+ return () => {
306
+ set.delete(handler);
307
+ };
308
+ }
309
+ /** Subscribe to literally everything. The fleet roll-up uses this. */
310
+ onAny(handler) {
311
+ this.any.add(handler);
312
+ return () => {
313
+ this.any.delete(handler);
314
+ };
315
+ }
316
+ emit(event) {
317
+ const byId = this.byId.get(event.subagentId);
318
+ if (byId)
319
+ for (const h of byId) {
320
+ try {
321
+ h(event);
322
+ } catch {
323
+ }
324
+ }
325
+ const byType = this.byType.get(event.type);
326
+ if (byType)
327
+ for (const h of byType) {
328
+ try {
329
+ h(event);
330
+ } catch {
331
+ }
332
+ }
333
+ for (const h of this.any) {
334
+ try {
335
+ h(event);
336
+ } catch {
337
+ }
338
+ }
339
+ }
340
+ };
341
+ var FleetUsageAggregator = class {
342
+ constructor(bus, priceLookup, metaLookup) {
343
+ this.bus = bus;
344
+ this.priceLookup = priceLookup;
345
+ this.metaLookup = metaLookup;
346
+ bus.filter("provider.response", (e) => this.onProviderResponse(e));
347
+ bus.filter("tool.executed", (e) => this.onToolExecuted(e));
348
+ bus.filter("iteration.started", (e) => this.onIterationStarted(e));
349
+ }
350
+ bus;
351
+ priceLookup;
352
+ metaLookup;
353
+ perSubagent = /* @__PURE__ */ new Map();
354
+ total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
355
+ /** Live snapshot — safe to call from a tool's execute() body. */
356
+ snapshot() {
357
+ return {
358
+ total: { ...this.total },
359
+ perSubagent: Object.fromEntries(
360
+ Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }])
361
+ )
362
+ };
363
+ }
364
+ ensure(subagentId) {
365
+ let snap = this.perSubagent.get(subagentId);
366
+ if (!snap) {
367
+ const meta = this.metaLookup?.(subagentId);
368
+ snap = {
369
+ subagentId,
370
+ provider: meta?.provider,
371
+ model: meta?.model,
372
+ input: 0,
373
+ output: 0,
374
+ cacheRead: 0,
375
+ cacheWrite: 0,
376
+ cost: 0,
377
+ toolCalls: 0,
378
+ iterations: 0,
379
+ startedAt: Date.now(),
380
+ lastEventAt: Date.now()
381
+ };
382
+ this.perSubagent.set(subagentId, snap);
383
+ }
384
+ return snap;
385
+ }
386
+ onProviderResponse(e) {
387
+ const snap = this.ensure(e.subagentId);
388
+ const p = e.payload;
389
+ const usage = p?.usage;
390
+ if (!usage) return;
391
+ snap.input += usage.input ?? 0;
392
+ snap.output += usage.output ?? 0;
393
+ snap.cacheRead += usage.cacheRead ?? 0;
394
+ snap.cacheWrite += usage.cacheWrite ?? 0;
395
+ this.total.input += usage.input ?? 0;
396
+ this.total.output += usage.output ?? 0;
397
+ this.total.cacheRead += usage.cacheRead ?? 0;
398
+ this.total.cacheWrite += usage.cacheWrite ?? 0;
399
+ const price = this.priceLookup?.(e.subagentId);
400
+ if (price) {
401
+ 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);
402
+ snap.cost += delta;
403
+ this.total.cost += delta;
404
+ }
405
+ snap.lastEventAt = e.ts;
406
+ }
407
+ onToolExecuted(e) {
408
+ const snap = this.ensure(e.subagentId);
409
+ snap.toolCalls += 1;
410
+ snap.lastEventAt = e.ts;
411
+ }
412
+ onIterationStarted(e) {
413
+ const snap = this.ensure(e.subagentId);
414
+ snap.iterations += 1;
415
+ snap.lastEventAt = e.ts;
416
+ }
417
+ };
418
+
419
+ // src/coordination/subagent-budget.ts
420
+ var BudgetExceededError = class extends Error {
421
+ kind;
422
+ limit;
423
+ observed;
424
+ constructor(kind, limit, observed) {
425
+ super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);
426
+ this.name = "BudgetExceededError";
427
+ this.kind = kind;
428
+ this.limit = limit;
429
+ this.observed = observed;
430
+ }
431
+ };
432
+ var SubagentBudget = class {
433
+ limits;
434
+ iterations = 0;
435
+ toolCalls = 0;
436
+ tokenInput = 0;
437
+ tokenOutput = 0;
438
+ costUsd = 0;
439
+ startTime = null;
440
+ constructor(limits = {}) {
441
+ this.limits = Object.freeze({ ...limits });
442
+ }
443
+ start() {
444
+ this.startTime = Date.now();
445
+ }
446
+ recordIteration() {
447
+ this.iterations++;
448
+ if (this.limits.maxIterations !== void 0 && this.iterations > this.limits.maxIterations) {
449
+ throw new BudgetExceededError("iterations", this.limits.maxIterations, this.iterations);
450
+ }
451
+ }
452
+ recordToolCall() {
453
+ this.toolCalls++;
454
+ if (this.limits.maxToolCalls !== void 0 && this.toolCalls > this.limits.maxToolCalls) {
455
+ throw new BudgetExceededError("tool_calls", this.limits.maxToolCalls, this.toolCalls);
456
+ }
457
+ }
458
+ recordUsage(usage, costUsd = 0) {
459
+ this.tokenInput += usage.input;
460
+ this.tokenOutput += usage.output;
461
+ this.costUsd += costUsd;
462
+ const totalTokens = this.tokenInput + this.tokenOutput;
463
+ if (this.limits.maxTokens !== void 0 && totalTokens > this.limits.maxTokens) {
464
+ throw new BudgetExceededError("tokens", this.limits.maxTokens, totalTokens);
465
+ }
466
+ if (this.limits.maxCostUsd !== void 0 && this.costUsd > this.limits.maxCostUsd) {
467
+ throw new BudgetExceededError("cost", this.limits.maxCostUsd, this.costUsd);
468
+ }
469
+ }
470
+ /**
471
+ * Throws if the wall-clock budget is exhausted. Call this from the iteration
472
+ * loop so a hung tool can't keep a subagent running past its deadline.
473
+ */
474
+ checkTimeout() {
475
+ if (this.startTime === null || this.limits.timeoutMs === void 0) return;
476
+ const elapsed = Date.now() - this.startTime;
477
+ if (elapsed > this.limits.timeoutMs) {
478
+ throw new BudgetExceededError("timeout", this.limits.timeoutMs, elapsed);
479
+ }
480
+ }
481
+ /** Returns true if a timeout has occurred without throwing. Useful for races. */
482
+ isTimedOut() {
483
+ if (this.startTime === null || this.limits.timeoutMs === void 0) return false;
484
+ return Date.now() - this.startTime > this.limits.timeoutMs;
485
+ }
486
+ usage() {
487
+ return {
488
+ iterations: this.iterations,
489
+ toolCalls: this.toolCalls,
490
+ tokens: {
491
+ input: this.tokenInput,
492
+ output: this.tokenOutput,
493
+ total: this.tokenInput + this.tokenOutput
494
+ },
495
+ costUsd: this.costUsd,
496
+ elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime
497
+ };
498
+ }
499
+ };
500
+
501
+ // src/coordination/multi-agent-coordinator.ts
502
+ var DefaultMultiAgentCoordinator = class extends EventEmitter {
503
+ coordinatorId;
504
+ config;
505
+ runner;
506
+ subagents = /* @__PURE__ */ new Map();
507
+ pendingTasks = [];
508
+ completedResults = [];
509
+ totalIterations = 0;
510
+ inFlight = 0;
511
+ constructor(config, options = {}) {
512
+ super();
513
+ this.coordinatorId = config.coordinatorId;
514
+ this.config = config;
515
+ this.runner = options.runner;
516
+ }
517
+ async spawn(subagent) {
518
+ const id = subagent.id || randomUUID();
519
+ const context = {
520
+ subagentId: id,
521
+ tasks: [],
522
+ // Wired later by the caller via setSubagentBridge() once the
523
+ // bidirectional bridge is created. Readers must null-check / use
524
+ // hasParentBridge() — the type now reflects this.
525
+ parentBridge: null,
526
+ doneCondition: this.config.doneCondition,
527
+ maxConcurrent: this.config.maxConcurrent ?? 4
528
+ };
529
+ this.subagents.set(id, {
530
+ config: { ...subagent, id },
531
+ context,
532
+ status: "idle",
533
+ abortController: new AbortController()
534
+ });
535
+ this.emit("subagent.started", { subagent: { ...subagent, id } });
536
+ return { subagentId: id, agentId: id };
537
+ }
538
+ async assign(task) {
539
+ this.pendingTasks.push(task);
540
+ this.tryDispatchNext();
541
+ }
542
+ async delegate(to, msg) {
543
+ const subagent = this.subagents.get(to);
544
+ if (!subagent) throw new Error(`Subagent "${to}" not found`);
545
+ if (!subagent.context.parentBridge) {
546
+ throw new Error(`Subagent "${to}" has no parentBridge \u2014 call setSubagentBridge() first`);
547
+ }
548
+ await subagent.context.parentBridge.send(msg);
549
+ }
550
+ /**
551
+ * Wire up the communication bridge for a subagent. Call after spawn() once
552
+ * the caller has created the bidirectional connection.
553
+ */
554
+ setSubagentBridge(subagentId, bridge) {
555
+ const subagent = this.subagents.get(subagentId);
556
+ if (!subagent) throw new Error(`Subagent "${subagentId}" not found`);
557
+ subagent.context.parentBridge = bridge;
558
+ }
559
+ async stop(subagentId) {
560
+ const subagent = this.subagents.get(subagentId);
561
+ if (!subagent) return;
562
+ subagent.abortController.abort();
563
+ subagent.status = "stopped";
564
+ subagent.currentTask = void 0;
565
+ subagent.context.parentBridge = null;
566
+ this.emit("subagent.stopped", { subagentId, reason: "stopped by coordinator" });
567
+ }
568
+ async stopAll() {
569
+ await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));
570
+ }
571
+ getStatus() {
572
+ return {
573
+ coordinatorId: this.coordinatorId,
574
+ subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({
575
+ id,
576
+ name: s.config.name,
577
+ status: s.status,
578
+ currentTask: s.currentTask
579
+ })),
580
+ pendingTasks: this.pendingTasks.length,
581
+ completedTasks: this.completedResults.length,
582
+ totalIterations: this.totalIterations,
583
+ done: this.isDone()
584
+ };
585
+ }
586
+ /** Expose snapshot of completed results — useful for callers awaiting all done. */
587
+ results() {
588
+ return this.completedResults;
589
+ }
590
+ /**
591
+ * Manual completion — for callers that drive subagents without a runner
592
+ * (e.g. external orchestrators). When a runner is configured the coordinator
593
+ * calls this itself.
594
+ */
595
+ completeTask(result) {
596
+ this.recordCompletion(result);
597
+ }
598
+ // --- internal dispatching ---------------------------------------------
599
+ tryDispatchNext() {
600
+ while (this.canDispatch()) {
601
+ const subagentId = this.findIdleSubagent();
602
+ if (!subagentId) return;
603
+ const task = this.pendingTasks.shift();
604
+ if (!task) return;
605
+ this.runDispatched(subagentId, task).catch((err) => {
606
+ this.recordCompletion({
607
+ subagentId,
608
+ taskId: task.id,
609
+ status: "failed",
610
+ error: err instanceof Error ? err.message : String(err),
611
+ iterations: 0,
612
+ toolCalls: 0,
613
+ durationMs: 0
614
+ });
615
+ });
616
+ }
617
+ }
618
+ canDispatch() {
619
+ const max = this.config.maxConcurrent ?? 4;
620
+ return this.inFlight < max && this.pendingTasks.length > 0;
621
+ }
622
+ findIdleSubagent() {
623
+ for (const [id, s] of this.subagents) {
624
+ if (s.status === "idle") return id;
625
+ }
626
+ return null;
627
+ }
628
+ async runDispatched(subagentId, task) {
629
+ const subagent = this.subagents.get(subagentId);
630
+ if (!subagent) return;
631
+ subagent.status = "running";
632
+ subagent.currentTask = task.id;
633
+ task.subagentId = subagentId;
634
+ subagent.context.tasks.push(task);
635
+ this.emit("task.assigned", { task, subagentId });
636
+ const budget = new SubagentBudget({
637
+ maxIterations: subagent.config.maxIterations ?? this.config.defaultBudget?.maxIterations,
638
+ maxToolCalls: task.maxToolCalls ?? subagent.config.maxToolCalls ?? this.config.defaultBudget?.maxToolCalls,
639
+ maxTokens: subagent.config.maxTokens ?? this.config.defaultBudget?.maxTokens,
640
+ maxCostUsd: subagent.config.maxCostUsd ?? this.config.defaultBudget?.maxCostUsd,
641
+ timeoutMs: task.timeoutMs ?? subagent.config.timeoutMs ?? this.config.defaultBudget?.timeoutMs
642
+ });
643
+ subagent.activeBudget = budget;
644
+ if (!this.runner) {
645
+ return;
646
+ }
647
+ this.inFlight++;
648
+ const startTime = Date.now();
649
+ const runCtx = {
650
+ subagentId,
651
+ config: subagent.config,
652
+ budget,
653
+ signal: subagent.abortController.signal,
654
+ bridge: subagent.context.parentBridge || null
655
+ };
656
+ let result;
657
+ budget.start();
658
+ try {
659
+ const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);
660
+ result = {
661
+ subagentId,
662
+ taskId: task.id,
663
+ status: "success",
664
+ result: outcome.result,
665
+ iterations: outcome.iterations,
666
+ toolCalls: outcome.toolCalls,
667
+ durationMs: Date.now() - startTime
668
+ };
669
+ } catch (err) {
670
+ const status = err instanceof BudgetExceededError && err.kind === "timeout" ? "timeout" : subagent.abortController.signal.aborted ? "stopped" : "failed";
671
+ const usage = budget.usage();
672
+ result = {
673
+ subagentId,
674
+ taskId: task.id,
675
+ status,
676
+ error: err instanceof Error ? err.message : String(err),
677
+ iterations: usage.iterations,
678
+ toolCalls: usage.toolCalls,
679
+ durationMs: Date.now() - startTime
680
+ };
681
+ }
682
+ this.recordCompletion(result);
683
+ }
684
+ async executeWithTimeout(runner, task, ctx, budget) {
685
+ const timeoutMs = budget.limits.timeoutMs;
686
+ if (timeoutMs === void 0) return runner(task, ctx);
687
+ let timer = null;
688
+ const timeoutPromise = new Promise((_, reject) => {
689
+ timer = setTimeout(() => {
690
+ this.subagents.get(ctx.subagentId)?.abortController.abort();
691
+ reject(new BudgetExceededError("timeout", timeoutMs, Date.now()));
692
+ }, timeoutMs);
693
+ });
694
+ try {
695
+ return await Promise.race([runner(task, ctx), timeoutPromise]);
696
+ } finally {
697
+ if (timer) clearTimeout(timer);
698
+ }
699
+ }
700
+ recordCompletion(result) {
701
+ this.completedResults.push(result);
702
+ this.totalIterations += result.iterations;
703
+ if (this.inFlight > 0) {
704
+ this.inFlight--;
705
+ } else if (this.runner) {
706
+ this.emit("warning", {
707
+ type: "inFlight_underflow",
708
+ taskId: result.taskId,
709
+ subagentId: result.subagentId
710
+ });
711
+ return;
712
+ }
713
+ const subagent = this.subagents.get(result.subagentId);
714
+ if (subagent && subagent.status !== "stopped") {
715
+ const failed = result.status === "failed" || result.status === "timeout";
716
+ subagent.status = failed ? "error" : "idle";
717
+ subagent.currentTask = void 0;
718
+ if (subagent.abortController.signal.aborted) {
719
+ subagent.abortController = new AbortController();
720
+ }
721
+ if (subagent.status === "error") {
722
+ queueMicrotask(() => {
723
+ if (subagent.status === "error") subagent.status = "idle";
724
+ this.tryDispatchNext();
725
+ });
726
+ }
727
+ }
728
+ this.emit("task.completed", {
729
+ task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },
730
+ result
731
+ });
732
+ this.tryDispatchNext();
733
+ if (this.isDone()) {
734
+ this.emit("done", {
735
+ results: this.completedResults,
736
+ totalIterations: this.totalIterations
737
+ });
738
+ }
739
+ }
740
+ isDone() {
741
+ if (this.config.doneCondition.type === "all_tasks_done") {
742
+ return this.pendingTasks.length === 0 && this.inFlight === 0;
743
+ }
744
+ if (this.config.doneCondition.maxIterations !== void 0 && this.totalIterations >= this.config.doneCondition.maxIterations) {
745
+ return true;
746
+ }
747
+ return false;
748
+ }
749
+ };
750
+
751
+ // src/coordination/director.ts
752
+ var DirectorBudgetError = class extends Error {
753
+ kind;
754
+ limit;
755
+ observed;
756
+ constructor(kind, limit, observed) {
757
+ super(
758
+ kind === "max_spawns" ? `Director spawn budget exceeded: tried to spawn #${observed} but maxSpawns is ${limit}` : `Director spawn depth budget exceeded: this director is at depth ${observed} and maxSpawnDepth is ${limit}`
759
+ );
760
+ this.name = "DirectorBudgetError";
761
+ this.kind = kind;
762
+ this.limit = limit;
763
+ this.observed = observed;
764
+ }
765
+ };
766
+ var Director = class {
767
+ id;
768
+ fleet;
769
+ usage;
770
+ /**
771
+ * Director-side bridge endpoint. Subagents are wired to the same
772
+ * in-memory transport so the director can `ask()` them synchronously
773
+ * and they can `send()` progress back. Exposed so external code (e.g.
774
+ * the TUI) can subscribe to inbound messages.
775
+ */
776
+ bridge;
777
+ transport;
778
+ coordinator;
779
+ /** Resolves with the matching `TaskResult` the first time the
780
+ * coordinator emits `task.completed` for a given task id. Each entry
781
+ * is created lazily on first poll/await and cleared once consumed. */
782
+ taskWaiters = /* @__PURE__ */ new Map();
783
+ /** Cache of completed results in case the consumer asks AFTER the
784
+ * coordinator already fired the event — `awaitTasks(['t-1'])` after
785
+ * t-1 finished should resolve immediately, not hang. */
786
+ completed = /* @__PURE__ */ new Map();
787
+ /** Per-subagent provider/model metadata, captured at spawn time so the
788
+ * FleetUsageAggregator's metaLookup can surface readable rows. */
789
+ subagentMeta = /* @__PURE__ */ new Map();
790
+ priceLookups = /* @__PURE__ */ new Map();
791
+ /** Bridge endpoints we created per subagent (so we can `stop()` them
792
+ * on shutdown and free transport subscriptions). */
793
+ subagentBridges = /* @__PURE__ */ new Map();
794
+ /** Tracks per-spawn config + assigned task ids for manifest writing. */
795
+ manifestEntries = /* @__PURE__ */ new Map();
796
+ manifestPath;
797
+ roster;
798
+ directorPreamble;
799
+ subagentBaseline;
800
+ /** Absolute path to the fleet's shared scratchpad directory, or null
801
+ * when none was configured. Exposed as a readonly getter for callers
802
+ * that need to surface the path to the user (e.g. the CLI logging
803
+ * the location after `--director` boots). */
804
+ sharedScratchpadPath;
805
+ /** Spawn cap (lifetime total). Infinity means unlimited. */
806
+ maxSpawns;
807
+ /** Nesting cap. The N-th director in a chain has `spawnDepth = N-1`. */
808
+ maxSpawnDepth;
809
+ /** This director's position in a director chain. Root director = 0. */
810
+ spawnDepth;
811
+ /** Live spawn counter for `maxSpawns` enforcement. */
812
+ spawnCount = 0;
813
+ constructor(opts) {
814
+ this.id = opts.config.coordinatorId || randomUUID();
815
+ this.manifestPath = opts.manifestPath;
816
+ this.roster = opts.roster;
817
+ this.directorPreamble = opts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
818
+ this.subagentBaseline = opts.subagentBaseline ?? DEFAULT_SUBAGENT_BASELINE;
819
+ this.sharedScratchpadPath = opts.sharedScratchpadPath ?? null;
820
+ this.maxSpawns = opts.maxSpawns ?? Number.POSITIVE_INFINITY;
821
+ this.maxSpawnDepth = opts.maxSpawnDepth ?? 2;
822
+ this.spawnDepth = opts.spawnDepth ?? 0;
823
+ if (this.sharedScratchpadPath) {
824
+ void fsp2.mkdir(this.sharedScratchpadPath, { recursive: true }).catch(() => void 0);
825
+ }
826
+ this.transport = new InMemoryBridgeTransport();
827
+ this.bridge = new InMemoryAgentBridge(
828
+ { agentId: this.id, coordinatorId: this.id },
829
+ this.transport
830
+ );
831
+ this.fleet = new FleetBus();
832
+ this.usage = new FleetUsageAggregator(
833
+ this.fleet,
834
+ (id) => this.priceLookups.get(id),
835
+ (id) => this.subagentMeta.get(id)
836
+ );
837
+ this.coordinator = new DefaultMultiAgentCoordinator(
838
+ { ...opts.config, coordinatorId: this.id },
839
+ { runner: opts.runner }
840
+ );
841
+ this.coordinator.on("task.completed", (payload) => {
842
+ const r = payload.result;
843
+ this.completed.set(r.taskId, r);
844
+ const waiter = this.taskWaiters.get(r.taskId);
845
+ if (waiter) {
846
+ waiter.resolve(r);
847
+ this.taskWaiters.delete(r.taskId);
848
+ }
849
+ });
850
+ }
851
+ /**
852
+ * Spawn a subagent. Identical to the coordinator's `spawn()` but
853
+ * captures provider/model metadata for the usage aggregator and
854
+ * lets the FleetBus attach to the runner's EventBus when the task
855
+ * actually runs (see `attachSubagentBus`).
856
+ *
857
+ * Caller-supplied `priceLookup` is optional but recommended — without
858
+ * it the `cost` column in `usage.snapshot()` stays at 0.
859
+ */
860
+ async spawn(config, priceLookup) {
861
+ if (this.spawnDepth >= this.maxSpawnDepth) {
862
+ throw new DirectorBudgetError("max_spawn_depth", this.maxSpawnDepth, this.spawnDepth);
863
+ }
864
+ if (this.spawnCount >= this.maxSpawns) {
865
+ throw new DirectorBudgetError("max_spawns", this.maxSpawns, this.spawnCount + 1);
866
+ }
867
+ this.spawnCount += 1;
868
+ const result = await this.coordinator.spawn(config);
869
+ this.subagentMeta.set(result.subagentId, {
870
+ provider: config.provider,
871
+ model: config.model
872
+ });
873
+ if (priceLookup) this.priceLookups.set(result.subagentId, priceLookup);
874
+ const subagentBridge = new InMemoryAgentBridge(
875
+ { agentId: result.subagentId, coordinatorId: this.id },
876
+ this.transport
877
+ );
878
+ this.coordinator.setSubagentBridge(result.subagentId, subagentBridge);
879
+ this.subagentBridges.set(result.subagentId, subagentBridge);
880
+ this.manifestEntries.set(result.subagentId, {
881
+ subagentId: result.subagentId,
882
+ name: config.name,
883
+ role: config.role,
884
+ provider: config.provider,
885
+ model: config.model,
886
+ taskIds: []
887
+ });
888
+ return result.subagentId;
889
+ }
890
+ /**
891
+ * Synchronously ask a subagent something via the bridge. Sends a
892
+ * `task` message addressed to the subagent and awaits a matching
893
+ * reply (matched by message id). Subagent runners that handle these
894
+ * requests subscribe to `ctx.bridge` and reply with a message whose
895
+ * `id` equals the incoming request's id (see `InMemoryAgentBridge`'s
896
+ * `request<T>` implementation).
897
+ *
898
+ * Returns the response payload directly (the bridge wrapper is
899
+ * unwrapped for ergonomics). Times out after `timeoutMs` (default
900
+ * matches the bridge's own default of 30s) — surface those rejections
901
+ * to the caller as actionable errors instead of letting tools hang.
902
+ */
903
+ async ask(subagentId, payload, timeoutMs) {
904
+ if (!this.subagentBridges.has(subagentId)) {
905
+ throw new Error(
906
+ `ask: unknown subagent "${subagentId}" (spawn() it first; current fleet: ${Array.from(this.subagentBridges.keys()).join(", ") || "(empty)"})`
907
+ );
908
+ }
909
+ const msg = {
910
+ id: randomUUID(),
911
+ type: "task",
912
+ from: this.id,
913
+ to: subagentId,
914
+ payload,
915
+ timestamp: Date.now(),
916
+ priority: "normal"
917
+ };
918
+ const reply = await this.bridge.request(msg, timeoutMs);
919
+ return reply.payload;
920
+ }
921
+ /**
922
+ * Read completed task results and format them as a structured text
923
+ * block the director's LLM can paste into its own context. The
924
+ * Director keeps every completed `TaskResult` in `completed` so this
925
+ * is a pure read — no bridge round-trip, cheap to call.
926
+ *
927
+ * The returned string is intentionally markdown-flavored: headers per
928
+ * subagent, a one-line meta row (iter / tools / ms), and the task's
929
+ * result text. Pass `style: 'json'` for a programmatic shape instead
930
+ * (useful when the director model is doing structured-output work).
931
+ */
932
+ rollUp(taskIds, style = "markdown") {
933
+ const rows = taskIds.map((id) => this.completed.get(id)).filter((r) => !!r);
934
+ if (style === "json") {
935
+ return JSON.stringify(
936
+ rows.map((r) => ({
937
+ taskId: r.taskId,
938
+ subagentId: r.subagentId,
939
+ status: r.status,
940
+ iterations: r.iterations,
941
+ toolCalls: r.toolCalls,
942
+ durationMs: r.durationMs,
943
+ result: r.result,
944
+ error: r.error
945
+ })),
946
+ null,
947
+ 2
948
+ );
949
+ }
950
+ if (rows.length === 0) {
951
+ return "_No completed tasks for the requested ids \u2014 try waiting first._";
952
+ }
953
+ const lines = [];
954
+ for (const r of rows) {
955
+ const meta = this.subagentMeta.get(r.subagentId);
956
+ const tag = meta?.provider && meta?.model ? ` \xB7 ${meta.provider}/${meta.model}` : "";
957
+ lines.push(`### ${r.subagentId}${tag}`);
958
+ lines.push(`_${r.status} \u2014 ${r.iterations} iter \xB7 ${r.toolCalls} tools \xB7 ${r.durationMs}ms_`);
959
+ lines.push("");
960
+ if (r.error) lines.push(`**Error:** ${r.error}`);
961
+ else if (typeof r.result === "string") lines.push(r.result);
962
+ else if (r.result !== void 0)
963
+ lines.push("```json\n" + JSON.stringify(r.result, null, 2) + "\n```");
964
+ else lines.push("_(no output)_");
965
+ lines.push("");
966
+ }
967
+ return lines.join("\n").trimEnd();
968
+ }
969
+ /**
970
+ * Write the fleet manifest to `manifestPath`. Returns the path written
971
+ * or null when no path was configured. Captures every spawn + its
972
+ * assigned tasks — paired with per-subagent JSONLs, this is enough to
973
+ * replay an entire director run.
974
+ */
975
+ async writeManifest() {
976
+ if (!this.manifestPath) return null;
977
+ const manifest = {
978
+ directorRunId: this.id,
979
+ writtenAt: (/* @__PURE__ */ new Date()).toISOString(),
980
+ children: Array.from(this.manifestEntries.values()).map((e) => ({
981
+ ...e,
982
+ // Surface final status from `completed` when available — manifest
983
+ // becomes much more useful for replay when it carries the
984
+ // success/failure state.
985
+ results: e.taskIds.map((tid) => {
986
+ const r = this.completed.get(tid);
987
+ return r ? {
988
+ taskId: tid,
989
+ status: r.status,
990
+ iterations: r.iterations,
991
+ toolCalls: r.toolCalls,
992
+ durationMs: r.durationMs
993
+ } : { taskId: tid, status: "pending" };
994
+ })
995
+ })),
996
+ usage: this.usage.snapshot()
997
+ };
998
+ await fsp2.mkdir(path3.dirname(this.manifestPath), { recursive: true });
999
+ await fsp2.writeFile(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 384 });
1000
+ return this.manifestPath;
1001
+ }
1002
+ /**
1003
+ * Tear down the director: stop every subagent, close every bridge
1004
+ * endpoint, and (when configured) write the final manifest. Idempotent
1005
+ * — calling shutdown twice is a no-op on the second invocation.
1006
+ */
1007
+ async shutdown() {
1008
+ await this.coordinator.stopAll();
1009
+ for (const b of this.subagentBridges.values()) {
1010
+ await b.stop().catch(() => void 0);
1011
+ }
1012
+ this.subagentBridges.clear();
1013
+ await this.bridge.stop().catch(() => void 0);
1014
+ if (this.manifestPath) await this.writeManifest().catch(() => void 0);
1015
+ }
1016
+ /**
1017
+ * Hand a task to the coordinator. Returns the assigned task id so
1018
+ * callers can wait on it via `awaitTasks([id])`. The coordinator's
1019
+ * concurrency limit applies — the task may queue before running.
1020
+ */
1021
+ async assign(task) {
1022
+ const taskWithId = task.id ? task : { ...task, id: randomUUID() };
1023
+ if (task.subagentId) {
1024
+ const entry = this.manifestEntries.get(task.subagentId);
1025
+ if (entry) entry.taskIds.push(taskWithId.id);
1026
+ }
1027
+ await this.coordinator.assign(taskWithId);
1028
+ return taskWithId.id;
1029
+ }
1030
+ /**
1031
+ * Block until every task id resolves. Returns results in the same
1032
+ * order as the input. If any task hasn't completed by the time this
1033
+ * is called, the promise hangs until it does — pair with a timeout
1034
+ * at the caller if that's a concern. Resolves immediately for ids
1035
+ * whose results were already cached.
1036
+ */
1037
+ awaitTasks(taskIds) {
1038
+ return Promise.all(
1039
+ taskIds.map((id) => {
1040
+ const cached = this.completed.get(id);
1041
+ if (cached) return cached;
1042
+ const existing = this.taskWaiters.get(id);
1043
+ if (existing) return existing.promise;
1044
+ let resolve;
1045
+ const promise = new Promise((res) => {
1046
+ resolve = res;
1047
+ });
1048
+ this.taskWaiters.set(id, { promise, resolve });
1049
+ return promise;
1050
+ })
1051
+ );
1052
+ }
1053
+ async terminate(subagentId) {
1054
+ await this.coordinator.stop(subagentId);
1055
+ }
1056
+ async terminateAll() {
1057
+ await this.coordinator.stopAll();
1058
+ }
1059
+ status() {
1060
+ return this.coordinator.getStatus();
1061
+ }
1062
+ /**
1063
+ * Subscribe to coordinator events. Currently only `task.completed` is
1064
+ * exposed (the others are internal lifecycle). Returns an unsubscribe
1065
+ * function. External callers (e.g. the CLI's `MultiAgentHost`) use this
1066
+ * to drive their own pending/results tracking without poking the
1067
+ * coordinator directly.
1068
+ */
1069
+ on(event, handler) {
1070
+ this.coordinator.on(event, handler);
1071
+ return () => {
1072
+ this.coordinator.off(event, handler);
1073
+ };
1074
+ }
1075
+ /**
1076
+ * Snapshot of every task that has resolved (success, failed, timeout,
1077
+ * stopped) since the director started. Returned in completion order
1078
+ * via the internal map's iteration order. Used by `/fleet status` to
1079
+ * paint the completed table without reaching into private state.
1080
+ */
1081
+ completedResults() {
1082
+ return Array.from(this.completed.values());
1083
+ }
1084
+ snapshot() {
1085
+ return this.usage.snapshot();
1086
+ }
1087
+ /**
1088
+ * Compose the leader/director-agent system prompt: fleet preamble +
1089
+ * (optional) roster summary + user base prompt. Pass the result to your
1090
+ * leader Agent's `ctx.systemPrompt` when constructing it.
1091
+ *
1092
+ * `basePrompt` defaults to `config.leaderSystemPrompt` so callers can
1093
+ * use the no-arg form when the multi-agent config already carries it.
1094
+ */
1095
+ leaderSystemPrompt(basePrompt) {
1096
+ return composeDirectorPrompt({
1097
+ basePrompt: basePrompt ?? this.coordinator.config.leaderSystemPrompt,
1098
+ directorPreamble: this.directorPreamble,
1099
+ rosterSummary: this.roster ? rosterSummaryFromConfigs(this.roster) : void 0
1100
+ });
1101
+ }
1102
+ /**
1103
+ * Compose a subagent's system prompt for a given `SubagentConfig`:
1104
+ * baseline + role + task + per-spawn override. Returned by value — does
1105
+ * not mutate the config. Factories (the user-supplied `AgentFactory`)
1106
+ * should call this when building each subagent's Agent so the bridge
1107
+ * contract, role context, and override are all surfaced.
1108
+ *
1109
+ * When `taskBrief` is omitted the Task section is dropped. Pass the
1110
+ * actual task description here to reinforce it in the system prompt
1111
+ * (the runner already passes it as user input — duplicating in the
1112
+ * system prompt is optional but improves anchoring on small models).
1113
+ */
1114
+ subagentSystemPrompt(config, taskBrief) {
1115
+ return composeSubagentPrompt({
1116
+ baseline: this.subagentBaseline,
1117
+ role: config.prompt,
1118
+ task: taskBrief,
1119
+ sharedScratchpad: this.sharedScratchpadPath ?? void 0,
1120
+ override: config.systemPromptOverride
1121
+ });
1122
+ }
1123
+ /**
1124
+ * Build the tool set the LLM-driven director uses to orchestrate.
1125
+ * Returns an array of `Tool` definitions; register these on the
1126
+ * director's `Agent` to expose `spawn_subagent`, `assign_task`, etc.
1127
+ * Each tool's `execute()` delegates straight to the matching method
1128
+ * above.
1129
+ *
1130
+ * Tools all carry `permission: 'auto'` — the *user* has already
1131
+ * approved running the director when they kicked off the run, so
1132
+ * gating individual orchestration calls behind a confirm prompt
1133
+ * would just be noise. The actual subagent tools they spawn are
1134
+ * still permission-checked normally.
1135
+ */
1136
+ tools(roster) {
1137
+ const t = [
1138
+ makeSpawnTool(this, roster),
1139
+ makeAssignTool(this),
1140
+ makeAwaitTasksTool(this),
1141
+ makeAskTool(this),
1142
+ makeRollUpTool(this),
1143
+ makeTerminateTool(this),
1144
+ makeFleetStatusTool(this),
1145
+ makeFleetUsageTool(this)
1146
+ ];
1147
+ return t;
1148
+ }
1149
+ };
1150
+ function makeSpawnTool(director, roster) {
1151
+ const inputSchema = {
1152
+ type: "object",
1153
+ properties: {
1154
+ role: {
1155
+ type: "string",
1156
+ description: "Roster role id (preferred). When set, the spawn uses the matching config from the roster and ignores other fields."
1157
+ },
1158
+ name: {
1159
+ type: "string",
1160
+ description: "Display name for the subagent. Required when not using roster."
1161
+ },
1162
+ provider: {
1163
+ type: "string",
1164
+ description: 'Provider id (e.g. "anthropic", "openai"). Defaults to the leader provider when omitted.'
1165
+ },
1166
+ model: {
1167
+ type: "string",
1168
+ description: "Model id within the provider. Defaults to the leader model when omitted."
1169
+ },
1170
+ systemPromptOverride: {
1171
+ type: "string",
1172
+ description: "Extra prompt text appended after the role-base prompt."
1173
+ },
1174
+ maxIterations: { type: "number" },
1175
+ maxToolCalls: { type: "number" },
1176
+ maxCostUsd: { type: "number" }
1177
+ },
1178
+ required: []
1179
+ };
1180
+ return {
1181
+ name: "spawn_subagent",
1182
+ description: "Create a new subagent under this director. Returns the subagent id. Use this when you need a worker with a specific provider, model, or role to handle a piece of the plan.",
1183
+ usageHint: "Either pass `role` (matches the roster) OR pass `name` + optional `provider`/`model`. Returns `{ subagentId }`.",
1184
+ permission: "auto",
1185
+ mutating: false,
1186
+ inputSchema,
1187
+ async execute(input) {
1188
+ const i = input ?? {};
1189
+ const role = typeof i.role === "string" ? i.role : void 0;
1190
+ const base = role && roster ? roster[role] : void 0;
1191
+ if (role && !base) {
1192
+ return {
1193
+ error: `unknown role "${role}". roster has: ${roster ? Object.keys(roster).join(", ") : "(empty)"}`
1194
+ };
1195
+ }
1196
+ const cfg = {
1197
+ ...base ?? { name: i.name ?? "subagent" }
1198
+ };
1199
+ if (typeof i.name === "string") cfg.name = i.name;
1200
+ if (typeof i.provider === "string") cfg.provider = i.provider;
1201
+ if (typeof i.model === "string") cfg.model = i.model;
1202
+ if (typeof i.systemPromptOverride === "string")
1203
+ cfg.systemPromptOverride = i.systemPromptOverride;
1204
+ if (typeof i.maxIterations === "number") cfg.maxIterations = i.maxIterations;
1205
+ if (typeof i.maxToolCalls === "number") cfg.maxToolCalls = i.maxToolCalls;
1206
+ if (typeof i.maxCostUsd === "number") cfg.maxCostUsd = i.maxCostUsd;
1207
+ try {
1208
+ const subagentId = await director.spawn(cfg);
1209
+ return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name };
1210
+ } catch (err) {
1211
+ if (err instanceof DirectorBudgetError) {
1212
+ return { error: err.message, kind: err.kind, limit: err.limit, observed: err.observed };
1213
+ }
1214
+ return { error: err instanceof Error ? err.message : String(err) };
1215
+ }
1216
+ }
1217
+ };
1218
+ }
1219
+ function makeAssignTool(director) {
1220
+ const inputSchema = {
1221
+ type: "object",
1222
+ properties: {
1223
+ subagentId: { type: "string", description: "Target subagent id. Required." },
1224
+ description: {
1225
+ type: "string",
1226
+ description: "The task in natural language \u2014 what you want this subagent to do."
1227
+ },
1228
+ maxToolCalls: { type: "number", description: "Optional per-task tool-call budget override." },
1229
+ timeoutMs: { type: "number", description: "Optional per-task timeout in ms." }
1230
+ },
1231
+ required: ["subagentId", "description"]
1232
+ };
1233
+ return {
1234
+ name: "assign_task",
1235
+ description: "Hand a task to a previously spawned subagent. Returns the task id \u2014 pass it to `await_tasks` to block on completion.",
1236
+ permission: "auto",
1237
+ mutating: false,
1238
+ inputSchema,
1239
+ async execute(input) {
1240
+ const i = input;
1241
+ const task = {
1242
+ id: randomUUID(),
1243
+ description: i.description,
1244
+ subagentId: i.subagentId,
1245
+ maxToolCalls: i.maxToolCalls,
1246
+ timeoutMs: i.timeoutMs
1247
+ };
1248
+ const taskId = await director.assign(task);
1249
+ return { taskId, subagentId: i.subagentId };
1250
+ }
1251
+ };
1252
+ }
1253
+ function makeAwaitTasksTool(director) {
1254
+ const inputSchema = {
1255
+ type: "object",
1256
+ properties: {
1257
+ taskIds: {
1258
+ type: "array",
1259
+ items: { type: "string" },
1260
+ description: "One or more task ids returned by `assign_task`. The call blocks until every id resolves."
1261
+ }
1262
+ },
1263
+ required: ["taskIds"]
1264
+ };
1265
+ return {
1266
+ name: "await_tasks",
1267
+ description: "Block until every named task completes. Returns the array of TaskResult \u2014 use this to gather subagent output before deciding the next step.",
1268
+ permission: "auto",
1269
+ mutating: false,
1270
+ inputSchema,
1271
+ async execute(input) {
1272
+ const i = input;
1273
+ const results = await director.awaitTasks(i.taskIds);
1274
+ return { results };
1275
+ }
1276
+ };
1277
+ }
1278
+ function makeAskTool(director) {
1279
+ const inputSchema = {
1280
+ type: "object",
1281
+ properties: {
1282
+ subagentId: {
1283
+ type: "string",
1284
+ description: "Subagent to ask. Must be a previously spawned id."
1285
+ },
1286
+ question: {
1287
+ type: "string",
1288
+ description: "The question or instruction. Sent as the bridge message payload."
1289
+ },
1290
+ timeoutMs: { type: "number", description: "Optional timeout in ms (default 30s)." }
1291
+ },
1292
+ required: ["subagentId", "question"]
1293
+ };
1294
+ return {
1295
+ name: "ask_subagent",
1296
+ description: "Synchronously ask a subagent a question. Blocks until the subagent replies via the bridge (or the timeout fires). Use this when you need a one-shot answer without spawning a fresh task.",
1297
+ permission: "auto",
1298
+ mutating: false,
1299
+ inputSchema,
1300
+ async execute(input) {
1301
+ const i = input;
1302
+ try {
1303
+ const answer = await director.ask(i.subagentId, { question: i.question }, i.timeoutMs);
1304
+ return { ok: true, answer };
1305
+ } catch (err) {
1306
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1307
+ }
1308
+ }
1309
+ };
1310
+ }
1311
+ function makeRollUpTool(director) {
1312
+ const inputSchema = {
1313
+ type: "object",
1314
+ properties: {
1315
+ taskIds: {
1316
+ type: "array",
1317
+ items: { type: "string" },
1318
+ description: "Completed task ids to aggregate. Pass the ids returned by previous `assign_task` calls."
1319
+ },
1320
+ style: {
1321
+ type: "string",
1322
+ enum: ["markdown", "json"],
1323
+ description: "Output flavor \u2014 markdown (default) for in-prompt summarization, json for structured downstream processing."
1324
+ }
1325
+ },
1326
+ required: ["taskIds"]
1327
+ };
1328
+ return {
1329
+ name: "roll_up",
1330
+ description: "Aggregate completed task results into a single formatted summary. Use this after `await_tasks` to fold subagent outputs back into the director's context before deciding the next step.",
1331
+ permission: "auto",
1332
+ mutating: false,
1333
+ inputSchema,
1334
+ async execute(input) {
1335
+ const i = input;
1336
+ const summary = director.rollUp(i.taskIds, i.style ?? "markdown");
1337
+ return { summary, count: i.taskIds.length };
1338
+ }
1339
+ };
1340
+ }
1341
+ function makeTerminateTool(director) {
1342
+ const inputSchema = {
1343
+ type: "object",
1344
+ properties: {
1345
+ subagentId: { type: "string", description: "Subagent to abort." }
1346
+ },
1347
+ required: ["subagentId"]
1348
+ };
1349
+ return {
1350
+ name: "terminate_subagent",
1351
+ description: 'Forcibly abort a subagent. Use sparingly \u2014 prefer waiting on the natural budget to expire. The current task (if any) ends with status "stopped".',
1352
+ permission: "auto",
1353
+ mutating: true,
1354
+ inputSchema,
1355
+ async execute(input) {
1356
+ const i = input;
1357
+ await director.terminate(i.subagentId);
1358
+ return { ok: true };
1359
+ }
1360
+ };
1361
+ }
1362
+ function makeFleetStatusTool(director) {
1363
+ return {
1364
+ name: "fleet_status",
1365
+ description: "Snapshot of the fleet \u2014 every subagent's current status, pending vs. completed task counts, and the running total iteration count. Cheap; call freely.",
1366
+ permission: "auto",
1367
+ mutating: false,
1368
+ inputSchema: { type: "object", properties: {}, required: [] },
1369
+ async execute() {
1370
+ return director.status();
1371
+ }
1372
+ };
1373
+ }
1374
+ function makeFleetUsageTool(director) {
1375
+ return {
1376
+ name: "fleet_usage",
1377
+ description: "Token + cost breakdown across the fleet, per-subagent and totals. Use this to reason about which workers to assign costly tasks to or when to wrap up to stay within budget.",
1378
+ permission: "auto",
1379
+ mutating: false,
1380
+ inputSchema: { type: "object", properties: {}, required: [] },
1381
+ async execute() {
1382
+ return director.snapshot();
1383
+ }
1384
+ };
1385
+ }
1386
+
1387
+ // src/coordination/agent-subagent-runner.ts
1388
+ function makeAgentSubagentRunner(opts) {
1389
+ const format = opts.formatTaskInput ?? defaultFormatTaskInput;
1390
+ return async (task, ctx) => {
1391
+ const { agent, events } = await opts.factory(ctx.config);
1392
+ const aborter = new AbortController();
1393
+ let budgetError = null;
1394
+ const onBudgetError = (err) => {
1395
+ aborter.abort();
1396
+ budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
1397
+ "tool_calls",
1398
+ 0,
1399
+ 0
1400
+ );
1401
+ if (budgetError !== err && err instanceof Error) {
1402
+ budgetError.message += ` (caused by: ${err.message})`;
1403
+ }
1404
+ };
1405
+ const unsub = [];
1406
+ unsub.push(
1407
+ events.on("tool.started", () => {
1408
+ try {
1409
+ ctx.budget.recordToolCall();
1410
+ } catch (e) {
1411
+ onBudgetError(e);
1412
+ }
1413
+ }),
1414
+ events.on("provider.response", (e) => {
1415
+ try {
1416
+ ctx.budget.recordUsage(e.usage);
1417
+ } catch (e2) {
1418
+ onBudgetError(e2);
1419
+ }
1420
+ }),
1421
+ events.on("iteration.started", () => {
1422
+ try {
1423
+ ctx.budget.recordIteration();
1424
+ ctx.budget.checkTimeout();
1425
+ } catch (e) {
1426
+ onBudgetError(e);
1427
+ }
1428
+ })
1429
+ );
1430
+ const onParentAbort = () => aborter.abort();
1431
+ ctx.signal.addEventListener("abort", onParentAbort);
1432
+ let result;
1433
+ try {
1434
+ result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
1435
+ } finally {
1436
+ ctx.signal.removeEventListener("abort", onParentAbort);
1437
+ for (const u of unsub) u();
1438
+ }
1439
+ if (budgetError) throw budgetError;
1440
+ if (result.status === "failed") {
1441
+ throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
1442
+ }
1443
+ if (result.status === "aborted") {
1444
+ throw new Error("agent aborted");
1445
+ }
1446
+ if (result.status === "max_iterations") {
1447
+ throw new Error("agent exhausted iteration limit");
1448
+ }
1449
+ const usage = ctx.budget.usage();
1450
+ return {
1451
+ result: result.finalText,
1452
+ iterations: result.iterations,
1453
+ toolCalls: usage.toolCalls
1454
+ };
1455
+ };
1456
+ }
1457
+ function defaultFormatTaskInput(task) {
1458
+ return task.description ?? "";
1459
+ }
1460
+ async function ensureDir(dir) {
1461
+ await fsp2.mkdir(dir, { recursive: true });
1462
+ }
1463
+
1464
+ // src/storage/session-store.ts
1465
+ var DefaultSessionStore = class {
1466
+ dir;
1467
+ events;
1468
+ constructor(opts) {
1469
+ this.dir = opts.dir;
1470
+ this.events = opts.events;
1471
+ }
1472
+ async create(meta) {
1473
+ await ensureDir(this.dir);
1474
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1475
+ const id = meta.id ?? `${startedAt.replace(/[:.]/g, "-")}-${randomBytes(2).toString("hex")}`;
1476
+ const file = path3.join(this.dir, `${id}.jsonl`);
1477
+ let handle;
1478
+ try {
1479
+ handle = await fsp2.open(file, "a", 384);
1480
+ } catch (err) {
1481
+ throw new Error(
1482
+ `Failed to open session file: ${err instanceof Error ? err.message : String(err)}`,
1483
+ {
1484
+ cause: err
1485
+ }
1486
+ );
1487
+ }
1488
+ try {
1489
+ return new FileSessionWriter(id, handle, startedAt, meta, { dir: this.dir, filePath: file });
1490
+ } catch (err) {
1491
+ await handle.close().catch(() => {
1492
+ });
1493
+ throw err;
1494
+ }
1495
+ }
1496
+ async resume(id) {
1497
+ const data = await this.load(id);
1498
+ const file = path3.join(this.dir, `${id}.jsonl`);
1499
+ let handle;
1500
+ try {
1501
+ handle = await fsp2.open(file, "a", 384);
1502
+ } catch (err) {
1503
+ throw new Error(
1504
+ `Failed to open session "${id}" for append: ${err instanceof Error ? err.message : String(err)}`,
1505
+ { cause: err }
1506
+ );
1507
+ }
1508
+ const writer = new FileSessionWriter(
1509
+ id,
1510
+ handle,
1511
+ (/* @__PURE__ */ new Date()).toISOString(),
1512
+ {
1513
+ id,
1514
+ model: data.metadata.model,
1515
+ provider: data.metadata.provider
1516
+ },
1517
+ { resumed: true, dir: this.dir, filePath: file }
1518
+ );
1519
+ return { writer, data };
1520
+ }
1521
+ async load(id) {
1522
+ const file = path3.join(this.dir, `${id}.jsonl`);
1523
+ const raw = await fsp2.readFile(file, "utf8");
1524
+ const lines = raw.split("\n").filter((l) => l.trim());
1525
+ const events = [];
1526
+ for (const line of lines) {
1527
+ try {
1528
+ const parsed = JSON.parse(line);
1529
+ if (parsed !== null && typeof parsed === "object" && typeof parsed.type === "string" && typeof parsed.ts === "string") {
1530
+ events.push(parsed);
1531
+ }
1532
+ } catch {
1533
+ }
1534
+ }
1535
+ const meta = this.metaFromEvents(id, events);
1536
+ const { messages, usage } = this.replay(events, id);
1537
+ return { metadata: meta, events, messages, usage };
1538
+ }
1539
+ async list(limit = 20) {
1540
+ try {
1541
+ await ensureDir(this.dir);
1542
+ const files = await fsp2.readdir(this.dir);
1543
+ const ids = files.filter((f) => f.endsWith(".jsonl")).map((f) => f.replace(/\.jsonl$/, ""));
1544
+ const sessions = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));
1545
+ const out = sessions.filter((s) => s !== null);
1546
+ out.sort((a, b) => {
1547
+ if (a.startedAt < b.startedAt) return 1;
1548
+ if (a.startedAt > b.startedAt) return -1;
1549
+ return a.id.localeCompare(b.id);
1550
+ });
1551
+ return out.slice(0, limit);
1552
+ } catch {
1553
+ return [];
1554
+ }
1555
+ }
1556
+ async summaryFor(id) {
1557
+ const manifest = path3.join(this.dir, `${id}.summary.json`);
1558
+ try {
1559
+ const raw = await fsp2.readFile(manifest, "utf8");
1560
+ return JSON.parse(raw);
1561
+ } catch {
1562
+ const full = path3.join(this.dir, `${id}.jsonl`);
1563
+ const stat3 = await fsp2.stat(full);
1564
+ const summary = await this.summarize(id, stat3.mtime.toISOString());
1565
+ await fsp2.writeFile(manifest, JSON.stringify(summary), { mode: 384 }).catch((err) => {
1566
+ console.warn(
1567
+ `[session-store] Failed to write manifest for "${id}":`,
1568
+ err instanceof Error ? err.message : String(err)
1569
+ );
1570
+ });
1571
+ return summary;
1572
+ }
1573
+ }
1574
+ async delete(id) {
1575
+ await fsp2.unlink(path3.join(this.dir, `${id}.jsonl`));
1576
+ await fsp2.unlink(path3.join(this.dir, `${id}.summary.json`)).catch(() => void 0);
1577
+ }
1578
+ async summarize(id, mtime) {
1579
+ try {
1580
+ const data = await this.load(id);
1581
+ const firstUser = data.events.find((e) => e.type === "user_input");
1582
+ const title = firstUser && firstUser.type === "user_input" ? userInputTitle(firstUser.content) : "(empty session)";
1583
+ return {
1584
+ id,
1585
+ title,
1586
+ startedAt: data.metadata.startedAt,
1587
+ model: data.metadata.model ?? "unknown",
1588
+ provider: data.metadata.provider ?? "unknown",
1589
+ tokenTotal: data.usage.input + data.usage.output
1590
+ };
1591
+ } catch {
1592
+ return {
1593
+ id,
1594
+ title: "(damaged)",
1595
+ startedAt: mtime,
1596
+ model: "unknown",
1597
+ provider: "unknown",
1598
+ tokenTotal: 0
1599
+ };
1600
+ }
1601
+ }
1602
+ metaFromEvents(id, events) {
1603
+ const start = events.find((e) => e.type === "session_start");
1604
+ const end = events.find((e) => e.type === "session_end");
1605
+ return {
1606
+ id,
1607
+ startedAt: start?.ts ?? (/* @__PURE__ */ new Date(0)).toISOString(),
1608
+ endedAt: end?.ts,
1609
+ model: start?.model,
1610
+ provider: start?.provider
1611
+ };
1612
+ }
1613
+ replay(events, sessionId = "unknown") {
1614
+ const messages = [];
1615
+ let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1616
+ const openToolUses = /* @__PURE__ */ new Set();
1617
+ for (const e of events) {
1618
+ if (e.type === "user_input") {
1619
+ openToolUses.clear();
1620
+ messages.push({ role: "user", content: e.content });
1621
+ } else if (e.type === "llm_response") {
1622
+ messages.push({ role: "assistant", content: e.content });
1623
+ for (const b of e.content) {
1624
+ if (b.type === "tool_use") openToolUses.add(b.id);
1625
+ }
1626
+ usage = {
1627
+ input: usage.input + (e.usage.input ?? 0),
1628
+ output: usage.output + (e.usage.output ?? 0),
1629
+ cacheRead: (usage.cacheRead ?? 0) + (e.usage.cacheRead ?? 0),
1630
+ cacheWrite: (usage.cacheWrite ?? 0) + (e.usage.cacheWrite ?? 0)
1631
+ };
1632
+ } else if (e.type === "tool_result") {
1633
+ if (!openToolUses.has(e.id)) {
1634
+ this.events?.emit("session.damaged", {
1635
+ sessionId,
1636
+ detail: `Orphan tool_result "${e.id}" has no matching tool_use`
1637
+ });
1638
+ continue;
1639
+ }
1640
+ openToolUses.delete(e.id);
1641
+ const content = [
1642
+ {
1643
+ type: "tool_result",
1644
+ tool_use_id: e.id,
1645
+ content: typeof e.content === "string" ? e.content : JSON.stringify(e.content),
1646
+ is_error: e.isError
1647
+ }
1648
+ ];
1649
+ const last = messages[messages.length - 1];
1650
+ if (last && last.role === "user") {
1651
+ if (Array.isArray(last.content)) {
1652
+ last.content.push(...content);
1653
+ } else if (typeof last.content === "string") {
1654
+ last.content = [{ type: "text", text: last.content }, ...content];
1655
+ } else {
1656
+ messages.push({ role: "user", content });
1657
+ }
1658
+ } else {
1659
+ messages.push({ role: "user", content });
1660
+ }
1661
+ }
1662
+ }
1663
+ if (openToolUses.size > 0) {
1664
+ this.events?.emit("session.damaged", {
1665
+ sessionId,
1666
+ detail: `${openToolUses.size} tool_use blocks without matching results \u2014 replay truncated`
1667
+ });
1668
+ return { messages, usage };
1669
+ }
1670
+ return { messages, usage };
1671
+ }
1672
+ };
1673
+ var FileSessionWriter = class {
1674
+ constructor(id, handle, startedAt, meta, opts = {}) {
1675
+ this.id = id;
1676
+ this.handle = handle;
1677
+ this.startedAt = startedAt;
1678
+ this.meta = meta;
1679
+ this.resumed = opts.resumed ?? false;
1680
+ this.manifestFile = opts.dir ? path3.join(opts.dir, `${id}.summary.json`) : "";
1681
+ this.filePath = opts.filePath ?? "";
1682
+ this.summary = {
1683
+ id,
1684
+ title: "(empty session)",
1685
+ startedAt,
1686
+ model: meta.model ?? "unknown",
1687
+ provider: meta.provider ?? "unknown",
1688
+ tokenTotal: 0
1689
+ };
1690
+ }
1691
+ id;
1692
+ handle;
1693
+ startedAt;
1694
+ meta;
1695
+ closed = false;
1696
+ manifestFile;
1697
+ summary;
1698
+ tokenIn = 0;
1699
+ tokenOut = 0;
1700
+ filePath;
1701
+ initDone = false;
1702
+ resumed;
1703
+ appendFailCount = 0;
1704
+ lastAppendWarnAt = 0;
1705
+ async writeSessionStart() {
1706
+ if (this.initDone || this.closed) return;
1707
+ this.initDone = true;
1708
+ const record = `${JSON.stringify({
1709
+ type: this.resumed ? "session_resumed" : "session_start",
1710
+ ts: this.startedAt,
1711
+ id: this.id,
1712
+ model: this.meta.model ?? "unknown",
1713
+ provider: this.meta.provider ?? "unknown"
1714
+ })}
1715
+ `;
1716
+ try {
1717
+ if (this.filePath) {
1718
+ await fsp2.writeFile(this.filePath, record, { flag: "a", mode: 384 });
1719
+ }
1720
+ } catch {
1721
+ }
1722
+ }
1723
+ async append(event) {
1724
+ if (this.closed) return;
1725
+ if (!this.initDone) {
1726
+ await this.writeSessionStart();
1727
+ }
1728
+ this.observeForSummary(event);
1729
+ try {
1730
+ await this.handle.appendFile(`${JSON.stringify(event)}
1731
+ `, "utf8");
1732
+ } catch (err) {
1733
+ this.appendFailCount++;
1734
+ const now = Date.now();
1735
+ if (now - this.lastAppendWarnAt > 5e3) {
1736
+ const suppressed = this.appendFailCount - 1;
1737
+ const tail = suppressed > 0 ? ` (+${suppressed} suppressed)` : "";
1738
+ console.warn(
1739
+ "[session] append failed:",
1740
+ err instanceof Error ? err.message : String(err),
1741
+ tail
1742
+ );
1743
+ this.lastAppendWarnAt = now;
1744
+ this.appendFailCount = 0;
1745
+ }
1746
+ }
1747
+ }
1748
+ /**
1749
+ * Watch events as they're appended and keep the summary state hot, so
1750
+ * `close()` can flush a `<id>.summary.json` manifest without re-reading
1751
+ * the JSONL. `list()` reads only manifests, turning a per-session full
1752
+ * parse into a single stat+read.
1753
+ */
1754
+ observeForSummary(event) {
1755
+ if (event.type === "user_input" && this.summary.title === "(empty session)") {
1756
+ this.summary = { ...this.summary, title: userInputTitle(event.content) };
1757
+ } else if (event.type === "llm_response") {
1758
+ this.tokenIn += event.usage.input;
1759
+ this.tokenOut += event.usage.output;
1760
+ this.summary = { ...this.summary, tokenTotal: this.tokenIn + this.tokenOut };
1761
+ } else if (event.type === "session_end") {
1762
+ const total = event.usage.input + event.usage.output;
1763
+ if (total > 0) this.summary = { ...this.summary, tokenTotal: total };
1764
+ }
1765
+ }
1766
+ async close() {
1767
+ if (this.closed) return;
1768
+ this.closed = true;
1769
+ if (this.manifestFile) {
1770
+ try {
1771
+ await fsp2.writeFile(this.manifestFile, JSON.stringify(this.summary), { mode: 384 });
1772
+ } catch {
1773
+ }
1774
+ }
1775
+ try {
1776
+ await this.handle.close();
1777
+ } catch {
1778
+ }
1779
+ }
1780
+ };
1781
+ function userInputTitle(content) {
1782
+ if (typeof content === "string") return content.slice(0, 60);
1783
+ const text = content.filter((b) => b.type === "text").map((b) => b.text).join(" ");
1784
+ return (text || "(non-text input)").slice(0, 60);
1785
+ }
1786
+
1787
+ // src/coordination/director-session.ts
1788
+ function makeDirectorSessionFactory(opts) {
1789
+ const runId = opts.directorRunId ?? `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-director`;
1790
+ let store;
1791
+ let dir;
1792
+ if (opts.store) {
1793
+ store = opts.store;
1794
+ dir = opts.sessionsRoot ? path3.join(opts.sessionsRoot, runId) : "(caller-managed)";
1795
+ } else if (opts.sessionsRoot) {
1796
+ dir = path3.join(opts.sessionsRoot, runId);
1797
+ store = new DefaultSessionStore({ dir });
1798
+ } else {
1799
+ throw new Error("makeDirectorSessionFactory requires either `store` or `sessionsRoot`");
1800
+ }
1801
+ return {
1802
+ dir,
1803
+ directorRunId: runId,
1804
+ async createSubagentSession({ subagentId, provider, model, title }) {
1805
+ return store.create({
1806
+ id: subagentId,
1807
+ title: title ?? subagentId,
1808
+ provider: provider ?? "unknown",
1809
+ model: model ?? "unknown"
1810
+ });
1811
+ }
1812
+ };
1813
+ }
1814
+
1815
+ // src/coordination/fleet.ts
1816
+ var AUDIT_LOG_AGENT = {
1817
+ id: "audit-log",
1818
+ name: "Audit Log",
1819
+ role: "audit-log",
1820
+ prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL
1821
+ session logs and produce actionable markdown reports.
1822
+
1823
+ Scope:
1824
+ - Parse session logs (iteration counts, tool calls, errors, usage)
1825
+ - Detect repeated failure patterns across multiple runs
1826
+ - Identify tool usage anomalies (over-use, failures, unexpected chains)
1827
+ - Track token consumption trends
1828
+ - Generate structured audit reports with severity ratings
1829
+
1830
+ Input format you accept:
1831
+ { "task": "analyze | report | trends", "sessionPath": "<path>", "focus": "errors | tools | usage | all" }
1832
+
1833
+ Output: Markdown audit report with sections:
1834
+ - ## Summary (totals, error rate)
1835
+ - ## Top Errors (count + context)
1836
+ - ## Tool Usage (table with calls, failures, avg duration)
1837
+ - ## Anomalies (pattern \u2192 severity)
1838
+
1839
+ Working rules:
1840
+ - Never fabricate numbers \u2014 read the actual logs first
1841
+ - Always include file:line references for errors
1842
+ - If sessionPath is missing, ask the director to provide it
1843
+ - Report confidence level: high (>90% accuracy), medium, low`,
1844
+ maxIterations: 50,
1845
+ maxToolCalls: 200,
1846
+ timeoutMs: 12e4
1847
+ };
1848
+ var BUG_HUNTER_AGENT = {
1849
+ id: "bug-hunter",
1850
+ name: "Bug Hunter",
1851
+ role: "bug-hunter",
1852
+ prompt: `You are the Bug Hunter agent. Your job is to systematically scan
1853
+ source code for bugs, anti-patterns, and code smells using pattern matching
1854
+ and heuristics. Output a prioritized hit list with file:line references.
1855
+
1856
+ Scope:
1857
+ - Detect common bug patterns (uncaught errors, resource leaks, race conditions)
1858
+ - Identify anti-patterns (callback hell, God objects, circular deps)
1859
+ - Find TypeScript-specific issues (unsafe any, missing null checks, branded types)
1860
+ - Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)
1861
+ - Rank findings: critical > high > medium > low
1862
+
1863
+ Input format you accept:
1864
+ { "task": "scan | hunt | check", "paths": ["src/**/*.ts"], "focus": "bugs | patterns | security | all", "severityThreshold": "medium" }
1865
+
1866
+ Output: Markdown bug hunt report:
1867
+ - ## Critical (must fix first)
1868
+ - ## High (should fix)
1869
+ - ## Medium
1870
+ - ## Low (consider)
1871
+ Each entry: **[TYPE]** \`file:line\` \u2014 description + suggested fix
1872
+
1873
+ Bug pattern reference you know:
1874
+ | Pattern | Regex hint | Severity |
1875
+ |---------|------------|----------|
1876
+ | Uncaught promise | /.then\\(.*\\)/ without catch | high |
1877
+ | Event leak | on\\( without off/removeListener | high |
1878
+ | Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |
1879
+ | unsafe any | : any\\b or <any> | medium |
1880
+ | innerHTML | innerHTML\\s*= | high |
1881
+
1882
+ Working rules:
1883
+ - Never scan node_modules \u2014 it's noise
1884
+ - Always include file:line for every finding
1885
+ - If >30% of findings are false positives, note the confidence level
1886
+ - Ask director for clarification if paths are ambiguous`,
1887
+ maxIterations: 80,
1888
+ maxToolCalls: 300,
1889
+ timeoutMs: 18e4
1890
+ };
1891
+ var REFACTOR_PLANNER_AGENT = {
1892
+ id: "refactor-planner",
1893
+ name: "Refactor Planner",
1894
+ role: "refactor-planner",
1895
+ prompt: `You are the Refactor Planner agent. Your job is to analyze code
1896
+ structure and produce a concrete, phased refactoring plan with risk
1897
+ assessment, dependency ordering, and rollback strategy.
1898
+
1899
+ Scope:
1900
+ - Map module-level dependencies (import graph)
1901
+ - Identify coupling hotspots (high fan-in/out modules)
1902
+ - Assess refactoring risk by complexity and test coverage
1903
+ - Generate phased plans with checkpoint milestones
1904
+ - Produce diff-friendly task lists (one task = one concern)
1905
+
1906
+ Input format you accept:
1907
+ { "task": "plan | assess | roadmap", "target": "src/core", "constraint": "no-breaking-changes | minimal-downtime | full-rewrite", "focus": "architecture | performance | maintainability" }
1908
+
1909
+ Output: Markdown refactor plan:
1910
+ - ## Phase 1: Low Risk / High Payoff (do first)
1911
+ Table: | # | Task | Module | Risk | Est. Time |
1912
+ - ## Phase 2: Medium Risk
1913
+ - ## Phase 3: High Risk (requires full regression)
1914
+ - ## Dependency Graph (abbreviated ASCII)
1915
+ - ## Rollback Strategy
1916
+ - ## Exit Criteria (checkbox list)
1917
+
1918
+ Risk scoring criteria:
1919
+ | Factor | Low | Medium | High |
1920
+ |--------|-----|--------|------|
1921
+ | Cyclomatic complexity | <10 | 10-20 | >20 |
1922
+ | Test coverage | >80% | 50-80% | <50% |
1923
+ | Fan-out (imports) | <5 | 5-15 | >15 |
1924
+
1925
+ Working rules:
1926
+ - Always include rollback strategy \u2014 every refactor can fail
1927
+ - Merge tasks that take <1h into a single phase
1928
+ - Respect team constraints (reviewer availability, parallelization)
1929
+ - Never plan without analyzing the actual code first`,
1930
+ maxIterations: 60,
1931
+ maxToolCalls: 250,
1932
+ timeoutMs: 15e4
1933
+ };
1934
+ var SECURITY_SCANNER_AGENT = {
1935
+ id: "security-scanner",
1936
+ name: "Security Scanner",
1937
+ role: "security-scanner",
1938
+ prompt: `You are the Security Scanner agent. Your job is to scan code,
1939
+ configs, and dependencies for security issues from hardcoded secrets to
1940
+ supply chain risks.
1941
+
1942
+ Scope:
1943
+ - Detect hardcoded secrets: API keys, tokens, passwords, private keys
1944
+ - Find injection vectors: eval, innerHTML, SQL concat, shell injection
1945
+ - Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS
1946
+ - Scan dependencies for known CVEs (via npm/pnpm audit)
1947
+ - Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc
1948
+
1949
+ Input format you accept:
1950
+ { "task": "scan | audit | secrets | dependencies", "paths": ["src", "config"], "depth": "quick | normal | deep" }
1951
+
1952
+ Output: Markdown security report:
1953
+ - ## CRITICAL: Secrets Found (with code snippets)
1954
+ - ## HIGH: Injection Vectors
1955
+ - ## MEDIUM: Insecure Patterns
1956
+ - ## Dependency Issues (CVE list)
1957
+ - ## Summary table (severity \u2192 count)
1958
+ - ## Remediation Checklist (with checkboxes)
1959
+
1960
+ Secret patterns you detect:
1961
+ | Pattern | Example | Severity |
1962
+ |---------|---------|----------|
1963
+ | AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |
1964
+ | AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |
1965
+ | GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |
1966
+ | Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |
1967
+ | JWT | eyJ[a-zA-Z0-9_-]+ | high |
1968
+
1969
+ Injection patterns:
1970
+ | Construct | Safe alternative |
1971
+ |-----------|-----------------|
1972
+ | eval(str) | new Function() or parse |
1973
+ | innerHTML = x | textContent or sanitize |
1974
+ | exec(\`cmd \${x}\`) | execFile with args array |
1975
+
1976
+ Working rules:
1977
+ - Never scan node_modules \u2014 use npm audit instead
1978
+ - Always provide remediation steps, not just findings
1979
+ - Verify regex-based secrets before flagging (false positive risk)
1980
+ - When in doubt, flag as medium rather than ignoring potential issues`,
1981
+ maxIterations: 70,
1982
+ maxToolCalls: 280,
1983
+ timeoutMs: 16e4
1984
+ };
1985
+ var FLEET_ROSTER = {
1986
+ "audit-log": AUDIT_LOG_AGENT,
1987
+ "bug-hunter": BUG_HUNTER_AGENT,
1988
+ "refactor-planner": REFACTOR_PLANNER_AGENT,
1989
+ "security-scanner": SECURITY_SCANNER_AGENT
1990
+ };
1991
+ var ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);
1992
+
1993
+ export { ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, BUG_HUNTER_AGENT, BudgetExceededError, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DefaultMultiAgentCoordinator, Director, DirectorBudgetError, FLEET_ROSTER, FleetBus, FleetUsageAggregator, InMemoryAgentBridge, InMemoryBridgeTransport, REFACTOR_PLANNER_AGENT, SECURITY_SCANNER_AGENT, SubagentBudget, composeDirectorPrompt, composeSubagentPrompt, createMessage, makeAgentSubagentRunner, makeDirectorSessionFactory, rosterSummaryFromConfigs };
1994
+ //# sourceMappingURL=index.js.map
1995
+ //# sourceMappingURL=index.js.map