All files / api/src/middlewares tool.ts

81.45% Statements 101/124
78.57% Branches 22/28
100% Functions 4/4
81.45% Lines 101/124

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191    1x                                       1x 1x   1x                         10x 10x 10x 10x   10x   10x 10x 10x 10x 10x 10x   10x 10x 10x 10x   9x 9x 9x 9x   9x       9x 9x   1x 1x 1x 1x   1x       1x 1x   10x 10x 10x 10x       10x 10x 10x   10x 10x 1x 10x 9x 9x 1x 1x 1x 1x   10x 10x 10x     10x 10x 10x       10x 9x 10x   8x 8x 10x                           10x 10x 10x 10x 10x 10x 10x   10x 10x 10x   1x 10x 10x 10x   1x 1x 13x   13x     13x 2x 2x     11x 11x 2x 2x 13x 1x 1x   13x                 13x 10x 10x 10x 10x 10x 10x 10x 13x 1x  
import type { UserDataStorageConnector } from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import {
  type ChatCompletionRequestData,
  FunctionName,
  type ResponsesRequestData,
  type StreamChatCompletionRequestData,
} from '@shared/types/api/request';
import type {
  CodeInterpreter,
  ComputerTool,
  CustomTool,
  FileSearchTool,
  FunctionTool,
  ImageGeneration,
  LocalShell,
  Mcp,
  WebSearchTool,
} from '@shared/types/api/routes/responses-api/request';
import type { ChatCompletionTool } from '@shared/types/api/routes/shared/tools';
import type { ToolCreateParams } from '@shared/types/data/tool';
import type { Next } from 'hono';
import { getRuntimeKey } from 'hono/adapter';
import { createMiddleware } from 'hono/factory';
 
import stableStringify from 'json-stable-stringify';
 
type ResponsesTool =
  | FunctionTool
  | FileSearchTool
  | WebSearchTool
  | ComputerTool
  | Mcp
  | CodeInterpreter
  | ImageGeneration
  | LocalShell
  | CustomTool;
 
async function produceToolCache(
  completionTool: ChatCompletionTool | ResponsesTool,
): Promise<string> {
  const stringToHash = stableStringify(completionTool);
 
  const encodedHash = new TextEncoder().encode(stringToHash);
 
  const cacheDigest = await crypto.subtle.digest(
    {
      name: 'SHA-256',
    },
    encodedHash,
  );
 
  return Array.from(new Uint8Array(cacheDigest))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');
}
 
function getToolsFromChatCompletionRequest(
  saRequestData: ChatCompletionRequestData | StreamChatCompletionRequestData,
): ChatCompletionTool[] {
  const tools = saRequestData.requestBody.tools || [];
 
  if (!tools) {
    return [];
  }
 
  return tools;
}
 
function getToolsFromCreateModelResponseRequest(
  saRequestData: ResponsesRequestData,
): ResponsesTool[] {
  const tools = saRequestData.requestBody.tools || [];
 
  if (!tools) {
    return [];
  }
 
  return tools;
}
 
async function captureTool(
  c: AppContext,
  agent_id: string,
  saRequestData:
    | ChatCompletionRequestData
    | StreamChatCompletionRequestData
    | ResponsesRequestData,
  userDataStorageConnector: UserDataStorageConnector,
): Promise<void> {
  let completionTools: (ChatCompletionTool | ResponsesTool)[] = [];
 
  if (
    saRequestData.functionName === FunctionName.CHAT_COMPLETE ||
    saRequestData.functionName === FunctionName.STREAM_CHAT_COMPLETE
  ) {
    completionTools = getToolsFromChatCompletionRequest(saRequestData);
  } else if (
    saRequestData.functionName === FunctionName.CREATE_MODEL_RESPONSE
  ) {
    completionTools = getToolsFromCreateModelResponseRequest(saRequestData);
  }
 
  await Promise.all(
    completionTools.map(async (completionTool) => {
      const hash = await produceToolCache(completionTool);
 
      // Extract name based on tool type
      let toolName = '';
      if (completionTool.type === 'function') {
        if ('name' in completionTool) {
          // New ResponsesTool FunctionTool format
          toolName = completionTool.name as string;
        } else if (
          'function' in completionTool &&
          completionTool.function?.name
        ) {
          // Legacy ChatCompletionTool format
          toolName = (completionTool as ChatCompletionTool).function.name;
        }
      } else if (
        completionTool.type === 'mcp' &&
        'server_label' in completionTool
      ) {
        // MCP tools use server_label
        toolName = (completionTool as Mcp).server_label;
      } else if (completionTool.type === 'custom' && 'name' in completionTool) {
        // Custom tools have name
        toolName = (completionTool as CustomTool).name;
      } else {
        // For other tool types, use the type as name
        toolName = completionTool.type;
      }
 
      const tool: ToolCreateParams = {
        agent_id,
        hash,
        type: completionTool.type,
        name: toolName,
        raw_data: completionTool,
      };
 
      try {
        await userDataStorageConnector.createTool(c, tool);
      } catch {
        // If the tool already exists, we don't need to do anything
      }
    }),
  );
}
 
export const toolMiddleware = createMiddleware(
  async (c: AppContext, next: Next) => {
    await next();
 
    const saRequestData = c.get('sa_request_data');
 
    // If saRequestData is not set, it means that this is not an endpoint that we want to capture
    if (!saRequestData) {
      return;
    }
 
    // These are the endpoints that can contain tools
    if (
      saRequestData.functionName !== FunctionName.CHAT_COMPLETE &&
      saRequestData.functionName !== FunctionName.STREAM_CHAT_COMPLETE &&
      saRequestData.functionName !== FunctionName.CREATE_MODEL_RESPONSE
    ) {
      return;
    }
 
    if (getRuntimeKey() === 'workerd') {
      c.executionCtx.waitUntil(
        captureTool(
          c,
          c.get('agent').id,
          saRequestData,
          c.get('user_data_storage_connector'),
        ),
      );
    } else {
      await captureTool(
        c,
        c.get('agent').id,
        saRequestData,
        c.get('user_data_storage_connector'),
      );
    }
  },
);