UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

204 lines (203 loc) • 6.87 kB
import { Fn as object, Jn as string, qn as strictObject } from "./schemas-Cy6abvsu.mjs"; import { i as buildNativeRuntimeFetch, n as NativeRuntimeIdentifier, t as NativeRuntimeConfigSchema } from "./native-runtime-config-BhaaooA4.mjs"; import { t as nativeRuntimeModelUnsupportedReason } from "./native-runtime-model-support-DiBEivd-.mjs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import { realpath, stat } from "node:fs/promises"; import { isCredentialFieldName } from "@openclaw/ai/internal/shared"; import { cleanupSessionResources } from "@openclaw/ai/internal/runtime"; import { createNodeLlmRuntime } from "@openclaw/ai"; import { registerBuiltInApiProviders } from "@openclaw/ai/providers"; //#region src/worker/native-runtime.ts const BindingSchema = object({ workspacePath: string().optional() }); const SelectionSchema = strictObject({ provider: NativeRuntimeConfigSchema.shape.models.element.shape.provider, modelId: NativeRuntimeIdentifier }); const MIN_CREDENTIAL_PREFIX_CHARS = 8; const FULL_CREDENTIAL_PREFIX_SCAN_MAX_CHARS = 16; async function assertWorkspace(e) { const t = await realpath(e.sourcePath); const n = await stat(t); if (t !== e.canonicalPath || !n.isDirectory() || n.dev !== e.dev || n.ino !== e.ino) throw new Error("Native runtime workspace changed since startup"); } /** * Owns provider I/O in the dedicated runtime process. In particular, do not import * src/llm/stream: that facade installs Gateway transport policy and auth state. */ async function createNativeRuntime(e, t) { const n = NativeRuntimeConfigSchema.parse(e); const r = createNodeLlmRuntime(void 0, { buildModelFetch: buildNativeRuntimeFetch, requiresManagedTransport: () => true }); registerBuiltInApiProviders(r.registry); const i = /* @__PURE__ */ new Map(); const a = /* @__PURE__ */ new Set(); const addProtocolSecret = (e) => { a.add(e); const t = e.trim(); if (t) a.add(t); }; for (const e of n.models) { const n = `${e.provider}/${e.id}`; const o = t[n]; if (!o?.trim()) throw new Error(`Native runtime credential is unavailable for ${n}`); addProtocolSecret(o); const s = nativeRuntimeModelUnsupportedReason(e.api, o); if (!r.registry.getApiProvider(e.api) || s) throw new Error(s ?? `Unsupported native runtime API: ${e.api}`); const { headers: c, ...l } = e; const u = Object.fromEntries(Object.entries(c ?? {}).map(([e, t]) => [e.toLowerCase(), t])); if (e.api === "openai-completions" || e.api === "openai-responses") { u["openai-organization"] ??= ""; u["openai-project"] ??= ""; } const d = { ...l, name: e.name ?? e.id, reasoning: e.reasoning ?? false, input: e.input ?? ["text"] }; Object.freeze(d.input); Object.freeze(d.cost); if (d.thinkingLevelMap) Object.freeze(d.thinkingLevelMap); Object.freeze(d); i.set(n, { model: d, credential: o, headers: u }); for (const [e, t] of Object.entries(u)) { if (!t) continue; addProtocolSecret(t); if (isCredentialFieldName(e)) { const e = /^(?:Bearer|Basic)\s+(\S+)$/iu.exec(t.trim())?.[1]; if (e) a.add(e); } } } const o = path.resolve(n.workspace); const s = await realpath(o); const c = await stat(s); if (!c.isDirectory()) throw new Error("Native runtime workspace must be a directory"); const l = { sourcePath: o, canonicalPath: s, dev: c.dev, ino: c.ino }; const u = [...a].flatMap((e) => [e, JSON.stringify(e).slice(1, -1)]); const hasCredentialPrefix = (e) => { if (typeof e === "string") { for (const t of a) { const n = Math.min(e.length, t.length - 1); const r = t.length <= FULL_CREDENTIAL_PREFIX_SCAN_MAX_CHARS ? 1 : MIN_CREDENTIAL_PREFIX_CHARS; for (let i = n; i >= r && i > 0; i--) if (t.startsWith(e.slice(-i))) return true; } return false; } return e !== null && typeof e === "object" && Object.values(e).some(hasCredentialPrefix); }; let d = false; const f = /* @__PURE__ */ new Set(); function assertOpen() { if (d) throw new Error("Native runtime is closed"); } return { async withTurn(e, t) { assertOpen(); const n = BindingSchema.parse(e.binding); const a = SelectionSchema.parse(e.selection); const o = `${a.provider}/${a.modelId}`; const s = i.get(o); if (!s) throw new Error("Native runtime model selection is not configured"); await assertWorkspace(l); const c = n.workspacePath ? await realpath(n.workspacePath) : l.canonicalPath; if (c !== l.canonicalPath) throw new Error("Native runtime workspace does not match the admitted workspace"); const d = await stat(c); if (!d.isDirectory()) throw new Error("Native runtime assigned workspace is not a directory"); const p = { ...l, sourcePath: n.workspacePath ?? l.sourcePath, canonicalPath: c, dev: d.dev, ino: d.ino }; assertOpen(); const m = new AbortController(); f.add(m); const h = randomUUID(); const assertActive = () => { assertOpen(); if (m.signal.aborted) throw new Error("Native runtime turn is closed"); }; const streamFn = async (e, t, n) => { assertActive(); if (e !== s.model) throw new Error("Native runtime requires the exact selected local model"); await assertWorkspace(l); await assertWorkspace(p); assertActive(); const i = { temperature: n?.temperature, maxTokens: s.model.maxTokens, reasoning: n?.reasoning, thinkingBudgets: n?.thinkingBudgets, responseFormat: n?.responseFormat, stop: n?.stop, serviceTier: n?.serviceTier, cacheRetention: n?.cacheRetention, promptCacheTtl: n?.promptCacheTtl, timeoutMs: n?.timeoutMs, maxRetryDelayMs: n?.maxRetryDelayMs, onActiveResponse: n?.onActiveResponse, asyncToolExecution: n?.asyncToolExecution, apiKey: s.credential, headers: { ...s.headers }, sessionId: h, transport: "sse", signal: n?.signal ? AbortSignal.any([m.signal, n.signal]) : m.signal }; i.signal?.throwIfAborted(); return r.streamSimple(s.model, t, i); }; try { const e = await t({ model: s.model, streamFn, workspacePath: c, hasCredentialPrefix: (e) => { assertActive(); return hasCredentialPrefix(e); }, assertProtocolSafe: (e) => { assertActive(); const t = JSON.stringify(e); if (u.some((e) => t.includes(e))) throw new Error("Native credential appeared in a protocol payload"); } }); assertActive(); return e; } finally { f.delete(m); m.abort(); cleanupSessionResources(h); } }, close() { if (d) return; d = true; for (const e of f) e.abort(); f.clear(); for (const e of i.values()) { e.headers = {}; e.credential = ""; } i.clear(); a.clear(); u.length = 0; r.registry.clearApiProviders(); } }; } //#endregion export { createNativeRuntime };