UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 6.98 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import{a as CLAUDE_CLI_MODEL_ALIASES,i as CLAUDE_CLI_DEFAULT_MODEL_REF,r as CLAUDE_CLI_CLEAR_ENV,t as CLAUDE_CLI_BACKEND_ID,u as CLAUDE_CLI_SESSION_ID_FIELDS}from"./cli-constants-Cc2K557b.mjs";import{a as resolveClaudeCliExecutionArgs,i as resolveClaudeCliAutoCompactEnv,n as normalizeClaudeBackendConfig,o as resolveClaudeCliThinkingEnv}from"./cli-shared-Cw8E_ipC.mjs";import{i as parseClaudeCliJsonlLifecycleEvent,r as parseClaudeCliJsonlEvent,t as classifyClaudeCliErrorCode}from"./cli-output-D1htBScr.mjs";import{t as appendClaudeCliToolNamingGuidance}from"./cli-tool-naming-DK8hVBTZ.mjs";import{createHmac,randomBytes}from"node:crypto"; //!extensions/anthropic/cli-backend.ts const CLAUDE_CLI_CREDENTIAL_FINGERPRINT_KEY=randomBytes(32);const CLAUDE_CLI_DEFAULT_ARGS=[`-p`,`--output-format`,`stream-json`,`--include-partial-messages`,`--verbose`,`--setting-sources`,`user`,`--allowedTools`,`mcp__openclaw__*`,`--disallowedTools`,`ScheduleWakeup,CronCreate,CronList,Bash(run_in_background:true),Monitor`];const CLAUDE_NATIVE_TOOL_CAPABILITIES={read:`read`,grep:`read`,write:`write`,edit:`edit`,bash:`exec`,webfetch:`web_fetch`,websearch:`web_search`,askuserquestion:`ask_user`};function projectClaudeNativeToolAuthority(e){const t=new Set(e.map(e=>e.trim().toLowerCase()));return[...new Set(Object.entries(CLAUDE_NATIVE_TOOL_CAPABILITIES).filter(([e])=>t.has(e)).map(([,e])=>e))]}const CLAUDE_MANAGED_NATIVE_TOOLS=[`Agent`,`Workflow`,`WebSearch`];const CLAUDE_DEFAULT_MANAGED_NATIVE_TOOLS=[`WebSearch`];function resolveClaudeManagedNativeTools(e){const t=e.config?.plugins?.entries?.anthropic?.config;const n=isRecord(t)?t.managedNativeTools:void 0;const r=isRecord(n)?n:{};const i=isRecord(r.agents)?r.agents:void 0;const a=Object.hasOwn(i??{},e.agentId)?i?.[e.agentId]:Object.hasOwn(r,`default`)?r.default:CLAUDE_DEFAULT_MANAGED_NATIVE_TOOLS;return Array.isArray(a)?CLAUDE_MANAGED_NATIVE_TOOLS.filter(e=>a.includes(e)):[]}function createClaudeCliAuthInput(e){const t=e.value.trim();if(!t)return;const n=Buffer.from(t,`utf8`);let r=false;return{env:{[e.envName]:`3`},clearEnv:[...CLAUDE_CLI_CLEAR_ENV],secretInput:{fd:3,fingerprint:createHmac(`sha256`,CLAUDE_CLI_CREDENTIAL_FINGERPRINT_KEY).update(n).digest(`hex`),createData:()=>{if(r)throw new Error(`Claude CLI credential input is no longer available`);return Buffer.from(n)}},cleanup:async()=>{r=true;n.fill(0)}}}function resolveClaudeCliAuthInput(e,t){if(e?.type===`oauth`&&`access`in e){const t=`expires`in e?e.expires:void 0;if(typeof t!==`number`||!Number.isFinite(t)||t<=Date.now())throw new Error(`Selected Claude CLI OAuth credential is expired or invalid. Re-authenticate the selected profile and retry. OpenClaw did not start the run.`);if(typeof e.access!==`string`)return;return createClaudeCliAuthInput({envName:`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`,value:e.access})}if(e?.type===`token`&&`token`in e&&typeof e.token===`string`)return createClaudeCliAuthInput({envName:`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`,value:e.token});if(e?.type===`api_key`&&`key`in e&&typeof e.key===`string`)return createClaudeCliAuthInput({envName:t(e.key)?`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`:`CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR`,value:e.key})}function buildAnthropicCliBackend(e={}){return{id:CLAUDE_CLI_BACKEND_ID,modelProvider:`anthropic`,liveTest:{defaultModelRef:CLAUDE_CLI_DEFAULT_MODEL_REF,defaultImageProbe:true,defaultMcpProbe:true,docker:{npmPackage:`@anthropic-ai/claude-code`,binaryName:`claude`}},runtimeArtifact:{kind:`bundled-package-tree`,packageName:`@anthropic-ai/claude-code`,entrypoint:`command`,nativeExecutableNames:[`claude`,`claude.exe`]},bundleMcp:true,bundleMcpMode:`claude-config-file`,nativeToolMode:`selectable`,hostOwnedTools:[`exec`,`process`],toolAvailabilityEnforcement:`execution-args`,transformSystemPrompt:({systemPrompt:e,openClawMcpToolNames:t})=>appendClaudeCliToolNamingGuidance(e,t),projectNativeToolAuthority:projectClaudeNativeToolAuthority,resolveManagedNativeTools:resolveClaudeManagedNativeTools,nativeToolSearch:`ToolSearch`,sideQuestionToolMode:`disabled`,ownsNativeCompaction:true,manualCompaction:{buildPrompt:e=>{const t=e?.trim();return t?`/compact ${t}`:`/compact`},input:`arg`,systemPromptFileArg:`--system-prompt-file`,validateOutput:e=>{for(const t of e.split(` `))try{const e=JSON.parse(t);if(e.compact_result===`success`||e.type===`system`&&e.subtype===`compact_boundary`)return{ok:true}}catch{}return{ok:false,reason:`Claude CLI did not confirm that native compaction ran.`}}},subscriptionAuthDispatch:true,config:{command:`claude`,args:[...CLAUDE_CLI_DEFAULT_ARGS],resumeArgs:[...CLAUDE_CLI_DEFAULT_ARGS,`--resume`,`{sessionId}`],forkArg:`--fork-session`,resumeAtArg:`--resume-session-at`,output:`jsonl`,liveSession:`claude-stdio`,input:`stdin`,modelArg:`--model`,modelAliases:CLAUDE_CLI_MODEL_ALIASES,imageArg:`@`,imagePathScope:`workspace`,sessionArgs:[`--session-id`,`{sessionId}`],sessionMode:`always`,reseedFromRawTranscriptWhenUncompacted:true,freshSessionRecovery:`invalidated-only`,sessionIdFields:[...CLAUDE_CLI_SESSION_ID_FIELDS],systemPromptFileArg:`--append-system-prompt-file`,systemPromptMode:`append`,systemPromptWhen:`always`,clearEnv:[...CLAUDE_CLI_CLEAR_ENV],serialize:true},normalizeConfig:normalizeClaudeBackendConfig,resolveModelId:({modelId:e,contextWindow:t})=>t===`1m`?`${e}[1m]`:e,authEpochMode:`profile-only`,autoSelectAuthProfile:false,prepareExecution:t=>{const n=t;const prepare=(e=()=>false)=>{const r=resolveClaudeCliAuthInput(n.authCredential,e);const i=n.isolatedCompletionPrompt!==void 0;const a=!i&&t.executionMode===`agent`?{async*execute(e){const{executeClaudeCli:t}=await import(`./extensions/anthropic/cli.runtime.js`);e.assertCurrent?.();yield*t(e,r?.secretInput)}}:void 0;return{env:{CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS:`1`,...t.toolAvailability?{ENABLE_TOOL_SEARCH:t.toolAvailability.discovery?.includes(`ToolSearch`)||t.toolAvailability.native.includes(`ToolSearch`)?`true`:`false`}:{},...resolveClaudeCliAutoCompactEnv(t.contextTokenBudget),...t.contextWindow===`200k`?{CLAUDE_CODE_DISABLE_1M_CONTEXT:`1`}:{},...resolveClaudeCliThinkingEnv(t.thinkingLevel),...r?.env},...i?{isolatedCompletionEnforced:true}:{},...r?.clearEnv?{clearEnv:r.clearEnv}:{},...r?.secretInput?{secretInput:r.secretInput}:{},...r?.cleanup?{cleanup:r.cleanup}:{},...a}};const r=e.ensureDynamicSystemPromptSectionsSupport?.();const i=n.authCredential?.type===`api_key`?import(`./plugin-sdk/provider-stream-shared.js`).then(e=>e.isAnthropicOAuthApiKey):void 0;return r||i?Promise.all([r,i]).then(([,e])=>prepare(e)):prepare()},parseJsonlEvent:parseClaudeCliJsonlEvent,classifyErrorCode:classifyClaudeCliErrorCode,parseJsonlLifecycleEvent:parseClaudeCliJsonlLifecycleEvent,resolveExecutionArgs:t=>resolveClaudeCliExecutionArgs(t,{excludeDynamicSystemPromptSections:e.supportsDynamicSystemPromptSections?.()})}}export{buildAnthropicCliBackend as t};