UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

176 lines (175 loc) • 6.16 kB
import { a as extractErrorCode } from "../../error-coercion-hDrHOSGy.mjs"; import { r as resolveStateDir } from "../../state-dir-DiG0gXzD.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "../../tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Un as record, sr as unknown } from "../../schemas-Cy6abvsu.mjs"; import { t as runCommandBuffered } from "../../exec-aRIvS9s4.mjs"; import "../../state-paths-qdCZ9HDY.mjs"; import "../../process-runtime-DcBPEA8Y.mjs"; import "../../error-runtime-BM740gJj.mjs"; import { n as parseJsonPreservingUnsafeIntegers } from "../../json-unsafe-integers-DcKagBUk.mjs"; import "../../temp-path-CW7QMeae.mjs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; //#region extensions/apple-fm/native.ts const SETUP_REQUIRED = "Run Apple Foundation Models setup again to build its native helper."; const infoSchema = object({ available: boolean(), reason: string().optional(), modelName: string(), contextWindow: number().int().nonnegative() }); const resultSchema = object({ text: string(), toolCalls: array(object({ id: string().min(1), name: string().min(1), arguments: record(string(), unknown()) })), inputTokens: number().int().nonnegative(), outputTokens: number().int().nonnegative() }); function supportsNativeModel() { return process.platform === "darwin" && process.arch === "arm64" && Number(os.release().split(".")[0]) >= 26; } function nativeEnvironment(e = process.env) { return { HOME: e.HOME ?? os.homedir(), PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ...e.TMPDIR ? { TMPDIR: e.TMPDIR } : {}, ...e.DEVELOPER_DIR ? { DEVELOPER_DIR: e.DEVELOPER_DIR } : {} }; } function createAppleFmNative(e) { const t = path.join(e, "assets", "AppleFoundationModels.swift"); let n; async function helperPath(e) { n ??= fs.readFile(t).then((e) => createHash("sha256").update(e).digest("hex")); return path.join(resolveStateDir(e), "tools", "apple-fm", `${await n}-${os.release().split(".")[0]}`, "helper"); } async function helperExists(e) { try { const t = await fs.lstat(e); return t.isFile() && (t.mode & 73) !== 0; } catch (e) { if (extractErrorCode(e) === "ENOENT") return false; throw e; } } async function invoke(e, t, n, r) { r.signal?.throwIfAborted(); const i = await runCommandBuffered([e, ...t], { input: n, baseEnv: nativeEnvironment(r.env), signal: r.signal, timeoutMs: t[0] === "info" ? 15e3 : 12e4, maxOutputBytes: { stdout: 2097152, stderr: 8192 }, killProcessTree: true }); r.signal?.throwIfAborted(); if (i.code !== 0 || i.termination !== "exit") throw new Error(`Apple Foundation Models helper failed (${i.termination}, exit ${i.code ?? "none"}). ${i.stderr.toString("utf8").trim()}`); const a = parseJsonPreservingUnsafeIntegers(i.stdout.toString("utf8")); const o = object({ error: string() }).safeParse(a); if (o.success) throw new Error(o.data.error); return a; } async function probeAppleFm(e = {}) { e.signal?.throwIfAborted(); if (!supportsNativeModel()) return null; const t = await helperPath(e.env); if (await helperExists(t)) return infoSchema.parse(await invoke(t, ["info"], "", e)); const n = await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "openclaw-apple-fm-probe-")); const r = path.join(n, "helper"); const i = AbortSignal.timeout(3e4); const a = { ...e, signal: e.signal ? AbortSignal.any([e.signal, i]) : i }; try { await compileHelper(r, a, "-Onone"); return infoSchema.parse(await invoke(r, ["info"], "", a)); } finally { await fs.rm(n, { recursive: true, force: true }); } } async function compileHelper(e, n, r) { n.signal?.throwIfAborted(); const i = await runCommandBuffered(["/usr/bin/xcode-select", "-p"], { input: "", baseEnv: nativeEnvironment(n.env), signal: n.signal, timeoutMs: 1e4, maxOutputBytes: 4096 }); n.signal?.throwIfAborted(); if (i.code !== 0) throw new Error("Install Apple's developer tools with the macOS 27 SDK, then rerun Apple Foundation Models setup. OpenClaw does not install developer tools automatically."); const a = await runCommandBuffered([ "/usr/bin/xcrun", "--sdk", "macosx", "swiftc", "-parse-as-library", r, "-target", "arm64-apple-macos27.0", t, "-o", e ], { input: "", baseEnv: nativeEnvironment(n.env), signal: n.signal, timeoutMs: 12e4, maxOutputBytes: 65536, killProcessTree: true }); n.signal?.throwIfAborted(); if (a.code !== 0 || a.termination !== "exit") throw new Error(`Could not build the Apple Foundation Models helper. Select Apple developer tools with the macOS 27 SDK and retry setup. ${a.stderr.toString("utf8").trim()}`); } /** Only selected setup publishes the helper used by ordinary inference. */ async function prepareAppleFm(e = {}) { e.signal?.throwIfAborted(); if (!supportsNativeModel()) throw new Error("Apple Foundation Models requires an Apple Silicon Mac running macOS 27 or later."); const t = await helperPath(e.env); if (!await helperExists(t)) { await fs.mkdir(path.dirname(t), { recursive: true, mode: 448 }); const n = await fs.mkdtemp(path.join(path.dirname(t), "build-")); const r = path.join(n, "helper"); try { await compileHelper(r, e, "-O"); await fs.chmod(r, 448); e.signal?.throwIfAborted(); await fs.rename(r, t); } finally { await fs.rm(n, { recursive: true, force: true }); } } return infoSchema.parse(await invoke(t, ["info"], "", e)); } async function runAppleFm(e, t = {}) { if (!supportsNativeModel()) throw new Error("Apple Foundation Models is only available on Apple Silicon with macOS 27 or later."); const n = await helperPath(t.env); if (!await helperExists(n)) throw new Error(SETUP_REQUIRED); return resultSchema.parse(await invoke(n, ["run"], JSON.stringify(e), t)); } return { probe: probeAppleFm, prepare: prepareAppleFm, run: runAppleFm }; } //#endregion export { createAppleFmNative };