openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
384 lines (383 loc) • 16.1 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { _ as sql, a as executeSqliteQueryTakeFirstSync, c as iterateSqliteQuerySync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { w as getPostgresPhysicalFacts } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as tableExists, i as readTableColumns } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { m as withExistingOpenClawStateDatabaseReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs";
import { a as mapNestedStrings } from "./plugin-text-transforms-CMotGmZ0.mjs";
import { n as agentEngineInput } from "./openclaw-agent-db-engine-CFD02117.mjs";
import { o as closeOpenClawAgentDatabaseByPathAsync } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs";
import { n as withOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-COYfV-vn.mjs";
import { r as isOpenClawAgentDatabaseOpen, s as runOpenClawAgentWriteTransaction } from "./openclaw-agent-db-CwXW4hGa.mjs";
import { t as attachSessionEntrySnapshots } from "./session-entry-snapshot-values-CTzX9hmQ.mjs";
import { n as sessionEntrySnapshotColumns } from "./session-entry-snapshots-BIxBwjSA.mjs";
import { r as publishSessionEntryCacheInvalidation } from "./session-accessor.sqlite-entry-cache-l5776yJA.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { n as listSessionEntryKeysReadOnly } from "./session-retirement-read-DHZnxRqj.mjs";
import { n as createLegacyStateMigrationStepReceipt, t as DoctorStateMigrationRefusalError } from "./state-migrations.messages-CNB52OxC.mjs";
import { r as rewriteDoctorSessionEntries } from "./session-entry-rewrite-ql1B0nFY.mjs";
import { r as listExistingAgentDatabaseTargets, u as resolveTargetSqliteOptions } from "./session-sqlite-migration-readers-DbmEQzSW.mjs";
import { t as runDoctorAgentDatabaseOperation } from "./doctor-agent-database-operation-BYsIdRWr.mjs";
//#region src/commands/doctor-session-incognito-key-repair-state.ts
const REPAIR_JOURNAL_SCOPE = "doctor-session-key-migration";
const REPAIR_JOURNAL_KEY = "reserved-incognito-v1";
function listTuiLastSessionStateRows(e) {
const t = getNodeSqliteKysely(e);
return executeSqliteQuerySync(e, t.selectFrom("config_machine_state").select(["state_key", "value_json"]).where("state_key", "like", "tui.lastSession.%")).rows;
}
function schemaIdentifier(e) {
return sql.id(e);
}
function listSharedStateSessionKeyColumns(e) {
const t = getNodeSqliteKysely(e);
return (isPostgresSqlConnection(e) ? getPostgresPhysicalFacts(e)?.catalog.filter((e) => e.kind === "table").map((e) => ({ name: e.table })) ?? [] : executeSqliteQuerySync(e, t.selectFrom("sqlite_schema").select("name").where("type", "=", "table").where("name", "not like", "sqlite_%")).rows).flatMap(({ name: n }) => {
return (isPostgresSqlConnection(e) ? [...readTableColumns(e, n)].map((e) => ({ name: e })) : executeSqliteQuerySync(e, t.selectFrom(sql`pragma_table_info(${n})`.as("pragma_columns")).select(sql`name`.as("name"))).rows).flatMap(({ name: e }) => {
if (e === "session_key" || e.endsWith("_session_key")) return [{
table: n,
column: e,
json: false
}];
return e.endsWith("_session_keys_json") ? [{
table: n,
column: e,
json: true
}] : [];
});
});
}
function collectSharedStateSessionKeys(e) {
const t = getNodeSqliteKysely(e);
const n = /* @__PURE__ */ new Set();
for (const { table: r, column: i, json: a } of listSharedStateSessionKeyColumns(e)) {
const o = schemaIdentifier(i);
const s = executeSqliteQuerySync(e, t.selectFrom(sql`${schemaIdentifier(r)}`.as("session_key_table")).select(o.as("value")).where(o, "is not", null)).rows;
for (const { value: e } of s) if (!a && typeof e === "string") n.add(e);
else if (a && typeof e === "string") try {
collectJsonStringValues(JSON.parse(e), n);
} catch {}
}
for (const t of listTuiLastSessionStateRows(e)) {
const e = JSON.parse(t.value_json);
if (typeof e === "string") n.add(e);
}
return n;
}
function rewriteSharedStateSessionKeys(e, t) {
const n = getNodeSqliteKysely(e);
for (const { table: r, column: i, json: a } of listSharedStateSessionKeyColumns(e)) {
const o = schemaIdentifier(r);
const s = schemaIdentifier(i);
if (!a) {
for (const [r, i] of t) executeSqliteQuerySync(e, n.updateTable(sql`${o}`.as("session_key_table")).set(s, i).where(s, "=", r));
continue;
}
const c = executeSqliteQuerySync(e, n.selectFrom(sql`${o}`.as("session_key_table")).select(s.as("value"))).rows;
for (const r of c) {
if (typeof r.value !== "string") continue;
let i;
try {
i = JSON.parse(r.value);
} catch {
continue;
}
const a = JSON.stringify(mapNestedStrings(i, (e) => t.get(e) ?? e));
if (a !== r.value) executeSqliteQuerySync(e, n.updateTable(sql`${o}`.as("session_key_table")).set(s, a).where(s, "=", r.value));
}
}
const r = getNodeSqliteKysely(e);
for (const n of listTuiLastSessionStateRows(e)) {
const i = JSON.parse(n.value_json);
const a = typeof i === "string" ? t.get(i) : void 0;
if (a) executeSqliteQuerySync(e, r.updateTable("config_machine_state").set({ value_json: JSON.stringify(a) }).where("state_key", "=", n.state_key));
}
}
function collectJsonStringValues(e, t) {
if (typeof e === "string") {
t.add(e);
return;
}
if (!e || typeof e !== "object") return;
for (const n of Array.isArray(e) ? e : Object.values(e)) collectJsonStringValues(n, t);
}
function readRepairJournal(e) {
const t = getNodeSqliteKysely(e);
const n = executeSqliteQueryTakeFirstSync(e, t.selectFrom("state_leases").select("payload_json").where("scope", "=", REPAIR_JOURNAL_SCOPE).where("lease_key", "=", REPAIR_JOURNAL_KEY));
if (!n?.payload_json) return [];
const r = JSON.parse(n.payload_json);
if (r.version !== 1 || !Array.isArray(r.renames)) throw new Error("Invalid reserved incognito session key repair journal");
return r.renames.map((e) => {
if (!isRecord(e) || typeof e.from !== "string" || typeof e.to !== "string") throw new Error("Invalid reserved incognito session key repair journal entry");
return {
from: e.from,
to: e.to
};
});
}
function readReservedIncognitoKeyRepairState(e) {
const t = collectSharedStateSessionKeys(e);
return {
occupiedKeys: t,
reservedKeys: [...t].filter(isIncognitoSessionKey),
renames: readRepairJournal(e)
};
}
function writeRepairJournal(e, t) {
const n = Date.now();
const r = getNodeSqliteKysely(e);
executeSqliteQuerySync(e, r.insertInto("state_leases").values({
scope: REPAIR_JOURNAL_SCOPE,
lease_key: REPAIR_JOURNAL_KEY,
owner: "openclaw-doctor",
expires_at: null,
heartbeat_at: null,
payload_json: JSON.stringify({
version: 1,
renames: t
}),
created_at: n,
updated_at: n
}).onConflict((e) => e.columns(["scope", "lease_key"]).doUpdateSet({
owner: "openclaw-doctor",
payload_json: JSON.stringify({
version: 1,
renames: t
}),
updated_at: n
})));
}
function deleteRepairJournal(e) {
const t = getNodeSqliteKysely(e);
executeSqliteQuerySync(e, t.deleteFrom("state_leases").where("scope", "=", REPAIR_JOURNAL_SCOPE).where("lease_key", "=", REPAIR_JOURNAL_KEY));
}
//#endregion
//#region src/commands/doctor-session-incognito-key-repair.ts
var ReservedIncognitoSessionKeyRepairError = class extends DoctorStateMigrationRefusalError {
constructor(e = "Reserved-incognito session keys cannot be repaired in PostgreSQL. Re-adopt from a repaired SQLite source: run openclaw doctor --fix on the SQLite installation, then retry adoption.") {
const t = [{
kind: "owner",
id: "reserved-incognito-session-keys"
}];
super([createLegacyStateMigrationStepReceipt({
id: "reserved-incognito-session-keys",
phase: "final",
source: t,
target: t,
requiredness: "required",
reversibility: "not-applicable",
refusal: {
code: "RESERVED_INCOGNITO_SESSION_KEYS",
message: e
}
}, {
changes: [],
warnings: [e],
notices: [e]
})]);
this.code = "RESERVED_INCOGNITO_SESSION_KEYS";
}
};
async function repairReservedIncognitoSessionKeys(e) {
const t = (e.targets ?? listExistingAgentDatabaseTargets(e.cfg, e.env)).map((t) => ({
target: t,
databaseOptions: resolveTargetSqliteOptions(t, e.env)
}));
const n = withExistingOpenClawStateDatabaseReadOnly((e) => readReservedIncognitoKeyRepairState(e.db), { env: e.env });
const r = n?.renames ?? [];
const i = n?.occupiedKeys ?? /* @__PURE__ */ new Set();
let a = agentEngineInput() !== void 0;
let o = false;
for (const { target: e, databaseOptions: n } of t) {
const t = runDoctorAgentDatabaseOperation({
agentId: e.agentId,
path: e.sqlitePath,
run: () => withOpenClawAgentDatabaseReadOnly((e) => {
a ||= isPostgresSqlConnection(e.db);
return collectOccupiedSessionKeys(e.db);
}, n)
});
if (!t.ok) o = true;
else if (t.value.found) for (const e of t.value.value) i.add(e);
}
const s = new Set([...i].filter(isIncognitoSessionKey));
const c = new Set(s);
for (const e of r) c.add(e.from);
if (c.size > 0 && a) throw new ReservedIncognitoSessionKeyRepairError();
if (c.size > 0 && o) throw new ReservedIncognitoSessionKeyRepairError("Reserved-incognito session-key repair could not inspect every agent database. Resolve the reported Doctor database warnings, then retry openclaw doctor --fix.");
if (!e.apply) return {
found: c.size,
repaired: 0
};
if (s.size === 0 && r.length === 0) return {
found: 0,
repaired: 0
};
for (const e of r) i.add(e.to);
const l = new Set(r.map((e) => e.from));
const u = planReservedIncognitoKeyRenames([...s].filter((e) => !l.has(e)).toSorted(), i);
const d = [...r, ...u];
const f = new Map(d.map((e) => [e.from, e.to]));
runOpenClawStateWriteTransaction((e) => writeRepairJournal(e.db, d), { env: e.env }, { operationLabel: "doctor.journal-reserved-incognito-session-keys" });
runOpenClawStateWriteTransaction((e) => rewriteSharedStateSessionKeys(e.db, f), { env: e.env }, { operationLabel: "doctor.rename-reserved-incognito-shared-state-keys" });
for (const { target: n, databaseOptions: r } of t) {
const t = isOpenClawAgentDatabaseOpen(n.sqlitePath);
try {
runOpenClawAgentWriteTransaction((e) => applyReservedIncognitoKeyRenameColumns(e, d), r, {
operationLabel: "doctor.rename-reserved-incognito-session-keys",
repairAdmission: {
integrityCheck: e.integrityCheck ?? "quick",
integrityTables: [
"session_windows",
"session_nodes",
"session_entry_snapshots",
"conversation_deliveries",
"session_members",
"board_tabs",
"board_widgets",
"heartbeat_outcomes"
]
}
});
rewriteDoctorSessionEntries({
scope: {
agentId: n.agentId,
env: e.env,
storePath: n.storePath
},
integrityCheck: e.integrityCheck ?? "quick",
sessionKeys: await listSessionEntryKeysReadOnly({
agentId: n.agentId,
env: e.env,
storePath: n.storePath
}),
transform: (e) => rewriteSessionEntryKeyFields(e, f)
});
} finally {
if (!t) await closeOpenClawAgentDatabaseByPathAsync(n.sqlitePath);
}
}
runOpenClawStateWriteTransaction((e) => deleteRepairJournal(e.db), { env: e.env }, { operationLabel: "doctor.complete-reserved-incognito-session-keys" });
return {
found: c.size,
repaired: d.length
};
}
function planReservedIncognitoKeyRenames(e, t) {
return e.map((e) => {
const n = legacyIncognitoSessionKey(e);
if (parseAgentSessionKey(e)?.rest.startsWith("internal-session-effects:") && t.has(n)) throw new Error(`Cannot repair internal session key because ${n} already exists`);
let r = n;
let i = 1;
while (t.has(r)) {
r = `${n}-${i}`;
i += 1;
}
t.add(r);
return {
from: e,
to: r
};
});
}
function applyReservedIncognitoKeyRenameColumns(e, t) {
if (t.length === 0) return;
e.db.exec("PRAGMA defer_foreign_keys = ON;");
for (const n of t) {
const t = executeSqliteQuerySync(e.db, getNodeSqliteKysely(e.db).selectFrom("session_nodes").select("session_key").where((e) => e.or([
e("session_key", "=", n.from),
e("parent_session_key", "=", n.from),
e("spawned_by", "=", n.from),
e("fork_source_session_key", "=", n.from)
]))).rows;
updateSessionKeyColumns(e.db, n);
for (const r of /* @__PURE__ */ new Set([n.to, ...t.map((e) => e.session_key)])) publishSessionEntryCacheInvalidation(e, { sessionKey: r });
}
}
function legacyIncognitoSessionKey(e) {
const t = parseAgentSessionKey(e);
if (!t || !isIncognitoSessionKey(e)) throw new Error(`Cannot rename non-incognito session key: ${e}`);
return `agent:${t.agentId}:${t.rest.replace(":incognito-", ":legacy-incognito-")}`;
}
function listReservedIncognitoKeys(e) {
return [...collectOccupiedSessionKeys(e)].filter(isIncognitoSessionKey).toSorted();
}
function collectOccupiedSessionKeys(e) {
const t = getNodeSqliteKysely(e);
const n = tableExists(e, "session_entry_snapshots");
const r = /* @__PURE__ */ new Set();
const collectColumns = (t) => {
for (const n of executeSqliteQuerySync(e, t).rows) for (const e of Object.values(n)) if (e) r.add(e);
};
collectColumns(t.selectFrom("session_windows").select([
"session_key",
"parent_session_key",
"spawned_by"
]));
collectColumns(t.selectFrom("session_nodes").select([
"session_key",
"parent_session_key",
"spawned_by",
"fork_source_session_key"
]));
collectColumns(t.selectFrom("conversation_deliveries").select("source_session_key"));
collectColumns(t.selectFrom("session_members").select("session_key"));
if (n) collectColumns(t.selectFrom("session_entry_snapshots").select("session_key"));
for (const i of iterateSqliteQuerySync(e, t.selectFrom("session_nodes").select("entry_json").$if(n, (e) => e.select(sessionEntrySnapshotColumns)))) try {
const e = JSON.parse(i.entry_json);
if (isRecord(e)) collectSessionEntryKeyFields(attachSessionEntrySnapshots(e, i), r);
} catch {}
collectColumns(t.selectFrom("board_tabs").select("session_key"));
collectColumns(t.selectFrom("board_widgets").select("session_key"));
collectColumns(t.selectFrom("heartbeat_outcomes").select(["session_key", "run_session_key"]));
return r;
}
function updateSessionKeyColumns(e, t) {
const n = getNodeSqliteKysely(e);
for (const [r, i] of [
["session_windows", "session_key"],
["session_windows", "parent_session_key"],
["session_windows", "spawned_by"],
["session_nodes", "session_key"],
["session_entry_snapshots", "session_key"],
["session_nodes", "parent_session_key"],
["session_nodes", "spawned_by"],
["session_nodes", "fork_source_session_key"],
["conversation_deliveries", "source_session_key"],
["session_members", "session_key"],
["board_tabs", "session_key"],
["board_widgets", "session_key"],
["heartbeat_outcomes", "session_key"],
["heartbeat_outcomes", "run_session_key"]
]) executeSqliteQuerySync(e, n.updateTable(r).set(i, t.to).where(i, "=", t.from));
}
function rewriteSessionEntryKeyFields(e, t) {
visitSessionEntryKeyFields(e, (e, n) => {
const r = e[n];
if (typeof r === "string") e[n] = t.get(r) ?? r;
});
return e;
}
function collectSessionEntryKeyFields(e, t) {
visitSessionEntryKeyFields(e, (e, n) => {
const r = e[n];
if (typeof r === "string") t.add(r);
});
}
function visitSessionEntryKeyFields(e, t) {
if (!isRecord(e)) return;
for (const n of [
"heartbeatIsolatedBaseSessionKey",
"spawnedBy",
"completionOwnerSessionKey",
"parentSessionKey"
]) t(e, n);
if (isRecord(e.forkSource)) t(e.forkSource, "sessionKey");
if (Array.isArray(e.compactionCheckpoints)) {
for (const n of e.compactionCheckpoints) if (isRecord(n)) t(n, "sessionKey");
}
if (isRecord(e.systemPromptReport)) t(e.systemPromptReport, "sessionKey");
}
//#endregion
export { repairReservedIncognitoSessionKeys as n, readReservedIncognitoKeyRepairState as r, listReservedIncognitoKeys as t };