openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
268 lines (267 loc) • 8.42 kB
JavaScript
import { a as CLAUDE_CLI_NATIVE_AUTH_MARKER, n as CLAUDE_CLI_CLEAR_ENV, t as CLAUDE_CLI_BACKEND_ID } from "./.setup/cli-constants-D8BFCp6p.mjs";
import { t as createClaudeCliTransport } from "./.setup/cli-transport-JXX3vbiu.mjs";
import { filterStringEntries, isRecord, normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { runUtf8CommandWithTimeout } from "openclaw/plugin-sdk/process-runtime";
import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
import { addAbortListener } from "node:events";
import { requiresClaudeMandatoryAdaptiveThinking } from "openclaw/plugin-sdk/claude-model-runtime";
//#region extensions/anthropic/cli-auth-seam.ts
const CLAUDE_CLI_AUTH_TIMEOUT_MS = 1e4;
const CLAUDE_CLI_AUTH_METHODS = [
"claude.ai",
"api_key",
"api_key_helper",
"oauth_token",
"third_party",
"none"
];
const CLI_BACKEND_PRESERVE_ENV = "OPENCLAW_LIVE_CLI_BACKEND_PRESERVE_ENV";
function readPreservedCliEnv(e) {
const t = e[CLI_BACKEND_PRESERVE_ENV]?.trim();
if (!t) return /* @__PURE__ */ new Set();
if (t.startsWith("[")) try {
return new Set(filterStringEntries(JSON.parse(t)));
} catch {
return /* @__PURE__ */ new Set();
}
return new Set(t.split(/[,\s]+/).filter(Boolean));
}
/** Ask Claude CLI whether its own login is usable without reading token material. */
async function probeClaudeCliAuthStatus(e) {
const t = { ...e?.env ?? process.env };
const n = readPreservedCliEnv(t);
for (const e of CLAUDE_CLI_CLEAR_ENV) if (!n.has(e)) delete t[e];
try {
const n = resolveWindowsSpawnProgram({
command: e?.command ?? "claude",
env: t,
packageName: "@anthropic-ai/claude-code"
});
const r = materializeWindowsSpawnProgram(n, [
"auth",
"status",
"--json"
]);
e?.signal?.throwIfAborted();
const i = await runUtf8CommandWithTimeout([r.command, ...r.argv], {
baseEnv: t,
maxOutputBytes: 65536,
maxCombinedOutputBytes: 65536,
terminateOnOutputLimit: true,
timeoutMs: CLAUDE_CLI_AUTH_TIMEOUT_MS,
killProcessTree: true
});
e?.signal?.throwIfAborted();
if (i.termination === "timeout") return {
status: "timeout",
timeoutMs: CLAUDE_CLI_AUTH_TIMEOUT_MS
};
if (i.termination !== "exit" || i.code === null) return { status: "unreadable" };
const a = JSON.parse(i.stdout);
if (!isRecord(a) || typeof a.loggedIn !== "boolean") return { status: "unreadable" };
if (!a.loggedIn) return { status: "missing" };
if (i.code !== 0) return { status: "unreadable" };
const o = CLAUDE_CLI_AUTH_METHODS.find((e) => e === a.authMethod);
const s = o === "claude.ai" ? normalizeOptionalString(a.email) : void 0;
return {
status: "available",
...o ? { authMethod: o } : {},
...s && s.length <= 320 && !/[\r\n]/u.test(s) ? { email: s } : {}
};
} catch (t) {
e?.signal?.throwIfAborted();
return { status: isRecord(t) && t.code === "ENOENT" ? "not-installed" : "unreadable" };
}
}
//#endregion
//#region extensions/anthropic/cli-model-discovery.ts
const INITIALIZE_TIMEOUT_MS = 3e4;
const NATIVE_EFFORT_LEVELS = [
"low",
"medium",
"high",
"xhigh",
"max"
];
/** Discover the native menu without submitting a user message or starting a turn. */
async function discoverClaudeCliModels(e) {
e.signal?.throwIfAborted();
const t = Object.fromEntries(Object.entries(e.env).filter((e) => e[1] !== void 0));
for (const e of CLAUDE_CLI_CLEAR_ENV) delete t[e];
const n = resolveWindowsSpawnProgram({
command: "claude",
env: t,
packageName: "@anthropic-ai/claude-code"
});
const r = materializeWindowsSpawnProgram(n, [
"--print",
"--input-format",
"stream-json",
"--output-format",
"stream-json",
"--verbose",
"--permission-prompt-tool",
"stdio",
"--setting-sources",
"user",
"--settings",
"{\"disableAllHooks\":true,\"enabledPlugins\":{}}",
"--strict-mcp-config",
"--mcp-config",
"{\"mcpServers\":{}}",
"--tools",
""
]);
const i = new AbortController();
const a = setTimeout(() => i.abort(/* @__PURE__ */ new Error("Claude CLI model discovery timed out.")), INITIALIZE_TIMEOUT_MS);
a.unref();
const o = e.signal ? AbortSignal.any([e.signal, i.signal]) : i.signal;
const s = {
command: r.command,
args: r.argv,
cwd: t.HOME ?? process.cwd(),
env: t,
abortSignal: o,
assertCurrent: () => o.throwIfAborted()
};
let c;
let l;
try {
c = await createClaudeCliTransport({
context: s,
args: r.argv,
currentContext: () => o.aborted ? void 0 : s,
initialize: { hooks: {} },
onMessage: async () => {},
onRequest: async () => {
throw new Error("Model discovery cannot authorize native requests.");
},
onError: () => {}
});
l = addAbortListener(o, () => c?.close());
const e = await c.initialize();
o.throwIfAborted();
if (!Array.isArray(e.models)) throw new Error("Claude CLI initialization did not return a model menu.");
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Set();
for (const r of e.models) {
if (!isRecord(r) || typeof r.resolvedModel !== "string" || !r.resolvedModel.trim()) continue;
const e = r.resolvedModel.trim();
const i = typeof r.displayName === "string" ? r.displayName : e;
const a = t.get(e);
if (a) {
if (r.value !== "default" && n.delete(e)) a.name = i;
continue;
}
if (r.value === "default") n.add(e);
const o = Array.isArray(r.supportedEffortLevels) ? r.supportedEffortLevels : [];
const s = NATIVE_EFFORT_LEVELS.filter((e) => o.includes(e));
t.set(e, {
id: e,
name: i,
reasoning: s.length > 0,
input: ["text", "image"],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
maxTokens: 128e3,
thinkingLevelMap: {
off: requiresClaudeMandatoryAdaptiveThinking({ id: e }) ? null : "off",
minimal: null,
...Object.fromEntries(NATIVE_EFFORT_LEVELS.map((e) => [e, s.includes(e) ? e : null]))
}
});
}
return [...t.values()];
} finally {
clearTimeout(a);
l?.[Symbol.dispose]();
c?.close();
await c?.waitForExit();
}
}
//#endregion
//#region extensions/anthropic/provider-discovery.ts
const modelCaptures = /* @__PURE__ */ new WeakMap();
const availability = /* @__PURE__ */ new WeakMap();
async function prepareClaudeCliAuth({ config: e, provider: t, env: n = process.env, signal: r }) {
r?.throwIfAborted();
if (!e || normalizeLowercaseStringOrEmpty(t) !== "claude-cli") return;
const i = availability.get(e) ?? /* @__PURE__ */ new WeakMap();
availability.set(e, i);
const a = i.get(n) ?? /* @__PURE__ */ new WeakMap();
i.set(n, a);
const o = r ?? e;
const s = Date.now();
let c = a.get(o);
if (!c || c.expiresAt <= s) {
c = {
expiresAt: s + 6e4,
pending: probeClaudeCliAuthStatus({
env: n,
signal: r
})
};
a.set(o, c);
}
const l = await c.pending;
r?.throwIfAborted();
return l.status !== "missing" && l.status !== "not-installed" ? {
apiKey: CLAUDE_CLI_NATIVE_AUTH_MARKER,
source: "Claude CLI native auth",
mode: "oauth",
nativeAuth: {
runtime: CLAUDE_CLI_BACKEND_ID,
mode: "oauth"
}
} : void 0;
}
const anthropicProviderDiscovery = {
id: CLAUDE_CLI_BACKEND_ID,
label: "Claude CLI",
docsPath: "/providers/models",
auth: [],
catalog: {
order: "simple",
async run(e) {
if (e.providerIds && !e.providerIds.includes("claude-cli")) return null;
if (!(await prepareClaudeCliAuth({
config: e.config,
provider: "claude-cli",
env: e.env,
signal: e.signal
}))?.apiKey) return null;
e.signal?.throwIfAborted();
const t = modelCaptures.get(e.config) ?? /* @__PURE__ */ new WeakMap();
modelCaptures.set(e.config, t);
const n = t.get(e.env) ?? /* @__PURE__ */ new WeakMap();
t.set(e.env, n);
const r = e.signal ?? e.config;
const i = n.get(r) ?? discoverClaudeCliModels(e);
n.set(r, i);
const a = await i.catch(() => void 0);
e.signal?.throwIfAborted();
return {
providers: { [CLAUDE_CLI_BACKEND_ID]: {
baseUrl: "https://api.anthropic.com",
api: "anthropic-messages",
models: a ?? []
} },
outcomes: [a ? {
provider: CLAUDE_CLI_BACKEND_ID,
status: "ready",
listedModelIds: a.map((e) => e.id)
} : {
provider: CLAUDE_CLI_BACKEND_ID,
status: "unavailable"
}]
};
}
},
prepareSyntheticAuth: prepareClaudeCliAuth
};
//#endregion
export { anthropicProviderDiscovery as default };