Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 95 additions & 1 deletion scripts/verify/versioned-context.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,15 @@ function createAgent(workspace, store, options = {}) {
},
sessionStore: store,
workspaceDir: workspace,
taskIntent: true,
taskIntent: options.taskIntent ?? true,
model: 'scripted-versioned',
contextTokens: 32_000,
maxTokens: 1024,
baseSystemPrompt: 'Follow the authenticated current user and use source evidence.',
domainPrompt: false,
enableSteering: false,
enableFollowUpGuard: false,
...(options.reasoning ? { reasoning: options.reasoning } : {}),
...(options.hooks ? { hooks: options.hooks } : {}),
});
return { agent, modelRequests, summaryRequests };
Expand Down Expand Up @@ -399,6 +400,98 @@ async function testProgressiveStages(workspace) {
);
}

async function testPressureContinuation(workspace) {
const session = 'pressure-continuation';
const visiblePrefix = 'The measured size is 4096 bytes. ';
const privateReasoning = 'Discarded private reasoning. '.repeat(180);
const userText = 'Report the measured byte count and verification status.';
await usingAgent(
workspace,
async ({ agent, store }) => {
const receipt = 'Observed bytes=4096.\n' + 'Repeated archived output.\n'.repeat(350);
await add(
store,
session,
'user',
[{ type: 'tool_result', tool_use_id: 'archived', name: 'read_file', content: receipt }],
'legacy'
);
await add(store, session, 'assistant', 'Earlier analysis. '.repeat(1100));
await add(store, session, 'user', userText);
const input = {
sessionKey: session,
window: 16_000,
output: 4096,
minOutput: 1024,
force: true,
policyKey: 'pressure-continuation-probe',
measure: (messages) => 13_350 + Math.ceil(Buffer.byteLength(JSON.stringify(messages)) / 4),
summarize: async () =>
JSON.stringify([
{ kind: 'observation', text: 'Observed bytes=4096.', sourceIds: ['s1'] },
]),
signal: AbortSignal.timeout(8_000),
};
const pipeline = new VersionedContextPipeline(store);
const projection = await pipeline.prepare(input);
assert(projection.stages.includes('S5'));
assert(projection.output >= 2000, `only ${projection.output} tokens left to answer`);
assert.match(JSON.stringify(projection.messages), /Observed bytes=4096/);
assert(JSON.stringify(projection.messages).includes(userText));
assert.equal((await store.sourceMessages(session))[0].message.content[0].content, receipt);

const oversized = 'Required user text. '.repeat(1400);
await add(store, 'oversized-user', 'user', oversized);
await assert.rejects(pipeline.prepare({ ...input, sessionKey: 'oversized-user' }), {
code: 'PROVIDER_CONTEXT_OVERFLOW',
});
assert.equal((await store.sourceMessages('oversized-user'))[0].message.content, oversized);

const reply = await agent.chat('live-continuation', userText, {
taskFlow: false,
maxTurns: 6,
});
assert.equal(reply.response, `${visiblePrefix}Verification complete.`);
const original = await store.sourceMessages('live-continuation');
assert.equal(
original.filter(({ message }) => message.outputLimit === 'continuation').length,
2
);
assert(original.some(({ message }) => message.thinking?.join('').includes(privateReasoning)));
},
{
taskIntent: false,
reasoning: 'medium',
onMain(request, count) {
const sent = JSON.stringify(request.messages);
assert(sent.includes(userText));
assert.doesNotMatch(sent, /Discarded private reasoning/);
if (count === 1) {
assert.equal(request.reasoning, 'medium');
return { stopReason: 'max_tokens', content: [], thinking: [privateReasoning] };
}
assert.equal(request.reasoning, 'low');
if (count === 2) {
assert.match(sent, /used the entire output budget on private reasoning/);
return {
stopReason: 'max_tokens',
content: [text(`${visiblePrefix}<think>${privateReasoning}`)],
thinking: [privateReasoning],
};
}
assert.equal(count, 3);
assert.match(sent, /The measured size is 4096 bytes/);
assert.match(sent, /previous response was truncated/);
assert.doesNotMatch(sent, /used the entire output budget on private reasoning/);
return response(text('Verification complete.'));
},
}
);
console.log(
'PASS pressured checkpoints reserve output and cutoff retries retain only visible context'
);
}

async function testConcurrentSummary(workspace) {
const summaryStarted = latch();
const releaseSummary = latch();
Expand Down Expand Up @@ -1266,6 +1359,7 @@ const workspace = await fs.realpath(
try {
for (const [directory, test] of [
['progressive', testProgressiveStages],
['pressure-continuation', testPressureContinuation],
['checkpoint', testConcurrentSummary],
['source-validation', testSummarySourceValidation],
['approval', testApproval],
Expand Down
3 changes: 3 additions & 0 deletions src/contracts/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ export interface Message {

thinking?: string[];

/** Runtime metadata for projecting a truncated reply and its one-shot retry prompt. */
outputLimit?: 'truncated' | 'continuation';

/**
* Model id the gateway reported for this assistant turn, when the response
* included one. Absent on user messages and on providers that omit it.
Expand Down
4 changes: 3 additions & 1 deletion src/core/loop/agent-loop-llm-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,9 @@ export async function executeLlmTurn(params: ExecuteLlmTurnParams): Promise<Exec
if (
state.reasoningOverrideNextTurn &&
effectiveReasoning !== undefined &&
effectiveReasoning !== null
effectiveReasoning !== null &&
effectiveReasoning !== 'off' &&
(effectiveReasoning !== 'minimal' || state.reasoningOverrideNextTurn === 'off')
) {
effectiveReasoning = state.reasoningOverrideNextTurn;
}
Expand Down
26 changes: 18 additions & 8 deletions src/core/loop/agent-loop-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import {
shouldNudgeMissingToolInvocation,
} from './agent-loop-assistant-turn.js';
import { buildNamedWebToolMatcher } from '../../prompts/plan-detection.js';
import { stripThinkingTagsKeepVisible } from '../llm/inline-thinking-stream.js';
import {
THINKING_ONLY_RETRY_BUDGET,
decidePostLlmAction,
nextThinkingOnlyRetryAttempts,
thinkingOnlyReasoningOverride,
} from './agent-loop-post-llm.js';
import {
escalateOutputTokens,
Expand Down Expand Up @@ -259,7 +261,9 @@ export async function processLlmResponse(
turnTextParts.push(intentResponse.answer);
assistantContent.push({ type: 'text', text: intentResponse.answer });
}
const turnText = turnTextParts.join('');
const turnText = outputLimited
? stripThinkingTagsKeepVisible(turnTextParts.join(''))
: turnTextParts.join('');

const hasThinkingOnly = isThinkingOnlyAssistantTurn({
visibleText: turnText,
Expand All @@ -275,14 +279,15 @@ export async function processLlmResponse(
timestamp: Date.now(),
...(messageThinkingChunks.length > 0 ? { thinking: [...messageThinkingChunks] } : {}),
...(servedModel ? { model: servedModel } : {}),
...(outputLimited ? { outputLimit: 'truncated' as const } : {}),
};

if (!hasThinkingOnly) {
assistantBuffer.push(assistantMsg);
}

let visibleAssistantText = buildVisibleAssistantText({
textParts: turnTextParts,
textParts: [turnText],
// A cutoff fragment, and the piece that continues one, must keep the
// whitespace the model actually emitted so the stitch has no extra gap
// and does not eat the gap the model already wrote.
Expand Down Expand Up @@ -532,17 +537,22 @@ export async function processLlmResponse(
case 'continuation': {
state.outputContinuationCount++;
const raised = escalateOutputTokens(state.outputTokenBudget, state.outputTokenCeiling);
const grew = raised > state.outputTokenBudget;
if (grew) state.outputTokenBudget = raised;
state.outputTokenBudget = raised;
if (postLlmAction.mode === 'thinking' || messageThinkingChunks.length > 0) {
state.reasoningOverrideNextTurn = thinkingOnlyReasoningOverride(
params.provider,
state.outputContinuationCount - 1,
params.modelId
);
}
if (postLlmAction.mode !== 'thinking') {
state.carriedAssistantText = stitchedAssistantText;
}
const systemText = grew
? `${postLlmAction.systemText} A larger output budget is available for this retry.`
: postLlmAction.systemText;
// Flush the truncated assistant (stop length → max_tokens) before the
// notice so stream-json hosts see the cutoff on that message.
state.pendingMessages = [buildCorrectionMessage(systemText)];
state.pendingMessages = [
{ ...buildCorrectionMessage(postLlmAction.systemText), outputLimit: 'continuation' },
];
pushTurnEnd();
push({
type: 'output_continuation',
Expand Down
107 changes: 80 additions & 27 deletions src/core/session/versioned-context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHash, randomUUID } from 'node:crypto';
import type { Message } from '../../contracts/messages.js';
import type { LLMContentBlock } from '../../contracts/llm-messages.js';
import { createCompactionSummaryMessage } from '../../contracts/messages.js';
import type {
ContextCheckpoint,
Expand All @@ -10,6 +11,7 @@ import type {
import { ErrorCode, MossError } from '../../errors.js';
import { hashContextSources, type VersionedSessionStore } from './versioned-session-store.js';
import { abortable } from '../agent/abort.js';
import { stripThinkingTagsKeepVisible } from '../llm/inline-thinking-stream.js';
import { CONTEXT_CLAIMS_TOOL } from './context-claim-declaration.js';
import { TURN_DECISION_TOOL } from './task-intent-state.js';
import {
Expand Down Expand Up @@ -62,7 +64,16 @@ function trustedUser(source: ContextSourceMessage): boolean {
export function contextSourceView(snapshot: VersionedContextSnapshot): ContextSourceMessage[] {
const internalCalls = new Set<string>();
const businessCalls = new Set<string>();
for (const { message } of snapshot.messages) {
// A retry instruction applies only until it is replaced or the model or
// user advances the turn. The SQLite archive keeps every original message.
let latestContinuationId: string | undefined;
for (const source of snapshot.messages) {
const { message } = source;
if (source.origin === 'runtime' && asMessage(source).outputLimit === 'continuation') {
latestContinuationId = source.id;
} else if (trustedUser(source) || message.role === 'assistant' || source.origin === 'tool') {
latestContinuationId = undefined;
}
if (typeof message.content === 'string') continue;
for (const block of message.content) {
if (block.type !== 'tool_use') continue;
Expand All @@ -75,14 +86,27 @@ export function contextSourceView(snapshot: VersionedContextSnapshot): ContextSo
return snapshot.messages.flatMap((source) => {
const message = asMessage(source);
if (isCompactionSummaryMessage(message)) return [];
if (
source.origin === 'runtime' &&
message.outputLimit === 'continuation' &&
source.id !== latestContinuationId
)
return [];
const affected = snapshot.corrections.some(
(record) =>
source.ordinal >= record.fromOrdinal &&
(source.ordinal <= record.throughOrdinal ||
(source.generatedRevision !== undefined && source.generatedRevision < record.revision))
);
const hideProse = affected && !trustedUser(source) && source.origin !== 'tool';
if (typeof source.message.content === 'string') return hideProse ? [] : [source];
const truncated = message.role === 'assistant' && message.outputLimit === 'truncated';
if (typeof source.message.content === 'string') {
if (hideProse) return [];
if (!truncated) return [source];
const content = stripThinkingTagsKeepVisible(source.message.content);
const { thinking: _thinking, ...visible } = source.message;
return content.trim() ? [{ ...source, message: { ...visible, content } }] : [];
}
const content = source.message.content.filter((block) => {
if (block.type === 'tool_use') return !internalCalls.has(block.id);
if (block.type === 'tool_result') {
Expand All @@ -95,10 +119,23 @@ export function contextSourceView(snapshot: VersionedContextSnapshot): ContextSo
}
return !hideProse;
});
if (!content.length) return [];
if (!hideProse && content.length === source.message.content.length) return [source];
const visibleContent = truncated
? content.flatMap<LLMContentBlock>((block) => {
if (block.type !== 'text') return [block];
const text = stripThinkingTagsKeepVisible(block.text);
return text.trim() ? [{ ...block, text }] : [];
})
: content;
if (!visibleContent.length) return [];
if (!truncated && !hideProse && content.length === source.message.content.length)
return [source];
const { thinking: _thinking, ...visible } = source.message;
return [{ ...source, message: { ...visible, content } }];
return [
{
...source,
message: { ...visible, content: visibleContent },
},
];
});
}

Expand All @@ -124,10 +161,15 @@ function correctionMessage(snapshot: VersionedContextSnapshot): Message[] {
];
}

interface SummaryEvidenceView {
evidence?: ContextSourceMessage;
historical?: HistoricalSourceExcerpt[];
compactEvidence?: boolean;
}

function summaryMessage(
checkpoint: ContextCheckpoint,
evidence?: ContextSourceMessage,
historical: HistoricalSourceExcerpt[] = []
{ evidence, historical = [], compactEvidence = false }: SummaryEvidenceView = {}
): Message {
const excerpts =
evidence && Array.isArray(evidence.message.content)
Expand All @@ -138,8 +180,8 @@ function summaryMessage(
limitToolOutput(
part.content,
evidence.id,
HISTORICAL_TOOL_HEAD_CHARS,
HISTORICAL_TOOL_TAIL_CHARS
compactEvidence ? 240 : HISTORICAL_TOOL_HEAD_CHARS,
compactEvidence ? 80 : HISTORICAL_TOOL_TAIL_CHARS
),
]
: []
Expand Down Expand Up @@ -318,6 +360,10 @@ export class VersionedContextPipeline {
const policy = `${SUMMARY_POLICY}:${input.policyKey}`;
const margin = Math.max(128, Math.floor(input.window * 0.02));
const capacity = input.window - margin - input.output;
const preferredOutput = Math.min(
input.output,
Math.max(input.minOutput, Math.min(2048, Math.floor(input.window / 8)))
);
const stages: string[] = [];
const complete = (rows: Message[]) => [...corrections, ...rows, ...(input.ephemeral ?? [])];
const fit = (messages: Message[]) => {
Expand Down Expand Up @@ -397,25 +443,32 @@ export class VersionedContextPipeline {
focus
)
: [];
if (historical.length) {
const withHistory = fit(
complete([summaryMessage(checkpoint, evidence, historical), ...tail])
);
if (withHistory.legal && withHistory.tokens < selected.tokens) {
return { ...withHistory, evidence, historical };
}
}
if (evidence) {
const withEvidence = fit(complete([summaryMessage(checkpoint, evidence), ...tail]));
if (withEvidence.legal && withEvidence.tokens < selected.tokens) {
return { ...withEvidence, evidence, historical: [] };
}
const views: SummaryEvidenceView[] = [
{ evidence, historical },
...(evidence && historical.length
? [{ evidence, historical, compactEvidence: true }, { historical }, { evidence }]
: []),
...(evidence ? [{ evidence, compactEvidence: true }] : []),
];
let best:
| (ReturnType<typeof fit> & {
evidence?: ContextSourceMessage;
historical: HistoricalSourceExcerpt[];
})
| undefined;
for (const view of views) {
const next = fit(complete([summaryMessage(checkpoint, view), ...tail]));
if (!next.legal || next.tokens >= selected.tokens) continue;
const projection = { ...next, evidence: view.evidence, historical: view.historical ?? [] };
// Reduce optional excerpts before agreeing to an output cap that can
// spend the entire response on reasoning. Keep the durable checkpoint.
if (next.output >= preferredOutput) return projection;
if (!best || next.output > best.output) best = projection;
}
return {
...fit(complete([summaryMessage(checkpoint), ...tail])),
evidence: undefined,
historical: [],
};
const minimal = fit(complete([summaryMessage(checkpoint), ...tail]));
if (!best || (minimal.legal && minimal.output > best.output))
return { ...minimal, evidence: undefined, historical: [] };
return best;
};
if (isCompatible) {
const projection = projected(candidate);
Expand Down
Loading