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.
package/dist/stats.js ADDED
@@ -0,0 +1,80 @@
1
+ export function emptyCounters() {
2
+ return { messagesSent: 0, messagesReceived: 0, wakes: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0, cost: 0 };
3
+ }
4
+ function accumulate(base, delta) {
5
+ return {
6
+ messagesSent: base.messagesSent + (delta.messagesSent ?? 0),
7
+ messagesReceived: base.messagesReceived + (delta.messagesReceived ?? 0),
8
+ wakes: base.wakes + (delta.wakes ?? 0),
9
+ inputTokens: base.inputTokens + (delta.inputTokens ?? 0),
10
+ outputTokens: base.outputTokens + (delta.outputTokens ?? 0),
11
+ totalTokens: base.totalTokens + (delta.totalTokens ?? 0),
12
+ cost: base.cost + (delta.cost ?? 0),
13
+ };
14
+ }
15
+ /**
16
+ * The default: per-process counters, gone on restart — and that is the right default, because a
17
+ * persisted budget forces a question this package cannot answer for the host: WHEN does the
18
+ * budget reset? (A durable ledger that never resets bricks the network on its first exhaustion —
19
+ * every restart wakes up already over quota.) A host that wants a fleet ledger spanning restarts
20
+ * implements this facet on its own store and owns the reset semantics with it.
21
+ */
22
+ export class MemoryPeerStatsStore {
23
+ perAgent = new Map();
24
+ async add(agentId, delta) {
25
+ this.perAgent.set(agentId, accumulate(this.perAgent.get(agentId) ?? emptyCounters(), delta));
26
+ }
27
+ async snapshot() {
28
+ const agents = [...this.perAgent.entries()].map(([agentId, counters]) => ({ agentId, ...counters }));
29
+ const totals = agents.reduce((acc, a) => accumulate(acc, a), emptyCounters());
30
+ return { agents, totals };
31
+ }
32
+ }
33
+ /**
34
+ * Turns `usage.updated` events into increments. The event carries the reporting run's RUNNING
35
+ * TOTAL, so summing raw events would count the same tokens many times over — we diff against the
36
+ * last value seen.
37
+ *
38
+ * Keyed by AGENT, not by frame address: every session's root frame is `main`, so an address-keyed
39
+ * map would have one session's totals subtracted from another's.
40
+ */
41
+ export class UsageDiff {
42
+ lastUsage = new Map();
43
+ delta(agentId, usage) {
44
+ const current = {
45
+ ...emptyCounters(),
46
+ inputTokens: usage.input,
47
+ outputTokens: usage.output,
48
+ totalTokens: usage.totalTokens ?? usage.input + usage.output,
49
+ cost: usage.cost?.total ?? 0,
50
+ };
51
+ // A total that went DOWN means a fresh run started counting from zero, so there is no
52
+ // previous value to diff against — usage is monotonic within a run, never across them.
53
+ const last = this.lastUsage.get(agentId);
54
+ const previous = last === undefined || current.totalTokens < last.totalTokens ? emptyCounters() : last;
55
+ this.lastUsage.set(agentId, current);
56
+ return {
57
+ inputTokens: current.inputTokens - previous.inputTokens,
58
+ outputTokens: current.outputTokens - previous.outputTokens,
59
+ totalTokens: current.totalTokens - previous.totalTokens,
60
+ cost: current.cost - previous.cost,
61
+ };
62
+ }
63
+ }
64
+ /** The budget line this snapshot has crossed, if any. */
65
+ export function budgetExceeded(stats, budget) {
66
+ if (budget === undefined)
67
+ return undefined;
68
+ const { totals } = stats;
69
+ if (budget.maxTotalTokens !== undefined && totals.totalTokens >= budget.maxTotalTokens) {
70
+ return `fleet token budget reached (${totals.totalTokens}/${budget.maxTotalTokens})`;
71
+ }
72
+ if (budget.maxTotalCost !== undefined && totals.cost >= budget.maxTotalCost) {
73
+ return `fleet cost budget reached (${totals.cost.toFixed(4)}/${budget.maxTotalCost})`;
74
+ }
75
+ if (budget.maxWakes !== undefined && totals.wakes >= budget.maxWakes) {
76
+ return `fleet wake budget reached (${totals.wakes}/${budget.maxWakes})`;
77
+ }
78
+ return undefined;
79
+ }
80
+ //# sourceMappingURL=stats.js.map
@@ -0,0 +1,4 @@
1
+ import type { Tool } from "operon-agents-core";
2
+ import type { PeerExtensionOptions, PeerNetworkHandle } from "./network.ts";
3
+ export declare function buildTeamTool(network: PeerNetworkHandle, sessionIdOf: () => string | undefined, options: PeerExtensionOptions): Tool;
4
+ //# sourceMappingURL=team-tool.d.ts.map
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The `Team` tool — the CREATOR surface. What an ordinary agent holds from birth: it can form a
3
+ * team, spawn session teammates into it, and talk to exactly those members. It has no general
4
+ * peer messaging — that is the member `Hub`, which only spawned teammates are born with.
5
+ *
6
+ * `wait` is deliberately absent here too: teammates report back by messaging, which wakes the
7
+ * creator; a blocking op would only add a way to deadlock.
8
+ */
9
+ import { z } from "zod";
10
+ import { defineTool } from "./define-tool.js";
11
+ const teamInput = z.discriminatedUnion("op", [
12
+ z.object({
13
+ op: z.literal("create").describe("Form a team. Do this once, before spawning members."),
14
+ name: z.string().describe('Short team name, e.g. "db-migration". Letters, digits, _ and - only.'),
15
+ }),
16
+ z.object({
17
+ op: z.literal("spawn").describe("Create one teammate in your team. It starts on the prompt immediately and reports back by message."),
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."),
20
+ prompt: z.string().describe("Its initial assignment. Plain prose; share paths and ids, not pasted blobs."),
21
+ team: z.string().optional().describe("Which of your teams it joins. Only needed when you created more than one."),
22
+ }),
23
+ z.object({
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."),
26
+ message: z.string().describe("Plain prose."),
27
+ replyTo: z.string().optional().describe("messageId you are answering, when this is a reply."),
28
+ 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
+ z.object({ op: z.literal("list").describe("List the members of teams you created, with their status.") }),
31
+ z.object({ op: z.literal("inbox").describe("Read messages routed to you that never reached your conversation.") }),
32
+ ]);
33
+ function memberRow(ref) {
34
+ return {
35
+ name: ref.agentId,
36
+ type: ref.type,
37
+ status: ref.status,
38
+ ...(ref.description !== undefined ? { description: ref.description } : {}),
39
+ ...(ref.labels !== undefined && ref.labels.length > 0 ? { teams: ref.labels } : {}),
40
+ };
41
+ }
42
+ function text(body, details, isError) {
43
+ return { content: [{ type: "text", text: body }], ...(details !== undefined ? { details } : {}), ...(isError === true ? { isError: true } : {}) };
44
+ }
45
+ export function buildTeamTool(network, sessionIdOf, options) {
46
+ const description = [
47
+ "Form and run a team of durable agents for work that needs several of them talking to each other.",
48
+ "",
49
+ "- `create` forms a team (do it once).",
50
+ "- `spawn` creates one teammate in it: an independent agent that starts on your prompt right away,",
51
+ " works in its own session, and reports back by message — which arrives in a LATER turn of yours.",
52
+ "- `send` messages one of your members; `list` shows them; `inbox` drains undelivered messages.",
53
+ "",
54
+ "Rules:",
55
+ "- Teammates can message you and each other directly; you do not relay between them.",
56
+ "- `send` and `spawn` return immediately. NEVER wait or poll for a reply — continue your work;",
57
+ " reports arrive on their own.",
58
+ "- A `failed` receipt is final for that reason — do not retry the same send.",
59
+ "- A `parked` member is asleep, not gone: messaging it wakes it.",
60
+ "- Use a plain Agent(...) delegation for quick self-contained work; spawn a teammate only for",
61
+ " work that needs an agent that outlives one call and converses.",
62
+ ].join("\n");
63
+ return defineTool({
64
+ name: "Team",
65
+ description,
66
+ params: teamInput,
67
+ resolve: (args) => ({
68
+ // `spawn` and `send` wake agents and spend budget; reads are cheap.
69
+ approvalRule: `team.${args.op}`,
70
+ display: {
71
+ title: "Team",
72
+ detail: args.op === "spawn" ? `spawn ${args.type} "${args.name}"`
73
+ : args.op === "send" ? `send → ${args.to}`
74
+ : args.op === "create" ? `create ${args.name}`
75
+ : args.op,
76
+ },
77
+ run: async (ctx) => {
78
+ const sessionId = sessionIdOf();
79
+ if (sessionId === undefined)
80
+ return text("Team coordination is unavailable in this session.", { op: args.op }, true);
81
+ const address = ctx.address ?? "main";
82
+ const isRoot = address === "main";
83
+ const selfId = isRoot ? sessionId : address.slice(address.lastIndexOf("/") + 1);
84
+ const caller = {
85
+ agentId: selfId,
86
+ sessionId,
87
+ address,
88
+ ...(isRoot && options.type !== undefined ? { type: options.type } : {}),
89
+ ...(isRoot && options.description !== undefined ? { description: options.description } : {}),
90
+ };
91
+ if (args.op === "create") {
92
+ const result = await network.createTeam(caller, args.name);
93
+ if ("error" in result)
94
+ return text(result.error, { op: args.op }, true);
95
+ return text([
96
+ `Team "${args.name}" formed.`,
97
+ "",
98
+ "Recruit with Team spawn(type, name, prompt). Members join automatically and can message you and each other by name.",
99
+ ].join("\n"), { op: args.op, label: result.label });
100
+ }
101
+ if (args.op === "spawn") {
102
+ if (network.overBudget(selfId, ctx.turnId)) {
103
+ return text("Outbound peer budget for this turn is exhausted. Continue your work; spawn again in a later turn.", { op: args.op, reason: "quota_exceeded" }, true);
104
+ }
105
+ const result = await network.spawnTeammate(selfId, args);
106
+ if ("error" in result)
107
+ return text(result.error, { op: args.op }, true);
108
+ return text([
109
+ `Teammate "${result.name}" (${args.type}) is working on it.`,
110
+ "",
111
+ "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 });
113
+ }
114
+ if (args.op === "list") {
115
+ const members = await network.ownedMembers(selfId);
116
+ return text(members.length === 0 ? "You have no team members. Team create, then Team spawn." : JSON.stringify({ you: selfId, members: members.map(memberRow) }, null, 2), { op: args.op, count: members.length });
117
+ }
118
+ if (args.op === "inbox") {
119
+ const pending = await network.drainInbox(selfId);
120
+ return text(pending.length === 0
121
+ ? "No undelivered peer messages."
122
+ : 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 });
123
+ }
124
+ if (network.overBudget(selfId, ctx.turnId)) {
125
+ 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
+ }
127
+ const receipt = await network.sendWithinTeam(selfId, args.to, args.message, {
128
+ ...(args.replyTo !== undefined ? { replyTo: args.replyTo } : {}),
129
+ ...(args.interrupt !== undefined ? { interrupt: args.interrupt } : {}),
130
+ });
131
+ const body = receipt.status === "failed"
132
+ ? `send failed (${receipt.reason}): ${receipt.detail ?? ""}`.trim()
133
+ : `Message ${receipt.messageId} delivered to ${receipt.to}. It will answer in its own turn — do not wait for it.`;
134
+ return text(body, { op: args.op, ...receipt }, receipt.status === "failed");
135
+ },
136
+ }),
137
+ });
138
+ }
139
+ //# sourceMappingURL=team-tool.js.map
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "operon-agents-peers",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Peer discovery and messaging between operon-agents agents, built on the engine's steerTo seam.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/nickqiaoo/operon-agents.git",
10
+ "directory": "packages/agents-peers"
11
+ },
12
+ "homepage": "https://github.com/nickqiaoo/operon-agents/tree/main/packages/agents-peers#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/nickqiaoo/operon-agents/issues"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "!dist/**/*.map",
28
+ "README.md"
29
+ ],
30
+ "dependencies": {
31
+ "zod": "^4.0.0",
32
+ "operon-agents": "0.1.0-alpha.0",
33
+ "operon-agents-core": "0.1.0-alpha.0"
34
+ },
35
+ "scripts": {
36
+ "clean": "rm -rf dist *.tsbuildinfo",
37
+ "build": "pnpm --filter operon-agents build && tsc -p tsconfig.build.json",
38
+ "typecheck": "tsc --noEmit -p tsconfig.json",
39
+ "test": "for f in test/e2e*.ts; do echo \"\\n▶ $f\"; node --experimental-strip-types --no-warnings \"$f\" || exit 1; done"
40
+ }
41
+ }