openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
357 lines (356 loc) • 16.4 kB
JavaScript
import { l as normalizeOptionalString, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { n as resolveFilesystemPath } from "./home-dir-EKmgmdPG.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { a as captureAsyncWorkTracker, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { i as DEFAULT_PROVIDER } from "./defaults-BWyoTPqn.mjs";
import { l as normalizeThinkLevel, r as THINKING_LEVELS_HELP } from "./thinking.shared-jmDGV33r.mjs";
import { t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { d as normalizeMimeType, n as detectMime } from "./mime-D2wVBzpa.mjs";
import { t as collectTextContentBlocks } from "./content-blocks-DgfxPwgj.mjs";
import { a as providerSummaryText, i as formatEnvelopeForText, n as runCapabilityCommand, t as registerLocalProvidersCommand } from "./providers-command-D9EdIVJQ.mjs";
import { t as collectOption } from "./helpers-Cxs4nwgv.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
//#region src/cli/capability-cli/model.ts
const LOCAL_MODEL_RUN_SYSTEM_PROMPT = "You are a personal assistant running inside OpenClaw.";
const HEIC_MODEL_RUN_MIMES = /* @__PURE__ */ new Set([
"image/heic",
"image/heic-sequence",
"image/heif",
"image/heif-sequence"
]);
async function loadModelCatalogForInspection(e, t) {
const { resolveCapabilityProviderAgentId: n } = await import("./shared-CwcDzg1K.mjs");
const { readPreparedModelCatalog: r } = await import("./prepared-model-catalog-guV7T9CV.mjs");
return (await r({
config: e,
agentId: t === void 0 ? void 0 : n(e, t),
readOnly: true
})).toSorted((e, t) => e.provider.localeCompare(t.provider) || e.id.localeCompare(t.id));
}
async function buildModelProviders(e, t) {
const { providerHasGenericConfig: n } = await import("./shared-CwcDzg1K.mjs");
const { resolveModelRefOverride: r } = await import("./model-ref-override-DzIx1V0p.mjs");
const { resolveAgentEffectiveModelPrimary: i } = await import("./agent-scope-7S_X4gNj.mjs");
const { getProviderEnvVarsCore: a } = await import("./provider-env-vars-BkV4-5UO.mjs");
const o = await loadModelCatalogForInspection(e, t);
const s = r(i(e, t)).provider;
const c = /* @__PURE__ */ new Map();
for (const r of o) {
const i = c.get(r.provider) ?? {
provider: r.provider,
count: 0,
defaults: [],
available: true,
configured: n({
cfg: e,
providerId: r.provider,
agentId: t,
envVars: a(r.provider)
}),
selected: s === r.provider
};
i.count += 1;
if (i.defaults.length < 3) i.defaults.push(r.id);
c.set(r.provider, i);
}
return [...c.values()].toSorted((e, t) => e.provider.localeCompare(t.provider));
}
function registerModelCapabilityCommands(e) {
const t = e.command("model").description("Text inference and model catalog commands").option("--agent <id>", "Agent whose model and auth state should be used");
t.command("run").description("Run a one-shot model turn").requiredOption("--prompt <text>", "Prompt text").option("--file <path>", "Image file", collectOption, []).option("--model <provider/model>", "Model override").option("--thinking <level>", "Thinking level override").option("--local", "Force local execution", false).option("--gateway", "Force gateway execution", false).option("--agent <id>", "Agent whose model and credentials own the run (default: agents.defaults.systemAgent.agentId, then the sole agent)").option("--json", "Output JSON", false).action((e, t) => runCapabilityCommand(e.json, formatEnvelopeForText, async () => {
const { resolveCapabilityAgentOption: n, resolveTransport: r } = await import("./shared-CwcDzg1K.mjs");
const i = e.prompt;
if (normalizeOptionalString(i) === void 0) throw new Error("--prompt cannot be empty or whitespace-only.");
const a = normalizeThinkLevel(e.thinking);
if (e.thinking !== void 0 && !a) throw new Error(`Invalid thinking level. Use one of: ${THINKING_LEVELS_HELP}.`);
const o = r({
local: Boolean(e.local),
gateway: Boolean(e.gateway),
defaultTransport: "local"
});
const s = n(t, e.agent);
const run = async (t) => {
const n = e.file;
const r = e.model;
const { requireProviderModelOverride: o, resolveCapabilityProviderAgentId: c, resolveLocalCapabilityRuntimeConfig: l } = await import("./shared-CwcDzg1K.mjs");
const { getModelsCommandSecretTargetIds: u } = await import("./command-secret-targets-CYdGJLhL.mjs");
const { captureRuntimeConfigAsyncReader: d } = await import("./config/config.js");
const { canonicalizeCaseOnlyCatalogModelRef: f } = await import("./model-selection-MVvzg347.mjs");
const { hasObservedModelUsage: p, normalizeUsage: m } = await import("./usage-GPW6DCHT.mjs");
const h = o(r);
const g = !t ? await l({
commandName: "infer model run",
targetIds: u()
}) : await d()();
const _ = c(g, s, "infer model run");
const v = await f({
raw: r,
cfg: g,
defaultProvider: DEFAULT_PROVIDER,
loadCatalog: () => loadModelCatalogForInspection(g, _),
preserveAuthProfile: !t
});
const y = Boolean(h);
const b = await Promise.all((n ?? []).map(async (e) => {
const t = resolveFilesystemPath(e);
const n = await fs.readFile(t);
const r = normalizeMimeType(await detectMime({
buffer: n,
filePath: t
}));
if (!r?.startsWith("image/")) throw new Error(`Unsupported --file for model run: ${t}. Only image files are supported; use infer audio transcribe for audio files.`);
const i = HEIC_MODEL_RUN_MIMES.has(r);
const a = i ? await (await import("./media-services-B_q3spOh.mjs")).convertHeicToJpeg(n) : n;
return {
path: t,
fileName: path.basename(t),
mimeType: i ? "image/jpeg" : r,
data: a.toString("base64")
};
}));
const x = b.length > 0 ? { inputs: b.map((e) => ({
path: e.path,
mimeType: e.mimeType
})) } : {};
const S = b.length > 0 ? [{
type: "text",
text: i
}, ...b.map((e) => ({
type: "image",
data: e.data,
mimeType: e.mimeType
}))] : i;
if (!t) {
const { acquireSimpleCompletionModelForAgent: e, completeWithPreparedSimpleCompletionModel: t } = await import("./simple-completion-runtime-DuiQKH14.mjs");
const n = createDeferredCore();
captureAsyncWorkTracker()(async () => {
const { prepareLocalCapabilityAccountSecrets: r } = await import("./local-account-secrets-B8YxDtK0.mjs");
await r({
cfg: g,
agentId: _
});
const i = await e({
cfg: g,
agentId: _,
modelRef: v,
allowMissingApiKeyModes: ["aws-sdk"],
...y ? { allowBundledStaticCatalogFallback: true } : {},
skipAgentDiscovery: true
});
if ("error" in i) throw new Error(i.error);
const o = new AsyncWorkScope();
try {
n.resolve(await o.track(async () => {
if (i.selection.provider === "codex") throw new Error("The codex provider is served by the Codex app-server agent runtime, not the local simple-completion transport. Use an openai/<model> ref with provider/model agentRuntime.id: \"codex\", run through the gateway, or use /codex commands.");
if (b.length > 0 && !i.model.input.includes("image")) throw new Error(`Model "${i.selection.provider}/${i.selection.modelId}" does not accept image input, so --file cannot be sent to it. Use an image-capable model, run openclaw infer image describe, or add --gateway to describe images for text-only models.`);
const e = i.model.api === "openai-chatgpt-responses" ? LOCAL_MODEL_RUN_SYSTEM_PROMPT : void 0;
const n = await t({
model: i.model,
auth: i.auth,
cfg: g,
context: {
...e ? { systemPrompt: e } : {},
messages: [{
role: "user",
content: S,
timestamp: Date.now()
}]
},
options: {
maxTokens: typeof i.model.maxTokens === "number" && Number.isFinite(i.model.maxTokens) ? i.model.maxTokens : void 0,
...a ? { reasoning: a } : {}
}
});
const r = collectTextContentBlocks(n.content).join("").trim();
const o = n.errorMessage?.trim();
const s = `for provider "${i.selection.provider}" model "${i.selection.modelId}"${o ? `: ${o}` : ""}.`;
if (!r) {
const { hasOnlyAssistantReasoningContent: e, isReasoningOnlyLengthAssistantTurn: t } = await import("@openclaw/ai/internal/shared");
if ((n.stopReason === "stop" || n.stopReason === "length") && !o && e(n)) {
const e = t(n) ? " It stopped at the output token limit while reasoning; a lower --thinking level may leave room for text." : "";
throw new Error(`Model returned reasoning but no text output ${s}${e}`);
}
throw new Error(`No text output returned ${s}`);
}
if (n.stopReason === "error" || n.stopReason === "aborted") throw new Error(`Model run ${n.stopReason === "aborted" ? "aborted" : "failed"} ${s}`);
const c = m(n.usage);
const l = p(c) ? c : void 0;
return {
ok: true,
capability: "model.run",
transport: "local",
provider: i.selection.provider,
model: i.selection.modelId,
usage: l,
lastCallUsage: l,
attempts: [],
...x,
outputs: [{
text: r,
mediaUrl: null
}]
};
}));
} catch (e) {
n.reject(e);
} finally {
await o.drain();
await i[Symbol.asyncDispose]();
}
}).catch((e) => n.reject(e));
return await n.promise;
}
const { buildExplicitSessionIdSessionKey: C } = await import("./session-DP6gKahJ.mjs");
const { randomIdempotencyKey: w } = await import("./call-CT5jlfNe.mjs");
const { provider: T, model: E } = o(v) ?? {};
const D = `model-run-${randomUUID()}`;
const O = await t({
agentId: _,
sessionId: D,
sessionKey: C({
agentId: _,
sessionId: D
}),
message: i,
attachments: b.length > 0 ? b.map((e) => ({
type: "image",
fileName: e.fileName,
mimeType: e.mimeType,
content: e.data
})) : void 0,
provider: T,
model: E,
...a ? { thinking: a } : {},
modelRun: true,
promptMode: "none",
cleanupBundleMcpOnRunEnd: true,
idempotencyKey: w()
}, Boolean(T || E));
if (O.status && O.status !== "ok" && O.status !== "completed") throw new Error(O.result?.meta?.error?.message || O.summary || `Gateway model run ${O.status}.`);
const k = O.result?.meta?.agentMeta;
return {
ok: true,
capability: "model.run",
transport: "gateway",
provider: k?.provider,
model: k?.model,
usage: k?.usage?.costStatus !== void 0 || p(k?.usage) ? k?.usage : void 0,
lastCallUsage: p(k?.lastCallUsage) ? k.lastCallUsage : void 0,
attempts: k?.fallbackAttempts ?? [],
outputs: (O?.result?.payloads ?? []).map((e) => ({
text: e.text,
mediaUrl: e.mediaUrl,
mediaUrls: e.mediaUrls
})),
...x
};
};
if (o === "gateway") {
const { callGateway: e } = await import("./call-CT5jlfNe.mjs");
return await run((t, n) => e({
method: "agent",
params: t,
expectFinal: true,
timeoutMs: 12e4,
clientName: n ? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT : GATEWAY_CLIENT_NAMES.CLI,
mode: n ? GATEWAY_CLIENT_MODES.BACKEND : GATEWAY_CLIENT_MODES.CLI,
...n ? { scopes: [ADMIN_SCOPE] } : {}
}));
}
const { runWithLocalStateOwner: c } = await import("./local-state-owner-CxFnsNJm.mjs");
return await c({
method: "infer model run",
params: {},
target: "agent model credentials",
timeoutMs: 12e4,
requireLocalBackendSharedAuth: true,
onlineAlternative: "Omit --local to run it through the Gateway.",
onForeignOwner: e.local ? "refuse" : ({ requestOwner: e }) => run((t) => e("agent", t, { expectFinal: true })),
runLocal: () => run()
});
}));
t.command("list").description("List known models").option("--json", "Output JSON", false).action((e, t) => runCapabilityCommand(e.json, providerSummaryText, async () => {
const { resolveCapabilityAgentOption: n } = await import("./shared-CwcDzg1K.mjs");
const { captureRuntimeConfigAsyncReader: r } = await import("./config/config.js");
return loadModelCatalogForInspection(await r()(), n(t, e.agent));
}));
t.command("inspect").description("Inspect one model catalog entry").requiredOption("--model <provider/model>", "Model id").option("--json", "Output JSON", false).action((e, t) => runCapabilityCommand(e.json, void 0, async () => {
const { resolveCapabilityAgentOption: n } = await import("./shared-CwcDzg1K.mjs");
const { captureRuntimeConfigAsyncReader: r } = await import("./config/config.js");
const i = normalizeStringifiedOptionalString(e.model) ?? "";
const a = await loadModelCatalogForInspection(await r()(), n(t, e.agent));
const o = a.find((e) => `${e.provider}/${e.id}` === i) ?? a.find((e) => e.id === i);
if (!o) throw new Error(`Model not found: ${i}`);
return o;
}));
registerLocalProvidersCommand(t, "List model providers from the catalog", buildModelProviders, providerSummaryText);
const n = t.command("auth").description("Provider auth helpers").option("--agent <id>", "Agent id (default: configured default agent)");
const resolveModelAuthAgent = async (e, t, n) => {
const { resolveCapabilityProviderAgentId: r, resolveCapabilityAgentOption: i } = await import("./shared-CwcDzg1K.mjs");
const { captureRuntimeConfigAsyncReader: a } = await import("./config/config.js");
return r(await a()(), i(e, t), n);
};
n.command("login").description("Run provider auth login").requiredOption("--provider <id>", "Provider id").option("--method <id>", "Provider auth method id").option("--agent <id>", "Agent id (default: configured default agent)").action(async (e, t) => {
const { runAuthModelCommand: n } = await import("./models-cli-BODJqsbp.mjs");
await n(t, (t) => ({
provider: String(e.provider),
method: e.method,
agent: t
}), async () => (await import("./auth-eCQF7CRE.mjs")).modelsAuthLoginCommand);
});
n.command("logout").description("Remove saved auth profiles for one provider").requiredOption("--provider <id>", "Provider id").option("--agent <id>", "Agent id (default: agents.defaults.systemAgent.agentId, then the sole agent)").option("--json", "Output JSON", false).action((e, t) => runCapabilityCommand(e.json, void 0, async () => {
const { runWithLocalStateOwner: n } = await import("./local-state-owner-CxFnsNJm.mjs");
return await n({
method: "models.auth",
params: {},
target: "system/agent credentials",
onForeignOwner: "refuse",
runLocal: async ({ config: n }) => {
const r = String(e.provider);
const [i, { resolveAgentDir: a }, o, { removeModelAuthCredentials: s }] = await Promise.all([
import("./shared-CwcDzg1K.mjs"),
import("./agent-scope-7S_X4gNj.mjs"),
import("./auth-profiles-UUzo-h8d.mjs"),
import("./auth-logout-B6kuM0jE.mjs")
]);
const c = a(n, i.resolveCapabilityProviderAgentId(n, i.resolveCapabilityAgentOption(t, e.agent), "infer model auth logout"));
const l = await o.ensureAuthProfileStoreWithoutExternalProfilesAsync(c);
const u = o.listProfilesForProvider(l, r);
const d = await s({
cfg: n,
agentDir: c,
profileIds: u,
provider: r
});
return {
provider: r,
removedProfiles: u,
...d ? { warning: d } : {}
};
}
});
}));
n.command("status").description("Show configured auth state").option("--agent <id>", "Agent id (default: configured default agent)").option("--json", "Output JSON", false).action((e, t) => runCapabilityCommand(e.json, void 0, async () => {
const n = await resolveModelAuthAgent(t, e.agent, "infer model auth status");
const r = [];
const { modelsStatusCommand: i } = await import("./list.status-command-B4_qkhZB.mjs");
await i({
json: true,
agent: n
}, {
log: (...e) => r.push(e.join(" ")),
error: defaultRuntime.error,
exit: (e) => {
throw new Error(`exit ${e}`);
}
});
const a = r.find((e) => e.trim().startsWith("{"));
return a ? JSON.parse(a) : {};
}));
}
//#endregion
export { registerModelCapabilityCommands };