openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,005 lines (1,004 loc) • 40 kB
JavaScript
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs";
import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import "./utils-C8YECn2Q.mjs";
import { o as isDefaultInstallIdentity } from "./paths-DAcAg5aV.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { t as buildModelCatalogMergeKey } from "./model-catalog-refs-Bk2MNoCv.mjs";
import { i as listAgentIds, n as listAgentEntries, p as tryResolveSoleAgentId, r as listAgentEntriesWithSource } from "./agent-roster-t1ooUdXp.mjs";
import "./agent-scope-config-DmXgFGKP.mjs";
import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs";
import { o as resolveDefaultModelMaxTokens, t as DEFAULT_CONTEXT_TOKENS } from "./defaults-BWyoTPqn.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import "./model-selection-C2A4Wyix.mjs";
import { n as hasAmbiguousGatewayAuthModeConfig } from "./auth-mode-policy-Dn8RauUH.mjs";
import { a as shellCompletionStatusToRepairEffects, i as shellCompletionStatusToHealthFindings, t as checkShellCompletionStatus } from "./doctor-completion-C54QgZLk.mjs";
import { i as legacyOwnedRepair } from "./doctor-health-contribution-t31v9kPi.mjs";
import { n as configValidationIssuesToHealthFindings, r as configValidationWarningsToHealthFindings, t as FINAL_CONFIG_VALIDATION_CHECK_ID } from "./doctor-config-validation-findings-DUD4Pgv3.mjs";
import { i as hasConfiguredCommandOwners } from "./doctor-command-owner-Dul2IrrD.mjs";
import { t as resolveSkillWorkshopConfig } from "./config-DO1phBEt.mjs";
import { t as detectSkillWorkshopToolPolicyDiagnostic } from "./tool-policy-diagnostic-DpGYE1Ax.mjs";
import { n as maybeRepairOwnedChromeExtensionNativeHosts, t as collectBrowserReadinessFindings } from "./doctor-browser-CBeYYwMh.mjs";
import { t as hasActiveGatewayExecCredential } from "./doctor-gateway-exec-credential-n80b7QiI.mjs";
import { t as classifyLegacyServices } from "./doctor-gateway-legacy-services-BBb-0U5c.mjs";
import { n as disableUnavailableSkillsInConfig, r as formatMissingSkillSummary } from "./doctor-skills-core-3U8Csb15.mjs";
import { i as uiProtocolFreshnessIssueToRepairEffects, r as uiProtocolFreshnessIssueToHealthFinding, t as detectUiProtocolFreshnessIssues } from "./doctor-ui-DOpIa1Za.mjs";
import { a as collectDisabledCodexPluginRouteIssues, i as resolveKnownModelRefMigrationTarget, n as collectCodexRuntimeCompatibilityWarnings } from "./codex-route-warnings-BTtNbHw_.mjs";
import { t as detectGatewayAuthHealth } from "./doctor-gateway-auth-BvSVhfZ3.mjs";
import { n as readModelCatalog, t as getModelCatalogWarnings } from "./catalog-warnings-DifFmrGP.mjs";
import { t as resolveDoctorWorkspaceSuggestionScopes } from "./doctor-workspace-suggestion-scopes-DDUxMVpQ.mjs";
import { n as securityAuditFindingToHealthFinding } from "./health-check-adapter-BIGrWaNz.mjs";
import path from "node:path";
import { lstat, realpath, rm } from "node:fs/promises";
//#region src/flows/doctor-acp-agent-model-check.ts
const CHECK_ID$3 = "core/doctor/acp-agent-model";
const acpAgentModelCheck = {
id: CHECK_ID$3,
kind: "core",
description: "ACP harness models and OpenClaw native defaults are shown separately.",
source: "doctor",
async detect(e) {
const t = e.cfg;
const n = [];
for (const { entry: e, source: r } of listAgentEntriesWithSource(t)) {
if (e.runtime?.type !== "acp") continue;
const i = resolveAgentModelPrimaryValue(e.model)?.trim();
const a = e.id?.trim();
if (!i || !a) continue;
const o = resolveDefaultModelForAgent({
cfg: t,
agentId: a
});
const s = sanitizeTerminalText(`${o.provider}/${o.model}`);
const c = r.kind === "entries" ? appendConfigPathSegment("agents.entries", r.key) : appendConfigPathSegment("agents.list", r.index);
const l = appendConfigPathSegment(c, "model");
const u = sanitizeTerminalText(typeof e.model === "string" ? l : appendConfigPathSegment(l, "primary"));
const d = sanitizeTerminalText(a);
const f = sanitizeTerminalText(i);
n.push({
checkId: CHECK_ID$3,
severity: "info",
source: "doctor",
target: d,
path: u,
message: `Agent "${d}" uses ACP harness model "${f}" from ${u}. Its OpenClaw native default is "${s}". Explicit native session, utility, and subagent model selections still apply.`
});
}
return n;
}
};
//#endregion
//#region src/flows/doctor-config-validation-check.ts
const finalConfigValidationCheck = {
id: FINAL_CONFIG_VALIDATION_CHECK_ID,
updateReadiness: "post-plugin",
kind: "core",
description: "Active openclaw.jsonc parses and conforms to the config schema.",
source: "doctor",
async detect(e) {
let t = e.mode === "lint" ? e.lintConfigSnapshot : void 0;
if (!t) {
const { readConfigFileSnapshot: e } = await import("./config/config.js");
t = await e({ observe: false });
}
if (!t.exists) return [];
return [...configValidationIssuesToHealthFindings(t.issues), ...configValidationWarningsToHealthFindings(t.warnings)];
}
};
//#endregion
//#region src/flows/doctor-core-bootstrap-size-check.ts
const bootstrapSizeCheck = {
id: "core/doctor/bootstrap-size",
description: "Workspace bootstrap files fit within configured injection limits.",
async detect(e) {
if (!e.cwd) return [];
const { collectBootstrapFileSize: t } = await import("./doctor-bootstrap-size-CIdxmtHh.mjs");
const { isFixedUserCapFile: n } = await import("./bootstrap-budget-Lxn03Iwq.mjs");
const { USER_BOOTSTRAP_MAX_CHARS: r } = await import("./bootstrap--hpiks7W.mjs");
const i = e.cwd;
const { analysis: a } = await t(e.cfg, i, tryResolveSoleAgentId(e.cfg));
const o = `Reduce the file size; USER.md has a fixed ${r.toLocaleString("en-US")}-character bootstrap cap that \`bootstrapMaxChars\` cannot raise.`;
const s = [];
for (const e of a.truncatedFiles) {
let t = "Reduce the file size or tune `agents.entries.*.bootstrapMaxChars` / `bootstrapTotalMaxChars` for this agent, or the corresponding `agents.defaults.*` fallback.";
if (e.causes.includes("per-file-limit") && n(e)) {
t = o;
if (e.causes.includes("total-limit")) t += " Also reduce total bootstrap size or tune `agents.entries.*.bootstrapTotalMaxChars` for this agent, or `agents.defaults.bootstrapTotalMaxChars` as fallback.";
}
s.push({
checkId: "core/doctor/bootstrap-size",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/concepts/agent-workspace",
severity: "warning",
message: `${e.name} exceeds bootstrap limits and will be truncated. ${e.retention}`,
path: e.path,
fixHint: t
});
}
for (const e of a.nearLimitFiles) {
if (e.truncated) continue;
s.push({
checkId: "core/doctor/bootstrap-size",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/concepts/agent-workspace",
severity: "info",
message: `${e.name} is near the configured bootstrap file limit.`,
path: e.path,
fixHint: n(e) ? o : "Reduce the file size or tune `agents.entries.*.bootstrapMaxChars` for this agent, or `agents.defaults.bootstrapMaxChars` as fallback, for per-file limits."
});
}
if (a.totalNearLimit) s.push({
checkId: "core/doctor/bootstrap-size",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/concepts/agent-workspace",
severity: a.hasTruncation ? "warning" : "info",
message: "Total bootstrap context is near the configured total limit.",
path: i,
fixHint: "Reduce bootstrap file sizes or tune `agents.entries.*.bootstrapTotalMaxChars` for this agent, or `agents.defaults.bootstrapTotalMaxChars` as fallback."
});
return s;
}
};
//#endregion
//#region src/flows/doctor-gateway-services-check.ts
const CHECK_ID$2 = "core/doctor/gateway-services/extra";
async function inspectGatewayServices(e) {
const { detectExtraGatewayServiceIssues: t } = await import("./doctor-gateway-services-CRRoZzfB.mjs");
return t({ deep: e.deep === true });
}
const gatewayServicesExtraCheck = {
id: CHECK_ID$2,
kind: "core",
description: "Extra gateway-like services and incomplete inspection are reported as findings.",
source: "doctor",
async detect(e) {
const { services: t, errors: n } = await inspectGatewayServices(e);
return t.map((e) => ({
checkId: CHECK_ID$2,
severity: e.legacy === true ? "warning" : "info",
message: `Other gateway-like service detected: ${e.label} (${e.scope}, ${e.detail})`,
source: e.platform,
target: e.label,
fixHint: e.legacy === true ? "Run `openclaw doctor` interactively to review legacy gateway services and confirm supported cleanup." : "Run a single gateway per machine unless this extra gateway is intentional."
})).concat(n.map((e) => ({
checkId: CHECK_ID$2,
severity: "warning",
message: `Gateway service inspection incomplete: ${e.message}`,
source: "doctor",
target: e.source,
fixHint: "Restore access to the native service definition or service manager, then run `openclaw doctor --deep` again."
})));
},
async repair(e) {
const { services: t } = await inspectGatewayServices(e);
const { darwinUserServices: n, linuxUserServices: r } = classifyLegacyServices(t.filter((e) => e.legacy === true));
const i = [...n, ...r].map((e) => ({
kind: "service",
action: "would-remove-legacy-gateway-service",
target: e.label,
dryRunSafe: false
}));
return e.dryRun === true ? {
status: "repaired",
changes: [],
effects: i
} : {
status: "skipped",
reason: "legacy doctor gateway service contribution owns cleanup",
changes: [],
effects: i
};
}
};
//#endregion
//#region src/flows/doctor-legacy-output-cap-check.ts
const CHECK_ID$1 = "core/doctor/legacy-output-cap";
const LEGACY_SAVED_OUTPUT_CAPS = /* @__PURE__ */ new Set([4096, 8192]);
const PROVIDERS_WITH_INTENTIONAL_CAPS = /* @__PURE__ */ new Set(["mistral"]);
const MAX_LISTED_MODELS = 5;
function positiveNumber(e) {
return typeof e === "number" && Number.isFinite(e) && e > 0 ? e : void 0;
}
/** Context-sized fallback only; a catalog limit may still apply after removing the saved cap. */
function defaultCapWithoutSavedValue(e) {
const t = positiveNumber(e.contextWindow) ?? 2e5;
const n = positiveNumber(e.contextTokens) ?? t;
return resolveDefaultModelMaxTokens(Math.min(n, t));
}
/**
* Explains the raised default output cap to users whose config still pins an old
* onboarding default. Notice only: a saved maxTokens may be deliberate, so Doctor
* never rewrites it.
*/
const legacyOutputCapCheck = {
id: CHECK_ID$1,
kind: "core",
description: "Saved model output caps that match a former onboarding default are reported.",
source: "doctor",
async detect(e) {
const t = [];
const n = asNullableRecord(asNullableRecord(e.cfg.models)?.providers) ?? {};
for (const [e, r] of Object.entries(n)) {
const n = asNullableRecord(r);
if (!n || PROVIDERS_WITH_INTENTIONAL_CAPS.has(normalizeProviderId(e))) continue;
if (positiveNumber(n.maxTokens) !== void 0) continue;
const i = Array.isArray(n.models) ? n.models : [];
const a = [];
for (const e of i) {
const t = asNullableRecord(e);
const n = positiveNumber(t?.maxTokens);
if (!t || n === void 0 || !LEGACY_SAVED_OUTPUT_CAPS.has(n)) continue;
const r = defaultCapWithoutSavedValue(t);
if (r <= n) continue;
const i = typeof t.id === "string" && t.id.trim() ? t.id.trim() : "?";
a.push({
id: sanitizeTerminalText(i),
saved: n,
next: r
});
}
if (a.length === 0) continue;
const o = sanitizeTerminalText(e);
const s = sanitizeTerminalText(appendConfigPathSegment(appendConfigPathSegment("models.providers", e), "models"));
const c = a.slice(0, MAX_LISTED_MODELS).map(({ id: e, saved: t }) => `${e} (${t})`).join(", ");
const l = a.length > MAX_LISTED_MODELS ? ` and ${a.length - MAX_LISTED_MODELS} more` : "";
const u = Math.max(...a.map((e) => e.next));
t.push({
checkId: CHECK_ID$1,
severity: "info",
source: "doctor",
target: o,
path: s,
message: `Provider "${o}" has saved maxTokens values matching former onboarding defaults on ${c}${l}. OpenClaw's default output cap for models without a known limit is now up to ${u} tokens. A provider catalog limit may leave the output cap unchanged or lower it when the saved value is removed.`,
fixHint: "If you did not choose these values, remove maxTokens from those model rows to use the provider catalog limit or the new default. Keep them if your server needs the lower cap.",
docsUrl: "https://docs.openclaw.ai/concepts/model-providers/custom-providers"
});
}
return t;
}
};
//#endregion
//#region src/flows/doctor-model-reference-check.ts
const modelReferenceCheck = {
id: "core/doctor/model-references",
kind: "core",
description: "Configured model references have known providers and server catalog diagnostics.",
source: "doctor",
async detect(e) {
const { inspectConfiguredModelReferences: t } = await import("./model-reference-validation-BRfGhO4O.mjs");
const n = e.allowExecSecretRefs !== true && await hasActiveGatewayExecCredential({
cfg: e.cfg,
env: e.env
});
const r = n ? void 0 : await readModelCatalog(e.cfg);
const i = t({
cfg: e.cfg,
env: e.env,
workspaceDir: e.cwd
}).flatMap((t) => {
const n = resolveKnownModelRefMigrationTarget(e.cfg, t.ref);
const i = n ? {
message: `Configured model "${t.ref}" is a legacy reference. Doctor can migrate it to "${n}".`,
requirement: `full model reference "${n}"`,
fixHint: `Run \`openclaw doctor --fix\` to migrate this model reference to "${n}".`
} : void 0;
const a = t.status === "unknown-provider";
const o = buildModelCatalogMergeKey(t.provider, t.model);
const s = r?.models.some(({ provider: e, id: t }) => buildModelCatalogMergeKey(e, t) === o);
const c = t.status === "unknown-model" && !s;
const l = i && (t.status === "unknown-model" || t.status === "uncatalogued-provider");
if (!a && !(t.active && (c || l))) return [];
return [{
checkId: "core/doctor/model-references",
severity: a ? "warning" : "info",
source: "doctor",
target: t.ref,
...i ?? (a ? {
message: `Configured model "${t.ref}" uses unknown provider "${t.provider}". No installed plugin manifest or models.providers entry declares it.`,
requirement: "an installed plugin manifest or models.providers configuration",
fixHint: "Install a plugin that declares this provider, configure it under models.providers, or remove the model reference."
} : {
message: `Configured model "${t.ref}" uses a known provider but is not in the local model catalog. It may be newly released or self-hosted.`,
requirement: "a provider-supported model id",
fixHint: "Verify the model id with the provider, or rerun with --severity-min info after refreshing the local catalog."
})
}];
});
if (n) {
i.push({
checkId: "core/doctor/model-references",
severity: "info",
source: "doctor",
message: "Server catalog inspection skipped because the selected Gateway uses an exec SecretRef.",
fixHint: "Run openclaw doctor --allow-exec to permit configured secret execution."
});
return i;
}
for (const e of getModelCatalogWarnings(r)) i.push({
checkId: "core/doctor/model-references",
severity: "warning",
source: "doctor",
target: e.ref,
message: e.message,
fixHint: e.fixHint
});
return i;
}
};
//#endregion
//#region src/flows/doctor-removed-workspaces-state-check.ts
const CHECK_ID = "core/doctor/removed-workspaces-state";
function resolveRemovedWorkspacesStateDir() {
return path.join(resolveStateDir(process.env), "workspaces");
}
async function pathKind(e) {
const t = await lstat(e).catch(ignoreMissingPath);
return t?.isDirectory() ? "directory" : t?.isFile() ? "file" : null;
}
async function hasRemovedWorkspacesFingerprint(e) {
if (await pathKind(e) !== "directory") return false;
if (await pathKind(path.join(e, "workspaces.sqlite")) === "file") return true;
const [t, n] = await Promise.all([pathKind(path.join(e, "widgets")), pathKind(path.join(e, "data"))]);
return t === "directory" && n === "directory";
}
async function canonicalPath(e) {
const t = path.resolve(e);
try {
return await realpath(t);
} catch (e) {
const n = e.code;
if (n === "ENOENT" || n === "ENOTDIR") return t;
throw e;
}
}
async function configuredAgentWorkspaceCollisions(e, t) {
const n = [{
label: "agents.defaults.workspace",
workspace: e.agents?.defaults?.workspace
}, ...listAgentEntries(e).map((e) => ({
label: `agents.entries.${e.id}.workspace`,
workspace: e.workspace
}))];
const r = await canonicalPath(t);
return (await Promise.all(n.filter((e) => typeof e.workspace === "string" && e.workspace.trim().length > 0).map(async (e) => ({
label: e.label,
resolvedWorkspace: await canonicalPath(resolveUserPath(e.workspace, process.env))
})))).filter((e) => isPathInside(r, e.resolvedWorkspace) || isPathInside(e.resolvedWorkspace, r)).map((e) => e.label);
}
function collisionWarning(e, t) {
return `Retired Workspaces plugin fingerprints remain at ${e}, but ${t.join(", ")} resolves to that directory or an overlapping path. Automatic removal is disabled.`;
}
function repairEffect(e, t) {
return {
kind: "state",
action: t ? "would-remove-retired-workspaces-state" : "remove-retired-workspaces-state",
target: e,
dryRunSafe: false
};
}
const removedWorkspacesStateCheck = {
id: CHECK_ID,
kind: "core",
description: "State from the retired experimental Workspaces plugin has been removed.",
source: "doctor",
async detect(e, t) {
const n = resolveRemovedWorkspacesStateDir();
const r = new Set(t?.paths ?? []);
if (r.size > 0 && !r.has(n) || !await hasRemovedWorkspacesFingerprint(n)) return [];
const i = await configuredAgentWorkspaceCollisions(e.cfg, n);
return [{
checkId: CHECK_ID,
severity: "warning",
message: i.length > 0 ? collisionWarning(n, i) : `Retired Workspaces plugin state remains at ${n}.`,
path: n,
...i.length > 0 ? {} : { fixHint: "Run `openclaw doctor --fix` to remove the stale plugin state." }
}];
},
async repair(e) {
const t = resolveRemovedWorkspacesStateDir();
if (!await hasRemovedWorkspacesFingerprint(t)) return {
status: "skipped",
reason: "retired Workspaces plugin fingerprints are absent",
changes: []
};
const n = await configuredAgentWorkspaceCollisions(e.cfg, t);
if (n.length > 0) {
const e = collisionWarning(t, n);
return {
status: "skipped",
reason: e,
changes: [],
warnings: [e]
};
}
const r = e.dryRun === true;
const i = [repairEffect(t, r)];
if (r) return {
changes: [`Would remove retired Workspaces plugin state at ${t}.`],
effects: i
};
await rm(t, {
force: true,
recursive: true
});
return {
changes: [`Removed retired Workspaces plugin state at ${t}.`],
effects: i
};
}
};
//#endregion
//#region src/flows/doctor-tool-schema-check.ts
const runtimeToolSchemaCheck = {
id: "core/doctor/runtime-tool-schemas",
kind: "core",
description: "Active agent tool schemas project into model/runtime-compatible tool inputs.",
source: "doctor",
async detect(e) {
const t = await import("./doctor-tool-schema-runtime-1_Okc55i.mjs");
const { runWithPluginMetadataSnapshot: n, deferInspectionDisposal: r } = e;
return t.collectRuntimeToolSchemaFindings(e.cfg, {
mode: e.mode,
env: e.env,
...n ? { runWithPluginMetadataSnapshot: n } : {},
...r ? { deferInspectionDisposal: r } : {}
});
}
};
//#endregion
//#region src/flows/doctor-core-checks.ts
const CODEX_SESSION_ROUTES_CHECK_ID = "core/doctor/codex-session-routes";
const GATEWAY_DAEMON_CHECK_ID = "core/doctor/gateway-daemon";
const GATEWAY_HEALTH_CHECK_ID = "core/doctor/gateway-health";
const TELEGRAM_GENERAL_TOPIC_CONVERSATIONS_CHECK_ID = "core/doctor/telegram-general-topic-conversations";
const SKILL_WORKSHOP_TOOL_POLICY_CHECK_ID = "core/doctor/skill-workshop-tool-policy";
const gatewayConfigCheck = {
id: "core/doctor/gateway-config",
description: "openclaw.jsonc gateway block is set and unambiguous.",
async detect(e) {
const t = [];
if (!e.cfg.gateway?.mode) t.push({
checkId: "core/doctor/gateway-config",
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/gateway/configuration",
severity: "warning",
message: "gateway.mode is unset; gateway start will be blocked.",
path: "gateway.mode",
fixHint: "Run `openclaw configure` and set Gateway mode (local/remote), or `openclaw config set gateway.mode local`."
});
if (e.cfg.gateway?.mode !== "remote" && hasAmbiguousGatewayAuthModeConfig(e.cfg)) t.push({
checkId: "core/doctor/gateway-config",
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/gateway/configuration",
severity: "warning",
message: "gateway.auth.token and gateway.auth.password are both configured while gateway.auth.mode is unset; auth selection is ambiguous.",
path: "gateway.auth.mode",
fixHint: "Set an explicit mode: `openclaw config set gateway.auth.mode token` or `... password`."
});
return t;
}
};
const commandOwnerCheck = {
id: "core/doctor/command-owner",
description: "An owner account is configured for owner-only commands.",
async detect(e) {
if (hasConfiguredCommandOwners(e.cfg)) return [];
return [{
checkId: "core/doctor/command-owner",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/tools/slash-commands",
severity: "info",
message: "No command owner is configured. Owner-only commands (/diagnostics, /export-trajectory, /config, exec approvals) have no allowed sender.",
path: "commands.ownerAllowFrom",
fixHint: "Set commands.ownerAllowFrom to your channel user id, e.g. `openclaw config set commands.ownerAllowFrom '[\"telegram:123456789\"]'`."
}];
}
};
const skillWorkshopToolPolicyCheck = {
id: SKILL_WORKSHOP_TOOL_POLICY_CHECK_ID,
description: "Autonomous Skill Workshop capture has a callable review tool.",
async detect(e) {
const t = resolveSkillWorkshopConfig(e.cfg).autonomous.mode !== "off";
const n = listAgentIds(e.cfg);
return (n.length > 0 ? n : [void 0]).flatMap((n) => {
const r = detectSkillWorkshopToolPolicyDiagnostic({
config: e.cfg,
workshopEnabled: t,
...n ? { agentId: n } : {}
});
return r ? [r] : [];
}).map((e) => ({
checkId: SKILL_WORKSHOP_TOOL_POLICY_CHECK_ID,
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/tools/skill-workshop",
severity: "warning",
message: e.detail,
path: e.source,
target: e.agentId,
requirement: "Autonomous Skill Workshop review requires the skill_workshop tool.",
fixHint: e.fix
}));
}
};
const gatewayAuthCheck = {
id: "core/doctor/gateway-auth",
description: "Local Gateway auth mode has a usable token or another explicit auth mode.",
detect: detectGatewayAuthHealth
};
const hooksModelCheck = {
id: "core/doctor/hooks-model",
description: "hooks.gmail.model resolves to an allowed catalog model.",
async detect(e) {
const { collectHooksModelIssues: t } = await import("./doctor-hooks-model-o2TDmMwH.mjs");
return (await t(e.cfg)).map(({ kind: e, model: t }) => {
return {
checkId: "core/doctor/hooks-model",
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/automation/cron-jobs/gmail",
severity: "warning",
path: "hooks.gmail.model",
message: e === "unresolved" ? `hooks.gmail.model "${t}" could not be resolved.` : e === "not-allowed" ? `hooks.gmail.model "${t}" is not allowed by agents.defaults.modelPolicy.allow.` : `hooks.gmail.model "${t}" is not in the model catalog.`,
fixHint: e === "not-allowed" ? "Add the model or its provider wildcard to agents.defaults.modelPolicy.allow, or remove hooks.gmail.model." : "Run `openclaw models list` and set hooks.gmail.model to a configured provider/model, or remove the override to use the agent default."
};
});
}
};
const legacyStateCheck = {
id: "core/doctor/legacy-state",
description: "Legacy sessions, agent state, and channel auth paths have been migrated.",
defaultEnabled: false,
async detect(e) {
const { detectLegacyStateMigrations: t } = await import("./state-migrations.doctor-CODMy_h9.mjs");
const { prepareLegacySessionSurfaces: n } = await import("./legacy-session-surfaces-D1Fxqfg5.mjs");
const r = n({ config: e.cfg });
const i = await t({
cfg: e.cfg,
doctorOnlyStateMigrations: true,
legacySessionSurfaces: r
});
return [...i.preview.map((e) => ({
checkId: "core/doctor/legacy-state",
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/cli/doctor/state-migrations",
severity: "warning",
message: e.replace(/^- /, ""),
path: i.stateDir,
fixHint: "Run `openclaw doctor --fix` to migrate legacy state."
})), ...i.warnings.map((e) => ({
checkId: "core/doctor/legacy-state",
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/cli/doctor/state-migrations",
severity: "warning",
message: e,
path: i.stateDir,
fixHint: "Resolve the warning, then rerun `openclaw doctor --fix`."
}))];
}
};
function noteTextToFinding(e) {
const t = e.text.split("\n");
const n = (t[0] ?? e.text).replace(/^- /, "").trim();
const r = t.slice(1).join("\n");
return {
checkId: e.checkId,
severity: e.severity,
...e.category ? { category: e.category } : {},
...e.docsUrl ? { docsUrl: e.docsUrl } : {},
message: n,
...e.target ? { target: e.target } : {},
...r ? { fixHint: r } : {}
};
}
function inferCapturedNoteSeverity(e) {
if (e.includes("CRITICAL")) return "error";
return [
"- Fix:",
"unavailable",
"not found",
"missing",
"not readable",
"not writable",
"readonly"
].some((t) => e.includes(t)) ? "warning" : "info";
}
function createNoteCollector(e) {
const t = [];
return {
findings: t,
noteFn(n) {
const r = noteMessageToText(n);
if (!r.trim()) return;
const i = inferCapturedNoteSeverity(r);
if (i === "info") return;
t.push(noteTextToFinding({
checkId: e,
severity: i,
text: r
}));
}
};
}
function noteMessageToText(e) {
if (e instanceof Error) return e.message;
if (e == null) return "";
if (typeof e === "string") return e;
if (typeof e === "number" || typeof e === "boolean" || typeof e === "bigint") return String(e);
try {
return JSON.stringify(e) ?? "";
} catch {
return "";
}
}
const claudeCliCheck = {
id: "core/doctor/claude-cli",
description: "Claude CLI readiness is captured as structured findings.",
async detect(e) {
const { noteClaudeCliHealth: t } = await import("./doctor-claude-cli-WPhqaCWp.mjs");
const n = createNoteCollector("core/doctor/claude-cli");
t(e.cfg, {
noteFn: n.noteFn,
...e.cwd ? { workspaceDir: e.cwd } : {}
});
return n.findings;
}
};
const openAIOAuthTlsCheck = {
id: "core/doctor/oauth-tls",
description: "OpenAI OAuth TLS prerequisites are satisfied before browser auth.",
async detect(e) {
const { formatOpenAIOAuthTlsPreflightFix: t, runOpenAIOAuthTlsPreflight: n, shouldRunOpenAIOAuthTlsPrerequisites: r } = await import("./provider-openai-chatgpt-oauth-tls-BlRv-B31.mjs");
if (!r({
cfg: e.cfg,
deep: e.mode === "doctor"
})) return [];
const i = await n({ timeoutMs: 4e3 });
if (i.ok || i.kind !== "tls-cert") return [];
return [noteTextToFinding({
checkId: "core/doctor/oauth-tls",
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/help/troubleshooting",
severity: "warning",
text: t(i)
})];
}
};
const legacyWhatsAppCrontabCheck = {
id: "core/doctor/legacy-whatsapp-crontab",
description: "Legacy WhatsApp crontab health entries are detected as structured findings.",
defaultEnabled: false,
async detect() {
const { collectLegacyWhatsAppCrontabHealthWarning: e } = await import("./cron-DcmWmEzN.mjs");
const t = await e();
if (!t) return [];
return [noteTextToFinding({
checkId: "core/doctor/legacy-whatsapp-crontab",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/cli/doctor/checks",
severity: "warning",
text: t
})];
}
};
const legacyCronStoreCheck = {
id: "core/doctor/legacy-cron-store",
description: "Legacy cron store, run-log, and payload state is normalized.",
defaultEnabled: false,
async detect(e) {
const { collectLegacyCronStoreHealthFindings: t } = await import("./cron-DcmWmEzN.mjs");
return t({ cfg: e.cfg });
}
};
const staleRuntimeBuildCheck = {
id: "core/doctor/stale-runtime-build",
description: "The loaded runtime was built from the checkout's current commit.",
async detect() {
const { collectStaleRuntimeBuildFindings: e } = await import("./doctor-stale-runtime-build-Dvl4JEMy.mjs");
return e();
}
};
const codexSessionRoutesCheck = {
id: CODEX_SESSION_ROUTES_CHECK_ID,
description: "Codex runtime routes are compatible with the configured plugin harness.",
async detect(e) {
const t = collectDisabledCodexPluginRouteIssues(e.cfg, e.env).map((e) => ({
checkId: CODEX_SESSION_ROUTES_CHECK_ID,
severity: "warning",
message: [`${e.path} routes ${e.modelRef} to ${e.canonicalModel}`, "with Codex runtime, but the Codex plugin is disabled by config."].join(" "),
path: e.path,
target: e.canonicalModel,
requirement: "Codex plugin enabled for routes that use the Codex runtime.",
fixHint: e.repairBlocked ? ["Enable plugins.entries.codex and plugin loading, and remove codex from plugins.deny;", "or set the affected OpenAI models to an OpenClaw runtime policy."].join(" ") : ["Run `openclaw doctor --fix`: it enables plugins.entries.codex,", "or set the affected OpenAI models to an OpenClaw runtime policy."].join(" ")
}));
const n = collectCodexRuntimeCompatibilityWarnings(e.cfg, e.env).map((e) => noteTextToFinding({
checkId: CODEX_SESSION_ROUTES_CHECK_ID,
severity: "warning",
text: e
}));
return [...t, ...n];
}
};
const telegramGeneralTopicConversationsCheck = {
id: TELEGRAM_GENERAL_TOPIC_CONVERSATIONS_CHECK_ID,
description: "Telegram General-topic conversation bindings use the chat target.",
async detect(e) {
const { detectTelegramGeneralTopicConversationRepairs: t } = await import("./doctor-telegram-general-topic-conversations-B-sIwPSo.mjs");
return t({
cfg: e.cfg,
...e.env ? { env: e.env } : {}
}).map((e) => ({
checkId: TELEGRAM_GENERAL_TOPIC_CONVERSATIONS_CHECK_ID,
category: "fix-now",
docsUrl: "https://docs.openclaw.ai/channels/telegram",
severity: "warning",
message: `Agent ${e.agentId} has a stale Telegram General-topic conversation identity.`,
target: e.agentId,
requirement: "One chat-scoped conversation binding for Telegram General topic.",
fixHint: "Run `openclaw doctor --fix` to merge the stale topic-qualified identity."
}));
},
async repair(e) {
const { repairTelegramGeneralTopicConversations: t } = await import("./doctor-telegram-general-topic-conversations-B-sIwPSo.mjs");
const n = {
kind: "state",
action: e.dryRun ? "would-merge-stale-bindings" : "merge-stale-bindings",
target: "Telegram General topic conversations",
dryRunSafe: false
};
if (e.dryRun) return {
changes: ["Would merge stale Telegram General-topic identities."],
effects: [n]
};
const r = await t({
cfg: e.cfg,
...e.env ? { env: e.env } : {}
});
return {
changes: [`Merged ${r} stale Telegram General-topic conversation identity row(s).`],
effects: r > 0 ? [n] : []
};
}
};
const gatewayPlatformNotesCheck = {
id: "core/doctor/gateway-services/platform-notes",
description: "Gateway platform notes are captured as structured findings.",
async detect(e) {
if (!isDefaultInstallIdentity(process.env)) return [];
const { collectGatewayPlatformWarnings: t } = await import("./doctor-platform-notes-D5JnL-um.mjs");
return (await t(e.cfg)).map((e) => noteTextToFinding({
checkId: "core/doctor/gateway-services/platform-notes",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/cli/doctor/recovery",
severity: "warning",
text: e
}));
}
};
const nodeRuntimeCheck = {
id: "core/doctor/node-runtime",
description: "Node SQLite capabilities and version support are represented as structured findings.",
async detect(e) {
const { collectNodeRuntimeFindings: t } = await import("./node-runtime-diagnostics-C4MzJK1U.mjs");
return t(e.env);
}
};
const browserCheck = {
id: "core/doctor/browser",
description: "Browser readiness is captured as structured findings.",
async detect(e) {
return await collectBrowserReadinessFindings(e.cfg);
},
async repair(e) {
if (e.dryRun === true) return {
status: "skipped",
reason: "native-host repair requires filesystem writes",
changes: []
};
const t = await maybeRepairOwnedChromeExtensionNativeHosts();
return {
...t.status ? {
status: t.status,
reason: t.reason
} : t.changes.length === 0 && t.warnings.length > 0 ? {
status: "failed",
reason: t.warnings.join("; ")
} : {},
changes: t.changes,
warnings: t.warnings
};
}
};
async function detectSkillsReadiness(e) {
const { runWithPluginMetadataSnapshot: t } = e;
const detect = async () => {
if (!e.cwd) return [];
const { detectUnavailableSkills: t } = await import("./doctor-core-checks.runtime.js");
return t(e.cfg, e.cwd);
};
if (!t) return await detect();
return await t({
config: e.cfg,
workspaceDir: e.cwd
}, detect);
}
const skillsReadinessCheck = {
id: "core/doctor/skills-readiness",
description: "Allowed skills are usable in the current runtime environment.",
defaultEnabled: false,
async detect(e, t) {
return filterUnavailableSkillsForScope(await detectSkillsReadiness(e), t?.paths).map(unavailableSkillToFinding);
},
async repair(e, t) {
const n = filterUnavailableSkillsForScope(await detectSkillsReadiness(e), t.map((e) => e.path));
if (n.length === 0) return { changes: [] };
return {
config: disableUnavailableSkillsInConfig(e.cfg, n),
changes: n.map((e) => `Disabled unavailable skill ${e.name}.`),
effects: n.map((t) => ({
kind: "config",
action: e.dryRun === true ? "would-disable-skill" : "disable-skill",
target: skillReadinessPath(t),
dryRunSafe: true
}))
};
}
};
function unavailableSkillToFinding(e) {
return {
checkId: "core/doctor/skills-readiness",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/tools/skills",
severity: "warning",
message: `${e.name} is allowed but unavailable: ${formatMissingSkillSummary(e)}.`,
path: skillReadinessPath(e),
fixHint: "Install/configure the missing requirement, or run `openclaw doctor --fix` to disable unused unavailable skills."
};
}
function filterUnavailableSkillsForScope(e, t) {
const n = new Set(t?.filter((e) => e !== void 0) ?? []);
if (n.size === 0) return [...e];
return e.filter((e) => n.has(skillReadinessPath(e)));
}
function skillReadinessPath(e) {
return `skills.entries.${e.skillKey}.enabled`;
}
const shellCompletionCheck = {
id: "core/doctor/shell-completion",
description: "Shell completion uses the cached completion path when configured.",
async detect() {
return shellCompletionStatusToHealthFindings(await checkShellCompletionStatus());
},
repair: legacyOwnedRepair(async () => {
return shellCompletionStatusToRepairEffects(await checkShellCompletionStatus());
}, "legacy doctor shell-completion repair owns real mutations")
};
const uiProtocolFreshnessCheck = {
id: "core/doctor/ui-protocol-freshness",
description: "Control UI assets are present and current with the Gateway protocol schema.",
async detect() {
return (await detectUiProtocolFreshnessIssues()).map(uiProtocolFreshnessIssueToHealthFinding);
},
repair: legacyOwnedRepair(async () => {
return (await detectUiProtocolFreshnessIssues()).flatMap(uiProtocolFreshnessIssueToRepairEffects);
}, "legacy doctor UI freshness repair owns real mutations")
};
const workspaceSuggestionsCheck = {
id: "core/doctor/workspace-suggestions",
description: "Workspace backup and memory-system suggestions are captured as structured findings.",
defaultEnabled: false,
async detect(e) {
const t = resolveDoctorWorkspaceSuggestionScopes(e.cfg);
const { collectWorkspaceSuggestionNotes: n } = await import("./doctor-workspace-suggestions-CjWcstdm.mjs");
return (await Promise.all(t.map(async ({ agentId: e, workspaceDir: t, labelAgent: r }) => {
const i = r ? `Agent "${e}": ` : "";
const a = [];
for await (const e of n(t)) a.push(e);
return a.map((t) => noteTextToFinding({
checkId: "core/doctor/workspace-suggestions",
category: "recommended",
docsUrl: "https://docs.openclaw.ai/concepts/agent-workspace",
severity: "info",
text: `${i}${t}`,
...r ? { target: e } : {}
}));
}))).flat();
}
};
function createCoreHealthChecks() {
return [
gatewayConfigCheck,
claudeCliCheck,
gatewayAuthCheck,
legacyStateCheck,
removedWorkspacesStateCheck,
legacyWhatsAppCrontabCheck,
legacyCronStoreCheck,
staleRuntimeBuildCheck,
codexSessionRoutesCheck,
telegramGeneralTopicConversationsCheck,
shellCompletionCheck,
uiProtocolFreshnessCheck,
gatewayServicesExtraCheck,
gatewayPlatformNotesCheck,
{
id: GATEWAY_HEALTH_CHECK_ID,
description: "Authenticated Gateway health and degraded secret owners are structured findings.",
defaultEnabled: false,
async detect(e) {
const { collectGatewayHealthFindings: t } = await import("./doctor-gateway-health-DptzvbmT.mjs");
return t(e);
}
},
{
id: GATEWAY_DAEMON_CHECK_ID,
description: "Local Gateway daemon service state is represented as structured findings.",
defaultEnabled: false,
async detect(e) {
const { collectGatewayDaemonFindings: t } = await import("./doctor-core-checks.runtime.js");
return t(e);
}
},
nodeRuntimeCheck,
{
id: "core/doctor/runtime-capabilities",
description: "Report capabilities of the Doctor process without executing optional features.",
async detect() {
const { collectRuntimeCapabilities: e, formatRuntimeCapabilities: t } = await import("./runtime-capabilities-DEj69bmH.mjs");
return [{
checkId: "core/doctor/runtime-capabilities",
severity: "info",
source: "doctor-process",
message: `Runtime capabilities (Doctor process)\n${t(e())}`
}];
}
},
{
id: "core/doctor/security",
updateReadiness: "post-plugin",
description: "Security posture checks produce structured findings.",
async detect(e) {
const { collectSecurityWarnings: t } = await import("./doctor-security-CBz4iSug.mjs");
return (await t(e.cfg, e.env)).map(securityAuditFindingToHealthFinding);
}
},
browserCheck,
openAIOAuthTlsCheck,
hooksModelCheck,
bootstrapSizeCheck,
modelReferenceCheck,
acpAgentModelCheck,
legacyOutputCapCheck,
{
id: "core/doctor/provider-catalog-projection",
description: "Provider catalog hooks project into unified text model catalog rows.",
async detect(e) {
const { collectProviderCatalogProjectionFindings: t } = await import("./doctor-core-checks.runtime.js");
return t(e.cfg, e.cwd);
}
},
{
id: "core/doctor/local-audio-acceleration",
description: "Local STT auto-selection and acceleration evidence are visible.",
async detect() {
const { collectLocalAudioAccelerationFindings: e } = await import("./doctor-core-checks.runtime.js");
return e();
}
},
runtimeToolSchemaCheck,
workspaceSuggestionsCheck,
skillWorkshopToolPolicyCheck,
commandOwnerCheck,
skillsReadinessCheck,
finalConfigValidationCheck
].map((e) => Object.assign({}, e, {
kind: "core",
source: "doctor"
}));
}
const CORE_HEALTH_CHECKS = createCoreHealthChecks();
//#endregion
export { createCoreHealthChecks as n, CORE_HEALTH_CHECKS as t };