openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,969 lines • 96.1 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.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 { o as normalizeModelRef } from "./model-ref-shared-DqE2RqZv.mjs";
import { i as parseModelCatalogRef } from "./model-catalog-refs-Bk2MNoCv.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as getProcessGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-state-BmYo9Q7A.mjs";
import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { g as resolveAdmittedRunActiveAssertion, i as bindOperatorModelExecution, p as readAdmittedRunOperatorAuthority, r as assertOperatorModelAllowed } from "./admitted-run-context-D3Jvk_f_.mjs";
import { f as recordSessionHumanDirectMessage } from "./session-state-events-ChAYnzQG.mjs";
import { X as captureSessionTarget, Z as sessionTargetOwnersMatch } from "./session-controller.state-BApgK0mV.mjs";
import { C as trackSessionControllerSourceWork, L as getCurrentSessionControllerClaim, R as getCurrentSessionControllerOwner, i as runSessionMutation } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { i as captureSessionControllerStop } from "./session-controller.stop-BqKrTY7V.mjs";
import { a as toAcpRuntimeError, n as AcpRuntimeError, o as withAcpRuntimeErrorBoundary, r as formatAcpErrorChain } from "./errors-DGA2X_Nu.mjs";
import { a as identityHasStableSessionId, c as resolveRuntimeHandleIdentifiersFromIdentity, i as identityEquals, l as resolveRuntimeResumeSessionId, n as createIdentityFromHandleEvent, o as isSessionIdentityPending, r as createIdentityFromStatus, s as mergeSessionIdentity, t as createIdentityFromEnsure, u as resolveSessionIdentityFromMeta } from "./session-identity-BhobFDyP.mjs";
import "./errors-C4nx2HUe.mjs";
import { n as resolveSessionStorePathForAcp } from "./session-meta-store-X3_cjz74.mjs";
import { a as hasLegacyAcpIdentityProjection, c as requireReadySessionMeta, d as resolveAcpSessionTarget, f as resolveStoredAcpSession, i as createUnsupportedControlError, l as resolveAcpAgentFromSessionKey, n as assertCurrentAcpActor, o as isSupersededActorError, r as createSupersededActorError, s as normalizeAcpErrorCode, t as acpSessionActorKey, u as resolveAcpSessionResolutionError } from "./manager.utils-CiSXdCbv.mjs";
import { r as markAcpTurnActive } from "./active-turns-DUjJqsXZ.mjs";
import { i as requireAcpRuntimeBackend, t as getAcpRuntimeBackend } from "./registry-C2WH06NS.mjs";
import { s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import { n as matchesAcpSessionRuntimeLocator, r as resolveAcpSessionControlOwner, t as matchesAcpSessionControlBinding } from "./session-control-owner-DDgpDoxT.mjs";
import { t as assertAcpSessionMutationEntry } from "./session-meta-entry.kernel-DN2jvKpc.mjs";
import { t as withSessionTurn } from "./session-controller.admission-DDiE4tNx.mjs";
import { n as recordSubagentTerminalState } from "./subagent-terminal-state-1K9x3dH6.mjs";
import { a as buildRuntimeConfigOptionPairs, b as validateRuntimeOptionPatch, c as isThinkingConfigKey, f as reconcileAcceptedRuntimeOptions, g as validateRuntimeConfigOptionInput, h as runtimeOptionsEqual, i as resolveTurnTimeoutMs, l as mergeRuntimeOptions, m as resolveRuntimeOptionsFromMeta, n as awaitTurnWithTimeout, o as buildRuntimeControlSignature, p as resolveRuntimeConfigOptionKey, r as cleanupTimedOutTurn, s as inferRuntimeOptionPatchFromConfigOption, t as ACP_TURN_TIMEOUT_DETAIL_CODE, u as normalizeRuntimeOptions, v as validateRuntimeModeInput } from "./manager.turn-timeout-BI2AZt1S.mjs";
import { n as readAcpSessionEntryAsync } from "./session-meta-read-BC53uDBL.mjs";
import { a as upsertAcpSessionMetaForControl, i as upsertAcpSessionMeta, o as listAcpSessionEntries, r as prepareAcpSessionControlRead, t as readAcpSessionEntry } from "./session-meta-CupK_5Fp.mjs";
//#region src/sessions/session-controller.producer-custody.ts
const producersByOwner = /* @__PURE__ */ new WeakMap();
/** Individual producer custody can borrow a turn without taking its parent's cancellation. */
function registerSessionControllerProducer(e) {
const t = producersByOwner.get(e.owner) ?? /* @__PURE__ */ new Set();
producersByOwner.set(e.owner, t);
const n = new AbortController();
const r = createDeferredCore();
r.promise.catch(() => {});
let i = false;
let a;
let o;
const s = {
target: e.target,
runInstance: e.runInstance,
signal: n.signal,
settled: r.promise,
cancel(e, t) {
if (i) return;
t?.assertCurrent();
if (!n.signal.aborted) {
o = t;
n.abort(e);
}
},
async revalidateCancellation() {
await o?.revalidate();
},
assertCancellationAllowed() {
o?.assertCurrent();
},
recordCancellationFailure(e) {
a ??= e;
},
retainCleanupForSources(e) {
for (const t of e) trackSessionControllerSourceWork(t, r.promise);
},
release() {
if (i) return;
i = true;
t.delete(s);
if (!t.size) producersByOwner.delete(e.owner);
if (a === void 0) r.resolve();
else r.reject(a);
}
};
t.add(s);
return s;
}
/** Capture before awaiting authority; later arrivals cannot enter this selection. */
function captureSessionControllerProducers(e) {
return [...producersByOwner.get(e.owner) ?? []].filter((t) => (!e.target || sessionTargetOwnersMatch(t.target, e.target) && t.target.sessionKey === e.target.sessionKey) && (!e.expectedRunId || t.runInstance.runId === e.expectedRunId) && (!e.expectedInstanceId || t.runInstance.instanceId === e.expectedInstanceId));
}
//#endregion
//#region src/acp/control-plane/manager.turn-stream.ts
async function consumeAcpTurnEvents(e) {
let t = null;
let n = false;
let r;
for await (const i of e.events) {
if (!e.eventGate.open) continue;
let a = i;
if (i.type === "done") {
r = i.status ?? (i.stopReason === "cancel" || i.stopReason === "cancelled" || i.stopReason === "manual-cancel" ? "cancelled" : "completed");
a = {
...i,
status: r
};
} else if (i.type === "error") t = new AcpRuntimeError(normalizeAcpErrorCode(i.code), normalizeOptionalString(i.message) || "ACP turn failed before completion.", i.detailCode ? { detailCode: i.detailCode } : void 0);
const o = i.type === "text_delta" || i.type === "tool_call" ? i : void 0;
if (o) n = true;
e.eventGate.pendingDelivery = Promise.resolve(o ? e.onOutputEvent?.(o) : void 0).then(() => e.onEvent?.(a));
try {
await e.eventGate.pendingDelivery;
} finally {
e.eventGate.pendingDelivery = void 0;
}
}
if (e.eventGate.open && t) throw t;
return {
sawOutput: n,
terminalStatus: r
};
}
function waitForQueuedEvents() {
return new Promise((e) => {
setTimeout(() => e("pending"), 0);
});
}
/** A pre-submission cancellation has a normal terminal event, not a failed prompt. */
async function emitCancelledAcpTurn(e) {
await e?.({
type: "done",
status: "cancelled",
stopReason: "cancel"
});
return {
sawOutput: false,
terminalStatus: "cancelled"
};
}
async function consumeAcpTurnStream(e) {
if (e.turn.signal?.aborted) {
await e.onCancellation?.();
return await emitCancelledAcpTurn(e.onEvent);
}
if (e.onBeforePrompt) await e.onBeforePrompt();
if (e.turn.signal?.aborted) {
await e.onCancellation?.();
return await emitCancelledAcpTurn(e.onEvent);
}
if (e.runtime.startTurn) {
const t = e.runtime.startTurn.bind(e.runtime);
const { turn: n } = await runWithAgentToolSourceExecutionScope(e.source, async () => {
e.source?.();
return { turn: t(e.turn) };
});
let r = true;
let i = false;
const a = n.promptStarted?.then(async () => {
if (!r || !e.eventGate.open) return { kind: "prompt-start-closed" };
i = true;
try {
await e.onPromptStarted?.({ authoritative: true });
} catch (e) {
return {
kind: "prompt-start-error",
error: e
};
}
return { kind: "prompt-started" };
}, (e) => ({
kind: "prompt-start-error",
error: e
}));
const o = n.result.then(async (e) => {
r = false;
if (i) await a;
return {
kind: "result",
result: e
};
}, async (e) => {
r = false;
if (i) await a;
return {
kind: "result-error",
error: e
};
});
const s = consumeAcpTurnEvents({
events: n.events,
eventGate: e.eventGate,
onEvent: e.onEvent,
onOutputEvent: e.onOutputEvent
}).then((e) => ({
kind: "events",
outcome: e
}), async (e) => {
await n.cancel({ reason: "turn-events-error" }).catch(() => {});
await n.closeStream({ reason: "turn-events-error" }).catch(() => {});
await o;
return {
kind: "event-error",
error: e
};
});
if (a) {
const e = await Promise.race([a, o]);
if (e.kind === "prompt-start-error") {
await n.closeStream({ reason: "turn-prompt-start-error" }).catch(() => {});
const t = await o;
if (t.kind === "result" && t.result.status === "completed") throw e.error;
}
} else await e.onPromptStarted?.({ authoritative: false });
const c = await Promise.race([s, o]);
if (c.kind === "event-error") throw c.error;
const l = c.kind === "events" ? await o : c;
if (l.kind === "result-error") {
await n.closeStream({ reason: "turn-result-error" }).catch(() => {});
throw l.error;
}
const u = l.result;
let d = c.kind === "events" ? c.outcome : null;
let f = false;
while (!d) {
await e.eventGate.pendingDelivery?.catch(() => {});
let t = await Promise.race([s, waitForQueuedEvents()]);
if (t === "pending") {
if (e.eventGate.pendingDelivery) continue;
await n.closeStream({ reason: `turn-result-${u.status}` }).catch(() => {});
f = true;
t = await s;
}
if (t.kind === "event-error") throw t.error;
d = t.outcome;
}
if (u.status !== "completed" && !f) await n.closeStream({ reason: `turn-result-${u.status}` }).catch(() => {});
const { eventGate: p, onEvent: m } = e;
if (p.open) {
if (u.status === "completed" || u.status === "cancelled") await m?.({
type: "done",
status: u.status,
...u.stopReason ? { stopReason: u.stopReason } : {}
});
else await m?.({
type: "error",
code: normalizeAcpErrorCode(u.error.code),
...u.error.detailCode ? { detailCode: u.error.detailCode } : {},
message: normalizeOptionalString(u.error.message) || "ACP turn failed before completion.",
...u.error.retryable === void 0 ? {} : { retryable: u.error.retryable }
});
}
if (u.status === "failed") throw new AcpRuntimeError(normalizeAcpErrorCode(u.error.code), normalizeOptionalString(u.error.message) || "ACP turn failed before completion.", u.error.detailCode ? { detailCode: u.error.detailCode } : void 0);
return {
sawOutput: d.sawOutput,
terminalStatus: u.status
};
}
const t = startLegacyTurnEvents(e.runtime, e.turn, e.source);
await e.onPromptStarted?.({ authoritative: false });
return await consumeAcpTurnEvents({
events: t,
eventGate: e.eventGate,
onEvent: e.onEvent,
onOutputEvent: e.onOutputEvent
});
}
async function* startLegacyTurnEvents(e, t, n) {
let r;
try {
const i = await runWithAgentToolSourceExecutionScope(n, async () => {
n?.();
const i = e.runTurn(t)[Symbol.asyncIterator]();
r = i;
return {
iterator: i,
next: await i.next()
};
});
let a = i.next;
while (!a.done) {
yield a.value;
a = await i.iterator.next();
}
r = void 0;
} finally {
await r?.return?.();
}
}
//#endregion
//#region src/acp/control-plane/manager.cancel-session.ts
/** Selects cancellation targets before awaiting authority, excluding later arrivals. */
async function runManagerCancelSession(e) {
e.assertActive?.();
const t = resolveAcpSessionTarget(e);
const { storePath: n, storeSessionKey: r } = resolveSessionStorePathForAcp({
cfg: e.cfg,
...t
});
const i = captureSessionTarget({
storeScope: n,
sessionKey: r,
agentId: t.agentId
});
const a = e.expectedRunId?.trim();
const o = e.expectedInstanceId?.trim();
const s = e.expectedOwnerKey?.trim();
const c = captureSessionControllerProducers({
owner: e.producerOwner,
target: i,
expectedRunId: a,
expectedInstanceId: o
});
if (c.length) {
await cancelManagerProducers({
...e,
...t,
expectedOwnerKey: s,
producers: c
});
return;
}
if (a || o) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP task is no longer the active run.");
await runSessionMutation({
target: i,
policy: "allow-live",
assertCurrent: e.assertActive,
run: async () => {
const n = captureSessionControllerStop({ targets: [i] });
if (n.operations.length || n.inputs.some((e) => e.claim && !e.claim.released)) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP session has controller-owned work; cancel it through Stop.");
await cancelIdleManagerSession({
...e,
...t,
expectedOwnerKey: s
});
}
});
}
/** Cancels only the invocation snapshot, retaining its authority guard through backend effects. */
async function cancelManagerProducers(e) {
e.assertActive?.();
const t = e.expectedOwnerKey ? await e.prepareSessionControlRead({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId
}) : void 0;
const assertCurrent = () => {
t?.assertCurrent(e.cfg);
e.assertActive?.();
};
const revalidate = async () => {
assertCurrent();
if (t) {
const n = await t.readCurrent(e.cfg);
assertCurrent();
if (!n.session?.acp || resolveAcpSessionControlOwner(n.entry) !== e.expectedOwnerKey) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP task owner could not be verified.");
}
};
try {
await revalidate();
const t = (await Promise.allSettled(e.producers.map(async (t) => {
t.cancel(e.reason, {
revalidate,
assertCurrent
});
await t.settled;
}))).find((e) => e.status === "rejected");
if (t?.status === "rejected") throw t.reason;
} finally {
t?.release();
}
}
/** Sends ACP cancel to a backend that has no OpenClaw turn, such as a persistent runtime. */
async function cancelIdleManagerSession(e) {
e.assertActive?.();
const t = {
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId
};
const readCurrentOwner = async (t) => {
const n = await t.readCurrent(e.cfg);
t.assertCurrent(e.cfg);
if (!n.session?.acp || e.expectedOwnerKey && resolveAcpSessionControlOwner(n.entry) !== e.expectedOwnerKey) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP task owner could not be verified.");
return n;
};
await e.withSessionActor(e, async (n) => {
const r = await e.prepareSessionControlRead(t);
let i;
const assertTargetCurrent = () => {
r.assertCurrent(e.cfg);
r.assertAcpCurrent?.(e.cfg, i);
if (!n()) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP session actor was replaced.");
};
const assertAdmission = () => {
assertTargetCurrent();
e.assertActive?.();
};
try {
assertAdmission();
if (e.expectedOwnerKey) {
await readCurrentOwner(r);
assertAdmission();
}
const a = await e.resolveSession({
...t,
assertCurrent: assertAdmission
});
assertAdmission();
const o = requireReadySessionMeta(a);
const { entry: s, constraint: c } = await readCurrentOwner(r);
assertAdmission();
const l = resolveAcpSessionControlOwner(s);
const { runtime: u, handle: d } = await e.ensureRuntimeHandle({
...t,
assertActive: assertAdmission,
meta: o,
isCurrentActor: n,
readAcpControl: () => c,
assertMetadataCommitAllowed: (t) => {
r.assertAcpCurrent?.(e.cfg, t);
},
expectedControlBinding: s && l ? {
sessionId: s.sessionId,
lifecycleRevision: s.lifecycleRevision,
sessionStartedAt: s.sessionStartedAt,
ownerKey: l
} : void 0
});
const f = {
backend: d.backend,
runtimeSessionName: d.runtimeSessionName
};
i = f;
const readCurrentRuntime = async () => {
const e = await readCurrentOwner(r);
if (!matchesAcpSessionRuntimeLocator(e.session.acp, f)) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP runtime locator changed before cancellation.");
return e.constraint ? {
...e.constraint,
runtimeLocator: f
} : void 0;
};
let p;
try {
await readCurrentRuntime();
assertAdmission();
try {
await u.cancel({
handle: d,
reason: e.reason
});
} catch (e) {
p = toAcpRuntimeError({
error: e,
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "ACP cancel failed before completion."
});
}
const r = await readCurrentRuntime();
assertTargetCurrent();
await e.setSessionState({
...t,
state: p ? "error" : "idle",
lastError: p?.message,
clearLastError: !p,
isCurrentActor: n,
assertCurrent: assertTargetCurrent,
acpControl: r
});
} catch (r) {
if (n() && e.runtimeHandles.get(t)?.handle === d) e.runtimeHandles.clearIfHandleMatches({
...t,
handle: d
});
throw r;
}
if (p) throw p;
} finally {
r.release();
}
});
}
/** Aborts and deduplicates runtime cancellation for one active manager turn. */
async function cancelManagerActiveTurn(e) {
if (!e.activeTurn.cancelPromise) {
let t = false;
const n = withAcpRuntimeErrorBoundary({
run: async () => {
await (e.revalidate?.() ?? Promise.resolve());
e.assertCurrent?.();
e.activeTurn.abortController.abort();
t = true;
await e.activeTurn.runtime.cancel({
handle: e.activeTurn.handle,
reason: e.reason
});
},
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "ACP cancel failed before completion."
});
e.activeTurn.cancelPromise = n;
n.catch(() => {
if (!t && e.activeTurn.cancelPromise === n) e.activeTurn.cancelPromise = void 0;
});
}
await e.activeTurn.cancelPromise;
}
/** Persists a queued cancellation before publishing its terminal event. */
async function publishManagerCancelledTurnBeforeStart(e) {
const { input: t, target: n, ownsRunTerminal: r, assertActorCurrent: i } = e;
const a = await e.prepareSessionControlRead({
cfg: t.cfg,
...n,
assertCurrent: i
});
const assertCurrent = () => {
i();
a.assertCurrent(t.cfg);
a.assertAcpCurrent?.(t.cfg);
};
try {
assertCurrent();
if (t.mode === "prompt" && r) {
const { entry: e, constraint: r } = a.initialRead;
const i = normalizeOptionalString(e?.spawnedBy) ?? normalizeOptionalString(e?.parentSessionKey);
if (i) await recordSubagentTerminalState({
childSessionKey: n.sessionKey,
agentId: n.agentId,
runId: t.requestId,
requesterSessionKey: i,
outcomeStatus: "cancelled"
}, assertCurrent, r);
}
const e = await a.readCurrent(t.cfg);
assertCurrent();
if (!e.session.acp) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP metadata changed before cancellation publication.");
await emitCancelledAcpTurn(t.onEvent);
} finally {
a.release();
}
}
//#endregion
//#region src/acp/control-plane/manager.runtime-owner.ts
/** Old backends can isolate qualified keys, but silently ignore an added owner field. */
function assertAcpRuntimeOwnerSupport(e, t) {
if (!parseAgentSessionKey(t.sessionKey) && e.ownerAwareSessions !== 1) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", "This ACP backend cannot isolate bare session keys by owner. Upgrade the backend to support ownerAwareSessions version 1.", { detailCode: "SESSION_OWNER_UNSUPPORTED" });
}
/** These operator repairs must never become resume recovery, failover, or a successful reset. */
function isAcpOwnerRepairRequired(e) {
let t = e;
for (let e = 0; t instanceof Error && e < 8; e++) {
const e = "detailCode" in t ? t.detailCode : void 0;
if (e === "SESSION_OWNER_MIGRATION_REQUIRED" || e === "SESSION_OWNER_UNSUPPORTED") return true;
t = t.cause;
}
return false;
}
function persistedAcpRuntimeHandle(e, t) {
const n = resolveSessionIdentityFromMeta(t);
return {
sessionKey: e.sessionKey,
agentId: e.agentId,
backend: t.backend,
runtimeSessionName: t.runtimeSessionName,
cwd: t.cwd,
acpxRecordId: n?.acpxRecordId,
...resolveRuntimeHandleIdentifiersFromIdentity(n)
};
}
//#endregion
//#region src/acp/control-plane/manager.runtime-resume-state.ts
function isRecoverableManagerAcpxExitError(e) {
return /^acpx exited with (code \d+|signal [a-z0-9]+)/i.test(e.trim());
}
const SESSION_RESUME_REQUIRED_DETAIL_CODE = "SESSION_RESUME_REQUIRED";
function isRecoverableMissingManagerPersistentSessionError(e) {
let t = e;
for (let e = 0; t && e < 8; e += 1) {
if (t.detailCode === SESSION_RESUME_REQUIRED_DETAIL_CODE) return true;
t = t.cause;
}
return false;
}
/** Prepares a one-time fresh-handle retry only before authoritative prompt submission. */
async function prepareFreshManagerRuntimeHandleRetry(e) {
if (!e.isCurrentActor() || isAcpOwnerRepairRequired(e.error) || e.attempt > 0 || e.promptStarted || e.sawTurnOutput) return false;
if (isRecoverableManagerAcpxExitError(e.error.message)) {
e.runtimeHandles.clear(e);
logVerbose(`acp-manager: retrying ${e.sessionKey} with a fresh runtime handle after early turn failure: ${e.error.message}`);
return true;
}
if (!e.runtime || !e.meta || e.meta.mode !== "persistent" || !isRecoverableMissingManagerPersistentSessionError(e.error)) return false;
if (e.runtime.prepareFreshSession) try {
await e.runtime.prepareFreshSession({
persistedHandle: persistedAcpRuntimeHandle(e, e.meta),
sessionKey: e.sessionKey,
agentId: e.agentId
});
if (!e.isCurrentActor()) return false;
} catch (t) {
if (isAcpOwnerRepairRequired(t)) throw t;
logVerbose(`acp-manager: failed preparing a fresh persistent session for ${e.sessionKey}: ${formatErrorMessage(t)}`);
return false;
}
if (!await clearPersistedRuntimeResumeState({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
writeSessionMeta: e.writeSessionMeta,
isCurrentActor: e.isCurrentActor
}) || !e.isCurrentActor()) return false;
e.runtimeHandles.clear(e);
logVerbose(`acp-manager: retrying ${e.sessionKey} with a fresh persistent session after missing backend resume target: ${e.error.message}`);
return true;
}
async function clearPersistedRuntimeResumeState(e) {
const t = Date.now();
if (!await e.writeSessionMeta({
assertCommitAllowed: e.assertCommitAllowed,
expectedControlBinding: e.expectedControlBinding,
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
isCurrentActor: e.isCurrentActor,
mutate: (n, r) => {
if (!e.isCurrentActor()) return;
if (!r || !n) return null;
const i = resolveSessionIdentityFromMeta(n);
if (!e.discardPersistentState && !i?.acpxSessionId && !i?.agentSessionId) return n;
const a = i ? {
state: "pending",
...i.acpxRecordId ? { acpxRecordId: i.acpxRecordId } : {},
source: i.source,
lastUpdatedAt: t
} : void 0;
return {
backend: n.backend,
agent: n.agent,
runtimeSessionName: n.runtimeSessionName,
...a ? { identity: a } : {},
mode: n.mode,
...n.runtimeOptions ? { runtimeOptions: n.runtimeOptions } : {},
...n.cwd ? { cwd: n.cwd } : {},
state: e.discardPersistentState ? "idle" : n.state,
lastActivityAt: t,
...!e.discardPersistentState && n.lastError ? { lastError: n.lastError } : {}
};
},
...e.discardPersistentState ? { failOnError: true } : {}
})) {
if (!e.discardPersistentState) logVerbose(`acp-manager: unable to clear persisted runtime resume state for ${e.sessionKey}`);
return false;
}
return true;
}
/** Clears persisted runtime resume identifiers while preserving the manager session shell. */
async function discardPersistedManagerRuntimeState(e) {
await clearPersistedRuntimeResumeState({
...e,
discardPersistentState: true
});
}
/** Every skipped reset records why, so retained backend history is visible to the caller. */
async function tryPrepareFreshManagerRuntimeSession(e) {
const t = (e.meta.backend || e.cfg.acp?.backend || "").trim();
try {
const n = e.deps.getRuntimeBackend(t || void 0);
if (!n) {
if (e.missingBackendError) throw toErrorObject(e.missingBackendError, "Non-Error thrown");
logVerbose(`${e.logPrefix}: fresh-session preparation skipped for ${e.sessionKey}: ACP backend "${t || "(default)"}" is not registered`);
return;
}
assertAcpRuntimeOwnerSupport(n.runtime, e);
if (!n.runtime.prepareFreshSession) {
logVerbose(`${e.logPrefix}: fresh-session preparation skipped for ${e.sessionKey}: ACP backend "${n.id}" does not support prepareFreshSession`);
return;
}
await n.runtime.prepareFreshSession({
persistedHandle: persistedAcpRuntimeHandle(e, e.meta),
sessionKey: e.sessionKey,
agentId: e.agentId
});
} catch (t) {
if (isAcpOwnerRepairRequired(t)) throw t;
logVerbose(`${e.logPrefix}: unable to prepare fresh session for ${e.sessionKey}: ${formatErrorMessage(t)}`);
}
}
//#endregion
//#region src/acp/control-plane/manager.close-session.ts
async function runManagerCloseSession(e) {
const { input: t, sessionKey: n, agentId: r } = e;
const i = t.expectedControlBinding;
const assertCurrent = () => {
assertCurrentAcpActor(e.isCurrentActor(), n);
t.assertActive?.();
};
assertCurrent();
const a = await e.resolveSession({
cfg: t.cfg,
sessionKey: n,
agentId: r,
assertCurrent
});
assertCurrent();
const o = resolveAcpSessionResolutionError(a);
if (o) {
if (t.requireAcpSession ?? true) throw o;
return {
runtimeClosed: false,
metaCleared: false
};
}
const assertControlBinding = (e) => {
if (i && !matchesAcpSessionControlBinding(e, i)) throw createSupersededActorError(n);
};
const refreshControlBinding = async () => {
const i = await e.resolveSession({
cfg: t.cfg,
sessionKey: n,
agentId: r,
assertCurrent
});
assertCurrent();
assertControlBinding(i.kind === "ready" ? i.entry : void 0);
};
assertControlBinding(a.kind === "ready" ? a.entry : void 0);
const s = requireReadySessionMeta(a);
const c = resolveSessionIdentityFromMeta(s);
const l = t.discardPersistentState && c != null && !identityHasStableSessionId(c);
let u = false;
let d;
if (l) {
t.assertActive?.();
await tryPrepareFreshManagerRuntimeSession({
deps: e.deps,
cfg: t.cfg,
meta: s,
sessionKey: n,
agentId: r,
logPrefix: "acp close fast-reset"
});
assertCurrent();
e.runtimeHandles.clear(e);
} else try {
const { runtime: a, handle: o } = await e.ensureRuntimeHandle({
assertActive: assertCurrent,
expectedControlBinding: i,
cfg: t.cfg,
sessionKey: n,
agentId: r,
meta: s,
isCurrentActor: e.isCurrentActor
});
assertCurrentAcpActor(e.isCurrentActor(), n);
t.assertActive?.();
if (i) await refreshControlBinding();
assertCurrent();
await a.close({
handle: o,
reason: t.reason,
discardPersistentState: t.discardPersistentState
});
u = true;
assertCurrent();
e.runtimeHandles.clear(e);
} catch (a) {
const o = toAcpRuntimeError({
error: a,
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "ACP close failed before completion."
});
if (!e.isCurrentActor() || isSupersededActorError(o)) throw o;
t.assertActive?.();
if (!isAcpOwnerRepairRequired(o) && t.allowBackendUnavailable && (o.code === "ACP_BACKEND_MISSING" || o.code === "ACP_BACKEND_UNAVAILABLE" || t.discardPersistentState && o.code === "ACP_SESSION_INIT_FAILED" || t.discardPersistentState && o.code === "ACP_BACKEND_UNSUPPORTED_CONTROL" || isRecoverableManagerAcpxExitError(o.message))) {
if (i) await refreshControlBinding();
assertCurrent();
if (t.discardPersistentState) {
await tryPrepareFreshManagerRuntimeSession({
deps: e.deps,
cfg: t.cfg,
meta: s,
sessionKey: n,
agentId: r,
logPrefix: "acp close recovery",
missingBackendError: o
});
assertCurrent();
}
e.runtimeHandles.clear(e);
d = o.message;
} else throw o;
}
assertCurrent();
if (t.discardPersistentState && !t.clearMeta) await discardPersistedManagerRuntimeState({
assertCommitAllowed: assertCurrent,
expectedControlBinding: i,
cfg: t.cfg,
sessionKey: n,
agentId: r,
writeSessionMeta: e.writeSessionMeta,
isCurrentActor: e.isCurrentActor
});
assertCurrent();
const f = Boolean(t.clearMeta);
if (f) {
await e.writeSessionMeta({
assertCommitAllowed: assertCurrent,
expectedControlBinding: i,
cfg: t.cfg,
sessionKey: n,
agentId: r,
isCurrentActor: e.isCurrentActor,
mutate: () => null,
failOnError: true
});
assertCurrent();
}
return {
runtimeClosed: u,
runtimeNotice: d,
metaCleared: f
};
}
//#endregion
//#region src/acp/control-plane/manager.identity-reconcile.ts
async function reconcileManagerRuntimeSessionIdentifiers(e) {
const t = e.isCurrentActor ?? (() => true);
const assertCurrent = () => {
e.assertCurrent?.();
assertCurrentAcpActor(t(), e.sessionKey);
};
const n = e.revalidateControl?.();
let r = n ? await n || void 0 : void 0;
assertCurrent();
let i = e.runtimeStatus;
if (!i && e.runtime.getStatus) {
try {
i = await withAcpRuntimeErrorBoundary({
run: async () => await e.runtime.getStatus({ handle: e.handle }),
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not read ACP runtime status."
});
} catch (t) {
if (e.failOnStatusError || isAcpOwnerRepairRequired(t)) throw t;
assertCurrent();
logVerbose(`acp-manager: failed to refresh ACP runtime status for ${e.sessionKey}: ${String(t)}`);
return {
handle: e.handle,
meta: e.meta,
runtimeStatus: i
};
}
const t = e.revalidateControl?.();
r = t ? await t || void 0 : r;
assertCurrent();
}
const a = Date.now();
const o = resolveSessionIdentityFromMeta(e.meta);
const s = createIdentityFromHandleEvent({
handle: e.handle,
now: a
});
const c = mergeSessionIdentity({
current: o,
incoming: s,
now: a
}) ?? o;
const l = mergeSessionIdentity({
current: c,
incoming: createIdentityFromStatus({
status: i,
now: a
}),
now: a
}) ?? c;
const u = resolveRuntimeHandleIdentifiersFromIdentity(l);
const d = u.backendSessionId !== e.handle.backendSessionId || u.agentSessionId !== e.handle.agentSessionId;
const f = d ? {
...e.handle,
...u.backendSessionId ? { backendSessionId: u.backendSessionId } : {},
...u.agentSessionId ? { agentSessionId: u.agentSessionId } : {}
} : e.handle;
if (d) e.setCachedHandle(e, f);
if (!(!identityEquals(o, l) || hasLegacyAcpIdentityProjection(e.meta))) {
assertCurrent();
return {
handle: f,
meta: e.meta,
runtimeStatus: i
};
}
const projectMeta = (e) => ({
backend: e.backend,
agent: e.agent,
runtimeSessionName: e.runtimeSessionName,
...l ? { identity: l } : {},
mode: e.mode,
...e.runtimeOptions ? { runtimeOptions: e.runtimeOptions } : {},
...e.cwd ? { cwd: e.cwd } : {},
state: e.state,
lastActivityAt: a,
...e.lastError ? { lastError: e.lastError } : {}
});
const p = projectMeta(e.meta);
assertCurrent();
await e.writeSessionMeta({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
isCurrentActor: t,
assertCommitAllowed: assertCurrent,
acpControl: r,
mutate: (n, r) => {
if (!t()) return;
e.assertCurrent?.();
return r && n ? projectMeta(n) : null;
}
});
assertCurrent();
return {
handle: f,
meta: p,
runtimeStatus: i
};
}
//#endregion
//#region src/acp/control-plane/manager.runtime-handle-ensure.ts
async function ensureManagerRuntimeHandle(e) {
const t = {
backend: e.meta.backend,
runtimeSessionName: e.meta.runtimeSessionName
};
const n = e.isCurrentActor ?? (() => true);
const r = e.expectedControlBinding ? { ...e.expectedControlBinding } : void 0;
const assertCurrent = () => {
assertCurrentAcpActor(n(), e.sessionKey);
e.assertActive?.();
};
const assertControlBindingCurrent = async () => {
assertCurrent();
const t = await e.deps.loadSessionEntryAsync({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
clone: false,
assertCurrent
});
assertCurrent();
const n = e.readAcpControl?.();
if (n) {
assertAcpSessionMutationEntry(t?.entry, n.entry ?? null, void 0, "control read");
if (!t?.acp || resolveAcpSessionControlOwner(t.entry) !== n.ownerKey) throw createSupersededActorError(e.sessionKey);
}
if (t?.storeReadFailed || r && !matchesAcpSessionControlBinding(t?.entry, r)) throw createSupersededActorError(e.sessionKey);
};
assertCurrent();
const i = normalizeOptionalString(e.meta.agent) || resolveAcpAgentFromSessionKey(e.sessionKey);
const a = e.meta.mode;
const o = resolveRuntimeOptionsFromMeta(e.meta);
const { cwd: s, model: c, thinking: l } = o;
const u = (e.selectedBackend || e.meta.backend || e.cfg.acp?.backend || "").trim();
const d = e.deps.requireRuntimeBackend(u || void 0);
const f = d.runtime;
assertAcpRuntimeOwnerSupport(f, e);
const p = e.runtimeHandles.get(e);
if (p) {
const t = !u || p.backend === u;
const o = p.agent === i;
const c = p.mode === a;
const l = (p.cwd ?? "") === (s ?? "");
const d = e.runtimeHandles.handleMatchesMeta({
handle: p.handle,
meta: e.meta
});
const m = t && o && c && l && p.runtime === f && d && await e.runtimeHandles.isReusable({
sessionKey: e.sessionKey,
runtime: p.runtime,
handle: p.handle
});
assertCurrentAcpActor(n(), e.sessionKey);
e.assertActive?.();
if (r || e.readAcpControl?.()) await assertControlBindingCurrent();
if (m) {
assertCurrentAcpActor(n(), e.sessionKey);
return {
runtime: p.runtime,
handle: p.handle,
meta: e.meta
};
}
await e.runtimeHandles.close({
assertActive: e.assertActive,
sessionKey: e.sessionKey,
agentId: e.agentId,
reason: "runtime-handle-replaced",
expectedHandle: p.handle
});
assertCurrentAcpActor(n(), e.sessionKey);
}
const m = e.meta;
const h = resolveSessionIdentityFromMeta(m);
const g = m.backend === d.id;
const _ = g ? h : void 0;
const v = g ? persistedAcpRuntimeHandle(e, m) : void 0;
let y = _;
const b = a === "persistent" ? resolveRuntimeResumeSessionId(_) : void 0;
const x = a === "persistent" && _ != null && !identityHasStableSessionId(_);
const ensureSession = async (t) => {
if (r || e.readAcpControl?.()) await assertControlBindingCurrent();
assertCurrent();
const o = await withAcpRuntimeErrorBoundary({
run: async () => await f.ensureSession({
persistedHandle: v,
sessionKey: e.sessionKey,
agentId: e.agentId,
agent: i,
mode: a,
...t ? { resumeSessionId: t } : {},
...c ? { model: c } : {},
...l ? { thinking: l } : {},
cwd: s
}),
fallbackCode: "ACP_SESSION_INIT_FAILED",
fallbackMessage: "Could not initialize ACP session runtime."
});
try {
assertCurrent();
return o;
} catch (t) {
if (!n()) await closeSupersededRuntimeHandle({
runtime: f,
handle: o,
sessionKey: e.sessionKey
});
throw t;
}
};
let S;
if (x) {
if (r || e.readAcpControl?.()) await assertControlBindingCurrent();
assertCurrent();
await f.prepareFreshSession?.({
persistedHandle: v,
sessionKey: e.sessionKey,
agentId: e.agentId
});
assertCurrentAcpActor(n(), e.sessionKey);
}
if (b) try {
S = await ensureSession(b);
} catch (t) {
const r = toAcpRuntimeError({
error: t,
fallbackCode: "ACP_SESSION_INIT_FAILED",
fallbackMessage: "Could not initialize ACP session runtime."
});
if (!n()) throw r;
e.assertActive?.();
if (isAcpOwnerRepairRequired(r) || isSupersededActorError(r) || r.code !== "ACP_SESSION_INIT_FAILED") throw r;
logVerbose(`acp-manager: resume init failed for ${e.sessionKey}; retrying without persisted ACP session id: ${r.message}`);
if (y) {
const { acpxSessionId: e, agentSessionId: t, ...n } = y;
y = {
...n,
state: "pending"
};
}
S = await ensureSession();
}
else S = await ensureSession();
const C = Date.now();
const w = normalizeOptionalString(S.cwd) ?? s;
const T = {
...o,
...w ? { cwd: w } : {}
};
const E = createIdentityFromEnsure({
handle: S,
now: C
});
if (y?.acpxRecordId && E?.acpxRecordId && y.acpxRecordId !== E.acpxRecordId) y = void 0;
const D = mergeSessionIdentity({
current: y,
incoming: E,
now: C
}) ?? y;
const O = resolveRuntimeHandleIdentifiersFromIdentity(D);
const k = S.backend || d.id;
const A = {
...S,
backend: k,
sessionKey: e.sessionKey,
agentId: e.agentId,
...O.backendSessionId ? { backendSessionId: O.backendSessionId } : {},
...O.agentSessionId ? { agentSessionId: O.agentSessionId } : {}
};
const j = {
backend: k,
agent: i,
runtimeSessionName: S.runtimeSessionName,
...D ? { identity: D } : {},
mode: e.meta.mode,
...Object.keys(T).length > 0 ? { runtimeOptions: T } : {},
...w ? { cwd: w } : {},
state: m.state,
lastActivityAt: C,
...m.lastError ? { lastError: m.lastError } : {}
};
const M = m.backend !== j.backend || m.runtimeSessionName !== j.runtimeSessionName || !identityEquals(h, D) || m.agent !== j.agent || m.cwd !== j.cwd || !runtimeOptionsEqual(m.runtimeOptions, j.runtimeOptions) || hasLegacyAcpIdentityProjection(m);
try {
assertCurrent();
if (M) {
const i = e.readAcpControl?.();
const a = i?.runtimeLocator ?? t;
const o = i ? {
...i,
runtimeLocator: a
} : void 0;
const s = {};
const assertPublicationCurrent = () => {
try {
assertCurrent();
e.assertMetadataCommitAllowed?.(a);
if (!i && e.readAcpControl?.()) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP cancellation was admitted after metadata preparation.");
} catch (e) {
s.refusal ??= { error: e };
throw e;
}
};
assertPublicationCurrent();
await e.writeSessionMeta({
assertCommitAllowed: assertPublicationCurrent,
...r ? {
expectedControlBinding: r,
failOnError: true
} : {},
...o ? {
acpControl: o,
failOnError: true
} : {},
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
isCurrentActor: n,
mutate: (e, t) => {
assertCurrent();
return t ? j : null;
}
});
if (s.refusal) throw s.refusal.error;
}
assertCurrent();
e.runtimeHandles.set(e, {
runtime: f,
handle: A,
backend: k,
agent: i,
mode: a,
cwd: w,
appliedControlSignature: void 0
});
return {
runtime: f,
handle: A,
meta: j
};
} catch (t) {
if (!n()) await closeSupersededRuntimeHandle({
runtime: f,
handle: A,
sessionKey: e.sessionKey
});
throw t;
}
}
async function closeSupersededRuntimeHandle(e) {
await e.runtime.close({
handle: e.handle,
reason: "session-actor-superseded",
discardPersistentState: true
}).catch((t) => {
logVerbose(`acp-manager: failed discarding superseded runtime for ${e.sessionKey}: ${String(t)}`);
});
}
//#endregion
//#region src/acp/control-plane/manager.initialize-session.ts
async function runManagerInitializeSession(e) {
const { input: t, sessionKey: n, agentId: r } = e;
const i = e.isCurrentActor ?? (() => true);
assertCurrentAcpActor(i(), n);
const a = e.deps.requireRuntimeBackend(t.backendId || t.cfg.acp?.backend);
const o = a.runtime;
assertAcpRuntimeOwnerSupport(o, e);
const s = normalizeAgentId(t.agent);
const c = validateRuntimeOptionPatch({
...t.runtimeOptions,
...t.cwd !== void 0 ? { cwd: t.cwd } : {}
});
const l = c.cwd;
const u = c.model;
const d = c.thinking;
const assertCurrent = () => {
assertCurrentAcpActor(i(), n);
t.assertActive?.();
};
const f = (await e.deps.loadSessionEntryAsync({
cfg: t.cfg,
sessionKey: n,
agentId: r,
assertCurrent
}))?.acp;
const p = await t.revalidateResume?.();
assertCurrent();
p?.();
const m = {
...await withAcpRuntimeErrorBoundary({
run: async () => await o.ensureSession({
sessionKey: n,
agentId: r,
persistedHandle: f?.backend === a.id ? persistedAcpRuntimeHandle(e, f) : void 0,
agent: s,
mode: t.mode,
resumeSessionId: t.resumeSessionId,
...u ? { model: u } : {},
...u && t.modelExplicit ? { modelExplicit: true } : {},
...d ? { thinking: d } : {},
...d && t.thinkingExplicit !== void 0 ? { thinkingExplicit: t.thinkingExplicit } : {},
cwd: l
}),
fallbackCode: "ACP_SESSION_INIT_FAILED",
fallbackMessage: "Could not initialize ACP session runtime."
}),
agentId: r,
sessionKey: n
};
if (!i()) {
await closeSupersededRuntimeHandle({
runtime: o,
handle: m,
sessionKey: n
});
throw createSupersededActorError(n);
}
const h = normalizeOptionalString(m.cwd) ?? l;
const g = normalizeRuntimeOptions({
...c,
model: m.appliedModel ? m.appliedModel.kind === "applied" ? m.appliedModel.model : void 0 : u,
thinking: m.appliedThinking ? m.appliedThinking.kind === "applied" ? m.appliedThinking.thinking : void 0 : d,
...h ? { cwd: h } : {}
});
const _ = Date.now();
const v = createIdentityFromEnsure({
handle: m,
now: _
}) ?? {
state: "pending",
source: "ensure",
lastUpdatedAt: _
};
const y = {
backend: m.backend || a.id,
agent: s,
runtimeSessionName: m.runtimeSessionName,
identity: v,
mode: t.mode,
...Object.keys(g).length > 0 ? { runtimeOptions: g } : {},
cwd: h,
state: "idle",
lastActivityAt: Date.now()
};
let b;
try {
b = await e.writeSessionMeta({
cfg: t.cfg,
sessionKey: n,
agentId: r,
mutate: () => y,
isCurrentActor: i,
failOnError: true,
assertCommitAllowed: t.assertActive
});
if (!b?.acp) throw new AcpRuntimeError("ACP_SESSION_INIT_FAILED", `Could not persist ACP metadata for ${n}.`);
} catch (e) {
await o.close({
handle: m,
reason: "init-meta-failed"
}).catch((e) => {
logVerbose(`acp-manager: cleanup close failed after metadata write error for ${n}: ${String(e)}`);
});
throw e;
}
if (!i()) {
await closeSupersededRuntimeHandle({
runtime: o,
handle: m,
sessionKey: n
});
throw createSupersededActorError(n);
}
e.runtimeHandles.set(e, {
runtime: o,
handle: m,
backend: m.backend || a.id,
agent: s,
mode: t.mode,
cwd: h
});
return {
runtime: o,
handle: m,
meta: y,
sessionEntry: b
};
}
//#endregion
//#region src/acp/control-plane/manager.lifecycle.ts
const ACP_SESSION_MANAGER_DISPOSERS = /* @__PURE__ */ new WeakMap();
function registerAcpSessionManagerDisposer(e, t) {
ACP_SESSION_MANAGER_DISPOSERS.set(e, t);
}
/** Stops active turns and closes process-local handles without widening the public manager API. */
async function disposeAcpSessionManagerInstance(e, t) {
const n = ACP_SESSION_MANAGER_DISPOSERS.get(e);
if (!n) throw new Error("ACP session manager disposer unavailable");
await n(t);
}
//#endregion
//#region src/acp/control-plane/manager.reset-controls.ts
const RESET_CONTROLS = /* @__PURE__ */ new WeakMap();
function registerAcpSessionResetControls(e, t) {
RESET_CONTROLS.set(e, t);
}
function getAcpSessionResetControls(e) {
const t = RESET_CONTROLS.get(e);
if (!t) throw new Error("ACP session manager reset controls unavailable");
return t;
}
//#endregion
//#region src/acp/control-plane/manager.runtime-handle-cache.ts
/** Process-local cache of live ACP runtime handles keyed by canonical session actor. */
var ManagerRuntimeHandleCache = class {
constructor() {
this.runtimeCache = /* @__PURE__ */ new Map();
}
get(e) {
return this.runtimeCache.get(acpSessionActorKey(e)) ?? null;
}
set(e, t) {
this.runtimeCache.set(acpSessionActorKey(e), t);
}
clear(e) {
this.runtimeCache.delete(acpSessionActorKey(e));
}
getObservabilitySnapshot() {
return {
activeSessions: this.runtimeCache.size,
idleTtlMs: 0,
evictedTotal: 0
};
}
async close(e) {
const t = this.get(e);
if (!t || e.expectedHandle && t.handle !== e.expectedHandle) return;
e.assertActive?.();
await this.closeCached(acpSessionActorKey(e), t, e.reason, e.sessionKey, Boolean(e.expectedHandle));
}
/** Drains every cached handle behind its session actor before process shutdown. */
async closeAll(e) {
await Promise.all([...this.runtimeCache.keys()].map((t) => e.actorQueue.run(t, async () => {
const n = this.runtimeCache.get(t);
if (n) await this.closeCached(t, n, e.reason, n.handle.sessionKey);
})));
}
async closeCached(e, t, n, r, i = false) {
try {
await t.runtime.close({
handle: t.handle,
reason: n
});
} catch (e) {
if (i && isAcpOwnerRepairRequired(e)) throw e;
logVerbose(`acp-manager: cached runtime close failed for ${r}: ${String(e)}`);
} finally {
if (this.runtimeCache.get(e) === t) this.runtimeCache.delete(e);
}
}
/** Clears a cached handle only when the caller still owns the same runtime identifiers. */
clearIfHandleMatches(e) {
const t = this.get(e);
if (!t || !this.handlesMatch(t.handle, e.handle)) return;
this.clear(e);
}
/** Removes the captured cache entry synchronously before backend cleanup. */
take(e) {
const t = this.get(e);
if (t) this.clear(e);
return t;
}
async isReusable(e) {
if (!e.runtime.getStatus) return true;
try {
const t = await e.runtime.getStatus({ handle: e.handle });
if (isRuntimeStatusUnavailable(t)) {
logVerbose(`acp-manager: evicting cached runtime handle for ${e.sessionKey} after unhealthy status check: ${t.summary ?? "status unavailable"}`);
return false;
}
return true;
} catch (t) {
if (isAcpOwnerRepairRequired(t)) throw t;
logVerbose(`acp-manager: evicting cached runtime handle for ${e.sessionKey} after status check failed: ${String(t)}`);
return false;
}
}
handleMatchesMeta(e) {
const t = resolveSessionIdentityFromMeta(e.meta);
const n = resolveRuntimeHandleIdentifiersFromIdentity(t);
if ((e.handle.backendSessionId ?? "") !== (n.backendSessionId ?? "")) return false;
if ((e.handle.agentSessionId ?? "") !== (n.agentSessionId ?? "")) return false;
const r = t?.acpxRecordId ?? "";
return (normalizeOptionalString(e.handle.acpxRecordId) ?? "") === r;
}
handlesMatch(e, t) {
return e.sessionKey === t.sessionKey && e.agentId === t.agentId && e.backend === t.backend && e.runtimeSessionName === t.runtimeSessionName && (e.cwd ?? "") === (t.cwd ?? "") && (e.acpxRecordId ?? "") === (t.acpxRecordId ?? "") && (e.backendSessionId ?? "") === (t.backendSessionId ?? "") && (e.agentSessionId ?? "") === (t.agentSessionId ?? "");
}
};
function isRuntimeStatusUnavailable(e) {
if (!e) return false;
const t = normalizeLowercaseStringOrEmpty(e.details?.status);
if (t === "dead" || t === "no-session") return true;
const n = e.summary?.match(/\bstatus=([^\s]+)/i);
const r = normalizeLowercaseStringOrEmpty(n?.[1]);
return r === "dead" || r === "no-session";
}
//#endregion
//#region src/acp/control-plane/manager.runtime-controls.ts
const OPTIONAL_TIMEOUT_CONFIG_KEYS = /* @__PURE__ */ new Set(["timeout", "timeout_seconds"]);
const ACP_CONFIG_REJECTION_CODE_RE = /-3260[23]/;
const CONFIG_OPTION_REJECTION_RE = /invalid params|unsupported|not supported|not implement|invalid value|unknown config option|unknown value|not a valid value|must be one of/;
function extractConfigOptionKeys(e) {
if (!Array.isArray(e)) return [];
return e.map((e) => {
if (typeof e === "string") return normalizeOptionalString(e);
const t = asNullableRecord(e);
return normalizeOptionalString(t?.id ?? t?.key);
}).filter(Boolean);
}
function extractRuntimeStatusConfigOptionKeys(e) {
const t = asNullableRecord(e?.details);
return [...extractConfigOptionKeys(t?.configOptions), ...extractConfigOptionKeys(t?.config_options)];
}
function isOptionalTimeoutConfigKey(e) {
return OPTIONAL_TIMEOUT_CONFIG_KEYS.has(normalizeLowercaseStringOrEmpty(e));
}
function isUnsupportedControlRejection(e) {
return (e && typeof e === "object" ? e.code : null) === "ACP_BACKEND_UNSUPPORTED_CONTROL";
}
function describeConfigOptionRejection(e) {
const t = toAcpRuntimeError({
error: e,
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: ""
});
return normalizeLowercaseStringOrEmpty(`${formatAcpErrorChain(e)} ${t.message}`);
}
function isUnsupportedOptionalTimeoutConfigRejection(e, t) {
if (!isOptionalTimeoutConfigKey(e)) return false;
if (isUnsupportedControlRejection(t)) return true;
const n = t instanceof Error ? t.message : typeof t === "string" ? t : String(t);
const r = normalizeLowercaseStringOrEmpty(n);
return r.includes("session/set_config_option") && (r.includes("-32602") || r.includes("invalid params") || r.includes("unsupported") || r.includes("not supported") || r.includes("not implement"));
}
/** The adapter named the config option and refused its value, as claude-agent-acp does for `effort`. */
function isRejectedConfigOptionValue(e, t) {
const n = describeConfigOptionRejection(e);
return (n.includes("session/set_config_option") || n.includes("config option") && (!t || n.includes(normalizeLowercaseStringOrEmpty(t)))) && ACP_CONFIG_REJECTION_CODE_RE.test(n) && CONFIG_OPTION_REJECTION_RE.test(n);
}
function isRejectedThinkingConfigOption(e, t) {
return isThinkingConfigKey(e) && (isUnsupportedControlRejection(t) || isRejectedConfigOptionValue(t, e));
}
async function resolveManagerRuntimeCapabilities(e) {
let t;
if (e.runtime.getCapabilities) t = await withAcpRuntimeErrorBoundary({
run: async () => await e.runtime.getCapabilities({ handle: e.handle }),
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not read ACP runtime capabilities."
});
const n = new Set(t?.controls ?? []);
if (e.runtime.setMode) n.add("session/set_mode");
if (e.runtime.setConfigOption) n.add("session/set_config_option");
if (e.runtime.getStatus) n.add("session/status");
const r = new Set((t?.configOptionKeys ?? []).map((e) => normalizeOptionalString(e)).filter(Boolean));
if (r.size === 0 && e.includeStatusConfigOptionKeys && e.runtime.getStatus) try {
const t = await e.runtime.getStatus({ handle: e.handle });
for (const e of extractRuntimeStatusConfigOptionKeys(t)) r.add(e);
} catch (e) {
if (isAcpOwnerRepairRequired(e)) throw e;
}
return {
controls: [...n].toSorted(),
...r.size > 0 ? { configOptionKeys: [...r] } : {}
};
}
/** Applies persisted runtime options to a live handle once per unique option signature. */
async function applyManagerRuntimeControls(e) {
const t = e.isCurrentActor ?? (() => true);
assertCurrentAcpActor(t(), e.sessionKey);
let n = resolveRuntimeOptionsFromMeta(e.meta);
const r = buildRuntimeControlSignature(n);
const i = e.getCachedRuntimeState(e.sessionKey);
if (i?.appliedControlSignature === r) return;
const a = buildRuntimeConfigOptionPairs(n).length > 0;
const o = await resolveManagerRuntimeCapabilities({
runtime: e.runtime,
handle: e.handle,
includeStatusConfigOptionKeys: a
});
const s = e.handle.backend || e.meta.backend;
const c = n.runtimeMode;
const l = buildRuntimeConfigOptionPairs(n, o.configOptionKeys);
const u = n.thinking ? resolveRuntimeConfigOptionKey("thinking", o.configOptionKeys) : void 0;
const d = new Set((o.configOptionKeys ?? []).map((e) => normalizeLowercaseStringOrEmpty(e)).filter(Boolean));
await withAcpRuntimeErrorBoundary({
run: async () => {
assertCurrentAcpActor(t(), e.sessionKey);
if (c) {
if (!e.runtime.setMode) throw createUnsupportedControlError({
backend: s,
control: "session/set_mode"
});
await e.runtime.setMode({
handle: e.handle,
mode: c
});
}
if (l.length > 0) {
if (!e.runtime.setConfigOption) throw createUnsupportedControlError({
backend: s,
control: "session/set_config_option"
});
for (const [r, i] of l) {
assertCurrentAcpActor(t(), e.sessionKey);
const a = r === u ? n.thinking : i;
if (a === void 0) continue;
if (d.size > 0 && !d.has(normalizeLowercaseStringOrEmpty(r))) throw new AcpRuntimeError("ACP_BACKEND_UNSUPPORTED_CONTROL", `ACP backend "${s}" does not accept config key "${r}".`);
try {
const i = await e.runtime.setConfigOption({
handle: e.handle,
key: r,
value: a
});
assertCurrentAcpActor(t(), e.sessionKey);
if (r === resolveRuntimeConfigOptionKey("model", o.configOptionKeys)) {
const t = i?.configOptions.find((e) => e.id === r);
e.onModelApplied?.(i ? typeof t?.currentValue === "string" ? t.currentValue : void 0 : a);
}
const s = reconcileAcceptedRuntimeOptions(n, i, normalizeLowercaseStringOrEmpty(r) === "model" ? n.thinking : void 0);
if (!runtimeOptionsEqual(n, s)) {
await e.onOptionsChanged(s);
assertCurrentAcpActor(t(), e.sessionKey);
n = s;
}
} catch (n) {
assertCurrentAcpActor(t(), e.sessionKey);
if (isUnsupportedOptionalTimeoutConfigRejection(r, n) || isRejectedThinkingConfigOption(r, n)) continue;
throw n;
}
}
}
},
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not apply ACP runtime options before turn execution."
});
assertCurrentAcpActor(t(), e.sessionKey);
if (i) i.appliedControlSignature = buildRuntimeControlSignature(n);
}
//#endregion
//#region src/acp/control-plane/manager.runtime-options-commands.ts
async function resolveRuntimeOptionSessionMeta(e) {
const assertCurrent = () => {
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
e.assertActive?.();
};
assertCurrent();
const t = await e.resolveSession({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
assertCurrent
});
assertCurrent();
return requireReadySessionMeta(t);
}
async function runSetManagerSessionRuntimeOption(e) {
const t = await resolveRuntimeOptionSessionMeta(e);
const { runtime: n, handle: r, meta: i } = await e.ensureRuntimeHandle({
assertActive: e.assertActive,
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
meta: t,
isCurrentActor: e.isCurrentActor
});
e.assertActive?.();
const a = e.update;
const o = "runtimeMode" in a ? a : inferRuntimeOptionPatchFromConfigOption(a.key, a.value);
const s = await resolveManagerRuntimeCapabilities({
runtime: n,
handle: r,
..."key" in a ? { includeStatusConfigOptionKeys: true } : {}
});
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
let c = void 0;
if ("runtimeMode" in a) {
if (!n.setMode) throw createUnsupportedControlError({
backend: r.backend || i.backend,
control: "session/set_mode"
});
await withAcpRuntimeErrorBoundary({
run: async () => {
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
e.assertActive?.();
await n.setMode({
handle: r,
mode: a.runtimeMode
});
},
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not update ACP runtime mode."
});
} else {
if (!n.setConfigOption) throw createUnsupportedControlError({
backend: r.backend || i.backend,
control: "session/set_config_option"
});
const t = new Set((s.configOptionKeys ?? []).map((e) => normalizeLowercaseStringOrEmpty(e)).filter(Boolean));
const o = resolveRuntimeConfigOptionKey(a.key, s.configOptionKeys);
if (t.size > 0 && !t.has(normalizeLowercaseStringOrEmpty(o))) throw new AcpRuntimeError("ACP_BACKEND_UNSUPPORTED_CONTROL", `ACP backend "${r.backend || i.backend}" does not accept config key "${o}".`);
e.assertActive?.();
c = await withAcpRuntimeErrorBoundary({
run: async () => await n.setConfigOption({
handle: r,
key: o,
value: a.value
}),
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not update ACP runtime config option."
});
}
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
const l = reconcileAcceptedRuntimeOptions(mergeRuntimeOptions({
current: resolveRuntimeOptionsFromMeta(i),
patch: o
}), c);
await persistManagerRuntimeOptions({
...e,
options: l
});
return l;
}
async function runUpdateManagerSessionRuntimeOptions(e) {
const t = await resolveRuntimeOptionSessionMeta(e);
const n = mergeRuntimeOptions({
current: resolveRuntimeOptionsFromMeta(t),
patch: e.patch
});
await persistManagerRuntimeOptions({
...e,
assertCommitAllowed: e.assertActive,
options: n
});
return n;
}
async function runResetManagerSessionRuntimeOptions(e) {
await resolveRuntimeOptionSessionMeta(e);
const t = e.runtimeHandles.get(e);
if (t) {
await withAcpRuntimeErrorBoundary({
run: async () => {
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
e.assertActive?.();
await t.runtime.close({
handle: t.handle,
reason: "reset-runtime-options"
});
},
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not reset ACP runtime options."
});
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
e.runtimeHandles.clearIfHandleMatches({
...e,
handle: t.handle
});
}
await persistManagerRuntimeOptions({
...e,
assertCommitAllowed: t ? void 0 : e.assertActive,
options: {}
});
return {};
}
async function persistManagerRuntimeOptions(e) {
const t = e.options;
const n = Object.keys(t).length > 0;
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
await e.writeSessionMeta({
assertCommitAllowed: e.assertCommitAllowed,
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
isCurrentActor: e.isCurrentActor,
mutate: (e, r) => {
if (!r || !e) return null;
return {
backend: e.backend,
agent: e.agent,
runtimeSessionName: e.runtimeSessionName,
...e.identity ? { identity: e.identity } : {},
mode: e.mode,
runtimeOptions: n ? t : void 0,
cwd: t.cwd,
state: e.state,
lastActivityAt: Date.now(),
...e.lastError ? { lastError: e.lastError } : {}
};
},
failOnError: true
});
assertCurrentAcpActor(e.isCurrentActor(), e.sessionKey);
const r = e.runtimeHandles.get(e);
if (!r) return;
r.appliedControlSignature = void 0;
}
//#endregion
//#region src/acp/control-plane/manager.startup-identity-reconcile.ts
async function runManagerStartupIdentityReconcile(e) {
let t = 0;
let n = 0;
let r = 0;
let i;
try {
i = await e.deps.listAcpSessions({ cfg: e.cfg });
} catch (e) {
logVerbose(`acp-manager: startup identity scan failed: ${String(e)}`);
return {
checked: t,
resolved: n,
failed: r + 1
};
}
for (const a of i) {
if (!a.acp || !a.sessionKey) continue;
if (a.acp.mode === "oneshot") continue;
const i = resolveSessionIdentityFromMeta(a.acp);
if (!isSessionIdentityPending(i) || !identityHasStableSessionId(i)) continue;
t += 1;
try {
const t = resolveAcpSessionTarget({
cfg: e.cfg,
sessionKey: a.sessionKey,
agentId: a.agentId
});
if (await e.withSessionActor(t, async (n) => {
const assertCurrent = () => {
assertCurrentAcpActor(n(), t.sessionKey);
};
const r = await e.resolveSession({
cfg: e.cfg,
...t,
assertCurrent
});
assertCurrent();
if (r.kind !== "ready") return false;
const { runtime: i, handle: a, meta: o } = await e.ensureRuntimeHandle({
cfg: e.cfg,
...t,
meta: r.meta,
isCurrentActor: n
});
const s = await e.reconcileRuntimeSessionIdentifiers({
cfg: e.cfg,
...t,
runtime: i,
handle: a,
meta: o,
failOnStatusError: false,
isCurrentActor: n
});
return !isSessionIdentityPending(resolveSessionIdentityFromMeta(s.meta));
})) n += 1;
} catch (e) {
r += 1;
logVerbose(`acp-manager: startup identity reconcile failed for ${a.sessionKey}: ${String(e)}`);
}
}
return {
checked: t,
resolved: n,
failed: r
};
}
//#endregion
//#region src/acp/control-plane/manager.status.ts
async function runManagerGetSessionStatus(e) {
const t = e.isCurrentActor ?? (() => true);
const assertCurrent = () => {
assertCurrentAcpActor(t(), e.sessionKey);
e.assertActive?.();
e.throwIfAborted(e.signal);
};
assertCurrent();
const n = await e.resolveSession({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
assertCurrent
});
assertCurrent();
const r = requireReadySessionMeta(n);
const { runtime: i, handle: a, meta: o } = await e.ensureRuntimeHandle({
assertActive: e.assertActive,
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
meta: r,
isCurrentActor: t
});
e.assertActive?.();
const s = await resolveManagerRuntimeCapabilities({
runtime: i,
handle: a
});
assertCurrentAcpActor(t(), e.sessionKey);
let c;
if (i.getStatus) c = await withAcpRuntimeErrorBoundary({
run: async () => {
e.throwIfAborted(e.signal);
e.assertActive?.();
const t = await i.getStatus({
handle: a,
...e.signal ? { signal: e.signal } : {}
});
e.throwIfAborted(e.signal);
return t;
},
fallbackCode: "ACP_TURN_FAILED",
fallbackMessage: "Could not read ACP runtime status."
});
assertCurrentAcpActor(t(), e.sessionKey);
const l = await e.reconcileRuntimeSessionIdentifiers({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
runtime: i,
handle: a,
meta: o,
runtimeStatus: c,
failOnStatusError: true,
isCurrentActor: t
});
const u = l.meta;
const d = resolveSessionIdentityFromMeta(u);
return {
sessionKey: e.sessionKey,
agentId: e.agentId,
backend: l.handle.backend || u.backend,
agent: u.agent,
...d ? { identity: d } : {},
state: u.state,
mode: u.mode,
runtimeOptions: resolveRuntimeOptionsFromMeta(u),
capabilities: s,
runtimeStatus: l.runtimeStatus,
lastActivityAt: u.lastActivityAt,
lastError: u.lastError
};
}
//#endregion
//#region src/acp/control-plane/manager.backend-failover.ts
/** Builds the deduped backend order from configured primary, resolved primary, and fallbacks. */
function resolveBackendCandidatePlan(e) {
const t = normalizeOptionalString(e.configuredPrimaryBackend);
const n = normalizeOptionalString(e.resolvedPrimaryBackend);
const r = (e.fallbackBackends ?? []).map((e) => normalizeOptionalString(e)).filter((e) => e != null);
return {
candidateBackends: Array.from(/* @__PURE__ */ new Set([t ?? n ?? "", ...r])),
describeBackendCandidate: (e) => e || n || t || "<auto>"
};
}
/** Returns true for early transient backend errors where trying another backend is safe. */
function isFailoverWorthyBackendError(e) {
return !e.promptStarted && !e.sawOutput && (e.code === "ACP_TURN_FAILED" || e.code === "ACP_SESSION_INIT_FAILED" || e.code === "ACP_BACKEND_UNAVAILABLE") && /\b(?:unavailable|rate[-\s]?limit(?:ed|ing)?|quota|exhausted|temporar(?:y|ily)|overloaded)\b/i.test(e.error);
}
//#endregion
//#region src/acp/control-plane/manager.turn-runner.ts
const ACP_TURN_TIMEOUT_GRACE_MS = 1e3;
async function runManagerTurn(e) {
const { input: t, sessionKey: n, agentId: r } = e;
const cancellationCleanupFailed = (t) => {
if (l.aborted) e.producer.recordCancellationFailure(t);
throw t;
};
const i = readAdmittedRunOperatorAuthority(t.admittedRunContext);
const a = getProcessGatewayPluginMetadataSnapshot() ?? [];
const resolveModelRef = (e) => {
const t = e ? parseModelCatalogRef(e) : void 0;
return t ? normalizeModelRef(t.provider, t.modelId, {
allowPluginNormalization: false,
manifestPlugins: a
}) : void 0;
};
const assertModelAllowed = (e) => assertOperatorModelAllowed(i, resolveModelRef(e));
if (t.admittedRunContext.operationalRunInstance.runId !== t.requestId) throw new Error("ACP operational run instance disagrees with the admitted request");
const o = Date.now();
const s = acpSessionActorKey(e);
const c = new AbortController();
let l = t.signal ? AbortSignal.any([t.signal, c.signal]) : c.signal;
let u = resolveAdmittedRunActiveAssertion(t.admittedRunContext, l);
const assertActorCurrent = () => {
assertCurrentAcpActor(e.isCurrentActor(), n);
};
const assertSignalCurrent = () => {
assertActorCurrent();
l.throwIfAborted();
u?.();
};
assertSignalCurrent();
let d = markAcpTurnActive(e);
let f;
let p;
let m;
let h;
const assertCancellationCurrent = () => {
assertActorCurrent();
p?.assertCurrent(t.cfg);
p?.assertAcpCurrent?.(t.cfg, h);
};
const revalidateCancellation = async () => {
try {
const e = await p?.readCurrent(t.cfg);
assertCancellationCurrent();
if (h && !matchesAcpSessionRuntimeLocator(e?.session.acp, h)) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP runtime locator changed before cancellation.");
m = e?.constraint ? {
...e.constraint,
...h ? { runtimeLocator: h } : {}
} : void 0;
return m;
} catch (t) {
e.producer.recordCancellationFailure(t);
const n = e.runtimeHandles.get(e)?.handle;
if (n && e.isCurrentActor() && n === h) e.runtimeHandles.clearIfHandleMatches({
...e,
handle: n
});
throw t;
}
};
const recordTerminalState = async (e, i) => {
if (i) await revalidateCancellation();
if (f) await recordSubagentTerminalState({
childSessionKey: n,
agentId: r,
runId: t.requestId,
requesterSessionKey: f,
outcomeStatus: e
}, i ? assertCancellationCurrent : assertActorCurrent, i ? m : void 0).catch(cancellationCleanupFailed);
};
try {
let a;
let g;
try {
p = await e.prepareSessionControlRead({
cfg: t.cfg,
sessionKey: n,
agentId: r,
assertCurrent: assertActorCurrent
});
a = resolveStoredAcpSession({
sessionKey: n,
agentId: r
}, p.initialRead.session);
assertSignalCurrent();
g = requireReadySessionMeta(a);
f = a.kind === "ready" ? a.entry?.spawnedBy ?? a.entry?.parentSessionKey : void 0;
if (f) d = markAcpTurnActive({
...e,
ownerSessionKey: f
});
await recordSessionHumanDirectMessage({
sessionKey: n,
agentId: r,
entry: a.kind === "ready" ? a.entry : void 0,
actor: { actorType: t.provenance },
channel: "acp",
runId: t.requestId
}, { assertCurrent: assertSignalCurrent });
assertSignalCurrent();
} catch (t) {
const n = l.aborted;
const r = toAcpRuntimeError({
error: t,
fallbackCode: n ? "ACP_TURN_FAILED" : "ACP_SESSION_INIT_FAILED",
fallbackMessage: n ? "ACP operation aborted." : "Could not prepare ACP session runtime."
});
e.recordTurnCompletion({
startedAt: o,
...n ? {} : { errorCode: r.code }
});
if (f && e.isCurrentActor()) await recordTerminalState(n ? "cancelled" : r.detailCode === "TURN_TIMEOUT" ? "timeout" : "error", n);
throw r;
}
const { storePath: _ } = resolveSessionStorePathForAcp({
cfg: t.cfg,
sessionKey: n,
agentId: r
});
return await withSessionTurn({
sessionKey: n,
agentId: r,
storePath: _,
sessionId: a.kind === "ready" ? a.entry?.sessionId : void 0,
abortSignal: l
}, async (d, _) => {
l = _;
u = resolveAdmittedRunActiveAssertion(t.admittedRunContext, l);
const { candidateBackends: v, describeBackendCandidate: y } = resolveBackendCandidatePlan({
configuredPrimaryBackend: t.cfg.acp?.backend,
resolvedPrimaryBackend: g.backend,
fallbackBackends: t.cfg.acp?.fallbacks
});
const b = [];
const recordBackendFailure = async (i) => {
assertActorCurrent();
const a = b.map((e) => `${e.backend}: ${e.error}`).join(" | ");
const s = b.length > 1 ? new AcpRuntimeError(i.code, `All ACP backends failed (${b.length}): ${a}`, { detailCode: i.detailCode }) : i;
e.recordTurnCompletion({
startedAt: o,
errorCode: s.code
});
const c = l.aborted;
if (c || f) await recordTerminalState(s.detailCode === "TURN_TIMEOUT" ? "timeout" : "error", c);
if (f) assertActorCurrent();
await e.setSessionState({
cfg: t.cfg,
sessionKey: n,
agentId: r,
isCurrentActor: e.isCurrentActor,
state: "error",
lastError: formatAcpErrorChain(s),
...c ? {
assertCurrent: assertCancellationCurrent,
acpControl: m
} : {}
}).catch(cancellationCleanupFailed);
throw s;
};
for (const [g, _] of v.entries()) {
if (g > 0) {
await e.runtimeHandles.close({
sessionKey: n,
agentId: r,
reason: "backend-failover"
});
logVerbose(`acp-manager: switching backend for ${n} from ${y(expectDefined(v[g - 1], "candidate backends entry at backend idx 1"))} to ${y(_)}`);
}
for (let x = 0; x < 2; x += 1) {
const S = g === 0 && x === 0 ? a : await e.resolveSession({
cfg: t.cfg,
sessionKey: n,
agentId: r,
assertCurrent: assertSignalCurrent
});
assertSignalCurrent();
const C = requireReadySessionMeta(S);
assertModelAllowed(C.runtimeOptions?.model);
let w;
let T;
let E;
let D;
let O = false;
let k = false;
let A = false;
let j = false;
let M = false;
let N = false;
let P;
const onModelRevoked = () => c.abort(P?.signal.reason);
let onTurnAborted;
try {
h = {
backend: C.backend,
runtimeSessionName: C.runtimeSessionName
};
const a = await e.ensureRuntimeHandle({
readAcpControl: () => l.aborted ? m ?? p?.initialRead.constraint : void 0,
assertMetadataCommitAllowed: (e) => {
if (l.aborted) {
assertCancellationCurrent();
p?.assertAcpCurrent?.(t.cfg, e);
}
},
cfg: t.cfg,
sessionKey: n,
agentId: r,
meta: C,
selectedBackend: _,
isCurrentActor: e.isCurrentActor
});
assertActorCurrent();
w = a.runtime;
T = a.handle;
h = T;
E = a.meta;
let g = T.appliedModel ? T.appliedModel.kind === "applied" ? T.appliedModel.model : void 0 : E.runtimeOptions?.model;
assertModelAllowed(g);
D = {
runtime: w,
handle: T,
abortController: c
};
e.activeTurnBySession.set(s, D);
if (!l.aborted) await applyManagerRuntimeControls({
sessionKey: n,
runtime: w,
handle: T,
meta: E,
isCurrentActor: e.isCurrentActor,
getCachedRuntimeState: () => e.runtimeHandles.get(e),
onModelApplied: (e) => {
g = e;
assertModelAllowed(g);
},
onOptionsChanged: async (i) => {
await e.writeSessionMeta({
cfg: t.cfg,
sessionKey: n,
agentId: r,
isCurrentActor: e.isCurrentActor,
mutate: (e) => e ? {
...e,
runtimeOptions: i
} : null,
failOnError: true
});
E = {
...a.meta,
runtimeOptions: i
};
}
});
P = bindOperatorModelExecution(i, resolveModelRef(g));
P?.signal.addEventListener("abort", onModelRevoked, { once: true });
P?.assertCurrent();
if (!l.aborted) await e.setSessionState({
cfg: t.cfg,
sessionKey: n,
agentId: r,
isCurrentActor: e.isCurrentActor,
state: "running",
clearLastError: true
});
assertActorCurrent();
O = true;
const v = D;
const cancelTurn = () => cancelManagerActiveTurn({
activeTurn: v,
reason: typeof l.reason === "string" ? l.reason : void 0,
revalidate: async () => {
await revalidateCancellation();
await e.producer.revalidateCancellation();
},
assertCurrent: () => {
assertCancellationCurrent();
e.producer.assertCancellationAllowed();
}
}).catch(cancellationCleanupFailed);
onTurnAborted = () => {
if (A) return;
cancelTurn().catch((e) => {
logVerbose(`acp-manager: runtime cancel failed for ${n}: ${String(e)}`);
});
};
l.addEventListener("abort", onTurnAborted, { once: true });
const y = { open: true };
const b = consumeAcpTurnStream({
runtime: w,
source: composeSessionSourceAssertion([u], (e) => {
assertActorCurrent();
l.throwIfAborted();
P?.assertCurrent();
e();
}),
turn: {
handle: T,
text: t.text,
attachments: t.attachments,
mode: t.mode,
requestId: t.requestId,
signal: l,
onElicitation: t.onElicitation
},
eventGate: y,
onBeforePrompt: async () => {
await t.onBeforePrompt?.();
P?.assertCurrent();
},
onCancellation: cancelTurn,
onPromptStarted: async ({ authoritative: r }) => {
if (!e.isCurrentActor()) return;
k = r;
if (r) {
const e = resolveAdmittedRunActiveAssertion(t.admittedRunContext);
if (!e) throw new Error("ACP execution authority closed before prompt submission");
e();
}
try {
await t.onLifecycle?.({
type: "prompt_submitted",
at: Date.now()
});
} catch (e) {
logVerbose(`acp-manager: prompt submission observer failed for ${n}: ${String(e)}`);
}
},
onOutputEvent: () => {
P?.signal.throwIfAborted();
if (!e.isCurrentActor()) return;
j = true;
},
onEvent: async (n) => {
if (n.type === "done") {
A = true;
if (e.ownsTurnTerminal) d?.freezeAbort();
}
P?.signal.throwIfAborted();
if (e.isCurrentActor()) try {
await t.onEvent?.(n);
} catch (e) {
cancellationCleanupFailed(e);
}
}
});
const x = resolveTurnTimeoutMs({
cfg: t.cfg,
meta: E
});
const S = E.mode;
const M = await awaitTurnWithTimeout({
sessionKey: n,
turnPromise: b,
timeoutMs: x + ACP_TURN_TIMEOUT_GRACE_MS,
timeoutLabelMs: x,
onTimeout: async () => {
y.open = false;
N = true;
if (!D) return;
await cleanupTimedOutTurn({
sessionKey: n,
activeTurn: D,
mode: S,
clearCachedRuntimeStateIfHandleMatches: (t) => {
if (!e.isCurrentActor()) return;
e.runtimeHandles.clearIfHandleMatches({
sessionKey: n,
agentId: r,
handle: t.handle
});
}
});
}
});
assertActorCurrent();
P?.assertCurrent();
if (!M.terminalStatus) throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP turn ended without a terminal done event.");
e.recordTurnCompletion({ startedAt: o });
A = true;
if (e.ownsTurnTerminal) d?.freezeAbort();
const F = M.terminalStatus === "cancelled";
const I = F || l.aborted;
if (I || f) await recordTerminalState(F ? "cancelled" : "ok", I);
if (f) assertActorCurrent();
await e.setSessionState({
cfg: t.cfg,
sessionKey: n,
agentId: r,
isCurrentActor: e.isCurrentActor,
state: "idle",
clearLastError: true,
...I ? {
assertCurrent: assertCancellationCurrent,
acpControl: m
} : {}
}).catch(cancellationCleanupFailed);
return;
} catch (i) {
const a = toAcpRuntimeError({
error: i,
fallbackCode: O ? "ACP_TURN_FAILED" : "ACP_SESSION_INIT_FAILED",
fallbackMessage: O ? "ACP turn failed before completion." : "Could not initialize ACP session runtime."
});
assertActorCurrent();
M = await prepareFreshManagerRuntimeHandleRetry({
attempt: x,
cfg: t.cfg,
sessionKey: n,
agentId: r,
error: a,
promptStarted: k,
sawTurnOutput: j,
runtime: w,
meta: E,
runtimeHandles: e.runtimeHandles,
writeSessionMeta: e.writeSessionMeta,
isCurrentActor: e.isCurrentActor
});
assertActorCurrent();
if (M) continue;
const o = {
backend: y(_),
error: a.message,
code: a.code,
promptStarted: k,
sawOutput: j
};
b.push(o);
if (isAcpOwnerRepairRequired(a) || !isFailoverWorthyBackendError(o) || g >= v.length - 1) await recordBackendFailure(a);
break;
} finally {
if (onTurnAborted) l.removeEventListener("abort", onTurnAborted);
try {
await D?.cancelPromise;
} finally {
P?.signal.removeEventListener("abort", onModelRevoked);
P?.release();
if (D && e.activeTurnBySession.get(s) === D) e.activeTurnBySession.delete(s);
if (!M && !N && w && T && E && e.isCurrentActor()) ({handle: T, meta: E} = await e.reconcileRuntimeSessionIdentifiers({
cfg: t.cfg,
sessionKey: n,
agentId: r,
runtime: w,
handle: T,
meta: E,
failOnStatusError: false,
isCurrentActor: e.isCurrentActor,
...l.aborted ? {
revalidateControl: revalidateCancellation,
assertCurrent: assertCancellationCurrent
} : {}
}).catch(cancellationCleanupFailed));
if (!M && !N && w && T && E && e.isCurrentActor() && E.mode === "oneshot") try {
await w.close({
handle: T,
reason: "oneshot-complete"
});
} catch (e) {
logVerbose(`acp-manager: ACP oneshot close failed for ${n}: ${String(e)}`);
} finally {
if (e.isCurrentActor()) e.runtimeHandles.clearIfHandleMatches({
...e,
handle: T
});
}
}
}
}
}
});
} finally {
p?.release();
d?.();
}
}
//#endregion
//#region src/acp/control-plane/manager.types.ts
const DEFAULT_DEPS = {
listAcpSessions: listAcpSessionEntries,
loadSessionEntry: readAcpSessionEntry,
loadSessionEntryAsync: readAcpSessionEntryAsync,
prepareSessionControlRead: prepareAcpSessionControlRead,
upsertSessionMeta: upsertAcpSessionMeta,
upsertSessionMetaForControl: upsertAcpSessionMetaForControl,
getRuntimeBackend: getAcpRuntimeBackend,
requireRuntimeBackend: requireAcpRuntimeBackend
};
//#endregion
//#region src/acp/control-plane/session-actor-queue.ts
/** Serializes each current actor lane without retaining a history of retired lanes. */
var SessionActorQueue = class {
constructor() {
this.lanes = /* @__PURE__ */ new Map();
this.pendingCount = 0;
}
getTotalPendingCount() {
return this.pendingCount;
}
/** Holds a generation until the caller releases its cleanup/operation custody. */
capture(e) {
let t = this.lanes.get(e);
if (!t) {
t = {
queue: new KeyedAsyncQueue(),
users: 0,
retired: false
};
this.lanes.set(e, t);
}
const n = t;
n.users += 1;
let r = false;
return {
queue: n.queue,
isCurrent: () => !r && !n.retired,
release: () => {
if (r) return;
r = true;
n.users -= 1;
if (n.users === 0 && this.lanes.get(e) === n) this.lanes.delete(e);
}
};
}
async run(e, t) {
const n = this.capture(e);
try {
return await n.queue.enqueue(e, async () => {
if (!n.isCurrent()) throw new Error(`ACP session actor was superseded for ${e}.`);
return await t(n.isCurrent);
}, {
onEnqueue: () => {
this.pendingCount += 1;
},
onSettle: () => {
this.pendingCount -= 1;
}
});
} finally {
n.release();
}
}
/** Fresh work bypasses a stuck lane; only outstanding operations retain the retired token. */
rotate(e) {
const t = this.lanes.get(e);
if (t) {
t.retired = true;
this.lanes.delete(e);
}
}
};
//#endregion
//#region src/acp/control-plane/manager.core.ts
var AcpSessionManager = class {
constructor(e = DEFAULT_DEPS) {
this.actorQueue = new SessionActorQueue();
this.runtimeHandles = new ManagerRuntimeHandleCache();
this.activeTurnBySession = /* @__PURE__ */ new Map();
this.liveTurnRequests = /* @__PURE__ */ new Map();
this.lifecycle = new AbortController();
this.producerOwner = {};
this.turnLatencyStats = {
completed: 0,
failed: 0,
totalMs: 0,
maxMs: 0
};
this.errorCountsByCode = /* @__PURE__ */ new Map();
this.deps = e;
registerAcpSessionResetControls(this, {
captureSessionRuntimeOwnership: (e) => {
const t = this.actorQueue.capture(acpSessionActorKey(resolveAcpSessionTarget(e)));
return {
isCurrent: t.isCurrent,
release: t.release
};
},
/** Evicts only the captured runtime generation; old handles close in the background. */
forceDiscardSessionRuntime: async (e) => {
e.assertCurrent?.();
if (e.isCurrent && !e.isCurrent()) throw createSupersededActorError(e.sessionKey);
const t = resolveAcpSessionTarget(e);
const { sessionKey: n } = t;
const r = acpSessionActorKey(t);
this.actorQueue.rotate(r);
const i = this.activeTurnBySession.get(r);
if (i) {
i.abortController.abort();
if (this.activeTurnBySession.get(r) === i) this.activeTurnBySession.delete(r);
}
const a = this.runtimeHandles.take(t);
const o = [...i ? [{
runtime: i.runtime,
handle: i.handle
}] : [], ...a && (!i || !this.runtimeHandles.handlesMatch(a.handle, i.handle)) ? [{
runtime: a.runtime,
handle: a.handle
}] : []];
Promise.allSettled(o.map(async ({ runtime: t, handle: n }) => {
await t.close({
handle: n,
reason: e.reason,
discardPersistentState: true
});
})).then((e) => {
const t = e.find((e) => e.status === "rejected");
if (t) logVerbose(`acp-manager: force-discard runtime close failed for ${n}: ${String(t.reason)}`);
});
}
});
registerAcpSessionManagerDisposer(this, async (e) => {
this.lifecycle.abort();
await Promise.allSettled(captureSessionControllerProducers({ owner: this.producerOwner }).map((e) => e.settled));
await this.runtimeHandles.closeAll({
actorQueue: this.actorQueue,
reason: e
});
this.activeTurnBySession.clear();
});
}
/** @deprecated Use resolveSessionAsync; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
resolveSession(e) {
warnPluginSdkDeprecation({
family: "acp-session",
method: "AcpSessionManager.resolveSession",
replacement: "AcpSessionManager.resolveSessionAsync"
});
if (!e.sessionKey.trim()) return {
kind: "none",
sessionKey: ""
};
const t = resolveAcpSessionTarget(e);
return resolveStoredAcpSession(t, this.deps.loadSessionEntry({
cfg: e.cfg,
...t,
clone: false
}));
}
async resolveSessionAsync(e) {
e.assertCurrent?.();
if (!e.sessionKey.trim()) return {
kind: "none",
sessionKey: ""
};
const t = resolveAcpSessionTarget(e);
const n = await this.deps.loadSessionEntryAsync({
cfg: e.cfg,
...t,
clone: false,
...e.assertCurrent ? { assertCurrent: e.assertCurrent } : {}
});
e.assertCurrent?.();
return resolveStoredAcpSession(t, n);
}
getObservabilitySnapshot() {
const e = this.turnLatencyStats.completed + this.turnLatencyStats.failed;
const t = e > 0 ? Math.round(this.turnLatencyStats.totalMs / e) : 0;
return {
runtimeCache: this.runtimeHandles.getObservabilitySnapshot(),
turns: {
active: this.activeTurnBySession.size,
queueDepth: this.actorQueue.getTotalPendingCount(),
completed: this.turnLatencyStats.completed,
failed: this.turnLatencyStats.failed,
averageLatencyMs: t,
maxLatencyMs: this.turnLatencyStats.maxMs
},
errorsByCode: Object.fromEntries([...this.errorCountsByCode.entries()].toSorted(([e], [t]) => e.localeCompare(t)))
};
}
async reconcilePendingSessionIdentities(e) {
return await runManagerStartupIdentityReconcile({
cfg: e.cfg,
deps: this.deps,
withSessionActor: this.withSessionActor.bind(this),
resolveSession: this.resolveSessionAsync.bind(this),
ensureRuntimeHandle: this.ensureRuntimeHandle.bind(this),
reconcileRuntimeSessionIdentifiers: this.reconcileRuntimeSessionIdentifiers.bind(this)
});
}
async initializeSession(e) {
const t = resolveAcpSessionTarget(e);
return await this.withSessionActor(t, async (n) => {
const r = await runManagerInitializeSession({
input: e,
...t,
deps: this.deps,
runtimeHandles: this.runtimeHandles,
writeSessionMeta: this.writeSessionMeta.bind(this),
isCurrentActor: n
});
return {
...r,
closeRuntimeOnFailure: () => this.withSessionActor(t, () => this.runtimeHandles.close({
...t,
reason: "spawn-failed",
expectedHandle: r.handle
}))
};
});
}
async getSessionStatus(e) {
const t = resolveAcpSessionTarget(e);
this.throwIfAborted(e.signal);
return await this.withSessionActor(t, async (n) => await runManagerGetSessionStatus({
assertActive: e.assertActive,
cfg: e.cfg,
...t,
signal: e.signal,
throwIfAborted: this.throwIfAborted.bind(this),
resolveSession: this.resolveSessionAsync.bind(this),
ensureRuntimeHandle: this.ensureRuntimeHandle.bind(this),
reconcileRuntimeSessionIdentifiers: this.reconcileRuntimeSessionIdentifiers.bind(this),
isCurrentActor: n
}), e.signal);
}
async setSessionRuntimeMode(e) {
const t = resolveAcpSessionTarget(e);
const n = validateRuntimeModeInput(e.runtimeMode);
return await this.withSessionActor(t, async (r) => {
return await runSetManagerSessionRuntimeOption({
assertActive: e.assertActive,
cfg: e.cfg,
...t,
update: { runtimeMode: n },
...this.runtimeOptionCommandServices(r)
});
});
}
async setSessionConfigOption(e) {
const t = resolveAcpSessionTarget(e);
const { key: n, value: r } = validateRuntimeConfigOptionInput(e.key, e.value);
return await this.withSessionActor(t, async (i) => {
return await runSetManagerSessionRuntimeOption({
assertActive: e.assertActive,
cfg: e.cfg,
...t,
update: {
key: n,
value: r
},
...this.runtimeOptionCommandServices(i)
});
});
}
async updateSessionRuntimeOptions(e) {
const t = resolveAcpSessionTarget(e);
const n = validateRuntimeOptionPatch(e.patch);
return await this.withSessionActor(t, async (r) => {
return await runUpdateManagerSessionRuntimeOptions({
assertActive: e.assertActive,
cfg: e.cfg,
...t,
patch: n,
...this.runtimeOptionCommandServices(r)
});
});
}
async resetSessionRuntimeOptions(e) {
const t = resolveAcpSessionTarget(e);
return await this.withSessionActor(t, async (n) => {
return await runResetManagerSessionRuntimeOptions({
assertActive: e.assertActive,
cfg: e.cfg,
...t,
...this.runtimeOptionCommandServices(n)
});
});
}
/**
* Runs one ACP turn as a session-controller turn on its target session.
* A same-session caller's turn is inherited; any other caller waits in the target's mailbox.
*/
async runTurn(e) {
const t = resolveAcpSessionTarget(e);
const { storePath: n, storeSessionKey: r } = resolveSessionStorePathForAcp({
cfg: e.cfg,
...t
});
const i = registerSessionControllerProducer({
owner: this.producerOwner,
target: captureSessionTarget({
storeScope: n,
sessionKey: r,
agentId: t.agentId
}),
runInstance: e.admittedRunContext.operationalRunInstance
});
const a = getCurrentSessionControllerClaim();
const o = getCurrentSessionControllerOwner();
const s = this.actorQueue.capture(acpSessionActorKey(t));
const assertCurrent = () => {
if (!s.isCurrent()) throw createSupersededActorError(t.sessionKey);
};
const c = Date.now();
const l = `${n}\u0000${acpSessionActorKey(t)}\u0000${e.requestId}`;
this.liveTurnRequests.set(l, (this.liveTurnRequests.get(l) ?? 0) + 1);
let u = true;
const leave = () => {
if (u) {
u = false;
const e = (this.liveTurnRequests.get(l) ?? 1) - 1;
if (e > 0) this.liveTurnRequests.set(l, e);
else this.liveTurnRequests.delete(l);
}
return !this.liveTurnRequests.has(l);
};
const d = AbortSignal.any([
i.signal,
this.lifecycle.signal,
...e.signal ? [e.signal] : []
]);
let f = false;
let p = d.aborted;
let m;
const publishCancelled = () => {
m ??= publishManagerCancelledTurnBeforeStart({
input: e,
target: t,
ownsRunTerminal: leave(),
assertActorCurrent: assertCurrent,
prepareSessionControlRead: (e) => this.deps.prepareSessionControlRead(e)
}).then(() => {
this.recordTurnCompletion({ startedAt: c });
});
return m;
};
try {
await withSessionTurn({
...t,
storePath: n,
abortSignal: d,
onCancelled: () => {
p = true;
},
onSettled: async () => {
if (!f && (p || d.aborted)) await publishCancelled();
}
}, async (n, r) => {
i.retainCleanupForSources(getCurrentSessionControllerClaim()?.inputs ?? []);
try {
await this.withSessionActor(t, async (s) => {
f = true;
await runManagerTurn({
input: {
...e,
signal: r
},
...t,
runtimeHandles: this.runtimeHandles,
activeTurnBySession: this.activeTurnBySession,
resolveSession: this.resolveSessionAsync.bind(this),
prepareSessionControlRead: this.deps.prepareSessionControlRead,
ensureRuntimeHandle: this.ensureRuntimeHandle.bind(this),
setSessionState: this.setSessionState.bind(this),
recordTurnCompletion: this.recordTurnCompletion.bind(this),
reconcileRuntimeSessionIdentifiers: this.reconcileRuntimeSessionIdentifiers.bind(this),
writeSessionMeta: this.writeSessionMeta.bind(this),
isCurrentActor: s,
producer: i,
ownsTurnTerminal: getCurrentSessionControllerClaim() !== a || n !== void 0 && n !== o
});
}, r);
} catch (e) {
if (f || !r.aborted) throw e;
p = true;
await publishCancelled();
}
});
} catch (e) {
if (f || !(p || d.aborted || isAbortError(e))) throw e;
try {
await publishCancelled();
} catch (e) {
i.recordCancellationFailure(e);
throw e;
}
} finally {
leave();
s.release();
i.release();
}
}
/** Cancels captured ACP invocations, or the idle backend when no turn was accepted. */
async cancelSession(e) {
await runManagerCancelSession({
...e,
producerOwner: this.producerOwner,
withSessionActor: this.withSessionActor.bind(this),
resolveSession: this.resolveSessionAsync.bind(this),
prepareSessionControlRead: this.deps.prepareSessionControlRead,
ensureRuntimeHandle: this.ensureRuntimeHandle.bind(this),
runtimeHandles: this.runtimeHandles,
setSessionState: this.setSessionState.bind(this)
});
}
async closeSession(e) {
const t = {
...e,
expectedControlBinding: e.expectedControlBinding ? { ...e.expectedControlBinding } : void 0
};
const n = resolveAcpSessionTarget(t);
return await this.withSessionActor(n, async (e) => await runManagerCloseSession({
input: t,
...n,
deps: this.deps,
runtimeHandles: this.runtimeHandles,
resolveSession: this.resolveSessionAsync.bind(this),
ensureRuntimeHandle: this.ensureRuntimeHandle.bind(this),
writeSessionMeta: this.writeSessionMeta.bind(this),
isCurrentActor: e
}));
}
async ensureRuntimeHandle(e) {
return await ensureManagerRuntimeHandle({
...e,
deps: this.deps,
runtimeHandles: this.runtimeHandles,
writeSessionMeta: this.writeSessionMeta.bind(this)
});
}
runtimeOptionCommandServices(e) {
return {
runtimeHandles: this.runtimeHandles,
resolveSession: this.resolveSessionAsync.bind(this),
ensureRuntimeHandle: this.ensureRuntimeHandle.bind(this),
writeSessionMeta: this.writeSessionMeta.bind(this),
isCurrentActor: e
};
}
recordTurnCompletion(e) {
const t = Math.max(0, Date.now() - e.startedAt);
this.turnLatencyStats.totalMs += t;
this.turnLatencyStats.maxMs = Math.max(this.turnLatencyStats.maxMs, t);
if (e.errorCode) {
this.turnLatencyStats.failed += 1;
const t = normalizeAcpErrorCode(e.errorCode);
this.errorCountsByCode.set(t, (this.errorCountsByCode.get(t) ?? 0) + 1);
return;
}
this.turnLatencyStats.completed += 1;
}
async setSessionState(e) {
await this.writeSessionMeta({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
skipMaintenance: true,
takeCacheOwnership: true,
isCurrentActor: e.isCurrentActor,
assertCommitAllowed: e.assertCurrent,
failOnError: e.assertCurrent !== void 0,
acpControl: e.acpControl,
mutate: (t, n) => {
e.assertCurrent?.();
if (!n || !t) return null;
const r = {
backend: t.backend,
agent: t.agent,
runtimeSessionName: t.runtimeSessionName,
...t.identity ? { identity: t.identity } : {},
mode: t.mode,
...t.runtimeOptions ? { runtimeOptions: t.runtimeOptions } : {},
...t.cwd ? { cwd: t.cwd } : {},
state: e.state,
lastActivityAt: Date.now(),
...t.lastError ? { lastError: t.lastError } : {}
};
const i = normalizeOptionalString(e.lastError);
if (i) r.lastError = i;
else if (e.clearLastError) delete r.lastError;
return r;
}
});
}
async reconcileRuntimeSessionIdentifiers(e) {
return await reconcileManagerRuntimeSessionIdentifiers({
...e,
setCachedHandle: (e, t) => {
const n = this.runtimeHandles.get(e);
if (n) n.handle = t;
},
writeSessionMeta: this.writeSessionMeta.bind(this)
});
}
async writeSessionMeta(e) {
try {
const t = {
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId,
mutate: e.mutate,
...e.expectedControlBinding ? { expectedControlBinding: e.expectedControlBinding } : {},
assertCommitAllowed: () => {
e.assertCommitAllowed?.();
if (e.isCurrentActor && !e.isCurrentActor()) throw createSupersededActorError(e.sessionKey);
},
...e.skipMaintenance === true ? { skipMaintenance: true } : {},
...e.takeCacheOwnership === true ? { takeCacheOwnership: true } : {}
};
return e.acpControl ? await this.deps.upsertSessionMetaForControl(t, e.acpControl) : await this.deps.upsertSessionMeta(t);
} catch (t) {
if (e.isCurrentActor && !e.isCurrentActor()) throw createSupersededActorError(e.sessionKey);
if (e.failOnError || t instanceof AgentSelectionRequiredError) throw t;
logVerbose(`acp-manager: failed persisting ACP metadata for ${e.sessionKey}: ${String(t)}`);
return null;
}
}
async withSessionActor(e, t, n) {
const r = acpSessionActorKey(e);
this.throwIfAborted(n);
let i = false;
const a = this.actorQueue.run(r, async (e) => {
i = true;
this.throwIfAborted(n);
return await t(e);
});
if (!n) return await a;
const o = createDeferredCore();
const onAbort = () => {
if (i) return;
try {
this.throwIfAborted(n);
} catch (e) {
o.reject(e);
}
};
n.addEventListener("abort", onAbort, { once: true });
a.then(o.resolve, (e) => o.reject(toErrorObject(e, "Non-Error rejection")));
if (n.aborted) onAbort();
try {
return await o.promise;
} finally {
n.removeEventListener("abort", onAbort);
}
}
throwIfAborted(e) {
if (!e?.aborted) return;
throw new AcpRuntimeError("ACP_TURN_FAILED", "ACP operation aborted.");
}
};
//#endregion
//#region src/acp/control-plane/manager.ts
/** Public singleton facade for the ACP session manager control plane. */
let ACP_SESSION_MANAGER_SINGLETON = null;
/** Returns the process-wide ACP session manager singleton. */
function getAcpSessionManager() {
if (!ACP_SESSION_MANAGER_SINGLETON) ACP_SESSION_MANAGER_SINGLETON = new AcpSessionManager();
return ACP_SESSION_MANAGER_SINGLETON;
}
/**
* Drains the process-wide manager and retires it, so a same-process Gateway
* restart builds a fresh manager instead of inheriting a stopped one.
*/
async function disposeAcpSessionManager(e) {
const t = ACP_SESSION_MANAGER_SINGLETON;
if (!t) return;
try {
await disposeAcpSessionManagerInstance(t, e);
} finally {
if (ACP_SESSION_MANAGER_SINGLETON === t) ACP_SESSION_MANAGER_SINGLETON = null;
}
}
const testing = {
resetAcpSessionManagerForTests() {
ACP_SESSION_MANAGER_SINGLETON = null;
},
setAcpSessionManagerForTests(e) {
ACP_SESSION_MANAGER_SINGLETON = e;
}
};
//#endregion
export { isRejectedConfigOptionValue as a, isAcpOwnerRepairRequired as c, AcpSessionManager as i, consumeAcpTurnStream as l, getAcpSessionManager as n, getAcpSessionResetControls as o, testing as r, tryPrepareFreshManagerRuntimeSession as s, disposeAcpSessionManager as t };