operon-managed-agents 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +103 -0
  3. package/dist/client/client.d.ts +80 -0
  4. package/dist/client/client.js +232 -0
  5. package/dist/client/errors.d.ts +7 -0
  6. package/dist/client/errors.js +21 -0
  7. package/dist/client/index.d.ts +4 -0
  8. package/dist/client/index.js +4 -0
  9. package/dist/client/run.d.ts +71 -0
  10. package/dist/client/run.js +144 -0
  11. package/dist/index.d.ts +4 -0
  12. package/dist/index.js +4 -0
  13. package/dist/protocol/index.d.ts +3 -0
  14. package/dist/protocol/index.js +3 -0
  15. package/dist/protocol/sse.d.ts +7 -0
  16. package/dist/protocol/sse.js +53 -0
  17. package/dist/protocol/types.d.ts +102 -0
  18. package/dist/protocol/types.js +2 -0
  19. package/dist/server/broadcast.d.ts +105 -0
  20. package/dist/server/broadcast.js +130 -0
  21. package/dist/server/errors.d.ts +23 -0
  22. package/dist/server/errors.js +43 -0
  23. package/dist/server/http-server.d.ts +54 -0
  24. package/dist/server/http-server.js +325 -0
  25. package/dist/server/idempotency.d.ts +24 -0
  26. package/dist/server/idempotency.js +52 -0
  27. package/dist/server/inbox.d.ts +64 -0
  28. package/dist/server/inbox.js +71 -0
  29. package/dist/server/index.d.ts +14 -0
  30. package/dist/server/index.js +14 -0
  31. package/dist/server/metadata-pg.d.ts +31 -0
  32. package/dist/server/metadata-pg.js +64 -0
  33. package/dist/server/metadata.d.ts +38 -0
  34. package/dist/server/metadata.js +107 -0
  35. package/dist/server/registries.d.ts +40 -0
  36. package/dist/server/registries.js +26 -0
  37. package/dist/server/session-service.d.ts +181 -0
  38. package/dist/server/session-service.js +658 -0
  39. package/dist/server/session-worker.d.ts +136 -0
  40. package/dist/server/session-worker.js +428 -0
  41. package/dist/server/work-memory.d.ts +27 -0
  42. package/dist/server/work-memory.js +85 -0
  43. package/dist/server/work-pg.d.ts +46 -0
  44. package/dist/server/work-pg.js +122 -0
  45. package/dist/server/work.d.ts +49 -0
  46. package/dist/server/work.js +2 -0
  47. package/package.json +56 -0
@@ -0,0 +1,54 @@
1
+ import { type IncomingMessage, type Server } from "node:http";
2
+ import type { SessionService } from "./session-service.ts";
3
+ import type { SessionWorker } from "./session-worker.ts";
4
+ export type ManagedAuthorizationAction = "sessions.create" | "sessions.list" | "sessions.read" | "sessions.delete" | "messages.create" | "events.list" | "events.stream" | "sessions.cancel" | "interruptions.list" | "sessions.resume";
5
+ export interface ManagedAuthorizationContext {
6
+ readonly action: ManagedAuthorizationAction;
7
+ readonly sessionId?: string;
8
+ }
9
+ export type ManagedAuthorize = (request: IncomingMessage, context: ManagedAuthorizationContext) => boolean | void | Promise<boolean | void>;
10
+ /**
11
+ * Authorize every request. For local demos and tests only.
12
+ *
13
+ * It exists so that running without authorization is something you write down, rather than
14
+ * something you get by forgetting to pass an option — grep for this name to find every
15
+ * deployment that has no access control.
16
+ */
17
+ export declare const allowAllRequests: ManagedAuthorize;
18
+ export interface ManagedHttpServerOptions<TContext = unknown> {
19
+ /** Reads and writes of session state. Every route that is not execution goes here. */
20
+ readonly service: SessionService;
21
+ /**
22
+ * Execution. Optional: a deployment can run the API surface with no worker in this process at
23
+ * all — accepted inputs and commands wait for a worker elsewhere to claim them, because the
24
+ * work table is what connects the two. With one, it is nudged after every write so the common
25
+ * single-process case needs no claim latency. Nothing here is answered BY the worker: every
26
+ * route is a store operation, so any node can serve any session.
27
+ */
28
+ readonly worker?: SessionWorker<TContext>;
29
+ readonly basePath?: string;
30
+ readonly heartbeatMs?: number;
31
+ readonly maxBodyBytes?: number;
32
+ /**
33
+ * Authentication and ownership. REQUIRED — a managed server has no safe default here.
34
+ *
35
+ * It used to be optional and absent meant "allow everything", so a deployment that forgot to
36
+ * wire it was open to anyone who could reach the port, with no symptom to notice. Making it
37
+ * mandatory turns that from a deployment checklist item into something the type system will
38
+ * not let you skip. To deliberately run without checks (a local demo, a test), pass
39
+ * `allowAllRequests` and let the name say so at the call site.
40
+ *
41
+ * Returning false denies the request; throwing ManagedUnauthorizedError or
42
+ * ManagedForbiddenError preserves the distinction between "who are you" and "not yours".
43
+ * Throwing ManagedSessionNotFoundError instead is how a multi-tenant deployment avoids
44
+ * turning 403-vs-404 into an existence oracle for other tenants' session ids.
45
+ */
46
+ readonly authorize: ManagedAuthorize;
47
+ }
48
+ export interface ManagedHttpServer {
49
+ readonly server: Server;
50
+ listen(port: number, hostname?: string): Promise<void>;
51
+ close(): Promise<void>;
52
+ }
53
+ export declare function createManagedHttpServer<TContext = unknown>(options: ManagedHttpServerOptions<TContext>): ManagedHttpServer;
54
+ //# sourceMappingURL=http-server.d.ts.map
@@ -0,0 +1,325 @@
1
+ import { createServer } from "node:http";
2
+ import { isDurableAgentEvent } from "operon-agents";
3
+ import { ManagedForbiddenError, ManagedInvalidRequestError, ManagedServerError, } from "./errors.js";
4
+ /**
5
+ * Authorize every request. For local demos and tests only.
6
+ *
7
+ * It exists so that running without authorization is something you write down, rather than
8
+ * something you get by forgetting to pass an option — grep for this name to find every
9
+ * deployment that has no access control.
10
+ */
11
+ export const allowAllRequests = () => true;
12
+ export function createManagedHttpServer(options) {
13
+ const basePath = normalizeBasePath(options.basePath ?? "/v1");
14
+ const heartbeatMs = options.heartbeatMs ?? 15_000;
15
+ const maxBodyBytes = options.maxBodyBytes ?? 1024 * 1024;
16
+ const openStreams = new Map();
17
+ const server = createServer((request, response) => {
18
+ void route(request, response).catch((error) => {
19
+ if (response.headersSent) {
20
+ response.end();
21
+ return;
22
+ }
23
+ const managed = error instanceof ManagedServerError
24
+ ? error
25
+ : error instanceof SyntaxError
26
+ ? new ManagedInvalidRequestError("request body must be valid JSON")
27
+ : undefined;
28
+ sendJson(response, managed?.status ?? 500, apiError(managed?.code ?? "internal_error", managed?.message ?? messageOf(error)));
29
+ });
30
+ });
31
+ async function route(request, response) {
32
+ const url = new URL(request.url ?? "/", "http://managed.local");
33
+ if (!url.pathname.startsWith(`${basePath}/`) && url.pathname !== basePath) {
34
+ return sendJson(response, 404, apiError("not_found", "route not found"));
35
+ }
36
+ const relative = url.pathname.slice(basePath.length);
37
+ const parts = relative.split("/").filter(Boolean).map(decodeURIComponent);
38
+ const method = request.method ?? "GET";
39
+ if (method === "POST" && parts.length === 1 && parts[0] === "sessions") {
40
+ await authorize(request, "sessions.create");
41
+ const body = await readJson(request, maxBodyBytes);
42
+ return sendJson(response, 201, await options.service.create(body));
43
+ }
44
+ if (method === "GET" && parts.length === 1 && parts[0] === "sessions") {
45
+ await authorize(request, "sessions.list");
46
+ const body = { data: await options.service.list() };
47
+ return sendJson(response, 200, body);
48
+ }
49
+ if (parts[0] !== "sessions" || parts[1] === undefined) {
50
+ return sendJson(response, 404, apiError("not_found", "route not found"));
51
+ }
52
+ const sessionId = parts[1];
53
+ if (method === "GET" && parts.length === 2) {
54
+ await authorize(request, "sessions.read", sessionId);
55
+ return sendJson(response, 200, await options.service.get(sessionId));
56
+ }
57
+ if (method === "DELETE" && parts.length === 2) {
58
+ await authorize(request, "sessions.delete", sessionId);
59
+ await options.service.delete(sessionId);
60
+ response.writeHead(204);
61
+ response.end();
62
+ return;
63
+ }
64
+ if (method === "POST" && parts[2] === "messages" && parts.length === 3) {
65
+ await authorize(request, "messages.create", sessionId);
66
+ const body = await readJson(request, maxBodyBytes);
67
+ if (typeof body.input !== "string" || !body.input.trim()) {
68
+ return sendJson(response, 400, apiError("invalid_request", "input must not be empty"));
69
+ }
70
+ const idempotencyKey = singleHeader(request.headers["idempotency-key"]);
71
+ const receipt = await options.service.appendEvent(sessionId, body, idempotencyKey);
72
+ // Nudge the local worker, if this node has one. Fire-and-forget on purpose: the append
73
+ // already woke the session in the work table, so a failed or skipped nudge costs latency
74
+ // until a claim loop gets to it, never the message. Redundant nudges are free.
75
+ void options.worker?.drain(sessionId).catch(() => undefined);
76
+ return sendJson(response, 202, receipt);
77
+ }
78
+ if (method === "GET" && parts[2] === "events" && parts.length === 3) {
79
+ await authorize(request, "events.list", sessionId);
80
+ let limit;
81
+ let requestedOrder;
82
+ let cursor;
83
+ try {
84
+ limit = positiveInteger(url.searchParams.get("limit"), 100, 500);
85
+ requestedOrder = eventOrder(url.searchParams.get("order"));
86
+ cursor = decodePage(url.searchParams.get("page"));
87
+ }
88
+ catch (error) {
89
+ return sendJson(response, 400, apiError("invalid_request", messageOf(error)));
90
+ }
91
+ const requestedAddress = url.searchParams.get("address") ?? undefined;
92
+ if (cursor !== undefined) {
93
+ if (requestedOrder !== undefined && requestedOrder !== cursor.order) {
94
+ return sendJson(response, 400, apiError("invalid_request", "page cursor order does not match order"));
95
+ }
96
+ if (requestedAddress !== undefined && requestedAddress !== cursor.address) {
97
+ return sendJson(response, 400, apiError("invalid_request", "page cursor address does not match address"));
98
+ }
99
+ }
100
+ const order = requestedOrder ?? cursor?.order ?? "asc";
101
+ const address = requestedAddress ?? cursor?.address;
102
+ const page = await options.service.listEvents(sessionId, {
103
+ limit,
104
+ order,
105
+ ...(address !== undefined ? { address } : {}),
106
+ ...(cursor !== undefined ? { after: cursor.sequence } : {}),
107
+ });
108
+ const body = {
109
+ data: page.data,
110
+ nextPage: page.next === undefined ? null : encodePage({ sequence: page.next, order, ...(address !== undefined ? { address } : {}) }),
111
+ };
112
+ return sendJson(response, 200, body);
113
+ }
114
+ if (method === "GET" && parts[2] === "events" && parts[3] === "stream" && parts.length === 4) {
115
+ await authorize(request, "events.stream", sessionId);
116
+ // `Last-Event-ID` is what EventSource sends on its own reconnect; `after` is the same
117
+ // cursor for clients that manage reconnection themselves. The header wins when both are
118
+ // present, since it describes what this connection actually last received.
119
+ const after = singleHeader(request.headers["last-event-id"]) ?? url.searchParams.get("after") ?? undefined;
120
+ return streamEvents(sessionId, url.searchParams.get("address") ?? undefined, after, request, response);
121
+ }
122
+ // Control commands are writes, like messages: the command is journaled and the worker that
123
+ // holds the session — wherever it is — acts on it. 202 here means "durable", not "done".
124
+ if (method === "POST" && parts[2] === "cancel" && parts.length === 3) {
125
+ await authorize(request, "sessions.cancel", sessionId);
126
+ const receipt = await options.service.requestCancel(sessionId);
127
+ void options.worker?.drain(sessionId).catch(() => undefined);
128
+ return sendJson(response, 202, receipt);
129
+ }
130
+ if (method === "GET" && parts[2] === "interruptions" && parts.length === 3) {
131
+ await authorize(request, "interruptions.list", sessionId);
132
+ const body = { data: await options.service.interruptions(sessionId) };
133
+ return sendJson(response, 200, body);
134
+ }
135
+ if (method === "POST" && parts[2] === "resume" && parts.length === 3) {
136
+ await authorize(request, "sessions.resume", sessionId);
137
+ const body = await readJson(request, maxBodyBytes);
138
+ if (!isRecord(body.answers))
139
+ return sendJson(response, 400, apiError("invalid_request", "answers must be an object"));
140
+ const receipt = await options.service.answerInterruption(sessionId, body.answers);
141
+ void options.worker?.drain(sessionId).catch(() => undefined);
142
+ return sendJson(response, 202, receipt);
143
+ }
144
+ return sendJson(response, 404, apiError("not_found", "route not found"));
145
+ }
146
+ async function streamEvents(sessionId, address, after, request, response) {
147
+ response.writeHead(200, {
148
+ "content-type": "text/event-stream",
149
+ "cache-control": "no-cache, no-transform",
150
+ connection: "keep-alive",
151
+ "x-accel-buffering": "no",
152
+ });
153
+ // Never attaches to a running session: the service backfills from the log and then follows
154
+ // the broadcast channel, so subscribing starts nothing and any replica can serve any
155
+ // session. Whether live-only events (token deltas) appear depends on whether a broadcaster
156
+ // was configured — without one this carries the persisted stream alone.
157
+ const controller = new AbortController();
158
+ const pump = (async () => {
159
+ try {
160
+ for await (const event of options.service.watchEvents(sessionId, {
161
+ ...(address !== undefined ? { address } : {}),
162
+ ...(after !== undefined ? { after } : {}),
163
+ signal: controller.signal,
164
+ })) {
165
+ if (response.destroyed || response.writableEnded)
166
+ break;
167
+ // `id:` only on events a reconnect can resume from. Per the SSE spec a frame without
168
+ // one leaves the client's last-event-id untouched, so a delta never becomes a cursor
169
+ // that points at nothing in the log.
170
+ const id = isDurableAgentEvent(event) ? event.eventId : undefined;
171
+ // If the transport's own buffer fills, terminate this client rather than letting an
172
+ // unbounded SSE queue turn into memory growth.
173
+ if (!writeSse(response, "session.event", event, id)) {
174
+ response.destroy();
175
+ break;
176
+ }
177
+ }
178
+ }
179
+ catch {
180
+ if (!response.destroyed)
181
+ response.destroy();
182
+ }
183
+ })();
184
+ pump.catch(() => undefined);
185
+ response.flushHeaders();
186
+ response.write(": connected\n\n");
187
+ manageStream(request, response, () => controller.abort());
188
+ }
189
+ async function authorize(request, action, sessionId) {
190
+ const allowed = await options.authorize(request, {
191
+ action,
192
+ ...(sessionId !== undefined ? { sessionId } : {}),
193
+ });
194
+ if (allowed === false)
195
+ throw new ManagedForbiddenError();
196
+ }
197
+ function manageStream(request, response, unsubscribe) {
198
+ const heartbeat = setInterval(() => {
199
+ if (!response.write(": heartbeat\n\n"))
200
+ response.destroy();
201
+ }, heartbeatMs);
202
+ let closed = false;
203
+ const close = () => {
204
+ if (closed)
205
+ return;
206
+ closed = true;
207
+ clearInterval(heartbeat);
208
+ unsubscribe();
209
+ openStreams.delete(response);
210
+ if (!response.writableEnded)
211
+ response.end();
212
+ };
213
+ openStreams.set(response, close);
214
+ request.once("close", close);
215
+ response.once("close", close);
216
+ }
217
+ return {
218
+ server,
219
+ listen: (port, hostname) => new Promise((resolve, reject) => {
220
+ const onError = (error) => reject(error);
221
+ server.once("error", onError);
222
+ server.listen(port, hostname, () => {
223
+ server.off("error", onError);
224
+ resolve();
225
+ });
226
+ }),
227
+ close: async () => {
228
+ // End long-lived SSE connections before waiting for Node's server to drain them.
229
+ for (const close of [...openStreams.values()])
230
+ close();
231
+ openStreams.clear();
232
+ await new Promise((resolve, reject) => {
233
+ if (!server.listening)
234
+ return resolve();
235
+ server.close((error) => error === undefined ? resolve() : reject(error));
236
+ });
237
+ await options.worker?.stop();
238
+ },
239
+ };
240
+ }
241
+ function normalizeBasePath(path) {
242
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
243
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
244
+ }
245
+ function sendJson(response, status, body) {
246
+ const json = JSON.stringify(body);
247
+ response.writeHead(status, {
248
+ "content-type": "application/json; charset=utf-8",
249
+ "content-length": Buffer.byteLength(json),
250
+ });
251
+ response.end(json);
252
+ }
253
+ function writeSse(response, event, data, id) {
254
+ const frame = `${id !== undefined ? `id: ${id.replace(/[\r\n]/g, "")}\n` : ""}event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
255
+ return response.write(frame);
256
+ }
257
+ async function readJson(request, maxBytes) {
258
+ const chunks = [];
259
+ let bytes = 0;
260
+ for await (const chunk of request) {
261
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
262
+ bytes += buffer.length;
263
+ if (bytes > maxBytes)
264
+ throw new ManagedInvalidRequestError(`request body exceeds ${maxBytes} bytes`);
265
+ chunks.push(buffer);
266
+ }
267
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
268
+ return (raw ? JSON.parse(raw) : {});
269
+ }
270
+ function isRecord(value) {
271
+ return typeof value === "object" && value !== null && !Array.isArray(value);
272
+ }
273
+ function singleHeader(value) {
274
+ if (value === undefined)
275
+ return undefined;
276
+ const header = Array.isArray(value) ? value[0] : value;
277
+ return header?.trim() || undefined;
278
+ }
279
+ function apiError(code, message) {
280
+ return { error: { code, message } };
281
+ }
282
+ function messageOf(error) {
283
+ return error instanceof Error ? error.message : String(error);
284
+ }
285
+ function encodePage(cursor) {
286
+ return Buffer.from(JSON.stringify({ v: 1, ...cursor }), "utf8").toString("base64url");
287
+ }
288
+ function decodePage(value) {
289
+ if (value === null)
290
+ return undefined;
291
+ try {
292
+ const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
293
+ if (parsed["v"] !== 1 || typeof parsed["sequence"] !== "string" || !/^[1-9]\d*$/.test(parsed["sequence"]))
294
+ throw new Error();
295
+ if (parsed["order"] !== "asc" && parsed["order"] !== "desc")
296
+ throw new Error();
297
+ if (parsed["address"] !== undefined && typeof parsed["address"] !== "string")
298
+ throw new Error();
299
+ return {
300
+ sequence: parsed["sequence"],
301
+ order: parsed["order"],
302
+ ...(typeof parsed["address"] === "string" ? { address: parsed["address"] } : {}),
303
+ };
304
+ }
305
+ catch {
306
+ throw new Error("invalid event page cursor");
307
+ }
308
+ }
309
+ function positiveInteger(value, fallback, max) {
310
+ if (value === null)
311
+ return fallback;
312
+ const parsed = Number(value);
313
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > max) {
314
+ throw new Error(`limit must be an integer between 1 and ${String(max)}`);
315
+ }
316
+ return parsed;
317
+ }
318
+ function eventOrder(value) {
319
+ if (value === null)
320
+ return undefined;
321
+ if (value === "asc" || value === "desc")
322
+ return value;
323
+ throw new Error("order must be asc or desc");
324
+ }
325
+ //# sourceMappingURL=http-server.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Delivery idempotency.
3
+ *
4
+ * A client that retries a message after a timeout must not have it delivered twice, and it
5
+ * cannot tell from a failed request whether the first attempt landed. Keyed by
6
+ * `(sessionId, key)`: the same key on a different session is a different delivery.
7
+ */
8
+ import type { DeliveryReceiptResource } from "../protocol/types.ts";
9
+ export interface ManagedDeliveryIdempotencyStore {
10
+ run(sessionId: string, key: string, operation: () => Promise<DeliveryReceiptResource>): Promise<DeliveryReceiptResource>;
11
+ }
12
+ export declare class MemoryManagedDeliveryIdempotencyStore implements ManagedDeliveryIdempotencyStore {
13
+ private readonly entries;
14
+ private readonly ttlMs;
15
+ private readonly maxEntries;
16
+ constructor(options?: {
17
+ readonly ttlMs?: number;
18
+ readonly maxEntries?: number;
19
+ });
20
+ run(sessionId: string, key: string, operation: () => Promise<DeliveryReceiptResource>): Promise<DeliveryReceiptResource>;
21
+ private pruneExpired;
22
+ private makeRoom;
23
+ }
24
+ //# sourceMappingURL=idempotency.d.ts.map
@@ -0,0 +1,52 @@
1
+ export class MemoryManagedDeliveryIdempotencyStore {
2
+ entries = new Map();
3
+ ttlMs;
4
+ maxEntries;
5
+ constructor(options = {}) {
6
+ this.ttlMs = options.ttlMs ?? 24 * 60 * 60 * 1000;
7
+ this.maxEntries = options.maxEntries ?? 10_000;
8
+ if (!Number.isFinite(this.ttlMs) || this.ttlMs <= 0)
9
+ throw new Error("idempotency ttlMs must be positive");
10
+ if (!Number.isSafeInteger(this.maxEntries) || this.maxEntries < 1)
11
+ throw new Error("idempotency maxEntries must be a positive integer");
12
+ }
13
+ async run(sessionId, key, operation) {
14
+ const compound = `${sessionId}\0${key}`;
15
+ const now = Date.now();
16
+ this.pruneExpired(now);
17
+ const existing = this.entries.get(compound);
18
+ if (existing !== undefined && (!existing.settled || existing.expiresAt > now))
19
+ return existing.result;
20
+ this.makeRoom();
21
+ const result = operation();
22
+ const entry = { result, settled: false, expiresAt: Number.POSITIVE_INFINITY };
23
+ this.entries.set(compound, entry);
24
+ void result.then(() => {
25
+ if (this.entries.get(compound) !== entry)
26
+ return;
27
+ entry.settled = true;
28
+ entry.expiresAt = Date.now() + this.ttlMs;
29
+ }, () => {
30
+ if (this.entries.get(compound) === entry)
31
+ this.entries.delete(compound);
32
+ });
33
+ return result;
34
+ }
35
+ pruneExpired(now) {
36
+ for (const [key, entry] of this.entries) {
37
+ if (entry.settled && entry.expiresAt <= now)
38
+ this.entries.delete(key);
39
+ }
40
+ }
41
+ makeRoom() {
42
+ while (this.entries.size >= this.maxEntries) {
43
+ const oldestSettled = [...this.entries].find(([, entry]) => entry.settled)?.[0];
44
+ // Never evict an in-flight key: that would permit the same delivery concurrently.
45
+ // A burst may exceed maxEntries temporarily; completion makes it evictable.
46
+ if (oldestSettled === undefined)
47
+ break;
48
+ this.entries.delete(oldestSettled);
49
+ }
50
+ }
51
+ }
52
+ //# sourceMappingURL=idempotency.js.map
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The inbox: what a session has been asked to do that no turn has dealt with yet.
3
+ *
4
+ * It is not a table. It is a READ of the session log — every `inbox.received` and every
5
+ * control record after the worker's cursor — which is what makes it impossible to lose: the
6
+ * log is the only thing a delivery writes, so there is no second place for the two to disagree.
7
+ * Queues, pending marks and wake-up signals are indexes over this read, never the truth of it.
8
+ *
9
+ * Shared by the two things that need the same answer to "is there work here?": the worker (to
10
+ * do it) and the service (to tell a watching client nobody is doing it). One definition, so
11
+ * they can never disagree on what counts. The work table's `woken` flag is an index over this
12
+ * read — set by the same write that creates an item, cleared by a holder about to read — never
13
+ * the truth of it.
14
+ */
15
+ import type { InterruptAnswer, SessionStore } from "operon-agents";
16
+ import type { ExternalOriginMetadataValue } from "operon-agents";
17
+ /** Where processing stopped. Everything at or before it has been dealt with. */
18
+ export declare const INBOX_CURSOR_KEY = "inbox:cursor";
19
+ /**
20
+ * Control records ride the log as `custom` records under this name. The log's record
21
+ * vocabulary is the framework's; the managed layer's commands are its own, and `custom` is the
22
+ * extension point the framework left for exactly that.
23
+ */
24
+ export declare const CONTROL_RECORD_NAME = "managed.control";
25
+ export type ControlCommand = {
26
+ readonly kind: "cancel";
27
+ /** Idempotency identity, the way `deliveryId` is for an input. */
28
+ readonly commandId: string;
29
+ readonly requestedAt: number;
30
+ readonly actor?: string;
31
+ } | {
32
+ readonly kind: "resume";
33
+ readonly commandId: string;
34
+ readonly requestedAt: number;
35
+ readonly answers: Readonly<Record<string, InterruptAnswer>>;
36
+ readonly actor?: string;
37
+ };
38
+ export interface InboxInput {
39
+ readonly kind: "input";
40
+ readonly sequence: string;
41
+ readonly input: string;
42
+ readonly origin: {
43
+ readonly kind: "external";
44
+ readonly source: string;
45
+ readonly deliveryId: string;
46
+ readonly actor?: string;
47
+ readonly metadata?: Readonly<Record<string, ExternalOriginMetadataValue>>;
48
+ };
49
+ readonly mode: "auto" | "steer" | "follow_up";
50
+ }
51
+ export interface InboxControl {
52
+ readonly kind: "control";
53
+ readonly sequence: string;
54
+ readonly command: ControlCommand;
55
+ }
56
+ export type InboxItem = InboxInput | InboxControl;
57
+ /** The identity an item is tracked by once dispatched: `deliveryId` or `commandId`. */
58
+ export declare function inboxItemId(item: InboxItem): string;
59
+ export declare function readInboxCursor(store: SessionStore): Promise<string | undefined>;
60
+ /** Inbox records after `cursor`, in log order, excluding sequences in `exclude`. */
61
+ export declare function readInbox(store: SessionStore, cursor: string | undefined, exclude?: ReadonlySet<string>): Promise<readonly InboxItem[]>;
62
+ /** Is there anything after the cursor a worker would act on? */
63
+ export declare function hasUnprocessedInbox(store: SessionStore): Promise<boolean>;
64
+ //# sourceMappingURL=inbox.d.ts.map
@@ -0,0 +1,71 @@
1
+ /** Where processing stopped. Everything at or before it has been dealt with. */
2
+ export const INBOX_CURSOR_KEY = "inbox:cursor";
3
+ /**
4
+ * Control records ride the log as `custom` records under this name. The log's record
5
+ * vocabulary is the framework's; the managed layer's commands are its own, and `custom` is the
6
+ * extension point the framework left for exactly that.
7
+ */
8
+ export const CONTROL_RECORD_NAME = "managed.control";
9
+ /** The identity an item is tracked by once dispatched: `deliveryId` or `commandId`. */
10
+ export function inboxItemId(item) {
11
+ return item.kind === "input" ? item.origin.deliveryId : item.command.commandId;
12
+ }
13
+ export async function readInboxCursor(store) {
14
+ const raw = await store.getState(INBOX_CURSOR_KEY);
15
+ return typeof raw === "string" ? raw : undefined;
16
+ }
17
+ /** Inbox records after `cursor`, in log order, excluding sequences in `exclude`. */
18
+ export async function readInbox(store, cursor, exclude = new Set()) {
19
+ const page = await store.readRecordPage({
20
+ limit: 128,
21
+ ...(cursor !== undefined ? { after: cursor } : {}),
22
+ address: "main",
23
+ });
24
+ const items = [];
25
+ for (const stored of page.data) {
26
+ if (exclude.has(stored.sequence))
27
+ continue;
28
+ const item = inboxItemFromRecord(stored.sequence, stored.record);
29
+ if (item !== undefined)
30
+ items.push(item);
31
+ }
32
+ return items;
33
+ }
34
+ /** Is there anything after the cursor a worker would act on? */
35
+ export async function hasUnprocessedInbox(store) {
36
+ return (await readInbox(store, await readInboxCursor(store))).length > 0;
37
+ }
38
+ function inboxItemFromRecord(sequence, record) {
39
+ if (record.type === "inbox.received") {
40
+ return { kind: "input", sequence, input: record.input, origin: record.origin, mode: record.mode };
41
+ }
42
+ if (record.type === "custom" && record.name === CONTROL_RECORD_NAME) {
43
+ const command = parseControlCommand(record.data);
44
+ return command === undefined ? undefined : { kind: "control", sequence, command };
45
+ }
46
+ return undefined;
47
+ }
48
+ /**
49
+ * Tolerant on purpose: a record this version does not understand is skipped, not fatal. A
50
+ * newer API node may write a command an older worker has not learned yet, and refusing to
51
+ * drain the whole session over it would strand every input behind it.
52
+ */
53
+ function parseControlCommand(data) {
54
+ if (typeof data !== "object" || data === null)
55
+ return undefined;
56
+ const raw = data;
57
+ if (typeof raw["commandId"] !== "string" || typeof raw["requestedAt"] !== "number")
58
+ return undefined;
59
+ const base = {
60
+ commandId: raw["commandId"],
61
+ requestedAt: raw["requestedAt"],
62
+ ...(typeof raw["actor"] === "string" ? { actor: raw["actor"] } : {}),
63
+ };
64
+ if (raw["kind"] === "cancel")
65
+ return { kind: "cancel", ...base };
66
+ if (raw["kind"] === "resume" && typeof raw["answers"] === "object" && raw["answers"] !== null) {
67
+ return { kind: "resume", ...base, answers: raw["answers"] };
68
+ }
69
+ return undefined;
70
+ }
71
+ //# sourceMappingURL=inbox.js.map
@@ -0,0 +1,14 @@
1
+ export * from "./http-server.ts";
2
+ export * from "./errors.ts";
3
+ export * from "./metadata.ts";
4
+ export * from "./metadata-pg.ts";
5
+ export * from "./work.ts";
6
+ export * from "./work-memory.ts";
7
+ export * from "./work-pg.ts";
8
+ export * from "./registries.ts";
9
+ export * from "./broadcast.ts";
10
+ export * from "./idempotency.ts";
11
+ export * from "./session-service.ts";
12
+ export * from "./session-worker.ts";
13
+ export * from "./inbox.ts";
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,14 @@
1
+ export * from "./http-server.js";
2
+ export * from "./errors.js";
3
+ export * from "./metadata.js";
4
+ export * from "./metadata-pg.js";
5
+ export * from "./work.js";
6
+ export * from "./work-memory.js";
7
+ export * from "./work-pg.js";
8
+ export * from "./registries.js";
9
+ export * from "./broadcast.js";
10
+ export * from "./idempotency.js";
11
+ export * from "./session-service.js";
12
+ export * from "./session-worker.js";
13
+ export * from "./inbox.js";
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Managed session metadata in Postgres.
3
+ *
4
+ * The memory and disk stores are single-process by construction: with the memory one a restart
5
+ * loses every session's identity, and with the disk one a second node cannot resolve sessions
6
+ * the first created. Since the default is the memory store, a multi-node deployment that never
7
+ * supplies one appears to work until the first restart — this is the implementation that makes
8
+ * "more than one process" actually hold.
9
+ *
10
+ * The row is a write-ahead identity record: it is claimed before the repository row is created,
11
+ * so a crash in between leaves a resolvable-but-unused id rather than a durable session the
12
+ * managed layer cannot name.
13
+ */
14
+ import type { PgExecutor } from "operon-agents";
15
+ import type { ManagedSessionMetadata, ManagedSessionMetadataStore } from "./metadata.ts";
16
+ export interface PgManagedSessionMetadataStoreOptions {
17
+ readonly pool: PgExecutor;
18
+ readonly table?: string;
19
+ }
20
+ export declare function managedSessionMetadataTableDDL(table?: string): string;
21
+ export declare class PgManagedSessionMetadataStore implements ManagedSessionMetadataStore {
22
+ private readonly pool;
23
+ private readonly table;
24
+ constructor(options: PgManagedSessionMetadataStoreOptions);
25
+ get(sessionId: string): Promise<ManagedSessionMetadata | undefined>;
26
+ getMany(sessionIds: readonly string[]): Promise<ReadonlyMap<string, ManagedSessionMetadata>>;
27
+ /** Atomic claim: false means another creator already owns this id. */
28
+ create(metadata: ManagedSessionMetadata): Promise<boolean>;
29
+ delete(sessionId: string): Promise<void>;
30
+ }
31
+ //# sourceMappingURL=metadata-pg.d.ts.map