openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
364 lines (363 loc) • 20.3 kB
JavaScript
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs";
import { n as inheritOptionFromParent } from "./command-options-D76J8Wl7.mjs";
import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs";
import { n as isModelsStatusJsonOutput } from "./models-output-mode-DpMdNIya.mjs";
import { t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs";
import { n as setCommandJsonMode } from "./json-mode-DF5JGxtm.mjs";
import { randomUUID } from "node:crypto";
//#region src/cli/models-cli.ts
function addAccountOptions(e) {
return e.option("--url <url>", "Gateway WebSocket URL (defaults to the configured Gateway)").option("--port <port>", "Local Gateway port").option("--token-file <path>", "Read the Gateway token from a file").option("--password-file <path>", "Read the Gateway password from a file").option("--timeout <ms>", "Gateway connection and request timeout in ms", "30000").option("--json", "Output JSON", false);
}
async function withModelsRuntime(e) {
const t = await import("./models-cli.runtime.js");
return t.runModelsCommand(() => e(t));
}
function runAuthModelCommand(e, t, n) {
return withModelsRuntime(async ({ defaultRuntime: r, resolveModelAgentOption: i }) => {
const a = i(e);
const o = t(a);
if (e.name() === "login" || e.name() === "login-github-copilot") {
const t = e.opts();
const i = e.name() === "login-github-copilot";
const s = randomUUID();
const c = [
t.profileId?.trim() ? "--profile-id" : void 0,
t.force ? "--force" : void 0,
t.setDefault ? "--set-default" : void 0,
t.yes ? "--yes" : void 0
].filter(Boolean);
let l = false;
await runWithLocalStateOwner({
method: "models.authLogin",
params: async (e) => {
const { readGatewayLoginParams: n } = await import("./auth-login-gateway-BGH3IVEs.mjs");
return n({
provider: i ? "github-copilot" : t.provider,
method: i ? "device" : t.deviceCode ? "device-code" : t.method,
agent: a
}, s, e);
},
target: "system/agent provider sign-in",
requireLocalBackendSharedAuth: true,
requiredCapabilities: [GATEWAY_SERVER_CAPS.MODELS_AUTH_LOGIN_OWNER],
timeoutMs: 15e5,
onForeignOwner: c.length ? async () => {
throw new Error(`${c.join(", ")} cannot be represented by models.authLogin. Omit these options, or stop the Gateway through its service owner and rerun this command offline. No credential was changed.`);
} : void 0,
onGatewayResponse: async (e, t) => {
const { runGatewayLoginWizard: n } = await import("./auth-login-gateway-BGH3IVEs.mjs");
await n(e, s, t, r);
},
onGatewaySignalAbort: async (e) => {
await e("wizard.cancel", {
sessionId: s,
closeInput: true
});
l = true;
},
runLocal: async () => {
await (await n())(o, r);
}
}).catch((e) => {
if (!l) throw e;
r.log("Login session closed. Credentials already saved were not undone.");
});
return;
}
const s = e.name() === "paste-api-key";
const { provider: c, profileId: l } = e.opts();
const u = await runWithLocalStateOwner({
method: s ? "models.authSetApiKey" : "models.auth",
params: s ? async (e) => {
const { readGatewayApiKeyParams: t } = await import("./auth-gateway-BDhkbHTb.mjs");
return t({
provider: c,
agent: a
}, e);
} : {},
target: e.name() === "paste-token" ? "token credentials (models.authSetApiKey cannot store token types or --expires-in)" : "system/agent credentials",
requireLocalBackendSharedAuth: s,
requiredCapabilities: s ? [GATEWAY_SERVER_CAPS.MODELS_AUTH_SET_API_KEY_OWNER] : void 0,
onForeignOwner: !s ? "refuse" : l?.trim() ? async () => {
throw new Error("--profile-id is not supported by models.authSetApiKey. Omit --profile-id to use the Gateway's API-key profile, or stop the Gateway through its service owner and rerun this command.");
} : void 0,
runLocal: async () => {
await (await n())(o, r);
}
});
if (u) {
if (u.warning) r.error(sanitizeTerminalText(u.warning));
r.log(`Auth profile: ${sanitizeTerminalText(u.profileId)} (${sanitizeTerminalText(u.provider)}/api_key)`);
}
});
}
/** Run a command that edits global defaults, rejecting the inherited `models --agent`. */
async function withGlobalModelsRuntime(e, t, n) {
return withModelsRuntime(async (r) => {
r.rejectAgentScopedModelCommand(e, t);
await n(r);
});
}
function registerModelsCli(e) {
const t = e.command("models").description("Model discovery, scanning, and configuration").option("--json", "Output JSON (alias for `models status --json`)", false).option("--status-json", "Output JSON (alias for `models status --json`)", false).option("--status-plain", "Plain output (alias for `models status --plain`)", false).option("--agent <id>", "Agent id to inspect (overrides OPENCLAW_AGENT_DIR)").addHelpText("after", () => formatDocsHelp("/cli/models"));
const hasJsonOutput = (e) => Boolean(e?.json || t.opts().json);
setCommandJsonMode(t, "output", ({ argv: e, command: t }) => isModelsStatusJsonOutput(e, t));
const n = addAccountOptions(t.command("accounts").description("Manage your personal model accounts on the Gateway")).addHelpText("after", "\nPersonal accounts belong to your signed-in person, not an agent. New sessions use the selected default; existing sessions keep their account. Shared credentials remain under `models auth`.\n");
n.action(() => n.help());
const run = async (e, t) => {
const n = await import("./models-cli.runtime.js");
await n.runModelsCommand(async () => {
if (n.resolveModelAgentOption(e) !== void 0) throw new Error("`models accounts` does not support --agent; it uses your signed-in Gateway person.");
const r = await import("./accounts-C1M9wpQg.mjs");
const i = e.opts();
const resolve = (t) => inheritOptionFromParent(e, t) ?? i[t];
await t(r, n, {
url: resolve("url"),
port: resolve("port"),
tokenFile: resolve("tokenFile"),
passwordFile: resolve("passwordFile"),
timeout: resolve("timeout"),
json: resolve("json")
});
});
};
addAccountOptions(n.command("list").description("List one page of your saved accounts")).option("--cursor <cursor>", "Continue from nextCursor in the previous page").action(async (e, t) => {
await run(t, (t, n, r) => t.modelsAccountsListCommand({
...r,
cursor: e.cursor
}, n.defaultRuntime));
});
addAccountOptions(n.command("login [provider]").description("Add a personal account using this Gateway's provider and sign-in methods")).option("--method <id>", "Choose a sign-in method instead of prompting").action(async (e, t, n) => {
await run(n, (n, r, i) => n.modelsAccountsLoginCommand({
...i,
provider: e,
method: t.method
}, r.defaultRuntime));
});
for (const [e, t, r] of [[
"use",
"account-id",
"Select one of your accounts for new sessions"
], [
"clear-default",
"provider",
"Clear a personal default without deleting credentials or changing existing sessions"
]]) addAccountOptions(n.command(`${e} <${t}>`).description(r)).action(async (t, n, r) => {
await run(r, (n, r, i) => n.modelsAccountsUpdateDefaultCommand({
...i,
...e === "use" ? {
action: e,
authProfileId: t
} : {
action: e,
provider: t
}
}, r.defaultRuntime));
});
t.command("list").description("List models (configured by default)").option("--refresh", "Refresh provider discovery before listing", false).option("--all", "Show full model catalog", false).option("--local", "Filter to local models", false).option("--provider <id>", "Filter by provider id").option("--agent <id>", "Agent id to inspect (overrides OPENCLAW_AGENT_DIR)").option("--json", "Output JSON", false).option("--plain", "Plain line output", false).action(async (e, t) => {
await withModelsRuntime(async ({ defaultRuntime: n, resolveModelAgentOption: r }) => {
const { modelsListCommand: i } = await import("./list.list-command-DE-fXf__.mjs");
await i({
...e,
json: hasJsonOutput(e),
agent: r(t)
}, n);
});
});
t.command("status").description("Show configured model state").option("--json", "Output JSON", false).option("--plain", "Plain output", false).option("--check", "Check auth/runtime readiness (1=missing/expired/unavailable/incompatible/indeterminate, 2=expiring)", false).option("--probe", "Check configured provider auth (live)", false).option("--probe-provider <name>", "Only check a single provider").option("--probe-profile <id>", "Only check specific auth profile ids (repeat or comma-separated)", (e, t) => {
const n = Array.isArray(t) ? t : t ? [t] : [];
n.push(e);
return n;
}).option("--probe-timeout <ms>", "Timeout per check in ms").option("--probe-concurrency <n>", "Concurrent checks").option("--probe-max-tokens <n>", "Maximum tokens per check (best-effort)").option("--agent <id>", "Agent id to inspect (overrides OPENCLAW_AGENT_DIR)").action((e, t) => withModelsRuntime(async ({ defaultRuntime: n, resolveModelAgentOption: r }) => {
const i = r(t);
const { modelsStatusCommand: a } = await import("./list.status-command-B4_qkhZB.mjs");
await a({
...e,
json: hasJsonOutput(e),
agent: i
}, n);
}));
t.command("refresh").description("Refresh the hosted model catalog").option("--json", "Output JSON", false).action(async (e, t) => {
await withGlobalModelsRuntime(t, "refresh", async ({ defaultRuntime: t }) => {
const { modelsRefreshCommand: n } = await import("./refresh-BDubfh5y.mjs");
await n({ json: hasJsonOutput(e) }, t);
});
});
for (const [e, n, r] of [[
"set",
"Set the default model",
"model"
], [
"set-image",
"Set the image model",
"imageModel"
]]) t.command(e).description(n).argument("<model>", "Model id or alias").action(async (t, n, i) => {
await withGlobalModelsRuntime(i, e, async ({ defaultRuntime: e }) => {
const { modelsSetCommand: n } = await import("./set-De9zyyF1.mjs");
await n(t, e, r);
});
});
const r = t.command("aliases").description("Manage model aliases");
r.command("list").description("List model aliases").option("--json", "Output JSON", false).option("--plain", "Plain output", false).action(async (e, t) => {
await withGlobalModelsRuntime(t, "aliases list", async ({ defaultRuntime: t }) => {
const { modelsAliasesListCommand: n } = await import("./aliases-D4sPFl5Q.mjs");
await n({
...e,
json: hasJsonOutput(e)
}, t);
});
});
r.command("add").description("Add or update a model alias").argument("<alias>", "Alias name").argument("<model>", "Model id or alias").action(async (e, t, n, r) => {
await withGlobalModelsRuntime(r, "aliases add", async ({ defaultRuntime: n }) => {
const { modelsAliasesAddCommand: r } = await import("./aliases-D4sPFl5Q.mjs");
await r(e, t, n);
});
});
r.command("remove").description("Remove a model alias").argument("<alias>", "Alias name").action(async (e, t, n) => {
await withGlobalModelsRuntime(n, "aliases remove", async ({ defaultRuntime: t }) => {
const { modelsAliasesRemoveCommand: n } = await import("./aliases-D4sPFl5Q.mjs");
await n(e, t);
});
});
for (const e of [{
name: "fallbacks",
modelType: "model",
noun: "fallback",
article: "a",
key: "model",
label: "Fallbacks",
notFoundLabel: "Fallback",
clearedMessage: "Fallback list cleared."
}, {
name: "image-fallbacks",
modelType: "image model",
noun: "image fallback",
article: "an",
key: "imageModel",
label: "Image fallbacks",
notFoundLabel: "Image fallback",
clearedMessage: "Image fallback list cleared."
}]) {
const { name: n, modelType: r, noun: i, article: a } = e;
const o = t.command(n).description(`Manage ${r} fallback list`);
o.command("list").description(`List ${i} models`).option("--json", "Output JSON", false).option("--plain", "Plain output", false).action(async (t) => {
await withModelsRuntime(async ({ defaultRuntime: n }) => {
const { listFallbacksCommand: r } = await import("./fallbacks-shared-DXwFg4Xp.mjs");
await r(e, {
...t,
json: hasJsonOutput(t)
}, n);
});
});
for (const t of ["add", "remove"]) o.command(t).description(`${t === "add" ? "Add" : "Remove"} ${a} ${i} model`).argument("<model>", "Model id or alias").action(async (r, i, a) => {
await withGlobalModelsRuntime(a, `${n} ${t}`, async ({ defaultRuntime: n }) => {
const { changeFallbacksCommand: i } = await import("./fallbacks-shared-DXwFg4Xp.mjs");
await i({
...e,
action: t
}, r, n);
});
});
o.command("clear").description(`Clear all ${i} models`).action(async (t, r) => {
await withGlobalModelsRuntime(r, `${n} clear`, async ({ defaultRuntime: t }) => {
const { clearFallbacksCommand: n } = await import("./fallbacks-shared-DXwFg4Xp.mjs");
await n(e, t);
});
});
}
t.command("scan").description("Scan OpenRouter free models for tools + images").option("--min-params <b>", "Minimum parameter size (billions)").option("--max-age-days <days>", "Skip models older than N days").option("--provider <name>", "Filter by provider prefix").option("--max-candidates <n>", "Max fallback candidates", "6").option("--timeout <ms>", "Timeout per check in ms").option("--concurrency <n>", "Check concurrency").option("--no-probe", "Skip live checks; list free candidates only (writes no config)").option("--yes", "Accept defaults without prompting", false).option("--no-input", "Disable prompts (use defaults)").option("--set-default", "Also set agents.defaults.model primary to the first selection (fallbacks are replaced either way)", false).option("--set-image", "Also set agents.defaults.imageModel primary to the first image selection", false).option("--json", "Output JSON", false).action(async (e, t) => {
await withGlobalModelsRuntime(t, "scan", async ({ defaultRuntime: t }) => {
const { modelsScanCommand: n } = await import("./scan-BZWsICcb.mjs");
await n({
...e,
json: hasJsonOutput(e)
}, t);
});
});
t.action(async (e) => {
await withModelsRuntime(async ({ defaultRuntime: t }) => {
const { modelsStatusCommand: n } = await import("./list.status-command-B4_qkhZB.mjs");
await n({
json: Boolean(e?.json || e?.statusJson),
plain: Boolean(e?.statusPlain),
agent: e?.agent
}, t);
});
});
const i = t.command("auth").description("Manage system/agent credentials on this machine");
i.option("--agent <id>", "Agent id for auth commands");
i.action(() => {
i.help();
});
i.command("list").description("List saved auth profiles").option("--provider <id>", "Filter by provider id").option("--agent <id>", "Agent id (default: configured system agent)").option("--json", "Output JSON", false).action((e, t) => runAuthModelCommand(t, (t) => ({
...e,
agent: t,
json: hasJsonOutput(e)
}), async () => (await import("./auth-list-Dih8_q27.mjs")).modelsAuthListCommand));
i.command("add").description("Interactive auth helper (provider auth or paste token)").option("--agent <id>", "Agent id (default: configured default agent)").action((e, t) => runAuthModelCommand(t, (e) => ({ agent: e }), async () => (await import("./auth-eCQF7CRE.mjs")).modelsAuthAddCommand));
i.command("activate").description("Test a saved sign-in and use it for this agent").argument("<profileId>", "Saved sign-in id from models auth list").option("--agent <id>", "Agent id (default: the only configured agent)").action((e, t, n) => runAuthModelCommand(n, (t) => ({
profileId: e,
agent: t
}), async () => (await import("./auth-activate-Dr3iRRG2.mjs")).modelsAuthActivateCommand));
i.command("logout").description("Remove a saved auth profile (see `models auth list` for ids)").argument("<profileId>", "Auth profile id (e.g. openai:manual)").option("--agent <id>", "Agent id (default: configured default agent)").option("--yes", "Skip the confirmation prompt", false).action((e, t, n) => runAuthModelCommand(n, (n) => ({
...t,
profileId: e,
agent: n
}), async () => (await import("./auth-logout-B6kuM0jE.mjs")).modelsAuthLogoutCommand));
i.command("login").description("Sign in for system/agent use on this machine (OAuth/API key)").option("--agent <id>", "Agent id (default: configured default agent)").option("--provider <id>", "Provider id registered by a plugin").option("--method <id>", "Provider auth method id").option("--device-code", "Use the provider device-code auth method", false).option("--profile-id <id>", "Auth profile id override for single-profile login methods").option("--set-default", "Apply the provider's default model recommendation", false).option("--force", "Remove existing profiles for the provider before logging in (use when a cached OAuth profile is stuck or you want to switch accounts)", false).action(async ({ deviceCode: e, ...t }, n) => {
if (e && typeof t.method === "string" && t.method !== "device-code") throw new Error("--device-code cannot be combined with --method unless method is device-code.");
await runAuthModelCommand(n, (n) => ({
...t,
method: e ? "device-code" : t.method,
agent: n
}), async () => (await import("./auth-eCQF7CRE.mjs")).modelsAuthLoginCommand);
});
i.command("setup-token").description("Run a provider CLI to create/sync a token (TTY required)").option("--agent <id>", "Agent id (default: configured default agent)").option("--provider <name>", "Provider id").option("--yes", "Skip confirmation", false).action((e, t) => runAuthModelCommand(t, (t) => ({
...e,
agent: t
}), async () => (await import("./auth-eCQF7CRE.mjs")).modelsAuthSetupTokenCommand));
for (const [e, t, n, r] of [[
"paste-token",
"token",
"anthropic",
"modelsAuthPasteTokenCommand"
], [
"paste-api-key",
"API key",
"openai",
"modelsAuthPasteApiKeyCommand"
]]) {
const a = i.command(e).description(`Save ${e === "paste-token" ? "a" : "an"} ${t} in an auth profile and update config`).option("--agent <id>", "Agent id (default: configured default agent)").requiredOption("--provider <name>", `Provider id (e.g. ${n})`).option("--profile-id <id>", "Auth profile id (default: <provider>:manual)");
if (e === "paste-token") a.option("--expires-in <duration>", "Optional expiry duration (e.g. 365d, 12h). Stored as absolute expiresAt.");
a.action((e, t) => runAuthModelCommand(t, (t) => ({
...e,
agent: t
}), async () => (await import("./auth-eCQF7CRE.mjs"))[r]));
}
i.command("login-github-copilot").description("Login to GitHub Copilot via GitHub device flow (TTY required)").option("--agent <id>", "Agent id (default: configured default agent)").option("--yes", "Overwrite existing profile without prompting", false).action((e, t) => runAuthModelCommand(t, (t) => ({
...e,
provider: "github-copilot",
method: "device",
agent: t
}), async () => (await import("./auth-eCQF7CRE.mjs")).modelsAuthLoginCommand));
const a = i.command("order").description("Manage per-agent auth profile order overrides");
a.command("get").description("Show per-agent auth profile order override").requiredOption("--provider <name>", "Provider id (e.g. anthropic)").option("--agent <id>", "Agent id (default: configured system agent)").option("--json", "Output JSON", false).action((e, t) => runAuthModelCommand(t, (t) => ({
...e,
agent: t,
json: hasJsonOutput(e)
}), async () => (await import("./auth-order-D8lmDtog.mjs")).modelsAuthOrderGetCommand));
a.command("set").description("Set per-agent auth profile order override").requiredOption("--provider <name>", "Provider id (e.g. anthropic)").option("--agent <id>", "Agent id (default: configured default agent)").argument("<profileIds...>", "Auth profile ids (e.g. anthropic:default)").action((e, t, n) => runAuthModelCommand(n, (n) => ({
...t,
agent: n,
order: e
}), async () => (await import("./auth-order-D8lmDtog.mjs")).modelsAuthOrderUpdateCommand));
a.command("clear").description("Clear per-agent auth profile order override").requiredOption("--provider <name>", "Provider id (e.g. anthropic)").option("--agent <id>", "Agent id (default: configured default agent)").action((e, t) => runAuthModelCommand(t, (t) => ({
...e,
agent: t,
order: null
}), async () => (await import("./auth-order-D8lmDtog.mjs")).modelsAuthOrderUpdateCommand));
}
//#endregion
export { registerModelsCli, runAuthModelCommand };