operon-agents-peers 0.1.0-alpha.0

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.
@@ -0,0 +1,526 @@
1
+ import { CardSyncedDirectory, MemoryAgentDirectory, } from "./directory.js";
2
+ import { createMemoryPeerRepo } from "./repo.js";
3
+ import { budgetExceeded, UsageDiff } from "./stats.js";
4
+ import { buildTeamTool } from "./team-tool.js";
5
+ import { buildMemberTool } from "./member-tool.js";
6
+ /** Marks a peer message on the wire and in the recipient's journal. `deliveryId` is the reconcile
7
+ * anchor — a restart matches it against the recipient's log to tell delivered from lost. */
8
+ export const PEER_SOURCE = "peer";
9
+ let messageCounter = 0;
10
+ function newMessageId() {
11
+ messageCounter += 1;
12
+ return `pm_${Date.now().toString(36)}_${messageCounter.toString(36)}`;
13
+ }
14
+ function addressTail(address) {
15
+ const index = address.lastIndexOf("/");
16
+ return index < 0 ? address : address.slice(index + 1);
17
+ }
18
+ /**
19
+ * A team label is `team:<creator>:<name>`.
20
+ *
21
+ * The creator segment is stamped by us, never by the model, and that is the whole security
22
+ * argument: two agents that both name a team "migration" get two different labels, so neither
23
+ * can join the other's team by guessing its name. Teams stay FLAT — the segments make a label
24
+ * unique, they do not nest one team inside another.
25
+ */
26
+ function teamLabel(creatorId, name) {
27
+ return `team:${creatorId}:${name}`;
28
+ }
29
+ function ownedTeamLabels(ref) {
30
+ const prefix = `team:${ref.agentId}:`;
31
+ return (ref.labels ?? []).filter((label) => label.startsWith(prefix));
32
+ }
33
+ function invalidName(kind, name) {
34
+ if (name.length === 0 || name.length > 48)
35
+ return `${kind} name must be 1-48 characters.`;
36
+ if (!/^[a-zA-Z0-9_-]+$/.test(name))
37
+ return `${kind} name "${name}" may only contain letters, digits, "_" and "-".`;
38
+ return undefined;
39
+ }
40
+ export class PeerNetwork {
41
+ directory;
42
+ mailbox;
43
+ visibility;
44
+ limits;
45
+ spawnable;
46
+ /** Any session's actions will do — `openSession` reaches every session on the harness. */
47
+ actions;
48
+ /** Per-turn outbound counters, keyed by "<agentId>:<turnId>" so they self-expire. */
49
+ outbound = new Map();
50
+ budget;
51
+ statistics;
52
+ usageDiff = new UsageDiff();
53
+ /**
54
+ * Roster seeding from the card store, kicked off at construction. Every public entry point
55
+ * awaits it, so a durable repo's parked teammates are discoverable before the first route —
56
+ * without forcing hosts through a separate init call.
57
+ */
58
+ ready;
59
+ /** Deliveries handed to a recipient that was not running — each one starts a turn. Consumed
60
+ * when the message surfaces in the recipient's conversation. */
61
+ wokenBy = new Set();
62
+ constructor(options) {
63
+ const repo = options.repo ?? createMemoryPeerRepo();
64
+ const directory = new CardSyncedDirectory(new MemoryAgentDirectory(), repo.cards);
65
+ this.directory = directory;
66
+ this.mailbox = repo.mailbox;
67
+ this.statistics = repo.stats;
68
+ this.visibility = options.visibility;
69
+ this.limits = options.limits;
70
+ this.budget = options.budget;
71
+ this.spawnable = options.spawnable;
72
+ this.ready = directory.seed().catch(() => undefined);
73
+ }
74
+ /** What the fleet has spent, per agent and in total. The view a host needs to notice a runaway
75
+ * team before the bill does. */
76
+ async stats() {
77
+ await this.ready;
78
+ return this.statistics.snapshot();
79
+ }
80
+ /** Idempotent: the first session to mount wins — any session's actions reach every session
81
+ * (`openSession` spans the harness). Mounts also re-arm this on every observed event, which
82
+ * is what re-connects a REPLACEMENT instance (whose own `actions` starts empty) without any
83
+ * session being touched. */
84
+ attachActions(actions) {
85
+ this.actions ??= actions;
86
+ }
87
+ /** Roster lookup in method form — field access (`.directory`) does not survive a service
88
+ * handle, which exposes methods only. Host-side code may keep using `.directory`. */
89
+ async getAgent(agentId) {
90
+ await this.ready;
91
+ return this.directory.get(agentId);
92
+ }
93
+ /** Mark an agent parked (its session closed / its member session ended). */
94
+ async parkAgent(agentId) {
95
+ await this.ready;
96
+ await this.directory.setStatus(agentId, "parked");
97
+ }
98
+ /** Member identity registration at session start — what `mountHub` calls from `session.start`. */
99
+ async registerMemberSession(options, sessionId) {
100
+ await this.ready;
101
+ await this.directory.register({
102
+ agentId: options.name,
103
+ type: options.type ?? "member",
104
+ kind: "session",
105
+ sessionId,
106
+ address: "main",
107
+ status: "idle",
108
+ labels: [options.team],
109
+ ...(options.description !== undefined ? { description: options.description } : {}),
110
+ updatedAt: Date.now(),
111
+ });
112
+ }
113
+ /**
114
+ * Detach from the harness and drop in-memory coordination state. This is the replace/unload
115
+ * dispose hook: calls already in flight (leased on this instance) finish normally; later
116
+ * deliveries fail with the existing "unreachable" receipt. The repo behind cards/mailbox/stats
117
+ * is HOST-owned and deliberately left open — a successor instance re-seeds from it.
118
+ */
119
+ async close() {
120
+ await this.ready;
121
+ this.actions = undefined;
122
+ this.outbound.clear();
123
+ this.wokenBy.clear();
124
+ }
125
+ /**
126
+ * Refresh the STATUS of rows explicit acts created — nothing more. Identity never comes from
127
+ * here: members are registered at spawn (or member session start), creators at `Team create`.
128
+ * A frame the roster does not know (every ordinary delegation) falls through `setStatus`'s
129
+ * no-op, which is exactly the point.
130
+ */
131
+ observe(event, rosterId) {
132
+ const address = event.address;
133
+ if (address === undefined || rosterId === undefined)
134
+ return;
135
+ const isRoot = address === "main";
136
+ const key = isRoot ? rosterId : addressTail(address);
137
+ if (event.type === "agent.started") {
138
+ void this.directory.setStatus(key, "running");
139
+ return;
140
+ }
141
+ if (event.type === "agent.ended") {
142
+ // A subagent creator that finished stays on the roster as a record — `parked`, continuable
143
+ // only by its parent; a root agent going quiet is just `idle`.
144
+ void this.directory.setStatus(key, isRoot ? "idle" : "parked");
145
+ return;
146
+ }
147
+ if (event.type === "message.appended") {
148
+ // A peer message reached the recipient's conversation — NOW it is safe to clear the ledger.
149
+ //
150
+ // Settling at delivery time instead would defeat the point: `steerTo` only puts the message
151
+ // on an in-memory queue, so a crash before the recipient consumed it would lose the message
152
+ // AND its ledger entry. Waiting for this event is what makes the write-ahead real.
153
+ const origin = event.origin;
154
+ if (origin?.kind !== "external" || origin.source !== PEER_SOURCE)
155
+ return;
156
+ const woken = this.wokenBy.delete(origin.deliveryId);
157
+ void this.statistics.add(key, { messagesReceived: 1, wakes: woken ? 1 : 0 }).catch(() => undefined);
158
+ void this.mailbox.settle(key, origin.deliveryId).catch(() => undefined);
159
+ return;
160
+ }
161
+ if (event.type === "usage.updated") {
162
+ // Attributed to the SESSION's roster identity: a delegation's spend is its session's spend.
163
+ // The delta MUST be taken synchronously — `UsageDiff` relies on seeing running totals in
164
+ // event order; only the resulting increment is handed to the (possibly async) store.
165
+ const delta = this.usageDiff.delta(rosterId, event.usage);
166
+ void this.statistics.add(rosterId, delta).catch(() => undefined);
167
+ }
168
+ }
169
+ async list(filter) {
170
+ await this.ready;
171
+ return this.directory.list(filter);
172
+ }
173
+ /** Peers `selfId` may see, excluding itself. Backs the member `Hub list`. */
174
+ async visiblePeers(selfId) {
175
+ await this.ready;
176
+ const self = await this.directory.get(selfId);
177
+ if (self === undefined)
178
+ return [];
179
+ const all = await this.directory.list();
180
+ return all.filter((ref) => ref.agentId !== selfId && this.visibility(self, ref));
181
+ }
182
+ /** Members of teams `selfId` created. Backs `Team list` and `Team send`'s scope. */
183
+ async ownedMembers(selfId) {
184
+ await this.ready;
185
+ const prefix = `team:${selfId}:`;
186
+ const all = await this.directory.list();
187
+ return all.filter((ref) => ref.agentId !== selfId && (ref.labels ?? []).some((label) => label.startsWith(prefix)));
188
+ }
189
+ /**
190
+ * Form a team. The one act that puts a CREATOR on the roster — its identity and its team are
191
+ * produced together, which is why "holding the Team tool but unknown to the roster" is not a
192
+ * reachable state for anything that matters: every op that needs an identity either creates it
193
+ * (here) or requires a team to exist (everywhere else).
194
+ *
195
+ * Membership cannot be extended sideways: the only agents that ever wear the label are ones
196
+ * `Team spawn` creates under it. So a team can never widen what its creator could already
197
+ * reach — no agent can pull a stranger in, or push itself into someone else's team.
198
+ */
199
+ async createTeam(caller, name) {
200
+ const invalid = invalidName("Team", name);
201
+ if (invalid !== undefined)
202
+ return { error: invalid };
203
+ await this.ready;
204
+ const label = teamLabel(caller.agentId, name);
205
+ const existing = await this.directory.get(caller.agentId);
206
+ const labels = existing?.labels ?? [];
207
+ if (!labels.includes(label)) {
208
+ const isRoot = caller.address === "main";
209
+ // Awaited: the label is the one piece of team state that exists nowhere else, so the card
210
+ // write must land before the caller is told the team exists.
211
+ await this.directory.register({
212
+ agentId: caller.agentId,
213
+ type: existing?.type ?? caller.type ?? (isRoot ? "session" : "subagent"),
214
+ kind: isRoot ? "session" : "subagent",
215
+ sessionId: caller.sessionId,
216
+ address: caller.address,
217
+ status: "running",
218
+ labels: [...labels, label],
219
+ ...(caller.description !== undefined ? { description: caller.description } : {}),
220
+ updatedAt: Date.now(),
221
+ });
222
+ }
223
+ return { label };
224
+ }
225
+ /**
226
+ * Create one teammate: resolve the host's factory for `type`, let it build the session (which
227
+ * tags it `params: { peers: { member } }`, so identity + Hub arrive with birth), then hand the initial
228
+ * prompt over as the first peer message — the write-ahead ledger covers the crash window
229
+ * between session creation and the prompt entering its conversation.
230
+ */
231
+ async spawnTeammate(creatorId, args) {
232
+ await this.ready;
233
+ const factory = this.spawnable?.[args.type];
234
+ if (factory === undefined) {
235
+ const available = Object.keys(this.spawnable ?? {});
236
+ return { error: available.length === 0 ? "No teammate types are configured; spawning is unavailable here." : `Unknown teammate type "${args.type}". Available: ${available.join(", ")}` };
237
+ }
238
+ const creator = await this.directory.get(creatorId);
239
+ const owned = creator === undefined ? [] : ownedTeamLabels(creator);
240
+ if (creator === undefined || owned.length === 0) {
241
+ return { error: `Create a team first (Team create), then spawn into it.` };
242
+ }
243
+ let label;
244
+ if (args.team !== undefined) {
245
+ label = teamLabel(creatorId, args.team);
246
+ if (!owned.includes(label))
247
+ return { error: `You have no team named "${args.team}".` };
248
+ }
249
+ else if (owned.length === 1) {
250
+ label = owned[0];
251
+ }
252
+ else {
253
+ return { error: `You own several teams — say which: team must be one of ${owned.map((l) => l.slice(`team:${creatorId}:`.length)).join(", ")}.` };
254
+ }
255
+ const invalid = invalidName("Agent", args.name);
256
+ if (invalid !== undefined)
257
+ return { error: invalid };
258
+ if ((await this.directory.get(args.name)) !== undefined) {
259
+ return { error: `The name "${args.name}" is already taken on the roster. Pick another.` };
260
+ }
261
+ const overspent = budgetExceeded(await this.statistics.snapshot(), this.budget);
262
+ if (overspent !== undefined)
263
+ return { error: `${overspent}. Spawning is paused.` };
264
+ let session;
265
+ try {
266
+ session = await factory({ name: args.name, type: args.type, team: label, creatorId });
267
+ }
268
+ catch (error) {
269
+ return { error: `Could not create teammate "${args.name}": ${error instanceof Error ? error.message : String(error)}` };
270
+ }
271
+ // The member was registered at its session start (params.member → Hub); this merge
272
+ // is belt-and-braces against a factory that resolved before that handler settled.
273
+ await this.directory.register({
274
+ agentId: args.name,
275
+ type: args.type,
276
+ kind: "session",
277
+ sessionId: session.id,
278
+ address: "main",
279
+ status: "idle",
280
+ labels: [label],
281
+ updatedAt: Date.now(),
282
+ });
283
+ const to = await this.directory.get(args.name);
284
+ if (to === undefined)
285
+ return { error: `Teammate "${args.name}" was created but never appeared on the roster — did the spawn factory set params.member?` };
286
+ const receipt = await this.dispatch(creator, to, args.prompt, {});
287
+ return { name: args.name, sessionId: session.id, team: label, receipt };
288
+ }
289
+ /** Charge one outbound message against the sender's per-turn budget. */
290
+ overBudget(selfId, turnId) {
291
+ const limit = this.limits?.maxOutboundPerTurn;
292
+ if (limit === undefined)
293
+ return false;
294
+ const key = `${selfId}:${turnId}`;
295
+ const used = this.outbound.get(key) ?? 0;
296
+ if (used >= limit)
297
+ return true;
298
+ this.outbound.set(key, used + 1);
299
+ return false;
300
+ }
301
+ /**
302
+ * MEMBER send: the general peer path, gated by the `visibility` policy. The single enforcement
303
+ * point for the boundary — a member may only address a peer its policy admits.
304
+ */
305
+ async route(from, toId, content, opts = {}) {
306
+ await this.ready;
307
+ const fail = (reason, detail) => ({ messageId: newMessageId(), to: toId, status: "failed", reason, detail });
308
+ if (toId === from.agentId)
309
+ return fail("self_send", "Cannot send a message to yourself.");
310
+ const to = await this.directory.get(toId);
311
+ if (to === undefined)
312
+ return fail("unknown_agent", `No agent "${toId}" is on the roster. Use Hub list; never invent an id.`);
313
+ if (!this.visibility(from, to))
314
+ return fail("not_visible", `Agent "${toId}" is not addressable from here.`);
315
+ return this.dispatch(from, to, content, opts);
316
+ }
317
+ /**
318
+ * CREATOR send: scope replaces policy — a creator reaches exactly the members wearing one of
319
+ * its own team labels, and nothing else. No visibility function is consulted.
320
+ */
321
+ async sendWithinTeam(fromId, toId, content, opts = {}) {
322
+ await this.ready;
323
+ const fail = (reason, detail) => ({ messageId: newMessageId(), to: toId, status: "failed", reason, detail });
324
+ const from = await this.directory.get(fromId);
325
+ if (from === undefined)
326
+ return fail("unknown_agent", "Create a team first (Team create).");
327
+ const to = await this.directory.get(toId);
328
+ const prefix = `team:${fromId}:`;
329
+ if (to === undefined || !(to.labels ?? []).some((label) => label.startsWith(prefix))) {
330
+ return fail("not_visible", `"${toId}" is not a member of any team you created. Team list shows your members.`);
331
+ }
332
+ return this.dispatch(from, to, content, opts);
333
+ }
334
+ /** The shared tail of every send: budget → write-ahead ledger (capacity enforced atomically
335
+ * inside) → delivery. Callers have already established WHO may talk to WHOM. */
336
+ async dispatch(from, to, content, opts) {
337
+ const messageId = newMessageId();
338
+ const fail = (reason, detail) => ({ messageId, to: to.agentId, status: "failed", reason, detail });
339
+ const overspent = budgetExceeded(await this.statistics.snapshot(), this.budget);
340
+ if (overspent !== undefined) {
341
+ // Stops peer traffic only. Agents already running finish their own work — `maxTurns` owns
342
+ // that, and cutting a run off mid-flight would strand it worse than letting it end.
343
+ return fail("quota_exceeded", `${overspent}. Peer messaging is paused; finish what you have.`);
344
+ }
345
+ const message = { messageId, from: from.agentId, to: to.agentId, content, queuedAt: Date.now(), ...(opts.replyTo !== undefined ? { replyTo: opts.replyTo } : {}) };
346
+ const { accepted } = await this.mailbox.enqueue(message, { ...(this.limits?.mailboxCapacity !== undefined ? { capacity: this.limits.mailboxCapacity } : {}) });
347
+ if (!accepted)
348
+ return fail("mailbox_full", `Agent "${to.agentId}" has too many undelivered messages.`);
349
+ return this.deliver(to, message, opts.interrupt === true);
350
+ }
351
+ /**
352
+ * Hand an already-ledgered message to its recipient. Split out from the send paths so a
353
+ * redelivery (see `reconcile`) does not re-run the checks or write a second ledger entry.
354
+ */
355
+ async deliver(to, message, interrupt) {
356
+ const { messageId, to: toId, content } = message;
357
+ const fail = (reason, detail) => ({ messageId, to: toId, status: "failed", reason, detail });
358
+ const origin = {
359
+ kind: "external",
360
+ source: PEER_SOURCE,
361
+ deliveryId: messageId,
362
+ actor: message.from,
363
+ // follow_up by default: peers interject between turns, they do not interrupt work in flight.
364
+ channel: interrupt ? "steering" : "follow_up",
365
+ ...(message.replyTo !== undefined ? { metadata: { replyTo: message.replyTo } } : {}),
366
+ };
367
+ await this.statistics.add(message.from, { messagesSent: 1 });
368
+ // Whether this delivery will start a turn: a recipient that is not currently running has to
369
+ // be woken to see it.
370
+ if (to.status !== "running")
371
+ this.wokenBy.add(messageId);
372
+ try {
373
+ if (this.actions === undefined)
374
+ return fail("unreachable", "Peer networking is not attached to a harness.");
375
+ // Reopens the session when it was closed — which is what makes a parked teammate wakeable.
376
+ const handle = await this.actions.openSession(to.sessionId);
377
+ // NOTE: no `settle` on success. The ledger entry is cleared when the recipient's
378
+ // `message.appended` shows the message actually entered its conversation (see `observe`) —
379
+ // delivery here only means it reached an in-memory queue.
380
+ if (!handle.steerTo(to.address, content, origin)) {
381
+ // The session is open but no frame is running at that address. For a member session that
382
+ // cannot happen (its root frame revives on open); it happens for a subagent CREATOR whose
383
+ // delegation finished — continuing it is its parent's call, not a message.
384
+ await this.mailbox.settle(toId, messageId);
385
+ return fail("unreachable", to.kind === "subagent"
386
+ ? `Agent "${toId}" has finished. Its parent can continue it with Agent(resume="${toId}", prompt=...); it cannot be messaged.`
387
+ : `No frame is running at "${to.address}" in session "${to.sessionId}".`);
388
+ }
389
+ }
390
+ catch (error) {
391
+ return fail("unreachable", `Could not reach session "${to.sessionId}": ${error instanceof Error ? error.message : String(error)}`);
392
+ }
393
+ return { messageId, to: toId, status: "delivered" };
394
+ }
395
+ /**
396
+ * Redeliver everything the ledger still holds. Call once on startup, after at least one session
397
+ * with the extension is attached (that is what connects the network to a harness). Recipients
398
+ * themselves need not be open: a card-seeded parked teammate is found on the roster and delivery
399
+ * reopens its session.
400
+ *
401
+ * The ledger only ever contains messages whose recipient never took them into its conversation
402
+ * (entries clear on `message.appended`), so anything left after a restart was genuinely lost in
403
+ * the crash window — no journal comparison needed to tell that apart.
404
+ *
405
+ * A message whose recipient is no longer on the roster is dropped rather than retried forever;
406
+ * `dropped` is reported so a host can log it instead of discovering the gap later.
407
+ */
408
+ async reconcile() {
409
+ await this.ready;
410
+ let redelivered = 0;
411
+ let dropped = 0;
412
+ for (const recipientId of await this.mailbox.pendingRecipients()) {
413
+ const to = await this.directory.get(recipientId);
414
+ for (const message of await this.mailbox.pending(recipientId)) {
415
+ if (to === undefined) {
416
+ await this.mailbox.settle(recipientId, message.messageId);
417
+ dropped += 1;
418
+ continue;
419
+ }
420
+ const receipt = await this.deliver(to, message, false);
421
+ if (receipt.status === "delivered")
422
+ redelivered += 1;
423
+ else
424
+ dropped += 1;
425
+ }
426
+ }
427
+ return { redelivered, dropped };
428
+ }
429
+ /** Undelivered ledger entries for one agent — what was routed but never reached its
430
+ * conversation (the crash window). */
431
+ async drainInbox(agentId) {
432
+ await this.ready;
433
+ const pending = await this.mailbox.pending(agentId);
434
+ for (const message of pending)
435
+ await this.mailbox.settle(agentId, message.messageId);
436
+ return pending;
437
+ }
438
+ }
439
+ /** The extension id, and so the service name its `create` half's network is registered under.
440
+ * A session's `setup` reaches the network as `ctx.shared`; the host reaches it with
441
+ * `harness.services.handle<PeerNetworkHandle>(PEERS_SERVICE)`. */
442
+ export const PEERS_SERVICE = "peers";
443
+ /** Mount the creator side (the `Team` tool) onto a session — what `peers().setup` does for an
444
+ * ordinary session. */
445
+ export function mountTeam(network, api, options = {}) {
446
+ let sessionId;
447
+ network.attachActions(api.actions);
448
+ api.on("session.start", (event) => {
449
+ sessionId = event.sessionId;
450
+ });
451
+ api.on("session.end", () => {
452
+ if (sessionId !== undefined)
453
+ void network.parkAgent(sessionId);
454
+ });
455
+ api.onEvent((event) => {
456
+ // Re-arm on every event: through a handle this lands on the CURRENT instance, so a
457
+ // replacement network regains a route back into the harness without any session redoing
458
+ // setup. Idempotent and cheap on the live instance.
459
+ network.attachActions(api.actions);
460
+ network.observe(event, sessionId);
461
+ });
462
+ api.registerTool(buildTeamTool(network, () => sessionId, options));
463
+ }
464
+ /** Mount the member side (the `Hub` tool + identity registration) onto a session — what
465
+ * `peers().setup` does for a teammate. */
466
+ export function mountHub(network, api, options) {
467
+ network.attachActions(api.actions);
468
+ api.on("session.start", (event) => {
469
+ void network.registerMemberSession(options, event.sessionId);
470
+ });
471
+ api.on("session.end", () => {
472
+ void network.parkAgent(options.name);
473
+ });
474
+ api.onEvent((event) => {
475
+ network.attachActions(api.actions);
476
+ network.observe(event, options.name);
477
+ });
478
+ api.registerTool(buildMemberTool(network, options.name));
479
+ }
480
+ export function createPeerNetwork(options) {
481
+ return new PeerNetwork(options);
482
+ }
483
+ /**
484
+ * The peers extension — ONE definition, both halves:
485
+ *
486
+ * - `create` (the process-shared half) runs once per harness and returns the shared
487
+ * `PeerNetwork`, which the framework registers as the `peers` service. Its spawn factory
488
+ * creates each teammate through `host.createSession`, tagging it `params: { peers: { member } }`.
489
+ * - `setup` (the per-session half) runs on every session: a teammate (has `params.member`) gets
490
+ * the member `Hub`; every other session gets the creator `Team`. It reaches the network only
491
+ * through the `shared` handle, so a reload swaps the network under live sessions.
492
+ *
493
+ * Server: `createHarness({ extensions: [peers({...})] })`. Desktop: a bundle in `extensionDir`
494
+ * whose default export is `peers({...})`. Same definition, only the channel differs.
495
+ */
496
+ export function peers(options) {
497
+ const { teammates, team = {}, repo, ...networkOptions } = options;
498
+ return {
499
+ id: PEERS_SERVICE,
500
+ create(host) {
501
+ const resolvedRepo = typeof repo === "function" ? repo(host) : repo;
502
+ const spawnable = teammates === undefined
503
+ ? undefined
504
+ : Object.fromEntries(Object.entries(teammates).map(([type, sessionOptions]) => [
505
+ type,
506
+ async (request) => {
507
+ const base = typeof sessionOptions === "function" ? await sessionOptions(request) : sessionOptions;
508
+ const member = { name: request.name, team: request.team, type: request.type };
509
+ return host.createSession({ ...base, params: { ...(base.params ?? {}), [PEERS_SERVICE]: { member } } });
510
+ },
511
+ ]));
512
+ return createPeerNetwork({
513
+ ...networkOptions,
514
+ ...(resolvedRepo !== undefined ? { repo: resolvedRepo } : {}),
515
+ ...(spawnable !== undefined ? { spawnable } : {}),
516
+ });
517
+ },
518
+ setup(api, { shared: network, params }) {
519
+ if (params?.member !== undefined)
520
+ mountHub(network, api, params.member);
521
+ else
522
+ mountTeam(network, api, team);
523
+ },
524
+ };
525
+ }
526
+ //# sourceMappingURL=network.js.map
package/dist/repo.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The one injection seam for peer persistence: the host hands `PeerNetwork` a repo, the repo
3
+ * decides where things live (memory, files, PG, Redis, …).
4
+ *
5
+ * Why an OPERATION-level interface and not key/value: with get/put the caller must read-modify-
6
+ * write, and no backend can make that safe. Defined by intent — `enqueue`, `settle`, `put`,
7
+ * `add` — every backend can make each single call atomic with its own primitives (a transaction,
8
+ * a list op, an increment). The contract, stated once here and relied on everywhere: **each
9
+ * method is atomic in the backend; no caller ever does a cross-call read-modify-write.** That is
10
+ * why sharing one repo between processes cannot corrupt it.
11
+ *
12
+ * What each facet persists is exactly what only peers knows:
13
+ * - `mailbox` — messages in flight. The only facet that protects CORRECTNESS: a crash between
14
+ * routing and consumption loses the message without it.
15
+ * - `cards` — team labels + the type/description card. Invented at runtime, recorded nowhere
16
+ * else; without them a restart leaves parked teammates undiscoverable, hence unwakeable.
17
+ * - `stats` — fleet accounting. Memory by default, deliberately: persisting the budget ledger
18
+ * forces reset semantics only the host can decide (see `MemoryPeerStatsStore`).
19
+ */
20
+ import { type PeerCardStore } from "./directory.ts";
21
+ import { type PeerMailbox } from "./mailbox.ts";
22
+ import { type PeerStatsStore } from "./stats.ts";
23
+ export interface PeerRepo {
24
+ readonly mailbox: PeerMailbox;
25
+ readonly cards: PeerCardStore;
26
+ readonly stats: PeerStatsStore;
27
+ }
28
+ /** Everything in memory: routes fine in one process, remembers nothing across a restart. */
29
+ export declare function createMemoryPeerRepo(): PeerRepo;
30
+ //# sourceMappingURL=repo.d.ts.map
package/dist/repo.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The one injection seam for peer persistence: the host hands `PeerNetwork` a repo, the repo
3
+ * decides where things live (memory, files, PG, Redis, …).
4
+ *
5
+ * Why an OPERATION-level interface and not key/value: with get/put the caller must read-modify-
6
+ * write, and no backend can make that safe. Defined by intent — `enqueue`, `settle`, `put`,
7
+ * `add` — every backend can make each single call atomic with its own primitives (a transaction,
8
+ * a list op, an increment). The contract, stated once here and relied on everywhere: **each
9
+ * method is atomic in the backend; no caller ever does a cross-call read-modify-write.** That is
10
+ * why sharing one repo between processes cannot corrupt it.
11
+ *
12
+ * What each facet persists is exactly what only peers knows:
13
+ * - `mailbox` — messages in flight. The only facet that protects CORRECTNESS: a crash between
14
+ * routing and consumption loses the message without it.
15
+ * - `cards` — team labels + the type/description card. Invented at runtime, recorded nowhere
16
+ * else; without them a restart leaves parked teammates undiscoverable, hence unwakeable.
17
+ * - `stats` — fleet accounting. Memory by default, deliberately: persisting the budget ledger
18
+ * forces reset semantics only the host can decide (see `MemoryPeerStatsStore`).
19
+ */
20
+ import { MemoryPeerCardStore } from "./directory.js";
21
+ import { MemoryPeerMailbox } from "./mailbox.js";
22
+ import { MemoryPeerStatsStore } from "./stats.js";
23
+ /** Everything in memory: routes fine in one process, remembers nothing across a restart. */
24
+ export function createMemoryPeerRepo() {
25
+ return { mailbox: new MemoryPeerMailbox(), cards: new MemoryPeerCardStore(), stats: new MemoryPeerStatsStore() };
26
+ }
27
+ //# sourceMappingURL=repo.js.map
@@ -0,0 +1,80 @@
1
+ /**
2
+ * What the fleet is costing, and the ceiling on it.
3
+ *
4
+ * Two problems this answers, which are really one:
5
+ *
6
+ * - **Observability.** A host running a team of agents otherwise has no aggregate view — each
7
+ * session reports its own usage and nobody sums them. Peer coordination makes that worse: one
8
+ * message can wake an idle teammate and start a turn, so cost accrues without anyone prompting.
9
+ * - **A ceiling.** `maxTurns` bounds a single agent. It cannot stop ten agents each burning their
10
+ * own budget, and it cannot see that they kept waking each other to do it.
11
+ *
12
+ * Deliberately NOT a cap on conversation length: a long peer exchange is normal collaboration.
13
+ * What is bounded is the total spend, which is the thing that actually hurts.
14
+ *
15
+ * SPLIT: turning `usage.updated` running totals into increments (`UsageDiff`) stays in the
16
+ * extension — an agent's events only ever arrive in the process hosting it, so per-process
17
+ * diffing is correct by construction. The store only ever receives deltas, and `add` is an atomic
18
+ * accumulate — every backend has a native primitive for that (memory `+=`, SQL `SET x = x + ?`,
19
+ * Redis `HINCRBY`), so no backend ever needs read-modify-write.
20
+ */
21
+ import type { Usage } from "operon-agents-core";
22
+ export interface PeerCounters {
23
+ readonly messagesSent: number;
24
+ readonly messagesReceived: number;
25
+ /** Deliveries that started a turn on an idle or parked recipient — the expensive kind. */
26
+ readonly wakes: number;
27
+ readonly inputTokens: number;
28
+ readonly outputTokens: number;
29
+ readonly totalTokens: number;
30
+ readonly cost: number;
31
+ }
32
+ export interface PeerAgentStats extends PeerCounters {
33
+ readonly agentId: string;
34
+ }
35
+ export interface PeerFleetStats {
36
+ readonly agents: readonly PeerAgentStats[];
37
+ readonly totals: PeerCounters;
38
+ }
39
+ /** Spend ceiling for the whole network. Reaching it stops PEER traffic — it cannot and does not
40
+ * stop an agent already running from finishing its own work. */
41
+ export interface PeerBudget {
42
+ readonly maxTotalTokens?: number;
43
+ readonly maxTotalCost?: number;
44
+ /** Deliveries that start a turn on an idle/parked recipient. The sharpest lever: each one is a
45
+ * fresh LLM call nobody explicitly asked for. */
46
+ readonly maxWakes?: number;
47
+ }
48
+ export interface PeerStatsStore {
49
+ /** Atomic accumulate. Missing fields mean +0. */
50
+ add(agentId: string, delta: Partial<PeerCounters>): Promise<void>;
51
+ snapshot(): Promise<PeerFleetStats>;
52
+ }
53
+ export declare function emptyCounters(): PeerCounters;
54
+ /**
55
+ * The default: per-process counters, gone on restart — and that is the right default, because a
56
+ * persisted budget forces a question this package cannot answer for the host: WHEN does the
57
+ * budget reset? (A durable ledger that never resets bricks the network on its first exhaustion —
58
+ * every restart wakes up already over quota.) A host that wants a fleet ledger spanning restarts
59
+ * implements this facet on its own store and owns the reset semantics with it.
60
+ */
61
+ export declare class MemoryPeerStatsStore implements PeerStatsStore {
62
+ private readonly perAgent;
63
+ add(agentId: string, delta: Partial<PeerCounters>): Promise<void>;
64
+ snapshot(): Promise<PeerFleetStats>;
65
+ }
66
+ /**
67
+ * Turns `usage.updated` events into increments. The event carries the reporting run's RUNNING
68
+ * TOTAL, so summing raw events would count the same tokens many times over — we diff against the
69
+ * last value seen.
70
+ *
71
+ * Keyed by AGENT, not by frame address: every session's root frame is `main`, so an address-keyed
72
+ * map would have one session's totals subtracted from another's.
73
+ */
74
+ export declare class UsageDiff {
75
+ private readonly lastUsage;
76
+ delta(agentId: string, usage: Usage): Partial<PeerCounters>;
77
+ }
78
+ /** The budget line this snapshot has crossed, if any. */
79
+ export declare function budgetExceeded(stats: PeerFleetStats, budget: PeerBudget | undefined): string | undefined;
80
+ //# sourceMappingURL=stats.d.ts.map