openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
544 lines (543 loc) • 19.8 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { d as readErrorName, p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as SessionTranscriptReadFenceError } from "./session-transcript-read-fence-error-cGIB8yjw.mjs";
import { D as runWithGatewayRootWorkReadmission, f as isGatewaySubordinateWorkAdmissionClosed, g as resetGatewayWorkAdmission, t as GatewayDrainingError } from "./gateway-work-admission-79pid1hQ.mjs";
import { i as logLaneEnqueue, r as logLaneDequeue, t as diagnosticLogger } from "./diagnostic-runtime-BxwnWXDu.mjs";
import { n as SUBAGENT_LANE_PREFIX, r as SWARM_LANE_PREFIX } from "./lanes-BXfh4YnJ.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/process/command-queue.state.ts
function getDefaultLaneConcurrency(e) {
if (e === "restart-recovery") return 4;
return e.startsWith("subagent:") && !e.startsWith("subagent:swarm:") ? getQueueState().lanes.get("subagent")?.maxConcurrent ?? 1 : 1;
}
const PRIORITY_HEAD_START_MS = 15e3;
function getLaneState(e) {
const t = getQueueState();
const n = t.lanes.get(e);
if (n) return n;
const r = {
lane: e,
queue: createLaneQueue(),
activeTasks: /* @__PURE__ */ new Map(),
maxConcurrent: getDefaultLaneConcurrency(e),
draining: false,
generation: 0
};
t.lanes.set(e, r);
return r;
}
function createQueueFifo() {
return {
head: void 0,
tail: void 0
};
}
function createLaneQueue() {
return {
background: createQueueFifo(),
normal: createQueueFifo(),
foreground: createQueueFifo(),
length: 0
};
}
function getPriorityFifo(e, t) {
switch (t) {
case 1: return e.foreground;
case -1: return e.background;
default: return e.normal;
}
}
/** Append to a priority FIFO; return enqueue-time backlog, not predicted admission order. */
function enqueueLaneQueue(e, t) {
const n = getPriorityFifo(e, t.priority);
const r = e.length;
t.queued = true;
t.previous = n.tail;
t.next = void 0;
if (n.tail) n.tail.next = t;
else n.head = t;
n.tail = t;
e.length += 1;
return r;
}
function peekLaneQueue(e) {
let t = e.foreground.head;
for (const n of [e.normal.head, e.background.head]) if (n && (!t || compareQueueEntries(n, t) < 0)) t = n;
return t;
}
/** Bound priority overtaking without timers, promotion, or scanning a backlog. */
function compareQueueEntries(e, t) {
return e.enqueuedAt - t.enqueuedAt + (t.priority - e.priority) * PRIORITY_HEAD_START_MS || e.sequence - t.sequence;
}
function dequeueLaneQueue(e) {
const t = peekLaneQueue(e);
if (t) removeLaneQueueEntry(e, t);
return t;
}
/** Unlink without scanning successors, including when one abort cancels an entire backlog. */
function removeLaneQueueEntry(e, t) {
if (!t.queued) return false;
const n = getPriorityFifo(e, t.priority);
if (t.previous) t.previous.next = t.next;
else n.head = t.next;
if (t.next) t.next.previous = t.previous;
else n.tail = t.previous;
t.queued = void 0;
e.length -= 1;
const r = t.releaseQueuedAbort;
t.previous = void 0;
t.next = void 0;
t.releaseQueuedAbort = void 0;
r?.();
return true;
}
const queueState = resolveGlobalSingleton(Symbol.for("openclaw.commandQueueState"), () => ({
lanes: /* @__PURE__ */ new Map(),
nextTaskId: 1,
nextQueueSequence: 1,
laneGroups: /* @__PURE__ */ new Map(),
laneGroupByLane: /* @__PURE__ */ new Map()
}));
function getQueueState() {
return queueState;
}
function normalizeLane(e) {
return e.trim() || "main";
}
//#endregion
//#region src/process/command-queue.capacity-groups.ts
/** Shared across fresh module instances so one group cannot re-enter its arbiter. */
const DRAINING_GROUPS = resolveGlobalSingleton(Symbol.for("openclaw.commandQueueDrainingGroups"), () => /* @__PURE__ */ new WeakSet());
/**
* Lanes that must never join a group, because a group member can be made to
* wait for a sibling and these lanes can be synchronously awaited by other
* lanes — which would turn a wait into a deadlock.
*
* Known wait edges at this base: outer `cron` -> `cron-nested`
* (`server-cron.ts` passes lane "cron"; `agents/lanes.ts` remaps inner work),
* `main` -> `system-agent` -> `system-agent-inference` (delegated expert
* inference), and setup probes -> their embedded-agent global lane.
*/
const GROUP_INELIGIBLE_LANES = /* @__PURE__ */ new Set([
"cron",
"main",
"system-agent",
"subagent",
"nested"
]);
const GROUP_INELIGIBLE_PREFIXES = [
"session:probe-",
"nested:",
SUBAGENT_LANE_PREFIX,
"context-engine-turn-maintenance:"
];
function assertGroupEligibleLane(e) {
if (GROUP_INELIGIBLE_LANES.has(e)) throw new Error(`command lane "${e}" cannot join a capacity group: it can be synchronously awaited by another lane`);
for (const t of GROUP_INELIGIBLE_PREFIXES) if (e.startsWith(t)) throw new Error(`command lane "${e}" cannot join a capacity group: "${t}*" lanes can be synchronously awaited`);
}
function getLaneGroup(e) {
const { laneGroups: t, laneGroupByLane: n } = getQueueState();
const r = n.get(e);
return r ? t.get(r) : void 0;
}
/**
* Active task count for a group member WITHOUT creating the lane. Creating it
* here would resurrect lanes that `retireIdleScopedCommandLane` just removed.
*/
function getMemberActiveCount(e) {
return getQueueState().lanes.get(e)?.activeTasks.size ?? 0;
}
function readGroupCapacity(e) {
let t = 0;
let n = 0;
for (const r of e.members) {
const i = getMemberActiveCount(r);
t += i;
n += Math.max(0, (e.reservations.get(r) ?? 0) - i);
}
return {
active: t,
reserved: n
};
}
function resolveGroupBlockReason(e, t, n) {
if (n.active >= e.budget) return "group-budget";
if (getMemberActiveCount(t) < (e.reservations.get(t) ?? 0)) return null;
return n.active + n.reserved < e.budget ? null : "sibling-reservation";
}
/** Fill a fresh snapshot from one synchronous group-capacity observation. */
function applyCommandLaneCapacity(e) {
const t = getLaneGroup(e.lane);
const n = t ? readGroupCapacity(t) : void 0;
e.blockedBy = e.activeCount >= e.maxConcurrent ? "lane" : t && n ? resolveGroupBlockReason(t, e.lane, n) : null;
if (t && n) {
e.group = t.group;
e.groupActive = n.active;
e.groupBudget = t.budget;
e.reservedForLane = t.reservations.get(e.lane) ?? 0;
}
}
function canAdmitInGroup(e) {
const t = getLaneGroup(e);
return !t || resolveGroupBlockReason(t, e, readGroupCapacity(t)) === null;
}
/**
* Membership is held here, keyed by lane name, and deliberately NOT inside
* `LaneState`: `setCommandLaneConcurrency` must not be able to detach a lane
* from its group, or session suspend/resume would silently restore a member to
* ungoverned concurrency.
*/
function validateCommandLaneGroupSpec(e, t) {
const n = new Set(t.members.map((e) => normalizeLane(e)));
for (const e of n) assertGroupEligibleLane(e);
const r = /* @__PURE__ */ new Map();
let i = 0;
for (const [a, o] of Object.entries(t.reservations ?? {})) {
const t = normalizeLane(a);
if (!n.has(t)) throw new Error(`command lane group "${e}" reserves for non-member lane "${t}"`);
const s = Math.max(0, Math.floor(o));
r.set(t, s);
i += s;
}
const a = Math.max(0, Math.floor(t.budget));
if (i > a) throw new Error(`command lane group "${e}" reserves ${i} slots but its budget is ${a}`);
return {
group: e,
budget: a,
members: n,
reservations: r
};
}
/** Install a validated group, detaching its members from any previous owner. */
function installCommandLaneGroup(e) {
const { laneGroups: t, laneGroupByLane: n } = getQueueState();
const r = t.get(e.group);
if (r) for (const e of r.members) n.delete(e);
for (const r of e.members) {
const i = n.get(r);
if (i && i !== e.group) t.get(i)?.members.delete(r);
}
t.set(e.group, e);
for (const t of e.members) n.set(t, e.group);
}
/**
* Select the earliest eligible head under the queue's bounded priority order.
*/
function resolveNextGroupLane(e) {
let t;
let n;
for (const r of e.members) {
const i = getQueueState().lanes.get(r);
const a = i ? peekLaneQueue(i.queue) : void 0;
if (!i || !a || i.draining || i.activeTasks.size >= i.maxConcurrent) continue;
n ??= readGroupCapacity(e);
if (resolveGroupBlockReason(e, r, n) !== null) continue;
if (!t || compareQueueEntries(a, t.head) < 0) t = {
lane: r,
head: a
};
}
return t?.lane;
}
/**
* Drain a capacity group one admission at a time.
*
* Per-lane queues already apply bounded priority and global sequence. The
* group applies the same order across member queue heads so a completing lane
* cannot synchronously reclaim shared capacity ahead of an older sibling.
*/
function drainCommandLaneGroup(e, t) {
const n = getLaneGroup(e);
if (!n || DRAINING_GROUPS.has(n)) return;
DRAINING_GROUPS.add(n);
try {
while (getQueueState().laneGroups.get(n.group) === n) {
const e = resolveNextGroupLane(n);
if (!e || t(e, 1) === 0) return;
}
} finally {
DRAINING_GROUPS.delete(n);
}
}
//#endregion
//#region src/process/expected-run-cancellation.ts
function isExpectedRunCancellation(e) {
if (e instanceof GatewayDrainingError || e instanceof SessionTranscriptReadFenceError) return true;
if (e instanceof AggregateError) return e.errors.length > 0 && e.errors.every(isExpectedRunCancellation) && (e.cause === void 0 || isExpectedRunCancellation(e.cause));
return e instanceof Error && e.cause !== void 0 && isExpectedRunCancellation(e.cause);
}
//#endregion
//#region src/process/command-queue.ts
/**
* Dedicated error type thrown when an active command exceeds its caller-owned
* lane timeout. The underlying task may still be unwinding, but the lane is
* released so queued work is not blocked forever.
*/
var CommandLaneTaskTimeoutError = class extends Error {
constructor(e, t) {
const n = (() => {
switch (t.cause) {
case "task-budget": return `elapsed ${t.elapsedMs}ms reached task budget ${t.taskBudgetMs}ms`;
case "owner-deadline": return `owner deadline reached after ${t.elapsedMs}ms`;
case "progress-idle": return `no progress for ${t.idleMs}ms (task budget ${t.taskBudgetMs}ms, elapsed ${t.elapsedMs}ms)`;
case "abort-grace": return `abort grace ${t.graceMs}ms elapsed (task budget ${t.taskBudgetMs}ms, elapsed ${t.elapsedMs}ms)`;
case "release-signal": return `lane release requested after ${t.elapsedMs}ms (task budget ${t.taskBudgetMs}ms)`;
default: throw new TypeError("Unsupported command lane timeout cause");
}
})();
super(`Command lane "${e}" task timed out: ${n}`);
this.name = "CommandLaneTaskTimeoutError";
}
};
function isCommandLaneTaskTimeoutError(e, t) {
if (!(e instanceof Error)) return false;
if (!(e instanceof CommandLaneTaskTimeoutError || e.name === "CommandLaneTaskTimeoutError")) return false;
return t === void 0 || e.message.includes(`Command lane "${t}" task timed out`);
}
function isExpectedNonErrorLaneFailure(e) {
return e instanceof Error && e.name === "LiveSessionModelSwitchError" || isExpectedRunCancellation(e);
}
function isQuietProbeLane(e) {
return e.startsWith("auth-probe:") || e.startsWith("session:probe-") || e.startsWith("session:temp:setup-inference:probe-setup-inference-");
}
function getLaneDepth(e) {
return e.queue.length + e.activeTasks.size;
}
function retireIdleScopedCommandLane(e) {
if (e.draining || e.activeTasks.size > 0 || e.queue.length > 0 || !e.lane.startsWith("subagent:") && (e.maxConcurrent !== 1 || !e.lane.startsWith("session:probe-") && !e.lane.startsWith("nested:") && !e.lane.startsWith("cli:") && !e.lane.startsWith("context-engine-turn-maintenance:"))) return;
const t = getQueueState().lanes;
if (t.get(e.lane) === e) t.delete(e.lane);
}
function resolveQueuePriority(e) {
switch (e) {
case "foreground": return 1;
case "background": return -1;
default: return 0;
}
}
function drainLane(e, t = Number.POSITIVE_INFINITY, n = getLaneState(e)) {
if (n.draining) {
if (n.activeTasks.size === 0 && n.queue.length > 0) diagnosticLogger.warn(`drainLane blocked: lane=${e} draining=true active=0 queue=${n.queue.length}`);
return 0;
}
n.draining = true;
let r = 0;
try {
while (r < t && n.activeTasks.size < n.maxConcurrent && n.queue.length > 0 && canAdmitInGroup(e)) {
const t = dequeueLaneQueue(n.queue);
const i = Math.floor(performance.now()) - t.enqueuedAt;
const a = n.activeTasks.size;
const o = getQueueState().nextTaskId++;
const s = n.generation;
n.activeTasks.set(o, t.sessionTarget);
r += 1;
const c = Date.now();
(async () => {
try {
if (i >= t.warnAfterMs) {
try {
t.onWait?.(i, t.queuedAheadAtEnqueue);
} catch (t) {
diagnosticLogger.error(`lane onWait callback failed: lane=${e} error="${String(t)}"`);
}
diagnosticLogger.warn(`lane wait exceeded: lane=${e} waitedMs=${i} queueAhead=${t.queuedAheadAtEnqueue} activeAhead=${t.activeAheadAtEnqueue} activeNow=${a} queueBehind=${n.queue.length}`, t.taskIdentity);
}
logLaneDequeue(e, i, n.queue.length);
return await Promise.resolve().then(() => t.task());
} finally {
if (s === n.generation) {
n.activeTasks.delete(o);
drainReadyCommandLane(e, n);
}
}
})().then((e) => {
t.resolve(e);
}, (n) => {
t.reject(n);
const r = isQuietProbeLane(e) || t.taskIdentity?.modelFallbackCandidate && readErrorName(n) === "FailoverError";
if (!r && !isExpectedNonErrorLaneFailure(n)) diagnosticLogger.error(`lane task error: lane=${e} durationMs=${Date.now() - c} error=${JSON.stringify(formatErrorMessage(n))}`, {
errorName: readErrorName(n) || void 0,
...t.taskIdentity
});
else if (!r) diagnosticLogger.debug(`lane task interrupted: lane=${e} durationMs=${Date.now() - c} reason="${String(n)}"`);
}).catch(() => {
try {
diagnosticLogger.warn(`lane task diagnostics failed after settlement: lane=${e} taskId=${o} generation=${s}`, t.taskIdentity);
} catch {}
});
}
} finally {
n.draining = false;
retireIdleScopedCommandLane(n);
}
return r;
}
function drainReadyCommandLane(e, t) {
runInDetachedAsyncContext(() => {
if (getLaneGroup(e)) {
drainCommandLaneGroup(e, drainLane);
return;
}
drainLane(e, Number.POSITIVE_INFINITY, t);
});
}
function updateLaneConcurrency(e, t) {
const n = getLaneState(e);
const r = isQuietProbeLane(e) ? 1 : 0;
n.maxConcurrent = Math.max(r, Math.floor(t));
const i = [n];
if (e === "subagent") {
for (const e of getQueueState().lanes.values()) if (e.lane.startsWith("subagent:") && !e.lane.startsWith("subagent:swarm:")) {
e.maxConcurrent = n.maxConcurrent;
i.push(e);
}
}
return i;
}
/**
* Publish lane widths and groups before draining: per-lane setters could admit
* work before its group budget exists. Grouped callers must use this transaction.
*/
function publishLaneConfiguration(e) {
const t = Object.entries(e.groups ?? {}).map(([e, t]) => validateCommandLaneGroupSpec(e, t));
const n = /* @__PURE__ */ new Set();
for (const [t, r] of Object.entries(e.lanes ?? {})) {
const e = normalizeLane(t);
for (const t of updateLaneConcurrency(e, r)) n.add(t.lane);
}
for (const t of e.clearGroups ?? []) {
const { laneGroups: e, laneGroupByLane: r } = getQueueState();
const i = e.get(t);
if (i) {
for (const e of i.members) {
r.delete(e);
n.add(e);
}
e.delete(t);
}
}
for (const e of t) {
const { laneGroups: t, laneGroupByLane: r } = getQueueState();
const i = t.get(e.group);
for (const e of i?.members ?? []) n.add(e);
for (const i of e.members) {
const e = r.get(i);
for (const r of t.get(e ?? "")?.members ?? []) n.add(r);
}
installCommandLaneGroup(e);
for (const t of e.members) n.add(t);
}
for (const e of n) {
const t = getQueueState().lanes.get(e);
if (t && t.maxConcurrent > 0 && t.queue.length > 0 && !t.draining) drainReadyCommandLane(e);
}
}
function setCommandLaneConcurrency(e, t) {
const n = normalizeLane(e);
for (const e of updateLaneConcurrency(n, t)) if (e.maxConcurrent > 0) drainReadyCommandLane(e.lane);
}
function enqueueCommandInLane(e, t, n) {
if (n?.abortSignal?.aborted) return Promise.reject(toErrorObject(n.abortSignal.reason, "Queued command aborted"));
const r = getQueueState();
if (isGatewaySubordinateWorkAdmissionClosed()) return Promise.reject(new GatewayDrainingError());
const i = AsyncLocalStorage.snapshot();
const { onWait: a } = n ?? {};
const o = normalizeLane(e);
const s = n?.warnAfterMs ?? 2e3;
const c = getLaneState(o);
if (n?.maxConcurrent !== void 0) c.maxConcurrent = Math.max(0, Math.floor(n.maxConcurrent));
return new Promise((e, l) => {
const u = {
task: () => i(runWithGatewayRootWorkReadmission, t),
resolve: (t) => e(t),
reject: l,
enqueuedAt: Math.floor(performance.now()),
sequence: r.nextQueueSequence++,
priority: resolveQueuePriority(n?.priority),
warnAfterMs: s,
queuedAheadAtEnqueue: 0,
activeAheadAtEnqueue: 0,
taskIdentity: n?.taskIdentity ? { ...n.taskIdentity } : void 0,
sessionTarget: n?.sessionTarget ? { ...n.sessionTarget } : void 0,
onWait: a ? (...e) => i(a, ...e) : void 0
};
u.queuedAheadAtEnqueue = enqueueLaneQueue(c.queue, u);
u.activeAheadAtEnqueue = c.activeTasks.size;
const d = n?.abortSignal;
if (d) {
const onAbort = () => {
u.releaseQueuedAbort = void 0;
if (removeLaneQueueEntry(c.queue, u)) {
u.reject(toErrorObject(d.reason, "Queued command aborted"));
retireIdleScopedCommandLane(c);
}
};
d.addEventListener("abort", onAbort, { once: true });
u.releaseQueuedAbort = () => d.removeEventListener("abort", onAbort);
}
logLaneEnqueue(o, getLaneDepth(c));
drainReadyCommandLane(o);
if (u.queued) try {
n?.onQueued?.();
} catch (e) {
diagnosticLogger.error(`lane onQueued callback failed: lane=${o} error="${String(e)}"`);
}
});
}
function getQueueSize(e = "main") {
const t = getQueueState().lanes.get(normalizeLane(e));
if (!t) return 0;
return getLaneDepth(t);
}
function getCommandLaneSnapshot(e = "main") {
const t = normalizeLane(e);
const n = getQueueState().lanes.get(t);
const r = {
lane: n?.lane ?? t,
queuedCount: n?.queue.length ?? 0,
activeCount: n?.activeTasks.size ?? 0,
maxConcurrent: n?.maxConcurrent ?? getDefaultLaneConcurrency(t),
draining: n?.draining ?? false,
generation: n?.generation ?? 0,
blockedBy: null,
...t.startsWith("subagent:swarm:") ? {
concurrencyScope: "swarm",
swarmGroupKey: t.slice(SWARM_LANE_PREFIX.length)
} : {}
};
applyCommandLaneCapacity(r);
return r;
}
/** Per-lane work totals for every live lane; diagnostics composition lives in command-lane-diagnostics.ts. */
function listCommandLaneTotals() {
return [...getQueueState().lanes.values()].map((e) => ({
lane: e.lane,
activeCount: e.activeTasks.size,
queuedCount: e.queue.length
}));
}
function getTotalQueueSize() {
let e = 0;
for (const t of getQueueState().lanes.values()) e += getLaneDepth(t);
return e;
}
/**
* SIGUSR2 may abandon finally blocks. Retire old active generations while
* preserving and immediately draining queued user work under the reset state.
*/
function resetAllLanes() {
const e = getQueueState();
resetGatewayWorkAdmission();
const t = [];
for (const n of e.lanes.values()) {
n.generation += 1;
n.activeTasks.clear();
n.draining = false;
if (n.queue.length > 0) t.push(n.lane);
}
for (const e of t) drainReadyCommandLane(e);
}
//#endregion
export { getTotalQueueSize as a, publishLaneConfiguration as c, isExpectedRunCancellation as d, getLaneGroup as f, getQueueSize as i, resetAllLanes as l, enqueueCommandInLane as n, isCommandLaneTaskTimeoutError as o, getQueueState as p, getCommandLaneSnapshot as r, listCommandLaneTotals as s, CommandLaneTaskTimeoutError as t, setCommandLaneConcurrency as u };