@wrongstack/core 0.1.7 → 0.1.8
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.
- package/dist/defaults/index.d.ts +492 -3
- package/dist/defaults/index.js +862 -5
- package/dist/defaults/index.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.js +869 -12
- package/dist/index.js.map +1 -1
- package/dist/{session-reader-7AutWHut.d.ts → session-reader-9sOTgmeC.d.ts} +31 -0
- package/dist/types/index.d.ts +1 -1
- package/package.json +2 -2
package/dist/defaults/index.js
CHANGED
|
@@ -3713,6 +3713,182 @@ function defaultFormatTaskInput(task) {
|
|
|
3713
3713
|
return task.description ?? "";
|
|
3714
3714
|
}
|
|
3715
3715
|
|
|
3716
|
+
// src/defaults/fleet-bus.ts
|
|
3717
|
+
var FleetBus = class {
|
|
3718
|
+
byId = /* @__PURE__ */ new Map();
|
|
3719
|
+
byType = /* @__PURE__ */ new Map();
|
|
3720
|
+
any = /* @__PURE__ */ new Set();
|
|
3721
|
+
/**
|
|
3722
|
+
* Hook a subagent's EventBus into the fleet. EventBus is strongly
|
|
3723
|
+
* typed and doesn't expose an `onAny` hook, so we subscribe to the
|
|
3724
|
+
* canonical set of event types a subagent emits during a run. New
|
|
3725
|
+
* event types added to the kernel must be added here too — but the
|
|
3726
|
+
* cost is a tiny single line per type, and the explicit list keeps
|
|
3727
|
+
* the wire format clear.
|
|
3728
|
+
*
|
|
3729
|
+
* Returns a disposer that detaches every subscription; call on
|
|
3730
|
+
* subagent teardown so the listeners don't outlive the run.
|
|
3731
|
+
*/
|
|
3732
|
+
attach(subagentId, bus, taskId) {
|
|
3733
|
+
const FORWARDED_TYPES = [
|
|
3734
|
+
"tool.started",
|
|
3735
|
+
"tool.executed",
|
|
3736
|
+
"tool.progress",
|
|
3737
|
+
"tool.confirm_needed",
|
|
3738
|
+
"iteration.started",
|
|
3739
|
+
"iteration.completed",
|
|
3740
|
+
"provider.text_delta",
|
|
3741
|
+
"provider.response",
|
|
3742
|
+
"provider.retry",
|
|
3743
|
+
"provider.error",
|
|
3744
|
+
"session.started",
|
|
3745
|
+
"session.ended",
|
|
3746
|
+
"token.threshold"
|
|
3747
|
+
];
|
|
3748
|
+
const offs = [];
|
|
3749
|
+
for (const t of FORWARDED_TYPES) {
|
|
3750
|
+
offs.push(
|
|
3751
|
+
bus.on(t, (payload) => {
|
|
3752
|
+
this.emit({ subagentId, taskId, ts: Date.now(), type: t, payload });
|
|
3753
|
+
})
|
|
3754
|
+
);
|
|
3755
|
+
}
|
|
3756
|
+
return () => {
|
|
3757
|
+
for (const off of offs) off();
|
|
3758
|
+
};
|
|
3759
|
+
}
|
|
3760
|
+
/** Subscribe to every event from one subagent. */
|
|
3761
|
+
subscribe(subagentId, handler) {
|
|
3762
|
+
let set = this.byId.get(subagentId);
|
|
3763
|
+
if (!set) {
|
|
3764
|
+
set = /* @__PURE__ */ new Set();
|
|
3765
|
+
this.byId.set(subagentId, set);
|
|
3766
|
+
}
|
|
3767
|
+
set.add(handler);
|
|
3768
|
+
return () => {
|
|
3769
|
+
set.delete(handler);
|
|
3770
|
+
};
|
|
3771
|
+
}
|
|
3772
|
+
/** Subscribe to one event type across all subagents. */
|
|
3773
|
+
filter(type, handler) {
|
|
3774
|
+
let set = this.byType.get(type);
|
|
3775
|
+
if (!set) {
|
|
3776
|
+
set = /* @__PURE__ */ new Set();
|
|
3777
|
+
this.byType.set(type, set);
|
|
3778
|
+
}
|
|
3779
|
+
set.add(handler);
|
|
3780
|
+
return () => {
|
|
3781
|
+
set.delete(handler);
|
|
3782
|
+
};
|
|
3783
|
+
}
|
|
3784
|
+
/** Subscribe to literally everything. The fleet roll-up uses this. */
|
|
3785
|
+
onAny(handler) {
|
|
3786
|
+
this.any.add(handler);
|
|
3787
|
+
return () => {
|
|
3788
|
+
this.any.delete(handler);
|
|
3789
|
+
};
|
|
3790
|
+
}
|
|
3791
|
+
emit(event) {
|
|
3792
|
+
const byId = this.byId.get(event.subagentId);
|
|
3793
|
+
if (byId) for (const h of byId) {
|
|
3794
|
+
try {
|
|
3795
|
+
h(event);
|
|
3796
|
+
} catch {
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
const byType = this.byType.get(event.type);
|
|
3800
|
+
if (byType) for (const h of byType) {
|
|
3801
|
+
try {
|
|
3802
|
+
h(event);
|
|
3803
|
+
} catch {
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
for (const h of this.any) {
|
|
3807
|
+
try {
|
|
3808
|
+
h(event);
|
|
3809
|
+
} catch {
|
|
3810
|
+
}
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
};
|
|
3814
|
+
var FleetUsageAggregator = class {
|
|
3815
|
+
constructor(bus, priceLookup, metaLookup) {
|
|
3816
|
+
this.bus = bus;
|
|
3817
|
+
this.priceLookup = priceLookup;
|
|
3818
|
+
this.metaLookup = metaLookup;
|
|
3819
|
+
bus.filter("provider.response", (e) => this.onProviderResponse(e));
|
|
3820
|
+
bus.filter("tool.executed", (e) => this.onToolExecuted(e));
|
|
3821
|
+
bus.filter("iteration.started", (e) => this.onIterationStarted(e));
|
|
3822
|
+
}
|
|
3823
|
+
bus;
|
|
3824
|
+
priceLookup;
|
|
3825
|
+
metaLookup;
|
|
3826
|
+
perSubagent = /* @__PURE__ */ new Map();
|
|
3827
|
+
total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
3828
|
+
/** Live snapshot — safe to call from a tool's execute() body. */
|
|
3829
|
+
snapshot() {
|
|
3830
|
+
return {
|
|
3831
|
+
total: { ...this.total },
|
|
3832
|
+
perSubagent: Object.fromEntries(
|
|
3833
|
+
Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }])
|
|
3834
|
+
)
|
|
3835
|
+
};
|
|
3836
|
+
}
|
|
3837
|
+
ensure(subagentId) {
|
|
3838
|
+
let snap = this.perSubagent.get(subagentId);
|
|
3839
|
+
if (!snap) {
|
|
3840
|
+
const meta = this.metaLookup?.(subagentId);
|
|
3841
|
+
snap = {
|
|
3842
|
+
subagentId,
|
|
3843
|
+
provider: meta?.provider,
|
|
3844
|
+
model: meta?.model,
|
|
3845
|
+
input: 0,
|
|
3846
|
+
output: 0,
|
|
3847
|
+
cacheRead: 0,
|
|
3848
|
+
cacheWrite: 0,
|
|
3849
|
+
cost: 0,
|
|
3850
|
+
toolCalls: 0,
|
|
3851
|
+
iterations: 0,
|
|
3852
|
+
startedAt: Date.now(),
|
|
3853
|
+
lastEventAt: Date.now()
|
|
3854
|
+
};
|
|
3855
|
+
this.perSubagent.set(subagentId, snap);
|
|
3856
|
+
}
|
|
3857
|
+
return snap;
|
|
3858
|
+
}
|
|
3859
|
+
onProviderResponse(e) {
|
|
3860
|
+
const snap = this.ensure(e.subagentId);
|
|
3861
|
+
const p = e.payload;
|
|
3862
|
+
const usage = p?.usage;
|
|
3863
|
+
if (!usage) return;
|
|
3864
|
+
snap.input += usage.input ?? 0;
|
|
3865
|
+
snap.output += usage.output ?? 0;
|
|
3866
|
+
snap.cacheRead += usage.cacheRead ?? 0;
|
|
3867
|
+
snap.cacheWrite += usage.cacheWrite ?? 0;
|
|
3868
|
+
this.total.input += usage.input ?? 0;
|
|
3869
|
+
this.total.output += usage.output ?? 0;
|
|
3870
|
+
this.total.cacheRead += usage.cacheRead ?? 0;
|
|
3871
|
+
this.total.cacheWrite += usage.cacheWrite ?? 0;
|
|
3872
|
+
const price = this.priceLookup?.(e.subagentId);
|
|
3873
|
+
if (price) {
|
|
3874
|
+
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);
|
|
3875
|
+
snap.cost += delta;
|
|
3876
|
+
this.total.cost += delta;
|
|
3877
|
+
}
|
|
3878
|
+
snap.lastEventAt = e.ts;
|
|
3879
|
+
}
|
|
3880
|
+
onToolExecuted(e) {
|
|
3881
|
+
const snap = this.ensure(e.subagentId);
|
|
3882
|
+
snap.toolCalls += 1;
|
|
3883
|
+
snap.lastEventAt = e.ts;
|
|
3884
|
+
}
|
|
3885
|
+
onIterationStarted(e) {
|
|
3886
|
+
const snap = this.ensure(e.subagentId);
|
|
3887
|
+
snap.iterations += 1;
|
|
3888
|
+
snap.lastEventAt = e.ts;
|
|
3889
|
+
}
|
|
3890
|
+
};
|
|
3891
|
+
|
|
3716
3892
|
// src/defaults/transport/in-memory-transport.ts
|
|
3717
3893
|
var InMemoryBridgeTransport = class {
|
|
3718
3894
|
subs = /* @__PURE__ */ new Map();
|
|
@@ -3840,6 +4016,678 @@ function createMessage(type, from, payload, to) {
|
|
|
3840
4016
|
};
|
|
3841
4017
|
}
|
|
3842
4018
|
|
|
4019
|
+
// src/defaults/director-prompts.ts
|
|
4020
|
+
var DEFAULT_DIRECTOR_PREAMBLE = `You are the Director of a multi-agent fleet. You orchestrate worker
|
|
4021
|
+
subagents by spawning them, assigning tasks, awaiting completions, and
|
|
4022
|
+
rolling up their outputs into your next decision.
|
|
4023
|
+
|
|
4024
|
+
Core fleet tools available to you:
|
|
4025
|
+
- spawn_subagent \u2014 create a worker with a chosen provider / model / role
|
|
4026
|
+
- assign_task \u2014 hand a piece of work to a specific subagent
|
|
4027
|
+
- await_tasks \u2014 block until named task ids complete (parallel-safe)
|
|
4028
|
+
- ask_subagent \u2014 synchronously query a running subagent via the bridge
|
|
4029
|
+
- roll_up \u2014 aggregate finished tasks into a markdown/json summary
|
|
4030
|
+
- terminate_subagent \u2014 abort a stuck worker (use sparingly)
|
|
4031
|
+
- fleet_status \u2014 snapshot of all subagents and pending tasks
|
|
4032
|
+
- fleet_usage \u2014 token + cost breakdown per subagent and total
|
|
4033
|
+
|
|
4034
|
+
Working rules:
|
|
4035
|
+
1. Decompose first. Before spawning, decide which sub-tasks are
|
|
4036
|
+
independent and can run in parallel. Sequential work doesn't need a
|
|
4037
|
+
subagent \u2014 do it yourself.
|
|
4038
|
+
2. Match worker to job. Cheap/fast model for triage, capable model for
|
|
4039
|
+
synthesis. Different providers per sibling is allowed and encouraged.
|
|
4040
|
+
3. Always pair an assign with an await. Don't fire-and-forget; you owe
|
|
4041
|
+
the user a single coherent answer at the end.
|
|
4042
|
+
4. Roll up before deciding. After await_tasks resolves, call roll_up so
|
|
4043
|
+
the results are folded back into your context in a compact form.
|
|
4044
|
+
5. Budget is real. Check fleet_usage periodically. If a subagent is
|
|
4045
|
+
thrashing, terminate it rather than letting cost climb silently.
|
|
4046
|
+
6. Never claim a subagent's work as your own without verifying it. If a
|
|
4047
|
+
result looks wrong, ask_subagent for clarification before passing it
|
|
4048
|
+
to the user.`;
|
|
4049
|
+
var DEFAULT_SUBAGENT_BASELINE = `You are a subagent operating under a Director. You were spawned to handle
|
|
4050
|
+
a specific slice of a larger plan \u2014 do that slice well and report back.
|
|
4051
|
+
|
|
4052
|
+
Bridge contract:
|
|
4053
|
+
- You have a parent (the Director). You may call \`request\` on the
|
|
4054
|
+
parent bridge to ask a clarifying question. Use this sparingly; the
|
|
4055
|
+
parent is also working.
|
|
4056
|
+
- You MAY NOT request the parent's system prompt, tool list, or other
|
|
4057
|
+
subagents' context. Those are not yours to read.
|
|
4058
|
+
- Your final task output is what the Director sees. Be concise,
|
|
4059
|
+
structured, and self-contained \u2014 assume the Director will paste your
|
|
4060
|
+
output into its own context.`;
|
|
4061
|
+
function composeDirectorPrompt(parts = {}) {
|
|
4062
|
+
const sections = [];
|
|
4063
|
+
const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
|
|
4064
|
+
if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());
|
|
4065
|
+
if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {
|
|
4066
|
+
sections.push(`Available roles you can spawn:
|
|
4067
|
+
${parts.rosterSummary.trim()}`);
|
|
4068
|
+
}
|
|
4069
|
+
if (parts.basePrompt && parts.basePrompt.trim().length > 0) {
|
|
4070
|
+
sections.push(parts.basePrompt.trim());
|
|
4071
|
+
}
|
|
4072
|
+
return sections.join("\n\n");
|
|
4073
|
+
}
|
|
4074
|
+
function composeSubagentPrompt(parts = {}) {
|
|
4075
|
+
const sections = [];
|
|
4076
|
+
const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;
|
|
4077
|
+
if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());
|
|
4078
|
+
if (parts.role && parts.role.trim().length > 0) {
|
|
4079
|
+
sections.push(`Role:
|
|
4080
|
+
${parts.role.trim()}`);
|
|
4081
|
+
}
|
|
4082
|
+
if (parts.task && parts.task.trim().length > 0) {
|
|
4083
|
+
sections.push(`Task:
|
|
4084
|
+
${parts.task.trim()}`);
|
|
4085
|
+
}
|
|
4086
|
+
if (parts.override && parts.override.trim().length > 0) {
|
|
4087
|
+
sections.push(parts.override.trim());
|
|
4088
|
+
}
|
|
4089
|
+
return sections.join("\n\n");
|
|
4090
|
+
}
|
|
4091
|
+
function rosterSummaryFromConfigs(roster) {
|
|
4092
|
+
const lines = [];
|
|
4093
|
+
for (const [roleId, cfg] of Object.entries(roster)) {
|
|
4094
|
+
const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : "";
|
|
4095
|
+
const headline = cfg.prompt ? (cfg.prompt.split("\n").find((l) => l.trim().length > 0) ?? "").trim().slice(0, 80) : "";
|
|
4096
|
+
const tail = headline ? ` \u2014 ${headline}` : "";
|
|
4097
|
+
lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);
|
|
4098
|
+
}
|
|
4099
|
+
return lines.join("\n");
|
|
4100
|
+
}
|
|
4101
|
+
|
|
4102
|
+
// src/defaults/director.ts
|
|
4103
|
+
var Director = class {
|
|
4104
|
+
id;
|
|
4105
|
+
fleet;
|
|
4106
|
+
usage;
|
|
4107
|
+
/**
|
|
4108
|
+
* Director-side bridge endpoint. Subagents are wired to the same
|
|
4109
|
+
* in-memory transport so the director can `ask()` them synchronously
|
|
4110
|
+
* and they can `send()` progress back. Exposed so external code (e.g.
|
|
4111
|
+
* the TUI) can subscribe to inbound messages.
|
|
4112
|
+
*/
|
|
4113
|
+
bridge;
|
|
4114
|
+
transport;
|
|
4115
|
+
coordinator;
|
|
4116
|
+
/** Resolves with the matching `TaskResult` the first time the
|
|
4117
|
+
* coordinator emits `task.completed` for a given task id. Each entry
|
|
4118
|
+
* is created lazily on first poll/await and cleared once consumed. */
|
|
4119
|
+
taskWaiters = /* @__PURE__ */ new Map();
|
|
4120
|
+
/** Cache of completed results in case the consumer asks AFTER the
|
|
4121
|
+
* coordinator already fired the event — `awaitTasks(['t-1'])` after
|
|
4122
|
+
* t-1 finished should resolve immediately, not hang. */
|
|
4123
|
+
completed = /* @__PURE__ */ new Map();
|
|
4124
|
+
/** Per-subagent provider/model metadata, captured at spawn time so the
|
|
4125
|
+
* FleetUsageAggregator's metaLookup can surface readable rows. */
|
|
4126
|
+
subagentMeta = /* @__PURE__ */ new Map();
|
|
4127
|
+
priceLookups = /* @__PURE__ */ new Map();
|
|
4128
|
+
/** Bridge endpoints we created per subagent (so we can `stop()` them
|
|
4129
|
+
* on shutdown and free transport subscriptions). */
|
|
4130
|
+
subagentBridges = /* @__PURE__ */ new Map();
|
|
4131
|
+
/** Tracks per-spawn config + assigned task ids for manifest writing. */
|
|
4132
|
+
manifestEntries = /* @__PURE__ */ new Map();
|
|
4133
|
+
manifestPath;
|
|
4134
|
+
roster;
|
|
4135
|
+
directorPreamble;
|
|
4136
|
+
subagentBaseline;
|
|
4137
|
+
constructor(opts) {
|
|
4138
|
+
this.id = opts.config.coordinatorId || randomUUID();
|
|
4139
|
+
this.manifestPath = opts.manifestPath;
|
|
4140
|
+
this.roster = opts.roster;
|
|
4141
|
+
this.directorPreamble = opts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;
|
|
4142
|
+
this.subagentBaseline = opts.subagentBaseline ?? DEFAULT_SUBAGENT_BASELINE;
|
|
4143
|
+
this.transport = new InMemoryBridgeTransport();
|
|
4144
|
+
this.bridge = new InMemoryAgentBridge(
|
|
4145
|
+
{ agentId: this.id, coordinatorId: this.id },
|
|
4146
|
+
this.transport
|
|
4147
|
+
);
|
|
4148
|
+
this.fleet = new FleetBus();
|
|
4149
|
+
this.usage = new FleetUsageAggregator(
|
|
4150
|
+
this.fleet,
|
|
4151
|
+
(id) => this.priceLookups.get(id),
|
|
4152
|
+
(id) => this.subagentMeta.get(id)
|
|
4153
|
+
);
|
|
4154
|
+
this.coordinator = new DefaultMultiAgentCoordinator(
|
|
4155
|
+
{ ...opts.config, coordinatorId: this.id },
|
|
4156
|
+
{ runner: opts.runner }
|
|
4157
|
+
);
|
|
4158
|
+
this.coordinator.on("task.completed", (payload) => {
|
|
4159
|
+
const r = payload.result;
|
|
4160
|
+
this.completed.set(r.taskId, r);
|
|
4161
|
+
const waiter = this.taskWaiters.get(r.taskId);
|
|
4162
|
+
if (waiter) {
|
|
4163
|
+
waiter.resolve(r);
|
|
4164
|
+
this.taskWaiters.delete(r.taskId);
|
|
4165
|
+
}
|
|
4166
|
+
});
|
|
4167
|
+
}
|
|
4168
|
+
/**
|
|
4169
|
+
* Spawn a subagent. Identical to the coordinator's `spawn()` but
|
|
4170
|
+
* captures provider/model metadata for the usage aggregator and
|
|
4171
|
+
* lets the FleetBus attach to the runner's EventBus when the task
|
|
4172
|
+
* actually runs (see `attachSubagentBus`).
|
|
4173
|
+
*
|
|
4174
|
+
* Caller-supplied `priceLookup` is optional but recommended — without
|
|
4175
|
+
* it the `cost` column in `usage.snapshot()` stays at 0.
|
|
4176
|
+
*/
|
|
4177
|
+
async spawn(config, priceLookup) {
|
|
4178
|
+
const result = await this.coordinator.spawn(config);
|
|
4179
|
+
this.subagentMeta.set(result.subagentId, {
|
|
4180
|
+
provider: config.provider,
|
|
4181
|
+
model: config.model
|
|
4182
|
+
});
|
|
4183
|
+
if (priceLookup) this.priceLookups.set(result.subagentId, priceLookup);
|
|
4184
|
+
const subagentBridge = new InMemoryAgentBridge(
|
|
4185
|
+
{ agentId: result.subagentId, coordinatorId: this.id },
|
|
4186
|
+
this.transport
|
|
4187
|
+
);
|
|
4188
|
+
this.coordinator.setSubagentBridge(result.subagentId, subagentBridge);
|
|
4189
|
+
this.subagentBridges.set(result.subagentId, subagentBridge);
|
|
4190
|
+
this.manifestEntries.set(result.subagentId, {
|
|
4191
|
+
subagentId: result.subagentId,
|
|
4192
|
+
name: config.name,
|
|
4193
|
+
role: config.role,
|
|
4194
|
+
provider: config.provider,
|
|
4195
|
+
model: config.model,
|
|
4196
|
+
taskIds: []
|
|
4197
|
+
});
|
|
4198
|
+
return result.subagentId;
|
|
4199
|
+
}
|
|
4200
|
+
/**
|
|
4201
|
+
* Synchronously ask a subagent something via the bridge. Sends a
|
|
4202
|
+
* `task` message addressed to the subagent and awaits a matching
|
|
4203
|
+
* reply (matched by message id). Subagent runners that handle these
|
|
4204
|
+
* requests subscribe to `ctx.bridge` and reply with a message whose
|
|
4205
|
+
* `id` equals the incoming request's id (see `InMemoryAgentBridge`'s
|
|
4206
|
+
* `request<T>` implementation).
|
|
4207
|
+
*
|
|
4208
|
+
* Returns the response payload directly (the bridge wrapper is
|
|
4209
|
+
* unwrapped for ergonomics). Times out after `timeoutMs` (default
|
|
4210
|
+
* matches the bridge's own default of 30s) — surface those rejections
|
|
4211
|
+
* to the caller as actionable errors instead of letting tools hang.
|
|
4212
|
+
*/
|
|
4213
|
+
async ask(subagentId, payload, timeoutMs) {
|
|
4214
|
+
if (!this.subagentBridges.has(subagentId)) {
|
|
4215
|
+
throw new Error(
|
|
4216
|
+
`ask: unknown subagent "${subagentId}" (spawn() it first; current fleet: ${Array.from(this.subagentBridges.keys()).join(", ") || "(empty)"})`
|
|
4217
|
+
);
|
|
4218
|
+
}
|
|
4219
|
+
const msg = {
|
|
4220
|
+
id: randomUUID(),
|
|
4221
|
+
type: "task",
|
|
4222
|
+
from: this.id,
|
|
4223
|
+
to: subagentId,
|
|
4224
|
+
payload,
|
|
4225
|
+
timestamp: Date.now(),
|
|
4226
|
+
priority: "normal"
|
|
4227
|
+
};
|
|
4228
|
+
const reply = await this.bridge.request(msg, timeoutMs);
|
|
4229
|
+
return reply.payload;
|
|
4230
|
+
}
|
|
4231
|
+
/**
|
|
4232
|
+
* Read completed task results and format them as a structured text
|
|
4233
|
+
* block the director's LLM can paste into its own context. The
|
|
4234
|
+
* Director keeps every completed `TaskResult` in `completed` so this
|
|
4235
|
+
* is a pure read — no bridge round-trip, cheap to call.
|
|
4236
|
+
*
|
|
4237
|
+
* The returned string is intentionally markdown-flavored: headers per
|
|
4238
|
+
* subagent, a one-line meta row (iter / tools / ms), and the task's
|
|
4239
|
+
* result text. Pass `style: 'json'` for a programmatic shape instead
|
|
4240
|
+
* (useful when the director model is doing structured-output work).
|
|
4241
|
+
*/
|
|
4242
|
+
rollUp(taskIds, style = "markdown") {
|
|
4243
|
+
const rows = taskIds.map((id) => this.completed.get(id)).filter(
|
|
4244
|
+
(r) => !!r
|
|
4245
|
+
);
|
|
4246
|
+
if (style === "json") {
|
|
4247
|
+
return JSON.stringify(
|
|
4248
|
+
rows.map((r) => ({
|
|
4249
|
+
taskId: r.taskId,
|
|
4250
|
+
subagentId: r.subagentId,
|
|
4251
|
+
status: r.status,
|
|
4252
|
+
iterations: r.iterations,
|
|
4253
|
+
toolCalls: r.toolCalls,
|
|
4254
|
+
durationMs: r.durationMs,
|
|
4255
|
+
result: r.result,
|
|
4256
|
+
error: r.error
|
|
4257
|
+
})),
|
|
4258
|
+
null,
|
|
4259
|
+
2
|
|
4260
|
+
);
|
|
4261
|
+
}
|
|
4262
|
+
if (rows.length === 0) {
|
|
4263
|
+
return "_No completed tasks for the requested ids \u2014 try waiting first._";
|
|
4264
|
+
}
|
|
4265
|
+
const lines = [];
|
|
4266
|
+
for (const r of rows) {
|
|
4267
|
+
const meta = this.subagentMeta.get(r.subagentId);
|
|
4268
|
+
const tag = meta?.provider && meta?.model ? ` \xB7 ${meta.provider}/${meta.model}` : "";
|
|
4269
|
+
lines.push(`### ${r.subagentId}${tag}`);
|
|
4270
|
+
lines.push(
|
|
4271
|
+
`_${r.status} \u2014 ${r.iterations} iter \xB7 ${r.toolCalls} tools \xB7 ${r.durationMs}ms_`
|
|
4272
|
+
);
|
|
4273
|
+
lines.push("");
|
|
4274
|
+
if (r.error) lines.push(`**Error:** ${r.error}`);
|
|
4275
|
+
else if (typeof r.result === "string") lines.push(r.result);
|
|
4276
|
+
else if (r.result !== void 0) lines.push("```json\n" + JSON.stringify(r.result, null, 2) + "\n```");
|
|
4277
|
+
else lines.push("_(no output)_");
|
|
4278
|
+
lines.push("");
|
|
4279
|
+
}
|
|
4280
|
+
return lines.join("\n").trimEnd();
|
|
4281
|
+
}
|
|
4282
|
+
/**
|
|
4283
|
+
* Write the fleet manifest to `manifestPath`. Returns the path written
|
|
4284
|
+
* or null when no path was configured. Captures every spawn + its
|
|
4285
|
+
* assigned tasks — paired with per-subagent JSONLs, this is enough to
|
|
4286
|
+
* replay an entire director run.
|
|
4287
|
+
*/
|
|
4288
|
+
async writeManifest() {
|
|
4289
|
+
if (!this.manifestPath) return null;
|
|
4290
|
+
const manifest = {
|
|
4291
|
+
directorRunId: this.id,
|
|
4292
|
+
writtenAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4293
|
+
children: Array.from(this.manifestEntries.values()).map((e) => ({
|
|
4294
|
+
...e,
|
|
4295
|
+
// Surface final status from `completed` when available — manifest
|
|
4296
|
+
// becomes much more useful for replay when it carries the
|
|
4297
|
+
// success/failure state.
|
|
4298
|
+
results: e.taskIds.map((tid) => {
|
|
4299
|
+
const r = this.completed.get(tid);
|
|
4300
|
+
return r ? {
|
|
4301
|
+
taskId: tid,
|
|
4302
|
+
status: r.status,
|
|
4303
|
+
iterations: r.iterations,
|
|
4304
|
+
toolCalls: r.toolCalls,
|
|
4305
|
+
durationMs: r.durationMs
|
|
4306
|
+
} : { taskId: tid, status: "pending" };
|
|
4307
|
+
})
|
|
4308
|
+
})),
|
|
4309
|
+
usage: this.usage.snapshot()
|
|
4310
|
+
};
|
|
4311
|
+
await fsp.mkdir(path2.dirname(this.manifestPath), { recursive: true });
|
|
4312
|
+
await fsp.writeFile(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 384 });
|
|
4313
|
+
return this.manifestPath;
|
|
4314
|
+
}
|
|
4315
|
+
/**
|
|
4316
|
+
* Tear down the director: stop every subagent, close every bridge
|
|
4317
|
+
* endpoint, and (when configured) write the final manifest. Idempotent
|
|
4318
|
+
* — calling shutdown twice is a no-op on the second invocation.
|
|
4319
|
+
*/
|
|
4320
|
+
async shutdown() {
|
|
4321
|
+
await this.coordinator.stopAll();
|
|
4322
|
+
for (const b of this.subagentBridges.values()) {
|
|
4323
|
+
await b.stop().catch(() => void 0);
|
|
4324
|
+
}
|
|
4325
|
+
this.subagentBridges.clear();
|
|
4326
|
+
await this.bridge.stop().catch(() => void 0);
|
|
4327
|
+
if (this.manifestPath) await this.writeManifest().catch(() => void 0);
|
|
4328
|
+
}
|
|
4329
|
+
/**
|
|
4330
|
+
* Hand a task to the coordinator. Returns the assigned task id so
|
|
4331
|
+
* callers can wait on it via `awaitTasks([id])`. The coordinator's
|
|
4332
|
+
* concurrency limit applies — the task may queue before running.
|
|
4333
|
+
*/
|
|
4334
|
+
async assign(task) {
|
|
4335
|
+
const taskWithId = task.id ? task : { ...task, id: randomUUID() };
|
|
4336
|
+
if (task.subagentId) {
|
|
4337
|
+
const entry = this.manifestEntries.get(task.subagentId);
|
|
4338
|
+
if (entry) entry.taskIds.push(taskWithId.id);
|
|
4339
|
+
}
|
|
4340
|
+
await this.coordinator.assign(taskWithId);
|
|
4341
|
+
return taskWithId.id;
|
|
4342
|
+
}
|
|
4343
|
+
/**
|
|
4344
|
+
* Block until every task id resolves. Returns results in the same
|
|
4345
|
+
* order as the input. If any task hasn't completed by the time this
|
|
4346
|
+
* is called, the promise hangs until it does — pair with a timeout
|
|
4347
|
+
* at the caller if that's a concern. Resolves immediately for ids
|
|
4348
|
+
* whose results were already cached.
|
|
4349
|
+
*/
|
|
4350
|
+
awaitTasks(taskIds) {
|
|
4351
|
+
return Promise.all(taskIds.map((id) => {
|
|
4352
|
+
const cached = this.completed.get(id);
|
|
4353
|
+
if (cached) return cached;
|
|
4354
|
+
const existing = this.taskWaiters.get(id);
|
|
4355
|
+
if (existing) return existing.promise;
|
|
4356
|
+
let resolve3;
|
|
4357
|
+
const promise = new Promise((res) => {
|
|
4358
|
+
resolve3 = res;
|
|
4359
|
+
});
|
|
4360
|
+
this.taskWaiters.set(id, { promise, resolve: resolve3 });
|
|
4361
|
+
return promise;
|
|
4362
|
+
}));
|
|
4363
|
+
}
|
|
4364
|
+
async terminate(subagentId) {
|
|
4365
|
+
await this.coordinator.stop(subagentId);
|
|
4366
|
+
}
|
|
4367
|
+
async terminateAll() {
|
|
4368
|
+
await this.coordinator.stopAll();
|
|
4369
|
+
}
|
|
4370
|
+
status() {
|
|
4371
|
+
return this.coordinator.getStatus();
|
|
4372
|
+
}
|
|
4373
|
+
/**
|
|
4374
|
+
* Subscribe to coordinator events. Currently only `task.completed` is
|
|
4375
|
+
* exposed (the others are internal lifecycle). Returns an unsubscribe
|
|
4376
|
+
* function. External callers (e.g. the CLI's `MultiAgentHost`) use this
|
|
4377
|
+
* to drive their own pending/results tracking without poking the
|
|
4378
|
+
* coordinator directly.
|
|
4379
|
+
*/
|
|
4380
|
+
on(event, handler) {
|
|
4381
|
+
this.coordinator.on(event, handler);
|
|
4382
|
+
return () => {
|
|
4383
|
+
this.coordinator.off(event, handler);
|
|
4384
|
+
};
|
|
4385
|
+
}
|
|
4386
|
+
/**
|
|
4387
|
+
* Snapshot of every task that has resolved (success, failed, timeout,
|
|
4388
|
+
* stopped) since the director started. Returned in completion order
|
|
4389
|
+
* via the internal map's iteration order. Used by `/fleet status` to
|
|
4390
|
+
* paint the completed table without reaching into private state.
|
|
4391
|
+
*/
|
|
4392
|
+
completedResults() {
|
|
4393
|
+
return Array.from(this.completed.values());
|
|
4394
|
+
}
|
|
4395
|
+
snapshot() {
|
|
4396
|
+
return this.usage.snapshot();
|
|
4397
|
+
}
|
|
4398
|
+
/**
|
|
4399
|
+
* Compose the leader/director-agent system prompt: fleet preamble +
|
|
4400
|
+
* (optional) roster summary + user base prompt. Pass the result to your
|
|
4401
|
+
* leader Agent's `ctx.systemPrompt` when constructing it.
|
|
4402
|
+
*
|
|
4403
|
+
* `basePrompt` defaults to `config.leaderSystemPrompt` so callers can
|
|
4404
|
+
* use the no-arg form when the multi-agent config already carries it.
|
|
4405
|
+
*/
|
|
4406
|
+
leaderSystemPrompt(basePrompt) {
|
|
4407
|
+
return composeDirectorPrompt({
|
|
4408
|
+
basePrompt: basePrompt ?? this.coordinator.config.leaderSystemPrompt,
|
|
4409
|
+
directorPreamble: this.directorPreamble,
|
|
4410
|
+
rosterSummary: this.roster ? rosterSummaryFromConfigs(this.roster) : void 0
|
|
4411
|
+
});
|
|
4412
|
+
}
|
|
4413
|
+
/**
|
|
4414
|
+
* Compose a subagent's system prompt for a given `SubagentConfig`:
|
|
4415
|
+
* baseline + role + task + per-spawn override. Returned by value — does
|
|
4416
|
+
* not mutate the config. Factories (the user-supplied `AgentFactory`)
|
|
4417
|
+
* should call this when building each subagent's Agent so the bridge
|
|
4418
|
+
* contract, role context, and override are all surfaced.
|
|
4419
|
+
*
|
|
4420
|
+
* When `taskBrief` is omitted the Task section is dropped. Pass the
|
|
4421
|
+
* actual task description here to reinforce it in the system prompt
|
|
4422
|
+
* (the runner already passes it as user input — duplicating in the
|
|
4423
|
+
* system prompt is optional but improves anchoring on small models).
|
|
4424
|
+
*/
|
|
4425
|
+
subagentSystemPrompt(config, taskBrief) {
|
|
4426
|
+
return composeSubagentPrompt({
|
|
4427
|
+
baseline: this.subagentBaseline,
|
|
4428
|
+
role: config.prompt,
|
|
4429
|
+
task: taskBrief,
|
|
4430
|
+
override: config.systemPromptOverride
|
|
4431
|
+
});
|
|
4432
|
+
}
|
|
4433
|
+
/**
|
|
4434
|
+
* Build the tool set the LLM-driven director uses to orchestrate.
|
|
4435
|
+
* Returns an array of `Tool` definitions; register these on the
|
|
4436
|
+
* director's `Agent` to expose `spawn_subagent`, `assign_task`, etc.
|
|
4437
|
+
* Each tool's `execute()` delegates straight to the matching method
|
|
4438
|
+
* above.
|
|
4439
|
+
*
|
|
4440
|
+
* Tools all carry `permission: 'auto'` — the *user* has already
|
|
4441
|
+
* approved running the director when they kicked off the run, so
|
|
4442
|
+
* gating individual orchestration calls behind a confirm prompt
|
|
4443
|
+
* would just be noise. The actual subagent tools they spawn are
|
|
4444
|
+
* still permission-checked normally.
|
|
4445
|
+
*/
|
|
4446
|
+
tools(roster) {
|
|
4447
|
+
const t = [
|
|
4448
|
+
makeSpawnTool(this, roster),
|
|
4449
|
+
makeAssignTool(this),
|
|
4450
|
+
makeAwaitTasksTool(this),
|
|
4451
|
+
makeAskTool(this),
|
|
4452
|
+
makeRollUpTool(this),
|
|
4453
|
+
makeTerminateTool(this),
|
|
4454
|
+
makeFleetStatusTool(this),
|
|
4455
|
+
makeFleetUsageTool(this)
|
|
4456
|
+
];
|
|
4457
|
+
return t;
|
|
4458
|
+
}
|
|
4459
|
+
};
|
|
4460
|
+
function makeSpawnTool(director, roster) {
|
|
4461
|
+
const inputSchema = {
|
|
4462
|
+
type: "object",
|
|
4463
|
+
properties: {
|
|
4464
|
+
role: { type: "string", description: "Roster role id (preferred). When set, the spawn uses the matching config from the roster and ignores other fields." },
|
|
4465
|
+
name: { type: "string", description: "Display name for the subagent. Required when not using roster." },
|
|
4466
|
+
provider: { type: "string", description: 'Provider id (e.g. "anthropic", "openai"). Defaults to the leader provider when omitted.' },
|
|
4467
|
+
model: { type: "string", description: "Model id within the provider. Defaults to the leader model when omitted." },
|
|
4468
|
+
systemPromptOverride: { type: "string", description: "Extra prompt text appended after the role-base prompt." },
|
|
4469
|
+
maxIterations: { type: "number" },
|
|
4470
|
+
maxToolCalls: { type: "number" },
|
|
4471
|
+
maxCostUsd: { type: "number" }
|
|
4472
|
+
},
|
|
4473
|
+
required: []
|
|
4474
|
+
};
|
|
4475
|
+
return {
|
|
4476
|
+
name: "spawn_subagent",
|
|
4477
|
+
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.",
|
|
4478
|
+
usageHint: "Either pass `role` (matches the roster) OR pass `name` + optional `provider`/`model`. Returns `{ subagentId }`.",
|
|
4479
|
+
permission: "auto",
|
|
4480
|
+
mutating: false,
|
|
4481
|
+
inputSchema,
|
|
4482
|
+
async execute(input) {
|
|
4483
|
+
const i = input ?? {};
|
|
4484
|
+
const role = typeof i.role === "string" ? i.role : void 0;
|
|
4485
|
+
const base = role && roster ? roster[role] : void 0;
|
|
4486
|
+
if (role && !base) {
|
|
4487
|
+
return { error: `unknown role "${role}". roster has: ${roster ? Object.keys(roster).join(", ") : "(empty)"}` };
|
|
4488
|
+
}
|
|
4489
|
+
const cfg = {
|
|
4490
|
+
...base ?? { name: i.name ?? "subagent" }
|
|
4491
|
+
};
|
|
4492
|
+
if (typeof i.name === "string") cfg.name = i.name;
|
|
4493
|
+
if (typeof i.provider === "string") cfg.provider = i.provider;
|
|
4494
|
+
if (typeof i.model === "string") cfg.model = i.model;
|
|
4495
|
+
if (typeof i.systemPromptOverride === "string") cfg.systemPromptOverride = i.systemPromptOverride;
|
|
4496
|
+
if (typeof i.maxIterations === "number") cfg.maxIterations = i.maxIterations;
|
|
4497
|
+
if (typeof i.maxToolCalls === "number") cfg.maxToolCalls = i.maxToolCalls;
|
|
4498
|
+
if (typeof i.maxCostUsd === "number") cfg.maxCostUsd = i.maxCostUsd;
|
|
4499
|
+
const subagentId = await director.spawn(cfg);
|
|
4500
|
+
return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name };
|
|
4501
|
+
}
|
|
4502
|
+
};
|
|
4503
|
+
}
|
|
4504
|
+
function makeAssignTool(director) {
|
|
4505
|
+
const inputSchema = {
|
|
4506
|
+
type: "object",
|
|
4507
|
+
properties: {
|
|
4508
|
+
subagentId: { type: "string", description: "Target subagent id. Required." },
|
|
4509
|
+
description: { type: "string", description: "The task in natural language \u2014 what you want this subagent to do." },
|
|
4510
|
+
maxToolCalls: { type: "number", description: "Optional per-task tool-call budget override." },
|
|
4511
|
+
timeoutMs: { type: "number", description: "Optional per-task timeout in ms." }
|
|
4512
|
+
},
|
|
4513
|
+
required: ["subagentId", "description"]
|
|
4514
|
+
};
|
|
4515
|
+
return {
|
|
4516
|
+
name: "assign_task",
|
|
4517
|
+
description: "Hand a task to a previously spawned subagent. Returns the task id \u2014 pass it to `await_tasks` to block on completion.",
|
|
4518
|
+
permission: "auto",
|
|
4519
|
+
mutating: false,
|
|
4520
|
+
inputSchema,
|
|
4521
|
+
async execute(input) {
|
|
4522
|
+
const i = input;
|
|
4523
|
+
const task = {
|
|
4524
|
+
id: randomUUID(),
|
|
4525
|
+
description: i.description,
|
|
4526
|
+
subagentId: i.subagentId,
|
|
4527
|
+
maxToolCalls: i.maxToolCalls,
|
|
4528
|
+
timeoutMs: i.timeoutMs
|
|
4529
|
+
};
|
|
4530
|
+
const taskId = await director.assign(task);
|
|
4531
|
+
return { taskId, subagentId: i.subagentId };
|
|
4532
|
+
}
|
|
4533
|
+
};
|
|
4534
|
+
}
|
|
4535
|
+
function makeAwaitTasksTool(director) {
|
|
4536
|
+
const inputSchema = {
|
|
4537
|
+
type: "object",
|
|
4538
|
+
properties: {
|
|
4539
|
+
taskIds: {
|
|
4540
|
+
type: "array",
|
|
4541
|
+
items: { type: "string" },
|
|
4542
|
+
description: "One or more task ids returned by `assign_task`. The call blocks until every id resolves."
|
|
4543
|
+
}
|
|
4544
|
+
},
|
|
4545
|
+
required: ["taskIds"]
|
|
4546
|
+
};
|
|
4547
|
+
return {
|
|
4548
|
+
name: "await_tasks",
|
|
4549
|
+
description: "Block until every named task completes. Returns the array of TaskResult \u2014 use this to gather subagent output before deciding the next step.",
|
|
4550
|
+
permission: "auto",
|
|
4551
|
+
mutating: false,
|
|
4552
|
+
inputSchema,
|
|
4553
|
+
async execute(input) {
|
|
4554
|
+
const i = input;
|
|
4555
|
+
const results = await director.awaitTasks(i.taskIds);
|
|
4556
|
+
return { results };
|
|
4557
|
+
}
|
|
4558
|
+
};
|
|
4559
|
+
}
|
|
4560
|
+
function makeAskTool(director) {
|
|
4561
|
+
const inputSchema = {
|
|
4562
|
+
type: "object",
|
|
4563
|
+
properties: {
|
|
4564
|
+
subagentId: { type: "string", description: "Subagent to ask. Must be a previously spawned id." },
|
|
4565
|
+
question: { type: "string", description: "The question or instruction. Sent as the bridge message payload." },
|
|
4566
|
+
timeoutMs: { type: "number", description: "Optional timeout in ms (default 30s)." }
|
|
4567
|
+
},
|
|
4568
|
+
required: ["subagentId", "question"]
|
|
4569
|
+
};
|
|
4570
|
+
return {
|
|
4571
|
+
name: "ask_subagent",
|
|
4572
|
+
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.",
|
|
4573
|
+
permission: "auto",
|
|
4574
|
+
mutating: false,
|
|
4575
|
+
inputSchema,
|
|
4576
|
+
async execute(input) {
|
|
4577
|
+
const i = input;
|
|
4578
|
+
try {
|
|
4579
|
+
const answer = await director.ask(i.subagentId, { question: i.question }, i.timeoutMs);
|
|
4580
|
+
return { ok: true, answer };
|
|
4581
|
+
} catch (err) {
|
|
4582
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
4583
|
+
}
|
|
4584
|
+
}
|
|
4585
|
+
};
|
|
4586
|
+
}
|
|
4587
|
+
function makeRollUpTool(director) {
|
|
4588
|
+
const inputSchema = {
|
|
4589
|
+
type: "object",
|
|
4590
|
+
properties: {
|
|
4591
|
+
taskIds: {
|
|
4592
|
+
type: "array",
|
|
4593
|
+
items: { type: "string" },
|
|
4594
|
+
description: "Completed task ids to aggregate. Pass the ids returned by previous `assign_task` calls."
|
|
4595
|
+
},
|
|
4596
|
+
style: {
|
|
4597
|
+
type: "string",
|
|
4598
|
+
enum: ["markdown", "json"],
|
|
4599
|
+
description: "Output flavor \u2014 markdown (default) for in-prompt summarization, json for structured downstream processing."
|
|
4600
|
+
}
|
|
4601
|
+
},
|
|
4602
|
+
required: ["taskIds"]
|
|
4603
|
+
};
|
|
4604
|
+
return {
|
|
4605
|
+
name: "roll_up",
|
|
4606
|
+
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.",
|
|
4607
|
+
permission: "auto",
|
|
4608
|
+
mutating: false,
|
|
4609
|
+
inputSchema,
|
|
4610
|
+
async execute(input) {
|
|
4611
|
+
const i = input;
|
|
4612
|
+
const summary = director.rollUp(i.taskIds, i.style ?? "markdown");
|
|
4613
|
+
return { summary, count: i.taskIds.length };
|
|
4614
|
+
}
|
|
4615
|
+
};
|
|
4616
|
+
}
|
|
4617
|
+
function makeTerminateTool(director) {
|
|
4618
|
+
const inputSchema = {
|
|
4619
|
+
type: "object",
|
|
4620
|
+
properties: {
|
|
4621
|
+
subagentId: { type: "string", description: "Subagent to abort." }
|
|
4622
|
+
},
|
|
4623
|
+
required: ["subagentId"]
|
|
4624
|
+
};
|
|
4625
|
+
return {
|
|
4626
|
+
name: "terminate_subagent",
|
|
4627
|
+
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".',
|
|
4628
|
+
permission: "auto",
|
|
4629
|
+
mutating: true,
|
|
4630
|
+
inputSchema,
|
|
4631
|
+
async execute(input) {
|
|
4632
|
+
const i = input;
|
|
4633
|
+
await director.terminate(i.subagentId);
|
|
4634
|
+
return { ok: true };
|
|
4635
|
+
}
|
|
4636
|
+
};
|
|
4637
|
+
}
|
|
4638
|
+
function makeFleetStatusTool(director) {
|
|
4639
|
+
return {
|
|
4640
|
+
name: "fleet_status",
|
|
4641
|
+
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.",
|
|
4642
|
+
permission: "auto",
|
|
4643
|
+
mutating: false,
|
|
4644
|
+
inputSchema: { type: "object", properties: {}, required: [] },
|
|
4645
|
+
async execute() {
|
|
4646
|
+
return director.status();
|
|
4647
|
+
}
|
|
4648
|
+
};
|
|
4649
|
+
}
|
|
4650
|
+
function makeFleetUsageTool(director) {
|
|
4651
|
+
return {
|
|
4652
|
+
name: "fleet_usage",
|
|
4653
|
+
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.",
|
|
4654
|
+
permission: "auto",
|
|
4655
|
+
mutating: false,
|
|
4656
|
+
inputSchema: { type: "object", properties: {}, required: [] },
|
|
4657
|
+
async execute() {
|
|
4658
|
+
return director.snapshot();
|
|
4659
|
+
}
|
|
4660
|
+
};
|
|
4661
|
+
}
|
|
4662
|
+
function makeDirectorSessionFactory(opts) {
|
|
4663
|
+
const runId = opts.directorRunId ?? `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-director`;
|
|
4664
|
+
let store;
|
|
4665
|
+
let dir;
|
|
4666
|
+
if (opts.store) {
|
|
4667
|
+
store = opts.store;
|
|
4668
|
+
dir = opts.sessionsRoot ? path2.join(opts.sessionsRoot, runId) : "(caller-managed)";
|
|
4669
|
+
} else if (opts.sessionsRoot) {
|
|
4670
|
+
dir = path2.join(opts.sessionsRoot, runId);
|
|
4671
|
+
store = new DefaultSessionStore({ dir });
|
|
4672
|
+
} else {
|
|
4673
|
+
throw new Error(
|
|
4674
|
+
"makeDirectorSessionFactory requires either `store` or `sessionsRoot`"
|
|
4675
|
+
);
|
|
4676
|
+
}
|
|
4677
|
+
return {
|
|
4678
|
+
dir,
|
|
4679
|
+
directorRunId: runId,
|
|
4680
|
+
async createSubagentSession({ subagentId, provider, model, title }) {
|
|
4681
|
+
return store.create({
|
|
4682
|
+
id: subagentId,
|
|
4683
|
+
title: title ?? subagentId,
|
|
4684
|
+
provider: provider ?? "unknown",
|
|
4685
|
+
model: model ?? "unknown"
|
|
4686
|
+
});
|
|
4687
|
+
}
|
|
4688
|
+
};
|
|
4689
|
+
}
|
|
4690
|
+
|
|
3843
4691
|
// src/defaults/autonomous-runner.ts
|
|
3844
4692
|
var DoneConditionChecker = class {
|
|
3845
4693
|
constructor(condition) {
|
|
@@ -3881,6 +4729,16 @@ var AutonomousRunner = class {
|
|
|
3881
4729
|
stopped = false;
|
|
3882
4730
|
doneChecker;
|
|
3883
4731
|
async run() {
|
|
4732
|
+
const offToolExecuted = this.opts.agent.events?.on?.("tool.executed", () => {
|
|
4733
|
+
this.toolCalls++;
|
|
4734
|
+
});
|
|
4735
|
+
try {
|
|
4736
|
+
return await this.runLoop();
|
|
4737
|
+
} finally {
|
|
4738
|
+
offToolExecuted?.();
|
|
4739
|
+
}
|
|
4740
|
+
}
|
|
4741
|
+
async runLoop() {
|
|
3884
4742
|
while (!this.stopped) {
|
|
3885
4743
|
const check = this.doneChecker.check({
|
|
3886
4744
|
iterations: this.iterations,
|
|
@@ -3907,7 +4765,6 @@ var AutonomousRunner = class {
|
|
|
3907
4765
|
);
|
|
3908
4766
|
this.iterations++;
|
|
3909
4767
|
this.lastOutput = result.finalText;
|
|
3910
|
-
this.toolCalls++;
|
|
3911
4768
|
if (result.status === "failed" || result.status === "aborted") {
|
|
3912
4769
|
const failedResult = {
|
|
3913
4770
|
status: result.status,
|
|
@@ -5801,7 +6658,7 @@ var PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
|
|
|
5801
6658
|
async function startMetricsServer(opts) {
|
|
5802
6659
|
const { createServer } = await import('http');
|
|
5803
6660
|
const host = opts.host ?? "127.0.0.1";
|
|
5804
|
-
const
|
|
6661
|
+
const path15 = opts.path ?? "/metrics";
|
|
5805
6662
|
const healthPath = opts.healthPath ?? "/healthz";
|
|
5806
6663
|
const healthRegistry = opts.healthRegistry;
|
|
5807
6664
|
const server = createServer((req, res) => {
|
|
@@ -5811,7 +6668,7 @@ async function startMetricsServer(opts) {
|
|
|
5811
6668
|
return;
|
|
5812
6669
|
}
|
|
5813
6670
|
const url = req.url.split("?")[0];
|
|
5814
|
-
if (url ===
|
|
6671
|
+
if (url === path15) {
|
|
5815
6672
|
let body;
|
|
5816
6673
|
try {
|
|
5817
6674
|
body = renderPrometheus(opts.sink.snapshot());
|
|
@@ -5862,7 +6719,7 @@ async function startMetricsServer(opts) {
|
|
|
5862
6719
|
const boundPort = typeof addr === "object" && addr ? addr.port : opts.port;
|
|
5863
6720
|
return {
|
|
5864
6721
|
port: boundPort,
|
|
5865
|
-
url: `http://${host}:${boundPort}${
|
|
6722
|
+
url: `http://${host}:${boundPort}${path15}`,
|
|
5866
6723
|
close: () => new Promise((resolve3, reject) => {
|
|
5867
6724
|
server.close((err) => err ? reject(err) : resolve3());
|
|
5868
6725
|
})
|
|
@@ -6396,6 +7253,6 @@ var allServers = () => ({
|
|
|
6396
7253
|
sentinel: { ...sentinelServer(), enabled: false }
|
|
6397
7254
|
});
|
|
6398
7255
|
|
|
6399
|
-
export { AutoCompactionMiddleware, AutonomousRunner, BudgetExceededError, ConfigMigrationError, DEFAULT_CONFIG_MIGRATIONS, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, DefaultTokenCounter, DoneConditionChecker, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, LLMSelector, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, QueueStore, RecoveryLock, SelectiveCompactor, SpecDrivenDev, SpecParser, SubagentBudget, TaskFlow, TaskGenerator, TaskTracker, ToolExecutor, allServers, awsServer, blockServer, braveSearchServer, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, context7Server, contextManagerTool, createContextManagerTool, createMessage, decryptConfigSecrets, encryptConfigSecrets, everArtServer, filesystemServer, githubServer, googleMapsServer, loadProjectModes, loadUserModes, makeAgentSubagentRunner, migratePlaintextSecrets, renderPrometheus, rewriteConfigEncrypted, runConfigMigrations, sentinelServer, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, wireMetricsToEvents };
|
|
7256
|
+
export { AutoCompactionMiddleware, AutonomousRunner, BudgetExceededError, ConfigMigrationError, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, DefaultTokenCounter, Director, DoneConditionChecker, FleetBus, FleetUsageAggregator, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, LLMSelector, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, QueueStore, RecoveryLock, SelectiveCompactor, SpecDrivenDev, SpecParser, SubagentBudget, TaskFlow, TaskGenerator, TaskTracker, ToolExecutor, allServers, awsServer, blockServer, braveSearchServer, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, composeDirectorPrompt, composeSubagentPrompt, context7Server, contextManagerTool, createContextManagerTool, createMessage, decryptConfigSecrets, encryptConfigSecrets, everArtServer, filesystemServer, githubServer, googleMapsServer, loadProjectModes, loadUserModes, makeAgentSubagentRunner, makeDirectorSessionFactory, migratePlaintextSecrets, renderPrometheus, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, sentinelServer, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, wireMetricsToEvents };
|
|
6400
7257
|
//# sourceMappingURL=index.js.map
|
|
6401
7258
|
//# sourceMappingURL=index.js.map
|