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,658 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The managed API surface: reads and writes of session state.
|
|
3
|
+
*
|
|
4
|
+
* Every method here is a store operation. Nothing opens a session, assembles capabilities,
|
|
5
|
+
* connects an MCP server or boots a sandbox — that is what running a turn does, and running is
|
|
6
|
+
* the worker's job (`SessionWorker`), reached by writing to the log rather than by calling in.
|
|
7
|
+
*
|
|
8
|
+
* The practical consequence is that this object is stateless and horizontally scalable: any
|
|
9
|
+
* replica can serve any request for any session, because the session is not "somewhere" — it is
|
|
10
|
+
* in the store. A gateway in front of it needs no lease lookup and no owner affinity; it is a
|
|
11
|
+
* plain reverse proxy.
|
|
12
|
+
*
|
|
13
|
+
* What this deliberately does NOT have is an `open()`. A resource API that can only be reached
|
|
14
|
+
* by first reviving a runtime makes every read a potential sandbox wake-up, which is how a
|
|
15
|
+
* simple event-stream subscription ends up billing for compute.
|
|
16
|
+
*/
|
|
17
|
+
import { agentEventFromRecord, INTERRUPTION_STATE_KEY, newAgentEventId, flattenPendingInterrupts, parseInterruptionState, watchRecordsByPolling, SessionRepositoryConflictError, } from "operon-agents";
|
|
18
|
+
import { CONTROL_RECORD_NAME, hasUnprocessedInbox } from "./inbox.js";
|
|
19
|
+
import { MemoryManagedSessionMetadataStore, } from "./metadata.js";
|
|
20
|
+
import { MemoryManagedDeliveryIdempotencyStore, } from "./idempotency.js";
|
|
21
|
+
import { ManagedConflictError, ManagedInvalidRequestError, ManagedSessionNotFoundError } from "./errors.js";
|
|
22
|
+
export class SessionService {
|
|
23
|
+
repository;
|
|
24
|
+
environments;
|
|
25
|
+
metadata;
|
|
26
|
+
ownerKey;
|
|
27
|
+
work;
|
|
28
|
+
idempotency;
|
|
29
|
+
broadcaster;
|
|
30
|
+
stallCheckMs;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.repository = options.repository;
|
|
33
|
+
this.environments = options.environments;
|
|
34
|
+
this.metadata = options.metadataStore ?? new MemoryManagedSessionMetadataStore();
|
|
35
|
+
this.ownerKey = options.ownerKey;
|
|
36
|
+
this.work = options.work;
|
|
37
|
+
this.idempotency = options.idempotencyStore ?? new MemoryManagedDeliveryIdempotencyStore();
|
|
38
|
+
this.broadcaster = options.broadcaster;
|
|
39
|
+
this.stallCheckMs = options.stallCheckMs ?? 20_000;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Is this session waiting on work nobody is doing?
|
|
43
|
+
*
|
|
44
|
+
* BOTH conditions are required, and each alone is a false positive waiting to happen: an idle
|
|
45
|
+
* session has no holder and that is fine, and a session mid-turn has unprocessed input right
|
|
46
|
+
* up until the cursor advances. Only "there is work AND nobody holds it" is unambiguous.
|
|
47
|
+
*
|
|
48
|
+
* Undefined when it cannot be determined (the table cannot be asked), because reporting a
|
|
49
|
+
* problem on missing evidence is worse than reporting nothing.
|
|
50
|
+
*/
|
|
51
|
+
async isStranded(id) {
|
|
52
|
+
try {
|
|
53
|
+
if (await this.work.peek(id))
|
|
54
|
+
return false;
|
|
55
|
+
// Waiting on a person is not waiting on a worker.
|
|
56
|
+
if ((await this.summary(id)).durableState === "interrupted")
|
|
57
|
+
return false;
|
|
58
|
+
const store = await this.openStore(id);
|
|
59
|
+
try {
|
|
60
|
+
// Unprocessed INBOX, not "cursor behind the log head": every turn writes records after
|
|
61
|
+
// the input it answered, so the head is past the cursor on every session that has ever
|
|
62
|
+
// run. Only inputs and commands after the cursor mean there is work.
|
|
63
|
+
return await hasUnprocessedInbox(store);
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await store.close?.();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Register a session. Creating it starts no work and provisions nothing: the record exists in
|
|
75
|
+
* the repository and a worker picks it up the first time there is something to process.
|
|
76
|
+
*
|
|
77
|
+
* The agent reference is recorded, not resolved — turning it into an `Agent` needs the model
|
|
78
|
+
* and tool configuration a worker holds, and doing it here would make creation depend on
|
|
79
|
+
* execution being available.
|
|
80
|
+
*/
|
|
81
|
+
async create(input) {
|
|
82
|
+
assertCreateSessionRequest(input);
|
|
83
|
+
const agent = agentRef(input.agent);
|
|
84
|
+
const environment = environmentRef(input.environment);
|
|
85
|
+
const resolved = await this.environments.resolve(environment);
|
|
86
|
+
const now = Date.now();
|
|
87
|
+
const sessionId = input.id ?? managedSessionId();
|
|
88
|
+
// Metadata is the write-ahead identity record: after the repository commits, a crash must
|
|
89
|
+
// never leave a durable session the managed layer cannot resolve on restart.
|
|
90
|
+
const claimed = await this.metadata.create({
|
|
91
|
+
version: 1,
|
|
92
|
+
sessionId,
|
|
93
|
+
agent,
|
|
94
|
+
environment,
|
|
95
|
+
...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
|
|
96
|
+
createdAt: now,
|
|
97
|
+
updatedAt: now,
|
|
98
|
+
});
|
|
99
|
+
if (!claimed)
|
|
100
|
+
throw new ManagedConflictError(`session "${sessionId}" already exists`);
|
|
101
|
+
try {
|
|
102
|
+
const handle = await this.repository.create({
|
|
103
|
+
id: sessionId,
|
|
104
|
+
workDir: resolved.workDir,
|
|
105
|
+
...(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : {}),
|
|
106
|
+
...(input.title !== undefined ? { title: input.title } : {}),
|
|
107
|
+
});
|
|
108
|
+
await handle.store.close?.();
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
await this.metadata.delete(sessionId).catch(() => undefined);
|
|
112
|
+
if (error instanceof SessionRepositoryConflictError)
|
|
113
|
+
throw new ManagedConflictError(error.message);
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
id: sessionId,
|
|
118
|
+
...(input.title !== undefined ? { title: input.title } : {}),
|
|
119
|
+
agent,
|
|
120
|
+
environment,
|
|
121
|
+
createdAt: now,
|
|
122
|
+
updatedAt: now,
|
|
123
|
+
state: "idle",
|
|
124
|
+
activeTurnId: null,
|
|
125
|
+
hasQueuedMessages: false,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async get(id) {
|
|
129
|
+
const metadata = await this.requireMetadata(id);
|
|
130
|
+
const summary = await this.summary(id);
|
|
131
|
+
return this.toManagedSession(summary, metadata);
|
|
132
|
+
}
|
|
133
|
+
async list() {
|
|
134
|
+
const summaries = await this.repository.list(this.ownerKey !== undefined ? { ownerKey: this.ownerKey } : undefined);
|
|
135
|
+
const metadataById = await this.metadata.getMany(summaries.map((summary) => summary.id));
|
|
136
|
+
const result = [];
|
|
137
|
+
for (const summary of summaries) {
|
|
138
|
+
const metadata = metadataById.get(summary.id);
|
|
139
|
+
if (metadata === undefined)
|
|
140
|
+
continue;
|
|
141
|
+
result.push(this.toManagedSession(summary, metadata));
|
|
142
|
+
}
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
async listEvents(id, options) {
|
|
146
|
+
await this.requireMetadata(id);
|
|
147
|
+
const store = await this.openStore(id);
|
|
148
|
+
try {
|
|
149
|
+
let cursor = options.after;
|
|
150
|
+
// Read ahead until one extra PROJECTABLE event is found. Records such as metadata,
|
|
151
|
+
// permission and config are intentionally absent from AgentEvent; they must not create a
|
|
152
|
+
// second managed-only event vocabulary merely to make pages look full.
|
|
153
|
+
const wanted = options.limit + 1;
|
|
154
|
+
const events = [];
|
|
155
|
+
let exhausted = false;
|
|
156
|
+
while (events.length < wanted && !exhausted) {
|
|
157
|
+
const page = await store.readRecordPage({
|
|
158
|
+
limit: Math.max(64, wanted - events.length),
|
|
159
|
+
...(cursor !== undefined ? { after: cursor } : {}),
|
|
160
|
+
...(options.order !== undefined ? { order: options.order } : {}),
|
|
161
|
+
...(options.address !== undefined ? { address: options.address } : {}),
|
|
162
|
+
});
|
|
163
|
+
for (const stored of page.data) {
|
|
164
|
+
cursor = stored.sequence;
|
|
165
|
+
const event = agentEventFromRecord(stored.record, id);
|
|
166
|
+
if (event !== undefined)
|
|
167
|
+
events.push({ sequence: stored.sequence, event });
|
|
168
|
+
if (events.length === wanted)
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
if (events.length === wanted)
|
|
172
|
+
break;
|
|
173
|
+
if (page.next === undefined)
|
|
174
|
+
exhausted = true;
|
|
175
|
+
else
|
|
176
|
+
cursor = page.next;
|
|
177
|
+
}
|
|
178
|
+
const pageItems = events.slice(0, options.limit);
|
|
179
|
+
return {
|
|
180
|
+
data: pageItems.map((item) => item.event),
|
|
181
|
+
...(events.length > options.limit && pageItems.length > 0
|
|
182
|
+
? { next: pageItems[pageItems.length - 1].sequence }
|
|
183
|
+
: {}),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
await store.close?.();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Follow a session's events from a cursor.
|
|
192
|
+
*
|
|
193
|
+
* Order of operations matters and is the whole reason this is not two loops glued together:
|
|
194
|
+
* the broadcast subscription is opened FIRST and buffered, the store is read second, and only
|
|
195
|
+
* then does the buffer drain. Reading first and subscribing after leaves a window in which
|
|
196
|
+
* events land in neither — the exact race a client cannot detect, because the stream simply
|
|
197
|
+
* appears to skip.
|
|
198
|
+
*
|
|
199
|
+
* Duplicates across the seam are removed by event id: an event may legitimately arrive from
|
|
200
|
+
* both sides when it was persisted just as the backfill was catching up.
|
|
201
|
+
*
|
|
202
|
+
* Without a broadcaster this degrades to polling the store, which carries only persisted
|
|
203
|
+
* events. That is correct, just later and thinner.
|
|
204
|
+
*/
|
|
205
|
+
async *watchEvents(id, options = {}) {
|
|
206
|
+
await this.requireMetadata(id);
|
|
207
|
+
if (this.broadcaster === undefined) {
|
|
208
|
+
yield* this.watchStore(id, options);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const queue = new EventQueue();
|
|
212
|
+
const matches = (event) => options.address === undefined || event.address === options.address;
|
|
213
|
+
const unsubscribe = this.broadcaster.subscribe(id, (event) => {
|
|
214
|
+
if (matches(event))
|
|
215
|
+
queue.push(event);
|
|
216
|
+
});
|
|
217
|
+
const stopSubscription = () => {
|
|
218
|
+
unsubscribe();
|
|
219
|
+
queue.close();
|
|
220
|
+
};
|
|
221
|
+
options.signal?.addEventListener("abort", stopSubscription, { once: true });
|
|
222
|
+
try {
|
|
223
|
+
const seen = new Set();
|
|
224
|
+
// Backfill. The subscription is already buffering everything produced meanwhile.
|
|
225
|
+
// Events from the live side that the backfill has not reached yet are the overlap; the
|
|
226
|
+
// cursor only bounds how far back the backfill starts, never what the live side carries.
|
|
227
|
+
const backfill = new AbortController();
|
|
228
|
+
const onAbort = () => backfill.abort();
|
|
229
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
230
|
+
try {
|
|
231
|
+
for await (const event of this.watchStore(id, {
|
|
232
|
+
...options,
|
|
233
|
+
signal: backfill.signal,
|
|
234
|
+
untilCaughtUp: true,
|
|
235
|
+
})) {
|
|
236
|
+
seen.add(event.eventId);
|
|
237
|
+
yield event;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
242
|
+
}
|
|
243
|
+
if (options.signal?.aborted === true)
|
|
244
|
+
return;
|
|
245
|
+
// Hand over to the live tail, dropping anything the backfill already produced.
|
|
246
|
+
let warnedStranded = false;
|
|
247
|
+
for await (const event of queue.withIdleTicks(this.stallCheckMs)) {
|
|
248
|
+
if (event === IDLE) {
|
|
249
|
+
// Silence is only meaningful if the session is supposed to be busy.
|
|
250
|
+
if (warnedStranded)
|
|
251
|
+
continue;
|
|
252
|
+
const stranded = await this.isStranded(id);
|
|
253
|
+
if (stranded !== true)
|
|
254
|
+
continue;
|
|
255
|
+
warnedStranded = true;
|
|
256
|
+
yield {
|
|
257
|
+
type: "warning",
|
|
258
|
+
message: "This session has unprocessed input but no runner holds it — it is waiting to be " +
|
|
259
|
+
"picked up. Work resumes automatically once a worker claims it.",
|
|
260
|
+
address: options.address ?? "main",
|
|
261
|
+
sessionId: id,
|
|
262
|
+
eventId: `evt_stalled_${String(Date.now())}`,
|
|
263
|
+
};
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
warnedStranded = false;
|
|
267
|
+
if (seen.size > 0 && seen.has(event.eventId))
|
|
268
|
+
continue;
|
|
269
|
+
// The overlap window closes once the first non-duplicate arrives; keeping the set around
|
|
270
|
+
// after that would grow without bound for the life of the connection.
|
|
271
|
+
if (seen.size > 0)
|
|
272
|
+
seen.clear();
|
|
273
|
+
yield event;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
options.signal?.removeEventListener("abort", stopSubscription);
|
|
278
|
+
stopSubscription();
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/** Read the log, either to the current head (`untilCaughtUp`) or indefinitely. */
|
|
282
|
+
async *watchStore(id, options) {
|
|
283
|
+
const store = await this.openStore(id);
|
|
284
|
+
try {
|
|
285
|
+
// The public cursor is an event id; the store's is a sequence. Translate once, up front.
|
|
286
|
+
let cursor = options.after === undefined
|
|
287
|
+
? undefined
|
|
288
|
+
: await sequenceOfEvent(store, options.after, options.address);
|
|
289
|
+
if (options.untilCaughtUp === true) {
|
|
290
|
+
for (;;) {
|
|
291
|
+
if (options.signal?.aborted === true)
|
|
292
|
+
return;
|
|
293
|
+
const page = await store.readRecordPage({
|
|
294
|
+
limit: 256,
|
|
295
|
+
...(cursor !== undefined ? { after: cursor } : {}),
|
|
296
|
+
...(options.address !== undefined ? { address: options.address } : {}),
|
|
297
|
+
});
|
|
298
|
+
for (const stored of page.data) {
|
|
299
|
+
cursor = stored.sequence;
|
|
300
|
+
const event = agentEventFromRecord(stored.record, id);
|
|
301
|
+
if (event !== undefined)
|
|
302
|
+
yield event;
|
|
303
|
+
}
|
|
304
|
+
if (page.data.length < 256)
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const watch = store.watch?.bind(store) ?? ((o) => watchRecordsByPolling(store, o));
|
|
309
|
+
for await (const stored of watch({
|
|
310
|
+
...(cursor !== undefined ? { after: cursor } : {}),
|
|
311
|
+
...(options.address !== undefined ? { address: options.address } : {}),
|
|
312
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
313
|
+
})) {
|
|
314
|
+
const event = agentEventFromRecord(stored.record, id);
|
|
315
|
+
if (event !== undefined)
|
|
316
|
+
yield event;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
await store.close?.();
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
async interruptions(id) {
|
|
324
|
+
await this.requireMetadata(id);
|
|
325
|
+
const store = await this.openStore(id);
|
|
326
|
+
try {
|
|
327
|
+
const raw = await store.getState(INTERRUPTION_STATE_KEY);
|
|
328
|
+
return raw === null ? [] : flattenPendingInterrupts(parseInterruptionState(raw));
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
await store.close?.();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Accept an input and return a receipt. The write is awaited, so the receipt means the input
|
|
336
|
+
* survives a crash — not merely that it reached a process.
|
|
337
|
+
*
|
|
338
|
+
* Acceptance is all this does. Whether the input steers a turn already in flight or starts a
|
|
339
|
+
* fresh one is decided when a worker processes it, which can be an arbitrary moment later.
|
|
340
|
+
*/
|
|
341
|
+
async appendEvent(id, request, idempotencyKey) {
|
|
342
|
+
assertCreateMessageRequest(request);
|
|
343
|
+
if (idempotencyKey !== undefined) {
|
|
344
|
+
return this.idempotency.run(id, idempotencyKey, () => this.acceptEvent(id, request));
|
|
345
|
+
}
|
|
346
|
+
return this.acceptEvent(id, request);
|
|
347
|
+
}
|
|
348
|
+
async acceptEvent(id, request) {
|
|
349
|
+
const summary = await this.summary(id);
|
|
350
|
+
await this.requireMetadata(id);
|
|
351
|
+
if (summary.durableState === "interrupted") {
|
|
352
|
+
throw new ManagedConflictError(`session "${id}" is interrupted; resume it before delivering new work`);
|
|
353
|
+
}
|
|
354
|
+
const acceptedAt = Date.now();
|
|
355
|
+
const deliveryId = managedDeliveryId();
|
|
356
|
+
const mode = request.mode ?? "auto";
|
|
357
|
+
await this.work.append(id, {
|
|
358
|
+
type: "inbox.received",
|
|
359
|
+
// Assigned here because this writes through a plain repository handle, not through a
|
|
360
|
+
// session's publishing store (which stamps one on the way past). Without it the record
|
|
361
|
+
// is unprojectable — invisible to `listEvents` and to every client, whose reconnect
|
|
362
|
+
// protocol dedupes on exactly this id.
|
|
363
|
+
eventId: newAgentEventId(),
|
|
364
|
+
time: acceptedAt,
|
|
365
|
+
address: "main",
|
|
366
|
+
input: request.input,
|
|
367
|
+
origin: {
|
|
368
|
+
kind: "external",
|
|
369
|
+
source: request.source ?? "managed-api",
|
|
370
|
+
deliveryId,
|
|
371
|
+
...(request.actor !== undefined ? { actor: request.actor } : {}),
|
|
372
|
+
...(request.metadata !== undefined
|
|
373
|
+
? { metadata: request.metadata }
|
|
374
|
+
: {}),
|
|
375
|
+
},
|
|
376
|
+
mode,
|
|
377
|
+
});
|
|
378
|
+
return {
|
|
379
|
+
deliveryId,
|
|
380
|
+
sessionId: id,
|
|
381
|
+
acceptedAt,
|
|
382
|
+
status: "queued",
|
|
383
|
+
channel: mode === "follow_up" ? "follow_up" : mode === "steer" ? "steering" : "turn",
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Ask whoever is running this session to stop, or — if nobody is — discard what is waiting.
|
|
388
|
+
*
|
|
389
|
+
* Written to the log like an input, and for the same reason: the process running the turn
|
|
390
|
+
* may be anywhere, and the only address every node shares is the store. The holder learns of
|
|
391
|
+
* it from its next heartbeat and reads it; with no holder the next worker to claim the
|
|
392
|
+
* session reads it first and skips the inputs it precedes.
|
|
393
|
+
*/
|
|
394
|
+
async requestCancel(id, options = {}) {
|
|
395
|
+
return this.appendControl(id, {
|
|
396
|
+
kind: "cancel",
|
|
397
|
+
commandId: managedCommandId(),
|
|
398
|
+
requestedAt: Date.now(),
|
|
399
|
+
...(options.actor !== undefined ? { actor: options.actor } : {}),
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Answer a durable interruption. The answers are journaled with the command, so a worker
|
|
404
|
+
* that dies mid-continuation leaves nothing for the client to resend: the next holder reads
|
|
405
|
+
* the same record and continues from the last durable pause.
|
|
406
|
+
*/
|
|
407
|
+
async answerInterruption(id, answers, options = {}) {
|
|
408
|
+
if ((await this.summary(id)).durableState !== "interrupted") {
|
|
409
|
+
throw new ManagedConflictError(`session "${id}" has no interrupted run to resume`);
|
|
410
|
+
}
|
|
411
|
+
return this.appendControl(id, {
|
|
412
|
+
kind: "resume",
|
|
413
|
+
commandId: managedCommandId(),
|
|
414
|
+
requestedAt: Date.now(),
|
|
415
|
+
answers,
|
|
416
|
+
...(options.actor !== undefined ? { actor: options.actor } : {}),
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
async appendControl(id, command) {
|
|
420
|
+
await this.requireMetadata(id);
|
|
421
|
+
await this.summary(id);
|
|
422
|
+
await this.work.append(id, {
|
|
423
|
+
type: "custom",
|
|
424
|
+
name: CONTROL_RECORD_NAME,
|
|
425
|
+
time: command.requestedAt,
|
|
426
|
+
address: "main",
|
|
427
|
+
data: command,
|
|
428
|
+
});
|
|
429
|
+
return { accepted: true, commandId: command.commandId, sessionId: id, acceptedAt: command.requestedAt };
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Soft by default: the durable record and its managed metadata are retained, and every route
|
|
433
|
+
* that resolves a session starts returning 404. `{ purge: true }` destroys both — deliberately
|
|
434
|
+
* not reachable over HTTP, so retention stays a decision the host makes on its own schedule.
|
|
435
|
+
*/
|
|
436
|
+
async delete(id, options) {
|
|
437
|
+
await this.requireMetadata(id);
|
|
438
|
+
await this.repository.delete(id, options);
|
|
439
|
+
if (options?.purge === true)
|
|
440
|
+
await this.metadata.delete(id);
|
|
441
|
+
}
|
|
442
|
+
/** Undo a soft delete. Throws when the session was purged (its metadata is gone). */
|
|
443
|
+
async restore(id) {
|
|
444
|
+
await this.requireMetadata(id);
|
|
445
|
+
await this.repository.restore(id);
|
|
446
|
+
}
|
|
447
|
+
async openStore(id) {
|
|
448
|
+
const handle = await this.repository.open(id);
|
|
449
|
+
if (handle === undefined)
|
|
450
|
+
throw new ManagedSessionNotFoundError(id);
|
|
451
|
+
return handle.store;
|
|
452
|
+
}
|
|
453
|
+
async requireMetadata(id) {
|
|
454
|
+
const metadata = await this.metadata.get(id);
|
|
455
|
+
if (metadata === undefined)
|
|
456
|
+
throw new ManagedSessionNotFoundError(id);
|
|
457
|
+
return metadata;
|
|
458
|
+
}
|
|
459
|
+
async summary(id) {
|
|
460
|
+
const summary = await this.repository.get(id);
|
|
461
|
+
// `get` on the repository deliberately still returns a soft-deleted session — it is the
|
|
462
|
+
// audit read. The managed API is the other side of that line: to a client, deleted is gone.
|
|
463
|
+
if (summary === undefined || summary.deletedAt !== undefined)
|
|
464
|
+
throw new ManagedSessionNotFoundError(id);
|
|
465
|
+
return summary;
|
|
466
|
+
}
|
|
467
|
+
toManagedSession(summary, metadata) {
|
|
468
|
+
return {
|
|
469
|
+
id: summary.id,
|
|
470
|
+
...(summary.title !== undefined ? { title: summary.title } : {}),
|
|
471
|
+
agent: metadata.agent,
|
|
472
|
+
environment: metadata.environment,
|
|
473
|
+
createdAt: summary.createdAt,
|
|
474
|
+
updatedAt: summary.updatedAt,
|
|
475
|
+
state: summary.durableState === "interrupted" ? "interrupted" : "idle",
|
|
476
|
+
activeTurnId: null,
|
|
477
|
+
hasQueuedMessages: false,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function agentRef(value) {
|
|
482
|
+
if (typeof value === "string") {
|
|
483
|
+
if (!value.trim())
|
|
484
|
+
throw new ManagedInvalidRequestError("agent id must not be empty");
|
|
485
|
+
return { id: value };
|
|
486
|
+
}
|
|
487
|
+
if (!isRecord(value) || typeof value.id !== "string" || !value.id.trim()) {
|
|
488
|
+
throw new ManagedInvalidRequestError("agent must be an id string or an object with a non-empty id");
|
|
489
|
+
}
|
|
490
|
+
if (value.version !== undefined && typeof value.version !== "string") {
|
|
491
|
+
throw new ManagedInvalidRequestError("agent version must be a string");
|
|
492
|
+
}
|
|
493
|
+
return value;
|
|
494
|
+
}
|
|
495
|
+
function environmentRef(value) {
|
|
496
|
+
if (typeof value === "string") {
|
|
497
|
+
if (!value.trim())
|
|
498
|
+
throw new ManagedInvalidRequestError("environment id must not be empty");
|
|
499
|
+
return { id: value };
|
|
500
|
+
}
|
|
501
|
+
if (!isRecord(value) || typeof value.id !== "string" || !value.id.trim()) {
|
|
502
|
+
throw new ManagedInvalidRequestError("environment must be an id string or an object with a non-empty id");
|
|
503
|
+
}
|
|
504
|
+
return value;
|
|
505
|
+
}
|
|
506
|
+
function assertCreateSessionRequest(input) {
|
|
507
|
+
if (!isRecord(input))
|
|
508
|
+
throw new ManagedInvalidRequestError("request body must be an object");
|
|
509
|
+
if (input.id !== undefined && (typeof input.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(input.id))) {
|
|
510
|
+
throw new ManagedInvalidRequestError("session id may contain only letters, digits, underscores and hyphens");
|
|
511
|
+
}
|
|
512
|
+
if (input.title !== undefined && typeof input.title !== "string") {
|
|
513
|
+
throw new ManagedInvalidRequestError("title must be a string");
|
|
514
|
+
}
|
|
515
|
+
if (input.metadata !== undefined && !isRecord(input.metadata)) {
|
|
516
|
+
throw new ManagedInvalidRequestError("metadata must be an object");
|
|
517
|
+
}
|
|
518
|
+
agentRef(input.agent);
|
|
519
|
+
environmentRef(input.environment);
|
|
520
|
+
}
|
|
521
|
+
function assertCreateMessageRequest(input) {
|
|
522
|
+
if (!isRecord(input))
|
|
523
|
+
throw new ManagedInvalidRequestError("request body must be an object");
|
|
524
|
+
if (typeof input.input !== "string" || !input.input.trim()) {
|
|
525
|
+
throw new ManagedInvalidRequestError("input must not be empty");
|
|
526
|
+
}
|
|
527
|
+
if (input.source !== undefined && (typeof input.source !== "string" || !input.source.trim())) {
|
|
528
|
+
throw new ManagedInvalidRequestError("source must be a non-empty string");
|
|
529
|
+
}
|
|
530
|
+
if (input.actor !== undefined && typeof input.actor !== "string") {
|
|
531
|
+
throw new ManagedInvalidRequestError("actor must be a string");
|
|
532
|
+
}
|
|
533
|
+
if (input.metadata !== undefined && !isRecord(input.metadata)) {
|
|
534
|
+
throw new ManagedInvalidRequestError("metadata must be an object");
|
|
535
|
+
}
|
|
536
|
+
if (input.mode !== undefined && input.mode !== "auto" && input.mode !== "steer" && input.mode !== "follow_up") {
|
|
537
|
+
throw new ManagedInvalidRequestError("mode must be auto, steer or follow_up");
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function isRecord(value) {
|
|
541
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
542
|
+
}
|
|
543
|
+
let managedIdCounter = 0;
|
|
544
|
+
function managedSessionId() {
|
|
545
|
+
managedIdCounter += 1;
|
|
546
|
+
return `ms_${Date.now().toString(36)}_${managedIdCounter.toString(36)}`;
|
|
547
|
+
}
|
|
548
|
+
let deliveryCounter = 0;
|
|
549
|
+
function managedDeliveryId() {
|
|
550
|
+
deliveryCounter += 1;
|
|
551
|
+
return `delivery_${Date.now().toString(36)}_${deliveryCounter.toString(36)}`;
|
|
552
|
+
}
|
|
553
|
+
let commandCounter = 0;
|
|
554
|
+
function managedCommandId() {
|
|
555
|
+
commandCounter += 1;
|
|
556
|
+
return `cmd_${Date.now().toString(36)}_${commandCounter.toString(36)}`;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Find the log position of a public event id, scanning backwards because a resume cursor is
|
|
560
|
+
* almost always near the tail. Undefined when the log has no such event — a live-only id, or
|
|
561
|
+
* one from a session this is not — in which case the caller replays from the start.
|
|
562
|
+
*/
|
|
563
|
+
async function sequenceOfEvent(store, eventId, address) {
|
|
564
|
+
let cursor;
|
|
565
|
+
for (;;) {
|
|
566
|
+
const page = await store.readRecordPage({
|
|
567
|
+
limit: 256,
|
|
568
|
+
order: "desc",
|
|
569
|
+
...(cursor !== undefined ? { after: cursor } : {}),
|
|
570
|
+
...(address !== undefined ? { address } : {}),
|
|
571
|
+
});
|
|
572
|
+
for (const stored of page.data) {
|
|
573
|
+
if (stored.record.eventId === eventId)
|
|
574
|
+
return stored.sequence;
|
|
575
|
+
}
|
|
576
|
+
if (page.next === undefined)
|
|
577
|
+
return undefined;
|
|
578
|
+
cursor = page.next;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* A bounded async queue bridging a push callback to a `for await` loop.
|
|
583
|
+
*
|
|
584
|
+
* Bounded on purpose: a subscriber that cannot keep up must not turn an unbounded buffer into
|
|
585
|
+
* memory growth. Overflow drops the OLDEST events, because the newest are what a live view
|
|
586
|
+
* needs — and anything dropped that was persisted is still recoverable from the log.
|
|
587
|
+
*/
|
|
588
|
+
const IDLE = Symbol("idle");
|
|
589
|
+
class EventQueue {
|
|
590
|
+
items = [];
|
|
591
|
+
waiters = [];
|
|
592
|
+
closed = false;
|
|
593
|
+
capacity;
|
|
594
|
+
constructor(capacity = 1024) {
|
|
595
|
+
this.capacity = capacity;
|
|
596
|
+
}
|
|
597
|
+
push(event) {
|
|
598
|
+
if (this.closed)
|
|
599
|
+
return;
|
|
600
|
+
const waiter = this.waiters.shift();
|
|
601
|
+
if (waiter !== undefined) {
|
|
602
|
+
waiter({ value: event, done: false });
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (this.items.length >= this.capacity)
|
|
606
|
+
this.items.shift();
|
|
607
|
+
this.items.push(event);
|
|
608
|
+
}
|
|
609
|
+
close() {
|
|
610
|
+
this.closed = true;
|
|
611
|
+
for (const waiter of this.waiters.splice(0))
|
|
612
|
+
waiter({ value: undefined, done: true });
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* The same stream, but yielding `IDLE` whenever nothing has arrived for `ms`.
|
|
616
|
+
*
|
|
617
|
+
* A quiet stream is ambiguous — the model may be thinking, or whoever was running may be gone.
|
|
618
|
+
* The tick is what gives a consumer a chance to find out; it carries no information itself.
|
|
619
|
+
*/
|
|
620
|
+
async *withIdleTicks(ms) {
|
|
621
|
+
for (;;) {
|
|
622
|
+
const next = this[Symbol.asyncIterator]().next();
|
|
623
|
+
let timer;
|
|
624
|
+
const idle = new Promise((resolve) => {
|
|
625
|
+
timer = setTimeout(() => resolve(IDLE), ms);
|
|
626
|
+
timer.unref?.();
|
|
627
|
+
});
|
|
628
|
+
const winner = await Promise.race([next, idle]);
|
|
629
|
+
if (winner === IDLE) {
|
|
630
|
+
yield IDLE;
|
|
631
|
+
// The pending `next` stays pending and resolves on the following loop's race.
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
if (timer !== undefined)
|
|
635
|
+
clearTimeout(timer);
|
|
636
|
+
if (winner.done === true)
|
|
637
|
+
return;
|
|
638
|
+
yield winner.value;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
[Symbol.asyncIterator]() {
|
|
642
|
+
return {
|
|
643
|
+
next: () => {
|
|
644
|
+
const item = this.items.shift();
|
|
645
|
+
if (item !== undefined)
|
|
646
|
+
return Promise.resolve({ value: item, done: false });
|
|
647
|
+
if (this.closed)
|
|
648
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
649
|
+
return new Promise((resolve) => this.waiters.push(resolve));
|
|
650
|
+
},
|
|
651
|
+
return: () => {
|
|
652
|
+
this.close();
|
|
653
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
654
|
+
},
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
//# sourceMappingURL=session-service.js.map
|