openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
280 lines (279 loc) • 12.5 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { O as tryResolveAmbientOwnerAgentId, a as resolveAgentDir, f as resolveAgentWorkspaceDir, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs";
import { a as resolveMergedModelProviderConfig } from "./model-provider-config-Bbah_2ON.mjs";
import { i as resolveSessionAuthProfileOverrideSource } from "./auth-profile-override-provenance-B7WULxR7.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as captureRuntimeConfig } from "./runtime-source-projection-DTwMWCo9.mjs";
import { d as isConfiguredKeyAuthSource } from "./provider-model-route-auth-dD2KD9io.mjs";
import { o as resolveProviderModelAuthPolicy, r as resolveModelRuntimePolicy } from "./model-runtime-policy-Cfudvy7O.mjs";
import { t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { n as isStoredCredentialCompatibleWithAuthProvider, o as resolveAuthProfileOrderWithMetadata } from "./order-jOvee2J6.mjs";
import { a as isCliRuntimeProvider, c as resolveCliRuntimeExecutionProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { i as resolveSessionRuntimeOverrideForProvider } from "./session-runtime-compat-C_CO9LR_.mjs";
import { i as hasSyntheticLocalProviderAuthConfig, v as resolveProviderEntryApiKeyProfileReference } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { g as loadAuthProfileStoreWithoutExternalProfilesAsync } from "./store-runtime-dW0pXLJI.mjs";
import { i as tryResolveCronJobEffectiveAgentId } from "./agent-id-CX8HtxAT.mjs";
import { t as resolveCronAgentSessionKey } from "./session-key-BQPSZVRH.mjs";
import { i as isInvalidCronSessionTargetIdError, r as isDetachedCronSessionTarget, s as resolveCronSessionTargetSessionKey } from "./session-target-C-4MLah6.mjs";
import { o as resolveProviderAuthProfileId } from "./provider-hook-runtime-CNiG8a3j.mjs";
import "./provider-runtime-BddjXkmv.mjs";
import { t as normalizeCronJobCreate } from "./normalize-DLzfR3Jc.mjs";
import { a as repairCronInferenceBindingsForDoctor, r as inspectCronJobsForDoctor } from "./store-repair-Dv1WdfLr.mjs";
import { r as prepareAgentRuntimeAuth } from "./prepare-auth-Ck7RPVAG.mjs";
import { t as resolveCronModelSelection } from "./model-selection-BZhMpZwE.mjs";
import { t as captureAuthProfileAuthorization } from "./authorization-BCfvcvWl.mjs";
import { n as prepareCronSession } from "./session-Wmk7eSa1.mjs";
//#region src/commands/doctor/cron/inference-binding-migration.ts
/** Adopt a current, unambiguous account once; never reinterpret run telemetry as authority. */
async function maybeRepairCronInferenceBindings(e) {
const t = e.env ?? process.env;
const n = [];
const r = [];
const i = [];
const a = [];
const o = /* @__PURE__ */ new Map();
const captureConfig = (e) => {
let t = o.get(e);
if (!t) {
t = captureRuntimeConfig(e);
o.set(e, t);
}
return t;
};
try {
const o = getOpenClawDatabaseMaintenanceScope();
if (e.shouldRepair && !o?.ownsSchemaMaintenance) throw new Error("Inference account migration requires offline Doctor maintenance.");
const s = await inspectCronJobsForDoctor({ env: t });
for (const o of s.jobs) {
const s = o.definition;
if (!s || o.invalidReason || s.inferenceBinding !== void 0 || s.runtimeAuthority !== void 0 || s.runtimeAuthorityRecoveryRequired) continue;
let c;
const l = `${normalizeOptionalString(s.name) ?? o.id} (${o.id})`;
try {
const u = normalizeCronJobCreate(s);
if (!u || u.payload.kind !== "agentTurn" || u.sessionTarget === "main") continue;
c = u.payload.model;
const d = tryResolveCronJobEffectiveAgentId(u, tryResolveAmbientOwnerAgentId(e.cfg));
if (!d || !resolveAgentConfig(e.cfg, d)) throw new Error("Select the job's execution agent before adopting an inference account.");
const f = captureConfig(e.cfg);
const p = resolveCronSessionTargetSessionKey(u.sessionTarget) ?? `cron:${o.id}`;
const m = resolveCronAgentSessionKey({
cfg: f,
agentId: d,
sessionKey: p
});
const h = u.sessionTarget === "current" && u.sessionKey ? resolveCronAgentSessionKey({
cfg: f,
agentId: d,
sessionKey: u.sessionKey
}) : void 0;
const g = await prepareCronSession({
cfg: f,
agentId: d,
sessionKey: m,
sourceSessionKey: h,
forceNew: isDetachedCronSessionTarget(u.sessionTarget),
exactRunSession: true,
nowMs: Date.now()
});
if (g.initialSessionEntry?.modelSelectionLocked === true) {
n.push(`Automation ${l}: its session is owned by a native runtime; no host inference account was adopted. Recover ownership through that runtime before changing this job.`);
continue;
}
const _ = await resolveCronModelSelection({
cfg: f,
agentId: d,
agentDir: resolveAgentDir(f, d),
workspaceDir: resolveAgentWorkspaceDir(f, d),
agentConfigOverride: resolveAgentConfig(f, d),
sessionEntry: g.sessionEntry,
payloadModel: u.payload.model,
isGmailHook: u.payload.externalContentSource === "gmail"
});
if (!_.ok) throw new Error(_.error);
c = `${_.provider}/${_.model}`;
const v = captureConfig(_.owner.config);
if (isCliRuntimeProvider(_.provider, { config: v }) || resolveCliRuntimeExecutionProvider({
cfg: v,
agentId: d,
provider: _.provider,
modelId: _.model
})) continue;
const y = resolveSessionRuntimeOverrideForProvider({
cfg: v,
provider: _.provider,
entry: g.sessionEntry
}) ?? resolveModelRuntimePolicy({
config: v,
agentId: d,
provider: _.provider,
modelId: _.model
}).policy?.id;
if (y && y !== "openclaw" && y !== "auto") {
n.push(`Automation ${l}: runtime ${y} inference ownership was left unchanged; no host account was adopted. Use that runtime's account/recovery flow if this job needs adoption.`);
continue;
}
const b = await loadAuthProfileStoreWithoutExternalProfilesAsync(_.owner.agentDir);
const x = resolveSessionAuthProfileOverrideSource(g.sessionEntry);
const S = g.sessionEntry.authProfileOverride;
const C = S ? b.profiles[S] : void 0;
const w = !C || isStoredCredentialCompatibleWithAuthProvider({
cfg: v,
provider: _.provider,
credential: C
});
let T = _.configuredProfileId ?? ((x === "user" || x === "user-link") && w ? S : void 0);
const E = Boolean(T);
const D = prepareAgentRuntimeAuth({
config: v,
provider: _.provider,
modelId: _.model,
agentId: d,
agentDir: _.owner.agentDir,
workspaceDir: _.owner.workspaceDir,
authProfileStore: {
...b,
usageStats: Object.fromEntries(Object.entries(b.usageStats ?? {}).map(([e, { cooldownUntil: t, cooldownReason: n, cooldownModel: r, ...i }]) => [e, i]))
},
sessionAuthProfileId: T,
sessionAuthProfileSource: T ? "user" : void 0,
...T ? {
requiredAuthProfileId: T,
allowAuthProfileFallback: false
} : {},
resolveProviderPreferredProfileId: (e) => resolveProviderAuthProfileId({
provider: _.provider,
config: v,
workspaceDir: _.owner.workspaceDir,
env: t,
context: e
})
});
const O = D.attempts[0]?.plan.credentialSource;
if (isConfiguredKeyAuthSource(O)) continue;
if (O?.kind === "direct") throw new Error("The current route uses an ambient credential, not a durable stored account.");
if (!T) {
const e = resolveProviderEntryApiKeyProfileReference({
cfg: v,
provider: _.provider,
store: b
});
const t = D.attempts[0];
if (e.kind === "profile" && t?.kind === "profile" && t.profileId === e.profileId) T = e.profileId;
}
const k = T ? [T] : resolveAuthProfileOrderWithMetadata({
cfg: v,
store: b,
provider: _.provider,
forModel: _.model,
readinessMode: "read-only",
includePendingOAuthRefresh: true
}).profileIds;
const A = [];
for (const e of k) try {
const [t] = prepareAgentRuntimeAuth({
config: v,
provider: _.provider,
modelId: _.model,
agentId: d,
agentDir: _.owner.agentDir,
workspaceDir: _.owner.workspaceDir,
authProfileStore: b,
requiredAuthProfileId: e,
allowAuthProfileFallback: false
}).attempts;
const n = b.profiles[e];
const r = t?.plan.modelRoute?.authRequirement ?? (n && resolveProviderModelAuthPolicy({
provider: _.provider,
mode: n.type,
authFlow: n.type === "oauth" ? n.authFlow : void 0
}).authRequirement);
if (t?.kind === "profile" && t.profileId === e && r) A.push({
profileId: e,
authRequirement: r
});
} catch (e) {
if (T) throw e;
}
if (A.length === 0 && !T) {
if (prepareAgentRuntimeAuth({
config: v,
provider: _.provider,
modelId: _.model,
agentId: d,
agentDir: _.owner.agentDir,
authProfileStore: b
}).attempts.every(({ plan: e }) => e.credentialSource?.kind === "direct" && e.credentialSource.evidence === "synthetic") || hasSyntheticLocalProviderAuthConfig({
cfg: v,
provider: _.provider,
route: resolveMergedModelProviderConfig(v, _.provider)
})) continue;
}
const j = D.attempts[0]?.kind === "profile" ? D.attempts[0].profileId : void 0;
const M = A.length === 1 ? A[0] : T ? void 0 : A.find((e) => e.profileId === j);
if (!M) throw new Error(A.length > 1 ? `More than one inference account is eligible: ${A.map((e) => e.profileId).join(", ")}.` : "No available stored inference account can be retained.");
const N = A.filter((e) => e.profileId !== M.profileId).map((e) => e.profileId);
if (isUserModelAuthProfileId(M.profileId)) throw new Error("A personal inference account requires explicit adoption by its authorized owner.");
const P = `Automation ${l}: retain ${M.profileId} for ${c}; model/default/fallback selections stay unchanged.${N.length > 0 ? ` Also eligible: ${N.join(", ")}; to change, run openclaw automations edit ${quoteCliArg(o.id)} --model ${quoteCliArg(`${c}@<profileId>`)}.` : ""}`;
if (!e.shouldRepair) {
n.push(`${P} Its runs are refused until it records this account. Run openclaw doctor --fix to record it.`);
continue;
}
const F = await captureAuthProfileAuthorization({
profileId: M.profileId,
agentDir: _.owner.agentDir,
cfg: v,
assertCurrent() {}
});
r.push(F);
F.assertCurrent();
i.push({
job: o,
binding: {
version: 1,
provider: _.provider,
profileId: M.profileId,
authorizationId: F.authorizationId,
authRequirement: M.authRequirement,
source: E ? "user" : D.plan.forwardedAuthProfileSource ?? "auto"
}
});
a.push(P);
} catch (e) {
const t = isInvalidCronSessionTargetIdError(e) ? `Repair its session target with openclaw automations edit ${quoteCliArg(o.id)} --session <target>, then retry Doctor.` : `Explicitly adopt the intended stored account with openclaw automations edit ${quoteCliArg(o.id)} --model ${quoteCliArg(`${c ?? "<provider/model>"}@<profileId>`)}.`;
n.push(`Automation ${l}: inference account was not migrated: ${formatErrorMessage(e)} ${t}`);
}
}
if (i.length === 0) return {
changes: [],
warnings: n
};
if (!o?.ownsSchemaMaintenance) throw new Error("Inference account migration requires offline Doctor maintenance.");
const assertCurrent = () => {
o.assertDatabaseAccess(resolveOpenClawStateSqlitePath(t));
for (const e of r) e.assertCurrent();
};
const c = await repairCronInferenceBindingsForDoctor({ env: t }, {
assertCurrent,
assertOwnedInTransaction: assertCurrent
}, s, i);
return {
changes: [...a, `Saved pre-repair cron backup: ${c.backupPath}`],
warnings: n
};
} catch (e) {
return {
changes: [],
warnings: [...n, `Cron inference account migration was not committed: ${formatErrorMessage(e)}`]
};
} finally {
for (const e of r) e.dispose();
}
}
//#endregion
export { maybeRepairCronInferenceBindings };