openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
199 lines (198 loc) • 9.45 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as resolveRequiredHomeDir } from "./home-dir-EKmgmdPG.mjs";
import { o as asRecord } from "./record-coerce-CVPuDqcc.mjs";
import { m as normalizeTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { a as executeSqliteQueryTakeFirstSync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { i as resolveLegacyInstalledPluginIndexStorePath } from "./installed-plugin-index-store-path-VYnur1Rc.mjs";
import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs";
import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs";
import { r as updateConfigMachineState } from "./config-machine-state-write-DanSUxEP.mjs";
import { i as listExistingRetiredStateFiles } from "./state-migrations.retired-files-CuvyprJk.mjs";
import { t as backupLegacyStateSource } from "./state-migrations.source-backup-C2EON6dL.mjs";
import { f as updateCurrentConversationBindingRecordInDatabase } from "./current-conversation-bindings.kernel-Ap5fhzOe.mjs";
import { r as normalizeConversationRef } from "./session-binding-normalization-c5CMRfx2.mjs";
import { n as importRetiredStateSource, t as archiveRetiredStateFiles } from "./state-migrations.retired-archive-CeUxFagC.mjs";
import { t as listRetiredDeliveryQueueFiles } from "./state-migrations.retired-delivery-files-B976zD9Q.mjs";
import { n as listRetiredRestartSentinelFiles } from "./state-migrations.restart-sentinel-BWB7va0P.mjs";
import { r as listRetiredRuntimeStateFiles } from "./state-migrations.retired-runtime-files-BpaOYE7l.mjs";
import { t as withLegacyMigrationStateLock } from "./state-migrations.lock-DKVTkbR4.mjs";
import { n as upsertPluginBindingApprovalInDatabase, t as readPluginBindingApprovalsInDatabase } from "./conversation-binding-state.kernel-DBgNORJc.mjs";
import path from "node:path";
import os from "node:os";
//#region src/infra/state-migrations.retired-runtime.ts
function normalizeLegacyBinding(e) {
const t = asRecord(e);
const n = asRecord(t.conversation);
const r = normalizeOptionalString(n.channel);
const i = normalizeOptionalString(n.conversationId);
const a = normalizeOptionalString(t.targetSessionKey);
if (!r || !i || !a) throw new Error("Invalid legacy conversation binding");
const o = normalizeConversationRef({
channel: r,
accountId: normalizeOptionalString(n.accountId) ?? "default",
conversationId: i,
...typeof n.parentConversationId === "string" ? { parentConversationId: n.parentConversationId } : {}
});
return {
bindingId: `generic:${[
o.channel,
o.accountId,
o.parentConversationId ?? "",
o.conversationId
].join("␟")}`,
targetSessionKey: a,
targetKind: t.targetKind === "subagent" ? "subagent" : "session",
conversation: o,
status: t.status === "ending" || t.status === "ended" ? t.status : "active",
boundAt: typeof t.boundAt === "number" && Number.isFinite(t.boundAt) ? Math.floor(t.boundAt) : Date.now(),
...typeof t.expiresAt === "number" && Number.isFinite(t.expiresAt) ? { expiresAt: Math.floor(t.expiresAt) } : {},
...t.metadata && typeof t.metadata === "object" && !Array.isArray(t.metadata) ? { metadata: asRecord(t.metadata) } : {}
};
}
/** Doctor-only import; ordinary runtime readers never open these retired sources. */
async function migrateRetiredRuntimeState(e) {
const t = {
...e.env ?? process.env,
OPENCLAW_STATE_DIR: e.stateDir
};
const n = {
changes: [],
warnings: []
};
async function migrate(t, r, i, a) {
const o = path.join(e.stateDir, t);
if (listExistingRetiredStateFiles([o]).length === 0) return;
await importRetiredStateSource({
source: await backupLegacyStateSource({
filePath: o,
assertCurrent: e.assertCurrent
}),
label: t,
parse: (e) => r(JSON.parse(decodeUtf8Input(e, `Legacy ${t}`))),
commit: i,
recoveryInstructions: a,
result: n
});
}
await migrate("settings/voicewake.json", (e) => {
const t = normalizeTrimmedStringList(asRecord(e).triggers);
if (t.length === 0) throw new Error("No valid voice wake triggers");
return t;
}, (e) => {
updateConfigMachineState("voicewake.triggers", (t) => t === void 0 ? e : t, { env: t });
}, "Restore the listed trigger phrases through Voice Wake settings.");
await migrate("settings/voicewake-routing.json", (e) => {
const t = asRecord(e);
if (!Array.isArray(t.routes)) throw new Error("Invalid voice wake routing rules");
return t;
}, (e) => {
updateConfigMachineState("voicewake.routing", (t) => t === void 0 ? e : t, { env: t });
}, "Restore the archived defaultTarget and routes through Voice Wake routing settings.");
await migrate("bindings/current-conversations.json", (e) => {
const t = asRecord(e);
if (t.version !== 1 || !Array.isArray(t.bindings)) throw new Error("Expected version 1 conversation bindings");
return t.bindings.map(normalizeLegacyBinding);
}, (n) => {
runOpenClawStateWriteTransaction(({ db: t }) => {
e.assertCurrent();
for (const e of n) if (!executeSqliteQueryTakeFirstSync(t, getNodeSqliteKysely(t).selectFrom("current_conversation_bindings").select("binding_key").where("binding_key", "=", e.bindingId.slice(8)))) updateCurrentConversationBindingRecordInDatabase(t, e.conversation, () => e);
}, { env: t });
}, "Use /focus in each archived conversation to reconnect its target session.");
const r = path.join(resolveRequiredHomeDir(t, os.homedir), ".openclaw");
if (path.resolve(e.stateDir) === path.resolve(r)) await migrate("plugin-binding-approvals.json", (e) => {
const t = asRecord(e);
if (t.version !== 1 || !Array.isArray(t.approvals)) throw new Error("Expected version 1 plugin binding approvals");
return t.approvals.map((e) => {
const t = asRecord(e);
const n = normalizeOptionalString(t.pluginRoot);
const r = normalizeOptionalString(t.pluginId);
const i = normalizeOptionalString(t.channel)?.toLowerCase();
if (!n || !r || !i) throw new Error("Invalid plugin binding approval");
return {
pluginRoot: n,
pluginId: r,
channel: i,
accountId: normalizeOptionalString(t.accountId) ?? "default",
pluginName: normalizeOptionalString(t.pluginName),
approvedAt: typeof t.approvedAt === "number" && Number.isFinite(t.approvedAt) ? Math.floor(t.approvedAt) : Date.now()
};
});
}, (n) => {
runOpenClawStateWriteTransaction(({ db: t }) => {
e.assertCurrent();
const r = readPluginBindingApprovalsInDatabase(t);
for (const e of n) if (!r.some((t) => t.pluginRoot === e.pluginRoot && t.channel === e.channel && t.accountId === e.accountId)) upsertPluginBindingApprovalInDatabase(t, e);
}, { env: t });
}, "Review and approve the plugin again when binding its channel conversation.");
const i = await archiveRetiredStateFiles({
label: "runtime replay and notification state",
paths: [...[
"acp/event-ledger.json",
"acp/event-ledger.json.doctor-import",
"update-check.json"
].map((t) => path.join(e.stateDir, t)), ...listRetiredRestartSentinelFiles(e.stateDir)],
assertCurrent: e.assertCurrent,
recoveryInstructions: "Replay history and restart notifications are no longer active. Consult this archive to recover old event or notification details; new sessions and update checks rebuild runtime state."
});
n.changes.push(...i.changes);
n.warnings.push(...i.warnings);
return n;
}
//#endregion
//#region src/commands/doctor-retired-state-repair.ts
/** Run before plugin discovery and config recovery can hide the original locators. */
async function repairRetiredDoctorState(e = process.env) {
const t = resolveStateDir(e);
const n = listRetiredDeliveryQueueFiles(t);
const r = resolveLegacyInstalledPluginIndexStorePath({ stateDir: t });
if (listExistingRetiredStateFiles([
...listRetiredRuntimeStateFiles(t, e),
...n,
r
]).length === 0) return {
changes: [],
warnings: []
};
return withLegacyMigrationStateLock({
stateDir: t,
env: e,
label: "retired state",
releaseLabel: "Retired state",
run: async (e) => {
const i = getOpenClawDatabaseMaintenanceScope();
if (!i) throw new Error("Retired state repair requires exclusive maintenance ownership");
const a = i.assertOwnerCurrent;
const o = await migrateRetiredRuntimeState({
stateDir: t,
env: e,
assertCurrent: a
});
for (const e of [{
label: "delivery queue",
paths: n,
recoveryInstructions: "Legacy deliveries are not replayed automatically because they may already have been sent. Inspect the archived payload and explicitly resend any still-needed message through its channel; do not restore it to the queue."
}, {
label: "plugin install index",
paths: [r],
recoveryInstructions: "Doctor rebuilds the plugin inventory from configured installs. If a plugin is missing, inspect this archive for its package spec and run openclaw plugins install <package-spec>."
}]) {
const t = await archiveRetiredStateFiles({
...e,
assertCurrent: a
});
o.changes.push(...t.changes);
o.warnings.push(...t.warnings);
}
return {
...o,
warningDisposition: "recoverable"
};
}
});
}
//#endregion
export { repairRetiredDoctorState };