@saturn-universe/context 0.1.2-dev.5 → 0.1.2-dev.9

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/dist/history.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { BACKGROUND_CONTEXT_PREFIX, ENDED_HISTORY_CONTEXT_PREFIX, BudgetError, canonicalJson, pruneToolOutcome, RuntimeError, modelConfiguration, selectPrunableToolCallIds, } from '@saturn-universe/core';
2
2
  import { formatModelToolOutcome, modelToolOutcome } from './tool-output.js';
3
+ import { projectRemovedToolHistory } from './removed-tool-history.js';
3
4
  export class ContinuationBudgetError extends BudgetError {
4
5
  requiredTokens;
5
6
  allowedTokens;
@@ -83,6 +84,11 @@ export function createHistoryBuilder(d) {
83
84
  return outcome;
84
85
  }
85
86
  : defaultOutcome;
87
+ // An existing chain must keep the projection that produced its original prefix.
88
+ const recordedPlan = input.frozenRequest?.responses ?? currentBlocks[0]?.requestPlan;
89
+ const removedHistory = !recordedPlan || recordedPlan.projectedToolHistory
90
+ ? projectRemovedToolHistory(input, active)
91
+ : undefined;
86
92
  while (true) {
87
93
  const items = active.filter((item) => selected.has(item.message.turnId));
88
94
  const omitted = active.filter((item) => !selected.has(item.message.turnId));
@@ -109,7 +115,10 @@ export function createHistoryBuilder(d) {
109
115
  return pruned;
110
116
  return basePresent(result);
111
117
  };
112
- const responses = await plan(input, items, omitted.length > 0, chain, anyPruned, background, d, present, basePresent);
118
+ const projected = items.some(({ message }) => removedHistory?.assistants.has(message.id))
119
+ ? removedHistory
120
+ : undefined;
121
+ const responses = await plan(input, items, omitted.length > 0, chain, anyPruned, background, d, present, basePresent, projected);
113
122
  const replayed = new Map();
114
123
  if (formatToolResult) {
115
124
  // An appended native prefix already contains the presentation that was sent.
@@ -120,7 +129,15 @@ export function createHistoryBuilder(d) {
120
129
  replayed.set(item.call_id, item.output);
121
130
  }
122
131
  }
123
- const messages = historyMessages(items, input.systemPrompt, background, (result, providerCallId) => {
132
+ const history = projected
133
+ ? items.flatMap((item) => {
134
+ const message = projected.assistants.get(item.message.id) ?? item.message;
135
+ return message.role === 'tool' && projected.calls.has(message.result.toolCallId)
136
+ ? []
137
+ : [{ ...item, message }];
138
+ })
139
+ : items;
140
+ const messages = historyMessages(history, input.systemPrompt, background, (result, providerCallId) => {
124
141
  const pruned = prunedOutcomes.get(result);
125
142
  if (pruned)
126
143
  return pruned;
@@ -187,7 +204,7 @@ export function createHistoryBuilder(d) {
187
204
  },
188
205
  };
189
206
  }
190
- async function plan(input, items, trimmed, chain, prunedToolResults, background, d, present, basePresent) {
207
+ async function plan(input, items, trimmed, chain, prunedToolResults, background, d, present, basePresent, projected) {
191
208
  const blocks = input.surface.continuations.filter((block) => block.active && items.some((item) => item.message.id === block.assistantMessageId));
192
209
  const latest = blocks.at(-1);
193
210
  const backgroundDigest = input.frozenRequest
@@ -227,6 +244,8 @@ async function plan(input, items, trimmed, chain, prunedToolResults, background,
227
244
  reason = 'prefix_changed';
228
245
  else if (prunedToolResults)
229
246
  reason = 'history_trimmed';
247
+ else if (projected && !latest?.requestPlan.projectedToolHistory)
248
+ reason = 'prefix_changed';
230
249
  const prunerReset = prunedToolResults && reason === 'history_trimmed';
231
250
  if (chain && reason && !prunerReset)
232
251
  throw new RuntimeError('CONTINUATION_PREFIX_CHANGED', 'cannot reset inside active native chain');
@@ -244,7 +263,7 @@ async function plan(input, items, trimmed, chain, prunedToolResults, background,
244
263
  let decision = { kind: 'new' };
245
264
  let epochId;
246
265
  if (latest && !reason) {
247
- const priorFullInput = await reconstructPriorFullInput(input, items, blocks, latest, background, encode);
266
+ const priorFullInput = await reconstructPriorFullInput(input, items, blocks, latest, background, encode, projected);
248
267
  const replay = latest.state.outputItems.map((item) => codec.replayItem(item));
249
268
  fullInput = [...priorFullInput, ...replay.map((item) => item.input)];
250
269
  replaySources = [
@@ -284,7 +303,7 @@ async function plan(input, items, trimmed, chain, prunedToolResults, background,
284
303
  decision = { kind: 'reset', atTurnId: input.selection.requiredTurnId, reason };
285
304
  const older = items.filter((item) => item.message.turnId !== input.selection.requiredTurnId);
286
305
  if (older.length)
287
- await appendEndedHistory(fullInput, older, input.surface.continuations, present);
306
+ await appendEndedHistory(fullInput, older, input.surface.continuations, present, projected);
288
307
  await appendItems(fullInput, items.filter((item) => item.message.turnId === input.selection.requiredTurnId), encode, reason === 'compacted' || reason === 'history_trimmed');
289
308
  }
290
309
  else
@@ -321,6 +340,7 @@ async function plan(input, items, trimmed, chain, prunedToolResults, background,
321
340
  ? { instructions: input.systemPrompt }
322
341
  : {}),
323
342
  ...(prunedToolResults && decision.kind === 'reset' ? { prunedToolResults: true } : {}),
343
+ ...(projected ? { projectedToolHistory: true } : {}),
324
344
  fullInput,
325
345
  fullInputDigest: d.hash(fullInput),
326
346
  configurationDigest,
@@ -329,16 +349,21 @@ async function plan(input, items, trimmed, chain, prunedToolResults, background,
329
349
  transport: { kind: 'local_replay' },
330
350
  };
331
351
  }
332
- async function appendEndedHistory(output, older, continuations, present) {
352
+ async function appendEndedHistory(output, older, continuations, present, projected) {
333
353
  const ended = [];
334
- for (const { message } of older) {
354
+ for (const item of older) {
355
+ const { id } = item.message;
356
+ const replacement = projected?.assistants.get(id);
357
+ const message = replacement ?? item.message;
358
+ if (message.role === 'tool' && projected?.calls.has(message.result.toolCallId))
359
+ continue;
335
360
  const outcome = message.role === 'tool' ? await present(message.result) : undefined;
336
361
  ended.push({
337
362
  sourceMessageId: message.id,
338
363
  message: message.role === 'tool' && outcome !== message.result.outcome
339
364
  ? { ...message, result: { ...message.result, outcome } }
340
365
  : message,
341
- nativePhases: continuations
366
+ nativePhases: (replacement ? [] : continuations)
342
367
  .filter((block) => block.assistantMessageId === message.id)
343
368
  .flatMap((block) => block.state.outputItems.flatMap((outputItem) => outputItem.kind === 'message' ? [outputItem.value.phase ?? null] : [])),
344
369
  });
@@ -354,7 +379,7 @@ async function appendEndedHistory(output, older, continuations, present) {
354
379
  ],
355
380
  });
356
381
  }
357
- async function reconstructPriorFullInput(input, items, blocks, latest, background, encode) {
382
+ async function reconstructPriorFullInput(input, items, blocks, latest, background, encode, projected) {
358
383
  const epochBlocks = blocks.filter((block) => block.state.epochId === latest.state.epochId);
359
384
  const first = epochBlocks[0];
360
385
  if (!first)
@@ -389,7 +414,7 @@ async function reconstructPriorFullInput(input, items, blocks, latest, backgroun
389
414
  const resetReason = first.requestPlan.decision.reason;
390
415
  const older = firstItems.filter((item) => item.message.turnId !== resetTurnId);
391
416
  if (older.length)
392
- await appendEndedHistory(reconstructed, older, input.surface.continuations, presentFirst);
417
+ await appendEndedHistory(reconstructed, older, input.surface.continuations, presentFirst, first.requestPlan.projectedToolHistory ? projected : undefined);
393
418
  await appendItems(reconstructed, firstItems.filter((item) => item.message.turnId === resetTurnId), encodeFirst, resetReason === 'compacted' || resetReason === 'history_trimmed');
394
419
  }
395
420
  else {
package/dist/index.js CHANGED
@@ -299,6 +299,8 @@ export function createContextComposer(d) {
299
299
  const result = await d.builder
300
300
  .build({
301
301
  surface,
302
+ ...(input.config.modeRef ? { modeRef: input.config.modeRef } : {}),
303
+ ...(state.historicalRunModes ? { historicalRunModes: state.historicalRunModes } : {}),
302
304
  model: input.config.model,
303
305
  binding,
304
306
  capabilities,
@@ -0,0 +1,6 @@
1
+ import type { AssistantMessage, HistoryBuildInput, MessageId, SurfaceItem, ToolCallId } from '@saturn-universe/core';
2
+ export interface RemovedToolHistory {
3
+ readonly assistants: ReadonlyMap<MessageId, AssistantMessage>;
4
+ readonly calls: ReadonlySet<ToolCallId>;
5
+ }
6
+ export declare function projectRemovedToolHistory({ modeRef, historicalRunModes, tools, selection, }: Pick<HistoryBuildInput, 'modeRef' | 'historicalRunModes' | 'tools' | 'selection'>, items: readonly SurfaceItem[]): RemovedToolHistory | undefined;
@@ -0,0 +1,58 @@
1
+ import { canonicalJson } from '@saturn-universe/core';
2
+ import { toolResultTextPage } from './tool-output.js';
3
+ const argumentBytes = 512;
4
+ const resultBytes = 1024;
5
+ export function projectRemovedToolHistory({ modeRef, historicalRunModes, tools, selection, }, items) {
6
+ if (!modeRef || !historicalRunModes)
7
+ return undefined;
8
+ const available = new Set(tools.map(({ canonicalName }) => canonicalName));
9
+ const assistants = new Map();
10
+ const calls = new Set();
11
+ const outcomes = new Map();
12
+ for (const { message } of items) {
13
+ if (message.role === 'tool')
14
+ outcomes.set(message.result.toolCallId, message.result.outcome);
15
+ }
16
+ for (const { message } of items) {
17
+ const historicalMode = historicalRunModes[message.runId];
18
+ if (message.role !== 'assistant' ||
19
+ message.turnId === selection.requiredTurnId ||
20
+ !historicalMode ||
21
+ historicalMode === modeRef)
22
+ continue;
23
+ const removed = message.toolCalls.filter(({ toolName }) => !available.has(toolName));
24
+ if (!removed.length)
25
+ continue;
26
+ for (const call of removed)
27
+ calls.add(call.id);
28
+ assistants.set(message.id, {
29
+ ...message,
30
+ toolCalls: message.toolCalls.filter(({ id }) => !calls.has(id)),
31
+ content: [
32
+ ...message.content,
33
+ ...removed.map((call) => ({
34
+ type: 'text',
35
+ text: summarize(call, outcomes.get(call.id)),
36
+ })),
37
+ ],
38
+ });
39
+ }
40
+ return assistants.size ? { assistants, calls } : undefined;
41
+ }
42
+ function summarize(call, outcome) {
43
+ const args = call.arguments.kind === 'json' ? canonicalJson(call.arguments.value) : call.arguments.raw;
44
+ const bytes = Buffer.from(args);
45
+ let end = Math.min(bytes.length, argumentBytes);
46
+ while (end < bytes.length && (bytes[end] & 0xc0) === 0x80)
47
+ end--;
48
+ const argumentsText = bytes.toString('utf8', 0, end) + (end < bytes.length ? '… [truncated]' : '');
49
+ const page = outcome && toolResultTextPage(outcome, { maxBytes: resultBytes });
50
+ const resultText = page
51
+ ? page.text + (page.nextByteOffset === null ? '' : '… [truncated]')
52
+ : '(unavailable)';
53
+ return [
54
+ `[Historical tool unavailable in the current Mode: ${call.toolName}]`,
55
+ `Arguments: ${argumentsText}`,
56
+ `Result${outcome ? ` (${outcome.status})` : ''}: ${resultText}`,
57
+ ].join('\n');
58
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@saturn-universe/context",
3
- "version": "0.1.2-dev.5",
3
+ "version": "0.1.2-dev.9",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"
8
8
  ],
9
9
  "dependencies": {
10
- "@saturn-universe/core": "0.1.2-dev.5"
10
+ "@saturn-universe/core": "0.1.2-dev.9"
11
11
  },
12
12
  "exports": {
13
13
  ".": {