UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

306 lines (305 loc) • 12.5 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { D as parseStrictPositiveInteger, g as clampTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs"; import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs"; import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs"; import { r as logVerbose } from "./globals-CgepmiqE.mjs"; import { n as AcpRuntimeError } from "./errors-DGA2X_Nu.mjs"; import "./errors-C4nx2HUe.mjs"; import { isAbsolute } from "node:path"; //#region src/acp/control-plane/runtime-options.ts const MAX_RUNTIME_MODE_LENGTH = 64; const MAX_MODEL_LENGTH = 200; const MAX_THINKING_LENGTH = 32; const MAX_PERMISSION_PROFILE_LENGTH = 80; const MAX_CWD_LENGTH = 4096; const MIN_TIMEOUT_SECONDS = 1; const MAX_TIMEOUT_SECONDS = 86400; const MAX_BACKEND_OPTION_KEY_LENGTH = 64; const MAX_BACKEND_OPTION_VALUE_LENGTH = 512; const MAX_BACKEND_EXTRAS = 32; const SAFE_OPTION_KEY_RE = /^[a-z0-9][a-z0-9._:-]*$/i; const RUNTIME_CONFIG_OPTION_ALIASES = { model: ["model"], thinking: [ "thinking", "effort", "reasoning_effort", "thought_level" ], permissionProfile: [ "approval_policy", "permission_profile", "permissions", "permission_mode" ], timeoutSeconds: ["timeout", "timeout_seconds"] }; function failInvalidOption(e) { throw new AcpRuntimeError("ACP_INVALID_RUNTIME_OPTION", e); } function validateBoundedText(e, t, n) { const r = normalizeOptionalString(e); if (!r) failInvalidOption(`${t} must not be empty.`); if (r.length > n) failInvalidOption(`${t} must be at most ${n} characters.`); for (let e = 0; e < r.length; e += 1) { const n = r.charCodeAt(e); if (n < 32 || n === 127) failInvalidOption(`${t} must not include control characters.`); } return r; } function validateRuntimeModeInput(e) { return validateBoundedText(e, "Runtime mode", MAX_RUNTIME_MODE_LENGTH); } function validateRuntimeModelInput(e) { return validateBoundedText(e, "Model id", MAX_MODEL_LENGTH); } function validateRuntimeThinkingInput(e) { return validateBoundedText(e, "Thinking level", MAX_THINKING_LENGTH); } function validateRuntimePermissionProfileInput(e) { return validateBoundedText(e, "Permission profile", MAX_PERMISSION_PROFILE_LENGTH); } function validateRuntimeCwdInput(e) { const t = validateBoundedText(e, "Working directory", MAX_CWD_LENGTH); if (!isAbsolute(t)) failInvalidOption(`Working directory must be an absolute path. Received "${t}".`); return t; } function validateRuntimeTimeoutSecondsInput(e) { if (typeof e !== "number" || !Number.isFinite(e)) failInvalidOption("Timeout must be a positive integer in seconds."); const t = Math.round(e); if (t < MIN_TIMEOUT_SECONDS || t > MAX_TIMEOUT_SECONDS) failInvalidOption(`Timeout must be between ${MIN_TIMEOUT_SECONDS} and ${MAX_TIMEOUT_SECONDS} seconds.`); return t; } function parseRuntimeTimeoutSecondsInput(e) { const t = normalizeOptionalString(e); if (!t || !/^\d+$/.test(t)) failInvalidOption("Timeout must be a positive integer in seconds."); return validateRuntimeTimeoutSecondsInput(parseStrictPositiveInteger(t) ?? 0); } function validateRuntimeConfigOptionInput(e, t) { const n = validateBoundedText(e, "ACP config key", MAX_BACKEND_OPTION_KEY_LENGTH); if (!SAFE_OPTION_KEY_RE.test(n)) failInvalidOption("ACP config key must use letters, numbers, dots, colons, underscores, or dashes."); return { key: n, value: validateBoundedText(t, "ACP config value", MAX_BACKEND_OPTION_VALUE_LENGTH) }; } function validateRuntimeOptionPatch(e) { if (!e) return {}; const t = e; const n = /* @__PURE__ */ new Set([ "runtimeMode", "model", "thinking", "cwd", "permissionProfile", "timeoutSeconds", "backendExtras" ]); for (const e of Object.keys(t)) if (!n.has(e)) failInvalidOption(`Unknown runtime option "${e}".`); const r = {}; function setOption(e, n) { if (Object.hasOwn(t, e)) r[e] = t[e] === void 0 ? void 0 : n(t[e]); } setOption("runtimeMode", validateRuntimeModeInput); setOption("model", validateRuntimeModelInput); setOption("thinking", validateRuntimeThinkingInput); setOption("cwd", validateRuntimeCwdInput); setOption("permissionProfile", validateRuntimePermissionProfileInput); setOption("timeoutSeconds", validateRuntimeTimeoutSecondsInput); if (Object.hasOwn(t, "backendExtras")) { const e = t.backendExtras; if (e === void 0) r.backendExtras = void 0; else if (!e || typeof e !== "object" || Array.isArray(e)) failInvalidOption("Backend extras must be a key/value object."); else { const t = Object.entries(e); if (t.length > MAX_BACKEND_EXTRAS) failInvalidOption(`Backend extras must include at most ${MAX_BACKEND_EXTRAS} entries.`); const n = {}; for (const [e, r] of t) { const { key: t, value: i } = validateRuntimeConfigOptionInput(e, r); n[t] = i; } r.backendExtras = Object.keys(n).length > 0 ? n : void 0; } } return r; } function normalizeRuntimeOptions(e) { const t = {}; for (const n of [ "runtimeMode", "model", "thinking", "cwd", "permissionProfile" ]) { const r = normalizeOptionalString(e?.[n]); if (r) t[n] = r; } if (typeof e?.timeoutSeconds === "number" && Number.isFinite(e.timeoutSeconds)) { const n = Math.round(e.timeoutSeconds); if (n > 0) t.timeoutSeconds = n; } const n = Object.entries(e?.backendExtras ?? {}).map(([e, t]) => [normalizeOptionalString(e), normalizeOptionalString(t)]).filter(([e, t]) => Boolean(e && t)); if (n.length > 0) t.backendExtras = Object.fromEntries(n); return t; } /** Inputs have already passed manager validation and metadata normalization. */ function mergeRuntimeOptions({ current: e = {}, patch: t = {} }) { return normalizeRuntimeOptions({ ...e, ...t, ...t.backendExtras ? { backendExtras: { ...e.backendExtras, ...t.backendExtras } } : {} }); } function isThinkingConfigKey(e) { const t = normalizeLowercaseStringOrEmpty(e); return RUNTIME_CONFIG_OPTION_ALIASES.thinking.some((e) => e === t); } /** Reconcile only selected thinking; backend defaults must not become new session overrides. */ function reconcileAcceptedRuntimeOptions(e, t, n) { if (!t || !e.thinking) return e; const r = t.configOptions.find((e) => e.category === "thought_level" || isThinkingConfigKey(e.id)); if (n && (r?.currentValue === n || r?.options?.some((e) => "options" in e ? e.options.some((e) => e.value === n) : e.value === n))) return e; return normalizeRuntimeOptions({ ...e, thinking: typeof r?.currentValue === "string" ? r.currentValue : void 0 }); } function resolveRuntimeOptionsFromMeta(e) { return normalizeRuntimeOptions({ ...e.runtimeOptions, cwd: normalizeOptionalString(e.runtimeOptions?.cwd) ?? e.cwd }); } function runtimeOptionsEqual(e, t) { return JSON.stringify(normalizeRuntimeOptions(e)) === JSON.stringify(normalizeRuntimeOptions(t)); } function buildRuntimeControlSignature(e) { const t = Object.entries(e.backendExtras ?? {}).toSorted(([e], [t]) => e.localeCompare(t)); return JSON.stringify({ runtimeMode: e.runtimeMode ?? null, model: e.model ?? null, thinking: e.thinking ?? null, permissionProfile: e.permissionProfile ?? null, timeoutSeconds: e.timeoutSeconds ?? null, backendExtras: t }); } function buildRuntimeConfigOptionPairs(e, t) { const n = /* @__PURE__ */ new Map(); const r = buildAdvertisedConfigOptionKeyMap(t); const resolveKey = (e) => resolveRuntimeConfigOptionKeyFromMap(e, r); const shouldEmit = (e) => r.size === 0 || e.some((e) => r.has(e)); if (e.model) n.set(resolveKey("model"), e.model); if (e.thinking && shouldEmit(RUNTIME_CONFIG_OPTION_ALIASES.thinking)) n.set(resolveKey("thinking"), e.thinking); if (e.permissionProfile) n.set(resolveKey("approval_policy"), e.permissionProfile); if (e.timeoutSeconds !== void 0 && shouldEmit(RUNTIME_CONFIG_OPTION_ALIASES.timeoutSeconds)) n.set(resolveKey("timeout"), String(e.timeoutSeconds)); for (const [t, r] of Object.entries(e.backendExtras ?? {})) { const e = resolveKey(t); if (!n.has(e)) n.set(e, r); } return [...n.entries()]; } function buildAdvertisedConfigOptionKeyMap(e) { const t = /* @__PURE__ */ new Map(); for (const n of e ?? []) { const e = normalizeOptionalString(n); if (e && !t.has(e.toLowerCase())) t.set(e.toLowerCase(), e); } return t; } function resolveRuntimeConfigOptionKey(e, t) { return resolveRuntimeConfigOptionKeyFromMap(e, buildAdvertisedConfigOptionKeyMap(t)); } function resolveRuntimeConfigOptionKeyFromMap(e, t) { const n = normalizeOptionalString(e) ?? ""; const r = n.toLowerCase(); if (!n || t.size === 0) return n; const i = t.get(r); if (i) return i; const a = Object.values(RUNTIME_CONFIG_OPTION_ALIASES).find((e) => e.some((e) => e === r)); for (const e of a ?? []) { const n = t.get(e); if (n) return n; } return n; } function inferRuntimeOptionPatchFromConfigOption(e, t) { const n = e.toLowerCase(); if (n === "model") return { model: validateRuntimeModelInput(t) }; if (isThinkingConfigKey(n)) return { thinking: validateRuntimeThinkingInput(t) }; if (RUNTIME_CONFIG_OPTION_ALIASES.permissionProfile.some((e) => e === n)) return { permissionProfile: validateRuntimePermissionProfileInput(t) }; if (RUNTIME_CONFIG_OPTION_ALIASES.timeoutSeconds.some((e) => e === n)) return { timeoutSeconds: parseRuntimeTimeoutSecondsInput(t) }; if (n === "cwd") return { cwd: validateRuntimeCwdInput(t) }; return { backendExtras: { [e]: t } }; } //#endregion //#region src/acp/control-plane/manager.turn-timeout.ts const ACP_TURN_TIMEOUT_CLEANUP_GRACE_MS = 2e3; const ACP_TURN_TIMEOUT_REASON = "turn-timeout"; const ACP_TURN_TIMEOUT_DETAIL_CODE = "TURN_TIMEOUT"; function resolveTurnTimeoutMs(e) { const t = resolveRuntimeOptionsFromMeta(e.meta).timeoutSeconds; if (t !== void 0) return clampTimerTimeoutMs(t * 1e3, 1e3) ?? 1e3; return resolveAgentTimeoutMs({ cfg: e.cfg, minMs: 1e3 }); } async function awaitTurnWithTimeout(e) { const t = e.timeoutMs <= 0 ? void 0 : clampTimerTimeoutMs(e.timeoutMs, 1); if (t !== void 0 && !await settlesWithin(e.turnPromise, t)) { e.turnPromise.catch((t) => { logVerbose(`acp-manager: detached late turn error after timeout for ${e.sessionKey}: ${String(t)}`); }); await e.onTimeout(); throw new AcpRuntimeError("ACP_TURN_FAILED", `ACP turn timed out after ${Math.max(1, Math.round(e.timeoutLabelMs / 1e3))}s.`, { detailCode: ACP_TURN_TIMEOUT_DETAIL_CODE }); } return await e.turnPromise; } async function cleanupTimedOutTurn(e) { e.activeTurn.abortController.abort(ACP_TURN_TIMEOUT_REASON); if (!e.activeTurn.cancelPromise) e.activeTurn.cancelPromise = e.activeTurn.runtime.cancel({ handle: e.activeTurn.handle, reason: ACP_TURN_TIMEOUT_REASON }); const t = await awaitCleanupWithGrace({ sessionKey: e.sessionKey, label: "cancel", promise: e.activeTurn.cancelPromise }); if (e.mode !== "oneshot") return; const n = e.activeTurn.runtime.close({ handle: e.activeTurn.handle, reason: ACP_TURN_TIMEOUT_REASON }); const r = await awaitCleanupWithGrace({ sessionKey: e.sessionKey, label: "close", promise: n }); if (t && r) { e.clearCachedRuntimeStateIfHandleMatches(e.activeTurn); return; } Promise.allSettled([e.activeTurn.cancelPromise, n]).then(() => { e.clearCachedRuntimeStateIfHandleMatches(e.activeTurn); }); } async function awaitCleanupWithGrace(e) { let t = false; const n = e.promise.catch((n) => { logVerbose(`acp-manager: ${t ? "detached " : ""}timed-out turn ${e.label} cleanup failed for ${e.sessionKey}: ${String(n)}`); }); if (!await settlesWithin(n, ACP_TURN_TIMEOUT_CLEANUP_GRACE_MS)) { t = true; logVerbose(`acp-manager: timed-out turn ${e.label} cleanup exceeded ${ACP_TURN_TIMEOUT_CLEANUP_GRACE_MS}ms for ${e.sessionKey}`); return false; } return true; } //#endregion export { validateRuntimeCwdInput as _, buildRuntimeConfigOptionPairs as a, validateRuntimeOptionPatch as b, isThinkingConfigKey as c, parseRuntimeTimeoutSecondsInput as d, reconcileAcceptedRuntimeOptions as f, validateRuntimeConfigOptionInput as g, runtimeOptionsEqual as h, resolveTurnTimeoutMs as i, mergeRuntimeOptions as l, resolveRuntimeOptionsFromMeta as m, awaitTurnWithTimeout as n, buildRuntimeControlSignature as o, resolveRuntimeConfigOptionKey as p, cleanupTimedOutTurn as r, inferRuntimeOptionPatchFromConfigOption as s, ACP_TURN_TIMEOUT_DETAIL_CODE as t, normalizeRuntimeOptions as u, validateRuntimeModeInput as v, validateRuntimePermissionProfileInput as x, validateRuntimeModelInput as y };