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AAM,EACtB,oBAAoB,EAAE,OAAO,GAC3B,uBAAuB,CAezB;AAED,oFAAoF;AACpF,wBAAsB,iBAAiB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EAC1E,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE,cAAc,EACrB,MAAM,EAAE,aAAa,EACrB,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,qBAAqB,EAAE,OAAO,GAC5B,OAAO,CAAC,iBAAiB,CAAC,CA6D5B;AAED,wBAAgB,uBAAuB,CACtC,SAAS,EAAE,iBAAiB,EAC5B,MAAM,EAAE,YAAY,EACpB,eAAe,EAAE,MAAM,EACvB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GACX,YAAY,EAAE,CAKhB;AAED,6FAA6F;AAC7F,wBAAsB,iBAAiB,CAAC,QAAQ,SAAS,MAAM,GAAG,SAAS,EAAE,MAAM,SAAS,uBAAuB,EAClH,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,OAAO,CAAC,mBAAmB,CAAC,cAAc,CAAC,EAAE;IAAE,IAAI,EAAE,YAAY,CAAA;CAAE,CAAC,EAClF,eAAe,EAAE,SAAS,MAAM,EAAE,EAClC,aAAa,GAAE,YAAY,EAAO,GAChC,OAAO,CAAC,eAAe,CAAC,CA2F1B","sourcesContent":["import type { HarnessEvent, LaneQueuedItem } from \"../../agent-harness.ts\";\nimport { insertEntry } from \"../../session/commit.ts\";\nimport { SessionInvariantError } from \"../../session/session.ts\";\nimport type {\n\tAssistantReadyOperation,\n\tCheckpointOperation,\n\tCommitResult,\n\tNewEntry,\n\tNormalizedRetryPolicy,\n\tOperationScope,\n\tSessionReader,\n\tSummaryDecidingOperation,\n\tSummaryEffectPendingOperation,\n\tSummaryReadyOperation,\n\tWrite,\n} from \"../../session/types.ts\";\nimport { branchTip, deleteValue, pendingEntry, setValue } from \"../../session/values.ts\";\nimport type { Lane } from \"../lane.ts\";\nimport { committedEntryEvents, entryLifecycleEvents, readBoundedContext, readLaneQueues } from \"../transcript.ts\";\nimport type { Drive, LaneState, ProcedureResult } from \"../types.ts\";\nimport { operationCleanupWrites, operationResultRecord } from \"./terminal.ts\";\n\nexport interface BoundaryFinishPending {\n\tkind: \"finish_pending\";\n\tentryIds: string[];\n}\n\nexport interface BoundaryPlacement {\n\tentries: NewEntry[];\n\twrites: Write[];\n\ttipId: string | null;\n\tinbox: LaneState[\"inbox\"];\n\ttriggerEntryId?: string;\n\tqueues?: LaneQueuedItem[];\n}\n\ntype FinishBoundaryOperation =\n\t| CheckpointOperation\n\t| SummaryDecidingOperation\n\t| SummaryReadyOperation\n\t| SummaryEffectPendingOperation;\n\nexport function normalizedRetryPolicy<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n): NormalizedRetryPolicy {\n\tconst retry = lane.readConfig().retryPolicy;\n\treturn retry.enabled\n\t\t? { maxAttempts: retry.maxRetries + 1, baseDelayMs: retry.baseDelayMs }\n\t\t: { maxAttempts: 1, baseDelayMs: retry.baseDelayMs };\n}\n\nexport function assistantReadyAtBoundary<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tstate: LaneState,\n\tscope: OperationScope,\n\ttriggerEntryId: string,\n\toverflowRecoveryUsed: boolean,\n): AssistantReadyOperation {\n\tconst config = lane.readConfig();\n\treturn {\n\t\t...scope,\n\t\tat: \"assistant.ready\",\n\t\tgenerationContext: {\n\t\t\tstepId: lane.session.idGenerator.next(),\n\t\t\ttriggerEntryId,\n\t\t\tconfiguration: state.configuration,\n\t\t\tstreamOptions: config.streamOptions,\n\t\t\tretryPolicy: normalizedRetryPolicy(lane),\n\t\t\toverflowRecoveryUsed,\n\t\t},\n\t\tnextAttempt: 1,\n\t};\n}\n\n/** Select and materialize one boundary's lane-owned input without committing it. */\nexport async function planBoundaryInbox<TContext extends object | undefined>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tstate: LaneState,\n\tscope: OperationScope,\n\treader: SessionReader,\n\ttipId: string | null,\n\tfollowUpWhenNoTrigger: boolean,\n): Promise<BoundaryPlacement> {\n\tconst steer = state.inbox.filter((item) => item.kind === \"steer\");\n\tconst selectedSteer = scope.settings.steeringMode === \"all\" ? steer : steer.slice(0, 1);\n\tlet selected = state.inbox.filter(\n\t\t(item) => item.kind === \"write\" || selectedSteer.some((candidate) => candidate.entryId === item.entryId),\n\t);\n\tconst load = (items: typeof selected) =>\n\t\tPromise.all(\n\t\t\titems.map(async (item) => {\n\t\t\t\tconst stored = await reader.getValue(pendingEntry(item.entryId), drive.context);\n\t\t\t\tif (stored === undefined) {\n\t\t\t\t\tthrow new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);\n\t\t\t\t}\n\t\t\t\tif (item.kind !== \"write\" && stored.value.type !== \"message\") {\n\t\t\t\t\tthrow new SessionInvariantError(`Queued ${item.kind} entry ${item.entryId} is not a message`);\n\t\t\t\t}\n\t\t\t\treturn { item, pending: stored.value };\n\t\t\t}),\n\t\t);\n\tlet pending = await load(selected);\n\tconst projects = (value: (typeof pending)[number][\"pending\"]): boolean =>\n\t\tvalue.type === \"message\" || lane.readConfig().entryProjectors[value.customType] !== undefined;\n\tif (followUpWhenNoTrigger && !pending.some(({ pending: value }) => projects(value))) {\n\t\tconst followUp = state.inbox.filter((item) => item.kind === \"followUp\");\n\t\tconst selectedFollowUp = scope.settings.followUpMode === \"all\" ? followUp : followUp.slice(0, 1);\n\t\tselected = [...selected, ...selectedFollowUp].sort((a, b) => state.inbox.indexOf(a) - state.inbox.indexOf(b));\n\t\tpending = await load(selected);\n\t}\n\n\tlet parentId = tipId;\n\tlet triggerEntryId: string | undefined;\n\tconst entries: NewEntry[] = pending.map(({ item, pending: value }) => {\n\t\tconst entry: NewEntry =\n\t\t\tvalue.type === \"message\"\n\t\t\t\t? { id: item.entryId, parentId, type: \"message\", message: value.payload }\n\t\t\t\t: {\n\t\t\t\t\t\tid: item.entryId,\n\t\t\t\t\t\tparentId,\n\t\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\t\tcustomType: value.customType,\n\t\t\t\t\t\t...(value.payload === undefined ? {} : { data: value.payload }),\n\t\t\t\t\t};\n\t\tparentId = item.entryId;\n\t\tif (projects(value)) triggerEntryId = item.entryId;\n\t\treturn entry;\n\t});\n\tconst selectedIds = new Set(selected.map((item) => item.entryId));\n\tconst inbox = state.inbox.filter((item) => !selectedIds.has(item.entryId));\n\tconst queues = selected.length === 0 ? undefined : await readLaneQueues(reader, inbox, drive.context);\n\treturn {\n\t\tentries,\n\t\twrites: [\n\t\t\t...entries.map((entry) => insertEntry(entry)),\n\t\t\t...selected.map((item) => deleteValue(pendingEntry(item.entryId))),\n\t\t\t...(entries.length === 0 ? [] : [setValue(branchTip(lane.name), parentId)]),\n\t\t],\n\t\ttipId: parentId,\n\t\tinbox,\n\t\t...(triggerEntryId === undefined ? {} : { triggerEntryId }),\n\t\t...(queues === undefined ? {} : { queues }),\n\t};\n}\n\nexport function boundaryPlacementEvents(\n\tplacement: BoundaryPlacement,\n\tcommit: CommitResult,\n\tfirstWriteIndex: number,\n\tlane: string,\n\trunId: string,\n): HarnessEvent[] {\n\treturn [\n\t\t...committedEntryEvents(placement.entries, commit, lane, runId, firstWriteIndex),\n\t\t...(placement.queues === undefined ? [] : [{ type: \"queue_update\" as const, lane, queues: placement.queues }]),\n\t];\n}\n\n/** Replan after before_run_end and commit either renewed work or the terminal run result. */\nexport async function finishRunBoundary<TContext extends object | undefined, TState extends FinishBoundaryOperation>(\n\tlane: Lane<TContext>,\n\tdrive: Drive,\n\tcapability: TState,\n\tcontinuation: Extract<CheckpointOperation[\"continuation\"], { kind: \"may_finish\" }>,\n\tplannedEntryIds: readonly string[],\n\tpendingEvents: HarnessEvent[] = [],\n): Promise<ProcedureResult> {\n\tconst context = await readBoundedContext(lane, drive, capability);\n\tif (context.kind === \"cancel_requested\") return { kind: \"continue\" };\n\tconst hook = await lane.hooks.runWithGate(\n\t\t\"before_run_end\",\n\t\t{ lane: lane.name, runId: drive.operationId, messages: context.value },\n\t\tdrive.gate,\n\t\tdrive.context,\n\t);\n\tconst followUp =\n\t\thook?.followUp === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\tid: lane.session.idGenerator.next(),\n\t\t\t\t\tmessage: { role: \"user\" as const, content: hook.followUp, timestamp: Date.now() },\n\t\t\t\t};\n\tconst result = await lane.continueOperation<TState, ProcedureResult>(\n\t\tcapability,\n\t\tasync (state, current, meta, reader) => {\n\t\t\tconst placement = await planBoundaryInbox(lane, drive, state, current, reader, state.tipId, true);\n\t\t\tif (placement.triggerEntryId !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"commit\",\n\t\t\t\t\twrites: placement.writes,\n\t\t\t\t\toperationState: assistantReadyAtBoundary(lane, state, current, placement.triggerEntryId, false),\n\t\t\t\t\tlane: { tipId: placement.tipId, inbox: placement.inbox },\n\t\t\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\t\t\tevents: (commit) => [\n\t\t\t\t\t\t...pendingEvents,\n\t\t\t\t\t\t...boundaryPlacementEvents(placement, commit, 0, lane.name, drive.operationId),\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst hookPlanIsCurrent =\n\t\t\t\tplacement.entries.length === plannedEntryIds.length &&\n\t\t\t\tplacement.entries.every((entry, index) => entry.id === plannedEntryIds[index]);\n\t\t\tif (hookPlanIsCurrent && followUp !== undefined) {\n\t\t\t\tconst entry: NewEntry = {\n\t\t\t\t\tid: followUp.id,\n\t\t\t\t\tparentId: placement.tipId,\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\tmessage: followUp.message,\n\t\t\t\t};\n\t\t\t\tconst entryWriteIndex = placement.writes.length;\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"commit\",\n\t\t\t\t\twrites: [...placement.writes, insertEntry(entry), setValue(branchTip(lane.name), followUp.id)],\n\t\t\t\t\toperationState: assistantReadyAtBoundary(lane, state, current, followUp.id, false),\n\t\t\t\t\tlane: { tipId: followUp.id, inbox: placement.inbox },\n\t\t\t\t\tmaterialize: () => ({ kind: \"continue\" }) as const,\n\t\t\t\t\tevents: (commit) => [\n\t\t\t\t\t\t...pendingEvents,\n\t\t\t\t\t\t...boundaryPlacementEvents(placement, commit, 0, lane.name, drive.operationId),\n\t\t\t\t\t\t...entryLifecycleEvents(\n\t\t\t\t\t\t\t{ ...entry, seq: commit.seqs[entryWriteIndex]!, timestamp: commit.timestamp },\n\t\t\t\t\t\t\tlane.name,\n\t\t\t\t\t\t\tdrive.operationId,\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\tif (placement.tipId === null) throw new SessionInvariantError(\"Completed run has no tip\");\n\t\t\tif (continuation.includeFinalAssistant && current.latestAssistantEntryId === null) {\n\t\t\t\tthrow new SessionInvariantError(\"Completed run is missing its final assistant\");\n\t\t\t}\n\t\t\tconst record = operationResultRecord(meta, \"completed\", placement.tipId);\n\t\t\tconst cleanup = await operationCleanupWrites(reader, drive.operationId, current, drive.context);\n\t\t\treturn {\n\t\t\t\tkind: \"finish\",\n\t\t\t\twrites: [...placement.writes, ...cleanup],\n\t\t\t\trecord,\n\t\t\t\tlane: { tipId: placement.tipId, inbox: placement.inbox },\n\t\t\t\tmaterialize: () => ({ kind: \"settled\", outcome: record }) as const,\n\t\t\t\tevents: (commit) => [\n\t\t\t\t\t...pendingEvents,\n\t\t\t\t\t...boundaryPlacementEvents(placement, commit, 0, lane.name, drive.operationId),\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"run_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\tstatus: \"completed\",\n\t\t\t\t\t\tfromTipId: meta.sourceTipId,\n\t\t\t\t\t\ttipId: placement.tipId,\n\t\t\t\t\t\tendedAt: record.endedAt,\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 result.kind === \"cancel_requested\" ? { kind: \"continue\" } : result.value;\n}\n"]}