UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

348 lines (347 loc) • 11.4 kB
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs"; import "./utils-C8YECn2Q.mjs"; import { i as isLocalStorageOutcomeError } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import "./tool-policy-BR4v75RA.mjs"; import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs"; import { i as getCodeModeExecBeforeHookMetadata, l as normalizeCodeModeExecBeforeHookParams, r as copyCodeModeControlToolIdentity } from "./code-mode-control-tools-2pBIuXDg.mjs"; import { p as copyInternalToolResultState, s as attachInternalToolExecutionPreparer, v as getInternalToolExecutionPreparer } from "./internal-hooks-Ch3rqxs-.mjs"; import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs"; import { n as jsonResult } from "./tool-results-CcV0sxnb.mjs"; import { D as isToolWrappedWithBeforeToolCallHook, g as copyAgentToolReplaySafety } from "./agent-tool-metadata-nrQgRaqv.mjs"; import { n as ToolInputError } from "./tool-input-error-B1hgavSw.mjs"; import { o as payloadTextResult } from "./common-njQNtpnW.mjs"; import { n as logError, t as logDebug } from "./logger-CIwfuhOU.mjs"; import { a as recordStructuredReplayTrustForToolCall, c as createInternalExecutionPreparer, f as runBeforeToolCallHook, i as prepareBeforeToolCallExecutionParams, l as readInternalExecutionControl, n as finalizeBeforeToolCallExecutionParams, t as buildBlockedToolResult } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs"; import { f as recordAdjustedParamsForToolCall } from "./agent-tools.before-tool-call.state-C5F7vnXY.mjs"; import { o as runAgentToolSourceExecutionGuard, r as captureAgentToolSourceExecutionGuard } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs"; import "./agent-tools.before-tool-call-CCkSq-k3.mjs"; import { t as readNodePermissionError } from "./node-permission-error-FsjZ46I7.mjs"; import { n as projectAgentToolDefinition } from "./prepared-tool-surface-CsmkqTkz.mjs"; import { t as readToolOperatorHint } from "./tool-operator-hint-BZarHbv6.mjs"; //#region src/agents/agent-tool-definition-adapter.ts /** * Owns hook execution, client-tool delegation, result coercion, and safe * logging for failed tool calls. */ function captureSourceInvocationGuard(e, t) { const n = captureAgentToolSourceExecutionGuard(t); return () => { n(); runAgentToolSourceExecutionGuard(e); }; } const toolDefinitionSources = /* @__PURE__ */ new WeakMap(); /** Policy follows the concrete registered definition back to its runtime-owned source. */ function getToolDefinitionSource(e) { return toolDefinitionSources.get(e); } function describeToolExecutionError(e) { const t = readToolOperatorHint(e); if (e instanceof Error) return { message: e.message?.trim() ? e.message : String(e), ...t ? { operatorHint: t } : {} }; return { message: String(e) }; } function buildToolExecutionErrorResult(e) { const t = readNodePermissionError(e.cause); return jsonResult({ status: "error", tool: e.toolName, error: e.message, ...t ? { permissionMissing: t } : {} }); } async function executeAdaptedToolOperation(e) { try { const t = e.normalizedToolName; const n = await e.run(); if (n && typeof n === "object") { const e = n; if (Array.isArray(e.content)) return n; logDebug(`tools: ${t} returned non-standard result (missing content[]); coercing`); return payloadTextResult(("details" in e ? e.details : e) ?? { status: "ok", tool: t }); } return payloadTextResult(n ?? { status: "ok", tool: t }); } catch (t) { if (e.signal?.aborted || isLocalStorageOutcomeError(t)) throw t; const n = describeToolExecutionError(t); const r = n.operatorHint ? ` ${n.operatorHint}` : ""; logError(`[tools] ${e.normalizedToolName} failed:${r}`); const i = buildToolExecutionErrorResult({ toolName: e.normalizedToolName, message: n.message, cause: t }); return typeof t === "object" && t !== null ? copyInternalToolResultState(t, i) : i; } } function attachAdapterExecutionPreparer(e) { return attachInternalToolExecutionPreparer(e, createInternalExecutionPreparer((t, n) => e.execute(t.toolCallId, t.args, t.signal, t.onUpdate, n))); } const CLIENT_TOOL_NAME_CONFLICT_PREFIX = "client tool name conflict:"; function findClientToolNameConflicts(e) { const t = /* @__PURE__ */ new Set(); for (const n of e.existingToolNames ?? []) { const e = n.trim(); if (e) t.add(normalizeToolPolicyName(e)); } const n = /* @__PURE__ */ new Set(); const r = /* @__PURE__ */ new Map(); for (const i of e.tools) { const e = (i.function?.name ?? "").trim(); if (!e) continue; const a = normalizeToolPolicyName(e); if (t.has(a)) n.add(e); const o = r.get(a); if (o) { n.add(o); n.add(e); continue; } r.set(a, e); } return Array.from(n); } /** Detect client tool conflict errors without depending on object identity. */ function isClientToolNameConflictError(e) { return e instanceof Error && e.message.startsWith("client tool name conflict:"); } function toToolDefinitions(e, t, n) { const resolveAbortSignal = (e) => e && n ? AbortSignal.any([e, n]) : e ?? n; return e.map((e) => { const n = e.name || "tool"; const r = getPluginToolMeta(e)?.pluginId; const i = normalizeToolPolicyName(n); const a = isToolWrappedWithBeforeToolCallHook(e); const o = getInternalToolExecutionPreparer(e); const s = { ...projectAgentToolDefinition(e), prepareArguments: e.prepareArguments, execute: async (...o) => { const [s, c, l, u] = o; const d = resolveAbortSignal(l); d?.throwIfAborted(); const f = captureSourceInvocationGuard(e, d); const p = readInternalExecutionControl(o[4]); recordStructuredReplayTrustForToolCall(s, e, t?.runId); let m = c; return await executeAdaptedToolOperation({ normalizedToolName: i, signal: d, run: async () => { if (!a) { const i = await prepareBeforeToolCallExecutionParams({ tool: e, params: c, ...s ? { toolCallId: s } : {}, ...t ? { ctx: t } : {}, ...d ? { signal: d } : {} }); const a = normalizeCodeModeExecBeforeHookParams({ tool: e, params: i }); const o = getCodeModeExecBeforeHookMetadata({ tool: e, params: i }); const l = await runBeforeToolCallHook({ toolName: n, params: a, ...o, toolCallId: s, ctx: t ? { ...t, toolOwnerPluginId: r } : r ? { toolOwnerPluginId: r } : void 0, signal: d }); if (l.blocked) { if (l.kind === "veto") return buildBlockedToolResult({ reason: l.reason, deniedReason: l.deniedReason, toolCallId: s, runId: t?.runId }); throw new Error(l.reason); } m = finalizeBeforeToolCallExecutionParams({ tool: e, preparedParams: i, hookParams: a, adjustedParams: l.params, finalizerMode: "adapter" }); const u = p ? await p.pause(m) : void 0; if (u && !u.launch) return { content: [], details: { status: "skipped" } }; f(); u?.start?.(); recordAdjustedParamsForToolCall(s, m, t?.runId); } f(); return await e.execute(s, m, d, u); } }); } }; toolDefinitionSources.set(s, e); copyCodeModeControlToolIdentity(e, s); copyAgentToolReplaySafety(e, s); if (!o) return a ? s : attachAdapterExecutionPreparer(s); return attachInternalToolExecutionPreparer(s, async (n) => { const r = resolveAbortSignal(n.signal); const a = captureSourceInvocationGuard(e, r); r?.throwIfAborted(); recordStructuredReplayTrustForToolCall(n.toolCallId, e, t?.runId); const settle = (e) => executeAdaptedToolOperation({ normalizedToolName: i, signal: r, run: e }); const settleImmediate = async (e, t) => { let n; try { n = { kind: "result", result: await settle(async () => { if (e.kind === "error") throw e.error; return e.result; }), isError: e.kind === "result" && e.isError }; } catch (e) { n = { kind: "error", error: e }; } return { kind: "immediate", outcome: n, dispose: t }; }; let s; try { a(); s = await o({ toolCallId: n.toolCallId, args: n.args, ...r ? { signal: r } : {}, ...n.onUpdate ? { onUpdate: n.onUpdate } : {} }); } catch (e) { return await settleImmediate({ kind: "error", error: e }, () => {}); } if (s.kind === "immediate") return await settleImmediate(s.outcome, s.dispose); const c = s; return { kind: "ready", args: c.args, execute: (e) => settle(async () => { a(); return await c.execute(e); }), dispose: c.dispose }; }); }); } function coerceParamsRecord(e, t) { let n = e; if (typeof e === "string") { const t = e.trim(); try { n = t ? JSON.parse(t) : void 0; } catch { throw new ToolInputError("Invalid client tool arguments: expected a JSON object"); } } const r = n ?? {}; if (!isPlainObject(r)) throw new ToolInputError("Invalid client tool arguments: expected a JSON object"); const i = (Array.isArray(t?.required) ? t.required.filter((e) => typeof e === "string") : []).filter((e) => !Object.hasOwn(r, e)); if (i.length > 0) throw new ToolInputError(`Invalid client tool arguments: missing required ${i.join(", ")}`); return r; } function toClientToolDefinitions(e, t, n) { const r = typeof t === "object" ? t : void 0; return e.map((e) => { const i = e.function; return attachAdapterExecutionPreparer({ name: i.name, label: i.name, description: i.description ?? "", parameters: i.parameters, execute: async (...e) => { const [a, o, s] = e; const c = captureAgentToolSourceExecutionGuard(s); const l = readInternalExecutionControl(e[4]); r?.reserve?.(a, i.name); try { const e = coerceParamsRecord(o, i.parameters); const u = await runBeforeToolCallHook({ toolName: i.name, params: e, toolCallId: a, ctx: n, signal: s }); if (u.blocked) { r?.discard?.(a, i.name); if (u.kind === "veto") return buildBlockedToolResult({ reason: u.reason, deniedReason: u.deniedReason, toolCallId: a, runId: n?.runId }); throw new Error(u.reason); } const d = coerceParamsRecord(u.params, i.parameters); const f = l ? await l.pause(d) : void 0; if (f && !f.launch) { r?.discard?.(a, i.name); return { content: [], details: { status: "skipped" } }; } c(); f?.start?.(); if (typeof t === "function") t(i.name, d); else r?.complete(a, i.name, d); } catch (e) { r?.discard?.(a, i.name); if (s?.aborted) throw e; if (e instanceof ToolInputError) return buildToolExecutionErrorResult({ toolName: i.name, message: e.message }); throw e; } return { ...jsonResult({ status: "pending", tool: i.name, message: "Tool execution delegated to client" }), terminate: true }; } }); }); } //#endregion export { toClientToolDefinitions as a, isClientToolNameConflictError as i, findClientToolNameConflicts as n, toToolDefinitions as o, getToolDefinitionSource as r, CLIENT_TOOL_NAME_CONFLICT_PREFIX as t };