@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
package/dist/index.js
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
import { BudgetError, isLimited, modelTokenBudget, RuntimeError, settledModelTokens, } from '@saturn-universe/core';
|
|
2
|
+
import { ContinuationBudgetError } from './history.js';
|
|
3
|
+
import { extensionProviders } from './extensions.js';
|
|
4
|
+
import { buildCoreSystemPrompt } from './prompts.js';
|
|
5
|
+
export { createHistoryBuilder } from './history.js';
|
|
6
|
+
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';
|
|
7
|
+
export { modelToolOutcome, toolResultPage, toolResultTextPage } from './tool-output.js';
|
|
8
|
+
export { buildCoreSystemPrompt, buildEnvironmentContext, buildExecutionPolicyPrompt, buildPlannerModeInstructions, buildTeamHintPrompt, } from './prompts.js';
|
|
9
|
+
export function createPromptComposer(hash) {
|
|
10
|
+
return {
|
|
11
|
+
compose(sections) {
|
|
12
|
+
unique(sections.map((section) => section.id), 'section');
|
|
13
|
+
const sorted = [...sections].sort((a, b) => Number(b.authority === 'core') - Number(a.authority === 'core') ||
|
|
14
|
+
Number(a.authority === 'background') - Number(b.authority === 'background') ||
|
|
15
|
+
b.priority - a.priority ||
|
|
16
|
+
a.id.localeCompare(b.id));
|
|
17
|
+
const systemPrompt = sorted.map((section) => section.text.replace(/\r\n/g, '\n').trim()).join('\n\n');
|
|
18
|
+
return { systemPrompt, digest: hash(systemPrompt) };
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const maxSharedWindowOutput = 131_072;
|
|
23
|
+
function outputReserve(capabilities, desired, safetyMargin) {
|
|
24
|
+
const { contextWindow, maxOutputTokens } = capabilities;
|
|
25
|
+
const limit = maxOutputTokens >= contextWindow
|
|
26
|
+
? Math.min(maxSharedWindowOutput, Math.floor((contextWindow - safetyMargin) / 2))
|
|
27
|
+
: maxOutputTokens;
|
|
28
|
+
return Math.min(desired, limit);
|
|
29
|
+
}
|
|
30
|
+
export function createTokenBudgetManager() {
|
|
31
|
+
return {
|
|
32
|
+
plan({ capabilities, remainingRunTokens, desiredOutputTokens, safetyMargin }) {
|
|
33
|
+
const outputTokens = outputReserve(capabilities, desiredOutputTokens, safetyMargin);
|
|
34
|
+
const windowInputTokens = capabilities.contextWindow - outputTokens - safetyMargin;
|
|
35
|
+
if (outputTokens < 1 || windowInputTokens < 1)
|
|
36
|
+
throw new RuntimeError('CONTEXT_BUDGET_EXCEEDED', 'no input/output budget');
|
|
37
|
+
const unlimited = remainingRunTokens === Infinity;
|
|
38
|
+
if (!unlimited && remainingRunTokens <= outputTokens)
|
|
39
|
+
throw new RuntimeError('RUN_BUDGET_EXCEEDED', 'Run cannot reserve input and output tokens');
|
|
40
|
+
const maxInputTokens = unlimited
|
|
41
|
+
? windowInputTokens
|
|
42
|
+
: Math.min(windowInputTokens, remainingRunTokens - outputTokens);
|
|
43
|
+
return {
|
|
44
|
+
history: {
|
|
45
|
+
contextWindow: capabilities.contextWindow,
|
|
46
|
+
maxInputTokens,
|
|
47
|
+
outputReserve: outputTokens,
|
|
48
|
+
safetyMargin,
|
|
49
|
+
},
|
|
50
|
+
outputTokens,
|
|
51
|
+
remainingRunTokens,
|
|
52
|
+
};
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export function createBuiltinProviders(tools, corePrompt = buildCoreSystemPrompt(), options) {
|
|
57
|
+
const contribution = (id) => ({
|
|
58
|
+
providerId: id,
|
|
59
|
+
version: '1',
|
|
60
|
+
prompt: [],
|
|
61
|
+
background: [],
|
|
62
|
+
tools: [],
|
|
63
|
+
relevantTurnIds: [],
|
|
64
|
+
});
|
|
65
|
+
return [
|
|
66
|
+
{
|
|
67
|
+
id: 'core',
|
|
68
|
+
version: '1',
|
|
69
|
+
phase: 'core',
|
|
70
|
+
priority: 100,
|
|
71
|
+
required: true,
|
|
72
|
+
timeoutMs: 15_000,
|
|
73
|
+
async collect() {
|
|
74
|
+
const prompt = [
|
|
75
|
+
{
|
|
76
|
+
id: 'runtime',
|
|
77
|
+
source: 'core',
|
|
78
|
+
priority: 100,
|
|
79
|
+
authority: 'core',
|
|
80
|
+
required: true,
|
|
81
|
+
text: corePrompt,
|
|
82
|
+
},
|
|
83
|
+
];
|
|
84
|
+
if (options?.executionPolicyPrompt?.trim()) {
|
|
85
|
+
prompt.push({
|
|
86
|
+
id: 'execution-policy',
|
|
87
|
+
source: 'core',
|
|
88
|
+
priority: 90,
|
|
89
|
+
authority: 'core',
|
|
90
|
+
required: true,
|
|
91
|
+
text: options.executionPolicyPrompt,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
for (const extra of options?.extraCoreSections ?? []) {
|
|
95
|
+
if (!extra.text.trim())
|
|
96
|
+
continue;
|
|
97
|
+
prompt.push({
|
|
98
|
+
id: extra.id,
|
|
99
|
+
source: 'core',
|
|
100
|
+
priority: extra.priority ?? 80,
|
|
101
|
+
authority: 'core',
|
|
102
|
+
required: extra.required ?? false,
|
|
103
|
+
text: extra.text,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
...contribution('core'),
|
|
108
|
+
prompt,
|
|
109
|
+
};
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
id: 'tools',
|
|
114
|
+
version: '1',
|
|
115
|
+
phase: 'tools',
|
|
116
|
+
priority: 0,
|
|
117
|
+
required: true,
|
|
118
|
+
timeoutMs: 15_000,
|
|
119
|
+
async collect() {
|
|
120
|
+
return { ...contribution('tools'), tools };
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
id: 'session',
|
|
125
|
+
version: '1',
|
|
126
|
+
phase: 'session',
|
|
127
|
+
priority: 0,
|
|
128
|
+
required: true,
|
|
129
|
+
timeoutMs: 15_000,
|
|
130
|
+
async collect(input) {
|
|
131
|
+
return { ...contribution('session'), surface: input.state.surface };
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
];
|
|
135
|
+
}
|
|
136
|
+
export function createContextProviderRegistry() {
|
|
137
|
+
const active = new Map();
|
|
138
|
+
const retained = new Map();
|
|
139
|
+
const key = (id, version) => JSON.stringify([id, version]);
|
|
140
|
+
function activateProvider(provider) {
|
|
141
|
+
const { id } = provider;
|
|
142
|
+
if (active.has(id))
|
|
143
|
+
throw new RuntimeError('PROVIDER_CONFLICT', 'duplicate active provider ID');
|
|
144
|
+
const registration = { provider };
|
|
145
|
+
active.set(id, registration);
|
|
146
|
+
return () => {
|
|
147
|
+
if (active.get(id) === registration)
|
|
148
|
+
active.delete(id);
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
register(provider) {
|
|
153
|
+
const { id, version } = provider;
|
|
154
|
+
if (active.has(id) || retained.has(key(id, version)))
|
|
155
|
+
throw new RuntimeError('PROVIDER_CONFLICT', 'duplicate provider ID or retained version');
|
|
156
|
+
validateProvider(provider);
|
|
157
|
+
const stop = activateProvider(provider);
|
|
158
|
+
retained.set(key(id, version), provider);
|
|
159
|
+
return stop;
|
|
160
|
+
},
|
|
161
|
+
activate(id, version) {
|
|
162
|
+
return activateProvider(requireProvider(retained.get(key(id, version)), id, version));
|
|
163
|
+
},
|
|
164
|
+
list: () => registerProviders([...active.values()].map(({ provider }) => provider)),
|
|
165
|
+
resolve(id, version) {
|
|
166
|
+
return requireProvider(retained.get(key(id, version)), id, version);
|
|
167
|
+
},
|
|
168
|
+
release(id, version) {
|
|
169
|
+
if (active.get(id)?.provider.version === version)
|
|
170
|
+
active.delete(id);
|
|
171
|
+
return retained.delete(key(id, version));
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function requireProvider(provider, id, version) {
|
|
176
|
+
if (!provider)
|
|
177
|
+
throw new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `Context provider ${id}@${version} is unavailable`);
|
|
178
|
+
return provider;
|
|
179
|
+
}
|
|
180
|
+
export function createContextComposer(d) {
|
|
181
|
+
if (Boolean(d.providers) === Boolean(d.providerRegistry))
|
|
182
|
+
throw new RuntimeError('PROVIDER_CONFIG', 'one provider source is required');
|
|
183
|
+
const staticProviders = d.providers && registerProviders(d.providers);
|
|
184
|
+
const promptComposer = createPromptComposer(d.hash);
|
|
185
|
+
const budgetManager = createTokenBudgetManager();
|
|
186
|
+
async function assemble(input, overflowRequest, side) {
|
|
187
|
+
const bindings = input.config.pluginBindings?.contextProviders;
|
|
188
|
+
const providers = bindings
|
|
189
|
+
? registerProviders(bindings.map(({ id, version, scopeKey }) => d.providerRegistry
|
|
190
|
+
? d.providerRegistry.resolve(id, version, scopeKey)
|
|
191
|
+
: requireProvider(staticProviders.find((p) => p.id === id && p.version === version), id, version)))
|
|
192
|
+
: (staticProviders ?? (d.listProviders ? await d.listProviders(input) : d.providerRegistry.list()));
|
|
193
|
+
const formatToolResult = (await d.hooks?.(input.config, input))?.formatToolResult;
|
|
194
|
+
const state = side?.snapshot ?? (await d.reader.read(input.agentSessionId, input.runId));
|
|
195
|
+
if (state.surface.agentSessionId !== input.agentSessionId ||
|
|
196
|
+
state.runState.runId !== input.runId ||
|
|
197
|
+
state.surface.generation !== state.generation)
|
|
198
|
+
throw new RuntimeError('CONTEXT_SNAPSHOT', 'context snapshot mismatch');
|
|
199
|
+
const extensions = extensionProviders(input.config);
|
|
200
|
+
const activeProviders = extensions.length ? registerProviders([...providers, ...extensions]) : providers;
|
|
201
|
+
const checkpointSourceRunId = input.config.checkpoint?.sourceRunId;
|
|
202
|
+
const { contributions, warnings, versions } = await collectContributions(activeProviders, {
|
|
203
|
+
...input,
|
|
204
|
+
...(checkpointSourceRunId ? { checkpointSourceRunId } : {}),
|
|
205
|
+
state,
|
|
206
|
+
});
|
|
207
|
+
let providerVersions = versions;
|
|
208
|
+
const sources = contributions.filter((c) => c.surface);
|
|
209
|
+
if (sources.length !== 1 || sources[0].providerId !== 'session')
|
|
210
|
+
throw new RuntimeError('PROVIDER_CONFLICT', 'one session Surface source required');
|
|
211
|
+
const surface = sources[0].surface;
|
|
212
|
+
if (surface.agentSessionId !== input.agentSessionId)
|
|
213
|
+
throw new RuntimeError('HISTORY_ISOLATION', 'foreign Surface');
|
|
214
|
+
let prompt = contributions.flatMap((c) => c.prompt);
|
|
215
|
+
let background = contributions.flatMap((c) => c.background);
|
|
216
|
+
if (input.config.checkpoint)
|
|
217
|
+
background.push({
|
|
218
|
+
id: 'run-checkpoint',
|
|
219
|
+
source: 'runtime',
|
|
220
|
+
priority: 100,
|
|
221
|
+
required: true,
|
|
222
|
+
text: input.config.checkpoint.summary,
|
|
223
|
+
});
|
|
224
|
+
const reportsDeliveredInTurn = surface.items.some((item) => item.active &&
|
|
225
|
+
item.message.runId === input.runId &&
|
|
226
|
+
item.message.role === 'user' &&
|
|
227
|
+
item.message.content.some((part) => part.type === 'text' && part.text.includes('Team reports from direct reports (background data)')));
|
|
228
|
+
if (state.teamReports?.length && !reportsDeliveredInTurn)
|
|
229
|
+
background.push({
|
|
230
|
+
id: 'team-reports',
|
|
231
|
+
source: 'team',
|
|
232
|
+
priority: 100,
|
|
233
|
+
required: true,
|
|
234
|
+
text: `Team reports from direct reports (background data)\n${JSON.stringify(state.teamReports)}`,
|
|
235
|
+
});
|
|
236
|
+
if (state.planSummary?.trim())
|
|
237
|
+
background.push({
|
|
238
|
+
id: 'planner-summary',
|
|
239
|
+
source: 'planner',
|
|
240
|
+
priority: 95,
|
|
241
|
+
required: false,
|
|
242
|
+
text: `Planner execution plan (background data)\n${state.planSummary}`,
|
|
243
|
+
});
|
|
244
|
+
const tools = contributions.flatMap((c) => c.tools);
|
|
245
|
+
unique([...prompt.map((section) => section.id), ...background.map((section) => section.id)], 'section');
|
|
246
|
+
unique(tools.map((tool) => tool.canonicalName), 'tool');
|
|
247
|
+
unique(tools.map((tool) => tool.wireName), 'wire tool');
|
|
248
|
+
const activeFrozen = state.activeRequest?.turnId === input.turnId &&
|
|
249
|
+
(surface.lastCompactionSeq ?? 0) <= state.activeRequest.context.surfaceSeq
|
|
250
|
+
? state.activeRequest
|
|
251
|
+
: undefined;
|
|
252
|
+
const frozen = overflowRequest ?? side?.previous ?? activeFrozen;
|
|
253
|
+
if (frozen) {
|
|
254
|
+
const frozenSystem = frozen.responses.initialSystemPrompt ??
|
|
255
|
+
surface.continuations.find((block) => block.active &&
|
|
256
|
+
block.state.epochId === frozen.responses.epochId &&
|
|
257
|
+
block.requestPlan.initialSystemPrompt !== undefined)?.requestPlan.initialSystemPrompt;
|
|
258
|
+
if (frozenSystem !== undefined) {
|
|
259
|
+
prompt = [
|
|
260
|
+
{
|
|
261
|
+
id: 'frozen-core',
|
|
262
|
+
source: 'core',
|
|
263
|
+
authority: 'core',
|
|
264
|
+
required: true,
|
|
265
|
+
priority: 100,
|
|
266
|
+
text: frozenSystem,
|
|
267
|
+
},
|
|
268
|
+
];
|
|
269
|
+
}
|
|
270
|
+
background = [];
|
|
271
|
+
providerVersions = { ...frozen.context.providerVersions };
|
|
272
|
+
warnings.push('session: FROZEN_CONTEXT');
|
|
273
|
+
}
|
|
274
|
+
const { binding, capabilities } = await d.describe.describe(input.config.model);
|
|
275
|
+
if (input.config.providerBinding && d.hash(input.config.providerBinding) !== d.hash(binding))
|
|
276
|
+
throw new RuntimeError('INVALID_CONFIG', 'Frozen Run Provider binding is unavailable');
|
|
277
|
+
const used = settledModelTokens(state.runState);
|
|
278
|
+
const tokenLimited = !side && isLimited(input.config.limits.maxTotalTokens);
|
|
279
|
+
const remaining = tokenLimited
|
|
280
|
+
? input.config.limits.maxTotalTokens - used - state.runState.reservedTokens
|
|
281
|
+
: Infinity;
|
|
282
|
+
const desiredOutputTokens = side ? 512 : (d.desiredOutputTokens ?? capabilities.maxOutputTokens);
|
|
283
|
+
const safetyMargin = d.safetyMargin ?? 64;
|
|
284
|
+
const output = outputReserve(capabilities, desiredOutputTokens, safetyMargin);
|
|
285
|
+
if (tokenLimited &&
|
|
286
|
+
remaining <= output &&
|
|
287
|
+
output > 0 &&
|
|
288
|
+
capabilities.contextWindow > output + safetyMargin)
|
|
289
|
+
throw runTokenError(1, output);
|
|
290
|
+
const budget = budgetManager.plan({
|
|
291
|
+
capabilities,
|
|
292
|
+
remainingRunTokens: remaining,
|
|
293
|
+
desiredOutputTokens,
|
|
294
|
+
safetyMargin,
|
|
295
|
+
});
|
|
296
|
+
const windowInputTokens = budget.history.contextWindow - budget.outputTokens - budget.history.safetyMargin;
|
|
297
|
+
while (true) {
|
|
298
|
+
const { systemPrompt } = promptComposer.compose(prompt);
|
|
299
|
+
const result = await d.builder
|
|
300
|
+
.build({
|
|
301
|
+
surface,
|
|
302
|
+
model: input.config.model,
|
|
303
|
+
binding,
|
|
304
|
+
capabilities,
|
|
305
|
+
responsesPolicy: input.config.responses,
|
|
306
|
+
systemPrompt,
|
|
307
|
+
tools,
|
|
308
|
+
background: [...background]
|
|
309
|
+
.sort((a, b) => b.priority - a.priority || a.id.localeCompare(b.id))
|
|
310
|
+
.map((section) => section.text),
|
|
311
|
+
budget: budget.history,
|
|
312
|
+
selection: {
|
|
313
|
+
requiredTurnId: input.turnId,
|
|
314
|
+
relevantTurnIds: overflowRequest || input.config.checkpoint
|
|
315
|
+
? []
|
|
316
|
+
: contributions.flatMap((c) => c.relevantTurnIds),
|
|
317
|
+
keepRecentTurns: overflowRequest || input.config.checkpoint ? 0 : (d.keepRecentTurns ?? 8),
|
|
318
|
+
...(input.config.checkpoint ? { keepSummaries: false } : {}),
|
|
319
|
+
},
|
|
320
|
+
...(frozen ? { frozenRequest: frozen } : {}),
|
|
321
|
+
...(input.pruneToolResults ? { pruneToolResults: true } : {}),
|
|
322
|
+
}, formatToolResult)
|
|
323
|
+
.catch((error) => {
|
|
324
|
+
if (error instanceof ContinuationBudgetError) {
|
|
325
|
+
if (tokenLimited && error.requiredTokens <= windowInputTokens)
|
|
326
|
+
throw runTokenError(error.requiredTokens);
|
|
327
|
+
throw new ContinuationBudgetError(error.requiredTokens, windowInputTokens);
|
|
328
|
+
}
|
|
329
|
+
throw error;
|
|
330
|
+
});
|
|
331
|
+
if (result.status === 'blocked')
|
|
332
|
+
throw new RuntimeError('CONTEXT_BLOCKED', 'pending tools');
|
|
333
|
+
if (result.status === 'over_budget') {
|
|
334
|
+
const trimmed = trimOptionalContext(prompt, background);
|
|
335
|
+
if (!trimmed) {
|
|
336
|
+
if (tokenLimited && result.requiredTokens <= windowInputTokens)
|
|
337
|
+
throw runTokenError(result.requiredTokens);
|
|
338
|
+
throw new BudgetError('CONTEXT_BUDGET_EXCEEDED', {
|
|
339
|
+
resource: 'context',
|
|
340
|
+
used: 0,
|
|
341
|
+
max: windowInputTokens,
|
|
342
|
+
required: result.requiredTokens,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
prompt = trimmed.prompt;
|
|
346
|
+
background = trimmed.background;
|
|
347
|
+
warnings.push(`${trimmed.source}: OPTIONAL_CONTEXT_DROPPED`);
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const assembly = {
|
|
351
|
+
messages: result.messages,
|
|
352
|
+
binding,
|
|
353
|
+
responses: result.responses,
|
|
354
|
+
tools,
|
|
355
|
+
model: input.config.model,
|
|
356
|
+
surfaceSeq: result.surfaceSeq,
|
|
357
|
+
selectedMessageIds: result.selectedMessageIds,
|
|
358
|
+
omittedMessageIds: result.omittedMessageIds,
|
|
359
|
+
providerVersions,
|
|
360
|
+
estimate: result.estimate,
|
|
361
|
+
outputReserve: budget.outputTokens,
|
|
362
|
+
contextWindow: capabilities.contextWindow,
|
|
363
|
+
windowInputTokens,
|
|
364
|
+
warnings,
|
|
365
|
+
};
|
|
366
|
+
return { ...assembly, assemblyHash: d.hash(assembly) };
|
|
367
|
+
}
|
|
368
|
+
function runTokenError(inputTokens, outputTokens = budget.outputTokens) {
|
|
369
|
+
return new BudgetError('RUN_BUDGET_EXCEEDED', modelTokenBudget(state.runState, input.config.limits.maxTotalTokens, state.runState.reservedTokens + inputTokens + outputTokens));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
assemble: (input) => assemble(input),
|
|
374
|
+
assembleSideContext(input, snapshot, previous) {
|
|
375
|
+
const { surface } = snapshot;
|
|
376
|
+
const incomplete = new Set(surface.groups.filter((group) => !group.complete).map((group) => group.assistantMessageId));
|
|
377
|
+
const boundary = surface.items.findIndex((item) => item.active && incomplete.has(item.message.id));
|
|
378
|
+
const items = boundary < 0 ? surface.items : surface.items.slice(0, boundary);
|
|
379
|
+
const retained = new Set(items.map((item) => item.message.id));
|
|
380
|
+
return assemble(input, undefined, {
|
|
381
|
+
previous,
|
|
382
|
+
snapshot: {
|
|
383
|
+
...snapshot,
|
|
384
|
+
surface: {
|
|
385
|
+
...surface,
|
|
386
|
+
items,
|
|
387
|
+
groups: surface.groups.filter((group) => retained.has(group.assistantMessageId)),
|
|
388
|
+
continuations: surface.continuations.filter((block) => retained.has(block.assistantMessageId)),
|
|
389
|
+
pendingRequestIds: [],
|
|
390
|
+
},
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
},
|
|
394
|
+
async rebuildAfterOverflow(input, previous) {
|
|
395
|
+
const state = await d.reader.read(input.agentSessionId, input.runId);
|
|
396
|
+
if (state.surface.continuations.some((block) => block.active &&
|
|
397
|
+
state.surface.items.find((item) => item.message.id === block.assistantMessageId)?.message
|
|
398
|
+
.turnId === input.turnId))
|
|
399
|
+
throw new RuntimeError('CONTINUATION_PREFIX_CHANGED', 'Cannot reset an active continuation');
|
|
400
|
+
return assemble(input, previous);
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
const phases = ['core', 'mode', 'tools', 'session', 'extensions'];
|
|
405
|
+
export function validateProvider(provider) {
|
|
406
|
+
if (!phases.includes(provider.phase) ||
|
|
407
|
+
(provider.phase === 'core' && provider.id !== 'core') ||
|
|
408
|
+
provider.timeoutMs < 1)
|
|
409
|
+
throw new RuntimeError('PROVIDER_CONFIG', 'invalid provider registration');
|
|
410
|
+
}
|
|
411
|
+
export function registerProviders(input) {
|
|
412
|
+
unique(input.map((provider) => provider.id), 'provider');
|
|
413
|
+
for (const provider of input)
|
|
414
|
+
validateProvider(provider);
|
|
415
|
+
for (const id of ['core', 'tools', 'session']) {
|
|
416
|
+
const provider = input.find((p) => p.id === id);
|
|
417
|
+
if (!provider?.required || provider.phase !== id)
|
|
418
|
+
throw new RuntimeError('PROVIDER_CONFIG', `${id} must be registered as required`);
|
|
419
|
+
}
|
|
420
|
+
return [...input].sort((a, b) => phases.indexOf(a.phase) - phases.indexOf(b.phase) ||
|
|
421
|
+
b.priority - a.priority ||
|
|
422
|
+
a.id.localeCompare(b.id));
|
|
423
|
+
}
|
|
424
|
+
async function collectContributions(providers, input) {
|
|
425
|
+
const warnings = [];
|
|
426
|
+
const contributions = [];
|
|
427
|
+
const providerVersions = {};
|
|
428
|
+
for (const p of providers) {
|
|
429
|
+
try {
|
|
430
|
+
const value = await collect(p, input);
|
|
431
|
+
if (value.providerId !== p.id ||
|
|
432
|
+
value.version !== p.version ||
|
|
433
|
+
value.prompt.some((section) => section.authority === 'core' && p.id !== 'core'))
|
|
434
|
+
throw new RuntimeError('PROVIDER_CONFLICT', 'invalid contribution identity/authority');
|
|
435
|
+
contributions.push(value);
|
|
436
|
+
providerVersions[p.id] = p.version;
|
|
437
|
+
}
|
|
438
|
+
catch (error) {
|
|
439
|
+
if (input.signal.aborted)
|
|
440
|
+
throw input.signal.reason;
|
|
441
|
+
if (error instanceof RuntimeError && error.code === 'PLUGIN_VERSION_UNAVAILABLE')
|
|
442
|
+
throw error;
|
|
443
|
+
if (p.required || (error instanceof RuntimeError && error.code === 'PROVIDER_CONFLICT')) {
|
|
444
|
+
const failure = new RuntimeError('CONTEXT_PROVIDER_FAILED', `${p.id}: provider failed`);
|
|
445
|
+
failure.cause = error;
|
|
446
|
+
throw failure;
|
|
447
|
+
}
|
|
448
|
+
warnings.push(`${p.id}: PROVIDER_FAILED`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return { contributions, warnings, versions: providerVersions };
|
|
452
|
+
}
|
|
453
|
+
function trimOptionalContext(prompt, background) {
|
|
454
|
+
const optional = [
|
|
455
|
+
...prompt.filter((section) => !section.required && section.authority !== 'core'),
|
|
456
|
+
...background.filter((section) => !section.required),
|
|
457
|
+
].sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id))[0];
|
|
458
|
+
if (!optional)
|
|
459
|
+
return;
|
|
460
|
+
return {
|
|
461
|
+
prompt: prompt.filter((section) => section.id !== optional.id),
|
|
462
|
+
background: background.filter((section) => section.id !== optional.id),
|
|
463
|
+
source: optional.source,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
async function collect(provider, input) {
|
|
467
|
+
input.signal.throwIfAborted();
|
|
468
|
+
const controller = new AbortController();
|
|
469
|
+
let timer;
|
|
470
|
+
const abort = () => controller.abort(input.signal.reason);
|
|
471
|
+
input.signal.addEventListener('abort', abort, { once: true });
|
|
472
|
+
try {
|
|
473
|
+
return await Promise.race([
|
|
474
|
+
provider.collect({ ...input, signal: controller.signal }),
|
|
475
|
+
new Promise((_, reject) => {
|
|
476
|
+
controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });
|
|
477
|
+
timer = setTimeout(() => controller.abort(new RuntimeError('PROVIDER_TIMEOUT', 'provider timeout')), provider.timeoutMs);
|
|
478
|
+
}),
|
|
479
|
+
]);
|
|
480
|
+
}
|
|
481
|
+
finally {
|
|
482
|
+
clearTimeout(timer);
|
|
483
|
+
input.signal.removeEventListener('abort', abort);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
function unique(ids, kind) {
|
|
487
|
+
if (new Set(ids).size !== ids.length)
|
|
488
|
+
throw new RuntimeError('PROVIDER_CONFLICT', `duplicate ${kind} ID`);
|
|
489
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export interface HostEnvironmentInfo {
|
|
2
|
+
readonly platform: NodeJS.Platform;
|
|
3
|
+
readonly arch: string;
|
|
4
|
+
readonly osRelease?: string;
|
|
5
|
+
readonly pathSep?: string;
|
|
6
|
+
readonly availableReadonlyCommands?: readonly string[];
|
|
7
|
+
readonly missingReadonlyCommands?: readonly string[];
|
|
8
|
+
readonly availableRuntimes?: readonly string[];
|
|
9
|
+
readonly workspaceRoot?: string;
|
|
10
|
+
readonly workSubpath?: string;
|
|
11
|
+
readonly workspaceEntries?: readonly string[];
|
|
12
|
+
readonly isGitRepo?: boolean;
|
|
13
|
+
readonly gitBranch?: string;
|
|
14
|
+
readonly mcpServers?: readonly {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly discovery: 'ready' | 'auth_required' | 'pending_trust' | 'trust_required' | 'unavailable';
|
|
17
|
+
readonly toolCount: number;
|
|
18
|
+
readonly error?: string;
|
|
19
|
+
}[];
|
|
20
|
+
readonly sandbox?: {
|
|
21
|
+
readonly backend: string;
|
|
22
|
+
readonly image?: string;
|
|
23
|
+
readonly containerWorkDir?: string;
|
|
24
|
+
readonly network?: string;
|
|
25
|
+
readonly fallbackActive?: boolean;
|
|
26
|
+
readonly probeSummary?: string;
|
|
27
|
+
readonly capAdd?: readonly string[];
|
|
28
|
+
readonly tmpNoexec?: boolean;
|
|
29
|
+
readonly kvmActive?: boolean;
|
|
30
|
+
readonly targetServicesAvailable?: boolean;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export interface TeamHintPromptInput {
|
|
34
|
+
readonly force?: boolean;
|
|
35
|
+
readonly concurrency?: number;
|
|
36
|
+
readonly maxMembers?: number;
|
|
37
|
+
}
|
|
38
|
+
export declare function buildCoreSystemPrompt(): string;
|
|
39
|
+
export declare function buildExecutionPolicyPrompt(): string;
|
|
40
|
+
export declare function buildEnvironmentContext(env: HostEnvironmentInfo): string;
|
|
41
|
+
export declare function buildTeamHintPrompt(hint: TeamHintPromptInput): string;
|
|
42
|
+
export declare function buildPlannerModeInstructions(hasWorkspaceTools: boolean): string;
|