operon-agents-peers 0.1.0-alpha.2 → 0.1.0-alpha.3

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/README.md CHANGED
@@ -53,10 +53,12 @@ Team(op: "spawn", type: "coder", name: "dba", prompt: "…")
53
53
  Team(op: "spawn", type: "coder", name: "reviewer", prompt: "…")
54
54
  ```
55
55
 
56
- `dba` and `reviewer` are independent sessions. They start on their prompts immediately, message each other and the lead directly over `Hub`, and report back by message — which wakes the lead in a later turn. The lead steers them with `Team send`, whose reach is **scope, not policy**: a creator reaches exactly the members wearing one of its own team labels, and nothing else.
56
+ `dba` and `reviewer` are independent sessions. They start on their prompts immediately, message each other by name and the lead as `lead` over `Hub`, and report back by message — which wakes the lead in a later turn. The lead steers them with `Team send`, whose reach is **scope, not policy**: a creator reaches exactly the members wearing one of its own team labels, and nothing else.
57
57
 
58
58
  The team label is `team:<creator>:<name>`. That creator segment is stamped by the network, never by the model, so two agents that both name a team `migration` get two different teams — and membership can never widen past what its creator spawned.
59
59
 
60
+ A teammate's name is unique **within its team**, not across the roster: its roster id is `<team label>/<name>`, so two teams can each have a `dba`. `Team send` and `Hub send` take the short name (`Team send` adds `team` when the creator has the same name in several teams; a member sees its creator as `lead`, which is reserved). Roster rows carry the `id` for exact addressing whenever it differs from the name.
61
+
60
62
  The `create` half runs synchronously inside `createHarness`, so the service exists before the first session; `harness.close()` takes it down again (unregister → `close()`). The host reaches the network the same way sessions do — `harness.services.handle<PeerNetworkHandle>(PEERS_SERVICE)` — for `list()`, `stats()`, `reconcile()`.
61
63
 
62
64
  ### Desktop: load it from a file
@@ -105,7 +107,7 @@ const bob = await harness.createSession({
105
107
 
106
108
  The param persists with the session, so a `resumeSession` brings `alice` back as a member without repeating it.
107
109
 
108
- **State a `type` and `description`.** They are what makes the roster useful: without them every teammate lists as an anonymous `member` and a model has no way to tell who to ask. The `name` is the agent's peer identity — teammates address it by name, and it must be unique on the roster.
110
+ **State a `type` and `description`.** They are what makes the roster useful: without them every teammate lists as an anonymous `member` and a model has no way to tell who to ask. The `name` is what teammates address it by — unique within `team` (its roster id is `<team>/<name>`).
109
111
 
110
112
  ## What it rests on
111
113
 
@@ -129,7 +131,7 @@ The param persists with the session, so a `resumeSession` brings `alice` back as
129
131
 
130
132
  **`send` never blocks.** There is no `wait` op, deliberately: a teammate answers by being woken, background work already has `BackgroundOutput(block)`, and a blocking op would introduce the one thing this design otherwise has none of — a way for two agents to deadlock.
131
133
 
132
- **Failures are explicit.** A `failed` receipt names its cause (`unknown_agent`, `not_visible`, `mailbox_full`, `quota_exceeded`, `unreachable`) so a model can tell "wrong name" from "you sent too much" and stop retrying what cannot succeed. A full mailbox rejects rather than dropping the oldest message.
134
+ **Failures are explicit.** A `failed` receipt names its cause (`unknown_agent`, `ambiguous`, `not_visible`, `mailbox_full`, `quota_exceeded`, `unreachable`) so a model can tell "wrong name" from "you sent too much" and stop retrying what cannot succeed. A full mailbox rejects rather than dropping the oldest message.
133
135
 
134
136
  ## Permissions
135
137
 
@@ -36,6 +36,12 @@ export type AgentRefKind = "session" | "subagent";
36
36
  export type AgentRefStatus = "running" | "idle" | "parked" | "error";
37
37
  export interface AgentRef {
38
38
  readonly agentId: string;
39
+ /**
40
+ * The short name agents use for each other. A spawned teammate's is the name the model chose,
41
+ * unique WITHIN ITS TEAM (its `agentId` is `<team label>/<name>`, which is what keeps two
42
+ * teams' "dba"s apart on one roster). Absent for creators, whose `agentId` is their session id.
43
+ */
44
+ readonly name?: string;
39
45
  readonly type: string;
40
46
  readonly kind: AgentRefKind;
41
47
  readonly sessionId: string;
@@ -77,6 +83,8 @@ export interface AgentDirectory {
77
83
  */
78
84
  export interface PeerCard {
79
85
  readonly type: string;
86
+ /** The short name (see `AgentRef.name`). */
87
+ readonly name?: string;
80
88
  readonly description?: string;
81
89
  readonly labels?: readonly string[];
82
90
  /** The session behind this agent. Spawned teammates are addressed by their NAME, which is not
package/dist/directory.js CHANGED
@@ -29,6 +29,7 @@ export function refFromCard(agentId, card) {
29
29
  sessionId: card.sessionId ?? agentId,
30
30
  address: "main",
31
31
  status: "parked",
32
+ ...(card.name !== undefined ? { name: card.name } : {}),
32
33
  ...(card.description !== undefined ? { description: card.description } : {}),
33
34
  ...(card.labels !== undefined ? { labels: card.labels } : {}),
34
35
  updatedAt: 0,
@@ -59,6 +60,7 @@ export class CardSyncedDirectory {
59
60
  await this.cards.put(merged.agentId, {
60
61
  type: merged.type,
61
62
  sessionId: merged.sessionId,
63
+ ...(merged.name !== undefined ? { name: merged.name } : {}),
62
64
  ...(merged.description !== undefined ? { description: merged.description } : {}),
63
65
  ...(merged.labels !== undefined ? { labels: merged.labels } : {}),
64
66
  });
package/dist/index.d.ts CHANGED
@@ -22,7 +22,7 @@
22
22
  * never `Team`: it is a member, not a team-former. `setup` reaches the network only through the
23
23
  * shared handle, which is what lets a reload swap the network under live sessions.
24
24
  */
25
- export { PeerNetwork, createPeerNetwork, peers, mountTeam, mountHub, PEER_SOURCE, PEERS_SERVICE } from "./network.ts";
25
+ export { PeerNetwork, createPeerNetwork, peers, mountTeam, mountHub, memberAgentId, LEAD_ALIAS, PEER_SOURCE, PEERS_SERVICE } from "./network.ts";
26
26
  export type { PeerNetworkHandle } from "./network.ts";
27
27
  export type { PeerExtensionOptions, PeerMemberOptions, PeerNetworkOptions, PeerOptions, PeerParams, PeerReceipt, TeamCaller, TeammateFactory, TeammateSessionOptions, TeammateSpawnRequest, } from "./network.ts";
28
28
  export { MemoryPeerStatsStore, UsageDiff, budgetExceeded } from "./stats.ts";
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * never `Team`: it is a member, not a team-former. `setup` reaches the network only through the
23
23
  * shared handle, which is what lets a reload swap the network under live sessions.
24
24
  */
25
- export { PeerNetwork, createPeerNetwork, peers, mountTeam, mountHub, PEER_SOURCE, PEERS_SERVICE } from "./network.js";
25
+ export { PeerNetwork, createPeerNetwork, peers, mountTeam, mountHub, memberAgentId, LEAD_ALIAS, PEER_SOURCE, PEERS_SERVICE } from "./network.js";
26
26
  export { MemoryPeerStatsStore, UsageDiff, budgetExceeded } from "./stats.js";
27
27
  export { MemoryAgentDirectory, MemoryPeerCardStore, anyOf, sameSessionVisibility, sharedLabelVisibility } from "./directory.js";
28
28
  export { MemoryPeerMailbox } from "./mailbox.js";
@@ -1,4 +1,8 @@
1
1
  import type { Tool } from "operon-agents-core";
2
- import type { PeerNetworkHandle } from "./network.ts";
3
- export declare function buildMemberTool(network: PeerNetworkHandle, selfName: string): Tool;
2
+ import { type PeerNetworkHandle } from "./network.ts";
3
+ /**
4
+ * @param selfId the member's roster id (`<team>/<name>`), what every network call takes
5
+ * @param selfName its short name, what the roster shows as `you`
6
+ */
7
+ export declare function buildMemberTool(network: PeerNetworkHandle, selfId: string, selfName?: string): Tool;
4
8
  //# sourceMappingURL=member-tool.d.ts.map
@@ -9,20 +9,26 @@
9
9
  */
10
10
  import { z } from "zod";
11
11
  import { defineTool } from "./define-tool.js";
12
+ import { LEAD_ALIAS } from "./network.js";
12
13
  const hubInput = z.discriminatedUnion("op", [
13
14
  z.object({ op: z.literal("list").describe("List the peers you can address.") }),
14
15
  z.object({
15
16
  op: z.literal("send").describe("Send a message to a peer. Returns immediately; never waits for a reply."),
16
- to: z.string().describe("Exact agent name from the roster."),
17
+ to: z.string().describe('Peer name from Hub list — a teammate\'s name, or "lead" for whoever created your team.'),
17
18
  message: z.string().describe("Plain prose. Share paths and ids, not pasted blobs."),
18
19
  replyTo: z.string().optional().describe("messageId you are answering, when this is a reply."),
19
20
  interrupt: z.boolean().optional().describe("Cut into the peer's current work instead of waiting for its turn boundary. Reserve for 'stop, you're going the wrong way'."),
20
21
  }),
21
22
  z.object({ op: z.literal("inbox").describe("Read messages routed to you that never reached your conversation.") }),
22
23
  ]);
23
- function rosterRow(ref) {
24
+ /** What a peer is called from `self`'s seat: its own name, `lead` for the creator of one of
25
+ * self's teams, otherwise its id. The `id` rides along whenever it differs, for exact addressing. */
26
+ function rosterRow(ref, self) {
27
+ const leads = (self?.labels ?? []).some((label) => label.startsWith("team:") && label.slice("team:".length, label.lastIndexOf(":")) === ref.agentId);
28
+ const name = ref.name ?? (leads ? LEAD_ALIAS : ref.agentId);
24
29
  return {
25
- name: ref.agentId,
30
+ name,
31
+ ...(name !== ref.agentId ? { id: ref.agentId } : {}),
26
32
  type: ref.type,
27
33
  status: ref.status,
28
34
  ...(ref.description !== undefined ? { description: ref.description } : {}),
@@ -32,17 +38,21 @@ function rosterRow(ref) {
32
38
  function text(body, details, isError) {
33
39
  return { content: [{ type: "text", text: body }], ...(details !== undefined ? { details } : {}), ...(isError === true ? { isError: true } : {}) };
34
40
  }
35
- export function buildMemberTool(network, selfName) {
41
+ /**
42
+ * @param selfId the member's roster id (`<team>/<name>`), what every network call takes
43
+ * @param selfName its short name, what the roster shows as `you`
44
+ */
45
+ export function buildMemberTool(network, selfId, selfName = selfId) {
36
46
  const description = [
37
47
  "Coordinate with your peers: the teammates working alongside you, and whoever created your team.",
38
48
  "",
39
- "- `list` shows who you can address, with their name and status.",
49
+ "- `list` shows who you can address, with their name and status. Your team's creator is `lead`.",
40
50
  "- `send` hands a message to one peer and returns immediately — it does NOT wait for a reply.",
41
51
  " The peer sees it at its next turn boundary and answers in its own turn.",
42
52
  "- `inbox` drains messages routed to you that never reached your conversation.",
43
53
  "",
44
54
  "Rules:",
45
- "- Address a peer by its exact name from the roster. NEVER invent a name.",
55
+ "- Address a peer by its name from the roster (`lead` for your team's creator). NEVER invent a name.",
46
56
  "- A `failed` receipt is final for that reason — do not retry the same send.",
47
57
  "- A `parked` peer is asleep, not gone: messaging one wakes it.",
48
58
  "- Plain prose only. Share paths and ids rather than pasting large blobs.",
@@ -67,19 +77,19 @@ export function buildMemberTool(network, selfName) {
67
77
  return text("Peer messaging belongs to this session's root agent; a delegation reports to its spawner instead.", { op: args.op }, true);
68
78
  }
69
79
  if (args.op === "list") {
70
- const roster = await network.visiblePeers(selfName);
71
- return text(roster.length === 0 ? "No peers are visible to you." : JSON.stringify({ you: selfName, peers: roster.map(rosterRow) }, null, 2), { op: args.op, count: roster.length });
80
+ const [roster, self] = await Promise.all([network.visiblePeers(selfId), network.getAgent(selfId)]);
81
+ return text(roster.length === 0 ? "No peers are visible to you." : JSON.stringify({ you: selfName, peers: roster.map((ref) => rosterRow(ref, self)) }, null, 2), { op: args.op, count: roster.length });
72
82
  }
73
83
  if (args.op === "inbox") {
74
- const pending = await network.drainInbox(selfName);
84
+ const pending = await network.drainInbox(selfId);
75
85
  return text(pending.length === 0
76
86
  ? "No undelivered peer messages."
77
87
  : JSON.stringify(pending.map((m) => ({ from: m.from, messageId: m.messageId, content: m.content, queuedAt: m.queuedAt })), null, 2), { op: args.op, count: pending.length });
78
88
  }
79
- const self = await network.getAgent(selfName);
89
+ const self = await network.getAgent(selfId);
80
90
  if (self === undefined)
81
91
  return text("You are not on the peer roster.", { op: args.op }, true);
82
- if (network.overBudget(selfName, ctx.turnId)) {
92
+ if (network.overBudget(selfId, ctx.turnId)) {
83
93
  return text("Outbound peer-message budget for this turn is exhausted. Continue your work; send again in a later turn.", { op: args.op, reason: "quota_exceeded" }, true);
84
94
  }
85
95
  const receipt = await network.route(self, args.to, args.message, {
package/dist/network.d.ts CHANGED
@@ -41,7 +41,7 @@ export interface PeerReceipt {
41
41
  readonly status: "delivered" | "failed";
42
42
  /** Machine-readable cause, so a model can tell "wrong id" from "you sent too much" and stop
43
43
  * retrying what cannot succeed. */
44
- readonly reason?: "unknown_agent" | "not_visible" | "self_send" | "quota_exceeded" | "mailbox_full" | "unreachable";
44
+ readonly reason?: "unknown_agent" | "ambiguous" | "not_visible" | "self_send" | "quota_exceeded" | "mailbox_full" | "unreachable";
45
45
  readonly detail?: string;
46
46
  }
47
47
  /** What `Team spawn` hands a teammate factory. The `peers()` extension's own factory creates the
@@ -89,8 +89,9 @@ export interface PeerExtensionOptions {
89
89
  /** One line on what this agent is for. Shown on the roster next to `type`. */
90
90
  readonly description?: string;
91
91
  }
92
- /** Options for the member-side extension. `name` is the agent's peer identity (what teammates
93
- * address), `team` the full label it belongs to. A host can also attach this directly to
92
+ /** Options for the member-side extension. `name` is the agent's short name (what teammates
93
+ * address it by — unique within `team`, not across the roster), `team` the full label it
94
+ * belongs to; its roster id is `<team>/<name>`. A host can also attach this directly to
94
95
  * pre-arrange a standing team without any model-driven spawn. */
95
96
  export interface PeerMemberOptions {
96
97
  readonly name: string;
@@ -100,6 +101,14 @@ export interface PeerMemberOptions {
100
101
  readonly type?: string;
101
102
  readonly description?: string;
102
103
  }
104
+ /**
105
+ * A member's roster id: the team label plus its short name. Names are unique WITHIN a team, so
106
+ * the label is what keeps two teams' "dba"s apart — and the `/` cannot collide with a session
107
+ * id or a label (a team name admits neither `/` nor `:`).
108
+ */
109
+ export declare function memberAgentId(team: string, name: string): string;
110
+ /** What a member calls the creator of its team in `Hub send`. Reserved: no teammate may take it. */
111
+ export declare const LEAD_ALIAS = "lead";
103
112
  /** Who is calling a Team op: resolved per call from the frame address, because the Team tool is
104
113
  * shared by every frame of its session — the root agent IS the session for addressing purposes,
105
114
  * a subagent frame is its own (memory-only) identity. */
@@ -195,12 +204,33 @@ export declare class PeerNetwork {
195
204
  readonly team?: string;
196
205
  }): Promise<{
197
206
  readonly name: string;
207
+ readonly agentId: string;
198
208
  readonly sessionId: string;
199
209
  readonly team: string;
200
210
  readonly receipt: PeerReceipt;
201
211
  } | {
202
212
  readonly error: string;
203
213
  }>;
214
+ /**
215
+ * Tear a team down: every member leaves the roster (their undelivered mail is dropped), and the
216
+ * creator sheds the label — leaving the roster too once it owns no team. Returns the members'
217
+ * rows so the host can close their sessions; the roster never owned those.
218
+ */
219
+ disbandTeam(label: string): Promise<{
220
+ readonly members: readonly AgentRef[];
221
+ readonly creatorId: string | undefined;
222
+ }>;
223
+ /**
224
+ * What a MEMBER means by `to`: an exact roster id first; then `lead` for the creator of a team
225
+ * it belongs to; then a teammate's short name within its own teams. A short name that matches
226
+ * in several of its teams is refused rather than guessed.
227
+ */
228
+ private resolvePeer;
229
+ /**
230
+ * What a CREATOR means by `to`: an exact roster id, or a member's short name — qualified by
231
+ * `team` when the creator owns several and the name is used in more than one.
232
+ */
233
+ private resolveMember;
204
234
  /** Charge one outbound message against the sender's per-turn budget. */
205
235
  overBudget(selfId: string, turnId: string): boolean;
206
236
  /**
@@ -218,6 +248,7 @@ export declare class PeerNetwork {
218
248
  sendWithinTeam(fromId: string, toId: string, content: string, opts?: {
219
249
  readonly replyTo?: string;
220
250
  readonly interrupt?: boolean;
251
+ readonly team?: string;
221
252
  }): Promise<PeerReceipt>;
222
253
  /** The shared tail of every send: budget → write-ahead ledger (capacity enforced atomically
223
254
  * inside) → delivery. Callers have already established WHO may talk to WHOM. */
@@ -254,7 +285,7 @@ export declare class PeerNetwork {
254
285
  * nothing here is a field (`.directory` stays host-side). Methods must not return objects
255
286
  * that carry the instance (the one leak a handle cannot stop).
256
287
  */
257
- export type PeerNetworkHandle = Pick<PeerNetwork, "attachActions" | "observe" | "parkAgent" | "registerMemberSession" | "getAgent" | "list" | "visiblePeers" | "ownedMembers" | "createTeam" | "spawnTeammate" | "overBudget" | "route" | "sendWithinTeam" | "drainInbox" | "stats" | "reconcile">;
288
+ export type PeerNetworkHandle = Pick<PeerNetwork, "attachActions" | "observe" | "parkAgent" | "registerMemberSession" | "getAgent" | "list" | "visiblePeers" | "ownedMembers" | "createTeam" | "spawnTeammate" | "disbandTeam" | "overBudget" | "route" | "sendWithinTeam" | "drainInbox" | "stats" | "reconcile">;
258
289
  /** The extension id, and so the service name its `create` half's network is registered under.
259
290
  * A session's `setup` reaches the network as `ctx.shared`; the host reaches it with
260
291
  * `harness.services.handle<PeerNetworkHandle>(PEERS_SERVICE)`. */
package/dist/network.js CHANGED
@@ -30,6 +30,39 @@ function ownedTeamLabels(ref) {
30
30
  const prefix = `team:${ref.agentId}:`;
31
31
  return (ref.labels ?? []).filter((label) => label.startsWith(prefix));
32
32
  }
33
+ /** The labels on `ref` that `creatorId` owns. */
34
+ function ownedLabelsOf(creatorId, ref) {
35
+ const prefix = `team:${creatorId}:`;
36
+ return (ref.labels ?? []).filter((label) => label.startsWith(prefix));
37
+ }
38
+ /**
39
+ * A member's roster id: the team label plus its short name. Names are unique WITHIN a team, so
40
+ * the label is what keeps two teams' "dba"s apart — and the `/` cannot collide with a session
41
+ * id or a label (a team name admits neither `/` nor `:`).
42
+ */
43
+ export function memberAgentId(team, name) {
44
+ return `${team}/${name}`;
45
+ }
46
+ /** The creator segment of a `team:<creator>:<name>` label; `undefined` for host-arranged labels
47
+ * that do not follow the convention. The name is the LAST segment (it admits no `:`), so a
48
+ * creator id containing `:` is safe. */
49
+ function creatorOfLabel(label) {
50
+ if (!label.startsWith("team:"))
51
+ return undefined;
52
+ const cut = label.lastIndexOf(":");
53
+ return cut <= "team:".length ? undefined : label.slice("team:".length, cut);
54
+ }
55
+ /** The short name `from` shows up as in `to`'s conversation: its own name when it has one, and
56
+ * `lead` when it is the creator of a team `to` belongs to — the same word `Hub send` accepts
57
+ * back, so a member can reply to whatever addressed it without ever seeing a session id. */
58
+ function displayNameFor(from, to) {
59
+ if (from.name !== undefined)
60
+ return from.name;
61
+ const leads = (to.labels ?? []).some((label) => creatorOfLabel(label) === from.agentId);
62
+ return leads ? LEAD_ALIAS : from.agentId;
63
+ }
64
+ /** What a member calls the creator of its team in `Hub send`. Reserved: no teammate may take it. */
65
+ export const LEAD_ALIAS = "lead";
33
66
  function invalidName(kind, name) {
34
67
  if (name.length === 0 || name.length > 48)
35
68
  return `${kind} name must be 1-48 characters.`;
@@ -99,7 +132,8 @@ export class PeerNetwork {
99
132
  async registerMemberSession(options, sessionId) {
100
133
  await this.ready;
101
134
  await this.directory.register({
102
- agentId: options.name,
135
+ agentId: memberAgentId(options.team, options.name),
136
+ name: options.name,
103
137
  type: options.type ?? "member",
104
138
  kind: "session",
105
139
  sessionId,
@@ -255,8 +289,12 @@ export class PeerNetwork {
255
289
  const invalid = invalidName("Agent", args.name);
256
290
  if (invalid !== undefined)
257
291
  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.` };
292
+ if (args.name === LEAD_ALIAS)
293
+ return { error: `"${LEAD_ALIAS}" is reserved — it is what your members call you. Pick another name.` };
294
+ // Unique within THIS team only: another team's "dba" is a different agent with a different id.
295
+ const agentId = memberAgentId(label, args.name);
296
+ if ((await this.directory.get(agentId)) !== undefined) {
297
+ return { error: `The name "${args.name}" is already taken in team "${label.slice(`team:${creatorId}:`.length)}". Pick another.` };
260
298
  }
261
299
  const overspent = budgetExceeded(await this.statistics.snapshot(), this.budget);
262
300
  if (overspent !== undefined)
@@ -271,7 +309,8 @@ export class PeerNetwork {
271
309
  // The member was registered at its session start (params.member → Hub); this merge
272
310
  // is belt-and-braces against a factory that resolved before that handler settled.
273
311
  await this.directory.register({
274
- agentId: args.name,
312
+ agentId,
313
+ name: args.name,
275
314
  type: args.type,
276
315
  kind: "session",
277
316
  sessionId: session.id,
@@ -280,11 +319,92 @@ export class PeerNetwork {
280
319
  labels: [label],
281
320
  updatedAt: Date.now(),
282
321
  });
283
- const to = await this.directory.get(args.name);
322
+ const to = await this.directory.get(agentId);
284
323
  if (to === undefined)
285
324
  return { error: `Teammate "${args.name}" was created but never appeared on the roster — did the spawn factory set params.member?` };
286
325
  const receipt = await this.dispatch(creator, to, args.prompt, {});
287
- return { name: args.name, sessionId: session.id, team: label, receipt };
326
+ return { name: args.name, agentId, sessionId: session.id, team: label, receipt };
327
+ }
328
+ /**
329
+ * Tear a team down: every member leaves the roster (their undelivered mail is dropped), and the
330
+ * creator sheds the label — leaving the roster too once it owns no team. Returns the members'
331
+ * rows so the host can close their sessions; the roster never owned those.
332
+ */
333
+ async disbandTeam(label) {
334
+ await this.ready;
335
+ const wearing = await this.directory.list({ label });
336
+ const creator = wearing.find((ref) => creatorOfLabel(label) === ref.agentId);
337
+ const members = wearing.filter((ref) => ref !== creator);
338
+ for (const member of members) {
339
+ for (const message of await this.mailbox.pending(member.agentId))
340
+ await this.mailbox.settle(member.agentId, message.messageId);
341
+ await this.directory.unregister(member.agentId);
342
+ }
343
+ if (creator !== undefined) {
344
+ const remaining = (creator.labels ?? []).filter((other) => other !== label);
345
+ if (remaining.length === 0)
346
+ await this.directory.unregister(creator.agentId);
347
+ else
348
+ await this.directory.register({ ...creator, labels: remaining, updatedAt: Date.now() });
349
+ }
350
+ return { members, creatorId: creator?.agentId };
351
+ }
352
+ /**
353
+ * What a MEMBER means by `to`: an exact roster id first; then `lead` for the creator of a team
354
+ * it belongs to; then a teammate's short name within its own teams. A short name that matches
355
+ * in several of its teams is refused rather than guessed.
356
+ */
357
+ async resolvePeer(from, toId) {
358
+ const exact = await this.directory.get(toId);
359
+ if (exact !== undefined)
360
+ return exact;
361
+ const labels = from.labels ?? [];
362
+ if (toId === LEAD_ALIAS) {
363
+ const creators = new Set(labels.map(creatorOfLabel).filter((id) => id !== undefined && id !== from.agentId));
364
+ if (creators.size === 0)
365
+ return { reason: "unknown_agent", detail: "No team of yours has a lead on the roster. Use Hub list." };
366
+ if (creators.size > 1)
367
+ return { reason: "ambiguous", detail: `You belong to several teams with different leads — address one by its id from Hub list.` };
368
+ const creator = await this.directory.get([...creators][0]);
369
+ if (creator === undefined)
370
+ return { reason: "unknown_agent", detail: "Your lead has left the roster." };
371
+ return creator;
372
+ }
373
+ const matches = [];
374
+ for (const label of labels) {
375
+ const ref = await this.directory.get(memberAgentId(label, toId));
376
+ if (ref !== undefined)
377
+ matches.push(ref);
378
+ }
379
+ if (matches.length === 1)
380
+ return matches[0];
381
+ if (matches.length > 1)
382
+ return { reason: "ambiguous", detail: `"${toId}" names a teammate in several of your teams — address one by its id from Hub list.` };
383
+ // A name that exists only outside the sender's teams is a boundary refusal, not a typo — the
384
+ // distinction a model needs to stop retrying rather than re-spell.
385
+ const elsewhere = (await this.directory.list()).some((ref) => ref.name === toId);
386
+ if (elsewhere)
387
+ return { reason: "not_visible", detail: `Agent "${toId}" is not addressable from here.` };
388
+ return { reason: "unknown_agent", detail: `No agent "${toId}" is on the roster. Use Hub list; never invent a name.` };
389
+ }
390
+ /**
391
+ * What a CREATOR means by `to`: an exact roster id, or a member's short name — qualified by
392
+ * `team` when the creator owns several and the name is used in more than one.
393
+ */
394
+ async resolveMember(creatorId, toId, team) {
395
+ const members = await this.ownedMembers(creatorId);
396
+ const exact = members.find((ref) => ref.agentId === toId);
397
+ if (exact !== undefined)
398
+ return exact;
399
+ const label = team === undefined ? undefined : teamLabel(creatorId, team);
400
+ const matches = members.filter((ref) => ref.name === toId && (label === undefined || (ref.labels ?? []).includes(label)));
401
+ if (matches.length === 1)
402
+ return matches[0];
403
+ if (matches.length > 1) {
404
+ const teams = matches.flatMap((ref) => ownedLabelsOf(creatorId, ref)).map((l) => l.slice(`team:${creatorId}:`.length));
405
+ return { reason: "ambiguous", detail: `"${toId}" is a member of several of your teams (${teams.join(", ")}) — say which with team.` };
406
+ }
407
+ return { reason: "not_visible", detail: `"${toId}" is not a member of any team you created. Team list shows your members.` };
288
408
  }
289
409
  /** Charge one outbound message against the sender's per-turn budget. */
290
410
  overBudget(selfId, turnId) {
@@ -305,11 +425,11 @@ export class PeerNetwork {
305
425
  async route(from, toId, content, opts = {}) {
306
426
  await this.ready;
307
427
  const fail = (reason, detail) => ({ messageId: newMessageId(), to: toId, status: "failed", reason, detail });
308
- if (toId === from.agentId)
428
+ const to = await this.resolvePeer(from, toId);
429
+ if (!("agentId" in to))
430
+ return fail(to.reason, to.detail);
431
+ if (to.agentId === from.agentId)
309
432
  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
433
  if (!this.visibility(from, to))
314
434
  return fail("not_visible", `Agent "${toId}" is not addressable from here.`);
315
435
  return this.dispatch(from, to, content, opts);
@@ -324,11 +444,9 @@ export class PeerNetwork {
324
444
  const from = await this.directory.get(fromId);
325
445
  if (from === undefined)
326
446
  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
- }
447
+ const to = await this.resolveMember(fromId, toId, opts.team);
448
+ if (!("agentId" in to))
449
+ return fail(to.reason, to.detail);
332
450
  return this.dispatch(from, to, content, opts);
333
451
  }
334
452
  /** The shared tail of every send: budget → write-ahead ledger (capacity enforced atomically
@@ -355,11 +473,14 @@ export class PeerNetwork {
355
473
  async deliver(to, message, interrupt) {
356
474
  const { messageId, to: toId, content } = message;
357
475
  const fail = (reason, detail) => ({ messageId, to: toId, status: "failed", reason, detail });
476
+ // The sender shows up under the name the recipient can answer to (`dba`, `lead`), never a
477
+ // roster id it would have to decode.
478
+ const sender = await this.directory.get(message.from);
358
479
  const origin = {
359
480
  kind: "external",
360
481
  source: PEER_SOURCE,
361
482
  deliveryId: messageId,
362
- actor: message.from,
483
+ actor: sender === undefined ? message.from : displayNameFor(sender, to),
363
484
  // follow_up by default: peers interject between turns, they do not interrupt work in flight.
364
485
  channel: interrupt ? "steering" : "follow_up",
365
486
  ...(message.replyTo !== undefined ? { metadata: { replyTo: message.replyTo } } : {}),
@@ -464,18 +585,19 @@ export function mountTeam(network, api, options = {}) {
464
585
  /** Mount the member side (the `Hub` tool + identity registration) onto a session — what
465
586
  * `peers().setup` does for a teammate. */
466
587
  export function mountHub(network, api, options) {
588
+ const selfId = memberAgentId(options.team, options.name);
467
589
  network.attachActions(api.actions);
468
590
  api.on("session.start", (event) => {
469
591
  void network.registerMemberSession(options, event.sessionId);
470
592
  });
471
593
  api.on("session.end", () => {
472
- void network.parkAgent(options.name);
594
+ void network.parkAgent(selfId);
473
595
  });
474
596
  api.onEvent((event) => {
475
597
  network.attachActions(api.actions);
476
- network.observe(event, options.name);
598
+ network.observe(event, selfId);
477
599
  });
478
- api.registerTool(buildMemberTool(network, options.name));
600
+ api.registerTool(buildMemberTool(network, selfId, options.name));
479
601
  }
480
602
  export function createPeerNetwork(options) {
481
603
  return new PeerNetwork(options);
package/dist/team-tool.js CHANGED
@@ -16,14 +16,15 @@ const teamInput = z.discriminatedUnion("op", [
16
16
  z.object({
17
17
  op: z.literal("spawn").describe("Create one teammate in your team. It starts on the prompt immediately and reports back by message."),
18
18
  type: z.string().describe("A teammate type configured by the host. An unknown type fails and lists what is available."),
19
- name: z.string().describe("The teammate's name — unique on the roster; it is how you and its teammates address it."),
19
+ name: z.string().describe('The teammate\'s name — unique within the team; it is how you and its teammates address it. "lead" is reserved for you.'),
20
20
  prompt: z.string().describe("Its initial assignment. Plain prose; share paths and ids, not pasted blobs."),
21
21
  team: z.string().optional().describe("Which of your teams it joins. Only needed when you created more than one."),
22
22
  }),
23
23
  z.object({
24
24
  op: z.literal("send").describe("Message one of YOUR team's members. Returns immediately; never waits for a reply."),
25
- to: z.string().describe("Exact member name from Team list."),
25
+ to: z.string().describe("Member name (or id) from Team list."),
26
26
  message: z.string().describe("Plain prose."),
27
+ team: z.string().optional().describe("Which of your teams the member is in. Only needed when the same name exists in several of your teams."),
27
28
  replyTo: z.string().optional().describe("messageId you are answering, when this is a reply."),
28
29
  interrupt: z.boolean().optional().describe("Cut into the member's current work instead of waiting for its turn boundary. Reserve for 'stop, you're going the wrong way'."),
29
30
  }),
@@ -32,7 +33,8 @@ const teamInput = z.discriminatedUnion("op", [
32
33
  ]);
33
34
  function memberRow(ref) {
34
35
  return {
35
- name: ref.agentId,
36
+ name: ref.name ?? ref.agentId,
37
+ ...(ref.name !== undefined ? { id: ref.agentId } : {}),
36
38
  type: ref.type,
37
39
  status: ref.status,
38
40
  ...(ref.description !== undefined ? { description: ref.description } : {}),
@@ -95,7 +97,7 @@ export function buildTeamTool(network, sessionIdOf, options) {
95
97
  return text([
96
98
  `Team "${args.name}" formed.`,
97
99
  "",
98
- "Recruit with Team spawn(type, name, prompt). Members join automatically and can message you and each other by name.",
100
+ "Recruit with Team spawn(type, name, prompt). Members join automatically and can message you (as \"lead\") and each other by name.",
99
101
  ].join("\n"), { op: args.op, label: result.label });
100
102
  }
101
103
  if (args.op === "spawn") {
@@ -109,7 +111,7 @@ export function buildTeamTool(network, sessionIdOf, options) {
109
111
  `Teammate "${result.name}" (${args.type}) is working on it.`,
110
112
  "",
111
113
  "It reports back by message in a later turn — do not wait for it. Team send to steer it; Team list to see your members.",
112
- ].join("\n"), { op: args.op, name: result.name, sessionId: result.sessionId, team: result.team, receipt: result.receipt });
114
+ ].join("\n"), { op: args.op, name: result.name, agentId: result.agentId, sessionId: result.sessionId, team: result.team, receipt: result.receipt });
113
115
  }
114
116
  if (args.op === "list") {
115
117
  const members = await network.ownedMembers(selfId);
@@ -125,6 +127,7 @@ export function buildTeamTool(network, sessionIdOf, options) {
125
127
  return text("Outbound peer-message budget for this turn is exhausted. Continue your work; send again in a later turn.", { op: args.op, reason: "quota_exceeded" }, true);
126
128
  }
127
129
  const receipt = await network.sendWithinTeam(selfId, args.to, args.message, {
130
+ ...(args.team !== undefined ? { team: args.team } : {}),
128
131
  ...(args.replyTo !== undefined ? { replyTo: args.replyTo } : {}),
129
132
  ...(args.interrupt !== undefined ? { interrupt: args.interrupt } : {}),
130
133
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "operon-agents-peers",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "Peer discovery and messaging between operon-agents agents, built on the engine's steerTo seam.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -32,8 +32,8 @@
32
32
  ],
33
33
  "dependencies": {
34
34
  "zod": "^4.0.0",
35
- "operon-agents": "0.1.0-alpha.2",
36
- "operon-agents-core": "0.1.0-alpha.2"
35
+ "operon-agents": "0.1.0-alpha.3",
36
+ "operon-agents-core": "0.1.0-alpha.3"
37
37
  },
38
38
  "scripts": {
39
39
  "clean": "rm -rf dist *.tsbuildinfo",