UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

654 lines (653 loc) • 30.7 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { o as getAdmittedSqliteSchemaFacts } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { f as requestSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { o as isGatewayExternallySupervised } from "./gateway-supervision-C1X-e8qk.mjs"; import { r as ensureStatePostgresFragment } from "./openclaw-state-db-engine-sM0tpxNy.mjs"; import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs"; import { t as createSqliteSchemaEnsurer } from "./sqlite-schema-ensure-B6yDrFvM.mjs"; import { t as getOpenClawStateFeatureSchemaSql } from "./openclaw-state-feature-schema-CEI_WUTe.mjs"; import { i as updateConfigMachineStateInDatabase } from "./config-machine-state-write-DanSUxEP.mjs"; import { t as engineGreatest } from "./scalar-Bs87vfbL.mjs"; import { i as normalizeStoredNodeHostConfig } from "./node-worker-prepared-workspace-publication-BHZAZGva.mjs"; import { i as nodeWorkerTurnMatchesIdentity } from "./node-supervisor-protocol-BD491Brs.mjs"; import { t as NodeWorkerPreparedWorkspaceKernel } from "./node-worker-prepared-workspace-store.kernel-CbhSu1Dx.mjs"; //#region src/node-host/node-worker-launch-receipt.ts function validateIdentifier(e, t) { if (!e || e.trim() !== e || e.length > 256 || e.includes("\0")) throw new Error(`${t} must be a bounded non-empty identifier`); } function rowMatchesImmutableIdentity(e, t) { return e.launch_id === t.launchId && e.plan_hash === t.planHash && e.environment_id === t.environmentId && e.session_id === t.sessionId && e.owner_epoch === t.ownerEpoch && e.placement_generation === t.placementGeneration && e.run_id === t.runId; } function isNodeWorkerTerminalState(e) { return e === "completed" || e === "failed" || e === "interrupted" || e === "cancelled"; } function validateNodeWorkerPlanHash(e) { if (!/^[a-f0-9]{64}$/u.test(e)) throw new Error("node worker plan hash must be 64 lowercase hexadecimal characters"); } function validateNodeWorkerProcessIdentity(e) { if (!Number.isSafeInteger(e.pid) || e.pid <= 0 || e.pid > 2147483647 || !Number.isSafeInteger(e.startTime) || e.startTime < 0) throw new Error("node worker process identity must contain a bounded pid and start time"); } function validateNodeWorkerContainerIdentity(e) { if (e.engine !== "docker" && e.engine !== "podman") throw new Error("node worker container engine must be docker or podman"); if (!/^[a-f0-9]{64}$/u.test(e.containerId)) throw new Error("node worker container id must contain exactly 64 lowercase hexadecimal digits"); if (!/^[a-f0-9]{64}$/u.test(e.engineTarget)) throw new Error("node worker container engine target must contain exactly 64 lowercase hexadecimal digits"); } function containerIdentity(e) { if (e == null) return null; let t; try { t = JSON.parse(e); } catch { throw new Error("invalid node worker container identity"); } if (!isRecord(t) || Object.keys(t).length !== 3 || t.engine !== "docker" && t.engine !== "podman" || typeof t.containerId !== "string" || typeof t.engineTarget !== "string") throw new Error("invalid node worker container identity"); const n = { engine: t.engine, containerId: t.containerId, engineTarget: t.engineTarget }; validateNodeWorkerContainerIdentity(n); return n; } function nodeWorkerLaunchReceiptFromRow(e) { if (e.state !== "pending" && e.state !== "running" && !isNodeWorkerTerminalState(e.state)) throw new Error(`invalid node worker launch state ${e.state}`); const t = containerIdentity(e.container_json); const n = e.cleanup_mode ?? null; if (e.scope_kind != null && (e.scope_kind !== "linux-subreaper" || n !== "owned-anchor")) throw new Error("invalid node worker process scope"); if (n !== null && n !== "process-group" && n !== "owned-anchor") throw new Error("invalid node worker cleanup mode"); return { launchId: e.launch_id, planHash: e.plan_hash, gatewayNamespace: e.gateway_namespace, environmentId: e.environment_id, sessionId: e.session_id, ownerEpoch: e.owner_epoch, placementGeneration: e.placement_generation, runId: e.run_id, state: e.state, supervisor: { pid: e.supervisor_pid, startTime: e.supervisor_start_time }, ...e.boot_id ? { bootId: e.boot_id } : {}, worker: e.worker_pid === null || e.worker_start_time === null ? null : { pid: e.worker_pid, startTime: e.worker_start_time }, workerCleanupMode: n === "owned-anchor" && e.boot_id?.startsWith("win32:") ? "windows-job" : e.scope_kind === "linux-subreaper" ? "linux-subreaper" : n, ...e.scope_kind === "linux-subreaper" ? { workerDescendantsReaped: e.descendants_reaped === 1 } : {}, workerLineageSettled: e.lineage_settled === 1, ...t ? { container: t } : {}, resultJson: e.result_json, errorText: e.error_text, completedAtMs: e.completed_at_ms, createdAtMs: e.created_at_ms, updatedAtMs: e.updated_at_ms }; } //#endregion //#region src/node-host/node-worker-launch-schema.ts const NODE_WORKER_LAUNCH_SCHEMA_END = "\n WHERE completed_at_ms IS NOT NULL;"; const launchSchemaEnsurers = new Map([ "node_worker_launches", "node_worker_launch_boots", "node_worker_launch_containers", "node_worker_launch_cleanup", "node_worker_launch_process_scopes" ].map((e) => [e, createSqliteSchemaEnsurer(() => getOpenClawStateFeatureSchemaSql(e, { endMarker: e === "node_worker_launches" ? NODE_WORKER_LAUNCH_SCHEMA_END : void 0 }), { tables: [e], indexes: e === "node_worker_launches" ? ["idx_node_worker_launches_terminal_completed"] : [] })])); const ensureNodeWorkerLaunchSchema = (e, t) => { if (isPostgresSqlConnection(e)) ensureStatePostgresFragment(e, t); else launchSchemaEnsurers.get(t)(e); }; //#endregion //#region src/node-host/node-worker-turn-settlement.worker.ts /** Physical extinction closes unfinished turns, never a result already recorded by the worker. */ function settleNodeWorkerActiveTurns(e, t, n = getAdmittedSqliteSchemaFacts(e), r = false) { if (t.state === "pending" || t.state === "running" || !(n ? n.tables.has("node_worker_turns") : tableExists(e, "node_worker_turns"))) return; const i = getNodeSqliteKysely(e).updateTable("node_worker_turns").set((n) => { const r = engineGreatest(e, [ n.ref("created_at_ms"), n.ref("updated_at_ms"), n.val(t.updatedAtMs) ]); return { state: t.state === "completed" ? "interrupted" : t.state, result_json: null, error_text: t.errorText ?? "node worker stopped before its turn completed", completed_at_ms: r, updated_at_ms: r }; }).where("owner_launch_id", "=", t.launchId).where("state", "=", "running"); if (r) return executeSqliteQueryTakeFirstSync(e, i.returningAll()); executeSqliteQuerySync(e, i); } //#endregion //#region src/node-host/node-worker-launch-store.kernel.ts const TERMINAL_RECEIPT_RETENTION_MS$1 = 864e5; const TERMINAL_PRUNE_BATCH_LIMIT$1 = 256; function query$1(e) { return getNodeSqliteKysely(e); } function hasLaunchTable(e, t, n) { return t ? t.tables.has(n) : tableExists(e, n); } function selectLaunchRows(e, t) { return query$1(e).selectFrom("node_worker_launches").selectAll("node_worker_launches").$if(hasLaunchTable(e, t, "node_worker_launch_boots"), (e) => e.leftJoin("node_worker_launch_boots", "node_worker_launch_boots.launch_id", "node_worker_launches.launch_id").select("node_worker_launch_boots.boot_id")).$if(hasLaunchTable(e, t, "node_worker_launch_containers"), (e) => e.leftJoin("node_worker_launch_containers", "node_worker_launch_containers.launch_id", "node_worker_launches.launch_id").select("node_worker_launch_containers.container_json")).$if(hasLaunchTable(e, t, "node_worker_launch_cleanup"), (e) => e.leftJoin("node_worker_launch_cleanup", "node_worker_launch_cleanup.launch_id", "node_worker_launches.launch_id").select(["node_worker_launch_cleanup.cleanup_mode", "node_worker_launch_cleanup.lineage_settled"])).$if(hasLaunchTable(e, t, "node_worker_launch_process_scopes"), (e) => e.leftJoin("node_worker_launch_process_scopes", "node_worker_launch_process_scopes.launch_id", "node_worker_launches.launch_id").select(["node_worker_launch_process_scopes.scope_kind", "node_worker_launch_process_scopes.descendants_reaped"])); } function readRow$1(e, t, n) { return executeSqliteQueryTakeFirstSync(e, selectLaunchRows(e, n).where("node_worker_launches.launch_id", "=", t)); } function readNonterminalCount(e) { return executeSqliteQueryTakeFirstSync(e, query$1(e).selectFrom("node_worker_launches").select((e) => e.fn.countAll().as("count")).where("state", "in", ["pending", "running"]))?.count ?? 0; } function readNonterminalRows(e, t) { return executeSqliteQuerySync(e, selectLaunchRows(e, t).where("node_worker_launches.state", "in", ["pending", "running"]).orderBy("node_worker_launches.launch_id", "asc")).rows; } function pruneTerminalRows(e) { let t = query$1(e.database).selectFrom("node_worker_launches").select("launch_id").where("state", "in", [ "completed", "failed", "interrupted", "cancelled" ]).where("completed_at_ms", "<=", e.cutoffMs).orderBy("completed_at_ms", "asc").orderBy("launch_id", "asc").limit(e.limit); if (e.excludeLaunchId) t = t.where("launch_id", "!=", e.excludeLaunchId); const n = executeSqliteQuerySync(e.database, t).rows.map((e) => e.launch_id); if (n.length === 0) return 0; if (hasLaunchTable(e.database, e.schema, "node_worker_launch_containers")) executeSqliteQuerySync(e.database, query$1(e.database).deleteFrom("node_worker_launch_containers").where("launch_id", "in", n)); const r = executeSqliteQuerySync(e.database, query$1(e.database).deleteFrom("node_worker_launches").where("launch_id", "in", n).where("state", "in", [ "completed", "failed", "interrupted", "cancelled" ]).where("completed_at_ms", "<=", e.cutoffMs)); return Number(r.numAffectedRows ?? 0n); } /** Read the authoritative physical owner within an already-open journal transaction. */ function readNodeWorkerLaunchReceipt(e, t) { const n = getAdmittedSqliteSchemaFacts(e); if (!hasLaunchTable(e, n, "node_worker_launches")) return; const r = readRow$1(e, t, n); return r ? nodeWorkerLaunchReceiptFromRow(r) : void 0; } function validateTimestamp(e) { if (!Number.isSafeInteger(e) || e < 0) throw new Error("node worker launch timestamp must be a non-negative safe integer"); } function validatePruneLimit(e) { if (!Number.isSafeInteger(e) || e < 1 || e > 1e3) throw new Error("node worker launch prune limit must be between 1 and 1000"); } function requireMatchingRow(e, t, n) { const { launchId: r, planHash: i } = t; const a = readRow$1(e, r, n); if (!a) throw new Error(`node worker launch ${r} does not exist`); if (a.plan_hash !== i) throw new Error(`node worker launch ${r} was replayed with a different plan`); return a; } function rowHasSupervisor(e, t) { return e.supervisor_pid === t.pid && e.supervisor_start_time === t.startTime; } function rowHasWorker(e, t) { return t === null ? e.worker_pid === null && e.worker_start_time === null : e.worker_pid === t.pid && e.worker_start_time === t.startTime; } function sameObservedOwner(e, t) { return e.state === t.state && e.supervisor_pid === t.supervisor_pid && e.supervisor_start_time === t.supervisor_start_time && e.worker_pid === t.worker_pid && e.worker_start_time === t.worker_start_time; } function finishOwnedRow(e, t, n, r, i) { if (isNodeWorkerTerminalState(t.state) || !rowHasSupervisor(t, n.supervisor) || !rowHasWorker(t, n.worker)) return; const a = Math.max(r, t.created_at_ms, t.updated_at_ms); let o = query$1(e).updateTable("node_worker_launches").set({ state: n.state, result_json: n.state === "completed" ? n.resultJson ?? null : null, error_text: n.state === "completed" ? null : n.errorText ?? null, completed_at_ms: a, updated_at_ms: a }).where("launch_id", "=", t.launch_id).where("plan_hash", "=", t.plan_hash); if (i) o = o.where("environment_id", "=", i.environmentId).where("session_id", "=", i.sessionId).where("owner_epoch", "=", i.ownerEpoch).where("placement_generation", "=", i.placementGeneration).where("run_id", "=", i.runId); o = o.where("state", "in", ["pending", "running"]).where("supervisor_pid", "=", n.supervisor.pid).where("supervisor_start_time", "=", n.supervisor.startTime); o = n.worker ? o.where("worker_pid", "=", n.worker.pid).where("worker_start_time", "=", n.worker.startTime) : o.where("worker_pid", "is", null).where("worker_start_time", "is", null); const s = executeSqliteQueryTakeFirstSync(e, o.returning([ "state", "result_json", "error_text", "completed_at_ms", "updated_at_ms" ])); return s ? { ...t, ...s } : void 0; } /** Connection-bound launch journal; every operation retains its original write transaction. */ var NodeWorkerLaunchKernel = class { constructor(e) { this.databaseOptions = e; } write(e, t) { return runOpenClawStateWriteTransaction(({ db: e, path: n }) => { requestSqliteWorkerOperationAdmission({ stage: "transaction", facts: { kind: "node-worker-journal" } }); ensureNodeWorkerLaunchSchema(e, "node_worker_launches"); return t(e, getAdmittedSqliteSchemaFacts(e), n); }, this.databaseOptions, { operationLabel: e }); } claimObservation(e, t, n, r = Date.now()) { validateIdentifier(e.launchId, "node worker launch id"); validateNodeWorkerPlanHash(e.planHash); validateTimestamp(r); validateNodeWorkerProcessIdentity(t); if (!Number.isSafeInteger(n) || n < 1) throw new Error("node worker capacity must be a positive safe integer"); return this.write("node-worker-launch.claim-inspect", (t, n) => { const r = readRow$1(t, e.launchId, n); if (!r) return; return { plan_hash: r.plan_hash, state: r.state, supervisor_pid: r.supervisor_pid, supervisor_start_time: r.supervisor_start_time, worker_pid: r.worker_pid, worker_start_time: r.worker_start_time }; }); } claim(e, t, n, r, i, a, o) { return this.write("node-worker-launch.claim", (s, c) => { const finalize = (t) => { pruneTerminalRows({ database: s, schema: c, cutoffMs: Math.max(0, r - TERMINAL_RECEIPT_RETENTION_MS$1), limit: TERMINAL_PRUNE_BATCH_LIMIT$1, excludeLaunchId: e.launchId }); return t; }; let l = readRow$1(s, e.launchId, c); let u = "replay"; if (!l) { const i = readNonterminalCount(s); if (i >= n) return finalize({ action: "at-capacity", nonterminalCount: i }); l = executeSqliteQueryTakeFirstSync(s, query$1(s).insertInto("node_worker_launches").values({ launch_id: e.launchId, plan_hash: e.planHash, gateway_namespace: e.gatewayNamespace, environment_id: e.environmentId, session_id: e.sessionId, owner_epoch: e.ownerEpoch, placement_generation: e.placementGeneration, run_id: e.runId, state: "pending", supervisor_pid: t.pid, supervisor_start_time: t.startTime, worker_pid: null, worker_start_time: null, result_json: null, error_text: null, completed_at_ms: null, created_at_ms: r, updated_at_ms: r }).returningAll()); if (o) { ensureNodeWorkerLaunchSchema(s, "node_worker_launch_boots"); executeSqliteQuerySync(s, query$1(s).insertInto("node_worker_launch_boots").values({ launch_id: e.launchId, boot_id: o })); l.boot_id = o; } u = "start"; } else if (l.plan_hash !== e.planHash) throw new Error(`node worker launch ${e.launchId} was replayed with a different plan`); else if (i && sameObservedOwner(l, i) && (a === "dead" || a === "reused")) { if (l.state === "pending") { const n = Math.max(r, l.created_at_ms, l.updated_at_ms); const a = executeSqliteQueryTakeFirstSync(s, query$1(s).updateTable("node_worker_launches").set({ supervisor_pid: t.pid, supervisor_start_time: t.startTime, updated_at_ms: n }).where("launch_id", "=", e.launchId).where("plan_hash", "=", e.planHash).where("state", "=", "pending").where("supervisor_pid", "=", i.supervisor_pid).where("supervisor_start_time", "=", i.supervisor_start_time).where("worker_pid", "is", null).where("worker_start_time", "is", null).returning([ "supervisor_pid", "supervisor_start_time", "updated_at_ms" ])); if (a) l = { ...l, ...a }; if (l.boot_id) { executeSqliteQuerySync(s, query$1(s).updateTable("node_worker_launch_boots").set({ boot_id: o ?? null }).where("launch_id", "=", e.launchId)); l.boot_id = o ?? null; } u = rowHasSupervisor(l, t) ? "start" : "replay"; } else if (l.state === "running") u = "recover"; } return finalize({ action: u, receipt: nodeWorkerLaunchReceiptFromRow(l), nonterminalCount: readNonterminalCount(s) }); }); } listNonterminal() { return this.write("node-worker-launch.list-nonterminal", (e, t) => readNonterminalRows(e, t).map(nodeWorkerLaunchReceiptFromRow)); } nonterminalCount() { return this.write("node-worker-launch.count-nonterminal", readNonterminalCount); } pruneExpiredTerminal(e = {}) { const t = e.nowMs ?? Date.now(); const n = e.limit ?? TERMINAL_PRUNE_BATCH_LIMIT$1; validateTimestamp(t); validatePruneLimit(n); return this.write("node-worker-launch.prune-terminal", (e, r) => pruneTerminalRows({ database: e, schema: r, cutoffMs: Math.max(0, t - TERMINAL_RECEIPT_RETENTION_MS$1), limit: n })); } get(e) { validateIdentifier(e, "node worker launch id"); return this.write("node-worker-launch.get", (t, n) => { const r = readRow$1(t, e, n); return r ? nodeWorkerLaunchReceiptFromRow(r) : void 0; }); } getMatching(e) { validateIdentifier(e.launchId, "node worker launch id"); validateNodeWorkerPlanHash(e.planHash); return this.write("node-worker-launch.get-matching", (t, n) => { const r = readRow$1(t, e.launchId, n); return r && rowMatchesImmutableIdentity(r, e) ? nodeWorkerLaunchReceiptFromRow(r) : void 0; }); } cleanupBinding(e) { return this.write("node-worker-launch.cleanup-binding", (t, n, r) => { const i = requireMatchingRow(t, e, n); if (isNodeWorkerTerminalState(i.state) || !rowHasSupervisor(i, e.supervisor)) throw new Error("node worker cleanup binding no longer owns its launch"); return { databasePath: r, externallySupervised: isGatewayExternallySupervised(this.databaseOptions.env), launchId: e.launchId, planHash: e.planHash, supervisor: { ...e.supervisor } }; }); } finishCancelled(e) { const t = e.nowMs ?? Date.now(); validateTimestamp(t); validateNodeWorkerProcessIdentity(e.supervisor); if (e.worker) validateNodeWorkerProcessIdentity(e.worker); return this.write("node-worker-launch.finish-cancelled", (n, r) => { const i = readRow$1(n, e.expected.launchId, r); if (!i || !rowMatchesImmutableIdentity(i, e.expected)) return; const a = finishOwnedRow(n, i, { supervisor: e.supervisor, worker: e.worker, state: "cancelled", errorText: "node worker launch cancelled" }, t, e.expected) ?? i; if (!rowMatchesImmutableIdentity(a, e.expected)) return; const o = nodeWorkerLaunchReceiptFromRow(a); settleNodeWorkerActiveTurns(n, o, r); return o; }); } markRunning(e) { const t = e.nowMs ?? Date.now(); validateTimestamp(t); validateNodeWorkerProcessIdentity(e.supervisor); validateNodeWorkerProcessIdentity(e.worker); if (e.container) validateNodeWorkerContainerIdentity(e.container); return this.write("node-worker-launch.mark-running", (n, r) => { const i = requireMatchingRow(n, e, r); if (isNodeWorkerTerminalState(i.state) || i.state === "running") return nodeWorkerLaunchReceiptFromRow(i); if (!rowHasSupervisor(i, e.supervisor) || !rowHasWorker(i, null)) return nodeWorkerLaunchReceiptFromRow(i); if (e.container) { ensureNodeWorkerLaunchSchema(n, "node_worker_launch_containers"); executeSqliteQuerySync(n, query$1(n).insertInto("node_worker_launch_containers").values({ launch_id: e.launchId, container_json: JSON.stringify({ engine: e.container.engine, containerId: e.container.containerId, engineTarget: e.container.engineTarget }) })); } if (e.cleanupMode !== null) { ensureNodeWorkerLaunchSchema(n, "node_worker_launch_cleanup"); executeSqliteQuerySync(n, query$1(n).insertInto("node_worker_launch_cleanup").values({ launch_id: e.launchId, cleanup_mode: e.cleanupMode === "linux-subreaper" ? "owned-anchor" : e.cleanupMode === "windows-job" ? i.boot_id?.startsWith("win32:") ? "owned-anchor" : "process-group" : e.cleanupMode, lineage_settled: null })); } if (e.cleanupMode === "linux-subreaper") { ensureNodeWorkerLaunchSchema(n, "node_worker_launch_process_scopes"); executeSqliteQuerySync(n, query$1(n).insertInto("node_worker_launch_process_scopes").values({ launch_id: e.launchId, scope_kind: "linux-subreaper", descendants_reaped: null })); } const a = Math.max(t, i.created_at_ms, i.updated_at_ms); executeSqliteQuerySync(n, query$1(n).updateTable("node_worker_launches").set({ state: "running", worker_pid: e.worker.pid, worker_start_time: e.worker.startTime, updated_at_ms: a }).where("launch_id", "=", e.launchId).where("plan_hash", "=", e.planHash).where("state", "=", "pending").where("supervisor_pid", "=", e.supervisor.pid).where("supervisor_start_time", "=", e.supervisor.startTime).where("worker_pid", "is", null).where("worker_start_time", "is", null)); return nodeWorkerLaunchReceiptFromRow(requireMatchingRow(n, e, getAdmittedSqliteSchemaFacts(n))); }); } finish(e) { const t = e.nowMs ?? Date.now(); validateTimestamp(t); validateNodeWorkerProcessIdentity(e.supervisor); if (e.worker) validateNodeWorkerProcessIdentity(e.worker); return this.write("node-worker-launch.finish", (n, r) => { const i = requireMatchingRow(n, e, r); const a = finishOwnedRow(n, i, e, t); const o = nodeWorkerLaunchReceiptFromRow(a ?? i); settleNodeWorkerActiveTurns(n, o, r); return o; }); } }; //#endregion //#region src/node-host/node-worker-turn-store.kernel.ts const TERMINAL_RECEIPT_RETENTION_MS = 864e5; const TERMINAL_PRUNE_BATCH_LIMIT = 256; function query(e) { return getNodeSqliteKysely(e); } const turnSchema = createSqliteSchemaEnsurer(() => getOpenClawStateFeatureSchemaSql("node_worker_turns", { endMarker: "\n WHERE state = 'running';", errorMessage: "OpenClaw node worker turn schema marker is missing." }), { tables: ["node_worker_turns"], indexes: ["idx_node_worker_turns_terminal_completed", "idx_node_worker_turns_active_owner"] }); function readRow(e, t) { return executeSqliteQueryTakeFirstSync(e, query(e).selectFrom("node_worker_turns").selectAll().where("turn_id", "=", t)); } function readReceipt(e, t) { let n = readRow(e, t); if (!n) return; const r = readNodeWorkerLaunchReceipt(e, n.owner_launch_id); if (!r) throw new Error(`node worker turn ${t} has no physical owner`); if (n.state === "running" && r.state !== "pending" && r.state !== "running") n = settleNodeWorkerActiveTurns(e, r, void 0, true); return turnReceiptFromRow(n, r); } function turnReceiptFromRow(e, t) { const n = e.state === "running" && t.state === "pending" ? "pending" : e.state; if (n !== "pending" && n !== "running" && !isNodeWorkerTerminalState(n)) throw new Error(`invalid node worker turn state ${n}`); return { ...t, ownerLaunchId: e.owner_launch_id, launchId: e.turn_id, planHash: e.plan_hash, runId: e.run_id, state: n, resultJson: e.result_json, errorText: e.error_text, completedAtMs: e.completed_at_ms, createdAtMs: e.created_at_ms, updatedAtMs: e.updated_at_ms }; } function matchesProcess(e, t, n) { return e.supervisor.pid === t.pid && e.supervisor.startTime === t.startTime && e.worker?.pid === n?.pid && e.worker?.startTime === n?.startTime; } function pruneTerminal(e, t, n) { executeSqliteQuerySync(e, query(e).deleteFrom("node_worker_turns").where("turn_id", "in", query(e).selectFrom("node_worker_turns").select("turn_id").where("completed_at_ms", "<=", Math.max(0, t - TERMINAL_RECEIPT_RETENTION_MS)).where("turn_id", "!=", n).orderBy("completed_at_ms", "asc").orderBy("turn_id", "asc").limit(TERMINAL_PRUNE_BATCH_LIMIT))); } /** Immutable turn outcomes attached to a separately supervised physical worker. */ var NodeWorkerTurnKernel = class { constructor(e) { this.databaseOptions = e; } write(e, t) { return runOpenClawStateWriteTransaction(({ db: e }) => { requestSqliteWorkerOperationAdmission({ stage: "transaction", facts: { kind: "node-worker-journal" } }); if (isPostgresSqlConnection(e)) ensureStatePostgresFragment(e, "node_worker_turns"); else turnSchema(e); return t(e); }, this.databaseOptions, { operationLabel: e }); } claim(e) { const { claim: t, ownerLaunchId: n, supervisor: r } = e; const i = e.nowMs ?? Date.now(); return this.write("node-worker-turn.claim", (a) => { const o = readReceipt(a, t.launchId); if (o) { if (!nodeWorkerTurnMatchesIdentity(o, t) || o.gatewayNamespace !== t.gatewayNamespace || o.ownerLaunchId !== n) throw new Error(`node worker turn ${t.launchId} was replayed with a different plan or owner`); pruneTerminal(a, i, t.launchId); return { action: "replay", receipt: o }; } const s = readNodeWorkerLaunchReceipt(a, n); if (!s || s.state !== "pending" && s.state !== "running" || !matchesProcess(s, r, e.worker ?? null) || s.gatewayNamespace !== t.gatewayNamespace || s.environmentId !== t.environmentId || s.sessionId !== t.sessionId || s.ownerEpoch !== t.ownerEpoch || s.placementGeneration !== t.placementGeneration || s.state === "pending" && s.launchId !== t.launchId || s.launchId === t.launchId && (s.state !== "pending" || s.planHash !== t.planHash || s.runId !== t.runId)) throw new Error(`node worker turn ${t.launchId} does not match its live physical owner`); const c = executeSqliteQueryTakeFirstSync(a, query(a).insertInto("node_worker_turns").values({ turn_id: t.launchId, owner_launch_id: n, plan_hash: t.planHash, run_id: t.runId, state: "running", result_json: null, error_text: null, completed_at_ms: null, created_at_ms: i, updated_at_ms: i }).returningAll()); pruneTerminal(a, i, t.launchId); return { action: "start", receipt: turnReceiptFromRow(c, s) }; }); } get(e) { return this.write("node-worker-turn.get", (t) => readReceipt(t, e)); } finish(e) { return this.write("node-worker-turn.finish", (t) => { const n = readReceipt(t, e.expected.launchId); if (!n || !nodeWorkerTurnMatchesIdentity(n, e.expected) || n.ownerLaunchId !== e.ownerLaunchId) return; if (n.state !== "pending" && n.state !== "running" || !matchesProcess(n, e.supervisor, e.worker)) return n; const r = e.nowMs ?? Date.now(); const i = Math.max(r, n.createdAtMs, n.updatedAtMs); const a = executeSqliteQueryTakeFirstSync(t, query(t).updateTable("node_worker_turns").set({ state: e.state, result_json: e.state === "completed" ? e.resultJson ?? null : null, error_text: e.state === "completed" ? null : e.errorText ?? null, completed_at_ms: i, updated_at_ms: i }).where("turn_id", "=", n.launchId).where("state", "=", "running").returningAll()); pruneTerminal(t, r, n.launchId); return turnReceiptFromRow(a, n); }); } }; //#endregion //#region src/node-host/node-worker-journal.worker.ts function configureNodeHostInWorker([e], { write: t }) { return t(({ db: t }) => { requestSqliteWorkerOperationAdmission({ stage: "transaction", facts: { kind: "node-worker-journal" } }); let n = false; return { config: updateConfigMachineStateInDatabase(t, "nodeHost.config", (t) => { const r = t === void 0 ? void 0 : normalizeStoredNodeHostConfig(t); n = e.allCommands === true && r?.commands !== void 0; const i = e.allCommands ? void 0 : e.commands ?? r?.commands; return { version: 1, nodeId: e.explicitNodeId ?? r?.nodeId ?? e.candidateNodeId, displayName: e.explicitDisplayName ?? r?.displayName ?? e.fallbackDisplayName, gateway: e.gateway, installedAppsSharing: e.installedAppsSharing ?? r?.installedAppsSharing ?? false, ...i !== void 0 ? { commands: i } : {} }; }, e.updatedAtMs), clearedCommands: n }; }, { operationLabel: "node-host.configure" }); } function journalKernel(e) { return (t) => (n, r) => t(e(r))(...n); } const preparedRead = journalKernel(({ stateOptions: e }) => new NodeWorkerPreparedWorkspaceKernel(e())); const preparedWrite = journalKernel(({ stateOptions: e, open: t }) => new NodeWorkerPreparedWorkspaceKernel({ ...e(), database: t() })); const launch = journalKernel(({ stateOptions: e, open: t }) => new NodeWorkerLaunchKernel({ ...e(), database: t() })); const turn = journalKernel(({ stateOptions: e, open: t }) => new NodeWorkerTurnKernel({ ...e(), database: t() })); const nodeWorkerJournalOperations = { "nodeWorker.configure": configureNodeHostInWorker, "nodeWorker.prepared.find": preparedRead((e) => e.find.bind(e)), "nodeWorker.prepared.list": preparedRead((e) => e.list.bind(e)), "nodeWorker.prepared.register": preparedWrite((e) => e.register.bind(e)), "nodeWorker.prepared.bind": preparedWrite((e) => e.bind.bind(e)), "nodeWorker.prepared.retire": preparedWrite((e) => e.retire.bind(e)), "nodeWorker.prepared.completeMutation": preparedWrite((e) => e.completeMutation.bind(e)), "nodeWorker.launch.claimObservation": launch((e) => e.claimObservation.bind(e)), "nodeWorker.launch.claim": launch((e) => e.claim.bind(e)), "nodeWorker.launch.listNonterminal": launch((e) => e.listNonterminal.bind(e)), "nodeWorker.launch.nonterminalCount": launch((e) => e.nonterminalCount.bind(e)), "nodeWorker.launch.pruneExpiredTerminal": launch((e) => e.pruneExpiredTerminal.bind(e)), "nodeWorker.launch.get": launch((e) => e.get.bind(e)), "nodeWorker.launch.getMatching": launch((e) => e.getMatching.bind(e)), "nodeWorker.launch.cleanupBinding": launch((e) => e.cleanupBinding.bind(e)), "nodeWorker.launch.finishCancelled": launch((e) => e.finishCancelled.bind(e)), "nodeWorker.launch.markRunning": launch((e) => e.markRunning.bind(e)), "nodeWorker.launch.finish": launch((e) => e.finish.bind(e)), "nodeWorker.turn.claim": turn((e) => e.claim.bind(e)), "nodeWorker.turn.get": turn((e) => e.get.bind(e)), "nodeWorker.turn.finish": turn((e) => e.finish.bind(e)) }; //#endregion export { nodeWorkerJournalOperations };