UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4,950 lines • 181 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { d as readErrorName, p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { m as normalizeTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { a as withoutRuntimeOutput, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import "./gateway-request-scope-BvvDhs5D.mjs";
import { t as PluginRuntimeCloseCompletedError } from "./runtime-close-error-Ak-r7PLO.mjs";
import { t as bindGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { C as isSubagentSessionKey, j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey, o as classifySessionKeyShape, w as parseCronRunScopeSuffix, x as isCronSessionKey, y as isAcpSessionKey } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as emitDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as runWithSessionControllerCleanup } from "./session-controller.cleanup-context-DsmTHS1X.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { a as hasGatewayClientCap, t as GATEWAY_CLIENT_CAPS } from "./client-info-Cm1BcrMm.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { f as pluginInvocationContext } from "./plugin-instance-scope-oezVdCr2.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { c as normalizeAgentRunTimeoutPhase, i as classifyAgentRunTerminalOutcome, n as AGENT_RUN_RESTART_ABORT_STOP_REASON } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { O as validateAgentRunDelegatedAuthority, i as claimAgentRunContext, l as getAgentRunContext, o as clearAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { d as getAgentEventLifecycleGeneration, f as isAgentEventLifecycleGenerationCurrent, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs";
import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { n as withPluginRetentionOwner } from "./plugin-retention-diagnostics-gj7JVNsM.mjs";
import { d as hasGatewayAdminScope, t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { r as isInternalNonDeliveryChannel, t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import "./io-4QsrsWTJ.mjs";
import { C as runWithGatewayDetachedWorkContinuation, T as runWithGatewayIndependentRootWorkContinuation, _ as retainGatewayRootWorkAdmissionContinuation } from "./gateway-work-admission-79pid1hQ.mjs";
import { o as readUserTurnRequesterOrigin, s as readWithdrawnUserTurnInputId } from "./user-turn-transcript-admission-BdVewOwR.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { n as isGatewayMessageChannel, t as isDeliverableMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs";
import { a as resolveRequesterPrincipalKey, t as captureRequesterOrigin } from "./requester-origin-DG-fk-U0.mjs";
import { s as executionIdentitySpawnAdmission } from "./execution-identity-admission-EuMO_R29.mjs";
import { S as createOperationalRunInstanceRef, l as getAdmittedRunDelegatedAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { l as AGENT_SESSION_RESET_COMMAND_RE } from "./method-scopes-Dpyb0Ck-.mjs";
import { a as isInternalMessageChannel, s as isOperatorUiClient } from "./message-channel-DTYVLJT1.mjs";
import { c as mergeSessionSnapshotChanges } from "./session-entry-patch-operation--iew--8y.mjs";
import { n as buildAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { f as isTimeoutError } from "./error-BCRqSFIY.mjs";
import { l as isAgentRunDirectAbortReason, m as resolveAgentRunErrorLifecycleFields, u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs";
import { i as resolveSessionWorkStartError } from "./session-work-start-CFJs8WNp.mjs";
import { a as normalizeCronToolsAllowExecTarget, c as resolveCronToolsAllowExecTargetRecoveryError, i as normalizeCronScheduledToolPolicy, l as restoreCronPinnedExecGrant, r as normalizeCronScheduledToolCallerOrigin } from "./scheduled-tool-policy-C_pucbBp.mjs";
import { f as withExecRequestTurn, n as adoptExecRequestSession } from "./exec-request-context-C8VKkMcB.mjs";
import { a as mergeDeliveryContext, c as normalizeDeliveryContext, l as normalizeSessionDeliveryState } from "./delivery-context.shared-CRlipPTj.mjs";
import { X as captureSessionTarget, d as getSessionControllerOperation } from "./session-controller.state-BApgK0mV.mjs";
import { c as setChannelSourceTurnId, s as resolveReplySourceTurnId } from "./session-event-handoff-CC7Ui3SA.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { m as missingScopeErrorShape, p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { d as resolveCreatorSandbox, r as authorizeGatewaySessionCreation } from "./operator-role-policy-DhcqVpmG.mjs";
import { i as buildSessionCreationStamp } from "./session-entry-provenance-01l9mXT0.mjs";
import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs";
import { _ as normalizeInputProvenance, a as annotateInterSessionPromptText, d as isCronExecutionInputProvenance, g as isSubagentCoordinationInputProvenance, u as isCompletionReportInputProvenance } from "./input-provenance-DupvvURj.mjs";
import { i as resolveExplicitAgentSessionKey, r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs";
import { i as sessionDeliveryRoute, n as sessionDeliveryChannel, r as sessionDeliveryOrigin, t as deliveryContextFromSession } from "./delivery-context.read-BrYAJ7RK.mjs";
import { a as normalizeStoreSessionKey } from "./store-entry-BTUJi0xl.mjs";
import { o as runWithSessionActorStorage } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { l as normalizeAgentRunTerminalReceipt, r as normalizeAgentRunTerminalReplySnapshot } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { r as mergeSessionEntry } from "./types-BUko5WqP.mjs";
import { c as resolveMaintenanceConfigFromInput } from "./store-maintenance-Ba-_6wiR.mjs";
import { M as readSessionSubmittedInput } from "./session-accessor-CizTbDQj.mjs";
import { r as getCliSessionBinding, t as clearAllCliSessions } from "./cli-session-binding-BEOgFSDg.mjs";
import { n as createSessionResetBoundaryId } from "./session-reset-boundary-event-COASu9ts.mjs";
import { i as buildRunUserTurnIdempotencyKey } from "./user-turn-transcript.metadata-GFtsH_a_.mjs";
import { t as acquireSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs";
import { C as trackSessionControllerSourceWork, E as captureRpcSourceScopeMatcher, W as withSessionControllerSource, b as retireSessionControllerInput, t as beginSessionEffect } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { r as resolveRequestedSessionAgentId, s as tryResolveSessionCompatibilityOwnerAgentId } from "./session-request-agent-tfwWH53J.mjs";
import { a as resolveSessionStoreIdentity, o as resolveSessionStoreKey } from "./session-store-key-CEwU3noi.mjs";
import { a as patchSessionEntryTarget } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs";
import { l as resolveAgentHarnessSessionContextError, t as AGENT_HARNESS_MODEL_RUN_FORBIDDEN_MESSAGE, u as resolveAgentHarnessSessionIdMismatchError } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { b as applySessionEntryExactReplacements } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { r as resetSessionEntryLifecycle } from "./session-accessor.sqlite-lifecycle-DYu1Pygl.mjs";
import { n as readSessionTranscriptAnchorsAsync } from "./session-transcript-anchor-read-BUt-Wh3r.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { n as resolveTerminalMainSessionTranscriptRegistryCheck } from "./lifecycle-BFcckgci.mjs";
import { a as resolveSessionResetPolicy, i as evaluateSessionFreshness, n as resolveSessionResetType, t as resolveChannelResetConfig } from "./reset-mDbPCz5g.mjs";
import { o as resolveChatSendCallerContext, r as gatewayClientSenderFields } from "./gateway-client-identity-BkzV3v8p.mjs";
import { a as authorizeResolvedSessionMutationAsync } from "./session-sharing-policy-3TAaxC-R.mjs";
import { D as updateRpcSourceSessionId, O as resolveAgentRunExpiresAtMs, a as getRpcSourceIdentity, c as getRpcSourceStartedAt, d as hasUnretiredRpcSource, g as isRpcSourceRegistered, l as hasRpcSource, n as getRpcSource, o as getRpcSourceLifecycleGeneration, p as isRpcSourceActive, r as getRpcSourceForGateway, u as hasRpcSourceForController, v as listRpcSourceEntries } from "./session-controller.rpc-sources-CTFbRW2t.mjs";
import { r as resolveChatRunOwnerAgentId } from "./chat-run-owner-2pVCqGmw.mjs";
import { r as getGatewayLocalUserIngress } from "./local-user-ingress-CLpC74uh.mjs";
import { c as resolveExactSubagentCompletionEvent, d as hasGeneratedMediaCompletionEvent, o as isSubagentAnnounceCompletionHandoff } from "./requester-tool-policy-BFuyRJjU.mjs";
import { n as resolveScheduledToolPolicyContext } from "./scheduled-tool-policy-CXHVgGTq.mjs";
import { a as resolveSubagentChildAuthority } from "./subagent-child-owner-match-BFVxB68G.mjs";
import { l as isSameSubagentRunOwner } from "./subagent-run-generation-BCjO9e0_.mjs";
import { o as readInProcessSubagentResume } from "./server-plugin-runtime-client-DE2ydcEw.mjs";
import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs";
import { i as getLatestLiveSubagentRunByChildSessionKey } from "./subagent-registry-read-DHkmVSx2.mjs";
import { t as loadGatewaySessionEntryReadOnlyInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs";
import { c as retargetSessionControllerSource, s as reserveSessionControllerSource } from "./session-controller.mailbox-BcK8UF_b.mjs";
import { a as withPreparedModelRuntimePluginGenerationScope, i as scopePreparedModelRuntimeLease } from "./prepared-model-runtime-generation-scope-Dpvf6WHJ.mjs";
import { n as runAgentHarnessBeforeMessageWriteHook } from "./hook-helpers-DKwpcDXZ.mjs";
import { n as completeUserTurnProcessing, r as retainsUserTurnTranscriptMedia, t as createUserTurnTranscriptRecorder } from "./user-turn-transcript-CQTz-i5Y.mjs";
import "./session-sharing-BIP3raq1.mjs";
import { s as resolvePersistedOverrideModelRef } from "./model-selection-C2A4Wyix.mjs";
import { t as isCliProvider } from "./model-selection-cli-CkH04Wst.mjs";
import { c as resolveCliRuntimeExecutionProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs";
import { o as resolveEffectiveAgentRuntime } from "./thinking-runtime-BKWl4CUs.mjs";
import { r as resolveGatewayModelSupportsImages } from "./session-utils-model-BFA7PxHy.mjs";
import { t as setSafeTimeout } from "./timer-delay-DMmvi2s2.mjs";
import { r as PreparedModelRuntimePublicationSupersededError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs";
import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs";
import { r as prepareCommandOwnerAuthority } from "./command-auth-CC1Z19Eh.mjs";
import { o as prepareDeletedAgentSessionCheck } from "./session-utils-store-CiI_s_OK.mjs";
import { g as loadPublishedGatewayReplyDispatchRuntime, t as acquireAgentRunPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import "./prepared-model-runtime.errors-BRsU9-dm.mjs";
import { n as resolveSendPolicy } from "./send-policy-Be9xpkMD.mjs";
import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs";
import { t as hasProviderOwnedSession } from "./entry-freshness-QZXboFNc.mjs";
import { n as resolveSessionLifecycleTimestampsAsync } from "./lifecycle-read-Dg9D2Bz2.mjs";
import "./failover-error-CbIiC30n.mjs";
import "./cli-session-BsEOjZRc.mjs";
import { i as resolveSessionKeyForRequestCore, n as resolveExistingSessionKeyForRequest, o as clearRotatedSessionMetadata } from "./session-Cf7LaLt9.mjs";
import { c as hasNewGeneratedMediaTaskForSessionKey, s as getGeneratedMediaTaskIdsForSessionKey } from "./media-generation-activity-C0NELI_p.mjs";
import { n as resolveAgentRunSessionCreation } from "./session-creation-provenance-DCFhTDpD.mjs";
import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { t as errorShapeFromError } from "./error-shape-BcwiXcnc.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { n as runWithAgentWorkspaceReadiness } from "./workspace-readiness-ClUjI0tp.mjs";
import { a as consumeAgentRuntimeExecutionLineage, s as readAgentRuntimeExecutionLineage } from "./agent-runtime-identity-token-BK52eBqW.mjs";
import { d as createCronCreatorAuthorityCapability, p as runWithCronCreatorAuthorityCapability } from "./cron-creator-authority-context-D4fHKVAj.mjs";
import { c as createPrivateContextCarrier } from "./server-plugin-in-process-authority-6ufuLah5.mjs";
import { r as takeInProcessFreshChildSession } from "./in-process-session-run-BwEg7-a8.mjs";
import { n as consumeSubagentCompletionToolHandoff } from "./subagent-completion-tool-handoff-cAKxL2DF.mjs";
import { d as readSessionSendDeliveryAdmission } from "./in-process-gateway-Cy0xoBmg.mjs";
import { t as withSessionTurn } from "./session-controller.admission-DDiE4tNx.mjs";
import { n as readAcpSessionEntryAsync } from "./session-meta-read-BC53uDBL.mjs";
import "./session-meta-CupK_5Fp.mjs";
import { i as deleteMediaBuffer } from "./store-zsTAVy24.mjs";
import { n as readAgentRunTerminalOutcome, t as readAgentRunTerminalError } from "./agent-run-terminal-outcome-BQoZ_25h.mjs";
import { i as isHostMissingReplyNoticeText } from "./reply-completion-CrT6uEHT.mjs";
import "./session-controller-Bu0l-8-p.mjs";
import { t as isRecoverableTerminalSessionStatus } from "./terminal-status-4Rh8bAKD.mjs";
import { d as createClosedSessionTranscriptSource, f as createResetBoundaryTranscriptSource } from "./active-sessions-shutdown-tracker-Cjs-M-Ky.mjs";
import { s as withCurrentUserTurnInput } from "./user-turn-transcript-runtime-context-BZjNfwCQ.mjs";
import { t as assertPreparedSkillLibrarySelection } from "./selection-Bz10gm8A.mjs";
import { t as recordSessionCreated } from "./session-created-Cgp2r4Ic.mjs";
import { r as resolveIngressWorkspaceOverrideForSessionRun } from "./spawned-context-wZ6NGSBl.mjs";
import { a as readFollowupSuccessor, i as readFollowupRequest, t as SessionFollowupCompletion } from "./session-followup-completion-DdZ4759A.mjs";
import { r as captureRequesterCronAuthorityAdmissionAssertion } from "./subagent-requester-owner-BJOQsDFh.mjs";
import { n as shouldDowngradeDeliveryToSessionOnly } from "./best-effort-delivery-BHi41M3Q.mjs";
import { n as resolveChatAttachmentMaxBytes } from "./chat-attachment-policy-7g-oMINW.mjs";
import { a as validateExpectedExistingSessionTarget, n as assertExpectedExistingSession, r as consumeExpectedSessionWorkAdmission, t as ExpectedExistingSessionChangedError } from "./agent-expected-session-tLzLj-o-.mjs";
import "./session-utils-CavYkLyd.mjs";
import { r as resolveMessageChannelSelection } from "./channel-selection-DBeuWpKq.mjs";
import { n as clearCommittedSessionResetRuntimeState } from "./session-reset-cleanup-xD3c68B-.mjs";
import { t as recordSessionParticipantBestEffort } from "./session-participant-recording-DOa32JGj.mjs";
import { a as attachAgentCommandAdmissionFacts, i as withAgentCommandExecutionIdentitySpawnFacts } from "./agent-command-execution-identity-3BFl0Qcl.mjs";
import { n as agentCommandFromGatewayIngress } from "./agent-command-FXkX3hj5.mjs";
import { n as resolveAgentExplicitRecipientSession, r as resolveAgentOutboundTarget, t as resolveAgentDeliveryPlanWithSessionRoute } from "./agent-delivery-U5Z9_Vg5.mjs";
import { r as findReplaySafeRunAbort } from "./transcript-conflict-BirOVa3J.mjs";
import { n as runWithCanonicalSkillWorkspace } from "./skill-workshop-workspace-context-BoZq1zd3.mjs";
import { i as assertParentSubagentResumeSuccessorCurrent, o as prepareParentSubagentResume, r as assertParentSubagentResumeCurrent, t as createAgentPreacceptRefusal } from "./agent-admission-refusal-CezC239U.mjs";
import "./agent-WNO-h9tH.mjs";
import { r as buildExecApprovalContinuationPrompt, t as EXEC_APPROVAL_FOLLOWUP_HANDOFF_MESSAGE } from "./bash-tools.exec-approval-output-Cb90XzcX.mjs";
import { t as captureAgentJobSession } from "./agent-job-mP_hfXWa.mjs";
import { a as readGatewayDedupeEntry, i as isPreRegistrationAbortedAgentDedupeEntryForSession, l as setAbortedAgentDedupeEntries, n as buildAbortedAgentPayload, o as replayAgentTurnIfCached, r as isAcceptedAgentDedupePayload, t as AgentRequestReservationEndedError, u as setGatewayDedupeEntries } from "./agent-dedupe-DvejJfx2.mjs";
import { t as prepareAgentWaitForTurn } from "./agent-wait-CQ6JYxlo.mjs";
import { i as isExecApprovalFollowupSessionRebound, n as claimExecApprovalFollowupRuntimeHandoff, r as finalizeExecApprovalFollowupRuntimeHandoff, s as releaseExecApprovalFollowupRuntimeHandoff } from "./bash-tools.exec-approval-followup-state-CdzwahWm.mjs";
import { n as registerPluginSubagentRunFromGateway, r as resolveAgentSessionGroup, t as normalizeTrustedGroupMetadata } from "./agent-subagent-registration-BnRif7AQ.mjs";
import { t as normalizeRpcAttachmentsToChatAttachments } from "./attachment-normalize-Cx4U0DTw.mjs";
import { i as emitGatewaySessionStartPluginHook, n as performGatewaySessionReset, r as emitGatewaySessionEndPluginHook } from "./session-reset-service-DH7-Rpxw.mjs";
import { a as resolveChatAbortStopReason, i as registerChatAbortController, o as updateChatRunProvider, t as abortChatRunById } from "./chat-abort-DHc0iNFP.mjs";
import { t as prepareSkillLibrarySessionCreation } from "./skill-library-session-CBGwzYPf.mjs";
import { n as resolveVoiceWakeRouteByTrigger, t as loadVoiceWakeRoutingConfig } from "./voicewake-routing-CWXNXBoJ.mjs";
import { a as parseMessageWithAttachments, i as logAttachmentFailure, n as MediaOffloadError, o as persistInboundImagesForTranscript, r as discardPreparedInboundMedia, s as stripImageMediaMarkers, t as INLINE_IMAGE_DURABLE_OMISSION_MARKER } from "./chat-attachments-CZUu2WVn.mjs";
import { n as createChatAbortOps } from "./chat-abort-ops-BGjSJRNq.mjs";
import { i as resolveGatewayInputParticipant, l as retainGatewayOperatorRun, n as prepareGatewaySkillAuthoring, s as prepareGatewayCronCreatorAuthorityAdmission } from "./skill-library-authoring-CwgXRvu2.mjs";
import { i as prepareSessionWorkspaceForRun } from "./session-create-project-BLnUiBsn.mjs";
import { t as reactivateCompletedSubagentSession } from "./session-subagent-reactivation-BFHueipd.mjs";
import { t as captureGatewayUiCommandTarget } from "./ui-command-target-O1ior1sD.mjs";
import { randomUUID } from "node:crypto";
//#region src/gateway/agent-turn/agent-handler-helpers.ts
const CRON_CONTINUATION_RELEASE_RECOVERY_DELAYS_MS = [
	250,
	1e3,
	4e3,
	15e3
];
function canPrepareAgentSessionWorktree(e, t) {
	return Boolean(e && t?.pendingWorktree) && t?.pendingProjectGitUrl === void 0;
}
function resolveAgentSessionWorkStartError(e, t) {
	return resolveSessionWorkStartError(e, t, canPrepareAgentSessionWorktree(e, t) ? { allowPendingWorkspace: true } : void 0);
}
function respondDeletedAgentSession(e) {
	const t = prepareDeletedAgentSessionCheck({
		cfg: e.cfg,
		sessionKey: e.canonicalKey,
		entry: e.entry,
		acpMetadataSessionKey: e.acpMetadataSessionKey,
		assertCurrent: e.assertCurrent
	});
	const respond = (t) => {
		if (t === null) return false;
		respondError(e.respond, ErrorCodes.INVALID_REQUEST, `Agent "${t}" no longer exists in configuration`);
		return true;
	};
	return t instanceof Promise ? t.then((t) => {
		e.assertCurrent?.();
		return respond(t);
	}) : respond(t);
}
function respondUnavailableAgentSession(e) {
	const { cfg: t, entry: n, canonicalKey: r, legacyKey: i } = e.loaded;
	const a = respondDeletedAgentSession({
		cfg: t,
		canonicalKey: r,
		entry: n,
		acpMetadataSessionKey: i,
		respond: e.respond,
		assertCurrent: e.assertCurrent
	});
	const respondUnavailable = (t) => {
		if (t) return true;
		const i = resolveAgentHarnessSessionContextError(r, n) || resolveAgentHarnessSessionIdMismatchError(n, e.requestedSessionId) || (e.isRawModelRun && n?.modelSelectionLocked === true ? "Agent harness-owned sessions cannot be used for one-shot model runs." : void 0) || resolveAgentSessionWorkStartError(r, n);
		if (!i) return false;
		respondError(e.respond, ErrorCodes.INVALID_REQUEST, i);
		return true;
	};
	return a instanceof Promise ? a.then((t) => {
		e.assertCurrent?.();
		return respondUnavailable(t);
	}) : respondUnavailable(a);
}
function cronContinuationHasReusableRuntime(e) {
	const t = resolveCliRuntimeExecutionProvider({
		provider: e.provider,
		cfg: e.cfg,
		agentId: e.agentId,
		modelId: e.model
	}) ?? e.provider;
	return !isCliProvider(t, e.cfg) || Boolean(getCliSessionBinding(e.entry, t)?.sessionId);
}
function withoutCronRunContinuation(e) {
	const { cronRunContinuation: t, ...n } = e;
	return n;
}
function yieldAfterAgentAcceptedAck() {
	return new Promise((e) => {
		setTimeout(e, 10);
	});
}
function waitForCronContinuationReleaseRecovery(e) {
	return new Promise((t) => {
		setSafeTimeout(t, e).unref();
	});
}
//#endregion
//#region src/gateway/server-methods/agent-cron-continuation.ts
function createCronContinuationController(e) {
	let t;
	let n = false;
	const release = async (n) => {
		const r = t;
		if (!r) return true;
		const i = parseCronRunScopeSuffix(r.sessionKey).baseSessionKey;
		for (let a = 1; a <= 3; a += 1) try {
			const a = await applySessionEntryExactReplacements({
				activeSessionKey: r.sessionKey,
				agentId: r.sessionAgentId,
				requireWriteSuccess: true,
				sessionKeys: i && i !== r.sessionKey ? [r.sessionKey, i] : [r.sessionKey],
				skipMaintenance: false,
				storePath: r.storePath,
				update: (t) => {
					const a = new Map(t.map(({ sessionKey: e, entry: t }) => [e, t]));
					let o = a.get(r.sessionKey);
					const s = o?.cronRunContinuation;
					if (!o || s?.phase !== "continuing" || s.ownerRunId !== e.runId || s.ownerLifecycleGeneration !== e.lifecycleGeneration || s.lifecycleRevision !== r.lifecycleRevision) return { result: false };
					const c = n?.terminalOutcome.reason === "completed" || hasNewGeneratedMediaTaskForSessionKey(r.sessionKey, r.mediaTaskIdsBefore, r.sessionAgentId);
					if (!c) o = structuredClone(r.initialEntry);
					else if (n?.terminalOutcome) {
						o.status = n.terminalOutcome.status === "ok" ? "done" : n.terminalOutcome.status === "timeout" ? "timeout" : "failed";
						o.endedAt = n.terminalOutcome.endedAt ?? Date.now();
					}
					const l = i ? a.get(i) : void 0;
					const u = i !== void 0 && i !== r.sessionKey && l?.lifecycleRevision === r.lifecycleRevision;
					const d = [];
					if (c && u && l && i) d.push({
						sessionKey: i,
						entry: mergeSessionSnapshotChanges({
							initial: withoutCronRunContinuation(r.initialEntry),
							next: withoutCronRunContinuation(o),
							current: l
						})
					});
					const { ownerRunId: f, ownerLifecycleGeneration: p, ...m } = c ? s : r.initialEntry.cronRunContinuation ?? s;
					const h = Boolean(l && l.lifecycleRevision !== r.lifecycleRevision);
					o.cronRunContinuation = {
						...m,
						phase: "ready",
						basePersisted: m.basePersisted === true || u || h
					};
					o.updatedAt = Date.now();
					d.push({
						sessionKey: r.sessionKey,
						entry: o
					});
					return {
						replacements: d,
						result: true
					};
				}
			});
			t = void 0;
			if (a && i) emitSessionsChanged(e.context, {
				sessionKey: i,
				agentId: r.sessionAgentId,
				reason: "cron-continuation"
			});
			return a;
		} catch (t) {
			e.context.logGateway.warn(`failed to release cron continuation ${e.runId} (${a}/3): ${formatForLog(t)}`);
		}
		return false;
	};
	const releaseWithRecovery = async (r, i) => {
		const a = await release(r);
		const o = t;
		if (a || !o || n) return a;
		n = true;
		runWithGatewayIndependentRootWorkContinuation(async () => {
			for (const n of CRON_CONTINUATION_RELEASE_RECOVERY_DELAYS_MS) {
				await waitForCronContinuationReleaseRecovery(n);
				if (t !== o || getAgentEventLifecycleGeneration() !== e.lifecycleGeneration) return;
				if (await release(r)) {
					try {
						i?.();
					} catch (t) {
						e.context.logGateway.warn(`failed to refresh recovered cron continuation dedupe ${e.runId}: ${formatForLog(t)}`);
					}
					return;
				}
			}
			e.context.logGateway.warn(`cron continuation release recovery exhausted for ${e.runId}`);
		}, "cron:continuation-recovery");
		return false;
	};
	return {
		releaseWithRecovery,
		setClaim: (e) => {
			t = e;
		}
	};
}
//#endregion
//#region src/gateway/server-methods/agent-session-reset.ts
function sessionResetAckText(e) {
	return e === "new" ? "✅ New session started." : "✅ Session reset.";
}
function buildBareSessionResetResult(e) {
	return {
		payloads: [{
			text: e.ackText ?? sessionResetAckText(e.reason),
			isStatusNotice: true
		}],
		meta: {
			durationMs: 0,
			...e.sessionId ? { agentMeta: { sessionId: e.sessionId } } : {}
		}
	};
}
function buildBareSessionResetResponse(e) {
	return {
		runId: e.runId,
		status: "ok",
		summary: "completed",
		result: e.result
	};
}
async function resolveBareSessionResetResult(e) {
	e.assertCurrent?.();
	if (e.request.deliver !== true) return buildBareSessionResetResult(e);
	if (resolveSendPolicy({
		cfg: e.cfg,
		entry: e.sessionEntry,
		sessionKey: e.sessionKey,
		channel: sessionDeliveryChannel(e.sessionEntry),
		chatType: e.sessionEntry?.chatType
	}) === "deny") throw new Error("send blocked by session policy");
	const t = await resolveAgentDeliveryPlanWithSessionRoute({
		cfg: e.cfg,
		agentId: e.agentId ?? resolveAgentIdFromSessionKey(e.sessionKey),
		currentSessionKey: e.sessionKey,
		sessionEntry: e.sessionEntry,
		requestedChannel: normalizeOptionalString(e.request.replyChannel) ?? normalizeOptionalString(e.request.channel),
		explicitTo: normalizeOptionalString(e.request.replyTo) ?? normalizeOptionalString(e.request.to),
		explicitThreadId: normalizeOptionalString(e.request.threadId),
		accountId: normalizeOptionalString(e.request.replyAccountId) ?? normalizeOptionalString(e.request.accountId),
		wantsDelivery: true,
		turnSourceChannel: normalizeOptionalString(e.request.channel),
		turnSourceTo: normalizeOptionalString(e.request.to),
		turnSourceAccountId: normalizeOptionalString(e.request.accountId),
		turnSourceThreadId: normalizeOptionalString(e.request.threadId)
	});
	e.assertCurrent?.();
	const n = resolveAgentMainSessionKey({
		cfg: e.cfg,
		agentId: e.agentId ?? resolveAgentIdFromSessionKey(e.sessionKey)
	});
	const r = typeof e.request.bestEffortDeliver === "boolean" ? e.request.bestEffortDeliver : e.sessionKey === n || e.sessionKey === "global" ? true : void 0;
	const i = {
		...e.request,
		channel: t.resolvedChannel,
		to: t.resolvedTo ?? t.baseDelivery.to,
		accountId: t.resolvedAccountId ?? t.baseDelivery.accountId,
		threadId: t.resolvedThreadId
	};
	const a = e.originMessageChannel ?? t.resolvedChannel;
	const { deliverAgentCommandResult: o } = await import("./delivery.runtime.js");
	e.assertCurrent?.();
	const s = buildBareSessionResetResult(e);
	return await o({
		cfg: e.cfg,
		deps: e.context.deps,
		runtime: withoutRuntimeOutput(defaultRuntime),
		opts: {
			message: e.ackText ?? sessionResetAckText(e.reason),
			...e.agentId ? { agentId: e.agentId } : {},
			...e.sessionId ? { sessionId: e.sessionId } : {},
			sessionKey: e.sessionKey,
			deliver: true,
			replyTo: i.replyTo,
			to: i.to,
			replyChannel: i.replyChannel,
			channel: i.channel,
			replyAccountId: i.replyAccountId,
			accountId: i.accountId,
			threadId: i.threadId,
			deliveryTargetMode: t.deliveryTargetMode ?? t.baseDelivery.mode,
			bestEffortDeliver: r,
			runId: e.runId,
			messageChannel: a,
			runContext: {
				messageChannel: a,
				accountId: i.replyAccountId ?? i.accountId,
				currentThreadTs: i.threadId != null ? String(i.threadId) : void 0
			},
			allowModelOverride: false
		},
		outboundSession: void 0,
		sessionEntry: e.sessionEntry,
		result: s,
		payloads: s.payloads,
		preparedPlugin: t.plugin,
		assertDeliveryCurrent: e.assertCurrent
	});
}
async function loadBareSessionResetDeliverySession(e) {
	const t = await loadGatewaySessionEntryReadOnlyInWorker({
		cfg: readRuntimeConfig(),
		key: e.sessionKey,
		excludeInternalEffects: true,
		...e.agentId ? { agentId: e.agentId } : {}
	});
	return {
		cfg: t.cfg,
		entry: t.entry,
		agentId: resolveAgentIdFromSessionKey(e.sessionKey, e.agentId)
	};
}
function resolveSessionRuntimeCwd(e) {
	return normalizeOptionalString(e.requestedCwd ?? e.sessionEntry?.spawnedCwd);
}
//#endregion
//#region src/gateway/server-methods/agent-reset-phase.ts
async function runAgentResetPhase(e) {
	const t = {
		requestedSessionKey: e.requestedSessionKey,
		resolvedSessionId: e.resolvedSessionId,
		effectiveTranscriptInputText: e.effectiveTranscriptInputText,
		message: e.message
	};
	const n = e.message.match(AGENT_SESSION_RESET_COMMAND_RE);
	if (!n || !e.requestedSessionKey) return {
		...t,
		stop: false,
		accepted: false
	};
	const r = e.requestedSessionKey;
	const i = normalizeOptionalString(n[2]) ?? "";
	if (!hasGatewayAdminScope(e.client)) {
		e.respond(false, void 0, missingScopeErrorShape({
			missingScope: ADMIN_SCOPE,
			requiredScopes: [ADMIN_SCOPE]
		}));
		return {
			...t,
			stop: true,
			accepted: false
		};
	}
	const a = normalizeOptionalLowercaseString(n[1]) === "new" ? "new" : "reset";
	e.assertAdmissionCurrent?.();
	const o = await prepareSkillLibrarySessionCreation(e.client, e.context.getRuntimeConfig, resolveAgentRunSessionCreation(e.client));
	const s = await captureGatewayOperatorRunAuthority({
		client: e.client,
		context: e.context,
		invocationAuthority: { assertCurrent: () => e.assertAdmissionCurrent?.() }
	});
	const c = await (async () => {
		try {
			return await performGatewaySessionReset({
				operatorAuthority: s?.authority,
				key: r,
				...e.agentId ? { agentId: e.agentId } : {},
				reason: a,
				commandSource: "gateway:agent",
				armSessionDiffBaselineCapture: true,
				creation: o,
				...e.client?.authenticatedUserProfile?.profileId ? { requestingOperatorProfileId: e.client.authenticatedUserProfile.profileId } : {},
				...e.client?.internal?.operatorRoleActor ? { operatorRoleActor: e.client.internal.operatorRoleActor } : {},
				assertCurrent: () => {
					e.assertAdmissionCurrent?.();
					assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
					assertPreparedSkillLibrarySelection(o.skillLibrarySelections);
				},
				onCommitted: (t) => {
					e.setCommittedResetCompletion({
						reason: a,
						sessionId: t.sessionId,
						sessionKey: t.key,
						agentId: e.agentId,
						followUpPending: Boolean(i)
					});
				}
			});
		} finally {
			s?.release();
		}
	})();
	if (!c.ok) {
		e.respond(false, void 0, c.error);
		return {
			...t,
			stop: true,
			accepted: false
		};
	}
	const l = "incognitoDeleted" in c ? void 0 : c.entry.sessionId;
	const u = {
		...t,
		requestedSessionKey: c.key,
		resolvedSessionId: l ?? e.resolvedSessionId
	};
	const d = {
		reason: a,
		sessionId: l,
		sessionKey: c.key,
		agentId: e.agentId,
		followUpPending: Boolean(i)
	};
	e.setCommittedResetCompletion(d);
	e.assertAdmissionCurrent?.();
	if (i) return {
		...u,
		stop: false,
		accepted: false,
		effectiveTranscriptInputText: i,
		message: i
	};
	try {
		const t = e.request.deliver === true ? await loadBareSessionResetDeliverySession({
			sessionKey: c.key,
			...e.agentId ? { agentId: e.agentId } : {}
		}) : void 0;
		const n = await resolveBareSessionResetResult({
			cfg: t?.cfg ?? e.cfg,
			context: e.context,
			reason: a,
			sessionId: l,
			sessionKey: c.key,
			agentId: t?.agentId ?? e.agentId,
			sessionEntry: t?.entry,
			request: e.sessionKeyFromTo ? {
				...e.request,
				to: void 0
			} : e.request,
			runId: e.runId,
			assertCurrent: () => {
				e.assertAdmissionCurrent?.();
				assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
			}
		});
		e.assertAdmissionCurrent?.();
		const r = buildBareSessionResetResponse({
			runId: e.runId,
			result: n
		});
		setGatewayDedupeEntries({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys,
			entry: {
				ts: Date.now(),
				ok: true,
				payload: r
			}
		});
		e.respond(true, r, void 0, { runId: e.runId });
		emitSessionsChanged(e.context, {
			sessionKey: c.key,
			...e.agentId ? { agentId: e.agentId } : {},
			reason: a
		});
		return {
			...u,
			stop: true,
			accepted: true
		};
	} catch (t) {
		const n = errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(t));
		if (e.request.deliver === true) e.setCommittedResetCompletion({
			...d,
			replyError: n
		});
		e.respond(false, void 0, n);
		return {
			...u,
			stop: true,
			accepted: false
		};
	}
}
//#endregion
//#region src/gateway/server-methods/agent-session-patch.ts
async function buildAgentSessionPatch(e) {
	const t = e.freshEntry ? await resolveSessionLifecycleTimestampsAsync({
		entry: e.freshEntry,
		storePath: e.storePath,
		agentId: e.sessionAgentId,
		sessionKey: e.canonicalSessionKey
	}) : void 0;
	const n = e.expectedExistingSessionId !== void 0 || e.hasRestoredCronContinuation || e.freshEntry?.modelSelectionLocked === true || e.resetPolicy.configured !== true && hasProviderOwnedSession(e.freshEntry);
	const r = e.freshEntry ? n ? { fresh: true } : evaluateSessionFreshness({
		updatedAt: e.freshEntry.updatedAt,
		...t,
		now: e.now,
		policy: e.resetPolicy
	}) : void 0;
	const i = Boolean(e.requestedSessionId && e.freshEntry?.sessionId?.trim() === e.requestedSessionId);
	const a = e.isSystemGatewayRun || i ? void 0 : resolveTerminalMainSessionTranscriptRegistryCheck({
		entry: e.freshEntry,
		sessionScope: e.cfg.session?.scope,
		sessionKey: e.canonicalSessionKey,
		agentId: e.sessionAgentId,
		mainKey: e.cfg.session?.mainKey,
		storePath: e.storePath
	});
	const o = e.freshEntry?.status === "failed" && Boolean(e.freshEntry.sessionId?.trim());
	const s = o || a !== void 0;
	const c = e.freshEntry && s ? await readSessionTranscriptAnchorsAsync({
		agentId: e.sessionAgentId,
		sessionId: e.freshEntry.sessionId,
		sessionKey: e.canonicalSessionKey,
		storePath: e.storePath
	}, {
		entryIds: [],
		includeMetadata: true
	}).then((e) => e.metadata, () => void 0) : void 0;
	const l = Boolean(a && c?.updatedAt != null && Number.isFinite(c.updatedAt) && Math.floor(c.updatedAt) > Math.floor(c.observedAt ?? a.registryTimestampMs));
	const u = Boolean(e.freshEntry?.sessionId) && e.visibleRequest && isRecoverableTerminalSessionStatus(e.freshEntry?.status);
	const d = getSessionControllerOperation(e.canonicalSessionKey, captureSessionTarget({
		storeScope: e.storePath,
		sessionKey: e.canonicalSessionKey,
		agentId: e.sessionAgentId
	}));
	const f = r?.fresh === false && d?.phase !== "queued" && d?.sessionId === e.freshEntry?.sessionId;
	const p = Boolean(e.freshEntry?.sessionId) && ((r?.fresh ?? false) || f || u) && !(o && !c?.present) && !l;
	const m = e.requestedSessionId && (!e.freshEntry?.sessionId || p) ? e.requestedSessionId : void 0;
	const h = !p && !m && !(o && !c?.present) && !l ? r?.staleReason : void 0;
	const g = m ?? (p || h ? e.freshEntry?.sessionId : void 0);
	const _ = !e.freshEntry || !p && !m || Boolean(m && e.freshEntry?.sessionId !== m);
	const v = normalizeOptionalString(e.freshEntry?.spawnedBy);
	const y = v ? resolveSessionStoreKey({
		cfg: e.cfg,
		sessionKey: v,
		storeAgentId: e.sessionAgentId
	}) : void 0;
	const b = normalizeTrustedGroupMetadata(e.freshEntry);
	let x;
	if (y && (!b.groupId || !b.groupChannel || !b.groupSpace)) try {
		const t = (await loadGatewaySessionEntryReadOnlyInWorker({
			cfg: e.cfg,
			key: y
		})).entry;
		x = normalizeTrustedGroupMetadata({
			groupId: t?.groupId,
			groupChannel: t?.groupChannel,
			groupSpace: t?.space
		});
	} catch (e) {
		if (e?.code === "SESSION_CANONICAL_KEY_MIGRATION_REQUIRED") throw e;
	}
	const S = resolveAgentSessionGroup({
		sessionKey: e.canonicalSessionKey,
		spawnedBy: y,
		stored: b,
		inherited: x,
		requested: e.normalizedSpawned
	});
	const C = mergeDeliveryContext(deliveryContextFromSession(e.freshEntry), e.requestDeliveryHint);
	const w = !e.requestDeliveryHint && e.freshEntry?.delivery ? e.freshEntry.delivery : normalizeSessionDeliveryState({
		route: sessionDeliveryRoute(e.freshEntry),
		context: C,
		origin: sessionDeliveryOrigin(e.freshEntry)
	});
	const T = normalizeOptionalString(e.requestLabel) || e.freshEntry?.label;
	const E = e.freshEntry === void 0 && e.visibleRequest && normalizeOptionalString(e.explicitSessionKey) && !T && !isCronSessionKey(e.canonicalSessionKey) && !isSubagentSessionKey(e.canonicalSessionKey) && !isAcpSessionKey(e.canonicalSessionKey) ? parseAgentSessionKey(e.canonicalSessionKey)?.rest.trim() : void 0;
	const D = Boolean(e.initialEntry?.sessionId && e.freshEntry?.sessionId && e.freshEntry.sessionId !== e.initialEntry.sessionId);
	const O = g ?? e.fallbackSessionId ?? randomUUID();
	const k = Boolean(e.freshEntry?.sessionId && e.freshEntry.sessionId !== O);
	const A = D ? e.freshEntry?.sessionId : O;
	const j = k && !D;
	const M = p && u && !D && A === e.freshEntry?.sessionId;
	const N = {
		...h && e.freshEntry ? {
			...clearRotatedSessionMetadata(e.freshEntry),
			agentHarnessId: void 0
		} : {},
		sessionId: A,
		updatedAt: e.now,
		..._ && !D ? {
			lifecycleRevision: randomUUID(),
			sessionStartedAt: e.now
		} : e.freshEntry?.sessionStartedAt === void 0 && A === e.freshEntry?.sessionId && t?.sessionStartedAt !== void 0 ? { sessionStartedAt: t.sessionStartedAt } : {},
		...e.touchInteraction ? {
			lastInteractionAt: e.now,
			agentStatus: void 0
		} : {},
		...j ? { resumeAfterRestart: void 0 } : {},
		delivery: w,
		...T ? { label: T } : {},
		...E ? { displayName: E } : {},
		...y ? { spawnedBy: y } : {},
		groupId: S.groupId,
		groupChannel: S.groupChannel,
		space: S.groupSpace,
		...e.freshEntry === void 0 && e.pluginOwnerId ? { pluginOwnerId: e.pluginOwnerId } : {},
		...j || M ? {
			status: void 0,
			lifecycleRunId: void 0,
			lastRunId: void 0,
			startedAt: void 0,
			endedAt: void 0,
			runtimeMs: void 0,
			abortedLastRun: void 0
		} : {}
	};
	if (j) clearAllCliSessions(N);
	return {
		patch: N,
		...h ? { automaticResetReason: h } : {},
		spawnedBy: y,
		...S,
		freshSessionRotatedSinceLoad: D,
		isNewSession: _,
		rotatedSessionId: k,
		usableRequestedSessionId: m,
		freshness: r
	};
}
//#endregion
//#region src/gateway/server-methods/agent-session-prepare.ts
async function prepareAgentSession(e) {
	e.assertCurrent?.();
	const t = resolveRequestedSessionAgentId(e.cfg, e.requestedSessionKey, e.agentId);
	if (!t.ok) {
		e.respond(false, void 0, t.error);
		return;
	}
	const n = t.agentId;
	const r = takeInProcessFreshChildSession(e.request);
	if (r) return prepareAdmittedAgentSession(e, {
		cfg: e.cfg,
		storePath: r.storePath,
		entry: r.entry,
		canonicalKey: e.requestedSessionKey,
		storeKeys: [e.requestedSessionKey],
		legacyKey: void 0
	}, r.agentId, r);
	return prepareAdmittedAgentSession(e, await loadGatewaySessionEntryReadOnlyInWorker({
		cfg: e.cfg,
		key: e.requestedSessionKey,
		agentId: n,
		excludeInternalEffects: true,
		assertActive: e.assertCurrent
	}), n);
}
async function prepareAdmittedAgentSession(e, t, n, r) {
	const { cfg: i, storePath: a, entry: o, canonicalKey: s, legacyKey: c, storeKeys: l } = t;
	const u = parseAgentSessionKey(s)?.agentId ?? n;
	if (e.expectedExistingSessionId && o?.sessionId !== e.expectedExistingSessionId) {
		respondError(e.respond, ErrorCodes.UNAVAILABLE, `Session "${s}" changed before expected work could start.`);
		return;
	}
	let d = e.effectiveBootstrapContextRunKind;
	let f;
	if (hasGeneratedMediaCompletionEvent(e.request.internalEvents) && parseCronRunScopeSuffix(s).runId !== void 0) {
		if (!e.canUseCronRunContinuation) {
			respondError(e.respond, ErrorCodes.INVALID_REQUEST, "cron run completion handoffs are reserved for server-owned callers");
			return;
		}
		const t = o?.cronRunContinuation;
		const n = normalizeOptionalString(o?.sessionId);
		const r = t?.phase === "continuing" && t.ownerLifecycleGeneration !== e.lifecycleGeneration;
		if (r || t?.phase === "ready" && t.basePersisted !== true) {
			respondError(e.respond, ErrorCodes.INVALID_REQUEST, r ? "cron run continuation owner was lost during gateway restart" : "cron run continuation base session was not persisted");
			return;
		}
		if (!t || t.phase !== "ready" || !n) {
			respondError(e.respond, ErrorCodes.UNAVAILABLE, "cron run continuation is not ready");
			return;
		}
		if (e.requestedSessionId && e.requestedSessionId !== n) {
			respondError(e.respond, ErrorCodes.UNAVAILABLE, "cron run continuation session changed");
			return;
		}
		f = {
			lifecycleRevision: t.lifecycleRevision,
			sessionId: n
		};
		d = "cron";
	}
	const p = e.preAttachmentSession?.canonicalKey === s ? e.preAttachmentSession : void 0;
	if (p && (!o || o.sessionId !== p.sessionId)) {
		respondError(e.respond, ErrorCodes.INVALID_REQUEST, `Session "${s}" ${o ? "changed" : "was deleted"} while starting work. Retry.`);
		return;
	}
	const m = respondDeletedAgentSession({
		cfg: i,
		canonicalKey: s,
		entry: o,
		acpMetadataSessionKey: c,
		respond: e.respond,
		assertCurrent: e.assertCurrent
	});
	if (m instanceof Promise ? await m : m) return;
	const h = resolveAgentSessionWorkStartError(s, o);
	if (h) {
		respondError(e.respond, ErrorCodes.INVALID_REQUEST, h);
		return;
	}
	const g = Date.now();
	const _ = resolveSessionResetPolicy({
		sessionCfg: i.session,
		resetType: resolveSessionResetType({ sessionKey: s }),
		resetOverride: resolveChannelResetConfig({
			sessionCfg: i.session,
			channel: sessionDeliveryChannel(o) ?? e.recipientChannel
		})
	});
	const v = d === "cron";
	const y = !v && !e.request.internalEvents?.length;
	const b = resolveAgentMainSessionKey({
		cfg: i,
		agentId: u
	});
	e.assertCurrent?.();
	return {
		cfg: i,
		storePath: a,
		physicalStorePath: t.readSource?.path,
		entry: o,
		canonicalKey: s,
		storeKeys: l,
		maintenanceConfig: resolveMaintenanceConfigFromInput(i.session?.maintenance),
		canonicalSessionAgentId: u,
		resetPolicy: _,
		now: g,
		visibleRequest: y,
		mainSessionKey: b,
		isSystemGatewayRun: v,
		touchInteraction: y,
		sessionPersistedBeforeGatewayAdmission: o !== void 0,
		effectiveBootstrapContextRunKind: d,
		restoredCronContinuationIdentity: f,
		freshChild: r !== void 0
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-admission-controller.ts
function createAgentAdmissionController(e) {
	let t;
	let n;
	let r;
	let i;
	let a = false;
	const admissionAgentId = () => {
		const t = e.getResolvedSessionKey();
		return e.getResolvedSessionAgentId() ?? (t ? e.getAgentId() : void 0);
	};
	const assertAllowed = (t = true) => {
		e.assertAdmissionCurrent?.();
		const n = e.getResolvedSessionKey();
		const o = e.getRequestedSessionKey();
		const s = readGatewayDedupeEntry({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys
		});
		if (isPreRegistrationAbortedAgentDedupeEntryForSession({
			entry: s,
			runId: e.runId,
			sessionKey: n,
			alternateSessionKeys: [e.preAcceptedReservedSessionKey, o],
			agentId: admissionAgentId()
		})) {
			if (t) r = s;
			return;
		}
		if (e.dedupeLifecycle.isReserved()) {
			let o;
			if (s) {
				if (!s.ok || !isAcceptedAgentDedupePayload(s.payload)) {
					if (t) r = s;
					return;
				}
				if (!e.dedupeLifecycle.ownsReservation()) {
					if (t) a = true;
					return;
				}
				o = s.payload.expiresAtMs;
			}
			if (!s || !isFutureDateTimestampMs(o, { nowMs: Date.now() })) {
				if (t) {
					i = buildAbortedAgentPayload(e.runId, "timeout");
					setAbortedAgentDedupeEntries({
						dedupe: e.context.dedupe,
						keys: e.dedupeLifecycle.ownedReservationKeys(),
						agentId: admissionAgentId(),
						sessionKey: n,
						runId: e.runId,
						stopReason: "timeout"
					});
				}
				return;
			}
		}
		if (!n) return;
		const c = e.getSessionEntry();
		assertExpectedExistingSession({
			constraint: e.expectedSession,
			entry: c,
			message: `Session "${n}" changed while starting expected work. Retry.`
		});
		if (e.getSessionPersisted() && !c) throw new Error(`Session "${n}" was deleted while starting work. Retry.`);
		const l = resolveAgentSessionWorkStartError(n, c);
		if (l) throw new Error(l);
		if (t && c?.sessionId && c.sessionId !== e.getSupersededSessionId()) e.setAdmittedSessionId(c.sessionId);
		return c;
	};
	const interrupt = (t) => {
		if (n?.controller.signal.aborted) return;
		const r = isAgentRunRestartAbortReason(t) ? AGENT_RUN_RESTART_ABORT_STOP_REASON : "rpc";
		if (n?.entry) n.entry.adapter.abortStopReason = r;
		if (n) {
			const r = n.entry;
			const i = r !== void 0 && isRpcSourceRegistered(r) && !r.input.retirementRequested;
			n.controller.abort(t);
			return i ? { runId: e.runId } : void 0;
		}
		const i = e.dedupeLifecycle.ownedReservationKeys();
		if (i.length) {
			setAbortedAgentDedupeEntries({
				dedupe: e.context.dedupe,
				keys: i,
				agentId: admissionAgentId(),
				sessionKey: e.getResolvedSessionKey(),
				runId: e.runId,
				stopReason: r
			});
			return { runId: e.runId };
		}
	};
	const acquire = async (r) => {
		if (t) return;
		const isSettling = () => n?.entry?.adapter.terminalOutcomeObserved === true;
		const getAbortReason = () => n?.controller.signal.reason;
		const i = e.getResolvedSessionKey();
		if (!i) {
			assertAllowed();
			return;
		}
		const a = captureSessionTarget({
			storeScope: r,
			sessionKey: i,
			aliases: [e.getRequestedSessionKey()],
			agentId: admissionAgentId(),
			incarnation: e.getResolvedSessionId()
		});
		t = consumeExpectedSessionWorkAdmission({
			constraint: e.expectedSession,
			target: a,
			onInterrupt: interrupt,
			isSettling,
			getAbortReason
		}) ?? await beginSessionEffect({
			agentId: admissionAgentId(),
			target: a,
			sourceInput: n?.entry?.input,
			isSettling,
			getAbortReason,
			storeWriterIdentities: parseAgentSessionKey(i) && normalizeStoreSessionKey(i) === i ? [i] : void 0,
			assertAllowed: () => {
				assertAllowed(false);
			},
			revalidateAllowed: () => {
				assertAllowed();
			},
			onInterrupt: interrupt
		});
		if (i) {
			const t = await loadGatewaySessionEntryReadOnlyInWorker({
				cfg: e.context.getRuntimeConfig(),
				key: i,
				agentId: admissionAgentId(),
				excludeInternalEffects: true,
				assertActive: e.assertAdmissionCurrent
			});
			e.setSessionEntry(t.entry);
			assertAllowed();
		}
	};
	const respondToOutcome = () => {
		if (r || i || a) {
			t?.release();
			e.dedupeLifecycle.markAccepted(true);
			e.io.emitAcceptance(r ? [
				r.ok,
				r.payload,
				r.error
			] : [
				true,
				i ?? {
					runId: e.runId,
					status: "in_flight"
				},
				void 0
			], {
				cached: true,
				runId: e.runId
			});
			return true;
		}
		return false;
	};
	return {
		admissionAgentId,
		assertAllowed,
		acquire,
		respondToOutcome,
		hasOutcome: () => Boolean(r || i || a),
		getAdmission: () => t,
		getAdmittedRunAbort: () => n,
		setAdmittedRunAbort: (e) => {
			n = e;
		},
		release: () => {
			n?.cleanup();
			t?.release();
		}
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-content-phase.ts
async function prepareAgentContentPhase(e) {
	const t = e.request.message.trim();
	let n = {
		message: e.isRawModelRun ? t : annotateInterSessionPromptText(t, e.inputProvenance),
		images: [],
		imageOrder: [],
		media: [],
		offloadedRefs: []
	};
	let r = false;
	let i = e.agentId;
	let a = e.requestedSessionKey;
	const isKnownGatewayChannel = (e) => isGatewayMessageChannel(e) || isInternalNonDeliveryChannel(e);
	const o = normalizeTrimmedStringList([e.request.channel, e.request.replyChannel]);
	for (const t of o) {
		const n = normalizeMessageChannel(t);
		if (n && n !== "last" && !isKnownGatewayChannel(n)) {
			respondError(e.respond, ErrorCodes.INVALID_REQUEST, `invalid agent params: unknown channel: ${n}`);
			return;
		}
	}
	const s = normalizeOptionalString(e.request.voiceWakeTrigger) ?? "";
	const c = normalizeOptionalString(e.request.replyTo) ?? "";
	const l = e.explicitRecipientSession?.channel ?? e.request.channel;
	const u = e.explicitRecipientSession?.accountId ?? e.request.accountId;
	const d = e.explicitRecipientSession?.threadId ?? e.request.threadId;
	const f = e.sessionKeyFromTo ? "" : e.explicitRecipientSession?.to ?? e.requestedToRaw ?? "";
	const p = Object.hasOwn(e.request, "voiceWakeTrigger") && !normalizeOptionalString(e.request.agentId) && !e.requestedSessionId && !c && !f;
	const m = p && e.requestedSessionKeyRaw ? (() => {
		const t = e.cfg;
		const { canonicalKey: n } = resolveSessionStoreIdentity({
			cfg: t,
			sessionKey: e.requestedSessionKeyRaw,
			...i ? { agentId: i } : {}
		});
		const r = resolveAgentIdFromSessionKey(n, i);
		const a = tryResolveSessionCompatibilityOwnerAgentId(t, n);
		if (!a || r !== a) return true;
		return n !== resolveAgentMainSessionKey({
			cfg: t,
			agentId: r
		});
	})() : false;
	if (p && !m) try {
		const t = resolveVoiceWakeRouteByTrigger({
			trigger: s || void 0,
			config: await loadVoiceWakeRoutingConfig()
		});
		if ("agentId" in t) {
			if (e.knownAgents.includes(t.agentId)) {
				i = t.agentId;
				a = resolveExplicitAgentSessionKey({
					cfg: e.cfg,
					agentId: i
				});
			} else e.context.logGateway.warn(`voicewake routing ignored unknown agentId="${t.agentId}" trigger="${s}"`);
		} else if ("sessionKey" in t) {
			if (classifySessionKeyShape(t.sessionKey) !== "malformed_agent") {
				const { canonicalKey: n } = resolveSessionStoreIdentity({
					cfg: e.cfg,
					sessionKey: t.sessionKey
				});
				const r = resolveAgentIdFromSessionKey(n);
				if (e.knownAgents.includes(r)) {
					a = n;
					i = r;
				} else e.context.logGateway.warn(`voicewake routing ignored unknown session agent="${r}" sessionKey="${n}" trigger="${s}"`);
			} else e.context.logGateway.warn(`voicewake routing ignored malformed sessionKey="${t.sessionKey}" trigger="${s}"`);
		}
	} catch (t) {
		e.context.logGateway.warn(`voicewake routing load failed: ${formatForLog(t)}`);
	}
	e.assertAdmissionCurrent?.();
	if (await e.onTargetResolved?.({
		sessionKey: a,
		agentId: i
	}) === false) return;
	if (e.normalizedAttachments.length > 0) {
		let t = null;
		let o = i;
		const s = a ?? e.requestedSessionKeyRaw;
		if (s) {
			const n = resolveSessionStoreIdentity({
				cfg: e.cfg,
				sessionKey: s,
				agentId: i
			});
			t = await readAcpSessionEntryAsync({
				cfg: e.cfg,
				agentId: n.agentId,
				sessionKey: n.canonicalKey,
				assertCurrent: e.assertAdmissionCurrent
			});
			e.assertAdmissionCurrent?.();
			o = n.agentId;
		}
		const c = resolveSessionModelRef(t?.cfg ?? e.cfg, t?.entry, o);
		const l = e.modelOverride ? resolvePersistedOverrideModelRef({
			defaultProvider: e.providerOverride ?? c.provider,
			overrideProvider: e.providerOverride,
			overrideModel: e.modelOverride
		}) ?? c : {
			provider: e.providerOverride ?? c.provider,
			model: c.model
		};
		const u = e.request.acpTurnSource === "manual_spawn" && e.requestedSessionKeyRaw !== void 0 && isAcpSessionKey(e.requestedSessionKeyRaw) && t?.acp != null || await resolveGatewayModelSupportsImages({
			loadGatewayModelCatalog: e.context.loadGatewayModelCatalog,
			loadGatewayModelCatalogSnapshot: e.context.loadGatewayModelCatalogSnapshot,
			agentId: o,
			...l
		});
		r = !u;
		e.assertAdmissionCurrent?.();
		try {
			n = await parseMessageWithAttachments(n.message, e.normalizedAttachments, {
				maxBytes: resolveChatAttachmentMaxBytes(e.cfg),
				log: e.context.logGateway,
				supportsImages: u,
				acceptNonImage: false,
				assertCurrent: e.assertAdmissionCurrent
			});
			n.message = (r ? stripImageMediaMarkers(n.message, n.offloadedRefs) : n.message).trim();
		} catch (t) {
			e.assertAdmissionCurrent?.();
			if (t instanceof AgentRequestReservationEndedError) throw t;
			logAttachmentFailure(e.context.logGateway, "agent attachment parse failed", t);
			e.respond(false, void 0, t instanceof SessionMutationAuthorizationChangedError ? t.error : errorShape(t instanceof MediaOffloadError ? ErrorCodes.UNAVAILABLE : ErrorCodes.INVALID_REQUEST, String(t)));
			return;
		}
	}
	return {
		agentId: i,
		requestedSessionKey: a,
		needsImageUnderstanding: r,
		effectiveTranscriptInputText: t,
		...n,
		replyTo: c,
		recipientChannel: l,
		recipientAccountId: u,
		recipientThreadId: d,
		to: f
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-dedupe-lifecycle.ts
function createAgentDedupeLifecycle(e) {
	let t = false;
	let n = false;
	let r;
	let i;
	const a = randomUUID();
	const reserve = (n, i) => {
		if (t) return;
		const o = readGatewayDedupeEntry({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys
		});
		const s = isPreRegistrationAbortedAgentDedupeEntryForSession({
			entry: o,
			runId: e.runId,
			sessionKey: n,
			agentId: i
		});
		const hasCurrentSource = () => hasUnretiredRpcSource(e.runId, {
			sessionKey: n,
			agentId: i
		}, e.context.resolveGatewayContext);
		const c = asOptionalRecord(o?.payload);
		const l = c?.timeoutPhase === "queue" && c.providerStarted === false;
		if (s && (!e.reconcileDurableInput || hasCurrentSource() || l)) {
			r = o;
			return;
		}
		const u = Date.now();
		const d = resolveAgentTimeoutMs({
			cfg: e.cfg,
			overrideSeconds: e.request.timeout
		});
		setGatewayDedupeEntries({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys,
			...e.reconcileDurableInput && !hasCurrentSource() ? { startNewAttempt: true } : {},
			entry: {
				ts: u,
				ok: true,
				payload: {
					runId: e.runId,
					reservationId: a,
					status: "accepted",
					...n ? { sessionKey: n } : {},
					...i ? { agentId: i } : {},
					controlUiVisible: !e.suppressVisibleSessionEffects && !isSubagentCoordinationInputProvenance(e.inputProvenance),
					acceptedAt: u,
					dedupeKeys: e.agentDedupeKeys,
					expiresAtMs: resolveAgentRunExpiresAtMs({
						now: u,
						timeoutMs: d
					}),
					ownerConnId: e.ownerConnId,
					ownerDeviceId: e.ownerDeviceId
				}
			}
		});
		t = true;
	};
	const ownedReservationKeys = () => !t || n ? [] : e.agentDedupeKeys.filter((t) => {
		const n = e.context.dedupe.get(t);
		return n?.ok && isAcceptedAgentDedupePayload(n.payload) && n.payload.reservationId === a;
	});
	const ownsReservation = () => ownedReservationKeys().length === e.agentDedupeKeys.length;
	const assertReservationCurrent = () => {
		if (!ownsReservation()) throw new AgentRequestReservationEndedError();
	};
	const handlePreparationFailure = (t) => (n) => {
		t?.();
		if (!ownsReservation() && replayAgentTurnIfCached({
			preflight: e,
			context: e.context,
			io: e.io,
			acceptedOnly: e.reconcileDurableInput && !(r && readGatewayDedupeEntry({
				dedupe: e.context.dedupe,
				keys: e.agentDedupeKeys
			}) === r)
		})) return;
		if (n instanceof AgentRequestReservationEndedError) {
			logAttachmentFailure(e.context.logGateway, "agent attachment parse failed", n);
			e.io.emitAcceptance([
				false,
				void 0,
				errorShape(ErrorCodes.INVALID_REQUEST, String(n))
			]);
			return;
		}
		throw n;
	};
	const clearUnaccepted = () => {
		const r = ownedReservationKeys();
		if (!r.length) return;
		if (i) {
			const t = i;
			const a = t.replyError ? [
				false,
				void 0,
				t.replyError
			] : [
				true,
				buildBareSessionResetResponse({
					runId: e.runId,
					result: buildBareSessionResetResult({
						reason: t.reason,
						sessionId: t.sessionId,
						ackText: t.followUpPending ? `${sessionResetAckText(t.reason)} Request ended before the follow-up ran; send the follow-up message again.` : void 0
					})
				}),
				void 0
			];
			setGatewayDedupeEntries({
				dedupe: e.context.dedupe,
				keys: r,
				entry: {
					ts: Date.now(),
					ok: a[0],
					payload: a[1],
					error: a[2]
				}
			});
			n = true;
			return;
		}
		for (const t of r) e.context.dedupe.delete(t);
		t = false;
	};
	const cancelOwnedReservation = (t) => {
		if (n) return false;
		try {
			e.assertAdmissionCurrent?.();
		} catch {
			const t = getRpcSourceForGateway(e.runId, e.context.resolveGatewayContext);
			if (!e.assertCancellationCurrent || t?.adapter.projectSessionTerminalPending) return false;
			try {
				e.assertCancellationCurrent();
			} catch {
				return false;
			}
		}
		const r = ownedReservationKeys();
		if (r.length !== e.agentDedupeKeys.length) return false;
		setAbortedAgentDedupeEntries({
			dedupe: e.context.dedupe,
			keys: r,
			agentId: t.agentId,
			sessionKey: t.sessionKey,
			runId: e.runId,
			stopReason: t.stopReason
		});
		n = true;
		return true;
	};
	const bindSessionTarget = (t) => {
		const n = readGatewayDedupeEntry({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys
		});
		if (!n?.ok || !isAcceptedAgentDedupePayload(n.payload) || n.payload.reservationId !== a) return;
		const r = typeof n.payload.sessionKey === "string" ? n.payload.sessionKey : void 0;
		setGatewayDedupeEntries({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys.filter((t) => e.context.dedupe.get(t)?.payload === n.payload),
			entry: {
				...n,
				payload: {
					...n.payload,
					...t,
					...r && r !== t.sessionKey ? { sessionKeyAliases: [r] } : {}
				}
			}
		});
	};
	return {
		reservationId: a,
		ownsReservation,
		ownedReservationKeys,
		assertReservationCurrent,
		handlePreparationFailure,
		reserve,
		bindSessionTarget,
		clearUnaccepted,
		releaseUnacceptedReservation: () => {
			if (n || i || !ownsReservation()) return false;
			clearUnaccepted();
			return !t;
		},
		cancelOwnedReservation,
		isReserved: () => t,
		markAccepted: (e) => {
			n = e;
		},
		setCommittedResetCompletion: (e) => {
			i = e;
		}
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-delivery-phase.ts
async function resolveAgentDeliveryPhase(e) {
	const t = e.sessionEntry?.incognito === true || isIncognitoSessionKey(e.resolvedSessionKey);
	const respond = (n, r, i) => {
		if (t && i) {
			e.respond(n, r, i, { errorMessage: "Incognito agent error." });
			return;
		}
		e.respond(n, r, i);
	};
	const n = e.resolvedSessionAgentId ? e.resolvedSessionAgentId : e.resolvedSessionKey ? resolveAgentIdFromSessionKey(e.resolvedSessionKey, e.agentId) : e.agentId;
	if (!n) {
		respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "agent selection is required for this session"));
		return;
	}
	if (e.onRunObserved) {
		e.onRunObserved(e.runId);
		const t = e.resolvedSessionKey ? tryResolveSessionCompatibilityOwnerAgentId(e.cfgForAgent ?? e.cfg, e.resolvedSessionKey) : void 0;
		const r = e.storePath ? captureRpcSourceScopeMatcher({
			storePath: e.storePath,
			resolveGatewayContext: e.context.resolveGatewayContext
		}) : void 0;
		for (const [i, a] of listRpcSourceEntries()) {
			const o = getRpcSourceIdentity(a);
			const s = o.sessionKey === e.resolvedSessionKey;
			const c = resolveChatRunOwnerAgentId({
				agentId: o.agentId,
				sessionKey: o.sessionKey,
				defaultAgentId: t
			});
			if (i !== e.runId && s && c === n && r?.(a) && isRpcSourceActive(a)) e.onRunObserved(i);
		}
	}
	const r = normalizeMessageChannel(e.recipientChannel);
	const i = e.client?.connect && e.isWebchatConnect(e.client.connect);
	const a = normalizeMessageChannel(e.request.replyChannel ?? r);
	const o = a === "webchat" || i && (!a || a === "last") && !e.replyTo && !e.to;
	const s = e.request.deliver === true && !o;
	const c = o ? void 0 : normalizeOptionalString(e.recipientThreadId);
	const l = await resolveAgentDeliveryPlanWithSessionRoute({
		cfg: e.cfgForAgent ?? e.cfg,
		agentId: n,
		currentSessionKey: e.resolvedSessionKey,
		sessionEntry: o ? void 0 : e.sessionEntry,
		requestedChannel: o ? INTERNAL_MESSAGE_CHANNEL : a,
		explicitTo: o ? void 0 : e.replyTo || e.to || void 0,
		explicitThreadId: c,
		accountId: o ? void 0 : e.request.replyAccountId ?? e.recipientAccountId,
		wantsDelivery: s,
		turnSourceChannel: r,
		turnSourceTo: e.to || void 0,
		turnSourceAccountId: normalizeOptionalString(e.recipientAccountId),
		turnSourceThreadId: c
	});
	let u = l.resolvedChannel;
	let d = l.deliveryTargetMode;
	const f = l.resolvedAccountId;
	let p = l.resolvedTo;
	let m = l;
	let h = null;
	let g = l.targetResolutionError;
	if (s && u === "webchat") try {
		const t = await resolveMessageChannelSelection({ cfg: e.cfgForAgent ?? e.cfg });
		u = t.channel;
		d = d ?? "implicit";
		m = {
			...l,
			resolvedChannel: u,
			plugin: t.plugin,
			deliveryTargetMode: d,
			resolvedAccountId: f
		};
	} catch (t) {
		if (!shouldDowngradeDeliveryToSessionOnly({
			wantsDelivery: s,
			bestEffortDeliver: e.bestEffortDeliver,
			resolvedChannel: u
		})) {
			respond(false, void 0, errorShapeFromError(ErrorCodes.INVALID_REQUEST, t));
			return;
		}
		h = String(t);
	}
	if (s && g && !e.bestEffortDeliver) {
		respond(false, void 0, errorShapeFromError(ErrorCodes.INVALID_REQUEST, g));
		return;
	}
	if (!p && isDeliverableMessageChannel(u)) {
		const t = await resolveAgentOutboundTarget({
			cfg: e.cfgForAgent ?? e.cfg,
			plan: m,
			targetMode: d ?? "implicit",
			validateExplicitTarget: false
		});
		if (t.resolvedTarget?.ok) p = t.resolvedTo;
		else if (t.resolvedTarget && !t.resolvedTarget.ok) g = t.resolvedTarget.error;
	}
	const _ = isDeliverableMessageChannel(u) && !p;
	if (s && (_ || u === "webchat")) {
		if (!e.bestEffortDeliver) {
			respond(false, void 0, _ && g ? errorShapeFromError(ErrorCodes.INVALID_REQUEST, g) : errorShape(ErrorCodes.INVALID_REQUEST, _ ? `delivery target is required for ${u}: pass --to/--reply-to or configure a default target` : "delivery channel is required: pass --channel/--reply-channel or use a main session with a previous channel"));
			return;
		}
		e.context.logGateway.info(_ ? g && !t ? `agent delivery target missing (bestEffortDeliver): ${String(g)}` : "agent delivery target missing (bestEffortDeliver): no deliverable target" : h && !t ? `agent delivery unresolved (bestEffortDeliver); final delivery will report: ${h}` : "agent delivery unresolved (bestEffortDeliver); final delivery will report: no deliverable channel");
	}
	const v = r && (isGatewayMessageChannel(r) || isInternalNonDeliveryChannel(r)) ? r : void 0;
	return {
		activeSessionAgentId: n,
		deliveryPlan: m,
		resolvedChannel: u,
		deliveryTargetMode: d,
		resolvedAccountId: f,
		resolvedTo: p,
		originMessageChannel: v ?? (i ? "webchat" : u !== "webchat" || l.baseDelivery.channel || normalizeMessageChannel(e.request.replyChannel) === "webchat" ? u : void 0),
		deliver: s,
		explicitThreadId: c
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-request-routing.ts
async function prepareAgentRequestRouting(e) {
	const rejectInvalidRequest = (t) => {
		e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, t));
	};
	const t = normalizeRpcAttachmentsToChatAttachments(e.request.attachments);
	const n = listAgentIds(e.cfg);
	const r = normalizeOptionalString(e.request.agentId) ?? "";
	let i = r ? normalizeAgentId(r) : void 0;
	if (i && !n.includes(i)) return rejectInvalidRequest(`invalid agent params: unknown agent id "${e.request.agentId}"`);
	const a = normalizeOptionalString(e.request.sessionKey);
	const o = normalizeOptionalString(e.request.sessionId);
	const s = normalizeOptionalString(e.request.to);
	const c = !a && !o && classifySessionKeyShape(s) === "agent" ? s : void 0;
	const l = a ?? c;
	const u = l ?? (!o && !i ? "main" : void 0);
	if (u) {
		const t = resolveRequestedSessionAgentId(e.cfg, u, i);
		if (!t.ok) {
			e.respond(false, void 0, t.error);
			return;
		}
		i = t.agentId;
	}
	let d;
	if (o && !l) try {
		e.reserveDedupe(void 0, i);
		d = await (e.request.createSessionIfMissing ? resolveSessionKeyForRequestCore : resolveExistingSessionKeyForRequest)({
			cfg: e.cfg,
			sessionId: o,
			agentId: i
		});
		i = d.agentId ?? i;
	} catch (t) {
		e.assertCurrent?.();
		e.clearDedupe();
		return rejectInvalidRequest(formatForLog(t));
	}
	const f = normalizeMessageChannel(e.request.channel);
	const p = !l && !o && i && f && isDeliverableMessageChannel(f) && s ? {
		agentId: i,
		channel: f,
		to: s
	} : void 0;
	let m;
	if (p) {
		e.reserveDedupe(void 0, p.agentId);
		try {
			m = await resolveAgentExplicitRecipientSession({
				cfg: e.cfg,
				...p,
				accountId: normalizeOptionalString(e.request.accountId),
				threadId: e.request.threadId
			});
		} catch (t) {
			e.assertCurrent?.();
			e.clearDedupe();
			return rejectInvalidRequest(formatForLog(t));
		}
	}
	if (d || p) e.assertCurrent?.();
	if (m?.error) {
		e.clearDedupe();
		return rejectInvalidRequest(m.error.message);
	}
	const h = l ?? d?.sessionKey ?? m?.sessionKey ?? (!o ? resolveExplicitAgentSessionKey({
		cfg: e.cfg,
		agentId: r ? i : void 0
	}) : void 0);
	const g = validateExpectedExistingSessionTarget({
		constraint: e.expectedSession,
		requestedSessionId: o,
		requestedSessionKey: h
	});
	if (g) {
		e.clearDedupe();
		return rejectInvalidRequest(g);
	}
	let _;
	if (h) {
		e.reserveDedupe(h, i);
		try {
			_ = await loadGatewaySessionEntryReadOnlyInWorker({
				cfg: e.cfg,
				key: h,
				agentId: i,
				projection: "list",
				excludeInternalEffects: true,
				assertActive: e.assertCurrent
			});
			const t = respondUnavailableAgentSession({
				loaded: _,
				requestedSessionId: o,
				isRawModelRun: e.isRawModelRun,
				respond: e.respond,
				assertCurrent: e.assertCurrent
			});
			if (t instanceof Promise ? await t : t) {
				e.clearDedupe();
				return;
			}
		} catch (t) {
			e.clearDedupe();
			throw t;
		}
	}
	if (e.execApprovalFollowupApprovalId && l) {
		const t = normalizeOptionalString(e.request.execApprovalFollowupExpectedSessionId);
		const n = normalizeOptionalString(_?.entry?.sessionId);
		if (isExecApprovalFollowupSessionRebound({
			expectedSessionId: t,
			resolvedSessionId: n
		})) {
			emitDiagnosticEvent({
				type: "exec.approval.followup_suppressed",
				approvalId: e.execApprovalFollowupApprovalId,
				reason: "session_rebound",
				phase: "gateway_preflight"
			});
			e.context.logGateway.info(`Dropping stale exec approval followup ${e.execApprovalFollowupApprovalId}: session ${l} rebound (expected ${t}, current ${n}) before the approval resolved`);
			const r = {
				runId: e.runId,
				status: "ok",
				summary: "exec approval followup dropped: session was reset before the approval resolved"
			};
			setGatewayDedupeEntries({
				dedupe: e.context.dedupe,
				keys: e.agentDedupeKeys,
				entry: {
					ts: Date.now(),
					ok: true,
					payload: r
				}
			});
			e.respond(true, r, void 0, { runId: e.runId });
			return;
		}
	}
	const v = h && resolveSessionStoreKey({
		cfg: e.cfg,
		sessionKey: h,
		storeAgentId: i
	}) === "global" ? "global" : h;
	e.reserveDedupe(v, i);
	if (_) e.bindDedupeSessionTarget({
		sessionKey: _.canonicalKey,
		agentId: i,
		sessionId: _.entry?.sessionId
	});
	return {
		normalizedAttachments: t,
		requestedBestEffortDeliver: e.request.bestEffortDeliver,
		knownAgents: n,
		agentId: i,
		requestedSessionId: o,
		requestedToRaw: s,
		sessionKeyFromTo: c,
		requestedSessionKeyRaw: l,
		requestedSessionKey: h,
		explicitRecipientSession: m,
		preAcceptedReservedSessionKey: v,
		preAttachmentSession: _?.entry ? {
			canonicalKey: _.canonicalKey,
			sessionId: _.entry.sessionId
		} : void 0
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-diagnostics.ts
/** Capture privacy once for command output, failure diagnostics, and later RPC replay. */
function createAgentRunDiagnostics(e, t, n) {
	const r = t === true || isIncognitoSessionKey(e);
	const i = "Incognito agent error.";
	return {
		incognito: r,
		runtime: r ? {
			log() {},
			error() {},
			exit: defaultRuntime.exit
		} : defaultRuntime,
		warning: (e) => (t) => n.warn(`${e}: ${r ? i : formatForLog(t)}`),
		forReplay: (e) => r ? {
			...e,
			incognito: true
		} : e,
		errorMeta: (e, t = true) => ({
			...e !== void 0 && t ? { error: r ? i : e } : {},
			...e !== void 0 && r ? { errorMessage: i } : {}
		})
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-subagent.ts
/** Native subagent registration and paused-run adoption precede Gateway acceptance. */
function resolveGatewayPluginSubagentToolPolicy(e) {
	return {
		runtimePluginToolGrant: e?.internal?.agentRunTracking === "plugin_subagent" && e.internal.pluginRuntimeOwnerId === e.internal.runtimePluginToolGrant?.pluginId ? e.internal.runtimePluginToolGrant : void 0,
		pluginSubagentToolsAllow: e?.internal?.agentRunTracking === "plugin_subagent" && Array.isArray(e.internal.pluginSubagentToolsAllow) ? [...e.internal.pluginSubagentToolsAllow] : void 0
	};
}
async function prepareGatewaySubagentRun(e) {
	const t = e.resolvedSessionKey ? readFollowupSuccessor(e.runId, e.resolvedSessionKey) : void 0;
	if (t) {
		e.assertResumeAdmissionCurrent();
		await t.owner.prepareSuccessor(t);
		e.assertResumeAdmissionCurrent();
		t.assertCurrent();
		return {
			pluginSubagent: false,
			reactivateSubagent: false,
			followupCompletion: t.owner,
			followupSuccessor: t
		};
	}
	const n = readInProcessSubagentResume(e.client?.internal);
	if (n) return {
		pluginSubagent: false,
		reactivateSubagent: false,
		adoptParentResume: await prepareParentSubagentResume({
			cfg: e.cfg,
			resume: n,
			sessionKey: e.resolvedSessionKey,
			getSessionId: e.getAdmittedSessionId,
			runId: e.runId,
			task: e.request.message,
			assertAdmissionCurrent: e.assertResumeAdmissionCurrent,
			onAdopted: e.onParentResumeAdopted,
			gatewayContextResolver: e.context.resolveGatewayContext
		})
	};
	const r = e.resolvedSessionKey?.trim();
	const i = r ? readFollowupRequest(e.runId, r) : void 0;
	if (i) {
		if (i.requesterSessionKey !== e.inputProvenance?.sourceSessionKey) throw new Error("Follow-up requester does not match its completion custody.");
		const t = SessionFollowupCompletion.bind(i, e.assertResumeAdmissionCurrent);
		i.completion = t;
		return {
			pluginSubagent: false,
			reactivateSubagent: false,
			followupCompletion: t
		};
	}
	const a = e.client?.internal?.agentRunTracking;
	const o = e.inputProvenance?.kind === "inter_session";
	const s = Boolean(!e.isOneShotModelRun && r && (o ? e.inputProvenance?.sourceTool === "subagent_settle" && getLatestLiveSubagentRunByChildSessionKey(r, (e) => e.pauseReason === "sessions_yield", e.activeSessionAgentId) : a === "plugin_subagent"));
	e.assertResumeAdmissionCurrent();
	const c = s && r ? async () => {
		try {
			await registerPluginSubagentRunFromGateway({
				cfg: e.cfg,
				runId: e.runId,
				childSessionKey: r,
				childAgentId: e.activeSessionAgentId,
				task: e.request.message.trim(),
				requester: e.client?.internal?.pluginSubagentRequester,
				pluginId: normalizeOptionalString(e.client?.internal?.pluginRuntimeOwnerId),
				assertCurrent: e.assertResumeAdmissionCurrent,
				retainAdmission: e.retainPluginSubagentAdmission,
				admittedSession: {
					sessionId: e.getAdmittedSessionId(),
					storePath: e.lifecycleStorePath,
					entry: e.assertResumeAdmissionCurrent()
				},
				gatewayContextResolver: e.context.resolveGatewayContext
			});
		} catch (t) {
			e.assertResumeAdmissionCurrent();
			e.context.logGateway.warn(`failed to register plugin subagent run ${e.runId}; rejecting untracked dispatch: ${formatForLog(t)}`);
			throw new Error("plugin subagent registry persistence failed; run was not started", { cause: t });
		}
	} : void 0;
	return {
		pluginSubagent: s,
		reactivateSubagent: Boolean(r && !e.isOneShotModelRun && !o && !s && a !== "native_subagent" && !isAcpSessionKey(r)),
		registerPluginSubagent: c
	};
}
function settleUnstartedGatewayParentResume(e, t) {
	return runWithGatewayDetachedWorkContinuation(async () => {
		const n = await import("./subagent-registry-DxTolEfW.mjs");
		const ownsAdoption = () => isSameSubagentRunOwner(getLatestLiveSubagentRunByChildSessionKey(e.childSessionKey, void 0, e.childAgentId), e);
		if (!ownsAdoption()) return;
		if (!await n.markSubagentRunTerminated({
			runId: e.runId,
			reason: t ?? "Parent resume admission ended before acceptance.",
			suppressTaskDelivery: true,
			suppressSessionEffects: true,
			assertCurrent: () => {
				if (!ownsAdoption()) throw new Error("Adopted parent resume changed before admission rejection settled");
			}
		}) && ownsAdoption()) throw new Error("Adopted parent resume could not be durably settled after admission rejection");
	}, "subagents:unstarted-resume");
}
/** Rejection may settle only the exact physical execution already adopted by this admission. */
async function settleUnstartedGatewayFollowup(e) {
	const t = e.completion;
	if (!t?.ownsExecution(e.runId)) return;
	try {
		await t.settle(e.runId, {
			...e.outcome,
			endedAt: e.outcome.endedAt ?? Date.now()
		}, () => {
			const n = e.admittedRunEntry && isRpcSourceRegistered(e.admittedRunEntry) ? e.admittedRunEntry : getRpcSourceForGateway(e.runId, e.context.resolveGatewayContext, e.admittedRunEntry?.input.target);
			const r = e.admittedRunIdentity;
			const i = n === e.admittedRunEntry && r && n?.input.abortSignal === r.controller.signal && n.adapter.operationalRunInstance === r.operationalRunInstance && getRpcSourceLifecycleGeneration(n) === r.lifecycleGeneration && getRpcSourceIdentity(n).sessionKey === r.sessionKey;
			if (n && !i && (n === e.admittedRunEntry || getRpcSourceIdentity(n).sessionKey === t.request.targetSessionKey)) throw new Error("Follow-up admission was replaced before cleanup.");
		});
	} catch (n) {
		t.close(n);
		createAgentRunDiagnostics(t.request.targetSessionKey, e.isIncognito, e.context.logGateway).warning(`failed to settle unstarted follow-up ${e.runId}`)(n);
	}
}
/** A registered subagent run passes its timeout only to the turn admitted for its own session. */
function resolveRegisteredSubagentTimeoutSeconds(e) {
	const t = e.sessionKey ? getLatestLiveSubagentRunByChildSessionKey(e.sessionKey, void 0, e.agentId) : void 0;
	const n = t ? resolveSubagentChildAuthority(t, e.admittedSessionEntry) : void 0;
	return t && (!t.execution.suppressSessionEffects || n?.status === "legacy-unverified") && e.admittedSessionEntry?.sessionId === e.admittedSessionId && t.childSessionIdentity?.sessionId === e.admittedSessionId && t.childSessionIdentity?.lifecycleRevision === e.admittedSessionEntry?.lifecycleRevision && n?.status !== "mismatch" ? t.runTimeoutSeconds ?? 0 : void 0;
}
function consumeGatewaySubagentCompletionToolHandoff(e, t, n) {
	const r = resolveExactSubagentCompletionEvent({
		inputProvenance: t,
		internalEvents: e.request.internalEvents
	});
	return e.providerOverride === void 0 && e.modelOverride === void 0 && e.restoredCronContinuation === void 0 ? consumeSubagentCompletionToolHandoff({
		handoffId: e.client?.internal?.delegatedToolPolicyHandoffId,
		sourceTool: t?.sourceTool,
		sourceSessionKey: t?.kind === "inter_session" && t.sourceTool === "subagent_settle" ? t.sourceSessionKey : r?.childSessionKey,
		sourceSessionId: r?.childSessionId,
		targetSessionKey: e.resolvedSessionKey,
		targetSessionId: e.getAdmittedSessionId(),
		idempotencyKey: e.request.idempotencyKey,
		provider: n.provider,
		model: n.model
	}) : void 0;
}
//#endregion
//#region src/gateway/agent-turn/agent-run-admission-cleanup.ts
/** Retire rejected preparation only after its adopted task and runtime resources settle. */
async function cleanupRejectedAgentRunAdmission({ runId: e, context: t, incognito: n, activeRunAbort: r, activeGatewayWorkAdmission: i, admittedRunIdentity: a, admittedRunContext: o, releaseCallerAuthority: s, lease: c, completion: l, adopted: u, admissionReleased: d, failure: f }) {
	try {
		if (u) await settleUnstartedGatewayParentResume(u, f);
		if (l) await settleUnstartedGatewayFollowup({
			completion: l,
			runId: e,
			admittedRunEntry: r.entry,
			admittedRunIdentity: a,
			context: t,
			isIncognito: n,
			outcome: buildAgentRunTerminalOutcome({
				status: r.controller.signal.aborted ? "timeout" : "error",
				stopReason: r.controller.signal.aborted ? r.entry?.adapter.abortStopReason ?? "rpc" : void 0,
				error: f ?? "Follow-up admission ended before acceptance."
			})
		});
	} finally {
		try {
			await c?.[Symbol.asyncDispose]();
		} finally {
			try {
				try {
					s?.();
				} finally {
					if (o && a && getAgentRunContext(e) === o && (!hasRpcSource(e) || getRpcSource(e) === r.entry) && r.entry?.adapter.operationalRunInstance === a.operationalRunInstance) clearAgentRunContext(e, a.lifecycleGeneration);
				}
				r.cleanup();
				if (!d) i?.release();
			} finally {
				l?.finishExecution(e);
			}
		}
	}
}
//#endregion
//#region src/gateway/agent-turn/agent-run-admission-model.ts
function resolveAgentRunAdmissionModel(e) {
	const t = e.restoredCronContinuation?.provider ?? e.providerOverride;
	const n = e.restoredCronContinuation?.model ?? e.modelOverride;
	const r = e.restoredCronContinuation ? e.restoredCronContinuation.thinking : e.request.thinking;
	const i = e.allowModelOverride || e.restoredCronContinuation !== void 0;
	const a = e.cfgForAgent ?? e.cfg;
	const o = resolveSessionModelRef(a, e.sessionEntry, e.activeSessionAgentId);
	const s = n ? resolvePersistedOverrideModelRef({
		defaultProvider: t ?? o.provider,
		overrideProvider: t,
		overrideModel: n
	}) ?? o : {
		provider: t ?? o.provider,
		model: o.model
	};
	return {
		effectiveProviderOverride: t,
		effectiveModelOverride: n,
		effectiveThinking: r,
		effectiveAllowModelOverride: i,
		resolvedRuntime: {
			harness: resolveEffectiveAgentRuntime({
				cfg: a,
				provider: s.provider,
				modelId: s.model,
				agentId: e.activeSessionAgentId,
				sessionKey: e.resolvedSessionKey,
				sessionEntry: e.sessionEntry
			}),
			provider: s.provider,
			model: s.model
		},
		lifecycleStorePath: e.lifecycleStorePath
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-user-turn.ts
function reconcileAgentRunUserTurnCompletion(e, t, n, r) {
	const i = e.recorder?.getProcessingCompletion?.();
	if (!i) return;
	return n().then(() => {
		r.emitAcceptance([
			true,
			{
				...t,
				status: i.status,
				summary: i.reason,
				...i.stopReason ? { stopReason: i.stopReason } : {},
				...i.reason === "completed" ? { inputProcessingCompleted: true } : {}
			},
			void 0
		], { runId: t.runId });
	});
}
function recordAgentRunUserTurnParticipant(e, t, n) {
	const r = resolveGatewayInputParticipant(e.client, e.inputProvenance);
	if (r && e.resolvedSessionKey && !e.suppressVisibleSessionEffects && !t.suppressPromptPersistence) recordSessionParticipantBestEffort({
		identity: r,
		promptedAt: e.promptedAt,
		agentId: e.activeSessionAgentId,
		sessionKey: e.resolvedSessionKey,
		storePath: n,
		onError: (t) => e.context.logGateway.warn(`agent participant persistence failed: ${formatForLog(t)}`)
	});
}
async function prepareAgentRunUserTurn(e) {
	const t = e.client?.internal?.agentToolCaller;
	const n = e.client?.internal?.operatorRunAuthority;
	n?.assertCurrent();
	let r = t ? captureRequesterOrigin(t) : n || e.client?.authenticatedUserProfile && !e.client.internal?.syntheticClient ? captureRequesterOrigin({
		sessionKey: e.resolvedSessionKey,
		operatorProfileId: n?.profileId ?? e.client?.authenticatedUserProfile?.profileId
	}) : void 0;
	const resolveRuntimeSenderIsOwner = () => Boolean(e.restoredCronContinuation || hasGatewayAdminScope(e.client)) && (!r || Boolean(r.operatorProfileId) || (!r.messageProvider || r.messageProvider === "webchat") && !resolveRequesterPrincipalKey({ requesterOrigin: r }) && e.client?.internal?.operatorRoleActor?.kind === "system");
	const i = randomUUID();
	let a;
	let o = [];
	let s;
	try {
		const claimFollowup = (t) => claimExecApprovalFollowupRuntimeHandoff({
			handoffId: e.request.internalRuntimeHandoffId,
			approvalId: e.execApprovalFollowupApprovalId,
			idempotencyKey: e.runId,
			sessionKey: t,
			claimId: i
		});
		let t;
		if (e.canUseInternalRuntimeHandoff && e.execApprovalFollowupApprovalId) {
			t = claimFollowup(e.resolvedSessionKey);
			if (!t && e.requestedSessionKeyRaw && e.requestedSessionKeyRaw !== e.resolvedSessionKey) t = claimFollowup(e.requestedSessionKeyRaw);
		}
		if (t) a = e.request.internalRuntimeHandoffId;
		let n = e.message;
		const c = e.client?.internal?.runtimeContextFragments;
		let l = e.effectiveTranscriptInputText;
		let u;
		if (t?.resultText !== void 0) {
			const e = buildExecApprovalContinuationPrompt(t.resultText);
			n = e.message;
			l = e.message;
			u = e.resultRange;
		} else if (n === "An approved async exec completed; load the authenticated completion handoff.") throw new Error("exec approval followup runtime handoff is unavailable");
		let d = resolveRuntimeSenderIsOwner();
		const f = e.settleWakeReplay;
		if (f && (!e.runId.startsWith("announce:") || e.inputProvenance?.kind !== "inter_session" || e.inputProvenance.sourceTool !== "subagent_settle" || !e.inputProvenance.sourceSessionKey || !f.sourceSessionKeys.includes(e.inputProvenance.sourceSessionKey))) throw new Error("Settle replay requires an exact internal frozen-cohort source");
		let p = e.inputProvenance;
		if (e.privateCompletion && (e.request.deliver !== false || e.request.expectedExistingSessionId !== e.admittedSessionId || !e.runId.startsWith("announce:") || e.inputProvenance?.kind !== "inter_session" || !["subagent_announce", "subagent_settle"].includes(e.inputProvenance.sourceTool ?? ""))) throw new Error("Private completion requires an exact internal requester turn with delivery disabled");
		const m = e.privateCompletion || f !== void 0 || isSubagentAnnounceCompletionHandoff({
			inputProvenance: e.inputProvenance,
			internalEvents: e.request.internalEvents
		});
		const h = !e.privateCompletion && e.requestedPromptPersistenceSuppression;
		if (e.resolvedSessionKey && !e.suppressVisibleSessionEffects && !h) {
			const t = await persistInboundImagesForTranscript({
				images: e.images,
				offloadedRefs: e.offloadedRefs,
				log: e.context.logGateway,
				logContext: "agent",
				assertCurrent: e.assertCurrent
			});
			o = t.entries.filter((e) => e.imageKind === "inline").map((e) => e.id);
			e.assertCurrent();
			const n = t.entries.map((e) => e.fact);
			const i = t.entries.flatMap((e, t) => e.imageKind ? [{
				kind: e.imageKind,
				factIndex: t
			}] : []);
			const resolveTarget = async () => {
				e.assertCurrent();
				const t = e.freshChildStorePath ? {
					entry: e.sessionEntry,
					storePath: e.freshChildStorePath,
					store: void 0
				} : await loadGatewaySessionEntryReadOnlyInWorker({
					cfg: e.cfgForAgent ?? e.cfg,
					key: e.resolvedSessionKey,
					agentId: e.activeSessionAgentId,
					assertActive: e.assertCurrent,
					excludeInternalEffects: true
				});
				e.assertCurrent();
				const n = t.entry;
				const r = n?.sessionId?.trim();
				if (!e.freshChildStorePath && (!n || r !== e.admittedSessionId)) return;
				return {
					sessionId: e.admittedSessionId,
					expectedSessionId: e.admittedSessionId,
					sessionKey: e.resolvedSessionKey,
					sessionEntry: n,
					sessionStore: t.store,
					storePath: t.storePath,
					agentId: e.activeSessionAgentId,
					cwd: resolveSessionRuntimeCwd({ sessionEntry: n }),
					...e.resolvedThreadId != null ? { threadId: e.resolvedThreadId } : {},
					config: e.cfgForAgent ?? e.cfg
				};
			};
			const a = m ? await resolveTarget() : void 0;
			const c = gatewayClientSenderFields(e.client);
			if (a) {
				const t = await readSessionSubmittedInput(a, buildRunUserTurnIdempotencyKey(e.runId));
				e.assertCurrent();
				const n = c.sender;
				const i = t?.["__openclaw"];
				const o = n?.id ?? r?.operatorProfileId;
				if (o && i?.senderId === o) c.sender = {
					...n,
					id: o,
					name: typeof i.senderName === "string" ? i.senderName : void 0
				};
			}
			const u = {
				...e.privateCompletion || isCompletionReportInputProvenance(e.inputProvenance) || isSubagentCoordinationInputProvenance(e.inputProvenance) ? { display: false } : {},
				text: t.omission === "inline-image-save-failed" ? [l, INLINE_IMAGE_DURABLE_OMISSION_MARKER].filter(Boolean).join("\n") : l,
				timestamp: Date.now(),
				idempotencyKey: buildRunUserTurnIdempotencyKey(e.runId),
				...c,
				senderIsOwner: d,
				requesterOrigin: r,
				...e.inputProvenance ? { provenance: e.inputProvenance } : {},
				...n.length > 0 ? { media: n } : {},
				...i.length > 0 ? { mediaImageLayout: { slots: i } } : {}
			};
			const h = readSessionSendDeliveryAdmission({
				runId: e.runId,
				sessionKey: e.resolvedSessionKey,
				sessionId: e.admittedSessionId,
				agentId: e.activeSessionAgentId
			});
			s = createUserTurnTranscriptRecorder({
				trackInputCompletion: m || h !== void 0,
				pendingInputReplaySourceSessionKeys: f?.sourceSessionKeys,
				input: u,
				target: m ? () => {
					e.assertCurrent();
					return a;
				} : resolveTarget,
				errorContext: "gateway agent user turn transcript",
				...e.onTranscriptCommitted ? e.request.internalEvents?.length ? { onInputSubmitted: () => e.onTranscriptCommitted?.(e.runId) } : { onMessagePersisted: () => e.onTranscriptCommitted?.(e.runId) } : {},
				beforeMessageWrite: (t) => {
					const n = runAgentHarnessBeforeMessageWriteHook(t);
					e.assertCurrent();
					return n;
				},
				onPersistenceError: (t) => {
					e.context.logGateway.warn(`gateway agent user transcript persistence failed: ${formatForLog(t)}`);
				}
			});
			if (!await s.stageApproved({
				runId: e.runId,
				retryCancelled: m,
				storageTarget: e.freshChildStorePath ? {
					agentId: e.activeSessionAgentId,
					sessionId: e.admittedSessionId,
					sessionKey: e.resolvedSessionKey,
					storePath: e.freshChildStorePath
				} : void 0,
				assertCurrent: () => {
					e.assertCurrent();
					f?.assertCurrent();
				},
				assertAdmittedCurrent: e.assertCurrent,
				assertCompletionCurrent: e.assertCompletionCurrent
			}) && !s.getProcessingCompletion?.()) throw new Error("agent turn was not durably admitted");
			if (f) p = normalizeInputProvenance(s.getPendingInputMessage?.()?.provenance);
			r = readUserTurnRequesterOrigin(s) ?? r;
		}
		const g = r?.messageProvider && r.messageProvider !== "webchat" && !r.operatorProfileId ? await prepareCommandOwnerAuthority(e.cfg, {
			channel: r.messageProvider,
			accountId: r.accountId ?? void 0,
			senderId: r.senderId ?? void 0,
			senderE164: r.senderE164 ?? void 0
		}) : void 0;
		e.assertCurrent();
		if (r && !r.operatorProfileId) d = g?.isCurrent(e.cfg) === true || resolveRuntimeSenderIsOwner();
		const _ = g && d ? () => {
			if (!g.isCurrent(e.context.getRuntimeConfig())) throw new Error("Requester owner authority changed; send a new request.");
		} : void 0;
		_?.();
		let releaseProcessingAbortObserver;
		if (m && s && !s.getProcessingCompletion?.()) {
			const recordAbort = () => {
				const t = e.getAbortStopReason?.() ?? "rpc";
				if (t === "timeout") return;
				completeUserTurnProcessing(s, buildAgentRunTerminalOutcome({
					status: "error",
					stopReason: t
				})).catch((t) => {
					e.context.logGateway.warn(`private input cancellation persistence failed: ${formatForLog(t)}`);
				});
			};
			e.abortSignal?.addEventListener("abort", recordAbort, { once: true });
			releaseProcessingAbortObserver = () => e.abortSignal?.removeEventListener("abort", recordAbort);
			if (e.abortSignal?.aborted) recordAbort();
		}
		return {
			...e.privateCompletion ? { privateCompletion: true } : {},
			replyExpectation: e.replyExpectation,
			...releaseProcessingAbortObserver ? { releaseProcessingAbortObserver } : {},
			...t?.bashElevated ? { bashElevated: t.bashElevated } : {},
			...a ? { claimedExecApprovalFollowupHandoffId: a } : {},
			execApprovalFollowupHandoffClaimId: i,
			...u ? { execApprovalContinuationPromptRange: u } : {},
			message: n,
			...c ? { runtimeContextFragments: c } : {},
			inputProvenance: p,
			...s ? { recorder: s } : {},
			senderIsOwner: d,
			requesterOrigin: r,
			assertRequesterCurrent: _,
			suppressPromptPersistence: h
		};
	} catch (t) {
		const n = s !== void 0 && retainsUserTurnTranscriptMedia(s);
		if (n) e.onUserTurnMediaPersisted();
		const r = await releasePreparedAgentRunUserTurnAfterFailure({
			recorder: s,
			claimedExecApprovalFollowupHandoffId: a,
			execApprovalFollowupHandoffClaimId: i
		}, t);
		if (!n) await Promise.allSettled(o.map((e) => deleteMediaBuffer(e, "inbound")));
		throw r;
	}
}
function annotateAgentRunUserTurnPrompt(e) {
	const t = annotateInterSessionPromptText(e.message, e.inputProvenance);
	let n = e.execApprovalContinuationPromptRange;
	if (n) {
		if (!t.endsWith(e.message)) throw new Error("exec approval continuation prompt range could not be annotated");
		const r = t.length - e.message.length;
		n = {
			start: r + n.start,
			end: r + n.end
		};
	}
	return {
		message: t,
		execApprovalContinuationPromptRange: n
	};
}
function finalizePreparedAgentRunUserTurn(e) {
	const t = e.claimedExecApprovalFollowupHandoffId;
	if (!t) return;
	if (!finalizeExecApprovalFollowupRuntimeHandoff({
		handoffId: t,
		claimId: e.execApprovalFollowupHandoffClaimId
	})) throw new Error("exec approval followup runtime handoff expired before dispatch");
}
async function releasePreparedAgentRunUserTurn(e, t = "cancelled") {
	try {
		e.releaseProcessingAbortObserver?.();
		e.recorder?.finishPendingInput?.(t);
	} finally {
		try {
			await e.recorder?.waitForPendingInputSettlement?.();
		} finally {
			releaseExecApprovalFollowupRuntimeHandoff({
				handoffId: e.claimedExecApprovalFollowupHandoffId,
				claimId: e.execApprovalFollowupHandoffClaimId
			});
		}
	}
}
/** A recorded abort cannot replace a failed custody settlement. */
var AgentRunUserTurnCleanupError = class extends AggregateError {
	constructor(e, t) {
		super([e, t], `${formatForLog(e)}; pending input cleanup failed: ${formatForLog(t)}`);
	}
};
/** Settles failed input while preserving both admission and settlement failures. */
async function releasePreparedAgentRunUserTurnAfterFailure(e, t, n = "cancelled") {
	try {
		await releasePreparedAgentRunUserTurn(e, n);
		return t;
	} catch (e) {
		return new AgentRunUserTurnCleanupError(t, e);
	}
}
//#endregion
//#region src/gateway/agent-turn/agent-run-admission-revalidation.ts
/** Keep owner-provided policy failures intact across every preaccept preparation phase. */
function resolveAgentRunAdmissionError(e, t) {
	return t instanceof SessionMutationAuthorizationChangedError ? t.error : t instanceof PreparedModelRuntimePublicationSupersededError ? errorShapeFromError(ErrorCodes.UNAVAILABLE, t, {
		message: "Model runtime changed before this turn started. Retry the request.",
		retryable: true,
		retryAfterMs: 0
	}) : errorShapeFromError(e, t);
}
/** Join rejected input and preaccept cleanup without losing either failure. */
async function releaseFailedAgentRunAdmission(e, t, n) {
	const r = await releasePreparedAgentRunUserTurnAfterFailure(e, t);
	try {
		await n();
	} catch (e) {
		throw new AggregateError([r, e], `${formatForLog(r)}; agent admission cleanup failed: ${formatForLog(e)}`, { cause: e });
	}
	throw r;
}
/** Revalidate the same prepared admission after each asynchronous preparation step. */
function createAgentRunAdmissionRevalidator(e) {
	const { source: t, activeRunAbort: n, parentResume: r, rejectPreaccept: i, cleanupPreaccept: a } = e;
	const publishAborted = () => {
		if (n.controller.signal.aborted) setAbortedAgentDedupeEntries({
			dedupe: t.context.dedupe,
			keys: t.getOwnedAgentDedupeKeys(),
			agentId: t.admissionAgentId(),
			runId: t.runId,
			stopReason: n.entry?.adapter.abortStopReason ?? "rpc"
		});
	};
	return (e) => {
		try {
			const e = t.assertGatewayWorkAdmissionAllowed();
			if (r) {
				if (t.client?.internal?.syntheticClient !== true) throw new Error("Task resume requires trusted in-process admission.");
				assertParentSubagentResumeCurrent({
					cfg: t.cfg,
					resume: r,
					sessionKey: t.resolvedSessionKey,
					sessionId: t.getAdmittedSessionId(),
					sessionLifecycleRevision: e?.lifecycleRevision
				});
			}
		} catch (t) {
			return (async () => {
				const n = e ? await releasePreparedAgentRunUserTurnAfterFailure(e, t) : t;
				if (n === t) publishAborted();
				return i(resolveAgentRunAdmissionError(ErrorCodes.INVALID_REQUEST, n));
			})();
		}
		if (!n.controller.signal.aborted && !t.hasGatewayAdmissionOutcome()) return true;
		return (async () => {
			try {
				if (e) await releasePreparedAgentRunUserTurn(e);
				publishAborted();
				t.assertGatewayWorkAdmissionAllowed();
			} catch (e) {
				return i(resolveAgentRunAdmissionError(ErrorCodes.INVALID_REQUEST, e));
			}
			const n = t.respondToGatewayAdmissionOutcome();
			await a(n);
		})();
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-dispatch-outcome.ts
function projectWithdrawnAgentInput(e, t, n) {
	if (!t || !isRecord(e)) return e;
	const r = n ?? e.stopReason;
	if (e.status === "error" && r !== "rpc" && r !== "stop" && r !== "timeout") return e;
	return {
		...e,
		...n ? { stopReason: n } : {},
		reason: "input_withdrawn_before_turn",
		pendingInputId: t,
		summary: `Input ${t} was withdrawn before its turn started and was not delivered.` + (r === "timeout" ? " Raise --timeout and retry." : " Resend it when ready.")
	};
}
function resolveResolvedAgentTimeoutStopReason(e, t) {
	if (!t.aborted) return;
	const n = isRecord(e) ? e : void 0;
	if (n?.aborted !== true && n?.stopReason !== "toolUse") return;
	return resolveGatewayAgentAbortStopReason(t) === "timeout" ? "timeout" : void 0;
}
function isGatewayAbortSignalReason(e) {
	return e === void 0 || isAbortError(e) || readErrorName(e) === "TimeoutError";
}
function isGatewayAgentAbortRejection(e, t) {
	if (!t.aborted) return isAgentRunDirectAbortReason(e) || resolveAgentRunErrorLifecycleFields(e, void 0).stopReason === "restart";
	if (resolveAgentRunErrorLifecycleFields(void 0, t).stopReason === "restart") return true;
	if (t.reason === "timeout" || readErrorName(t.reason) === "TimeoutError") return true;
	if (t.reason === "rpc" || t.reason === "stop") return true;
	if (!isGatewayAbortSignalReason(t.reason)) return false;
	return isAbortError(e) || readErrorName(e) === "TimeoutError";
}
function resolveGatewayAgentAbortStopReason(e, t) {
	const n = resolveAgentRunErrorLifecycleFields(t, e).stopReason;
	return n === "restart" || n === "timeout" ? n : "rpc";
}
const RESOLVED_GATEWAY_STATUS_BY_TERMINAL_CLASSIFICATION = {
	success: "ok",
	timeout: "timeout",
	cancellation: "timeout",
	failure: "error"
};
function projectRejectedGatewayStatus(e) {
	return e.reason === "cancelled" || e.reason === "superseded" || e.stopReason === "timeout" ? "timeout" : "error";
}
//#endregion
//#region src/gateway/agent-turn/agent-run-admission-phase.ts
async function prepareAgentRunDispatch(e) {
	const t = captureRequesterCronAuthorityAdmissionAssertion({
		runId: e.runId,
		sessionKey: e.resolvedSessionKey,
		sessionId: e.getAdmittedSessionId(),
		inputProvenance: e.inputProvenance
	});
	t?.();
	const n = e.privateCompletion || isSubagentCoordinationInputProvenance(e.inputProvenance);
	const r = !e.suppressVisibleSessionEffects && !n;
	const i = readInProcessSubagentResume(e.client?.internal);
	const a = readGatewayDedupeEntry({
		dedupe: e.context.dedupe,
		keys: e.agentDedupeKeys
	});
	if (isPreRegistrationAbortedAgentDedupeEntryForSession({
		entry: a,
		runId: e.runId,
		sessionKey: e.resolvedSessionKey,
		alternateSessionKeys: [e.preAcceptedReservedSessionKey, e.requestedSessionKey],
		agentId: e.activeSessionAgentId
	})) {
		e.markAgentRunAccepted(true);
		e.io.emitAcceptance([
			true,
			a?.payload,
			void 0
		], {
			cached: true,
			runId: e.runId
		});
		return;
	}
	if (e.restoredCronContinuationIdentity && !e.restoredCronContinuation) {
		e.io.emitAcceptance([
			false,
			void 0,
			errorShape(ErrorCodes.UNAVAILABLE, "cron run continuation could not be restored")
		]);
		return;
	}
	const { resolvedRuntime: o, ...s } = resolveAgentRunAdmissionModel(e);
	const { lifecycleStorePath: c } = s;
	let l;
	let u = true;
	let d;
	try {
		if (c) await e.acquireGatewayWorkAdmission(c);
		const t = e.assertGatewayWorkAdmissionAllowed();
		if (!e.hasGatewayAdmissionOutcome()) {
			e.context.requestEntryLifetime?.signal.throwIfAborted();
			const n = e.getAdmittedRunAbort();
			d = n?.entry?.adapter.operationalRunInstance ?? createOperationalRunInstanceRef(e.runId);
			l = e.request.timeout ?? resolveRegisteredSubagentTimeoutSeconds({
				sessionKey: e.isOneShotModelRun ? void 0 : e.resolvedSessionKey,
				agentId: e.activeSessionAgentId,
				admittedSessionId: e.getAdmittedSessionId(),
				admittedSessionEntry: t
			});
			const i = resolveAgentTimeoutMs({
				cfg: e.cfgForAgent ?? e.cfg,
				overrideSeconds: l
			});
			const a = {
				providerId: o.provider,
				authProviderId: resolveProviderIdForAuth(o.provider, { config: e.cfgForAgent ?? e.cfg })
			};
			if (n?.entry) {
				updateRpcSourceSessionId(n.entry, e.getAdmittedSessionId());
				Object.assign(n.entry.adapter, a);
			} else e.setAdmittedRunAbort(registerChatAbortController({
				sourceWork: e.sourceWork,
				runId: e.runId,
				sessionId: e.getAdmittedSessionId(),
				sessionKey: e.resolvedSessionKey,
				...e.resolvedSessionKey && c ? { target: captureSessionTarget({
					storeScope: c,
					sessionKey: e.resolvedSessionKey,
					aliases: [e.requestedSessionKey],
					agentId: e.admissionAgentId(),
					incarnation: e.getAdmittedSessionId()
				}) } : {},
				authority: { assertCurrent: () => {
					if (u) e.assertAdmissionCurrent?.();
				} },
				agentId: e.admissionAgentId(),
				timeoutMs: i,
				ownerConnId: e.ownerConnId,
				ownerDeviceId: e.ownerDeviceId,
				...a,
				controlUiVisible: r,
				kind: "agent",
				lifecycleGeneration: e.lifecycleGeneration,
				operationalRunInstance: d
			}));
			e.getAdmittedRunAbort()?.initializeTiming({
				timeoutMs: i,
				onQueueTimeout: (t) => void abortChatRunById(createChatAbortOps(e.context), {
					runId: e.runId,
					sessionKey: getRpcSourceIdentity(t).sessionKey,
					stopReason: "timeout",
					expectedEntry: t
				})
			});
		}
	} catch (t) {
		e.io.emitAcceptance([
			false,
			void 0,
			errorShape(ErrorCodes.INVALID_REQUEST, formatForLog(t))
		]);
		return;
	}
	if (e.respondToGatewayAdmissionOutcome()) return;
	const f = e.getGatewayWorkAdmission();
	if (e.resolvedSessionKey && !f) {
		e.io.emitAcceptance([
			false,
			void 0,
			errorShape(ErrorCodes.UNAVAILABLE, "agent run admission failed")
		]);
		return;
	}
	const p = e.getAdmittedRunAbort();
	if (!p || !d) {
		p?.cleanup();
		f?.release();
		e.io.emitAcceptance([
			false,
			void 0,
			errorShape(ErrorCodes.UNAVAILABLE, "agent run admission failed")
		]);
		return;
	}
	const m = p.existingEntry;
	if (!p.registered && m) {
		f?.release();
		e.markAgentRunAccepted(m.adapter.kind === "agent");
		e.io.emitAcceptance([
			true,
			{
				runId: e.runId,
				status: "in_flight"
			},
			void 0
		], {
			cached: true,
			runId: e.runId
		});
		return;
	}
	const h = p.entry ? {
		controller: p.controller,
		operationalRunInstance: d,
		lifecycleGeneration: e.lifecycleGeneration,
		sessionKey: getRpcSourceIdentity(p.entry).sessionKey
	} : void 0;
	let g;
	if (!p.registered) f?.release();
	else {
		if (e.pendingChatRun) e.context.addChatRun(e.runId, {
			...e.pendingChatRun,
			clientRunId: e.runId
		});
		if (e.resolvedSessionKey) {
			claimAgentRunContext(e.runId, {
				...e.suppressVisibleSessionEffects ? {} : { sessionKey: e.resolvedSessionKey },
				agentId: getRpcSourceIdentity(p.entry).agentId,
				isControlUiVisible: r,
				...e.privateCompletion ? { sessionEventDelivery: false } : {},
				...n ? {
					projectSessionMessages: false,
					projectSessionActive: false
				} : {},
				lifecycleGeneration: e.lifecycleGeneration
			});
			g = getAgentRunContext(e.runId);
		}
		e.io.emitStartOwner?.(e.runId, p.entry);
	}
	const _ = resolveIngressWorkspaceOverrideForSessionRun({
		spawnedBy: e.sessionEntry?.spawnedBy,
		workspaceDir: e.sessionEntry?.spawnedWorkspaceDir,
		cwd: e.sessionEntry?.spawnedCwd
	});
	let v;
	let y;
	let b;
	let x;
	let S = false;
	const releaseCallerAuthority = () => {
		if (S) return;
		S = true;
		try {
			x?.release?.();
		} finally {
			b?.release();
		}
	};
	let C;
	let w;
	let T;
	const cleanupPreaccept = async (t = false, n) => {
		const r = v;
		const i = C;
		const a = w;
		v = void 0;
		C = void 0;
		w = void 0;
		const o = T;
		T = void 0;
		try {
			await o?.(n ?? "Plugin subagent admission ended before acceptance.");
		} finally {
			await cleanupRejectedAgentRunAdmission({
				runId: e.runId,
				context: e.context,
				incognito: e.sessionEntry?.incognito,
				activeRunAbort: p,
				activeGatewayWorkAdmission: f,
				admittedRunIdentity: h,
				admittedRunContext: g,
				releaseCallerAuthority,
				lease: r,
				completion: i,
				adopted: a,
				admissionReleased: t,
				failure: n
			});
		}
	};
	const E = createAgentPreacceptRefusal(e, cleanupPreaccept);
	const D = createAgentRunAdmissionRevalidator({
		source: e,
		activeRunAbort: p,
		parentResume: i,
		rejectPreaccept: E,
		cleanupPreaccept
	});
	let O;
	let k;
	try {
		const t = await loadPublishedGatewayReplyDispatchRuntime({
			agentId: e.activeSessionAgentId,
			abortSignal: p.controller.signal,
			onRuntimeLease: (e) => {
				y = scopePreparedModelRuntimeLease(e);
				v = y;
			}
		});
		const n = D();
		if (n !== true) return n;
		const r = y;
		if (!t || !r) throw new Error(`published reply runtime missing for ${e.activeSessionAgentId}`);
		O = t;
		const acquireRuntime = (e) => r.run(() => pluginInvocationContext.exit(() => acquireAgentRunPreparedModelRuntime({
			config: O.config,
			agentId: O.agentId,
			agentDir: O.agentDir,
			allowGatewaySubagentBinding: true,
			workspaceDir: e ?? O.workspaceDir,
			runtimePluginSelections: [{
				provider: o.provider,
				modelId: o.model,
				runtime: o.harness
			}]
		}, {
			catalogMode: "static",
			pluginGeneration: O.pluginGeneration,
			abortSignal: p.controller.signal
		})));
		if (canPrepareAgentSessionWorktree(e.resolvedSessionKey, e.sessionEntry)) k = {
			preparedModelRuntimeLease: r,
			acquireWorkspaceModelRuntime: acquireRuntime
		};
		else {
			v = await acquireRuntime(_);
			await r[Symbol.asyncDispose]();
			k = { preparedModelRuntimeLease: v };
			const e = D();
			if (e !== true) return e;
			O = Object.freeze({
				...O,
				pluginGeneration: v.pluginGeneration
			});
		}
	} catch (e) {
		const t = D();
		if (t !== true) return t;
		return E(resolveAgentRunAdmissionError(ErrorCodes.UNAVAILABLE, e));
	}
	E.stage = "subagent-preparation";
	const A = e.delivery.explicitThreadId ?? e.delivery.deliveryPlan.resolvedThreadId;
	let j;
	try {
		j = await prepareGatewaySubagentRun({
			...e,
			lifecycleStorePath: c,
			retainPluginSubagentAdmission: (e) => {
				T = e;
			},
			onParentResumeAdopted: (e) => {
				w = e;
			},
			assertResumeAdmissionCurrent: () => {
				e.assertAdmissionCurrent?.();
				const t = e.assertGatewayWorkAdmissionAllowed();
				p.controller.signal.throwIfAborted();
				assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
				return t;
			}
		});
		C = j.followupCompletion;
		const t = D();
		if (t !== true) return t;
	} catch (e) {
		return E(resolveAgentRunAdmissionError(ErrorCodes.UNAVAILABLE, e));
	}
	const { pluginSubagent: M, reactivateSubagent: N, adoptParentResume: P, followupSuccessor: F } = j;
	E.stage = "input-preparation";
	let I = e.assertAdmissionCurrent;
	let L = false;
	let R;
	const assertInputOwnerCurrent = (n = false) => {
		I?.();
		t?.();
		R?.assertRequesterCurrent?.();
		C?.assertCurrent();
		if (!L) F?.assertCurrent();
		else if (F && !F.owner.ownsExecution(e.runId)) throw new Error("Follow-up input no longer owns its admitted execution.");
		if (i && L && !n) assertParentSubagentResumeSuccessorCurrent(i, e.runId);
		assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
		const r = p.entry;
		if (r !== void 0 && !isRpcSourceRegistered(r) && (!n || hasRpcSourceForController(e.runId, r)) || r === void 0 && getRpcSourceForGateway(e.runId, e.context.resolveGatewayContext) || r !== void 0 && r.adapter.operationalRunInstance !== d || !n && r?.input.retirementRequested) throw new Error("agent input admission no longer owns this run");
	};
	try {
		I?.();
		R = await prepareAgentRunUserTurn({
			...e,
			assertCurrent: () => {
				assertInputOwnerCurrent();
				p.controller.signal.throwIfAborted();
			},
			assertCompletionCurrent: () => assertInputOwnerCurrent(true),
			onTranscriptCommitted: p.entry?.input.onTranscriptCommitted,
			abortSignal: p.controller.signal,
			getAbortStopReason: () => p.entry?.adapter.abortStopReason ?? "rpc",
			admittedSessionId: e.getAdmittedSessionId(),
			freshChildStorePath: e.freshChild ? c : void 0,
			resolvedThreadId: A
		});
		R.assertRequesterCurrent?.();
		if (R.recorder) e.onUserTurnMediaPersisted();
	} catch (e) {
		const t = R ? await releasePreparedAgentRunUserTurnAfterFailure(R, e) : e;
		if (!(t instanceof AgentRunUserTurnCleanupError) && isGatewayAgentAbortRejection(t, p.controller.signal)) {
			const e = D();
			if (e !== true) return e;
		}
		return E(resolveAgentRunAdmissionError(ErrorCodes.UNAVAILABLE, t));
	}
	const z = D(R);
	if (z !== true) return z;
	E.stage = "acceptance";
	const B = {
		runId: e.runId,
		sessionKey: e.resolvedSessionKey,
		agentId: e.activeSessionAgentId,
		status: "accepted",
		acceptedAt: Date.now(),
		...M ? { runtime: o } : {},
		...i ? { taskRunId: i.taskRunId } : {}
	};
	const V = reconcileAgentRunUserTurnCompletion(R, B, cleanupPreaccept, e.io);
	if (V) {
		await V;
		return;
	}
	try {
		const t = e.context.resolveGatewayContext?.();
		const n = t && e.canUseInternalRuntimeHandoff && e.client?.internal?.syntheticClient === true && e.client.internal.operatorRoleActor?.kind === "system" && !e.client.internal.operatorRunAuthority && !e.client.authenticatedUserProfile && !e.client.internal.cronRunContinuation && !e.restoredCronContinuation && e.resolvedSessionKey && !isCronSessionKey(e.resolvedSessionKey) && R.inputProvenance?.kind === "internal_system" && !isCronExecutionInputProvenance(R.inputProvenance) ? {
			context: t,
			agentId: e.activeSessionAgentId,
			sessionKey: e.resolvedSessionKey,
			sessionId: e.getAdmittedSessionId(),
			storePath: c,
			assertCurrent: () => {
				assertInputOwnerCurrent();
				p.controller.signal.throwIfAborted();
			}
		} : void 0;
		b = await retainGatewayOperatorRun({
			...e,
			systemTurn: n,
			entry: p.entry,
			abortSession: e.resolvedSessionKey ? {
				cfg: e.cfg,
				storePath: e.lifecycleStorePath,
				entry: e.sessionEntry,
				canonicalKey: e.resolvedSessionKey,
				agentId: e.activeSessionAgentId
			} : void 0
		});
		const r = D(R);
		if (r !== true) return await r;
		assertInputOwnerCurrent();
		b.authority?.assertCurrent();
	} catch (e) {
		const t = await releasePreparedAgentRunUserTurnAfterFailure(R, e);
		return E(resolveAgentRunAdmissionError(ErrorCodes.INVALID_REQUEST, t));
	}
	try {
		if (j.registerPluginSubagent) {
			await j.registerPluginSubagent();
			const e = D(R);
			if (e !== true) return await e;
			assertInputOwnerCurrent();
			b.authority?.assertCurrent();
		}
	} catch (e) {
		const t = await releasePreparedAgentRunUserTurnAfterFailure(R, e);
		return E(resolveAgentRunAdmissionError(ErrorCodes.UNAVAILABLE, t));
	}
	try {
		const t = consumeGatewaySubagentCompletionToolHandoff(e, R.inputProvenance, o);
		if (C) {
			assertInputOwnerCurrent();
			e.assertGatewayWorkAdmissionAllowed();
			p.controller.signal.throwIfAborted();
			if (F) {
				C.adopt(F);
				L = true;
			}
		}
		if (P) try {
			await P();
			L = true;
			assertInputOwnerCurrent();
			e.assertGatewayWorkAdmissionAllowed();
			p.controller.signal.throwIfAborted();
			b.authority?.assertCurrent();
		} catch (e) {
			const t = await releasePreparedAgentRunUserTurnAfterFailure(R, e);
			return E(resolveAgentRunAdmissionError(ErrorCodes.UNAVAILABLE, t));
		}
		x = prepareGatewayCronCreatorAuthorityAdmission({
			...e,
			sessionId: e.getAdmittedSessionId(),
			spawnedBy: e.sessionEntry?.spawnedBy,
			isCurrent: e.hasCurrentClientAuthority,
			inputProvenance: R.inputProvenance,
			hasRestoredCronContinuation: e.restoredCronContinuation !== void 0
		}, p.controller.signal);
		C?.markAccepted(e.runId);
		e.markAgentRunAccepted(true);
		w = void 0;
		setGatewayDedupeEntries({
			dedupe: e.context.dedupe,
			keys: e.agentDedupeKeys,
			entry: {
				ts: Date.now(),
				ok: true,
				payload: {
					...B,
					controlUiVisible: r,
					dedupeKeys: e.agentDedupeKeys,
					ownerConnId: e.ownerConnId,
					ownerDeviceId: e.ownerDeviceId
				}
			}
		});
		I = void 0;
		u = false;
		e.io.emitAcceptance([
			true,
			B,
			void 0
		], { runId: e.runId });
		b.armCancellation();
		if (c) recordAgentRunUserTurnParticipant({
			...e,
			inputProvenance: R.inputProvenance
		}, R, c);
		T = void 0;
		return {
			activeGatewayWorkAdmission: f,
			activeRunAbort: p,
			...x ? { cronCreatorAuthority: x } : {},
			releaseCallerAuthority,
			...b.authority ? { operatorAuthority: b.authority } : {},
			operationalRunInstance: d,
			timeoutSeconds: l,
			...s,
			imageUnderstandingModel: e.needsImageUnderstanding ? o : void 0,
			trustedInternalHandoff: t,
			restoredCronContinuationLifecycleRevision: e.restoredCronContinuation?.lifecycleRevision,
			resolvedThreadId: A,
			reactivateSubagent: N,
			followupCompletion: C,
			...k,
			replyDispatchRuntime: O,
			unpersistedOffloadedRefs: R.recorder ? [] : e.offloadedRefs,
			userTurn: R,
			workspaceOverride: _
		};
	} catch (e) {
		return releaseFailedAgentRunAdmission(R, e, cleanupPreaccept);
	}
}
//#endregion
//#region src/gateway/server-methods/agent-run-model-selection.ts
function createAgentRunModelSelectionHandler(e) {
	return async ({ provider: t, model: n }) => {
		if (e.trustedInternalHandoff) {
			e.trustedInternalHandoff.provider = t.trim().toLowerCase();
			e.trustedInternalHandoff.model = n.trim();
		}
		updateChatRunProvider({
			runId: e.runId,
			resolveGatewayContext: e.resolveGatewayContext,
			providerId: t,
			authProviderId: resolveProviderIdForAuth(t, { config: e.cfgForAgent ?? e.cfg })
		});
		if (!e.restoredCronContinuationLifecycleRevision || !e.resolvedSessionKey) return;
		if (!e.lifecycleStorePath) throw new Error("cron continuation physical store is unavailable");
		if (!await applySessionEntryExactReplacements({
			activeSessionKey: e.resolvedSessionKey,
			requireWriteSuccess: true,
			sessionKeys: [e.resolvedSessionKey],
			skipMaintenance: false,
			storePath: e.lifecycleStorePath,
			update: (r) => {
				const i = r.find((t) => t.sessionKey === e.resolvedSessionKey)?.entry;
				const a = i?.cronRunContinuation;
				if (!i || a?.phase !== "continuing" || a.ownerRunId !== e.runId || a.lifecycleRevision !== e.restoredCronContinuationLifecycleRevision) return { result: false };
				const o = resolveCliRuntimeExecutionProvider({
					provider: t,
					cfg: e.cfgForAgent ?? e.cfg,
					agentId: e.activeSessionAgentId,
					modelId: n
				}) ?? t;
				const s = { ...a };
				if (isCliProvider(o, e.cfgForAgent ?? e.cfg)) s.cliExecutionProvider = o;
				else delete s.cliExecutionProvider;
				return {
					replacements: [{
						sessionKey: e.resolvedSessionKey,
						entry: {
							...i,
							cronRunContinuation: s,
							modelProvider: t,
							model: n,
							updatedAt: Date.now()
						}
					}],
					result: true
				};
			}
		})) throw new Error("cron run continuation changed before model execution");
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-dispatch-execution-identity.ts
const { carry: withAgentRunDispatchExecutionIdentity, read: readAgentRunDispatchExecutionIdentity } = createPrivateContextCarrier();
//#endregion
//#region src/gateway/agent-turn/agent-run-execution-lineage.ts
function prepareAgentRunExecutionIdentityFacts(e, t, n) {
	const r = e.client?.internal?.agentRuntimeIdentity;
	const i = r && e.context.validateAgentRuntimeApprovalAuthority?.(r) === true ? r : void 0;
	const a = resolveExecutionIdentitySpawnFacts(i, n);
	const o = getGatewayLocalUserIngress(e.client);
	const s = e.client?.internal?.agentToolCaller?.agentId ?? i?.agentId;
	if (s) attachAgentCommandAdmissionFacts(t, {
		ingress: {
			kind: "api",
			boundary: "gateway.agent-tool",
			state: "present"
		},
		invoker: {
			state: "present",
			kind: "agent",
			rawPrincipalRef: s
		},
		...n !== void 0 ? { representedSubject: {
			state: "present",
			kind: "person",
			rawPrincipalRef: n
		} } : {}
	});
	else if (o) attachAgentCommandAdmissionFacts(t, o.facts);
	return a;
}
/** Consume authenticated spawn provenance once, at the child admission owner. */
function resolveExecutionIdentitySpawnFacts(e, t) {
	const n = readAgentRuntimeExecutionLineage(e?.sessionSpawnContext);
	if (!e || !n || !consumeAgentRuntimeExecutionLineage(e)) return;
	const r = e.executionIdentity;
	return {
		ingress: {
			kind: n.externalNativeActions === "unsupported" ? "acp" : "subagent",
			boundary: `sessions_spawn.${n.externalNativeActions === "unsupported" ? "acp" : "subagent"}`,
			state: "present"
		},
		invoker: {
			state: "present",
			kind: "agent",
			rawPrincipalRef: e.agentId
		},
		...t ? { representedSubject: {
			state: "present",
			kind: "person",
			rawPrincipalRef: t
		} } : {},
		applicableGrants: n.applicableGrantRefs.map((e) => ({
			rawGrantRef: e,
			state: "present"
		})),
		assurance: [{
			kind: "spawn-lineage",
			rawEvidenceRef: n.requesterRef,
			strength: "boundary-verified"
		}, ...n.runtimeAssuranceRefs.map((e) => ({
			kind: "runtime-binding",
			rawEvidenceRef: e,
			strength: "boundary-verified"
		}))],
		spawnAdmission: executionIdentitySpawnAdmission({
			operation: "serialize",
			value: {
				...r?.contextId ? { parentContextId: r.contextId } : {},
				...r?.executionId ? { parentExecutionId: r.executionId } : {},
				...r?.runId ? { parentRunId: r.runId } : {},
				parentAgentId: e.agentId,
				relation: n.relation,
				rawRequesterRef: n.requesterRef,
				rawControllerRef: n.controllerRef,
				depth: n.depth,
				localPolicyRefs: n.localPolicyRefs,
				targetPolicyRefs: n.targetPolicyRefs
			},
			extra: [
				...!r?.contextId ? ["lineage.parent-context"] : [],
				...!r?.executionId ? ["lineage.parent-execution"] : [],
				...!r?.runId ? ["lineage.parent-run"] : [],
				...n.externalNativeActions === "unsupported" ? ["acp.native-action-callback"] : []
			]
		})
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-dispatch.ts
function dispatchAgentRunFromGateway(e) {
	const t = createAgentRunDiagnostics(e.ingressOpts.sessionKey, e.isIncognito, e.context.logGateway);
	const n = e.assertSettlementCurrent;
	const r = e.admittedRunEntry;
	const captureJobSession = () => captureAgentJobSession(r ? {
		...getRpcSourceIdentity(r),
		lifecycleGeneration: getRpcSourceLifecycleGeneration(r)
	} : e.ingressOpts);
	let i = false;
	const projectInputOutcome = (t) => projectWithdrawnAgentInput(t, readWithdrawnUserTurnInputId(e.ingressOpts.userTurnTranscriptRecorder), r?.adapter.abortStopReason);
	let a;
	const publishReplay = (n) => {
		if (!i) {
			a = n;
			return;
		}
		setGatewayDedupeEntries({
			dedupe: e.context.dedupe,
			keys: e.dedupeKeys,
			session: captureJobSession(),
			entry: t.forReplay({
				...n,
				payload: projectInputOutcome(n.payload)
			})
		});
	};
	const o = r?.adapter.operationalRunInstance;
	const s = r && getRpcSourceLifecycleGeneration(r);
	const c = r && getRpcSourceIdentity(r).sessionKey;
	const currentRunRegistration = () => getRpcSourceForGateway(e.runId, e.context.resolveGatewayContext, r?.input.target);
	const ownsRunRegistration = () => {
		const t = currentRunRegistration();
		return !t || t === r && t.input.abortSignal === e.abortController.signal && t.adapter.operationalRunInstance === o && getRpcSourceLifecycleGeneration(t) === s && getRpcSourceIdentity(t).sessionKey === c;
	};
	const assertCurrent = () => {
		e.abortController.signal.throwIfAborted();
		e.assertCurrent?.();
		e.abortController.signal.throwIfAborted();
	};
	const l = e.followupCompletion;
	const settleFollowup = async (t) => {
		if (!l?.ownsExecution(e.runId)) return;
		try {
			await l.settle(e.runId, t, () => {
				n?.();
				const e = currentRunRegistration();
				if (!ownsRunRegistration() && (e === r || e && getRpcSourceIdentity(e).sessionKey === c)) throw new Error("Followup physical execution lost its Gateway registration.");
			});
		} catch (e) {
			l.close(e);
			throw e;
		}
	};
	const settle = async (n) => {
		try {
			return await e.onSettled?.(n) ?? true;
		} catch (n) {
			t.warning(`failed to settle agent continuation ${e.runId}`)(n);
			return false;
		}
	};
	let u = false;
	let d;
	const cleanupRunOwner = () => {
		if (u) return d;
		u = true;
		if ((!hasRpcSource(e.runId) || r !== void 0 && getRpcSource(e.runId) === r) && ownsRunRegistration()) clearAgentRunContext(e.runId, e.ingressOpts.lifecycleGeneration);
		return d = Promise.resolve(e.cleanupAbortController()).then(() => {
			i = true;
			if (a) {
				const e = a;
				a = void 0;
				publishReplay(e);
			}
		});
	};
	const f = e.cronCreatorAuthority ? e.cronCreatorAuthority.boundRunScope ?? createCronCreatorAuthorityCapability(e.cronCreatorAuthority.runId, e.cronCreatorAuthority.callerOrigin, e.cronCreatorAuthority.managementEntitlement, e.cronCreatorAuthority.isCurrent, void 0, e.cronCreatorAuthority.requesterOwner, e.cronCreatorAuthority.callerScopedCreation) : void 0;
	if (f && !e.cronCreatorAuthority?.boundRunScope) e.cronCreatorAuthority?.bindRunScope?.(f);
	/** Binds canonical transcript settlement to the exact registered API producer. */
	const p = r;
	const m = e.abortController;
	const h = e.ingressOpts;
	const g = p?.adapter.operationalRunInstance;
	const _ = p && getRpcSourceLifecycleGeneration(p);
	const v = p && getRpcSourceIdentity(p).sessionKey;
	const y = createDeferredCore();
	let b;
	if (p && h.abortSignal === m.signal) p.adapter.resolveTerminalProducer = () => {
		const { sessionId: e, sessionKey: t } = getRpcSourceIdentity(p);
		const isCurrent = () => {
			const n = p.adapter.agentRunDelegatedAuthority;
			return !u && !m.signal.aborted && h.abortSignal === m.signal && isRpcSourceRegistered(p) && p.input.abortSignal === m.signal && p.adapter.operationalRunInstance === g && getRpcSourceLifecycleGeneration(p) === _ && getRpcSourceIdentity(p).sessionId === e && getRpcSourceIdentity(p).sessionKey === t && t === v && !p.input.retirementRequested && (!_ || isAgentEventLifecycleGenerationCurrent(_)) && (getRpcSourceStartedAt(p) === void 0 || n !== void 0) && (!n || n.operationalRunInstance === g && validateAgentRunDelegatedAuthority(n));
		};
		if (!isCurrent()) return;
		return {
			sessionId: e,
			sessionKey: t,
			handoff: (e) => {
				if (!isCurrent()) return false;
				const t = e(y.promise);
				b = b ? Promise.all([b, t]).then(() => void 0) : t;
				return true;
			}
		};
	};
	const complete = async (e) => {
		y.resolve(e);
		let t;
		do {
			t = b;
			await t;
		} while (t !== b);
	};
	const x = {
		complete,
		async settle(e) {
			let t;
			try {
				return await e;
			} catch (e) {
				t = e;
				throw e;
			} finally {
				await complete(t);
			}
		}
	};
	const activateAgent = (n) => {
		assertCurrent();
		const i = withAgentCommandExecutionIdentitySpawnFacts({
			...e.ingressOpts,
			...n ? { prepareAssistantTranscriptMessage: n.prepareAssistantTranscriptMessage } : {},
			beforeTerminalDelivery: async (e, t) => {
				try {
					await n?.finalize(e);
				} finally {
					await x.complete(t);
				}
			},
			isTerminalOutcomeObserved: () => r?.adapter.terminalOutcomeObserved === true
		}, readAgentRunDispatchExecutionIdentity(e));
		const invoke = () => runWithCanonicalSkillWorkspace(e.canonicalSkillWorkspaceDir, () => agentCommandFromGatewayIngress(f ? {
			...i,
			cronCreatorAuthorityCapability: f
		} : i, t.runtime, e.context.deps, e.commandRuntimeContext));
		if (l) {
			if (!r || !ownsRunRegistration() || !isRpcSourceRegistered(r) || r.input.retirementRequested) throw new Error("Followup no longer owns its Gateway run registration.");
			l.assertExecutionCurrent(e.runId);
		}
		return n ? n.run(invoke) : invoke();
	};
	const runAgent = () => {
		try {
			assertCurrent();
			return e.loadMedia ? e.loadMedia().then(activateAgent) : activateAgent();
		} catch (e) {
			const t = toErrorObject(e, formatErrorMessage(e));
			if (!(e instanceof Error)) t.cause = e;
			return Promise.reject(t);
		}
	};
	const runOwnedAgent = () => withExecRequestTurn({
		identity: {
			runId: e.runId,
			sessionKey: r && getRpcSourceIdentity(r).sessionKey,
			sessionId: r && getRpcSourceIdentity(r).sessionId,
			agentId: r && getRpcSourceIdentity(r).agentId,
			ownerConnId: r?.adapter.requester?.connectionId,
			ownerDeviceId: r?.adapter.requester?.deviceId,
			initiatingPersonalOperator: r?.adapter.initiatingPersonalOperator,
			controlUiVisible: r?.adapter.controlUiVisible,
			turnKind: r?.adapter.turnKind
		},
		abortSignal: e.abortController.signal
	}, runAgent);
	const S = f ? runWithCronCreatorAuthorityCapability(f, runOwnedAgent, e.abortController.signal) : runOwnedAgent();
	const C = (async () => {
		let e;
		try {
			return await S;
		} catch (t) {
			e = t;
			throw t;
		} finally {
			await x.complete(e);
		}
	})();
	let w = false;
	const T = C.then(async (t) => {
		const n = readAgentRunTerminalOutcome(t);
		const r = resolveResolvedAgentTimeoutStopReason(t?.meta, e.abortController.signal);
		const i = t?.meta?.aborted === true || r !== void 0;
		const a = r ? r : i ? t?.meta?.stopReason ?? "rpc" : void 0;
		const o = normalizeAgentRunTimeoutPhase(t?.meta?.timeoutPhase);
		const s = readAgentRunTerminalError(t) ?? t?.meta?.error?.message;
		let c = buildAgentRunTerminalOutcome({
			status: i || t?.meta?.stopReason === "timeout" || o ? "timeout" : n === "failed" || t?.meta?.error || t?.meta?.stopReason === "error" ? "error" : "ok",
			error: s ? formatErrorMessage(s) : void 0,
			stopReason: a ?? t?.meta?.stopReason,
			livenessState: t?.meta?.livenessState,
			timeoutPhase: o,
			providerStarted: t?.meta?.providerStarted
		});
		let l;
		try {
			l = await completeUserTurnProcessing(e.ingressOpts.userTurnTranscriptRecorder, c);
			c = l ?? c;
		} catch (e) {
			w = true;
			throw e;
		}
		const u = RESOLVED_GATEWAY_STATUS_BY_TERMINAL_CLASSIFICATION[classifyAgentRunTerminalOutcome(c)];
		const d = normalizeAgentRunTerminalReplySnapshot(t?.meta?.terminalReply);
		const f = normalizeAgentRunTerminalReceipt(t?.meta?.agentMeta?.terminalReceipt);
		await settleFollowup({
			...c,
			endedAt: c.endedAt ?? Date.now(),
			yielded: t?.meta?.yielded === true,
			terminalReply: d,
			...d?.disposition === "visible" ? { replyText: t?.meta?.finalAssistantVisibleText ?? d.text } : {},
			...f?.runId === e.runId && f.sourceReplyDelivered ? { sourceReplyDelivered: true } : {}
		});
		const p = l?.reason === "completed" && u === "ok";
		const m = {
			runId: e.runId,
			status: u,
			summary: u === "timeout" ? "aborted" : u === "error" ? "failed" : "completed",
			...u === "error" && isHostMissingReplyNoticeText(c.error) ? { error: c.error } : {},
			...u !== "ok" && c.stopReason ? { stopReason: c.stopReason } : {},
			...u === "timeout" && c.timeoutPhase ? { timeoutPhase: c.timeoutPhase } : {},
			...u === "timeout" && c.providerStarted !== void 0 ? { providerStarted: c.providerStarted } : {},
			result: t,
			...p ? { inputProcessingCompleted: true } : {}
		};
		const persistTerminalDedupe = () => {
			publishReplay({
				ts: Date.now(),
				ok: true,
				payload: m
			});
		};
		const h = await settle({
			terminalOutcome: c,
			onRecovered: persistTerminalDedupe
		});
		if (!h) {
			const t = "failed to persist cron continuation settlement";
			const n = errorShape(ErrorCodes.UNAVAILABLE, t);
			const r = {
				runId: e.runId,
				status: "error",
				summary: t
			};
			publishReplay({
				ts: Date.now(),
				ok: false,
				payload: r,
				error: n
			});
			await cleanupRunOwner();
			e.io.emitFinal([
				false,
				r,
				n
			], {
				runId: e.runId,
				error: t
			});
			return {
				terminalOutcome: c,
				settled: h
			};
		}
		persistTerminalDedupe();
		await cleanupRunOwner();
		e.io.emitFinal([
			true,
			projectInputOutcome(m),
			void 0
		], { runId: e.runId });
		return {
			terminalOutcome: c,
			settled: h
		};
	}).catch(async (n) => {
		const r = findReplaySafeRunAbort(n);
		const i = r?.cause ?? n;
		const a = e.admittedRunEntry?.input.claim?.operation;
		const o = a?.result?.kind === "aborted" && isGatewayAgentAbortRejection(a.abortSignal.reason, a.abortSignal) || isGatewayAgentAbortRejection(i, e.abortController.signal);
		const s = errorShapeFromError(ErrorCodes.UNAVAILABLE, n);
		const c = s.message;
		const l = o ? resolveGatewayAgentAbortStopReason(e.abortController.signal, i) : isAbortError(n) ? "aborted" : void 0;
		let u = buildAgentRunTerminalOutcome({
			status: o || isTimeoutError(n) ? "timeout" : "error",
			error: c,
			stopReason: l,
			timeoutPhase: l === "restart" ? "gateway_draining" : void 0
		});
		if (!w) try {
			u = await completeUserTurnProcessing(e.ingressOpts.userTurnTranscriptRecorder, u) ?? u;
		} catch (e) {
			t.warning("input completion persistence failed")(e);
		}
		const d = projectRejectedGatewayStatus(u);
		await settleFollowup({
			...u,
			error: c,
			endedAt: u.endedAt ?? Date.now()
		});
		Object.defineProperty(s, "cause", { value: n });
		const f = {
			runId: e.runId,
			status: d,
			summary: o ? "aborted" : c,
			...o ? {
				stopReason: l,
				...r ? { replaySafe: true } : {},
				...u.timeoutPhase ? { timeoutPhase: u.timeoutPhase } : {}
			} : {}
		};
		const persistTerminalDedupe = (e) => {
			publishReplay({
				ts: Date.now(),
				ok: o && e,
				payload: f,
				...o ? {} : { error: s }
			});
		};
		const p = await settle({
			terminalOutcome: u,
			onRecovered: () => persistTerminalDedupe(true)
		});
		persistTerminalDedupe(p);
		await cleanupRunOwner();
		const m = o && p ? void 0 : s;
		e.io.emitFinal([
			o && p,
			projectInputOutcome(f),
			m
		], {
			runId: e.runId,
			...t.errorMeta(m?.message, !o)
		});
		return {
			terminalOutcome: u,
			settled: p
		};
	});
	return (async () => {
		try {
			return await T;
		} finally {
			try {
				await cleanupRunOwner();
			} finally {
				l?.finishExecution(e.runId);
			}
		}
	})();
}
//#endregion
//#region src/gateway/agent-turn/agent-run-media.ts
/** Prepare input and assistant media while dispatch retains the run's authority. */
function dispatchAgentRunWithMedia(e, t) {
	const { ingressOpts: n, admittedRunEntry: r, abortController: i } = e;
	const a = n.sessionKey;
	if (!a && !t.prepared.imageUnderstandingModel) return dispatchAgentRunFromGateway(e);
	const o = t.client ? resolveChatSendCallerContext(t.client) : void 0;
	const s = n.runContext;
	e.loadMedia = async () => {
		const c = e.commandRuntimeContext?.config ?? t.cfg;
		if (t.prepared.imageUnderstandingModel) {
			const { prepareAgentImageUnderstanding: r } = await import("./agent-image-understanding-DfO8E3B7.mjs");
			const o = t.prepared.replyDispatchRuntime;
			e.assertCurrent?.();
			const l = await r({
				message: n.message,
				media: n.media ?? [],
				cfg: c,
				agentId: t.activeSessionAgentId,
				agentDir: o.agentDir,
				workspaceDir: n.workspaceDir ?? o.workspaceDir,
				sessionKey: a,
				channel: s?.messageChannel ?? n.messageChannel,
				chatType: t.sessionEntry?.chatType,
				activeModel: t.prepared.imageUnderstandingModel,
				execution: {
					signal: i.signal,
					assertCurrent: () => e.assertCurrent?.()
				}
			});
			e.assertCurrent?.();
			Object.assign(n, l, { imageOrder: [] });
		}
		if (!a) return;
		const { createAssistantCommentaryMediaCustody: l } = await import("./chat-send-commentary-media-DzK7Q55H.mjs");
		const { createOutboundPayloadPlan: u } = await import("./payloads-CnJuG_O9.mjs");
		const d = {
			options: n,
			incognito: e.isIncognito === true,
			session: {
				agentId: t.activeSessionAgentId,
				cfg: c,
				storePath: t.prepared.lifecycleStorePath,
				sessionKey: a,
				sessionLoadOptions: { agentId: t.activeSessionAgentId }
			},
			requesterContext: {
				...o,
				SenderId: s?.senderId ?? o?.SenderId,
				GroupChannel: s?.groupChannel ?? n.groupChannel ?? o?.GroupChannel,
				GroupSpace: s?.groupSpace ?? n.groupSpace ?? o?.GroupSpace,
				Provider: s?.messageChannel ?? n.messageChannel ?? o?.Provider,
				Surface: s?.messageChannel ?? n.messageChannel ?? o?.Surface
			},
			accountId: n.accountId,
			getRunId: () => e.runId,
			isCurrent: () => {
				try {
					e.assertCurrent?.();
					return r !== void 0 && isRpcSourceRegistered(r) && r.input.abortSignal === i.signal && !r.input.retirementRequested && !i.signal.aborted;
				} catch {
					return false;
				}
			},
			abortSignal: i.signal,
			logGateway: e.context.logGateway,
			prepareAssistantTranscriptMessage: n.prepareAssistantTranscriptMessage
		};
		const f = l(d);
		return {
			run: f.run,
			prepareAssistantTranscriptMessage: f.prepareAssistantTranscriptMessage,
			finalize: async (e) => {
				if (!e || d.incognito || n.privateCompletion || n.sessionEffects === "internal" || n.deliver === true || !isInternalMessageChannel(n.channel ?? n.messageChannel)) return;
				const t = u(e.payloads).filter(({ payload: e }) => e.sensitiveMedia !== true);
				if (!t.some(({ parts: e }) => e.mediaUrls.length > 0)) return;
				const { finalizeAgentRunMedia: r } = await import("./agent-run-final-media-Bw44axj4.mjs");
				await r(d, e, t);
			}
		};
	};
	return dispatchAgentRunFromGateway(e);
}
//#endregion
//#region src/gateway/agent-turn/agent-run-undispatched-outcome.ts
/** Settle admitted input before queuing the undispatched result for post-cleanup publication. */
function createAgentRunUndispatchedOutcome({ execution: e, diagnostics: t, captureJobSession: n, settleUnstartedFollowup: r, deferFinal: i }) {
	const { prepared: a } = e;
	let publishAfterCleanup;
	const finishFailure = async (o, s = true) => {
		const c = errorShapeFromError(ErrorCodes.UNAVAILABLE, o);
		const l = c.message;
		const u = buildAgentRunTerminalOutcome({
			status: "error",
			error: l
		});
		if (s) try {
			await completeUserTurnProcessing(a.userTurn.recorder, u);
		} catch (e) {
			t.warning("input completion persistence failed")(e);
		}
		await r(u);
		const d = {
			runId: e.runId,
			status: "error",
			summary: l
		};
		publishAfterCleanup = () => {
			setGatewayDedupeEntries({
				dedupe: e.context.dedupe,
				keys: e.agentDedupeKeys,
				session: n(),
				entry: t.forReplay({
					ts: Date.now(),
					ok: false,
					payload: d,
					error: c
				})
			});
			i([
				false,
				d,
				c
			], {
				runId: e.runId,
				...t.errorMeta(l)
			});
		};
	};
	const finishUndispatchedAbort = async () => {
		const o = a.activeRunAbort.entry?.adapter.abortStopReason?.trim() || "rpc";
		const s = buildAgentRunTerminalOutcome({
			status: "timeout",
			stopReason: o,
			timeoutPhase: "queue",
			providerStarted: false
		});
		try {
			await completeUserTurnProcessing(a.userTurn.recorder, s);
		} catch (e) {
			await finishFailure(e, false);
			return;
		}
		await r(s);
		publishAfterCleanup = () => {
			const r = projectWithdrawnAgentInput(buildAbortedAgentPayload(e.runId, o, { agentId: e.activeSessionAgentId }), readWithdrawnUserTurnInputId(a.userTurn.recorder));
			setGatewayDedupeEntries({
				dedupe: e.context.dedupe,
				keys: e.agentDedupeKeys,
				session: n(),
				entry: t.forReplay({
					ts: Date.now(),
					ok: true,
					payload: r
				})
			});
			i([
				true,
				r,
				void 0
			], { runId: e.runId });
		};
	};
	return {
		finishFailure,
		finishUndispatchedAbort,
		publishAfterCleanup: () => publishAfterCleanup?.()
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-run-execution-phase.ts
async function startAgentRunExecution(e) {
	const t = e.prepared.activeRunAbort.entry?.input;
	const n = createDeferredCore();
	if (t) trackSessionControllerSourceWork(t, n.promise);
	const run = () => runWithAgentWorkspaceReadiness(void 0, () => executeAgentRun(e, n.resolve));
	await runWithSessionControllerCleanup(() => t ? withSessionControllerSource(t, run) : run());
	n.resolve();
}
async function executeAgentRun(e, t) {
	const { prepared: n } = e;
	let deliverFinal;
	const deferFinal = (...t) => {
		deliverFinal = () => e.io.emitFinal(...t);
	};
	const r = createAgentRunDiagnostics(e.resolvedSessionKey, e.sessionEntry?.incognito, e.context.logGateway);
	const captureJobSession = () => captureAgentJobSession(n.activeRunAbort.entry ? {
		...getRpcSourceIdentity(n.activeRunAbort.entry),
		lifecycleGeneration: getRpcSourceLifecycleGeneration(n.activeRunAbort.entry)
	} : {
		sessionKey: e.resolvedSessionKey,
		sessionId: e.resolvedSessionId,
		agentId: e.activeSessionAgentId,
		lifecycleGeneration: e.lifecycleGeneration
	});
	let i = n.unpersistedOffloadedRefs;
	const a = retainGatewayRootWorkAdmissionContinuation() ?? void 0;
	let o = false;
	let s = false;
	let c = false;
	try {
		try {
			var l = _usingCtx();
			const t = l.a({
				stack: new AsyncDisposableStack(),
				async [Symbol.asyncDispose]() {
					try {
						await this.stack.disposeAsync();
						c = true;
					} catch (e) {
						c = e instanceof PluginRuntimeCloseCompletedError;
						throw e;
					}
				}
			});
			let a = t.stack.use(n.preparedModelRuntimeLease);
			let u = n.replyDispatchRuntime;
			let d = n.workspaceOverride;
			let f = true;
			const { entry: p, controller: m } = n.activeRunAbort;
			const h = n.operationalRunInstance;
			const g = p && getRpcSourceIdentity(p).sessionKey;
			const _ = p ? {
				controller: m,
				operationalRunInstance: h,
				lifecycleGeneration: e.lifecycleGeneration,
				sessionKey: getRpcSourceIdentity(p).sessionKey
			} : void 0;
			const assertSettlementCurrent = () => {
				e.assertGatewayLifetimeCurrent?.();
				assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
				if (!f || n.activeRunAbort.registered && n.activeGatewayWorkAdmission?.isActive() === false) throw new Error("Agent settlement no longer owns this Gateway run");
			};
			const assertDispatchCurrent = () => {
				e.assertGatewayLifetimeCurrent?.();
				e.executionSource?.();
				n.operatorAuthority?.assertCurrent();
				n.userTurn.assertRequesterCurrent?.();
				m.signal.throwIfAborted();
				assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
				if (!f || n.activeRunAbort.registered && (n.activeGatewayWorkAdmission?.isActive() === false || !p || !isRpcSourceRegistered(p) || p.input.abortSignal !== m.signal || p.adapter.operationalRunInstance !== h || getRpcSourceLifecycleGeneration(p) !== e.lifecycleGeneration || getRpcSourceIdentity(p).sessionKey !== g || p.input.retirementRequested)) throw new Error("agent dispatch no longer owns this Gateway run");
			};
			let v;
			const cleanupAdmittedRun = async () => {
				const t = i;
				i = [];
				try {
					await releasePreparedAgentRunUserTurn(n.userTurn);
				} catch (e) {
					r.warning("failed to settle pending agent input")(e);
				}
				n.activeRunAbort.cleanup();
				n.activeGatewayWorkAdmission?.release();
				f = false;
				v ??= discardPreparedInboundMedia(t, e.context.logGateway);
				if (n.userTurn.recorder && e.resolvedSessionKey) emitSessionsChanged(e.context, {
					sessionKey: e.resolvedSessionKey,
					agentId: e.activeSessionAgentId,
					reason: "agent.input.settled"
				}, {
					accessChanged: false,
					rowScope: "runtime"
				});
			};
			const dispatchAdmittedAgentRun = (t) => withCurrentUserTurnInput(n.userTurn.recorder, () => withSessionTurn({
				controllerInput: p?.input,
				sessionKey: e.resolvedSessionKey,
				sessionId: e.resolvedSessionId,
				agentId: e.activeSessionAgentId,
				storePath: e.resolvedSessionKey ? n.lifecycleStorePath : void 0,
				abortSignal: m.signal
			}, async () => withPreparedModelRuntimePluginGenerationScope(u.pluginGeneration, () => {
				o = true;
				return dispatchAgentRunWithMedia(t, e);
			}, () => f ? a.snapshot : void 0)));
			const execute = async () => {
				await yieldAfterAgentAcceptedAck();
				const settleUnstartedFollowup = (t) => !o ? settleUnstartedGatewayFollowup({
					completion: n.followupCompletion,
					runId: e.runId,
					admittedRunEntry: p,
					admittedRunIdentity: _,
					context: e.context,
					isIncognito: r.incognito,
					outcome: t
				}) : void 0;
				const { finishFailure: i, finishUndispatchedAbort: s, publishAfterCleanup: c } = createAgentRunUndispatchedOutcome({
					execution: e,
					diagnostics: r,
					captureJobSession,
					settleUnstartedFollowup,
					deferFinal
				});
				try {
					if (n.activeRunAbort.controller.signal.aborted) {
						await s();
						return;
					}
					if (n.acquireWorkspaceModelRuntime) {
						let r = e.sessionEntry;
						const i = n.lifecycleStorePath;
						if (!r || !e.resolvedSessionKey || !i || r.sessionId !== (p ? getRpcSourceIdentity(p).sessionId : void 0)) throw new Error("Session changed before preparing its worktree.");
						e.sessionEntry = r = { ...r };
						await prepareSessionWorkspaceForRun({
							entry: r,
							cfg: e.cfgForAgent ?? e.cfg,
							agentId: e.activeSessionAgentId,
							runId: e.runId,
							sessionKey: e.resolvedSessionKey,
							storePath: i,
							context: e.context,
							signal: m.signal,
							assertCurrent: assertDispatchCurrent,
							runSetupScript: e.client?.connect.scopes?.includes(ADMIN_SCOPE) === true
						});
						assertDispatchCurrent();
						d = resolveIngressWorkspaceOverrideForSessionRun({
							spawnedBy: r.spawnedBy,
							workspaceDir: r.spawnedWorkspaceDir,
							cwd: r.spawnedCwd
						});
						a = t.stack.use(await n.acquireWorkspaceModelRuntime(d));
						assertDispatchCurrent();
						u = Object.freeze({
							...u,
							pluginGeneration: a.pluginGeneration
						});
					}
					let { message: i, execApprovalContinuationPromptRange: o } = n.userTurn;
					const c = o;
					if (n.reactivateSubagent && e.resolvedSessionKey) await reactivateCompletedSubagentSession({
						sessionKey: e.resolvedSessionKey,
						runId: e.runId,
						task: i,
						gatewayContextResolver: e.context.resolveGatewayContext,
						assertCurrent: assertDispatchCurrent,
						session: e
					});
					if (!e.suppressVisibleSessionEffects && e.requestedSessionKey && e.resolvedSessionKey && e.isNewSession) emitSessionsChanged(e.context, {
						sessionKey: e.resolvedSessionKey,
						agentId: e.activeSessionAgentId,
						reason: "create"
					});
					if (!e.suppressVisibleSessionEffects && e.resolvedSessionKey) emitSessionsChanged(e.context, {
						sessionKey: e.resolvedSessionKey,
						agentId: e.activeSessionAgentId,
						reason: "send"
					}, { accessChanged: false });
					if (!e.isRawModelRun) ({message: i, execApprovalContinuationPromptRange: o} = annotateAgentRunUserTurnPrompt({
						message: i,
						inputProvenance: e.inputProvenance,
						execApprovalContinuationPromptRange: o
					}));
					const l = e.resolvedSessionKey ? e.activeSessionAgentId : e.agentId;
					const { runtimePluginToolGrant: f, pluginSubagentToolsAllow: h } = resolveGatewayPluginSubagentToolPolicy(e.client);
					const g = {
						messageChannel: e.delivery.originMessageChannel,
						accountId: e.delivery.resolvedAccountId,
						groupId: e.groupId,
						groupChannel: e.groupChannel,
						groupSpace: e.groupSpace,
						currentThreadTs: n.resolvedThreadId != null ? String(n.resolvedThreadId) : void 0
					};
					setChannelSourceTurnId(g, resolveReplySourceTurnId({
						admissionRunId: e.runId,
						ingressProvider: g.messageChannel
					}));
					const _ = prepareAgentRunExecutionIdentityFacts(e, g, n.operatorAuthority?.profileId);
					e.assertGatewayLifetimeCurrent?.();
					const v = resolveChatSendCallerContext(e.client);
					const y = [...v.GatewayClientCaps];
					const b = captureGatewayUiCommandTarget(e.client);
					const x = isOperatorUiClient(e.client?.connect.client) && e.client?.connect.scopes?.includes("operator.admin") === true && hasGatewayClientCap(y, GATEWAY_CLIENT_CAPS.TASK_SUGGESTIONS);
					const S = e.context.resolveGatewayContext?.();
					const C = S && e.resolvedSessionKey ? await prepareGatewaySkillAuthoring({
						client: e.client,
						context: S,
						sessionMutationCommitGuard: e.assertGatewayLifetimeCurrent
					}, e.resolvedSessionKey, !e.inputProvenance && !e.restoredCronContinuation && !e.isOneShotModelRun && !e.request.internalEvents && !e.request.internalRuntimeHandoffId && !e.request.execApprovalFollowupExpectedSessionId && e.sessionEffects !== "internal" && !e.request.suppressPromptPersistence && !e.request.swarmCollector && e.request.lane !== "subagent") : void 0;
					finalizePreparedAgentRunUserTurn(n.userTurn);
					await dispatchAdmittedAgentRun(withAgentRunDispatchExecutionIdentity({
						assertCurrent: assertDispatchCurrent,
						assertSettlementCurrent,
						admittedRunEntry: p,
						commandRuntimeContext: {
							config: u.config,
							pluginGeneration: u.pluginGeneration,
							freshChild: e.freshChild
						},
						cronCreatorAuthority: n.cronCreatorAuthority,
						ingressOpts: {
							assertSourceCurrent: n.userTurn.assertRequesterCurrent ? composeSessionSourceAssertion([e.executionSource, n.userTurn.assertRequesterCurrent]) : e.executionSource,
							skillLibraryAuthoring: C,
							message: i,
							images: e.images,
							imageOrder: e.imageOrder,
							media: e.media,
							agentId: l,
							provider: n.effectiveProviderOverride,
							model: n.effectiveModelOverride,
							to: e.delivery.resolvedTo,
							sessionId: e.resolvedSessionId,
							sessionKey: e.resolvedSessionKey,
							thinking: n.effectiveThinking,
							deliver: e.delivery.deliver,
							deliveryTargetMode: e.delivery.deliveryTargetMode,
							channel: e.delivery.originMessageChannel ? e.delivery.resolvedChannel : void 0,
							accountId: e.delivery.resolvedAccountId,
							threadId: n.resolvedThreadId,
							runContext: g,
							clientCaps: y,
							gatewayUiCommandTarget: b,
							approvalReviewerDeviceId: v.ApprovalReviewerDeviceId,
							taskSuggestionDeliveryMode: x ? "gateway" : void 0,
							...n.userTurn.bashElevated ? { bashElevated: n.userTurn.bashElevated } : {},
							...o ? { execApprovalContinuationPromptRange: o } : {},
							execApprovalContinuationTranscriptPromptRange: c,
							groupId: e.groupId,
							groupChannel: e.groupChannel,
							groupSpace: e.groupSpace,
							spawnedBy: e.spawnedBy,
							timeout: n.timeoutSeconds?.toString(),
							bestEffortDeliver: e.bestEffortDeliver,
							messageChannel: e.delivery.originMessageChannel,
							runId: e.runId,
							lane: e.request.lane,
							swarmExecutionLane: e.swarmExecutionLane,
							modelRun: e.request.modelRun === true,
							promptMode: e.request.promptMode,
							extraSystemPrompt: e.request.extraSystemPrompt,
							bootstrapContextMode: e.request.bootstrapContextMode,
							bootstrapContextRunKind: e.effectiveBootstrapContextRunKind,
							toolsAllow: h ?? e.restoredCronContinuation?.toolsAllow,
							runtimePluginToolGrant: f,
							trustedInternalHandoff: n.trustedInternalHandoff,
							toolsAllowIsDefault: e.restoredCronContinuation?.toolsAllowIsDefault,
							scheduledToolPolicy: e.restoredCronContinuation ? resolveScheduledToolPolicyContext({
								toolsAllow: e.restoredCronContinuation.toolsAllow,
								scheduledToolPolicy: e.restoredCronContinuation.scheduledToolPolicy,
								callerOrigin: e.restoredCronContinuation.scheduledToolCallerOrigin,
								execTarget: e.restoredCronContinuation.toolsAllowExecTarget
							}) : void 0,
							requireExplicitMessageTarget: e.restoredCronContinuation?.cliSessionBindingFacts?.requireExplicitMessageTarget,
							cliSessionBindingFacts: e.restoredCronContinuation?.cliSessionBindingFacts,
							acpTurnSource: e.request.acpTurnSource,
							internalEvents: e.request.internalEvents,
							runtimeContextFragments: n.userTurn.runtimeContextFragments,
							inputProvenance: e.inputProvenance,
							privateCompletion: n.userTurn.privateCompletion,
							replyExpectation: n.userTurn.replyExpectation,
							requesterOrigin: n.userTurn.requesterOrigin,
							senderIsOwner: n.userTurn.senderIsOwner,
							sessionEffects: e.sessionEffects,
							skipInitialSessionTouch: e.skipAgentInitialSessionTouch,
							preserveUserFacingSessionModelState: e.preserveUserFacingSessionModelState && !e.restoredCronContinuation,
							sourceReplyDeliveryMode: e.restoredCronContinuation ? e.restoredCronContinuation.cliSessionBindingFacts?.sourceReplyDeliveryMode : e.request.sourceReplyDeliveryMode,
							disableMessageTool: e.request.disableMessageTool,
							swarmCollector: e.request.swarmCollector,
							swarmOutputSchema: e.request.swarmOutputSchema,
							operationalRunInstance: n.operationalRunInstance,
							operatorAuthority: n.operatorAuthority,
							onAdmittedRunContext: (t) => {
								C?.bind(t);
								bindGatewayContextResolver(t, e.context.resolveGatewayContext);
								const r = getAdmittedRunDelegatedAuthority(t);
								if (!r) throw new Error("agent run delegated authority was not admitted");
								if (n.activeRunAbort.registered) n.activeRunAbort.bindAgentRunDelegatedAuthority(r);
							},
							internalDeliverySuppressErrors: e.client?.internal?.internalDeliverySuppressErrors,
							suppressPromptPersistence: n.userTurn.suppressPromptPersistence,
							userTurnTranscriptRecorder: n.userTurn.recorder,
							cleanupBundleMcpOnRunEnd: e.request.cleanupBundleMcpOnRunEnd,
							abortSignal: n.activeRunAbort.controller.signal,
							lifecycleGeneration: e.lifecycleGeneration,
							onExecutionStarted: () => {
								if (!n.activeRunAbort.markExecutionStarted()) return;
								e.io.emitExecutionStarted?.();
							},
							onActiveModelSelected: createAgentRunModelSelectionHandler({
								runId: e.runId,
								resolveGatewayContext: e.context.resolveGatewayContext,
								cfg: e.cfg,
								cfgForAgent: e.cfgForAgent,
								restoredCronContinuationLifecycleRevision: n.restoredCronContinuationLifecycleRevision,
								resolvedSessionKey: e.resolvedSessionKey,
								lifecycleStorePath: n.lifecycleStorePath,
								activeSessionAgentId: e.activeSessionAgentId,
								trustedInternalHandoff: n.trustedInternalHandoff
							}),
							onSessionIdChanged: (t) => {
								if (n.activeRunAbort.entry) {
									adoptExecRequestSession({
										runId: e.runId,
										previousSessionId: getRpcSourceIdentity(n.activeRunAbort.entry).sessionId,
										sessionId: t
									});
									updateRpcSourceSessionId(n.activeRunAbort.entry, t);
								}
							},
							workspaceDir: d ?? u.workspaceDir,
							cwd: resolveSessionRuntimeCwd({
								requestedCwd: e.request.cwd,
								sessionEntry: e.sessionEntry
							}),
							allowGatewaySubagentBinding: true,
							allowModelOverride: n.effectiveAllowModelOverride
						},
						runId: e.runId,
						dedupeKeys: e.agentDedupeKeys,
						abortController: n.activeRunAbort.controller,
						cleanupAbortController: cleanupAdmittedRun,
						onSettled: e.restoredCronContinuation ? async ({ terminalOutcome: t, onRecovered: n }) => await e.releaseCronContinuationClaimWithRecovery({ terminalOutcome: t }, n) : void 0,
						io: {
							...e.io,
							emitFinal: deferFinal
						},
						context: e.context,
						isIncognito: r.incognito,
						followupCompletion: n.followupCompletion,
						canonicalSkillWorkspaceDir: e.sessionEntry?.worktree?.canonicalWorkspaceDir
					}, _));
				} catch (e) {
					if (n.activeRunAbort.controller.signal.aborted && (!o || isAbortError(e))) {
						await s();
						return;
					}
					await i(e);
				} finally {
					try {
						if (!o) try {
							await e.releaseCronContinuationClaimWithRecovery();
						} finally {
							await cleanupAdmittedRun();
						}
					} finally {
						try {
							await v;
						} finally {
							c();
						}
					}
				}
			};
			await (n.activeGatewayWorkAdmission ? n.activeGatewayWorkAdmission.run(execute) : execute());
			s = true;
			deliverFinal?.();
		} catch (e) {
			l.e = e;
		} finally {
			await l.d();
		}
	} finally {
		try {
			n.releaseCallerAuthority?.();
			a?.();
		} finally {
			if (!o) n.followupCompletion?.finishExecution(e.runId);
		}
		if (s && c) t();
	}
}
//#endregion
//#region src/gateway/agent-turn/agent-session-persist.ts
async function persistAgentSessionPhase(e) {
	let t = e.initialPatchBuild;
	const n = t.automaticResetReason;
	const r = n ? createSessionResetBoundaryId() : void 0;
	let { sessionEntry: i, resolvedSessionId: a, sessionPersistedBeforeGatewayAdmission: o, supersededSessionId: s } = e.state;
	let c;
	let l = false;
	let u = false;
	const isDeliveryDenied = (t) => e.request.deliver === true && resolveSendPolicy({
		cfg: e.cfg,
		entry: t,
		sessionKey: e.canonicalSessionKey,
		channel: sessionDeliveryChannel(t),
		chatType: t?.chatType
	}) === "deny";
	const rejectDelivery = () => {
		e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "send blocked by session policy"));
	};
	if (e.freshChild) {
		e.assertGatewayWorkAdmissionAllowed();
		if (e.respondToGatewayAdmissionOutcome()) return;
		if (i) e.onSessionCommitted?.(i);
		l = true;
	} else if (e.storePath && !e.suppressVisibleSessionEffects) {
		let d;
		let f;
		let p;
		let m;
		function rejectMutation(e, t) {
			p = errorShape(e, t);
			throw new Error(t);
		}
		const buildEntry = async (r) => {
			assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
			assertExpectedExistingSession({
				constraint: e.expectedSession,
				entry: r,
				message: `Session "${e.canonicalSessionKey}" changed before expected work could start.`
			});
			if (e.entry && !r) rejectMutation(ErrorCodes.INVALID_REQUEST, `Session "${e.canonicalSessionKey}" was deleted while starting work. Retry.`);
			const i = resolveAgentSessionWorkStartError(e.canonicalSessionKey, r);
			if (i) rejectMutation(ErrorCodes.INVALID_REQUEST, i);
			let a = r;
			if (e.restoredCronContinuationIdentity) {
				const t = r?.cronRunContinuation;
				const n = normalizeOptionalString(r?.modelProvider);
				const i = normalizeOptionalString(r?.model);
				if (!(t?.phase === "ready" && t.basePersisted === true && t.lifecycleRevision === e.restoredCronContinuationIdentity.lifecycleRevision && r?.sessionId === e.restoredCronContinuationIdentity.sessionId) || !r || !n || !i) rejectMutation(ErrorCodes.UNAVAILABLE, "cron run continuation changed before admission");
				if (!cronContinuationHasReusableRuntime({
					cfg: e.cfg,
					entry: r,
					agentId: e.sessionAgentId,
					provider: n,
					model: i
				})) rejectMutation(ErrorCodes.UNAVAILABLE, "cron run continuation has no reusable native CLI session");
				const o = resolveCronToolsAllowExecTargetRecoveryError({
					requirement: t.toolsAllowExecTargetRequirement,
					execTarget: t.toolsAllowExecTarget
				});
				if (o) rejectMutation(ErrorCodes.UNAVAILABLE, o);
				const s = restoreCronPinnedExecGrant({
					toolsAllow: t.toolsAllow,
					requirement: t.toolsAllowExecTargetRequirement,
					execTarget: t.toolsAllowExecTarget
				});
				const l = normalizeCronScheduledToolPolicy(t.scheduledToolPolicy);
				const u = normalizeCronToolsAllowExecTarget(t.toolsAllowExecTarget);
				c = {
					...e.restoredCronContinuationIdentity,
					provider: n,
					model: i,
					...r.thinkingLevel ? { thinking: r.thinkingLevel } : {},
					...s !== void 0 ? { toolsAllow: s } : {},
					...t.toolsAllowIsDefault === true ? { toolsAllowIsDefault: true } : {},
					...l ? { scheduledToolPolicy: l } : {},
					...l?.mode === "account" ? { scheduledToolCallerOrigin: normalizeCronScheduledToolCallerOrigin(t.scheduledToolCallerOrigin) } : {},
					...u ? { toolsAllowExecTarget: u } : {},
					...t.cliSessionBindingFacts ? { cliSessionBindingFacts: { ...t.cliSessionBindingFacts } } : {}
				};
				a = {
					...r,
					cronRunContinuation: {
						...t,
						phase: "continuing",
						ownerRunId: e.runId,
						ownerLifecycleGeneration: e.lifecycleGeneration
					}
				};
				e.setCronContinuationClaim({
					storePath: e.storePath,
					sessionKey: e.canonicalSessionKey,
					sessionAgentId: e.sessionAgentId,
					lifecycleRevision: t.lifecycleRevision,
					initialEntry: structuredClone(a),
					mediaTaskIdsBefore: getGeneratedMediaTaskIdsForSessionKey(e.canonicalSessionKey, e.sessionAgentId)
				});
			}
			t = await e.buildSessionPatch(a);
			if (t.automaticResetReason !== n || n && (r?.sessionId !== e.entry?.sessionId || r?.lifecycleRevision !== e.entry?.lifecycleRevision)) rejectMutation(ErrorCodes.UNAVAILABLE, "Session changed before automatic reset. Retry.");
			e.assertAdmissionCurrent?.();
			assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration);
			if (!r) {
				m = authorizeGatewaySessionCreation({
					cfg: e.cfg,
					agentId: e.sessionAgentId,
					...e.operatorRoleActor ? { actor: e.operatorRoleActor } : { profileId: e.requestingOperatorProfileId }
				});
				if (m) throw new Error(m.message);
			}
			const o = t.patch;
			const s = normalizeOptionalString(r?.sessionId);
			const l = normalizeOptionalString(o.sessionId);
			const f = s && l && s !== l ? { previousSessionId: s } : {};
			const p = e.operatorRoleActor;
			const h = !r && !e.creation.actor && e.cfg.gateway?.roles && p?.kind === "operator" ? {
				...e.creation,
				actor: {
					type: "human",
					source: "profile",
					id: p.profileId
				}
			} : e.creation;
			const g = r ? void 0 : resolveCreatorSandbox(e.cfg, h);
			const _ = r ? {
				...o,
				...f
			} : {
				...o,
				...buildSessionCreationStamp(g ? {
					...h,
					sandbox: g
				} : e.creation)
			};
			u = r === void 0;
			const v = mergeSessionEntry(a, _);
			if (isDeliveryDenied(v)) {
				d = v;
				return null;
			}
			return v;
		};
		const h = composeSessionSourceAssertion([e.assertAdmissionCurrent], (t) => {
			t();
			if (u) assertPreparedSkillLibrarySelection(e.creation.skillLibrarySelections);
		});
		const g = {
			canonicalKey: e.canonicalSessionKey,
			storeKeys: e.storeKeys ?? [e.canonicalSessionKey]
		};
		try {
			if (n) {
				const t = await resetSessionEntryLifecycle({
					agentId: e.sessionAgentId,
					storePath: e.storePath,
					target: g,
					commitGuard: h,
					resetBoundary: {
						boundaryId: r,
						context: "preserve-tail",
						reason: n,
						cwd: e.entry?.spawnedCwd ?? resolveAgentWorkspaceDir(e.cfg, e.sessionAgentId)
					},
					buildNextEntry: async ({ currentEntry: e }) => {
						const t = await buildEntry(e);
						if (!t) rejectMutation(ErrorCodes.INVALID_REQUEST, "send blocked by session policy");
						return t;
					},
					afterEntryMutation: ({ nextEntry: t }) => e.onSessionCommitted?.(t)
				});
				f = t.nextEntry;
				const cleanup = () => clearCommittedSessionResetRuntimeState({
					previousSessionEntry: t.previousEntry,
					agentId: e.sessionAgentId,
					sessionKey: e.canonicalSessionKey,
					storePath: e.storePath,
					onError: (e) => createSubsystemLogger("gateway").warn(`Failed to clear reset runtime state: ${String(e)}`)
				});
				if (e.controllerInput) withSessionControllerSource(e.controllerInput, cleanup);
				else cleanup();
			} else f = await patchSessionEntryTarget({
				agentId: e.sessionAgentId,
				storePath: e.storePath,
				target: g
			}, (e, t) => buildEntry(t.existingEntry), {
				fallbackEntry: e.entry ?? mergeSessionEntry(void 0, t.patch),
				onCommitted: e.onSessionCommitted,
				replaceEntry: true,
				takeCacheOwnership: true,
				maintenanceConfig: e.maintenanceConfig,
				workerGuard: { source: h }
			}) ?? void 0;
		} catch (t) {
			if (m) {
				e.respond(false, void 0, m);
				return;
			}
			if (t instanceof ExpectedExistingSessionChangedError) p = errorShape(ErrorCodes.UNAVAILABLE, t.message);
			if (p) {
				e.respond(false, void 0, p);
				return;
			}
			throw t;
		}
		if (d) {
			i = d;
			a = i.sessionId;
		} else if (f) {
			i = f;
			a = i.sessionId;
			o = true;
		}
		if (t.isNewSession && e.entry?.sessionId && a !== e.entry.sessionId) s = e.entry.sessionId;
		const _ = a ?? e.runId;
		Object.assign(e.state, {
			resolvedSessionId: a,
			admittedSessionId: _,
			supersededSessionId: s,
			sessionPersistedBeforeGatewayAdmission: o
		});
		try {
			e.assertGatewayWorkAdmissionAllowed();
		} catch (t) {
			e.respond(false, void 0, errorShapeFromError(ErrorCodes.INVALID_REQUEST, t));
			return;
		}
		if (e.respondToGatewayAdmissionOutcome()) return;
		l = e.touchInteraction;
		if (d) return rejectDelivery();
	}
	const { isNewSession: d, rotatedSessionId: f, usableRequestedSessionId: p, freshness: m } = t;
	if (u && i) await recordSessionCreated(e.cfg, {
		sessionKey: e.canonicalSessionKey,
		agentId: e.sessionAgentId,
		entry: i
	});
	if (d && e.entry?.sessionId && a !== e.entry.sessionId) s = e.entry.sessionId;
	if (!e.suppressVisibleSessionEffects && d && a && e.storePath && !t.freshSessionRotatedSinceLoad) {
		const t = f || n ? e.entry?.sessionId : void 0;
		if (t) emitGatewaySessionEndPluginHook({
			cfg: e.cfg,
			sessionKey: e.canonicalSessionKey,
			sessionId: t,
			storePath: e.storePath,
			sessionFile: void 0,
			agentId: e.sessionAgentId,
			workspaceDir: e.entry?.spawnedWorkspaceDir,
			reason: m?.staleReason ?? (p && e.entry?.sessionId !== p ? "new" : "unknown"),
			nextSessionId: a,
			nextSessionKey: e.canonicalSessionKey,
			endedTranscript: r ? createResetBoundaryTranscriptSource({
				agentId: e.sessionAgentId,
				sessionId: t,
				sessionKey: e.canonicalSessionKey,
				storePath: e.storePath
			}, r) : createClosedSessionTranscriptSource({
				agentId: e.sessionAgentId,
				sessionId: t,
				sessionKey: e.canonicalSessionKey,
				storePath: e.storePath
			})
		});
		emitGatewaySessionStartPluginHook({
			sessionKey: e.canonicalSessionKey,
			sessionId: a,
			resumedFrom: t,
			storePath: e.storePath,
			sessionFile: void 0,
			agentId: e.sessionAgentId
		});
	}
	if (isDeliveryDenied(i)) return rejectDelivery();
	const h = !e.suppressVisibleSessionEffects && (e.canonicalSessionKey === e.mainSessionKey || e.canonicalSessionKey === "global");
	return {
		sessionEntry: i,
		resolvedSessionId: a,
		sessionPersistedBeforeGatewayAdmission: o,
		supersededSessionId: s,
		admittedSessionId: e.state.admittedSessionId,
		skipAgentInitialSessionTouch: l,
		isNewSession: d,
		spawnedBy: e.freshChild ? i?.spawnedBy : t.spawnedBy,
		groupId: e.freshChild ? i?.groupId : t.groupId,
		groupChannel: e.freshChild ? i?.groupChannel : t.groupChannel,
		groupSpace: e.freshChild ? i?.space : t.groupSpace,
		pendingChatRun: h ? {
			sessionKey: e.canonicalSessionKey,
			agentId: e.sessionAgentId
		} : void 0,
		bestEffortDeliver: h && e.requestedBestEffortDeliver === void 0 ? true : e.state.bestEffortDeliver,
		restoredCronContinuation: c
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-turn-admission-cleanup.ts
/** Finish preparation custody after owner release, even when cleanup rejects. */
async function finishAgentTurnPreparation(e) {
	try {
		if (!e.transferred) await cleanupAgentTurnAdmission(e);
	} finally {
		try {
			await discardPreparedInboundMedia(e.getOffloadedRefs());
			e.clearUnaccepted();
		} finally {
			if (!e.transferred) e.settleSourceWork();
		}
	}
}
/** Release failed preparation after its accepted persistence has settled. */
async function cleanupAgentTurnAdmission({ cleanupRunAbort: e, releaseGatewayAdmission: t, releaseCronContinuation: n }) {
	try {
		e?.();
		t();
	} finally {
		await n();
	}
}
//#endregion
//#region src/gateway/agent-turn/agent-turn-preparation-source.ts
/** Retain the exact request while routing has not yet selected a physical session. */
function createAgentTurnPreparationSource(e) {
	const t = createDeferredCore();
	const n = {};
	let r = e.controllerInput;
	let i;
	let a = false;
	let o = false;
	const publishCancellation = () => {
		if (r) {
			const t = r.target;
			const a = resolveChatAbortStopReason(r.abortSignal);
			const o = a === "rpc" && i && (!t || t.aliases.includes(i)) ? i : t?.sessionKey ?? i;
			e.onCancelled({
				agentId: t?.agentId ?? n.agentId,
				sessionKey: o,
				stopReason: a
			});
		}
	};
	const settle = () => {
		r?.abortSignal.removeEventListener("abort", publishCancellation);
		t.resolve();
	};
	return {
		get input() {
			return r;
		},
		work: t.promise,
		assertCurrent() {
			r?.abortSignal.throwIfAborted();
		},
		reserve(o, s) {
			i = o ?? i;
			n.agentId = s ?? n.agentId;
			if (!r) {
				r = reserveSessionControllerSource(`agent-request:${e.runId}`, {
					protocolRunId: e.runId,
					sourceTurnId: e.runId,
					policy: { mode: "followup" },
					adapter: {
						preparation: n,
						requester: e.requester,
						authority: { assertCurrent: () => e.assertAdmissionCurrent?.() }
					}
				});
				bindGatewayContextResolver(r, e.context.resolveGatewayContext);
			}
			if (!a) {
				a = true;
				trackSessionControllerSourceWork(r, t.promise);
				r.abortSignal.addEventListener("abort", publishCancellation, { once: true });
				if (r.abortSignal.aborted) publishCancellation();
			}
			r.abortSignal.throwIfAborted();
		},
		settle,
		transfer() {
			o = true;
			settle();
		},
		[Symbol.dispose]() {
			if (r && !e.controllerInput && (!o || !r.target)) retireSessionControllerInput(r);
			settle();
		}
	};
}
//#endregion
//#region src/gateway/agent-turn/agent-turn-source-admission.ts
/** Authorize a principal to create or mutate the canonical session an agent turn targets. */
async function authorizeAgentTurnSession({ cfg: e, principal: t, agentId: n, sessionKey: r }) {
	return authorizeGatewaySessionCreation({
		cfg: e,
		client: t,
		agentId: n
	}) ?? await authorizeResolvedSessionMutationAsync({
		cfg: e,
		client: t,
		sessionKey: r,
		agentId: n
	});
}
/** Register the turn's abortable source on its physical session target and announce its owner. */
function registerAgentTurnRunAbort(e, t) {
	const { request: n, runId: r, suppressVisibleSessionEffects: i, inputProvenance: a } = e.preflight;
	const o = captureSessionTarget({
		storeScope: t.storeScope,
		physicalStorePath: t.physicalStorePath,
		sessionKey: t.sessionKey,
		aliases: t.aliases,
		agentId: t.agentId,
		incarnation: t.incarnation
	});
	if (e.controllerInput && !e.controllerInput.target) retargetSessionControllerSource(e.controllerInput, o);
	const s = registerChatAbortController({
		sourceWork: e.sourceWork,
		runId: r,
		sessionKey: t.sessionKey,
		sessionId: t.sessionId ?? "",
		target: o,
		authority: { assertCurrent: () => {
			if (!e.isSourcePreparationComplete()) e.assertAdmissionCurrent?.();
		} },
		agentId: t.agentId,
		timeoutMs: resolveAgentTimeoutMs({
			cfg: t.cfg,
			overrideSeconds: n.timeout
		}),
		ownerConnId: e.ownerConnId,
		ownerDeviceId: e.ownerDeviceId,
		kind: "agent",
		lifecycleGeneration: e.lifecycleGeneration,
		controlUiVisible: !i && !isSubagentCoordinationInputProvenance(a),
		operationalRunInstance: createOperationalRunInstanceRef(r),
		onCancel: (n) => e.onCancelled({
			agentId: t.agentId,
			sessionKey: t.sessionKey,
			stopReason: n
		}),
		sourceInput: e.controllerInput
	});
	e.onRegistered(s);
	if (s.entry) e.io.emitStartOwner?.(r, s.entry);
}
/** Bind preparation custody to the authorized physical target before attachment work yields. */
async function registerAgentTurnSourceAdmission({ sessionKey: e, agentId: t, principal: n, assertRequestCurrent: r, ...i }) {
	if (!e || AGENT_SESSION_RESET_COMMAND_RE.test(i.preflight.request.message ?? "")) return;
	const a = await loadGatewaySessionEntryReadOnlyInWorker({
		cfg: i.preflight.cfg,
		key: e,
		agentId: t,
		excludeInternalEffects: true,
		assertActive: r
	});
	const o = resolveAgentIdFromSessionKey(a.canonicalKey, t);
	const s = await authorizeAgentTurnSession({
		cfg: a.cfg,
		principal: n,
		sessionKey: a.canonicalKey,
		agentId: o
	});
	if (s) {
		i.io.emitAcceptance([
			false,
			void 0,
			s
		]);
		return false;
	}
	r();
	registerAgentTurnRunAbort(i, {
		cfg: i.preflight.cfg,
		storeScope: a.storePath,
		physicalStorePath: a.readSource?.path,
		sessionKey: a.canonicalKey,
		aliases: [e],
		agentId: o,
		sessionId: a.entry?.sessionId,
		incarnation: a.entry?.sessionId
	});
}
//#endregion
//#region src/gateway/agent-turn/agent-turn-service.ts
function createAgentTurnService({ context: e, isWebchatConnect: t }, n) {
	const startTurn = async ({ controllerInput: r, privateCompletion: i, replyExpectation: a, settleWakeReplay: o, assertAdmissionCurrent: s, assertCancellationCurrent: c, executionSource: l, assertInputCommitAllowed: u, hasCurrentClientAuthority: d, preflight: f, principal: p, io: m, onRunObserved: h }) => {
		try {
			var g = _usingCtx();
			const _ = Date.now();
			s?.();
			const v = i === true || readInProcessSubagentResume(p?.internal) !== void 0;
			if (replayAgentTurnIfCached({
				preflight: f,
				context: e,
				io: m,
				acceptedOnly: v
			})) return;
			const y = getRpcSourceForGateway(f.runId, e.resolveGatewayContext);
			if (y && y.input !== r) {
				m.emitAcceptance([
					true,
					{
						runId: f.runId,
						status: "in_flight"
					},
					void 0
				], {
					cached: true,
					runId: f.runId
				});
				return;
			}
			u?.();
			const respond = (e, t, n, r) => m.emitAcceptance([
				e,
				t,
				n
			], r);
			const { request: b, cfg: x, runId: S, canUseCronRunContinuation: C, expectedSession: w, expectedExistingSessionId: T, normalizedSpawned: E, suppressVisibleSessionEffects: D, agentDedupeKeys: O } = f;
			const k = getAgentEventLifecycleGeneration();
			const A = typeof p?.connId === "string" ? p.connId : void 0;
			const j = typeof p?.connect?.device?.id === "string" ? p.connect.device.id : void 0;
			const M = createAgentDedupeLifecycle({
				...f,
				reconcileDurableInput: v,
				assertAdmissionCurrent: s,
				assertCancellationCurrent: c,
				ownerConnId: A,
				ownerDeviceId: j,
				context: e,
				io: m
			});
			let N = false;
			let P;
			const F = g.u(createAgentTurnPreparationSource({
				runId: S,
				context: e,
				controllerInput: r,
				requester: {
					connectionId: A,
					deviceId: j
				},
				assertAdmissionCurrent: s,
				onCancelled: M.cancelOwnedReservation
			}));
			const I = composeSessionSourceAssertion([
				n,
				s,
				() => {
					const e = F.input?.abortSignal;
					if (e?.aborted && !isGatewayAgentAbortRejection(e.reason, e)) e.throwIfAborted();
					M.assertReservationCurrent();
				},
				F.assertCurrent,
				() => {
					if (P?.entry && !isRpcSourceRegistered(P.entry)) throw new Error("Agent request no longer owns its RPC source");
				},
				u
			]);
			const L = await prepareAgentRequestRouting({
				...f,
				context: e,
				respond,
				reserveDedupe: (e, t) => {
					M.reserve(e, t);
					M.assertReservationCurrent();
					F.reserve(e, t);
				},
				bindDedupeSessionTarget: M.bindSessionTarget,
				clearDedupe: M.clearUnaccepted,
				assertCurrent: I
			}).catch((e) => {
				M.clearUnaccepted();
				return M.handlePreparationFailure(s)(e);
			});
			if (!L) return;
			let R = true;
			let z = false;
			const assertStorageCurrent = () => {
				if (!R) throw new Error("Agent session storage admission ended");
				n?.();
			};
			const B = await acquireSessionActorStorage({
				sessionKey: L.requestedSessionKey,
				agentId: L.agentId
			}, {
				lifetime: {
					assertCurrent: assertStorageCurrent,
					assertReadable: assertStorageCurrent
				},
				authority: {
					assertCurrent: assertStorageCurrent,
					authorize: assertStorageCurrent
				}
			}).catch((e) => {
				M.clearUnaccepted();
				throw e;
			});
			const releaseSessionStorage = async () => {
				if (!R) return;
				R = false;
				await B?.actor.release();
			};
			const execute = async () => {
				const { requestedBestEffortDeliver: r, requestedSessionId: c, sessionKeyFromTo: u, requestedSessionKeyRaw: g, preAcceptedReservedSessionKey: v, preAttachmentSession: y } = L;
				const R = {
					preflight: f,
					io: m,
					sourceWork: F.work,
					lifecycleGeneration: k,
					ownerConnId: A,
					ownerDeviceId: j,
					assertAdmissionCurrent: s,
					isSourcePreparationComplete: () => N,
					onCancelled: M.cancelOwnedReservation,
					controllerInput: F.input
				};
				let B = L.agentId;
				let V = L.requestedSessionKey;
				let H = [];
				let releaseGatewayAdmission = () => {};
				let respondToAdmissionOutcome = () => false;
				const U = createCronContinuationController({
					runId: S,
					lifecycleGeneration: k,
					context: e
				});
				try {
					s?.();
					const W = await prepareAgentContentPhase({
						...f,
						...L,
						assertAdmissionCurrent: I,
						context: e,
						respond,
						requestedSessionKey: V,
						agentId: B,
						onTargetResolved: (e) => registerAgentTurnSourceAdmission({
							...e,
							...R,
							principal: p,
							assertRequestCurrent: I,
							onRegistered: (e) => {
								P = e;
							}
						})
					}).catch(M.handlePreparationFailure(s));
					if (!W) return;
					H = W.offloadedRefs;
					s?.();
					B = W.agentId;
					V = W.requestedSessionKey;
					let ee = W.effectiveTranscriptInputText;
					let te = W.message;
					const { images: ne, imageOrder: re, media: ie, offloadedRefs: ae, recipientChannel: oe, recipientAccountId: se, recipientThreadId: ce, to: le } = W;
					const G = {
						resolvedSessionId: c,
						sessionPersistedBeforeGatewayAdmission: false,
						bestEffortDeliver: r ?? false,
						isNewSession: false,
						skipAgentInitialSessionTouch: false,
						admittedSessionId: c ?? S,
						groupId: E.groupId,
						groupChannel: E.groupChannel,
						groupSpace: E.groupSpace
					};
					let K = f.bootstrapContextRunKind;
					let q;
					let J;
					let ue = false;
					let Y;
					let X = V;
					let de;
					const Z = createAgentAdmissionController({
						assertAdmissionCurrent: s,
						runId: S,
						agentDedupeKeys: O,
						preAcceptedReservedSessionKey: v,
						expectedSession: w,
						context: e,
						io: m,
						dedupeLifecycle: M,
						getRequestedSessionKey: () => V,
						getResolvedSessionKey: () => X,
						getResolvedSessionId: () => G.resolvedSessionId,
						getSessionEntry: () => G.sessionEntry,
						setSessionEntry: (e) => {
							G.sessionEntry = e;
						},
						getResolvedSessionAgentId: () => de,
						getAgentId: () => B,
						getSessionPersisted: () => G.sessionPersistedBeforeGatewayAdmission,
						getSupersededSessionId: () => G.supersededSessionId,
						setAdmittedSessionId: (e) => {
							G.admittedSessionId = e;
						}
					});
					if (P) Z.setAdmittedRunAbort(P);
					releaseGatewayAdmission = Z.release;
					respondToAdmissionOutcome = () => {
						Z.assertAllowed();
						return Z.respondToOutcome();
					};
					const Q = await runAgentResetPhase({
						assertAdmissionCurrent: I,
						request: b,
						cfg: x,
						requestedSessionKey: V,
						resolvedSessionId: G.resolvedSessionId,
						effectiveTranscriptInputText: ee,
						message: te,
						agentId: B,
						sessionKeyFromTo: u,
						lifecycleGeneration: k,
						runId: S,
						agentDedupeKeys: O,
						client: p,
						context: e,
						respond,
						setCommittedResetCompletion: M.setCommittedResetCompletion
					});
					V = Q.requestedSessionKey;
					G.resolvedSessionId = Q.resolvedSessionId;
					ee = Q.effectiveTranscriptInputText;
					te = Q.message;
					if (Q.accepted) M.markAccepted(true);
					if (Q.stop) return;
					if (V) {
						const t = await prepareAgentSession({
							cfg: x,
							requestedSessionKey: V,
							requestedSessionId: c,
							expectedExistingSessionId: T,
							agentId: B,
							recipientChannel: oe,
							request: b,
							canUseCronRunContinuation: C,
							lifecycleGeneration: k,
							effectiveBootstrapContextRunKind: K,
							preAttachmentSession: y,
							respond,
							assertCurrent: I
						});
						I();
						if (!t) return;
						const { cfg: n, storePath: i, canonicalKey: a, storeKeys: o, maintenanceConfig: s, canonicalSessionAgentId: l, mainSessionKey: u, touchInteraction: d } = t;
						const { entry: f } = t;
						J = n;
						ue = t.freshChild;
						Y = i;
						const h = await authorizeAgentTurnSession({
							cfg: n,
							principal: p,
							sessionKey: a,
							agentId: l
						});
						if (h) {
							m.emitAcceptance([
								false,
								void 0,
								h
							]);
							return;
						}
						K = t.effectiveBootstrapContextRunKind;
						q = t.restoredCronContinuationIdentity;
						G.sessionPersistedBeforeGatewayAdmission = t.sessionPersistedBeforeGatewayAdmission;
						const g = normalizeDeliveryContext({
							channel: oe?.trim(),
							to: le,
							accountId: se?.trim(),
							threadId: ce
						});
						const _ = normalizeOptionalString(b.sessionKey);
						const buildSessionPatch = (e, n) => buildAgentSessionPatch({
							...t,
							freshEntry: e,
							initialEntry: f,
							sessionAgentId: l,
							canonicalSessionKey: a,
							normalizedSpawned: E,
							requestDeliveryHint: g,
							requestLabel: b.label,
							..._ ? { explicitSessionKey: _ } : {},
							pluginOwnerId: e === void 0 ? normalizeOptionalString(p?.internal?.pluginRuntimeOwnerId) : void 0,
							expectedExistingSessionId: T,
							hasRestoredCronContinuation: q !== void 0,
							requestedSessionId: c,
							fallbackSessionId: n
						});
						const v = t.freshChild ? {
							patch: {},
							spawnedBy: f?.spawnedBy,
							groupId: f?.groupId,
							groupChannel: f?.groupChannel,
							groupSpace: f?.space,
							freshSessionRotatedSinceLoad: false,
							isNewSession: false,
							rotatedSessionId: false,
							usableRequestedSessionId: void 0,
							freshness: { fresh: true }
						} : await buildSessionPatch(f);
						I();
						G.sessionEntry = f;
						G.resolvedSessionId = mergeSessionEntry(f, v.patch).sessionId;
						const O = G.resolvedSessionId;
						G.admittedSessionId = G.resolvedSessionId ?? S;
						X = a;
						de = l;
						if (!Z.getAdmittedRunAbort()) registerAgentTurnRunAbort({
							...R,
							onRegistered: (e) => {
								P = e;
								Z.setAdmittedRunAbort(e);
							}
						}, {
							cfg: n,
							storeScope: i,
							physicalStorePath: t.physicalStorePath,
							sessionKey: a,
							aliases: [V],
							agentId: l,
							sessionId: G.resolvedSessionId,
							incarnation: f?.sessionId
						});
						try {
							await Z.acquire(i ?? `agent:${l}`);
						} catch (e) {
							m.emitAcceptance([
								false,
								void 0,
								errorShapeFromError(ErrorCodes.INVALID_REQUEST, e)
							]);
							return;
						}
						if (Z.respondToOutcome()) return;
						const A = await persistAgentSessionPhase({
							controllerInput: P?.entry?.input,
							freshChild: t.freshChild,
							onSessionCommitted: (e) => {
								G.sessionEntry = e;
								if (P?.entry) updateRpcSourceSessionId(P.entry, e.sessionId);
								M.bindSessionTarget({
									sessionKey: a,
									agentId: l,
									sessionId: e.sessionId
								});
							},
							assertAdmissionCurrent: I,
							request: b,
							cfg: n,
							storePath: i,
							storeKeys: o,
							entry: f,
							canonicalSessionKey: a,
							sessionAgentId: l,
							mainSessionKey: u,
							creation: await prepareSkillLibrarySessionCreation(p, () => e.getRuntimeConfig(), resolveAgentRunSessionCreation(p)),
							...p?.authenticatedUserProfile ? { requestingOperatorProfileId: p.authenticatedUserProfile.profileId } : {},
							...p?.internal?.operatorRoleActor ? { operatorRoleActor: p.internal.operatorRoleActor } : {},
							lifecycleGeneration: k,
							runId: S,
							agentId: B,
							suppressVisibleSessionEffects: D,
							restoredCronContinuationIdentity: q,
							initialPatchBuild: v,
							buildSessionPatch: (e) => buildSessionPatch(e, O),
							state: G,
							touchInteraction: d,
							requestedBestEffortDeliver: r,
							expectedSession: w,
							maintenanceConfig: s,
							assertGatewayWorkAdmissionAllowed: Z.assertAllowed,
							respondToGatewayAdmissionOutcome: Z.respondToOutcome,
							setCronContinuationClaim: U.setClaim,
							respond
						});
						if (!A) return;
						Object.assign(G, A);
					}
					const fe = await resolveAgentDeliveryPhase({
						...W,
						...G,
						request: b,
						cfg: x,
						cfgForAgent: J,
						resolvedSessionKey: X,
						storePath: Y,
						resolvedSessionAgentId: de,
						agentId: B,
						runId: S,
						client: p,
						context: e,
						respond,
						isWebchatConnect: t,
						onRunObserved: h
					});
					if (!fe) return;
					const { activeSessionAgentId: pe } = fe;
					const me = {
						...f,
						...G,
						cfgForAgent: J,
						freshChild: ue,
						resolvedSessionKey: X,
						requestedSessionKey: V,
						activeSessionAgentId: pe,
						delivery: fe,
						lifecycleGeneration: k,
						images: ne,
						context: e,
						io: m,
						client: p
					};
					const $ = await prepareAgentRunDispatch({
						...me,
						sourceWork: F.work,
						needsImageUnderstanding: W.needsImageUnderstanding,
						lifecycleStorePath: Y ?? `agent:${pe}`,
						assertAdmissionCurrent: I,
						hasCurrentClientAuthority: d,
						promptedAt: _,
						requestedSessionKeyRaw: g,
						preAcceptedReservedSessionKey: v,
						restoredCronContinuationIdentity: q,
						getAdmittedSessionId: () => G.admittedSessionId,
						ownerConnId: A,
						ownerDeviceId: j,
						message: te,
						effectiveTranscriptInputText: ee,
						offloadedRefs: ae,
						onUserTurnMediaPersisted: () => {
							H = [];
						},
						privateCompletion: i,
						replyExpectation: a,
						settleWakeReplay: o,
						acquireGatewayWorkAdmission: Z.acquire,
						assertGatewayWorkAdmissionAllowed: Z.assertAllowed,
						hasGatewayAdmissionOutcome: Z.hasOutcome,
						respondToGatewayAdmissionOutcome: Z.respondToOutcome,
						admissionAgentId: Z.admissionAgentId,
						getGatewayWorkAdmission: Z.getAdmission,
						setAdmittedRunAbort: Z.setAdmittedRunAbort,
						getAdmittedRunAbort: Z.getAdmittedRunAbort,
						markAgentRunAccepted: (e) => {
							if (e) N = true;
							M.markAccepted(e);
						},
						getOwnedAgentDedupeKeys: M.ownedReservationKeys,
						releaseUnacceptedReservation: M.releaseUnacceptedReservation
					});
					if (!$) return;
					G.resolvedSessionId = G.admittedSessionId;
					H = [];
					N = true;
					(async () => {
						try {
							await e.trackExecution(() => startAgentRunExecution({
								...me,
								...G,
								assertGatewayLifetimeCurrent: n,
								executionSource: l,
								prepared: $,
								agentId: B,
								imageOrder: re,
								media: ie,
								inputProvenance: $.userTurn.inputProvenance,
								effectiveBootstrapContextRunKind: K,
								releaseCronContinuationClaimWithRecovery: U.releaseWithRecovery
							}));
						} finally {
							await releaseSessionStorage();
						}
					})().catch((t) => {
						$.releaseCallerAuthority?.();
						e.logGateway.warn(`agent execution cleanup failed: ${String(t)}`);
					});
					F.transfer();
					z = true;
				} catch (e) {
					if (!(e instanceof AgentRequestReservationEndedError)) throw e;
					if (!respondToAdmissionOutcome()) M.handlePreparationFailure(s)(e);
				} finally {
					await finishAgentTurnPreparation({
						transferred: z,
						cleanupRunAbort: () => P?.cleanup(),
						releaseGatewayAdmission,
						releaseCronContinuation: U.releaseWithRecovery,
						getOffloadedRefs: () => H,
						clearUnaccepted: M.clearUnaccepted,
						settleSourceWork: F.settle
					});
				}
			};
			try {
				await withPluginRetentionOwner({
					runId: S,
					serviceId: "gateway-agent-turn"
				}, () => B ? runWithSessionActorStorage(B, execute) : execute());
			} finally {
				if (!z) await releaseSessionStorage();
			}
		} catch (e) {
			g.e = e;
		} finally {
			g.d();
		}
	};
	const prepareWaitForTurn = (t) => prepareAgentWaitForTurn(e, t, { exactTurnSource: true });
	const waitForTurn = async (e) => await prepareWaitForTurn(e).wait();
	return {
		startTurn,
		prepareWaitForTurn,
		waitForTurn
	};
}
//#endregion
export { createAgentTurnService as t };