|
| 1 | +import type { IncomingMessage, ServerResponse } from "node:http"; |
| 2 | + |
| 3 | +import { loadConfig } from "../config/config.js"; |
| 4 | +import { resolveAgentIdFromSessionKey } from "../agents/agent-scope.js"; |
| 5 | +import { createClawdbotTools } from "../agents/clawdbot-tools.js"; |
| 6 | +import { |
| 7 | + resolveEffectiveToolPolicy, |
| 8 | + resolveGroupToolPolicy, |
| 9 | + isToolAllowedByPolicies, |
| 10 | +} from "../agents/pi-tools.policy.js"; |
| 11 | +import { normalizeMessageChannel } from "../utils/message-channel.js"; |
| 12 | + |
| 13 | +import { authorizeGatewayConnect, type ResolvedGatewayAuth } from "./auth.js"; |
| 14 | +import { getBearerToken, getHeader } from "./http-utils.js"; |
| 15 | +import { |
| 16 | + readJsonBodyOrError, |
| 17 | + sendInvalidRequest, |
| 18 | + sendJson, |
| 19 | + sendMethodNotAllowed, |
| 20 | + sendUnauthorized, |
| 21 | +} from "./http-common.js"; |
| 22 | + |
| 23 | +const DEFAULT_BODY_BYTES = 2 * 1024 * 1024; |
| 24 | + |
| 25 | +type ToolsInvokeBody = { |
| 26 | + tool?: unknown; |
| 27 | + action?: unknown; |
| 28 | + args?: unknown; |
| 29 | + sessionKey?: unknown; |
| 30 | + dryRun?: unknown; |
| 31 | +}; |
| 32 | + |
| 33 | +function resolveSessionKeyFromBody(body: ToolsInvokeBody): string | undefined { |
| 34 | + if (typeof body.sessionKey === "string" && body.sessionKey.trim()) return body.sessionKey.trim(); |
| 35 | + return undefined; |
| 36 | +} |
| 37 | + |
| 38 | +function mergeActionIntoArgsIfSupported(params: { |
| 39 | + toolSchema: unknown; |
| 40 | + action: string | undefined; |
| 41 | + args: Record<string, unknown>; |
| 42 | +}): Record<string, unknown> { |
| 43 | + const { toolSchema, action, args } = params; |
| 44 | + if (!action) return args; |
| 45 | + if (args.action !== undefined) return args; |
| 46 | + // TypeBox schemas are plain objects; many tools define an `action` property. |
| 47 | + const schemaObj = toolSchema as { properties?: Record<string, unknown> } | null; |
| 48 | + const hasAction = Boolean( |
| 49 | + schemaObj && |
| 50 | + typeof schemaObj === "object" && |
| 51 | + schemaObj.properties && |
| 52 | + "action" in schemaObj.properties, |
| 53 | + ); |
| 54 | + if (!hasAction) return args; |
| 55 | + return { ...args, action }; |
| 56 | +} |
| 57 | + |
| 58 | +export async function handleToolsInvokeHttpRequest( |
| 59 | + req: IncomingMessage, |
| 60 | + res: ServerResponse, |
| 61 | + opts: { auth: ResolvedGatewayAuth; maxBodyBytes?: number }, |
| 62 | +): Promise<boolean> { |
| 63 | + const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`); |
| 64 | + if (url.pathname !== "/tools/invoke") return false; |
| 65 | + |
| 66 | + if (req.method !== "POST") { |
| 67 | + sendMethodNotAllowed(res, "POST"); |
| 68 | + return true; |
| 69 | + } |
| 70 | + |
| 71 | + const token = getBearerToken(req); |
| 72 | + const authResult = await authorizeGatewayConnect({ |
| 73 | + auth: opts.auth, |
| 74 | + connectAuth: token ? { token } : null, |
| 75 | + req, |
| 76 | + }); |
| 77 | + if (!authResult.ok) { |
| 78 | + sendUnauthorized(res); |
| 79 | + return true; |
| 80 | + } |
| 81 | + |
| 82 | + const bodyUnknown = await readJsonBodyOrError(req, res, opts.maxBodyBytes ?? DEFAULT_BODY_BYTES); |
| 83 | + if (bodyUnknown === undefined) return true; |
| 84 | + const body = (bodyUnknown ?? {}) as ToolsInvokeBody; |
| 85 | + |
| 86 | + const toolName = typeof body.tool === "string" ? body.tool.trim() : ""; |
| 87 | + if (!toolName) { |
| 88 | + sendInvalidRequest(res, "tools.invoke requires body.tool"); |
| 89 | + return true; |
| 90 | + } |
| 91 | + |
| 92 | + const action = typeof body.action === "string" ? body.action.trim() : undefined; |
| 93 | + |
| 94 | + const argsRaw = body.args; |
| 95 | + const args = ( |
| 96 | + argsRaw && typeof argsRaw === "object" && !Array.isArray(argsRaw) |
| 97 | + ? (argsRaw as Record<string, unknown>) |
| 98 | + : {} |
| 99 | + ) as Record<string, unknown>; |
| 100 | + |
| 101 | + const sessionKey = resolveSessionKeyFromBody(body) ?? "main"; |
| 102 | + const cfg = loadConfig(); |
| 103 | + const agentId = resolveAgentIdFromSessionKey(sessionKey); |
| 104 | + |
| 105 | + // Resolve message channel/account hints (optional headers) for policy inheritance. |
| 106 | + const messageChannel = normalizeMessageChannel( |
| 107 | + getHeader(req, "x-clawdbot-message-channel") ?? "", |
| 108 | + ); |
| 109 | + const accountId = getHeader(req, "x-clawdbot-account-id")?.trim() || undefined; |
| 110 | + |
| 111 | + // Build tool list (core + plugin tools). |
| 112 | + const allTools = createClawdbotTools({ |
| 113 | + agentSessionKey: sessionKey, |
| 114 | + agentChannel: messageChannel ?? undefined, |
| 115 | + agentAccountId: accountId, |
| 116 | + config: cfg, |
| 117 | + }); |
| 118 | + |
| 119 | + const policy = resolveEffectiveToolPolicy({ config: cfg, sessionKey }); |
| 120 | + const groupPolicy = resolveGroupToolPolicy({ |
| 121 | + config: cfg, |
| 122 | + sessionKey, |
| 123 | + messageProvider: messageChannel ?? undefined, |
| 124 | + accountId: accountId ?? null, |
| 125 | + }); |
| 126 | + |
| 127 | + const allowed = (name: string) => |
| 128 | + isToolAllowedByPolicies(name, [ |
| 129 | + policy.globalPolicy, |
| 130 | + policy.agentPolicy, |
| 131 | + policy.globalProviderPolicy, |
| 132 | + policy.agentProviderPolicy, |
| 133 | + groupPolicy, |
| 134 | + ]); |
| 135 | + |
| 136 | + const tools = (allTools as any[]).filter((t) => allowed(t.name)); |
| 137 | + |
| 138 | + const tool = tools.find((t) => t.name === toolName); |
| 139 | + if (!tool) { |
| 140 | + sendJson(res, 404, { |
| 141 | + ok: false, |
| 142 | + error: { type: "not_found", message: `Tool not available: ${toolName}` }, |
| 143 | + }); |
| 144 | + return true; |
| 145 | + } |
| 146 | + |
| 147 | + try { |
| 148 | + const toolArgs = mergeActionIntoArgsIfSupported({ |
| 149 | + toolSchema: (tool as any).parameters, |
| 150 | + action, |
| 151 | + args, |
| 152 | + }); |
| 153 | + const result = await (tool as any).execute?.(`http-${Date.now()}`, toolArgs); |
| 154 | + sendJson(res, 200, { ok: true, result }); |
| 155 | + } catch (err) { |
| 156 | + sendJson(res, 400, { |
| 157 | + ok: false, |
| 158 | + error: { type: "tool_error", message: err instanceof Error ? err.message : String(err) }, |
| 159 | + }); |
| 160 | + } |
| 161 | + |
| 162 | + return true; |
| 163 | +} |
0 commit comments