UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

250 lines (249 loc) • 10.5 kB
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs"; import { r as MAX_IMAGE_BYTES } from "./constants-ChkaB-HW.mjs"; import { r as extensionForMime } from "./mime-D2wVBzpa.mjs"; import { i as resolveRuntimeOsLabel } from "./os-summary-CMRUbVgk.mjs"; import "./model-selection-C2A4Wyix.mjs"; import { i as listRegisteredPluginAgentPromptGuidance } from "./command-registry-state-D8aXLQW8.mjs"; import { t as privateFileStore } from "./private-file-store-D564pKJx.mjs"; import { t as isAcpRuntimeSpawnAvailable } from "./availability-CBszSK60.mjs"; import { n as cliBackendLog } from "./log-C54MYINf.mjs"; import { r as detectRuntimeShell } from "./shell-utils-rrqUwXNm.mjs"; import { t as formatTomlConfigOverride } from "./toml-inline-CbBxtJfx.mjs"; import { t as buildSystemPromptParams } from "./system-prompt-params-B0WSdtCC.mjs"; import { t as formatCliImageTurnContext } from "./cli-image-turn-correlation-DVP0DD-I.mjs"; import { n as detectAndLoadPromptImages, r as detectImageReferences } from "./images-BfGn0xAm.mjs"; import { t as buildConfiguredAgentSystemPrompt } from "./system-prompt-config-Cs2owSg-.mjs"; import path from "node:path"; import crypto from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; import { tempWorkspace } from "@openclaw/fs-safe/temp"; import { stripSystemPromptCacheBoundary } from "@openclaw/ai/internal/shared"; import { fileStore } from "@openclaw/fs-safe/store"; //#region src/agents/cli-runner/helpers.ts const CLI_IMAGE_SWEEP_TTL_MS = 6048e5; const CLI_IMAGE_SWEEP_RECURRENCE_MS = 864e5; const lastCliImageRootSweepMs = /* @__PURE__ */ new Map(); function isClaudeCliBackendId(e) { return normalizeOptionalLowercaseString(e) === "claude-cli"; } function resolveCliRunQueueKey(e) { const t = e.liveSession !== void 0; if (e.serialize === false && !t) return `${e.backendId}:${e.runId}`; const n = e.ownerKey?.trim(); if (t && n) return `${e.backendId}:owner:${n}`; if (isClaudeCliBackendId(e.backendId)) { const t = e.cliSessionId?.trim(); if (t) return `${e.backendId}:session:${t}`; if (n) return `${e.backendId}:owner:${n}`; const r = e.workspaceDir.trim(); if (r) return `${e.backendId}:workspace:${r}`; } return e.backendId; } function buildCliAgentSystemPrompt(e) { const t = e.cwd?.trim() || e.workspaceDir; const n = resolveDefaultModelForAgent({ cfg: e.config ?? {}, agentId: e.agentId }); const r = `${n.provider}/${n.model}`; const { runtimeInfo: i } = buildSystemPromptParams({ config: e.config, agentId: e.agentId, workspaceDir: t, cwd: t, preparedRepoRoot: e.preparedRepoRoot, preparedGitCoauthorPrompt: e.preparedGitCoauthorPrompt, preparedSessionEntry: e.preparedSessionEntry, requesterProfileId: e.requesterProfileId, runtime: { sessionKey: e.sessionKey, sessionId: e.sessionId, host: "openclaw", os: resolveRuntimeOsLabel(), arch: os.arch(), node: process.version, model: e.modelDisplay, defaultModel: r, shell: detectRuntimeShell(), channel: e.runtimeChannel, chatType: e.runtimeChatType, capabilities: e.runtimeCapabilities, customInlineButtonHint: e.customInlineButtonHint, blind: e.preparedSessionEntry?.blindPrompt } }); return buildConfiguredAgentSystemPrompt({ config: e.config, preparedModelRuntime: e.preparedModelRuntime, preparedTtsPreferences: e.preparedTtsPreferences, agentId: e.agentId, workspaceDir: e.workspaceDir, runtimeCwd: t, extraSystemPrompt: e.extraSystemPrompt, sourceReplyDeliveryMode: e.sourceReplyDeliveryMode, requireExplicitMessageTarget: e.requireExplicitMessageTarget, silentReplyPromptMode: e.silentReplyPromptMode, ownerNumbers: e.ownerNumbers, reasoningTagHint: false, docsPath: e.docsPath, sourcePath: e.sourcePath, acpEnabled: isAcpRuntimeSpawnAvailable({ config: e.config }), promptSurface: "cli_backend", nativeCommandGuidanceLines: listRegisteredPluginAgentPromptGuidance({ surface: "cli_backend" }), runtimeInfo: i, messageToolHints: e.messageToolHints, toolNames: e.tools.map((e) => e.name), messageTool: e.tools.find((e) => e.name.trim().toLowerCase() === "message"), skillsPrompt: e.skillsPrompt, contextFiles: e.contextFiles, bootstrapMode: e.bootstrapMode, bootstrapTruncationNotice: e.bootstrapTruncationNotice }); } function normalizeCliModel(e, t) { const n = e.trim(); if (!n) return n; return t.modelAliases?.[n] || t.modelAliases?.[n.toLowerCase()] || n; } function resolveSystemPromptUsage(e) { const t = e.systemPrompt?.trim(); const n = e.backend.systemPromptWhen ?? "first"; if (!t || n === "never" || n === "first" && !e.isNewSession || !e.backend.systemPromptArg?.trim() && !e.backend.systemPromptFileArg?.trim() && !e.backend.systemPromptFileConfigKey?.trim()) return null; return t; } function resolveSessionIdToSend(e) { const t = e.backend.sessionMode ?? "always"; const n = e.cliSessionId?.trim(); return { sessionId: t === "none" ? void 0 : t === "existing" || n ? n : crypto.randomUUID(), isNew: !n }; } function resolvePromptInput(e) { if (e.backend.input === "stdin" || e.backend.maxPromptArgChars && e.prompt.length > e.backend.maxPromptArgChars) return { stdin: e.prompt }; return { argsPrompt: e.prompt }; } function resolveCliImageFileName(e) { const t = extensionForMime(e.mimeType) ?? ".bin"; return `${sha256Hex(`${e.mimeType}\0${e.data}`)}${t}`; } async function sweepCliImageRoot(e) { const t = Date.now(); const n = lastCliImageRootSweepMs.get(e); if (n !== void 0 && t - n < CLI_IMAGE_SWEEP_RECURRENCE_MS) return; lastCliImageRootSweepMs.set(e, t); try { await fileStore({ rootDir: e }).pruneExpired({ ttlMs: CLI_IMAGE_SWEEP_TTL_MS }); } catch (t) { lastCliImageRootSweepMs.delete(e); cliBackendLog.debug(`cli image cache sweep failed: ${String(t)}`); } } function appendImagePathsToPrompt(e, t, n = "") { if (!t.length) return e; const r = e.trimEnd(); return `${r}${r ? "\n\n" : ""}${t.map((e) => `${n}${e}`).join("\n")}`; } async function writeCliImages(e) { const t = e.backend.imagePathScope === "workspace" ? path.join(e.workspaceDir, ".openclaw-cli-images") : path.join(resolvePreferredOpenClawTmpDir(), "openclaw-cli-images"); await fs.mkdir(t, { recursive: true, mode: 448 }); await sweepCliImageRoot(t); const n = privateFileStore(t); const r = []; for (const t of e.images) { const e = resolveCliImageFileName(t); const i = Buffer.from(t.data, "base64"); await n.writeText(e, i, { durable: false }); r.push(n.path(e)); } return r; } async function writeCliSystemPromptFile(e) { if (!e.backend.systemPromptFileArg?.trim() && !e.backend.systemPromptFileConfigKey?.trim()) return { cleanup: async () => {} }; const t = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-cli-system-prompt-" }); return { filePath: await t.store.write("system-prompt.md", stripSystemPromptCacheBoundary(e.systemPrompt), { durable: false }), cleanup: () => t.cleanup().then(() => void 0) }; } async function loadCliPromptImages(e) { const t = e.imagePrompt ?? e.prompt; const n = e.imagePrompt !== void 0 || Boolean(e.media?.length) || Boolean(e.mediaImageLayout) || !e.images?.length && detectImageReferences(t).length > 0 ? await detectAndLoadPromptImages({ prompt: t, media: e.media, workspaceDir: e.workspaceDir, model: { input: ["text", "image"] }, existingImages: e.images, imageOrder: e.imageOrder, mediaImageLayout: e.mediaImageLayout, maxBytes: MAX_IMAGE_BYTES, localRoots: e.localRoots }) : void 0; if (n?.failedMediaCount) throw new Error(`failed to hydrate ${n.failedMediaCount} structured image attachment(s) for CLI input`); return n?.images ?? e.images ?? []; } async function prepareCliPromptImagePayload(e) { let t = e.prompt; const n = e.preparedImages ?? await loadCliPromptImages(e); if (n.length === 0) return { prompt: t }; const r = await writeCliImages({ backend: e.backend, workspaceDir: e.workspaceDir, images: n }); if (!e.backend.imageArg || e.backend.input === "stdin" || e.backend.imageArg === "@") { if (e.imageTurnKey) t = `${t.trimEnd()}\n\n${formatCliImageTurnContext(e.imageTurnKey)}`; t = appendImagePathsToPrompt(t, r, e.backend.imageArg === "@" ? "@" : ""); } return { prompt: t, imagePaths: r }; } function buildCliArgs(e) { const t = [...e.baseArgs]; const n = !e.useResume || e.backend.systemPromptWhen === "always" || e.sendSystemPromptOnResume; if (e.backend.modelArg && e.modelId) t.push(e.backend.modelArg, e.modelId); if (n && e.systemPrompt) { if (e.systemPromptFilePath && e.backend.systemPromptFileArg) t.push(e.backend.systemPromptFileArg, e.systemPromptFilePath); else if (e.systemPromptFilePath && e.backend.systemPromptFileConfigKey) t.push(e.backend.systemPromptFileConfigArg ?? "-c", formatTomlConfigOverride(e.backend.systemPromptFileConfigKey, e.systemPromptFilePath)); else if (e.backend.systemPromptArg) t.push(e.backend.systemPromptArg, stripSystemPromptCacheBoundary(e.systemPrompt)); } if (!e.useResume && e.sessionId) for (const n of e.backend.sessionArgs ?? []) t.push(n.replaceAll("{sessionId}", e.sessionId)); if (e.useResume && e.forkResume) { if (!e.backend.forkArg) throw new Error("CLI backend does not support forked session resume"); t.push(e.backend.forkArg); } if (e.resumeAt) { if (!e.useResume || !e.backend.resumeAtArg) throw new Error("CLI backend does not support checkpointed session resume"); t.push(e.backend.resumeAtArg, e.resumeAt); } if (e.promptArg !== void 0) { let n = false; for (let r = 0; r < t.length; r += 1) if (t[r] === "{prompt}") { t[r] = e.promptArg; n = true; } if (!n) t.push(e.promptArg); } const r = e.backend.imageArg; if (e.imagePaths?.length && r && r !== "@") { if (e.backend.imageMode === "list") t.push(r, e.imagePaths.join(",")); else for (const n of e.imagePaths) t.push(r, n); } return t; } //#endregion export { normalizeCliModel as a, resolvePromptInput as c, writeCliSystemPromptFile as d, loadCliPromptImages as i, resolveSessionIdToSend as l, buildCliArgs as n, prepareCliPromptImagePayload as o, isClaudeCliBackendId as r, resolveCliRunQueueKey as s, buildCliAgentSystemPrompt as t, resolveSystemPromptUsage as u };