openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
302 lines (301 loc) • 10.9 kB
JavaScript
import { s as normalizeNullableString } from "./string-coerce-CCIiB4H7.mjs";
import { m as toStringifiedError } from "./error-coercion-hDrHOSGy.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as resolveRuntimeWorkerArgv } from "./runtime-worker-url-DRDkoS4J.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs";
import { S as readSqliteDatabaseCleanClose, a as getOrLoadSqliteDatabaseAdmissionForPath, g as prepareSqliteDatabaseAdmission } from "./sqlite-database-admission-DQIqro3d.mjs";
import { l as quoteSqliteIdentifier } from "./sqlite-schema-sql-CPyk_2Hd.mjs";
import { t as agentSchemaMetadataKey } from "./openclaw-agent-db-metadata-C3YvwHLh.mjs";
import { a as readSqliteInspectionBudget, g as sqliteInspectionTimeoutError, i as isSqliteInspectionDeadlineOwnedByCaller, l as resolveSqliteInspectionSignal } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { o as observeChildRuntime, t as assertChildRuntimeAvailable } from "./child-runtime-viability-DFyU3D5D.mjs";
import { n as getDatabaseEngineSelection, t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs";
import { r as readSqliteIntegrityFileIdentity } from "./sqlite-file-generation-DHPWG9de.mjs";
import { t as agentDatabaseValidationKey } from "./openclaw-agent-db-validation-facts-CaK2iz32.mjs";
import { t as restoreAgentSchemaInspectionError } from "./openclaw-agent-schema-inspection-response-Cd8G_meQ.mjs";
import { existsSync } from "node:fs";
import { fork } from "node:child_process";
//#region src/state/openclaw-agent-schema-inspection-worker.ts
function retireReader(e) {
if (e.retired) return;
e.retired = true;
if (e.child.connected) e.child.send({ type: "close" }, (t) => {
if (t) e.child.kill("SIGKILL");
});
}
/** One scheduler slot reuses imports and canonical schema contracts, never database reads. */
function createAgentSchemaInspectionWorker() {
let e;
let t = false;
let n = false;
let r = 0;
let i = 0;
let a = 0;
let o = 0;
let s;
const startReader = (e) => {
const t = resolveRuntimeProcessEntrypointUrl("agentSchemaInspection");
assertChildRuntimeAvailable();
const n = fork(t, [], {
execArgv: resolveRuntimeWorkerArgv(t).slice(0, -1),
serialization: "advanced",
stdio: [
"ignore",
"ignore",
"pipe",
"ipc"
]
});
r += 1;
const i = observeChildRuntime(n);
const a = createDeferredCore();
const o = {
child: n,
closed: a.promise,
retired: false,
closeBudgetMs: e
};
n.on("error", (e) => {
o.failure ??= e;
retireReader(o);
});
n.once("close", () => {
o.runtimeFailure = i();
o.retired = true;
a.resolve();
});
return o;
};
const c = { inspect: async (r, c, l) => {
const { input: u, kind: d } = r;
const f = resolveSqliteInspectionSignal(c);
f?.throwIfAborted();
if (t || n) throw new Error(t ? "Agent schema inspection worker is closed" : "Agent schema inspection worker is busy");
n = true;
try {
const n = d === "agent" && !u.verifyCurrentSchemaShape && !u.requireStartupMigrationReadiness && !u.inspectEmptyStore;
let r = Boolean(getDatabaseEngineInput("agent"));
let c;
const p = getDatabaseEngineSelection();
if (n && p?.postgres) {
if (!existsSync(l ?? u.pathname)) return null;
const [{ readBackupEngine: e }, { readBackupEngineImage: t }] = await Promise.all([import("./physical-store-8O6jdX6H.mjs"), import("./physical-store-inspection-CcPsh5hD.mjs")]);
const n = l ? t(l, u.pathname) : e(u.pathname);
f?.throwIfAborted();
if (n.engine === "sqlite") {
if (r && !l) return null;
r = false;
} else {
const { withPostgresStoreMetadata: e } = await import("./postgres-store-metadata-CFFkRXRj.mjs");
const t = await e(p.postgres, n, async (e, t) => {
if (t.store !== "agent") throw new Error("PostgreSQL agent inspection requires an agent store.");
if (!u.inspectOwnership) return { version: t.version };
const { rows: r } = await e.query(`SELECT agent_id, role, schema_version::integer AS schema_version
FROM ${quoteSqliteIdentifier(n.namespace)}.schema_meta WHERE meta_key = 'primary'`);
const i = r[0];
return {
version: t.version,
agentSchemaMeta: i ? {
agentId: normalizeNullableString(i.agent_id),
role: i.role,
schemaVersion: i.schema_version
} : null
};
});
f?.throwIfAborted();
i += 1;
return t;
}
}
if (d === "agent" && r) {
if (l) throw new Error("PostgreSQL agent inspection requires its live engine owner, not a SQLite snapshot.");
const { getPendingOpenClawAgentDatabasePreparation: e } = await import("./openclaw-agent-execution-D8fPsYYC.mjs");
await e(u.pathname);
f?.throwIfAborted();
let t = u.agentId ?? getOrLoadSqliteDatabaseAdmissionForPath(u.pathname, agentSchemaMetadataKey, () => void 0)?.agentId;
if (!t) {
const { prepareSqliteTargetFromSessionStorePath: e } = await import("./session-sqlite-target-DDpmcfGH.mjs");
const n = await e(u.pathname, { env: u.env ?? process.env }, f);
if (!n.agentId || n.ownerSource !== void 0 && n.ownerSource !== "database-path" && n.ownerSource !== "database-registry") throw new Error("PostgreSQL schema inspection could not establish the custom store owner.");
t = n.agentId;
}
c = t;
}
if (d !== "state" && !r && !l && u.requireStartupMigrationReadiness && readSqliteDatabaseCleanClose(u.pathname)) {
const e = getOrLoadSqliteDatabaseAdmissionForPath(u.pathname, agentDatabaseValidationKey, () => void 0);
const t = getOrLoadSqliteDatabaseAdmissionForPath(u.pathname, agentSchemaMetadataKey, () => void 0);
if (e?.schema?.facts?.userVersion === u.supportedVersion && Atomics.load(new Int32Array(e.valid), 0) === 1 && Atomics.load(new Int32Array(e.schema.valid), 0) === 1 && prepareSqliteDatabaseAdmission(u.pathname) === `${e.identity}:${e.birthtime}` && t?.agentId === e.agentId && (u.agentId === void 0 || u.agentId === e.agentId) && t.role === "agent" && t.schemaVersion === u.supportedVersion) return {
version: u.supportedVersion,
integrityGateOutcome: "cached",
agentSchemaMeta: t
};
}
const m = l ? {
pathname: l,
identity: readSqliteIntegrityFileIdentity(l)
} : void 0;
if (e?.retired) {
await e.closed;
e = void 0;
}
f?.throwIfAborted();
if (t) throw new Error("Agent schema inspection worker is closed");
const { timeoutMs: h, size: g } = readSqliteInspectionBudget(u.requireStartupMigrationReadiness ? "startup readiness" : "schema inspection", u.pathname);
const _ = e ??= startReader(h);
_.closeBudgetMs = h;
s?.();
s = void 0;
const v = ++o;
const y = createDeferredCore();
let b;
const kill = () => {
_.retired = true;
_.child.kill("SIGKILL");
};
const onAbort = () => {
b = toStringifiedError(f?.reason);
kill();
};
const onMessage = (e) => {
if (b) return;
if (e.requestId !== v) {
b = /* @__PURE__ */ new Error("Invalid agent schema inspection response");
kill();
} else if (!e.ok) {
b = restoreAgentSchemaInspectionError(e.error);
retireReader(_);
} else {
if (d === "state") {
const t = e.stateInspection;
if (t === null) {
y.resolve(null);
return;
}
if (t === void 0) {
b = /* @__PURE__ */ new Error("Invalid state schema inspection response");
kill();
return;
}
y.resolve({
...t,
inspectionErrors: t.inspectionErrors.map(restoreAgentSchemaInspectionError)
});
return;
}
const t = e.inspection;
y.resolve(t ? {
...t,
failure: t.failure ? restoreAgentSchemaInspectionError(t.failure) : void 0
} : null);
}
};
const onClose = (e, t) => {
y.reject(f?.aborted ? toStringifiedError(f.reason) : _.runtimeFailure ?? b ?? _.failure ?? (t === "SIGKILL" ? sqliteInspectionTimeoutError("schema inspection", u.pathname, h, g) : /* @__PURE__ */ new Error(`Agent schema inspection exited ${e} without a completed result`)));
};
const x = isSqliteInspectionDeadlineOwnedByCaller() ? void 0 : setTimeout(() => {
b ??= sqliteInspectionTimeoutError("schema inspection", u.pathname, h, g);
kill();
}, h);
x?.unref();
_.child.on("message", onMessage);
_.child.once("close", onClose);
f?.addEventListener("abort", onAbort, { once: true });
try {
_.child.send({
type: d === "state" ? "inspect-state" : "inspect",
requestId: v,
input: {
...u,
...c ? { agentId: c } : {},
..."env" in u && u.env ? { env: { ...u.env } } : {}
},
snapshot: m,
...d === "agent" && r ? { databaseEngineSelection: p } : {}
}, (e) => {
if (e) {
b ??= e;
kill();
}
});
const e = await y.promise;
if (f?.aborted) {
kill();
await _.closed;
throw toStringifiedError(f.reason);
}
if (m) readSqliteIntegrityFileIdentity(m.pathname, m.identity);
if (e) {
i += 1;
a += m ? 1 : 0;
}
return e;
} finally {
clearTimeout(x);
_.child.off("message", onMessage);
_.child.off("close", onClose);
f?.removeEventListener("abort", onAbort);
}
} finally {
n = false;
}
} };
return {
/** Load the isolated reader while startup discovers its targets; no database is opened. */
prestart(r) {
const i = resolveSqliteInspectionSignal(r);
i?.throwIfAborted();
if (t || n) throw new Error("Agent schema inspection worker is unavailable for prestart");
if (e) return;
const a = e = startReader(0);
const onAbort = () => {
a.retired = true;
a.child.kill("SIGKILL");
};
i?.addEventListener("abort", onAbort, { once: true });
const release = () => i?.removeEventListener("abort", onAbort);
s = release;
a.closed.then(release);
},
get processCount() {
return r;
},
get inspectionCount() {
return i;
},
get snapshotCount() {
return a;
},
inspect: async (e, t, n) => {
const r = await c.inspect({
kind: "agent",
input: e
}, t, n);
if (r && "schemas" in r) throw new Error("Unexpected state schema inspection result");
return r;
},
inspectState: async (e, t, n) => {
const r = await c.inspect({
kind: "state",
input: e
}, t, n);
if (r && !("schemas" in r)) throw new Error("Unexpected agent schema inspection result");
return r;
},
async [Symbol.asyncDispose]() {
t = true;
s?.();
s = void 0;
if (!e) return;
const n = e;
const r = setTimeout(() => n.child.kill("SIGKILL"), n.closeBudgetMs);
r.unref();
try {
retireReader(n);
await n.closed;
} finally {
clearTimeout(r);
}
}
};
}
//#endregion
export { createAgentSchemaInspectionWorker as t };