@masons/agent-network 0.5.321 → 0.5.323

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.
Files changed (102) hide show
  1. package/dist/runtime-endpoint-client.d.ts +10 -0
  2. package/dist/runtime-endpoint-client.d.ts.map +1 -1
  3. package/dist/runtime-endpoint-client.js +79 -0
  4. package/dist/version.d.ts +1 -1
  5. package/dist/version.js +1 -1
  6. package/package.json +14 -22
  7. package/dist/broker/broker-daemon.d.ts +0 -57
  8. package/dist/broker/broker-daemon.d.ts.map +0 -1
  9. package/dist/broker/broker-daemon.js +0 -759
  10. package/dist/broker/claude-code-spawn-driver.d.ts +0 -14
  11. package/dist/broker/claude-code-spawn-driver.d.ts.map +0 -1
  12. package/dist/broker/claude-code-spawn-driver.js +0 -39
  13. package/dist/broker/closed-endpoint-lookup.d.ts +0 -25
  14. package/dist/broker/closed-endpoint-lookup.d.ts.map +0 -1
  15. package/dist/broker/closed-endpoint-lookup.js +0 -59
  16. package/dist/broker/codex-spawn-driver-stub.d.ts +0 -7
  17. package/dist/broker/codex-spawn-driver-stub.d.ts.map +0 -1
  18. package/dist/broker/codex-spawn-driver-stub.js +0 -13
  19. package/dist/broker/connector-ws.d.ts +0 -47
  20. package/dist/broker/connector-ws.d.ts.map +0 -1
  21. package/dist/broker/connector-ws.js +0 -60
  22. package/dist/broker/control-event-dispatcher.d.ts +0 -21
  23. package/dist/broker/control-event-dispatcher.d.ts.map +0 -1
  24. package/dist/broker/control-event-dispatcher.js +0 -45
  25. package/dist/broker/control-event-types.d.ts +0 -28
  26. package/dist/broker/control-event-types.d.ts.map +0 -1
  27. package/dist/broker/control-event-types.js +0 -1
  28. package/dist/broker/correlation-ring.d.ts +0 -10
  29. package/dist/broker/correlation-ring.d.ts.map +0 -1
  30. package/dist/broker/correlation-ring.js +0 -32
  31. package/dist/broker/discovery-file.d.ts +0 -12
  32. package/dist/broker/discovery-file.d.ts.map +0 -1
  33. package/dist/broker/discovery-file.js +0 -77
  34. package/dist/broker/endpoint-registry.d.ts +0 -53
  35. package/dist/broker/endpoint-registry.d.ts.map +0 -1
  36. package/dist/broker/endpoint-registry.js +0 -83
  37. package/dist/broker/endpoint-state-machine.d.ts +0 -40
  38. package/dist/broker/endpoint-state-machine.d.ts.map +0 -1
  39. package/dist/broker/endpoint-state-machine.js +0 -92
  40. package/dist/broker/entry.d.ts +0 -13
  41. package/dist/broker/entry.d.ts.map +0 -1
  42. package/dist/broker/entry.js +0 -229
  43. package/dist/broker/grace-timer.d.ts +0 -9
  44. package/dist/broker/grace-timer.d.ts.map +0 -1
  45. package/dist/broker/grace-timer.js +0 -34
  46. package/dist/broker/ipc-server.d.ts +0 -79
  47. package/dist/broker/ipc-server.d.ts.map +0 -1
  48. package/dist/broker/ipc-server.js +0 -263
  49. package/dist/broker/logger.d.ts +0 -10
  50. package/dist/broker/logger.d.ts.map +0 -1
  51. package/dist/broker/logger.js +0 -34
  52. package/dist/broker/network-presence.d.ts +0 -31
  53. package/dist/broker/network-presence.d.ts.map +0 -1
  54. package/dist/broker/network-presence.js +0 -109
  55. package/dist/broker/paths.d.ts +0 -11
  56. package/dist/broker/paths.d.ts.map +0 -1
  57. package/dist/broker/paths.js +0 -30
  58. package/dist/broker/plugin-liveness.d.ts +0 -2
  59. package/dist/broker/plugin-liveness.d.ts.map +0 -1
  60. package/dist/broker/plugin-liveness.js +0 -15
  61. package/dist/broker/received-message-correlation-cache.d.ts +0 -23
  62. package/dist/broker/received-message-correlation-cache.d.ts.map +0 -1
  63. package/dist/broker/received-message-correlation-cache.js +0 -114
  64. package/dist/broker/reconnecting-buffer.d.ts +0 -23
  65. package/dist/broker/reconnecting-buffer.d.ts.map +0 -1
  66. package/dist/broker/reconnecting-buffer.js +0 -107
  67. package/dist/broker/routing-table.d.ts +0 -22
  68. package/dist/broker/routing-table.d.ts.map +0 -1
  69. package/dist/broker/routing-table.js +0 -35
  70. package/dist/broker/runtime-endpoint-port.d.ts +0 -8
  71. package/dist/broker/runtime-endpoint-port.d.ts.map +0 -1
  72. package/dist/broker/runtime-endpoint-port.js +0 -1
  73. package/dist/broker/services-event-client.d.ts +0 -21
  74. package/dist/broker/services-event-client.d.ts.map +0 -1
  75. package/dist/broker/services-event-client.js +0 -221
  76. package/dist/broker/spawn-correlation.d.ts +0 -28
  77. package/dist/broker/spawn-correlation.d.ts.map +0 -1
  78. package/dist/broker/spawn-correlation.js +0 -77
  79. package/dist/broker/spawn-driver.d.ts +0 -27
  80. package/dist/broker/spawn-driver.d.ts.map +0 -1
  81. package/dist/broker/spawn-driver.js +0 -15
  82. package/dist/broker/task-hint-handler.d.ts +0 -21
  83. package/dist/broker/task-hint-handler.d.ts.map +0 -1
  84. package/dist/broker/task-hint-handler.js +0 -33
  85. package/dist/broker/transition-state-retry-queue.d.ts +0 -20
  86. package/dist/broker/transition-state-retry-queue.d.ts.map +0 -1
  87. package/dist/broker/transition-state-retry-queue.js +0 -48
  88. package/dist/broker/undispatched-inbox.d.ts +0 -26
  89. package/dist/broker/undispatched-inbox.d.ts.map +0 -1
  90. package/dist/broker/undispatched-inbox.js +0 -53
  91. package/dist/broker/version-handshake.d.ts +0 -30
  92. package/dist/broker/version-handshake.d.ts.map +0 -1
  93. package/dist/broker/version-handshake.js +0 -47
  94. package/dist/broker-client/broker-client.d.ts +0 -65
  95. package/dist/broker-client/broker-client.d.ts.map +0 -1
  96. package/dist/broker-client/broker-client.js +0 -165
  97. package/dist/broker-client/lazy-spawn.d.ts +0 -18
  98. package/dist/broker-client/lazy-spawn.d.ts.map +0 -1
  99. package/dist/broker-client/lazy-spawn.js +0 -61
  100. package/dist/session-lifecycle.d.ts +0 -89
  101. package/dist/session-lifecycle.d.ts.map +0 -1
  102. package/dist/session-lifecycle.js +0 -348
@@ -1,263 +0,0 @@
1
- import { createServer } from "node:http";
2
- import { WebSocket, WebSocketServer } from "ws";
3
- import { PLUGIN_VERSION } from "../version.js";
4
- import { handleInitialize, IPC_PROTOCOL_VERSION, SERVER_CAPABILITIES, } from "./version-handshake.js";
5
- export class BrokerHttpError extends Error {
6
- status;
7
- code;
8
- constructor(status, code, message) {
9
- super(message);
10
- this.name = "BrokerHttpError";
11
- this.status = status;
12
- this.code = code;
13
- }
14
- }
15
- export async function startIPCServer(opts) {
16
- const { bearerToken, handlers, logger, onChannelOpened, onChannelClosed } = opts;
17
- const http = createServer((req, res) => {
18
- void routeHttp(req, res, bearerToken, handlers, logger);
19
- });
20
- const wss = new WebSocketServer({ noServer: true });
21
- http.on("upgrade", (req, socket, head) => {
22
- if (req.url !== "/v1/stream") {
23
- socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
24
- socket.destroy();
25
- return;
26
- }
27
- if (!authorizedRequest(req, bearerToken)) {
28
- socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
29
- socket.destroy();
30
- return;
31
- }
32
- const pid = readPluginPid(req);
33
- if (pid === null) {
34
- socket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
35
- socket.destroy();
36
- return;
37
- }
38
- wss.handleUpgrade(req, socket, head, (ws) => {
39
- onChannelOpened?.(pid, ws);
40
- ws.once("close", () => onChannelClosed?.(pid, ws));
41
- wss.emit("connection", ws, req);
42
- });
43
- });
44
- await new Promise((resolve, reject) => {
45
- http.once("error", reject);
46
- http.listen(0, "127.0.0.1", () => {
47
- http.off("error", reject);
48
- resolve();
49
- });
50
- });
51
- const addr = http.address();
52
- const ipcUrl = `http://127.0.0.1:${addr.port}`;
53
- logger.info("ipc_server_listening", { ipcUrl });
54
- return {
55
- ipcUrl,
56
- port: addr.port,
57
- async close() {
58
- await closeServer(http, wss);
59
- },
60
- };
61
- }
62
- async function routeHttp(req, res, bearerToken, handlers, logger) {
63
- const url = req.url ?? "";
64
- const method = req.method ?? "GET";
65
- if (method === "GET" && url === "/health") {
66
- sendJson(res, 200, {
67
- ok: true,
68
- version: PLUGIN_VERSION,
69
- protocol_version: IPC_PROTOCOL_VERSION,
70
- capabilities: SERVER_CAPABILITIES,
71
- });
72
- return;
73
- }
74
- if (!authorizedRequest(req, bearerToken)) {
75
- sendJson(res, 401, { error: "unauthorized" });
76
- return;
77
- }
78
- try {
79
- if (method === "POST" && url === "/v1/initialize") {
80
- const body = await readJson(req);
81
- const result = handleInitialize(body);
82
- sendJson(res, result.status, result.body);
83
- return;
84
- }
85
- if (method === "POST" && url === "/v1/endpoint/register") {
86
- const body = await readJson(req);
87
- const out = await handlers.registerEndpoint(body, null);
88
- sendJson(res, 200, out);
89
- return;
90
- }
91
- const heartbeatMatch = /^\/v1\/endpoint\/([^/]+)\/heartbeat$/.exec(url);
92
- if (method === "POST" && heartbeatMatch && heartbeatMatch[1]) {
93
- await handlers.heartbeatEndpoint(decodeURIComponent(heartbeatMatch[1]));
94
- sendJson(res, 200, { ok: true });
95
- return;
96
- }
97
- const reattachMatch = /^\/v1\/endpoint\/([^/]+)\/reattach$/.exec(url);
98
- if (method === "POST" && reattachMatch && reattachMatch[1]) {
99
- const body = await readJson(req);
100
- const pid = typeof body.plugin_pid === "number" ? body.plugin_pid : Number.NaN;
101
- if (!Number.isFinite(pid) || pid <= 0) {
102
- throw new BrokerHttpError(400, "plugin_pid_invalid", "plugin_pid is required and must be a positive number");
103
- }
104
- const out = await handlers.reattachEndpoint(decodeURIComponent(reattachMatch[1]), pid, null);
105
- sendJson(res, 200, out);
106
- return;
107
- }
108
- const unregisterMatch = /^\/v1\/endpoint\/([^/]+)$/.exec(url);
109
- if (method === "DELETE" && unregisterMatch && unregisterMatch[1]) {
110
- await handlers.unregisterEndpoint(decodeURIComponent(unregisterMatch[1]));
111
- sendJson(res, 200, { ok: true });
112
- return;
113
- }
114
- if (method === "POST" && url === "/v1/send") {
115
- const body = await readJson(req);
116
- const out = await handlers.send(body);
117
- sendJson(res, 200, out);
118
- return;
119
- }
120
- if (method === "GET" && url === "/v1/undispatched") {
121
- const items = await handlers.listUndispatched();
122
- sendJson(res, 200, { items });
123
- return;
124
- }
125
- if (method === "POST" && url === "/v1/dispatch") {
126
- const body = await readJson(req);
127
- const uid = typeof body.undispatched_id === "string"
128
- ? body.undispatched_id
129
- : undefined;
130
- const tid = typeof body.target_endpoint_id === "string"
131
- ? body.target_endpoint_id
132
- : undefined;
133
- if (!uid || !tid) {
134
- throw new BrokerHttpError(400, "dispatch_body_invalid", "POST /v1/dispatch requires { undispatched_id, target_endpoint_id }");
135
- }
136
- await handlers.dispatch(uid, tid);
137
- sendJson(res, 200, { ok: true });
138
- return;
139
- }
140
- const taskHintMatch = /^\/v1\/endpoint\/([^/]+)\/task-hint$/.exec(url);
141
- if (method === "POST" && taskHintMatch && taskHintMatch[1]) {
142
- const endpointId = decodeURIComponent(taskHintMatch[1]);
143
- const body = await readJson(req);
144
- const pid = typeof body.plugin_pid === "number" ? body.plugin_pid : Number.NaN;
145
- if (!Number.isFinite(pid) || pid <= 0) {
146
- throw new BrokerHttpError(400, "plugin_pid_invalid", "plugin_pid is required and must be a positive number");
147
- }
148
- const hint = typeof body.task_hint === "string" ? body.task_hint : undefined;
149
- if (hint === undefined) {
150
- throw new BrokerHttpError(400, "task_hint_invalid", "task_hint is required and must be a string");
151
- }
152
- await handlers.setTaskHint({
153
- endpoint_id: endpointId,
154
- plugin_pid: pid,
155
- task_hint: hint,
156
- });
157
- sendJson(res, 200, { ok: true });
158
- return;
159
- }
160
- sendJson(res, 404, { error: "not_found", path: url });
161
- }
162
- catch (err) {
163
- if (err instanceof BrokerHttpError) {
164
- logger.info("ipc_route_rejected", {
165
- url,
166
- method,
167
- status: err.status,
168
- code: err.code,
169
- message: err.message,
170
- });
171
- sendJson(res, err.status, { error: err.code, message: err.message });
172
- return;
173
- }
174
- logger.error("ipc_route_error", {
175
- url,
176
- method,
177
- err: err instanceof Error ? err.message : String(err),
178
- });
179
- sendJson(res, 500, {
180
- error: "internal_error",
181
- message: err instanceof Error ? err.message : "unknown",
182
- });
183
- }
184
- }
185
- function authorizedRequest(req, bearerToken) {
186
- const header = req.headers.authorization;
187
- if (typeof header !== "string")
188
- return false;
189
- const trimmed = header.startsWith("Bearer ")
190
- ? header.slice("Bearer ".length)
191
- : header;
192
- return constantTimeEquals(trimmed, bearerToken);
193
- }
194
- function readPluginPid(req) {
195
- const raw = req.headers["x-plugin-pid"];
196
- const str = Array.isArray(raw) ? raw[0] : raw;
197
- if (!str)
198
- return null;
199
- const n = Number.parseInt(str, 10);
200
- return Number.isFinite(n) && n > 0 ? n : null;
201
- }
202
- function constantTimeEquals(a, b) {
203
- if (a.length !== b.length)
204
- return false;
205
- let mismatch = 0;
206
- for (let i = 0; i < a.length; i++) {
207
- mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
208
- }
209
- return mismatch === 0;
210
- }
211
- async function readJson(req) {
212
- return new Promise((resolve, reject) => {
213
- const chunks = [];
214
- let total = 0;
215
- const MAX = 1 * 1024 * 1024;
216
- req.on("data", (chunk) => {
217
- const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
218
- total += buf.length;
219
- if (total > MAX) {
220
- reject(new Error("request body too large"));
221
- req.destroy();
222
- return;
223
- }
224
- chunks.push(buf);
225
- });
226
- req.on("end", () => {
227
- try {
228
- const raw = Buffer.concat(chunks).toString("utf8");
229
- resolve(raw.length === 0 ? {} : JSON.parse(raw));
230
- }
231
- catch (err) {
232
- reject(err instanceof Error ? err : new Error(String(err)));
233
- }
234
- });
235
- req.on("error", reject);
236
- });
237
- }
238
- function sendJson(res, status, body) {
239
- res.statusCode = status;
240
- res.setHeader("Content-Type", "application/json; charset=utf-8");
241
- res.end(JSON.stringify(body));
242
- }
243
- async function closeServer(http, wss) {
244
- await new Promise((resolve) => {
245
- wss.close(() => resolve());
246
- });
247
- await new Promise((resolve, reject) => {
248
- http.close((err) => (err ? reject(err) : resolve()));
249
- });
250
- }
251
- export function pushToPlugin(ws, event) {
252
- if (ws.readyState !== WebSocket.OPEN)
253
- return;
254
- ws.send(JSON.stringify(event));
255
- }
256
- export function parsePluginFrame(data) {
257
- try {
258
- return JSON.parse(data.toString());
259
- }
260
- catch {
261
- return null;
262
- }
263
- }
@@ -1,10 +0,0 @@
1
- export type LogLevel = "debug" | "info" | "warn" | "error";
2
- export interface BrokerLogger {
3
- debug(msg: string, fields?: Record<string, unknown>): void;
4
- info(msg: string, fields?: Record<string, unknown>): void;
5
- warn(msg: string, fields?: Record<string, unknown>): void;
6
- error(msg: string, fields?: Record<string, unknown>): void;
7
- }
8
- export declare function createBrokerLogger(logDir: string): BrokerLogger;
9
- export declare function createNullLogger(): BrokerLogger;
10
- //# sourceMappingURL=logger.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/broker/logger.ts"],"names":[],"mappings":"AAaA,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAE3D,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC3D,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1D,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1D,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC5D;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CA6B/D;AAGD,wBAAgB,gBAAgB,IAAI,YAAY,CAO/C"}
@@ -1,34 +0,0 @@
1
- import { appendFileSync, mkdirSync } from "node:fs";
2
- import { join } from "node:path";
3
- export function createBrokerLogger(logDir) {
4
- mkdirSync(logDir, { recursive: true, mode: 0o700 });
5
- const path = join(logDir, `broker-${process.pid}.log`);
6
- const write = (level, msg, fields) => {
7
- const line = JSON.stringify({
8
- ts: new Date().toISOString(),
9
- level,
10
- pid: process.pid,
11
- msg,
12
- ...fields,
13
- });
14
- try {
15
- appendFileSync(path, `${line}\n`);
16
- }
17
- catch {
18
- }
19
- };
20
- return {
21
- debug: (msg, fields) => write("debug", msg, fields),
22
- info: (msg, fields) => write("info", msg, fields),
23
- warn: (msg, fields) => write("warn", msg, fields),
24
- error: (msg, fields) => write("error", msg, fields),
25
- };
26
- }
27
- export function createNullLogger() {
28
- return {
29
- debug: () => { },
30
- info: () => { },
31
- warn: () => { },
32
- error: () => { },
33
- };
34
- }
@@ -1,31 +0,0 @@
1
- export declare const DEFAULT_PRESENCE_GRACE_MS: number;
2
- export type NetworkPresence = "online" | "reconnecting" | "offline";
3
- export type PresenceEvent = {
4
- type: "connector_connected";
5
- } | {
6
- type: "connector_disconnected";
7
- } | {
8
- type: "presence_grace_expired";
9
- } | {
10
- type: "shutdown";
11
- };
12
- export type PresenceEffect = {
13
- type: "start_grace_timer";
14
- deadline_ms: number;
15
- } | {
16
- type: "cancel_grace_timer";
17
- } | {
18
- type: "emit_presence";
19
- presence: NetworkPresence;
20
- reason: string;
21
- };
22
- export interface PresenceTransitionResult {
23
- next: NetworkPresence;
24
- effects: readonly PresenceEffect[];
25
- ignored?: boolean;
26
- }
27
- export interface PresenceTransitionOptions {
28
- graceMs?: number;
29
- }
30
- export declare function transitionPresence(current: NetworkPresence, event: PresenceEvent, opts?: PresenceTransitionOptions): PresenceTransitionResult;
31
- //# sourceMappingURL=network-presence.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-presence.d.ts","sourceRoot":"","sources":["../../src/broker/network-presence.ts"],"names":[],"mappings":"AA8BA,eAAO,MAAM,yBAAyB,QAAiB,CAAC;AAExD,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,cAAc,GAAG,SAAS,CAAC;AAEpE,MAAM,MAAM,aAAa,GACrB;IAAE,IAAI,EAAE,qBAAqB,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,wBAAwB,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,wBAAwB,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC;AAEzB,MAAM,MAAM,cAAc,GACtB;IAAE,IAAI,EAAE,mBAAmB,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,GAClD;IAAE,IAAI,EAAE,oBAAoB,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,eAAe,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzE,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,SAAS,cAAc,EAAE,CAAC;IACnC,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,yBAAyB;IACxC,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAOD,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,aAAa,EACpB,IAAI,GAAE,yBAA8B,GACnC,wBAAwB,CAgH1B"}
@@ -1,109 +0,0 @@
1
- export const DEFAULT_PRESENCE_GRACE_MS = 10 * 60 * 1000;
2
- export function transitionPresence(current, event, opts = {}) {
3
- const graceMs = opts.graceMs ?? DEFAULT_PRESENCE_GRACE_MS;
4
- switch (current) {
5
- case "offline": {
6
- switch (event.type) {
7
- case "connector_connected":
8
- return {
9
- next: "online",
10
- effects: [
11
- {
12
- type: "emit_presence",
13
- presence: "online",
14
- reason: "connector_connected",
15
- },
16
- ],
17
- };
18
- case "shutdown":
19
- return {
20
- next: "offline",
21
- effects: [
22
- {
23
- type: "emit_presence",
24
- presence: "offline",
25
- reason: "broker_shutdown",
26
- },
27
- ],
28
- };
29
- case "connector_disconnected":
30
- case "presence_grace_expired":
31
- return { next: "offline", effects: [], ignored: true };
32
- }
33
- return { next: current, effects: [], ignored: true };
34
- }
35
- case "online": {
36
- switch (event.type) {
37
- case "connector_disconnected":
38
- return {
39
- next: "reconnecting",
40
- effects: [
41
- { type: "start_grace_timer", deadline_ms: graceMs },
42
- {
43
- type: "emit_presence",
44
- presence: "reconnecting",
45
- reason: "connector_disconnected",
46
- },
47
- ],
48
- };
49
- case "shutdown":
50
- return {
51
- next: "offline",
52
- effects: [
53
- {
54
- type: "emit_presence",
55
- presence: "offline",
56
- reason: "broker_shutdown",
57
- },
58
- ],
59
- };
60
- case "connector_connected":
61
- case "presence_grace_expired":
62
- return { next: "online", effects: [], ignored: true };
63
- }
64
- return { next: current, effects: [], ignored: true };
65
- }
66
- case "reconnecting": {
67
- switch (event.type) {
68
- case "connector_connected":
69
- return {
70
- next: "online",
71
- effects: [
72
- { type: "cancel_grace_timer" },
73
- {
74
- type: "emit_presence",
75
- presence: "online",
76
- reason: "connector_reconnected",
77
- },
78
- ],
79
- };
80
- case "presence_grace_expired":
81
- return {
82
- next: "offline",
83
- effects: [
84
- {
85
- type: "emit_presence",
86
- presence: "offline",
87
- reason: "grace_timeout",
88
- },
89
- ],
90
- };
91
- case "shutdown":
92
- return {
93
- next: "offline",
94
- effects: [
95
- { type: "cancel_grace_timer" },
96
- {
97
- type: "emit_presence",
98
- presence: "offline",
99
- reason: "broker_shutdown",
100
- },
101
- ],
102
- };
103
- case "connector_disconnected":
104
- return { next: "reconnecting", effects: [], ignored: true };
105
- }
106
- return { next: current, effects: [], ignored: true };
107
- }
108
- }
109
- }
@@ -1,11 +0,0 @@
1
- export interface BrokerPathOptions {
2
- userDataDir?: string;
3
- }
4
- export interface BrokerPaths {
5
- discoveryFile: string;
6
- discoveryDir: string;
7
- logDir: string;
8
- buffersDir: string;
9
- }
10
- export declare function resolveBrokerPaths(principal: string, runtimeToken: string, opts?: BrokerPathOptions): BrokerPaths;
11
- //# sourceMappingURL=paths.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/broker/paths.ts"],"names":[],"mappings":"AAgCA,MAAM,WAAW,iBAAiB;IAEhC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,WAAW;IAE1B,aAAa,EAAE,MAAM,CAAC;IAEtB,YAAY,EAAE,MAAM,CAAC;IAErB,MAAM,EAAE,MAAM,CAAC;IAQf,UAAU,EAAE,MAAM,CAAC;CACpB;AASD,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,IAAI,GAAE,iBAAsB,GAC3B,WAAW,CAgCb"}
@@ -1,30 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { join } from "node:path";
3
- import envPaths from "env-paths";
4
- const AGENT_IDENTITY_HEX_LEN = 16;
5
- const ENV_PATHS_NAME = "masons-runtime-broker";
6
- export function resolveBrokerPaths(principal, runtimeToken, opts = {}) {
7
- if (!principal) {
8
- throw new Error("principal must be a non-empty string");
9
- }
10
- if (!runtimeToken) {
11
- throw new Error("runtimeToken must be a non-empty string");
12
- }
13
- const userData = opts.userDataDir ?? envPaths(ENV_PATHS_NAME, { suffix: "" }).data;
14
- const agentIdentity = createHash("sha256")
15
- .update(runtimeToken, "utf8")
16
- .digest("hex")
17
- .slice(0, AGENT_IDENTITY_HEX_LEN);
18
- const discoveryDir = join(userData, "runtime-broker", sanitizeSegment(principal), agentIdentity);
19
- const logDir = join(userData, "runtime-broker", "log");
20
- const buffersDir = join(discoveryDir, "buffers");
21
- return {
22
- discoveryFile: join(discoveryDir, "discovery.json"),
23
- discoveryDir,
24
- logDir,
25
- buffersDir,
26
- };
27
- }
28
- function sanitizeSegment(segment) {
29
- return segment.replace(/[^a-zA-Z0-9._-]/g, "_");
30
- }
@@ -1,2 +0,0 @@
1
- export declare function isPluginAlive(plugin_pid: number): boolean;
2
- //# sourceMappingURL=plugin-liveness.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"plugin-liveness.d.ts","sourceRoot":"","sources":["../../src/broker/plugin-liveness.ts"],"names":[],"mappings":"AAyBA,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAiBzD"}
@@ -1,15 +0,0 @@
1
- export function isPluginAlive(plugin_pid) {
2
- if (!Number.isFinite(plugin_pid) || plugin_pid <= 0) {
3
- return false;
4
- }
5
- try {
6
- process.kill(plugin_pid, 0);
7
- return true;
8
- }
9
- catch (err) {
10
- const code = err.code;
11
- if (code === "ESRCH")
12
- return false;
13
- return true;
14
- }
15
- }
@@ -1,23 +0,0 @@
1
- export declare const DEFAULT_TTL_MS = 86400000;
2
- export declare const DEFAULT_CAP_PER_ENDPOINT = 1000;
3
- export interface ReceivedMessageCorrelationCacheOptions {
4
- ttlMs?: number;
5
- capPerEndpoint?: number;
6
- now?: () => number;
7
- }
8
- export type ReplyAwareResolve = {
9
- ok: true;
10
- } | {
11
- ok: false;
12
- reason: "unknown_correlation_id" | "wrong_endpoint" | "ttl_expired";
13
- };
14
- export interface ReceivedMessageCorrelationCache {
15
- record(endpoint_id: string, correlation_id: string): void;
16
- resolve(endpoint_id: string, correlation_id: string): ReplyAwareResolve;
17
- size(): number;
18
- sizeForEndpoint(endpoint_id: string): number;
19
- sweep(now?: number): number;
20
- forgetEndpoint(endpoint_id: string): void;
21
- }
22
- export declare function createReceivedMessageCorrelationCache(opts?: ReceivedMessageCorrelationCacheOptions): ReceivedMessageCorrelationCache;
23
- //# sourceMappingURL=received-message-correlation-cache.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"received-message-correlation-cache.d.ts","sourceRoot":"","sources":["../../src/broker/received-message-correlation-cache.ts"],"names":[],"mappings":"AA8DA,eAAO,MAAM,cAAc,WAAa,CAAC;AAGzC,eAAO,MAAM,wBAAwB,OAAO,CAAC;AAE7C,MAAM,WAAW,sCAAsC;IAErD,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,iBAAiB,GACzB;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GACZ;IACE,EAAE,EAAE,KAAK,CAAC;IACV,MAAM,EAAE,wBAAwB,GAAG,gBAAgB,GAAG,aAAa,CAAC;CACrE,CAAC;AAMN,MAAM,WAAW,+BAA+B;IAa9C,MAAM,CAAC,WAAW,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAQ1D,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,iBAAiB,CAAC;IAGxE,IAAI,IAAI,MAAM,CAAC;IAGf,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IAQ7C,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAM5B,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3C;AAED,wBAAgB,qCAAqC,CACnD,IAAI,GAAE,sCAA2C,GAChD,+BAA+B,CAgIjC"}
@@ -1,114 +0,0 @@
1
- export const DEFAULT_TTL_MS = 86_400_000;
2
- export const DEFAULT_CAP_PER_ENDPOINT = 1000;
3
- export function createReceivedMessageCorrelationCache(opts = {}) {
4
- const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
5
- const cap = opts.capPerEndpoint ?? DEFAULT_CAP_PER_ENDPOINT;
6
- const clock = opts.now ?? Date.now;
7
- if (ttlMs <= 0)
8
- throw new Error(`ttlMs must be positive: ${ttlMs}`);
9
- if (cap <= 0)
10
- throw new Error(`capPerEndpoint must be positive: ${cap}`);
11
- const perEndpoint = new Map();
12
- const correlationOwner = new Map();
13
- const evict = (endpoint_id, correlation_id) => {
14
- const inner = perEndpoint.get(endpoint_id);
15
- if (!inner)
16
- return;
17
- inner.delete(correlation_id);
18
- if (inner.size === 0)
19
- perEndpoint.delete(endpoint_id);
20
- if (correlationOwner.get(correlation_id) === endpoint_id) {
21
- correlationOwner.delete(correlation_id);
22
- }
23
- };
24
- return {
25
- record(endpoint_id, correlation_id) {
26
- const priorOwner = correlationOwner.get(correlation_id);
27
- if (priorOwner && priorOwner !== endpoint_id) {
28
- const priorInner = perEndpoint.get(priorOwner);
29
- priorInner?.delete(correlation_id);
30
- if (priorInner && priorInner.size === 0) {
31
- perEndpoint.delete(priorOwner);
32
- }
33
- }
34
- let inner = perEndpoint.get(endpoint_id);
35
- if (!inner) {
36
- inner = new Map();
37
- perEndpoint.set(endpoint_id, inner);
38
- }
39
- inner.delete(correlation_id);
40
- inner.set(correlation_id, { received_at: clock() });
41
- correlationOwner.set(correlation_id, endpoint_id);
42
- while (inner.size > cap) {
43
- const oldestKey = inner.keys().next().value;
44
- if (oldestKey === undefined)
45
- break;
46
- inner.delete(oldestKey);
47
- if (correlationOwner.get(oldestKey) === endpoint_id) {
48
- correlationOwner.delete(oldestKey);
49
- }
50
- }
51
- },
52
- resolve(endpoint_id, correlation_id) {
53
- const owner = correlationOwner.get(correlation_id);
54
- if (!owner) {
55
- return { ok: false, reason: "unknown_correlation_id" };
56
- }
57
- if (owner !== endpoint_id) {
58
- return { ok: false, reason: "wrong_endpoint" };
59
- }
60
- const inner = perEndpoint.get(endpoint_id);
61
- const entry = inner?.get(correlation_id);
62
- if (!entry) {
63
- correlationOwner.delete(correlation_id);
64
- return { ok: false, reason: "unknown_correlation_id" };
65
- }
66
- if (clock() - entry.received_at >= ttlMs) {
67
- evict(endpoint_id, correlation_id);
68
- return { ok: false, reason: "ttl_expired" };
69
- }
70
- return { ok: true };
71
- },
72
- size() {
73
- let total = 0;
74
- for (const inner of perEndpoint.values())
75
- total += inner.size;
76
- return total;
77
- },
78
- sizeForEndpoint(endpoint_id) {
79
- return perEndpoint.get(endpoint_id)?.size ?? 0;
80
- },
81
- sweep(now = clock()) {
82
- let evicted = 0;
83
- for (const [endpoint_id, inner] of perEndpoint) {
84
- const expired = [];
85
- for (const [correlation_id, entry] of inner) {
86
- if (now - entry.received_at >= ttlMs) {
87
- expired.push(correlation_id);
88
- }
89
- }
90
- for (const correlation_id of expired) {
91
- inner.delete(correlation_id);
92
- if (correlationOwner.get(correlation_id) === endpoint_id) {
93
- correlationOwner.delete(correlation_id);
94
- }
95
- evicted++;
96
- }
97
- if (inner.size === 0)
98
- perEndpoint.delete(endpoint_id);
99
- }
100
- return evicted;
101
- },
102
- forgetEndpoint(endpoint_id) {
103
- const inner = perEndpoint.get(endpoint_id);
104
- if (!inner)
105
- return;
106
- for (const correlation_id of inner.keys()) {
107
- if (correlationOwner.get(correlation_id) === endpoint_id) {
108
- correlationOwner.delete(correlation_id);
109
- }
110
- }
111
- perEndpoint.delete(endpoint_id);
112
- },
113
- };
114
- }