Files
WeHub Mirror 6bf8bebf51
CI / Test and Build (push) Failing after 1s
CI / Migrate Dev DB (push) Has been skipped
CI / Migrate DB (push) Has been skipped
CodeQL / Analyze actions (push) Has been cancelled
CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI / Detect Version (push) Has been cancelled
CI / Detect Desktop Changes (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/cron.Dockerfile, ubuntu-latest, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build AMD64 (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/cron.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/db.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/pii.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/realtime.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-8vcpu-ubuntu-2404-arm, ./docker/app.Dockerfile, linux-arm64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
Helm Chart / Lint, test, and validate chart (push) Has been cancelled
Helm Chart / Chart version bumped (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Build Dev ECR (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core) (push) Has been cancelled
CI / Promote Images (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Check Desktop Signing Secrets (push) Has been cancelled
CI / Desktop Release (push) Has been cancelled
CI / Create Desktop Prerelease (push) Has been cancelled
CI / Desktop Prerelease Build (push) Has been cancelled
CI / Publish Desktop Prerelease (push) Has been cancelled
CI / Prune Desktop Prereleases (push) Has been cancelled
Helm Chart / Install on kind and run helm test (push) Has been cancelled
WeHub snapshot of cb28d14c6f2c081de7a0d8729a8c816c9adef67a
2026-08-10 11:17:50 +08:00

189 lines
6.0 KiB
TypeScript

import { createLogger } from '@sim/logger'
import { type PermissionType, permissionSatisfies } from '@sim/platform-authz/workspace'
import { toError } from '@sim/utils/errors'
import { projectToolErrorMessageForCopilot } from '@/lib/copilot/request/tools/resolved-secret-result'
import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/execution/constants'
import { executeTool as executeAppTool } from '@/tools'
import { getToolEntry, isClientExecuted, isKnownTool, isSimExecuted } from './router'
import type {
ToolCallDescriptor,
ToolExecutionContext,
ToolExecutionResult,
ToolHandler,
} from './types'
const logger = createLogger('ToolExecutor')
const FUNCTION_EXECUTE_TOOL_ID = 'function_execute'
const DEFAULT_FUNCTION_EXECUTE_TIMEOUT_SECONDS = 10
const MILLISECONDS_PER_SECOND = 1000
const handlerRegistry = new Map<string, ToolHandler>()
export function registerHandler(toolId: string, handler: ToolHandler): void {
handlerRegistry.set(toolId, handler)
}
export function registerHandlers(entries: Record<string, ToolHandler>): void {
for (const [toolId, handler] of Object.entries(entries)) {
handlerRegistry.set(toolId, handler)
}
}
export function getRegisteredToolIds(): string[] {
return Array.from(handlerRegistry.keys())
}
export function hasHandler(toolId: string): boolean {
return handlerRegistry.has(toolId)
}
export function clearHandlers(): void {
handlerRegistry.clear()
}
export async function executeTool(
toolId: string,
params: Record<string, unknown>,
context: ToolExecutionContext
): Promise<ToolExecutionResult> {
const requiredPermission = getToolEntry(toolId)?.requiredPermission
if (
requiredPermission &&
!permissionSatisfies(
(context.userPermission ?? null) as PermissionType | null,
requiredPermission
)
) {
return {
success: false,
error: `Permission denied: ${toolId} requires ${requiredPermission} access. You have '${context.userPermission ?? 'none'}' permission.`,
}
}
const normalizedParams = normalizeToolParams(toolId, params, context)
// Client-routed tools (e.g. run_workflow) are normally executed in the browser and never
// reach this point in interactive mode. In headless mode (Mothership block, no browser) there
// is no client to delegate to, so fall back to the registered server-side handler when one
// exists — otherwise the call would route to executeAppTool and throw "Tool not found".
const canUseRegisteredHandler =
isKnownTool(toolId) &&
(isSimExecuted(toolId) || (isClientExecuted(toolId) && hasHandler(toolId)))
if (!canUseRegisteredHandler) {
const appParams = buildAppToolParams(normalizedParams, context)
return context.resolvedSecretTraceRegistry
? executeAppTool(toolId, appParams, {
resolvedSecretTraceRegistry: context.resolvedSecretTraceRegistry,
})
: executeAppTool(toolId, appParams)
}
if (context.abortSignal?.aborted) {
logger.warn('Tool execution skipped: abort signal already set', {
toolId,
abortReason: context.abortSignal.reason ?? 'unknown',
})
return { success: false, error: 'Execution aborted: abort signal was set before tool started' }
}
const handler = handlerRegistry.get(toolId)
if (!handler) {
logger.warn('No handler registered for tool', { toolId })
return { success: false, error: `No handler for tool: ${toolId}` }
}
try {
return await handler(normalizedParams, context)
} catch (error) {
const message = toError(error).message
logger.error('Tool execution failed', {
toolId,
error: projectToolErrorMessageForCopilot(message, context.resolvedSecretTraceRegistry),
abortSignalAborted: context.abortSignal?.aborted ?? false,
})
return { success: false, error: message }
}
}
function normalizeToolParams(
toolId: string,
params: Record<string, unknown>,
context: ToolExecutionContext
): Record<string, unknown> {
if (toolId !== FUNCTION_EXECUTE_TOOL_ID || !context.copilotToolExecution) {
return params
}
const rawTimeoutSeconds =
params.timeout === undefined || params.timeout === null
? DEFAULT_FUNCTION_EXECUTE_TIMEOUT_SECONDS
: Number(params.timeout)
const timeoutSeconds =
Number.isFinite(rawTimeoutSeconds) && rawTimeoutSeconds > 0
? rawTimeoutSeconds
: DEFAULT_FUNCTION_EXECUTE_TIMEOUT_SECONDS
return {
...params,
timeout: Math.min(
Math.ceil(timeoutSeconds * MILLISECONDS_PER_SECOND),
DEFAULT_EXECUTION_TIMEOUT_MS
),
}
}
async function executeToolBatch(
toolCalls: ToolCallDescriptor[],
context: ToolExecutionContext
): Promise<Map<string, ToolExecutionResult>> {
const results = new Map<string, ToolExecutionResult>()
const executions = toolCalls.map(async ({ toolCallId, toolId, params }) => {
const result = await executeTool(toolId, params, context)
results.set(toolCallId, result)
})
await Promise.allSettled(executions)
for (const { toolCallId } of toolCalls) {
if (!results.has(toolCallId)) {
results.set(toolCallId, {
success: false,
error: 'Tool execution did not produce a result',
})
}
}
return results
}
function buildAppToolParams(
params: Record<string, unknown>,
context: ToolExecutionContext
): Record<string, unknown> {
const result = { ...params }
if (result.credentialId && !result.credential && !result.oauthCredential) {
result.credential = result.credentialId
}
result._context = {
...(typeof result._context === 'object' && result._context !== null
? (result._context as object)
: {}),
userId: context.userId,
workflowId: context.workflowId,
workspaceId: context.workspaceId,
chatId: context.chatId,
executionId: context.executionId,
runId: context.runId,
copilotToolExecution: context.copilotToolExecution,
requestMode: context.requestMode,
currentAgentId: context.currentAgentId,
enforceCredentialAccess: true,
...(context.billingAttribution ? { billingAttribution: context.billingAttribution } : {}),
}
return result
}