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.
- package/LICENSE +55 -0
- package/README.md +103 -0
- package/dist/client/client.d.ts +80 -0
- package/dist/client/client.js +232 -0
- package/dist/client/errors.d.ts +7 -0
- package/dist/client/errors.js +21 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +4 -0
- package/dist/client/run.d.ts +71 -0
- package/dist/client/run.js +144 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/protocol/index.d.ts +3 -0
- package/dist/protocol/index.js +3 -0
- package/dist/protocol/sse.d.ts +7 -0
- package/dist/protocol/sse.js +53 -0
- package/dist/protocol/types.d.ts +102 -0
- package/dist/protocol/types.js +2 -0
- package/dist/server/broadcast.d.ts +105 -0
- package/dist/server/broadcast.js +130 -0
- package/dist/server/errors.d.ts +23 -0
- package/dist/server/errors.js +43 -0
- package/dist/server/http-server.d.ts +54 -0
- package/dist/server/http-server.js +325 -0
- package/dist/server/idempotency.d.ts +24 -0
- package/dist/server/idempotency.js +52 -0
- package/dist/server/inbox.d.ts +64 -0
- package/dist/server/inbox.js +71 -0
- package/dist/server/index.d.ts +14 -0
- package/dist/server/index.js +14 -0
- package/dist/server/metadata-pg.d.ts +31 -0
- package/dist/server/metadata-pg.js +64 -0
- package/dist/server/metadata.d.ts +38 -0
- package/dist/server/metadata.js +107 -0
- package/dist/server/registries.d.ts +40 -0
- package/dist/server/registries.js +26 -0
- package/dist/server/session-service.d.ts +181 -0
- package/dist/server/session-service.js +658 -0
- package/dist/server/session-worker.d.ts +136 -0
- package/dist/server/session-worker.js +428 -0
- package/dist/server/work-memory.d.ts +27 -0
- package/dist/server/work-memory.js +85 -0
- package/dist/server/work-pg.d.ts +46 -0
- package/dist/server/work-pg.js +122 -0
- package/dist/server/work.d.ts +49 -0
- package/dist/server/work.js +2 -0
- package/package.json +56 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
export class RunInterruptedError extends Error {
|
|
2
|
+
sessionId;
|
|
3
|
+
pending;
|
|
4
|
+
constructor(sessionId, pending) {
|
|
5
|
+
super(`session "${sessionId}" is waiting for an answer, but run() was called without onInterrupt. ` +
|
|
6
|
+
`Pass onInterrupt to answer it, or use the event stream directly.`);
|
|
7
|
+
this.name = "RunInterruptedError";
|
|
8
|
+
this.sessionId = sessionId;
|
|
9
|
+
this.pending = pending;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class RunTimeoutError extends Error {
|
|
13
|
+
sessionId;
|
|
14
|
+
constructor(sessionId, timeoutMs) {
|
|
15
|
+
super(`session "${sessionId}" did not finish within ${String(timeoutMs)}ms`);
|
|
16
|
+
this.name = "RunTimeoutError";
|
|
17
|
+
this.sessionId = sessionId;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export async function run(client, sessionId, input, options = {}) {
|
|
21
|
+
const request = typeof input === "string" ? { input } : input;
|
|
22
|
+
const controller = new AbortController();
|
|
23
|
+
const abort = () => controller.abort();
|
|
24
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
25
|
+
const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => controller.abort(), options.timeoutMs);
|
|
26
|
+
const events = [];
|
|
27
|
+
let interruptionsAnswered = 0;
|
|
28
|
+
let output;
|
|
29
|
+
let timedOut = false;
|
|
30
|
+
let iterator;
|
|
31
|
+
try {
|
|
32
|
+
// Trap 1: open first, then send. Reversing these can drop everything in between.
|
|
33
|
+
const stream = await client.sessions.events.stream(sessionId, { signal: controller.signal });
|
|
34
|
+
iterator = stream[Symbol.asyncIterator]();
|
|
35
|
+
const { deliveryId } = await client.sessions.messages.create(sessionId, request);
|
|
36
|
+
// Trap 2: which turn is ours. Unknown until the delivery shows up — as the origin of a
|
|
37
|
+
// fresh `turn.started`, or as a `message.appended` inside a turn already running (a steer).
|
|
38
|
+
let currentTurn;
|
|
39
|
+
let ourTurn;
|
|
40
|
+
// After answering a pause, the continuation is ours whatever id it runs under.
|
|
41
|
+
let claimNextTurn = false;
|
|
42
|
+
for (;;) {
|
|
43
|
+
let sawTerminal = false;
|
|
44
|
+
for (;;) {
|
|
45
|
+
let next;
|
|
46
|
+
try {
|
|
47
|
+
next = await iterator.next();
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (controller.signal.aborted)
|
|
51
|
+
break;
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
if (next.done)
|
|
55
|
+
break;
|
|
56
|
+
const event = next.value;
|
|
57
|
+
events.push(event);
|
|
58
|
+
options.onEvent?.(event);
|
|
59
|
+
if (event.address !== "main")
|
|
60
|
+
continue;
|
|
61
|
+
if (event.type === "turn.started") {
|
|
62
|
+
currentTurn = event.turnId;
|
|
63
|
+
if (claimNextTurn || (event.origin?.kind === "external" && event.origin.deliveryId === deliveryId)) {
|
|
64
|
+
ourTurn = event.turnId;
|
|
65
|
+
claimNextTurn = false;
|
|
66
|
+
}
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (event.type === "message.appended") {
|
|
70
|
+
if (ourTurn === undefined && event.origin?.kind === "external" && event.origin.deliveryId === deliveryId) {
|
|
71
|
+
// Inside a turn: a steer, and that turn is ours. Between turns: the prompt was
|
|
72
|
+
// journaled ahead of its turn, so the next one to start is ours.
|
|
73
|
+
if (currentTurn !== undefined)
|
|
74
|
+
ourTurn = currentTurn;
|
|
75
|
+
else
|
|
76
|
+
claimNextTurn = true;
|
|
77
|
+
}
|
|
78
|
+
if (ourTurn !== undefined && ourTurn === currentTurn && event.message.role === "assistant") {
|
|
79
|
+
const text = textOf(event.message.content);
|
|
80
|
+
if (text !== undefined)
|
|
81
|
+
output = text;
|
|
82
|
+
}
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
// Traps 3 and 4: only OUR turn ending is an ending, and even then only if nothing is
|
|
86
|
+
// waiting on us — the interruption check below decides which of the two this is.
|
|
87
|
+
if (event.type === "turn.ended") {
|
|
88
|
+
const ours = ourTurn !== undefined && event.turnId === ourTurn;
|
|
89
|
+
currentTurn = undefined;
|
|
90
|
+
if (ours) {
|
|
91
|
+
sawTerminal = true;
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (controller.signal.aborted) {
|
|
97
|
+
if (options.timeoutMs !== undefined && options.signal?.aborted !== true)
|
|
98
|
+
timedOut = true;
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
if (!sawTerminal)
|
|
102
|
+
break;
|
|
103
|
+
const pending = (await client.sessions.interruptions(sessionId)).data;
|
|
104
|
+
if (pending.length === 0)
|
|
105
|
+
break;
|
|
106
|
+
// Trap 5: no handler means fail now, loudly, rather than wait on an answer that is not coming.
|
|
107
|
+
if (options.onInterrupt === undefined)
|
|
108
|
+
throw new RunInterruptedError(sessionId, pending);
|
|
109
|
+
const answers = await options.onInterrupt({ sessionId, pending });
|
|
110
|
+
// The stream stays open across the pause, so the continuation cannot be missed.
|
|
111
|
+
claimNextTurn = true;
|
|
112
|
+
await client.sessions.resume(sessionId, answers);
|
|
113
|
+
interruptionsAnswered += 1;
|
|
114
|
+
}
|
|
115
|
+
if (timedOut)
|
|
116
|
+
throw new RunTimeoutError(sessionId, options.timeoutMs);
|
|
117
|
+
const session = await client.sessions.retrieve(sessionId);
|
|
118
|
+
return {
|
|
119
|
+
sessionId,
|
|
120
|
+
events,
|
|
121
|
+
...(output !== undefined ? { output } : {}),
|
|
122
|
+
interruptionsAnswered,
|
|
123
|
+
session,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
if (timer !== undefined)
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
options.signal?.removeEventListener("abort", abort);
|
|
130
|
+
controller.abort();
|
|
131
|
+
await iterator?.return?.(undefined).catch(() => undefined);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function textOf(content) {
|
|
135
|
+
if (typeof content === "string")
|
|
136
|
+
return content;
|
|
137
|
+
if (!Array.isArray(content))
|
|
138
|
+
return undefined;
|
|
139
|
+
const parts = content
|
|
140
|
+
.filter((part) => part.type === "text")
|
|
141
|
+
.map((part) => part.text);
|
|
142
|
+
return parts.length === 0 ? undefined : parts.join("");
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=run.js.map
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export async function* parseSse(body) {
|
|
2
|
+
const reader = body.getReader();
|
|
3
|
+
const decoder = new TextDecoder();
|
|
4
|
+
let buffer = "";
|
|
5
|
+
try {
|
|
6
|
+
for (;;) {
|
|
7
|
+
const { value, done } = await reader.read();
|
|
8
|
+
if (done)
|
|
9
|
+
break;
|
|
10
|
+
buffer += decoder.decode(value, { stream: true }).replaceAll("\r\n", "\n");
|
|
11
|
+
let separator;
|
|
12
|
+
while ((separator = buffer.indexOf("\n\n")) !== -1) {
|
|
13
|
+
const frame = buffer.slice(0, separator);
|
|
14
|
+
buffer = buffer.slice(separator + 2);
|
|
15
|
+
const decoded = decodeSseFrame(frame);
|
|
16
|
+
if (decoded !== undefined)
|
|
17
|
+
yield decoded;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
buffer += decoder.decode();
|
|
21
|
+
const decoded = decodeSseFrame(buffer);
|
|
22
|
+
if (decoded !== undefined)
|
|
23
|
+
yield decoded;
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
await reader.cancel().catch(() => undefined);
|
|
27
|
+
reader.releaseLock();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function decodeSseFrame(frame) {
|
|
31
|
+
let event = "message";
|
|
32
|
+
let id;
|
|
33
|
+
const data = [];
|
|
34
|
+
for (const line of frame.split("\n")) {
|
|
35
|
+
if (line.startsWith(":"))
|
|
36
|
+
continue;
|
|
37
|
+
if (line.startsWith("event:"))
|
|
38
|
+
event = line.slice(6).trimStart();
|
|
39
|
+
else if (line.startsWith("id:"))
|
|
40
|
+
id = line.slice(3).trimStart();
|
|
41
|
+
else if (line.startsWith("data:"))
|
|
42
|
+
data.push(line.slice(5).trimStart());
|
|
43
|
+
}
|
|
44
|
+
if (data.length === 0)
|
|
45
|
+
return undefined;
|
|
46
|
+
const raw = data.join("\n");
|
|
47
|
+
return {
|
|
48
|
+
event,
|
|
49
|
+
...(id !== undefined ? { id } : {}),
|
|
50
|
+
data: JSON.parse(raw),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=sse.js.map
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { AgentEvent, InterruptAnswer, PendingRunInterrupt } from "operon-agents";
|
|
2
|
+
export declare const MANAGED_API_VERSION: "v1";
|
|
3
|
+
/** Stable server-side reference to executable host code. */
|
|
4
|
+
export interface AgentRef {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly version?: string;
|
|
7
|
+
}
|
|
8
|
+
/** Stable server-side reference to a workspace/sandbox allocation policy. */
|
|
9
|
+
export interface EnvironmentRef {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ManagedSession {
|
|
13
|
+
readonly id: string;
|
|
14
|
+
readonly title?: string;
|
|
15
|
+
readonly agent: AgentRef;
|
|
16
|
+
readonly environment: EnvironmentRef;
|
|
17
|
+
readonly createdAt: number;
|
|
18
|
+
readonly updatedAt: number;
|
|
19
|
+
readonly state: "idle" | "running" | "interrupted" | "closed";
|
|
20
|
+
readonly activeTurnId: string | null;
|
|
21
|
+
readonly hasQueuedMessages: boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface CreateManagedSessionRequest {
|
|
24
|
+
readonly id?: string;
|
|
25
|
+
readonly title?: string;
|
|
26
|
+
readonly agent: AgentRef | string;
|
|
27
|
+
readonly environment: EnvironmentRef | string;
|
|
28
|
+
readonly metadata?: Readonly<Record<string, unknown>>;
|
|
29
|
+
}
|
|
30
|
+
export interface ListManagedSessionsResponse {
|
|
31
|
+
readonly data: readonly ManagedSession[];
|
|
32
|
+
}
|
|
33
|
+
export interface CreateManagedMessageRequest {
|
|
34
|
+
readonly input: string;
|
|
35
|
+
readonly source?: string;
|
|
36
|
+
readonly actor?: string;
|
|
37
|
+
readonly metadata?: Readonly<Record<string, string | number | boolean | null>>;
|
|
38
|
+
readonly mode?: "auto" | "steer" | "follow_up";
|
|
39
|
+
}
|
|
40
|
+
export interface DeliveryReceiptResource {
|
|
41
|
+
readonly deliveryId: string;
|
|
42
|
+
readonly sessionId: string;
|
|
43
|
+
readonly acceptedAt: number;
|
|
44
|
+
readonly status: "started" | "queued";
|
|
45
|
+
readonly channel: "turn" | "steering" | "follow_up";
|
|
46
|
+
readonly steerId?: string;
|
|
47
|
+
}
|
|
48
|
+
export interface ListSessionEventsResponse {
|
|
49
|
+
/** Durable AgentEvents in store order. Store sequence remains inside the opaque page cursor;
|
|
50
|
+
* `eventId` is the stable public identity shared with events.stream(). */
|
|
51
|
+
readonly data: readonly AgentEvent[];
|
|
52
|
+
readonly nextPage: string | null;
|
|
53
|
+
}
|
|
54
|
+
export interface ListSessionEventsOptions {
|
|
55
|
+
readonly limit?: number;
|
|
56
|
+
readonly page?: string;
|
|
57
|
+
readonly order?: "asc" | "desc";
|
|
58
|
+
readonly address?: string;
|
|
59
|
+
}
|
|
60
|
+
export interface StreamSessionEventsOptions {
|
|
61
|
+
readonly signal?: AbortSignal;
|
|
62
|
+
/** Exact AgentEvent address filter, matching events.list({ address }). */
|
|
63
|
+
readonly address?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Resume after this event id. Omit to replay the session's history first, then follow live.
|
|
66
|
+
* The id to pass is the last one the previous stream delivered; see
|
|
67
|
+
* `ManagedSessionEventStream.lastEventId`.
|
|
68
|
+
*/
|
|
69
|
+
readonly after?: string;
|
|
70
|
+
/**
|
|
71
|
+
* Reopen the stream on a dropped connection, resuming after the last durable event seen,
|
|
72
|
+
* with events already delivered filtered out. Default true. A client that wants to see the
|
|
73
|
+
* drop itself — to decide, log, or back off on its own terms — turns it off.
|
|
74
|
+
*/
|
|
75
|
+
readonly reconnect?: boolean;
|
|
76
|
+
}
|
|
77
|
+
export interface ManagedApiError {
|
|
78
|
+
readonly error: {
|
|
79
|
+
readonly code: string;
|
|
80
|
+
readonly message: string;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
export interface ResumeManagedSessionRequest {
|
|
84
|
+
readonly answers: Readonly<Record<string, InterruptAnswer>>;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Receipt for a control command (cancel, resume). Like a delivery receipt it means the command
|
|
88
|
+
* is durable, not that it has been carried out: whoever holds the session acts on it next, and
|
|
89
|
+
* if nobody does, the next worker to claim the session will.
|
|
90
|
+
*/
|
|
91
|
+
export interface ControlReceiptResource {
|
|
92
|
+
readonly accepted: true;
|
|
93
|
+
readonly commandId: string;
|
|
94
|
+
readonly sessionId: string;
|
|
95
|
+
readonly acceptedAt: number;
|
|
96
|
+
}
|
|
97
|
+
export type ResumeManagedSessionResponse = ControlReceiptResource;
|
|
98
|
+
export type CancelManagedSessionResponse = ControlReceiptResource;
|
|
99
|
+
export interface InterruptionsResponse {
|
|
100
|
+
readonly data: readonly PendingRunInterrupt[];
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The low-latency path: events from whoever is running a session to whoever is watching it.
|
|
3
|
+
*
|
|
4
|
+
* The store is the source of truth, but it is a poor delivery channel — reading it to feed
|
|
5
|
+
* subscribers makes read load scale with connected viewers rather than with data, and adds a
|
|
6
|
+
* poll interval of latency to every token. A broadcast channel carries the same events on a
|
|
7
|
+
* separate, faster path.
|
|
8
|
+
*
|
|
9
|
+
* ## It is deliberately unreliable, and that is what makes it cheap
|
|
10
|
+
*
|
|
11
|
+
* A dropped message costs nothing durable: the persisted half of the stream can always be
|
|
12
|
+
* re-read, and clients reconcile by event id on reconnect. So this needs no acknowledgements,
|
|
13
|
+
* no retries, no dead letters, and no durable queue — which is what keeps it swappable for a
|
|
14
|
+
* Redis `PUBLISH` (or NATS, or nothing at all in a single process).
|
|
15
|
+
*
|
|
16
|
+
* ## Why everything goes through here, not just the ephemeral events
|
|
17
|
+
*
|
|
18
|
+
* It is tempting to send only live-only events (token deltas) this way and let persisted events
|
|
19
|
+
* arrive via the store. That breaks ordering: a delta belongs to the message it precedes, and
|
|
20
|
+
* two paths with different latencies deliver them out of order with no way for a client to
|
|
21
|
+
* reassemble. One channel carries all of it; the store is used to fill the gap before the
|
|
22
|
+
* subscription started, not to race it.
|
|
23
|
+
*/
|
|
24
|
+
import type { AgentEvent } from "operon-agents";
|
|
25
|
+
export type BroadcastListener = (event: AgentEvent) => void;
|
|
26
|
+
export interface EventBroadcaster {
|
|
27
|
+
/**
|
|
28
|
+
* Publish to whoever is listening. Returns nothing and never throws — a broadcaster that made
|
|
29
|
+
* callers await it would put a best-effort side channel on the critical path of writing a turn.
|
|
30
|
+
*/
|
|
31
|
+
publish(sessionId: string, event: AgentEvent): void;
|
|
32
|
+
/** Listen until the returned function is called. */
|
|
33
|
+
subscribe(sessionId: string, listener: BroadcastListener): () => void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Single-process broadcaster.
|
|
37
|
+
*
|
|
38
|
+
* Correct ONLY when the worker and the API surface share a process — a demo, a test, a
|
|
39
|
+
* single-binary deployment. It is not a smaller version of the cross-process one: a worker
|
|
40
|
+
* publishes into its own Map, and a subscriber in another process is looking at a different
|
|
41
|
+
* Map, so nothing ever arrives.
|
|
42
|
+
*
|
|
43
|
+
* **That failure is completely silent.** No error, no warning, no dropped-connection — the
|
|
44
|
+
* stream simply carries persisted events only, and live-only events (token deltas) never show
|
|
45
|
+
* up. It reads exactly like "the model isn't streaming", which sends you looking in the wrong
|
|
46
|
+
* place. In the deployment this framework is built for — API surface and workers as separate
|
|
47
|
+
* services — this class is the wrong choice; use {@link RedisEventBroadcaster}.
|
|
48
|
+
*/
|
|
49
|
+
export declare class MemoryEventBroadcaster implements EventBroadcaster {
|
|
50
|
+
private readonly listeners;
|
|
51
|
+
publish(sessionId: string, event: AgentEvent): void;
|
|
52
|
+
subscribe(sessionId: string, listener: BroadcastListener): () => void;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Minimal Redis surface for pub/sub, duck-typed the same way the core store's client is —
|
|
56
|
+
* `ioredis` and `node-redis` both satisfy it, and neither becomes a dependency here.
|
|
57
|
+
*/
|
|
58
|
+
export interface BroadcastPublisher {
|
|
59
|
+
publish(channel: string, message: string): Promise<unknown>;
|
|
60
|
+
}
|
|
61
|
+
export interface BroadcastSubscriber {
|
|
62
|
+
subscribe(channel: string, ...args: unknown[]): Promise<unknown>;
|
|
63
|
+
unsubscribe(channel: string, ...args: unknown[]): Promise<unknown>;
|
|
64
|
+
on(event: "message", listener: (channel: string, message: string) => void): unknown;
|
|
65
|
+
off?(event: "message", listener: (channel: string, message: string) => void): unknown;
|
|
66
|
+
}
|
|
67
|
+
export interface RedisEventBroadcasterOptions {
|
|
68
|
+
/** Any client. Used only for `PUBLISH`, so it can be the same pool everything else uses. */
|
|
69
|
+
readonly publisher: BroadcastPublisher;
|
|
70
|
+
/**
|
|
71
|
+
* A SEPARATE connection. Redis puts a subscribed connection into a mode where it accepts
|
|
72
|
+
* almost nothing else, so sharing one with normal commands breaks them — this is the single
|
|
73
|
+
* most common way a first pub/sub integration goes wrong.
|
|
74
|
+
*/
|
|
75
|
+
readonly subscriber: BroadcastSubscriber;
|
|
76
|
+
readonly channelPrefix?: string;
|
|
77
|
+
/** Called when a payload cannot be parsed or delivered. Defaults to silence. */
|
|
78
|
+
readonly onError?: (error: unknown) => void;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Cross-process broadcaster.
|
|
82
|
+
*
|
|
83
|
+
* Required as soon as the API surface and the workers are separate processes — which is the
|
|
84
|
+
* whole point of the architecture. With the in-memory implementation a worker publishes into
|
|
85
|
+
* its own process and a subscriber on another node hears nothing, so live-only events (token
|
|
86
|
+
* deltas) never arrive: the stream silently degrades to persisted events only, with no error
|
|
87
|
+
* anywhere to notice.
|
|
88
|
+
*
|
|
89
|
+
* Still best-effort. Redis pub/sub drops messages for disconnected subscribers and does not
|
|
90
|
+
* replay, which is exactly the contract this interface promises — durability lives in the log.
|
|
91
|
+
*/
|
|
92
|
+
export declare class RedisEventBroadcaster implements EventBroadcaster {
|
|
93
|
+
private readonly publisher;
|
|
94
|
+
private readonly subscriber;
|
|
95
|
+
private readonly prefix;
|
|
96
|
+
private readonly onError;
|
|
97
|
+
private readonly listeners;
|
|
98
|
+
private wired;
|
|
99
|
+
constructor(options: RedisEventBroadcasterOptions);
|
|
100
|
+
publish(sessionId: string, event: AgentEvent): void;
|
|
101
|
+
subscribe(sessionId: string, listener: BroadcastListener): () => void;
|
|
102
|
+
/** Attach the shared message handler once, not per subscription. */
|
|
103
|
+
private wire;
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=broadcast.d.ts.map
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single-process broadcaster.
|
|
3
|
+
*
|
|
4
|
+
* Correct ONLY when the worker and the API surface share a process — a demo, a test, a
|
|
5
|
+
* single-binary deployment. It is not a smaller version of the cross-process one: a worker
|
|
6
|
+
* publishes into its own Map, and a subscriber in another process is looking at a different
|
|
7
|
+
* Map, so nothing ever arrives.
|
|
8
|
+
*
|
|
9
|
+
* **That failure is completely silent.** No error, no warning, no dropped-connection — the
|
|
10
|
+
* stream simply carries persisted events only, and live-only events (token deltas) never show
|
|
11
|
+
* up. It reads exactly like "the model isn't streaming", which sends you looking in the wrong
|
|
12
|
+
* place. In the deployment this framework is built for — API surface and workers as separate
|
|
13
|
+
* services — this class is the wrong choice; use {@link RedisEventBroadcaster}.
|
|
14
|
+
*/
|
|
15
|
+
export class MemoryEventBroadcaster {
|
|
16
|
+
listeners = new Map();
|
|
17
|
+
publish(sessionId, event) {
|
|
18
|
+
const set = this.listeners.get(sessionId);
|
|
19
|
+
if (set === undefined)
|
|
20
|
+
return;
|
|
21
|
+
// Copy before iterating: a listener may unsubscribe itself while being notified.
|
|
22
|
+
for (const listener of [...set]) {
|
|
23
|
+
try {
|
|
24
|
+
listener(event);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// One bad subscriber must not stop delivery to the others, and must not surface as an
|
|
28
|
+
// error on the publishing side — the publisher is mid-turn and has nothing to do with it.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
subscribe(sessionId, listener) {
|
|
33
|
+
let set = this.listeners.get(sessionId);
|
|
34
|
+
if (set === undefined) {
|
|
35
|
+
set = new Set();
|
|
36
|
+
this.listeners.set(sessionId, set);
|
|
37
|
+
}
|
|
38
|
+
set.add(listener);
|
|
39
|
+
return () => {
|
|
40
|
+
const current = this.listeners.get(sessionId);
|
|
41
|
+
if (current === undefined)
|
|
42
|
+
return;
|
|
43
|
+
current.delete(listener);
|
|
44
|
+
if (current.size === 0)
|
|
45
|
+
this.listeners.delete(sessionId);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Cross-process broadcaster.
|
|
51
|
+
*
|
|
52
|
+
* Required as soon as the API surface and the workers are separate processes — which is the
|
|
53
|
+
* whole point of the architecture. With the in-memory implementation a worker publishes into
|
|
54
|
+
* its own process and a subscriber on another node hears nothing, so live-only events (token
|
|
55
|
+
* deltas) never arrive: the stream silently degrades to persisted events only, with no error
|
|
56
|
+
* anywhere to notice.
|
|
57
|
+
*
|
|
58
|
+
* Still best-effort. Redis pub/sub drops messages for disconnected subscribers and does not
|
|
59
|
+
* replay, which is exactly the contract this interface promises — durability lives in the log.
|
|
60
|
+
*/
|
|
61
|
+
export class RedisEventBroadcaster {
|
|
62
|
+
publisher;
|
|
63
|
+
subscriber;
|
|
64
|
+
prefix;
|
|
65
|
+
onError;
|
|
66
|
+
listeners = new Map();
|
|
67
|
+
wired = false;
|
|
68
|
+
constructor(options) {
|
|
69
|
+
this.publisher = options.publisher;
|
|
70
|
+
this.subscriber = options.subscriber;
|
|
71
|
+
this.prefix = options.channelPrefix ?? "session:events:";
|
|
72
|
+
this.onError = options.onError ?? (() => undefined);
|
|
73
|
+
}
|
|
74
|
+
publish(sessionId, event) {
|
|
75
|
+
// Fire-and-forget: the caller is mid-turn, and a side channel must never be able to slow
|
|
76
|
+
// down or fail the work that produced the event.
|
|
77
|
+
void Promise.resolve(this.publisher.publish(this.prefix + sessionId, JSON.stringify(event)))
|
|
78
|
+
.catch(this.onError);
|
|
79
|
+
}
|
|
80
|
+
subscribe(sessionId, listener) {
|
|
81
|
+
this.wire();
|
|
82
|
+
const channel = this.prefix + sessionId;
|
|
83
|
+
let set = this.listeners.get(channel);
|
|
84
|
+
if (set === undefined) {
|
|
85
|
+
set = new Set();
|
|
86
|
+
this.listeners.set(channel, set);
|
|
87
|
+
// One Redis subscription per session, regardless of how many local listeners it has.
|
|
88
|
+
void Promise.resolve(this.subscriber.subscribe(channel)).catch(this.onError);
|
|
89
|
+
}
|
|
90
|
+
set.add(listener);
|
|
91
|
+
return () => {
|
|
92
|
+
const current = this.listeners.get(channel);
|
|
93
|
+
if (current === undefined)
|
|
94
|
+
return;
|
|
95
|
+
current.delete(listener);
|
|
96
|
+
if (current.size > 0)
|
|
97
|
+
return;
|
|
98
|
+
this.listeners.delete(channel);
|
|
99
|
+
void Promise.resolve(this.subscriber.unsubscribe(channel)).catch(this.onError);
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** Attach the shared message handler once, not per subscription. */
|
|
103
|
+
wire() {
|
|
104
|
+
if (this.wired)
|
|
105
|
+
return;
|
|
106
|
+
this.wired = true;
|
|
107
|
+
this.subscriber.on("message", (channel, message) => {
|
|
108
|
+
const set = this.listeners.get(channel);
|
|
109
|
+
if (set === undefined || set.size === 0)
|
|
110
|
+
return;
|
|
111
|
+
let event;
|
|
112
|
+
try {
|
|
113
|
+
event = JSON.parse(message);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
this.onError(error);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
for (const listener of [...set]) {
|
|
120
|
+
try {
|
|
121
|
+
listener(event);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
this.onError(error);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
//# sourceMappingURL=broadcast.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export type ManagedErrorCode = "invalid_request" | "not_found" | "conflict" | "unauthorized" | "forbidden" | "internal_error";
|
|
2
|
+
export declare class ManagedServerError extends Error {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly code: ManagedErrorCode;
|
|
5
|
+
constructor(status: number, code: ManagedErrorCode, message: string);
|
|
6
|
+
}
|
|
7
|
+
export declare class ManagedSessionNotFoundError extends ManagedServerError {
|
|
8
|
+
readonly sessionId: string;
|
|
9
|
+
constructor(sessionId: string);
|
|
10
|
+
}
|
|
11
|
+
export declare class ManagedConflictError extends ManagedServerError {
|
|
12
|
+
constructor(message: string);
|
|
13
|
+
}
|
|
14
|
+
export declare class ManagedInvalidRequestError extends ManagedServerError {
|
|
15
|
+
constructor(message: string);
|
|
16
|
+
}
|
|
17
|
+
export declare class ManagedUnauthorizedError extends ManagedServerError {
|
|
18
|
+
constructor(message?: string);
|
|
19
|
+
}
|
|
20
|
+
export declare class ManagedForbiddenError extends ManagedServerError {
|
|
21
|
+
constructor(message?: string);
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export class ManagedServerError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
code;
|
|
4
|
+
constructor(status, code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "ManagedServerError";
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export class ManagedSessionNotFoundError extends ManagedServerError {
|
|
12
|
+
sessionId;
|
|
13
|
+
constructor(sessionId) {
|
|
14
|
+
super(404, "not_found", `session "${sessionId}" not found`);
|
|
15
|
+
this.name = "ManagedSessionNotFoundError";
|
|
16
|
+
this.sessionId = sessionId;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export class ManagedConflictError extends ManagedServerError {
|
|
20
|
+
constructor(message) {
|
|
21
|
+
super(409, "conflict", message);
|
|
22
|
+
this.name = "ManagedConflictError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export class ManagedInvalidRequestError extends ManagedServerError {
|
|
26
|
+
constructor(message) {
|
|
27
|
+
super(400, "invalid_request", message);
|
|
28
|
+
this.name = "ManagedInvalidRequestError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export class ManagedUnauthorizedError extends ManagedServerError {
|
|
32
|
+
constructor(message = "authentication required") {
|
|
33
|
+
super(401, "unauthorized", message);
|
|
34
|
+
this.name = "ManagedUnauthorizedError";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export class ManagedForbiddenError extends ManagedServerError {
|
|
38
|
+
constructor(message = "request is not authorized") {
|
|
39
|
+
super(403, "forbidden", message);
|
|
40
|
+
this.name = "ManagedForbiddenError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
//# sourceMappingURL=errors.js.map
|