@ponythewhite/base-context 1.0.14 → 1.0.15
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/CHANGELOG.md +9 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/{bundled-modules-UODO7ZR7.js → bundled-modules-O67MEO74.js} +2 -2
- package/dist/bundle/{chunk-NLRWERWA.js → chunk-DGO66I3L.js} +51 -20
- package/dist/bundle/{chunk-SX7CAXWU.js → chunk-RQFC34FM.js} +131 -49
- package/dist/bundle/{cli-main-6GXXIMQQ.js → cli-main-2RER6PBE.js} +2 -2
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{main-HF64B4HM.js → main-YERLD3T4.js} +2 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +36 -24
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +1 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +11 -9
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +13 -2
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/kernel/repl-manager.d.ts.map +1 -1
- package/dist/core/kernel/repl-manager.js +5 -0
- package/dist/core/kernel/repl-manager.js.map +1 -1
- package/dist/core/session-manager.d.ts +8 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +57 -0
- package/dist/core/session-manager.js.map +1 -1
- package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-mode.js +17 -17
- package/dist/modes/daemon/daemon-mode.js.map +1 -1
- package/dist/modes/daemon/daemon-worker-client.d.ts +1 -0
- package/dist/modes/daemon/daemon-worker-client.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-worker-client.js +8 -0
- package/dist/modes/daemon/daemon-worker-client.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +29 -4
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/upstream-1.0.15.md +83 -0
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EACN,iBAAiB,EACjB,oBAAoB,GAEpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACN,yBAAyB,EACzB,yBAAyB,EACzB,YAAY,EACZ,0BAA0B,EAC1B,8BAA8B,EAC9B,mBAAmB,EACnB,4BAA4B,GAC5B,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAA2C,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAYpB,qGAAqG;AACrG,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAA6E,CAAC;AACrH,MAAM,uBAAuB,GAAG,IAAI,OAAO,EAA0E,CAAC;AAEtH,SAAS,mBAAmB,CAC3B,KAAmB,EACnB,QAA0C,EAC1C,UAAqC,EACrC,IAAsD,EACvC;IACf,MAAM,OAAO,GACZ,QAAQ,YAAY,oBAAoB;QACvC,CAAC,CAAC,oBAAoB,CAAC,SAAS,CAAC,oBAAoB,CAAC,IAAI,CAAC,QAAQ,E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CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EACzC;QACC,OAAO,EAAE,SAAS;QAClB,aAAa,EAAE,wBAAwB;QACvC,WAAW,EAAE,OAAO,EAAE,CAAC,uBAAuB,CAAC;QAC/C,cAAc,EAAE,OAAO,EAAE,CAAC,uBAAuB,CAAC;KAClD,CACD,CAAC;IAEF,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC;IAClC,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,qCAAqC,QAAQ,CAAC,YAAY,IAAI,eAAe,EAAE,CAAC,CAAC;IAClG,CAAC;IAED,MAAM,KAAK,GAAiB;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;aACvB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,QAAQ,CAAC,KAAK;KACrB,CAAC;IACF,OAAO,mBAAmB,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;AAAA,CACvE","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport type { AssistantMessage, Model, Usage } from \"@ponythewhite/base-context-ai\";\nimport {\n\tcompleteInference,\n\tInferenceCoordinator,\n\ttype NativeCompactionOutputBinding,\n} from \"../inference-coordinator.js\";\nimport {\n\tCOMPACTION_SUMMARY_PREFIX,\n\tCOMPACTION_SUMMARY_SUFFIX,\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n\tHARNESS_SNAPSHOT_CUSTOM_TYPE,\n} from \"../messages.js\";\nimport type { NativeCompactionRequestOutputAssociation } from \"../request-events.js\";\nimport { MODEL_REQUEST_ID_HEADER } from \"../semantic-edges.js\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.js\";\nimport { TASK_FRAME_CUSTOM_TYPE } from \"../task-frame.js\";\nimport { addAssistantUsage, emptyUsage } from \"../usage.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.js\";\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport interface SummarySlice {\n\tsummary: string;\n\tusage?: Usage;\n}\n\n// Identity follows the actual completion -> text slice -> built-in composition, never copied fields.\nconst nativeSummarySlices = new WeakMap<SummarySlice, { summary: string; binding: NativeCompactionOutputBinding }>();\nconst nativeCompactionResults = new WeakMap<object, { summary: string; bindings: NativeCompactionOutputBinding[] }>();\n\nfunction captureSummarySlice(\n\tslice: SummarySlice,\n\trequests: InferenceCoordinator | undefined,\n\tcompletion: Promise<AssistantMessage>,\n\tpart: NativeCompactionRequestOutputAssociation[\"part\"],\n): SummarySlice {\n\tconst binding =\n\t\trequests instanceof InferenceCoordinator\n\t\t\t? InferenceCoordinator.prototype.takeCompactionOutput.call(requests, completion)\n\t\t\t: undefined;\n\tif (binding?.output.part === part) nativeSummarySlices.set(slice, { summary: slice.summary, binding });\n\treturn slice;\n}\n\n/** Internal append input: only this exact built-in result and original sink can contribute links. */\nexport function takeCompactionRequestOutputs(\n\tresult: object | undefined,\n\tsink: object,\n\tsummary: string,\n): readonly NativeCompactionRequestOutputAssociation[] | undefined {\n\tconst captured = result ? nativeCompactionResults.get(result) : undefined;\n\tif (result) nativeCompactionResults.delete(result);\n\t// Equality only checks an already privately bound projection for mutation; it never discovers a link.\n\tif (!captured || captured.summary !== summary) return undefined;\n\tconst outputs = captured.bindings.filter((binding) => binding.sink === sink).map((binding) => binding.output);\n\treturn outputs.length ? outputs : undefined;\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\n/** Preserve file operations recorded by prior compactions and current tool calls. */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn createCompactionSummaryMessage(\n\t\t\tentry.summary,\n\t\t\tentry.tokensBefore,\n\t\t\tentry.timestamp,\n\t\t\tentry.customInstructions,\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn getMessageFromEntry(entry);\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\t/** Prior-context estimate; null when the original context is not measurable. */\n\ttokensBefore: number | null;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n\t/** What the summarization call(s) billed; persisted on the compaction entry. */\n\tusage?: Usage;\n}\nexport const COMPACT_SKILL_NAME = \"compact\";\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n\t/** Soft working-context target; the model limit always takes precedence. */\n\ttargetTokens?: number | \"model-limit\";\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n};\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n *\n * Includes output: the assistant's response becomes part of the prompt on the next\n * request, so it counts toward the context the next turn will send.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: readonly AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(\n\tcontextTokens: number,\n\tcontextWindow: number,\n\tsettings: CompactionSettings,\n\tfixedContextTokens = 0,\n): boolean {\n\tif (!settings.enabled) return false;\n\tif (contextWindow <= 0) return false;\n\tconst modelLimit = contextWindow - settings.reserveTokens;\n\t// Fixed instructions cannot shrink. Leave meaningful room for retained history\n\t// and new work above that floor, without relaxing the actual model ceiling.\n\tconst target =\n\t\tsettings.targetTokens === \"model-limit\"\n\t\t\t? modelLimit\n\t\t\t: Math.max(\n\t\t\t\t\tsettings.targetTokens ?? Math.floor(contextWindow * 0.9),\n\t\t\t\t\tfixedContextTokens + 4 * settings.keepRecentTokens,\n\t\t\t\t);\n\treturn contextTokens > Math.min(target, modelLimit);\n}\n\n/** Chars/4 heuristic, not a provider count. Ordinary history never raises this floor. */\nexport function estimateFixedCompactionTokens(\n\tsystemPrompt: string,\n\ttools: readonly { name: string; description: string; parameters: unknown }[],\n\tmessages: readonly AgentMessage[],\n): number {\n\tconst toolSchemas = tools.map(({ name, description, parameters }) => ({ name, description, parameters }));\n\tlet tokens = Math.ceil((systemPrompt.length + (tools.length ? JSON.stringify(toolSchemas).length : 0)) / 4);\n\tlet hasHarnessSnapshot = false;\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"custom\") continue;\n\t\t// A TaskFrame may contain dependent sparse revisions; all current pieces count.\n\t\tif (message.customType === TASK_FRAME_CUSTOM_TYPE) tokens += estimateTokens(message);\n\t\telse if (message.customType === HARNESS_SNAPSHOT_CUSTOM_TYPE && !hasHarnessSnapshot) {\n\t\t\ttokens += estimateTokens(message);\n\t\t\thasHarnessSnapshot = true;\n\t\t}\n\t}\n\treturn tokens;\n}\n/** Raise suffix estimates when observed usage exceeds chars/4 for the same prefix. */\nfunction compactionTokenScale(messages: readonly AgentMessage[]): number {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\tif (!usageInfo) return 1;\n\tlet estimatedTokens = 0;\n\tfor (let index = 0; index <= usageInfo.index; index++) {\n\t\testimatedTokens += estimateTokens(messages[index]);\n\t}\n\treturn estimatedTokens > 0 ? Math.max(1, calculateContextTokens(usageInfo.usage) / estimatedTokens) : 1;\n}\n\n/** Estimate message tokens with chars/4; dense content can exceed this heuristic. */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tconst content = (message as { content: string | Array<{ type: string; text?: string }> }).content;\n\t\t\tif (typeof content === \"string\") {\n\t\t\t\tchars = content.length;\n\t\t\t} else if (Array.isArray(content)) {\n\t\t\t\tfor (const block of content) {\n\t\t\t\t\tif (block.type === \"text\" && block.text) {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tif (typeof message.content === \"string\") {\n\t\t\t\tchars = message.content.length;\n\t\t\t} else {\n\t\t\t\tfor (const block of message.content) {\n\t\t\t\t\tif (block.type === \"text\" && block.text) {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tchars += 4800; // Estimate images as 4000 chars, or 1200 tokens\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\t\t// Branch summaries and custom messages are user-role turn boundaries.\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n\tallowShortSession = false,\n\ttokenScale = 1,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\t\tconst messageTokens = estimateTokens(entry.message) * tokenScale;\n\t\taccumulatedTokens += messageTokens;\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\tcutIndex = cutPoints.filter((candidate) => candidate <= i).at(-1) ?? cutIndex;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (allowShortSession && cutIndex === cutPoints[0]) {\n\t\t// An explicit compact may summarize a short prefix, but must keep a real suffix.\n\t\tconst latest = cutPoints\n\t\t\t.filter((index) => {\n\t\t\t\tconst entry = entries[index];\n\t\t\t\treturn entry.type !== \"message\" || entry.message.role !== \"compactionSummary\";\n\t\t\t})\n\t\t\t.at(-1);\n\t\tif (latest !== undefined) cutIndex = latest;\n\t}\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\tbreak;\n\t\t}\n\t\tcutIndex--;\n\t}\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\t// A cut in a non-user turn requires a prefix summary.\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst RUNTIME_STATE_SUMMARY_NOTE =\n\t\"Runtime note: this summary does not establish whether a Python kernel is live or whether its variables, imports, helpers, or jobs remain available. Preserve useful names and their last observed state, including uncertainty. Use current runtime reports before relying on them; do not infer either survival or loss from compaction.\";\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Build the instruction portion of the summarization prompt: the initial or\n * update template, optional user instructions, and the runtime-state qualification.\n */\nexport function buildSummarizationPrompt(customInstructions?: string, previousSummary?: string): string {\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt += `\\n\\n<user-instructions>\\nThe user provided these instructions for this summary. Follow them with high priority while keeping the section format above: emphasize what they ask to focus on, and preserve verbatim anything they ask to remember.\\n${customInstructions}\\n</user-instructions>`;\n\t}\n\treturn `${basePrompt}\\n\\n${RUNTIME_STATE_SUMMARY_NOTE}`;\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\toutputTokenLimit?: number,\n): Promise<SummarySlice> {\n\tconst maxTokens = outputTokenLimit ?? Math.floor(0.8 * reserveTokens);\n\n\tconst basePrompt = buildSummarizationPrompt(customInstructions, previousSummary);\n\t// Serialize before the LLM call so it summarizes rather than continues this conversation.\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions =\n\t\tmodel.reasoning && thinkingLevel && thinkingLevel !== \"off\"\n\t\t\t? { maxTokens, signal, apiKey, headers, reasoning: thinkingLevel }\n\t\t\t: { maxTokens, signal, apiKey, headers };\n\n\tconst completion = completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\t{\n\t\t\tpurpose: \"summary\",\n\t\t\tpurposeDetail: \"compaction\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\n\tconst response = await completion;\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn captureSummarySlice({ summary: textContent, usage: response.usage }, requests, completion, \"history\");\n}\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\n/** Prepare the actual selected epoch view. Entry IDs are only real cut anchors, never synthetic rows. */\nexport function prepareViewCompaction(\n\tmessages: readonly AgentMessage[],\n\tentryIds: readonly (string | undefined)[],\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\tmaxCutEntryId?: string,\n\tallowShortSession = false,\n\tbudgetPressure = false,\n): CompactionPreparation | undefined {\n\tif (messages.length !== entryIds.length) throw new Error(\"Compaction views do not match their source anchors\");\n\t// firstKeptEntryId restores a chronological source suffix, not a selected-view suffix.\n\t// Older pinned views cannot become cut anchors across omitted source messages.\n\tconst selectedIds = new Set(entryIds);\n\tconst suffixAnchors = new Set<string>();\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (!getMessageFromEntryForCompaction(entry)) continue;\n\t\tif (!selectedIds.has(entry.id)) break;\n\t\tsuffixAnchors.add(entry.id);\n\t}\n\tlet cuts = messages.flatMap((message, index) =>\n\t\tentryIds[index] &&\n\t\tsuffixAnchors.has(entryIds[index]!) &&\n\t\tmessage.role !== \"toolResult\" &&\n\t\tmessage.role !== \"compactionSummary\"\n\t\t\t? [index]\n\t\t\t: [],\n\t);\n\tlet relaxRetention = false;\n\tif (budgetPressure) {\n\t\t// Only caller-confirmed public OVER may relax retention; source/tool groups remain whole.\n\t\tconst spans: [number, number][] = [];\n\t\tconst sourceStarts = new Map<string, number>();\n\t\tconst resultEnds = new Map<string, number>();\n\t\t// Public history renders original roles as custom text; use its captured source anchors.\n\t\tconst sourceMessages = new Map(pathEntries.map((entry) => [entry.id, getMessageFromEntry(entry)]));\n\t\tconst anchoredMessages = messages.map((message, index) => sourceMessages.get(entryIds[index] ?? \"\") ?? message);\n\t\tfor (const [index, message] of anchoredMessages.entries()) {\n\t\t\tconst entryId = entryIds[index];\n\t\t\tif (entryId) {\n\t\t\t\tconst start = sourceStarts.get(entryId);\n\t\t\t\tif (start === undefined) sourceStarts.set(entryId, index);\n\t\t\t\telse spans.push([start, index]);\n\t\t\t}\n\t\t\tif (message.role === \"toolResult\") resultEnds.set(message.toolCallId, index);\n\t\t}\n\t\tlet latestCompleteExchange = messages.length - 1;\n\t\tconst completedAssistants: number[] = [];\n\t\tfor (const [index, message] of anchoredMessages.entries()) {\n\t\t\tif (message.role !== \"assistant\") continue;\n\t\t\tconst calls = message.content.filter((block) => block.type === \"toolCall\");\n\t\t\tconst completeExchange = calls.length > 0 && calls.every((call) => (resultEnds.get(call.id) ?? -1) > index);\n\t\t\tif (completeExchange) latestCompleteExchange = index;\n\t\t\tif (completeExchange || (!calls.length && message.stopReason === \"stop\")) completedAssistants.push(index);\n\t\t\tfor (const call of calls) {\n\t\t\t\tconst end = resultEnds.get(call.id);\n\t\t\t\tif (end !== undefined && end > index) spans.push([index, end]);\n\t\t\t}\n\t\t}\n\t\t// A lone current instruction before its first exchange is not removable history.\n\t\trelaxRetention = completedAssistants.some((index) => index < latestCompleteExchange);\n\t\tif (relaxRetention) {\n\t\t\tcuts = cuts.filter(\n\t\t\t\t(candidate) =>\n\t\t\t\t\tcandidate <= latestCompleteExchange &&\n\t\t\t\t\tspans.every(([start, end]) => candidate <= start || candidate > end),\n\t\t\t);\n\t\t}\n\t}\n\tif (!cuts.length) return;\n\tconst tokenScale = compactionTokenScale(messages);\n\tlet cut = cuts[0];\n\tlet tokens = 0;\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tif (!entryIds[index] || messages[index].role === \"compactionSummary\") continue;\n\t\ttokens += estimateTokens(messages[index]) * tokenScale;\n\t\tif (tokens >= settings.keepRecentTokens) {\n\t\t\t// Include the message that crossed the threshold and its preceding legal group boundary.\n\t\t\tcut = cuts.filter((candidate) => candidate <= index).at(-1) ?? cut;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (relaxRetention || (allowShortSession && cut === cuts[0])) cut = cuts.at(-1)!;\n\tif (maxCutEntryId !== undefined) {\n\t\tconst maximum = entryIds.indexOf(maxCutEntryId);\n\t\tconst lastAllowed = cuts.filter((candidate) => candidate <= maximum).at(-1);\n\t\tif (lastAllowed === undefined) throw new Error(\"Compaction recovery boundary is unavailable\");\n\t\tcut = Math.min(cut, lastAllowed);\n\t}\n\tlet turnStart = -1;\n\tif (messages[cut].role !== \"user\") {\n\t\tfor (let index = cut; index >= 0; index--) {\n\t\t\tif (entryIds[index] && [\"user\", \"custom\", \"branchSummary\", \"bashExecution\"].includes(messages[index].role)) {\n\t\t\t\tturnStart = index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tconst isSplitTurn = turnStart >= 0;\n\tconst historyEnd = isSplitTurn ? turnStart : cut;\n\tlet previousSummary: string | undefined;\n\tlet previousSummaryIndex = -1;\n\tfor (const [index, message] of messages.entries()) {\n\t\tif (message.role !== \"compactionSummary\") continue;\n\t\tpreviousSummary = message.summary;\n\t\tpreviousSummaryIndex = pathEntries.findIndex((entry) => entry.id === entryIds[index]);\n\t}\n\tconst historical = messages.filter(\n\t\t(message, index) => entryIds[index] && index < historyEnd && message.role !== \"compactionSummary\",\n\t);\n\tconst turnPrefixMessages = isSplitTurn\n\t\t? messages.filter(\n\t\t\t\t(message, index) =>\n\t\t\t\t\tentryIds[index] && index >= turnStart && index < cut && message.role !== \"compactionSummary\",\n\t\t\t)\n\t\t: [];\n\tif (!historical.length && !turnPrefixMessages.length && (budgetPressure || allowShortSession || !previousSummary))\n\t\treturn;\n\t// Virtual TaskFrame displays are continuity input, never a canonical suffix boundary.\n\tconst messagesToSummarize = messages.filter(\n\t\t(message, index) => message.role !== \"compactionSummary\" && (!entryIds[index] || index < historyEnd),\n\t);\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, previousSummaryIndex);\n\tfor (const message of turnPrefixMessages) extractFileOpsFromMessage(message, fileOps);\n\treturn {\n\t\tfirstKeptEntryId: entryIds[cut]!,\n\t\tmessagesToSummarize: structuredClone(messagesToSummarize),\n\t\tturnPrefixMessages: structuredClone(turnPrefixMessages),\n\t\tisSplitTurn,\n\t\ttokensBefore: estimateContextTokens([...messages]).tokens,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\tallowShortSession = false,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst messages = buildSessionContext(pathEntries).messages;\n\tconst tokensBefore = estimateContextTokens(messages).tokens;\n\n\tconst cutPoint = findCutPoint(\n\t\tpathEntries,\n\t\tboundaryStart,\n\t\tboundaryEnd,\n\t\tsettings.keepRecentTokens,\n\t\tallowShortSession,\n\t\tcompactionTokenScale(messages),\n\t);\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Avoid a compaction that would summarize no history.\n\tif (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0 && (allowShortSession || !previousSummary)) {\n\t\treturn undefined;\n\t}\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\t// Split turns retain their suffix, but their prefix file operations still belong in the summary.\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\n/** Runs one summary wire call; hosts decorate each call with its own request identity. */\nexport type SummaryCallRunner = <T>(\n\tcall: (callHeaders: Record<string, string> | undefined) => Promise<T>,\n) => Promise<T>;\n\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tsummaryCall: SummaryCallRunner = (call) => call(headers),\n\trequests?: InferenceCoordinator,\n\tsummaryCapacity?: (wrapper: string) => number | undefined,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\tlet summary: string;\n\tconst slices: SummarySlice[] = [];\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tconst fileSummary = formatFileOperations(readFiles, modifiedFiles);\n\tconst split = isSplitTurn && turnPrefixMessages.length > 0;\n\tconst splitSeparator = \"\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n\";\n\tconst wrapper =\n\t\tCOMPACTION_SUMMARY_PREFIX +\n\t\t(split ? (messagesToSummarize.length ? \"\" : \"No prior history.\") + splitSeparator : \"\") +\n\t\tfileSummary +\n\t\tCOMPACTION_SUMMARY_SUFFIX;\n\tconst capacity = summaryCapacity?.(wrapper);\n\tconst historyNeeded = !split || messagesToSummarize.length > 0;\n\tconst calls = Number(historyNeeded) + Number(split);\n\tif (capacity !== undefined && capacity < calls)\n\t\tthrow new Error(\n\t\t\t\"Context capacity exceeded: required evidence, retained tail and summary wrapper leave no room for a summary.\",\n\t\t);\n\tconst historyLimit =\n\t\tcapacity === undefined\n\t\t\t? undefined\n\t\t\t: Math.min(\n\t\t\t\t\tMath.floor(0.8 * settings.reserveTokens),\n\t\t\t\t\tsplit && historyNeeded ? Math.max(1, Math.floor(capacity * 0.6)) : capacity,\n\t\t\t\t);\n\tconst turnLimit =\n\t\tcapacity === undefined\n\t\t\t? undefined\n\t\t\t: Math.min(Math.floor(0.5 * settings.reserveTokens), capacity - (historyNeeded ? historyLimit! : 0));\n\n\tif (split) {\n\t\t// Split turns make two wire calls with different bodies; each needs its own identity.\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? summaryCall((callHeaders) =>\n\t\t\t\t\t\tgenerateSummary(\n\t\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\tcallHeaders,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\t\trequests,\n\t\t\t\t\t\t\thistoryLimit,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve<SummarySlice>({ summary: \"No prior history.\" }),\n\t\t\tsummaryCall((callHeaders) =>\n\t\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\t\tturnPrefixMessages,\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tcallHeaders,\n\t\t\t\t\tsignal,\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\trequests,\n\t\t\t\t\tturnLimit,\n\t\t\t\t),\n\t\t\t),\n\t\t]);\n\t\tslices.push(historyResult, turnPrefixResult);\n\t\tsummary = `${historyResult.summary}${splitSeparator}${turnPrefixResult.summary}`;\n\t} else {\n\t\tconst result = await summaryCall((callHeaders) =>\n\t\t\tgenerateSummary(\n\t\t\t\tmessagesToSummarize,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\tcallHeaders,\n\t\t\t\tsignal,\n\t\t\t\tcustomInstructions,\n\t\t\t\tpreviousSummary,\n\t\t\t\tthinkingLevel,\n\t\t\t\trequests,\n\t\t\t\thistoryLimit,\n\t\t\t),\n\t\t);\n\t\tslices.push(result);\n\t\tsummary = result.summary;\n\t}\n\tsummary += fileSummary;\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\tlet usage: Usage | undefined;\n\tfor (const slice of slices) {\n\t\tif (!slice.usage) continue;\n\t\tusage ??= emptyUsage();\n\t\taddAssistantUsage(usage, slice.usage);\n\t}\n\tconst result: CompactionResult = {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t\tusage,\n\t};\n\tconst bindings = slices.flatMap((slice) => {\n\t\tconst captured = nativeSummarySlices.get(slice);\n\t\tnativeSummarySlices.delete(slice);\n\t\treturn captured?.summary === slice.summary ? [captured.binding] : [];\n\t});\n\tif (bindings.length) nativeCompactionResults.set(result, { summary, bindings });\n\treturn result;\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\toutputTokenLimit?: number,\n): Promise<SummarySlice> {\n\tconst maxTokens = outputTokenLimit ?? Math.floor(0.5 * reserveTokens); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completion = completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tmodel.reasoning && thinkingLevel && thinkingLevel !== \"off\"\n\t\t\t? { maxTokens, signal, apiKey, headers, reasoning: thinkingLevel }\n\t\t\t: { maxTokens, signal, apiKey, headers },\n\t\t{\n\t\t\tpurpose: \"summary\",\n\t\t\tpurposeDetail: \"compaction-turn-prefix\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\n\tconst response = await completion;\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst slice: SummarySlice = {\n\t\tsummary: response.content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\\n\"),\n\t\tusage: response.usage,\n\t};\n\treturn captureSummarySlice(slice, requests, completion, \"turn-prefix\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAA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,GAAG,MAAM,UAAU,CAAC;IAClC,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,qCAAqC,QAAQ,CAAC,YAAY,IAAI,eAAe,EAAE,CAAC,CAAC;IAClG,CAAC;IAED,MAAM,KAAK,GAAiB;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;aACvB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAClB,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,QAAQ,CAAC,KAAK;KACrB,CAAC;IACF,OAAO,mBAAmB,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;AAAA,CACvE","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport type { AssistantMessage, Model, Usage } from \"@ponythewhite/base-context-ai\";\nimport {\n\tcompleteInference,\n\tInferenceCoordinator,\n\ttype NativeCompactionOutputBinding,\n} from \"../inference-coordinator.js\";\nimport {\n\tCOMPACTION_SUMMARY_PREFIX,\n\tCOMPACTION_SUMMARY_SUFFIX,\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n\tHARNESS_SNAPSHOT_CUSTOM_TYPE,\n} from \"../messages.js\";\nimport type { NativeCompactionRequestOutputAssociation } from \"../request-events.js\";\nimport { MODEL_REQUEST_ID_HEADER } from \"../semantic-edges.js\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.js\";\nimport { TASK_FRAME_CUSTOM_TYPE } from \"../task-frame.js\";\nimport { addAssistantUsage, emptyUsage } from \"../usage.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.js\";\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport interface SummarySlice {\n\tsummary: string;\n\tusage?: Usage;\n}\n\n// Identity follows the actual completion -> text slice -> built-in composition, never copied fields.\nconst nativeSummarySlices = new WeakMap<SummarySlice, { summary: string; binding: NativeCompactionOutputBinding }>();\nconst nativeCompactionResults = new WeakMap<object, { summary: string; bindings: NativeCompactionOutputBinding[] }>();\n\nfunction captureSummarySlice(\n\tslice: SummarySlice,\n\trequests: InferenceCoordinator | undefined,\n\tcompletion: Promise<AssistantMessage>,\n\tpart: NativeCompactionRequestOutputAssociation[\"part\"],\n): SummarySlice {\n\tconst binding =\n\t\trequests instanceof InferenceCoordinator\n\t\t\t? InferenceCoordinator.prototype.takeCompactionOutput.call(requests, completion)\n\t\t\t: undefined;\n\tif (binding?.output.part === part) nativeSummarySlices.set(slice, { summary: slice.summary, binding });\n\treturn slice;\n}\n\n/** Internal append input: only this exact built-in result and original sink can contribute links. */\nexport function takeCompactionRequestOutputs(\n\tresult: object | undefined,\n\tsink: object,\n\tsummary: string,\n): readonly NativeCompactionRequestOutputAssociation[] | undefined {\n\tconst captured = result ? nativeCompactionResults.get(result) : undefined;\n\tif (result) nativeCompactionResults.delete(result);\n\t// Equality only checks an already privately bound projection for mutation; it never discovers a link.\n\tif (!captured || captured.summary !== summary) return undefined;\n\tconst outputs = captured.bindings.filter((binding) => binding.sink === sink).map((binding) => binding.output);\n\treturn outputs.length ? outputs : undefined;\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\n/** Preserve file operations recorded by prior compactions and current tool calls. */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn createCompactionSummaryMessage(\n\t\t\tentry.summary,\n\t\t\tentry.tokensBefore,\n\t\t\tentry.timestamp,\n\t\t\tentry.customInstructions,\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn getMessageFromEntry(entry);\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\t/** Prior-context estimate; null when the original context is not measurable. */\n\ttokensBefore: number | null;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n\t/** What the summarization call(s) billed; persisted on the compaction entry. */\n\tusage?: Usage;\n}\nexport const COMPACT_SKILL_NAME = \"compact\";\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n\t/** Soft working-context target; the model limit always takes precedence. */\n\ttargetTokens?: number | \"model-limit\";\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n};\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n *\n * Includes output: the assistant's response becomes part of the prompt on the next\n * request, so it counts toward the context the next turn will send.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: readonly AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(\n\tcontextTokens: number,\n\tcontextWindow: number,\n\tsettings: CompactionSettings,\n\tfixedContextTokens = 0,\n): boolean {\n\tif (!settings.enabled) return false;\n\tif (contextWindow <= 0) return false;\n\tconst modelLimit = contextWindow - settings.reserveTokens;\n\t// Fixed instructions cannot shrink. Leave meaningful room for retained history\n\t// and new work above that floor, without relaxing the actual model ceiling.\n\tconst target =\n\t\tsettings.targetTokens === \"model-limit\"\n\t\t\t? modelLimit\n\t\t\t: Math.max(\n\t\t\t\t\tsettings.targetTokens ?? Math.floor(contextWindow * 0.9),\n\t\t\t\t\tfixedContextTokens + 4 * settings.keepRecentTokens,\n\t\t\t\t);\n\treturn contextTokens > Math.min(target, modelLimit);\n}\n\n/** Chars/4 heuristic, not a provider count. Ordinary history never raises this floor. */\nexport function estimateFixedCompactionTokens(\n\tsystemPrompt: string,\n\ttools: readonly { name: string; description: string; parameters: unknown }[],\n\tmessages: readonly AgentMessage[],\n): number {\n\tconst toolSchemas = tools.map(({ name, description, parameters }) => ({ name, description, parameters }));\n\tlet tokens = Math.ceil((systemPrompt.length + (tools.length ? JSON.stringify(toolSchemas).length : 0)) / 4);\n\tlet hasHarnessSnapshot = false;\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"custom\") continue;\n\t\t// A TaskFrame may contain dependent sparse revisions; all current pieces count.\n\t\tif (message.customType === TASK_FRAME_CUSTOM_TYPE) tokens += estimateTokens(message);\n\t\telse if (message.customType === HARNESS_SNAPSHOT_CUSTOM_TYPE && !hasHarnessSnapshot) {\n\t\t\ttokens += estimateTokens(message);\n\t\t\thasHarnessSnapshot = true;\n\t\t}\n\t}\n\treturn tokens;\n}\n/** Raise suffix estimates when observed usage exceeds chars/4 for the same prefix. */\nfunction compactionTokenScale(messages: readonly AgentMessage[]): number {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\tif (!usageInfo) return 1;\n\tlet estimatedTokens = 0;\n\tfor (let index = 0; index <= usageInfo.index; index++) {\n\t\testimatedTokens += estimateTokens(messages[index]);\n\t}\n\treturn estimatedTokens > 0 ? Math.max(1, calculateContextTokens(usageInfo.usage) / estimatedTokens) : 1;\n}\n\n/** Estimate message tokens with chars/4; dense content can exceed this heuristic. */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tconst content = (message as { content: string | Array<{ type: string; text?: string }> }).content;\n\t\t\tif (typeof content === \"string\") {\n\t\t\t\tchars = content.length;\n\t\t\t} else if (Array.isArray(content)) {\n\t\t\t\tfor (const block of content) {\n\t\t\t\t\tif (block.type === \"text\" && block.text) {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tif (typeof message.content === \"string\") {\n\t\t\t\tchars = message.content.length;\n\t\t\t} else {\n\t\t\t\tfor (const block of message.content) {\n\t\t\t\t\tif (block.type === \"text\" && block.text) {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tchars += 4800; // Estimate images as 4000 chars, or 1200 tokens\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\t\t// Branch summaries and custom messages are user-role turn boundaries.\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n\tallowShortSession = false,\n\ttokenScale = 1,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\t\tconst messageTokens = estimateTokens(entry.message) * tokenScale;\n\t\taccumulatedTokens += messageTokens;\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\tcutIndex = cutPoints.filter((candidate) => candidate <= i).at(-1) ?? cutIndex;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (allowShortSession && cutIndex === cutPoints[0]) {\n\t\t// An explicit compact may summarize a short prefix, but must keep a real suffix.\n\t\tconst latest = cutPoints\n\t\t\t.filter((index) => {\n\t\t\t\tconst entry = entries[index];\n\t\t\t\treturn entry.type !== \"message\" || entry.message.role !== \"compactionSummary\";\n\t\t\t})\n\t\t\t.at(-1);\n\t\tif (latest !== undefined) cutIndex = latest;\n\t}\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\tbreak;\n\t\t}\n\t\tcutIndex--;\n\t}\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\t// A cut in a non-user turn requires a prefix summary.\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst RUNTIME_STATE_SUMMARY_NOTE =\n\t\"Runtime note: this summary does not establish whether a Python kernel is live or whether its variables, imports, helpers, or jobs remain available. Preserve useful names and their last observed state, including uncertainty. Use current runtime reports before relying on them; do not infer either survival or loss from compaction.\";\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Build the instruction portion of the summarization prompt: the initial or\n * update template, optional user instructions, and the runtime-state qualification.\n */\nexport function buildSummarizationPrompt(customInstructions?: string, previousSummary?: string): string {\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt += `\\n\\n<user-instructions>\\nThe user provided these instructions for this summary. Follow them with high priority while keeping the section format above: emphasize what they ask to focus on, and preserve verbatim anything they ask to remember.\\n${customInstructions}\\n</user-instructions>`;\n\t}\n\treturn `${basePrompt}\\n\\n${RUNTIME_STATE_SUMMARY_NOTE}`;\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\toutputTokenLimit?: number,\n): Promise<SummarySlice> {\n\tconst maxTokens = outputTokenLimit ?? Math.floor(0.8 * reserveTokens);\n\n\tconst basePrompt = buildSummarizationPrompt(customInstructions, previousSummary);\n\t// Serialize before the LLM call so it summarizes rather than continues this conversation.\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions =\n\t\tmodel.reasoning && thinkingLevel && thinkingLevel !== \"off\"\n\t\t\t? { maxTokens, signal, apiKey, headers, reasoning: thinkingLevel }\n\t\t\t: { maxTokens, signal, apiKey, headers };\n\n\tconst completion = completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\t{\n\t\t\tpurpose: \"summary\",\n\t\t\tpurposeDetail: \"compaction\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\n\tconst response = await completion;\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn captureSummarySlice({ summary: textContent, usage: response.usage }, requests, completion, \"history\");\n}\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\n/** Prepare the actual selected epoch view. Entry IDs are only real cut anchors, never synthetic rows. */\nexport function prepareViewCompaction(\n\tmessages: readonly AgentMessage[],\n\tentryIds: readonly (string | undefined)[],\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\tmaxCutEntryId?: string,\n\tallowShortSession = false,\n\tbudgetPressure = false,\n\tcapturedSuffixAnchors?: ReadonlySet<string>,\n): CompactionPreparation | undefined {\n\tif (messages.length !== entryIds.length) throw new Error(\"Compaction views do not match their source anchors\");\n\t// firstKeptEntryId restores a chronological source suffix, not a selected-view suffix.\n\t// Older pinned views cannot become cut anchors across omitted source messages.\n\tconst selectedIds = new Set(entryIds);\n\tconst suffixAnchors = new Set(capturedSuffixAnchors);\n\tif (!capturedSuffixAnchors) {\n\t\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\t\tconst entry = pathEntries[index];\n\t\t\tif (!getMessageFromEntryForCompaction(entry)) continue;\n\t\t\tif (!selectedIds.has(entry.id)) break;\n\t\t\tsuffixAnchors.add(entry.id);\n\t\t}\n\t}\n\tlet cuts = messages.flatMap((message, index) =>\n\t\tentryIds[index] &&\n\t\tsuffixAnchors.has(entryIds[index]!) &&\n\t\tmessage.role !== \"toolResult\" &&\n\t\tmessage.role !== \"compactionSummary\"\n\t\t\t? [index]\n\t\t\t: [],\n\t);\n\tlet relaxRetention = false;\n\tif (budgetPressure) {\n\t\t// Only caller-confirmed public OVER may relax retention; source/tool groups remain whole.\n\t\tconst spans: [number, number][] = [];\n\t\tconst sourceStarts = new Map<string, number>();\n\t\tconst resultEnds = new Map<string, number>();\n\t\t// Public history renders original roles as custom text; use its captured source anchors.\n\t\tconst sourceMessages = new Map(pathEntries.map((entry) => [entry.id, getMessageFromEntry(entry)]));\n\t\tconst anchoredMessages = messages.map((message, index) => sourceMessages.get(entryIds[index] ?? \"\") ?? message);\n\t\tfor (const [index, message] of anchoredMessages.entries()) {\n\t\t\tconst entryId = entryIds[index];\n\t\t\tif (entryId) {\n\t\t\t\tconst start = sourceStarts.get(entryId);\n\t\t\t\tif (start === undefined) sourceStarts.set(entryId, index);\n\t\t\t\telse spans.push([start, index]);\n\t\t\t}\n\t\t\tif (message.role === \"toolResult\") resultEnds.set(message.toolCallId, index);\n\t\t}\n\t\tlet latestCompleteExchange = messages.length - 1;\n\t\tconst completedAssistants: number[] = [];\n\t\tfor (const [index, message] of anchoredMessages.entries()) {\n\t\t\tif (message.role !== \"assistant\") continue;\n\t\t\tconst calls = message.content.filter((block) => block.type === \"toolCall\");\n\t\t\tconst completeExchange = calls.length > 0 && calls.every((call) => (resultEnds.get(call.id) ?? -1) > index);\n\t\t\tif (completeExchange) latestCompleteExchange = index;\n\t\t\tif (completeExchange || (!calls.length && message.stopReason === \"stop\")) completedAssistants.push(index);\n\t\t\tfor (const call of calls) {\n\t\t\t\tconst end = resultEnds.get(call.id);\n\t\t\t\tif (end !== undefined && end > index) spans.push([index, end]);\n\t\t\t}\n\t\t}\n\t\t// A lone current instruction before its first exchange is not removable history.\n\t\trelaxRetention = completedAssistants.some((index) => index < latestCompleteExchange);\n\t\tif (relaxRetention) {\n\t\t\tcuts = cuts.filter(\n\t\t\t\t(candidate) =>\n\t\t\t\t\tcandidate <= latestCompleteExchange &&\n\t\t\t\t\tspans.every(([start, end]) => candidate <= start || candidate > end),\n\t\t\t);\n\t\t}\n\t}\n\tif (!cuts.length) return;\n\tconst tokenScale = compactionTokenScale(messages);\n\tlet cut = cuts[0];\n\tlet tokens = 0;\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tif (!entryIds[index] || messages[index].role === \"compactionSummary\") continue;\n\t\ttokens += estimateTokens(messages[index]) * tokenScale;\n\t\tif (tokens >= settings.keepRecentTokens) {\n\t\t\t// Include the message that crossed the threshold and its preceding legal group boundary.\n\t\t\tcut = cuts.filter((candidate) => candidate <= index).at(-1) ?? cut;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (relaxRetention || (allowShortSession && cut === cuts[0])) cut = cuts.at(-1)!;\n\tif (maxCutEntryId !== undefined) {\n\t\tconst maximum = entryIds.indexOf(maxCutEntryId);\n\t\tconst lastAllowed = cuts.filter((candidate) => candidate <= maximum).at(-1);\n\t\tif (lastAllowed === undefined) throw new Error(\"Compaction recovery boundary is unavailable\");\n\t\tcut = Math.min(cut, lastAllowed);\n\t}\n\tlet turnStart = -1;\n\tif (messages[cut].role !== \"user\") {\n\t\tfor (let index = cut; index >= 0; index--) {\n\t\t\tif (entryIds[index] && [\"user\", \"custom\", \"branchSummary\", \"bashExecution\"].includes(messages[index].role)) {\n\t\t\t\tturnStart = index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tconst isSplitTurn = turnStart >= 0;\n\tconst historyEnd = isSplitTurn ? turnStart : cut;\n\tlet previousSummary: string | undefined;\n\tlet previousSummaryIndex = -1;\n\tfor (const [index, message] of messages.entries()) {\n\t\tif (message.role !== \"compactionSummary\") continue;\n\t\tpreviousSummary = message.summary;\n\t\tpreviousSummaryIndex = pathEntries.findIndex((entry) => entry.id === entryIds[index]);\n\t}\n\tconst historical = messages.filter(\n\t\t(message, index) => entryIds[index] && index < historyEnd && message.role !== \"compactionSummary\",\n\t);\n\tconst turnPrefixMessages = isSplitTurn\n\t\t? messages.filter(\n\t\t\t\t(message, index) =>\n\t\t\t\t\tentryIds[index] && index >= turnStart && index < cut && message.role !== \"compactionSummary\",\n\t\t\t)\n\t\t: [];\n\tif (!historical.length && !turnPrefixMessages.length && (budgetPressure || allowShortSession || !previousSummary))\n\t\treturn;\n\t// Virtual TaskFrame displays are continuity input, never a canonical suffix boundary.\n\tconst messagesToSummarize = messages.filter(\n\t\t(message, index) => message.role !== \"compactionSummary\" && (!entryIds[index] || index < historyEnd),\n\t);\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, previousSummaryIndex);\n\tfor (const message of turnPrefixMessages) extractFileOpsFromMessage(message, fileOps);\n\treturn {\n\t\tfirstKeptEntryId: entryIds[cut]!,\n\t\tmessagesToSummarize: structuredClone(messagesToSummarize),\n\t\tturnPrefixMessages: structuredClone(turnPrefixMessages),\n\t\tisSplitTurn,\n\t\ttokensBefore: estimateContextTokens([...messages]).tokens,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\tallowShortSession = false,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst messages = buildSessionContext(pathEntries).messages;\n\tconst tokensBefore = estimateContextTokens(messages).tokens;\n\n\tconst cutPoint = findCutPoint(\n\t\tpathEntries,\n\t\tboundaryStart,\n\t\tboundaryEnd,\n\t\tsettings.keepRecentTokens,\n\t\tallowShortSession,\n\t\tcompactionTokenScale(messages),\n\t);\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Avoid a compaction that would summarize no history.\n\tif (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0 && (allowShortSession || !previousSummary)) {\n\t\treturn undefined;\n\t}\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\t// Split turns retain their suffix, but their prefix file operations still belong in the summary.\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\n/** Runs one summary wire call; hosts decorate each call with its own request identity. */\nexport type SummaryCallRunner = <T>(\n\tcall: (callHeaders: Record<string, string> | undefined) => Promise<T>,\n) => Promise<T>;\n\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tsummaryCall: SummaryCallRunner = (call) => call(headers),\n\trequests?: InferenceCoordinator,\n\tsummaryCapacity?: (wrapper: string) => number | undefined,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\tlet summary: string;\n\tconst slices: SummarySlice[] = [];\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tconst fileSummary = formatFileOperations(readFiles, modifiedFiles);\n\tconst split = isSplitTurn && turnPrefixMessages.length > 0;\n\tconst splitSeparator = \"\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n\";\n\tconst wrapper =\n\t\tCOMPACTION_SUMMARY_PREFIX +\n\t\t(split ? (messagesToSummarize.length ? \"\" : \"No prior history.\") + splitSeparator : \"\") +\n\t\tfileSummary +\n\t\tCOMPACTION_SUMMARY_SUFFIX;\n\tconst capacity = summaryCapacity?.(wrapper);\n\tconst historyNeeded = !split || messagesToSummarize.length > 0;\n\tconst calls = Number(historyNeeded) + Number(split);\n\tif (capacity !== undefined && capacity < calls)\n\t\tthrow new Error(\n\t\t\t\"Context capacity exceeded: required evidence, retained tail and summary wrapper leave no room for a summary.\",\n\t\t);\n\tconst historyLimit =\n\t\tcapacity === undefined\n\t\t\t? undefined\n\t\t\t: Math.min(\n\t\t\t\t\tMath.floor(0.8 * settings.reserveTokens),\n\t\t\t\t\tsplit && historyNeeded ? Math.max(1, Math.floor(capacity * 0.6)) : capacity,\n\t\t\t\t);\n\tconst turnLimit =\n\t\tcapacity === undefined\n\t\t\t? undefined\n\t\t\t: Math.min(Math.floor(0.5 * settings.reserveTokens), capacity - (historyNeeded ? historyLimit! : 0));\n\n\tif (split) {\n\t\t// Split turns make two wire calls with different bodies; each needs its own identity.\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? summaryCall((callHeaders) =>\n\t\t\t\t\t\tgenerateSummary(\n\t\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\tcallHeaders,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\t\trequests,\n\t\t\t\t\t\t\thistoryLimit,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve<SummarySlice>({ summary: \"No prior history.\" }),\n\t\t\tsummaryCall((callHeaders) =>\n\t\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\t\tturnPrefixMessages,\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tcallHeaders,\n\t\t\t\t\tsignal,\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\trequests,\n\t\t\t\t\tturnLimit,\n\t\t\t\t),\n\t\t\t),\n\t\t]);\n\t\tslices.push(historyResult, turnPrefixResult);\n\t\tsummary = `${historyResult.summary}${splitSeparator}${turnPrefixResult.summary}`;\n\t} else {\n\t\tconst result = await summaryCall((callHeaders) =>\n\t\t\tgenerateSummary(\n\t\t\t\tmessagesToSummarize,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\tcallHeaders,\n\t\t\t\tsignal,\n\t\t\t\tcustomInstructions,\n\t\t\t\tpreviousSummary,\n\t\t\t\tthinkingLevel,\n\t\t\t\trequests,\n\t\t\t\thistoryLimit,\n\t\t\t),\n\t\t);\n\t\tslices.push(result);\n\t\tsummary = result.summary;\n\t}\n\tsummary += fileSummary;\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\tlet usage: Usage | undefined;\n\tfor (const slice of slices) {\n\t\tif (!slice.usage) continue;\n\t\tusage ??= emptyUsage();\n\t\taddAssistantUsage(usage, slice.usage);\n\t}\n\tconst result: CompactionResult = {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t\tusage,\n\t};\n\tconst bindings = slices.flatMap((slice) => {\n\t\tconst captured = nativeSummarySlices.get(slice);\n\t\tnativeSummarySlices.delete(slice);\n\t\treturn captured?.summary === slice.summary ? [captured.binding] : [];\n\t});\n\tif (bindings.length) nativeCompactionResults.set(result, { summary, bindings });\n\treturn result;\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\trequests?: InferenceCoordinator,\n\toutputTokenLimit?: number,\n): Promise<SummarySlice> {\n\tconst maxTokens = outputTokenLimit ?? Math.floor(0.5 * reserveTokens); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completion = completeInference(\n\t\trequests,\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tmodel.reasoning && thinkingLevel && thinkingLevel !== \"off\"\n\t\t\t? { maxTokens, signal, apiKey, headers, reasoning: thinkingLevel }\n\t\t\t: { maxTokens, signal, apiKey, headers },\n\t\t{\n\t\t\tpurpose: \"summary\",\n\t\t\tpurposeDetail: \"compaction-turn-prefix\",\n\t\t\toperationId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t\tsemanticEdgeId: headers?.[MODEL_REQUEST_ID_HEADER],\n\t\t},\n\t);\n\n\tconst response = await completion;\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst slice: SummarySlice = {\n\t\tsummary: response.content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\\n\"),\n\t\tusage: response.usage,\n\t};\n\treturn captureSummarySlice(slice, requests, completion, \"turn-prefix\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inference-coordinator.d.ts","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACnG,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAA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uB,GAAG,yBAAyB,CAuBnG;IAED,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,uBAAuB,GAAG,kBAAkB,CA4CnF;CACD;AAED,iGAAiG;AACjG,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,oBAAoB,GAAG,SAAS,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAE3B;AAED,MAAM,MAAM,yBAAyB,GAAG,QAAQ,GAAG;IAClD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,sBAAsB,CAAC,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3F,CAAC;AAEF,yFAAyF;AACzF,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,uBAAuB,GAC9B,yBAAyB,CAM3B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\ttype ProviderInputTokenCounter,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type { AuthSourceToken } from \"./auth-storage.js\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nfunction isPrimaryRequest(purpose: RequestPurpose): boolean {\n\treturn purpose === \"main\" || purpose === \"child\";\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\nconst nativeAuthSources = new WeakMap<AssistantMessage, AuthSourceToken>();\n\n/** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */\nexport function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined {\n\tconst source = nativeAuthSources.get(message);\n\tnativeAuthSources.delete(message);\n\treturn source;\n}\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions & { authSourceToken?: AuthSourceToken }>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst { authSourceToken, ...resolved } = await resolveOptions(model, context, options);\n\t\tconst events = streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t\tif (authSourceToken) {\n\t\t\tconst source = { ...authSourceToken };\n\t\t\tconst result = events.result().then((message) => {\n\t\t\t\tnativeAuthSources.set(message, source);\n\t\t\t\treturn message;\n\t\t\t});\n\t\t\tevents.result = () => result;\n\t\t}\n\t\treturn events;\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tresponsesMessageIds: new Map<string, number>(),\n\t\tresponsesIdentity: randomUUID(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit session-owned epoch boundary, on this same captured primary source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t\tisSourceCurrent?: () => boolean,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare, isSourceCurrent);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst inputCountAttempts = new Map<string, NativeRequestMetadata>();\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && isPrimaryRequest(operation.metadata.purpose))) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = isPrimaryRequest(operation.metadata.purpose) ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tlet countingInput = false;\n\t\t\tlet countedInput: { request: ProviderRequestRepresentation; tokens: number } | undefined;\n\t\t\tconst measure = (request: ProviderRequestRepresentation) => {\n\t\t\t\tconst same =\n\t\t\t\t\tcountedInput &&\n\t\t\t\t\t!request.retainedPrefix &&\n\t\t\t\t\tcountedInput.request.api === request.api &&\n\t\t\t\t\tcountedInput.request.provider === request.provider &&\n\t\t\t\t\tcountedInput.request.url === request.url &&\n\t\t\t\t\tcountedInput.request.body === request.body;\n\t\t\t\treturn budget?.measure(\n\t\t\t\t\trequest,\n\t\t\t\t\tsame\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tinputTokens: countedInput!.tokens,\n\t\t\t\t\t\t\t\tmethod: \"openai-responses-input-count\",\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst finalizeMeasurement = async (\n\t\t\t\trequest: ProviderRequestRepresentation,\n\t\t\t\tcountInput?: ProviderInputTokenCounter,\n\t\t\t\tpreparedAssessment?: RequestTokenAssessment,\n\t\t\t) => {\n\t\t\t\tlet assessment = countedInput ? measure(request) : (preparedAssessment ?? measure(request));\n\t\t\t\tconst estimated = assessment?.estimatedInputTokens;\n\t\t\t\tconst available = assessment?.availableInputTokens;\n\t\t\t\tif (\n\t\t\t\t\tcountInput &&\n\t\t\t\t\tassessment?.counter === \"openai-o200k-base-estimate\" &&\n\t\t\t\t\tassessment.status !== \"unknown\" &&\n\t\t\t\t\testimated !== null &&\n\t\t\t\t\testimated !== undefined &&\n\t\t\t\t\tavailable !== null &&\n\t\t\t\t\tavailable !== undefined &&\n\t\t\t\t\tavailable > 0 &&\n\t\t\t\t\testimated >= available * 0.9 &&\n\t\t\t\t\testimated <= available * 1.1\n\t\t\t\t) {\n\t\t\t\t\tthis.assertAdmission();\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tcountingInput = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst tokens = await countInput(request);\n\t\t\t\t\t\tcountedInput = { request: Object.freeze({ ...request }), tokens };\n\t\t\t\t\t\tassessment = measure(request);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcountingInput = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn assessment;\n\t\t\t};\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tconst requiredEpoch = boundary?.requiresEpoch === true;\n\t\t\tconst canSelect =\n\t\t\t\t(budget ||\n\t\t\t\t\tboundary?.fixedPrepare ||\n\t\t\t\t\trequiredPublic ||\n\t\t\t\t\trequiredEpoch ||\n\t\t\t\t\tboundary?.recoveryContractRequested) &&\n\t\t\t\tboundary &&\n\t\t\t\tmatchesRequestView(boundary, source, context);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tconst responsesMessageIds =\n\t\t\t\tcanSelect &&\n\t\t\t\t!boundary.fixedPrepare &&\n\t\t\t\t(model.api === \"openai-responses\" || model.api === \"openai-codex-responses\")\n\t\t\t\t\t? boundary.providerMessageIndices.map((index) => {\n\t\t\t\t\t\t\tconst unit = boundary.units[index];\n\t\t\t\t\t\t\tconst key = JSON.stringify([\n\t\t\t\t\t\t\t\tboundary.source.sessionId,\n\t\t\t\t\t\t\t\tboundary.source.sessionFile,\n\t\t\t\t\t\t\t\tunit.id,\n\t\t\t\t\t\t\t\tunit.sourceRevision,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tlet id = this.work.responsesMessageIds.get(key);\n\t\t\t\t\t\t\tif (id === undefined) {\n\t\t\t\t\t\t\t\tid = this.work.responsesMessageIds.size;\n\t\t\t\t\t\t\t\tthis.work.responsesMessageIds.set(key, id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn id;\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(responsesMessageIds ? { responsesMessageIds } : {}),\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(budget || canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection, countInput) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (!canSelect) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// An unmapped native body must pass the existing final boundary\n\t\t\t\t\t\t\t\t\t// validator before any provider call, including an input count.\n\t\t\t\t\t\t\t\t\tif (!projection) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\t...(responsesMessageIds ? { responseItemIdentity: this.work.responsesIdentity } : {}),\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t\t(request, assessment) => finalizeMeasurement(request, countInput, assessment),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tconst inputCount = descriptor.kind === \"input-count\";\n\t\t\t\t\tif (inputCount && !countingInput) throw new Error(\"Input count requires its owned prepared request\");\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tif (!inputCount && requiredEpoch && !selectedContextEpoch)\n\t\t\t\t\t\tthrow new Error(\"Context transition requires an acknowledged native epoch\");\n\t\t\t\t\tif (!inputCount && requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (!inputCount && measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch =\n\t\t\t\t\t\t!inputCount && selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst attemptMetadata: NativeRequestMetadata = inputCount\n\t\t\t\t\t\t? { ...metadata, purpose: \"native-control\", purposeDetail: \"input-token-count\" }\n\t\t\t\t\t\t: metadata;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...attemptMetadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (inputCount) inputCountAttempts.set(attemptId, attemptMetadata);\n\t\t\t\t\telse admittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst inputCountMetadata = inputCountAttempts.get(receipt.attemptId);\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...(inputCountMetadata ?? metadata),\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (!inputCountMetadata) parentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst sessionId =\n\t\t\t\toptions?.sessionId ??\n\t\t\t\t(isPrimaryRequest(operation.metadata.purpose)\n\t\t\t\t\t? source.sessionId\n\t\t\t\t\t: `${operation.metadata.purpose}:${source.sessionId}`);\n\t\t\tconst events = await send(model, context, {\n\t\t\t\t...options,\n\t\t\t\tsessionId,\n\t\t\t\tsignal,\n\t\t\t\tattempts,\n\t\t\t\trequireProviderAttempts: true,\n\t\t\t});\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && isPrimaryRequest(request.purpose),\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"inference-coordinator.d.ts","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACnG,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAAK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uB,GAAG,yBAAyB,CAuBnG;IAED,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,uBAAuB,GAAG,kBAAkB,CA4CnF;CACD;AAED,iGAAiG;AACjG,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,oBAAoB,GAAG,SAAS,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAE3B;AAED,MAAM,MAAM,yBAAyB,GAAG,QAAQ,GAAG;IAClD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,sBAAsB,CAAC,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3F,CAAC;AAEF,yFAAyF;AACzF,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,uBAAuB,GAC9B,yBAAyB,CAM3B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\ttype ProviderInputTokenCounter,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type { AuthSourceToken } from \"./auth-storage.js\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nfunction isPrimaryRequest(purpose: RequestPurpose): boolean {\n\treturn purpose === \"main\" || purpose === \"child\";\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\nconst nativeAuthSources = new WeakMap<AssistantMessage, AuthSourceToken>();\n\n/** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */\nexport function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined {\n\tconst source = nativeAuthSources.get(message);\n\tnativeAuthSources.delete(message);\n\treturn source;\n}\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions & { authSourceToken?: AuthSourceToken }>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst { authSourceToken, ...resolved } = await resolveOptions(model, context, options);\n\t\tconst events = streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t\tif (authSourceToken) {\n\t\t\tconst source = { ...authSourceToken };\n\t\t\tconst result = events.result().then((message) => {\n\t\t\t\tnativeAuthSources.set(message, source);\n\t\t\t\treturn message;\n\t\t\t});\n\t\t\tevents.result = () => result;\n\t\t}\n\t\treturn events;\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tresponsesMessageIds: new Map<string, number>(),\n\t\tresponsesIdentity: randomUUID(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit session-owned epoch boundary, on this same captured primary source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t\tisSourceCurrent?: () => boolean,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare, isSourceCurrent);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst inputCountAttempts = new Map<string, NativeRequestMetadata>();\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && isPrimaryRequest(operation.metadata.purpose))) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = isPrimaryRequest(operation.metadata.purpose) ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tlet countingInput = false;\n\t\t\tlet countedInput: { request: ProviderRequestRepresentation; tokens: number } | undefined;\n\t\t\tconst measure = (request: ProviderRequestRepresentation) => {\n\t\t\t\tconst same =\n\t\t\t\t\tcountedInput &&\n\t\t\t\t\t!request.retainedPrefix &&\n\t\t\t\t\tcountedInput.request.api === request.api &&\n\t\t\t\t\tcountedInput.request.provider === request.provider &&\n\t\t\t\t\tcountedInput.request.url === request.url &&\n\t\t\t\t\tcountedInput.request.body === request.body;\n\t\t\t\treturn budget?.measure(\n\t\t\t\t\trequest,\n\t\t\t\t\tsame\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tinputTokens: countedInput!.tokens,\n\t\t\t\t\t\t\t\tmethod: \"openai-responses-input-count\",\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst finalizeMeasurement = async (\n\t\t\t\trequest: ProviderRequestRepresentation,\n\t\t\t\tcountInput?: ProviderInputTokenCounter,\n\t\t\t\tpreparedAssessment?: RequestTokenAssessment,\n\t\t\t) => {\n\t\t\t\tlet assessment = countedInput ? measure(request) : (preparedAssessment ?? measure(request));\n\t\t\t\tconst estimated = assessment?.estimatedInputTokens;\n\t\t\t\tconst available = assessment?.availableInputTokens;\n\t\t\t\tif (\n\t\t\t\t\tcountInput &&\n\t\t\t\t\tassessment?.counter === \"openai-o200k-base-estimate\" &&\n\t\t\t\t\tassessment.status !== \"unknown\" &&\n\t\t\t\t\testimated !== null &&\n\t\t\t\t\testimated !== undefined &&\n\t\t\t\t\tavailable !== null &&\n\t\t\t\t\tavailable !== undefined &&\n\t\t\t\t\tavailable > 0 &&\n\t\t\t\t\testimated >= available * 0.9 &&\n\t\t\t\t\testimated <= available * 1.1\n\t\t\t\t) {\n\t\t\t\t\tthis.assertAdmission();\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tcountingInput = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst tokens = await countInput(request);\n\t\t\t\t\t\tcountedInput = { request: Object.freeze({ ...request }), tokens };\n\t\t\t\t\t\tassessment = measure(request);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcountingInput = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn assessment;\n\t\t\t};\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tconst requiredEpoch = boundary?.requiresEpoch === true;\n\t\t\tconst canSelect =\n\t\t\t\t(budget ||\n\t\t\t\t\tboundary?.fixedPrepare ||\n\t\t\t\t\trequiredPublic ||\n\t\t\t\t\trequiredEpoch ||\n\t\t\t\t\tboundary?.recoveryContractRequested) &&\n\t\t\t\tboundary &&\n\t\t\t\tmatchesRequestView(boundary, source, context);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tconst responsesMessageIds =\n\t\t\t\tcanSelect &&\n\t\t\t\t!boundary.fixedPrepare &&\n\t\t\t\t(model.api === \"openai-responses\" || model.api === \"openai-codex-responses\")\n\t\t\t\t\t? boundary.providerMessageIndices.map((index) => {\n\t\t\t\t\t\t\tconst unit = boundary.units[index];\n\t\t\t\t\t\t\tconst key = JSON.stringify([\n\t\t\t\t\t\t\t\tboundary.source.sessionId,\n\t\t\t\t\t\t\t\tboundary.source.sessionFile,\n\t\t\t\t\t\t\t\tunit.id,\n\t\t\t\t\t\t\t\tunit.sourceRevision,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tlet id = this.work.responsesMessageIds.get(key);\n\t\t\t\t\t\t\tif (id === undefined) {\n\t\t\t\t\t\t\t\tid = this.work.responsesMessageIds.size;\n\t\t\t\t\t\t\t\tthis.work.responsesMessageIds.set(key, id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn id;\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tlet preparedRequest: ProviderRequestRepresentation | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(responsesMessageIds ? { responsesMessageIds } : {}),\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(budget || canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection, countInput) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t// Adapters may retry the exact prepared body without another projection.\n\t\t\t\t\t\t\t\t\t// Keep its ACK only inside this captured execution; final measurement still runs.\n\t\t\t\t\t\t\t\t\tif (!projection && preparedRequest && isDeepStrictEqual(representation, preparedRequest))\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\tpreparedRequest = undefined;\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (!canSelect) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// An unmapped native body must pass the existing final boundary\n\t\t\t\t\t\t\t\t\t// validator before any provider call, including an input count.\n\t\t\t\t\t\t\t\t\tif (!projection) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) {\n\t\t\t\t\t\t\t\t\t\t\tselectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\tpreparedRequest = structuredClone(representation);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\t...(responsesMessageIds ? { responseItemIdentity: this.work.responsesIdentity } : {}),\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tselectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\t\tpreparedRequest = structuredClone(candidate.request);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t\t(request, assessment) => finalizeMeasurement(request, countInput, assessment),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tconst inputCount = descriptor.kind === \"input-count\";\n\t\t\t\t\tif (inputCount && !countingInput) throw new Error(\"Input count requires its owned prepared request\");\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tif (!inputCount && requiredEpoch && !selectedContextEpoch)\n\t\t\t\t\t\tthrow new Error(\"Context transition requires an acknowledged native epoch\");\n\t\t\t\t\tif (!inputCount && requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (!inputCount && measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch =\n\t\t\t\t\t\t!inputCount && selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst attemptMetadata: NativeRequestMetadata = inputCount\n\t\t\t\t\t\t? { ...metadata, purpose: \"native-control\", purposeDetail: \"input-token-count\" }\n\t\t\t\t\t\t: metadata;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...attemptMetadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (inputCount) inputCountAttempts.set(attemptId, attemptMetadata);\n\t\t\t\t\telse admittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst inputCountMetadata = inputCountAttempts.get(receipt.attemptId);\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...(inputCountMetadata ?? metadata),\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (!inputCountMetadata) parentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst sessionId =\n\t\t\t\toptions?.sessionId ??\n\t\t\t\t(isPrimaryRequest(operation.metadata.purpose)\n\t\t\t\t\t? source.sessionId\n\t\t\t\t\t: `${operation.metadata.purpose}:${source.sessionId}`);\n\t\t\tconst events = await send(model, context, {\n\t\t\t\t...options,\n\t\t\t\tsessionId,\n\t\t\t\tsignal,\n\t\t\t\tattempts,\n\t\t\t\trequireProviderAttempts: true,\n\t\t\t});\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && isPrimaryRequest(request.purpose),\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
|