openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,596 lines • 67.8 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { o as measureGatewayBootstrapStep } from "./startup-trace-DWZsuODq.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { o as copyConfigResolutionFactsThroughRewrite } from "./resolution-facts-xaIKuREs.mjs";
import { a as writeConfigMachineState } from "./config-machine-state-write-DanSUxEP.mjs";
import { t as captureRuntimeConfig } from "./runtime-source-projection-DTwMWCo9.mjs";
import { b as recordUpdateDoctorDeferredInspectionChecks } from "./update-doctor-result-DwaI51On.mjs";
import { t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs";
import { i as resolveCommandProcessSignal } from "./exec-spawn-DMKoejF-.mjs";
import { d as isUpdateDoctorInspectionReportMode, h as shouldDeferConfiguredPluginInstallRepair, l as isLegacyParentWritableUpdateDoctorPass } from "./update-phase-YdZvaQsy.mjs";
import { c as throwIfDoctorStateMigrationRefused, t as DoctorStateMigrationRefusalError } from "./state-migrations.messages-CNB52OxC.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { t as emitDoctorNotes } from "./emit-notes-llcc2fq-.mjs";
import { t as scrubDoctorErrorMessage } from "./doctor-error-message-BWgd1c6H.mjs";
import { i as resolveDoctorWorkspaceDir, n as noteDoctorRepairResult, r as resolveDoctorMode, t as isUpdateDoctorRun } from "./doctor-health-contribution-utils-vPLdl3Wb.mjs";
import { a as recordDoctorHealthWarnings, i as legacyOwnedRepair, n as createDoctorHealthContribution, o as renderStructuredHealthFindings, s as reportDoctorHealthFinding } from "./doctor-health-contribution-t31v9kPi.mjs";
import { i as runFinalConfigValidationHealth } from "./doctor-config-validation-findings-DUD4Pgv3.mjs";
import { f as withDoctorProgress } from "./doctor-health-startup-KiSUu3WC.mjs";
import { l as shouldManageGatewayService } from "./doctor-service-repair-policy-DAuL0W8-.mjs";
import { t as hasActiveGatewayExecCredential } from "./doctor-gateway-exec-credential-n80b7QiI.mjs";
import { t as resolveDoctorWorkspaceSuggestionScopes } from "./doctor-workspace-suggestion-scopes-DDUxMVpQ.mjs";
import { t as normalizeHealthCheck } from "./health-check-adapter-BIGrWaNz.mjs";
import { n as resolveDoctorUpdateBudget, t as admitDoctorUpdateInspection } from "./doctor-update-budget-ckRvPmaG.mjs";
import { n as noteBackupDoctorHint } from "./backup-health-CqDT5lI1.mjs";
import { n as runCoreHealthFindingNote, r as runStructuredHealthRepairs, t as runCoreContributionHealth } from "./doctor-health-contribution-core-CyuhnVOS.mjs";
import { i as runWriteConfigHealth, n as runInitialConfigWriteHealth, t as collectWriteConfigHealthFindings } from "./doctor-health-contribution-runners.config-DkeKQBD_.mjs";
import { a as runDevicePairingHealth, c as runGitHubProjectHealth, d as runSecurityHealth, f as runStartupChannelMaintenanceHealth, i as runCommandOwnerHealth, l as runHostDesktopHealth, m as runWhatsappResponsivenessHealth, n as runBundleLspEnvHealth, o as runGatewayDaemonHealth, p as runWebFetchProxyHealth, r as runClaudeCliHealth, s as runGatewayServicesHealth, t as runBrowserHealth, u as runOpenAIOAuthTlsHealth } from "./doctor-health-contribution-runners.gateway-BP3_nYLj.mjs";
import { randomUUID } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
//#region src/flows/doctor-auth-health.ts
async function runAuthProfileMigration(e) {
e.authProfileHealthReady = false;
const t = e.configResult.stateMigrationStepReceipts?.find((e) => e.id === "shared-auth-store");
if (t?.outcome === "skipped" && t.warnings.length > 0) return;
const { repairAuthProfileMigration: n } = await import("./auth-profile-repair-B0I6-wjp.mjs");
const { maybeRepairLegacyOAuthProfileIds: r } = await import("./doctor-auth-legacy-oauth-BPM9w4vQ.mjs");
const { maybeMigrateLegacyPluginModelCatalogs: i } = await import("./doctor-plugin-model-catalog-BUnglN-L.mjs");
const { buildGatewayConnectionDetails: a } = await import("./call-CT5jlfNe.mjs");
const { note: o } = await import("./terminal-core/note.js");
if (e.configResult.openAICodexAuthProfileIdMap === void 0) {
const t = await n({
cfg: e.cfg,
env: e.env,
prompter: e.prompter
});
emitDoctorNotes({
note: o,
changeNotes: t.storeChanges,
warningNotes: []
});
recordDoctorHealthWarnings(e, [], t.warnings);
renderStructuredHealthFindings(e, t.findings);
e.cfg = t.config;
e.configResult.openAICodexAuthProfileIdMap = t.profileIdMap;
if (t.changes.length > 0) e.configResult.pendingChangePanels = [...e.configResult.pendingChangePanels ?? [], t.changes.join("\n")];
}
const migrationContext = () => ({
cfg: e.cfg,
...e.env ? { env: e.env } : {},
prompter: e.prompter,
runtime: e.runtime,
reportFindings: (t, n) => {
recordDoctorHealthWarnings(e, n ? [] : t, n);
renderStructuredHealthFindings(e, t);
}
});
await i(migrationContext());
const s = e.cfg.agents?.defaults?.models;
const c = await r(e.cfg, e.prompter);
recordDoctorHealthWarnings(e, c.findings);
renderStructuredHealthFindings(e, c.findings);
e.cfg = c.config;
if (c.retiredProfileCleanupPlans.length > 0) e.configResult.retiredAuthProfileCleanupPlans = [...e.configResult.retiredAuthProfileCleanupPlans ?? [], ...c.retiredProfileCleanupPlans];
if (!isDeepStrictEqual(s, e.cfg.agents?.defaults?.models)) e.configResult.explicitSetPaths = [...e.configResult.explicitSetPaths ?? [], [
"agents",
"defaults",
"models"
]];
const { maybeMigrateModelCatalogCredentials: l } = await import("./doctor-model-catalog-credentials-BtazVeXG.mjs");
await l(migrationContext());
let u = true;
if (e.configResult.retiredAuthProfileCleanupPlans?.length || e.configResult.openAICodexAuthProfileIdMap?.size) {
const { runRetiredAuthProfileCleanup: t, runWriteConfigHealth: n } = await import("./doctor-health-contribution-runners.config-Cc5LqN_w.mjs");
u = await n(e, { runPostWriteRepairs: false }) && !e.configWriteRefusal && isDeepStrictEqual(e.cfg, e.cfgForPersistence);
if (u) await t(e);
}
e.authProfileHealthReady = u;
e.gatewayDetails = a({ config: e.cfg });
if (e.gatewayDetails.remoteFallbackNote) {
const t = [{
checkId: "core/doctor/gateway-remote-config",
severity: "warning",
category: "fix-now",
message: "Gateway remote mode is configured without a remote Gateway URL; Doctor fell back to the local address.",
fixHint: "Set gateway.remote.url to your remote Gateway address, or set gateway.mode=local if this host owns the Gateway. Run openclaw gateway status after correcting the configuration.",
docsUrl: "https://docs.openclaw.ai/gateway/remote"
}];
recordDoctorHealthWarnings(e, [], [e.gatewayDetails.remoteFallbackNote]);
renderStructuredHealthFindings(e, t);
}
}
async function runAuthProfileDiagnostics(e) {
const { inspectAuthProfileHealth: t, collectCopilotAmbientTokenFindings: n, collectLegacyCodexProviderOverrideFindings: r, collectSharedAuthStoreFindings: i } = await import("./doctor-auth-CRXNZkVG.mjs");
if (e.authProfileHealthReady !== false) renderStructuredHealthFindings(e, await t({
cfg: e.cfg,
prompter: e.prompter,
allowKeychainPrompt: e.options.nonInteractive !== true && process.stdin.isTTY
}));
renderStructuredHealthFindings(e, r(e.cfg));
renderStructuredHealthFindings(e, await i(e.env));
renderStructuredHealthFindings(e, n(e.cfg, e.env));
}
//#endregion
//#region src/flows/doctor-health-contribution-runners.workspace.ts
async function runMemorySearchHealthContribution(e) {
const t = captureRuntimeConfig(e.cfg);
const { maybeRepairMemoryRecallHealth: n, noteMemoryRecallHealth: r } = await import("./doctor-memory-recall-Diy8kIi0.mjs");
const { noteMemorySearchHealth: i } = await import("./doctor-memory-search-DhCMmsDI.mjs");
if (e.prompter.shouldRepair) await n({
cfg: t,
prompter: e.prompter
});
await i(t, {
env: e.env,
gatewayMemoryProbe: e.gatewayMemoryProbe ?? {
checked: false,
ready: false,
skipped: false
}
});
await r(t, e.options.deep === true);
}
//#endregion
//#region src/flows/doctor-health-contributions-final.ts
async function collectWorkspaceStatusPluginVersionReadiness(e) {
if (e.cfg.gateway?.mode === "remote" || !await shouldManageGatewayService()) return;
try {
const { gatherDaemonStatus: t } = await import("./status.gather-zCT6rmfM.mjs");
const n = await t({
rpc: {
timeout: e.options?.nonInteractive === true ? "3000" : "10000",
json: true
},
probe: true,
requireRpc: false,
deep: e.options?.deep === true,
allowExecSecretRefs: e.options?.allowExec === true,
pluginVersionTarget: "restart"
});
if (n.pluginVersionRestartReadiness?.status === "resolved") {
const { resolvePluginVersionDriftTargets: e } = await import("./plugin-version-drift-wgV8t-WY.mjs");
return {
...n.pluginVersionRestartReadiness,
report: await e(n.pluginVersionRestartReadiness.report)
};
}
return n.pluginVersionRestartReadiness;
} catch {
return;
}
}
const CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID = "core/doctor/channel-package-state-capabilities";
function resolveFinalDoctorHealthContributions(e) {
return [
createDoctorHealthContribution("doctor:gateway-services", "Gateway services", {
healthCheckIds: ["core/doctor/gateway-services/extra", "core/doctor/gateway-services/platform-notes"],
run: runGatewayServicesHealth
}),
createDoctorHealthContribution("doctor:host-desktop", "Host desktop", {
healthChecks: {
description: "Gateway-host desktop enablement, reachability, and RFB security state.",
defaultEnabled: false,
async detect(e) {
const { collectHostDesktopHealthFindings: t } = await import("./doctor-host-desktop-_uSIVIRm.mjs");
return t(e.cfg);
}
},
run: runHostDesktopHealth
}),
createDoctorHealthContribution("doctor:default-account-routing", "Default account routing", {
updateWork: {
kind: "inspection",
scope: "run"
},
healthChecks: {
description: "Multi-account channels have explicit default routing or complete bindings.",
defaultEnabled: false,
async detect(e) {
const { collectMissingDefaultAccountBindingWarnings: t, collectMissingExplicitDefaultAccountWarnings: n } = await import("./default-account-warnings-Bc6XfUvW.mjs");
return [...t(e.cfg), ...n(e.cfg)].map((e) => ({
checkId: "core/doctor/default-account-routing",
severity: "warning",
message: e.replace(/^- /, "").trim()
}));
}
}
}),
createDoctorHealthContribution("doctor:channel-package-state-capabilities", "Channel package-state capabilities", { healthChecks: {
id: CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID,
description: "Declared channel package-state checker modules must load.",
defaultEnabled: true,
async detect(e) {
if (shouldDeferConfiguredPluginInstallRepair(e.env ?? process.env)) return [];
const { collectBundledChannelPackageStateLoadFailures: t } = await import("./package-state-probes-JCmUWr84.mjs");
return t().map((e) => ({
checkId: CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID,
severity: "warning",
message: `Plugin ${e.pluginId} declared ${e.metadataKey}, but its checker failed to load: ${e.detail}`,
target: e.pluginId,
requirement: "declared-channel-package-state-capability-loadable",
fixHint: `Rebuild or reinstall plugin ${e.pluginId}, then rerun \`openclaw doctor\`.`
}));
}
} }),
createDoctorHealthContribution("doctor:startup-channel-maintenance", "Startup channel maintenance", {
healthChecks: [{
id: "core/doctor/channel-plugin-blockers",
description: "Configured channels must have loadable backing channel plugins.",
defaultEnabled: false,
async detect(e) {
const { channelPluginBlockerHitToHealthFinding: t, scanConfiguredChannelPluginBlockers: n } = await import("./channel-plugin-blockers-Bj32LIib.mjs");
return n(e.cfg, process.env).map(t);
}
}, {
id: "core/doctor/channel-preview-warnings",
description: "Channel doctor preview warnings are captured as structured findings.",
defaultEnabled: false,
async detect(e) {
const { collectChannelPreviewWarningHealthFindings: t } = await import("./doctor-startup-channel-maintenance-PdRY7-Oo.mjs");
return t({
cfg: e.cfg,
allowExec: e.allowExecSecretRefs === true
});
}
}],
run: runStartupChannelMaintenanceHealth
}),
createDoctorHealthContribution("doctor:security", "Security", {
updateWork: {
kind: "inspection",
scope: "agent"
},
healthCheckIds: ["core/doctor/security"],
run: runSecurityHealth
}),
createDoctorHealthContribution("doctor:web-fetch-proxy", "Web fetch proxy", {
updateWork: {
kind: "inspection",
scope: "run"
},
run: runWebFetchProxyHealth
}),
createDoctorHealthContribution("doctor:bundle-lsp-env", "Bundle LSP environment", {
updateWork: {
kind: "inspection",
scope: "agent"
},
run: runBundleLspEnvHealth
}),
createDoctorHealthContribution("doctor:github-projects", "GitHub projects", {
updateWork: { kind: "standalone" },
run: runGitHubProjectHealth
}),
createDoctorHealthContribution("doctor:browser", "Browser", {
healthCheckIds: ["core/doctor/browser"],
run: runBrowserHealth
}),
createDoctorHealthContribution("doctor:oauth-tls", "OAuth TLS", {
updateWork: {
kind: "inspection",
scope: "run"
},
healthCheckIds: ["core/doctor/oauth-tls"],
run: runOpenAIOAuthTlsHealth
}),
createDoctorHealthContribution("doctor:hooks-model", "Hooks model", {
updateWork: {
kind: "inspection",
scope: "run"
},
healthCheckIds: ["core/doctor/hooks-model"],
async run(e) {
const { collectHooksModelIssues: t } = await import("./doctor-hooks-model-o2TDmMwH.mjs");
const n = await t(e.cfg);
if (n.length === 0) return;
const { note: r } = await import("./terminal-core/note.js");
r(n.map(({ kind: e, model: t }) => e === "unresolved" ? `- hooks.gmail.model "${t}" could not be resolved` : e === "not-allowed" ? `- hooks.gmail.model "${t}" not allowed by agents.defaults.modelPolicy.allow (will use primary instead)` : `- hooks.gmail.model "${t}" not in the model catalog (may fail at runtime)`).join("\n"), "Hooks");
}
}),
createDoctorHealthContribution("doctor:legacy-output-cap", "Saved model output caps", {
updateWork: {
kind: "inspection",
scope: "run"
},
healthCheckIds: ["core/doctor/legacy-output-cap"],
run: (e) => runCoreHealthFindingNote(e, "core/doctor/legacy-output-cap", { infoNoteTitle: "Model output caps" })
}),
...[
[
"model-references",
"Model references",
"agent"
],
[
"acp-agent-model",
"ACP agent model",
"agent"
],
[
"provider-catalog-projection",
"Provider catalog projection",
"run"
],
[
"local-audio-acceleration",
"Local audio acceleration",
"run"
],
[
"runtime-tool-schemas",
"Runtime tool schemas",
"agent"
],
[
"skill-workshop-tool-policy",
"Skill Workshop tool policy",
"agent"
]
].map(([e, t, n]) => createDoctorHealthContribution(`doctor:${e}`, t, {
updateWork: {
kind: "inspection",
scope: n
},
healthCheckIds: [`core/doctor/${e}`],
run: (t) => runCoreHealthFindingNote(t, `core/doctor/${e}`)
})),
createDoctorHealthContribution("doctor:systemd-linger", "systemd linger", {
healthChecks: {
description: "Disabled systemd user lingering is reported as a finding.",
defaultEnabled: false,
detect: e.detectSystemdLingerFindings
},
run: e.runSystemdLingerHealth
}),
createDoctorHealthContribution("doctor:workspace-status", "Workspace status", {
updateWork: {
kind: "inspection",
scope: "agent"
},
healthChecks: {
description: "Workspace plugin/status diagnostics are exposed as findings.",
defaultEnabled: false,
async detect(e) {
const { collectWorkspaceStatusHealthFindings: t } = await import("./doctor-workspace-status-DjkzxzNA.mjs");
const n = await collectWorkspaceStatusPluginVersionReadiness({
cfg: e.cfg,
options: {
nonInteractive: true,
allowExec: e.allowExecSecretRefs === true
}
});
const r = e.runWithPluginMetadataSnapshot;
return t(e.cfg, {
pluginVersionReadiness: n,
...r ? { runWithPluginMetadataSnapshot: r } : {}
});
}
},
async run(e) {
const t = await collectWorkspaceStatusPluginVersionReadiness({
cfg: e.cfg,
options: e.options
});
const { collectWorkspaceStatusHealthFindings: n } = await import("./doctor-workspace-status-DjkzxzNA.mjs");
const r = n(e.cfg, {
pluginVersionReadiness: t,
...e.runWithPluginMetadataSnapshot ? { runWithPluginMetadataSnapshot: e.runWithPluginMetadataSnapshot } : {}
});
recordDoctorHealthWarnings(e, r);
renderStructuredHealthFindings(e, r);
}
}),
createDoctorHealthContribution("doctor:workspace-alias", "Workspace alias", {
healthChecks: {
description: "Persisted workspace aliases must resolve to the resolved target that owns their stored state.",
defaultEnabled: true,
async detect(e) {
const { collectRepointedWorkspaceAliasFindings: t } = await import("./doctor-workspace-alias-D2H8FfYG.mjs");
return t(e.cfg);
}
},
async run(e) {
const { collectRepointedWorkspaceAliasFindings: t } = await import("./doctor-workspace-alias-D2H8FfYG.mjs");
const n = await t(e.cfg);
renderStructuredHealthFindings(e, n);
}
}),
createDoctorHealthContribution("doctor:skills", "Skills", {
updateWork: {
kind: "inspection",
scope: "agent",
repairs: true
},
healthCheckIds: ["core/doctor/skills-readiness"],
async run(e) {
const { maybeRepairSkillReadiness: t } = await import("./doctor-skills-BRc6Rm8V.mjs");
e.cfg = await t({
cfg: e.cfg,
prompter: e.prompter,
...e.runWithPluginMetadataSnapshot ? { runWithPluginMetadataSnapshot: e.runWithPluginMetadataSnapshot } : {}
});
}
}),
createDoctorHealthContribution("doctor:bootstrap-size", "Bootstrap size", {
updateWork: { kind: "standalone" },
healthCheckIds: ["core/doctor/bootstrap-size"],
async run(e) {
const { noteBootstrapFileSize: t } = await import("./doctor-bootstrap-size-CIdxmtHh.mjs");
await t(e.cfg);
}
}),
createDoctorHealthContribution("doctor:heartbeat-cadence-migration", "Heartbeat cadence migration", {
healthChecks: {
description: "Heartbeat cadence config must be materialized in cron monitor rows.",
defaultEnabled: true,
async detect(e) {
const { collectHeartbeatCadenceMigrationFindings: t } = await import("./doctor-heartbeat-cadence-migration-DjSAsyvP.mjs");
return t(e.cfg, e.env);
}
},
async run(e) {
const { maybeMigrateHeartbeatCadenceToCron: t } = await import("./doctor-heartbeat-retirement-z8KwWn-S.mjs");
await t({
cfg: e.configResult.heartbeatMigrationSource ?? e.cfg,
shouldRepair: e.prompter.shouldRepair,
env: e.env
});
}
}),
createDoctorHealthContribution("doctor:heartbeat-scratch-migration", "Heartbeat scratch migration", {
healthChecks: {
description: "Workspace HEARTBEAT.md files must migrate into cron-owned scratch.",
defaultEnabled: true,
async detect(e) {
const { collectHeartbeatScratchMigrationFindings: t } = await import("./doctor-heartbeat-scratch-migration-C0ieo2Fx.mjs");
return t(e.cfg, e.env);
}
},
async run(e) {
const { maybeMigrateHeartbeatCadenceToCron: t } = await import("./doctor-heartbeat-retirement-z8KwWn-S.mjs");
await t({
cfg: e.configResult.heartbeatMigrationSource ?? e.cfg,
shouldRepair: e.prompter.shouldRepair,
env: e.env
});
}
}),
createDoctorHealthContribution("doctor:tools-md-migration", "TOOLS.md migration", {
healthChecks: {
description: "Workspace TOOLS.md notes must migrate into the AGENTS.md Tools section.",
defaultEnabled: true,
async detect(e) {
const { collectToolsMdMigrationFindings: t } = await import("./doctor-tools-md-migration-CiJXPoXG.mjs");
return t(e.cfg);
}
},
async run(e) {
const { maybeMigrateToolsMd: t } = await import("./doctor-tools-md-migration-CiJXPoXG.mjs");
await t({
cfg: e.cfg,
shouldRepair: e.prompter.shouldRepair,
env: e.env
});
}
}),
createDoctorHealthContribution("doctor:heartbeat-task-cron-migration", "Heartbeat task cron migration", {
healthChecks: {
description: "Heartbeat scratch task blocks must migrate into automations.",
defaultEnabled: true,
async detect(e) {
const { collectHeartbeatTaskMigrationFindings: t } = await import("./doctor-heartbeat-task-migration-Dws1aLOT.mjs");
return t(e.cfg, e.env);
}
},
async run(e) {
const { maybeMigrateHeartbeatTasksToCron: t } = await import("./doctor-heartbeat-task-migration-Dws1aLOT.mjs");
await t({
cfg: e.cfg,
shouldRepair: e.prompter.shouldRepair,
env: e.env
});
}
}),
createDoctorHealthContribution("doctor:shell-completion", "Shell completion", {
healthCheckIds: ["core/doctor/shell-completion"],
run: e.runShellCompletionHealth
}),
createDoctorHealthContribution("doctor:gateway-health", "Gateway health", {
healthCheckIds: ["core/doctor/gateway-health"],
run: e.runGatewayHealthChecks
}),
createDoctorHealthContribution("doctor:whatsapp-responsiveness", "WhatsApp responsiveness", {
updateWork: {
kind: "inspection",
scope: "run"
},
healthChecks: {
description: "Gateway pressure and local TUI observations when WhatsApp is enabled.",
defaultEnabled: false,
async detect(e) {
const { collectWhatsappResponsivenessHealthFindings: t } = await import("./doctor-whatsapp-responsiveness-DR0f1GZf.mjs");
const { bindAgentToolGatewayRequest: n } = await import("./in-process-gateway-uUYBiTqp.mjs");
const r = n({ hostedOnly: true });
let i;
if (!(await hasActiveGatewayExecCredential({ cfg: e.cfg }) && e.allowExecSecretRefs !== true)) i = await r({
method: "status",
params: { includeChannelSummary: false },
timeoutMs: 3e3,
config: e.cfg,
deviceIdentity: null
}).catch(() => void 0);
return t({
cfg: e.cfg,
status: i
});
}
},
run: runWhatsappResponsivenessHealth
}),
createDoctorHealthContribution("doctor:memory-search", "Memory search", {
updateWork: {
kind: "inspection",
scope: "agent",
repairs: true
},
healthChecks: {
description: "Memory search provider and backend readiness are captured as findings.",
defaultEnabled: false,
async detect(e) {
const { collectMemorySearchHealthFindings: t } = await import("./doctor-memory-search-DhCMmsDI.mjs");
return t(e);
}
},
run: runMemorySearchHealthContribution
}),
createDoctorHealthContribution("doctor:device-pairing", "Device pairing", {
healthChecks: {
description: "Device pairing requests and stale device-auth records are findings.",
defaultEnabled: false,
async detect(e) {
const { collectDevicePairingHealthFindings: t } = await import("./doctor-device-pairing-HraX7elt.mjs");
return t({
cfg: e.cfg,
healthOk: false,
env: e.env
});
}
},
run: runDevicePairingHealth
}),
createDoctorHealthContribution("doctor:gateway-daemon", "Gateway daemon", {
healthCheckIds: ["core/doctor/gateway-daemon"],
run: runGatewayDaemonHealth
}),
createDoctorHealthContribution("doctor:write-config", "Write config", {
updateWork: { kind: "finalize" },
healthChecks: {
description: "Config write blockers are findings before doctor repair writes.",
defaultEnabled: false,
detect: collectWriteConfigHealthFindings
},
async run(e) {
await runWriteConfigHealth(e);
}
}),
createDoctorHealthContribution("doctor:workspace-suggestions", "Workspace suggestions", {
updateWork: { kind: "standalone" },
healthCheckIds: ["core/doctor/workspace-suggestions"],
async run(e) {
if (e.options.workspaceSuggestions === false) return;
const { collectWorkspaceSuggestionNotes: t } = await import("./doctor-workspace-suggestions-CjWcstdm.mjs");
const { note: n } = await import("./terminal-core/note.js");
for (const { agentId: r, workspaceDir: i, labelAgent: a } of resolveDoctorWorkspaceSuggestionScopes(e.cfg)) {
const e = a ? `Agent "${r}": ` : "";
for await (const r of t(i)) n(`${e}${r}`, "Workspace");
}
}
}),
createDoctorHealthContribution("doctor:final-config-validation", "Final config validation", {
updateWork: { kind: "finalize" },
healthCheckIds: ["core/doctor/final-config-validation"],
run: runFinalConfigValidationHealth
})
];
}
//#endregion
//#region src/flows/doctor-health-contribution-runners.state.ts
async function runLegacyPluginManifestHealth(e) {
const { maybeRepairLegacyPluginManifestContracts: t } = await import("./doctor-plugin-manifests-CEEBuTlv.mjs");
if (await t({
config: e.cfg,
env: process.env,
runtime: e.runtime,
prompter: e.prompter
})) e.invalidatePluginMetadataSnapshot?.();
}
async function runAgentMemorySchemaHealth(e) {
const { noteDoctorAgentMemorySchemaHealth: t } = await import("./doctor-agent-memory-schema-yqtq5Rkl.mjs");
await t({
env: e.env ?? process.env,
shouldRepair: e.prompter.shouldRepair
});
}
async function runCodexSessionRouteHealth(e) {
const { maybeRepairCodexSessionRoutes: t } = await import("./codex-route-warnings-DqW_LD3c.mjs");
const n = await t({
cfg: e.cfg,
modelReplacements: e.options.modelReplacements,
...e.configResult.retiredModelRefConfig ? { retiredModelRefConfig: e.configResult.retiredModelRefConfig } : {},
env: e.env ?? process.env,
...!e.prompter.shouldRepair && e.configResult.providerRenames?.length ? { providerRenames: e.configResult.providerRenames } : {},
shouldRepair: e.prompter.shouldRepair,
...e.configResult.blockedCodexModelIdentities?.length ? { blockedModelIdentities: new Set(e.configResult.blockedCodexModelIdentities) } : {},
...e.configResult.openAICodexAuthProfileIdMap?.size ? {
authProfileIdMap: e.configResult.openAICodexAuthProfileIdMap,
...!e.prompter.shouldRepair ? { authProfileOnly: true } : {}
} : {}
});
noteDoctorRepairResult(n);
}
async function runSessionTranscriptsHealth(e) {
const { noteSessionTranscriptHealth: t } = await import("./doctor-session-transcripts-zvCkrP_M.mjs");
await t({
cfg: e.cfg,
env: e.env ?? process.env,
shouldRepair: e.prompter.shouldRepair,
integrityCheck: e.options.fullIntegrityCheck ? "full" : "quick",
onWarnings: (t) => recordDoctorHealthWarnings(e, [], t),
onFindings: (t) => renderStructuredHealthFindings(e, t),
...e.configResult.postSessionPluginMigration ? { postSessionPluginMigration: e.configResult.postSessionPluginMigration } : {},
...e.configResult.postSessionPluginMigrationPlanBound ? { postSessionPluginMigrationPlanBound: true } : {},
onStepReceipt: (t) => {
e.configResult.stateMigrationStepReceipts ??= [];
e.configResult.stateMigrationStepReceipts.push(t);
}
});
}
async function runLegacyCronHealth(e) {
const { maybeRepairLegacyCronStore: t, noteLegacyWhatsAppCrontabHealthCheck: n } = await import("./cron-DcmWmEzN.mjs");
await measureGatewayBootstrapStep("doctor.legacy-cron.crontab", () => n());
await measureGatewayBootstrapStep("doctor.legacy-cron.store", () => t({
cfg: e.cfg,
options: e.options,
prompter: e.prompter
}));
const { maybeRepairCronInferenceBindings: r } = await import("./inference-binding-migration-CLF83ThS.mjs");
const i = await measureGatewayBootstrapStep("doctor.legacy-cron.inference", () => r({
cfg: e.cfg,
env: e.env,
shouldRepair: e.prompter.shouldRepair
}));
noteDoctorRepairResult(i);
recordDoctorHealthWarnings(e, [], i.warnings);
const { noteScheduledContextReport: a } = await import("./execution-context-check-_89XcF24.mjs");
await measureGatewayBootstrapStep("doctor.legacy-cron.execution-context", () => a({
cfg: e.cfg,
env: e.env
}));
}
//#endregion
//#region src/flows/doctor-native-status-check.ts
const CHECK_ID = "core/doctor/native-status";
const nativeStatusCheck = {
id: CHECK_ID,
kind: "core",
source: "doctor",
description: "Native filesystem and process helpers are available for this runtime.",
async detect() {
const [{ getFsSafeNativeStatus: e }, { getProcSafeNativeStatus: t }] = await Promise.all([import("@openclaw/fs-safe"), import("@openclaw/proc-safe")]);
return (await Promise.all([e({ probe: true }), t({ probe: true })])).map((e, t) => {
const n = t === 0 ? "fs-safe" : "proc-safe";
const r = n === "proc-safe" && process.platform === "linux" && e.reason === "load-failed";
let i = "";
if (r) try {
const e = process.report.getReport();
const t = isRecord(e) ? e.header : void 0;
if (isRecord(t) && typeof t.glibcVersionRuntime === "string") i = ` (glibc ${t.glibcVersionRuntime})`;
} catch {}
return {
checkId: CHECK_ID,
severity: e.loaded || e.mode === "off" ? "info" : "warning",
message: `${n}: ${e.reason}${i}`,
fixHint: r ? `${e.guidance ? `${e.guidance} ` : ""}Linux update ancestry can use /proc/<pid>/stat without the native helper. If ancestry remains unavailable, restore readable /proc or install a compatible process helper; after the recorded update driver exits, run \`openclaw update repair\`.` : e.guidance
};
});
}
};
const appContainerSpawnCheck = {
id: "core/doctor/appcontainer-spawn",
kind: "core",
source: "doctor",
description: "The Windows runtime can create child pipes inside an AppContainer.",
async detect() {
const { assertAppContainerSpawnSupported: e, AppContainerSpawnUnsupportedError: t } = await import("./windows-appcontainer-spawn-l6VLCJGl.mjs");
try {
e();
return [];
} catch (e) {
if (!(e instanceof t)) throw e;
return [{
checkId: "core/doctor/appcontainer-spawn",
severity: "error",
errorCode: e.code,
message: e.message
}];
}
}
};
//#endregion
//#region src/flows/doctor-health-contributions-initial.ts
function coreHealthRunner(e) {
return async (t) => {
const { runCoreContributionHealth: n } = await import("./doctor-health-contribution-core-Bbu5S3nn.mjs");
await n(t, [e]);
};
}
const runStaleRuntimeBuildHealth = coreHealthRunner("core/doctor/stale-runtime-build");
const runTelegramGeneralTopicConversationHealth = coreHealthRunner("core/doctor/telegram-general-topic-conversations");
function resolveInitialDoctorHealthContributions(e) {
return [
createDoctorHealthContribution("doctor:write-config-migrations", "Write config migrations", {
required: true,
run: runInitialConfigWriteHealth
}),
createDoctorHealthContribution("doctor:agent-database-admission", "Agent database admission", { healthChecks: {
description: "Agent databases with mismatched ownership are isolated until repaired.",
async detect(e) {
const { evaluateAgentDatabaseAdmissions: t } = await import("./agent-database-admission-D63FKGXN.mjs");
return (e.agentDatabaseRefusals ?? await t(e.cfg, { env: e.env })).map((e) => ({
checkId: "core/doctor/agent-database-admission",
severity: "warning",
target: e.agentId,
requirement: e.code,
message: `Agent ${e.agentId} is degraded. ${e.reason}`,
fixHint: e.repairHint
}));
}
} }),
createDoctorHealthContribution("doctor:native-status", "Native helpers and child pipes", { healthChecks: [appContainerSpawnCheck, nativeStatusCheck] }),
createDoctorHealthContribution("doctor:node-runtime", "Node runtime", {
healthCheckIds: ["core/doctor/node-runtime"],
async run(e) {
const { runCoreHealthFindingNote: t } = await import("./doctor-health-contribution-core-Bbu5S3nn.mjs");
await t(e, "core/doctor/node-runtime");
}
}),
createDoctorHealthContribution("doctor:runtime-capabilities", "Runtime capabilities", {
healthCheckIds: ["core/doctor/runtime-capabilities"],
async run() {
const { collectRuntimeCapabilities: e, formatRuntimeCapabilities: t } = await import("./runtime-capabilities-DEj69bmH.mjs");
note(t(e()), "Runtime capabilities (Doctor process)");
}
}),
createDoctorHealthContribution("doctor:gateway-config", "Gateway config", {
healthCheckIds: ["core/doctor/gateway-config"],
run: e.runGatewayConfigHealth
}),
createDoctorHealthContribution("doctor:database-engine", "Database engines", {
updateWork: {
kind: "inspection",
scope: "agent"
},
healthChecks: {
description: "Selected database engines, physical store health, and recovery guidance.",
async detect(e) {
const { collectDoctorDatabaseEngineHealthFindings: t } = await import("./doctor-database-engine-5j6RDPO2.mjs");
return t(e.cfg, { env: e.env });
}
},
async run(e) {
const { noteDatabaseEngines: t } = await import("./doctor-database-engine-5j6RDPO2.mjs");
recordDoctorHealthWarnings(e, await t(e.cfg, { env: e.env }));
}
}),
createDoctorHealthContribution("doctor:auth-profile-migration", "Auth profile migration", {
updateWork: { kind: "startup" },
run: e.runAuthProfileMigration
}),
createDoctorHealthContribution("doctor:auth-profiles", "Auth profiles", {
updateWork: {
kind: "inspection",
scope: "agent",
repairs: true
},
healthChecks: {
description: "Auth profile cooldown, expiry, missing credential, and legacy override state",
defaultEnabled: false,
async detect(e) {
const { collectAuthProfileHealthFindings: t } = await import("./doctor-auth-CRXNZkVG.mjs");
return t({
cfg: e.cfg,
allowKeychainPrompt: false
});
}
},
run: e.runAuthProfileHealth
}),
createDoctorHealthContribution("doctor:claude-cli", "Claude CLI", {
updateWork: {
kind: "inspection",
scope: "agent"
},
healthCheckIds: ["core/doctor/claude-cli"],
run: runClaudeCliHealth
}),
createDoctorHealthContribution("doctor:gateway-auth", "Gateway auth", {
healthCheckIds: ["core/doctor/gateway-auth"],
run: e.runGatewayAuthHealth
}),
createDoctorHealthContribution("doctor:node-hosting-preconditions", "Node hosting preconditions", { healthChecks: {
description: "Gateway config can authenticate and onboard node and worker hosts.",
async detect(e) {
const { collectNodeHostingPreconditionFindings: t } = await import("./doctor-node-hosting-preconditions-CIJDMvUf.mjs");
const n = await t(e.cfg);
return resolveUpdateRehearsalRoot(e.env ?? process.env) ? n.filter((e) => e.requirement !== "node-onboarding-url") : n;
}
} }),
createDoctorHealthContribution("doctor:command-owner", "Command owner", {
updateWork: {
kind: "inspection",
scope: "run"
},
healthCheckIds: ["core/doctor/command-owner"],
run: runCommandOwnerHealth
}),
createDoctorHealthContribution("doctor:structured-health-repairs", "Plugin health inspection and repair", {
updateWork: {
kind: "inspection",
scope: "agent",
repairs: true
},
run: e.runStructuredHealthRepairs
}),
createDoctorHealthContribution("doctor:legacy-state", "Legacy state", {
healthCheckIds: ["core/doctor/legacy-state", "core/doctor/removed-workspaces-state"],
run: e.runLegacyStateHealth
}),
createDoctorHealthContribution("doctor:session-transcripts", "Session transcripts", {
healthChecks: {
description: "Legacy or branchy session transcript files are represented as findings.",
defaultEnabled: false,
async detect() {
const { detectSessionTranscriptHealthIssues: e, sessionTranscriptIssueToHealthFinding: t } = await import("./doctor-session-transcripts-zvCkrP_M.mjs");
return (await e()).map(t);
},
repair: legacyOwnedRepair(async () => {
const { detectSessionTranscriptHealthIssues: e, sessionTranscriptIssueToRepairEffect: t } = await import("./doctor-session-transcripts-zvCkrP_M.mjs");
return (await e()).map(t);
}, "legacy doctor session transcript contribution owns transcript rewrites")
},
run: runSessionTranscriptsHealth
}),
createDoctorHealthContribution("doctor:agent-memory-schema", "Agent memory schema", runAgentMemorySchemaHealth),
createDoctorHealthContribution("doctor:legacy-plugin-manifests", "Legacy plugin manifests", {
healthChecks: {
description: "Legacy plugin manifest capability keys are reported as findings.",
defaultEnabled: false,
async detect(e) {
const { collectLegacyPluginManifestContractMigrations: t, legacyPluginManifestContractMigrationToHealthFinding: n } = await import("./doctor-plugin-manifests-CEEBuTlv.mjs");
return t({
config: e.cfg,
env: process.env
}).map(n);
}
},
run: runLegacyPluginManifestHealth
}),
createDoctorHealthContribution("doctor:legacy-plugin-dependencies", "Legacy plugin dependencies", {
healthChecks: {
description: "Deprecated shared plugin dependency cleanup check.",
defaultEnabled: false,
async detect() {
return [{
checkId: "core/doctor/legacy-plugin-dependencies",
severity: "info",
message: "Deprecated check: Doctor preserves shared plugin runtime caches and no longer scans them for removal."
}];
}
},
run: async () => {}
}),
createDoctorHealthContribution("doctor:stale-plugin-runtime-symlinks", "Stale plugin runtime symlinks", {
healthChecks: {
description: "Stale plugin-runtime symlinks are represented as findings.",
defaultEnabled: false,
async detect() {
const { collectStalePluginRuntimeSymlinkHealthFindings: e } = await import("./plugin-runtime-symlinks-DtuEVBTr.mjs");
return e();
}
},
run: async () => {}
}),
createDoctorHealthContribution("doctor:release-configured-plugin-installs", "Configured plugin repair", {
healthChecks: {
id: "core/doctor/configured-plugin-installs",
description: "Configured plugin install records and package payloads are repairable.",
defaultEnabled: false,
async detect(e) {
const { detectConfiguredPluginInstallHealthIssues: t, configuredPluginInstallIssueToHealthFinding: n } = await import("./missing-configured-plugin-install-Dl_LMB36.mjs");
return (await t({
cfg: e.cfg,
env: process.env
})).map(n);
},
repair: legacyOwnedRepair(async (e) => {
const { detectConfiguredPluginInstallHealthIssues: t, configuredPluginInstallIssueToRepairEffect: n } = await import("./missing-configured-plugin-install-Dl_LMB36.mjs");
return (await t({
cfg: e.cfg,
env: process.env
})).map(n);
}, "legacy doctor configured plugin install repair owns package mutation")
},
async run(e) {
if (!e.sourceConfigValid || !e.prompter.shouldRepair) return;
const { maybeRunConfiguredPluginInstallReleaseStep: t } = await import("./release-configured-plugin-installs-CaFTGRiX.mjs");
const { VERSION: n } = await import("./version-Cu2zLIq0.mjs");
const r = await t({
cfg: e.cfg,
env: e.env ?? process.env,
touchedVersion: e.configResult.sourceLastTouchedVersion ?? e.cfg.meta?.lastTouchedVersion
});
if (r.pluginInventoryChanged) e.invalidatePluginMetadataSnapshot?.();
if (r.postInstallDoctorResult) e.postInstallDoctorResult = r.postInstallDoctorResult;
noteDoctorRepairResult(r);
if (!r.touchedConfig) return;
const i = isLegacyParentWritableUpdateDoctorPass(e.env ?? process.env) ? e.configResult.sourceLastTouchedVersion?.trim() || e.cfg.meta?.lastTouchedVersion || n : n;
const a = {
...e.cfg,
meta: {
...e.cfg.meta,
lastTouchedVersion: i
}
};
copyConfigResolutionFactsThroughRewrite(e.cfg, a);
e.cfg = a;
writeConfigMachineState("config.lastTouchedAt", (/* @__PURE__ */ new Date()).toISOString());
}
}),
createDoctorHealthContribution("doctor:plugin-registry", "Plugin registry", {
healthChecks: {
description: "Plugin registry migration, stale shadow, and peer-link issues are findings.",
defaultEnabled: false,
async detect(e) {
const { detectPluginRegistryHealthIssues: t, pluginRegistryIssueToHealthFinding: n } = await import("./doctor-plugin-registry-BXnhwqJz.mjs");
return (await t({
config: e.cfg,
env: process.env,
prompter: { shouldRepair: false }
})).map(n);
},
repair: legacyOwnedRepair(async (e) => {
const { detectPluginRegistryHealthIssues: t, pluginRegistryIssueToRepairEffect: n } = await import("./doctor-plugin-registry-BXnhwqJz.mjs");
return (await t({
config: e.cfg,
env: process.env,
prompter: { shouldRepair: false }
})).map(n);
}, "legacy doctor plugin registry contribution owns registry repairs")
},
async run(e) {
const { maybeRepairPluginRegistryState: t } = await import("./doctor-plugin-registry-BXnhwqJz.mjs");
const n = await t({
config: e.cfg,
env: process.env,
prompter: e.prompter
});
e.cfg = n.config;
if (n.pluginInventoryChanged) e.invalidatePluginMetadataSnapshot?.();
}
}),
createDoctorHealthContribution("doctor:legacy-plugin-source-captures", "Legacy plugin captures", {
updateWork: { kind: "startup" },
async run(e) {
const { noteLegacyPluginSourceCaptures: t } = await import("./doctor-plugin-source-captures-Cjz6NZJF.mjs");
await t(e.env ?? process.env, e.prompter.shouldRepair);
}
}),
createDoctorHealthContribution("doctor:retained-update-runtimes", "Updater runtimes", {
updateWork: { kind: "startup" },
async run(e) {
if (e.gatewayMaintenanceActive && e.prompter.shouldRepair) return;
const { prepareRetainedUpdateRuntimeCleanup: t } = await import("./doctor-retained-runtime-pctTetSz.mjs");
await (await t(e.env ?? process.env))(e.prompter.shouldRepair);
}
}),
createDoctorHealthContribution("doctor:update-snapshots", "Retained update database snapshots", {
updateWork: { kind: "standalone" },
healthChecks: {
description: "Retained npm update database snapshots need operator review before removal.",
defaultEnabled: true,
async detect(e) {
const { collectUpdateSnapshotHealthFindings: t } = await import("./doctor-update-snapshots-Basoc8Iw.mjs");
return t(e.env);
}
}
}),
createDoctorHealthContribution("doctor:ui-protocol-freshness", "UI protocol freshness", {
healthCheckIds: ["core/doctor/ui-protocol-freshness"],
run: async () => {}
}),
createDoctorHealthContribution("doctor:stale-runtime-build", "Stale runtime build", {
healthCheckIds: ["core/doctor/stale-runtime-build"],
run: runStaleRuntimeBuildHealth
}),
createDoctorHealthContribution("doctor:disk-space", "Disk space", {
healthChecks: {
description: "Low disk space around the OpenClaw state directory is a finding.",
defaultEnabled: false,
async detect(e) {
const { collectDiskSpaceHealthFindings: t } = await import("./doctor-disk-space-BJqL1oLR.mjs");
return t(e.env);
}
},
async run() {
const { noteDiskSpace: e } = await import("./doctor-disk-space-BJqL1oLR.mjs");
e();
}
}),
createDoctorHealthContribution("doctor:project-clone-shape", "Project clones", {
updateWork: { kind: "standalone" },
healthChecks: {
description: "Partial and shallow registry-owned project clones need manual repair.",
defaultEnabled: false,
async detect(e) {
const { collectProjectCloneShapeHealthFindings: t } = await import("./doctor-project-clone-shape-BLNZk_e1.mjs");
return await t(e.cfg);
}
},
async run(e) {
const { noteProjectCloneShape: t } = await import("./doctor-project-clone-shape-BLNZk_e1.mjs");
await t(e.cfg);
}
}),
createDoctorHealthContribution("doctor:db-bloat", "SQLite database size", {
updateWork: { kind: "standalone" },
async run() {
const { noteSqliteDatabaseBloat: e } = await import("./doctor-db-bloat-C87W46Nt.mjs");
await e();
}
}),
createDoctorHealthContribution("doctor:channel-ingress-dead-letters", "Channel ingress dead letters", {
updateWork: {
kind: "inspection",
scope: "run"
},
async run() {
const { noteChannelIngressDeadLetters: e } = await import("./doctor-channel-ingress-CQ0awCkA.mjs");
await e();
}
}),
createDoctorHealthContribution("doctor:state-integrity", "State integrity", {
healthChecks: {
description: "State directory, config permission, and runtime state issues are findings.",
defaultEnabled: false,
async detect(e) {
const { detectStateIntegrityHealthIssues: t, stateIntegrityIssueToHealthFinding: n } = await import("./doctor-state-integrity-BuapKq2h.mjs");
return t(e.cfg, {
configPath: e.configPath,
env: e.env ?? process.env
}).map(n);
},
repair: legacyOwnedRepair(async (e) => {
const { detectStateIntegrityHealthIssues: t, stateIntegrityIssueToRepairEffect: n } = await import("./doctor-state-integrity-BuapKq2h.mjs");
return t(e.cfg, {
configPath: e.configPath,
env: e.env ?? process.env
}).map(n);
}, "legacy doctor state integrity contribution owns state repairs")
},
async run(e) {
const { noteDoctorAgentDatabasePathHealth: t } = await import("./doctor-agent-database-paths-w7H8gWj6.mjs");
const n = t({
env: e.env ?? process.env,
shouldRepair: e.prompter.shouldRepair
});
if (n.length > 0) {
e.updateWarnings ??= [];
e.updateWarnings.push(...n);
}
const { noteStateIntegrity: r } = await import("./doctor-state-integrity-BuapKq2h.mjs");
await r(e.cfg, e.prompter, e.configPath, { stateDirExistedAtStart: e.stateDirExistedAtStart });
await noteBackupDoctorHint(e.env ?? process.env, e.cfg);
const { noteBackupScratchHealth: i } = await import("./doctor-backup-scratch-C_rzDr9k.mjs");
await i(e.env ?? process.env, e.prompter.shouldRepair);
}
}),
createDoctorHealthContribution("doctor:codex-session-routes", "Codex session routes", {
healthCheckIds: ["core/doctor/codex-session-routes"],
run: runCodexSessionRouteHealth
}),
createDoctorHealthContribution("doctor:telegram-general-topic-conversations", "Telegram General-topic conversations", {
healthCheckIds: ["core/doctor/telegram-general-topic-conversations"],
run: runTelegramGeneralTopicConversationHealth
}),
createDoctorHealthContribution("doctor:session-transcript-headers", "Session transcript headers", async (e) => {
const { noteSessionTranscriptHeaderHealth: t } = await import("./doctor-session-transcript-headers-c8rsUah_.mjs");
await t({
cfg: e.cfg,
env: e.env ?? process.env,
shouldRepair: e.prompter.shouldRepair,
integrityCheck: e.options.fullIntegrityCheck ? "full" : "quick"
});
}),
createDoctorHealthContribution("doctor:session-transcript-labels", "Session transcript labels", async (e) => {
const { noteSessionTranscriptLabelHealth: t } = await import("./doctor-session-transcript-labels-78tS2Hhb.mjs");
await t({
cfg: e.cfg,
env: e.env ?? process.env,
shouldRepair: e.prompter.shouldRepair,
integrityCheck: e.options.fullIntegrityCheck ? "full" : "quick"
});
}),
createDoctorHealthContribution("doctor:session-snapshots", "Session snapshots", {
updateWork: {
kind: "inspection",
scope: "agent"
},
healthChecks: {
description: "Historical session snapshot paths are advisory findings; originals are preserved.",
defaultEnabled: false,
async detect(e) {
const { detectSessionSnapshotHealthIssues: t, sessionSnapshotIssueToHealthFinding: n } = await import("./doctor-session-snapshots-CPntJxFA.mjs");
return (await t({
cfg: e.cfg,
env: process.env
})).map(n);
}
},
async run(e) {
const { noteSessionSnapshotHealth: t } = await import("./doctor-session-snapshots-CPntJxFA.mjs");
await t({
cfg: e.cfg,
env: e.env ?? process.env
});
}
}),
createDoctorHealthContribution("doctor:config-audit-scrub", "Config audit", {
healthChecks: {
description: "Historical config-audit argv redaction gaps are represented as structured findings.",
defaultEnabled: false,
async detect() {
const { configAuditScrubToHealthFinding: e, detectConfigAuditScrubIssue: t } = await import("./doctor-config-audit-scrub-BPGGOJKj.mjs");
const n = await t();
return n.rewritten > 0 ? [e(n)] : [];
},
repair: legacyOwnedRepair(async () => {
const { configAuditScrubToRepairEffect: e, detectConfigAuditScrubIssue: t } = await import("./doctor-config-audit-scrub-BPGGOJKj.mjs");
const n = await t();
return n.rewritten > 0 ? [e(n)] : [];
}, "legacy doctor config audit contribution owns cleanup")
},
async run(e) {
const { maybeRepairLegacyRuntimeFiles: t } = await import("./doctor-usage-cost-cache-kmyZ3hH5.mjs");
const n = await t(e.prompter.shouldRepair, e.env);
recordDoctorHealthWarnings(e, [], n);
}
}),
createDoctorHealthContribution("doctor:legacy-cron", "Legacy cron", {
healthCheckIds: ["core/doctor/legacy-whatsapp-crontab", "core/doctor/legacy-cron-store"],
run: runLegacyCronHealth
}),
createDoctorHealthContribution("doctor:sandbox", "Sandbox", {
healthChecks: {
id: "core/doctor/sandbox/registry-files",
description: "Legacy sandbox registry files are represented in SQLite registry storage.",
async detect() {
const { detectLegacySandboxRegistryFileIssues: e, legacySandboxRegistryInspectionToHealthFinding: t } = await import("./doctor-sandbox-BJ6aJphm.mjs");
return (await e()).map(t);
},
repair: legacyOwnedRepair(async () => {
const { detectLegacySandboxRegistryFileIssues: e, legacySandboxRegistryInspectionToRepairEffect: t } = await import("./doctor-sandbox-BJ6aJphm.mjs");
return (await e()).map(t);
}, "legacy doctor sandbox contribution owns registry migration")
},
async run(e) {
const { maybeRepairSandboxImages: t, maybeRepairSandboxRegistryFiles: n, noteSandboxScopeWarnings: r } = await import("./doctor-sandbox-BJ6aJphm.mjs");
const i = getOpenClawDatabaseMaintenanceScope();
await n(e.prompter, () => {
if (!i) throw new Error("Retired sandbox registry repair requires exclusive maintenance ownership");
i.assertOwnerCurrent();
});
const a = await t(e.cfg, e.runtime, e.prompter);
recordDoctorHealthWarnings(e, [], a);
r(e.cfg);
}
}),
createDoctorHealthContribution("doctor:codex-bwrap", "Codex bwrap sandbox", {
updateWork: { kind: "standalone" },
async run(e) {
const { noteCodexBwrapNamespaceWarnings: t } = await import("./doctor-sandbox-BJ6aJphm.mjs");
await t(e.cfg, {
env: e.env,
cwd: resolveDoctorWorkspaceDir(e.cfg, e.env)
});
}
})
];
}
//#endregion
//#region src/flows/doctor-health-contributions.ts
const MAX_DEFERRED_LEGACY_STATE_DETAILS = 20;
async function reportDeferredLegacyState(e) {
if (e.options.repair !== true && e.options.yes !== true) return;
const [{ detectLegacyStateMigrations: t }, { prepareLegacySessionSurfaces: n }] = await Promise.all([import("./state-migrations.doctor-CODMy_h9.mjs"), import("./legacy-session-surfaces-D1Fxqfg5.mjs")]);
const r = await t({
cfg: e.cfg,
doctorOnlyStateMigrations: true,
...e.env ? { env: e.env } : {},
legacySessionSurfaces: n({ config: e.cfg })
});
const i = [...r.warnings.map((e) => e.startsWith("- ") ? e : `- ${e}`), ...r.preview];
if (i.length === 0) return;
const a = i.slice(0, MAX_DEFERRED_LEGACY_STATE_DETAILS);
const o = i.length - a.length;
const s = e.configWriteRefusal === "validation" ? "Fix the config errors above." : e.configWriteRefusal === "include-ownership" ? "Repair the include boundary named above by hand." : "Resolve the Gateway or cron-store condition above.";
note([
"Pending owners and blockers:",
...a,
...o > 0 ? [`${o} additional pending entries were omitted from this report.`] : [],
"No listed legacy source was removed.",
s
].join("\n"), "Legacy state deferred");
}
async function runGatewayConfigHealth(e) {
await runCoreHealthFindingNote(e, "core/doctor/gateway-config");
}
async function runGatewayAuthHealth(e) {
if (!e.sourceConfigValid) return;
const { detectGatewayAuthHealth: t } = await import("./doctor-gateway-auth-DY6CjWfE.mjs");
const [n] = await t({
cfg: e.cfg,
env: e.env,
allowExecSecretRefs: e.options.allowExec
});
const { resolveSecretInputRef: r } = await import("./types.secrets-Djnm0_Tu.mjs");
const i = r({
value: e.cfg.gateway?.auth?.token,
defaults: e.cfg.secrets?.defaults
}).ref;
if (!n) {
if (i && e.options.generateGatewayToken === true) note(`Gateway token generation skipped because gateway.auth.token is managed by SecretRef ${i.source}:${i.provider}:${i.id}. The referenced credential was left unchanged.`, "Gateway auth");
return;
}
note([n.message, n.fixHint].filter(Boolean).join("\n"), "Gateway auth");
if (n.path !== "gateway.auth.token") {
recordDoctorHealthWarnings(e, [n]);
return;
}
if (i) {
if (i.source === "store" && n.requirement === "SECRET_REF_REDACTED_VALUE" && (e.options.generateGatewayToken === true || e.options.repair === true || e.options.yes === true)) {
const { isRedactedSecretValue: t } = await import("./redact-sentinel-DpyYZnhS.mjs");
const { readSecretStoreValue: n, writeSecretStoreEntry: r } = await import("./secret-store-xf4-UqW-.mjs");
const { createVerifiedSqliteSnapshot: a } = await import("./sqlite-snapshot-DGhn22ul.mjs");
const { resolveOpenClawStateSqlitePath: o } = await import("./openclaw-state-db.paths-DiM3pkKt.mjs");
const { randomToken: s } = await import("./onboard-helpers-Cy-Vj-Pl.mjs");
const c = { env: e.env ?? process.env };
const l = {
scope: { kind: "team" },
name: i.id,
database: c
};
try {
const e = await n(l);
if (!e.ok || !t(e.value)) {
note(`Secret store entry "${l.name}" changed; rerun Doctor to inspect it.`, "Gateway auth");
return;
}
const i = o(c.env);
const u = await a({
sourcePath: i,
targetPath: `${i}.doctor-gateway-token.${randomUUID()}.bak`,
preserveRowIds: true
});
const d = s();
await r({
...l,
value: d,
expectedValue: e.value,
kind: "secret",
updatedBy: "doctor"
});
note(`Regenerated Gateway token in secret store entry "${l.name}"; gateway.auth.token remains a SecretRef. Backup: ${u.path}\nRestart the Gateway, then reconnect or re-pair devices with the new token.`, "Gateway auth");
} catch (t) {
const n = `Could not repair Gateway token in secret store entry "${l.name}": ${scrubDoctorErrorMessage(t)}. Rerun \`openclaw doctor --fix\` after resolving the reported problem.`;
note(n, "Gateway auth");
recordDoctorHealthWarnings(e, [], [n]);
}
return;
}
note(`${e.options.generateGatewayToken === true ? "Gateway token generation skipped because a SecretRef is configured. " : ""}Doctor will not overwrite gateway.auth.token with a plaintext value.`, "Gateway auth");
return;
}
if (!(e.options.generateGatewayToken === true ? true : e.options.nonInteractive === true ? false : await e.prompter.confirmAutoFix({
message: "Generate and configure a gateway token now?",
initialValue: true
}))) return;
const { randomToken: a } = await import("./onboard-helpers-Cy-Vj-Pl.mjs");
const o = a();
const s = {
...e.cfg,
gateway: {
...e.cfg.gateway,
auth: {
...e.cfg.gateway?.auth,
mode: "token",
token: o
}
}
};
copyConfigResolutionFactsThroughRewrite(e.cfg, s);
e.cfg = s;
note("Gateway token configured.", "Gateway auth");
}
async function runLegacyStateHealth(e) {
await runCoreContributionHealth(e, ["core/doctor/removed-workspaces-state"]);
const t = e.options.repair === true || e.options.yes === true;
if (!t || !isDeepStrictEqual(e.configResult.preflightLegacyStateConfig, e.cfg)) {
const { detectLegacyStateMigrations: n, runLegacyStateMigrations: r } = await import("./state-migrations.doctor-CODMy_h9.mjs");
const { prepareLegacySessionSurfaces: i } = await import("./legacy-session-surfaces-D1Fxqfg5.mjs");
const a = i({ config: e.cfg });
const o = await n({
cfg: e.cfg,
...t ? { doctorOnlyStateMigrations: true } : {},
legacySessionSurfaces: a
});
const s = e.configResult.stateMigrationStepReceipts?.find((e) => e.id === "migration-detection");
noteDoctorRepairResult({
changes: [],
warnings: o.warnings.filter((e) => !s?.warnings.includes(e)),
notices: o.notices.filter((e) => !s?.notices?.includes(e))
});
if (o.preview.length > 0) {
note(o.preview.join("\n"), "Legacy state detected");
if (e.options.nonInteractive === true || await e.prompter.confirm({
message: "Migrate detected legacy state now?",
initialValue: true
})) {
const t = await r({
detected: o,
integrityCheck: e.options.fullIntegrityCheck ? "full" : "quick",
config: e.cfg,
legacySessionSurfaces: a
});
recordDoctorHealthWarnings(e, [], t.stepReceipts.flatMap((e) => e.outcome === "warning" || e.outcome === "deferred" ? e.warnings : []));
noteDoctorRepairResult(t);
}
}
}
if (!t) return;
const { repairObsoleteGeneratedExecApprovals: n } = await import("./exec-approvals-generated-migration-DQhVwBoB.mjs");
const { ExecApprovalsMigrationRequiredError: r } = await import("./exec-approvals-migration-gate-DRgt1dHP.mjs");
let i;
try {
i = n();
} catch (e) {
if (e instanceof r) return;
throw e;
}
if (i > 0) note(`Exec approvals updated: removed ${i} older generated ${i === 1 ? "approval" : "approvals"} that were not tied to a working directory. Manual allowlist rules were not changed. Rerun affected workflows and choose "Always allow here" when prompted.`, "Doctor changes");
}
async function shouldInspectSystemdLinger(e) {
if (process.platform !== "linux" || resolveDoctorMode(e.cfg) !== "local" || !await shouldManageGatewayService(e.env ?? process.env)) return false;
const t = e.env ?? process.env;
const { findInstalledSystemdGatewayScope: n } = await import("./systemd-C3ApdIee.mjs");
return (await n(t))?.scope === "user";
}
async function runSystemdLingerHealth(e) {
if (e.options.nonInteractive === true || !await shouldInspectSystemdLinger(e)) return;
const { readGatewayServiceState: t, resolveGatewayService: n } = await import("./service-D5ZNJZsc.mjs");
const { ensureSystemdUserLingerInteractive: r } = await import("./systemd-linger-CcpzZ-pu.mjs");
if ((await t(n(), { env: process.env })).loadState.status !== "loaded") return;
await r({
runtime: e.runtime,
prompter: {
confirm: async (t) => e.prompter.confirm(t),
note
},
reason: "Gateway runs as a systemd user service. Without lingering, systemd stops the user session on logout/idle and kills the Gateway.",
requireConfirm: true
});
}
async function detectSystemdLingerFindings(e) {
if (!await shouldInspectSystemdLinger(e)) return [];
const { readGatewayServiceState: t, resolveGatewayService: n } = await import("./service-D5ZNJZsc.mjs");
if ((await t(n(), { env: process.env })).loadState.status !== "loaded") return [];
const { isSystemdUserServiceAvailable: r, readSystemdUserLingerStatus: i, resolveSystemdUserServiceAccount: a } = await import("./systemd-C3ApdIee.mjs");
if (!await r(process.env)) return [];
const o = a(process.env);
if (!o) return [];
const s = await i({
env: process.env,
user: o
});
if (!s || s.linger === "yes") return [];
return [{
checkId: "core/doctor/systemd-linger",
severity: "warning",
source: "doctor",
message: `Systemd lingering is disabled for ${s.user}.`,
target: `systemd.user.${s.user}`,
requirement: "systemd user lingering enabled",
fixHint: `Run: sudo loginctl enable-linger ${s.user}`
}];
}
async function runShellCompletionHealth(e) {
const { doctorShellCompletion: t } = await import("./doctor-completion-BBj8V0v-.mjs");
await t(e.prompter, { nonInteractive: e.options.nonInteractive });
}
async function runGatewayHealthChecks(e) {
const t = e.gatewayMaintenanceActive ? "Gateway health will be checked after Doctor repair." : await hasActiveGatewayExecCredential(e) && e.options.allowExec !== true ? "Gateway health checks skipped because gateway credentials use an exec SecretRef. Run `openclaw doctor --allow-exec` to verify Gateway health with exec SecretRefs." : void 0;
if (t) {
note(t, "Gateway");
e.gatewayHealthSkipped = true;
e.gatewayMemoryProbe = {
checked: false,
ready: false,
skipped: true
};
return;
}
const { checkGatewayHealth: n, probeGatewayMemoryStatus: r } = await import("./doctor-gateway-health-DptzvbmT.mjs");
const { healthOk: i, authenticated: a, status: o } = await n({
runtime: e.runtime,
cfg: e.cfg,
onFinding: (t) => reportDoctorHealthFinding(e, t)
});
e.gatewayHealthSkipped = false;
e.healthOk = i;
e.gatewayStatus = o;
e.gatewayMemoryProbe = a ? await r({ cfg: e.cfg }) : {
checked: false,
ready: false,
skipped: i
};
}
function shouldDeferPostActivationInspections(e) {
return isUpdateDoctorRun(e) && !resolveUpdateRehearsalRoot(e) && isUpdateDoctorInspectionReportMode(e);
}
function resolveDoctorHealthContributions() {
return [...resolveInitialDoctorHealthContributions({
runStructuredHealthRepairs: (e) => runStructuredHealthRepairs(e, resolveDoctorContributionHealthChecks),
runGatewayConfigHealth,
runAuthProfileMigration,
runAuthProfileHealth: runAuthProfileDiagnostics,
runGatewayAuthHealth,
runLegacyStateHealth
}), ...resolveFinalDoctorHealthContributions({
runSystemdLingerHealth,
detectSystemdLingerFindings,
runShellCompletionHealth,
runGatewayHealthChecks
})];
}
async function loadCoreHealthChecksById() {
const { createCoreHealthChecks: e } = await import("./doctor-core-checks-5nniaFZH.mjs");
return new Map(e().map((e) => [e.id, e]));
}
function resolveContributionHealthChecks(e, t) {
if (e.healthChecks.length > 0) return e.healthChecks.map((t) => ({
...normalizeHealthCheck(t),
updateWork: e.updateWork
}));
return e.healthCheckIds.map((n) => {
const r = t.get(n);
if (r === void 0) throw new Error(`doctor contribution ${e.id} references unknown core health check ${n}`);
return {
...r,
updateWork: e.updateWork
};
});
}
async function resolveDoctorContributionHealthChecks() {
const e = await loadCoreHealthChecksById();
return resolveDoctorHealthContributions().flatMap((t) => resolveContributionHealthChecks(t, e));
}
/**
* Optional inspections whose every finding `doctor --lint` reproduces, so an
* updater can run them after the restarted Gateway is ready. Repairs, readiness
* checks and inspections without a lint check stay in the stopped window.
*/
async function selectPostActivationInspections(e) {
const t = await loadCoreHealthChecksById();
return e.flatMap((e) => {
if (e.required || e.updateWork?.kind !== "inspection" || e.updateWork.repairs) return [];
if (e.id === "doctor:session-snapshots" || e.id === "doctor:workspace-status") return [];
const n = resolveContributionHealthChecks(e, t);
return n.length > 0 && n.every((e) => e.updateReadiness === void 0 && e.repair === void 0) ? [{
contribution: e,
checks: n
}] : [];
});
}
async function runDoctorHealthContributionList(e, t) {
const n = resolveCommandProcessSignal(getAsyncWorkSignal());
n?.throwIfAborted();
const r = e.runWithPluginMetadataSnapshot;
throwIfDoctorStateMigrationRefused(e.configResult.stateMigrationStepReceipts);
const i = e.env ?? process.env;
e.updateBudget ??= await resolveDoctorUpdateBudget({
cfg: e.cfg,
env: i,
preparedAgentCount: e.preparedAgentCount
});
const a = isUpdateDoctorRun(i);
const o = resolveUpdateRehearsalRoot(i);
const s = new Set(o ? t.filter((e) => !e.required && e.updateWork?.kind === "inspection" && !e.updateWork.repairs) : []);
let c = shouldDeferPostActivationInspections(i) ? recordUpdateDoctorDeferredInspectionChecks([]) : void 0;
const l = new Map(c ? (await selectPostActivationInspections(t)).map(({ contribution: e, checks: t }) => [e, t.map((e) => e.id)]) : []);
const u = a ? t.filter((e) => e.updateWork?.kind === "standalone") : [];
if (u.length > 0) note(`Omitted during update: ${u.map((e) => e.label).join(", ")}.\nRun \`openclaw doctor\` after the update to inspect these diagnostics.`, "Update Doctor scope");
const d = e.updateBudget ? [
...t.filter((e) => e.updateWork === void 0 || e.updateWork.kind === "startup" || e.updateWork.kind === "standalone"),
...t.filter((e) => e.updateWork?.kind === "inspection"),
...t.filter((e) => e.updateWork?.kind === "finalize")
] : t;
try {
for (const t of d) {
n?.throwIfAborted();
const i = l.get(t);
if (i) {
c = recordUpdateDoctorDeferredInspectionChecks(i);
continue;
}
if (s.has(t) || a && t.updateWork?.kind === "standalone") continue;
if (t.updateWork?.kind === "inspection" && !admitDoctorUpdateInspection(e.updateBudget, t.updateWork.scope, (t.healthCheckIds.length ? t.healthCheckIds : [`core/doctor/${t.id.replace(/^doctor:/, "")}`]).map((e) => ({
id: e,
label: t.label
})))) continue;
try {
const run = async () => {
n?.throwIfAborted();
try {
await t.run(e);
} finally {
throwIfDoctorStateMigrationRefused(e.configResult.stateMigrationStepReceipts);
}
if (e.configWriteRefusal) await reportDeferredLegacyState(e);
};
await withDoctorProgress(t.label, () => measureGatewayBootstrapStep(`doctor.contribution.${t.id}`, async () => {
if (!r) await run();
else {
const t = resolveDoctorWorkspaceDir(e.cfg, e.env);
await r({
config: e.cfg,
workspaceDir: t
}, run);
}
}), e.options.json !== true);
n?.throwIfAborted();
if (e.configWriteRefusal) return;
} catch (r) {
n?.throwIfAborted();
if (t.required || r instanceof DoctorStateMigrationRefusalError || r instanceof ConfigWritePostCommitError) throw r;
const i = `${t.id} run failed: ${scrubDoctorErrorMessage(r)}`;
renderStructuredHealthFindings(e, [{
checkId: t.id,
severity: "warning",
category: "fix-now",
message: `Doctor could not complete ${t.label}: ${scrubDoctorErrorMessage(r)}`,
fixHint: "Resolve the reported inspection failure, then rerun openclaw doctor. This check could not establish its health."
}]);
recordDoctorHealthWarnings(e, [], [i]);
}
}
} finally {
if (s.size > 0) e.runtime.log(`Deferred advisory inspections during copied-state rehearsal: ${[...s].map((e) => e.id).join(", ")}. The live post-swap Doctor retains these checks.`);
if (c?.length) e.runtime.log(`Deferred advisory inspections until the restarted Gateway is ready: ${c.join(", ")}. The updater runs their \`openclaw doctor --lint\` checks after restart.`);
const t = [...e.updateBudget?.deferred.values() ?? []];
recordDoctorHealthWarnings(e, t, [], { prepend: true });
for (const n of t) e.runtime.log(`[warning] ${n.checkId} [${n.errorCode}]: ${n.message}`);
if (t.length > 0) e.runtime.log("Run `openclaw doctor --fix` after activation to complete deferred checks and repairs.");
}
}
async function runDoctorHealthContributions(e) {
await runDoctorHealthContributionList(e, resolveDoctorHealthContributions());
}
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.doctorHealthContributionsTestApi")] = {
resolveDoctorHealthContributions,
runDoctorHealthContributionList
};
//#endregion
export { resolveDoctorContributionHealthChecks, runDoctorHealthContributions };