openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,368 lines • 53 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as resolveRequiredHomeDir } from "./home-dir-EKmgmdPG.mjs";
import { i as asOptionalObjectRecord, l as isRecord, n as asNullableObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { t as safeParseJson } from "./json-coercion-CaJLaav-.mjs";
import { p as normalizeStringEntriesLower } from "./string-normalization-DLmfYZXI.mjs";
import { s as safeRealpathSync } from "./boundary-path-C2gXEiXe.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { c as safeStatSync } from "./path-guards-TIjxtj6H.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { T as resolveOAuthDir } from "./paths-DAcAg5aV.mjs";
import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { i as resolveEnvironmentValue } from "./process-env-DVJdcOcM.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { C as isSubagentSessionKey, g as toAgentStoreSessionKey, j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs";
import { g as isReservedSystemAgentId, i as listAgentIds, s as readAgentRosterProperty, u as tryResolveDefaultAgentId } from "./agent-roster-t1ooUdXp.mjs";
import { n as formatSessionArchiveTimestamp } from "./artifacts-D7SzhQlr.mjs";
import { c as resolveSessionFilePathOptions, l as resolveSessionStorePathCore, o as resolveSessionFilePathCore, u as resolveSessionTranscriptsDirForAgent } from "./paths-DvQ5AJvD.mjs";
import { f as resolveAgentWorkspaceDir, g as resolveDefaultAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as decodeMountInfoPath } from "./mountinfo-path-CJN-JB-q.mjs";
import { o as resolveAgentModelFallbackValues } from "./model-input-DrM4DWHG.mjs";
import { c as listConfiguredChannelIdsForReadOnlyScope } from "./channel-presence-policy-6XNqNGJr.mjs";
import { l as readDeferredPluginMigrations } from "./deferred-plugin-migrations-C_CU0aKR.mjs";
import { t as hasSessionActiveAutoModelFallback } from "./model-override-provenance-DeIPDBg8.mjs";
import { l as resolveAgentModelFallbacksOverride } from "./agent-scope-BwB8YH6y.mjs";
import { n as resolveSessionStoreCompatibilityAgentId } from "./legacy.default-agent-owner-DpmHgK0A.mjs";
import { a as normalizeOptionalAgentRuntimeId } from "./agent-runtime-id-D8s1CaYB.mjs";
import { m as resolveConfiguredModelPolicyAllow, n as buildAllowedModelSet } from "./model-selection-shared-9Kz63Hhm.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import { n as parseModelRef } from "./model-selection-normalize-DIZCRGVF.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import { S as readAgentDatabaseAdmissionRefusal } from "./agent-database-admission-CL6wHJ_N.mjs";
import { c as listOpenClawRegisteredAgentDatabases } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs";
import "./openclaw-agent-db-registry-DobcJNwx.mjs";
import { H as resolveNativeSharedAuthStorePath, V as prepareSharedAuthStoreOwnershipForNative, b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs";
import { o as resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target-C8iD4yIo.mjs";
import { n as resolveCanonicalMainSessionKey } from "./main-session-key-DT_l1IDv.mjs";
import { n as canonicalizeMainSessionAlias } from "./main-session-BNL3-mRV.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { P as isHeartbeatUserMessage } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { l as resolveSessionStoreTargets, s as resolveConfiguredAgentDatabaseTargets } from "./targets-BVE0__Jb.mjs";
import { y as scanDoctorSessionEntriesStrict } from "./session-accessor-CizTbDQj.mjs";
import { r as loadExactSessionEntryReadOnly } from "./session-accessor.sqlite-exact-read-CbvqUmsG.mjs";
import { c as isValidAgentHarnessSessionStoreEntry } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { b as applySessionEntryExactReplacements, g as applySessionEntryLifecycleMutation } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import "./model-selection-C2A4Wyix.mjs";
import "./channel-plugin-ids-DZDzcpUB.mjs";
import { n as createRetainedAgentDatabaseMatcher } from "./agent-deletion-discovery-BUESMyCH.mjs";
import { s as listPluginDoctorSessionRouteStateOwners } from "./doctor-contract-registry-CFzLZXmq.mjs";
import { a as preserveDeferredPluginSessionSource } from "./deferred-plugin-session-sources-BvErqlCR.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { n as discoverAgentDatabaseMigrationTargets } from "./state-migrations.media-persistence-targets-C3oqX64B.mjs";
import { i as updateLegacySessionStore, t as loadLegacySessionStore } from "./state-migrations.legacy-session-store-D6luaLu_.mjs";
import { t as countLabel } from "./doctor-state-integrity-format-XVQ-DkEv.mjs";
import { r as resolveProactiveDeliveryTarget } from "./targets-CiRFkgHi.mjs";
import { i as resolveLegacyHeartbeatAgents, s as resolveLegacyHeartbeatIntervalMs } from "./doctor-heartbeat-legacy-DmzlheVU.mjs";
import { i as isSharedAuthStoreOwner } from "./agent-delete-safety-CGn0sYfd.mjs";
import { n as clearTuiLastSessionPointers } from "./tui-last-session-Cp5dWsFx.mjs";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { StringDecoder } from "node:string_decoder";
//#region src/commands/doctor-heartbeat-main-session-repair.ts
const TRANSCRIPT_SCAN_CHUNK_BYTES = 65536;
const TRANSCRIPT_RECORD_MAX_CHARS = 262144;
function accumulateTranscriptHeartbeatMessage(e, t) {
const n = asNullableObjectRecord(safeParseJson(t.trim()));
const r = asNullableObjectRecord(n?.message) ?? n;
if (r?.role !== "user") return;
if (isHeartbeatUserMessage({
role: r.role,
content: r.content
})) e.heartbeatUserMessages += 1;
else e.nonHeartbeatUserMessages += 1;
}
function scanTranscriptHeartbeatMessages(e) {
let t;
try {
t = fs.openSync(e, "r");
} catch {
return null;
}
const n = {
heartbeatUserMessages: 0,
nonHeartbeatUserMessages: 0
};
try {
const e = new StringDecoder("utf8");
const r = Buffer.alloc(TRANSCRIPT_SCAN_CHUNK_BYTES);
let i = "";
for (;;) {
const a = fs.readSync(t, r, 0, r.length, null);
if (a <= 0) break;
i += e.write(r.subarray(0, a));
let o = i.indexOf("\n");
while (o >= 0) {
if (o > TRANSCRIPT_RECORD_MAX_CHARS) return "record-too-large";
const e = i.slice(0, o).replace(/\r$/, "");
i = i.slice(o + 1);
accumulateTranscriptHeartbeatMessage(n, e);
o = i.indexOf("\n");
}
if (i.length > TRANSCRIPT_RECORD_MAX_CHARS) return "record-too-large";
}
i += e.end();
if (i.length > TRANSCRIPT_RECORD_MAX_CHARS) return "record-too-large";
if (i) accumulateTranscriptHeartbeatMessage(n, i.replace(/\r$/, ""));
} finally {
fs.closeSync(t);
}
return n;
}
function resolveHeartbeatMainSessionRepairCandidate(e) {
const { entry: t, transcriptPath: n } = e;
if (!t || t.lastInteractionAt !== void 0) return null;
const r = typeof t.heartbeatIsolatedBaseSessionKey === "string" && t.heartbeatIsolatedBaseSessionKey.trim().length > 0;
if (!n) return r ? { reason: "heartbeat metadata" } : null;
const i = scanTranscriptHeartbeatMessages(n);
if (i === "record-too-large") return i;
if (!i) return null;
if (i.heartbeatUserMessages > 0 && i.nonHeartbeatUserMessages === 0) return { reason: r ? "heartbeat metadata" : `${i.heartbeatUserMessages} heartbeat-only user message(s)` };
return null;
}
function resolveHeartbeatMainRecoveryKey(e) {
const t = parseAgentSessionKey(e.mainKey);
if (!t) return null;
const n = formatSessionArchiveTimestamp().toLowerCase();
const r = `agent:${t.agentId}:heartbeat-recovered-${n}`;
for (let t = 1; t <= 100; t += 1) {
const n = t === 1 ? r : `${r}-${t}`;
if (!e.isSessionKeyOccupied(n)) return n;
}
return null;
}
async function repairHeartbeatPoisonedMainSession(e) {
const t = e.mainKey;
const n = e.mainEntry;
if (!n?.sessionId) return false;
let r;
try {
r = resolveSessionFilePathCore(n.sessionId, n, e.sessionPathOpts);
} catch {
r = void 0;
}
if (r && !fs.existsSync(r)) r = void 0;
const i = resolveHeartbeatMainSessionRepairCandidate({
entry: n,
transcriptPath: r
});
if (!i) return false;
if (i === "record-too-large") {
e.warnings.push(`- Skipped heartbeat main-session recovery for ${t}: the transcript contains a JSONL record larger than ${TRANSCRIPT_RECORD_MAX_CHARS} characters, so doctor left it unchanged.`);
return false;
}
const a = resolveHeartbeatMainRecoveryKey({
mainKey: t,
isSessionKeyOccupied: e.isSessionKeyOccupied
});
if (!a) {
e.warnings.push(`- Main session ${t} appears heartbeat-owned, but doctor could not choose a safe recovery key.`);
return false;
}
e.warnings.push([`- Main session ${t} appears to be a heartbeat-owned session (${i.reason}).`, ` Doctor can move it to ${a} and let the next interactive launch create a fresh main session.`].join("\n"));
if (!await e.prompter.confirmRuntimeRepair({
message: `Move heartbeat-owned main session ${t} to ${a} and clear stale TUI restore pointers?`,
initialValue: true
})) return false;
let o;
if (e.store.kind === "sqlite") {
if ((await applySessionEntryLifecycleMutation({
agentId: e.store.agentId,
removals: [{
archiveRemovedTranscript: false,
expectedEntry: n,
sessionKey: t
}],
skipMaintenance: true,
storePath: e.store.path,
upserts: [{
entry: n,
requiresRemovalSessionKey: t,
sessionKey: a
}]
})).removedSessionKeys.includes(t)) o = n;
} else await updateLegacySessionStore(e.store.path, (e) => {
const n = e[t];
const i = resolveHeartbeatMainSessionRepairCandidate({
entry: n,
transcriptPath: r
});
if (!i || i === "record-too-large") return;
if (n && !e[a]) {
e[a] = n;
delete e[t];
o = n;
}
});
if (!o) {
e.warnings.push(`- Main session ${t} changed before repair could move it.`);
return false;
}
let s = 0;
try {
s = await clearTuiLastSessionPointers({
stateDir: e.stateDir,
sessionKeys: /* @__PURE__ */ new Set([t])
});
} catch (n) {
e.warnings.push(`- Moved heartbeat-owned main session ${t}, but could not clear its TUI restore pointers: ${String(n)}`);
}
e.changes.push(`- Moved heartbeat-owned main session ${t} to ${a}.`);
if (s > 0) e.changes.push(`- Cleared ${countLabel(s, "stale TUI last-session pointer")} for ${t}.`);
return true;
}
//#endregion
//#region src/commands/doctor-heartbeat-session-target.ts
/** Warn without rewriting an operator's legacy session or delivery target. */
async function describeHeartbeatSessionTargetIssues(e) {
const t = [];
const n = e.session?.scope ?? "per-sender";
for (const { agentId: r, heartbeat: i } of resolveLegacyHeartbeatAgents(e)) {
if (!i || !resolveLegacyHeartbeatIntervalMs(e, void 0, i)) continue;
const a = normalizeOptionalString(i.session);
if (!a) continue;
const o = a.toLowerCase();
if (o === "main" || o === "global" || isSubagentSessionKey(a) || n === "global") continue;
const s = normalizeOptionalString(i.target);
if (s === "none") continue;
const c = await resolveProactiveDeliveryTarget({
cfg: e,
agentId: r,
policy: i
});
if (c.channel !== "none" && c.to) continue;
const l = toAgentStoreSessionKey({
agentId: r,
requestKey: a,
mainKey: e.session?.mainKey
});
if (isSubagentSessionKey(l)) continue;
const u = canonicalizeMainSessionAlias({
cfg: e,
agentId: r,
sessionKey: l
});
if (u === "global" || isSubagentSessionKey(u) || resolveAgentIdFromSessionKey(u) !== r) continue;
const d = resolveSessionStorePathCore(e.session?.store, { agentId: r });
if (await readSessionEntryReadOnlyInWorker({
agentId: r,
sessionKey: u,
storePath: d
}) ?? (!isIncognitoSessionKey(u) && !d.endsWith(".sqlite") && fs.existsSync(d) ? loadLegacySessionStore(d)[u] : void 0)) continue;
const f = resolveSqliteTargetFromSessionStorePath(d, { agentId: r }).path;
const p = s === void 0 || s === "owner";
const m = p ? " After migration, the automation uses standard delivery handling; a missing owner route can cause a delivery failure instead of skipping the run." : " After migration, the automation uses standard delivery handling; a missing session route or recipient can cause a delivery failure instead of skipping the run.";
const h = p ? ` Fix: set commands.ownerAllowFrom=["telegram:123456789"] or a channel allowFrom to a direct-message owner; for explicit delivery, set heartbeat.target="telegram" with heartbeat.to="123456789"; use heartbeat.target="none" to suppress delivery.` : ` Fix: point heartbeat.session at a session the agent actually owns, set heartbeat.target="none" to suppress delivery, or remove the heartbeat.session field to fall back to the agent main session.`;
t.push([
`- Agent ${r} heartbeat.session pins ${a} (resolved to ${u}) but that session has no entry in ${f}.`,
m,
h
].join("\n"));
}
return t;
}
//#endregion
//#region src/commands/doctor-session-state-providers.ts
function normalizeIdSet(e) {
return new Set((e ?? []).map((e) => normalizeProviderId(e)));
}
function ownsPrefixedValue(e, t) {
const n = normalizeOptionalString(t)?.toLowerCase();
return n !== void 0 && e.some((e) => n.startsWith(e));
}
function repairExample(e) {
return `${e.key} (${e.reasons.join(", ")})`;
}
function resolveSessionAgentId(e, t, n) {
return parseAgentSessionKey(t)?.agentId ?? n ?? tryResolveDefaultAgentId(e);
}
/** Resolves the currently configured provider/model/runtime route for a session key. */
function resolveConfiguredDoctorSessionStateRoute(e) {
const { agentId: t } = e;
const n = resolveDefaultModelForAgent({
cfg: e.cfg,
agentId: t
});
const r = /* @__PURE__ */ new Set([modelKey(n.provider, n.model)]);
const i = resolveAgentModelFallbacksOverride(e.cfg, t) ?? resolveAgentModelFallbackValues(e.cfg.agents?.defaults?.model);
for (const e of i) {
const t = parseModelRef(e, n.provider, {
allowManifestNormalization: false,
allowPluginNormalization: false
});
if (t) r.add(modelKey(t.provider, t.model));
}
const a = resolveAgentHarnessPolicy({
provider: n.provider,
modelId: n.model,
config: e.cfg,
agentId: t,
sessionKey: e.sessionKey
}).runtime;
return {
defaultProvider: n.provider,
configuredModelRefs: [...r],
modelPolicy: resolveConfiguredModelPolicyAllow({
cfg: e.cfg,
agentId: t
}).configPath === null ? void 0 : buildAllowedModelSet({
cfg: e.cfg,
catalog: [],
agentId: t,
defaultProvider: n.provider,
defaultModel: n
}),
runtime: a
};
}
function entryMayContainPluginSessionRouteState(e, t) {
if (isValidAgentHarnessSessionStoreEntry(e, t)) return false;
if (!isRecord(t)) return false;
const n = t;
return normalizeOptionalString(n.providerOverride) !== void 0 || normalizeOptionalString(n.modelOverride) !== void 0 || normalizeOptionalString(n.modelOverrideSource) !== void 0 || n.liveModelSwitchPending !== void 0 || normalizeOptionalString(n.modelProvider) !== void 0 || normalizeOptionalString(n.model) !== void 0 || normalizeOptionalString(n.agentHarnessId) !== void 0 || normalizeOptionalString(n.agentRuntimeOverride) !== void 0 || n.cliSessionBindings !== void 0 || n.cliSessionIds !== void 0 || normalizeOptionalString(n.claudeCliSessionId) !== void 0 || normalizeOptionalString(n.authProfileOverride) !== void 0 || normalizeOptionalString(n.authProfileOverrideSource) !== void 0;
}
function resolvePersistedOverrideModelRef(e) {
const t = normalizeOptionalString(e.overrideModel);
if (!t) return null;
const n = normalizeOptionalString(e.overrideProvider);
return parseModelRef(n ? `${n}/${t}` : t, e.defaultProvider, {
allowManifestNormalization: false,
allowPluginNormalization: false
});
}
function addReason(e, t) {
if (!e.includes(t)) e.push(t);
}
function hasOwnedCliSession(e) {
const t = [e.entry.cliSessionBindings, e.entry.cliSessionIds].map(asOptionalObjectRecord);
return e.cliSessionKeys.some((n) => n === "claude-cli" && normalizeOptionalString(e.entry.claudeCliSessionId) !== void 0 || t.some((e) => e && n in e && e[n] !== void 0));
}
function modelRefKey(e, t) {
return modelKey(e, t).toLowerCase();
}
function scanEntryForOwner(e) {
const t = normalizeIdSet(e.owner.providerIds);
const n = normalizeIdSet(e.owner.runtimeIds);
const r = [...normalizeIdSet(e.owner.cliSessionKeys)];
const i = normalizeStringEntriesLower(e.owner.authProfilePrefixes);
const a = n.has(normalizeProviderId(e.route.runtime));
const o = a || e.route.configuredModelRefs.some((e) => {
const n = e.indexOf("/");
return n > 0 && t.has(normalizeProviderId(e.slice(0, n)));
});
const s = [];
const c = [];
const l = resolvePersistedOverrideModelRef({
defaultProvider: e.route.defaultProvider,
overrideProvider: e.entry.providerOverride,
overrideModel: e.entry.modelOverride
});
const u = l ? modelRefKey(l.provider, l.model) : void 0;
const d = l !== null && t.has(normalizeProviderId(l.provider));
const f = u !== void 0 && e.route.configuredModelRefs.some((e) => e.toLowerCase() === u);
const p = e.entry.modelOverrideSource === "user" ? "user" : e.entry.modelOverrideSource === "auto" ? "auto" : e.entry.modelOverride ? "legacy" : void 0;
if (d && !f) {
if (p === "auto") {
if (hasSessionActiveAutoModelFallback({
providerOverride: normalizeOptionalString(e.entry.providerOverride),
modelOverride: normalizeOptionalString(e.entry.modelOverride),
modelOverrideSource: "auto",
modelOverrideFallbackOriginProvider: normalizeOptionalString(e.entry.modelOverrideFallbackOriginProvider),
modelOverrideFallbackOriginModel: normalizeOptionalString(e.entry.modelOverrideFallbackOriginModel)
}) || !e.route.modelPolicy?.allows(l)) addReason(s, "auto model override");
} else if (!o) return { manualReview: {
ownerLabel: e.owner.label,
message: `${e.key} (${modelRefKey(l.provider, l.model)}, ${p === "user" ? "user" : "legacy"})`
} };
}
const m = d && p !== void 0 && p !== "auto";
if (!a && !m) for (const t of ["agentHarnessId", "agentRuntimeOverride"]) {
const r = normalizeOptionalString(e.entry[t]);
if (r && n.has(normalizeProviderId(r))) {
addReason(s, "pinned runtime");
c.push(t);
}
}
if (!o && !m) {
const n = resolvePersistedOverrideModelRef({
defaultProvider: "",
overrideProvider: e.entry.modelProvider,
overrideModel: e.entry.model
});
if (n && t.has(normalizeProviderId(n.provider))) addReason(s, "runtime model state");
if (hasOwnedCliSession({
entry: e.entry,
cliSessionKeys: r
})) addReason(s, "CLI session binding");
if (e.entry.authProfileOverrideSource === "auto" && ownsPrefixedValue(i, e.entry.authProfileOverride)) addReason(s, "auto auth profile override");
}
if (s.length === 0) return {};
return { repair: {
key: e.key,
ownerLabel: e.owner.label,
reasons: s,
pinnedRuntimeKeys: c,
cliSessionKeys: r
} };
}
/** Streams session entries into compact plugin-owned route-state findings. */
function createPluginSessionStateDoctorScanner(e) {
const t = [];
const n = [];
let r;
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Map();
const recordScan = (e) => {
if (e.repair) t.push(e.repair);
if (e.manualReview) n.push(e.manualReview);
};
return {
scanEntry(t, n) {
if (!entryMayContainPluginSessionRouteState(t, n)) return;
r ??= listPluginDoctorSessionRouteStateOwners({
config: e.cfg,
env: e.env
});
if (r.length === 0) return;
const o = resolveSessionAgentId(e.cfg, t, e.agentId);
if (!o) return;
let s = i.get(o);
if (!s) {
s = resolveConfiguredDoctorSessionStateRoute({
agentId: o,
cfg: e.cfg,
sessionKey: t
});
i.set(o, s);
}
for (const e of r) {
const r = normalizeOptionalAgentRuntimeId(n.agentRuntimeOverride);
if (n.modelOverrideSource === "user" && r && normalizeIdSet(e.runtimeIds).has(normalizeProviderId(r))) {
const i = a.get(o) ?? [];
i.push({
key: t,
ownerLabel: e.label,
runtime: r,
model: resolvePersistedOverrideModelRef({
defaultProvider: s.defaultProvider,
overrideProvider: n.providerOverride,
overrideModel: n.modelOverride
})
});
a.set(o, i);
} else recordScan(scanEntryForOwner({
key: t,
entry: n,
owner: e,
route: s
}));
}
},
async result() {
if (a.size === 0) return {
repairs: t,
manualReview: n
};
const [{ resolveAgentRuntimePluginLoadPlan: r }, { buildAgentHarnessSupportContext: i }, { listCliRuntimeModelBackendBindings: o }, { acquirePluginRegistryForInspection: s }, { loadPluginMetadataSnapshot: c }, { withPluginRuntimeRegistryScope: l }] = await Promise.all([
import("./runtime-plugin-load-plan-DrPn-r0B.mjs"),
import("./support-CtkvMFW9.mjs"),
import("./cli-backends-C2g93C4O.mjs"),
import("./plugins/loader.js"),
import("./plugin-metadata-snapshot-PjL6_oGE.mjs"),
import("./gateway-request-scope-CF7UIf6R.mjs")
]);
for (const [n, u] of a) {
const a = resolveAgentWorkspaceDir(e.cfg, n);
const d = r({
config: e.cfg,
workspaceDir: a,
purpose: "isolated-completion",
selections: u.flatMap(({ model: e, runtime: t }) => e ? [{
provider: e.provider,
modelId: e.model,
runtime: t,
agentId: n
}] : []),
metadataSnapshot: c({
config: e.cfg,
workspaceDir: a,
env: e.env
})
});
const f = d.pluginIds?.length ? await s({
config: d.config ?? e.cfg,
env: e.env,
workspaceDir: a,
onlyPluginIds: d.pluginIds
}) : void 0;
try {
const r = f ? l(f.registry, () => o()) : [];
for (const a of u) {
const o = a.model;
const s = f?.registry.agentHarnesses.find((e) => e.harness.id === a.runtime)?.harness;
if (!Boolean(o && !e.cfg.cloudWorkers?.requiredProfile && (r.some((e) => e.runtime === a.runtime && e.provider === normalizeProviderId(o.provider)) || s && f && l(f.registry, () => s.supports(i({
provider: o.provider,
modelId: o.model,
requestedRuntime: a.runtime,
contextManagement: s.contextManagement,
config: e.cfg,
agentId: n,
sessionKey: a.key
}))).supported))) t.push({
key: a.key,
ownerLabel: a.ownerLabel,
reasons: ["pinned runtime"],
pinnedRuntimeKeys: ["agentRuntimeOverride"],
cliSessionKeys: []
});
}
} finally {
await f?.release();
}
}
a.clear();
return {
repairs: t,
manualReview: n
};
}
};
}
function clearRecordKeys(e, t, n) {
const r = asOptionalObjectRecord(e[t]);
if (!r) return false;
let i = false;
const a = { ...r };
for (const e of n) if (a[e] !== void 0) {
delete a[e];
i = true;
}
if (!i) return false;
e[t] = Object.keys(a).length > 0 ? a : void 0;
return true;
}
/** Clears stale plugin-owned routing fields from a session entry and refreshes updatedAt. */
function applySessionRouteStateRepair(e) {
if (isValidAgentHarnessSessionStoreEntry(e.sessionKey, e.entry)) return false;
let t = false;
const clear = (n) => {
if (e.entry[n] !== void 0) {
delete e.entry[n];
t = true;
}
};
if (e.repair.reasons.includes("auto model override")) {
clear("providerOverride");
clear("modelOverride");
clear("modelOverrideSource");
clear("modelOverrideFallbackOriginProvider");
clear("modelOverrideFallbackOriginModel");
clear("modelOverrideRouteResolution");
clear("liveModelSwitchPending");
}
if (e.repair.reasons.includes("runtime model state")) {
clear("model");
clear("modelProvider");
clear("contextTokens");
clear("systemPromptReport");
clear("fallbackNotice");
}
if (e.repair.reasons.includes("pinned runtime")) for (const t of e.repair.pinnedRuntimeKeys) clear(t);
if (e.repair.reasons.includes("CLI session binding")) {
t = clearRecordKeys(e.entry, "cliSessionBindings", e.repair.cliSessionKeys) || t;
t = clearRecordKeys(e.entry, "cliSessionIds", e.repair.cliSessionKeys) || t;
if (e.repair.cliSessionKeys.includes("claude-cli")) clear("claudeCliSessionId");
}
if (e.repair.reasons.includes("auto auth profile override")) {
clear("authProfileOverride");
clear("authProfileOverrideSource");
clear("authProfileOverrideCompactionCount");
}
if (t) e.entry.updatedAt = e.now;
return t;
}
/** Prompts for and applies plugin-owned session route state repairs to the session store. */
async function runPluginSessionStateDoctorRepairs(e) {
const { scan: t } = e;
for (const [n, r] of groupPluginRecords(t.repairs, (e) => e.ownerLabel)) {
const t = countLabel(r.length, "session");
e.warnings.push([
`- Found stale ${n} session routing state in ${t}.`,
" An unavailable runtime or legacy routing state can keep later runs on an obsolete route.",
` Examples: ${r.slice(0, 3).map(repairExample).join(", ")}`
].join("\n"));
if (await e.prompter.confirmRuntimeRepair({
message: `Clear stale ${n} session routing state for ${t}?`,
initialValue: true
})) {
let t = 0;
const i = Date.now();
const a = new Map(r.map((e) => [e.key, e]));
const repairEntry = (e, t) => {
const n = a.get(e);
return n && isRecord(t) && applySessionRouteStateRepair({
sessionKey: e,
entry: t,
repair: n,
now: i
});
};
if (e.store.kind === "sqlite") t = await applySessionEntryExactReplacements({
agentId: e.store.agentId,
sessionKeys: [...a.keys()],
storePath: e.store.path,
update: (e) => {
const t = e.filter(({ entry: e, sessionKey: t }) => repairEntry(t, e));
return {
replacements: t,
result: t.length
};
}
});
else await updateLegacySessionStore(e.store.path, (e) => {
for (const n of a.keys()) if (repairEntry(n, e[n])) t += 1;
});
if (t > 0) e.changes.push(`- Cleared stale ${n} session routing state for ${countLabel(t, "session")}.`);
}
}
for (const [n, r] of groupPluginRecords(t.manualReview, (e) => e.ownerLabel)) e.warnings.push([
`- Found explicit ${n} model overrides in ${countLabel(r.length, "session")} outside the current configured route.`,
" Doctor leaves explicit or legacy user selections untouched; switch them with /model or reset the session if that provider is no longer intended.",
` Examples: ${r.slice(0, 3).map((e) => e.message).join(", ")}`
].join("\n"));
}
//#endregion
//#region src/commands/doctor-state-storage-platform.ts
function resolvePathThroughExistingAncestor(e, t) {
const n = [];
let r = t.resolve(e);
while (true) {
const e = safeRealpathSync(r);
if (e) return t.resolve(e, ...n);
const i = t.dirname(r);
if (i === r) return null;
n.unshift(t.basename(r));
r = i;
}
}
function escapeControlCharsForTerminal(e) {
const t = {
"\r": "\\r",
"\n": "\\n",
" ": "\\t"
};
return Array.from(e, (e) => {
const n = e.charCodeAt(0);
return n <= 31 || n === 127 ? t[e] ?? `\\x${n.toString(16).padStart(2, "0")}` : e;
}).join("");
}
function parseLinuxMountInfo(e) {
const t = [];
for (const n of e.split("\n")) {
const e = n.trim();
if (!e) continue;
const r = e.indexOf(" - ");
if (r === -1) continue;
const i = e.slice(0, r);
const a = e.slice(r + 3);
const o = i.split(" ");
const s = a.split(" ");
if (o.length < 5 || s.length < 2) continue;
t.push({
mountPoint: decodeMountInfoPath(expectDefined(o[4], "left fields entry at 4")),
fsType: expectDefined(s[0], "right fields entry at 0"),
source: decodeMountInfoPath(expectDefined(s[1], "right fields entry at 1"))
});
}
return t;
}
function isPathUnderRoot(e, t, n = path) {
const r = n.resolve(e);
const i = n.resolve(t);
const a = n.parse(i).root;
if (i === a) return r.startsWith(a);
return r === i || r.startsWith(`${i}${n.sep}`);
}
function findLinuxMountInfoEntryForPath(e, t, n) {
const r = n.resolve(e);
let i = null;
for (const e of t) {
if (!isPathUnderRoot(r, e.mountPoint, n)) continue;
if (!i || n.resolve(e.mountPoint).length > n.resolve(i.mountPoint).length) i = e;
}
return i;
}
function isMmcDevicePath(e, t) {
const n = t.basename(e);
return /^mmcblk\d+(?:p\d+)?$/.test(n);
}
function tryReadLinuxMountInfo() {
try {
return fs.readFileSync("/proc/self/mountinfo", "utf8");
} catch {
return null;
}
}
function resolveLinuxStateMount(e) {
const t = path.posix;
const n = resolvePathThroughExistingAncestor(e, t) ?? t.resolve(e);
const r = tryReadLinuxMountInfo();
const i = r ? findLinuxMountInfoEntryForPath(n, parseLinuxMountInfo(r), t) : null;
return i ? {
path: t.resolve(n),
mountPoint: t.resolve(i.mountPoint),
fsType: i.fsType,
source: i.source
} : null;
}
/** Detects Linux state directories mounted from SD/eMMC-style block devices. */
function detectLinuxSdBackedStateDir(e) {
if (process.platform !== "linux") return null;
const t = path.posix;
const n = resolveLinuxStateMount(e);
if (!n) return null;
const r = [n.source];
if (n.source.startsWith("/dev/")) {
const e = safeRealpathSync(n.source);
if (e) r.push(t.resolve(e));
}
if (!r.some((e) => isMmcDevicePath(e, t))) return null;
return n;
}
function formatLinuxSdBackedStateDirWarning(e, t) {
const n = t.mountPoint === "/" ? "/" : shortenHomePath(t.mountPoint);
return [
`- State directory appears to be on SD/eMMC storage (${e}; device ${escapeControlCharsForTerminal(t.source)}, fs ${escapeControlCharsForTerminal(t.fsType)}, mount ${escapeControlCharsForTerminal(n)}).`,
"- SD/eMMC media can be slower for random I/O and wear faster under session/log churn.",
"- For better startup and state durability, prefer SSD/NVMe (or USB SSD on Raspberry Pi) for OPENCLAW_STATE_DIR."
].join("\n");
}
/** Filesystems whose state disappears on reboot. Docker overlayfs is intentionally excluded. */
const VOLATILE_FS_TYPES = /* @__PURE__ */ new Set(["tmpfs", "ramfs"]);
/** Detects Linux state directories mounted on filesystems that do not survive a reboot. */
function detectLinuxVolatileStateDir(e) {
if (process.platform !== "linux") return null;
const t = resolveLinuxStateMount(e);
if (!t || !VOLATILE_FS_TYPES.has(t.fsType)) return null;
const { source: n, ...r } = t;
return r;
}
function formatLinuxVolatileStateDirWarning(e, t) {
return [
`- State directory is on a volatile filesystem (${e}; fs ${escapeControlCharsForTerminal(t.fsType)}, mount ${t.mountPoint === "/" ? "/" : escapeControlCharsForTerminal(shortenHomePath(t.mountPoint))}).`,
"- Sessions, credentials, config, and SQLite state (including WAL/journal sidecars) will be lost on reboot.",
"- Move OPENCLAW_STATE_DIR to a persistent filesystem to avoid data loss."
].join("\n");
}
function detectCloudSyncedStateDir(e, t, n = false) {
if (t.length === 0) return null;
const r = resolvePathThroughExistingAncestor(e, path) ?? path.resolve(e);
const i = n ? r.toLowerCase() : r;
const a = t.find(({ root: e }) => isPathUnderRoot(i, n ? e.toLowerCase() : e));
return a ? {
path: r,
storage: a.storage
} : null;
}
/** Detects macOS state directories under iCloud Drive or CloudStorage providers. */
function detectMacCloudSyncedStateDir(e) {
if (process.platform !== "darwin") return null;
const t = os.homedir();
return detectCloudSyncedStateDir(e, [{
storage: "iCloud Drive",
root: path.join(t, "Library", "Mobile Documents", "com~apple~CloudDocs")
}, {
storage: "CloudStorage provider",
root: path.join(t, "Library", "CloudStorage")
}]);
}
/** Detects Windows state directories under OneDrive sync roots. */
function detectWindowsCloudSyncedStateDir(e, t = process.env) {
const n = process.platform;
if (n !== "win32") return null;
const r = [];
const addRoot = (e, t) => {
if (t && t.trim() !== "") r.push({
storage: e,
root: t
});
};
addRoot("OneDrive", resolveEnvironmentValue(t, "OneDrive", n));
addRoot("OneDrive", resolveEnvironmentValue(t, "OneDriveConsumer", n));
addRoot("OneDrive for Business", resolveEnvironmentValue(t, "OneDriveCommercial", n));
return detectCloudSyncedStateDir(e, r, true);
}
function formatWindowsCloudSyncedStateDirWarning(e, t) {
return [
`- State directory is under Windows cloud-synced storage (${e}; ${t.storage}).`,
"- This can cause slow I/O, sync/lock races, and Files On-Demand dehydration for sessions and credentials.",
"- Prefer a local non-synced state dir (for example: %USERPROFILE%\\.openclaw).",
"- To relocate: stop the Gateway, move the whole state directory, set",
" OPENCLAW_STATE_DIR to the new path for the Gateway service (not just",
" one shell), then restart it and re-run doctor to verify."
].join("\n");
}
//#endregion
//#region src/commands/doctor-unconfigured-agent-databases.ts
function isDefaultAgentDatabasePath(e, t) {
const n = path.relative(t, e).split(path.sep);
return n.length === 4 && n[0] === "agents" && n[2] === "agent" && n[3] === "openclaw-agent.sqlite";
}
/** Report retained stores without turning roster absence into deletion authority. */
function collectRetainedUnconfiguredAgentDatabaseWarnings(e) {
const t = e.env ?? process.env;
try {
const n = fs.realpathSync.native(resolveStateDir(t));
const r = listOpenClawRegisteredAgentDatabases({
env: t,
includeIncompatibleSchemaVersions: true
});
const i = resolveConfiguredAgentDatabaseTargets(e.cfg, {
env: t,
registeredDatabases: r
});
const a = discoverAgentDatabaseMigrationTargets({
configuredAgentDatabaseTargets: i,
registeredAgentDatabases: r,
env: t
});
return [...a.targets.flatMap((e) => {
if (e.source === "configured" || isDefaultAgentDatabasePath(e.realPath, n)) return [];
return [`- Retained unconfigured agent database "${sanitizeForLog(e.agentId)}" at ${sanitizeForLog(e.path)}. Doctor will not remove it automatically because it may contain retired or manually managed agent state.`];
}), ...a.externalWarnings];
} catch (e) {
return [`- Could not inspect retained unconfigured agent databases: ${sanitizeForLog(formatErrorMessage(e))}`];
}
}
//#endregion
//#region src/commands/doctor-state-integrity.ts
const STATE_INTEGRITY_CHECK_ID = "core/doctor/state-integrity";
function resolveSessionRuntimeDirectories(e, t, n) {
const r = /* @__PURE__ */ new Map();
const i = tryResolveDefaultAgentId(e);
if (i) {
r.set(resolveSessionTranscriptsDirForAgent(i, t, n), "Sessions dir");
r.set(path.dirname(resolveSessionStorePathCore(e.session?.store, {
agentId: i,
env: t
})), "Session store dir");
}
return r;
}
function tryResolveNativeRealPath(e) {
try {
return fs.realpathSync.native(e);
} catch {
return null;
}
}
function areComparablePathsEqual(e, t) {
const n = tryResolveNativeRealPath(e);
const r = tryResolveNativeRealPath(t);
return n !== null && n === r;
}
function isReachableConfiguredAgentDir(e) {
if (e.dirName === e.agentId) return true;
return areComparablePathsEqual(path.join(e.agentsRoot, e.dirName, "agent"), path.join(e.agentsRoot, e.agentId, "agent"));
}
function listOrphanAgentDirs(e, t) {
const n = new Set(listAgentIds(e));
const r = prepareSharedAuthStoreOwnershipForNative();
const i = resolveNativeSharedAuthStorePath();
const a = tryResolveDefaultAgentId(e);
const o = path.join(t, "agents");
const s = a ? resolveDefaultAgentDir(e) : void 0;
try {
return fs.readdirSync(o, { withFileTypes: true }).flatMap((e) => {
if (!e.isDirectory()) return [];
const t = e.name;
const a = normalizeAgentId(t);
const c = path.join(o, t, "agent");
if (!safeStatSync(c)?.isDirectory() || isReservedSystemAgentId(a) || isSharedAuthStoreOwner({
ownership: r,
agentAuthDbPath: resolveAuthProfileDatabasePath(c),
sharedAuthDbPath: i
}) || s && areComparablePathsEqual(c, s) || n.has(a) && isReachableConfiguredAgentDir({
agentsRoot: o,
dirName: t,
agentId: a
})) return [];
return [{
dirName: t,
agentId: a
}];
}).toSorted((e, t) => e.agentId.localeCompare(t.agentId) || e.dirName.localeCompare(t.dirName));
} catch {
return [];
}
}
function canWriteDir(e) {
try {
fs.accessSync(e, fs.constants.W_OK);
return true;
} catch {
return false;
}
}
function ensureDir(e) {
try {
fs.mkdirSync(e, { recursive: true });
return { ok: true };
} catch (e) {
return {
ok: false,
error: String(e)
};
}
}
function dirPermissionHint(e) {
const t = typeof process.getuid === "function" ? process.getuid() : null;
const n = typeof process.getgid === "function" ? process.getgid() : null;
try {
const r = fs.statSync(e);
if (t !== null && r.uid !== t) return `Owner mismatch (uid ${r.uid}). Run: sudo chown -R $USER "${e}"`;
if (n !== null && r.gid !== n) return `Group mismatch (gid ${r.gid}). If access fails, run: sudo chown -R $USER "${e}"`;
} catch {
return null;
}
return null;
}
function readGroupOrWorldAccessibleMode(e) {
const t = fs.lstatSync(e);
const n = t.isSymbolicLink();
const r = n ? fs.statSync(e) : t;
return !(n ? fs.realpathSync(e) : e).startsWith("/nix/store/") && (r.mode & 63) !== 0 ? r.mode : null;
}
function countJsonlLines(e) {
let t;
try {
t = fs.openSync(e, "r");
} catch {
return 0;
}
try {
const e = Buffer.alloc(65536);
let n = 0;
let r = true;
for (;;) {
const i = fs.readSync(t, e, 0, e.length, null);
if (i <= 0) break;
r = e[i - 1] === 10;
for (let t = 0; t < i; t += 1) if (e[t] === 10) n += 1;
}
if (!r) n += 1;
return n;
} catch {
return 0;
} finally {
fs.closeSync(t);
}
}
function isPairingPolicy(e) {
return normalizeOptionalLowercaseString(e) === "pairing";
}
function hasPairingPolicy(e) {
const t = asNullableObjectRecord(e);
if (!t) return false;
return isPairingPolicy(t.dmPolicy) || isPairingPolicy(asNullableObjectRecord(t.dm)?.policy) || Object.values(asNullableObjectRecord(t.accounts) ?? {}).some(hasPairingPolicy);
}
function shouldRequireOAuthDir(e, t) {
if (t.OPENCLAW_OAUTH_DIR?.trim()) return true;
const n = asNullableObjectRecord(e.channels);
if (!n) return false;
const r = new Set(listConfiguredChannelIdsForReadOnlyScope({
config: e,
env: t
}));
const i = new Set(listConfiguredChannelIdsForReadOnlyScope({
config: e,
env: t,
includePersistedAuthState: false
}));
if ([...r].some((e) => !i.has(e))) return true;
for (const [e, t] of Object.entries(n)) {
const n = normalizeOptionalLowercaseString(e);
if (!n || !r.has(n)) continue;
if (hasPairingPolicy(t)) return true;
}
return false;
}
function detectStateIntegrityHealthIssues(e, t) {
const n = [];
const appendDetectedIssue = (e) => {
if (e) n.push(e);
};
const r = t?.env ?? process.env;
const homedir = () => resolveRequiredHomeDir(r, os.homedir);
const i = resolveStateDir(r, homedir);
const a = resolveOAuthDir(r, i);
const o = resolveSessionRuntimeDirectories(e, r, homedir);
const s = shouldRequireOAuthDir(e, r);
const c = detectMacCloudSyncedStateDir(i);
appendDetectedIssue(c && {
kind: "mac-cloud-state-dir",
...c
});
const l = detectWindowsCloudSyncedStateDir(i, r);
appendDetectedIssue(l && {
kind: "windows-cloud-state-dir",
...l
});
const u = detectLinuxSdBackedStateDir(i);
appendDetectedIssue(u && {
kind: "linux-sd-state-dir",
...u
});
const d = detectLinuxVolatileStateDir(i);
appendDetectedIssue(d && {
kind: "linux-volatile-state-dir",
...d
});
const f = safeStatSync(i)?.isDirectory() === true;
if (!f) n.push({
kind: "missing-state-dir",
path: i
});
if (f && !canWriteDir(i)) {
const e = dirPermissionHint(i);
n.push({
kind: "state-dir-not-writable",
path: i,
...e ? { hint: e } : {}
});
}
if (f && process.platform !== "win32") try {
const e = readGroupOrWorldAccessibleMode(i);
if (e !== null) n.push({
kind: "state-dir-too-open",
path: i,
mode: e
});
} catch {}
if (t?.configPath && safeStatSync(t.configPath)?.isFile() && process.platform !== "win32") try {
const e = readGroupOrWorldAccessibleMode(t.configPath);
if (e !== null) n.push({
kind: "config-file-too-open",
path: t.configPath,
mode: e
});
} catch {}
if (f) {
if (s) o.set(a, "OAuth dir");
for (const [e, t] of o) {
if (!safeStatSync(e)?.isDirectory()) {
if (t === "OAuth dir") {
n.push({
kind: "missing-runtime-dir",
label: t,
path: e
});
continue;
}
continue;
}
if (!canWriteDir(e)) {
const r = dirPermissionHint(e);
n.push({
kind: "runtime-dir-not-writable",
label: t,
path: e,
...r ? { hint: r } : {}
});
}
}
}
return n;
}
function stateIntegrityIssueToHealthFinding(e) {
const finding = (t, n, r = "warning", i) => ({
checkId: STATE_INTEGRITY_CHECK_ID,
severity: r,
message: t,
path: e.path,
...i !== void 0 ? { target: i } : {},
fixHint: n
});
switch (e.kind) {
case "mac-cloud-state-dir": return finding(`State directory is under macOS cloud-synced storage (${e.storage}), which can cause slow I/O and sync races.`, "Move OPENCLAW_STATE_DIR to local non-synced storage such as ~/.openclaw.");
case "windows-cloud-state-dir": return finding(`State directory is under Windows cloud-synced storage (${e.storage}), which can cause slow I/O, sync races, and Files On-Demand dehydration.`, "Move OPENCLAW_STATE_DIR to local non-synced storage such as %USERPROFILE%\\.openclaw.");
case "linux-sd-state-dir": return finding(`State directory appears to be on SD/eMMC storage (${e.source}, ${e.fsType}), which can hurt startup and durability.`, "Move OPENCLAW_STATE_DIR to SSD/NVMe-backed storage.", "warning", e.mountPoint);
case "linux-volatile-state-dir": return finding(`State directory is on volatile ${e.fsType} storage and may disappear on reboot.`, "Move OPENCLAW_STATE_DIR to persistent local storage.", "warning", e.mountPoint);
case "missing-state-dir": return finding("State directory is missing. Sessions, credentials, logs, and config are stored there.", "Run `openclaw doctor --fix` to create the state directory.", "error");
case "state-dir-not-writable": return finding(e.hint ? `State directory is not writable. ${e.hint}` : "State directory is not writable.", "Run `openclaw doctor --fix` to repair state directory permissions.", "error");
case "state-dir-too-open": return finding("State directory permissions are too open. Recommend chmod 700.", "Run `openclaw doctor --fix` to tighten state directory permissions.");
case "config-file-too-open": return finding("Config file is group/world readable. Recommend chmod 600.", "Run `openclaw doctor --fix` to tighten config file permissions.");
case "missing-runtime-dir": return finding(`${e.label} is missing.`, "Run `openclaw doctor --fix` to create missing runtime state directories.");
case "runtime-dir-not-writable": return finding(e.hint ? `${e.label} is not writable. ${e.hint}` : `${e.label} is not writable.`, "Run `openclaw doctor --fix` to repair runtime state directory permissions.", "error");
}
return e;
}
function stateIntegrityIssueToRepairEffect(e) {
const effect = (t, n = false, r = "state") => ({
kind: r,
action: t,
target: e.path,
dryRunSafe: n
});
switch (e.kind) {
case "mac-cloud-state-dir":
case "windows-cloud-state-dir":
case "linux-sd-state-dir":
case "linux-volatile-state-dir": return effect("would-recommend-moving-state-dir", true);
case "missing-state-dir": return effect("would-create-state-dir");
case "state-dir-not-writable":
case "state-dir-too-open": return effect("would-repair-state-dir-permissions");
case "config-file-too-open": return effect("would-tighten-config-file-permissions", false, "file");
case "missing-runtime-dir": return effect("would-create-runtime-state-dir");
case "runtime-dir-not-writable": return effect("would-repair-runtime-state-dir-permissions");
}
return e;
}
/** Emits state integrity warnings and applies selected runtime repairs. */
async function noteStateIntegrity(e, t, n, r) {
const i = [];
const a = [];
const o = process.env;
const homedir = () => resolveRequiredHomeDir(o, os.homedir);
const s = resolveStateDir(o, homedir);
const c = resolveOAuthDir(o, s);
const l = resolveSessionRuntimeDirectories(e, o, homedir);
const u = shortenHomePath(s);
const d = shortenHomePath(c);
const f = n ? shortenHomePath(n) : void 0;
const p = shouldRequireOAuthDir(e, o);
const m = detectMacCloudSyncedStateDir(s);
const h = detectWindowsCloudSyncedStateDir(s);
const g = detectLinuxSdBackedStateDir(s);
const _ = detectLinuxVolatileStateDir(s);
const repairWritableDirectory = async (e, n, r) => {
if (canWriteDir(e)) return;
i.push(`- ${r ?? "State directory"} not writable (${n}).`);
const o = dirPermissionHint(e);
if (o) i.push(` ${o}`);
if (await t.confirmRuntimeRepair({
message: `Repair permissions on ${r ?? n}?`,
initialValue: true
})) try {
fs.chmodSync(e, fs.statSync(e).mode & 511 | 448);
a.push(`- Repaired permissions on ${r ? `${r}: ` : ""}${n}`);
} catch (e) {
i.push(`- Failed to repair ${n}: ${String(e)}`);
}
};
const tightenPermissions = async (e, n, r, o, s) => {
const c = r.toString(8);
try {
if (readGroupOrWorldAccessibleMode(e) === null) return;
i.push(o);
if (await t.confirmRuntimeRepair({
message: `Tighten permissions on ${n} to ${c}?`,
initialValue: true
})) {
fs.chmodSync(e, r);
a.push(`- Tightened permissions on ${n} to ${c}`);
}
} catch (e) {
i.push(`- Failed to read ${s}: ${String(e)}`);
}
};
if (m) i.push([
`- State directory is under macOS cloud-synced storage (${u}; ${m.storage}).`,
"- This can cause slow I/O and sync/lock races for sessions and credentials.",
"- Prefer a local non-synced state dir (for example: ~/.openclaw).",
` Set locally: OPENCLAW_STATE_DIR=~/.openclaw ${formatCliCommand("openclaw doctor")}`
].join("\n"));
if (h) i.push(formatWindowsCloudSyncedStateDirWarning(u, h));
if (g) i.push(formatLinuxSdBackedStateDirWarning(u, g));
if (_) i.push(formatLinuxVolatileStateDirWarning(u, _));
let v = safeStatSync(s)?.isDirectory() === true;
if (v && r?.stateDirExistedAtStart === false) i.push(`- State directory was missing at doctor start and was initialized during startup checks (${u}).`);
if (!v) {
i.push(`- CRITICAL: state directory missing (${u}). Sessions, credentials, logs, and config are stored there.`);
if (e.gateway?.mode === "remote") i.push("- Gateway is in remote mode; run doctor on the remote host where the gateway runs.");
if (await t.confirmRuntimeRepair({
message: `Create ${u} now?`,
initialValue: false
})) {
const e = ensureDir(s);
if (e.ok) {
a.push(`- Created ${u}`);
v = true;
} else i.push(`- Failed to create ${u}: ${e.error}`);
}
}
if (v) await repairWritableDirectory(s, u);
if (v && process.platform !== "win32") await tightenPermissions(s, u, 448, `- State directory permissions are too open (${u}). Recommend chmod 700.`, `${u} permissions`);
if (n && safeStatSync(n)?.isFile() && process.platform !== "win32") await tightenPermissions(n, f ?? n, 384, `- Config file is group/world readable (${f ?? n}). Recommend chmod 600.`, `config permissions (${f ?? n})`);
if (v) {
if (p) l.set(c, "OAuth dir");
else if (!safeStatSync(c)?.isDirectory()) i.push(`- OAuth dir not present (${d}). Skipping create because no WhatsApp/pairing channel config is active.`);
for (const [e, n] of l) {
const r = shortenHomePath(e);
if (!safeStatSync(e)?.isDirectory()) {
if (n !== "OAuth dir") continue;
i.push(`- ${n} missing (${r}).`);
if (await t.confirmRuntimeRepair({
message: `Create ${n} at ${r}?`,
initialValue: true
})) {
const t = ensureDir(e);
if (t.ok) a.push(`- Created ${n}: ${r}`);
else i.push(`- Failed to create ${r}: ${t.error}`);
}
continue;
}
await repairWritableDirectory(e, r, n);
}
}
const y = listOrphanAgentDirs(e, s);
if (y.length > 0) {
const t = y.slice(0, 3).map(({ dirName: e, agentId: t }) => e === t ? t : `${e} (id ${t})`);
const n = y.length - t.length;
const r = readAgentRosterProperty(e)?.kind === "list" ? "agents.list" : "agents.entries";
i.push([
`- Found ${countLabel(y.length, "agent directory", "agent directories")} on disk without a matching ${r} entry.`,
" These agents can still have sessions/auth state on disk, but config-driven routing, identity, and model selection will ignore them.",
` Examples: ${t.join(", ")}${n > 0 ? `, and ${n} more` : ""}`,
` Restore the missing ${r} entries or remove stale dirs after confirming they are no longer needed: ${shortenHomePath(path.join(s, "agents"))}`
].join("\n"));
}
if (v) i.push(...collectRetainedUnconfiguredAgentDatabaseWarnings({
cfg: e,
env: o
}));
const b = resolveSessionStoreCompatibilityAgentId(e);
const x = readDeferredPluginMigrations({ env: o });
const S = createRetainedAgentDatabaseMatcher(o, () => resolveConfiguredAgentDatabaseTargets(e, { env: o }));
const C = resolveSessionStoreTargets(e, { allAgents: true }, { env: o }).toSorted((e, t) => e.agentId === b ? -1 : t.agentId === b ? 1 : 0);
const inspectAgentSessionIntegrity = async (n, r) => {
const { agentId: c, storePath: l } = n;
const u = path.resolve(l);
const d = resolveSqliteTargetFromSessionStorePath(u, {
agentId: c,
defaultAgentId: b,
env: o
}).path;
if (S(d, c)) return;
const f = r && safeStatSync(u)?.isFile() && !preserveDeferredPluginSessionSource({
cfg: e,
env: o,
target: n,
pending: x
}) ? loadLegacySessionStore(u) : {};
const p = Object.entries(f).filter((e) => e[1] != null && typeof e[1] === "object");
const m = new Set(p.map(([e]) => e));
const h = /* @__PURE__ */ new Set();
const isSessionKeyOccupied = (e) => h.has(e) || m.has(e);
const g = resolveCanonicalMainSessionKey({
agentId: c,
mainKey: e.session?.mainKey,
sessionScope: e.session?.scope
});
const _ = createPluginSessionStateDoctorScanner({
agentId: c,
cfg: e,
env: o
});
const v = createPluginSessionStateDoctorScanner({
agentId: c,
cfg: e,
env: o
});
let y;
const inspectMergedEntry = (e, t) => {
if (e === g) y = t;
};
const C = scanDoctorSessionEntriesStrict({
agentId: c,
storePath: d
}, ({ entry: e, sessionKey: t }) => {
h.add(t);
_.scanEntry(t, e);
inspectMergedEntry(t, e);
});
for (const [e, t] of p) {
if (h.has(e)) continue;
v.scanEntry(e, t);
inspectMergedEntry(e, t);
}
const w = resolveSessionFilePathOptions({
agentId: c,
storePath: l
});
if (C > 0 || p.length > 0) {
await runPluginSessionStateDoctorRepairs({
scan: await _.result(),
store: {
kind: "sqlite",
agentId: c,
path: d
},
prompter: t,
warnings: i,
changes: a
});
await runPluginSessionStateDoctorRepairs({
scan: await v.result(),
store: {
kind: "legacy",
path: u
},
prompter: t,
warnings: i,
changes: a
});
if (h.has(g)) y = loadExactSessionEntryReadOnly({
agentId: c,
sessionKey: g,
storePath: d
})?.entry;
if (!await repairHeartbeatPoisonedMainSession({
mainKey: g,
mainEntry: y,
isSessionKeyOccupied,
store: h.has(g) ? {
kind: "sqlite",
agentId: c,
path: d
} : {
kind: "legacy",
path: u
},
stateDir: s,
sessionPathOpts: w,
prompter: t,
warnings: i,
changes: a
}) && y?.sessionId && !h.has(g)) {
const e = resolveSessionFilePathCore(y.sessionId, y, w);
if (!safeStatSync(e)?.isFile()) i.push(`- Main session transcript missing (${shortenHomePath(e)}). History will appear to reset.`);
else {
const t = countJsonlLines(e);
if (t <= 1) i.push(`- Main session transcript has only ${t} line. Session history may not be appending.`);
}
}
}
};
const w = /* @__PURE__ */ new Set();
for (const e of C) {
if (S(e.storePath, e.agentId) || readAgentDatabaseAdmissionRefusal(e.agentId, { env: o })) continue;
const t = path.resolve(e.storePath);
await inspectAgentSessionIntegrity(e, !t.endsWith(".sqlite") && !w.has(t));
w.add(t);
}
for (const t of await describeHeartbeatSessionTargetIssues(e)) i.push(t);
if (i.length > 0) note(i.join("\n"), "State integrity");
if (a.length > 0) note(a.join("\n"), "Doctor changes");
}
//#endregion
export { detectStateIntegrityHealthIssues, noteStateIntegrity, stateIntegrityIssueToHealthFinding, stateIntegrityIssueToRepairEffect };