diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index 1db503a4..fce7e9a7 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -117,7 +117,7 @@ function createAgent(workspace, store, options = {}) { }, sessionStore: store, workspaceDir: workspace, - taskIntent: true, + taskIntent: options.taskIntent ?? true, model: 'scripted-versioned', contextTokens: 32_000, maxTokens: 1024, @@ -125,6 +125,7 @@ function createAgent(workspace, store, options = {}) { domainPrompt: false, enableSteering: false, enableFollowUpGuard: false, + ...(options.reasoning ? { reasoning: options.reasoning } : {}), ...(options.hooks ? { hooks: options.hooks } : {}), }); return { agent, modelRequests, summaryRequests }; @@ -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}${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(); @@ -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], diff --git a/src/contracts/messages.ts b/src/contracts/messages.ts index 7cbf0198..32555aaf 100644 --- a/src/contracts/messages.ts +++ b/src/contracts/messages.ts @@ -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. diff --git a/src/core/loop/agent-loop-llm-call.ts b/src/core/loop/agent-loop-llm-call.ts index 2fd8d1ab..4f90e90b 100644 --- a/src/core/loop/agent-loop-llm-call.ts +++ b/src/core/loop/agent-loop-llm-call.ts @@ -157,7 +157,9 @@ export async function executeLlmTurn(params: ExecuteLlmTurnParams): Promise 0 ? { thinking: [...messageThinkingChunks] } : {}), ...(servedModel ? { model: servedModel } : {}), + ...(outputLimited ? { outputLimit: 'truncated' as const } : {}), }; if (!hasThinkingOnly) { @@ -282,7 +287,7 @@ export async function processLlmResponse( } 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. @@ -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', diff --git a/src/core/session/versioned-context.ts b/src/core/session/versioned-context.ts index 285a3a38..364a92bb 100644 --- a/src/core/session/versioned-context.ts +++ b/src/core/session/versioned-context.ts @@ -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, @@ -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 { @@ -62,7 +64,16 @@ function trustedUser(source: ContextSourceMessage): boolean { export function contextSourceView(snapshot: VersionedContextSnapshot): ContextSourceMessage[] { const internalCalls = new Set(); const businessCalls = new Set(); - 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; @@ -75,6 +86,12 @@ 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 && @@ -82,7 +99,14 @@ export function contextSourceView(snapshot: VersionedContextSnapshot): ContextSo (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') { @@ -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((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 }, + }, + ]; }); } @@ -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) @@ -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 ), ] : [] @@ -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[]) => { @@ -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 & { + 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);