openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
451 lines (450 loc) • 16.9 kB
JavaScript
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { C as isSubagentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as validateJsonSchemaValue } from "./schema-validator-NvoOmaWr.mjs";
import { a as getPluginToolSideEffectOwnerKey, i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { r as textResult } from "./tool-results-CcV0sxnb.mjs";
import { r as finalizeAgentToolAvailability } from "./agent-tool-availability-ecKW8hOH.mjs";
import { g as finalizeToolTerminalPresentation, r as getBeforeToolCallFailureDisposition } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { t as runAgentHarnessAfterToolCallHook } from "./hook-helpers-DKwpcDXZ.mjs";
import { i as resolveStoredSessionPermissionPolicy } from "./tool-fs-policy-dDd9W7xo.mjs";
import { n as isToolResultError, s as resolveToolExecutionErrorKind, t as formatToolExecutionErrorMessage } from "./tool-result-error-B2GHe83l.mjs";
import { n as isMessagingTool } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { r as isReplaySafeToolCall } from "./tool-mutation-BBJdXAL6.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { l as sliceToolResultTextToBudget } from "./tool-result-text-budget-DoGfZSLd.mjs";
import { r as resolveLiveToolResultMaxChars, t as DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS } from "./tool-result-limits-BISboI8s.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import { t as log } from "./logger-DgCpB-Fs.mjs";
import { a as normalizeAcceptedSessionSpawnResult } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { t as applyEmbeddedAttemptToolsAllow } from "./attempt-tool-construction-plan-Cp8YcsYs.mjs";
import "./json-schema-runtime-OTpXIHVF.mjs";
import { i as projectRuntimeToolInputSchema } from "./tool-schema-projection-D-AbMZEk.mjs";
import { n as normalizeAgentRuntimeTools } from "./tools-CX1i5Uw0.mjs";
import { t as buildAgentHookContextChannelFields } from "./hook-agent-context-sUFGgK45.mjs";
import { i as resolveMessageToolSourceReplyFinal, n as isDeliveredMessagingToolResult, t as isDeliveredMessageToolOnlySourceReplyResult } from "./embedded-agent-message-tool-source-reply-BLgXJNuN.mjs";
import { n as createAgentToolResultMiddlewareRunner } from "./tool-result-middleware-tMZkWoHr.mjs";
import "./agent-harness-runtime-BCklzcv7.mjs";
import { n as extractMessagingToolSendResult, r as extractMessagingToolSourceReplyPayload, t as extractMessagingToolSend } from "./embedded-agent-messaging-extraction-C5OCu-VM.mjs";
import { i as extractToolErrorMessage, l as readAsyncStartedTaskIds, o as isAsyncStartedToolResult, u as sanitizeToolResult } from "./embedded-agent-tool-results-DbtxSr9V.mjs";
import { t as collectMessagingMediaUrlsFromRecord } from "./embedded-agent-tool-media-Bzv7p-IE.mjs";
import { t as buildEmbeddedAttemptToolRunContext } from "./attempt-tool-run-context-DpLguX9-.mjs";
import "./agent-harness-attempt-runtime-DFFgKWgF.mjs";
import { n as recordAgentHarnessMessagingDelivery, r as recordAgentHarnessToolResultMedia } from "./tool-result-facts-C9Xta0St.mjs";
import { i as createAgentHarnessToolExecutionBoundaryRegistry, r as runAgentHarnessToolInvocation } from "./agent-harness-tool-runtime-CKwR4qJS.mjs";
import { v as normalizeOpenAIStrictCompatSchema } from "./provider-tools-BGinGjo7.mjs";
import { u as recordAgentsApiToolTranscript } from "./agentsapi-transcript-Cs7zhDPb.mjs";
//#region extensions/agentsapi/agentsapi-tools.ts
/** Gateway functions retain host authority; shell and file tools stay in the hosted VM. */
async function buildAgentsApiToolSurface(e, t, n, r) {
n();
const i = e.agentId;
if (!i) throw new Error("Agents API tool construction requires a resolved agent ID");
const a = e.disableMessageTool !== true && (e.forceMessageTool === true || e.sourceReplyDeliveryMode === "message_tool_only");
const o = buildEmbeddedAttemptToolRunContext({
...e,
forceMessageTool: a
});
const s = e.sandboxSessionKey ?? e.sessionKey;
const c = e.cwd ?? e.workspaceDir;
const l = buildAgentHookContextChannelFields({
...e,
sessionKey: s
}).channelId;
const u = e.hostCapabilities.createToolSurfaceAsync;
if (!u) throw new Error("Agents API tool construction requires a current host capability");
const d = e.disableTools ? [] : await u({
...o,
agentId: i,
policyAgentId: e.sandboxAgentId ?? i,
sessionKey: s,
runSessionKey: e.sessionKey !== s ? e.sessionKey : void 0,
sessionId: e.sessionId,
runId: e.runId,
config: e.config,
agentDir: e.agentDir ?? resolveAgentDir(e.config ?? {}, i),
workspaceDir: e.workspaceDir,
cwd: c,
sessionPermissionPolicy: resolveStoredSessionPermissionPolicy(e, e.workspaceDir),
requireWorkspaceOnly: e.requireWorkspaceOnly,
exec: {
...e.execOverrides,
config: e.config,
elevated: e.bashElevated
},
spawnWorkspaceDir: e.workspaceDir,
preparedModelRuntime: e.preparedModelRuntime,
skillsSnapshot: e.skillsSnapshot,
authProfileStore: e.toolAuthProfileStore ?? e.authProfileStore,
messageProvider: e.messageChannel ?? e.messageProvider,
messageChannel: e.messageChannel,
toolPolicyMessageProvider: e.messageProvider ?? e.messageChannel,
channelContext: e.channelContext,
hookChannelId: l,
inboundEventKind: e.currentInboundEventKind,
requireExplicitMessageTarget: e.requireExplicitMessageTarget ?? (e.sessionKey !== void 0 && isSubagentSessionKey(e.sessionKey)),
disableMessageTool: e.disableMessageTool,
forceMessageTool: a,
...e.onToolResult ? { questionPrompt: {
send: e.onToolResult,
messageChannel: e.messageChannel
} } : {},
inputProvenance: e.inputProvenance,
trustedInternalHandoff: e.trustedInternalHandoff,
delegationCapability: e.delegationCapability,
allowGatewaySubagentBinding: e.allowGatewaySubagentBinding,
githubPublicationAvailable: e.githubPublicationAvailable,
abortSignal: t,
onToolOutcome: e.onToolOutcome,
isTurnTainted: e.isTurnTainted,
allocateToolOutcomeOrdinal: e.allocateToolOutcomeOrdinal,
registerRunCleanup: r,
oneShotCliRun: e.oneShotCliRun,
modelProvider: e.model.provider,
modelId: e.modelId,
modelApi: e.model.api,
modelCompat: e.model.compat,
modelContextWindowTokens: e.contextTokenBudget ?? e.model.contextWindow,
modelHasVision: false,
includeToolSearchControls: false,
toolConstructionPlan: {
includeBaseCodingTools: false,
includeShellTools: false,
includeChannelTools: false,
includeOpenClawTools: true,
includePluginTools: true
}
}, { cwd: c });
n();
t.throwIfAborted();
const f = applyEmbeddedAttemptToolsAllow(d.filter((e) => e.name !== "web_search" && e.name !== "image_generate" && e.name !== "sessions_yield"), o.runtimeToolAllowlist, { toolMeta: getPluginToolMeta });
const p = normalizeAgentRuntimeTools({
tools: f,
runtimePlan: e.runtimePlan,
provider: e.provider,
config: e.config,
workspaceDir: e.workspaceDir,
modelId: e.modelId,
modelApi: e.model.api,
model: e.model,
allowProviderRuntimePluginLoad: false
});
finalizeAgentToolAvailability(p);
const m = p.toSorted((e, t) => e.name.localeCompare(t.name)).map((e) => {
const t = projectRuntimeToolInputSchema(normalizeOpenAIStrictCompatSchema(e.parameters) ?? e.parameters, `${e.name}.parameters`);
if (t.violations.length || !isRecord(t.schema)) throw new Error(`Agents API tool has an unsupported input schema: ${e.name}`);
return {
tool: e,
schema: t.schema,
validationCacheKey: `agentsapi-tool-input:${e.name}:${JSON.stringify(t.schema)}`
};
});
const h = new Map(m.map((e) => [e.tool.name, e]));
const g = m.map(({ tool: e, schema: t }) => ({
type: "function",
name: e.name,
description: e.description,
parameters: t
}));
const _ = createAgentToolResultMiddlewareRunner({
runtime: "agentsapi",
agentId: i,
sessionId: e.sessionId,
sessionKey: e.sessionKey,
runId: e.runId
});
const v = {
didSendViaMessagingTool: false,
messagingToolSentTexts: [],
messagingToolSentMediaUrls: [],
messagingToolSentTargets: [],
messagingToolSourceReplyPayloads: [],
toolMediaUrls: []
};
const y = [];
const b = { acceptedSessionSpawns: [] };
let x;
const S = createAgentHarnessToolExecutionBoundaryRegistry();
const C = e.contextTokenBudget ?? e.model.contextWindow;
const w = C === void 0 ? DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS : resolveLiveToolResultMaxChars({ contextWindowTokens: C });
return {
declarations: g,
delivery: v,
runtimeFacts: b,
toolMetas: y,
get lastToolError() {
return x;
},
execute: async (r) => {
n();
t.throwIfAborted();
const a = h.get(r.name);
let o;
let s = {};
let u;
let d = false;
let f = false;
let p = false;
let m = false;
let g = false;
let C = {};
let T = false;
let E = false;
const observeTerminal = (t, n, i) => {
if (d) return;
d = true;
u.capture();
s = u.executedArguments;
const o = a ? getPluginToolSideEffectOwnerKey(a.tool) : void 0;
const c = a ? getPluginToolMeta(a.tool) : void 0;
const l = e.observeToolTerminal?.({
toolCallId: r.call_id,
toolName: r.name,
arguments: s,
result: t,
outcome: n,
executionStarted: u.executionStarted,
replaySafe: !g && (!c || c.replaySafe === true) && isReplaySafeToolCall(r.name, s),
...o ? { ownerMutation: { ownerKey: o } } : {},
...i ? { failure: { error: i } } : {}
});
if (l) {
x = l.lastToolError;
if (l.executedArguments) s = l.executedArguments;
m = [
"not_started",
"read_completed",
"failed_no_effect"
].includes(l.effectReceipt.state);
}
};
const finishPresentation = (t, n) => {
if (f) return;
f = true;
y.push({
toolName: r.name,
toolCallId: r.call_id,
isError: n,
replaySafe: m,
...g ? {
asyncStarted: true,
...C
} : {},
...E ? { terminate: true } : {}
});
try {
e.onAgentToolResult?.({
toolName: r.name,
result: sanitizeToolResult(t),
isError: n
});
} catch (e) {
log.warn(`Agents API tool result observer failed: ${formatToolExecutionErrorMessage(e, "Unknown error")}`);
}
try {
finalizeToolTerminalPresentation({
toolCallId: r.call_id,
runId: e.runId,
toolName: r.name,
result: t,
isError: n,
observer: e.onToolOutcome
});
} catch (e) {
log.warn(`Agents API tool presentation observer failed: ${formatToolExecutionErrorMessage(e, "Unknown error")}`);
}
};
const dispatchAfterHook = (t, n) => {
if (p) return;
p = true;
runAgentHarnessAfterToolCallHook({
runId: e.runId,
agentId: i,
sessionId: e.sessionId,
sessionKey: e.sessionKey,
channelId: l,
toolName: r.name,
toolCallId: r.call_id,
startArgs: s,
...t !== void 0 ? { result: t } : {},
...n ? { error: n } : {},
startedAt: o
}).catch((e) => {
log.warn(`Agents API after-tool hook failed: ${formatToolExecutionErrorMessage(e, "Unknown error")}`);
});
};
const D = {
config: e.config,
currentChannelId: e.currentChannelId,
currentMessagingTarget: e.currentMessagingTarget,
currentThreadId: e.currentThreadTs,
currentMessageId: e.currentMessageId,
replyToMode: e.replyToMode,
hasRepliedRef: e.hasRepliedRef ? { value: e.hasRepliedRef.value } : void 0
};
const { transcriptResult: O, ...k } = await runAgentHarnessToolInvocation({
tool: a?.tool,
unavailableToolMessage: `OpenClaw tool is not available for this turn: ${r.name}`,
call: {
toolCallId: r.call_id,
toolName: r.name,
arguments: r.arguments,
turnId: r.turn_id,
cwd: c
},
runId: e.runId,
signal: t,
boundaries: S,
prepareArguments: (e) => {
if (!isRecord(e)) throw new Error(`Arguments for OpenClaw tool ${r.name} must be an object`);
return e;
},
assertCurrent: () => {
n();
t.throwIfAborted();
},
beforeExecute: async () => {
await e.onToolStreamBoundary?.();
n();
t.throwIfAborted();
},
validateArguments: a && getPluginToolMeta(a.tool)?.mcp?.operation !== "tool" ? (e) => {
n();
t.throwIfAborted();
const i = validateJsonSchemaValue({
schema: a.schema,
cacheKey: a.validationCacheKey,
value: e
});
if (!i.ok) throw new Error(`Invalid arguments for OpenClaw tool ${r.name}: ${i.errors.slice(0, 4).map((e) => e.text).join("; ")}`);
} : void 0,
applyMiddleware: (e) => _.applyToolResultMiddleware(e),
onExecutionResult: a ? (n) => {
u = n.boundary;
o = n.startedAt;
s = n.executedArguments;
const { rawResult: i, rawIsError: c } = n;
const l = a.tool;
g = !c && isAsyncStartedToolResult(i);
C = g ? readAsyncStartedTaskIds(i) : {};
const d = r.name === "sessions_spawn" && !c ? normalizeAcceptedSessionSpawnResult(i) : null;
if (d) b.acceptedSessionSpawns?.push(d);
T = r.name === "message" && asOptionalRecord(asOptionalRecord(i.details)?.messageDelivery)?.sourceReplyDelivered === true;
const f = isDeliveredMessageToolOnlySourceReplyResult({
sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
toolName: r.name,
args: s,
result: i,
isError: c
});
const p = resolveMessageToolSourceReplyFinal(s, e.messageToolFinalByDefault);
E = T && p || i.terminate === true && !(f && !p);
if (T) v.sourceReplyDelivered = true;
if (f || T) v.didDeliverSourceReplyViaMessageTool = true;
function recordDelivery(n) {
const r = s;
if (isMessagingTool(l.name) && isDeliveredMessagingToolResult({
toolName: l.name,
args: r,
result: i
})) {
const t = extractMessagingToolSourceReplyPayload(i);
if (t) recordAgentHarnessMessagingDelivery({
facts: v,
sourceReplyPayload: t,
sourceReplyFinal: p
});
else {
const t = {
provider: e.messageChannel ?? e.messageProvider,
...r
};
const a = extractMessagingToolSend(l.name, t, D);
const o = [
"message",
"text",
"content",
"body"
].map((e) => r[e]).find((e) => typeof e === "string" && e.trim().length > 0);
const s = collectMessagingMediaUrlsFromRecord(r);
recordAgentHarnessMessagingDelivery({
facts: v,
target: a ? extractMessagingToolSendResult(a, i) : void 0,
text: o,
mediaUrls: s,
sourceReplyFinal: n
});
}
}
if (t.aborted || isToolResultError(i)) return;
const a = getPluginToolMeta(l);
const o = a ? new Set(a.trustedLocalMedia === true ? [l.name] : []) : void 0;
const c = a && a.trustedLocalMedia !== true ? void 0 : l.name;
const u = recordAgentHarnessToolResultMedia({
facts: v,
toolName: c,
result: i,
trustedLocalMediaToolNames: o
});
if (!u) return;
if (u.trustedLocalMedia && (!a || a.trustedLocalMedia === true) && u.mediaUrls.length) v.toolTrustedLocalMedia = true;
}
recordDelivery(f ? p : void 0);
observeTerminal(i, c ? "failure" : "success", c ? extractToolErrorMessage(i) : void 0);
n.executedArguments = s;
} : void 0,
onResult: ({ result: e, observerResult: r, isError: i }) => {
finishPresentation(r, i);
n();
t.throwIfAborted();
dispatchAfterHook(e);
let a = "";
for (const t of e.content) {
if (a.length >= w) break;
const e = t.type === "text" ? t.text : "[Image result omitted from Agents API function output]";
a += `${a ? "\n" : ""}${sliceToolResultTextToBudget(e, w - a.length)}`;
}
a = sliceToolResultTextToBudget(a || "Tool completed with no text output.", w);
return {
transcriptResult: r,
...i ? {
success: false,
error: a
} : {
success: true,
output: a
}
};
},
onError: ({ error: e, boundary: r, executedArguments: i, rawResult: a, startedAt: c }) => {
u = r;
s = i;
o = c;
const l = formatToolExecutionErrorMessage(e, "OpenClaw tool failed");
const d = getBeforeToolCallFailureDisposition(e) ?? (t.aborted ? "cancelled" : resolveToolExecutionErrorKind(e));
const f = textResult(l, {
status: d,
error: l
});
observeTerminal(a ?? e, "failure", l);
finishPresentation(f, true);
t.throwIfAborted();
n();
dispatchAfterHook(void 0, l);
return {
transcriptResult: f,
success: false,
error: sliceToolResultTextToBudget(l, w)
};
}
});
await recordAgentsApiToolTranscript(e, r, O, !k.success, n);
return {
...k,
...E ? { terminate: true } : {}
};
}
};
}
//#endregion
export { buildAgentsApiToolSurface as t };