@saturn-universe/context 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/extensions.d.ts +2 -0
- package/dist/extensions.js +47 -0
- package/dist/history.d.ts +14 -0
- package/dist/history.js +510 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +489 -0
- package/dist/prompts.d.ts +42 -0
- package/dist/prompts.js +150 -0
- package/dist/tool-output.d.ts +30 -0
- package/dist/tool-output.js +267 -0
- package/package.json +15 -3
- package/README.md +0 -3
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export function extensionProviders(config) {
|
|
2
|
+
if (!config.contextExtensions)
|
|
3
|
+
return [];
|
|
4
|
+
const { mode, skills } = config.contextExtensions;
|
|
5
|
+
return [
|
|
6
|
+
...(mode && mode.instructions.trim() ? [provider('mode', mode.ref, mode.instructions, [])] : []),
|
|
7
|
+
...skills.map((skill) => provider('skill', skill.ref, skill.instructions, skill.resources)),
|
|
8
|
+
];
|
|
9
|
+
}
|
|
10
|
+
function provider(kind, ref, instructions, resources) {
|
|
11
|
+
const [name, version] = ref.split('@');
|
|
12
|
+
const id = `${kind}:${name}`;
|
|
13
|
+
const priority = kind === 'mode' ? 50 : 25;
|
|
14
|
+
return {
|
|
15
|
+
id,
|
|
16
|
+
version,
|
|
17
|
+
phase: kind === 'mode' ? 'mode' : 'extensions',
|
|
18
|
+
priority,
|
|
19
|
+
required: true,
|
|
20
|
+
timeoutMs: 15_000,
|
|
21
|
+
async collect() {
|
|
22
|
+
return {
|
|
23
|
+
providerId: id,
|
|
24
|
+
version,
|
|
25
|
+
tools: [],
|
|
26
|
+
relevantTurnIds: [],
|
|
27
|
+
prompt: [
|
|
28
|
+
{
|
|
29
|
+
id,
|
|
30
|
+
source: id,
|
|
31
|
+
priority,
|
|
32
|
+
authority: 'configured_instruction',
|
|
33
|
+
required: true,
|
|
34
|
+
text: instructions,
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
background: resources.map((resource) => ({
|
|
38
|
+
id: `${id}/${resource.path}`,
|
|
39
|
+
source: id,
|
|
40
|
+
priority: 0,
|
|
41
|
+
required: false,
|
|
42
|
+
text: `${ref}/${resource.path}\n${resource.text}`,
|
|
43
|
+
})),
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BudgetError } from '@saturn-universe/core';
|
|
2
|
+
import type { ArtifactReader, Hash, MessageHistoryBuilder, ResponsesCodecRegistry, TokenCounter, ResponsesInputItem, ContentPart } from '@saturn-universe/core';
|
|
3
|
+
export declare class ContinuationBudgetError extends BudgetError {
|
|
4
|
+
readonly requiredTokens: number;
|
|
5
|
+
readonly allowedTokens: number;
|
|
6
|
+
constructor(requiredTokens: number, allowedTokens: number);
|
|
7
|
+
}
|
|
8
|
+
export declare function createHistoryBuilder(d: {
|
|
9
|
+
hash: Hash;
|
|
10
|
+
counter: TokenCounter;
|
|
11
|
+
codecs: ResponsesCodecRegistry;
|
|
12
|
+
artifactReader?: ArtifactReader;
|
|
13
|
+
encodePart?: (part: ContentPart) => Promise<ResponsesInputItem>;
|
|
14
|
+
}): MessageHistoryBuilder;
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
import { BACKGROUND_CONTEXT_PREFIX, ENDED_HISTORY_CONTEXT_PREFIX, BudgetError, canonicalJson, pruneToolOutcome, RuntimeError, modelConfiguration, selectPrunableToolCallIds, } from '@saturn-universe/core';
|
|
2
|
+
import { formatModelToolOutcome, modelToolOutcome } from './tool-output.js';
|
|
3
|
+
export class ContinuationBudgetError extends BudgetError {
|
|
4
|
+
requiredTokens;
|
|
5
|
+
allowedTokens;
|
|
6
|
+
constructor(requiredTokens, allowedTokens) {
|
|
7
|
+
super('CONTINUATION_BUDGET_EXCEEDED', {
|
|
8
|
+
resource: 'context',
|
|
9
|
+
used: 0,
|
|
10
|
+
max: allowedTokens,
|
|
11
|
+
required: requiredTokens,
|
|
12
|
+
});
|
|
13
|
+
this.requiredTokens = requiredTokens;
|
|
14
|
+
this.allowedTokens = allowedTokens;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function createHistoryBuilder(d) {
|
|
18
|
+
return {
|
|
19
|
+
async build(input, formatToolResult) {
|
|
20
|
+
const surface = input.surface;
|
|
21
|
+
if (surface.items.some((item) => item.message.agentSessionId !== surface.agentSessionId))
|
|
22
|
+
throw new RuntimeError('HISTORY_ISOLATION', 'foreign Agent history');
|
|
23
|
+
const pending = surface.groups
|
|
24
|
+
.filter((g) => !g.complete)
|
|
25
|
+
.flatMap((g) => g.callIds.filter((id) => !g.settledCallIds.includes(id)));
|
|
26
|
+
if (pending.length)
|
|
27
|
+
return { status: 'blocked', callIds: pending };
|
|
28
|
+
if (surface.pendingRequestIds.length)
|
|
29
|
+
throw new RuntimeError('MODEL_IN_FLIGHT', 'cannot assemble another request while a model is in flight');
|
|
30
|
+
const active = surface.items.filter((item) => item.active);
|
|
31
|
+
const turns = [...new Set(active.map((item) => item.message.turnId))];
|
|
32
|
+
if (!turns.includes(input.selection.requiredTurnId))
|
|
33
|
+
throw new RuntimeError('INVALID_HISTORY', 'required Turn missing');
|
|
34
|
+
const currentBlocks = surface.continuations.filter((block) => block.active &&
|
|
35
|
+
active.find((item) => item.message.id === block.assistantMessageId)?.message.turnId ===
|
|
36
|
+
input.selection.requiredTurnId);
|
|
37
|
+
const chain = currentBlocks.length > 0;
|
|
38
|
+
const required = new Set([input.selection.requiredTurnId]);
|
|
39
|
+
const supersedingEvents = new Set(surface.items.map((item) => item.supersededBy).filter(Boolean));
|
|
40
|
+
const summaries = active.filter((item) => supersedingEvents.has(item.sourceEventId));
|
|
41
|
+
if (chain) {
|
|
42
|
+
const selectedIds = new Set(currentBlocks[0].selectedMessageIds);
|
|
43
|
+
active
|
|
44
|
+
.filter((item) => selectedIds.has(item.message.id))
|
|
45
|
+
.forEach((item) => required.add(item.message.turnId));
|
|
46
|
+
}
|
|
47
|
+
const selected = chain
|
|
48
|
+
? new Set(required)
|
|
49
|
+
: new Set([
|
|
50
|
+
...required,
|
|
51
|
+
...(input.selection.keepSummaries === false ? [] : summaries.map((item) => item.message.turnId)),
|
|
52
|
+
...input.selection.relevantTurnIds,
|
|
53
|
+
...(input.selection.keepRecentTurns > 0 ? turns.slice(-input.selection.keepRecentTurns) : []),
|
|
54
|
+
]);
|
|
55
|
+
const allowedTokens = Math.min(input.budget.maxInputTokens, input.budget.contextWindow - input.budget.outputReserve - input.budget.safetyMargin);
|
|
56
|
+
const defaultBackground = () => input.background.map((text, index) => ({
|
|
57
|
+
role: 'user',
|
|
58
|
+
content: [{ type: 'text', text: `${BACKGROUND_CONTEXT_PREFIX}${text}` }],
|
|
59
|
+
sourceBackgroundId: `background:${index}`,
|
|
60
|
+
}));
|
|
61
|
+
const frozenPlan = input.frozenRequest?.responses;
|
|
62
|
+
const background = frozenPlan
|
|
63
|
+
? frozenPlan.backgroundDigest === undefined
|
|
64
|
+
? []
|
|
65
|
+
: (frozenPlan.initialBackground ??
|
|
66
|
+
surface.continuations.find((block) => block.active &&
|
|
67
|
+
block.state.epochId === frozenPlan.epochId &&
|
|
68
|
+
block.requestPlan.initialBackground !== undefined)?.requestPlan.initialBackground ??
|
|
69
|
+
defaultBackground())
|
|
70
|
+
: defaultBackground();
|
|
71
|
+
const preview = input.tools.some((tool) => tool.canonicalName === 'read_tool_result')
|
|
72
|
+
? { contextWindow: input.capabilities.contextWindow }
|
|
73
|
+
: undefined;
|
|
74
|
+
const defaultOutcome = (result) => preview ? modelToolOutcome(result, preview) : result.outcome;
|
|
75
|
+
const presented = new Map();
|
|
76
|
+
const basePresent = formatToolResult
|
|
77
|
+
? async (result) => {
|
|
78
|
+
const cached = presented.get(result);
|
|
79
|
+
if (cached)
|
|
80
|
+
return cached;
|
|
81
|
+
const outcome = await formatModelToolOutcome(result, formatToolResult, preview);
|
|
82
|
+
presented.set(result, outcome);
|
|
83
|
+
return outcome;
|
|
84
|
+
}
|
|
85
|
+
: defaultOutcome;
|
|
86
|
+
while (true) {
|
|
87
|
+
const items = active.filter((item) => selected.has(item.message.turnId));
|
|
88
|
+
const omitted = active.filter((item) => !selected.has(item.message.turnId));
|
|
89
|
+
const prunableCallIds = input.pruneToolResults
|
|
90
|
+
? selectPrunableToolCallIds(items, { contextWindow: input.capabilities.contextWindow })
|
|
91
|
+
: new Set();
|
|
92
|
+
const prunedOutcomes = new Map();
|
|
93
|
+
let anyPruned = false;
|
|
94
|
+
if (prunableCallIds.size > 0) {
|
|
95
|
+
for (const item of items) {
|
|
96
|
+
if (item.message.role !== 'tool' || !prunableCallIds.has(item.message.result.toolCallId))
|
|
97
|
+
continue;
|
|
98
|
+
const base = await basePresent(item.message.result);
|
|
99
|
+
const pruned = pruneToolOutcome(base);
|
|
100
|
+
if (pruned.prunedChars > 0) {
|
|
101
|
+
anyPruned = true;
|
|
102
|
+
prunedOutcomes.set(item.message.result, pruned.outcome);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const present = async (result) => {
|
|
107
|
+
const pruned = prunedOutcomes.get(result);
|
|
108
|
+
if (pruned)
|
|
109
|
+
return pruned;
|
|
110
|
+
return basePresent(result);
|
|
111
|
+
};
|
|
112
|
+
const responses = await plan(input, items, omitted.length > 0, chain, anyPruned, background, d, present, basePresent);
|
|
113
|
+
const replayed = new Map();
|
|
114
|
+
if (formatToolResult) {
|
|
115
|
+
// An appended native prefix already contains the presentation that was sent.
|
|
116
|
+
for (const item of responses.fullInput) {
|
|
117
|
+
if (item.type === 'function_call_output' &&
|
|
118
|
+
typeof item.call_id === 'string' &&
|
|
119
|
+
typeof item.output === 'string')
|
|
120
|
+
replayed.set(item.call_id, item.output);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const messages = historyMessages(items, input.systemPrompt, background, (result, providerCallId) => {
|
|
124
|
+
const pruned = prunedOutcomes.get(result);
|
|
125
|
+
if (pruned)
|
|
126
|
+
return pruned;
|
|
127
|
+
const prior = replayed.get(providerCallId);
|
|
128
|
+
return (presented.get(result) ??
|
|
129
|
+
(prior === undefined ? defaultOutcome(result) : JSON.parse(prior)));
|
|
130
|
+
});
|
|
131
|
+
const opaqueReasoningBounds = new Map();
|
|
132
|
+
const blocks = new Map(surface.continuations.map((block) => [block.responseEventId, block]));
|
|
133
|
+
for (const source of responses.replaySources) {
|
|
134
|
+
const block = blocks.get(source.responseEventId);
|
|
135
|
+
if (!block)
|
|
136
|
+
continue;
|
|
137
|
+
// Charge one bound per response. Its reasoning may be spread across several replay items.
|
|
138
|
+
const bound = block.usage?.accuracy === 'reported' ? block.usage.outputTokens : block.maxOutputTokens;
|
|
139
|
+
if (bound === undefined)
|
|
140
|
+
continue;
|
|
141
|
+
let charge = bound;
|
|
142
|
+
for (const [index, item] of block.state.outputItems.entries()) {
|
|
143
|
+
if (item.kind !== 'reasoning')
|
|
144
|
+
continue;
|
|
145
|
+
opaqueReasoningBounds.set(source.inputStart + index, charge);
|
|
146
|
+
charge = 0;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const latestSource = responses.replaySources.at(-1);
|
|
150
|
+
const usage = latestSource && blocks.get(latestSource.responseEventId)?.usage;
|
|
151
|
+
const estimate = await d.counter.estimate({
|
|
152
|
+
model: input.model,
|
|
153
|
+
messages,
|
|
154
|
+
responses,
|
|
155
|
+
tools: input.tools,
|
|
156
|
+
opaqueReasoningBounds,
|
|
157
|
+
...(latestSource && usage?.accuracy === 'reported' && responses.decision.kind === 'append'
|
|
158
|
+
? {
|
|
159
|
+
replay: {
|
|
160
|
+
inputCount: latestSource.inputStart + latestSource.inputCount,
|
|
161
|
+
outputStart: latestSource.inputStart,
|
|
162
|
+
usage,
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
: {}),
|
|
166
|
+
});
|
|
167
|
+
if (!Number.isSafeInteger(estimate.inputTokens) || estimate.inputTokens < 0)
|
|
168
|
+
throw new RuntimeError('INVALID_TOKEN_ESTIMATE', 'invalid token estimate');
|
|
169
|
+
if (estimate.inputTokens <= allowedTokens)
|
|
170
|
+
return {
|
|
171
|
+
status: 'ready',
|
|
172
|
+
messages,
|
|
173
|
+
responses,
|
|
174
|
+
selectedMessageIds: items.map((item) => item.message.id),
|
|
175
|
+
omittedMessageIds: omitted.map((item) => item.message.id),
|
|
176
|
+
surfaceSeq: surface.lastStreamSeq,
|
|
177
|
+
estimate,
|
|
178
|
+
};
|
|
179
|
+
const optional = turns.find((turn) => selected.has(turn) && !required.has(turn));
|
|
180
|
+
if (!optional) {
|
|
181
|
+
if (chain)
|
|
182
|
+
throw new ContinuationBudgetError(estimate.inputTokens, allowedTokens);
|
|
183
|
+
return { status: 'over_budget', requiredTokens: estimate.inputTokens, allowedTokens };
|
|
184
|
+
}
|
|
185
|
+
selected.delete(optional);
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
async function plan(input, items, trimmed, chain, prunedToolResults, background, d, present, basePresent) {
|
|
191
|
+
const blocks = input.surface.continuations.filter((block) => block.active && items.some((item) => item.message.id === block.assistantMessageId));
|
|
192
|
+
const latest = blocks.at(-1);
|
|
193
|
+
const backgroundDigest = input.frozenRequest
|
|
194
|
+
? input.frozenRequest.responses.backgroundDigest
|
|
195
|
+
: background.length
|
|
196
|
+
? d.hash(background)
|
|
197
|
+
: undefined;
|
|
198
|
+
const configurationDigest = input.frozenRequest?.responses.configurationDigest ??
|
|
199
|
+
d.hash(modelConfiguration({
|
|
200
|
+
binding: input.binding,
|
|
201
|
+
instructions: input.systemPrompt,
|
|
202
|
+
placement: input.capabilities.responses.instructionPlacement,
|
|
203
|
+
tools: input.tools,
|
|
204
|
+
output: { kind: 'text' },
|
|
205
|
+
reasoning: input.responsesPolicy.reasoning,
|
|
206
|
+
}));
|
|
207
|
+
let reason;
|
|
208
|
+
const previousPrefix = latest
|
|
209
|
+
? items
|
|
210
|
+
.slice(0, items.findIndex((item) => item.message.id === latest.assistantMessageId))
|
|
211
|
+
.map((item) => item.message.id)
|
|
212
|
+
: undefined;
|
|
213
|
+
const samePrefix = latest && canonicalJson(previousPrefix) === canonicalJson(latest.selectedMessageIds);
|
|
214
|
+
if (!latest && input.surface.lastCompactionSeq !== undefined)
|
|
215
|
+
reason = 'compacted';
|
|
216
|
+
else if (trimmed && !samePrefix)
|
|
217
|
+
reason = 'history_trimmed';
|
|
218
|
+
else if (!latest && input.surface.continuations.some((block) => !block.active))
|
|
219
|
+
reason = 'compacted';
|
|
220
|
+
else if (latest && canonicalJson(latest.state.binding) !== canonicalJson(input.binding))
|
|
221
|
+
reason = 'binding_changed';
|
|
222
|
+
else if (latest && latest.requestPlan.configurationDigest !== configurationDigest)
|
|
223
|
+
reason = 'prefix_changed';
|
|
224
|
+
else if (latest && latest.requestPlan.backgroundDigest !== backgroundDigest)
|
|
225
|
+
reason = 'prefix_changed';
|
|
226
|
+
else if (latest && !samePrefix)
|
|
227
|
+
reason = 'prefix_changed';
|
|
228
|
+
else if (prunedToolResults)
|
|
229
|
+
reason = 'history_trimmed';
|
|
230
|
+
const prunerReset = prunedToolResults && reason === 'history_trimmed';
|
|
231
|
+
if (chain && reason && !prunerReset)
|
|
232
|
+
throw new RuntimeError('CONTINUATION_PREFIX_CHANGED', 'cannot reset inside active native chain');
|
|
233
|
+
const codec = d.codecs.get(input.binding.codecId, input.binding.codecVersion);
|
|
234
|
+
const encode = {
|
|
235
|
+
...d,
|
|
236
|
+
surfaceItems: input.surface.items,
|
|
237
|
+
capabilities: input.capabilities,
|
|
238
|
+
codec,
|
|
239
|
+
present,
|
|
240
|
+
basePresent,
|
|
241
|
+
};
|
|
242
|
+
let fullInput = [];
|
|
243
|
+
let replaySources = [];
|
|
244
|
+
let decision = { kind: 'new' };
|
|
245
|
+
let epochId;
|
|
246
|
+
if (latest && !reason) {
|
|
247
|
+
const priorFullInput = await reconstructPriorFullInput(input, items, blocks, latest, background, encode);
|
|
248
|
+
const replay = latest.state.outputItems.map((item) => codec.replayItem(item));
|
|
249
|
+
fullInput = [...priorFullInput, ...replay.map((item) => item.input)];
|
|
250
|
+
replaySources = [
|
|
251
|
+
...latest.requestPlan.replaySources,
|
|
252
|
+
{
|
|
253
|
+
responseEventId: latest.responseEventId,
|
|
254
|
+
outputDigest: latest.state.outputDigest,
|
|
255
|
+
inputStart: priorFullInput.length,
|
|
256
|
+
inputCount: replay.length,
|
|
257
|
+
removedOutputOnlyPaths: replay.flatMap((item) => item.removedOutputOnlyPaths),
|
|
258
|
+
},
|
|
259
|
+
];
|
|
260
|
+
decision = { kind: 'append', previousResponseEventId: latest.responseEventId };
|
|
261
|
+
epochId = latest.state.epochId;
|
|
262
|
+
const assistantIndex = items.findIndex((item) => item.message.id === latest.assistantMessageId);
|
|
263
|
+
await appendItems(fullInput, items.slice(assistantIndex + 1), encode);
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
const placement = input.capabilities.responses.instructionPlacement;
|
|
267
|
+
if (input.systemPrompt && placement !== 'instructions')
|
|
268
|
+
fullInput.push({
|
|
269
|
+
type: 'message',
|
|
270
|
+
role: placement === 'developer_item' ? 'developer' : 'system',
|
|
271
|
+
content: [{ type: 'input_text', text: input.systemPrompt }],
|
|
272
|
+
});
|
|
273
|
+
for (const message of background)
|
|
274
|
+
fullInput.push({
|
|
275
|
+
type: 'message',
|
|
276
|
+
role: 'user',
|
|
277
|
+
content: await encodeUserContent(message.content, {
|
|
278
|
+
...d,
|
|
279
|
+
capabilities: input.capabilities,
|
|
280
|
+
codec,
|
|
281
|
+
}),
|
|
282
|
+
});
|
|
283
|
+
if (reason) {
|
|
284
|
+
decision = { kind: 'reset', atTurnId: input.selection.requiredTurnId, reason };
|
|
285
|
+
const older = items.filter((item) => item.message.turnId !== input.selection.requiredTurnId);
|
|
286
|
+
if (older.length)
|
|
287
|
+
await appendEndedHistory(fullInput, older, input.surface.continuations, present);
|
|
288
|
+
await appendItems(fullInput, items.filter((item) => item.message.turnId === input.selection.requiredTurnId), encode, reason === 'compacted' || reason === 'history_trimmed');
|
|
289
|
+
}
|
|
290
|
+
else
|
|
291
|
+
await appendItems(fullInput, items, encode);
|
|
292
|
+
epochId = d.hash({
|
|
293
|
+
agentSessionId: input.surface.agentSessionId,
|
|
294
|
+
turnId: input.selection.requiredTurnId,
|
|
295
|
+
configurationDigest,
|
|
296
|
+
initialInput: fullInput,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
const seen = new Set();
|
|
300
|
+
const outputs = new Set();
|
|
301
|
+
for (const item of fullInput) {
|
|
302
|
+
if (item.type === 'function_call') {
|
|
303
|
+
if (typeof item.call_id !== 'string' || seen.has(item.call_id))
|
|
304
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'ambiguous call_id');
|
|
305
|
+
seen.add(item.call_id);
|
|
306
|
+
}
|
|
307
|
+
if (item.type === 'function_call_output') {
|
|
308
|
+
if (typeof item.call_id !== 'string' || !seen.has(item.call_id) || outputs.has(item.call_id))
|
|
309
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'unpaired function result');
|
|
310
|
+
outputs.add(item.call_id);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if ([...seen].some((id) => !outputs.has(id)))
|
|
314
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'missing native function result');
|
|
315
|
+
return {
|
|
316
|
+
version: 1,
|
|
317
|
+
binding: input.binding,
|
|
318
|
+
epochId,
|
|
319
|
+
decision,
|
|
320
|
+
...(input.capabilities.responses.instructionPlacement === 'instructions'
|
|
321
|
+
? { instructions: input.systemPrompt }
|
|
322
|
+
: {}),
|
|
323
|
+
...(prunedToolResults && decision.kind === 'reset' ? { prunedToolResults: true } : {}),
|
|
324
|
+
fullInput,
|
|
325
|
+
fullInputDigest: d.hash(fullInput),
|
|
326
|
+
configurationDigest,
|
|
327
|
+
...(backgroundDigest === undefined ? {} : { backgroundDigest }),
|
|
328
|
+
replaySources,
|
|
329
|
+
transport: { kind: 'local_replay' },
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
async function appendEndedHistory(output, older, continuations, present) {
|
|
333
|
+
const ended = [];
|
|
334
|
+
for (const { message } of older) {
|
|
335
|
+
const outcome = message.role === 'tool' ? await present(message.result) : undefined;
|
|
336
|
+
ended.push({
|
|
337
|
+
sourceMessageId: message.id,
|
|
338
|
+
message: message.role === 'tool' && outcome !== message.result.outcome
|
|
339
|
+
? { ...message, result: { ...message.result, outcome } }
|
|
340
|
+
: message,
|
|
341
|
+
nativePhases: continuations
|
|
342
|
+
.filter((block) => block.assistantMessageId === message.id)
|
|
343
|
+
.flatMap((block) => block.state.outputItems.flatMap((outputItem) => outputItem.kind === 'message' ? [outputItem.value.phase ?? null] : [])),
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
output.push({
|
|
347
|
+
type: 'message',
|
|
348
|
+
role: 'user',
|
|
349
|
+
content: [
|
|
350
|
+
{
|
|
351
|
+
type: 'input_text',
|
|
352
|
+
text: ENDED_HISTORY_CONTEXT_PREFIX + canonicalJson(ended),
|
|
353
|
+
},
|
|
354
|
+
],
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
async function reconstructPriorFullInput(input, items, blocks, latest, background, encode) {
|
|
358
|
+
const epochBlocks = blocks.filter((block) => block.state.epochId === latest.state.epochId);
|
|
359
|
+
const first = epochBlocks[0];
|
|
360
|
+
if (!first)
|
|
361
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'missing epoch start block');
|
|
362
|
+
const reconstructed = [];
|
|
363
|
+
const placement = input.capabilities.responses.instructionPlacement;
|
|
364
|
+
if (input.systemPrompt && placement !== 'instructions')
|
|
365
|
+
reconstructed.push({
|
|
366
|
+
type: 'message',
|
|
367
|
+
role: placement === 'developer_item' ? 'developer' : 'system',
|
|
368
|
+
content: [{ type: 'input_text', text: input.systemPrompt }],
|
|
369
|
+
});
|
|
370
|
+
const epochBackground = first.requestPlan.initialBackground ?? background;
|
|
371
|
+
for (const message of epochBackground)
|
|
372
|
+
reconstructed.push({
|
|
373
|
+
type: 'message',
|
|
374
|
+
role: 'user',
|
|
375
|
+
content: await encodeUserContent(message.content, encode),
|
|
376
|
+
});
|
|
377
|
+
const firstSelectedIds = new Set(first.selectedMessageIds);
|
|
378
|
+
const firstItems = items.filter((item) => firstSelectedIds.has(item.message.id));
|
|
379
|
+
const firstPrunableIds = first.requestPlan.prunedToolResults
|
|
380
|
+
? selectPrunableToolCallIds(firstItems, { contextWindow: input.capabilities.contextWindow })
|
|
381
|
+
: new Set();
|
|
382
|
+
const presentFirst = async (result) => {
|
|
383
|
+
const base = await encode.basePresent(result);
|
|
384
|
+
return firstPrunableIds.has(result.toolCallId) ? pruneToolOutcome(base).outcome : base;
|
|
385
|
+
};
|
|
386
|
+
const encodeFirst = { ...encode, present: presentFirst };
|
|
387
|
+
if (first.requestPlan.decision.kind === 'reset') {
|
|
388
|
+
const resetTurnId = first.requestPlan.decision.atTurnId;
|
|
389
|
+
const resetReason = first.requestPlan.decision.reason;
|
|
390
|
+
const older = firstItems.filter((item) => item.message.turnId !== resetTurnId);
|
|
391
|
+
if (older.length)
|
|
392
|
+
await appendEndedHistory(reconstructed, older, input.surface.continuations, presentFirst);
|
|
393
|
+
await appendItems(reconstructed, firstItems.filter((item) => item.message.turnId === resetTurnId), encodeFirst, resetReason === 'compacted' || resetReason === 'history_trimmed');
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
await appendItems(reconstructed, firstItems, encodeFirst);
|
|
397
|
+
}
|
|
398
|
+
for (let i = 0; i < epochBlocks.length - 1; i++) {
|
|
399
|
+
const current = epochBlocks[i];
|
|
400
|
+
const next = epochBlocks[i + 1];
|
|
401
|
+
for (const outputItem of current.state.outputItems) {
|
|
402
|
+
reconstructed.push(encode.codec.replayItem(outputItem).input);
|
|
403
|
+
}
|
|
404
|
+
const currentIdx = items.findIndex((item) => item.message.id === current.assistantMessageId);
|
|
405
|
+
const nextIdx = items.findIndex((item) => item.message.id === next.assistantMessageId);
|
|
406
|
+
if (currentIdx < 0 || nextIdx <= currentIdx)
|
|
407
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'broken continuation item ordering');
|
|
408
|
+
await appendItems(reconstructed, items.slice(currentIdx + 1, nextIdx), encode);
|
|
409
|
+
}
|
|
410
|
+
if (encode.hash(reconstructed) !== latest.requestPlan.fullInputDigest)
|
|
411
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'reconstructed continuation input digest mismatch');
|
|
412
|
+
return reconstructed;
|
|
413
|
+
}
|
|
414
|
+
async function appendItems(output, items, d, allowAssistants = false) {
|
|
415
|
+
for (const item of items) {
|
|
416
|
+
const m = item.message;
|
|
417
|
+
if (m.role === 'user') {
|
|
418
|
+
const content = await encodeUserContent(m.content, d);
|
|
419
|
+
output.push({ type: 'message', role: 'user', content });
|
|
420
|
+
}
|
|
421
|
+
else if (m.role === 'tool') {
|
|
422
|
+
const assistant = d.surfaceItems.find((value) => value.message.role === 'assistant' &&
|
|
423
|
+
value.message.toolCalls.some((call) => call.id === m.result.toolCallId));
|
|
424
|
+
const call = assistant?.message.role === 'assistant'
|
|
425
|
+
? assistant.message.toolCalls.find((call) => call.id === m.result.toolCallId)
|
|
426
|
+
: undefined;
|
|
427
|
+
const providerCallId = call?.providerCallId;
|
|
428
|
+
if (typeof providerCallId !== 'string')
|
|
429
|
+
throw new RuntimeError('CONTINUATION_MISMATCH', 'missing tool binding');
|
|
430
|
+
output.push({
|
|
431
|
+
type: 'function_call_output',
|
|
432
|
+
call_id: providerCallId,
|
|
433
|
+
output: canonicalJson(await d.present(m.result)),
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
else if (allowAssistants) {
|
|
437
|
+
const textParts = m.content
|
|
438
|
+
.filter((part) => part.type === 'text' && part.text.length > 0)
|
|
439
|
+
.map((part) => ({ type: 'output_text', text: part.text }));
|
|
440
|
+
if (textParts.length > 0) {
|
|
441
|
+
output.push({
|
|
442
|
+
type: 'message',
|
|
443
|
+
role: 'assistant',
|
|
444
|
+
id: m.id,
|
|
445
|
+
content: textParts,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
for (const call of m.toolCalls) {
|
|
449
|
+
output.push({
|
|
450
|
+
type: 'function_call',
|
|
451
|
+
id: call.id,
|
|
452
|
+
call_id: call.providerCallId,
|
|
453
|
+
name: call.toolName,
|
|
454
|
+
arguments: call.arguments.kind === 'json' ? canonicalJson(call.arguments.value) : call.arguments.raw,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
else
|
|
459
|
+
throw new RuntimeError('CONTINUATION_MISSING', 'assistant requires native continuation or safe reset');
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
async function encodeUserContent(parts, d) {
|
|
463
|
+
const content = [];
|
|
464
|
+
for (const part of parts) {
|
|
465
|
+
if (part.type === 'text')
|
|
466
|
+
content.push({ type: 'input_text', text: part.text });
|
|
467
|
+
else if (d.encodePart)
|
|
468
|
+
content.push(await d.encodePart(part));
|
|
469
|
+
else {
|
|
470
|
+
if (!d.artifactReader || !d.codec.encodePart)
|
|
471
|
+
throw new RuntimeError('UNSUPPORTED_ARTIFACT', 'artifact mapping is unavailable for this Responses codec');
|
|
472
|
+
const bytes = await d.artifactReader.read(part.artifact);
|
|
473
|
+
content.push(d.codec.encodePart(part, bytes, d.capabilities));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return content;
|
|
477
|
+
}
|
|
478
|
+
function historyMessages(items, prompt, background, outcome) {
|
|
479
|
+
const messages = prompt ? [{ role: 'system', content: prompt }] : [];
|
|
480
|
+
messages.push(...background);
|
|
481
|
+
for (const item of items) {
|
|
482
|
+
const m = item.message;
|
|
483
|
+
switch (m.role) {
|
|
484
|
+
case 'user':
|
|
485
|
+
messages.push({ role: 'user', content: m.content, sourceMessageId: m.id });
|
|
486
|
+
break;
|
|
487
|
+
case 'assistant':
|
|
488
|
+
messages.push({ role: 'assistant', content: m.content, calls: m.toolCalls, sourceMessageId: m.id });
|
|
489
|
+
break;
|
|
490
|
+
case 'tool': {
|
|
491
|
+
const parent = items.find((item) => item.message.role === 'assistant' &&
|
|
492
|
+
item.message.toolCalls.some((call) => call.id === m.result.toolCallId));
|
|
493
|
+
const call = parent?.message.role === 'assistant'
|
|
494
|
+
? parent.message.toolCalls.find((call) => call.id === m.result.toolCallId)
|
|
495
|
+
: undefined;
|
|
496
|
+
if (!call)
|
|
497
|
+
throw new RuntimeError('INVALID_HISTORY', 'orphan result');
|
|
498
|
+
messages.push({
|
|
499
|
+
role: 'tool',
|
|
500
|
+
callId: m.result.toolCallId,
|
|
501
|
+
providerCallId: call.providerCallId,
|
|
502
|
+
outcome: outcome(m.result, call.providerCallId),
|
|
503
|
+
sourceMessageId: m.id,
|
|
504
|
+
});
|
|
505
|
+
break;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return messages;
|
|
510
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Hash, ContextProvider, PromptComposer, TokenBudgetManager, ContextComposer, ContextStateReader, ModelGateway, MessageHistoryBuilder, ToolSpec, RunConfig, RuntimeHooks } from '@saturn-universe/core';
|
|
2
|
+
export { createHistoryBuilder } from './history.js';
|
|
3
|
+
export { DEFAULT_PRUNER_MAX_TOOL_CHARS, DEFAULT_PRUNER_MIN_RECENT_STEPS, DEFAULT_PRUNER_TAIL_WINDOW_RATIO, groupSurfaceUnits, pruneTextMiddle, pruneToolOutcome, selectPrunableToolCallIds, selectProtectedTailStart, selectSafeCompactionPrefix, shouldTriggerCompaction, } from '@saturn-universe/core';
|
|
4
|
+
export { modelToolOutcome, toolResultPage, toolResultTextPage } from './tool-output.js';
|
|
5
|
+
export type { ModelToolOutcomeOptions, ToolResultTextPage, ToolResultTextPageOptions, } from './tool-output.js';
|
|
6
|
+
export { buildCoreSystemPrompt, buildEnvironmentContext, buildExecutionPolicyPrompt, buildPlannerModeInstructions, buildTeamHintPrompt, } from './prompts.js';
|
|
7
|
+
export type { HostEnvironmentInfo, TeamHintPromptInput } from './prompts.js';
|
|
8
|
+
export declare function createPromptComposer(hash: Hash): PromptComposer;
|
|
9
|
+
export declare function createTokenBudgetManager(): TokenBudgetManager;
|
|
10
|
+
export interface BuiltinProviderSection {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly text: string;
|
|
13
|
+
readonly priority?: number;
|
|
14
|
+
readonly required?: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface BuiltinProviderOptions {
|
|
17
|
+
readonly executionPolicyPrompt?: string;
|
|
18
|
+
readonly extraCoreSections?: readonly BuiltinProviderSection[];
|
|
19
|
+
}
|
|
20
|
+
export declare function createBuiltinProviders(tools: readonly ToolSpec[], corePrompt?: string, options?: BuiltinProviderOptions): readonly ContextProvider[];
|
|
21
|
+
export interface ContextProviderRegistry {
|
|
22
|
+
register(provider: ContextProvider): () => void;
|
|
23
|
+
list(): readonly ContextProvider[];
|
|
24
|
+
resolve(id: string, version: string, scopeKey?: string): ContextProvider;
|
|
25
|
+
release(id: string, version: string): boolean;
|
|
26
|
+
}
|
|
27
|
+
export declare function createContextProviderRegistry(): ContextProviderRegistry & {
|
|
28
|
+
activate(id: string, version: string): () => void;
|
|
29
|
+
};
|
|
30
|
+
export declare function createContextComposer(d: {
|
|
31
|
+
reader: ContextStateReader;
|
|
32
|
+
describe: Pick<ModelGateway, 'describe'>;
|
|
33
|
+
builder: MessageHistoryBuilder;
|
|
34
|
+
hash: Hash;
|
|
35
|
+
hooks?: (config: RunConfig, input: import('@saturn-universe/core').ContextRequest) => RuntimeHooks | Promise<RuntimeHooks>;
|
|
36
|
+
listProviders?: (input: import('@saturn-universe/core').ContextRequest) => Promise<readonly ContextProvider[]>;
|
|
37
|
+
desiredOutputTokens?: number;
|
|
38
|
+
safetyMargin?: number;
|
|
39
|
+
keepRecentTurns?: number;
|
|
40
|
+
} & ({
|
|
41
|
+
providers: readonly ContextProvider[];
|
|
42
|
+
providerRegistry?: never;
|
|
43
|
+
} | {
|
|
44
|
+
providers?: never;
|
|
45
|
+
providerRegistry: ContextProviderRegistry;
|
|
46
|
+
})): ContextComposer & {
|
|
47
|
+
assembleSideContext(input: import('@saturn-universe/core').ContextRequest, snapshot: import('@saturn-universe/core').ContextStateSnapshot, previous?: import('@saturn-universe/core').PersistedModelRequest): ReturnType<ContextComposer['assemble']>;
|
|
48
|
+
};
|
|
49
|
+
export declare function validateProvider(provider: ContextProvider): void;
|
|
50
|
+
export declare function registerProviders(input: readonly ContextProvider[]): ContextProvider[];
|