openmsg 0.1.0 → 0.2.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,174 @@
1
+ // The identity of one owner, for version 0.2 of the protocol.
2
+ //
3
+ // An owner holds two keys: one signs a message, and one seals it. The private
4
+ // keys stay in `$OPENMSG_HOME/keys`, and they never travel. The public record
5
+ // travels, in an invitation and in the directory.
6
+ //
7
+ // The owner id and the fingerprint both come from the two public keys. A
8
+ // record that claims an owner id which its keys do not give is a false record,
9
+ // and `checkRecord` refuses it.
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import os from "node:os";
13
+ import crypto from "node:crypto";
14
+ import { canonical } from "./canonical.mjs";
15
+
16
+ export const VERSION = 2;
17
+
18
+ // The home reads from the environment at each call. Two homes on one machine
19
+ // therefore work in one process, and a test needs no second computer.
20
+ export function home() {
21
+ return process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg");
22
+ }
23
+
24
+ export function paths() {
25
+ const dir = path.join(home(), "keys");
26
+ return {
27
+ dir,
28
+ signing: path.join(dir, "signing.key"),
29
+ encryption: path.join(dir, "encryption.key"),
30
+ identity: path.join(dir, "identity.json"),
31
+ };
32
+ }
33
+
34
+ export function exists() {
35
+ return fs.existsSync(paths().identity);
36
+ }
37
+
38
+ // A new key loses the history that the old key sealed. The command therefore
39
+ // refuses to replace an identity without `force`.
40
+ export function create({ label, force = false } = {}) {
41
+ const p = paths();
42
+ if (exists() && !force) {
43
+ throw new Error(
44
+ `an identity is already in ${p.dir}. A new key cannot open what the old key sealed. ` +
45
+ "Use --force to replace it.",
46
+ );
47
+ }
48
+ fs.mkdirSync(p.dir, { recursive: true, mode: 0o700 });
49
+ fs.chmodSync(p.dir, 0o700);
50
+ const signing = crypto.generateKeyPairSync("ed25519");
51
+ const encryption = crypto.generateKeyPairSync("x25519");
52
+ writePrivate(p.signing, signing.privateKey);
53
+ writePrivate(p.encryption, encryption.privateKey);
54
+ const keys = {
55
+ signing: { alg: "Ed25519", x: jwkX(signing.publicKey) },
56
+ encryption: { alg: "X25519", x: jwkX(encryption.publicKey) },
57
+ };
58
+ const record = {
59
+ version: VERSION,
60
+ ownerId: ownerIdOf(keys),
61
+ label: label ?? defaultLabel(),
62
+ keys,
63
+ createdAt: new Date().toISOString(),
64
+ };
65
+ fs.writeFileSync(p.identity, JSON.stringify(record, null, 1) + "\n");
66
+ return record;
67
+ }
68
+
69
+ // The public record of this owner. It is the object that an invitation carries.
70
+ export function load() {
71
+ const p = paths();
72
+ if (!exists()) throw new Error(`no identity in ${p.dir}. Run: openmsg id create`);
73
+ const record = JSON.parse(fs.readFileSync(p.identity, "utf8"));
74
+ checkRecord(record);
75
+ return record;
76
+ }
77
+
78
+ export function checkRecord(record) {
79
+ if (!record || typeof record !== "object") throw new Error("an identity record is missing");
80
+ const { keys } = record;
81
+ if (!keys?.signing?.x || !keys?.encryption?.x) throw new Error("an identity record needs both public keys");
82
+ if (keys.signing.alg !== "Ed25519") throw new Error(`unknown signing algorithm: ${keys.signing.alg}`);
83
+ if (keys.encryption.alg !== "X25519") throw new Error(`unknown encryption algorithm: ${keys.encryption.alg}`);
84
+ const owner = ownerIdOf(keys);
85
+ if (record.ownerId !== owner) {
86
+ throw new Error(`the record claims the owner ${record.ownerId}, and its keys give ${owner}`);
87
+ }
88
+ return record;
89
+ }
90
+
91
+ // Both names come from the same digest of the two public keys. The label is
92
+ // outside the digest, so a person can rename an owner without a new identity.
93
+ function digest(keys) {
94
+ const text = canonical({ encryption: keys.encryption, signing: keys.signing });
95
+ return crypto.createHash("sha256").update(`openmsg-identity-v2\n${text}`).digest("hex");
96
+ }
97
+
98
+ export function ownerIdOf(keys) {
99
+ return `o_${digest(keys).slice(0, 8)}`;
100
+ }
101
+
102
+ // The text that two people read to each other, out of band, before the first
103
+ // message. It holds 128 bits of the digest, in eight groups of four.
104
+ export function fingerprint(record) {
105
+ return digest(record.keys).slice(0, 32).toUpperCase().match(/.{4}/g).join(" ");
106
+ }
107
+
108
+ export function normalizeFingerprint(text) {
109
+ return String(text ?? "").replace(/[^0-9a-fA-F]/g, "").toUpperCase();
110
+ }
111
+
112
+ export function sameFingerprint(a, b) {
113
+ const one = normalizeFingerprint(a);
114
+ const two = normalizeFingerprint(b);
115
+ return one.length === 32 && one === two;
116
+ }
117
+
118
+ export function publicKeyOf({ alg, x }) {
119
+ return crypto.createPublicKey({ key: { kty: "OKP", crv: alg, x }, format: "jwk" });
120
+ }
121
+
122
+ // A machine that holds a delegation keeps the public record of its owner and
123
+ // no private key of that owner. These two give a clear answer there.
124
+ function privateKey(file, which) {
125
+ if (!fs.existsSync(file)) {
126
+ throw new Error(
127
+ `this machine holds no ${which} key of the owner. It signs with its own key, ` +
128
+ "and a command that needs the owner key runs on the machine that made the identity.",
129
+ );
130
+ }
131
+ return crypto.createPrivateKey(fs.readFileSync(file, "utf8"));
132
+ }
133
+
134
+ export function hasPrivateKeys() {
135
+ const p = paths();
136
+ return fs.existsSync(p.signing) && fs.existsSync(p.encryption);
137
+ }
138
+
139
+ export function signingKey() {
140
+ return privateKey(paths().signing, "signing");
141
+ }
142
+
143
+ export function encryptionKey() {
144
+ return privateKey(paths().encryption, "encryption");
145
+ }
146
+
147
+ export function sign(bytes) {
148
+ return crypto.sign(null, Buffer.from(bytes), signingKey());
149
+ }
150
+
151
+ export function verifyWith(record, bytes, signature) {
152
+ try {
153
+ return crypto.verify(null, Buffer.from(bytes), publicKeyOf(record.keys.signing), Buffer.from(signature));
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
158
+
159
+ function writePrivate(file, key) {
160
+ fs.writeFileSync(file, key.export({ format: "pem", type: "pkcs8" }), { mode: 0o600 });
161
+ fs.chmodSync(file, 0o600);
162
+ }
163
+
164
+ function jwkX(key) {
165
+ return key.export({ format: "jwk" }).x;
166
+ }
167
+
168
+ function defaultLabel() {
169
+ try {
170
+ return os.userInfo().username;
171
+ } catch {
172
+ return "owner";
173
+ }
174
+ }
@@ -0,0 +1,89 @@
1
+ // The durable store of every message that arrived from another person.
2
+ //
3
+ // The receiver writes the message here before it gives the message to an
4
+ // agent. A crash after the write therefore leaves a record, and the owner sees
5
+ // the state that the message reached.
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { home } from "./identity.mjs";
9
+
10
+ // The seven states of section 8 of the spec. A message holds one of them.
11
+ //
12
+ // `adapter-accepted` says that the adapter of the vendor took the message.
13
+ // Whether the model read it is another question, and `agent-acknowledged`
14
+ // answers that one. Only an event from the agent gives that state.
15
+ export const STATES = [
16
+ "queued",
17
+ "held",
18
+ "adapter-accepted",
19
+ "agent-acknowledged",
20
+ "replied",
21
+ "refused",
22
+ "expired",
23
+ ];
24
+
25
+ function file() {
26
+ return path.join(home(), "inbound.jsonl");
27
+ }
28
+
29
+ // What each state says, in one sentence. A person reads these words, and case
30
+ // 14 of the acceptance demonstration needs them: after a crash between the
31
+ // injection and the acknowledgement, the receiver must say that it does not
32
+ // know whether the model read the message.
33
+ export const EXPLAIN = {
34
+ queued:
35
+ "it waits: the sender holds it, or the receiver holds it before the adapter takes it. " +
36
+ "After a stop here, nobody knows whether the adapter took it",
37
+ held: "it waits for the owner, and no model read it",
38
+ "adapter-accepted": "the adapter took it, and whether the model read it is unknown",
39
+ "agent-acknowledged": "the agent said that it read it",
40
+ replied: "the agent answered it",
41
+ refused: "a rule stopped it",
42
+ expired: "the deadline passed",
43
+ };
44
+
45
+ export function put(record) {
46
+ if (record.status && !STATES.includes(record.status)) {
47
+ throw new Error(`"${record.status}" is not a state of a message. The states are: ${STATES.join(", ")}`);
48
+ }
49
+ const target = file();
50
+ fs.mkdirSync(path.dirname(target), { recursive: true });
51
+ const now = new Date().toISOString();
52
+ // `receivedAt` is the arrival, and `at` is the last change of the state. A
53
+ // rate limit counts arrivals, so the two are not the same field.
54
+ const row = { ...record, receivedAt: record.receivedAt ?? now, at: now };
55
+ fs.appendFileSync(target, JSON.stringify(row) + "\n");
56
+ return row;
57
+ }
58
+
59
+ export function list({ status = null } = {}) {
60
+ let rows = [];
61
+ try {
62
+ rows = fs.readFileSync(file(), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
63
+ } catch {
64
+ return [];
65
+ }
66
+ // A later row for one message id replaces an earlier row. The file keeps the
67
+ // whole history, and the reader sees the state of now.
68
+ const latest = new Map();
69
+ for (const row of rows) latest.set(row.messageId, { ...(latest.get(row.messageId) ?? {}), ...row });
70
+ const out = [...latest.values()];
71
+ return status ? out.filter((r) => r.status === status) : out;
72
+ }
73
+
74
+ export function find(messageId) {
75
+ return list().find((r) => r.messageId === messageId) ?? null;
76
+ }
77
+
78
+ // A short id is enough for a person to name a held message.
79
+ export function findByPrefix(prefix) {
80
+ const matches = list().filter((r) => r.messageId.startsWith(prefix));
81
+ if (matches.length > 1) throw new Error(`"${prefix}" names ${matches.length} messages. Use more characters.`);
82
+ return matches[0] ?? null;
83
+ }
84
+
85
+ export function setStatus(messageId, status, extra = {}) {
86
+ const row = find(messageId);
87
+ if (!row) throw new Error(`no message ${messageId} in the store`);
88
+ return put({ ...row, status, ...extra, at: new Date().toISOString() });
89
+ }
package/src/invite.mjs ADDED
@@ -0,0 +1,102 @@
1
+ // An invitation carries the public identity of one owner into the directory of
2
+ // another owner, for one project.
3
+ //
4
+ // The token is signed by the key inside it, so a changed byte fails. A
5
+ // signature alone proves nothing about the person, because anybody can make a
6
+ // key. The two people therefore compare the fingerprint out of band, by voice
7
+ // or in a room, and `accept` refuses a token that does not match.
8
+ import crypto from "node:crypto";
9
+ import { canonicalBytes } from "./canonical.mjs";
10
+ import * as identity from "./identity.mjs";
11
+ import * as directory from "./directory.mjs";
12
+
13
+ const PREFIX = "openmsg-invite-v2";
14
+ export const DEFAULT_HOURS = 72;
15
+
16
+ // The project id is opaque. A git remote URL never travels, because it can
17
+ // hold a credential or the name of a private host.
18
+ export function newProjectId() {
19
+ return `p_${crypto.randomBytes(8).toString("hex")}`;
20
+ }
21
+
22
+ // `create` makes the token that the first person sends. `accept` makes the
23
+ // answer of the second person, with the type "accept", and that answer starts
24
+ // no third token.
25
+ export function create({ label, projectId, hours = DEFAULT_HOURS, type = "invite", endpoint = null } = {}) {
26
+ const me = identity.load();
27
+ const project = { id: projectId ?? newProjectId(), label: label ?? "project" };
28
+ const body = {
29
+ type,
30
+ version: identity.VERSION,
31
+ project,
32
+ identity: me,
33
+ // The address of the gateway of this owner. The directory of section 1 of
34
+ // the spec holds it, and a message needs it before the relay of phase 4.
35
+ endpoint,
36
+ createdAt: new Date().toISOString(),
37
+ expiresAt: new Date(Date.now() + hours * 3600 * 1000).toISOString(),
38
+ };
39
+ const bytes = canonicalBytes(body);
40
+ const token = [PREFIX, bytes.toString("base64url"), identity.sign(bytes).toString("base64url")].join(".");
41
+ directory.put(project, me, { source: "self", endpoint });
42
+ return { token, body, project, fingerprint: identity.fingerprint(me) };
43
+ }
44
+
45
+ // `open` reads a token and proves that it holds the bytes that its key signed.
46
+ // It writes nothing. A person reads the fingerprint from here before the
47
+ // accept step.
48
+ export function open(token) {
49
+ const parts = String(token ?? "").trim().split(".");
50
+ if (parts.length !== 3 || parts[0] !== PREFIX) throw new Error("this text is not an openmsg invitation");
51
+ const bytes = Buffer.from(parts[1], "base64url");
52
+ let body;
53
+ try {
54
+ body = JSON.parse(bytes.toString("utf8"));
55
+ } catch {
56
+ throw new Error("the invitation is damaged");
57
+ }
58
+ identity.checkRecord(body.identity);
59
+ if (!identity.verifyWith(body.identity, bytes, Buffer.from(parts[2], "base64url"))) {
60
+ throw new Error("the signature of the invitation does not match its text");
61
+ }
62
+ if (!body.project?.id) throw new Error("the invitation names no project");
63
+ return body;
64
+ }
65
+
66
+ export function accept(token, expected, { now = Date.now(), endpoint = null } = {}) {
67
+ const body = open(token);
68
+ if (!(Date.parse(body.expiresAt) > now)) {
69
+ throw new Error(`the invitation expired at ${body.expiresAt}. Ask for a new one.`);
70
+ }
71
+ const me = identity.load();
72
+ if (body.identity.ownerId === me.ownerId) {
73
+ throw new Error("this invitation holds your own identity");
74
+ }
75
+ const theirs = identity.fingerprint(body.identity);
76
+ const given = identity.normalizeFingerprint(expected);
77
+ if (!given) {
78
+ throw new Error(
79
+ "accept needs the fingerprint that the other person read to you: --fingerprint \"XXXX XXXX ...\". " +
80
+ `The token in your hand holds ${theirs}.`,
81
+ );
82
+ }
83
+ // A part of a fingerprint is not a fingerprint. A short value is a typing
84
+ // fault, and a comparison of a part gives a false confidence.
85
+ if (given.length !== 32) {
86
+ throw new Error(`a fingerprint holds 32 characters, and this one holds ${given.length}. Read all of it again.`);
87
+ }
88
+ if (!identity.sameFingerprint(expected, theirs)) {
89
+ throw new Error(`the fingerprint does not match. The token holds ${theirs}. Do not accept it.`);
90
+ }
91
+ if (directory.isRevoked(body.project.id, body.identity.ownerId)) {
92
+ throw new Error(`the team revoked ${body.identity.ownerId} in this project`);
93
+ }
94
+ const peer = directory.put(body.project, body.identity, { source: body.type, endpoint: body.endpoint ?? null });
95
+ directory.put(body.project, me, { source: "self", endpoint });
96
+ // An invitation gets an answer, and an answer gets none. Two tokens join two
97
+ // people, and the chain stops there.
98
+ const reply = body.type === "invite"
99
+ ? create({ label: body.project.label, projectId: body.project.id, type: "accept", endpoint })
100
+ : null;
101
+ return { peer, project: body.project, reply, mine: identity.fingerprint(me) };
102
+ }
package/src/limits.mjs ADDED
@@ -0,0 +1,63 @@
1
+ // The limits of the receiver. The `hops` list of a sender is not enough,
2
+ // because a sender writes that list itself.
3
+ //
4
+ // Three limits: how many messages one sender sends in a window, how many turns
5
+ // remote messages start in one session, and how many messages wait for the
6
+ // owner. The owner changes a value in `$OPENMSG_HOME/limits.json`.
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { home } from "./identity.mjs";
10
+
11
+ export const DEFAULTS = {
12
+ // Messages from one sender, in one project, inside the window.
13
+ senderPerWindow: 30,
14
+ senderWindowMs: 5 * 60_000,
15
+ // Turns that remote messages start in one session, inside the window. Above
16
+ // this number a message waits for the owner, and no work is lost.
17
+ turnsPerSession: 10,
18
+ turnWindowMs: 10 * 60_000,
19
+ // Messages that wait for the owner, over every project.
20
+ heldMax: 100,
21
+ };
22
+
23
+ export function values() {
24
+ try {
25
+ return { ...DEFAULTS, ...JSON.parse(fs.readFileSync(path.join(home(), "limits.json"), "utf8")) };
26
+ } catch {
27
+ return { ...DEFAULTS };
28
+ }
29
+ }
30
+
31
+ function since(rows, ms, now) {
32
+ return rows.filter((r) => now - Date.parse(r.receivedAt ?? r.at ?? 0) < ms);
33
+ }
34
+
35
+ // It gives null when the message passes every limit, and a reason when one
36
+ // limit stops it. "hold" means that the message waits for the owner instead.
37
+ export function check(rows, { owner, project, session, now = Date.now(), limits = values() } = {}) {
38
+ const fromSender = since(rows.filter((r) => r.from?.owner === owner && r.project === project), limits.senderWindowMs, now);
39
+ if (fromSender.length >= limits.senderPerWindow) {
40
+ return {
41
+ action: "refuse",
42
+ reason: "rate-limit",
43
+ detail: `${owner} sent ${fromSender.length} messages in ${Math.round(limits.senderWindowMs / 60_000)} minutes`,
44
+ };
45
+ }
46
+ const held = rows.filter((r) => r.status === "held");
47
+ if (held.length >= limits.heldMax) {
48
+ return { action: "refuse", reason: "queue-full", detail: `${held.length} messages wait for the owner` };
49
+ }
50
+ const started = since(
51
+ rows.filter((r) => r.target?.session === session && ["adapter-accepted", "agent-acknowledged", "replied"].includes(r.status)),
52
+ limits.turnWindowMs,
53
+ now,
54
+ );
55
+ if (started.length >= limits.turnsPerSession) {
56
+ return {
57
+ action: "hold",
58
+ reason: "turn-limit",
59
+ detail: `remote messages started ${started.length} turns in that session in ${Math.round(limits.turnWindowMs / 60_000)} minutes`,
60
+ };
61
+ }
62
+ return null;
63
+ }
package/src/mailbox.mjs CHANGED
@@ -7,7 +7,11 @@ import path from "node:path";
7
7
  import os from "node:os";
8
8
  import { address } from "./envelope.mjs";
9
9
 
10
- const ROOT = process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg");
10
+ // The home reads from the environment at each call, so one process can hold
11
+ // the mailbox of one person and the mailbox of another.
12
+ function root() {
13
+ return process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg");
14
+ }
11
15
 
12
16
  // The file name encodes the address. encodeURIComponent keeps the name unique,
13
17
  // because two different addresses never give the same name, and it removes the
@@ -21,7 +25,7 @@ function encodeName(addr) {
21
25
  }
22
26
 
23
27
  function boxPath(agent) {
24
- return path.join(ROOT, "inbox", `${encodeName(address(agent))}.jsonl`);
28
+ return path.join(root(), "inbox", `${encodeName(address(agent))}.jsonl`);
25
29
  }
26
30
 
27
31
  export function addressOfFile(file) {
package/src/outbox.mjs ADDED
@@ -0,0 +1,47 @@
1
+ // The copy of the sender. A message stays here until a receipt says that the
2
+ // other side holds it. The relay keeps its own copy, and the two copies mean
3
+ // that one loss on one side loses nothing.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { home } from "./identity.mjs";
7
+
8
+ function file() {
9
+ return path.join(home(), "outbox.jsonl");
10
+ }
11
+
12
+ export function put(record) {
13
+ const target = file();
14
+ fs.mkdirSync(path.dirname(target), { recursive: true });
15
+ const row = { ...record, at: new Date().toISOString() };
16
+ fs.appendFileSync(target, JSON.stringify(row) + "\n");
17
+ return row;
18
+ }
19
+
20
+ export function list({ state = null } = {}) {
21
+ let rows = [];
22
+ try {
23
+ rows = fs.readFileSync(file(), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
24
+ } catch {
25
+ return [];
26
+ }
27
+ const latest = new Map();
28
+ for (const row of rows) latest.set(row.messageId, { ...(latest.get(row.messageId) ?? {}), ...row });
29
+ const out = [...latest.values()];
30
+ return state ? out.filter((r) => r.state === state) : out;
31
+ }
32
+
33
+ export function find(messageId) {
34
+ return list().find((r) => r.messageId === messageId) ?? null;
35
+ }
36
+
37
+ export function setState(messageId, state, extra = {}) {
38
+ const row = find(messageId);
39
+ if (!row) return null;
40
+ return put({ ...row, state, ...extra });
41
+ }
42
+
43
+ // A message that waits for a receipt. The gateway sends these again when it
44
+ // reaches the relay.
45
+ export function waiting() {
46
+ return list().filter((r) => r.state === "sent" || r.state === "queued");
47
+ }
@@ -0,0 +1,56 @@
1
+ // A standing permission for each identity and for each project.
2
+ //
3
+ // `accept` means that a message goes to the agent. `hold` means that it waits
4
+ // for the owner. `refuse` means that it stops at the gateway.
5
+ //
6
+ // The default is `hold`, also for a person in the directory. Membership of a
7
+ // project says who somebody is. It does not say that their agent can write
8
+ // into a session of this machine. The owner gives that with one command.
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { home } from "./identity.mjs";
12
+
13
+ export const VALUES = ["accept", "hold", "refuse"];
14
+ export const DEFAULT = "hold";
15
+
16
+ function file() {
17
+ return path.join(home(), "permissions.json");
18
+ }
19
+
20
+ export function read() {
21
+ try {
22
+ return JSON.parse(fs.readFileSync(file(), "utf8"));
23
+ } catch {
24
+ return { version: 2, projects: {} };
25
+ }
26
+ }
27
+
28
+ function save(data) {
29
+ const target = file();
30
+ fs.mkdirSync(path.dirname(target), { recursive: true });
31
+ const tmp = `${target}.${process.pid}.tmp`;
32
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 1) + "\n");
33
+ fs.renameSync(tmp, target);
34
+ }
35
+
36
+ export function set(projectId, ownerId, value) {
37
+ if (!VALUES.includes(value)) throw new Error(`a permission is ${VALUES.join(", ")}, and not "${value}"`);
38
+ const data = read();
39
+ const project = data.projects[projectId] ?? {};
40
+ project[ownerId] = { value, at: new Date().toISOString() };
41
+ data.projects[projectId] = project;
42
+ save(data);
43
+ return project[ownerId];
44
+ }
45
+
46
+ export function of(projectId, ownerId) {
47
+ return read().projects[projectId]?.[ownerId]?.value ?? DEFAULT;
48
+ }
49
+
50
+ export function list() {
51
+ const out = [];
52
+ for (const [project, owners] of Object.entries(read().projects)) {
53
+ for (const [owner, record] of Object.entries(owners)) out.push({ project, owner, ...record });
54
+ }
55
+ return out;
56
+ }
@@ -0,0 +1,77 @@
1
+ // The sessions that this owner publishes. The default is that nothing is
2
+ // published, and a session reaches the network only after `openmsg publish`.
3
+ //
4
+ // The epoch belongs to the alias. A name can move to a new session, and the
5
+ // epoch counts that move. A message for an old epoch is refused, so a message
6
+ // never lands in a session that took the name later.
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { home } from "./identity.mjs";
10
+
11
+ function file() {
12
+ return path.join(home(), "published.json");
13
+ }
14
+
15
+ export function read() {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(file(), "utf8"));
18
+ } catch {
19
+ return { version: 2, projects: {} };
20
+ }
21
+ }
22
+
23
+ function save(data) {
24
+ const target = file();
25
+ fs.mkdirSync(path.dirname(target), { recursive: true });
26
+ const tmp = `${target}.${process.pid}.tmp`;
27
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 1) + "\n");
28
+ fs.renameSync(tmp, target);
29
+ }
30
+
31
+ export function aliasOf(agent) {
32
+ return `${agent.vendor}:${agent.name ?? agent.id}`;
33
+ }
34
+
35
+ export function publish(projectId, agent) {
36
+ const data = read();
37
+ const project = data.projects[projectId] ?? {};
38
+ const alias = aliasOf(agent);
39
+ const before = project[alias];
40
+ const record = {
41
+ alias,
42
+ vendor: agent.vendor,
43
+ name: agent.name ?? agent.id,
44
+ session: agent.id,
45
+ // A new session under one name is a new epoch.
46
+ epoch: before && before.session !== agent.id ? before.epoch + 1 : (before?.epoch ?? 1),
47
+ publishedAt: new Date().toISOString(),
48
+ };
49
+ project[alias] = record;
50
+ data.projects[projectId] = project;
51
+ save(data);
52
+ return record;
53
+ }
54
+
55
+ export function unpublish(projectId, alias) {
56
+ const data = read();
57
+ const project = data.projects[projectId];
58
+ if (!project?.[alias]) return null;
59
+ const gone = project[alias];
60
+ delete project[alias];
61
+ save(data);
62
+ return gone;
63
+ }
64
+
65
+ export function list(projectId = null) {
66
+ const data = read();
67
+ const out = [];
68
+ for (const [id, project] of Object.entries(data.projects)) {
69
+ if (projectId && id !== projectId) continue;
70
+ for (const record of Object.values(project)) out.push({ project: id, ...record });
71
+ }
72
+ return out;
73
+ }
74
+
75
+ export function find(projectId, { alias = null, session = null }) {
76
+ return list(projectId).find((r) => (alias ? r.alias === alias : true) && (session ? r.session === session : true)) ?? null;
77
+ }
package/src/registry.mjs CHANGED
@@ -218,6 +218,23 @@ export async function allAgents() {
218
218
  return [...claude, ...opencode, ...codex, ...registered()];
219
219
  }
220
220
 
221
+ // Discovery of one vendor. The gateway needs the session of one published
222
+ // alias, and discovery of every vendor costs seconds, because it asks the
223
+ // operating system for the open sockets of each process.
224
+ export async function agentsOfVendor(vendor) {
225
+ if (vendor === "claude") return claudeAgents();
226
+ if (vendor === "opencode") return opencodeAgents();
227
+ if (vendor === "codex") {
228
+ const live = await codexAgents();
229
+ return live.length > 0 ? live : codexAgentsFromFiles();
230
+ }
231
+ return registered();
232
+ }
233
+
234
+ export async function findSession(vendor, id) {
235
+ return (await agentsOfVendor(vendor)).find((a) => a.id === id) ?? null;
236
+ }
237
+
221
238
  export async function findAgent(query) {
222
239
  const agents = await allAgents();
223
240
  const [vendor, name] = query.includes(":") ? [query.split(":")[0], query.split(":").slice(1).join(":")] : [null, query];