openmsg 0.4.7 → 0.5.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/README.md +1 -0
- package/package.json +1 -1
- package/src/adapters/webhook.mjs +49 -0
- package/src/cli.mjs +90 -7
- package/src/deliver.mjs +21 -0
- package/src/dirsync.mjs +2 -2
- package/src/gateway.mjs +61 -5
- package/src/published.mjs +22 -0
- package/src/registry.mjs +9 -1
- package/src/relaylink.mjs +25 -1
- package/src/settings.mjs +19 -0
- package/src/webhooks.mjs +95 -0
- package/src/wsframe.mjs +10 -0
package/README.md
CHANGED
|
@@ -38,6 +38,7 @@ An address is `<vendor>:<name>`, for example `claude:api-worker`.
|
|
|
38
38
|
| OpenCode | 2.x: `POST /api/session/{id}/prompt` on the shared service, with the password from `~/.local/state/opencode/service.json`. 1.x: `POST /session/{id}/prompt_async` | Works both ways, tested live with 2.2.6 |
|
|
39
39
|
| Cursor CLI | A hook reads the mailbox at the end of each turn | Written, tested with fixtures. A live test needs `CURSOR_API_KEY` |
|
|
40
40
|
| Gemini CLI | The same hook, as an AfterAgent deny | Written, tested with fixtures. Gemini CLI is not installed here |
|
|
41
|
+
| An agent that wakes on an HTTP request | `openmsg webhook add <name> <url>`. The request carries a notice with no text of the sender, and the agent reads the message with `openmsg inbox` | Works, tested live with a hosted bot on its own machine, through a relay on a private network |
|
|
41
42
|
| Other agents | `tmux send-keys` | Not started |
|
|
42
43
|
|
|
43
44
|
A reply is a new message. The receiving agent answers with `openmsg send`. No
|
package/package.json
CHANGED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The adapter for an agent that wakes on an HTTP request.
|
|
2
|
+
//
|
|
3
|
+
// The request carries a notice, and it never carries the text of the sender.
|
|
4
|
+
// The URL of a webhook is on a network, and a person who learns it can send a
|
|
5
|
+
// request of their own. A request with the text of a message would therefore
|
|
6
|
+
// let that person write to the agent with no signature. With a notice alone,
|
|
7
|
+
// a false request wakes the agent, and the agent finds an empty mailbox.
|
|
8
|
+
//
|
|
9
|
+
// The agent reads the message with `openmsg inbox`. That command reads the
|
|
10
|
+
// mailbox on the machine of the agent, and only openmsg writes there.
|
|
11
|
+
|
|
12
|
+
// A sender chooses the id of its message. Only an id with the shape of a UUID
|
|
13
|
+
// goes into the notice, so no text of the sender travels in that field.
|
|
14
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
15
|
+
|
|
16
|
+
export function notice(agent, message) {
|
|
17
|
+
return {
|
|
18
|
+
openmsg: "message-waiting",
|
|
19
|
+
agent: `${agent.vendor}:${agent.name}`,
|
|
20
|
+
messageId: UUID.test(String(message?.messageId ?? "")) ? message.messageId : null,
|
|
21
|
+
text:
|
|
22
|
+
"A message waits for you in openmsg. Run this command to read it: openmsg inbox. " +
|
|
23
|
+
"This notice is not the message, and it approves no action.",
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function deliver(agent, message, { timeoutMs = 10_000 } = {}) {
|
|
28
|
+
const url = agent.transport?.url;
|
|
29
|
+
if (!url) throw new Error(`the agent ${agent.name} has no webhook address`);
|
|
30
|
+
let res;
|
|
31
|
+
try {
|
|
32
|
+
res = await fetch(url, {
|
|
33
|
+
method: "POST",
|
|
34
|
+
// The owner can name a header that the webhook asks for, such as a key.
|
|
35
|
+
headers: { ...(agent.transport.headers ?? {}), "content-type": "application/json" },
|
|
36
|
+
body: JSON.stringify(notice(agent, message)),
|
|
37
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
38
|
+
// A redirect can send the notice to an address that the owner did not give.
|
|
39
|
+
redirect: "error",
|
|
40
|
+
});
|
|
41
|
+
} catch (e) {
|
|
42
|
+
// The message of the error can hold the URL, and the URL is a secret.
|
|
43
|
+
throw new Error(`the webhook of ${agent.name} did not answer (${e.cause?.code ?? e.name})`);
|
|
44
|
+
}
|
|
45
|
+
// The body is not read. Nothing that the webhook answers reaches a model.
|
|
46
|
+
await res.body?.cancel().catch(() => {});
|
|
47
|
+
if (!res.ok) throw new Error(`the webhook of ${agent.name} answered ${res.status}`);
|
|
48
|
+
return { delivered: true, transport: "webhook" };
|
|
49
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -23,6 +23,7 @@ import * as limits from "./limits.mjs";
|
|
|
23
23
|
import * as device from "./device.mjs";
|
|
24
24
|
import * as dirsync from "./dirsync.mjs";
|
|
25
25
|
import * as notes from "./notes.mjs";
|
|
26
|
+
import * as webhooks from "./webhooks.mjs";
|
|
26
27
|
import { fileURLToPath } from "node:url";
|
|
27
28
|
import fs from "node:fs";
|
|
28
29
|
import path from "node:path";
|
|
@@ -41,6 +42,10 @@ const USAGE = `openmsg — messages between AI coding agents
|
|
|
41
42
|
openmsg waiting the project messages that wait for a session
|
|
42
43
|
openmsg inbox [--json] [--all] show the messages for this agent
|
|
43
44
|
openmsg whoami show how this agent is addressed
|
|
45
|
+
openmsg webhook add <name> <url> name an agent that wakes on an HTTP request
|
|
46
|
+
[--header "Name: value"] a header that the webhook asks for, such as a key
|
|
47
|
+
openmsg webhook remove <name> take that agent away
|
|
48
|
+
openmsg webhook list the agents that wake on an HTTP request
|
|
44
49
|
openmsg hook <vendor> run inside a hook of claude, cursor, or gemini
|
|
45
50
|
openmsg install let every agent on this machine answer messages
|
|
46
51
|
openmsg install --hooks add the hooks for claude, cursor, and gemini
|
|
@@ -60,7 +65,9 @@ For the agents of another person, on another machine:
|
|
|
60
65
|
openmsg dir revoke <project-id> <owner-id> [--reason <text>]
|
|
61
66
|
openmsg gateway start [--port <n>] [--host <h>]
|
|
62
67
|
openmsg publish <agent> let the project reach this session
|
|
68
|
+
openmsg publish --all let the project reach every session, and each new one
|
|
63
69
|
openmsg unpublish <alias> take a session back
|
|
70
|
+
openmsg unpublish --all go back to the sessions that you named
|
|
64
71
|
openmsg permit <owner> <accept|hold|refuse>
|
|
65
72
|
openmsg held [<id>] [--text] the messages that wait for you
|
|
66
73
|
openmsg held --all every message from another person, and its state
|
|
@@ -208,10 +215,14 @@ async function cmdSend(target, text, replyTo = null, args = []) {
|
|
|
208
215
|
// "delivered" means an adapter pushed the message into the live session.
|
|
209
216
|
// "queued" means it waits in the mailbox for an agent that reads it at the
|
|
210
217
|
// end of a turn.
|
|
211
|
-
|
|
218
|
+
// The adapter of a webhook agent writes the mailbox before it sends its
|
|
219
|
+
// notice, so the agent that wakes finds the message.
|
|
220
|
+
if (!result.stored) mailbox.put(to, message, result.delivered ? "delivered" : "queued");
|
|
212
221
|
const how = result.delivered
|
|
213
222
|
? `sent to ${address(to)} over ${result.transport}`
|
|
214
|
-
:
|
|
223
|
+
: result.detail
|
|
224
|
+
? `queued for ${address(to)} in the mailbox, because ${result.detail}. That agent reads it at its next check`
|
|
225
|
+
: `queued for ${address(to)} in the mailbox. That agent reads it at the end of its next turn`;
|
|
215
226
|
console.log(`${how} (${message.messageId})`);
|
|
216
227
|
}
|
|
217
228
|
|
|
@@ -304,11 +315,67 @@ async function cmdInbox(args) {
|
|
|
304
315
|
console.log("no messages");
|
|
305
316
|
} else {
|
|
306
317
|
for (const r of rows) {
|
|
307
|
-
|
|
318
|
+
// A message for a webhook agent holds the text that a model reads: the
|
|
319
|
+
// header, the text of the sender, and the notice after it. A session
|
|
320
|
+
// of another vendor got those words from its adapter.
|
|
321
|
+
if (r.rendered) console.log(`${r.rendered}\n`);
|
|
322
|
+
else console.log(`from ${address(r.openmsg.from)} at ${r.createdAt}\n${r.parts.map((p) => p.text).join("\n")}\n`);
|
|
308
323
|
}
|
|
309
324
|
}
|
|
310
325
|
}
|
|
311
326
|
mailbox.markRead(me, rows.map((r) => r.messageId));
|
|
327
|
+
await acknowledgeRead(rows);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// A read of the mailbox is an event from the agent, and rule 1 of section 8
|
|
331
|
+
// of the spec of 0.2 gives it the state "agent-acknowledged". Only a message
|
|
332
|
+
// from another person has a row in that store.
|
|
333
|
+
async function acknowledgeRead(rows) {
|
|
334
|
+
for (const r of rows) {
|
|
335
|
+
if (r.openmsg?.version !== remote.VERSION) continue;
|
|
336
|
+
const row = inbound.find(r.messageId);
|
|
337
|
+
if (!row || !["queued", "adapter-accepted"].includes(row.status)) continue;
|
|
338
|
+
inbound.setStatus(row.messageId, "agent-acknowledged");
|
|
339
|
+
// The sender learns the state when a way to it exists. A read never fails
|
|
340
|
+
// because the sender is offline.
|
|
341
|
+
await gateway.reportState(row, "agent-acknowledged").catch(() => {});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function cmdWebhook(args) {
|
|
346
|
+
// --header can come more than one time, and each one takes the next word.
|
|
347
|
+
const headers = [];
|
|
348
|
+
const words = [];
|
|
349
|
+
for (let i = 0; i < args.length; i++) {
|
|
350
|
+
if (args[i] === "--header") {
|
|
351
|
+
if (args[i + 1] === undefined) throw new Error('--header needs a value, such as "Authorization: Bearer <key>"');
|
|
352
|
+
headers.push(args[++i]);
|
|
353
|
+
} else words.push(args[i]);
|
|
354
|
+
}
|
|
355
|
+
const [sub, name, url] = words;
|
|
356
|
+
if (sub === "add") {
|
|
357
|
+
if (!name || !url) throw new Error('usage: openmsg webhook add <name> <url> [--header "Name: value"]');
|
|
358
|
+
const row = webhooks.add(name, url, { headers });
|
|
359
|
+
console.log(`webhook:${row.name} wakes on a request to the address that you gave`);
|
|
360
|
+
const names = Object.keys(row.headers);
|
|
361
|
+
if (names.length > 0) console.log(`Each request carries the header ${names.join(", ")}. Its value is a secret too.`);
|
|
362
|
+
console.log("That address is a secret. A person who holds it can wake the agent, and cannot write to it.");
|
|
363
|
+
console.log(`The agent names itself with: export OPENMSG_SELF=webhook:${row.name}`);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
if (sub === "remove") {
|
|
367
|
+
if (!name) throw new Error("usage: openmsg webhook remove <name>");
|
|
368
|
+
console.log(webhooks.remove(name) ? `webhook:${name} is gone` : `no agent webhook:${name}`);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (sub === undefined || sub === "list") {
|
|
372
|
+
const rows = webhooks.agents();
|
|
373
|
+
if (rows.length === 0) console.log("no agent wakes on an HTTP request. Run: openmsg webhook add <name> <url>");
|
|
374
|
+
// The host shows which service takes the notice. The path holds the secret.
|
|
375
|
+
for (const a of rows) console.log(`${address(a)} ${new URL(a.transport.url).host}`);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
throw new Error("usage: openmsg webhook add <name> <url> | webhook remove <name> | webhook list");
|
|
312
379
|
}
|
|
313
380
|
|
|
314
381
|
// --- version 0.2: identity, invitations, and the directory ----------------
|
|
@@ -628,7 +695,8 @@ async function cmdGateway(args) {
|
|
|
628
695
|
}
|
|
629
696
|
console.log(`gateway of ${me.label} (${me.ownerId}) listens on ${running.url}`);
|
|
630
697
|
const rows = published.list();
|
|
631
|
-
|
|
698
|
+
for (const id of published.openProjects()) stamp(`every session of this machine is published in ${id}`);
|
|
699
|
+
if (rows.length === 0 && published.openProjects().length === 0) console.log("nothing is published. Run: openmsg publish <agent>");
|
|
632
700
|
for (const r of rows) console.log(`published ${r.alias} · project ${r.project} · epoch ${r.epoch}`);
|
|
633
701
|
const stop = () => {
|
|
634
702
|
console.log("gateway stopped");
|
|
@@ -640,9 +708,18 @@ async function cmdGateway(args) {
|
|
|
640
708
|
|
|
641
709
|
async function cmdPublish(args) {
|
|
642
710
|
const [query] = positional(args, ["project"]);
|
|
711
|
+
if (args.includes("--all")) {
|
|
712
|
+
const project = projectId(args);
|
|
713
|
+
published.setOpen(project, true);
|
|
714
|
+
console.log(`every session of this machine can be reached in ${project}, and each new session too`);
|
|
715
|
+
console.log("A member of that project can write to each of them. Your permission for each sender still holds.");
|
|
716
|
+
console.log("Stop it: openmsg unpublish --all. A gateway that runs takes the change at once.");
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
643
719
|
if (!query) {
|
|
644
720
|
const rows = published.list();
|
|
645
|
-
|
|
721
|
+
for (const id of published.openProjects()) console.log(`${"every session".padEnd(28)} ${id} each session that runs, and each new one`);
|
|
722
|
+
if (rows.length === 0 && published.openProjects().length === 0) console.log("nothing is published");
|
|
646
723
|
for (const r of rows) console.log(`${r.alias.padEnd(28)} ${r.project} epoch ${r.epoch} session ${r.session}`);
|
|
647
724
|
return;
|
|
648
725
|
}
|
|
@@ -654,6 +731,11 @@ async function cmdPublish(args) {
|
|
|
654
731
|
|
|
655
732
|
function cmdUnpublish(args) {
|
|
656
733
|
const project = projectId(args);
|
|
734
|
+
if (args.includes("--all")) {
|
|
735
|
+
const was = published.setOpen(project, false);
|
|
736
|
+
console.log(was ? `only the sessions that you named are published in ${project} now` : `${project} did not take every session`);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
657
739
|
const [alias] = positional(args, ["project"]);
|
|
658
740
|
const gone = published.unpublish(project, alias);
|
|
659
741
|
console.log(gone ? `${alias} is not published any more` : `${alias} was not published in ${project}`);
|
|
@@ -815,7 +897,7 @@ function cmdInvite(args) {
|
|
|
815
897
|
label: flag(rest, "project"),
|
|
816
898
|
projectId: flag(rest, "project-id"),
|
|
817
899
|
hours: Number(flag(rest, "hours") ?? invite.DEFAULT_HOURS),
|
|
818
|
-
endpoint: flag(rest, "endpoint") ?? gateway.
|
|
900
|
+
endpoint: flag(rest, "endpoint") ?? gateway.advertised(),
|
|
819
901
|
});
|
|
820
902
|
console.log(`project ${out.project.id} (${out.project.label})`);
|
|
821
903
|
console.log(`fingerprint ${out.fingerprint}`);
|
|
@@ -840,7 +922,7 @@ function cmdInvite(args) {
|
|
|
840
922
|
if (sub === "accept") {
|
|
841
923
|
const [token] = positional(rest, ["fingerprint", "endpoint"]);
|
|
842
924
|
const out = invite.accept(token, flag(rest, "fingerprint"), {
|
|
843
|
-
endpoint: flag(rest, "endpoint") ?? gateway.
|
|
925
|
+
endpoint: flag(rest, "endpoint") ?? gateway.advertised(),
|
|
844
926
|
});
|
|
845
927
|
console.log(`${out.peer.ownerId} (${out.peer.label}) is now a member of ${out.project.id}`);
|
|
846
928
|
if (out.reply) {
|
|
@@ -1001,6 +1083,7 @@ try {
|
|
|
1001
1083
|
else if (cmd === "id") cmdId(args);
|
|
1002
1084
|
else if (cmd === "invite") cmdInvite(args);
|
|
1003
1085
|
else if (cmd === "dir") await cmdDir(args);
|
|
1086
|
+
else if (cmd === "webhook") cmdWebhook(args);
|
|
1004
1087
|
else if (cmd === "whoami") console.log(address(await self()));
|
|
1005
1088
|
else console.log(USAGE);
|
|
1006
1089
|
} catch (e) {
|
package/src/deliver.mjs
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
import * as claude from "./adapters/claude.mjs";
|
|
5
5
|
import * as opencode from "./adapters/opencode.mjs";
|
|
6
6
|
import * as codex from "./adapters/codex.mjs";
|
|
7
|
+
import * as webhook from "./adapters/webhook.mjs";
|
|
8
|
+
import * as mailbox from "./mailbox.mjs";
|
|
7
9
|
import { layoutOf, compose, bodyRange } from "./envelope.mjs";
|
|
8
10
|
|
|
9
11
|
// `parts` is the layout of the text that the model reads: the frame and the text
|
|
@@ -28,7 +30,26 @@ export async function deliverLocal(agent, message, { text = null, parts = null }
|
|
|
28
30
|
}
|
|
29
31
|
if (agent.vendor === "opencode") return opencode.deliver(agent, message, parts ? { layout: parts } : { text });
|
|
30
32
|
if (agent.vendor === "codex") return codex.deliver(agent, message, { text: plain, highlight: parts ? bodyRange(parts) : null });
|
|
33
|
+
if (agent.vendor === "webhook") return wake(agent, message, plain);
|
|
31
34
|
// An agent with no push entry point, such as Gemini CLI or Cursor CLI, reads
|
|
32
35
|
// its mailbox at the end of a turn. The message waits there.
|
|
33
36
|
return { delivered: false, transport: "mailbox" };
|
|
34
37
|
}
|
|
38
|
+
|
|
39
|
+
// An agent that wakes on an HTTP request. The message goes to the mailbox
|
|
40
|
+
// first, with the text that the model reads, and the request goes after it.
|
|
41
|
+
// The agent that wakes therefore always finds the message. `stored` tells the
|
|
42
|
+
// caller that the mailbox holds the message already.
|
|
43
|
+
async function wake(agent, message, rendered) {
|
|
44
|
+
// A message that arrives a second time, before the agent read the first
|
|
45
|
+
// copy, does not go to the mailbox twice. The agent still gets a new notice.
|
|
46
|
+
const waits = mailbox.list(agent, { unreadOnly: true }).some((m) => m.messageId === message.messageId);
|
|
47
|
+
if (!waits) mailbox.put(agent, { ...message, rendered }, "queued");
|
|
48
|
+
try {
|
|
49
|
+
return { ...(await webhook.deliver(agent, message)), stored: true };
|
|
50
|
+
} catch (e) {
|
|
51
|
+
// A notice that failed loses no message. The message waits in the mailbox,
|
|
52
|
+
// and the agent reads it at its next check.
|
|
53
|
+
return { delivered: false, transport: "mailbox", stored: true, detail: e.message };
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/dirsync.mjs
CHANGED
|
@@ -24,7 +24,7 @@ import * as identity from "./identity.mjs";
|
|
|
24
24
|
import * as device from "./device.mjs";
|
|
25
25
|
import * as directory from "./directory.mjs";
|
|
26
26
|
import * as permissions from "./permissions.mjs";
|
|
27
|
-
import { settings } from "./settings.mjs";
|
|
27
|
+
import { settings, advertised } from "./settings.mjs";
|
|
28
28
|
|
|
29
29
|
export const KINDS = ["self", "roster", "revoke-device"];
|
|
30
30
|
export const MAX_RECORD_BYTES = 16 * 1024;
|
|
@@ -52,7 +52,7 @@ export function selfRecord(project) {
|
|
|
52
52
|
owner: me.ownerId,
|
|
53
53
|
label: me.label,
|
|
54
54
|
keys: me.keys,
|
|
55
|
-
endpoint:
|
|
55
|
+
endpoint: advertised(),
|
|
56
56
|
at: new Date().toISOString(),
|
|
57
57
|
});
|
|
58
58
|
}
|
package/src/gateway.mjs
CHANGED
|
@@ -31,7 +31,7 @@ import * as relaylink from "./relaylink.mjs";
|
|
|
31
31
|
import * as limits from "./limits.mjs";
|
|
32
32
|
import * as device from "./device.mjs";
|
|
33
33
|
import * as dirsync from "./dirsync.mjs";
|
|
34
|
-
import { settings, saveSettings, endpointFor } from "./settings.mjs";
|
|
34
|
+
import { settings, saveSettings, endpointFor, advertised } from "./settings.mjs";
|
|
35
35
|
|
|
36
36
|
export const PATHS = {
|
|
37
37
|
message: "/openmsg/v2/message",
|
|
@@ -45,7 +45,7 @@ export const REQUEST_WINDOW_MS = 120_000;
|
|
|
45
45
|
|
|
46
46
|
// --- the address of this gateway -----------------------------------------
|
|
47
47
|
|
|
48
|
-
export { settings, saveSettings, endpointFor };
|
|
48
|
+
export { settings, saveSettings, endpointFor, advertised };
|
|
49
49
|
|
|
50
50
|
// --- signatures on a request and on an answer ------------------------------
|
|
51
51
|
|
|
@@ -84,11 +84,67 @@ async function liveAgents(vendor, { maxAgeMs = 5000 } = {}) {
|
|
|
84
84
|
return rows;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
// The vendors whose sessions an open project reaches. OPENMSG_OPEN_VENDORS
|
|
88
|
+
// holds another list, with a comma between the names. A webhook agent is not
|
|
89
|
+
// a session, so its owner publishes it by name.
|
|
90
|
+
function openVendors() {
|
|
91
|
+
const named = process.env.OPENMSG_OPEN_VENDORS;
|
|
92
|
+
return named ? named.split(",").map((v) => v.trim()).filter(Boolean) : ["claude", "codex", "opencode", "cursor", "gemini"];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// A row for a session that the owner did not name, in a project that takes
|
|
96
|
+
// every session. Its epoch is 1, because the session id names it, and a new
|
|
97
|
+
// session under the same name has another id.
|
|
98
|
+
function openRow(projectId, agent) {
|
|
99
|
+
return {
|
|
100
|
+
project: projectId,
|
|
101
|
+
alias: published.aliasOf(agent),
|
|
102
|
+
vendor: agent.vendor,
|
|
103
|
+
name: agent.name ?? agent.id,
|
|
104
|
+
session: agent.id,
|
|
105
|
+
epoch: 1,
|
|
106
|
+
open: true,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Every row of a project: the sessions that the owner named, and, in an open
|
|
111
|
+
// project, each other session that runs now. A background session, such as a
|
|
112
|
+
// program that uses the SDK, is not a session of a person, and it stays out.
|
|
113
|
+
async function rowsOf(projectId) {
|
|
114
|
+
const rows = published.list(projectId);
|
|
115
|
+
if (!published.isOpen(projectId)) return rows;
|
|
116
|
+
const sessions = new Set(rows.map((r) => r.session));
|
|
117
|
+
const aliases = new Set(rows.map((r) => r.alias));
|
|
118
|
+
for (const vendor of openVendors()) {
|
|
119
|
+
for (const agent of await liveAgents(vendor)) {
|
|
120
|
+
if (agent.vendor !== vendor || agent.background) continue;
|
|
121
|
+
// A name that the owner published holds its session and its epoch.
|
|
122
|
+
if (sessions.has(agent.id) || aliases.has(published.aliasOf(agent))) continue;
|
|
123
|
+
sessions.add(agent.id);
|
|
124
|
+
rows.push(openRow(projectId, agent));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return rows;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The row of one session. The envelope names the vendor of its target, so an
|
|
131
|
+
// open project asks one vendor, and not all of them.
|
|
132
|
+
async function rowOf(projectId, session, vendorHint = null) {
|
|
133
|
+
const named = published.find(projectId, { session });
|
|
134
|
+
if (named || !published.isOpen(projectId)) return named;
|
|
135
|
+
const vendors = openVendors();
|
|
136
|
+
for (const vendor of vendorHint && vendors.includes(vendorHint) ? [vendorHint] : vendors) {
|
|
137
|
+
const agent = (await liveAgents(vendor, { maxAgeMs: 0 })).find((a) => a.vendor === vendor && a.id === session && !a.background);
|
|
138
|
+
if (agent) return published.find(projectId, { alias: published.aliasOf(agent) }) ? null : openRow(projectId, agent);
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
87
143
|
// The two descriptions of section 9.4 of the spec. Presence is for a person,
|
|
88
144
|
// and routing data is for a gateway. Neither one carries a working directory,
|
|
89
145
|
// a socket path, or a token.
|
|
90
146
|
export async function descriptions(projectId) {
|
|
91
|
-
const rows =
|
|
147
|
+
const rows = await rowsOf(projectId);
|
|
92
148
|
const byVendor = new Map();
|
|
93
149
|
for (const vendor of new Set(rows.map((r) => r.vendor))) byVendor.set(vendor, await liveAgents(vendor));
|
|
94
150
|
const presence = [];
|
|
@@ -130,7 +186,7 @@ async function handleRouting(request) {
|
|
|
130
186
|
label: me.label,
|
|
131
187
|
project: projectId,
|
|
132
188
|
at: new Date().toISOString(),
|
|
133
|
-
endpoint:
|
|
189
|
+
endpoint: advertised(),
|
|
134
190
|
presence,
|
|
135
191
|
routing,
|
|
136
192
|
}),
|
|
@@ -249,7 +305,7 @@ export async function release(record, { deliver = deliverLocal, now = Date.now()
|
|
|
249
305
|
}
|
|
250
306
|
if (!(Date.parse(record.expiresAt) > now)) return stop("expired", `the deadline passed at ${record.expiresAt}`);
|
|
251
307
|
|
|
252
|
-
const mine =
|
|
308
|
+
const mine = await rowOf(record.project, record.target.session, record.message?.openmsg?.to?.vendor ?? null);
|
|
253
309
|
if (!mine) return stop("not-published", "that session is not published in this project");
|
|
254
310
|
if (record.target.epoch !== mine.epoch) {
|
|
255
311
|
return stop("old-epoch", `the message names epoch ${record.target.epoch}, and the session runs epoch ${mine.epoch}`);
|
package/src/published.mjs
CHANGED
|
@@ -62,6 +62,28 @@ export function unpublish(projectId, alias) {
|
|
|
62
62
|
return gone;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
// An owner can select every session of the machine for one project. Each
|
|
66
|
+
// session that runs then, and each new session, is published there. The owner
|
|
67
|
+
// types that choice, and nothing else turns it on.
|
|
68
|
+
export function setOpen(projectId, on) {
|
|
69
|
+
const data = read();
|
|
70
|
+
const open = data.open ?? {};
|
|
71
|
+
const was = Boolean(open[projectId]);
|
|
72
|
+
if (on) open[projectId] = { at: open[projectId]?.at ?? new Date().toISOString() };
|
|
73
|
+
else delete open[projectId];
|
|
74
|
+
data.open = open;
|
|
75
|
+
save(data);
|
|
76
|
+
return was;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function isOpen(projectId) {
|
|
80
|
+
return Boolean(read().open?.[projectId]);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function openProjects() {
|
|
84
|
+
return Object.keys(read().open ?? {});
|
|
85
|
+
}
|
|
86
|
+
|
|
65
87
|
export function list(projectId = null) {
|
|
66
88
|
const data = read();
|
|
67
89
|
const out = [];
|
package/src/registry.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import { execFile } from "node:child_process";
|
|
7
7
|
import { registered } from "./selfregistry.mjs";
|
|
8
|
+
import { agents as webhookAgents } from "./webhooks.mjs";
|
|
8
9
|
import { promisify } from "node:util";
|
|
9
10
|
|
|
10
11
|
const run = promisify(execFile);
|
|
@@ -435,7 +436,8 @@ export async function allAgents() {
|
|
|
435
436
|
codexAgents(),
|
|
436
437
|
]);
|
|
437
438
|
// An agent with no push entry point reports itself from its hook.
|
|
438
|
-
|
|
439
|
+
// An agent that wakes on an HTTP request has no session. Its owner named it.
|
|
440
|
+
return [...claude, ...opencode, ...codex, ...registered(), ...webhookAgents()];
|
|
439
441
|
}
|
|
440
442
|
|
|
441
443
|
// Discovery of one vendor. The gateway needs the session of one published
|
|
@@ -448,6 +450,7 @@ export async function agentsOfVendor(vendor) {
|
|
|
448
450
|
const live = await codexAgents();
|
|
449
451
|
return live.length > 0 ? live : codexAgentsFromFiles();
|
|
450
452
|
}
|
|
453
|
+
if (vendor === "webhook") return webhookAgents();
|
|
451
454
|
return registered();
|
|
452
455
|
}
|
|
453
456
|
|
|
@@ -528,6 +531,11 @@ export async function self() {
|
|
|
528
531
|
// reply that pins the session id of the sender fails.
|
|
529
532
|
if (process.env.OPENMSG_SELF) {
|
|
530
533
|
const value = process.env.OPENMSG_SELF;
|
|
534
|
+
// A webhook agent is in one file, so its lookup asks no vendor.
|
|
535
|
+
if (value.startsWith("webhook:")) {
|
|
536
|
+
const known = webhookAgents().find((a) => `webhook:${a.name}` === value);
|
|
537
|
+
if (known) return known;
|
|
538
|
+
}
|
|
531
539
|
try {
|
|
532
540
|
return await findAgent(value);
|
|
533
541
|
} catch {
|
package/src/relaylink.mjs
CHANGED
|
@@ -214,28 +214,52 @@ export async function open(url, handlers = {}) {
|
|
|
214
214
|
|
|
215
215
|
// The gateway keeps the connection. A relay that stops, or a network that
|
|
216
216
|
// fails, gives a wait that grows, and the gateway tries again.
|
|
217
|
-
|
|
217
|
+
//
|
|
218
|
+
// A connection can also stop with no sign: the relay restarts behind a
|
|
219
|
+
// private network, or its machine sleeps, and no FIN arrives. The gateway
|
|
220
|
+
// then holds a connection that carries nothing, and every message for it
|
|
221
|
+
// waits at the relay. The gateway therefore sends a ping at an interval. A
|
|
222
|
+
// relay that sends no frame for two and a half intervals is gone, and the
|
|
223
|
+
// gateway drops the connection and connects again.
|
|
224
|
+
export const HEARTBEAT_MS = 20_000;
|
|
225
|
+
|
|
226
|
+
export async function keep(url, handlers = {}, { heartbeatMs = HEARTBEAT_MS } = {}) {
|
|
218
227
|
let link = null;
|
|
219
228
|
let stopped = false;
|
|
220
229
|
let wait = 1000;
|
|
230
|
+
let beat = null;
|
|
221
231
|
const holder = {
|
|
222
232
|
get link() {
|
|
223
233
|
return link;
|
|
224
234
|
},
|
|
225
235
|
stop() {
|
|
226
236
|
stopped = true;
|
|
237
|
+
clearInterval(beat);
|
|
227
238
|
link?.close();
|
|
228
239
|
},
|
|
229
240
|
};
|
|
241
|
+
const watch = (current) => {
|
|
242
|
+
let seen = Date.now();
|
|
243
|
+
current.connection.on("message", () => {
|
|
244
|
+
seen = Date.now();
|
|
245
|
+
});
|
|
246
|
+
clearInterval(beat);
|
|
247
|
+
beat = setInterval(() => {
|
|
248
|
+
if (Date.now() - seen > heartbeatMs * 2.5) current.connection.drop();
|
|
249
|
+
else current.connection.send(JSON.stringify({ type: "ping" }));
|
|
250
|
+
}, heartbeatMs);
|
|
251
|
+
};
|
|
230
252
|
const again = async () => {
|
|
231
253
|
if (stopped) return;
|
|
232
254
|
try {
|
|
233
255
|
link = await open(url, { ...handlers, onClose: () => {
|
|
256
|
+
clearInterval(beat);
|
|
234
257
|
handlers.onClose?.();
|
|
235
258
|
link = null;
|
|
236
259
|
if (!stopped) setTimeout(again, wait);
|
|
237
260
|
} });
|
|
238
261
|
wait = 1000;
|
|
262
|
+
watch(link);
|
|
239
263
|
handlers.onOpen?.(link);
|
|
240
264
|
} catch (e) {
|
|
241
265
|
handlers.onError?.({ error: e.message });
|
package/src/settings.mjs
CHANGED
|
@@ -25,6 +25,25 @@ export function saveSettings(next) {
|
|
|
25
25
|
return data;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
// The address that this owner gives to other people, in an invitation, in the
|
|
29
|
+
// directory, and in the routing data. A loopback address means this machine
|
|
30
|
+
// alone. A gateway that listens there and uses a relay gives no address,
|
|
31
|
+
// because the relay is its way in. With that address in the directory, a
|
|
32
|
+
// sender on another machine writes to its own machine, and never to the relay.
|
|
33
|
+
const LOOPBACK = ["127.0.0.1", "localhost", "::1", "[::1]"];
|
|
34
|
+
|
|
35
|
+
export function advertised() {
|
|
36
|
+
const { endpoint, relay } = settings();
|
|
37
|
+
if (!endpoint) return null;
|
|
38
|
+
let host;
|
|
39
|
+
try {
|
|
40
|
+
host = new URL(endpoint).hostname;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
return relay && LOOPBACK.includes(host) ? null : endpoint;
|
|
45
|
+
}
|
|
46
|
+
|
|
28
47
|
export function endpointFor(host, port) {
|
|
29
48
|
const name = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
|
|
30
49
|
return `http://${name}:${port}`;
|
package/src/webhooks.mjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// The agents that wake on an HTTP request. Such an agent has no session that
|
|
2
|
+
// another program can write to. Its owner gives openmsg one URL, and a POST to
|
|
3
|
+
// that URL starts a turn of the agent.
|
|
4
|
+
//
|
|
5
|
+
// The URL is a secret: a person who holds it can wake the agent. The file is
|
|
6
|
+
// therefore readable by its owner only, and no command prints the URL in the
|
|
7
|
+
// routing data or in `list --json`.
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
|
|
12
|
+
// The home reads from the environment at each call, as the mailbox does.
|
|
13
|
+
function file() {
|
|
14
|
+
return path.join(process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg"), "webhooks.json");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function read() {
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(fs.readFileSync(file(), "utf8"));
|
|
20
|
+
} catch {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function save(data) {
|
|
26
|
+
fs.mkdirSync(path.dirname(file()), { recursive: true });
|
|
27
|
+
fs.writeFileSync(file(), JSON.stringify(data, null, 1), { mode: 0o600 });
|
|
28
|
+
// The mode of an existing file does not change on a write.
|
|
29
|
+
fs.chmodSync(file(), 0o600);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// A name is a part of an address, and of a file name of the mailbox.
|
|
33
|
+
const NAME = /^[a-z0-9][a-z0-9._-]{0,62}$/;
|
|
34
|
+
|
|
35
|
+
// A webhook can ask for a header, for example "Authorization: Bearer <key>".
|
|
36
|
+
// The value is a secret, as the URL is. A line break in a header starts a
|
|
37
|
+
// second header, so a value with one is refused. The error never holds the
|
|
38
|
+
// value.
|
|
39
|
+
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
|
|
40
|
+
|
|
41
|
+
export function parseHeader(line) {
|
|
42
|
+
const at = String(line ?? "").indexOf(":");
|
|
43
|
+
const name = at === -1 ? "" : line.slice(0, at).trim();
|
|
44
|
+
const value = at === -1 ? "" : line.slice(at + 1).trim();
|
|
45
|
+
if (!HEADER_NAME.test(name) || value === "" || /[\r\n\0]/.test(value)) {
|
|
46
|
+
throw new Error('a header has the shape "Name: value", on one line');
|
|
47
|
+
}
|
|
48
|
+
if (name.toLowerCase() === "content-type") throw new Error("the notice is JSON, and its content-type does not change");
|
|
49
|
+
return [name, value];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function add(name, url, { headers = [] } = {}) {
|
|
53
|
+
if (!NAME.test(String(name ?? ""))) {
|
|
54
|
+
throw new Error(`"${name}" is not a name. Use lowercase letters, digits, ".", "_", and "-"`);
|
|
55
|
+
}
|
|
56
|
+
let address;
|
|
57
|
+
try {
|
|
58
|
+
address = new URL(url);
|
|
59
|
+
} catch {
|
|
60
|
+
throw new Error(`"${url}" is not a URL`);
|
|
61
|
+
}
|
|
62
|
+
if (address.protocol !== "https:" && address.protocol !== "http:") {
|
|
63
|
+
throw new Error(`a webhook takes an http:// or https:// address, and "${url}" is neither`);
|
|
64
|
+
}
|
|
65
|
+
const extra = Object.fromEntries(headers.map(parseHeader));
|
|
66
|
+
const data = read();
|
|
67
|
+
data[name] = { url: address.href, headers: extra, addedAt: data[name]?.addedAt ?? new Date().toISOString() };
|
|
68
|
+
save(data);
|
|
69
|
+
return { name, ...data[name] };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function remove(name) {
|
|
73
|
+
const data = read();
|
|
74
|
+
if (!data[name]) return false;
|
|
75
|
+
delete data[name];
|
|
76
|
+
save(data);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The same shape that discovery gives for a session of a vendor. The name is
|
|
81
|
+
// also the id, because one name is one agent, and it has no session.
|
|
82
|
+
export function agents() {
|
|
83
|
+
return Object.entries(read()).map(([name, row]) => ({
|
|
84
|
+
vendor: "webhook",
|
|
85
|
+
id: name,
|
|
86
|
+
name,
|
|
87
|
+
pid: null,
|
|
88
|
+
cwd: null,
|
|
89
|
+
status: "waits",
|
|
90
|
+
title: "wakes on an HTTP request",
|
|
91
|
+
startedAt: null,
|
|
92
|
+
updatedAt: null,
|
|
93
|
+
transport: { kind: "webhook", url: row.url, headers: row.headers ?? {} },
|
|
94
|
+
}));
|
|
95
|
+
}
|
package/src/wsframe.mjs
CHANGED
|
@@ -54,6 +54,9 @@ export class Connection extends EventEmitter {
|
|
|
54
54
|
this.partsOpcode = null;
|
|
55
55
|
this.closed = false;
|
|
56
56
|
socket.on("data", (chunk) => this.read(chunk));
|
|
57
|
+
// A machine that sleeps, or a network that drops, sends no FIN. The
|
|
58
|
+
// operating system then asks the other side if it is there.
|
|
59
|
+
socket.setKeepAlive?.(true, 30_000);
|
|
57
60
|
// "end" arrives when the other side sends FIN. A process that stops gives
|
|
58
61
|
// FIN, and without this line the connection looks alive until the next
|
|
59
62
|
// write fails.
|
|
@@ -172,6 +175,13 @@ export class Connection extends EventEmitter {
|
|
|
172
175
|
this.end();
|
|
173
176
|
}
|
|
174
177
|
|
|
178
|
+
// The end of a connection that does not answer. A close frame to a side
|
|
179
|
+
// that is gone waits for nothing, so the socket stops at once.
|
|
180
|
+
drop() {
|
|
181
|
+
this.socket.destroy();
|
|
182
|
+
this.end();
|
|
183
|
+
}
|
|
184
|
+
|
|
175
185
|
end() {
|
|
176
186
|
if (this.closed) return;
|
|
177
187
|
this.closed = true;
|