openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
709 lines (708 loc) • 26.5 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { d as withPluginRuntimeRegistryScope, o as getPluginRuntimeGatewayRequestScope, r as getInProcessGatewayRequestContext } from "./gateway-request-scope-BvvDhs5D.mjs";
import "./model-ref-shared-DqE2RqZv.mjs";
import { C as resolveSessionAgentIds, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as resolveExternalPackageRuntimeEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { T as selectLiveRuntimeConfig, a as getRuntimeConfigSnapshot, n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { d as getActivePluginRegistryVersion, l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import { o as runOutsideCommandProcessScope } from "./exec-spawn-DMKoejF-.mjs";
import "./exec-aRIvS9s4.mjs";
import { o as resolveMessageActionTurnAuthorization, s as resolveMessageActionTurnCapability, u as selectMessageActionRequesterIdentity } from "./message-action-turn-capability-CQk0hiot.mjs";
import { i as bindOperatorModelExecution, t as assertAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { d as NODE_MCP_TOOL_CALL_TIMEOUT_MS, f as NODE_PLUGIN_TOOL_CALL_GATEWAY_TIMEOUT_MS, l as NODE_MCP_TOOLS_CALL_COMMAND, p as NODE_PLUGIN_TOOL_CALL_TIMEOUT_MS, u as NODE_MCP_TOOL_CALL_GATEWAY_TIMEOUT_MS } from "./node-commands-BfMJIlXP.mjs";
import { c as normalizeDeliveryContext } from "./delivery-context.shared-CRlipPTj.mjs";
import { c as sanitizeServerName, s as sanitizeNodeIdFragment } from "./agent-bundle-mcp-names-856aMFJA.mjs";
import "./tool-policy-BR4v75RA.mjs";
import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs";
import { n as matchesAnyGlobPattern, t as compileGlobPatterns } from "./glob-pattern-BfbeUKrV.mjs";
import { t as captureGatewayToolCallerAssertion } from "./gateway-caller-context-BNidAW8G.mjs";
import { o as setPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { n as jsonResult } from "./tool-results-CcV0sxnb.mjs";
import "./common-njQNtpnW.mjs";
import "./config-CMA-J084.mjs";
import { t as shellEscape } from "./shell-quote-DeRN90_2.mjs";
import { x as SANDBOX_COMMAND_MAX_BUFFER_BYTES } from "./constants-Dxjr8D5t.mjs";
import { n as resolveWorkspaceRoot } from "./workspace-dir-VdDz3_sC.mjs";
import { a as resolveAuthProfileOrder } from "./order-jOvee2J6.mjs";
import { r as getPluginRuntimeLoadContext } from "./load-context-CwTU1iXB.mjs";
import { m as resolveProviderAuthScope } from "./loader-runtime-load-Ba16vW6K.mjs";
import { r as PreparedModelRuntimePublicationSupersededError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs";
import "./prepared-model-runtime.errors-BRsU9-dm.mjs";
import "./remote-shell-command-fpopw-g2.mjs";
import { n as resolveApiKeyForProfile } from "./oauth--EeX6RHc.mjs";
import { t as captureAgentWorkspaceReadiness } from "./workspace-readiness-ClUjI0tp.mjs";
import { t as normalizeConversationReadInvocationOrigin } from "./conversation-read-origin-DMlgOstF.mjs";
import { a as resolvePluginToolsSteps, i as resolvePluginTools } from "./tools-B02IB3vZ.mjs";
import { n as assertMemoryAudienceSession, t as assertMemoryAudienceCurrent } from "./memory-audience-RRQiHS6M.mjs";
import { n as createPluginToolAllowlist } from "./tool-grant-allowlist-BZ6u_mqs.mjs";
import { t as canonicalizePath } from "./paths-CS5Q7ATF.mjs";
import { t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import { s as bindRequesterOwnerIdentity } from "./cron-creator-authority-context-D4fHKVAj.mjs";
import { i as resolveToolResultBudget, n as assertCompleteToolResult } from "./tool-result-limits-BISboI8s.mjs";
import { n as resolveAgentScopedOutboundMediaAccess } from "./read-capability-XYUFrpMj.mjs";
import { a as setMcpCodeModeGuestResultFromAgentResult, n as projectMcpCallToolResult } from "./mcp-content-CYbca1LN.mjs";
import "./auth-profiles-VRLhewIH.mjs";
import { t as resolveApiKeyForProviderCore } from "./model-auth-provider-CRnOp_fz.mjs";
import { n as hasRuntimeAvailableProviderAuth, t as createRuntimeProviderAuthLookup } from "./model-auth-runtime-BVYiZt5s.mjs";
import "./model-auth-CEsyk_Yg.mjs";
import { o as hasProviderAuthForTool } from "./model-config.helpers-FXb3KJo5.mjs";
import { n as getAgentToolAssistantTurnId } from "./tool-execution-context-D0eUSg2-.mjs";
import { n as prepareSandboxProcessCleanup } from "./process-cleanup-B7odWFkl.mjs";
import { i as resolveProtectedSandboxDirectory } from "./fs-paths-BcNIEM2k.mjs";
import { r as listConnectedNodePluginTools } from "./node-plugin-tool-snapshot-CrPIkFh2.mjs";
import { fileURLToPath } from "node:url";
import path from "node:path";
//#region src/agents/openclaw-tools.plugin-context.ts
function resolveOpenClawPluginToolInputs(e) {
const { options: t, resolvedConfig: n, runtimeConfig: r, getRuntimeConfig: i } = e;
const a = t?.runSessionKey ?? t?.agentSessionKey;
if (t?.memoryAudience) assertMemoryAudienceSession(t.memoryAudience, a);
const { sessionAgentId: o } = resolveSessionAgentIds({
sessionKey: a,
config: n,
agentId: t?.requesterAgentIdOverride
});
const s = t?.workspaceDir || !n ? void 0 : resolveAgentWorkspaceDir(n, o);
const c = resolveWorkspaceRoot(t?.workspaceDir ?? s);
const l = t?.modelProvider?.trim();
const u = t?.modelId?.trim();
const d = l || u ? {
...l ? { provider: l } : {},
...u ? { modelId: u } : {},
...l && u ? { modelRef: modelKey(l, u) } : {}
} : void 0;
const f = normalizeDeliveryContext({
channel: t?.agentChannel,
to: t?.agentTo ?? t?.currentMessagingTarget ?? t?.currentChannelId,
accountId: t?.agentAccountId,
threadId: t?.agentThreadId
});
return {
context: {
config: t?.config,
runtimeConfig: r,
getRuntimeConfig: i,
assertInputCommitAllowed: t?.assertInputCommitAllowed,
fsPolicy: t?.fsPolicy,
workspaceDir: c,
agentDir: t?.agentDir,
agentId: o,
sessionKey: a,
sessionId: t?.sessionId,
runId: t?.runId,
inputProvenance: t?.inputProvenance,
approvalReviewerDeviceIds: t?.approvalReviewerDeviceIds ? [...t.approvalReviewerDeviceIds] : t?.approvalReviewerDeviceId ? [t.approvalReviewerDeviceId] : void 0,
toolBindings: t?.toolBindings,
activeProjectKeys: t?.activeProjectKeys,
conversationRecall: t?.conversationRecall,
activeModel: d,
browser: {
sandboxBridgeUrl: t?.sandboxBrowserBridgeUrl,
allowHostControl: t?.allowHostBrowserControl,
...t?.assertLocalBrowserLoopbackCurrent ? { assertLocalLoopbackCurrent: t.assertLocalBrowserLoopbackCurrent } : {},
...t?.allowLocalBrowserLoopback !== void 0 ? { allowLocalLoopback: t.allowLocalBrowserLoopback } : {}
},
messageChannel: t?.agentChannel,
agentAccountId: t?.agentAccountId,
deliveryContext: f,
nativeChannelId: t?.nativeChannelId,
requesterSenderId: t?.requesterSenderId ?? void 0,
senderIsOwner: t?.senderIsOwner,
memoryAudience: t?.memoryAudience,
memoryFlush: t?.memoryFlush,
assertMemoryAudienceCurrent: t?.memoryAudience ? () => assertMemoryAudienceCurrent(t.memoryAudience) : void 0,
conversationReadOrigin: normalizeConversationReadInvocationOrigin(t?.conversationReadOrigin),
sandboxed: t?.sandboxed,
oneShotCliRun: t?.oneShotCliRun
},
allowGatewaySubagentBinding: t?.allowGatewaySubagentBinding
};
}
//#endregion
//#region src/plugins/requester-models.ts
/** Host-only minting: callers cannot supply selectors through the plugin-facing reader. */
function createPluginRequesterModels(e) {
const { authority: t, config: n, agentId: r, sessionKey: i, sessionId: a } = e;
if (!t || !n || !r || !i || !a) return;
assertAdmittedRunOperatorAuthority(t);
const o = getInProcessGatewayRequestContext();
const s = o?.getRuntimeConfig ?? createRuntimeConfigReader(n);
const assertCurrent = () => {
e.signal?.throwIfAborted();
e.assertCurrent();
t.assertCurrent();
};
return Object.freeze({ async list() {
assertCurrent();
const { readRequesterModelCatalog: n } = await import("./requester-model-catalog-BwiteA-Z.mjs");
assertCurrent();
const c = s();
const assertReadCurrent = () => {
assertCurrent();
if (s() !== c) throw new PreparedModelRuntimePublicationSupersededError("Requester config changed. Retry the request.");
};
const l = await n({
config: c,
agentId: r,
sessionKey: i,
sessionId: a,
authority: t,
preparedModelRuntime: e.preparedModelRuntime,
context: o,
assertCurrent: assertReadCurrent
});
assertReadCurrent();
return l;
} });
}
//#endregion
//#region src/agents/plugin-tool-execution.ts
/** Capture once at assembly; a retained plugin never resolves a later run's sandbox or identity. */
function preparePluginToolExecutionCapabilities(e) {
const t = e.sandbox;
const n = t?.backend;
const r = t?.workspaceCwd ? t.fsBridge?.resolvePath({
filePath: t.workspaceCwd,
cwd: t.workspaceDir
}).containerPath : t?.containerWorkdir;
const i = e.authority;
const a = i ? resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url }) : null;
const o = {};
if (t && n?.capabilities?.readOnlyResourceMounts) {
const n = e.skillsSnapshot;
for (const e of n?.discoverySkills ?? n?.resolvedSkills ?? []) {
if (![
"openclaw-managed",
"openclaw-library",
"openclaw-bundled",
"agents-skills-personal"
].includes(e.source) || e.disableModelInvocation || e.fileHost === "workspace") continue;
const r = n?.skills.find((t) => t.name === e.name)?.source;
if (r?.fileHost === "workspace") continue;
const i = r?.filePath ?? e.filePath;
const a = canonicalizePath(i);
const s = t.skillUsagePaths?.find((t) => t.skillName === e.name && t.skillFile === a);
if (!s) continue;
const c = resolveProtectedSandboxDirectory(t, path.dirname(s.readPath), path.dirname(i));
if (c) o[e.name] = c;
}
}
const s = resolveToolResultBudget(e.modelContextWindowTokens);
return (t, c) => ({
runtimeContext: { models: i ? createPluginRequesterModels({
...e,
assertCurrent: t,
signal: AbortSignal.any([e.signal, c].filter((e) => Boolean(e)))
}) : void 0 },
assertCompleteResult(e) {
t();
assertCompleteToolResult(e, s);
},
...i && a ? { modelExecution: {
cliEntryPath: fileURLToPath(resolveExternalPackageRuntimeEntrypointUrl("cliLauncher", a)),
async run(n, r, a) {
const o = AbortSignal.any([
e.signal,
c,
a,
i.signal
].filter((e) => Boolean(e)));
const assertCallerCurrent = () => {
o.throwIfAborted();
t();
i.assertCurrent();
};
assertCallerCurrent();
const [{ resolveAmbientOwnerAgentId: s }, { resolveDefaultModelForAgent: l }, { resolveModelRefFromString: u }, { createModelVisibilityPolicy: d }, { resolveOperatorModelDefault: f }] = await Promise.all([
import("./agent-scope-config-B1XZecUN.mjs"),
import("./model-selection-config-BIm6J9II.mjs"),
import("./model-selection-resolve-CfuUki4q.mjs"),
import("./model-visibility-policy-CznG3zb6.mjs"),
import("./operator-model-policy-7A5eUYK2.mjs")
]);
assertCallerCurrent();
const p = e.config ?? {};
const m = s(p, e.agentId);
const h = {
cfg: p,
agentId: m,
manifestPlugins: e.preparedModelRuntime?.metadataSnapshot
};
const g = l(h);
const _ = d({
...h,
catalog: e.preparedModelRuntime?.modelCatalog.entries ?? [],
defaultProvider: g.provider,
defaultModel: g
});
const v = n.model === null ? g : u({
...h,
raw: n.model,
defaultProvider: g.provider,
aliasIndex: _.selectionAliasIndex
})?.ref;
const y = v && (_.allows(v) ? v : n.explicit ? void 0 : _.resolveSelection({
...g,
routeResolution: "resolved"
}));
if (!y) throw new Error("No permitted reviewer model is available for this agent.");
const b = n.explicit ? y : f({
...h,
policy: i.modelPolicy,
model: y,
allows: _.allows
});
if (!b) throw new Error("No permitted reviewer model is available for this caller.");
const x = bindOperatorModelExecution(i, b);
const S = AbortSignal.any([x.signal, o]);
const assertCurrent = () => {
S.throwIfAborted();
assertCallerCurrent();
x.assertCurrent();
};
try {
assertCurrent();
const e = await r({
signal: S,
assertCurrent,
model: `${b.provider}/${b.model}`,
agentId: m
});
assertCurrent();
return e;
} finally {
x.release();
}
}
} } : {},
...n && r ? { sandbox: {
workspaceDir: r,
installedSkillRoots: Object.freeze(o),
async run({ argv: i, input: a, signal: o, maxOutputBytes: s = 4e6 }) {
try {
var l = _usingCtx();
const u = AbortSignal.any([
e.signal,
c,
o
].filter((e) => Boolean(e)));
const assertCurrent = () => {
u.throwIfAborted();
t();
};
assertCurrent();
if (!Number.isSafeInteger(s) || s < 1 || s > 104857600) throw new Error("Sandbox command output limit is outside the supported range.");
const d = prepareSandboxProcessCleanup(n, {});
const f = await n.buildExecSpec({
command: i.map(shellEscape).join(" "),
workdir: r,
env: d.env,
usePty: false,
stdin: a !== void 0
});
let p = false;
let m = null;
let h = false;
const g = l.a(new AsyncDisposableStack());
g.defer(async () => {
await n.finalizeExec?.({
status: p ? "completed" : "failed",
exitCode: m,
timedOut: h,
token: f.finalizeToken
});
});
g.defer(async () => {
if (!p) await runOutsideCommandProcessScope(() => d.terminate());
});
assertCurrent();
f.assertCurrent?.();
if (a !== void 0 && f.stdinMode !== "pipe-open") throw new Error("This sandbox backend does not support piped command input.");
const _ = await runCommandWithTimeout(f.argv, {
cwd: f.cwd,
baseEnv: f.env,
input: a ?? "",
signal: u,
killProcessTree: true,
maxOutputBytes: s,
outputCapture: "head",
terminateOnOutputLimit: true
});
p = _.termination === "exit" && !_.outputLimitExceeded && !_.stdoutTruncatedBytes && !_.stderrTruncatedBytes && _.cleanup !== "uncertain";
m = _.code;
h = _.termination === "timeout";
assertCurrent();
if (!p) throw new Error(`Sandbox command did not complete (${_.termination}).`);
return {
stdout: _.stdout,
stderr: _.stderr,
code: _.code ?? 1
};
} catch (e) {
l.e = e;
} finally {
await l.d();
}
}
} } : {}
});
}
//#endregion
//#region src/agents/openclaw-plugin-tools.ts
const NODE_PLUGIN_TOOL_NAME_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
const NODE_PLUGIN_TOOL_NAME_MAX_LENGTH = 64;
const NODE_MCP_PLUGIN_ID = "node-mcp";
function isAgentToolResult(e) {
return isRecord(e) && Array.isArray(e.content);
}
const loadMessageActionRunner = createLazyRuntimeModule(() => import("./message-action-runner-DkLM2ujR.mjs"));
function createPluginToolDelivery(e) {
const t = e.context.deliveryContext;
const n = e.context.agentId;
const r = e.context.sessionKey;
const i = e.context.sessionId;
const a = e.context.senderIsOwner;
const o = e.context.conversationReadOrigin;
const s = e.options?.runId;
const c = captureAgentWorkspaceReadiness(e.options?.runSessionKey ?? e.options?.agentSessionKey);
const l = e.options?.messageActionTurnCapability;
const u = getActivePluginRegistry();
const d = getActivePluginRegistryVersion();
if (!t?.channel || !t.to || !n || !r || !s || !l || !u) return;
const f = {
token: l,
agentId: n,
runId: s,
sessionKey: e.options?.agentSessionKey ?? r,
sessionId: i
};
const p = resolveMessageActionTurnAuthorization(f);
if (p?.scheduled || p?.deliveryAttempt) return;
if ((u.channels.find((e) => e.plugin.id === t.channel)?.plugin)?.outbound?.deliveryMode === "gateway") return;
const m = {
channel: t.channel,
to: t.to,
accountId: t.accountId,
threadId: t.threadId
};
const resolveAuthorization = () => {
if (getActivePluginRegistry() !== u || getActivePluginRegistryVersion() !== d) throw new Error("plugin delivery capability is no longer active");
const e = resolveMessageActionTurnCapability(f);
if (!e) throw new Error("plugin delivery capability is no longer active");
return e;
};
const h = resolveAuthorization();
const g = e.bindingConfig;
if (!g) return;
const _ = resolveAgentScopedOutboundMediaAccess({
cfg: g,
agentId: n,
workspaceDir: e.context.workspaceDir,
sessionKey: r,
accountId: h.requesterAccountId ?? m.accountId,
requesterSenderId: h.requesterSenderId,
requesterSenderName: h.requesterSenderName,
requesterSenderUsername: h.requesterSenderUsername,
requesterSenderE164: h.requesterSenderE164
});
return { send: async ({ text: t, mediaUrl: l }) => {
resolveAuthorization();
const { runMessageAction: d } = await loadMessageActionRunner();
const f = resolveAuthorization();
const p = e.resolveConfig();
if (!p) throw new Error("plugin delivery requires an active runtime config");
await withPluginRuntimeRegistryScope(u, () => d({
cfg: p,
action: "send",
params: {
channel: m.channel,
target: m.to,
...m.accountId ? { accountId: m.accountId } : {},
...m.threadId != null ? { threadId: m.threadId } : {},
...t !== void 0 ? { message: t } : {},
...l !== void 0 ? { mediaUrl: l } : {}
},
defaultAccountId: m.accountId,
...selectMessageActionRequesterIdentity(f),
messageActionAuthorization: {
requesterAccountId: f.requesterAccountId,
requesterSenderId: f.requesterSenderId,
toolContext: f.toolContext
},
senderIsOwner: a,
conversationReadOrigin: o,
toolContext: f.toolContext,
sessionKey: r,
sessionId: i,
runId: s,
agentId: n,
mediaAccess: _,
workspaceReadiness: c,
onPlatformSendDispatch: async () => {
resolveAuthorization();
},
forceCoreDelivery: true,
skipQueue: true,
dryRun: false
}));
resolveAuthorization();
} };
}
async function resolveOpenClawPluginToolsForOptionsAsync(e) {
const t = resolveOpenClawPluginToolSteps(e);
let n = t.next();
while (!n.done) {
await n.value;
n = t.next();
}
return n.value;
}
function resolveOpenClawPluginToolsForOptions(e) {
const t = resolveOpenClawPluginToolSteps(e).next();
if (!t.done) {
t.value.catch(() => {});
throw new Error("Workspace preparation is pending; use asynchronous tool construction.");
}
return t.value;
}
function* resolveOpenClawPluginToolSteps(e) {
const t = e.resolvedConfig ?? e.options?.config;
const n = selectLiveRuntimeConfig(t);
const r = t === void 0 || n === getRuntimeConfigSnapshot();
const resolveCurrentRuntimeConfig = () => r ? selectLiveRuntimeConfig() : n;
const i = resolveOpenClawPluginToolInputs({
options: e.options,
resolvedConfig: e.resolvedConfig,
runtimeConfig: n,
getRuntimeConfig: resolveCurrentRuntimeConfig
});
const a = e.options?.authProfileStore;
const o = i.context.senderIsOwner === true ? void 0 : bindRequesterOwnerIdentity({
runId: e.options?.runId,
sessionKey: i.context.sessionKey,
sessionId: i.context.sessionId,
agentId: i.context.agentId
});
const s = createPluginToolDelivery({
options: e.options,
context: i.context,
bindingConfig: n,
resolveConfig: resolveCurrentRuntimeConfig
});
const c = a ? createRuntimeProviderAuthLookup({
cfg: n,
workspaceDir: i.context.workspaceDir,
includePluginSyntheticAuth: false
}) : void 0;
const l = a ? (t) => hasProviderAuthForTool({
provider: t,
cfg: n,
workspaceDir: i.context.workspaceDir,
agentDir: e.options?.agentDir,
authStore: a,
runtimeLookup: c
}) : void 0;
const u = a ? async (t) => {
const n = resolveCurrentRuntimeConfig();
const r = i.context.workspaceDir;
if (resolveProviderAuthScope({
provider: t,
config: n,
workspaceDir: r
}) === "plugin") return;
for (const r of resolveAuthProfileOrder({
cfg: n,
store: a,
provider: t,
includePendingOAuthRefresh: true
})) {
const t = await resolveApiKeyForProfile({
cfg: n,
store: a,
profileId: r,
agentDir: e.options?.agentDir
});
if (t?.apiKey) return t.apiKey;
}
const o = createRuntimeProviderAuthLookup({
cfg: n,
workspaceDir: r,
includePluginSyntheticAuth: false
});
if (!hasRuntimeAvailableProviderAuth({
provider: t,
cfg: n,
workspaceDir: r,
allowPluginSyntheticAuth: false,
runtimeLookup: o
})) return;
try {
return (await resolveApiKeyForProviderCore({
provider: t,
cfg: n,
store: a,
agentDir: e.options?.agentDir,
workspaceDir: r,
credentialPrecedence: "env-first",
allowAuthProfileFallback: false
})).apiKey;
} catch {
return;
}
} : void 0;
const d = new Set(e.existingToolNames ?? []);
const f = e.options?.preparedModelRuntime;
const p = getPluginRuntimeGatewayRequestScope()?.pluginRegistry;
const m = p ?? getActivePluginRegistry() ?? void 0;
const h = f ? f.pluginRegistry : p;
const g = getPluginRuntimeLoadContext(h);
const _ = f?.metadataSnapshot ?? g?.metadataSnapshot;
const v = captureGatewayToolCallerAssertion();
const y = e.options?.assertInvocationCurrent;
const b = {
...i,
bindExecutionCapabilities: preparePluginToolExecutionCapabilities({
sandbox: e.options?.sandbox?.enabled ? e.options.sandbox : void 0,
skillsSnapshot: e.options?.pluginExecutionSkillsSnapshot,
signal: e.options?.abortSignal,
authority: e.options?.pluginExecutionAuthority,
modelContextWindowTokens: e.options?.modelContextWindowTokens,
preparedModelRuntime: f,
config: n,
agentId: i.context.agentId,
sessionKey: i.context.sessionKey,
sessionId: i.context.sessionId
}),
context: {
...i.context,
...s ? { delivery: s } : {},
...l ? { hasAuthForProvider: l } : {},
...u ? { resolveApiKeyForProvider: u } : {}
},
existingToolNames: d,
assertInvocationCurrent: y ? () => {
v?.();
y();
} : v,
ownerContinuation: o,
clientCaps: e.options?.clientCaps,
toolAllowlist: e.options?.pluginToolAllowlist,
toolDenylist: e.options?.pluginToolDenylist,
allowGatewaySubagentBinding: e.options?.allowGatewaySubagentBinding,
...l ? { hasAuthForProvider: l } : {},
...m ? { runtimeRegistry: m } : {},
..._ ? { preparedRuntime: {
loadContext: g,
metadataSnapshot: _,
registry: h
} } : {}
};
const x = captureAgentWorkspaceReadiness(i.context.sessionKey) ? yield* resolvePluginToolsSteps(b) : resolvePluginTools(b);
for (const e of x) d.add(e.name);
const S = i.context.sessionKey;
const C = new Set([...d].map(normalizeToolPolicyName));
const w = createPluginToolAllowlist(e.options?.pluginToolAllowlist);
const T = compileGlobPatterns({
raw: e.options?.pluginToolDenylist,
normalize: normalizeToolPolicyName
});
const E = [];
const D = /* @__PURE__ */ new Map();
for (const e of listConnectedNodePluginTools()) {
const t = e.descriptor;
const n = t.command?.trim();
const r = normalizeToolPolicyName(t.name);
if (!n || !r) continue;
E.push({
...e,
command: n,
normalizedName: r
});
D.set(r, (D.get(r) ?? 0) + 1);
}
for (const e of E) {
const t = e.descriptor;
let n = t.name;
if ((D.get(e.normalizedName) ?? 1) !== 1 || C.has(e.normalizedName)) {
n = void 0;
const r = `${sanitizeNodeIdFragment(e.nodeId)}_`;
for (let e = 0; e < 100; e += 1) {
const i = e === 0 ? "" : `_${e + 1}`;
const a = Math.max(1, NODE_PLUGIN_TOOL_NAME_MAX_LENGTH - r.length - i.length);
const o = `${r}${t.name.slice(0, a)}${i}`;
const s = normalizeToolPolicyName(o);
if (NODE_PLUGIN_TOOL_NAME_RE.test(o) && s && !C.has(s)) {
n = o;
break;
}
}
}
if (!n) continue;
const r = normalizeToolPolicyName(t.pluginId);
const i = normalizeToolPolicyName(n);
if (matchesAnyGlobPattern(r, T) || matchesAnyGlobPattern(e.normalizedName, T) || matchesAnyGlobPattern(i, T) || matchesAnyGlobPattern("group:plugins", T)) continue;
const a = e.registered || r === NODE_MCP_PLUGIN_ID;
if (!w.includesDefaults && !(a && w.allowsPlugin(r) || w.allowsToolName(e.normalizedName) || w.allowsToolName(i))) continue;
C.add(i);
const o = t.command === "mcp.tools.call.v1" ? t.mcp : void 0;
const s = {
name: n,
label: n,
description: `${t.description} (node: ${e.displayName?.trim() || e.nodeId})`,
parameters: t.parameters,
...o ? {
executionMode: "sequential",
resultContentSource: "network"
} : {},
execute: async (n, r, i) => {
const a = getAgentToolAssistantTurnId();
const s = await callGatewayTool("node.invoke", { timeoutMs: o ? NODE_MCP_TOOL_CALL_GATEWAY_TIMEOUT_MS : NODE_PLUGIN_TOOL_CALL_GATEWAY_TIMEOUT_MS }, {
nodeId: e.nodeId,
command: e.command,
params: o ? {
server: o.server,
tool: o.tool,
arguments: r
} : r,
timeoutMs: o ? NODE_MCP_TOOL_CALL_TIMEOUT_MS : NODE_PLUGIN_TOOL_CALL_TIMEOUT_MS,
idempotencyKey: a ? `${a}:${n}` : n,
...S ? { sessionKey: S } : {}
}, {
scopes: ["operator.write"],
...i ? { signal: i } : {}
});
const c = isRecord(s) && "payload" in s ? s.payload : s;
if (o) return isRecord(c) ? projectMcpCallToolResult(c, {
mcpServer: o.server,
mcpTool: o.tool
}) : jsonResult(c);
const l = isAgentToolResult(c) ? c : jsonResult(c);
return t.mcp ? setMcpCodeModeGuestResultFromAgentResult(l) : l;
}
};
setPluginToolMeta(s, {
pluginId: t.pluginId,
optional: false,
...t.mcp ? { mcp: {
serverName: t.mcp.server,
safeServerName: sanitizeServerName(t.mcp.server, /* @__PURE__ */ new Set()),
toolName: t.mcp.tool,
operation: "tool",
...t.pluginId === NODE_MCP_PLUGIN_ID && o ? { node: {
id: e.nodeId,
...e.displayName?.trim() ? { displayName: e.displayName.trim() } : {}
} } : {}
} } : {}
});
x.push(s);
}
return x;
}
//#endregion
export { resolveOpenClawPluginToolsForOptionsAsync as n, createPluginRequesterModels as r, resolveOpenClawPluginToolsForOptions as t };