@saturn-universe/runtime 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1072 @@
1
+ import { BudgetError, defaultModelTotalTimeoutMs, DEFAULT_SUBAGENT_WALL_TIME_MS, earlierDeadline, isLimited, maxModelReasoningSummaryLength, modelReasoningSummary, modelTokenBudget, reportDiagnostic, resolveSubagentMaxModelAttempts, resolveSubagentWallTimeMs, rewriteModelRequest, RuntimeError, shouldTriggerCompaction, slimModelRequest, validateStartedRun, } from '@saturn-universe/core';
2
+ import { autoCompactSurface, resolveAutoCompactionOptions, } from './compaction.js';
3
+ export function modelRetryDelayMs(retry, attempt, retryAfterMs, random = Math.random) {
4
+ if (retryAfterMs !== undefined)
5
+ return retryAfterMs;
6
+ const base = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1));
7
+ const sample = Math.max(0, Math.min(1, random()));
8
+ return Math.min(retry.maxDelayMs, Math.round(base * (0.85 + 0.3 * sample)));
9
+ }
10
+ export function createAgentLoop(d) {
11
+ const steering = new Map();
12
+ async function execute(input, signal) {
13
+ const previous = steering.get(input.agentSessionId);
14
+ const turn = {
15
+ input,
16
+ pending: previous?.input.turnId === input.turnId ? previous.pending : new Map(),
17
+ accepting: !signal.aborted,
18
+ };
19
+ steering.set(input.agentSessionId, turn);
20
+ let result;
21
+ try {
22
+ result = await executeTurn(input, signal, turn);
23
+ return result;
24
+ }
25
+ finally {
26
+ turn.accepting = false;
27
+ if (steering.get(input.agentSessionId) === turn && (result?.status !== 'paused' || !turn.pending.size))
28
+ steering.delete(input.agentSessionId);
29
+ d.liveAgents?.clearAgent(input);
30
+ }
31
+ }
32
+ async function appendSteering(turn, route) {
33
+ for (const [commandId, command] of [...turn.pending]) {
34
+ await d.journal.append(`steer:${commandId}`, [
35
+ d.journal.event('message.user.added', route, {
36
+ steering: true,
37
+ message: {
38
+ id: d.id(),
39
+ agentSessionId: route.agentSessionId,
40
+ runId: route.runId,
41
+ turnId: turn.input.turnId,
42
+ role: 'user',
43
+ content: [{ type: 'text', text: command.content }],
44
+ },
45
+ }),
46
+ ], undefined, command);
47
+ turn.pending.delete(commandId);
48
+ }
49
+ }
50
+ async function executeTurn(input, signal, steering) {
51
+ const env = await d.environment.load(input.runId, input.agentSessionId);
52
+ const { route, config } = env;
53
+ const previous = await d.state.turnResult(input.turnId);
54
+ if (previous && previous.status !== 'paused')
55
+ return previous;
56
+ const entry = await d.state.run(input.runId);
57
+ if (entry.status === 'cancelling' || signal.aborted)
58
+ return interrupt(input, 'cancelled');
59
+ const hooks = d.hooks?.(config, env);
60
+ const startedRun = validateStartedRun(entry, config.limits);
61
+ let turn = await d.state.turn(input.turnId);
62
+ if (turn.status === 'queued' && (await d.state.run(input.runId)).status === 'running') {
63
+ await d.journal.append(`turn:${input.turnId}:start`, [
64
+ d.journal.event('turn.started', route, { turnId: input.turnId, startedAt: d.clock.now() }),
65
+ ]);
66
+ turn = await d.state.turn(input.turnId);
67
+ }
68
+ if (d.liveAgents)
69
+ d.liveAgents.update(input, {
70
+ phase: 'idle',
71
+ stepCount: (await d.state.steps(input.turnId)).at(-1)?.ordinal ?? 0,
72
+ });
73
+ const deadlineAt = earlierDeadline(startedRun.deadlineAt, turn.deadlineAt);
74
+ const subagentWall = resolveSubagentWallTimeMs(config.limits);
75
+ const limitWallTimeMs = turn.deadlineAt && isLimited(subagentWall)
76
+ ? subagentWall
77
+ : isLimited(config.limits.wallTimeMs)
78
+ ? config.limits.wallTimeMs
79
+ : undefined;
80
+ let lastWireRequest;
81
+ const turnStartedAtMs = Date.parse(d.clock.now());
82
+ let softCheckpointCount = 0;
83
+ while (true) {
84
+ const run = await d.state.run(input.runId);
85
+ if (run.status === 'cancelling' || signal.aborted)
86
+ return interrupt(input, 'cancelled');
87
+ if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
88
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
89
+ turn = await d.state.turn(input.turnId);
90
+ if (turn.status === 'paused') {
91
+ const paused = await d.state.turnResult(turn.id);
92
+ if (paused?.status === 'paused')
93
+ return paused;
94
+ continue;
95
+ }
96
+ const attempts = await d.state.modelAttempts(input.turnId);
97
+ const last = attempts.at(-1);
98
+ if (last?.status === 'requested') {
99
+ await failAttempt(input, last, {
100
+ code: 'response_not_committed',
101
+ message: 'Uncommitted model response after recovery',
102
+ retryable: true,
103
+ outcomeUnknown: true,
104
+ });
105
+ continue;
106
+ }
107
+ if (last?.status === 'responded') {
108
+ const result = await consumePreviousResponse(input, signal, last, route, steering);
109
+ if (result)
110
+ return result;
111
+ }
112
+ if (steering.pending.size) {
113
+ if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
114
+ return interrupt(input, 'cancelled');
115
+ try {
116
+ await appendSteering(steering, route);
117
+ }
118
+ catch (error) {
119
+ if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
120
+ return interrupt(input, 'cancelled');
121
+ throw error;
122
+ }
123
+ if (steering.pending.size)
124
+ continue;
125
+ }
126
+ const state = await d.state.run(input.runId);
127
+ const isSubagentTurn = Boolean(turn.deadlineAt || env.membership?.role === 'worker' || env.membership?.searchBranchId !== undefined);
128
+ const softCheckpointMs = config.workerSoftCheckpointMs;
129
+ if (state.status === 'running' &&
130
+ turn.status === 'running' &&
131
+ isSubagentTurn &&
132
+ (config.agentDepth ?? 1) === 1 &&
133
+ softCheckpointMs !== undefined &&
134
+ softCheckpointMs > 0) {
135
+ const elapsedMs = Date.parse(d.clock.now()) - turnStartedAtMs;
136
+ if (elapsedMs >= softCheckpointMs * (softCheckpointCount + 1)) {
137
+ softCheckpointCount += 1;
138
+ const elapsedMin = Math.max(1, Math.round(elapsedMs / 60_000));
139
+ try {
140
+ await d.journal.append(`turn:${input.turnId}:soft-checkpoint:${softCheckpointCount}`, [
141
+ d.journal.event('message.user.added', route, {
142
+ steering: true,
143
+ message: {
144
+ id: d.id(),
145
+ agentSessionId: route.agentSessionId,
146
+ runId: route.runId,
147
+ turnId: input.turnId,
148
+ role: 'user',
149
+ content: [
150
+ {
151
+ type: 'text',
152
+ text: `[Soft Checkpoint · ${elapsedMin}m elapsed] Pause briefly to persist verified facts/hypotheses into the challenge ledger (\`ctf_record_fact\` / \`ctf_record_hypothesis\`). If you hit a heavy sub-problem you can isolate cleanly, consider spawning a focused Depth-2 Helper via \`spawn_team\`; if holding an unused remote container lease while analyzing offline, call \`ctf_platform_instance(action="stop")\`. If you have made no new verified progress (no new \`ctf_record_fact\` or distinct exploit primitive) since the previous checkpoint, do NOT continue open-ended trial-and-error: persist exact dead ends to the ledger, release any remote lease, mark the challenge \`blocked\` on the board, and return a concise summary immediately so the Coordinator can reallocate the slot.`,
153
+ },
154
+ ],
155
+ },
156
+ }),
157
+ ]);
158
+ }
159
+ catch (error) {
160
+ d.logger.info({
161
+ runId: input.runId,
162
+ turnId: input.turnId,
163
+ code: error instanceof RuntimeError ? error.code : 'SOFT_CHECKPOINT_SKIPPED',
164
+ error: error instanceof Error ? error.message : String(error),
165
+ }, 'Skipped non-fatal worker soft checkpoint reminder');
166
+ }
167
+ }
168
+ }
169
+ const subagentMaxAttempts = isSubagentTurn ? resolveSubagentMaxModelAttempts(config.limits) : 0;
170
+ const counters = [
171
+ ...(isLimited(config.limits.maxModelAttempts)
172
+ ? [
173
+ {
174
+ resource: 'modelAttempts',
175
+ used: state.modelAttempts,
176
+ max: config.limits.maxModelAttempts,
177
+ },
178
+ ]
179
+ : []),
180
+ ...(isLimited(subagentMaxAttempts)
181
+ ? [{ resource: 'modelAttempts', used: attempts.length, max: subagentMaxAttempts }]
182
+ : []),
183
+ ...(isLimited(config.limits.maxSteps)
184
+ ? [{ resource: 'steps', used: state.stepsStarted, max: config.limits.maxSteps }]
185
+ : []),
186
+ ...(isLimited(config.limits.maxTotalTokens)
187
+ ? [modelTokenBudget(state, config.limits.maxTotalTokens)]
188
+ : []),
189
+ ];
190
+ const exhausted = counters.find(({ used, max }) => used >= max);
191
+ if (exhausted)
192
+ return interrupt(input, 'limit', exhausted);
193
+ const planned = await planRequest(input, signal, route, config, attempts, deadlineAt, limitWallTimeMs, state.reservedTokens, hooks, lastWireRequest);
194
+ if (!planned)
195
+ continue;
196
+ if ('status' in planned)
197
+ return planned;
198
+ if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
199
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
200
+ const request = planned;
201
+ lastWireRequest = request;
202
+ if (isLimited(config.limits.maxTotalTokens)) {
203
+ const budget = modelTokenBudget(state, config.limits.maxTotalTokens, request.budget.reservedTotalTokens);
204
+ if (budget.required > budget.max)
205
+ return interrupt(input, 'limit', budget);
206
+ }
207
+ try {
208
+ if (steering.pending.size)
209
+ continue;
210
+ const result = await runModelAttempt(input, signal, env, request, deadlineAt, limitWallTimeMs, steering);
211
+ if (result)
212
+ return result;
213
+ }
214
+ finally {
215
+ steering.attempt = undefined;
216
+ if (config.streamText)
217
+ d.liveText?.clear(request.id);
218
+ }
219
+ }
220
+ }
221
+ async function consumePreviousResponse(input, signal, last, route, steering) {
222
+ if (last.response.finishReason === 'length')
223
+ return interrupt(input, 'limit', {
224
+ resource: 'modelOutput',
225
+ used: last.response.usage.outputTokens,
226
+ max: last.request.maxOutputTokens,
227
+ });
228
+ if (last.response.finishReason === 'content_filter')
229
+ return failTurn(input, {
230
+ code: 'CONTENT_FILTER',
231
+ message: 'Model output was filtered',
232
+ retryable: false,
233
+ });
234
+ if (last.response.toolCalls.length) {
235
+ const group = {
236
+ runId: input.runId,
237
+ turnId: input.turnId,
238
+ agentSessionId: input.agentSessionId,
239
+ assistantMessageId: last.assistant.id,
240
+ signal,
241
+ ...(d.liveAgents && {
242
+ onToolWaiting(currentTool, lastActivityAt) {
243
+ d.liveAgents?.update(input, {
244
+ phase: 'tool',
245
+ currentTool: `${currentTool} (queued)`,
246
+ lastActivityAt,
247
+ });
248
+ },
249
+ onToolStarted(currentTool, stepCount, lastActivityAt) {
250
+ d.liveAgents?.update(input, { phase: 'tool', currentTool, stepCount, lastActivityAt });
251
+ },
252
+ }),
253
+ };
254
+ const result = await d.executor.executeBatch(group);
255
+ d.liveAgents?.update(input, { phase: 'idle', lastActivityAt: d.clock.now() });
256
+ if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
257
+ return interrupt(input, 'cancelled');
258
+ if (result.status === 'paused')
259
+ return { status: 'paused', turnId: input.turnId, reason: result.reason };
260
+ if (result.status === 'cancelled')
261
+ return interrupt(input, 'cancelled');
262
+ if (result.status === 'interrupted')
263
+ return interrupt(input, result.reason, result.budget);
264
+ const spawnCallIds = new Set(last.assistant.toolCalls.filter((call) => call.toolName === 'spawn_team').map((call) => call.id));
265
+ if (spawnCallIds.size > 0 && !steering.pending.size) {
266
+ const surface = await d.surface.read(input.agentSessionId);
267
+ const settledSpawnTeam = surface.items.some((item) => {
268
+ if (!item.active ||
269
+ item.message.role !== 'tool' ||
270
+ item.message.turnId !== input.turnId ||
271
+ !spawnCallIds.has(item.message.result.toolCallId))
272
+ return false;
273
+ const outcome = item.message.result.outcome;
274
+ return (outcome.status === 'success' &&
275
+ Boolean(outcome.data) &&
276
+ typeof outcome.data === 'object' &&
277
+ !Array.isArray(outcome.data) &&
278
+ outcome.data.kind === 'spawn_team');
279
+ });
280
+ if (settledSpawnTeam) {
281
+ const usage = (await d.state.run(input.runId)).chargedUsage;
282
+ if (steering.pending.size)
283
+ return;
284
+ steering.accepting = false;
285
+ const completed = {
286
+ status: 'completed',
287
+ turnId: input.turnId,
288
+ finalMessageId: last.assistant.id,
289
+ usage,
290
+ };
291
+ await d.journal.append(`turn:${input.turnId}:completed`, [
292
+ d.journal.event('turn.completed', route, {
293
+ turnId: input.turnId,
294
+ finalMessageId: last.assistant.id,
295
+ usage,
296
+ }),
297
+ ]);
298
+ return completed;
299
+ }
300
+ }
301
+ }
302
+ else if (last.response.turnDisposition === 'final') {
303
+ const usage = (await d.state.run(input.runId)).chargedUsage;
304
+ if (steering.pending.size)
305
+ return;
306
+ steering.accepting = false;
307
+ const result = {
308
+ status: 'completed',
309
+ turnId: input.turnId,
310
+ finalMessageId: last.assistant.id,
311
+ usage,
312
+ };
313
+ await d.journal.append(`turn:${input.turnId}:completed`, [
314
+ d.journal.event('turn.completed', route, {
315
+ turnId: input.turnId,
316
+ finalMessageId: last.assistant.id,
317
+ usage,
318
+ }),
319
+ ]);
320
+ return result;
321
+ }
322
+ }
323
+ async function planRequest(input, signal, route, config, attempts, deadlineAt, limitWallTimeMs, reservedTokens, hooks, previousWireRequest) {
324
+ const last = attempts.at(-1);
325
+ const autoCompactOpts = resolveAutoCompactionOptions(d.autoCompaction);
326
+ const maxOverflowCompactionRecoveries = 2;
327
+ let request;
328
+ try {
329
+ const retryPrevious = last?.status === 'failed' &&
330
+ last.error.code !== 'steered' &&
331
+ !(await d.surface.read(input.agentSessionId)).items.some((item) => item.orderSeq > last.request.context.surfaceSeq &&
332
+ item.message.turnId === input.turnId &&
333
+ item.message.role === 'user');
334
+ if (retryPrevious) {
335
+ if (!last.error.retryable || last.request.attempt >= config.retry.modelMaxAttemptsPerCall)
336
+ return failTurn(input, { code: last.error.code, message: last.error.message, retryable: false });
337
+ const safeOverflow = last.error.code === 'context_overflow' &&
338
+ last.request.attempt === 1 &&
339
+ !attempts.some((attempt) => attempt.status === 'responded');
340
+ const callGroupOverflowCount = last.error.code === 'context_overflow'
341
+ ? attempts.filter((attempt) => attempt.request.callGroupId === last.request.callGroupId &&
342
+ attempt.status === 'failed' &&
343
+ attempt.error.code === 'context_overflow').length
344
+ : 0;
345
+ const canRecoverOverflowByCompaction = last.error.code === 'context_overflow' &&
346
+ !safeOverflow &&
347
+ autoCompactOpts.enabled &&
348
+ callGroupOverflowCount <= maxOverflowCompactionRecoveries;
349
+ if (last.error.code === 'context_overflow' && !safeOverflow && !canRecoverOverflowByCompaction)
350
+ return failTurn(input, { code: last.error.code, message: last.error.message, retryable: false });
351
+ const retryDelay = () => Math.max(0, Date.parse(last.retryAt ?? d.clock.now()) - Date.parse(d.clock.now()));
352
+ const retryExceedsDeadline = (delayMs) => {
353
+ if (!deadlineAt)
354
+ return false;
355
+ const remainingMs = Date.parse(deadlineAt) - Date.parse(d.clock.now());
356
+ if (delayMs < remainingMs)
357
+ return false;
358
+ d.logger.info({
359
+ runId: input.runId,
360
+ turnId: input.turnId,
361
+ requestId: last.request.id,
362
+ phase: last.error.details?.phase ?? null,
363
+ reason: 'retry_delay_reaches_deadline',
364
+ delayMs,
365
+ remainingMs,
366
+ deadlineAt,
367
+ retryAfterMs: last.error.retryAfterMs ?? null,
368
+ }, 'Model retry stopped because the required delay reaches the Run or Turn deadline');
369
+ return true;
370
+ };
371
+ const initialDelay = retryDelay();
372
+ if (deadlineAt && retryExceedsDeadline(initialDelay))
373
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt, initialDelay));
374
+ let compactedForOverflow = false;
375
+ if (canRecoverOverflowByCompaction) {
376
+ const contextWindow = await d.gateway
377
+ .describe(config.model)
378
+ .then((info) => info.capabilities.contextWindow)
379
+ .catch(() => undefined);
380
+ if (contextWindow !== undefined) {
381
+ const outcome = await autoCompactSurface({
382
+ surface: d.surface,
383
+ state: d.state,
384
+ journal: d.journal,
385
+ gateway: d.gateway,
386
+ hash: d.hash,
387
+ id: d.id,
388
+ logger: d.logger,
389
+ }, {
390
+ route,
391
+ turnId: input.turnId,
392
+ config,
393
+ contextWindow,
394
+ signal,
395
+ options: autoCompactOpts,
396
+ });
397
+ compactedForOverflow = outcome.compacted;
398
+ }
399
+ if (!compactedForOverflow)
400
+ return failTurn(input, { code: last.error.code, message: last.error.message, retryable: false });
401
+ }
402
+ const delay = retryDelay();
403
+ if (deadlineAt && retryExceedsDeadline(delay))
404
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt, delay));
405
+ const now = d.clock.now();
406
+ d.liveAgents?.update(input, {
407
+ phase: 'retrying',
408
+ requestStartedAt: now,
409
+ lastActivityAt: now,
410
+ retryAttempt: last.request.attempt + 1,
411
+ retryMaxAttempts: config.retry.modelMaxAttemptsPerCall,
412
+ });
413
+ try {
414
+ let remaining = delay;
415
+ while (remaining > 0) {
416
+ // Node timers overflow above the signed 32-bit limit.
417
+ const interval = Math.min(remaining, 2_147_483_647);
418
+ await d.clock.delay(interval, signal);
419
+ remaining -= interval;
420
+ }
421
+ }
422
+ catch {
423
+ return interrupt(input, 'cancelled');
424
+ }
425
+ const surface = await d.surface.read(input.agentSessionId);
426
+ const fullPrevious = previousWireRequest?.id === last.request.id ? previousWireRequest : undefined;
427
+ const surfaceWasCompacted = compactedForOverflow || (surface.lastCompactionSeq ?? 0) > last.request.context.surfaceSeq;
428
+ if (safeOverflow || surfaceWasCompacted) {
429
+ const assembly = surfaceWasCompacted
430
+ ? await d.composer.assemble({ ...input, config, signal })
431
+ : await d.composer.rebuildAfterOverflow({ ...input, config, signal }, fullPrevious ?? last.request);
432
+ request = {
433
+ ...last.request,
434
+ id: d.id(),
435
+ attempt: last.request.attempt + 1,
436
+ retryOf: last.request.id,
437
+ binding: assembly.binding,
438
+ messages: assembly.messages,
439
+ responses: assembly.responses,
440
+ tools: assembly.tools,
441
+ maxOutputTokens: assembly.outputReserve,
442
+ budget: {
443
+ estimatedInputTokens: assembly.estimate.inputTokens,
444
+ reservedTotalTokens: assembly.estimate.inputTokens + assembly.outputReserve,
445
+ accuracy: assembly.estimate.accuracy,
446
+ },
447
+ context: {
448
+ surfaceSeq: assembly.surfaceSeq,
449
+ selectedMessageIds: assembly.selectedMessageIds,
450
+ assemblyHash: assembly.assemblyHash,
451
+ providerVersions: assembly.providerVersions,
452
+ },
453
+ };
454
+ }
455
+ else if (fullPrevious) {
456
+ request = {
457
+ ...fullPrevious,
458
+ id: d.id(),
459
+ attempt: last.request.attempt + 1,
460
+ retryOf: last.request.id,
461
+ context: { ...last.request.context, surfaceSeq: surface.lastStreamSeq },
462
+ };
463
+ }
464
+ else {
465
+ const assembly = await d.composer.assemble({ ...input, config, signal });
466
+ request = {
467
+ ...last.request,
468
+ id: d.id(),
469
+ attempt: last.request.attempt + 1,
470
+ retryOf: last.request.id,
471
+ binding: assembly.binding,
472
+ messages: assembly.messages,
473
+ responses: assembly.responses,
474
+ tools: assembly.tools,
475
+ context: { ...last.request.context, surfaceSeq: surface.lastStreamSeq },
476
+ };
477
+ }
478
+ }
479
+ else {
480
+ const lastResponded = [...attempts]
481
+ .reverse()
482
+ .find((attempt) => attempt.status === 'responded');
483
+ const lastReportedInput = lastResponded?.response.usage.inputTokens;
484
+ let assembly;
485
+ let initialContextError;
486
+ try {
487
+ assembly = await d.composer.assemble({ ...input, config, signal });
488
+ }
489
+ catch (error) {
490
+ if (autoCompactOpts.enabled &&
491
+ error instanceof BudgetError &&
492
+ ['CONTEXT_BUDGET_EXCEEDED', 'CONTINUATION_BUDGET_EXCEEDED'].includes(error.code)) {
493
+ initialContextError = error;
494
+ }
495
+ else {
496
+ throw error;
497
+ }
498
+ }
499
+ const initialEstimatedInput = assembly?.estimate.inputTokens;
500
+ const contextWindow = assembly?.contextWindow ??
501
+ (await d.gateway
502
+ .describe(config.model)
503
+ .then((info) => info.capabilities.contextWindow)
504
+ .catch(() => undefined));
505
+ const needsCompaction = autoCompactOpts.enabled &&
506
+ contextWindow !== undefined &&
507
+ (assembly === undefined ||
508
+ shouldTriggerCompaction(Math.max(assembly.estimate.inputTokens, lastReportedInput ?? 0), contextWindow, autoCompactOpts));
509
+ if (needsCompaction && contextWindow !== undefined) {
510
+ // Stage 1: Model-free Tool Result Pruner
511
+ let prunedAssembly;
512
+ try {
513
+ prunedAssembly = await d.composer.assemble({ ...input, config, signal, pruneToolResults: true });
514
+ if (!assembly || prunedAssembly.estimate.inputTokens < assembly.estimate.inputTokens) {
515
+ assembly = prunedAssembly;
516
+ }
517
+ }
518
+ catch (error) {
519
+ if (!(error instanceof BudgetError &&
520
+ ['CONTEXT_BUDGET_EXCEEDED', 'CONTINUATION_BUDGET_EXCEEDED'].includes(error.code))) {
521
+ throw error;
522
+ }
523
+ }
524
+ const prunedSavings = initialEstimatedInput !== undefined && assembly !== undefined
525
+ ? Math.max(0, initialEstimatedInput - assembly.estimate.inputTokens)
526
+ : 0;
527
+ const effectivePostPruneTokens = assembly === undefined
528
+ ? undefined
529
+ : Math.max(assembly.estimate.inputTokens, (lastReportedInput ?? 0) - prunedSavings);
530
+ // Re-measure pressure after Stage 1 Pruner; only run Stage 2 if still over threshold.
531
+ const stillOverThreshold = effectivePostPruneTokens === undefined ||
532
+ shouldTriggerCompaction(effectivePostPruneTokens, contextWindow, autoCompactOpts);
533
+ if (stillOverThreshold) {
534
+ // Stage 2: Threshold-triggered auto-compaction (supports active turn closed step prefix).
535
+ const outcome = await autoCompactSurface({
536
+ surface: d.surface,
537
+ state: d.state,
538
+ journal: d.journal,
539
+ gateway: d.gateway,
540
+ hash: d.hash,
541
+ id: d.id,
542
+ logger: d.logger,
543
+ }, {
544
+ route,
545
+ turnId: input.turnId,
546
+ config,
547
+ contextWindow,
548
+ signal,
549
+ options: autoCompactOpts,
550
+ });
551
+ if (outcome.compacted) {
552
+ assembly = await d.composer.assemble({ ...input, config, signal });
553
+ }
554
+ }
555
+ }
556
+ if (!assembly)
557
+ throw initialContextError ?? new RuntimeError('CONTEXT_FAILED', 'Context could not be assembled');
558
+ if (d.checkpointOnContextPressure &&
559
+ !config.team &&
560
+ !config.planner &&
561
+ assembly.windowInputTokens !== undefined &&
562
+ assembly.responses.decision.kind === 'append' &&
563
+ attempts.filter((attempt) => attempt.status === 'responded' && attempt.response.toolCalls.length)
564
+ .length >= 2 &&
565
+ assembly.estimate.inputTokens >= Math.ceil(assembly.windowInputTokens * 0.8))
566
+ throw new BudgetError('CONTEXT_CHECKPOINT', {
567
+ resource: 'context',
568
+ used: assembly.estimate.inputTokens,
569
+ max: assembly.windowInputTokens,
570
+ });
571
+ const id = d.id();
572
+ request = {
573
+ id,
574
+ callGroupId: id,
575
+ attempt: 1,
576
+ agentSessionId: input.agentSessionId,
577
+ runId: input.runId,
578
+ turnId: input.turnId,
579
+ model: assembly.model,
580
+ binding: assembly.binding,
581
+ messages: assembly.messages,
582
+ responses: assembly.responses,
583
+ responsesOptions: config.responses,
584
+ tools: assembly.tools,
585
+ output: { kind: 'text' },
586
+ maxOutputTokens: assembly.outputReserve,
587
+ budget: {
588
+ estimatedInputTokens: assembly.estimate.inputTokens,
589
+ reservedTotalTokens: assembly.estimate.inputTokens + assembly.outputReserve,
590
+ accuracy: assembly.estimate.accuracy,
591
+ },
592
+ context: {
593
+ surfaceSeq: assembly.surfaceSeq,
594
+ selectedMessageIds: assembly.selectedMessageIds,
595
+ assemblyHash: assembly.assemblyHash,
596
+ providerVersions: assembly.providerVersions,
597
+ },
598
+ };
599
+ }
600
+ if (hooks?.beforeModelRequest) {
601
+ const rewritten = await rewriteModelRequest(request, hooks.beforeModelRequest);
602
+ if (rewritten !== request) {
603
+ if (!d.gateway.validateRequest)
604
+ throw new RuntimeError('MODEL_REQUEST_VALIDATOR_REQUIRED', 'Rewritten request requires validation');
605
+ await d.gateway.validateRequest(rewritten);
606
+ request = rewritten;
607
+ }
608
+ if (signal.aborted)
609
+ return interrupt(input, 'cancelled');
610
+ }
611
+ }
612
+ catch (error) {
613
+ if (signal.aborted)
614
+ return interrupt(input, 'cancelled');
615
+ if (error instanceof RuntimeError && error.code === 'PLUGIN_VERSION_UNAVAILABLE')
616
+ throw error;
617
+ if (error instanceof RuntimeError && error.code === 'RUN_BUDGET_EXCEEDED') {
618
+ if (config.team && (reservedTokens || (await d.state.run(input.runId)).reservedTokens)) {
619
+ await waitForBudget(signal);
620
+ return;
621
+ }
622
+ return interrupt(input, 'limit', error instanceof BudgetError ? error.budget : undefined);
623
+ }
624
+ reportDiagnostic(d.logger, error, d.id(), 'CONTEXT_FAILED', {
625
+ runId: input.runId,
626
+ turnId: input.turnId,
627
+ });
628
+ const modelError = error?.error;
629
+ return failTurn(input, {
630
+ code: modelError?.code ?? (error instanceof RuntimeError ? error.code : 'CONTEXT_FAILED'),
631
+ message: modelError?.message ??
632
+ (error instanceof RuntimeError ? error.message : 'Context could not be assembled'),
633
+ retryable: false,
634
+ ...(error instanceof BudgetError ? { budget: error.budget } : {}),
635
+ });
636
+ }
637
+ return request;
638
+ }
639
+ async function runModelAttempt(input, signal, env, request, deadlineAt, limitWallTimeMs, steering) {
640
+ const { route, config } = env;
641
+ const stepId = d.id();
642
+ let requestedEventId;
643
+ let stepCount;
644
+ try {
645
+ const started = await d.journal.append(`request:${request.id}:start`, (ordinal) => [
646
+ d.journal.event('step.started', route, {
647
+ step: { id: stepId, turnId: input.turnId, ordinal, kind: 'model', status: 'running' },
648
+ }),
649
+ d.journal.event('model.requested', route, { stepId, request: slimModelRequest(request) }),
650
+ ], input.turnId);
651
+ requestedEventId = started.events[1].id;
652
+ const step = started.events[0];
653
+ if (step?.type === 'step.started')
654
+ stepCount = step.payload.step.ordinal;
655
+ }
656
+ catch (error) {
657
+ const current = await d.state.run(input.runId);
658
+ if (current.status === 'cancelling' || signal.aborted)
659
+ return interrupt(input, 'cancelled');
660
+ if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
661
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
662
+ if ((config.team || env.membership?.searchBranchId !== undefined) &&
663
+ error instanceof RuntimeError &&
664
+ error.code === 'RUN_BUDGET_EXCEEDED') {
665
+ if ((isLimited(config.limits.maxModelAttempts) &&
666
+ current.modelAttempts >= config.limits.maxModelAttempts) ||
667
+ (isLimited(config.limits.maxSteps) && current.stepsStarted >= config.limits.maxSteps))
668
+ return interrupt(input, 'limit');
669
+ if (isLimited(config.limits.maxTotalTokens)) {
670
+ const budget = modelTokenBudget(current, config.limits.maxTotalTokens);
671
+ if (budget.used >= budget.max)
672
+ return interrupt(input, 'limit', budget);
673
+ }
674
+ // Another member reserved or charged tokens after this request was composed.
675
+ // Rebuild against current usage or let the competing reservation settle first.
676
+ if (current.reservedTokens)
677
+ await waitForBudget(signal);
678
+ return;
679
+ }
680
+ if (error instanceof RuntimeError &&
681
+ ['VERSION_CONFLICT', 'INVALID_TRANSITION'].includes(error.code) &&
682
+ ((await d.surface.read(input.agentSessionId)).lastCompactionSeq ?? 0) > request.context.surfaceSeq)
683
+ return; // A concurrent compaction won admission. The loop rebuilds from the new Surface.
684
+ throw error;
685
+ }
686
+ let response;
687
+ let modelContextWindow;
688
+ let firstTokenMs;
689
+ const observation = {};
690
+ const attemptStartMs = performance.now();
691
+ const attempt = new AbortController();
692
+ steering.attempt = attempt;
693
+ if (steering.pending.size)
694
+ attempt.abort();
695
+ const settleSteeredAttempt = () => failAttempt(input, { request, stepId, status: 'requested' }, {
696
+ code: 'steered',
697
+ message: 'Superseded by user steering',
698
+ retryable: false,
699
+ outcomeUnknown: false,
700
+ }, observation.usage ? { usage: observation.usage } : undefined, attemptStartMs);
701
+ try {
702
+ attempt.signal.throwIfAborted();
703
+ const modelInfo = await d.gateway.describe(request.model);
704
+ attempt.signal.throwIfAborted();
705
+ modelContextWindow = modelInfo.capabilities.contextWindow;
706
+ const streaming = config.streamText && modelInfo.capabilities.streaming;
707
+ const now = d.clock.now();
708
+ const remainingMs = deadlineAt ? Date.parse(deadlineAt) - Date.parse(now) : Infinity;
709
+ if (deadlineAt && remainingMs <= 0)
710
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
711
+ const { limits } = config;
712
+ const idleMs = limits.streamIdleTimeoutMs ?? limits.modelTimeoutMs;
713
+ const totalMs = limits.requestTotalTimeoutMs ??
714
+ defaultModelTotalTimeoutMs(Math.max(idleMs, limits.modelTimeoutMs), request.responsesOptions.reasoning?.effort);
715
+ const invocation = {
716
+ signal: AbortSignal.any([signal, attempt.signal]),
717
+ timeoutMs: limits.modelTimeoutMs,
718
+ streamIdleTimeoutMs: idleMs,
719
+ requestTotalTimeoutMs: totalMs,
720
+ ...(deadlineAt ? { deadlineTimeoutMs: remainingMs } : {}),
721
+ };
722
+ d.liveAgents?.update(input, {
723
+ phase: 'thinking',
724
+ ...(stepCount !== undefined ? { stepCount } : {}),
725
+ requestStartedAt: now,
726
+ lastActivityAt: now,
727
+ resetReasoning: true,
728
+ requestId: request.id,
729
+ contextWindow: modelContextWindow,
730
+ retryAttempt: request.attempt > 1 ? request.attempt : undefined,
731
+ retryMaxAttempts: request.attempt > 1 ? config.retry.modelMaxAttemptsPerCall : undefined,
732
+ });
733
+ if (streaming) {
734
+ const streamed = await streamResponse(input, request, invocation, observation, modelContextWindow);
735
+ response = streamed.response;
736
+ firstTokenMs = streamed.firstTokenMs;
737
+ }
738
+ else {
739
+ response = await d.gateway.execute(request, invocation);
740
+ }
741
+ }
742
+ catch (error) {
743
+ if (attempt.signal.aborted && !signal.aborted) {
744
+ await settleSteeredAttempt();
745
+ return;
746
+ }
747
+ const failure = error?.error ??
748
+ {
749
+ code: 'protocol',
750
+ message: 'Model request failed',
751
+ retryable: false,
752
+ outcomeUnknown: true,
753
+ };
754
+ await failAttempt(input, { request, stepId, status: 'requested' }, failure, observation, attemptStartMs);
755
+ if (deadlineAt && failure.details?.timeoutKind === 'deadline')
756
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
757
+ return;
758
+ }
759
+ observation.usage = response.usage;
760
+ const finishedMs = performance.now();
761
+ const rateStartMs = firstTokenMs ?? attemptStartMs;
762
+ const rateElapsedSec = Math.max(0.05, (finishedMs - rateStartMs) / 1000);
763
+ const outputTokensPerSec = response.usage.outputTokens > 0
764
+ ? Number((response.usage.outputTokens / rateElapsedSec).toFixed(1))
765
+ : undefined;
766
+ d.liveAgents?.update(input, {
767
+ phase: 'idle',
768
+ requestStartedAt: undefined,
769
+ requestId: undefined,
770
+ retryAttempt: undefined,
771
+ retryMaxAttempts: undefined,
772
+ lastActivityAt: d.clock.now(),
773
+ ...(modelContextWindow !== undefined ? { contextWindow: modelContextWindow } : {}),
774
+ lastInputTokens: response.usage.inputTokens,
775
+ lastOutputTokens: response.usage.outputTokens,
776
+ lastCachedInputTokens: response.usage.cachedInputTokens ?? 0,
777
+ ...(outputTokensPerSec !== undefined ? { outputTokensPerSec } : {}),
778
+ });
779
+ if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling') {
780
+ await failAttempt(input, { request, stepId, status: 'requested' }, {
781
+ code: 'cancelled',
782
+ message: 'Response rejected after cancellation',
783
+ retryable: false,
784
+ outcomeUnknown: false,
785
+ }, observation, attemptStartMs);
786
+ return;
787
+ }
788
+ if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt)) {
789
+ await failAttempt(input, { request, stepId, status: 'requested' }, {
790
+ code: 'timeout',
791
+ message: 'Run or Turn deadline reached before committing model response',
792
+ retryable: false,
793
+ outcomeUnknown: false,
794
+ }, observation, attemptStartMs);
795
+ return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
796
+ }
797
+ const assistantId = d.id();
798
+ const definitions = (await d.registry.snapshot(config)).definitions;
799
+ if (attempt.signal.aborted && !signal.aborted) {
800
+ await settleSteeredAttempt();
801
+ return;
802
+ }
803
+ steering.attempt = undefined;
804
+ if (response.turnDisposition === 'final' || ['length', 'content_filter'].includes(response.finishReason))
805
+ steering.accepting = false;
806
+ const toolCalls = response.toolCalls.map((call, callIndex) => ({
807
+ id: d.id(),
808
+ assistantMessageId: assistantId,
809
+ providerCallId: call.providerCallId,
810
+ callIndex,
811
+ toolName: call.toolName,
812
+ toolVersion: definitions.find((definition) => definition.name === call.toolName &&
813
+ request.tools.some((tool) => tool.canonicalName === definition.name && tool.version === definition.version))?.version ?? 'unresolved',
814
+ arguments: call.arguments,
815
+ }));
816
+ const reasoningSummary = observation.reasoningSummary && !modelReasoningSummary(response).trim()
817
+ ? observation.reasoningSummary
818
+ : undefined;
819
+ try {
820
+ await d.journal.append(`request:${request.id}:response`, [
821
+ d.journal.event('model.responded', route, {
822
+ stepId,
823
+ response,
824
+ ...(reasoningSummary ? { reasoningSummary } : {}),
825
+ }, requestedEventId),
826
+ d.journal.event('message.assistant.added', route, {
827
+ requestId: request.id,
828
+ message: {
829
+ id: assistantId,
830
+ agentSessionId: input.agentSessionId,
831
+ runId: input.runId,
832
+ turnId: input.turnId,
833
+ role: 'assistant',
834
+ content: response.content,
835
+ toolCalls,
836
+ ...(response.structuredOutput === undefined
837
+ ? {}
838
+ : { structuredOutput: response.structuredOutput }),
839
+ },
840
+ }),
841
+ ...toolCalls.map((call) => d.journal.event('tool.call.requested', route, {
842
+ turnId: input.turnId,
843
+ call,
844
+ executionKey: `saturn:${input.workspaceId}:${call.id}`,
845
+ policyVersion: config.policyVersion,
846
+ definition: call.toolVersion === 'unresolved'
847
+ ? null
848
+ : definitions.find((definition) => definition.name === call.toolName && definition.version === call.toolVersion),
849
+ })),
850
+ d.journal.event('step.completed', route, { stepId }),
851
+ ]);
852
+ }
853
+ catch (error) {
854
+ if ((await d.state.run(input.runId)).status === 'cancelling') {
855
+ await failAttempt(input, { request, stepId, status: 'requested' }, {
856
+ code: 'cancelled',
857
+ message: 'Response rejected after cancellation',
858
+ retryable: false,
859
+ outcomeUnknown: false,
860
+ }, observation, attemptStartMs);
861
+ return;
862
+ }
863
+ throw error;
864
+ }
865
+ }
866
+ async function streamResponse(input, request, invocation, observation, contextWindow) {
867
+ let firstTokenMs;
868
+ let streamedChars = 0;
869
+ const estimateRate = () => {
870
+ if (firstTokenMs === undefined || streamedChars <= 0)
871
+ return undefined;
872
+ const elapsedSec = (performance.now() - firstTokenMs) / 1000;
873
+ if (elapsedSec < 0.05)
874
+ return undefined;
875
+ return Number((Math.max(1, streamedChars / 4) / elapsedSec).toFixed(1));
876
+ };
877
+ for await (const part of d.gateway.stream(request, invocation)) {
878
+ switch (part.type) {
879
+ case 'text_delta': {
880
+ if (part.text.length > 0) {
881
+ if (firstTokenMs === undefined)
882
+ firstTokenMs = performance.now();
883
+ streamedChars += part.text.length;
884
+ }
885
+ d.liveText?.append(input, part);
886
+ const rate = estimateRate();
887
+ d.liveAgents?.update(input, {
888
+ phase: 'streaming',
889
+ lastActivityAt: d.clock.now(),
890
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
891
+ ...(rate !== undefined ? { outputTokensPerSec: rate } : {}),
892
+ });
893
+ break;
894
+ }
895
+ case 'reasoning_summary_delta': {
896
+ observation.reasoningSummary = ((observation.reasoningSummary ?? '') + part.text).slice(0, maxModelReasoningSummaryLength);
897
+ if (part.text.length > 0) {
898
+ if (firstTokenMs === undefined)
899
+ firstTokenMs = performance.now();
900
+ streamedChars += part.text.length;
901
+ }
902
+ const rate = estimateRate();
903
+ d.liveAgents?.update(input, {
904
+ reasoningDelta: part.text,
905
+ lastActivityAt: d.clock.now(),
906
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
907
+ ...(rate !== undefined ? { outputTokensPerSec: rate } : {}),
908
+ });
909
+ break;
910
+ }
911
+ case 'tool_delta': {
912
+ if (part.fragment.length > 0) {
913
+ if (firstTokenMs === undefined)
914
+ firstTokenMs = performance.now();
915
+ streamedChars += part.fragment.length;
916
+ }
917
+ const rate = estimateRate();
918
+ d.liveAgents?.update(input, {
919
+ lastActivityAt: d.clock.now(),
920
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
921
+ ...(rate !== undefined ? { outputTokensPerSec: rate } : {}),
922
+ });
923
+ break;
924
+ }
925
+ case 'activity':
926
+ d.liveAgents?.update(input, { lastActivityAt: d.clock.now() });
927
+ break;
928
+ case 'usage':
929
+ observation.usage = part.usage;
930
+ break;
931
+ case 'finished':
932
+ return { response: part.response, ...(firstTokenMs !== undefined ? { firstTokenMs } : {}) };
933
+ case 'failed':
934
+ throw Object.assign(new Error(part.error.message), { error: part.error });
935
+ }
936
+ }
937
+ throw new RuntimeError('MODEL_STREAM_INCOMPLETE', 'Model stream ended without a final response');
938
+ }
939
+ async function failAttempt(input, attempt, error, observation, startedAt) {
940
+ const { route, config } = await d.environment.load(input.runId, input.agentSessionId);
941
+ const { usage: errorUsage, ...failure } = error;
942
+ const usage = errorUsage ?? observation?.usage;
943
+ let retryAt;
944
+ if (error.retryable && attempt.request.attempt < config.retry.modelMaxAttemptsPerCall) {
945
+ const delay = modelRetryDelayMs(config.retry, attempt.request.attempt, error.retryAfterMs, d.random);
946
+ const retryTime = Date.parse(d.clock.now()) + delay;
947
+ retryAt = new Date(Math.min(8.64e15, retryTime)).toISOString();
948
+ }
949
+ const settlement = await d.journal.append(`recover:${attempt.request.id}:model-failed`, [
950
+ d.journal.event('model.failed', route, {
951
+ stepId: attempt.stepId,
952
+ requestId: attempt.request.id,
953
+ error: failure,
954
+ ...(usage?.accuracy === 'reported' ? { chargedUsage: usage } : {}),
955
+ ...(observation?.reasoningSummary ? { reasoningSummary: observation.reasoningSummary } : {}),
956
+ ...(retryAt ? { retryAt } : {}),
957
+ }),
958
+ d.journal.event('step.failed', route, {
959
+ stepId: attempt.stepId,
960
+ error: { code: error.code, message: error.message, retryable: error.retryable },
961
+ }),
962
+ ]);
963
+ d.liveAgents?.update(input, { phase: 'idle', requestId: undefined, requestStartedAt: undefined });
964
+ const details = failure.details;
965
+ if (error.code === 'steered')
966
+ return;
967
+ d.logger.error({
968
+ runId: input.runId,
969
+ turnId: input.turnId,
970
+ requestId: attempt.request.id,
971
+ diagnosticId: settlement.events[0].id,
972
+ attempt: attempt.request.attempt,
973
+ code: error.code,
974
+ retryable: error.retryable,
975
+ ...(retryAt ? { retryAt } : {}),
976
+ ...(details
977
+ ? {
978
+ ...details,
979
+ ...(details.causes ? { causes: details.causes.map((cause) => ({ ...cause })) } : {}),
980
+ }
981
+ : startedAt === undefined
982
+ ? {}
983
+ : { elapsedMs: Math.round(performance.now() - startedAt) }),
984
+ }, 'Model attempt failed');
985
+ }
986
+ async function cleanup(input, reason) {
987
+ const pending = await d.state.pendingTools(input.turnId);
988
+ const assistants = [...new Set(pending.map((call) => call.call.assistantMessageId))];
989
+ const signal = reason === 'cancelled' ? AbortSignal.abort() : new AbortController().signal;
990
+ for (const assistantMessageId of assistants) {
991
+ await d.executor.executeBatch({ ...input, assistantMessageId, signal }, reason === 'cancelled' ? undefined : reason);
992
+ }
993
+ }
994
+ async function interrupt(input, reason, budget) {
995
+ await cleanup(input, reason);
996
+ const state = await d.state.run(input.runId);
997
+ const { route } = await d.environment.load(input.runId, input.agentSessionId);
998
+ const attempts = await d.state.modelAttempts(input.turnId);
999
+ for (const attempt of attempts.filter((attempt) => attempt.status === 'requested'))
1000
+ await failAttempt(input, attempt, {
1001
+ code: reason === 'timeout' ? 'timeout' : 'cancelled',
1002
+ message: 'Model attempt interrupted',
1003
+ retryable: false,
1004
+ outcomeUnknown: true,
1005
+ });
1006
+ const current = await d.state.run(input.runId);
1007
+ const result = {
1008
+ status: 'interrupted',
1009
+ turnId: input.turnId,
1010
+ reason,
1011
+ unresolvedCallIds: state.unresolvedCallIds,
1012
+ usage: current.chargedUsage,
1013
+ ...(budget ? { budget } : {}),
1014
+ };
1015
+ await d.journal.append(`turn:${input.turnId}:interrupted`, [
1016
+ d.journal.event('turn.interrupted', route, {
1017
+ turnId: input.turnId,
1018
+ reason,
1019
+ usage: current.chargedUsage,
1020
+ unresolvedCallIds: state.unresolvedCallIds,
1021
+ ...(budget ? { budget } : {}),
1022
+ }),
1023
+ ]);
1024
+ return result;
1025
+ }
1026
+ async function failTurn(input, error) {
1027
+ await cleanup(input, 'cancelled');
1028
+ const { route } = await d.environment.load(input.runId, input.agentSessionId);
1029
+ const { chargedUsage: usage } = await d.state.run(input.runId);
1030
+ const events = [
1031
+ d.journal.event('turn.failed', route, { turnId: input.turnId, error, usage }),
1032
+ ];
1033
+ await d.journal.append(`turn:${input.turnId}:failed`, events);
1034
+ return { status: 'failed', turnId: input.turnId, error, usage };
1035
+ }
1036
+ return {
1037
+ execute,
1038
+ resume: execute,
1039
+ async steer(agentSessionId, commandId, command) {
1040
+ if (await d.journal.receipt(`steer:${commandId}`, command))
1041
+ return;
1042
+ const turn = steering.get(agentSessionId);
1043
+ if (!turn?.accepting || turn.input.runId !== command.runId)
1044
+ throw new RuntimeError('STEER_UNAVAILABLE', 'The target agent has no active turn accepting steering');
1045
+ const pending = turn.pending.get(commandId);
1046
+ if (pending && pending.content !== command.content)
1047
+ throw new RuntimeError('COMMAND_CONFLICT', 'Steering command ID is already in use');
1048
+ turn.pending.set(commandId, command);
1049
+ turn.attempt?.abort();
1050
+ },
1051
+ clearSteering(runId) {
1052
+ for (const [agentSessionId, turn] of steering) {
1053
+ if (turn.input.runId === runId)
1054
+ steering.delete(agentSessionId);
1055
+ }
1056
+ },
1057
+ };
1058
+ function elapsedBudget(maxWallTimeMs, deadlineAt, pendingDelay = 0) {
1059
+ const max = maxWallTimeMs ?? DEFAULT_SUBAGENT_WALL_TIME_MS;
1060
+ const used = Math.max(0, max + Date.parse(d.clock.now()) - Date.parse(deadlineAt));
1061
+ return { resource: 'timeMs', used, max, ...(pendingDelay ? { required: used + pendingDelay } : {}) };
1062
+ }
1063
+ async function waitForBudget(signal) {
1064
+ try {
1065
+ await d.clock.delay(20, signal);
1066
+ }
1067
+ catch (error) {
1068
+ if (!signal.aborted)
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ }