UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

750 lines (749 loc) • 30.1 kB
import { o as racePromiseWithAbortSignal, s as raceWithTimeout } from "./src-BPmQBLJp.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { c as withPluginRuntimeGatewayContextResolver, o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs"; import { o as getGatewayContextResolver, t as bindGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs"; import { j as parseAgentSessionKey, x as isCronSessionKey } from "./session-key-CqAyZeVk.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as SkillLibraryError } from "./skill-library-error-B7IM_P8I.mjs"; import { d as getAgentEventLifecycleGeneration } from "./agent-events-BdfWYmot.mjs"; import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs"; import { a as resolveRequesterPrincipalKey, i as requesterCreatorProfileId } from "./requester-origin-DG-fk-U0.mjs"; import { u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs"; import { r as resolveSessionWorkStartBlock } from "./session-work-start-CFJs8WNp.mjs"; import { C as observeReplyRunCompletions, Dt as lifecycleAdmissionByOperation, Ft as sessionControllers, N as resolveVisibleActiveWaitMs, P as runAfterReplyOperationClear, X as captureSessionTarget, _t as getSessionControllerEntryForOperation, a as expireVisibleStaleOperation, at as ReplyRunLifecycleAdmissionBlockedError, c as getAttachedBackend, et as evaluateTurnAdmission, f as hasCommittedReplyOperationOutcome, g as isReplyOperationAbortedForRestart, it as ReplyRunFollowupAdmissionBlockedError, nt as REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS, ot as ReplyRunSuccessorAdmissionBlockedError, r as bindSessionControllerEntryTarget, rt as ReplyRunAlreadyActiveError, s as findSessionControllerEntry, u as getSessionControllerEntry, x as mergeReplyRunAdmissionSource } from "./session-controller.state-BApgK0mV.mjs"; import { d as isCronExecutionInputProvenance } from "./input-provenance-DupvvURj.mjs"; import { a as normalizeStoreSessionKey } from "./store-entry-BTUJi0xl.mjs"; import { n as SessionWorkStartChangedError } from "./work-start-error-DaHE71YG.mjs"; import { U as withSessionControllerOwner, k as lifecycle, t as beginSessionEffect } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { r as createSessionControllerPhaseLogger } from "./session-controller.diagnostics-Da3aEb42.mjs"; import { f as loadSessionEntryForAdmission } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs"; import "./lifecycle-BFcckgci.mjs"; import { t as captureAgentWorkspaceReadiness } from "./workspace-readiness-ClUjI0tp.mjs"; import { t as createReplyOperation } from "./session-controller.operation-BXBO7UKT.mjs"; import { i as registerReplyOperationSuccessorBarrier, n as isReplyRunSuccessorAdmissionBlocked } from "./session-controller.barriers-DbvoxYCP.mjs"; import { n as waitForReplyRunSuccessorAdmission, r as waitForSessionRunIdle, t as waitForReplyRunFollowupAdmission } from "./session-controller.wait-DKnNX-C5.mjs"; import "./session-controller-Bu0l-8-p.mjs"; import { t as beginForegroundSessionMaintenance } from "./coordinator-C4xk0qGg.mjs"; import { t as formatSystemTurnPrompt } from "./system-turn-prompt-rhkEP4nq.mjs"; import { addAbortListener } from "node:events"; //#region src/auto-reply/reply/reply-turn-admission-wait.ts /** Observe the captured controller's custody; the admission owner decides wait policy. */ function createReplyTurnAdmissionWaiter(e, t) { return { async barrier(n) { const r = createSessionControllerPhaseLogger(n.phase, { sessionKey: t.sessionKey, sessionId: n.sessionId, sourceId: t.runId }); r("waiting"); const i = { signal: t.upstreamAbortSignal }; const a = n.phase === "followup-barrier" ? await waitForReplyRunFollowupAdmission(e.id, n.timeoutMs, i) : await waitForReplyRunSuccessorAdmission(e.id, n.timeoutMs, i); r(a.settled ? "settled" : "failed", a.settled ? void 0 : "aborted-or-deadline"); return a; }, async inputs(n, r) { const i = lifecycle(e).changed.promise; const a = r ?? e.mailbox?.entries.filter((e) => !e.claim?.operation?.admissionRetired) ?? []; const o = Promise.race([i, Promise.allSettled(a.map((e) => e.settlement.promise))]).then(() => true); try { return n === void 0 ? await racePromiseWithAbortSignal(o, t.upstreamAbortSignal) : await raceWithTimeout(o, Math.max(0, n - Date.now()), () => false, { ref: false, signal: t.upstreamAbortSignal, onAbort: () => false }); } catch (e) { if (!t.upstreamAbortSignal?.aborted) throw e; return false; } } }; } //#endregion //#region src/auto-reply/reply/reply-turn-admission-errors.ts /** Identifies queued follow-up work invalidated before it acquires the turn. */ var QueuedFollowupLifecycleInvalidatedError = class extends Error {}; /** Preserves each turn kind's lifecycle-invalidated error contract. */ function rejectLifecycleInvalidatedWork(e) { if (e.kind === "queued_followup") throw new QueuedFollowupLifecycleInvalidatedError(e.message, { cause: e.error }); if (e.kind === "visible" && e.transientSessionChange === true) throw new SessionWorkStartChangedError(e.message); throw e.error ?? new Error(e.message); } //#endregion //#region src/auto-reply/reply/reply-turn-admission-lifecycle.ts const log = createSubsystemLogger("auto-reply/reply-turn-admission"); function bindReplyAdmissionRelease(e) { const { operation: t, admission: n, databaseClaim: r, sessionId: i, sessionKey: a } = e; let o; let s; let c; const assertReaderOperation = () => { t.abortSignal.throwIfAborted(); if (s) e.workSignal?.throwIfAborted(); if (s || t.key !== a) throw new SessionWorkStartChangedError("Session reader operation is no longer current. Retry the turn."); }; const assertTransitionActive = () => { assertReaderOperation(); if (t.result) throw new SessionWorkStartChangedError("Reply transition is no longer active"); }; const releaseSessionActor = async () => { const e = c; const t = l.sessionActor; c = void 0; l.sessionActor = void 0; if (t) { await t.release(); return; } await (await e?.catch(() => void 0))?.release(); }; const l = { lease: n, databaseIdentity: r?.identity, databaseClaim: r, reader: r && "kind" in r ? r.reader : void 0, sessionTarget: r && "kind" in r ? r.target : void 0, resolveReader() { l.reader?.assertCurrent(); return l.reader; }, resolveSessionTarget() { assertReaderOperation(); l.databaseClaim?.assertCurrent(); return l.sessionTarget; }, acquireSessionActor() { assertReaderOperation(); const e = l.databaseClaim; if (!e || !("kind" in e)) throw new Error("Reply operation has no session actor admission"); c ??= e.acquireSessionActor({ assertCurrent: () => e.assertCurrent(), assertReadable() { assertReaderOperation(); e.assertCurrent(); } }).then((e) => { l.sessionActor = e; return e; }); return c; }, async afterTransition(e) { assertTransitionActive(); const t = l.databaseClaim; const n = t && "kind" in t ? t.afterTransition?.bind(t) : void 0; if (!t || !n) return; o = (async () => { const r = await n(e, assertTransitionActive); if (s) { await r.release(); assertReaderOperation(); } l.databaseClaim = r; l.reader = r.reader; l.sessionTarget = r.target; try { await releaseSessionActor(); } finally { await t.release(); } assertTransitionActive(); })(); try { await o; } finally { o = void 0; } } }; lifecycleAdmissionByOperation.set(t, l); const u = r && "kind" in r ? () => { if (!s) { const e = c ? releaseSessionActor() : void 0; const t = e ? void 0 : l.databaseClaim?.release(); s = (async () => { await Promise.allSettled([ o, t, e ]); if (t) await t; else try { await e; } finally { await l.databaseClaim?.release(); } })(); } return s; } : void 0; if (u) { let n = false; const releaseForRestart = (e) => { if (n || !isAgentRunRestartAbortReason(e.reason)) return; n = true; const r = getAttachedBackend(t)?.runId ?? "unbound"; u().then(() => log.info(`lease released: reason=restart-abort runId=${r} kind=reply-admission`, { sessionId: i }), (e) => log.warn(`failed to release restart-aborted reply database owner: ${formatErrorMessage(e)}`)); }; const r = [.../* @__PURE__ */ new Set([t.abortSignal, e.workSignal])].flatMap((e) => e ? [addAbortListener(e, () => releaseForRestart(e))] : []); runAfterReplyOperationClear(t, () => { for (const e of r) e[Symbol.dispose](); }); registerReplyOperationSuccessorBarrier({ operation: t, sessionId: i, sessionKeys: [a], start: u, deferUntilClear: true }); } if (n) runAfterReplyOperationClear(t, () => { l.lease = void 0; Promise.resolve(u?.()).then(() => { n.release(); }, (e) => { log.warn(`failed to release reply database owner: ${formatErrorMessage(e)}`); }); }); if (r && !("kind" in r)) runAfterReplyOperationClear(t, r.release); } /** Runs owner work with its admission marked as the initiating lifecycle context. */ async function runWithReplyOperationLifecycleAdmission(e, t) { const n = lifecycleAdmissionByOperation.get(e)?.lease; if (n) return await n.run(() => withSessionControllerOwner(e, t)); const r = getGatewayContextResolver(e); return await withPluginRuntimeGatewayContextResolver(r, () => withSessionControllerOwner(e, t)); } //#endregion //#region src/auto-reply/reply/reply-turn-admission-target.ts /** Bind admission to one physical controller before waiting or adopting an operation. */ function resolveReplyTurnController(e) { const t = e.storePath ? captureSessionTarget({ storeScope: e.storePath, sessionKey: e.sessionKey, agentId: e.agentId }) : void 0; if (t && e.adoptOperation) { const n = getSessionControllerEntryForOperation(e.adoptOperation).target; if (n && n.storeScope !== t.storeScope) throw new Error("Reply operation cannot move between physical stores"); } const n = e.mailboxClaim?.mailbox.owner ?? findSessionControllerEntry(e.sessionKey, t) ?? getSessionControllerEntry(e.sessionKey, t); if (t && !n.target) bindSessionControllerEntryTarget(n, t); if (t && n.target?.storeScope !== t.storeScope) throw new Error("Reply claim belongs to a different physical store"); return n; } //#endregion //#region src/auto-reply/reply/reply-turn-rotation.ts /** Retains invocation-local lineage evidence; the admission owner decides whether work may start. */ function createReplyTurnRotationEvidence(e) { const t = e.controller ?? getSessionControllerEntry(e.sessionKey); const n = /* @__PURE__ */ new Map(); const isCurrent = (n) => !isReplyOperationAbortedForRestart(n.operation) && (n.fromBarrier || getSessionControllerEntryForOperation(n.operation) === t && lifecycleAdmissionByOperation.get(n.operation)?.databaseIdentity === n.databaseIdentity && n.operation.key === e.sessionKey && (n.operation === t.active || n.operation.result !== null)); const mergeWaitedRotation = (e) => { const t = n.get(e.databaseIdentity); return mergeReplyRunAdmissionSource(e, t && isCurrent(t) ? { ...t, sessionIds: new Set(t.sessionIds) } : void 0); }; const recordSources = (e, t) => { for (const r of e) n.set(r.databaseIdentity, mergeWaitedRotation({ ...r, sessionIds: new Set(r.sessionIds), fromBarrier: t })); }; return { recordBarrierSources(e = []) { recordSources(e, true); }, observeAdmission() { const e = observeReplyRunCompletions(t.id); const n = t.active; return { recordCompletions: () => recordSources(e.read() ?? [], false), changed: () => e.read() !== void 0 || n !== t.active, dispose: () => { const t = e.read(); e.dispose(); recordSources(t ?? [], false); } }; }, recordCompletedOperation(e, t) { if (lifecycleAdmissionByOperation.get(e)?.databaseIdentity !== t) return; n.set(t, mergeWaitedRotation({ operation: e, sessionId: e.sessionId, sessionIds: e.captureOwnedSessionIds(), databaseIdentity: t, fromBarrier: false })); }, hasCurrentRotationEvidence() { return [...n.values()].some(isCurrent); }, takeStorelessRotation() { const e = n.get(void 0); n.delete(void 0); return e && isCurrent(e) ? e : void 0; }, hasExpectedSessionRotation(r) { const i = t.active; const a = [...n.values()]; for (const t of /* @__PURE__ */ new Set([ ...e.expectedActiveOperations ?? [], e.activeAtAdmission, i ])) if (t) { let e = mergeWaitedRotation({ operation: t, sessionId: t.sessionId, sessionIds: t.captureOwnedSessionIds(), databaseIdentity: lifecycleAdmissionByOperation.get(t)?.databaseIdentity, fromBarrier: false }); if (!isCurrent(e)) continue; for (const t of a) if (isCurrent(t)) e = mergeReplyRunAdmissionSource(e, { ...t, sessionIds: new Set(t.sessionIds) }); a.push(e); } return a.some((e) => r.expectedSessionId && r.databaseIdentity !== void 0 && e.databaseIdentity === r.databaseIdentity && r.sessionId === e.sessionId && isCurrent(e) && e.sessionIds.has(r.expectedSessionId)); } }; } //#endregion //#region src/auto-reply/reply/reply-turn-admission.ts var ReplyOperationChangedDuringAdmissionError = class extends Error {}; function isAbortSignalAborted(e) { return e?.aborted === true; } /** Waits for or claims the per-session reply run slot. */ async function admitReplyTurn(e) { const t = captureAgentWorkspaceReadiness(e.sessionKey); const n = getAsyncWorkSignal(); const r = resolveReplyTurnController(e); const i = r.id; const a = createReplyTurnAdmissionWaiter(r, e); const o = r.active; const s = e.kind === "visible" ? await beginForegroundSessionMaintenance(e.sessionKey) : void 0; let c = false; let l = o?.result && !isReplyOperationAbortedForRestart(o) && (!e.storePath && !e.expectedSessionId || o.captureOwnedSessionIds().has(e.expectedSessionId ?? e.sessionId)) ? o.sessionId : e.sessionId; const u = e.adoptOperation ? getGatewayContextResolver(e.adoptOperation) : Object.hasOwn(e, "resolveGatewayContext") ? e.resolveGatewayContext : getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext; let d = e.expectedSessionId; const f = getAgentEventLifecycleGeneration(); const p = e.rotationEvidence ?? createReplyTurnRotationEvidence({ sessionKey: e.sessionKey, controller: r, expectedActiveOperations: e.expectedActiveOperations, activeAtAdmission: o }); const m = e.waitTimeoutMs ?? (e.kind === "queued_followup" ? 15e3 : void 0); let h; let g; let _ = false; let v = true; let y; function rejectSessionChange(t = `Session "${e.sessionKey}" changed while starting work. Retry.`) { rejectLifecycleInvalidatedWork({ kind: e.kind, message: t, transientSessionChange: true }); } const assertDatabaseOwnerCurrent = (t) => { if (t && e.expectedDatabaseIncarnation !== void 0 && t.incarnation !== e.expectedDatabaseIncarnation || h && (!h.isCurrent() || t && t.incarnation !== h.incarnation)) { const n = t?.release(); if (n) { g = n; n.catch(() => {}); } rejectSessionChange(`Session store for "${e.sessionKey}" changed while starting work. Retry.`); } }; try { while (true) { if (e.upstreamAbortSignal?.aborted) return { status: "skipped", reason: "aborted" }; const o = !e.storePath ? p.takeStorelessRotation() : void 0; if (o) { if (d && !o.sessionIds.has(d)) return { status: "skipped", reason: "lifecycle-invalidated" }; l = o.sessionId; d = d ? o.sessionId : void 0; } if (isReplyRunSuccessorAdmissionBlocked(i)) { const t = await a.barrier({ phase: "successor-barrier", timeoutMs: e.kind === "visible" ? null : m, sessionId: l }); if (!t.settled) return { status: "skipped", reason: e.upstreamAbortSignal?.aborted ? "aborted" : "active-run" }; p.recordBarrierSources(t.sources); continue; } const g = evaluateTurnAdmission(r, { kind: e.kind, sessionKey: e.sessionKey, registeredEntry: sessionControllers.get(r.id), claim: e.mailboxClaim }); if (!g.admitted && g.reason === "followup-barrier") { if (e.storePath && !h) h = (await loadSessionEntryForAdmission({ agentId: e.agentId, storePath: e.storePath, sessionKey: e.sessionKey, readConsistency: "latest" }, { signal: e.upstreamAbortSignal, assertCurrent: () => e.assertRequestCurrent?.() })).databaseClaim; const t = await a.barrier({ phase: "followup-barrier", timeoutMs: m ?? 15e3, sessionId: l }); if (!t.settled) return { status: "skipped", reason: isAbortSignalAborted(e.upstreamAbortSignal) ? "aborted" : "active-run" }; if (h && !h.isCurrent()) return { status: "skipped", reason: "lifecycle-invalidated" }; p.recordBarrierSources(t.sources); continue; } if (!g.admitted && g.reason === "waiting-inputs") { if (e.waitForActive === false) return { status: "skipped", reason: "active-run" }; if (e.kind !== "visible" && m !== void 0) y ??= Date.now() + m; if (!await a.inputs(y)) return { status: "skipped", reason: e.upstreamAbortSignal?.aborted ? "aborted" : "active-run" }; continue; } y = void 0; const b = e.storePath ? p.observeAdmission() : void 0; try { const a = e.storePath; let o; let m; let g = false; const y = a ? await beginSessionEffect({ agentId: e.agentId, scope: a, isSettling: () => o !== void 0 && (o.result !== null || hasCommittedReplyOperationOutcome(o)), getAbortReason: () => o?.abortSignal.reason, resolveGatewayContext: u, identities: [e.sessionKey], storeWriterIdentities: parseAgentSessionKey(e.sessionKey) && normalizeStoreSessionKey(e.sessionKey) === e.sessionKey ? [e.sessionKey] : void 0, signal: e.upstreamAbortSignal, onInterrupt: (t) => { g = true; if (isAgentRunRestartAbortReason(t)) o?.abortForRestart(); else o?.abortByUser(); e.onLifecycleInterrupt?.(); }, assertAllowed: async (n) => { assertDatabaseOwnerCurrent(); const assertCurrent = () => { e.assertRequestCurrent?.(); t?.assertCurrent(); assertDatabaseOwnerCurrent(); if (!v || g || f !== getAgentEventLifecycleGeneration()) throw new SessionWorkStartChangedError("Session changed while waiting for state admission."); }; const r = await loadSessionEntryForAdmission({ agentId: e.agentId, storePath: a, sessionKey: e.sessionKey, readConsistency: "latest" }, { signal: n, assertCurrent, onRegistryChange: e.onDatabaseRegistration }); try { if (!v || g || e.upstreamAbortSignal?.aborted) throw new SessionWorkStartChangedError("Session changed during state admission."); e.assertRequestCurrent?.(); } catch (e) { await r.databaseClaim.release(); throw e; } assertDatabaseOwnerCurrent(r.databaseClaim); const i = h; h = r.databaseClaim; await i?.release(); n.throwIfAborted(); assertCurrent(); const o = r.entry; m = o; if (d && !o) rejectSessionChange(`Session "${e.sessionKey}" was deleted while starting work. Retry.`); b?.recordCompletions(); const s = p.hasExpectedSessionRotation({ expectedSessionId: d, sessionId: o?.sessionId, databaseIdentity: h?.identity }); if (d && o?.sessionId !== d && !s) rejectSessionChange(); if (s) d = o?.sessionId; const c = resolveSessionWorkStartBlock(e.sessionKey || l, o, { allowPendingWorkspace: t ? true : void 0, providerReviewAcknowledgment: e.providerReviewAcknowledgment }); if (c) rejectLifecycleInvalidatedWork({ kind: e.kind, message: c.message, error: c }); l = o?.sessionId ?? l; e.captureRunSelection?.(); } }) : void 0; try { if (isReplyRunSuccessorAdmissionBlocked(i)) throw new ReplyRunSuccessorAdmissionBlockedError(e.sessionKey); if (g || e.upstreamAbortSignal?.aborted) rejectSessionChange(); assertDatabaseOwnerCurrent(); if (b?.changed()) throw new ReplyOperationChangedDuringAdmissionError(); if (!a) e.captureRunSelection?.(); if (e.adoptOperation) { e.adoptOperation.updateSessionKey(e.sessionKey, e.agentId, e.mailboxClaim); o = e.adoptOperation; } else { o = createReplyOperation({ mailboxClaim: e.mailboxClaim, target: e.storePath ? captureSessionTarget({ storeScope: e.storePath, sessionKey: e.sessionKey, incarnation: l, agentId: e.agentId }) : void 0, sessionKey: e.sessionKey, sessionId: l, agentId: e.agentId, turnKind: e.kind, resetTriggered: e.resetTriggered, routeThreadId: e.routeThreadId, originatingLeafEntryId: e.originatingLeafEntryId, upstreamAbortSignal: e.upstreamAbortSignal }); bindGatewayContextResolver(o, u); } } catch (t) { if (t instanceof ReplyRunAlreadyActiveError && y && e.retainLifecycleAdmissionOnActive) return { status: "skipped", reason: "active-run", activeOperation: r.active, ...m ? { sessionEntry: m } : {}, lifecycleAdmission: y }; y?.release(); throw t instanceof ReplyRunLifecycleAdmissionBlockedError ? new ReplyRunLifecycleAdmissionBlockedError(e.sessionKey, h?.incarnation) : t; } bindReplyAdmissionRelease({ operation: o, admission: y, databaseClaim: h, sessionId: l, sessionKey: e.sessionKey, workSignal: n }); if (s) { c = true; runAfterReplyOperationClear(o, s); } _ = true; return { status: "owned", operation: o, databaseClaim: h, ...m ? { sessionEntry: m } : {} }; } catch (t) { if (e.upstreamAbortSignal?.aborted) return { status: "skipped", reason: "aborted" }; if (t instanceof QueuedFollowupLifecycleInvalidatedError) return { status: "skipped", reason: "lifecycle-invalidated", error: t.cause }; if (t instanceof ReplyOperationChangedDuringAdmissionError) { if (!p.hasCurrentRotationEvidence()) rejectLifecycleInvalidatedWork({ kind: e.kind, message: `Session "${e.sessionKey}" changed while starting work. Retry.`, transientSessionChange: true }); continue; } if (t instanceof ReplyRunSuccessorAdmissionBlockedError) continue; if (t instanceof ReplyRunFollowupAdmissionBlockedError) { const t = await waitForReplyRunFollowupAdmission(i, m ?? 15e3, { signal: e.upstreamAbortSignal }); if (!t.settled) return { status: "skipped", reason: e.upstreamAbortSignal?.aborted ? "aborted" : "active-run" }; p.recordBarrierSources(t.sources); continue; } if (!(t instanceof ReplyRunAlreadyActiveError)) throw t; const n = r.active; if (e.kind === "visible" && expireVisibleStaleOperation(n)) continue; if (e.waitForActive === false) return { status: "skipped", reason: "active-run", activeOperation: n }; const a = e.kind === "visible" ? resolveVisibleActiveWaitMs(n) : m; const o = n ? lifecycleAdmissionByOperation.get(n)?.databaseIdentity : void 0; if (!await waitForSessionRunIdle(i, a, { signal: e.upstreamAbortSignal })) { if (e.kind === "visible" && !e.upstreamAbortSignal?.aborted) { const e = r.active; expireVisibleStaleOperation(e ?? n); continue; } return { status: "skipped", reason: e.upstreamAbortSignal?.aborted ? "aborted" : "active-run", activeOperation: n }; } if (n) p.recordCompletedOperation(n, o); } finally { b?.dispose(); } } } finally { v = false; if (!c) s?.(); if (!_) try { await h?.release(); } finally { await g; } } } //#endregion //#region src/auto-reply/reply/transcript-followup-run.ts /** Internal continuations reuse the transcript, not the source turn's admission. */ function buildTranscriptFollowupRun(e, t) { const n = e.queuedFollowupReplyDisposition; return { ...e, sessionPrincipalTurn: e.sessionPrincipalTurn ?? (!e.run.scheduledAutomation && !isCronSessionKey(e.run.sessionKey ?? "") && !isCronExecutionInputProvenance(e.run.inputProvenance) && !resolveRequesterPrincipalKey({ requesterOrigin: e.run.requesterOrigin }) && !requesterCreatorProfileId(e.run.requesterOrigin)), prompt: formatSystemTurnPrompt(t.prompt), disableCollectBatching: true, enqueuedAt: Date.now(), transcriptPrompt: void 0, userTurnTranscriptRecorder: void 0, sourceTurnId: void 0, currentInboundContext: void 0, images: void 0, imageOrder: void 0, media: void 0, controllerInput: void 0, controllerClaim: void 0, turnAdoptionLifecycle: void 0, replyOperationRunStates: void 0, onQueueDisposition: void 0, queuedFollowupReplyDisposition: n?.kind === "deliver" ? { kind: "deliver", deliver: n.deliver.createSourceRetry?.() ?? n.deliver } : n, run: { ...e.run, inputProvenance: { kind: "internal_system", sourceTool: t.sourceTool }, suppressNextUserMessagePersistence: true, skillLibraryAuthoring: expireSkillLibraryAuthoring(e.run.skillLibraryAuthoring, t.expiredSkillAuthoringMessage) } }; } /** * The source grant cannot authorize a replacement turn. Keep a personal-only * expired grant so Workshop cannot fall back to wider workspace authoring. */ function expireSkillLibraryAuthoring(e, t) { return e && { target: "personal", defaultTarget: "personal", multipleProfiles: e.multipleProfiles, bind: () => {}, invoke: async () => { throw new SkillLibraryError("AUTHORITY_EXPIRED", t); } }; } //#endregion //#region src/auto-reply/reply/stalled-turn-recovery.ts const STALLED_TURN_NOTICE_TEXT = "⚠️ This turn was interrupted because it stopped making progress. Please try again."; const RATE_LIMITED_TURN_NOTICE_TEXT = "⚠️ This turn was stopped while the model provider was rate-limiting requests. Please try again in a few minutes."; /** Last-resort feedback once no continuation can answer a stalled turn. */ function resolveStalledTurnNoticeText(e) { return e?.staleExpiryReason === "rate_limited" ? RATE_LIMITED_TURN_NOTICE_TEXT : STALLED_TURN_NOTICE_TEXT; } const STALLED_TURN_GUIDANCE = "Your previous turn stopped making progress and was stopped before you replied, so the user's request from that turn is still unanswered. Answer it now, together with any newer message, from what the transcript already contains. Keep further tool use to a minimum, do not repeat actions that already ran, and briefly say what you could not verify."; /** A stale watchdog expired this operation before it delivered output: the user saw nothing. */ function isReplyOperationStalledBeforeOutput(e) { return e?.result?.kind === "failed" && !e.sourceReplyDelivered && e.result.code === "run_stalled" && (e.staleExpiryReason === "no_activity" || e.staleExpiryReason === "rate_limited" || e.staleExpiryReason === "stuck_recovery"); } /** Builds the one recovery run that answers a stalled turn over its persisted transcript. */ function buildStalledTurnRecoveryRun(e, t) { return { ...buildTranscriptFollowupRun(e, { prompt: t ?? "Your previous turn stopped making progress and was stopped before you replied, so the user's request from that turn is still unanswered. Answer it now, together with any newer message, from what the transcript already contains. Keep further tool use to a minimum, do not repeat actions that already ran, and briefly say what you could not verify.", sourceTool: "stalled-turn-recovery", expiredSkillAuthoringMessage: "Skill authoring is unavailable while recovering an interrupted turn. Send a fresh message requesting the change." }), summaryLine: "stalled-turn-recovery", stalledTurnRecovery: true, abortSignal: void 0 }; } //#endregion //#region src/auto-reply/reply/reply-run-finalization-lease.ts /** Delivery retains work on the operation's sole watchdog, never a parallel lease. */ function beginReplyOperationFinalizationWork(e, t) { return e.watchdog.beginFinalizationWork(t); } //#endregion //#region src/auto-reply/reply/commentary-progress-owner.ts /** Freezes and registers one commentary owner for the current agent turn. */ async function resolveTurnCommentaryProgressOwner(e) { const t = e.commentaryPayloadsEnabled ? e.options?.shouldDeliverCommentaryPayloads : void 0; if (e.options?.onVerboseProgressVisibilityAsync) { const n = t ? await e.resolveVerboseProgressVisibilityAsync() : void 0; await e.options.onVerboseProgressVisibilityAsync(n === void 0 ? e.resolveVerboseProgressVisibilityAsync : async () => n); } else if (e.options?.onVerboseProgressVisibility) { warnPluginSdkDeprecation({ family: "reply-visibility", method: "onVerboseProgressVisibility", replacement: "onVerboseProgressVisibilityAsync with awaited visibility predicates" }); const n = t ? e.resolveVerboseProgressVisibility() : void 0; e.options.onVerboseProgressVisibility(n === void 0 ? e.resolveVerboseProgressVisibility : () => n); } const n = e.commentaryPayloadsEnabled && (t?.() ?? true); return { commentaryPayloadsEnabled: n, draftOwnsCommentaryProgress: e.commentaryPayloadsEnabled && t !== void 0 && !n }; } //#endregion export { isReplyOperationStalledBeforeOutput as a, expireSkillLibraryAuthoring as c, runWithReplyOperationLifecycleAdmission as d, createReplyTurnAdmissionWaiter as f, buildStalledTurnRecoveryRun as i, admitReplyTurn as l, beginReplyOperationFinalizationWork as n, resolveStalledTurnNoticeText as o, STALLED_TURN_GUIDANCE as r, buildTranscriptFollowupRun as s, resolveTurnCommentaryProgressOwner as t, createReplyTurnRotationEvidence as u };