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/LICENSE +55 -0
- package/README.md +191 -0
- package/dist/define-tool.d.ts +16 -0
- package/dist/define-tool.js +17 -0
- package/dist/directory.d.ts +148 -0
- package/dist/directory.js +148 -0
- package/dist/file-repo.d.ts +3 -0
- package/dist/file-repo.js +119 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +33 -0
- package/dist/mailbox.d.ts +64 -0
- package/dist/mailbox.js +32 -0
- package/dist/member-tool.d.ts +4 -0
- package/dist/member-tool.js +97 -0
- package/dist/network.d.ts +320 -0
- package/dist/network.js +526 -0
- package/dist/repo.d.ts +30 -0
- package/dist/repo.js +27 -0
- package/dist/stats.d.ts +80 -0
- package/dist/stats.js +80 -0
- package/dist/team-tool.d.ts +4 -0
- package/dist/team-tool.js +139 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yingjie Qiao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
-------------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
THIRD-PARTY LICENSES
|
|
27
|
+
|
|
28
|
+
Portions of this software were adapted from kimi-code, which is distributed
|
|
29
|
+
under the MIT License. Its copyright and permission notice is reproduced below.
|
|
30
|
+
|
|
31
|
+
-------------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
kimi-code
|
|
34
|
+
|
|
35
|
+
MIT License
|
|
36
|
+
|
|
37
|
+
Copyright (c) 2026 Moonshot AI
|
|
38
|
+
|
|
39
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
40
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
41
|
+
in the Software without restriction, including without limitation the rights
|
|
42
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
43
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
44
|
+
furnished to do so, subject to the following conditions:
|
|
45
|
+
|
|
46
|
+
The above copyright notice and this permission notice shall be included in all
|
|
47
|
+
copies or substantial portions of the Software.
|
|
48
|
+
|
|
49
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
50
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
51
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
52
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
53
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
54
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
55
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# operon-agents-peers
|
|
2
|
+
|
|
3
|
+
Peer discovery and messaging between agents. **Nothing in this package lives in the engine** — it is built entirely on public seams.
|
|
4
|
+
|
|
5
|
+
The organizing rule: **capability follows birth, and identity is produced by explicit acts** — never inferred from event timing, never granted by being spawned at the right moment.
|
|
6
|
+
|
|
7
|
+
- An ordinary agent holds the **`Team` tool**: it can form a team, spawn teammates into it, and message exactly those members. It has no general peer messaging, and no roster identity until the moment it creates a team.
|
|
8
|
+
- A teammate is a **session** created on the host's terms (the `peers()` extension's `teammates` types), born with the member **`Hub` tool** (general peer messaging, gated by the visibility policy) and its roster identity — and **not** `Team`: a teammate is a member, not a team-former.
|
|
9
|
+
- A delegation (`Agent(...)`) never enters the peer world at all. Quick, self-contained work stays a function call; a teammate is for work that outlives one call and converses.
|
|
10
|
+
|
|
11
|
+
## One definition, two channels
|
|
12
|
+
|
|
13
|
+
peers is packaged as **one `ExtensionDefinition`, `peers(config)`** — an ordinary extension that happens to carry a `create` half (its process-shared `PeerNetwork`). A host takes it through whichever channel fits its deployment; nothing about the definition changes.
|
|
14
|
+
|
|
15
|
+
| | **Server — by value** | **Desktop — from a file** |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Hand-over | `createHarness({ extensions: [peers(config)] })` | a bundle in `extensionDir` whose default export is `peers(config)`, then `harness.extensions.load("peers")` |
|
|
18
|
+
| Config | in code | in the bundle; state in the data dir the framework hands it (`host.dataDir`) |
|
|
19
|
+
| Shipping a change | new build, rolling restart | `harness.extensions.reload("peers")`; sessions stay open |
|
|
20
|
+
| Reference | `test/e2e-peers-extension.ts` (a) | `examples/peers-extension`, `test/e2e-peers-extension.ts` (b) |
|
|
21
|
+
|
|
22
|
+
Same code, same tests on both. The framework runs the `create` half **once** and registers the network as the `peers` service; the extension's `setup` runs **per session** and reaches the network only through a stable handle (`shared`). That handle is what lets the file form reload the network under live sessions — and on the server it is a plain registry lookup with nothing dynamic behind it (not replaceable, no loader, no barrier).
|
|
23
|
+
|
|
24
|
+
Which tool a session gets is decided by its **per-session param**, not by wiring: a spawned teammate carries `params.peers = { member }` and gets `Hub`; every other session gets `Team`. Capability follows birth, and a teammate never holds `Team` — it is a member.
|
|
25
|
+
|
|
26
|
+
### Server: pass it by value
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createHarness } from "operon-agents";
|
|
30
|
+
import { createFilePeerRepo, peers, sharedLabelVisibility } from "operon-agents-peers";
|
|
31
|
+
|
|
32
|
+
const harness = createHarness({
|
|
33
|
+
model,
|
|
34
|
+
extensions: [
|
|
35
|
+
peers({
|
|
36
|
+
repo: createFilePeerRepo("/var/lib/myapp/peers"),
|
|
37
|
+
visibility: sharedLabelVisibility,
|
|
38
|
+
teammates: {
|
|
39
|
+
coder: { title: "coder" }, // what a `coder` teammate is born as
|
|
40
|
+
reviewer: ({ name }) => ({ title: `reviewer ${name}` }), // or computed per spawn
|
|
41
|
+
},
|
|
42
|
+
}),
|
|
43
|
+
],
|
|
44
|
+
});
|
|
45
|
+
const lead = await harness.createSession(); // an ordinary session — born holding Team
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`teammates` is the parameter boundary: the host decides what a `coder` teammate *is* — its session options (agent, model, permissions, title) — and the model only ever picks a type and a name. The extension tags each spawned session `params.peers = { member }` itself, so a teammate is born a member with `Hub`. Everything else is the agent's:
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
Team(op: "create", name: "db-migration")
|
|
52
|
+
Team(op: "spawn", type: "coder", name: "dba", prompt: "…")
|
|
53
|
+
Team(op: "spawn", type: "coder", name: "reviewer", prompt: "…")
|
|
54
|
+
```
|
|
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.
|
|
57
|
+
|
|
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
|
+
|
|
60
|
+
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
|
+
|
|
62
|
+
### Desktop: load it from a file
|
|
63
|
+
|
|
64
|
+
The host writes no peers code: it opens an `extensionDir` and loads. The bundle's default export is the same `peers(config)` — its state lives in the data dir the framework hands the extension (`host.dataDir`, outside the bundle), so it survives a reload and an update:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
~/.myapp/extensions/peers/
|
|
68
|
+
manifest.json { "id": "peers", "version": "0.1.0", "engine": "0.1.0-alpha.0", "entry": "index.js", "name": "Peers", "description": "…" }
|
|
69
|
+
index.js ← esbuild bundle of the file below, operon-agents-peers baked in
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// index.ts — the whole extension
|
|
74
|
+
import { createFilePeerRepo, createMemoryPeerRepo, peers, sharedLabelVisibility } from "operon-agents-peers";
|
|
75
|
+
|
|
76
|
+
export default peers({
|
|
77
|
+
repo: ({ dataDir }) => (dataDir !== undefined ? createFilePeerRepo(dataDir) : createMemoryPeerRepo()), // survives reload and update
|
|
78
|
+
visibility: sharedLabelVisibility,
|
|
79
|
+
teammates: { coder: { title: "coder" } },
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const harness = createHarness({ model, extensionDir: "~/.myapp/extensions" });
|
|
85
|
+
await harness.extensions!.load("peers"); // loading IS the approval, recorded at the bundle's mtime
|
|
86
|
+
const lead = await harness.createSession(); // from here on, identical to the server form
|
|
87
|
+
// …the bundle changes on disk…
|
|
88
|
+
await harness.extensions!.reload("peers"); // barrier → swap the per-session half + replace the service → release
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`reload` is one coordinated act: every session holding the peers half meets at its next run boundary, the half is swapped, the service is replaced (the old network's `close()` runs), and everyone resumes. No session is reopened and no conversation is interrupted; the repo in the extension's data dir carries the roster and mailbox across, so the same lead reaches the same teammate afterwards. Nothing watches the directory — a changed bundle loads only through an explicit `reload`, so an agent with write access cannot plant code that runs on next open. Two rules the bundle keeps: import the framework as types only (it belongs to the host — this package value-imports nothing from it, which is what keeps the bundle free of the core's native transitive deps), and keep state in the repo under `host.dataDir` (the instance is replaceable; a memory repo is wiped by reload). To ship it, `pnpm release` in `examples/peers-extension` produces the zip, its sha256 and an index entry for a download site.
|
|
92
|
+
|
|
93
|
+
## Pre-arranged teams
|
|
94
|
+
|
|
95
|
+
A host can stand up a team with no model-driven spawn at all — with `peers()` in `extensions`, hand each session its member identity as a param:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const alice = await harness.createSession({
|
|
99
|
+
params: { peers: { member: { name: "alice", team: "team:host:alpha", type: "lead", description: "Coordinates the work" } } },
|
|
100
|
+
});
|
|
101
|
+
const bob = await harness.createSession({
|
|
102
|
+
params: { peers: { member: { name: "bob", team: "team:host:alpha", type: "dba", description: "Postgres schema and query tuning" } } },
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The param persists with the session, so a `resumeSession` brings `alice` back as a member without repeating it.
|
|
107
|
+
|
|
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.
|
|
109
|
+
|
|
110
|
+
## What it rests on
|
|
111
|
+
|
|
112
|
+
| Seam | Used for |
|
|
113
|
+
|---|---|
|
|
114
|
+
| `api.onEvent` | root-frame lifecycle — who is awake, asleep, gone |
|
|
115
|
+
| `api.registerTool` | the `Team` tool (creators) and the `Hub` tool (members) |
|
|
116
|
+
| `actions.openSession` | reach another session, reopening it if it was closed |
|
|
117
|
+
| `handle.steerTo(address, …)` | hand a message to one specific frame |
|
|
118
|
+
| `create` half / `ctx.shared` | the extension's `create` publishes the network; `setup` reaches it through a method-only handle that outlives any one instance — what makes `reload` and `services.replace` land without touching a session |
|
|
119
|
+
|
|
120
|
+
## Design notes
|
|
121
|
+
|
|
122
|
+
**Off unless configured.** No extension, no tools. `visibility` is required — there is no permissive default, because directory visibility *is* the permission boundary for member messaging. (`Team send` needs no policy: its scope is its permission.)
|
|
123
|
+
|
|
124
|
+
**Identity by act, not by inference.** A member's roster row is written at spawn (or member session start); a creator's at `Team create`. The event stream only refreshes the *status* of rows those acts created — nothing is ever registered because it happened to start at the right time.
|
|
125
|
+
|
|
126
|
+
**Toolsets never change mid-conversation.** Which tools an agent holds is fixed at its birth (prompt-cache stability, and a model never faces a shifting tool surface). That is why capability follows birth rather than following any runtime state.
|
|
127
|
+
|
|
128
|
+
**A teammate and a delegation are different things.** A teammate is an independent session: its own store, permissions, and lifetime, addressable by name, wakeable by message. A delegation shares everything with its parent and reports through its tool result (or task notification). The two compose: a delegation holds the `Team` tool like any frame of its session, so delegated work can form a team of its own.
|
|
129
|
+
|
|
130
|
+
**`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
|
+
|
|
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.
|
|
133
|
+
|
|
134
|
+
## Permissions
|
|
135
|
+
|
|
136
|
+
`Team spawn`, `Team send` and `Hub send` wake agents and spend budget, so they are not auto-approved. Under `permission: { mode: "yolo" }` they just run; otherwise allow them explicitly.
|
|
137
|
+
|
|
138
|
+
## Storage
|
|
139
|
+
|
|
140
|
+
All peer state goes through one injectable seam — the host hands `createPeerNetwork` a `PeerRepo`, and the repo decides where things live:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { createFilePeerRepo } from "operon-agents-peers";
|
|
144
|
+
|
|
145
|
+
peers({
|
|
146
|
+
visibility: sharedLabelVisibility,
|
|
147
|
+
repo: createFilePeerRepo("/var/lib/myapp/peers"), // omit for the in-memory default; the bundle's own folder in the file form
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// On startup, once at least one session holding a peers extension is open:
|
|
151
|
+
const net = harness.services.handle<PeerNetworkHandle>(PEERS_SERVICE);
|
|
152
|
+
const { redelivered, dropped } = await net.reconcile();
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The interface is **operation-level, never key/value** — `enqueue`, `settle`, `put`, `add` — and the contract every implementation must honor is: *each method is atomic in the backend; no caller ever does a cross-call read-modify-write.* That is what lets one repo be shared without conflicts. Three facets, each persisting exactly what only peers knows:
|
|
156
|
+
|
|
157
|
+
| Facet | Persists | Why |
|
|
158
|
+
|---|---|---|
|
|
159
|
+
| `mailbox` | messages in flight | the only facet protecting **correctness** — see *Durability* |
|
|
160
|
+
| `cards` | name → session id, team labels, `type`/`description` | invented at runtime, recorded nowhere else; without them a restart leaves parked teammates undiscoverable, hence unwakeable |
|
|
161
|
+
| `stats` | nothing (memory), by design | a persisted budget ledger forces reset semantics only the host can decide — implement this facet yourself for a fleet ledger spanning restarts |
|
|
162
|
+
|
|
163
|
+
`createFilePeerRepo(dir)` is the local-first durable option: two JSON files, atomic-rename writes, mutations serialized per process. It is **single-process**; multi-process deployments implement `PeerRepo` on a store with real cross-process atomicity (PG, Redis).
|
|
164
|
+
|
|
165
|
+
## Durability
|
|
166
|
+
|
|
167
|
+
`steerTo` only puts a message on an in-memory queue, so a crash before the recipient consumes it would lose it. The mailbox ledger closes that window:
|
|
168
|
+
|
|
169
|
+
1. Every send records the message **before** delivery — and enforces `mailboxCapacity` inside that same atomic step, so the cap is a hard limit rather than a check-then-act race. A teammate's *initial prompt* travels this path too: spawn hands it over as the first peer message.
|
|
170
|
+
2. The entry clears only when the recipient's `message.appended` shows it entered their conversation.
|
|
171
|
+
3. So whatever is still on the ledger after a restart is exactly what was lost — no journal comparison needed.
|
|
172
|
+
|
|
173
|
+
The card store closes the other restart window: cards seed sleeping teammates back onto the roster as `parked` — discoverable, addressable, wakeable — with the name → session mapping that exists nowhere else. `reconcile()` then redelivers what the crash stranded, dropping (and counting) anything whose recipient is genuinely unknown.
|
|
174
|
+
|
|
175
|
+
## Fleet accounting
|
|
176
|
+
|
|
177
|
+
`maxTurns` bounds one agent. It cannot stop ten agents each burning their own budget, and it cannot see that they kept waking each other to do it — a peer message can start a turn on an idle teammate, so cost accrues without anyone prompting.
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
peers({
|
|
181
|
+
visibility: sharedLabelVisibility,
|
|
182
|
+
budget: { maxWakes: 200, maxTotalTokens: 5_000_000 },
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
await harness.services.handle<PeerNetworkHandle>(PEERS_SERVICE).stats();
|
|
186
|
+
// → { agents: [{ agentId, messagesSent, messagesReceived, wakes, totalTokens, cost }], totals }
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Reaching the ceiling **pauses peer traffic** — sends and spawns start refusing with `quota_exceeded` and the reason spelled out. Agents already running finish their own work. `wakes` is the sharpest lever: each one is a fresh LLM call nobody explicitly asked for.
|
|
190
|
+
|
|
191
|
+
The design history — including what was deliberately left out and why — is summarized in the sections above.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A local `defineTool` with the same shape as operon-agents-core's, kept here so this package
|
|
3
|
+
* VALUE-imports nothing from the framework: a file-extension bundle of it must not drag the core
|
|
4
|
+
* barrel (and its native transitive deps) into the bundle. `Tool` and friends are types only.
|
|
5
|
+
*/
|
|
6
|
+
import { z, type ZodType } from "zod";
|
|
7
|
+
import type { Tool, ToolPlan, ToolResolveContext } from "operon-agents-core";
|
|
8
|
+
export interface ToolDef<S extends ZodType> {
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly description: string;
|
|
11
|
+
readonly params: S;
|
|
12
|
+
readonly resolve: (args: z.infer<S>, ctx: ToolResolveContext) => ToolPlan | Promise<ToolPlan>;
|
|
13
|
+
}
|
|
14
|
+
/** Build a full-control tool: zod params → JSON Schema, parsed args → `resolve` → the plan. */
|
|
15
|
+
export declare function defineTool<S extends ZodType>(def: ToolDef<S>): Tool;
|
|
16
|
+
//# sourceMappingURL=define-tool.d.ts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A local `defineTool` with the same shape as operon-agents-core's, kept here so this package
|
|
3
|
+
* VALUE-imports nothing from the framework: a file-extension bundle of it must not drag the core
|
|
4
|
+
* barrel (and its native transitive deps) into the bundle. `Tool` and friends are types only.
|
|
5
|
+
*/
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
/** Build a full-control tool: zod params → JSON Schema, parsed args → `resolve` → the plan. */
|
|
8
|
+
export function defineTool(def) {
|
|
9
|
+
const parameters = z.toJSONSchema(def.params);
|
|
10
|
+
return {
|
|
11
|
+
schema: { name: def.name, description: def.description, parameters },
|
|
12
|
+
resolve(rawArgs, ctx) {
|
|
13
|
+
return def.resolve(def.params.parse(rawArgs), ctx);
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=define-tool.js.map
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who is on the field, across sessions.
|
|
3
|
+
*
|
|
4
|
+
* A PROJECTION, not a source of truth: durable state lives in each session's log, and this only
|
|
5
|
+
* aggregates what the event stream already says so agents can find — and address — each other.
|
|
6
|
+
* Losing it on restart costs discovery, not data.
|
|
7
|
+
*
|
|
8
|
+
* Two ids, deliberately separate: `agentId` is flat and unique (addressing), `address` stays
|
|
9
|
+
* hierarchical (journal sharding, and what `steerTo` takes).
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Two genuinely different things, not two flavours of one:
|
|
13
|
+
*
|
|
14
|
+
* `session` — an independent agent. Its own store, capabilities, permissions and lifetime; the
|
|
15
|
+
* host (or an extension) opens it, and closing it only puts it to sleep.
|
|
16
|
+
*
|
|
17
|
+
* `subagent` — one delegation inside a session. It SHARES the parent's store, capabilities,
|
|
18
|
+
* permissions and machine; only its conversation shard and its frame are its own, and its
|
|
19
|
+
* lifetime is the parent run's. That is the right shape for "go do this for me", and the wrong
|
|
20
|
+
* shape for a durable teammate — which is why the two are not unified.
|
|
21
|
+
*/
|
|
22
|
+
export type AgentRefKind = "session" | "subagent";
|
|
23
|
+
/**
|
|
24
|
+
* `parked` means different things for the two kinds, because they ARE different:
|
|
25
|
+
*
|
|
26
|
+
* - a closed `session` is asleep — reopening it (a message will) brings it back;
|
|
27
|
+
* - a finished `subagent` is a completed delegation — its shard stays replayable, but only the
|
|
28
|
+
* parent that spawned it can continue it (`Agent(resume=…)`), because everything else it ran
|
|
29
|
+
* on belongs to that parent.
|
|
30
|
+
*
|
|
31
|
+
* A `running` subagent, by contrast, is messageable like anyone else — which is what lets a batch
|
|
32
|
+
* of parallel delegates coordinate while they work.
|
|
33
|
+
*
|
|
34
|
+
* Being on the roster never implies permission: that is `visibility`, independent of status.
|
|
35
|
+
*/
|
|
36
|
+
export type AgentRefStatus = "running" | "idle" | "parked" | "error";
|
|
37
|
+
export interface AgentRef {
|
|
38
|
+
readonly agentId: string;
|
|
39
|
+
readonly type: string;
|
|
40
|
+
readonly kind: AgentRefKind;
|
|
41
|
+
readonly sessionId: string;
|
|
42
|
+
/** Journal address of its frame — `main`, or `main/<agentId>`. What `steerTo` addresses. */
|
|
43
|
+
readonly address: string;
|
|
44
|
+
/** Lineage only, NOT a control-flow relationship. */
|
|
45
|
+
readonly parentId?: string;
|
|
46
|
+
/** Open-ended grouping. Membership in a "team" is a label, not a container — which is what
|
|
47
|
+
* lets one team mix session-level teammates with subagents. */
|
|
48
|
+
readonly labels?: readonly string[];
|
|
49
|
+
readonly status: AgentRefStatus;
|
|
50
|
+
readonly description?: string;
|
|
51
|
+
readonly updatedAt: number;
|
|
52
|
+
}
|
|
53
|
+
export interface AgentListFilter {
|
|
54
|
+
readonly sessionId?: string;
|
|
55
|
+
readonly kind?: AgentRefKind;
|
|
56
|
+
readonly label?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface AgentDirectory {
|
|
59
|
+
register(ref: AgentRef): Promise<void>;
|
|
60
|
+
setStatus(agentId: string, status: AgentRefStatus): Promise<void>;
|
|
61
|
+
/** Drop an agent entirely. For deletion — a closed session is `parked`, not unregistered. */
|
|
62
|
+
unregister(agentId: string): Promise<void>;
|
|
63
|
+
get(agentId: string): Promise<AgentRef | undefined>;
|
|
64
|
+
list(filter?: AgentListFilter): Promise<readonly AgentRef[]>;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The durable slice of the roster: exactly what the runtime INVENTED and nothing else knows —
|
|
68
|
+
* team labels (`Hub team` writes them nowhere but here) and the `type`/`description` card stated
|
|
69
|
+
* when the extension was wired. Everything else on an `AgentRef` is derivable and deliberately
|
|
70
|
+
* NOT persisted: a session-level agent's `sessionId` is its `agentId`, its `address` is `"main"`,
|
|
71
|
+
* and its `status` after a restart is `parked` by definition — whatever a previous process
|
|
72
|
+
* recorded as `running` is a lie by the time anyone reads it.
|
|
73
|
+
*
|
|
74
|
+
* Only `kind: "session"` agents are carded. A parked subagent is a finished delegation — not
|
|
75
|
+
* addressable, only resumable by its parent — so persisting it would preserve a record, not a
|
|
76
|
+
* teammate.
|
|
77
|
+
*/
|
|
78
|
+
export interface PeerCard {
|
|
79
|
+
readonly type: string;
|
|
80
|
+
readonly description?: string;
|
|
81
|
+
readonly labels?: readonly string[];
|
|
82
|
+
/** The session behind this agent. Spawned teammates are addressed by their NAME, which is not
|
|
83
|
+
* the session id — omitting this would strand them after a restart. Absent on older cards,
|
|
84
|
+
* where the agent id WAS the session id. */
|
|
85
|
+
readonly sessionId?: string;
|
|
86
|
+
}
|
|
87
|
+
export interface PeerCardStore {
|
|
88
|
+
put(agentId: string, card: PeerCard): Promise<void>;
|
|
89
|
+
remove(agentId: string): Promise<void>;
|
|
90
|
+
list(): Promise<ReadonlyArray<{
|
|
91
|
+
readonly agentId: string;
|
|
92
|
+
readonly card: PeerCard;
|
|
93
|
+
}>>;
|
|
94
|
+
}
|
|
95
|
+
export declare class MemoryPeerCardStore implements PeerCardStore {
|
|
96
|
+
private readonly cards;
|
|
97
|
+
put(agentId: string, card: PeerCard): Promise<void>;
|
|
98
|
+
remove(agentId: string): Promise<void>;
|
|
99
|
+
list(): Promise<ReadonlyArray<{
|
|
100
|
+
readonly agentId: string;
|
|
101
|
+
readonly card: PeerCard;
|
|
102
|
+
}>>;
|
|
103
|
+
}
|
|
104
|
+
/** What a card seeds back onto the roster: identity from the card, everything derivable derived. */
|
|
105
|
+
export declare function refFromCard(agentId: string, card: PeerCard): AgentRef;
|
|
106
|
+
/**
|
|
107
|
+
* Keeps the card store mirroring the roster's durable slice, so callers never write both.
|
|
108
|
+
*
|
|
109
|
+
* The card is written from the MERGED ref read back after `register` — not from the incoming one —
|
|
110
|
+
* because `register` preserves labels the caller did not restate (a session reopening without
|
|
111
|
+
* `labels` must not wipe its persisted team membership). `setStatus` never touches the store:
|
|
112
|
+
* status is the field that flips every turn, and it is exactly the field that is not persisted.
|
|
113
|
+
*/
|
|
114
|
+
export declare class CardSyncedDirectory implements AgentDirectory {
|
|
115
|
+
private readonly inner;
|
|
116
|
+
private readonly cards;
|
|
117
|
+
constructor(inner: AgentDirectory, cards: PeerCardStore);
|
|
118
|
+
register(ref: AgentRef): Promise<void>;
|
|
119
|
+
setStatus(agentId: string, status: AgentRefStatus): Promise<void>;
|
|
120
|
+
unregister(agentId: string): Promise<void>;
|
|
121
|
+
get(agentId: string): Promise<AgentRef | undefined>;
|
|
122
|
+
list(filter?: AgentListFilter): Promise<readonly AgentRef[]>;
|
|
123
|
+
/** Rebuild the parked half of the roster from the card store. Never overwrites a live entry —
|
|
124
|
+
* a session that registered before seeding finished must keep its live status. */
|
|
125
|
+
seed(): Promise<void>;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Whether `from` may see (and therefore address) `to`. DENY BY DEFAULT — there is no built-in
|
|
129
|
+
* fallback that allows everything, because directory visibility IS the permission boundary: an
|
|
130
|
+
* agent that cannot see a privileged peer cannot ask it to act on its behalf.
|
|
131
|
+
*/
|
|
132
|
+
export type Visibility = (from: AgentRef, to: AgentRef) => boolean;
|
|
133
|
+
/** Everything in one session (a root agent and the subagents beneath it). The conservative
|
|
134
|
+
* starting point. */
|
|
135
|
+
export declare function sameSessionVisibility(from: AgentRef, to: AgentRef): boolean;
|
|
136
|
+
/** Shared labels — what a team application uses to draw its boundary. */
|
|
137
|
+
export declare function sharedLabelVisibility(from: AgentRef, to: AgentRef): boolean;
|
|
138
|
+
/** Allow anything the same session tree OR a shared label admits. */
|
|
139
|
+
export declare function anyOf(...policies: readonly Visibility[]): Visibility;
|
|
140
|
+
export declare class MemoryAgentDirectory implements AgentDirectory {
|
|
141
|
+
private readonly refs;
|
|
142
|
+
register(ref: AgentRef): Promise<void>;
|
|
143
|
+
setStatus(agentId: string, status: AgentRefStatus): Promise<void>;
|
|
144
|
+
unregister(agentId: string): Promise<void>;
|
|
145
|
+
get(agentId: string): Promise<AgentRef | undefined>;
|
|
146
|
+
list(filter?: AgentListFilter): Promise<readonly AgentRef[]>;
|
|
147
|
+
}
|
|
148
|
+
//# sourceMappingURL=directory.d.ts.map
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who is on the field, across sessions.
|
|
3
|
+
*
|
|
4
|
+
* A PROJECTION, not a source of truth: durable state lives in each session's log, and this only
|
|
5
|
+
* aggregates what the event stream already says so agents can find — and address — each other.
|
|
6
|
+
* Losing it on restart costs discovery, not data.
|
|
7
|
+
*
|
|
8
|
+
* Two ids, deliberately separate: `agentId` is flat and unique (addressing), `address` stays
|
|
9
|
+
* hierarchical (journal sharding, and what `steerTo` takes).
|
|
10
|
+
*/
|
|
11
|
+
export class MemoryPeerCardStore {
|
|
12
|
+
cards = new Map();
|
|
13
|
+
async put(agentId, card) {
|
|
14
|
+
this.cards.set(agentId, card);
|
|
15
|
+
}
|
|
16
|
+
async remove(agentId) {
|
|
17
|
+
this.cards.delete(agentId);
|
|
18
|
+
}
|
|
19
|
+
async list() {
|
|
20
|
+
return [...this.cards.entries()].map(([agentId, card]) => ({ agentId, card }));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** What a card seeds back onto the roster: identity from the card, everything derivable derived. */
|
|
24
|
+
export function refFromCard(agentId, card) {
|
|
25
|
+
return {
|
|
26
|
+
agentId,
|
|
27
|
+
type: card.type,
|
|
28
|
+
kind: "session",
|
|
29
|
+
sessionId: card.sessionId ?? agentId,
|
|
30
|
+
address: "main",
|
|
31
|
+
status: "parked",
|
|
32
|
+
...(card.description !== undefined ? { description: card.description } : {}),
|
|
33
|
+
...(card.labels !== undefined ? { labels: card.labels } : {}),
|
|
34
|
+
updatedAt: 0,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Keeps the card store mirroring the roster's durable slice, so callers never write both.
|
|
39
|
+
*
|
|
40
|
+
* The card is written from the MERGED ref read back after `register` — not from the incoming one —
|
|
41
|
+
* because `register` preserves labels the caller did not restate (a session reopening without
|
|
42
|
+
* `labels` must not wipe its persisted team membership). `setStatus` never touches the store:
|
|
43
|
+
* status is the field that flips every turn, and it is exactly the field that is not persisted.
|
|
44
|
+
*/
|
|
45
|
+
export class CardSyncedDirectory {
|
|
46
|
+
inner;
|
|
47
|
+
cards;
|
|
48
|
+
constructor(inner, cards) {
|
|
49
|
+
this.inner = inner;
|
|
50
|
+
this.cards = cards;
|
|
51
|
+
}
|
|
52
|
+
async register(ref) {
|
|
53
|
+
await this.inner.register(ref);
|
|
54
|
+
if (ref.kind !== "session")
|
|
55
|
+
return;
|
|
56
|
+
const merged = await this.inner.get(ref.agentId);
|
|
57
|
+
if (merged === undefined)
|
|
58
|
+
return;
|
|
59
|
+
await this.cards.put(merged.agentId, {
|
|
60
|
+
type: merged.type,
|
|
61
|
+
sessionId: merged.sessionId,
|
|
62
|
+
...(merged.description !== undefined ? { description: merged.description } : {}),
|
|
63
|
+
...(merged.labels !== undefined ? { labels: merged.labels } : {}),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
setStatus(agentId, status) {
|
|
67
|
+
return this.inner.setStatus(agentId, status);
|
|
68
|
+
}
|
|
69
|
+
async unregister(agentId) {
|
|
70
|
+
await this.inner.unregister(agentId);
|
|
71
|
+
await this.cards.remove(agentId);
|
|
72
|
+
}
|
|
73
|
+
async get(agentId) {
|
|
74
|
+
const live = await this.inner.get(agentId);
|
|
75
|
+
if (live !== undefined)
|
|
76
|
+
return live;
|
|
77
|
+
// Fall through to the card store on a miss: a row carded by a PREDECESSOR instance after
|
|
78
|
+
// this one seeded (the replace drain window) is recovered instead of lost. Same guard as
|
|
79
|
+
// `seed()` — never overwrite an entry that appeared in the meantime.
|
|
80
|
+
const card = (await this.cards.list()).find((row) => row.agentId === agentId)?.card;
|
|
81
|
+
if (card === undefined)
|
|
82
|
+
return undefined;
|
|
83
|
+
if ((await this.inner.get(agentId)) === undefined)
|
|
84
|
+
await this.inner.register(refFromCard(agentId, card));
|
|
85
|
+
return this.inner.get(agentId);
|
|
86
|
+
}
|
|
87
|
+
list(filter) {
|
|
88
|
+
return this.inner.list(filter);
|
|
89
|
+
}
|
|
90
|
+
/** Rebuild the parked half of the roster from the card store. Never overwrites a live entry —
|
|
91
|
+
* a session that registered before seeding finished must keep its live status. */
|
|
92
|
+
async seed() {
|
|
93
|
+
for (const { agentId, card } of await this.cards.list()) {
|
|
94
|
+
if ((await this.inner.get(agentId)) !== undefined)
|
|
95
|
+
continue;
|
|
96
|
+
await this.inner.register(refFromCard(agentId, card));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Everything in one session (a root agent and the subagents beneath it). The conservative
|
|
101
|
+
* starting point. */
|
|
102
|
+
export function sameSessionVisibility(from, to) {
|
|
103
|
+
return from.sessionId === to.sessionId;
|
|
104
|
+
}
|
|
105
|
+
/** Shared labels — what a team application uses to draw its boundary. */
|
|
106
|
+
export function sharedLabelVisibility(from, to) {
|
|
107
|
+
if (from.labels === undefined || to.labels === undefined)
|
|
108
|
+
return false;
|
|
109
|
+
return from.labels.some((label) => to.labels?.includes(label) === true);
|
|
110
|
+
}
|
|
111
|
+
/** Allow anything the same session tree OR a shared label admits. */
|
|
112
|
+
export function anyOf(...policies) {
|
|
113
|
+
return (from, to) => policies.some((policy) => policy(from, to));
|
|
114
|
+
}
|
|
115
|
+
export class MemoryAgentDirectory {
|
|
116
|
+
refs = new Map();
|
|
117
|
+
async register(ref) {
|
|
118
|
+
const existing = this.refs.get(ref.agentId);
|
|
119
|
+
// Re-registration (a session reopened) keeps labels the caller did not restate, so a revive
|
|
120
|
+
// cannot silently drop team membership.
|
|
121
|
+
this.refs.set(ref.agentId, existing === undefined ? ref : { ...existing, ...ref, labels: ref.labels ?? existing.labels });
|
|
122
|
+
}
|
|
123
|
+
async setStatus(agentId, status) {
|
|
124
|
+
const ref = this.refs.get(agentId);
|
|
125
|
+
if (ref === undefined || ref.status === status)
|
|
126
|
+
return;
|
|
127
|
+
this.refs.set(agentId, { ...ref, status, updatedAt: Date.now() });
|
|
128
|
+
}
|
|
129
|
+
async unregister(agentId) {
|
|
130
|
+
this.refs.delete(agentId);
|
|
131
|
+
}
|
|
132
|
+
async get(agentId) {
|
|
133
|
+
return this.refs.get(agentId);
|
|
134
|
+
}
|
|
135
|
+
async list(filter) {
|
|
136
|
+
const rows = [...this.refs.values()].filter((ref) => {
|
|
137
|
+
if (filter?.sessionId !== undefined && ref.sessionId !== filter.sessionId)
|
|
138
|
+
return false;
|
|
139
|
+
if (filter?.kind !== undefined && ref.kind !== filter.kind)
|
|
140
|
+
return false;
|
|
141
|
+
if (filter?.label !== undefined && ref.labels?.includes(filter.label) !== true)
|
|
142
|
+
return false;
|
|
143
|
+
return true;
|
|
144
|
+
});
|
|
145
|
+
return rows.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
//# sourceMappingURL=directory.js.map
|