openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
171 lines (170 loc) • 6.28 kB
JavaScript
import { i as throwCollectedErrors } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
//#region src/gateway/worker-environments/inference-control-internal.ts
var WorkerInferenceSessionDrainBusyError = class extends Error {
constructor(e) {
super(`Worker inference drain already owns session ${e}`);
}
};
const sessionControlByService = /* @__PURE__ */ new WeakMap();
function registerWorkerInferenceSessionControl(e, t) {
sessionControlByService.set(e, t);
}
function getWorkerInferenceSessionControl(e) {
if (typeof e !== "object" || e === null) return;
return sessionControlByService.get(e);
}
function safeRevalidate(e, t, n) {
try {
n?.();
return e?.() ?? null;
} catch (e) {
t?.(e);
return "provider-error";
}
}
function matchesIdentity(e, t) {
const n = e.turnClaim;
if (!n || e.sessionId !== t.sessionId || e.runId !== t.runId || n.sessionId !== t.sessionId || n.runId !== t.runId) return "session-not-attached";
if (e.ownerEpoch !== t.runEpoch) return "epoch-mismatch";
return null;
}
var WorkerInferenceAuthorityError = class extends Error {
constructor(e, t) {
super(`Worker inference authority changed: ${e}`, { cause: t });
this.reason = e;
}
};
function preserveInferenceAuthorityFailure(e, t) {
if (!t || e === t.error) return e;
if (e instanceof WorkerInferenceAuthorityError && e.cause === t.error && !hasSqliteWorkerOutcomeUnknown(e)) return t.error;
return new AggregateError([t.error, e], "Worker inference authority and settlement failed", { cause: e });
}
async function joinInferenceOperations(e, t = [], n = "Worker inference settlement failed") {
const r = await Promise.allSettled(e);
const i = [.../* @__PURE__ */ new Set([...r.flatMap((e) => e.status === "rejected" ? [e.reason] : []), ...t])];
throwCollectedErrors(i, n);
}
function createWorkerInferenceSessionControls(e) {
const { active: t, operations: n, unknownSettlements: r, recovered: i, settleAbort: a } = e;
const o = /* @__PURE__ */ new Map();
let s;
const captureCancellationEntries = (e) => [...t.values()].filter(e);
const cancelCaptured = (e, n, r) => {
const i = [];
let o;
try {
for (const o of e) {
r?.assertCurrent?.();
if (t.get(o.claimKey) !== o) continue;
i.push(a(o, n));
r?.onCancelled?.(o.request.runId);
}
} catch (e) {
o = { error: e };
}
return joinInferenceOperations(i, o ? [o.error] : []);
};
const cancelWhere = (e, t) => cancelCaptured(captureCancellationEntries(e), t);
const cancelEnvironment = (e) => cancelWhere((t) => t.identity.environmentId === e, "session-not-attached");
const cancelClaim = (e) => cancelWhere((t) => t.claimKey === e, "session-not-attached");
const captureSessionCancellation = (e, t) => {
const n = captureCancellationEntries((n) => n.request.sessionId === e && (t === void 0 || n.request.runId === t));
const r = joinInferenceOperations(n.flatMap((e) => e.execution ? [e.execution] : []));
r.catch(() => {});
return {
runIds: [...new Set(n.map((e) => e.request.runId))].toSorted(),
settled: r,
executing: n.some((e) => e.execution !== void 0 && !e.settled),
cancel(e) {
const t = /* @__PURE__ */ new Set();
return cancelCaptured(n, "cancelled", {
assertCurrent: e?.assertCurrent,
onCancelled(n) {
t.add(n);
e?.onCancelled?.(n);
}
}).then(() => [...t].toSorted());
}
};
};
const cancelSession = (e, t) => captureSessionCancellation(e, t).cancel();
const hasSession = (e, n) => [...t.values()].some((t) => t.request.sessionId === e && (n === void 0 || t.request.runId === n));
const hasSessionOperation = (e) => [...n.values()].some((t) => t.sessionId === e);
const reserveSessionDrain = (e) => {
if (o.has(e)) throw new WorkerInferenceSessionDrainBusyError(e);
const t = captureCancellationEntries((t) => t.request.sessionId === e);
const i = [...n].filter(([, t]) => t.sessionId === e);
const a = i.map(([e]) => e);
const s = /* @__PURE__ */ new Set([...t.map((e) => e.storeKey), ...i.map(([, e]) => e.storeKey)]);
let c = false;
let l = false;
let u = false;
const release = () => {
u = true;
if (l && o.get(e) === p) o.delete(e);
};
const d = createDeferredCore();
let f;
const p = d.promise.then(() => joinInferenceOperations([...a, f], [...s].flatMap((e) => Array.from(r.get(e) ?? []))));
o.set(e, p);
const settle = () => {
l = true;
if (u) release();
};
p.then(settle, settle);
return {
drained: p,
hasWork: () => hasSession(e) || hasSessionOperation(e),
start(e) {
if (!c) {
c = true;
f = cancelCaptured(t, "cancelled", { assertCurrent: e });
d.resolve();
}
},
release
};
};
const resolveSessionTargetForRunId = (e) => {
let n;
for (const r of t.values()) {
if (r.request.runId !== e) continue;
const t = r.sessionTarget;
if (n && (t.agentId !== n.agentId || t.sessionId !== n.sessionId || t.sessionKey !== n.sessionKey || t.storePath !== n.storePath || t.expectedLifecycleRevision !== n.expectedLifecycleRevision || t.expectedWriterRunId !== n.expectedWriterRunId)) return;
n = t;
}
return n;
};
const stop = () => {
if (s) return s;
const e = createDeferredCore();
s = e.promise;
const t = new Map(o);
const a = cancelWhere((e) => !t.has(e.request.sessionId), "provider-error");
joinInferenceOperations([
i,
...n.keys(),
...t.values(),
a
], [...r.values()].flatMap((e) => Array.from(e))).then(e.resolve, e.reject);
return s;
};
return {
isStopping: () => s !== void 0,
isDraining: (e) => o.has(e),
getClosing: (e) => o.get(e) ?? s,
cancelEnvironment,
cancelClaim,
cancelSession,
captureSessionCancellation,
reserveSessionDrain,
hasSession,
resolveSessionTargetForRunId,
stop
};
}
//#endregion
export { joinInferenceOperations as a, registerWorkerInferenceSessionControl as c, getWorkerInferenceSessionControl as i, safeRevalidate as l, WorkerInferenceSessionDrainBusyError as n, matchesIdentity as o, createWorkerInferenceSessionControls as r, preserveInferenceAuthorityFailure as s, WorkerInferenceAuthorityError as t };