@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.
- 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
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
import { canonicalJson, COMPACTION_SUMMARY_MARKER, DEFAULT_COMPACTION_HEADROOM_RATIO, DEFAULT_COMPACTION_MAX_HEADROOM_TOKENS, DEFAULT_COMPACTION_THRESHOLD_RATIO, DEFAULT_PRUNER_MIN_RECENT_STEPS, DEFAULT_PRUNER_TAIL_WINDOW_RATIO, DEFAULT_SUMMARY_MAX_HALVINGS, DEFAULT_SUMMARY_PREFLIGHT_WINDOW_RATIO, estimateTextTokens, modelConfiguration, pruneTextMiddle, pruneToolOutcome, RuntimeError, selectSafeCompactionPrefix, streamForScope, } from '@saturn-universe/core';
|
|
2
|
+
const COMPACTION_SYSTEM_PROMPT = [
|
|
3
|
+
'You are compacting earlier conversation history for an autonomous engineering agent.',
|
|
4
|
+
'Produce a concise, factual state handoff summary that preserves:',
|
|
5
|
+
'1. Original user objective and constraints.',
|
|
6
|
+
'2. Concrete verified findings, file paths, symbol names, commands, and errors.',
|
|
7
|
+
'3. Completed edits/actions and current state.',
|
|
8
|
+
'4. Pending next steps and open questions.',
|
|
9
|
+
'Rules: Be strictly concise and shorter than the source transcript. Omit verbose raw tool outputs and redundant prose. Output plain markdown only.',
|
|
10
|
+
].join('\n');
|
|
11
|
+
async function compactionBoundary(state, active, prefix) {
|
|
12
|
+
const { turnId } = prefix.at(-1).message;
|
|
13
|
+
const { status } = await state.turn(turnId);
|
|
14
|
+
const replacedIds = new Set(prefix.map(({ message }) => message.id));
|
|
15
|
+
const splitsTurn = active.some(({ message }) => message.turnId === turnId && !replacedIds.has(message.id));
|
|
16
|
+
return splitsTurn || ['queued', 'running', 'paused'].includes(status) ? 'step_prefix' : 'turn';
|
|
17
|
+
}
|
|
18
|
+
function prepareCompaction({ hash, id: nextId }, { id, route, expectedSurfaceSeq, prefix, summary, summaryModelRef, boundary, }) {
|
|
19
|
+
const { kind, workspaceId, sessionId, agentSessionId, agentId } = route;
|
|
20
|
+
const messages = prefix.map(({ message }) => message);
|
|
21
|
+
const { runId, turnId } = messages.at(-1);
|
|
22
|
+
return {
|
|
23
|
+
scope: { kind, workspaceId, sessionId, agentSessionId, agentId },
|
|
24
|
+
compaction: {
|
|
25
|
+
id,
|
|
26
|
+
expectedSurfaceSeq,
|
|
27
|
+
replacedMessageIds: messages.map(({ id }) => id),
|
|
28
|
+
sourceDigest: hash(messages),
|
|
29
|
+
...(summaryModelRef ? { summaryModelRef } : {}),
|
|
30
|
+
...(boundary ? { boundary } : {}),
|
|
31
|
+
replacement: {
|
|
32
|
+
id: nextId(),
|
|
33
|
+
role: 'user',
|
|
34
|
+
agentSessionId,
|
|
35
|
+
runId,
|
|
36
|
+
turnId,
|
|
37
|
+
content: [{ type: 'text', text: COMPACTION_SUMMARY_MARKER + '\n' + summary }],
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function committedCompaction(receipt) {
|
|
43
|
+
const event = receipt.events.find((item) => item.type === 'surface.compacted');
|
|
44
|
+
if (!event)
|
|
45
|
+
throw new Error('Compaction receipt is missing its committed event');
|
|
46
|
+
return event.payload.compaction;
|
|
47
|
+
}
|
|
48
|
+
const DEFAULT_SUMMARY_TIMEOUT_MS = 90_000;
|
|
49
|
+
export function resolveAutoCompactionOptions(options) {
|
|
50
|
+
const cfg = typeof options === 'object' ? options : {};
|
|
51
|
+
return {
|
|
52
|
+
enabled: options !== false && cfg.enabled !== false,
|
|
53
|
+
thresholdRatio: cfg.thresholdRatio ?? DEFAULT_COMPACTION_THRESHOLD_RATIO,
|
|
54
|
+
maxHeadroomTokens: cfg.maxHeadroomTokens ?? DEFAULT_COMPACTION_MAX_HEADROOM_TOKENS,
|
|
55
|
+
headroomRatio: cfg.headroomRatio ?? DEFAULT_COMPACTION_HEADROOM_RATIO,
|
|
56
|
+
minRecentSteps: cfg.minRecentSteps ?? DEFAULT_PRUNER_MIN_RECENT_STEPS,
|
|
57
|
+
tailWindowRatio: cfg.tailWindowRatio ?? DEFAULT_PRUNER_TAIL_WINDOW_RATIO,
|
|
58
|
+
preflightWindowRatio: cfg.preflightWindowRatio ?? DEFAULT_SUMMARY_PREFLIGHT_WINDOW_RATIO,
|
|
59
|
+
maxHalvings: cfg.maxHalvings ?? DEFAULT_SUMMARY_MAX_HALVINGS,
|
|
60
|
+
minPrefixChars: cfg.minPrefixChars ?? 256,
|
|
61
|
+
summaryTimeoutMs: cfg.summaryTimeoutMs ?? DEFAULT_SUMMARY_TIMEOUT_MS,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function serializeItemsForSummary(items, maxToolChars = 4096) {
|
|
65
|
+
const lines = [];
|
|
66
|
+
for (const { message } of items) {
|
|
67
|
+
if (message.role === 'user') {
|
|
68
|
+
const text = message.content
|
|
69
|
+
.map((part) => (part.type === 'text' ? part.text : `[${part.type}]`))
|
|
70
|
+
.join('\n')
|
|
71
|
+
.trim();
|
|
72
|
+
if (text)
|
|
73
|
+
lines.push(`[user]\n${text}`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (message.role === 'assistant') {
|
|
77
|
+
const text = message.content
|
|
78
|
+
.map((part) => (part.type === 'text' ? part.text : `[${part.type}]`))
|
|
79
|
+
.join('\n')
|
|
80
|
+
.trim();
|
|
81
|
+
const calls = message.toolCalls.map((call) => {
|
|
82
|
+
const rawArgs = call.arguments.kind === 'json' ? canonicalJson(call.arguments.value) : call.arguments.raw;
|
|
83
|
+
const clippedArgs = pruneTextMiddle(rawArgs, 512, 256, 128).text;
|
|
84
|
+
return `${call.toolName}(${clippedArgs})`;
|
|
85
|
+
});
|
|
86
|
+
const body = [text, calls.length ? `tool_calls: ${calls.join('; ')}` : ''].filter(Boolean).join('\n');
|
|
87
|
+
if (body)
|
|
88
|
+
lines.push(`[assistant]\n${body}`);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const pruned = pruneToolOutcome(message.result.outcome, {
|
|
92
|
+
maxToolResultChars: maxToolChars,
|
|
93
|
+
headChars: Math.floor(maxToolChars * 0.5),
|
|
94
|
+
tailChars: Math.floor(maxToolChars * 0.25),
|
|
95
|
+
}).outcome;
|
|
96
|
+
const outcomeText = pruned.status === 'success'
|
|
97
|
+
? pruned.content.map((part) => (part.type === 'text' ? part.text : `[${part.type}]`)).join('\n')
|
|
98
|
+
: `${pruned.status}:${pruned.error.code} ${pruned.error.message}`;
|
|
99
|
+
lines.push(`[tool:${message.result.toolCallId} (${pruned.status})]\n${outcomeText}`);
|
|
100
|
+
}
|
|
101
|
+
return lines.join('\n\n');
|
|
102
|
+
}
|
|
103
|
+
export function preparePreflightSummaryPlan(units, summaryContextWindow, options) {
|
|
104
|
+
if (!units.length || !Number.isFinite(summaryContextWindow) || summaryContextWindow < 256)
|
|
105
|
+
return undefined;
|
|
106
|
+
const ratio = options?.preflightWindowRatio ?? DEFAULT_SUMMARY_PREFLIGHT_WINDOW_RATIO;
|
|
107
|
+
const maxHalvings = Math.max(0, options?.maxHalvings ?? DEFAULT_SUMMARY_MAX_HALVINGS);
|
|
108
|
+
const safeBudgetTokens = Math.max(128, Math.floor(summaryContextWindow * ratio));
|
|
109
|
+
let candidateUnits = [...units];
|
|
110
|
+
let halvings = 0;
|
|
111
|
+
for (;;) {
|
|
112
|
+
const items = candidateUnits.flatMap((unit) => unit.items);
|
|
113
|
+
const transcript = serializeItemsForSummary(items);
|
|
114
|
+
const estimatedTokens = estimateTextTokens(COMPACTION_SYSTEM_PROMPT.length + transcript.length + 128);
|
|
115
|
+
const rawPrefixChars = candidateUnits.reduce((sum, unit) => sum + unit.estimatedChars, 0);
|
|
116
|
+
if (estimatedTokens <= safeBudgetTokens) {
|
|
117
|
+
return { units: candidateUnits, items, transcript, rawPrefixChars, estimatedTokens, halvings };
|
|
118
|
+
}
|
|
119
|
+
if (halvings >= maxHalvings || candidateUnits.length <= 1) {
|
|
120
|
+
// Final safety clamp: proportionally prune transcript text so pre-flight window is strictly respected.
|
|
121
|
+
const maxTranscriptChars = Math.max(256, Math.floor(safeBudgetTokens * 3.2) - COMPACTION_SYSTEM_PROMPT.length - 128);
|
|
122
|
+
if (maxTranscriptChars < 256)
|
|
123
|
+
return undefined;
|
|
124
|
+
const clamped = pruneTextMiddle(transcript, maxTranscriptChars, Math.floor(maxTranscriptChars * 0.55), Math.floor(maxTranscriptChars * 0.3)).text;
|
|
125
|
+
const clampedTokens = estimateTextTokens(COMPACTION_SYSTEM_PROMPT.length + clamped.length + 128);
|
|
126
|
+
if (clampedTokens > safeBudgetTokens)
|
|
127
|
+
return undefined;
|
|
128
|
+
return {
|
|
129
|
+
units: candidateUnits,
|
|
130
|
+
items,
|
|
131
|
+
transcript: clamped,
|
|
132
|
+
rawPrefixChars,
|
|
133
|
+
estimatedTokens: clampedTokens,
|
|
134
|
+
halvings,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
halvings += 1;
|
|
138
|
+
candidateUnits = candidateUnits.slice(0, Math.max(1, Math.floor(candidateUnits.length / 2)));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export async function generateCompactionSummary(deps, input) {
|
|
142
|
+
if (typeof deps.gateway.generate !== 'function') {
|
|
143
|
+
return { ok: false, reason: 'gateway_generate_unavailable' };
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
const { binding, capabilities } = await deps.gateway.describe(input.config.model);
|
|
147
|
+
const plan = preparePreflightSummaryPlan(input.units, capabilities.contextWindow, input.options);
|
|
148
|
+
if (!plan)
|
|
149
|
+
return { ok: false, reason: 'preflight_window_insufficient' };
|
|
150
|
+
const placement = capabilities.responses.instructionPlacement;
|
|
151
|
+
const userPrompt = [
|
|
152
|
+
'Summarize the following earlier conversation prefix for continued execution:',
|
|
153
|
+
'',
|
|
154
|
+
plan.transcript,
|
|
155
|
+
].join('\n');
|
|
156
|
+
const fullInput = [
|
|
157
|
+
...(placement !== 'instructions'
|
|
158
|
+
? [
|
|
159
|
+
{
|
|
160
|
+
type: 'message',
|
|
161
|
+
role: (placement === 'developer_item' ? 'developer' : 'system'),
|
|
162
|
+
content: [{ type: 'input_text', text: COMPACTION_SYSTEM_PROMPT }],
|
|
163
|
+
},
|
|
164
|
+
]
|
|
165
|
+
: []),
|
|
166
|
+
{
|
|
167
|
+
type: 'message',
|
|
168
|
+
role: 'user',
|
|
169
|
+
content: [{ type: 'input_text', text: userPrompt }],
|
|
170
|
+
},
|
|
171
|
+
];
|
|
172
|
+
const reasoning = capabilities.responses.reasoningModel && capabilities.responses.reasoningEfforts.includes('low')
|
|
173
|
+
? { effort: 'low' }
|
|
174
|
+
: undefined;
|
|
175
|
+
const requestId = deps.id();
|
|
176
|
+
const summarySessionId = `compaction-${input.runId}`;
|
|
177
|
+
const configurationDigest = deps.hash(modelConfiguration({
|
|
178
|
+
binding,
|
|
179
|
+
instructions: COMPACTION_SYSTEM_PROMPT,
|
|
180
|
+
placement,
|
|
181
|
+
tools: [],
|
|
182
|
+
output: { kind: 'text' },
|
|
183
|
+
reasoning,
|
|
184
|
+
}));
|
|
185
|
+
const fullInputDigest = deps.hash(fullInput);
|
|
186
|
+
const maxOutputTokens = Math.min(2048, capabilities.maxOutputTokens);
|
|
187
|
+
const request = {
|
|
188
|
+
id: requestId,
|
|
189
|
+
callGroupId: requestId,
|
|
190
|
+
attempt: 1,
|
|
191
|
+
agentSessionId: summarySessionId,
|
|
192
|
+
runId: input.runId,
|
|
193
|
+
turnId: input.turnId,
|
|
194
|
+
model: input.config.model,
|
|
195
|
+
binding,
|
|
196
|
+
messages: [
|
|
197
|
+
{ role: 'system', content: COMPACTION_SYSTEM_PROMPT },
|
|
198
|
+
{
|
|
199
|
+
role: 'user',
|
|
200
|
+
content: [{ type: 'text', text: userPrompt }],
|
|
201
|
+
sourceBackgroundId: 'compaction-input',
|
|
202
|
+
},
|
|
203
|
+
],
|
|
204
|
+
responses: {
|
|
205
|
+
version: 1,
|
|
206
|
+
binding,
|
|
207
|
+
epochId: deps.hash({ summarySessionId, turnId: input.turnId, configurationDigest, fullInputDigest }),
|
|
208
|
+
decision: { kind: 'new' },
|
|
209
|
+
...(placement === 'instructions' ? { instructions: COMPACTION_SYSTEM_PROMPT } : {}),
|
|
210
|
+
fullInput,
|
|
211
|
+
fullInputDigest,
|
|
212
|
+
configurationDigest,
|
|
213
|
+
replaySources: [],
|
|
214
|
+
transport: { kind: 'local_replay' },
|
|
215
|
+
},
|
|
216
|
+
responsesOptions: {
|
|
217
|
+
storage: 'local_stateless',
|
|
218
|
+
...(reasoning ? { reasoning } : {}),
|
|
219
|
+
},
|
|
220
|
+
tools: [],
|
|
221
|
+
output: { kind: 'text' },
|
|
222
|
+
maxOutputTokens,
|
|
223
|
+
budget: {
|
|
224
|
+
estimatedInputTokens: plan.estimatedTokens,
|
|
225
|
+
reservedTotalTokens: plan.estimatedTokens + maxOutputTokens,
|
|
226
|
+
accuracy: 'conservative_estimate',
|
|
227
|
+
},
|
|
228
|
+
context: {
|
|
229
|
+
surfaceSeq: 0,
|
|
230
|
+
selectedMessageIds: [],
|
|
231
|
+
assemblyHash: fullInputDigest,
|
|
232
|
+
providerVersions: {},
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
const timeoutMs = Math.min(input.options?.summaryTimeoutMs ?? DEFAULT_SUMMARY_TIMEOUT_MS, input.config.limits.modelTimeoutMs);
|
|
236
|
+
const response = await deps.gateway.generate(request, {
|
|
237
|
+
signal: input.signal,
|
|
238
|
+
timeoutMs: Math.max(1000, timeoutMs),
|
|
239
|
+
});
|
|
240
|
+
const summary = response.content
|
|
241
|
+
.flatMap((part) => (part.type === 'text' ? [part.text] : []))
|
|
242
|
+
.join('\n')
|
|
243
|
+
.trim();
|
|
244
|
+
if (!summary) {
|
|
245
|
+
deps.logger?.info({ runId: input.runId, turnId: input.turnId }, 'Compaction summary was empty; skipped');
|
|
246
|
+
return { ok: false, reason: 'empty_summary' };
|
|
247
|
+
}
|
|
248
|
+
if (summary.length >= plan.rawPrefixChars) {
|
|
249
|
+
deps.logger?.info({
|
|
250
|
+
runId: input.runId,
|
|
251
|
+
turnId: input.turnId,
|
|
252
|
+
summaryChars: summary.length,
|
|
253
|
+
rawPrefixChars: plan.rawPrefixChars,
|
|
254
|
+
}, 'Compaction summary was not shorter than source prefix; degrading safely');
|
|
255
|
+
return { ok: false, reason: 'summary_not_shorter' };
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
ok: true,
|
|
259
|
+
summary,
|
|
260
|
+
plan,
|
|
261
|
+
modelRef: `${input.config.model.providerId}/${input.config.model.modelId}`,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
deps.logger?.error({
|
|
266
|
+
code: error instanceof RuntimeError ? error.code : 'COMPACTION_SUMMARY_FAILED',
|
|
267
|
+
runId: input.runId,
|
|
268
|
+
turnId: input.turnId,
|
|
269
|
+
message: error instanceof Error ? error.message : String(error),
|
|
270
|
+
}, 'Auto-compaction summary call failed; degrading safely');
|
|
271
|
+
return { ok: false, reason: 'summary_call_failed' };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
export async function autoCompactSurface(deps, input) {
|
|
275
|
+
const opts = resolveAutoCompactionOptions(input.options);
|
|
276
|
+
if (!opts.enabled)
|
|
277
|
+
return { compacted: false, reason: 'disabled' };
|
|
278
|
+
const surface = await deps.surface.read(input.route.agentSessionId);
|
|
279
|
+
const selected = selectSafeCompactionPrefix(surface, {
|
|
280
|
+
contextWindow: input.contextWindow,
|
|
281
|
+
minRecentSteps: opts.minRecentSteps,
|
|
282
|
+
tailWindowRatio: opts.tailWindowRatio,
|
|
283
|
+
minPrefixChars: opts.minPrefixChars,
|
|
284
|
+
});
|
|
285
|
+
if (!selected)
|
|
286
|
+
return { compacted: false, reason: 'no_safe_prefix' };
|
|
287
|
+
const generated = await generateCompactionSummary(deps, {
|
|
288
|
+
runId: input.route.runId,
|
|
289
|
+
turnId: input.turnId,
|
|
290
|
+
config: input.config,
|
|
291
|
+
units: selected.units,
|
|
292
|
+
signal: input.signal,
|
|
293
|
+
options: opts,
|
|
294
|
+
});
|
|
295
|
+
if (!generated.ok)
|
|
296
|
+
return { compacted: false, reason: generated.reason };
|
|
297
|
+
const prefix = generated.plan.items;
|
|
298
|
+
const active = surface.items.filter((item) => item.active);
|
|
299
|
+
const boundary = await compactionBoundary(deps.state, active, prefix);
|
|
300
|
+
const compactionKey = `auto-compact:${input.route.agentSessionId}:${surface.lastStreamSeq}`;
|
|
301
|
+
try {
|
|
302
|
+
const { scope, compaction } = prepareCompaction(deps, {
|
|
303
|
+
id: deps.id(),
|
|
304
|
+
route: input.route,
|
|
305
|
+
expectedSurfaceSeq: surface.lastStreamSeq,
|
|
306
|
+
prefix,
|
|
307
|
+
summary: generated.summary,
|
|
308
|
+
summaryModelRef: generated.modelRef,
|
|
309
|
+
boundary,
|
|
310
|
+
});
|
|
311
|
+
const receipt = await deps.journal.append(compactionKey, [deps.journal.event('surface.compacted', scope, { compaction })], undefined, {
|
|
312
|
+
type: 'surface.auto_compact',
|
|
313
|
+
agentSessionId: input.route.agentSessionId,
|
|
314
|
+
expectedSurfaceSeq: surface.lastStreamSeq,
|
|
315
|
+
replacedMessageIds: compaction.replacedMessageIds,
|
|
316
|
+
});
|
|
317
|
+
const committed = committedCompaction(receipt);
|
|
318
|
+
return {
|
|
319
|
+
compacted: true,
|
|
320
|
+
compactionId: committed.id,
|
|
321
|
+
replacedCount: committed.replacedMessageIds.length,
|
|
322
|
+
halvings: generated.plan.halvings,
|
|
323
|
+
boundary: committed.boundary ?? 'turn',
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
deps.logger?.error({
|
|
328
|
+
code: error instanceof RuntimeError ? error.code : 'COMPACTION_COMMIT_FAILED',
|
|
329
|
+
runId: input.route.runId,
|
|
330
|
+
turnId: input.turnId,
|
|
331
|
+
message: error instanceof Error ? error.message : String(error),
|
|
332
|
+
}, 'Auto-compaction commit failed; degrading safely');
|
|
333
|
+
return { compacted: false, reason: 'commit_failed' };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
export async function compactSurface(d, commandId, command) {
|
|
337
|
+
const commandHash = d.hash(command);
|
|
338
|
+
let receipt = await d.receipt(commandId, commandHash);
|
|
339
|
+
if (!receipt) {
|
|
340
|
+
const { route, config } = await d.environment.load(command.runId);
|
|
341
|
+
const surface = await d.surfaceReader.read(route.agentSessionId);
|
|
342
|
+
const active = surface.items.filter((item) => item.active);
|
|
343
|
+
let prefix;
|
|
344
|
+
let summaryText;
|
|
345
|
+
let boundary;
|
|
346
|
+
let summaryModelRef;
|
|
347
|
+
if (command.throughTurnId && command.summary) {
|
|
348
|
+
const lastIndex = active.map((item) => item.message.turnId).lastIndexOf(command.throughTurnId);
|
|
349
|
+
if (lastIndex < 0)
|
|
350
|
+
throw new RuntimeError('INVALID_COMMAND', 'Turn is absent from the effective Surface');
|
|
351
|
+
prefix = active.slice(0, lastIndex + 1);
|
|
352
|
+
const { turnId } = prefix.at(-1).message;
|
|
353
|
+
const { status } = await d.stateReader.turn(turnId);
|
|
354
|
+
if (!['completed', 'failed', 'interrupted'].includes(status))
|
|
355
|
+
throw new RuntimeError('RUN_BLOCKED', 'Compaction must cover ended Turns only');
|
|
356
|
+
if (prefix.length === 1 && surface.items.some((item) => item.supersededBy === prefix[0].sourceEventId))
|
|
357
|
+
throw new RuntimeError('INVALID_COMMAND', 'Prefix has already been compacted');
|
|
358
|
+
summaryText = command.summary;
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
if (!d.gateway) {
|
|
362
|
+
throw new RuntimeError('INVALID_COMMAND', 'Auto compaction requires a model gateway or explicit throughTurnId and summary');
|
|
363
|
+
}
|
|
364
|
+
const { capabilities } = await d.gateway.describe(config.model);
|
|
365
|
+
const selected = selectSafeCompactionPrefix(surface, {
|
|
366
|
+
contextWindow: capabilities.contextWindow,
|
|
367
|
+
minRecentSteps: command.throughTurnId ? 0 : DEFAULT_PRUNER_MIN_RECENT_STEPS,
|
|
368
|
+
tailWindowRatio: command.throughTurnId ? 0 : DEFAULT_PRUNER_TAIL_WINDOW_RATIO,
|
|
369
|
+
minPrefixChars: 64,
|
|
370
|
+
});
|
|
371
|
+
if (!selected) {
|
|
372
|
+
throw new RuntimeError('INVALID_COMMAND', 'Nothing eligible to compact on the current Surface');
|
|
373
|
+
}
|
|
374
|
+
let targetUnits = selected.units;
|
|
375
|
+
if (command.throughTurnId) {
|
|
376
|
+
const lastUnitIdx = targetUnits.map((unit) => unit.turnId).lastIndexOf(command.throughTurnId);
|
|
377
|
+
if (lastUnitIdx < 0) {
|
|
378
|
+
throw new RuntimeError('INVALID_COMMAND', 'Turn is absent from the compactable Surface prefix');
|
|
379
|
+
}
|
|
380
|
+
targetUnits = targetUnits.slice(0, lastUnitIdx + 1);
|
|
381
|
+
}
|
|
382
|
+
const targetTurnId = targetUnits.at(-1).turnId;
|
|
383
|
+
if (command.summary) {
|
|
384
|
+
prefix = targetUnits.flatMap((unit) => unit.items);
|
|
385
|
+
summaryText = command.summary;
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
const controller = new AbortController();
|
|
389
|
+
const generated = await generateCompactionSummary({ gateway: d.gateway, hash: d.hash, id: d.id, ...(d.logger ? { logger: d.logger } : {}) }, {
|
|
390
|
+
runId: command.runId,
|
|
391
|
+
turnId: targetTurnId,
|
|
392
|
+
config,
|
|
393
|
+
units: targetUnits,
|
|
394
|
+
signal: controller.signal,
|
|
395
|
+
});
|
|
396
|
+
if (!generated.ok) {
|
|
397
|
+
throw new RuntimeError('COMPACTION_FAILED', `Automatic compaction skipped: ${generated.reason}`);
|
|
398
|
+
}
|
|
399
|
+
prefix = generated.plan.items;
|
|
400
|
+
summaryText = generated.summary;
|
|
401
|
+
summaryModelRef = generated.modelRef;
|
|
402
|
+
}
|
|
403
|
+
if ((await compactionBoundary(d.stateReader, active, prefix)) === 'step_prefix') {
|
|
404
|
+
boundary = 'step_prefix';
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const id = d.id();
|
|
408
|
+
const { scope, compaction } = prepareCompaction(d, {
|
|
409
|
+
id,
|
|
410
|
+
route,
|
|
411
|
+
expectedSurfaceSeq: surface.lastStreamSeq,
|
|
412
|
+
prefix,
|
|
413
|
+
summary: summaryText,
|
|
414
|
+
summaryModelRef,
|
|
415
|
+
boundary,
|
|
416
|
+
});
|
|
417
|
+
receipt = await d.commit.commit({
|
|
418
|
+
commandId,
|
|
419
|
+
commandHash,
|
|
420
|
+
correlationId: commandId,
|
|
421
|
+
actor: { kind: 'user', id: 'local' },
|
|
422
|
+
hostEpoch: d.epoch,
|
|
423
|
+
expected: [{ stream: streamForScope(scope), lastSeq: surface.lastStreamSeq }],
|
|
424
|
+
events: [
|
|
425
|
+
{
|
|
426
|
+
id,
|
|
427
|
+
type: 'surface.compacted',
|
|
428
|
+
eventVersion: 1,
|
|
429
|
+
scope,
|
|
430
|
+
occurredAt: d.now(),
|
|
431
|
+
causationId: null,
|
|
432
|
+
payload: { compaction },
|
|
433
|
+
},
|
|
434
|
+
],
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
const compaction = committedCompaction(receipt);
|
|
438
|
+
return {
|
|
439
|
+
runId: command.runId,
|
|
440
|
+
compactionId: compaction.id,
|
|
441
|
+
replacedCount: compaction.replacedMessageIds.length,
|
|
442
|
+
cursor: receipt.lastPosition,
|
|
443
|
+
};
|
|
444
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { AgentSessionId, RunCompletionPolicy, RunConfig, RunId, TurnId } from '@saturn-universe/core';
|
|
2
|
+
export interface SemanticCompletionJudgeInput {
|
|
3
|
+
readonly runId: RunId;
|
|
4
|
+
readonly agentSessionId: AgentSessionId;
|
|
5
|
+
readonly turnId: TurnId;
|
|
6
|
+
readonly config: RunConfig;
|
|
7
|
+
readonly userGoal: string;
|
|
8
|
+
readonly finalAssistantText: string;
|
|
9
|
+
readonly todos: readonly {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly content: string;
|
|
12
|
+
readonly status: string;
|
|
13
|
+
}[];
|
|
14
|
+
readonly toolSummary: string;
|
|
15
|
+
readonly continuationTurnsUsed: number;
|
|
16
|
+
}
|
|
17
|
+
export interface SemanticCompletionVerdict {
|
|
18
|
+
readonly goalAchieved: boolean;
|
|
19
|
+
readonly isGenuineExternalBlocker: boolean;
|
|
20
|
+
readonly missingCriteria: readonly string[];
|
|
21
|
+
readonly nextConcreteAction: string;
|
|
22
|
+
}
|
|
23
|
+
export type SemanticCompletionJudge = (input: SemanticCompletionJudgeInput) => Promise<SemanticCompletionVerdict | undefined>;
|
|
24
|
+
export interface ContinuationCompletionPolicyOptions {
|
|
25
|
+
readonly defaultMaxTurns?: number;
|
|
26
|
+
readonly now?: () => number;
|
|
27
|
+
readonly semanticJudge?: SemanticCompletionJudge;
|
|
28
|
+
readonly semanticJudgeMinToolCalls?: number;
|
|
29
|
+
}
|
|
30
|
+
export declare function createContinuationCompletionPolicy(options?: ContinuationCompletionPolicyOptions): RunCompletionPolicy;
|