@saturn-universe/runtime 0.0.0-stage → 0.1.1
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 +661 -0
- package/dist/agent-loop.d.ts +48 -0
- package/dist/agent-loop.js +1072 -0
- package/dist/command-dependencies.d.ts +14 -0
- package/dist/command-dependencies.js +1 -0
- package/dist/command-handler.d.ts +10 -0
- package/dist/command-handler.js +269 -0
- package/dist/compaction.d.ts +81 -0
- package/dist/compaction.js +444 -0
- package/dist/completion-policy.d.ts +30 -0
- package/dist/completion-policy.js +502 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +8 -0
- package/dist/journal.d.ts +28 -0
- package/dist/journal.js +473 -0
- package/dist/recovery.d.ts +19 -0
- package/dist/recovery.js +103 -0
- package/dist/run-loop.d.ts +49 -0
- package/dist/run-loop.js +739 -0
- package/dist/search-loop.d.ts +57 -0
- package/dist/search-loop.js +905 -0
- package/dist/team-loop.d.ts +46 -0
- package/dist/team-loop.js +936 -0
- package/package.json +15 -3
- package/README.md +0 -3
package/dist/journal.js
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import { eventPositionCodec, isTerminalRunEventType, RuntimeError, streamsRequiredForCommit, terminalRunEventTypes, } from '@saturn-universe/core';
|
|
2
|
+
export class CausationIndex {
|
|
3
|
+
facts = new Map();
|
|
4
|
+
through = eventPositionCodec.parse('0');
|
|
5
|
+
terminal = false;
|
|
6
|
+
add(event) {
|
|
7
|
+
if (isTerminalRunEventType(event.type))
|
|
8
|
+
this.terminal = true;
|
|
9
|
+
const fact = causalFact(event, event.metadata.correlationId, () => [...this.facts.values()]);
|
|
10
|
+
// Only the latest fact for each type/entity is needed to infer the next cause.
|
|
11
|
+
const entity = fact.attemptId ??
|
|
12
|
+
fact.requestId ??
|
|
13
|
+
fact.callId ??
|
|
14
|
+
fact.stepId ??
|
|
15
|
+
fact.turnId ??
|
|
16
|
+
fact.messageId ??
|
|
17
|
+
fact.runId ??
|
|
18
|
+
fact.id;
|
|
19
|
+
const key = `${fact.type}:${entity}`;
|
|
20
|
+
this.facts.delete(key);
|
|
21
|
+
this.facts.set(key, fact);
|
|
22
|
+
while (this.facts.size > 4096)
|
|
23
|
+
this.facts.delete(this.facts.keys().next().value);
|
|
24
|
+
if (BigInt(event.position) > BigInt(this.through))
|
|
25
|
+
this.through = event.position;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function createRuntimeJournal(d) {
|
|
29
|
+
let tail = Promise.resolve();
|
|
30
|
+
const indexes = new Map();
|
|
31
|
+
return {
|
|
32
|
+
event(type, scope, payload, causationId = null) {
|
|
33
|
+
return {
|
|
34
|
+
id: d.id(),
|
|
35
|
+
type,
|
|
36
|
+
eventVersion: 1,
|
|
37
|
+
scope,
|
|
38
|
+
payload,
|
|
39
|
+
occurredAt: d.now(),
|
|
40
|
+
causationId,
|
|
41
|
+
};
|
|
42
|
+
},
|
|
43
|
+
receipt(key, command) {
|
|
44
|
+
return d.receipt(key, d.hash(command));
|
|
45
|
+
},
|
|
46
|
+
append(key, build, turnId, command) {
|
|
47
|
+
const work = tail.then(async () => {
|
|
48
|
+
const step = typeof build === 'function' && turnId
|
|
49
|
+
? { turnId, ordinal: await d.reader.nextStepOrdinal(turnId) }
|
|
50
|
+
: undefined;
|
|
51
|
+
const built = typeof build === 'function' ? build(step?.ordinal ?? 1) : build;
|
|
52
|
+
const commandHash = d.hash(command ?? defaultCommand(built));
|
|
53
|
+
const previous = await d.receipt(key, commandHash);
|
|
54
|
+
if (previous)
|
|
55
|
+
return previous;
|
|
56
|
+
const streams = streamsRequiredForCommit(built);
|
|
57
|
+
const runIds = [
|
|
58
|
+
...new Set(built.flatMap((event) => 'runId' in event.scope && event.scope.runId ? [event.scope.runId] : [])),
|
|
59
|
+
];
|
|
60
|
+
let snapshot;
|
|
61
|
+
try {
|
|
62
|
+
snapshot = await d.reader.readJournalAppendSnapshot([...streams.values()], runIds.map((runId) => ({ runId, after: indexes.get(runId)?.through })), step);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error instanceof RuntimeError && error.code === 'VERSION_CONFLICT') {
|
|
66
|
+
// The same command may have won the race before the snapshot was read.
|
|
67
|
+
const concurrentReceipt = await d.receipt(key, commandHash);
|
|
68
|
+
if (concurrentReceipt)
|
|
69
|
+
return concurrentReceipt;
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
const { expected, tails } = snapshot;
|
|
74
|
+
const facts = [];
|
|
75
|
+
for (const { runId, events } of tails) {
|
|
76
|
+
const index = indexes.get(runId) ?? new CausationIndex();
|
|
77
|
+
for (const event of events)
|
|
78
|
+
index.add(event);
|
|
79
|
+
indexes.delete(runId);
|
|
80
|
+
indexes.set(runId, index);
|
|
81
|
+
facts.push(...index.facts.values());
|
|
82
|
+
}
|
|
83
|
+
const explicitIds = built.flatMap((event) => event.causationId && !facts.some((fact) => fact.id === event.causationId)
|
|
84
|
+
? [event.causationId]
|
|
85
|
+
: []);
|
|
86
|
+
if (explicitIds.length) {
|
|
87
|
+
for (const event of await d.reader.readForRuns([], explicitIds))
|
|
88
|
+
facts.push(causalFact(event, event.metadata.correlationId));
|
|
89
|
+
}
|
|
90
|
+
const events = [];
|
|
91
|
+
const readFacts = () => facts;
|
|
92
|
+
let correlation = key;
|
|
93
|
+
for (const event of built) {
|
|
94
|
+
let fact = causalFact(event, correlation, readFacts);
|
|
95
|
+
const cause = event.causationId
|
|
96
|
+
? facts.find((fact) => fact.id === event.causationId)
|
|
97
|
+
: findCause(event, fact, facts);
|
|
98
|
+
if (cause) {
|
|
99
|
+
correlation = cause.correlationId;
|
|
100
|
+
fact = { ...fact, correlationId: correlation };
|
|
101
|
+
}
|
|
102
|
+
events.push(event.causationId ? event : { ...event, causationId: cause?.id ?? null });
|
|
103
|
+
facts.push(fact);
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const receipt = await d.commit.commit({
|
|
107
|
+
commandId: key,
|
|
108
|
+
commandHash,
|
|
109
|
+
correlationId: correlation,
|
|
110
|
+
actor: { kind: 'runtime', id: 'saturn' },
|
|
111
|
+
hostEpoch: d.epoch,
|
|
112
|
+
events,
|
|
113
|
+
expected,
|
|
114
|
+
});
|
|
115
|
+
for (const event of receipt.events) {
|
|
116
|
+
const runId = runIdOf(event);
|
|
117
|
+
if (runId)
|
|
118
|
+
indexes.get(runId)?.add(event);
|
|
119
|
+
}
|
|
120
|
+
for (const [runId, index] of indexes)
|
|
121
|
+
if (index.terminal)
|
|
122
|
+
indexes.delete(runId);
|
|
123
|
+
while (indexes.size > 64)
|
|
124
|
+
indexes.delete(indexes.keys().next().value);
|
|
125
|
+
return receipt;
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
for (const runId of runIds)
|
|
129
|
+
indexes.delete(runId);
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
tail = work.then(() => undefined, () => undefined);
|
|
134
|
+
return work;
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function causalFact(event, correlationId, readFacts) {
|
|
139
|
+
const runId = runIdOf(event);
|
|
140
|
+
const stepId = stepIdOf(event);
|
|
141
|
+
const callId = toolCallIdOf(event);
|
|
142
|
+
const requestId = requestIdOf(event);
|
|
143
|
+
const attemptId = attemptIdOf(event);
|
|
144
|
+
let turnId = turnIdOf(event);
|
|
145
|
+
if (turnId === undefined &&
|
|
146
|
+
readFacts &&
|
|
147
|
+
(stepId !== undefined || callId !== undefined || requestId !== undefined || attemptId !== undefined)) {
|
|
148
|
+
turnId = lastMatch(readFacts(), (fact) => fact.runId === runId &&
|
|
149
|
+
fact.turnId !== undefined &&
|
|
150
|
+
((stepId !== undefined && fact.stepId === stepId) ||
|
|
151
|
+
(callId !== undefined && fact.callId === callId) ||
|
|
152
|
+
(requestId !== undefined && fact.requestId === requestId) ||
|
|
153
|
+
(attemptId !== undefined && fact.attemptId === attemptId)))?.turnId;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
id: event.id,
|
|
157
|
+
type: event.type,
|
|
158
|
+
runId,
|
|
159
|
+
turnId,
|
|
160
|
+
stepId,
|
|
161
|
+
callId,
|
|
162
|
+
attemptId,
|
|
163
|
+
requestId,
|
|
164
|
+
correlationId,
|
|
165
|
+
approvalId: event.type === 'tool.approval.requested'
|
|
166
|
+
? event.payload.request.approvalId
|
|
167
|
+
: event.type === 'tool.approval.resolved'
|
|
168
|
+
? event.payload.decision.approvalId
|
|
169
|
+
: undefined,
|
|
170
|
+
messageId: event.type === 'message.user.added' ||
|
|
171
|
+
event.type === 'message.assistant.added' ||
|
|
172
|
+
event.type === 'tool.call.settled'
|
|
173
|
+
? event.payload.message.id
|
|
174
|
+
: event.type === 'turn.completed'
|
|
175
|
+
? event.payload.finalMessageId
|
|
176
|
+
: event.type === 'run.team.message.sent' || event.type === 'run.team.message.read'
|
|
177
|
+
? event.payload.messageId
|
|
178
|
+
: undefined,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function defaultCommand(events) {
|
|
182
|
+
const generated = new Map();
|
|
183
|
+
const identify = (value) => {
|
|
184
|
+
if (!generated.has(value))
|
|
185
|
+
generated.set(value, `generated:${generated.size}`);
|
|
186
|
+
};
|
|
187
|
+
for (const event of events) {
|
|
188
|
+
switch (event.type) {
|
|
189
|
+
case 'step.started':
|
|
190
|
+
identify(event.payload.step.id);
|
|
191
|
+
break;
|
|
192
|
+
case 'model.requested':
|
|
193
|
+
identify(event.payload.request.id);
|
|
194
|
+
if (event.payload.request.attempt === 1)
|
|
195
|
+
identify(event.payload.request.callGroupId);
|
|
196
|
+
break;
|
|
197
|
+
case 'message.user.added':
|
|
198
|
+
case 'message.assistant.added':
|
|
199
|
+
case 'tool.call.settled':
|
|
200
|
+
identify(event.payload.message.id);
|
|
201
|
+
if (event.payload.message.role === 'assistant')
|
|
202
|
+
for (const call of event.payload.message.toolCalls)
|
|
203
|
+
identify(call.id);
|
|
204
|
+
break;
|
|
205
|
+
case 'tool.call.requested':
|
|
206
|
+
identify(event.payload.call.id);
|
|
207
|
+
break;
|
|
208
|
+
case 'tool.call.started':
|
|
209
|
+
identify(event.payload.attempt.id);
|
|
210
|
+
break;
|
|
211
|
+
case 'tool.approval.requested':
|
|
212
|
+
identify(event.payload.request.approvalId);
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const normalize = (value) => {
|
|
217
|
+
if (typeof value === 'string')
|
|
218
|
+
return generated.get(value) ?? value;
|
|
219
|
+
if (Array.isArray(value))
|
|
220
|
+
return value.map(normalize);
|
|
221
|
+
if (value === null || typeof value !== 'object')
|
|
222
|
+
return value;
|
|
223
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {
|
|
224
|
+
// Adapter/user JSON is semantic input, including any IDs or timestamps it contains.
|
|
225
|
+
if ([
|
|
226
|
+
'arguments',
|
|
227
|
+
'content',
|
|
228
|
+
'data',
|
|
229
|
+
'structuredOutput',
|
|
230
|
+
'responses',
|
|
231
|
+
'inputSchema',
|
|
232
|
+
'outputSchema',
|
|
233
|
+
].includes(key))
|
|
234
|
+
return [[key, item]];
|
|
235
|
+
if (key === 'executionKey' && typeof item === 'string')
|
|
236
|
+
return [
|
|
237
|
+
[
|
|
238
|
+
key,
|
|
239
|
+
item
|
|
240
|
+
.split(':')
|
|
241
|
+
.map((part) => generated.get(part) ?? part)
|
|
242
|
+
.join(':'),
|
|
243
|
+
],
|
|
244
|
+
];
|
|
245
|
+
if ([
|
|
246
|
+
'startedAt',
|
|
247
|
+
'createdAt',
|
|
248
|
+
'decidedAt',
|
|
249
|
+
'retryAt',
|
|
250
|
+
'expiresAt',
|
|
251
|
+
'executorInstanceId',
|
|
252
|
+
'hostEpoch',
|
|
253
|
+
].includes(key))
|
|
254
|
+
return [];
|
|
255
|
+
if (key === 'ordinal')
|
|
256
|
+
return [];
|
|
257
|
+
return [[key, normalize(item)]];
|
|
258
|
+
}));
|
|
259
|
+
};
|
|
260
|
+
return events.map(({ type, scope, payload }) => ({ type, scope, payload: normalize(payload) }));
|
|
261
|
+
}
|
|
262
|
+
function findCause(event, current, facts) {
|
|
263
|
+
const latest = (types, predicate) => lastMatch(facts, (fact) => types.includes(fact.type) && predicate(fact));
|
|
264
|
+
const { runId: run, turnId: turn, stepId: step, callId: call } = current;
|
|
265
|
+
const sameRun = (fact) => fact.runId === run;
|
|
266
|
+
const sameTurn = (fact) => turn !== undefined && fact.turnId === turn;
|
|
267
|
+
const sameStep = (fact) => step !== undefined && fact.stepId === step;
|
|
268
|
+
const sameCall = (fact) => call !== undefined && fact.callId === call;
|
|
269
|
+
switch (event.type) {
|
|
270
|
+
case 'run.started':
|
|
271
|
+
return latest(['run.created'], sameRun);
|
|
272
|
+
case 'turn.started':
|
|
273
|
+
return latest(['turn.queued'], sameTurn);
|
|
274
|
+
case 'model.requested':
|
|
275
|
+
return ((event.payload.request.retryOf
|
|
276
|
+
? latest(['model.failed'], (fact) => fact.requestId === event.payload.request.retryOf)
|
|
277
|
+
: undefined) ??
|
|
278
|
+
latest(['message.user.added', 'tool.call.settled'], sameTurn) ??
|
|
279
|
+
latest(['turn.started'], sameTurn));
|
|
280
|
+
case 'model.responded':
|
|
281
|
+
return latest(['model.requested'], sameStep);
|
|
282
|
+
case 'model.failed':
|
|
283
|
+
return latest(['model.requested'], (fact) => fact.requestId === event.payload.requestId);
|
|
284
|
+
case 'message.assistant.added': {
|
|
285
|
+
const request = latest(['model.requested'], (fact) => fact.requestId === event.payload.requestId);
|
|
286
|
+
return request ? latest(['model.responded'], (fact) => fact.stepId === request.stepId) : undefined;
|
|
287
|
+
}
|
|
288
|
+
case 'tool.call.requested':
|
|
289
|
+
return latest(['message.assistant.added'], (fact) => fact.messageId === event.payload.call.assistantMessageId);
|
|
290
|
+
case 'tool.approval.requested':
|
|
291
|
+
return latest(['tool.call.requested'], sameCall);
|
|
292
|
+
case 'tool.approval.resolved':
|
|
293
|
+
return latest(['tool.approval.requested'], (fact) => fact.approvalId === event.payload.decision.approvalId);
|
|
294
|
+
case 'tool.call.started':
|
|
295
|
+
return (latest(['tool.call.failed'], sameCall) ??
|
|
296
|
+
latest(['tool.call.reconciled'], sameCall) ??
|
|
297
|
+
latest(['tool.approval.resolved'], sameCall) ??
|
|
298
|
+
latest(['tool.call.requested'], sameCall));
|
|
299
|
+
case 'tool.call.completed':
|
|
300
|
+
case 'tool.call.failed':
|
|
301
|
+
case 'tool.call.outcome_unknown':
|
|
302
|
+
return latest(['tool.call.started'], (fact) => fact.attemptId === event.payload.attemptId);
|
|
303
|
+
case 'tool.call.reconciled':
|
|
304
|
+
return latest(['tool.call.outcome_unknown'], (fact) => fact.attemptId === event.payload.attemptId);
|
|
305
|
+
case 'tool.call.rejected':
|
|
306
|
+
case 'tool.call.denied':
|
|
307
|
+
return latest(['tool.approval.resolved'], sameCall) ?? latest(['tool.call.requested'], sameCall);
|
|
308
|
+
case 'tool.call.settled':
|
|
309
|
+
return (latest([
|
|
310
|
+
'tool.call.completed',
|
|
311
|
+
'tool.call.failed',
|
|
312
|
+
'tool.call.denied',
|
|
313
|
+
'tool.call.rejected',
|
|
314
|
+
'tool.call.reconciled',
|
|
315
|
+
], sameCall) ?? latest(['tool.call.requested'], sameCall));
|
|
316
|
+
case 'step.started':
|
|
317
|
+
return event.payload.step.kind === 'model'
|
|
318
|
+
? latest(['message.user.added', 'tool.call.settled'], sameTurn)
|
|
319
|
+
: latest(['tool.call.requested'], sameTurn);
|
|
320
|
+
case 'step.completed':
|
|
321
|
+
case 'step.failed':
|
|
322
|
+
case 'step.interrupted': {
|
|
323
|
+
const modelType = event.type === 'step.completed' ? 'model.responded' : 'model.failed';
|
|
324
|
+
const toolTypes = event.type === 'step.completed'
|
|
325
|
+
? ['tool.call.completed', 'tool.call.failed']
|
|
326
|
+
: event.type === 'step.failed'
|
|
327
|
+
? ['tool.call.failed']
|
|
328
|
+
: ['tool.call.outcome_unknown'];
|
|
329
|
+
return (latest([modelType], sameStep) ??
|
|
330
|
+
latest(toolTypes, (fact) => {
|
|
331
|
+
const started = latest(['tool.call.started'], (candidate) => candidate.attemptId === fact.attemptId);
|
|
332
|
+
return started?.stepId === step;
|
|
333
|
+
}));
|
|
334
|
+
}
|
|
335
|
+
case 'turn.paused':
|
|
336
|
+
return latest(['tool.approval.requested', 'tool.call.outcome_unknown'], sameTurn);
|
|
337
|
+
case 'run.paused':
|
|
338
|
+
return latest(['turn.paused'], (fact) => fact.turnId === event.payload.blockedTurnId);
|
|
339
|
+
case 'turn.resumed':
|
|
340
|
+
return latest(['tool.approval.resolved', 'tool.call.reconciled', 'run.paused'], sameRun);
|
|
341
|
+
case 'run.resumed':
|
|
342
|
+
return latest(['turn.resumed', 'tool.approval.resolved', 'tool.call.reconciled', 'run.paused'], sameRun);
|
|
343
|
+
case 'turn.completed':
|
|
344
|
+
return (latest(['message.assistant.added'], (fact) => fact.messageId === event.payload.finalMessageId) ??
|
|
345
|
+
latest(['model.responded'], sameTurn));
|
|
346
|
+
case 'run.team.planned':
|
|
347
|
+
return latest(['turn.completed'], sameRun) ?? latest(['run.started'], sameRun);
|
|
348
|
+
case 'run.team.message.sent':
|
|
349
|
+
return (latest(['turn.completed'], (fact) => fact.messageId === event.payload.messageId && sameRun(fact)) ??
|
|
350
|
+
latest(['tool.call.started', 'tool.call.requested'], sameRun) ??
|
|
351
|
+
latest(['turn.started', 'run.started'], sameRun));
|
|
352
|
+
case 'run.team.message.read':
|
|
353
|
+
return latest(['run.team.message.sent'], (fact) => fact.messageId === event.payload.messageId && sameRun(fact));
|
|
354
|
+
case 'turn.interrupted':
|
|
355
|
+
return (latest(['model.failed', 'tool.call.outcome_unknown'], sameTurn) ??
|
|
356
|
+
latest(['run.cancel_requested'], sameRun));
|
|
357
|
+
case 'turn.failed':
|
|
358
|
+
return latest(['model.failed', 'step.failed'], sameTurn);
|
|
359
|
+
case 'run.completed':
|
|
360
|
+
return latest(['turn.completed'], sameRun);
|
|
361
|
+
case 'run.failed':
|
|
362
|
+
return latest(['turn.failed', 'turn.interrupted'], sameRun);
|
|
363
|
+
case 'run.cancelled':
|
|
364
|
+
return latest(['run.cancel_requested', 'turn.interrupted'], sameRun);
|
|
365
|
+
case 'agent_session.archived':
|
|
366
|
+
return latest(terminalRunEventTypes, sameRun);
|
|
367
|
+
default:
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function toolCallIdOf(event) {
|
|
372
|
+
switch (event.type) {
|
|
373
|
+
case 'tool.call.requested':
|
|
374
|
+
return event.payload.call.id;
|
|
375
|
+
case 'tool.call.rejected':
|
|
376
|
+
case 'tool.call.denied':
|
|
377
|
+
case 'tool.call.outcome_unknown':
|
|
378
|
+
case 'tool.call.reconciled':
|
|
379
|
+
case 'tool.call.failed':
|
|
380
|
+
return event.payload.toolCallId;
|
|
381
|
+
case 'tool.call.started':
|
|
382
|
+
return event.payload.attempt.toolCallId;
|
|
383
|
+
case 'tool.call.completed':
|
|
384
|
+
return event.payload.result.toolCallId;
|
|
385
|
+
case 'tool.call.settled':
|
|
386
|
+
return event.payload.message.result.toolCallId;
|
|
387
|
+
case 'tool.approval.requested':
|
|
388
|
+
return event.payload.request.toolCallId;
|
|
389
|
+
case 'tool.approval.resolved':
|
|
390
|
+
return event.payload.decision.toolCallId;
|
|
391
|
+
default:
|
|
392
|
+
return undefined;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function turnIdOf(event) {
|
|
396
|
+
switch (event.type) {
|
|
397
|
+
case 'turn.queued':
|
|
398
|
+
case 'turn.started':
|
|
399
|
+
case 'turn.paused':
|
|
400
|
+
case 'turn.resumed':
|
|
401
|
+
case 'turn.completed':
|
|
402
|
+
case 'turn.failed':
|
|
403
|
+
case 'turn.interrupted':
|
|
404
|
+
return event.payload.turnId;
|
|
405
|
+
case 'model.requested':
|
|
406
|
+
return event.payload.request.turnId;
|
|
407
|
+
case 'tool.call.requested':
|
|
408
|
+
return event.payload.turnId;
|
|
409
|
+
case 'message.user.added':
|
|
410
|
+
case 'message.assistant.added':
|
|
411
|
+
case 'tool.call.settled':
|
|
412
|
+
return event.payload.message.turnId;
|
|
413
|
+
case 'step.started':
|
|
414
|
+
return event.payload.step.turnId;
|
|
415
|
+
default:
|
|
416
|
+
return undefined;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
function stepIdOf(event) {
|
|
420
|
+
if (!event)
|
|
421
|
+
return undefined;
|
|
422
|
+
switch (event.type) {
|
|
423
|
+
case 'model.requested':
|
|
424
|
+
case 'model.responded':
|
|
425
|
+
case 'model.failed':
|
|
426
|
+
return event.payload.stepId;
|
|
427
|
+
case 'step.started':
|
|
428
|
+
return event.payload.step.id;
|
|
429
|
+
case 'step.completed':
|
|
430
|
+
case 'step.failed':
|
|
431
|
+
case 'step.interrupted':
|
|
432
|
+
return event.payload.stepId;
|
|
433
|
+
case 'tool.call.started':
|
|
434
|
+
return event.payload.attempt.stepId;
|
|
435
|
+
default:
|
|
436
|
+
return undefined;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
function requestIdOf(event) {
|
|
440
|
+
switch (event.type) {
|
|
441
|
+
case 'model.requested':
|
|
442
|
+
return event.payload.request.id;
|
|
443
|
+
case 'model.responded':
|
|
444
|
+
return event.payload.response.requestId;
|
|
445
|
+
case 'model.failed':
|
|
446
|
+
case 'message.assistant.added':
|
|
447
|
+
return event.payload.requestId;
|
|
448
|
+
default:
|
|
449
|
+
return undefined;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
function attemptIdOf(event) {
|
|
453
|
+
switch (event.type) {
|
|
454
|
+
case 'tool.call.started':
|
|
455
|
+
return event.payload.attempt.id;
|
|
456
|
+
case 'tool.call.completed':
|
|
457
|
+
case 'tool.call.failed':
|
|
458
|
+
case 'tool.call.outcome_unknown':
|
|
459
|
+
case 'tool.call.reconciled':
|
|
460
|
+
return event.payload.attemptId;
|
|
461
|
+
default:
|
|
462
|
+
return undefined;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function runIdOf(event) {
|
|
466
|
+
return 'runId' in event.scope ? event.scope.runId : undefined;
|
|
467
|
+
}
|
|
468
|
+
function lastMatch(values, predicate) {
|
|
469
|
+
for (let index = values.length - 1; index >= 0; index--)
|
|
470
|
+
if (predicate(values[index]))
|
|
471
|
+
return values[index];
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { RunId, CommandId, ExecutionEnvironmentReader, ToolExecutor, RuntimeStateReader, RuntimeClock, ToolExecutionReader, Hash } from '@saturn-universe/core';
|
|
2
|
+
import type { CommandDependencies } from './command-dependencies.js';
|
|
3
|
+
export declare function recoverRuntime(d: {
|
|
4
|
+
reader: CommandDependencies['reader'] & {
|
|
5
|
+
recoverableRuns?(): Promise<readonly RunId[]>;
|
|
6
|
+
};
|
|
7
|
+
state: RuntimeStateReader;
|
|
8
|
+
environment?: ExecutionEnvironmentReader;
|
|
9
|
+
tools: ToolExecutionReader;
|
|
10
|
+
executor: ToolExecutor;
|
|
11
|
+
clock: RuntimeClock;
|
|
12
|
+
hash: Hash;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
loop: {
|
|
15
|
+
drive(runId: RunId, signal: AbortSignal): Promise<void>;
|
|
16
|
+
resume(runId: RunId, commandId: CommandId): Promise<void>;
|
|
17
|
+
checkPluginVersions?(runId: RunId): Promise<void>;
|
|
18
|
+
};
|
|
19
|
+
}, schedule?: (runId: RunId, prepare: (signal: AbortSignal) => Promise<void>) => void, selectedRuns?: readonly RunId[]): Promise<void>;
|
package/dist/recovery.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { isTerminalRunStatus, RuntimeError, validateStartedRun } from '@saturn-universe/core';
|
|
2
|
+
export async function recoverRuntime(d, schedule, selectedRuns) {
|
|
3
|
+
const runIds = selectedRuns ??
|
|
4
|
+
(d.reader.recoverableRuns
|
|
5
|
+
? await d.reader.recoverableRuns()
|
|
6
|
+
: Object.values((await d.reader.snapshot()).state.runs)
|
|
7
|
+
.filter((run) => !isTerminalRunStatus(run.status))
|
|
8
|
+
.map((run) => run.id));
|
|
9
|
+
const signal = d.signal ?? new AbortController().signal;
|
|
10
|
+
if (schedule) {
|
|
11
|
+
for (const runId of runIds)
|
|
12
|
+
schedule(runId, (activeSignal) => prepare(runId, activeSignal));
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
await Promise.all(runIds.map(async (runId) => {
|
|
16
|
+
try {
|
|
17
|
+
await d.loop.checkPluginVersions?.(runId);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error instanceof RuntimeError && error.code === 'PLUGIN_VERSION_UNAVAILABLE')
|
|
21
|
+
return;
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
await prepare(runId, signal);
|
|
25
|
+
if (!signal.aborted && !(await d.state.run(runId)).pluginBlock)
|
|
26
|
+
await d.loop.drive(runId, signal);
|
|
27
|
+
}));
|
|
28
|
+
async function prepare(runId, signal) {
|
|
29
|
+
if (signal.aborted)
|
|
30
|
+
return;
|
|
31
|
+
const entry = await d.state.run(runId);
|
|
32
|
+
if (entry.pluginBlock || isTerminalRunStatus(entry.status))
|
|
33
|
+
return;
|
|
34
|
+
// The active driver handles running batches after checking the saved model finish reason.
|
|
35
|
+
if (schedule && entry.status !== 'paused')
|
|
36
|
+
return;
|
|
37
|
+
const limits = d.environment ? (await d.environment.load(runId)).config.limits : undefined;
|
|
38
|
+
if (entry.status === 'running' || entry.status === 'paused') {
|
|
39
|
+
const { deadlineAt } = validateStartedRun(entry, limits);
|
|
40
|
+
if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (entry.status === 'running' && entry.blockedTurnIds.length)
|
|
44
|
+
return;
|
|
45
|
+
const multiMemberTeam = ((await d.state.team?.(runId))?.members.length ?? 0) > 1;
|
|
46
|
+
const turns = await d.state.turns(runId);
|
|
47
|
+
for (const turn of turns) {
|
|
48
|
+
if (multiMemberTeam && turn.status === 'paused' && entry.status === 'paused') {
|
|
49
|
+
const result = await d.state.turnResult(turn.id);
|
|
50
|
+
if (result?.status === 'paused' && result.reason === 'approval')
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const calls = await d.tools.pending(turn.id);
|
|
54
|
+
if (calls.length && entry.status === 'running') {
|
|
55
|
+
const last = (await d.state.modelAttempts(turn.id)).at(-1);
|
|
56
|
+
if (last?.status === 'responded' && ['length', 'content_filter'].includes(last.response.finishReason))
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
for (const assistantMessageId of new Set(calls.map((call) => call.call.assistantMessageId))) {
|
|
60
|
+
if (signal.aborted)
|
|
61
|
+
return;
|
|
62
|
+
const input = {
|
|
63
|
+
runId,
|
|
64
|
+
turnId: turn.id,
|
|
65
|
+
agentSessionId: turn.agentSessionId,
|
|
66
|
+
assistantMessageId,
|
|
67
|
+
signal,
|
|
68
|
+
};
|
|
69
|
+
if (schedule)
|
|
70
|
+
await d.executor.executeBatch(input);
|
|
71
|
+
else
|
|
72
|
+
await d.executor.recover(input);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (signal.aborted)
|
|
76
|
+
return;
|
|
77
|
+
const current = await d.state.run(runId);
|
|
78
|
+
if (current.status !== 'paused')
|
|
79
|
+
return;
|
|
80
|
+
if (multiMemberTeam)
|
|
81
|
+
return;
|
|
82
|
+
const currentDeadline = validateStartedRun(current, limits).deadlineAt;
|
|
83
|
+
if (currentDeadline && Date.parse(d.clock.now()) >= Date.parse(currentDeadline))
|
|
84
|
+
return;
|
|
85
|
+
const calls = (await Promise.all(turns.map((turn) => d.tools.pending(turn.id)))).flat();
|
|
86
|
+
if (signal.aborted ||
|
|
87
|
+
(await d.state.resumePreference?.(runId)) === 'deferred' ||
|
|
88
|
+
calls.some((call) => call.status === 'outcome_unknown' ||
|
|
89
|
+
call.status === 'running' ||
|
|
90
|
+
call.approval?.status === 'pending'))
|
|
91
|
+
return;
|
|
92
|
+
try {
|
|
93
|
+
await d.loop.resume(runId, `recover:${runId}:resume:${d.hash(calls.map((call) => ({ id: call.call.id, status: call.status, approval: call.approval ?? null })))}`);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (!schedule ||
|
|
97
|
+
!(error instanceof RuntimeError) ||
|
|
98
|
+
!['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code) ||
|
|
99
|
+
(await d.state.run(runId)).status === 'paused')
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { HostCommand, AgentSessionId, RunLoop, RunId, CommandId, AgentLoop, AgentInput, RuntimeJournal, RuntimeStateReader, ExecutionEnvironmentReader, RunCompletionPolicy, ToolExecutionReader, SurfaceReader, RunConfig, TeamConfig, RunCheckpoint, WorkerSandboxProfile } from '@saturn-universe/core';
|
|
2
|
+
import type { CommandDependencies } from './command-dependencies.js';
|
|
3
|
+
type PrepareRun = (signal: AbortSignal) => Promise<void>;
|
|
4
|
+
export declare const defaultCompletionPolicy: RunCompletionPolicy;
|
|
5
|
+
export declare function createRunLoop(d: CommandDependencies & {
|
|
6
|
+
journal: RuntimeJournal;
|
|
7
|
+
state: RuntimeStateReader;
|
|
8
|
+
environment: ExecutionEnvironmentReader;
|
|
9
|
+
agent: AgentLoop & Partial<Pick<ReturnType<typeof import('./agent-loop.js').createAgentLoop>, 'steer' | 'clearSteering'>>;
|
|
10
|
+
tools: ToolExecutionReader;
|
|
11
|
+
surface?: SurfaceReader;
|
|
12
|
+
freezeWorkerConfig?: (mainConfig: RunConfig, team: TeamConfig, id: AgentSessionId, options?: {
|
|
13
|
+
readonly depth?: number;
|
|
14
|
+
}) => Promise<RunConfig>;
|
|
15
|
+
verifyPluginVersions?: (runId: RunId) => Promise<void>;
|
|
16
|
+
completionPolicy?: RunCompletionPolicy;
|
|
17
|
+
createCheckpoint?: (input: AgentInput, prior?: RunCheckpoint) => Promise<RunCheckpoint | undefined>;
|
|
18
|
+
onWorkerStart?: (input: {
|
|
19
|
+
readonly runId: RunId;
|
|
20
|
+
readonly memberId: string;
|
|
21
|
+
readonly agentSessionId: AgentSessionId;
|
|
22
|
+
readonly parentMemberId?: string;
|
|
23
|
+
readonly parentAgentSessionId?: AgentSessionId;
|
|
24
|
+
readonly sandboxProfile?: WorkerSandboxProfile;
|
|
25
|
+
readonly workSubpath?: string;
|
|
26
|
+
}) => Promise<void>;
|
|
27
|
+
onWorkerComplete?: (input: {
|
|
28
|
+
readonly runId: RunId;
|
|
29
|
+
readonly memberId: string;
|
|
30
|
+
readonly agentSessionId: AgentSessionId;
|
|
31
|
+
readonly parentMemberId?: string;
|
|
32
|
+
readonly workSubpath?: string;
|
|
33
|
+
readonly status: 'completed' | 'failed' | 'interrupted';
|
|
34
|
+
}) => Promise<void>;
|
|
35
|
+
}): RunLoop & {
|
|
36
|
+
drive(runId: RunId, signal: AbortSignal, prepare?: PrepareRun): Promise<void>;
|
|
37
|
+
checkPluginVersions(runId: RunId): Promise<void>;
|
|
38
|
+
resumeAutomatically(runId: RunId, commandId: CommandId): Promise<boolean>;
|
|
39
|
+
wakeTeam(runId: RunId): Promise<void> | undefined;
|
|
40
|
+
steer(commandId: CommandId, command: Extract<HostCommand, {
|
|
41
|
+
type: 'run.steer';
|
|
42
|
+
}>): Promise<void>;
|
|
43
|
+
requestCancel(runId: RunId, commandId: CommandId, reason: string): Promise<{
|
|
44
|
+
work: Promise<void>;
|
|
45
|
+
}>;
|
|
46
|
+
drain(): Promise<void>;
|
|
47
|
+
stop(): Promise<void>;
|
|
48
|
+
};
|
|
49
|
+
export {};
|