@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/run-loop.js
ADDED
|
@@ -0,0 +1,739 @@
|
|
|
1
|
+
import { BACKGROUND_CONTEXT_PREFIX, isAsyncCoordinatorConfig, isTerminalRunStatus, maxRunTeamWorkers, RuntimeError, validateStartedRun, validateTeamConfig, } from '@saturn-universe/core';
|
|
2
|
+
import { createCommandHandler } from './command-handler.js';
|
|
3
|
+
import { approvalResumeDeadline, driveTeam, extractSpawnTeamCall } from './team-loop.js';
|
|
4
|
+
import { driveSelectiveSearch, formatSearchResultMessage, hasSearchBudget, searchTokenUsage, } from './search-loop.js';
|
|
5
|
+
export const defaultCompletionPolicy = {
|
|
6
|
+
decide(state, result) {
|
|
7
|
+
if (state.status === 'cancelling')
|
|
8
|
+
return 'cancel';
|
|
9
|
+
return result.status === 'completed'
|
|
10
|
+
? 'complete'
|
|
11
|
+
: result.status === 'paused'
|
|
12
|
+
? 'pause'
|
|
13
|
+
: result.status === 'interrupted' && result.reason === 'cancelled'
|
|
14
|
+
? 'cancel'
|
|
15
|
+
: 'fail';
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
export function createRunLoop(d) {
|
|
19
|
+
const handler = createCommandHandler(d);
|
|
20
|
+
const teamWakes = new Map();
|
|
21
|
+
const pendingCoordinatorSteers = new Map();
|
|
22
|
+
const getPendingCoordinatorSteers = (runId) => {
|
|
23
|
+
let map = pendingCoordinatorSteers.get(runId);
|
|
24
|
+
if (!map) {
|
|
25
|
+
map = new Map();
|
|
26
|
+
pendingCoordinatorSteers.set(runId, map);
|
|
27
|
+
}
|
|
28
|
+
return map;
|
|
29
|
+
};
|
|
30
|
+
const active = new Map();
|
|
31
|
+
const cancellations = new Set();
|
|
32
|
+
let stopping = false;
|
|
33
|
+
async function drive(runId, signal, prepare) {
|
|
34
|
+
const existing = active.get(runId);
|
|
35
|
+
if (existing)
|
|
36
|
+
return existing.work.then(async () => {
|
|
37
|
+
const current = await d.state.run(runId);
|
|
38
|
+
if (current.status === 'running' && !current.pluginBlock && !stopping && !active.has(runId))
|
|
39
|
+
await drive(runId, new AbortController().signal);
|
|
40
|
+
});
|
|
41
|
+
if (stopping)
|
|
42
|
+
return;
|
|
43
|
+
const controller = new AbortController();
|
|
44
|
+
const runSignal = AbortSignal.any([signal, controller.signal]);
|
|
45
|
+
const work = run(runId, runSignal, prepare)
|
|
46
|
+
.catch(async (error) => {
|
|
47
|
+
if (!(error instanceof RuntimeError) || error.code !== 'PLUGIN_VERSION_UNAVAILABLE')
|
|
48
|
+
throw error;
|
|
49
|
+
await recordPluginAvailability(runId, error);
|
|
50
|
+
})
|
|
51
|
+
.finally(async () => {
|
|
52
|
+
active.delete(runId);
|
|
53
|
+
const state = await d.state.run(runId);
|
|
54
|
+
if (isTerminalRunStatus(state.status)) {
|
|
55
|
+
d.agent.clearSteering?.(runId);
|
|
56
|
+
pendingCoordinatorSteers.delete(runId);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
active.set(runId, { work, controller });
|
|
60
|
+
return work;
|
|
61
|
+
}
|
|
62
|
+
async function recordPluginAvailability(runId, error) {
|
|
63
|
+
const state = await d.state.run(runId);
|
|
64
|
+
if (!['created', 'running', 'paused'].includes(state.status))
|
|
65
|
+
return;
|
|
66
|
+
if (state.pluginBlock?.message === error?.message)
|
|
67
|
+
return;
|
|
68
|
+
const { route } = await d.environment.load(runId);
|
|
69
|
+
const scope = { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId };
|
|
70
|
+
try {
|
|
71
|
+
await d.journal.append(`run:${runId}:plugin-availability:${state.lastRunSeq}`, [
|
|
72
|
+
d.journal.event('run.plugin.availability', scope, {
|
|
73
|
+
block: error ? { code: 'PLUGIN_VERSION_UNAVAILABLE', message: error.message } : null,
|
|
74
|
+
}),
|
|
75
|
+
]);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (['created', 'running', 'paused'].includes((await d.state.run(runId)).status))
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function checkPluginVersions(runId) {
|
|
83
|
+
if (!d.verifyPluginVersions)
|
|
84
|
+
return;
|
|
85
|
+
const state = await d.state.run(runId);
|
|
86
|
+
if (!['created', 'running', 'paused'].includes(state.status))
|
|
87
|
+
return;
|
|
88
|
+
try {
|
|
89
|
+
await d.verifyPluginVersions(runId);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error instanceof RuntimeError && error.code === 'PLUGIN_VERSION_UNAVAILABLE')
|
|
93
|
+
await recordPluginAvailability(runId, error);
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
if (state.pluginBlock)
|
|
97
|
+
await recordPluginAvailability(runId);
|
|
98
|
+
}
|
|
99
|
+
async function run(runId, signal, prepare) {
|
|
100
|
+
await checkPluginVersions(runId);
|
|
101
|
+
await prepare?.(signal);
|
|
102
|
+
const run = await d.state.run(runId);
|
|
103
|
+
if (isTerminalRunStatus(run.status))
|
|
104
|
+
return;
|
|
105
|
+
const env = await d.environment.load(runId);
|
|
106
|
+
if (run.status === 'running' || run.status === 'paused')
|
|
107
|
+
validateStartedRun(run, env.config.limits);
|
|
108
|
+
const team = env.config.team;
|
|
109
|
+
const route = env.route;
|
|
110
|
+
const mainTurns = (await d.state.turns(runId)).filter((candidate) => candidate.agentSessionId === route.agentSessionId);
|
|
111
|
+
let currentTurn = mainTurns.at(-1);
|
|
112
|
+
let continuationTurnsUsed = Math.max(0, mainTurns.length - 1);
|
|
113
|
+
const scope = { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId };
|
|
114
|
+
if (run.status === 'created') {
|
|
115
|
+
try {
|
|
116
|
+
await d.journal.append(`run:${runId}:start`, [
|
|
117
|
+
d.journal.event('run.started', scope, { startedAt: d.now() }),
|
|
118
|
+
...(!team
|
|
119
|
+
? [d.journal.event('turn.started', route, { turnId: currentTurn.id, startedAt: d.now() })]
|
|
120
|
+
: []),
|
|
121
|
+
]);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
const latest = await d.state.run(runId);
|
|
125
|
+
if (isTerminalRunStatus(latest.status))
|
|
126
|
+
return;
|
|
127
|
+
if (latest.status !== 'cancelling' ||
|
|
128
|
+
!(error instanceof RuntimeError) ||
|
|
129
|
+
!['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code))
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
let currentInput = {
|
|
134
|
+
workspaceId: route.workspaceId,
|
|
135
|
+
sessionId: route.sessionId,
|
|
136
|
+
runId,
|
|
137
|
+
agentId: route.agentId,
|
|
138
|
+
agentSessionId: route.agentSessionId,
|
|
139
|
+
turnId: currentTurn.id,
|
|
140
|
+
inputMessageId: currentTurn.inputMessageId,
|
|
141
|
+
};
|
|
142
|
+
let teamState = await d.state.team?.(runId);
|
|
143
|
+
let teamCompleted = false;
|
|
144
|
+
const completionPolicy = d.completionPolicy ?? defaultCompletionPolicy;
|
|
145
|
+
const maxContinuationTurns = env.config.continuation?.enabled === false ? 0 : (env.config.continuation?.maxTurns ?? 5);
|
|
146
|
+
let decision = 'fail';
|
|
147
|
+
let current = await d.state.run(runId);
|
|
148
|
+
let finalResult;
|
|
149
|
+
const admitFollowupTurn = async (key, text) => {
|
|
150
|
+
const nextOrdinal = currentTurn.ordinal + 1;
|
|
151
|
+
const nextTurnId = d.id();
|
|
152
|
+
const nextMessageId = d.id();
|
|
153
|
+
try {
|
|
154
|
+
const receipt = await d.journal.append(key, [
|
|
155
|
+
d.journal.event('turn.queued', route, {
|
|
156
|
+
turnId: nextTurnId,
|
|
157
|
+
ordinal: nextOrdinal,
|
|
158
|
+
inputMessageId: nextMessageId,
|
|
159
|
+
}),
|
|
160
|
+
d.journal.event('message.user.added', route, {
|
|
161
|
+
message: {
|
|
162
|
+
id: nextMessageId,
|
|
163
|
+
agentSessionId: route.agentSessionId,
|
|
164
|
+
runId,
|
|
165
|
+
turnId: nextTurnId,
|
|
166
|
+
role: 'user',
|
|
167
|
+
content: [{ type: 'text', text }],
|
|
168
|
+
},
|
|
169
|
+
}),
|
|
170
|
+
]);
|
|
171
|
+
const queued = receipt.events.find((event) => event.type === 'turn.queued');
|
|
172
|
+
currentTurn = {
|
|
173
|
+
id: queued.payload.turnId,
|
|
174
|
+
runId,
|
|
175
|
+
agentSessionId: route.agentSessionId,
|
|
176
|
+
inputMessageId: queued.payload.inputMessageId,
|
|
177
|
+
ordinal: queued.payload.ordinal,
|
|
178
|
+
status: 'queued',
|
|
179
|
+
};
|
|
180
|
+
currentInput = {
|
|
181
|
+
workspaceId: route.workspaceId,
|
|
182
|
+
sessionId: route.sessionId,
|
|
183
|
+
runId,
|
|
184
|
+
agentId: route.agentId,
|
|
185
|
+
agentSessionId: route.agentSessionId,
|
|
186
|
+
turnId: currentTurn.id,
|
|
187
|
+
inputMessageId: currentTurn.inputMessageId,
|
|
188
|
+
};
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
const latest = await d.state.run(runId);
|
|
193
|
+
if (isTerminalRunStatus(latest.status))
|
|
194
|
+
return false;
|
|
195
|
+
if (latest.status === 'cancelling' &&
|
|
196
|
+
error instanceof RuntimeError &&
|
|
197
|
+
['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code)) {
|
|
198
|
+
current = latest;
|
|
199
|
+
decision = 'cancel';
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const syncLatestMainTurn = async () => {
|
|
206
|
+
const latestMainTurn = (await d.state.turns(runId))
|
|
207
|
+
.filter((candidate) => candidate.agentSessionId === route.agentSessionId)
|
|
208
|
+
.at(-1);
|
|
209
|
+
if (latestMainTurn) {
|
|
210
|
+
currentTurn = latestMainTurn;
|
|
211
|
+
currentInput = {
|
|
212
|
+
workspaceId: route.workspaceId,
|
|
213
|
+
sessionId: route.sessionId,
|
|
214
|
+
runId,
|
|
215
|
+
agentId: route.agentId,
|
|
216
|
+
agentSessionId: route.agentSessionId,
|
|
217
|
+
turnId: currentTurn.id,
|
|
218
|
+
inputMessageId: currentTurn.inputMessageId,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
while (true) {
|
|
223
|
+
const shouldDriveTeam = Boolean(teamState && teamState.members.length > 1 && !teamCompleted);
|
|
224
|
+
let stepResult;
|
|
225
|
+
if (shouldDriveTeam) {
|
|
226
|
+
const wake = { target: new EventTarget(), waiters: new Set() };
|
|
227
|
+
teamWakes.set(runId, wake);
|
|
228
|
+
try {
|
|
229
|
+
stepResult = await driveTeam({
|
|
230
|
+
...d,
|
|
231
|
+
resumeAutomatically,
|
|
232
|
+
pendingSteers: getPendingCoordinatorSteers(runId),
|
|
233
|
+
...(d.freezeWorkerConfig ? { freezeWorkerConfig: d.freezeWorkerConfig } : {}),
|
|
234
|
+
...(d.onWorkerStart ? { onWorkerStart: d.onWorkerStart } : {}),
|
|
235
|
+
...(d.onWorkerComplete ? { onWorkerComplete: d.onWorkerComplete } : {}),
|
|
236
|
+
}, scope, signal, wake);
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
teamWakes.delete(runId);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
else
|
|
243
|
+
stepResult = await d.agent.resume(currentInput, signal);
|
|
244
|
+
if (!stepResult)
|
|
245
|
+
return;
|
|
246
|
+
if (shouldDriveTeam) {
|
|
247
|
+
await syncLatestMainTurn();
|
|
248
|
+
if (stepResult.status === 'completed')
|
|
249
|
+
teamCompleted = true;
|
|
250
|
+
}
|
|
251
|
+
current = await d.state.run(runId);
|
|
252
|
+
if (isTerminalRunStatus(current.status))
|
|
253
|
+
return;
|
|
254
|
+
const surface = d.surface && stepResult.status === 'completed'
|
|
255
|
+
? await d.surface.read(route.agentSessionId)
|
|
256
|
+
: undefined;
|
|
257
|
+
const spawnReq = (!teamState || teamCompleted || teamState.members.length === 1) &&
|
|
258
|
+
surface &&
|
|
259
|
+
stepResult.status === 'completed' &&
|
|
260
|
+
current.status === 'running' &&
|
|
261
|
+
!signal.aborted
|
|
262
|
+
? extractSpawnTeamCall(surface, currentInput.turnId)
|
|
263
|
+
: undefined;
|
|
264
|
+
if (spawnReq) {
|
|
265
|
+
let spawnedTeam;
|
|
266
|
+
let validationError;
|
|
267
|
+
try {
|
|
268
|
+
const byId = new Map(spawnReq.team.members.map((member) => [member.id, member]));
|
|
269
|
+
const normalizedMembers = spawnReq.team.members.map((member) => {
|
|
270
|
+
if (member.workSubpath !== undefined || member.parent === 'main')
|
|
271
|
+
return member;
|
|
272
|
+
const parentSubpath = byId.get(member.parent)?.workSubpath;
|
|
273
|
+
return parentSubpath !== undefined ? { ...member, workSubpath: parentSubpath } : member;
|
|
274
|
+
});
|
|
275
|
+
if (env.config.modeRef === 'ctf@1' || env.config.modeRef.startsWith('ctf@')) {
|
|
276
|
+
for (const member of normalizedMembers) {
|
|
277
|
+
if (member.parent !== 'main')
|
|
278
|
+
continue;
|
|
279
|
+
if (typeof member.workSubpath !== 'string' || !member.workSubpath.trim()) {
|
|
280
|
+
throw new RuntimeError('INVALID_TEAM_CONFIG', `In ctf@1 mode, Depth-1 worker "${member.id}" must provide a non-empty workSubpath`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
const asyncCoordinator = isAsyncCoordinatorConfig(env.config);
|
|
285
|
+
const rawConcurrency = spawnReq.team.concurrency ??
|
|
286
|
+
(teamState ? teamState.concurrency : env.config.teamHint?.concurrency);
|
|
287
|
+
const mergedConcurrency = asyncCoordinator && teamState && rawConcurrency !== undefined
|
|
288
|
+
? Math.max(teamState.concurrency, rawConcurrency)
|
|
289
|
+
: rawConcurrency;
|
|
290
|
+
const clampedConcurrency = mergedConcurrency !== undefined && env.config.teamMaxConcurrency !== undefined
|
|
291
|
+
? Math.min(mergedConcurrency, env.config.teamMaxConcurrency)
|
|
292
|
+
: mergedConcurrency;
|
|
293
|
+
const candidate = {
|
|
294
|
+
members: normalizedMembers,
|
|
295
|
+
...(clampedConcurrency !== undefined ? { concurrency: clampedConcurrency } : {}),
|
|
296
|
+
};
|
|
297
|
+
validateTeamConfig(candidate);
|
|
298
|
+
const historicalIds = new Set(teamState?.tasks.map(({ memberId }) => memberId));
|
|
299
|
+
const duplicate = candidate.members.find(({ id }) => historicalIds.has(id));
|
|
300
|
+
if (duplicate)
|
|
301
|
+
throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team reused member ID "${duplicate.id}"`);
|
|
302
|
+
const maxWorkers = maxRunTeamWorkers(env.config);
|
|
303
|
+
if (historicalIds.size + candidate.members.length > maxWorkers) {
|
|
304
|
+
throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team exceeded the Run limit of ${maxWorkers} workers`);
|
|
305
|
+
}
|
|
306
|
+
spawnedTeam = candidate;
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
validationError = error instanceof Error ? error.message : 'Invalid team configuration';
|
|
310
|
+
}
|
|
311
|
+
if (!spawnedTeam) {
|
|
312
|
+
decision = 'fail';
|
|
313
|
+
finalResult = {
|
|
314
|
+
status: 'failed',
|
|
315
|
+
turnId: currentTurn.id,
|
|
316
|
+
error: {
|
|
317
|
+
code: 'INVALID_TEAM_CONFIG',
|
|
318
|
+
message: validationError ?? 'Invalid team configuration',
|
|
319
|
+
retryable: false,
|
|
320
|
+
},
|
|
321
|
+
usage: current.chargedUsage,
|
|
322
|
+
};
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
const { planner: _planner, teamHint: _teamHint, ...baseConfig } = env.config;
|
|
326
|
+
const createdAt = d.now();
|
|
327
|
+
const spawnEvents = [
|
|
328
|
+
d.journal.event('run.team.planned', scope, {
|
|
329
|
+
plannerAgentSessionId: route.agentSessionId,
|
|
330
|
+
decision: 'team',
|
|
331
|
+
reason: spawnReq.reason,
|
|
332
|
+
team: spawnedTeam,
|
|
333
|
+
}),
|
|
334
|
+
];
|
|
335
|
+
for (const member of spawnedTeam.members) {
|
|
336
|
+
const workerAgentId = d.id();
|
|
337
|
+
const workerAgentSessionId = d.id();
|
|
338
|
+
const workerConfig = d.freezeWorkerConfig
|
|
339
|
+
? await d.freezeWorkerConfig(env.config, spawnedTeam, workerAgentSessionId, { depth: 1 })
|
|
340
|
+
: { ...baseConfig, team: spawnedTeam, agentDepth: 1 };
|
|
341
|
+
spawnEvents.push(d.journal.event('agent.created', { kind: 'workspace', workspaceId: route.workspaceId }, {
|
|
342
|
+
agent: {
|
|
343
|
+
id: workerAgentId,
|
|
344
|
+
workspaceId: route.workspaceId,
|
|
345
|
+
role: 'worker',
|
|
346
|
+
defaultScope: 'run',
|
|
347
|
+
modeRef: workerConfig.modeRef,
|
|
348
|
+
createdAt,
|
|
349
|
+
},
|
|
350
|
+
}), d.journal.event('agent_session.created', {
|
|
351
|
+
kind: 'agent_session',
|
|
352
|
+
workspaceId: route.workspaceId,
|
|
353
|
+
sessionId: route.sessionId,
|
|
354
|
+
runId,
|
|
355
|
+
agentId: workerAgentId,
|
|
356
|
+
agentSessionId: workerAgentSessionId,
|
|
357
|
+
}, {
|
|
358
|
+
agentSession: {
|
|
359
|
+
id: workerAgentSessionId,
|
|
360
|
+
workspaceId: route.workspaceId,
|
|
361
|
+
agentId: workerAgentId,
|
|
362
|
+
owner: { scope: 'run', sessionId: route.sessionId, runId },
|
|
363
|
+
status: 'open',
|
|
364
|
+
createdAt,
|
|
365
|
+
},
|
|
366
|
+
}), d.journal.event('run.agent.attached', scope, {
|
|
367
|
+
membership: {
|
|
368
|
+
runId,
|
|
369
|
+
agentId: workerAgentId,
|
|
370
|
+
agentSessionId: workerAgentSessionId,
|
|
371
|
+
role: 'worker',
|
|
372
|
+
teamMemberId: member.id,
|
|
373
|
+
config: workerConfig,
|
|
374
|
+
},
|
|
375
|
+
}));
|
|
376
|
+
}
|
|
377
|
+
try {
|
|
378
|
+
await d.journal.append(`team:${runId}:spawn:${currentTurn.ordinal}`, spawnEvents);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
const latest = await d.state.run(runId);
|
|
382
|
+
if (isTerminalRunStatus(latest.status))
|
|
383
|
+
return;
|
|
384
|
+
if (latest.status === 'cancelling' &&
|
|
385
|
+
error instanceof RuntimeError &&
|
|
386
|
+
['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code)) {
|
|
387
|
+
current = latest;
|
|
388
|
+
decision = 'cancel';
|
|
389
|
+
finalResult = stepResult;
|
|
390
|
+
break;
|
|
391
|
+
}
|
|
392
|
+
throw error;
|
|
393
|
+
}
|
|
394
|
+
teamState = await d.state.team?.(runId);
|
|
395
|
+
teamCompleted = false;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
const searches = env.config.search?.mode === 'selective' ? ((await d.state.searches?.(runId)) ?? []) : [];
|
|
399
|
+
const searchId = `execution-t${currentTurn.ordinal}`;
|
|
400
|
+
const priorSearch = searches.find((tree) => tree.searchId === searchId);
|
|
401
|
+
const searchesUsed = searches.filter((tree) => tree.searchId.startsWith('execution-') && tree !== priorSearch).length;
|
|
402
|
+
const completionContext = {
|
|
403
|
+
runId,
|
|
404
|
+
agentSessionId: route.agentSessionId,
|
|
405
|
+
turnId: currentInput.turnId,
|
|
406
|
+
continuationTurnsUsed,
|
|
407
|
+
maxContinuationTurns,
|
|
408
|
+
searchesUsed,
|
|
409
|
+
config: env.config,
|
|
410
|
+
...(surface ? { surface } : {}),
|
|
411
|
+
...(teamState?.plan ? { plan: teamState.plan } : {}),
|
|
412
|
+
};
|
|
413
|
+
const rawDecision = priorSearch?.trigger === 'stagnation' || priorSearch?.trigger === 'consecutive_failures'
|
|
414
|
+
? {
|
|
415
|
+
kind: 'branch',
|
|
416
|
+
trigger: priorSearch.trigger,
|
|
417
|
+
goal: priorSearch.goal,
|
|
418
|
+
reason: 'Continue the recorded search.',
|
|
419
|
+
}
|
|
420
|
+
: await completionPolicy.decide(current, stepResult, completionContext);
|
|
421
|
+
if (typeof rawDecision === 'string') {
|
|
422
|
+
decision = rawDecision;
|
|
423
|
+
finalResult = stepResult;
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
if (rawDecision.kind !== 'continue' && rawDecision.kind !== 'branch') {
|
|
427
|
+
decision = rawDecision.kind;
|
|
428
|
+
finalResult = stepResult;
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
if (current.status !== 'running' || signal.aborted || stepResult.status !== 'completed') {
|
|
432
|
+
decision = current.status === 'cancelling' || signal.aborted ? 'cancel' : 'complete';
|
|
433
|
+
finalResult = stepResult;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
let nextInput = rawDecision.input;
|
|
437
|
+
if (rawDecision.kind === 'branch') {
|
|
438
|
+
const search = env.config.search;
|
|
439
|
+
const maxRollouts = (search?.maxRollouts ?? 3) -
|
|
440
|
+
searches.reduce((count, tree) => count + (tree === priorSearch ? 0 : tree.branches.length), 0);
|
|
441
|
+
const triggers = search?.triggers ?? ['stagnation', 'consecutive_failures'];
|
|
442
|
+
const ratio = search?.maxBudgetRatio ?? 0.4;
|
|
443
|
+
if (search?.mode === 'selective' &&
|
|
444
|
+
triggers.includes(rawDecision.trigger) &&
|
|
445
|
+
!searchesUsed &&
|
|
446
|
+
(priorSearch ||
|
|
447
|
+
(maxRollouts >= 2 &&
|
|
448
|
+
hasSearchBudget(current, searchTokenUsage(current), env.config, ratio, Date.parse(d.now()))))) {
|
|
449
|
+
try {
|
|
450
|
+
const result = await driveSelectiveSearch(d, scope, {
|
|
451
|
+
searchId,
|
|
452
|
+
trigger: rawDecision.trigger,
|
|
453
|
+
phase: 'execution',
|
|
454
|
+
anchorAgentSessionId: route.agentSessionId,
|
|
455
|
+
anchorTurnId: currentTurn.id,
|
|
456
|
+
goal: rawDecision.goal,
|
|
457
|
+
isolation: 'readonly',
|
|
458
|
+
searchConfig: {
|
|
459
|
+
...search,
|
|
460
|
+
maxRollouts,
|
|
461
|
+
branchFactor: Math.min(3, Math.max(2, search.branchFactor ?? 2)),
|
|
462
|
+
},
|
|
463
|
+
baseConfig: env.config,
|
|
464
|
+
rootWorkingDirectory: env.workingDirectory,
|
|
465
|
+
rootWorkingDirectoryUri: d.rootUri,
|
|
466
|
+
initialHypotheses: rawDecision.hypotheses ?? [],
|
|
467
|
+
}, signal);
|
|
468
|
+
if (result.branchSummaries.length) {
|
|
469
|
+
nextInput = [
|
|
470
|
+
`${BACKGROUND_CONTEXT_PREFIX}${formatSearchResultMessage(result, 'execution')}`,
|
|
471
|
+
`Original user goal: ${rawDecision.goal}`,
|
|
472
|
+
'Use the findings as evidence. Continue working toward the user goal and verify the result.',
|
|
473
|
+
].join('\n\n');
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
if (!signal.aborted && (await d.state.run(runId)).status !== 'cancelling')
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
current = await d.state.run(runId);
|
|
481
|
+
if (signal.aborted || current.status === 'cancelling') {
|
|
482
|
+
decision = 'cancel';
|
|
483
|
+
finalResult = stepResult;
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
nextInput ??= 'Revisit the unresolved user goal and verify a different approach.';
|
|
488
|
+
}
|
|
489
|
+
const admitted = await admitFollowupTurn(`run:${runId}:continue:${currentTurn.ordinal + 1}`, nextInput);
|
|
490
|
+
if (!admitted) {
|
|
491
|
+
if (isTerminalRunStatus((await d.state.run(runId)).status))
|
|
492
|
+
return;
|
|
493
|
+
finalResult = stepResult;
|
|
494
|
+
break;
|
|
495
|
+
}
|
|
496
|
+
continuationTurnsUsed += 1;
|
|
497
|
+
}
|
|
498
|
+
if (decision === 'pause' || !finalResult)
|
|
499
|
+
return;
|
|
500
|
+
const events = [];
|
|
501
|
+
if (decision === 'complete' && finalResult.status === 'completed')
|
|
502
|
+
events.push(d.journal.event('run.completed', scope, {
|
|
503
|
+
resultMessageId: finalResult.finalMessageId,
|
|
504
|
+
usage: current.chargedUsage,
|
|
505
|
+
}));
|
|
506
|
+
else if (decision === 'cancel') {
|
|
507
|
+
const searches = (await d.state.searches?.(runId)) ?? [];
|
|
508
|
+
const branchSessions = new Set(searches
|
|
509
|
+
.filter(({ status }) => status === 'running')
|
|
510
|
+
.flatMap(({ branches }) => branches.map(({ agentSessionId }) => agentSessionId)));
|
|
511
|
+
if (branchSessions.size) {
|
|
512
|
+
for (const turn of await d.state.turns(runId)) {
|
|
513
|
+
if (!branchSessions.has(turn.agentSessionId) ||
|
|
514
|
+
!['queued', 'running', 'paused'].includes(turn.status))
|
|
515
|
+
continue;
|
|
516
|
+
const { route: branchRoute } = await d.environment.load(runId, turn.agentSessionId);
|
|
517
|
+
await d.agent.resume({ ...branchRoute, turnId: turn.id, inputMessageId: turn.inputMessageId }, AbortSignal.abort());
|
|
518
|
+
}
|
|
519
|
+
current = await d.state.run(runId);
|
|
520
|
+
}
|
|
521
|
+
if (current.status !== 'cancelling')
|
|
522
|
+
events.push(d.journal.event('run.cancel_requested', scope, { reason: 'Driver cancelled' }));
|
|
523
|
+
events.push(d.journal.event('run.cancelled', scope, {
|
|
524
|
+
reason: 'Cancelled',
|
|
525
|
+
unresolvedCallIds: current.unresolvedCallIds,
|
|
526
|
+
}));
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
const error = finalResult.status === 'failed'
|
|
530
|
+
? finalResult.error
|
|
531
|
+
: {
|
|
532
|
+
code: decision === 'continue'
|
|
533
|
+
? 'NEW_TURN_INPUT_REQUIRED'
|
|
534
|
+
: finalResult.status === 'interrupted'
|
|
535
|
+
? finalResult.reason.toUpperCase()
|
|
536
|
+
: 'COMPLETION_POLICY',
|
|
537
|
+
message: decision === 'continue'
|
|
538
|
+
? 'Continuation requires explicit new Turn input'
|
|
539
|
+
: 'Run did not complete',
|
|
540
|
+
retryable: false,
|
|
541
|
+
...(finalResult.status === 'interrupted' && finalResult.budget
|
|
542
|
+
? { budget: finalResult.budget }
|
|
543
|
+
: {}),
|
|
544
|
+
};
|
|
545
|
+
const checkpoint = !team &&
|
|
546
|
+
!teamState &&
|
|
547
|
+
!current.unresolvedCallIds.length &&
|
|
548
|
+
(error.budget || error.code === 'context_overflow') &&
|
|
549
|
+
(await d.createCheckpoint?.(currentInput, env.config.checkpoint));
|
|
550
|
+
events.push(d.journal.event('run.failed', scope, {
|
|
551
|
+
error: checkpoint ? { ...error, checkpoint } : error,
|
|
552
|
+
usage: current.chargedUsage,
|
|
553
|
+
}));
|
|
554
|
+
}
|
|
555
|
+
for (const agentSession of await d.state.ownedAgentSessions(runId))
|
|
556
|
+
if (agentSession.owner.scope === 'run' &&
|
|
557
|
+
agentSession.owner.runId === runId &&
|
|
558
|
+
agentSession.status === 'open')
|
|
559
|
+
events.push(d.journal.event('agent_session.archived', { ...route, agentSessionId: agentSession.id, agentId: agentSession.agentId }, { reason: 'run_ended' }));
|
|
560
|
+
try {
|
|
561
|
+
await d.journal.append(`run:${runId}:terminal`, events);
|
|
562
|
+
}
|
|
563
|
+
catch (error) {
|
|
564
|
+
const latest = await d.state.run(runId);
|
|
565
|
+
if (isTerminalRunStatus(latest.status))
|
|
566
|
+
return;
|
|
567
|
+
if (latest.status !== 'cancelling' ||
|
|
568
|
+
!(error instanceof RuntimeError) ||
|
|
569
|
+
!['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code))
|
|
570
|
+
throw error;
|
|
571
|
+
await d.journal.append(`run:${runId}:terminal`, [
|
|
572
|
+
d.journal.event('run.cancelled', scope, {
|
|
573
|
+
reason: 'Cancelled',
|
|
574
|
+
unresolvedCallIds: latest.unresolvedCallIds,
|
|
575
|
+
}),
|
|
576
|
+
...events.filter((event) => event.type === 'agent_session.archived'),
|
|
577
|
+
]);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
async function requestCancel(runId, commandId, reason) {
|
|
581
|
+
const command = { type: 'run.cancel', runId, reason };
|
|
582
|
+
const previous = await d.journal.receipt(commandId, command);
|
|
583
|
+
const state = await d.state.run(runId);
|
|
584
|
+
if (isTerminalRunStatus(state.status))
|
|
585
|
+
return { work: Promise.resolve() };
|
|
586
|
+
if (!previous && state.status !== 'cancelling') {
|
|
587
|
+
const { route } = await d.environment.load(runId);
|
|
588
|
+
try {
|
|
589
|
+
await d.journal.append(commandId, [
|
|
590
|
+
d.journal.event('run.cancel_requested', { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId }, { reason }),
|
|
591
|
+
], undefined, command);
|
|
592
|
+
}
|
|
593
|
+
catch (error) {
|
|
594
|
+
const latest = await d.state.run(runId);
|
|
595
|
+
if (!(error instanceof RuntimeError) ||
|
|
596
|
+
!['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code) ||
|
|
597
|
+
(latest.status !== 'cancelling' && !isTerminalRunStatus(latest.status)))
|
|
598
|
+
throw error;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
active.get(runId)?.controller.abort();
|
|
602
|
+
const work = drive(runId, new AbortController().signal).then(async () => {
|
|
603
|
+
// The active driver may have returned a pause just as cancellation committed.
|
|
604
|
+
if ((await d.state.run(runId)).status === 'cancelling')
|
|
605
|
+
await drive(runId, new AbortController().signal);
|
|
606
|
+
});
|
|
607
|
+
cancellations.add(work);
|
|
608
|
+
void work.then(() => cancellations.delete(work), () => cancellations.delete(work));
|
|
609
|
+
return { work };
|
|
610
|
+
}
|
|
611
|
+
async function resumeAutomatically(runId, commandId) {
|
|
612
|
+
return resume(runId, commandId, true);
|
|
613
|
+
}
|
|
614
|
+
async function resume(runId, commandId, automatic = false) {
|
|
615
|
+
const command = { type: 'run.resume', runId };
|
|
616
|
+
if (await d.journal.receipt(commandId, command))
|
|
617
|
+
return true;
|
|
618
|
+
const state = await d.state.run(runId);
|
|
619
|
+
if (state.status !== 'paused')
|
|
620
|
+
throw new RuntimeError('INVALID_TRANSITION', 'Only a paused Run can resume');
|
|
621
|
+
await checkPluginVersions(runId);
|
|
622
|
+
const { route } = await d.environment.load(runId);
|
|
623
|
+
const turns = await d.state.turns(runId);
|
|
624
|
+
const pending = await Promise.all(turns.map((turn) => d.tools.pending(turn.id)));
|
|
625
|
+
if (pending
|
|
626
|
+
.flat()
|
|
627
|
+
.some((call) => call.status === 'outcome_unknown' ||
|
|
628
|
+
call.status === 'running' ||
|
|
629
|
+
call.approval?.status === 'pending'))
|
|
630
|
+
throw new RuntimeError('RUN_BLOCKED', 'Run still has unresolved blockers');
|
|
631
|
+
if (automatic && (await d.state.resumePreference?.(runId)) !== 'automatic')
|
|
632
|
+
return false;
|
|
633
|
+
const team = await d.state.team?.(runId);
|
|
634
|
+
const blocked = state.blockedTurnIds.slice(0, team && team.members.length > 1 ? team.concurrency : undefined);
|
|
635
|
+
const resumedTurns = await Promise.all(blocked.map(async (turnId) => {
|
|
636
|
+
const blocked = turns.find((turn) => turn.id === turnId);
|
|
637
|
+
const { route } = await d.environment.load(runId, blocked.agentSessionId);
|
|
638
|
+
const result = team && (await d.state.turnResult(turnId));
|
|
639
|
+
const deadlineAt = result && result.status === 'paused' && result.reason === 'approval'
|
|
640
|
+
? approvalResumeDeadline(blocked, state, d.now())
|
|
641
|
+
: undefined;
|
|
642
|
+
return d.journal.event('turn.resumed', route, {
|
|
643
|
+
turnId,
|
|
644
|
+
reason: 'user',
|
|
645
|
+
...(deadlineAt ? { deadlineAt } : {}),
|
|
646
|
+
});
|
|
647
|
+
}));
|
|
648
|
+
await d.journal.append(commandId, [
|
|
649
|
+
...resumedTurns,
|
|
650
|
+
d.journal.event('run.resumed', { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId }, { reason: 'user' }),
|
|
651
|
+
], undefined, command);
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
return {
|
|
655
|
+
async submit(input) {
|
|
656
|
+
const { commandId, ...task } = input;
|
|
657
|
+
return (await handler.handle(commandId, { type: 'run.submit', input: task }));
|
|
658
|
+
},
|
|
659
|
+
drive,
|
|
660
|
+
checkPluginVersions,
|
|
661
|
+
requestCancel,
|
|
662
|
+
async steer(commandId, command) {
|
|
663
|
+
const { runId, agentSessionId } = command;
|
|
664
|
+
const { route } = await d.environment.load(runId, agentSessionId);
|
|
665
|
+
if (!d.agent.steer)
|
|
666
|
+
throw new RuntimeError('STEER_UNAVAILABLE', 'Runtime agent does not support steering');
|
|
667
|
+
try {
|
|
668
|
+
await d.agent.steer(route.agentSessionId, commandId, command);
|
|
669
|
+
}
|
|
670
|
+
catch (error) {
|
|
671
|
+
if (!(error instanceof RuntimeError) || error.code !== 'STEER_UNAVAILABLE')
|
|
672
|
+
throw error;
|
|
673
|
+
const [runState, teamState, mainEnv] = await Promise.all([
|
|
674
|
+
d.state.run(runId),
|
|
675
|
+
d.state.team?.(runId) ?? Promise.resolve(null),
|
|
676
|
+
d.environment.load(runId),
|
|
677
|
+
]);
|
|
678
|
+
const isIdleAsyncMain = runState.status === 'running' &&
|
|
679
|
+
Boolean(teamState) &&
|
|
680
|
+
isAsyncCoordinatorConfig(mainEnv.config) &&
|
|
681
|
+
route.agentSessionId === mainEnv.route.agentSessionId;
|
|
682
|
+
if (!isIdleAsyncMain)
|
|
683
|
+
throw error;
|
|
684
|
+
if (await d.journal.receipt(`steer:${commandId}`, command))
|
|
685
|
+
return;
|
|
686
|
+
const runSteers = getPendingCoordinatorSteers(runId);
|
|
687
|
+
const existing = runSteers.get(commandId);
|
|
688
|
+
if (existing && existing.content !== command.content) {
|
|
689
|
+
throw new RuntimeError('COMMAND_CONFLICT', 'Steering command ID is already in use');
|
|
690
|
+
}
|
|
691
|
+
runSteers.set(commandId, { commandId, content: command.content });
|
|
692
|
+
const wake = teamWakes.get(runId);
|
|
693
|
+
if (wake) {
|
|
694
|
+
wake.target.dispatchEvent(new Event('wake'));
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
},
|
|
698
|
+
async cancel(runId, commandId, reason) {
|
|
699
|
+
const { work } = await requestCancel(runId, commandId, reason);
|
|
700
|
+
await work;
|
|
701
|
+
},
|
|
702
|
+
async resume(runId, commandId) {
|
|
703
|
+
await resume(runId, commandId);
|
|
704
|
+
},
|
|
705
|
+
resumeAutomatically,
|
|
706
|
+
wakeTeam(runId) {
|
|
707
|
+
const wake = teamWakes.get(runId);
|
|
708
|
+
if (!wake)
|
|
709
|
+
return;
|
|
710
|
+
const checked = new Promise((resolve) => wake.waiters.add(resolve));
|
|
711
|
+
wake.target.dispatchEvent(new Event('wake'));
|
|
712
|
+
return checked;
|
|
713
|
+
},
|
|
714
|
+
async drain() {
|
|
715
|
+
await Promise.all([...cancellations, ...[...active.values()].map((item) => item.work)]);
|
|
716
|
+
},
|
|
717
|
+
async stop() {
|
|
718
|
+
stopping = true;
|
|
719
|
+
for (const [runId, item] of active) {
|
|
720
|
+
const state = await d.state.run(runId);
|
|
721
|
+
if (!state.pluginBlock && state.status !== 'cancelling' && !isTerminalRunStatus(state.status)) {
|
|
722
|
+
const { route } = await d.environment.load(runId);
|
|
723
|
+
try {
|
|
724
|
+
await d.journal.append(`shutdown:${runId}:cancel`, [
|
|
725
|
+
d.journal.event('run.cancel_requested', { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId }, { reason: 'Host shutdown' }),
|
|
726
|
+
]);
|
|
727
|
+
}
|
|
728
|
+
catch (error) {
|
|
729
|
+
const { status } = await d.state.run(runId);
|
|
730
|
+
if (status !== 'cancelling' && !isTerminalRunStatus(status))
|
|
731
|
+
throw error;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
item.controller.abort();
|
|
735
|
+
}
|
|
736
|
+
await Promise.all([...cancellations, ...[...active.values()].map((item) => item.work)]);
|
|
737
|
+
},
|
|
738
|
+
};
|
|
739
|
+
}
|