{"version":3,"file":"structural.d.ts","sourceRoot":"","sources":["../../../../src/harness/runtime/drive/structural.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,iBAAiB,EAAuB,MAAM,0CAA0C,CAAC;AAEvG,OAAO,KAAK,EAAE,qBAAqB,EAAiC,MAAM,gCAAgC,CAAC;AAO3G,OAAO,EACN,KAAK,+BAA+B,EAGpC,KAAK,mBAAmB,EAIxB,KAAK,4BAA4B,EAGjC,KAAK,gCAAgC,EAMrC,KAAK,wBAAwB,EAC7B,KAAK,6BAA6B,EAClC,KAAK,qBAAqB,EAC1B,KAAK,yBAAyB,EAI9B,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,KAAK,EAAE,uBAAuB,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AA2BnF,wBAAgB,4BAA4B,CAC3C,WAAW,EAAE,qBAAqB,GAChC,OAAO,CAAC,4BAA4B,EAAE;IAAE,IAAI,EAAE,YAAY,CAAA;CAAE,CAAC,CAY/D;AAED,wBAAgB,wBAAwB,CACvC,WAAW,EAAE,iBAAiB,GAC5B,OAAO,CAAC,4BAA4B,EAAE;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE,CAAC,CAOnE;AA2fD,oEAAoE;AACpE,wBAAsB,qBAAqB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EAC9E,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,wBAAwB,GAChC,OAAO,CAAC,eAAe,CAAC,CA4D1B;AAiVD,uDAAuD;AACvD,wBAAsB,uBAAuB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EAChF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,qBAAqB,GAC1B,OAAO,CAAC,eAAe,CAAC,CAe1B;AAED,4EAA4E;AAC5E,wBAAsB,sBAAsB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EAC/E,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,yBAAyB,GAC9B,OAAO,CAAC,eAAe,CAAC,CAsC1B;AAED,gGAAgG;AAChG,wBAAsB,2BAA2B,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EACpF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,6BAA6B,GACnC,OAAO,CAAC,eAAe,CAAC,CAkC1B;AAED,8FAA8F;AAC9F,wBAAsB,0BAA0B,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EACnF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,mBAAmB,GAC7B,OAAO,CAAC,uBAAuB,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,4BAA4B,CAAA;CAAE,GAAG,SAAS,CAAC,CAAC,CA8B7G;AAED,kFAAkF;AAClF,wBAAsB,yBAAyB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EAClF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,+BAA+B,GACzC,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,4BAA4B,CAAA;CAAE,GAAG,SAAS,CAAC,CAWpF;AAED,2EAA2E;AAC3E,wBAAgB,gBAAgB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EACnE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,gCAAgC,GAC1C,OAAO,CAAC,eAAe,CAAC,CA6C1B","sourcesContent":["import {\n\ttype Api,\n\ttype AssistantMessage,\n\tisRetryableAssistantError,\n\ttype Model,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport type { HarnessEvent } from \"../../agent-harness.ts\";\nimport type { BranchPreparation, BranchSummaryResult } from \"../../compaction/branch-summarization.ts\";\nimport { generateBranchSummaryWithRequest } from \"../../compaction/branch-summarization.ts\";\nimport type { CompactionPreparation, CompactResult, SummaryRequest } from \"../../compaction/compaction.ts\";\nimport { compactWithRequest, prepareCompaction, shouldCompact } from \"../../compaction/compaction.ts\";\nimport { type Context, getTelemetryContext, withAbortSignal } from \"../../context.ts\";\nimport { AbortRequested } from \"../../execution/effect-gate.ts\";\nimport { applyStreamOptionsPatch } from \"../../hooks.ts\";\nimport { insertEntry, insertUsage } from \"../../session/commit.ts\";\nimport { SessionInvariantError } from \"../../session/session.ts\";\nimport {\n\ttype AssistantEffectPendingOperation,\n\ttype AssistantReadyOperation,\n\ttype BranchSummaryEntry,\n\ttype CheckpointOperation,\n\ttype CommitResult,\n\ttype CompactionEntry,\n\ttype DurableFileOperations,\n\ttype DurableStructuralPreparation,\n\ttype JsonValue,\n\ttype LaneConfiguration,\n\ttype NavigationReadyToCommitOperation,\n\ttype NewEntry,\n\ttype OperationError,\n\toperationScopeOf,\n\ttype ResultBoundary,\n\ttype SummaryContext,\n\ttype SummaryDecidingOperation,\n\ttype SummaryEffectPendingOperation,\n\ttype SummaryReadyOperation,\n\ttype SummaryRetryWaitOperation,\n\ttype SummaryTask,\n\ttype UsageRow,\n\ttype Write,\n} from \"../../session/types.ts\";\nimport { branchTip, entryLabel, operationPreparation, setValue } from \"../../session/values.ts\";\nimport type { AgentHarnessStreamOptions } from \"../../types.ts\";\nimport type { Lane } from \"../lane.ts\";\nimport { committedEntryEvents, readBoundedEntries } from \"../transcript.ts\";\nimport type { ContinueOperationResult, Drive, ProcedureResult } from \"../types.ts\";\nimport {\n\tassistantReadyAtBoundary,\n\ttype BoundaryFinishPending,\n\tboundaryPlacementEvents,\n\tfinishRunBoundary,\n\tnormalizedRetryPolicy,\n\tplanBoundaryInbox,\n} from \"./boundary.ts\";\nimport { retryDelay, retryNotBefore, waitUntil } from \"./retry.ts\";\nimport { operationCleanupWrites, operationResultRecord } from \"./terminal.ts\";\n\nclass StructuralCancelled extends Error {\n\tconstructor() {\n\t\tsuper(\"Structural generation was cancelled\");\n\t\tthis.name = \"StructuralCancelled\";\n\t}\n}\n\nfunction durableFileOperations(fileOps: CompactionPreparation[\"fileOps\"]): DurableFileOperations {\n\treturn {\n\t\tread: [...fileOps.read],\n\t\twritten: [...fileOps.written],\n\t\tedited: [...fileOps.edited],\n\t};\n}\n\nexport function durableCompactionPreparation(\n\tpreparation: CompactionPreparation,\n): Extract<DurableStructuralPreparation, { kind: \"compaction\" }> {\n\treturn {\n\t\tkind: \"compaction\",\n\t\tmessagesToSummarize: preparation.messagesToSummarize,\n\t\tturnPrefixMessages: preparation.turnPrefixMessages,\n\t\tretainedTail: preparation.retainedTail,\n\t\tisSplitTurn: preparation.isSplitTurn,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\t...(preparation.previousSummary === undefined ? {} : { previousSummary: preparation.previousSummary }),\n\t\tfileOps: durableFileOperations(preparation.fileOps),\n\t\tsettings: preparation.settings,\n\t};\n}\n\nexport function durableBranchPreparation(\n\tpreparation: BranchPreparation,\n): Extract<DurableStructuralPreparation, { kind: \"branch_summary\" }> {\n\treturn {\n\t\tkind: \"branch_summary\",\n\t\tmessages: preparation.messages,\n\t\tfileOps: durableFileOperations(preparation.fileOps),\n\t\ttotalTokens: preparation.totalTokens,\n\t};\n}\n\nfunction fileOperations(fileOps: DurableFileOperations): CompactionPreparation[\"fileOps\"] {\n\treturn {\n\t\tread: new Set(fileOps.read),\n\t\twritten: new Set(fileOps.written),\n\t\tedited: new Set(fileOps.edited),\n\t};\n}\n\nfunction compactionPreparation(\n\tpreparation: Extract<DurableStructuralPreparation, { kind: \"compaction\" }>,\n): CompactionPreparation {\n\treturn {\n\t\tmessagesToSummarize: preparation.messagesToSummarize,\n\t\tturnPrefixMessages: preparation.turnPrefixMessages,\n\t\tretainedTail: preparation.retainedTail,\n\t\tisSplitTurn: preparation.isSplitTurn,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\t...(preparation.previousSummary === undefined ? {} : { previousSummary: preparation.previousSummary }),\n\t\tfileOps: fileOperations(preparation.fileOps),\n\t\tsettings: preparation.settings,\n\t};\n}\n\nfunction branchPreparation(\n\tpreparation: Extract<DurableStructuralPreparation, { kind: \"branch_summary\" }>,\n): BranchPreparation {\n\treturn {\n\t\tmessages: preparation.messages,\n\t\tfileOps: fileOperations(preparation.fileOps),\n\t\ttotalTokens: preparation.totalTokens,\n\t};\n}\n\nfunction summaryKind(task: SummaryTask): DurableStructuralPreparation[\"kind\"] {\n\treturn task.boundary.kind === \"commit_navigation\" ? \"branch_summary\" : \"compaction\";\n}\n\nfunction compactionReason(task: SummaryTask): \"manual\" | \"threshold\" | \"overflow\" {\n\tif (task.reason !== undefined) return task.reason;\n\tif (task.boundary.kind === \"finish\") return \"manual\";\n\tthrow new SessionInvariantError(`In-run compaction task ${task.taskId} is missing its reason`);\n}\n\nfunction navigationBoundary(task: SummaryTask): Extract<ResultBoundary, { kind: \"commit_navigation\" }> {\n\tif (task.boundary.kind !== \"commit_navigation\") {\n\t\tthrow new SessionInvariantError(`Summary task ${task.taskId} is not a navigation`);\n\t}\n\treturn task.boundary;\n}\n\nasync function readStructuralPreparation<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tdeciding: SummaryDecidingOperation,\n): Promise<ContinueOperationResult<CompactionPreparation | BranchPreparation>> {\n\treturn lane.continueOperation(\n\t\tdeciding,\n\t\tasync (_state, current, _meta, reader) => {\n\t\t\tconst expected = summaryKind(current.task);\n\t\t\tconst stored = await reader.getValue(\n\t\t\t\toperationPreparation(drive.operationId, current.task.taskId),\n\t\t\t\tdrive.context,\n\t\t\t);\n\t\t\tif (stored?.value.kind !== expected) {\n\t\t\t\tthrow new SessionInvariantError(\n\t\t\t\t\t`Structural task ${current.task.taskId} is missing its ${expected} preparation`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (current.task.boundary.kind === \"commit_navigation\") {\n\t\t\t\tconst targetId = current.task.boundary.targetId;\n\t\t\t\tif (!(await reader.getEntries([targetId], drive.context)).has(targetId)) {\n\t\t\t\t\tthrow new SessionInvariantError(`Navigation target ${targetId} is missing`);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"return\",\n\t\t\t\tresult:\n\t\t\t\t\tstored.value.kind === \"compaction\"\n\t\t\t\t\t\t? compactionPreparation(stored.value)\n\t\t\t\t\t\t: branchPreparation(stored.value),\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n}\n\nfunction summaryContext<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tresultEntryId: string,\n\tconfiguration: LaneConfiguration,\n): SummaryContext {\n\treturn {\n\t\tresultEntryId,\n\t\tconfiguration,\n\t\tstreamOptions: { ...lane.readConfig().streamOptions, deferred: false },\n\t\tretryPolicy: normalizedRetryPolicy(lane),\n\t};\n}\n\nfunction usageEvent(row: Omit<UsageRow, \"seq\">, writeIndex: number, commit: CommitResult, lane: string): HarnessEvent {\n\treturn {\n\t\ttype: \"usage\",\n\t\tlane,\n\t\trow: { ...row, seq: commit.seqs[writeIndex]! },\n\t\ttotals: commit.stats.usage,\n\t};\n}\n\nfunction operationError(code: string, message: string, details?: JsonValue): OperationError {\n\treturn { code, message, ...(details === undefined ? {} : { details }) };\n}\n\ntype StructuralOutcome =\n\t| { kind: \"compaction\"; resultEntryId: string; result: CompactResult; fromHook: boolean }\n\t| { kind: \"branch_summary\"; resultEntryId: string; result: BranchSummaryResult; fromHook: boolean }\n\t| { kind: \"declined\" }\n\t| { kind: \"failed\"; error: OperationError };\n\ntype StructuralPublication = ProcedureResult | BoundaryFinishPending;\n\nasync function publishStructuralOutcome<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tcapability: SummaryDecidingOperation | SummaryReadyOperation | SummaryEffectPendingOperation,\n\toutcome: StructuralOutcome,\n): Promise<ProcedureResult> {\n\tconst hookUsageId =\n\t\t(outcome.kind === \"compaction\" || outcome.kind === \"branch_summary\") &&\n\t\toutcome.fromHook &&\n\t\toutcome.result.usage !== undefined\n\t\t\t? lane.session.idGenerator.next()\n\t\t\t: undefined;\n\tconst published = await lane.continueOperation<\n\t\tSummaryDecidingOperation | SummaryReadyOperation | SummaryEffectPendingOperation,\n\t\tStructuralPublication\n\t>(\n\t\tcapability,\n\t\tasync (state, current, meta, reader) => {\n\t\t\tconst expected = summaryKind(current.task);\n\t\t\tlet terminalCompactionEndedAt: number | undefined;\n\t\t\tif ((outcome.kind === \"compaction\" || outcome.kind === \"branch_summary\") && outcome.kind !== expected) {\n\t\t\t\tthrow new SessionInvariantError(\n\t\t\t\t\t`Structural ${outcome.kind} result does not match ${expected} task ${current.task.taskId}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst writes: Write[] = [];\n\t\t\tconst baseEvents: ((commit: CommitResult) => HarnessEvent[])[] = [];\n\t\t\tlet terminalTipId = state.tipId;\n\t\t\tif (hookUsageId !== undefined && (outcome.kind === \"compaction\" || outcome.kind === \"branch_summary\")) {\n\t\t\t\tconst usage = outcome.result.usage;\n\t\t\t\tif (usage === undefined) throw new SessionInvariantError(\"Hook usage id exists without structural usage\");\n\t\t\t\tconst row: Omit<UsageRow, \"seq\"> = { id: hookUsageId, usage, adjustment: false };\n\t\t\t\tconst writeIndex = writes.length;\n\t\t\t\twrites.push(insertUsage(row));\n\t\t\t\tbaseEvents.push((commit) => [usageEvent(row, writeIndex, commit, lane.name)]);\n\t\t\t}\n\n\t\t\tif (outcome.kind === \"compaction\") {\n\t\t\t\tconst entry: NewEntry<CompactionEntry> = {\n\t\t\t\t\tid: outcome.resultEntryId,\n\t\t\t\t\tparentId: state.tipId,\n\t\t\t\t\ttype: \"compaction\",\n\t\t\t\t\tsummary: outcome.result.summary,\n\t\t\t\t\tretainedTail: outcome.result.retainedTail,\n\t\t\t\t\ttokensBefore: outcome.result.tokensBefore,\n\t\t\t\t\t...(outcome.result.details === undefined ? {} : { details: outcome.result.details }),\n\t\t\t\t\t...(outcome.result.usage === undefined ? {} : { usage: outcome.result.usage }),\n\t\t\t\t\tfromHook: outcome.fromHook,\n\t\t\t\t};\n\t\t\t\tconst entryWriteIndex = writes.length;\n\t\t\t\twrites.push(insertEntry(entry), setValue(branchTip(lane.name), outcome.resultEntryId));\n\t\t\t\tterminalTipId = outcome.resultEntryId;\n\t\t\t\tbaseEvents.push((commit) =>\n\t\t\t\t\tcommittedEntryEvents([entry], commit, lane.name, drive.operationId, entryWriteIndex),\n\t\t\t\t);\n\t\t\t} else if (outcome.kind === \"branch_summary\") {\n\t\t\t\tconst boundary = navigationBoundary(current.task);\n\t\t\t\tconst entry: NewEntry<BranchSummaryEntry> = {\n\t\t\t\t\tid: outcome.resultEntryId,\n\t\t\t\t\tparentId: boundary.targetId,\n\t\t\t\t\ttype: \"branch_summary\",\n\t\t\t\t\tfromId: meta.sourceTipId,\n\t\t\t\t\tsummary: outcome.result.summary,\n\t\t\t\t\tdetails: { readFiles: outcome.result.readFiles, modifiedFiles: outcome.result.modifiedFiles },\n\t\t\t\t\t...(outcome.result.usage === undefined ? {} : { usage: outcome.result.usage }),\n\t\t\t\t\tfromHook: outcome.fromHook,\n\t\t\t\t};\n\t\t\t\twrites.push(setValue(branchTip(lane.name), boundary.targetId));\n\t\t\t\tconst entryWriteIndex = writes.length;\n\t\t\t\twrites.push(insertEntry(entry), setValue(branchTip(lane.name), outcome.resultEntryId));\n\t\t\t\tif (boundary.label !== undefined) writes.push(setValue(entryLabel(boundary.targetId), boundary.label));\n\t\t\t\tterminalTipId = outcome.resultEntryId;\n\t\t\t\tbaseEvents.push((commit) =>\n\t\t\t\t\tcommittedEntryEvents([entry], commit, lane.name, drive.operationId, entryWriteIndex),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst attempt =\n\t\t\t\tcurrent.at === \"summary.ready\"\n\t\t\t\t\t? current.nextAttempt\n\t\t\t\t\t: current.at === \"summary.effect_pending\"\n\t\t\t\t\t\t? current.attempt\n\t\t\t\t\t\t: undefined;\n\t\t\tif (attempt !== undefined && attempt > 1) {\n\t\t\t\tbaseEvents.push(() => [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"retry_end\",\n\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\tstep: current.task.taskId,\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\tsuccess: outcome.kind === \"compaction\" || outcome.kind === \"branch_summary\",\n\t\t\t\t\t\t...(outcome.kind === \"failed\" ? { finalError: outcome.error.message } : {}),\n\t\t\t\t\t},\n\t\t\t\t]);\n\t\t\t}\n\t\t\tif (outcome.kind === \"compaction\") {\n\t\t\t\tbaseEvents.push((commit) => [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\treason: compactionReason(current.task),\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tentryId: outcome.resultEntryId,\n\t\t\t\t\t\tendedAt: terminalCompactionEndedAt ?? commit.timestamp,\n\t\t\t\t\t},\n\t\t\t\t]);\n\t\t\t}\n\t\t\tconst events = (commit: CommitResult): HarnessEvent[] =>\n\t\t\t\tbaseEvents.flatMap((materialize) => materialize(commit));\n\t\t\tswitch (current.task.boundary.kind) {\n\t\t\t\tcase \"resume_checkpoint\": {\n\t\t\t\t\tif (outcome.kind === \"branch_summary\") {\n\t\t\t\t\t\tthrow new SessionInvariantError(\"Run compaction boundary received a branch summary\");\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\toutcome.kind === \"compaction\" ||\n\t\t\t\t\t\t(outcome.kind === \"declined\" && current.task.reason === \"threshold\")\n\t\t\t\t\t) {\n\t\t\t\t\t\tif (terminalTipId === null) throw new SessionInvariantError(\"Run compaction has no Branch tip\");\n\t\t\t\t\t\tconst continuation = current.task.boundary.resumeAfter.continuation;\n\t\t\t\t\t\tconst placement = await planBoundaryInbox(\n\t\t\t\t\t\t\tlane,\n\t\t\t\t\t\t\tdrive,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tcurrent,\n\t\t\t\t\t\t\treader,\n\t\t\t\t\t\t\tterminalTipId,\n\t\t\t\t\t\t\toutcome.kind === \"declined\" && continuation.kind === \"may_finish\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\toutcome.kind === \"declined\" &&\n\t\t\t\t\t\t\tplacement.triggerEntryId === undefined &&\n\t\t\t\t\t\t\tcontinuation.kind === \"may_finish\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: \"return\",\n\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\tkind: \"finish_pending\",\n\t\t\t\t\t\t\t\t\tentryIds: placement.entries.map((entry) => entry.id),\n\t\t\t\t\t\t\t\t} as const,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst placementWriteIndex = writes.length;\n\t\t\t\t\t\twrites.push(...placement.writes);\n\t\t\t\t\t\tlet operationState: AssistantReadyOperation | CheckpointOperation;\n\t\t\t\t\t\tif (placement.triggerEntryId !== undefined || continuation.kind === \"need_assistant\") {\n\t\t\t\t\t\t\tconst overflowRecoveryUsed =\n\t\t\t\t\t\t\t\tplacement.triggerEntryId === undefined && continuation.kind === \"need_assistant\"\n\t\t\t\t\t\t\t\t\t? continuation.overflowRecoveryUsed\n\t\t\t\t\t\t\t\t\t: false;\n\t\t\t\t\t\t\toperationState = assistantReadyAtBoundary(\n\t\t\t\t\t\t\t\tlane,\n\t\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t\tcurrent,\n\t\t\t\t\t\t\t\tplacement.triggerEntryId ?? current.task.boundary.resumeAfter.triggerEntryId,\n\t\t\t\t\t\t\t\toverflowRecoveryUsed,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\toperationState = {\n\t\t\t\t\t\t\t\t...operationScopeOf(current),\n\t\t\t\t\t\t\t\tat: \"checkpoint\",\n\t\t\t\t\t\t\t\t...current.task.boundary.resumeAfter,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: \"commit\",\n\t\t\t\t\t\t\twrites,\n\t\t\t\t\t\t\toperationState,\n\t\t\t\t\t\t\tlane: { tipId: placement.tipId, inbox: placement.inbox },\n\t\t\t\t\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\t\t\t\t\tevents: (commit) => [\n\t\t\t\t\t\t\t\t...(outcome.kind === \"compaction\"\n\t\t\t\t\t\t\t\t\t? events(commit)\n\t\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"compaction_end\" as const,\n\t\t\t\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\t\t\t\treason: \"threshold\" as const,\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: \"declined\" as const,\n\t\t\t\t\t\t\t\t\t\t\t\tendedAt: commit.timestamp,\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...boundaryPlacementEvents(\n\t\t\t\t\t\t\t\t\tplacement,\n\t\t\t\t\t\t\t\t\tcommit,\n\t\t\t\t\t\t\t\t\tplacementWriteIndex,\n\t\t\t\t\t\t\t\t\tlane.name,\n\t\t\t\t\t\t\t\t\tdrive.operationId,\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\t}\n\t\t\t\t\tif (state.tipId === null) throw new SessionInvariantError(\"Failed run has no Branch tip\");\n\t\t\t\t\tconst error =\n\t\t\t\t\t\toutcome.kind === \"declined\"\n\t\t\t\t\t\t\t? operationError(\"compaction_declined\", \"Overflow compaction was declined\")\n\t\t\t\t\t\t\t: outcome.error;\n\t\t\t\t\tconst cleanup = await operationCleanupWrites(reader, drive.operationId, current, drive.context);\n\t\t\t\t\tconst record = operationResultRecord(meta, \"failed\", state.tipId, error);\n\t\t\t\t\tconst compactionEnd: HarnessEvent =\n\t\t\t\t\t\toutcome.kind === \"declined\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\treason: compactionReason(current.task),\n\t\t\t\t\t\t\t\t\tstatus: \"declined\",\n\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\treason: compactionReason(current.task),\n\t\t\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\t\t\terror: outcome.error,\n\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"finish\",\n\t\t\t\t\t\twrites: [...writes, ...cleanup],\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\tmaterialize: () => ({ kind: \"settled\", outcome: record }) as const,\n\t\t\t\t\t\tevents: (commit) => [\n\t\t\t\t\t\t\t...events(commit),\n\t\t\t\t\t\t\tcompactionEnd,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"run_end\",\n\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tfromTipId: meta.sourceTipId,\n\t\t\t\t\t\t\t\ttipId: state.tipId,\n\t\t\t\t\t\t\t\tendedAt: record.endedAt,\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}\n\t\t\t\tcase \"finish\": {\n\t\t\t\t\tif (outcome.kind === \"branch_summary\") {\n\t\t\t\t\t\tthrow new SessionInvariantError(\"Compaction finish boundary received a branch summary\");\n\t\t\t\t\t}\n\t\t\t\t\tif (outcome.kind !== \"compaction\" && state.tipId === null) {\n\t\t\t\t\t\tthrow new SessionInvariantError(\"Standalone compaction has no Branch tip\");\n\t\t\t\t\t}\n\t\t\t\t\tconst error = outcome.kind === \"failed\" ? outcome.error : undefined;\n\t\t\t\t\tconst status =\n\t\t\t\t\t\toutcome.kind === \"declined\" ? \"declined\" : outcome.kind === \"failed\" ? \"failed\" : \"completed\";\n\t\t\t\t\tconst cleanup = await operationCleanupWrites(reader, drive.operationId, current, drive.context);\n\t\t\t\t\tconst record = operationResultRecord(meta, status, terminalTipId, error);\n\t\t\t\t\tterminalCompactionEndedAt = record.endedAt;\n\t\t\t\t\tconst compactionEnd: HarnessEvent | undefined =\n\t\t\t\t\t\toutcome.kind === \"compaction\"\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: outcome.kind === \"declined\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\t\treason: \"manual\",\n\t\t\t\t\t\t\t\t\t\tstatus: \"declined\",\n\t\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\t\treason: \"manual\",\n\t\t\t\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\t\t\t\terror: outcome.error,\n\t\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"finish\",\n\t\t\t\t\t\twrites: [...writes, ...cleanup],\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\t...(outcome.kind === \"compaction\" ? { lane: { tipId: terminalTipId } } : {}),\n\t\t\t\t\t\tmaterialize: () => ({ kind: \"settled\", outcome: record }) as const,\n\t\t\t\t\t\tevents: (commit) => [...events(commit), ...(compactionEnd === undefined ? [] : [compactionEnd])],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"commit_navigation\": {\n\t\t\t\t\tif (outcome.kind === \"compaction\") {\n\t\t\t\t\t\tthrow new SessionInvariantError(\"Navigation boundary received a compaction result\");\n\t\t\t\t\t}\n\t\t\t\t\tconst error = outcome.kind === \"failed\" ? outcome.error : undefined;\n\t\t\t\t\tconst status =\n\t\t\t\t\t\toutcome.kind === \"declined\" ? \"declined\" : outcome.kind === \"failed\" ? \"failed\" : \"completed\";\n\t\t\t\t\tconst cleanup = await operationCleanupWrites(reader, drive.operationId, current, drive.context);\n\t\t\t\t\tconst record = operationResultRecord(meta, status, terminalTipId, error);\n\t\t\t\t\tconst navigationEnd: HarnessEvent =\n\t\t\t\t\t\toutcome.kind === \"branch_summary\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttype: \"navigation_end\",\n\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\t\t\tfromTipId: meta.sourceTipId,\n\t\t\t\t\t\t\t\t\ttipId: terminalTipId,\n\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: outcome.kind === \"declined\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttype: \"navigation_end\",\n\t\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\t\tstatus: \"declined\",\n\t\t\t\t\t\t\t\t\t\tfromTipId: meta.sourceTipId,\n\t\t\t\t\t\t\t\t\t\ttipId: terminalTipId,\n\t\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\ttype: \"navigation_end\",\n\t\t\t\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\t\t\t\terror: outcome.error,\n\t\t\t\t\t\t\t\t\t\tfromTipId: meta.sourceTipId,\n\t\t\t\t\t\t\t\t\t\ttipId: terminalTipId,\n\t\t\t\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"finish\",\n\t\t\t\t\t\twrites: [...writes, ...cleanup],\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\t...(outcome.kind === \"branch_summary\" ? { lane: { tipId: terminalTipId } } : {}),\n\t\t\t\t\t\tmaterialize: () => ({ kind: \"settled\", outcome: record }) as const,\n\t\t\t\t\t\tevents: (commit) => [...events(commit), navigationEnd],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tdrive.context,\n\t);\n\tif (published.kind === \"cancel_requested\") return { kind: \"continue\" };\n\tif (published.value.kind !== \"finish_pending\") return published.value;\n\tconst boundary = capability.task.boundary;\n\tif (boundary.kind !== \"resume_checkpoint\" || boundary.resumeAfter.continuation.kind !== \"may_finish\") {\n\t\tthrow new SessionInvariantError(\"Structural finish mediation requires a resumable finish boundary\");\n\t}\n\treturn finishRunBoundary(lane, drive, capability, boundary.resumeAfter.continuation, published.value.entryIds, [\n\t\t{\n\t\t\ttype: \"compaction_end\",\n\t\t\tlane: lane.name,\n\t\t\trunId: drive.operationId,\n\t\t\treason: \"threshold\",\n\t\t\tstatus: \"declined\",\n\t\t\tendedAt: Date.now(),\n\t\t},\n\t]);\n}\n\nasync function publishStructuralReady<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tdeciding: SummaryDecidingOperation,\n): Promise<ProcedureResult> {\n\tconst resultEntryId = lane.session.idGenerator.next();\n\tconst published = await lane.continueOperation(\n\t\tdeciding,\n\t\t(state, current) => {\n\t\t\tconst operationState: SummaryReadyOperation = {\n\t\t\t\t...operationScopeOf(current),\n\t\t\t\tat: \"summary.ready\",\n\t\t\t\ttask: current.task,\n\t\t\t\tsummaryContext: summaryContext(lane, resultEntryId, state.configuration),\n\t\t\t\tnextAttempt: 1,\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tkind: \"commit\",\n\t\t\t\twrites: [],\n\t\t\t\toperationState,\n\t\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n\treturn published.kind === \"cancel_requested\" ? { kind: \"continue\" } : published.value;\n}\n\n/** Consume one durable structural preparation and decision hook. */\nexport async function runStructuralDecision<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tdeciding: SummaryDecidingOperation,\n): Promise<ProcedureResult> {\n\tconst preparation = await readStructuralPreparation(lane, drive, deciding);\n\tif (preparation.kind === \"cancel_requested\") return { kind: \"continue\" };\n\tif (deciding.task.boundary.kind === \"commit_navigation\") {\n\t\tif (!(\"messages\" in preparation.value)) {\n\t\t\tthrow new SessionInvariantError(\"Navigation task has invalid durable preparation\");\n\t\t}\n\t\tconst hook = await lane.hooks.runWithGate(\n\t\t\t\"before_navigation\",\n\t\t\t{\n\t\t\t\tlane: lane.name,\n\t\t\t\trunId: drive.operationId,\n\t\t\t\ttargetId: deciding.task.boundary.targetId,\n\t\t\t\tpreparation: preparation.value,\n\t\t\t\t...(deciding.task.customInstructions === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { customInstructions: deciding.task.customInstructions }),\n\t\t\t},\n\t\t\tdrive.gate,\n\t\t\tdrive.context,\n\t\t);\n\t\tif (hook?.decline === true) return publishStructuralOutcome(lane, drive, deciding, { kind: \"declined\" });\n\t\tif (hook?.summary !== undefined) {\n\t\t\treturn publishStructuralOutcome(lane, drive, deciding, {\n\t\t\t\tkind: \"branch_summary\",\n\t\t\t\tresultEntryId: lane.session.idGenerator.next(),\n\t\t\t\tresult: hook.summary,\n\t\t\t\tfromHook: true,\n\t\t\t});\n\t\t}\n\t\treturn publishStructuralReady(lane, drive, deciding);\n\t}\n\n\tif (!(\"messagesToSummarize\" in preparation.value)) {\n\t\tthrow new SessionInvariantError(\"Compaction task has invalid durable preparation\");\n\t}\n\tconst hook = await lane.hooks.runWithGate(\n\t\t\"before_compaction\",\n\t\t{\n\t\t\tlane: lane.name,\n\t\t\trunId: drive.operationId,\n\t\t\treason: compactionReason(deciding.task),\n\t\t\tpreparation: preparation.value,\n\t\t\t...(deciding.task.customInstructions === undefined\n\t\t\t\t? {}\n\t\t\t\t: { customInstructions: deciding.task.customInstructions }),\n\t\t},\n\t\tdrive.gate,\n\t\tdrive.context,\n\t);\n\tif (hook?.decline === true) return publishStructuralOutcome(lane, drive, deciding, { kind: \"declined\" });\n\tif (hook?.compaction !== undefined) {\n\t\treturn publishStructuralOutcome(lane, drive, deciding, {\n\t\t\tkind: \"compaction\",\n\t\t\tresultEntryId: lane.session.idGenerator.next(),\n\t\t\tresult: hook.compaction,\n\t\t\tfromHook: true,\n\t\t});\n\t}\n\treturn publishStructuralReady(lane, drive, deciding);\n}\n\nfunction effectPendingFromReady(ready: SummaryReadyOperation): SummaryEffectPendingOperation {\n\treturn {\n\t\t...operationScopeOf(ready),\n\t\tat: \"summary.effect_pending\",\n\t\ttask: ready.task,\n\t\tsummaryContext: ready.summaryContext,\n\t\tattempt: ready.nextAttempt,\n\t\tusageIds: [],\n\t};\n}\n\nfunction retryWaitFromEffect(effect: SummaryEffectPendingOperation, errorMessage: string): SummaryRetryWaitOperation {\n\treturn {\n\t\t...operationScopeOf(effect),\n\t\tat: \"summary.retry_wait\",\n\t\ttask: effect.task,\n\t\tsummaryContext: effect.summaryContext,\n\t\tnextAttempt: effect.attempt + 1,\n\t\tnotBefore: retryNotBefore(effect.summaryContext.retryPolicy.baseDelayMs, effect.attempt),\n\t\terrorMessage,\n\t};\n}\n\nfunction readyFromRetryWait(retry: SummaryRetryWaitOperation): SummaryReadyOperation {\n\treturn {\n\t\t...operationScopeOf(retry),\n\t\tat: \"summary.ready\",\n\t\ttask: retry.task,\n\t\tsummaryContext: retry.summaryContext,\n\t\tnextAttempt: retry.nextAttempt,\n\t};\n}\n\nasync function publishAttemptIntent<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tready: SummaryReadyOperation,\n): Promise<ContinueOperationResult<SummaryEffectPendingOperation>> {\n\treturn lane.continueOperation(\n\t\tready,\n\t\t(_state, current) => {\n\t\t\tconst effectPending = effectPendingFromReady(current);\n\t\t\treturn {\n\t\t\t\tkind: \"commit\",\n\t\t\t\twrites: [],\n\t\t\t\toperationState: effectPending,\n\t\t\t\tmaterialize: () => effectPending,\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n}\n\nasync function publishNestedRequestIntent<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\teffect: SummaryEffectPendingOperation,\n\tindex: number,\n\tusageId: string,\n): Promise<ContinueOperationResult<SummaryEffectPendingOperation>> {\n\treturn lane.continueOperation(\n\t\teffect,\n\t\t(_state, current) => {\n\t\t\tconst next = { ...current, request: { index, usageId } };\n\t\t\treturn {\n\t\t\t\tkind: \"commit\",\n\t\t\t\twrites: [],\n\t\t\t\toperationState: next,\n\t\t\t\tmaterialize: () => next,\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n}\n\nasync function publishNestedRequestOutcome<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\teffect: SummaryEffectPendingOperation,\n\tusageId: string,\n\tresponse: AssistantMessage,\n): Promise<void> {\n\tawait lane.settleOperation(\n\t\teffect,\n\t\t(_state, current) => {\n\t\t\tconst next = { ...current, usageIds: [...current.usageIds, usageId] };\n\t\t\tdelete next.request;\n\t\t\tconst row: Omit<UsageRow, \"seq\"> = { id: usageId, usage: response.usage, adjustment: false };\n\t\t\treturn {\n\t\t\t\tkind: \"commit\",\n\t\t\t\twrites: [insertUsage(row)],\n\t\t\t\toperationState: next,\n\t\t\t\tmaterialize: () => undefined,\n\t\t\t\tevents: (commit) => [usageEvent(row, 0, commit, lane.name)],\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n}\n\nfunction requestStreamOptions(\n\toptions: SimpleStreamOptions,\n\tstreamOptions: AgentHarnessStreamOptions,\n\tcontext: Context,\n\tonPayload: NonNullable<SimpleStreamOptions[\"onPayload\"]>,\n): SimpleStreamOptions {\n\treturn {\n\t\t...options,\n\t\ttransport: streamOptions.transport,\n\t\ttimeoutMs: streamOptions.timeoutMs,\n\t\tmaxRetries: streamOptions.maxRetries,\n\t\tmaxRetryDelayMs: streamOptions.maxRetryDelayMs,\n\t\theaders: streamOptions.headers,\n\t\tmetadata: streamOptions.metadata,\n\t\tcacheRetention: \"none\",\n\t\tdeferred: false,\n\t\tsignal: context.abortSignal,\n\t\ttelemetryContext: getTelemetryContext(context),\n\t\tonPayload,\n\t};\n}\n\nasync function performStructuralAttempt<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\teffect: SummaryEffectPendingOperation,\n\tmodel: Model<Api>,\n\tpreparation: CompactionPreparation | BranchPreparation,\n): Promise<\n\t| { kind: \"compaction\"; result: CompactResult; retryable: boolean }\n\t| { kind: \"branch_summary\"; result: BranchSummaryResult; retryable: boolean }\n\t| { kind: \"error\"; error: OperationError; retryable: boolean }\n\t| { kind: \"cancel_requested\" }\n> {\n\tlet requestIndex = 0;\n\tlet lastResponse: AssistantMessage | undefined;\n\tconst request: SummaryRequest = async (aiContext, options, requestContext) => {\n\t\tconst baseOptions: AgentHarnessStreamOptions = { ...effect.summaryContext.streamOptions, deferred: false };\n\t\tconst beforeRequest = await lane.hooks\n\t\t\t.runWithGate(\n\t\t\t\t\"before_request\",\n\t\t\t\t{\n\t\t\t\t\tlane: lane.name,\n\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\tmodel,\n\t\t\t\t\tstep: summaryKind(effect.task),\n\t\t\t\t\tattempt: effect.attempt,\n\t\t\t\t\tstreamOptions: baseOptions,\n\t\t\t\t},\n\t\t\t\tdrive.gate,\n\t\t\t\trequestContext,\n\t\t\t)\n\t\t\t.catch(async (error: unknown) => {\n\t\t\t\tif (!(error instanceof AbortRequested)) throw error;\n\t\t\t\tawait error.cancellation;\n\t\t\t\tthrow new StructuralCancelled();\n\t\t\t});\n\t\tconst streamOptions = {\n\t\t\t...(beforeRequest?.streamOptions === undefined\n\t\t\t\t? baseOptions\n\t\t\t\t: applyStreamOptionsPatch(baseOptions, beforeRequest.streamOptions)),\n\t\t\tdeferred: false as const,\n\t\t};\n\t\tconst usageId = lane.session.idGenerator.next();\n\t\tconst intent = await publishNestedRequestIntent(lane, drive, effect, requestIndex, usageId);\n\t\trequestIndex += 1;\n\t\tif (intent.kind === \"cancel_requested\") throw new StructuralCancelled();\n\t\tconst admittedContext = withAbortSignal(drive.gate.signal, requestContext);\n\t\tlet response: AssistantMessage;\n\t\ttry {\n\t\t\tresponse = await drive.gate.admit(() =>\n\t\t\t\tlane.models.completeSimple(\n\t\t\t\t\tmodel,\n\t\t\t\t\taiContext,\n\t\t\t\t\trequestStreamOptions(options, streamOptions, admittedContext, async (payload, requestModel) => {\n\t\t\t\t\t\tconst hook = await lane.hooks.runWithGate(\n\t\t\t\t\t\t\t\"before_payload\",\n\t\t\t\t\t\t\t{ lane: lane.name, runId: drive.operationId, model: requestModel, payload },\n\t\t\t\t\t\t\tdrive.gate,\n\t\t\t\t\t\t\tadmittedContext,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn hook?.payload;\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof AbortRequested)) throw error;\n\t\t\tawait error.cancellation;\n\t\t\tthrow new StructuralCancelled();\n\t\t}\n\t\tlastResponse = response;\n\t\tawait publishNestedRequestOutcome(lane, drive, intent.value, usageId, response);\n\t\treturn response;\n\t};\n\n\ttry {\n\t\tif (summaryKind(effect.task) === \"compaction\") {\n\t\t\tif (!(\"messagesToSummarize\" in preparation)) {\n\t\t\t\tthrow new SessionInvariantError(\"Compaction summary has invalid durable preparation\");\n\t\t\t}\n\t\t\tconst result = await compactWithRequest(\n\t\t\t\tpreparation,\n\t\t\t\t{\n\t\t\t\t\tmodel,\n\t\t\t\t\tcustomInstructions: effect.task.customInstructions,\n\t\t\t\t\tthinkingLevel: effect.summaryContext.configuration.thinkingLevel,\n\t\t\t\t},\n\t\t\t\trequest,\n\t\t\t\tdrive.context,\n\t\t\t);\n\t\t\tif (!result.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\terror: operationError(result.error.code, result.error.message),\n\t\t\t\t\tretryable: lastResponse !== undefined && isRetryableAssistantError(lastResponse),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"compaction\",\n\t\t\t\tresult: result.value,\n\t\t\t\tretryable: lastResponse !== undefined && isRetryableAssistantError(lastResponse),\n\t\t\t};\n\t\t}\n\n\t\tif (!(\"messages\" in preparation)) {\n\t\t\tthrow new SessionInvariantError(\"Branch summary has invalid durable preparation\");\n\t\t}\n\t\tconst result = await generateBranchSummaryWithRequest(\n\t\t\tpreparation,\n\t\t\t{ customInstructions: effect.task.customInstructions },\n\t\t\trequest,\n\t\t\tdrive.context,\n\t\t);\n\t\tif (!result.ok) {\n\t\t\treturn {\n\t\t\t\tkind: \"error\",\n\t\t\t\terror: operationError(result.error.code, result.error.message),\n\t\t\t\tretryable: lastResponse !== undefined && isRetryableAssistantError(lastResponse),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: \"branch_summary\",\n\t\t\tresult: result.value,\n\t\t\tretryable: lastResponse !== undefined && isRetryableAssistantError(lastResponse),\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof StructuralCancelled) return { kind: \"cancel_requested\" };\n\t\tthrow error;\n\t}\n}\n\nasync function readAttemptPreparation<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tready: SummaryReadyOperation,\n): Promise<ContinueOperationResult<CompactionPreparation | BranchPreparation>> {\n\treturn lane.continueOperation(\n\t\tready,\n\t\tasync (_state, current, _meta, reader) => {\n\t\t\tconst expected = summaryKind(current.task);\n\t\t\tconst stored = await reader.getValue(\n\t\t\t\toperationPreparation(drive.operationId, current.task.taskId),\n\t\t\t\tdrive.context,\n\t\t\t);\n\t\t\tif (stored === undefined || stored.value.kind !== expected) {\n\t\t\t\tthrow new SessionInvariantError(`Structural task ${current.task.taskId} has invalid durable preparation`);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"return\",\n\t\t\t\tresult:\n\t\t\t\t\tstored.value.kind === \"compaction\"\n\t\t\t\t\t\t? compactionPreparation(stored.value)\n\t\t\t\t\t\t: branchPreparation(stored.value),\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n}\n\nasync function publishAttemptResult<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\teffect: SummaryEffectPendingOperation,\n\tresult: Awaited<ReturnType<typeof performStructuralAttempt<TContext>>>,\n): Promise<ProcedureResult> {\n\tif (result.kind === \"cancel_requested\") return { kind: \"continue\" };\n\tif (result.kind === \"compaction\") {\n\t\treturn publishStructuralOutcome(lane, drive, effect, {\n\t\t\tkind: \"compaction\",\n\t\t\tresultEntryId: effect.summaryContext.resultEntryId,\n\t\t\tresult: result.result,\n\t\t\tfromHook: false,\n\t\t});\n\t}\n\tif (result.kind === \"branch_summary\") {\n\t\treturn publishStructuralOutcome(lane, drive, effect, {\n\t\t\tkind: \"branch_summary\",\n\t\t\tresultEntryId: effect.summaryContext.resultEntryId,\n\t\t\tresult: result.result,\n\t\t\tfromHook: false,\n\t\t});\n\t}\n\tif (result.error.code === \"aborted\" && lane.state.operation!.state.control.status === \"running\") {\n\t\tthrow new SessionInvariantError(\"Structural provider response is aborted while durable control is running\");\n\t}\n\tif (result.retryable && effect.attempt < effect.summaryContext.retryPolicy.maxAttempts) {\n\t\tconst retryWait = retryWaitFromEffect(effect, result.error.message);\n\t\tconst published = await lane.continueOperation(\n\t\t\teffect,\n\t\t\t() => ({\n\t\t\t\tkind: \"commit\",\n\t\t\t\twrites: [],\n\t\t\t\toperationState: retryWait,\n\t\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\t\tevents: () => [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"retry_scheduled\",\n\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\tstep: effect.task.taskId,\n\t\t\t\t\t\tattempt: retryWait.nextAttempt,\n\t\t\t\t\t\tmaxAttempts: effect.summaryContext.retryPolicy.maxAttempts,\n\t\t\t\t\t\tdelayMs: retryDelay(effect.summaryContext.retryPolicy.baseDelayMs, effect.attempt),\n\t\t\t\t\t\tnotBefore: retryWait.notBefore,\n\t\t\t\t\t\terrorMessage: result.error.message,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}),\n\t\t\tdrive.context,\n\t\t);\n\t\treturn published.kind === \"cancel_requested\" ? { kind: \"continue\" } : published.value;\n\t}\n\treturn publishStructuralOutcome(lane, drive, effect, { kind: \"failed\", error: result.error });\n}\n\n/** Execute one ready structural generation attempt. */\nexport async function runStructuralGeneration<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tready: SummaryReadyOperation,\n): Promise<ProcedureResult> {\n\tconst preparation = await readAttemptPreparation(lane, drive, ready);\n\tif (preparation.kind === \"cancel_requested\") return { kind: \"continue\" };\n\tconst identity = ready.summaryContext.configuration.model;\n\tconst model = lane.models.getModel(identity.provider, identity.modelId);\n\tif (model === undefined) {\n\t\treturn publishStructuralOutcome(lane, drive, ready, {\n\t\t\tkind: \"failed\",\n\t\t\terror: operationError(\"model_unavailable\", \"The configured model is unavailable in this process\", identity),\n\t\t});\n\t}\n\tconst intent = await publishAttemptIntent(lane, drive, ready);\n\tif (intent.kind === \"cancel_requested\") return { kind: \"continue\" };\n\tconst result = await performStructuralAttempt(lane, drive, intent.value, model, preparation.value);\n\treturn publishAttemptResult(lane, drive, intent.value, result);\n}\n\n/** Consume one structural retry wait without starting a provider effect. */\nexport async function runStructuralRetryWait<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tretry: SummaryRetryWaitOperation,\n): Promise<ProcedureResult> {\n\tif (Date.now() < retry.notBefore) {\n\t\tif (!drive.waitForRetry) {\n\t\t\treturn {\n\t\t\t\tkind: \"waiting\",\n\t\t\t\toutcome: {\n\t\t\t\t\tkind: \"waiting\",\n\t\t\t\t\toperationId: drive.operationId,\n\t\t\t\t\treason: \"retry\",\n\t\t\t\t\tnotBefore: retry.notBefore,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tawait drive.gate.admit(() => waitUntil(retry.notBefore, drive.gate.signal));\n\t}\n\tconst published = await lane.continueOperation(\n\t\tretry,\n\t\t(_state, current) => {\n\t\t\tconst ready = readyFromRetryWait(current);\n\t\t\treturn {\n\t\t\t\tkind: \"commit\",\n\t\t\t\twrites: [],\n\t\t\t\toperationState: ready,\n\t\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\t\tevents: () => [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"retry_start\",\n\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\tstep: current.task.taskId,\n\t\t\t\t\t\tattempt: current.nextAttempt,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t},\n\t\tdrive.context,\n\t);\n\treturn published.kind === \"cancel_requested\" ? { kind: \"continue\" } : published.value;\n}\n\n/** Convert an orphaned structural attempt into a fresh numbered attempt or terminal failure. */\nexport async function recoverStructuralGeneration<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\teffect: SummaryEffectPendingOperation,\n): Promise<ProcedureResult> {\n\tconst error = operationError(\n\t\t\"structural_interrupted\",\n\t\t\"Structural summary attempt was interrupted and its external outcome is unknown\",\n\t);\n\tif (effect.attempt >= effect.summaryContext.retryPolicy.maxAttempts) {\n\t\treturn publishStructuralOutcome(lane, drive, effect, { kind: \"failed\", error });\n\t}\n\tconst retryWait = retryWaitFromEffect(effect, error.message);\n\tconst published = await lane.continueOperation(\n\t\teffect,\n\t\t() => ({\n\t\t\tkind: \"commit\",\n\t\t\twrites: [],\n\t\t\toperationState: retryWait,\n\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\tevents: () => [\n\t\t\t\t{\n\t\t\t\t\ttype: \"retry_scheduled\",\n\t\t\t\t\tlane: lane.name,\n\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\tstep: effect.task.taskId,\n\t\t\t\t\tattempt: retryWait.nextAttempt,\n\t\t\t\t\tmaxAttempts: effect.summaryContext.retryPolicy.maxAttempts,\n\t\t\t\t\tdelayMs: retryDelay(effect.summaryContext.retryPolicy.baseDelayMs, effect.attempt),\n\t\t\t\t\tnotBefore: retryWait.notBefore,\n\t\t\t\t\terrorMessage: error.message,\n\t\t\t\t\trecovery: true,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tdrive.context,\n\t);\n\treturn published.kind === \"cancel_requested\" ? { kind: \"continue\" } : published.value;\n}\n\n/** Prepare threshold compaction only when no newer compaction already guards this trigger. */\nexport async function prepareCompactionThreshold<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tcheckpoint: CheckpointOperation,\n): Promise<ContinueOperationResult<{ taskId: string; preparation: DurableStructuralPreparation } | undefined>> {\n\tconst settings = checkpoint.settings.compaction;\n\tconst identity = lane.state.configuration.model;\n\tconst model = lane.models.getModel(identity.provider, identity.modelId);\n\tif (!settings.enabled || model === undefined) return { kind: \"result\", value: undefined };\n\tconst path = await readBoundedEntries(lane, drive, checkpoint);\n\tif (path.kind === \"cancel_requested\") return path;\n\tconst triggerIndex = path.value.findIndex((entry) => entry.id === checkpoint.triggerEntryId);\n\tlet newestCompactionIndex = -1;\n\tfor (let index = path.value.length - 1; index >= 0; index--) {\n\t\tif (path.value[index]!.type === \"compaction\") {\n\t\t\tnewestCompactionIndex = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (newestCompactionIndex >= triggerIndex && newestCompactionIndex !== -1) {\n\t\treturn { kind: \"result\", value: undefined };\n\t}\n\tif (triggerIndex === -1) {\n\t\tthrow new SessionInvariantError(`Checkpoint trigger ${checkpoint.triggerEntryId} is missing from its Branch`);\n\t}\n\tconst prepared = prepareCompaction(path.value, settings);\n\tif (!prepared.ok) throw prepared.error;\n\tif (prepared.value === undefined || !shouldCompact(prepared.value.tokensBefore, model.contextWindow, settings)) {\n\t\treturn { kind: \"result\", value: undefined };\n\t}\n\treturn {\n\t\tkind: \"result\",\n\t\tvalue: { taskId: lane.session.idGenerator.next(), preparation: durableCompactionPreparation(prepared.value) },\n\t};\n}\n\n/** Prepare one overflow compaction before the response settlement transaction. */\nexport async function prepareOverflowCompaction<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tgeneration: AssistantEffectPendingOperation,\n): Promise<{ taskId: string; preparation: DurableStructuralPreparation } | undefined> {\n\tif (generation.generationContext.overflowRecoveryUsed) return undefined;\n\tconst path = await readBoundedEntries(lane, drive, generation);\n\tif (path.kind === \"cancel_requested\") return undefined;\n\tconst prepared = prepareCompaction(path.value, generation.settings.compaction);\n\tif (!prepared.ok) throw prepared.error;\n\tif (prepared.value === undefined) return undefined;\n\treturn {\n\t\ttaskId: lane.session.idGenerator.next(),\n\t\tpreparation: durableCompactionPreparation(prepared.value),\n\t};\n}\n\n/** Atomically move an unsummarized navigation and finish its operation. */\nexport function commitNavigation<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tnavigation: NavigationReadyToCommitOperation,\n): Promise<ProcedureResult> {\n\treturn lane\n\t\t.continueOperation(\n\t\t\tnavigation,\n\t\t\tasync (_state, current, meta, reader) => {\n\t\t\t\tif (\n\t\t\t\t\tcurrent.targetId !== null &&\n\t\t\t\t\t!(await reader.getEntries([current.targetId], drive.context)).has(current.targetId)\n\t\t\t\t) {\n\t\t\t\t\tthrow new SessionInvariantError(`Navigation target ${current.targetId} is missing`);\n\t\t\t\t}\n\t\t\t\tif (current.targetId === meta.sourceTipId) {\n\t\t\t\t\tthrow new SessionInvariantError(\"Navigation target must differ from its source tip\");\n\t\t\t\t}\n\t\t\t\tif (current.targetId === null && current.label !== undefined) {\n\t\t\t\t\tthrow new SessionInvariantError(\"Root navigation cannot set a label\");\n\t\t\t\t}\n\t\t\t\tconst writes: Write[] = [setValue(branchTip(lane.name), current.targetId)];\n\t\t\t\tif (current.label !== undefined && current.targetId !== null) {\n\t\t\t\t\twrites.push(setValue(entryLabel(current.targetId), current.label));\n\t\t\t\t}\n\t\t\t\tconst cleanup = await operationCleanupWrites(reader, drive.operationId, current, drive.context);\n\t\t\t\tconst record = operationResultRecord(meta, \"completed\", current.targetId);\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"finish\",\n\t\t\t\t\twrites: [...writes, ...cleanup],\n\t\t\t\t\trecord,\n\t\t\t\t\tlane: { tipId: current.targetId },\n\t\t\t\t\tmaterialize: () => ({ kind: \"settled\", outcome: record }) as const,\n\t\t\t\t\tevents: () => [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"navigation_end\",\n\t\t\t\t\t\t\tlane: lane.name,\n\t\t\t\t\t\t\trunId: drive.operationId,\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\tfromTipId: meta.sourceTipId,\n\t\t\t\t\t\t\ttipId: current.targetId,\n\t\t\t\t\t\t\tendedAt: record.endedAt,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t},\n\t\t\tdrive.context,\n\t\t)\n\t\t.then((result) => (result.kind === \"cancel_requested\" ? { kind: \"continue\" } : result.value));\n}\n"]}