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,136 @@
1
+ /**
2
+ * The execution half: moves a session's inbox into its conversation, and runs it.
3
+ *
4
+ * A worker is not part of the API surface and does not look for work on its own terms. It
5
+ * claims from the work table (`SessionWork`) — one row per session that has been appended to
6
+ * or is being run — and everything it does with a session happens under that session's lease.
7
+ * That is what lets the HTTP layer stay stateless, lets any node run any session, and lets a
8
+ * cancel reach the node that is running a turn without anyone knowing which node that is.
9
+ *
10
+ * ## What "processed" means
11
+ *
12
+ * An input is processed once it is IN THE CONVERSATION — once the session's own record holds
13
+ * it and the next turn, whoever runs it, will see it. That is the whole contract. Whether the
14
+ * turn it started reaches its end is not part of it: a turn that fails or dies halfway leaves
15
+ * the history intact up to where it stopped, the session reopens idle, and the next message
16
+ * continues from there. Nothing is re-run, so nothing is run twice.
17
+ *
18
+ * ## How work arrives
19
+ *
20
+ * Three ways, and all lead to `run()`:
21
+ *
22
+ * 1. `start()`: the claim loop. Asks the table for one woken session, runs it, asks again;
23
+ * when there is none, waits `claimIntervalMs`. This is the only path that exists across
24
+ * nodes, and it is one indexed statement per ask — the same thing a queue consumer's fetch
25
+ * is, and the same cost when the queue is empty.
26
+ * 2. A nudge: `drain(id)` from the API layer in the same process. Latency only — the append
27
+ * already woke the row, so a nudge that is lost or loses the lease race changes nothing
28
+ * except when the claim loop gets to it.
29
+ * 3. The heartbeat. While a session is held, every `renew` reports whether anything was
30
+ * appended since the last one. That is how a message or a cancel reaches a turn already
31
+ * running on this node when it was accepted on another.
32
+ *
33
+ * ## A worker that died mid-turn
34
+ *
35
+ * Leaves its row held past its TTL, and a `turn.started` with no end in the log. The claim
36
+ * loop takes such a row like any other; the first thing done under the new lease is to close
37
+ * the turn (`turn.ended`, reason `failed`) and hand that to live subscribers — so a client
38
+ * waiting on the turn learns it is over, instead of waiting for a message that will not come.
39
+ */
40
+ import { type Harness, type SessionRepository } from "operon-agents";
41
+ import type { ManagedSessionMetadataStore } from "./metadata.ts";
42
+ import type { ManagedAgentRegistry, ManagedEnvironmentRegistry } from "./registries.ts";
43
+ import type { EventBroadcaster } from "./broadcast.ts";
44
+ import type { SessionWork } from "./work.ts";
45
+ export interface SessionWorkerOptions<TContext = unknown> {
46
+ readonly harness: Harness<TContext>;
47
+ readonly repository: SessionRepository;
48
+ readonly metadataStore: ManagedSessionMetadataStore;
49
+ readonly environments: ManagedEnvironmentRegistry;
50
+ readonly agents?: ManagedAgentRegistry<TContext>;
51
+ /** The work table. MUST be the same one the service appends through, or nothing is ever claimed. */
52
+ readonly work: SessionWork;
53
+ readonly defaultAgentId?: string;
54
+ /**
55
+ * Heartbeat period while holding a session. MUST be comfortably below the table's TTL, and
56
+ * it is also the latency bound for a message or cancel accepted on another node to reach a
57
+ * turn running here — the renew is what carries it. Default 2s.
58
+ */
59
+ readonly renewIntervalMs?: number;
60
+ /** How long the claim loop waits after finding nothing. Default 1s. */
61
+ readonly claimIntervalMs?: number;
62
+ /** How many sessions the claim loop may hold at once. Nudges are not counted. Default 16. */
63
+ readonly concurrency?: number;
64
+ /**
65
+ * Where to republish this session's events for live subscribers.
66
+ *
67
+ * The worker is the only thing that sees an event at the moment it happens — including the
68
+ * ones that are never written down (token deltas, warnings). Handing them to a broadcaster
69
+ * here is what lets a subscriber elsewhere see them at all.
70
+ */
71
+ readonly broadcaster?: EventBroadcaster;
72
+ /**
73
+ * A run that threw — the environment would not resolve, the model was unreachable. The lease
74
+ * is released either way; what was not processed stays in the inbox, and the next append
75
+ * to that session wakes it again. Default: `console.error`.
76
+ */
77
+ readonly onError?: (error: unknown, sessionId: string) => void;
78
+ }
79
+ export declare class SessionWorker<TContext = unknown> {
80
+ private readonly harness;
81
+ private readonly repository;
82
+ private readonly metadata;
83
+ private readonly environments;
84
+ private readonly agents;
85
+ private readonly work;
86
+ private readonly renewIntervalMs;
87
+ private readonly claimIntervalMs;
88
+ private readonly concurrency;
89
+ private readonly broadcaster;
90
+ private readonly onError;
91
+ private readonly running;
92
+ /** Runs the claim loop started, counted synchronously so the cap is exact; nudges are not. */
93
+ private claimed;
94
+ private claiming;
95
+ private stopping;
96
+ private interruptPause;
97
+ constructor(options: SessionWorkerOptions<TContext>);
98
+ /** Begin claiming. Without this a worker only runs what it is nudged about in-process. */
99
+ start(): void;
100
+ /**
101
+ * Stop claiming, end every run, release every lease. Runs are ended by closing the harness
102
+ * (which aborts their turns) and told to go no further, so the leases come back promptly
103
+ * and another node can take the sessions over without waiting out a TTL.
104
+ */
105
+ stop(): Promise<void>;
106
+ private claimLoop;
107
+ /**
108
+ * Nudge: make sure this session's inbox is being read. Runs it here if nobody holds it;
109
+ * wakes the run if this process does; does nothing if another node does (its next heartbeat
110
+ * carries the wake). Resolves when the run it found or started is over, `false` when it
111
+ * could do nothing — which is not a failure, since the row is woken either way.
112
+ */
113
+ drain(sessionId: string): Promise<boolean>;
114
+ /** Everything that happens under one lease, from claim to release. Never rejects. */
115
+ private run;
116
+ private drainInbox;
117
+ private openSession;
118
+ /**
119
+ * Hand inbox items to the session in log order, advancing the cursor as soon as each one is
120
+ * in the conversation.
121
+ *
122
+ * "In the conversation" is the `message.appended` that names the item's delivery — for a
123
+ * steer, that is some step boundary of the running turn, which is why the cursor cannot
124
+ * simply move on dispatch. For an input that STARTED a turn, the turn settling counts too:
125
+ * a guardrail can refuse the input without ever journaling a message, and the input is no
126
+ * less dealt with for it.
127
+ *
128
+ * While a turn runs, the inbox is re-read on every wake — a nudge from this process, or a
129
+ * heartbeat that came back `woken` — so a message steers the turn and a cancel stops it,
130
+ * rather than waiting for it to finish. Nothing is re-read on a timer.
131
+ *
132
+ * Returns true when a cancel was processed, which ends this pass (see `drainInbox`).
133
+ */
134
+ private processInbox;
135
+ }
136
+ //# sourceMappingURL=session-worker.d.ts.map
@@ -0,0 +1,428 @@
1
+ /**
2
+ * The execution half: moves a session's inbox into its conversation, and runs it.
3
+ *
4
+ * A worker is not part of the API surface and does not look for work on its own terms. It
5
+ * claims from the work table (`SessionWork`) — one row per session that has been appended to
6
+ * or is being run — and everything it does with a session happens under that session's lease.
7
+ * That is what lets the HTTP layer stay stateless, lets any node run any session, and lets a
8
+ * cancel reach the node that is running a turn without anyone knowing which node that is.
9
+ *
10
+ * ## What "processed" means
11
+ *
12
+ * An input is processed once it is IN THE CONVERSATION — once the session's own record holds
13
+ * it and the next turn, whoever runs it, will see it. That is the whole contract. Whether the
14
+ * turn it started reaches its end is not part of it: a turn that fails or dies halfway leaves
15
+ * the history intact up to where it stopped, the session reopens idle, and the next message
16
+ * continues from there. Nothing is re-run, so nothing is run twice.
17
+ *
18
+ * ## How work arrives
19
+ *
20
+ * Three ways, and all lead to `run()`:
21
+ *
22
+ * 1. `start()`: the claim loop. Asks the table for one woken session, runs it, asks again;
23
+ * when there is none, waits `claimIntervalMs`. This is the only path that exists across
24
+ * nodes, and it is one indexed statement per ask — the same thing a queue consumer's fetch
25
+ * is, and the same cost when the queue is empty.
26
+ * 2. A nudge: `drain(id)` from the API layer in the same process. Latency only — the append
27
+ * already woke the row, so a nudge that is lost or loses the lease race changes nothing
28
+ * except when the claim loop gets to it.
29
+ * 3. The heartbeat. While a session is held, every `renew` reports whether anything was
30
+ * appended since the last one. That is how a message or a cancel reaches a turn already
31
+ * running on this node when it was accepted on another.
32
+ *
33
+ * ## A worker that died mid-turn
34
+ *
35
+ * Leaves its row held past its TTL, and a `turn.started` with no end in the log. The claim
36
+ * loop takes such a row like any other; the first thing done under the new lease is to close
37
+ * the turn (`turn.ended`, reason `failed`) and hand that to live subscribers — so a client
38
+ * waiting on the turn learns it is over, instead of waiting for a message that will not come.
39
+ */
40
+ import { closeOrphanedTurns, newAgentEventId, } from "operon-agents";
41
+ import { DefaultAgentRegistry } from "./registries.js";
42
+ import { INBOX_CURSOR_KEY, inboxItemId, readInbox, readInboxCursor, } from "./inbox.js";
43
+ export class SessionWorker {
44
+ harness;
45
+ repository;
46
+ metadata;
47
+ environments;
48
+ agents;
49
+ work;
50
+ renewIntervalMs;
51
+ claimIntervalMs;
52
+ concurrency;
53
+ broadcaster;
54
+ onError;
55
+ running = new Map();
56
+ /** Runs the claim loop started, counted synchronously so the cap is exact; nudges are not. */
57
+ claimed = 0;
58
+ claiming = false;
59
+ stopping = false;
60
+ interruptPause;
61
+ constructor(options) {
62
+ this.harness = options.harness;
63
+ this.repository = options.repository;
64
+ this.metadata = options.metadataStore;
65
+ this.environments = options.environments;
66
+ this.agents = options.agents ?? new DefaultAgentRegistry(options.defaultAgentId ?? "default");
67
+ this.work = options.work;
68
+ this.renewIntervalMs = options.renewIntervalMs ?? 2_000;
69
+ this.claimIntervalMs = options.claimIntervalMs ?? 1_000;
70
+ this.concurrency = options.concurrency ?? 16;
71
+ this.broadcaster = options.broadcaster;
72
+ this.onError = options.onError ?? ((error, sessionId) => { console.error(`session ${sessionId}:`, error); });
73
+ }
74
+ /** Begin claiming. Without this a worker only runs what it is nudged about in-process. */
75
+ start() {
76
+ if (this.claiming)
77
+ return;
78
+ this.claiming = true;
79
+ void this.claimLoop();
80
+ }
81
+ /**
82
+ * Stop claiming, end every run, release every lease. Runs are ended by closing the harness
83
+ * (which aborts their turns) and told to go no further, so the leases come back promptly
84
+ * and another node can take the sessions over without waiting out a TTL.
85
+ */
86
+ async stop() {
87
+ this.claiming = false;
88
+ this.stopping = true;
89
+ this.interruptPause?.();
90
+ for (const run of this.running.values())
91
+ run.wake.raise();
92
+ await this.harness.close();
93
+ await Promise.allSettled([...this.running.values()].map((run) => run.done));
94
+ }
95
+ async claimLoop() {
96
+ while (this.claiming) {
97
+ const lease = this.claimed < this.concurrency
98
+ ? await this.work.claim().catch(() => undefined)
99
+ : undefined;
100
+ if (lease !== undefined) {
101
+ this.claimed += 1;
102
+ void this.run(lease).finally(() => { this.claimed -= 1; });
103
+ continue;
104
+ }
105
+ await new Promise((resolve) => {
106
+ const timer = setTimeout(() => { this.interruptPause = undefined; resolve(); }, this.claimIntervalMs);
107
+ timer.unref?.();
108
+ this.interruptPause = () => { clearTimeout(timer); this.interruptPause = undefined; resolve(); };
109
+ });
110
+ }
111
+ }
112
+ /**
113
+ * Nudge: make sure this session's inbox is being read. Runs it here if nobody holds it;
114
+ * wakes the run if this process does; does nothing if another node does (its next heartbeat
115
+ * carries the wake). Resolves when the run it found or started is over, `false` when it
116
+ * could do nothing — which is not a failure, since the row is woken either way.
117
+ */
118
+ async drain(sessionId) {
119
+ const running = this.running.get(sessionId);
120
+ if (running !== undefined) {
121
+ running.wake.raise();
122
+ await running.done;
123
+ return true;
124
+ }
125
+ const lease = await this.work.acquire(sessionId);
126
+ if (lease === undefined)
127
+ return false;
128
+ await this.run(lease);
129
+ return true;
130
+ }
131
+ /** Everything that happens under one lease, from claim to release. Never rejects. */
132
+ async run(lease) {
133
+ const { sessionId } = lease;
134
+ const wake = new Wakeup();
135
+ // From the first moment, so nothing below — including waiting out a previous run of the
136
+ // same session here, whose lease this one took over — can outlast the TTL.
137
+ const heartbeat = setInterval(() => {
138
+ void lease.renew().then((beat) => { if (beat === "woken")
139
+ wake.raise(); }, () => undefined);
140
+ }, this.renewIntervalMs);
141
+ heartbeat.unref?.();
142
+ let finish;
143
+ const entry = { wake, done: new Promise((resolve) => { finish = resolve; }) };
144
+ try {
145
+ await this.running.get(sessionId)?.done;
146
+ this.running.set(sessionId, entry);
147
+ const metadata = await this.metadata.get(sessionId);
148
+ const handle = metadata === undefined ? undefined : await this.repository.open(sessionId);
149
+ if (metadata === undefined || handle === undefined)
150
+ return;
151
+ const halted = () => lease.signal.aborted || this.stopping;
152
+ try {
153
+ // A wake raised after the last inbox read means go around; one raised before it was
154
+ // covered by that read. `take` at the top of each pass draws that line.
155
+ do {
156
+ wake.take();
157
+ await this.drainInbox(sessionId, metadata, handle.store, halted, wake);
158
+ } while (wake.take() && !halted());
159
+ }
160
+ finally {
161
+ await handle.store.close?.();
162
+ }
163
+ }
164
+ catch (error) {
165
+ // A failure OUTSIDE any turn: the environment would not resolve, the sandbox would not
166
+ // boot, the store was unreachable. No turn was ever opened, so there is nothing for the
167
+ // runner to close (a failure INSIDE a turn is closed there, with `turn.ended` reason
168
+ // "failed"). Tell live subscribers with an `error` event. The unprocessed input is still
169
+ // in the inbox, so the stream's stranded check would eventually speak up on its own; this
170
+ // says what went wrong, now, instead of only that nobody is working.
171
+ this.broadcaster?.publish(sessionId, {
172
+ type: "error",
173
+ message: error instanceof Error ? error.message : String(error),
174
+ address: "main",
175
+ sessionId,
176
+ eventId: newAgentEventId(),
177
+ });
178
+ this.onError(error, sessionId);
179
+ }
180
+ finally {
181
+ clearInterval(heartbeat);
182
+ if (this.running.get(sessionId) === entry)
183
+ this.running.delete(sessionId);
184
+ await lease.release().catch(() => undefined);
185
+ finish();
186
+ }
187
+ }
188
+ async drainInbox(sessionId, metadata, store, halted, wake) {
189
+ // A turn the previous holder never finished is closed here, under the lease, before
190
+ // anything else — and its end is broadcast, which opening the session would not do.
191
+ if (await lastTurnIsOpen(store)) {
192
+ for (const event of await closeOrphanedTurns(sessionId, store))
193
+ this.broadcaster?.publish(sessionId, event);
194
+ }
195
+ for (;;) {
196
+ if (halted())
197
+ return;
198
+ const items = await readInbox(store, await readInboxCursor(store));
199
+ // Cheap check before paying for a session: an empty inbox means nothing to open for.
200
+ if (items.length === 0)
201
+ return;
202
+ // Cancels with nothing ahead of them to cancel are already in the state they ask for.
203
+ // Step over them without booting a sandbox to do it.
204
+ if (items.every((item) => item.kind === "control" && item.command.kind === "cancel")) {
205
+ await store.putState(INBOX_CURSOR_KEY, items[items.length - 1].sequence);
206
+ continue;
207
+ }
208
+ const session = await this.openSession(sessionId, metadata);
209
+ let cancelled;
210
+ try {
211
+ cancelled = await this.processInbox(session, store, halted, wake);
212
+ }
213
+ finally {
214
+ await session.close();
215
+ }
216
+ // After a cancel the object is thrown away: it may still hold, in its in-memory steer
217
+ // queues, inputs the cancel discarded, and a fresh object has none of them.
218
+ if (!cancelled)
219
+ return;
220
+ }
221
+ }
222
+ async openSession(sessionId, metadata) {
223
+ const [agentResolution, environmentResolution] = await Promise.all([
224
+ this.agents.resolve(metadata.agent),
225
+ this.environments.resolve(metadata.environment),
226
+ ]);
227
+ const session = await this.harness.resumeSession(sessionId, {
228
+ ...agentResolution.resumeOptions,
229
+ ...(environmentResolution.machine !== undefined ? { machine: environmentResolution.machine } : {}),
230
+ ...(agentResolution.agent !== undefined ? { agent: agentResolution.agent } : {}),
231
+ eventPublication: "committed",
232
+ });
233
+ if (this.broadcaster !== undefined) {
234
+ // Not unsubscribed: the subscription dies with the session it is attached to.
235
+ session.onEvent((event) => { this.broadcaster?.publish(sessionId, event); });
236
+ }
237
+ return session;
238
+ }
239
+ /**
240
+ * Hand inbox items to the session in log order, advancing the cursor as soon as each one is
241
+ * in the conversation.
242
+ *
243
+ * "In the conversation" is the `message.appended` that names the item's delivery — for a
244
+ * steer, that is some step boundary of the running turn, which is why the cursor cannot
245
+ * simply move on dispatch. For an input that STARTED a turn, the turn settling counts too:
246
+ * a guardrail can refuse the input without ever journaling a message, and the input is no
247
+ * less dealt with for it.
248
+ *
249
+ * While a turn runs, the inbox is re-read on every wake — a nudge from this process, or a
250
+ * heartbeat that came back `woken` — so a message steers the turn and a cancel stops it,
251
+ * rather than waiting for it to finish. Nothing is re-read on a timer.
252
+ *
253
+ * Returns true when a cancel was processed, which ends this pass (see `drainInbox`).
254
+ */
255
+ async processInbox(session, store, halted, wake) {
256
+ const consumed = new Set();
257
+ const unsubscribe = session.onEvent((event) => {
258
+ if (event.type !== "message.appended")
259
+ return;
260
+ const origin = event.origin;
261
+ if (origin?.kind !== "external")
262
+ return;
263
+ consumed.add(origin.deliveryId);
264
+ // Persist the cursor now, not when the turn ends: a holder that dies in between must not
265
+ // leave an input that IS in the conversation looking like one that is not.
266
+ wake.raise();
267
+ });
268
+ try {
269
+ let cursor = await readInboxCursor(store);
270
+ // Dispatched, not yet in the conversation, in log order. The cursor advances across the
271
+ // contiguous consumed prefix, so an item can never be skipped by a later one landing first.
272
+ const outstanding = [];
273
+ let completion;
274
+ const advance = async () => {
275
+ let moved = false;
276
+ while (outstanding.length > 0 && consumed.has(inboxItemId(outstanding[0]))) {
277
+ cursor = outstanding.shift().sequence;
278
+ moved = true;
279
+ }
280
+ if (moved)
281
+ await store.putState(INBOX_CURSOR_KEY, cursor);
282
+ };
283
+ for (;;) {
284
+ if (halted())
285
+ break;
286
+ wake.take();
287
+ const items = [...await readInbox(store, cursor, new Set(outstanding.map((item) => item.sequence)))];
288
+ // A cancel discards everything that precedes it: the turn in flight, inputs dispatched
289
+ // to it but not yet taken, and inputs in this batch that never got dispatched. "Stop"
290
+ // means stop, not "stop, then carry on with what was queued".
291
+ const lastCancel = findLastIndex(items, (item) => item.kind === "control" && item.command.kind === "cancel");
292
+ if (lastCancel !== -1) {
293
+ for (const item of outstanding)
294
+ consumed.add(inboxItemId(item));
295
+ for (const item of items.slice(0, lastCancel + 1)) {
296
+ outstanding.push(item);
297
+ consumed.add(inboxItemId(item));
298
+ }
299
+ if (completion !== undefined) {
300
+ session.cancel();
301
+ await completion;
302
+ }
303
+ await advance();
304
+ return true;
305
+ }
306
+ // Paused for an answer: inputs ahead of the resume that answers it are the ones the
307
+ // paused turn already took (the service accepts no new input while interrupted), so
308
+ // they are done, not dispatchable. Without a resume there is nothing to do but wait.
309
+ if (session.status.state === "interrupted" && completion === undefined) {
310
+ const resumeAt = items.findIndex((item) => item.kind === "control" && item.command.kind === "resume");
311
+ if (resumeAt === -1)
312
+ break;
313
+ for (const item of items.slice(0, resumeAt)) {
314
+ outstanding.push(item);
315
+ consumed.add(inboxItemId(item));
316
+ }
317
+ items.splice(0, resumeAt);
318
+ }
319
+ for (const item of items) {
320
+ if (halted())
321
+ break;
322
+ outstanding.push(item);
323
+ const id = inboxItemId(item);
324
+ if (item.kind === "input") {
325
+ const receipt = session.dispatchAccepted(item.input, {
326
+ kind: "external",
327
+ source: item.origin.source,
328
+ deliveryId: item.origin.deliveryId,
329
+ channel: item.mode === "follow_up" ? "follow_up" : "steering",
330
+ ...(item.origin.actor !== undefined ? { actor: item.origin.actor } : {}),
331
+ ...(item.origin.metadata !== undefined ? { metadata: item.origin.metadata } : {}),
332
+ });
333
+ if (receipt.completion !== undefined) {
334
+ // Resolved: the turn ran to some end (answered, refused by a guardrail, paused)
335
+ // and the input is dealt with even if no message ever named it. Rejected: the
336
+ // turn failed; if the message got in, `message.appended` already said so, and if
337
+ // it did not, the input is still after the cursor for the next drain.
338
+ completion = receipt.completion.then(() => { consumed.add(id); }, () => undefined);
339
+ }
340
+ }
341
+ else if (item.command.kind === "resume") {
342
+ completion = session.resume({ ...item.command.answers }).then(() => { consumed.add(id); }, () => { consumed.add(id); });
343
+ }
344
+ }
345
+ if (completion !== undefined) {
346
+ // A turn is running. Sleep until it ends or something new arrives, whichever first.
347
+ const settled = await Promise.race([
348
+ completion.then(() => "done"),
349
+ wake.wait().then(() => "woken"),
350
+ ]);
351
+ if (settled === "done")
352
+ completion = undefined;
353
+ }
354
+ await advance();
355
+ // Nothing running and nothing new: done. Anything still outstanding was dispatched to a
356
+ // turn that ended without taking it; it is still after the cursor, and the next run —
357
+ // the next append, or the next claim — dispatches it again on a fresh object.
358
+ if (completion === undefined && items.length === 0)
359
+ break;
360
+ }
361
+ }
362
+ finally {
363
+ unsubscribe();
364
+ }
365
+ return false;
366
+ }
367
+ }
368
+ /**
369
+ * A latch that remembers. `raise` sets it; `take` reads and clears it; `wait` resolves at the
370
+ * next raise, or at once if one is pending. Raises are never lost between a `take` and a
371
+ * `wait`, which is what lets the feed loop sleep on it without a timer as a backstop.
372
+ */
373
+ class Wakeup {
374
+ pending = false;
375
+ waiters = [];
376
+ raise() {
377
+ this.pending = true;
378
+ for (const waiter of this.waiters.splice(0))
379
+ waiter();
380
+ }
381
+ take() {
382
+ const was = this.pending;
383
+ this.pending = false;
384
+ return was;
385
+ }
386
+ wait() {
387
+ if (this.pending)
388
+ return Promise.resolve();
389
+ return new Promise((resolve) => { this.waiters.push(resolve); });
390
+ }
391
+ }
392
+ /**
393
+ * Is the main frame still inside a turn? Decided by the LAST turn lifecycle record, read
394
+ * backwards — a finished turn ends on its `turn.ended`, so this stops within a page for any
395
+ * session that is fine, and only walks a whole turn for one that was cut off inside it.
396
+ */
397
+ async function lastTurnIsOpen(store) {
398
+ let cursor;
399
+ for (;;) {
400
+ const page = await store.readRecordPage({
401
+ limit: 64,
402
+ order: "desc",
403
+ address: "main",
404
+ ...(cursor !== undefined ? { after: cursor } : {}),
405
+ });
406
+ for (const stored of page.data) {
407
+ const record = stored.record;
408
+ if (record.type !== "event.lifecycle")
409
+ continue;
410
+ const type = record.event.type;
411
+ if (type === "turn.started")
412
+ return true;
413
+ if (type === "turn.ended" || type === "turn.paused")
414
+ return false;
415
+ }
416
+ if (page.next === undefined)
417
+ return false;
418
+ cursor = page.next;
419
+ }
420
+ }
421
+ function findLastIndex(items, predicate) {
422
+ for (let index = items.length - 1; index >= 0; index -= 1) {
423
+ if (predicate(items[index]))
424
+ return index;
425
+ }
426
+ return -1;
427
+ }
428
+ //# sourceMappingURL=session-worker.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The work table in process memory: correct for one process, and shaped exactly like the
3
+ * Postgres one so a single-node deployment rehearses the multi-node behaviour — a claim loop
4
+ * finds what `append` woke, a holder's `renew` carries the wake, an expired lease is taken over.
5
+ *
6
+ * Not a substitute across processes: two processes over one disk repository each get their own
7
+ * table, and both would claim the same session.
8
+ */
9
+ import type { AgentRecord, SessionRepository } from "operon-agents";
10
+ import type { SessionWork, WorkLease } from "./work.ts";
11
+ export interface MemorySessionWorkOptions {
12
+ readonly repository: SessionRepository;
13
+ readonly ttlMs?: number;
14
+ }
15
+ export declare class MemorySessionWork implements SessionWork {
16
+ private readonly repository;
17
+ private readonly ttlMs;
18
+ private readonly rows;
19
+ constructor(options: MemorySessionWorkOptions);
20
+ append(sessionId: string, record: AgentRecord): Promise<void>;
21
+ claim(): Promise<WorkLease | undefined>;
22
+ acquire(sessionId: string): Promise<WorkLease | undefined>;
23
+ peek(sessionId: string): Promise<boolean>;
24
+ private row;
25
+ private take;
26
+ }
27
+ //# sourceMappingURL=work-memory.d.ts.map
@@ -0,0 +1,85 @@
1
+ import { ManagedSessionNotFoundError } from "./errors.js";
2
+ const DEFAULT_TTL_MS = 30_000;
3
+ export class MemorySessionWork {
4
+ repository;
5
+ ttlMs;
6
+ rows = new Map();
7
+ constructor(options) {
8
+ this.repository = options.repository;
9
+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
10
+ }
11
+ async append(sessionId, record) {
12
+ const handle = await this.repository.open(sessionId);
13
+ if (handle === undefined)
14
+ throw new ManagedSessionNotFoundError(sessionId);
15
+ try {
16
+ await handle.store.appendRecord(record);
17
+ }
18
+ finally {
19
+ await handle.store.close?.();
20
+ }
21
+ this.row(sessionId).woken = true;
22
+ }
23
+ async claim() {
24
+ const now = Date.now();
25
+ for (const [sessionId, row] of this.rows) {
26
+ const abandoned = row.holder !== undefined && row.holder.until < now;
27
+ const free = row.holder === undefined || abandoned;
28
+ if (free && (row.woken || abandoned))
29
+ return this.take(sessionId, row);
30
+ }
31
+ return undefined;
32
+ }
33
+ async acquire(sessionId) {
34
+ const row = this.row(sessionId);
35
+ if (row.holder !== undefined && row.holder.until > Date.now())
36
+ return undefined;
37
+ return this.take(sessionId, row);
38
+ }
39
+ async peek(sessionId) {
40
+ const holder = this.rows.get(sessionId)?.holder;
41
+ return holder !== undefined && holder.until > Date.now();
42
+ }
43
+ row(sessionId) {
44
+ let row = this.rows.get(sessionId);
45
+ if (row === undefined) {
46
+ row = { woken: false, fence: 0 };
47
+ this.rows.set(sessionId, row);
48
+ }
49
+ return row;
50
+ }
51
+ take(sessionId, row) {
52
+ // A holder that let its TTL lapse is gone — same rule the durable table applies — and learns
53
+ // so at its next renew, exactly as it would there.
54
+ row.holder?.controller.abort();
55
+ row.fence += 1;
56
+ row.woken = false;
57
+ const holder = { controller: new AbortController(), fence: row.fence, until: Date.now() + this.ttlMs };
58
+ row.holder = holder;
59
+ const mine = () => row.holder === holder;
60
+ return {
61
+ sessionId,
62
+ fence: holder.fence,
63
+ signal: holder.controller.signal,
64
+ renew: async () => {
65
+ if (!mine() || holder.until < Date.now()) {
66
+ holder.controller.abort();
67
+ return "lost";
68
+ }
69
+ holder.until = Date.now() + this.ttlMs;
70
+ const woken = row.woken;
71
+ row.woken = false;
72
+ return woken ? "woken" : "quiet";
73
+ },
74
+ release: async () => {
75
+ holder.controller.abort();
76
+ if (!mine())
77
+ return;
78
+ row.holder = undefined;
79
+ if (!row.woken)
80
+ this.rows.delete(sessionId);
81
+ },
82
+ };
83
+ }
84
+ }
85
+ //# sourceMappingURL=work-memory.js.map