@dainprotocol/service-sdk 2.0.46 → 2.0.48-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/__tests__/api-sdk.test.d.ts +1 -0
  2. package/dist/__tests__/api-sdk.test.js +102 -0
  3. package/dist/__tests__/api-sdk.test.js.map +1 -0
  4. package/dist/__tests__/auth.test.d.ts +1 -0
  5. package/dist/__tests__/auth.test.js +110 -0
  6. package/dist/__tests__/auth.test.js.map +1 -0
  7. package/dist/__tests__/citations-plugin.test.d.ts +1 -0
  8. package/dist/__tests__/citations-plugin.test.js +491 -0
  9. package/dist/__tests__/citations-plugin.test.js.map +1 -0
  10. package/dist/__tests__/context-behavior.test.d.ts +1 -0
  11. package/dist/__tests__/context-behavior.test.js +290 -0
  12. package/dist/__tests__/context-behavior.test.js.map +1 -0
  13. package/dist/__tests__/convertToVercelTool.test.d.ts +1 -0
  14. package/dist/__tests__/convertToVercelTool.test.js +527 -0
  15. package/dist/__tests__/convertToVercelTool.test.js.map +1 -0
  16. package/dist/__tests__/core.test.d.ts +1 -0
  17. package/dist/__tests__/core.test.js +154 -0
  18. package/dist/__tests__/core.test.js.map +1 -0
  19. package/dist/__tests__/crypto-plugin.test.d.ts +1 -0
  20. package/dist/__tests__/crypto-plugin.test.js +694 -0
  21. package/dist/__tests__/crypto-plugin.test.js.map +1 -0
  22. package/dist/__tests__/humanActions.test.d.ts +1 -0
  23. package/dist/__tests__/humanActions.test.js +221 -0
  24. package/dist/__tests__/humanActions.test.js.map +1 -0
  25. package/dist/__tests__/integration.test.d.ts +1 -0
  26. package/dist/__tests__/integration.test.js +1573 -0
  27. package/dist/__tests__/integration.test.js.map +1 -0
  28. package/dist/__tests__/mealMeSchemas.test.d.ts +576 -0
  29. package/dist/__tests__/mealMeSchemas.test.js +627 -0
  30. package/dist/__tests__/mealMeSchemas.test.js.map +1 -0
  31. package/dist/__tests__/oauth-context-simple.test.d.ts +1 -0
  32. package/dist/__tests__/oauth-context-simple.test.js +90 -0
  33. package/dist/__tests__/oauth-context-simple.test.js.map +1 -0
  34. package/dist/__tests__/oauth-context.test.d.ts +1 -0
  35. package/dist/__tests__/oauth-context.test.js +282 -0
  36. package/dist/__tests__/oauth-context.test.js.map +1 -0
  37. package/dist/__tests__/oauth.test.d.ts +1 -0
  38. package/dist/__tests__/oauth.test.js +378 -0
  39. package/dist/__tests__/oauth.test.js.map +1 -0
  40. package/dist/__tests__/oauth2-client-context.test.d.ts +1 -0
  41. package/dist/__tests__/oauth2-client-context.test.js +165 -0
  42. package/dist/__tests__/oauth2-client-context.test.js.map +1 -0
  43. package/dist/__tests__/oauth2-client-integration.test.d.ts +1 -0
  44. package/dist/__tests__/oauth2-client-integration.test.js +182 -0
  45. package/dist/__tests__/oauth2-client-integration.test.js.map +1 -0
  46. package/dist/__tests__/oauth2-client-simple.test.d.ts +1 -0
  47. package/dist/__tests__/oauth2-client-simple.test.js +144 -0
  48. package/dist/__tests__/oauth2-client-simple.test.js.map +1 -0
  49. package/dist/__tests__/oauth2-context.test.d.ts +1 -0
  50. package/dist/__tests__/oauth2-context.test.js +201 -0
  51. package/dist/__tests__/oauth2-context.test.js.map +1 -0
  52. package/dist/__tests__/oauth2-datasource.test.d.ts +1 -0
  53. package/dist/__tests__/oauth2-datasource.test.js +251 -0
  54. package/dist/__tests__/oauth2-datasource.test.js.map +1 -0
  55. package/dist/__tests__/plugin.test.d.ts +1 -0
  56. package/dist/__tests__/plugin.test.js +900 -0
  57. package/dist/__tests__/plugin.test.js.map +1 -0
  58. package/dist/__tests__/processes.test.d.ts +1 -0
  59. package/dist/__tests__/processes.test.js +239 -0
  60. package/dist/__tests__/processes.test.js.map +1 -0
  61. package/dist/__tests__/streaming.test.d.ts +1 -0
  62. package/dist/__tests__/streaming.test.js +592 -0
  63. package/dist/__tests__/streaming.test.js.map +1 -0
  64. package/dist/__tests__/testEnums.d.ts +1 -0
  65. package/dist/__tests__/testEnums.js +73 -0
  66. package/dist/__tests__/testEnums.js.map +1 -0
  67. package/dist/__tests__/testOptionals.test.d.ts +1 -0
  68. package/dist/__tests__/testOptionals.test.js +83 -0
  69. package/dist/__tests__/testOptionals.test.js.map +1 -0
  70. package/dist/__tests__/types.test.d.ts +1 -0
  71. package/dist/__tests__/types.test.js +98 -0
  72. package/dist/__tests__/types.test.js.map +1 -0
  73. package/dist/client/client.d.ts +5 -4
  74. package/dist/client/client.js +60 -26
  75. package/dist/client/client.js.map +1 -1
  76. package/dist/service/core.d.ts +23 -2
  77. package/dist/service/core.js +62 -15
  78. package/dist/service/core.js.map +1 -1
  79. package/dist/service/oauth2Manager.js +9 -2
  80. package/dist/service/oauth2Manager.js.map +1 -1
  81. package/dist/service/server.js +158 -40
  82. package/dist/service/server.js.map +1 -1
  83. package/dist/service/types.d.ts +1 -0
  84. package/dist/service/zod-json-converter.d.ts +14 -0
  85. package/dist/service/zod-json-converter.js +203 -0
  86. package/dist/service/zod-json-converter.js.map +1 -0
  87. package/package.json +13 -14
@@ -9,7 +9,6 @@ const cors_1 = require("hono/cors");
9
9
  const http_exception_1 = require("hono/http-exception");
10
10
  const auth_1 = require("./auth");
11
11
  const schemaStructure_1 = require("../lib/schemaStructure");
12
- const zod_1 = require("zod");
13
12
  const oauth2_1 = require("./oauth2");
14
13
  const bs58_1 = tslib_1.__importDefault(require("bs58"));
15
14
  const processes_1 = require("./processes");
@@ -20,7 +19,19 @@ const ed25519_1 = require("@noble/curves/ed25519");
20
19
  const sha256_1 = require("@noble/hashes/sha256");
21
20
  const utils_1 = require("@noble/hashes/utils");
22
21
  const auth_2 = require("./auth");
23
- console.log("OAuth2 package version:", package_json_1.default.dependencies["@dainprotocol/oauth2-token-manager"]);
22
+ const core_1 = require("./core");
23
+ const VERBOSE_SERVICE_LOGS = process.env.DAIN_VERBOSE_SERVICE_LOGS === "true";
24
+ const debugLog = (...args) => {
25
+ if (VERBOSE_SERVICE_LOGS) {
26
+ console.log(...args);
27
+ }
28
+ };
29
+ const debugWarn = (...args) => {
30
+ if (VERBOSE_SERVICE_LOGS) {
31
+ console.warn(...args);
32
+ }
33
+ };
34
+ debugLog("OAuth2 package version:", package_json_1.default.dependencies["@dainprotocol/oauth2-token-manager"]);
24
35
  /**
25
36
  * Middleware factory to require specific OAuth scopes
26
37
  * Defense-in-depth: Validates scopes even though JWT middleware already checked them
@@ -176,15 +187,19 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
176
187
  });
177
188
  // Dual Authentication: JWT (users) or API Key (services)
178
189
  app.use("*", async (c, next) => {
190
+ debugLog(`[Auth Middleware] Path: ${c.req.path}, Method: ${c.req.method}`);
179
191
  if (c.req.path.startsWith("/oauth2/callback/") ||
180
192
  c.req.path.startsWith("/addons") ||
181
193
  c.req.path.startsWith("/metadata") ||
182
194
  c.req.path.startsWith("/ping")) {
195
+ debugLog(`[Auth Middleware] Path ${c.req.path} - SKIPPING auth`);
183
196
  await next();
184
197
  return;
185
198
  }
199
+ debugLog(`[Auth Middleware] Path ${c.req.path} - REQUIRES auth`);
186
200
  const jwtToken = (0, auth_1.extractBearerToken)(c.req.header("Authorization"));
187
201
  const apiKey = c.req.header("X-DAIN-API-KEY");
202
+ debugLog(`[Auth Middleware] JWT present: ${!!jwtToken}, API Key present: ${!!apiKey}`);
188
203
  if (jwtToken) {
189
204
  // JWT Authentication (Users)
190
205
  // Auto-detect JWT audience from Host header (works with localhost, tunnels, production)
@@ -220,17 +235,20 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
220
235
  c.set('scope', result.scope);
221
236
  c.set('jwtPayload', result.payload);
222
237
  c.set('smartAccountPDA', c.req.header("X-DAIN-SMART-ACCOUNT-PDA"));
238
+ debugLog(`[Auth Middleware] JWT auth SUCCESS - smartAccountId: ${result.smartAccountId}`);
223
239
  }
224
240
  else if (apiKey) {
225
241
  // API Key Authentication (Services/Agents)
226
242
  const parsed = (0, auth_1.parseAPIKey)(apiKey);
227
243
  if (!parsed) {
244
+ debugLog(`[Auth Middleware] API Key auth FAILED - invalid format`);
228
245
  throw new http_exception_1.HTTPException(401, { message: "Invalid API key format" });
229
246
  }
230
247
  // Validate API key with platform (skip in dev mode if no platform URL)
231
248
  if (config.platformBaseUrl) {
232
249
  const isValid = await (0, auth_1.validateAPIKeyWithPlatform)(apiKey, config.platformBaseUrl);
233
250
  if (!isValid) {
251
+ debugLog(`[Auth Middleware] API Key auth FAILED - invalid with platform`);
234
252
  throw new http_exception_1.HTTPException(401, { message: "Invalid API key" });
235
253
  }
236
254
  }
@@ -239,34 +257,46 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
239
257
  c.set('orgId', parsed.orgId);
240
258
  c.set('address', parsed.agentId); // Use agentId as address for API key auth
241
259
  c.set('smartAccountPDA', c.req.header("X-DAIN-SMART-ACCOUNT-PDA"));
260
+ debugLog(`[Auth Middleware] API Key auth SUCCESS - agentId: ${parsed.agentId}, orgId: ${parsed.orgId}`);
242
261
  }
243
262
  else {
263
+ debugLog(`[Auth Middleware] Auth FAILED - no JWT or API key provided`);
244
264
  throw new http_exception_1.HTTPException(401, { message: "No authentication provided" });
245
265
  }
246
266
  await next();
247
267
  });
248
268
  async function getAgentInfo(c) {
269
+ debugLog("[getAgentInfo] START");
270
+ debugLog("[getAgentInfo] Auth method:", c.get('authMethod'));
249
271
  const smartAccountPDA = c.get('smartAccountPDA') || c.req.header("X-DAIN-SMART-ACCOUNT-PDA");
250
272
  const webhookUrl = c.req.header("X-DAIN-WEBHOOK-URL");
273
+ debugLog("[getAgentInfo] smartAccountPDA:", smartAccountPDA);
274
+ debugLog("[getAgentInfo] webhookUrl:", webhookUrl);
251
275
  if (c.get('authMethod') === 'jwt') {
252
276
  const smartAccountId = c.get('smartAccountId');
253
- return {
277
+ debugLog("[getAgentInfo] JWT auth - smartAccountId:", smartAccountId);
278
+ const agentInfo = {
254
279
  agentId: smartAccountId,
255
280
  address: smartAccountId,
256
281
  smartAccountPDA,
257
282
  id: smartAccountPDA ? `dain_id_${smartAccountPDA}` : `smart_account_${smartAccountId}`,
258
283
  webhookUrl,
259
284
  };
285
+ debugLog("[getAgentInfo] JWT - Returning agent info:", agentInfo);
286
+ return agentInfo;
260
287
  }
261
288
  const agentId = c.get('agentId');
262
289
  const address = c.get('address');
263
- return {
290
+ debugLog("[getAgentInfo] API Key auth - agentId:", agentId, "address:", address);
291
+ const agentInfo = {
264
292
  agentId,
265
293
  address,
266
294
  smartAccountPDA,
267
295
  id: smartAccountPDA ? `dain_id_${smartAccountPDA}` : `address_${address}`,
268
296
  webhookUrl,
269
297
  };
298
+ debugLog("[getAgentInfo] API Key - Returning agent info:", agentInfo);
299
+ return agentInfo;
270
300
  }
271
301
  // Setup default ping route
272
302
  app.get("/ping", (c) => c.json({ message: "pong", platform: "DAIN", service_version: metadata.version, dain_sdk_version: package_json_1.default.version }));
@@ -663,8 +693,8 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
663
693
  prompt: agent.prompt,
664
694
  resolveCondition: agent.resolveCondition,
665
695
  serviceConnections: agent.serviceConnections || [process.env.BASE_URL || 'http://localhost:3000'],
666
- inputSchema: (0, zod_1.toJSONSchema)(agent.input, { unrepresentable: "any" }),
667
- outputSchema: (0, zod_1.toJSONSchema)(agent.output, { unrepresentable: "any" }),
696
+ inputSchema: z.toJSONSchema(agent.input, { unrepresentable: "any" }),
697
+ outputSchema: z.toJSONSchema(agent.output, { unrepresentable: "any" }),
668
698
  }));
669
699
  return c.json(agentInfo);
670
700
  });
@@ -688,8 +718,8 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
688
718
  prompt: agent.prompt,
689
719
  resolveCondition: agent.resolveCondition,
690
720
  serviceConnections: agent.serviceConnections || [process.env.BASE_URL || 'http://localhost:3000'],
691
- inputSchema: (0, zod_1.toJSONSchema)(agent.input, { unrepresentable: "any" }),
692
- outputSchema: (0, zod_1.toJSONSchema)(agent.output, { unrepresentable: "any" }),
721
+ inputSchema: z.toJSONSchema(agent.input, { unrepresentable: "any" }),
722
+ outputSchema: z.toJSONSchema(agent.output, { unrepresentable: "any" }),
693
723
  }));
694
724
  // Process plugins for the response
695
725
  const processedResponse = await processPluginsForResponse(agentsInfo, body, { extraData: { plugins: processedPluginData.plugins } });
@@ -706,8 +736,8 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
706
736
  prompt: agent.prompt,
707
737
  resolveCondition: agent.resolveCondition,
708
738
  serviceConnections: agent.serviceConnections || [process.env.BASE_URL || 'http://localhost:3000'],
709
- inputSchema: (0, zod_1.toJSONSchema)(agent.input, { unrepresentable: "any" }),
710
- outputSchema: (0, zod_1.toJSONSchema)(agent.output, { unrepresentable: "any" }),
739
+ inputSchema: z.toJSONSchema(agent.input, { unrepresentable: "any" }),
740
+ outputSchema: z.toJSONSchema(agent.output, { unrepresentable: "any" }),
711
741
  };
712
742
  return c.json(agentDetails);
713
743
  }
@@ -737,8 +767,8 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
737
767
  prompt: agent.prompt,
738
768
  resolveCondition: agent.resolveCondition,
739
769
  serviceConnections: agent.serviceConnections || [process.env.BASE_URL || 'http://localhost:3000'],
740
- inputSchema: (0, zod_1.toJSONSchema)(agent.input, { unrepresentable: "any" }),
741
- outputSchema: (0, zod_1.toJSONSchema)(agent.output, { unrepresentable: "any" }),
770
+ inputSchema: z.toJSONSchema(agent.input, { unrepresentable: "any" }),
771
+ outputSchema: z.toJSONSchema(agent.output, { unrepresentable: "any" }),
742
772
  };
743
773
  // Process plugins for the response
744
774
  const processedResponse = await processPluginsForResponse(agentDetails, body, { extraData: { plugins: processedPluginData.plugins } });
@@ -749,15 +779,25 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
749
779
  }
750
780
  });
751
781
  app.get("/getAllToolsAsJsonSchema", (c) => {
752
- const toolInfo = tools.map((tool) => ({
753
- id: tool.id,
754
- name: tool.name,
755
- description: tool.description,
756
- inputSchema: (0, zod_1.toJSONSchema)(tool.input, { unrepresentable: "any" }),
757
- outputSchema: (0, zod_1.toJSONSchema)(tool.output, { unrepresentable: "any" }),
758
- interface: tool.interface,
759
- suggestConfirmation: tool.suggestConfirmation,
760
- }));
782
+ const toolInfo = tools.map((tool) => {
783
+ const inputSchema = z.toJSONSchema(tool.input, { unrepresentable: "any" });
784
+ // Log to file for debugging
785
+ try {
786
+ const fs = require('fs');
787
+ fs.appendFileSync('/tmp/dain-sdk-schemas.log', `\n\n=== Tool: ${tool.id} ===\n` +
788
+ JSON.stringify(inputSchema, null, 2) + '\n');
789
+ }
790
+ catch (e) { }
791
+ return {
792
+ id: tool.id,
793
+ name: tool.name,
794
+ description: tool.description,
795
+ inputSchema: inputSchema,
796
+ outputSchema: z.toJSONSchema(tool.output, { unrepresentable: "any" }),
797
+ interface: tool.interface,
798
+ suggestConfirmation: tool.suggestConfirmation,
799
+ };
800
+ });
761
801
  return c.json({
762
802
  tools: toolInfo,
763
803
  reccomendedPrompts: toolboxes.map((toolbox) => toolbox.recommendedPrompt),
@@ -780,8 +820,8 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
780
820
  id: tool.id,
781
821
  name: tool.name,
782
822
  description: tool.description,
783
- inputSchema: (0, zod_1.toJSONSchema)(tool.input, { unrepresentable: "any" }),
784
- outputSchema: (0, zod_1.toJSONSchema)(tool.output, { unrepresentable: "any" }),
823
+ inputSchema: z.toJSONSchema(tool.input, { unrepresentable: "any" }),
824
+ outputSchema: z.toJSONSchema(tool.output, { unrepresentable: "any" }),
785
825
  interface: tool.interface,
786
826
  suggestConfirmation: tool.suggestConfirmation,
787
827
  }));
@@ -868,10 +908,26 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
868
908
  throw new Error("config.oauth2.baseUrl is required for OAuth2");
869
909
  }
870
910
  const oauth2Handler = new oauth2_1.OAuth2Handler(bs58_1.default.encode(privateKey), config.oauth2.baseUrl, config.oauth2.tokenStore);
871
- // Register providers
872
- Object.entries(config.oauth2.providers).forEach(([name, providerConfig]) => {
873
- oauth2Handler.registerProvider(name, providerConfig);
911
+ // Auto-generate service slug from metadata title
912
+ const serviceSlug = (0, core_1.toSlug)(metadata.title);
913
+ // Register providers and auto-create OAuth tools
914
+ const autoOAuth2Tools = [];
915
+ Object.entries(config.oauth2.providers).forEach(([providerName, providerConfig]) => {
916
+ oauth2Handler.registerProvider(providerName, providerConfig);
917
+ // Auto-create OAuth tool for this provider
918
+ debugLog(`[OAuth Auto-Registration] Creating OAuth tool: oauth2-${serviceSlug}-${providerName}`);
919
+ const oauthTool = (0, core_1.createOAuth2Tool)(providerName, serviceSlug, {
920
+ logoUrl: providerConfig.logoUrl,
921
+ reason: providerConfig.reason,
922
+ requiredTools: providerConfig.requiredTools
923
+ });
924
+ autoOAuth2Tools.push(oauthTool);
874
925
  });
926
+ // Inject auto-created OAuth tools into the tools array
927
+ if (autoOAuth2Tools.length > 0) {
928
+ debugLog(`[OAuth Auto-Registration] Injecting ${autoOAuth2Tools.length} OAuth tool(s) into tools array`);
929
+ tools.push(...autoOAuth2Tools);
930
+ }
875
931
  // OAuth callback route
876
932
  app.get("/oauth2/callback/:provider", async (c) => {
877
933
  if (!app.oauth2) {
@@ -950,16 +1006,38 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
950
1006
  });
951
1007
  // Get auth URL for specific provider
952
1008
  app.get("/oauth2/connect/:provider", async (c) => {
1009
+ debugLog("[OAuth2 Connect] Route hit - START");
1010
+ debugLog("[OAuth2 Connect] Provider param:", c.req.param("provider"));
1011
+ debugLog("[OAuth2 Connect] Auth method:", c.get('authMethod'));
1012
+ debugLog("[OAuth2 Connect] Headers:", {
1013
+ authorization: c.req.header("Authorization"),
1014
+ apiKey: c.req.header("X-DAIN-API-KEY"),
1015
+ host: c.req.header("host"),
1016
+ });
953
1017
  if (!app.oauth2) {
1018
+ debugLog("[OAuth2 Connect] ERROR: OAuth2 not configured");
954
1019
  throw new http_exception_1.HTTPException(404, { message: "OAuth2 not configured" });
955
1020
  }
956
1021
  const provider = c.req.param("provider");
957
- const agentInfo = await getAgentInfo(c);
1022
+ debugLog("[OAuth2 Connect] Getting agent info...");
1023
+ let agentInfo;
958
1024
  try {
1025
+ agentInfo = await getAgentInfo(c);
1026
+ debugLog("[OAuth2 Connect] Agent info retrieved:", agentInfo);
1027
+ }
1028
+ catch (error) {
1029
+ debugLog("[OAuth2 Connect] ERROR getting agent info:", error);
1030
+ throw error;
1031
+ }
1032
+ try {
1033
+ debugLog("[OAuth2 Connect] Generating auth URL for provider:", provider, "for agent:", agentInfo.id);
1034
+ debugLog("[OAuth2 Connect] OAuth2 configured:", !!app.oauth2);
959
1035
  const authUrl = await app.oauth2.generateAuthUrl(provider, agentInfo.id);
1036
+ debugLog("[OAuth2 Connect] Auth URL generated successfully:", authUrl);
960
1037
  return c.json({ authUrl });
961
1038
  }
962
1039
  catch (error) {
1040
+ debugLog("[OAuth2 Connect] ERROR generating auth URL:", error);
963
1041
  throw new http_exception_1.HTTPException(400, {
964
1042
  message: `Invalid provider: ${provider}`
965
1043
  });
@@ -974,14 +1052,14 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
974
1052
  throw new http_exception_1.HTTPException(404, { message: "Process not found" });
975
1053
  }
976
1054
  if (process.agentId !== agentInfo.id) {
977
- console.log("Unauthorized access to process", process.agentId, agentInfo.id);
1055
+ debugLog("Unauthorized access to process", process.agentId, agentInfo.id);
978
1056
  throw new http_exception_1.HTTPException(403, { message: "Unauthorized access to process" });
979
1057
  }
980
1058
  return c.json(process.humanActions);
981
1059
  });
982
1060
  // Get specific human action
983
1061
  app.get("/processes/:processId/human-actions/:stepId", async (c) => {
984
- console.log('GET human action request:', c.req.path);
1062
+ debugLog('GET human action request:', c.req.path);
985
1063
  const processId = c.req.param("processId");
986
1064
  const stepId = c.req.param("stepId");
987
1065
  const agentInfo = await getAgentInfo(c);
@@ -990,7 +1068,7 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
990
1068
  throw new http_exception_1.HTTPException(404, { message: "Process not found" });
991
1069
  }
992
1070
  if (process.agentId !== agentInfo.id) {
993
- console.log("Unauthorized access to process", process.agentId, agentInfo.id);
1071
+ debugLog("Unauthorized access to process", process.agentId, agentInfo.id);
994
1072
  throw new http_exception_1.HTTPException(403, { message: "Unauthorized access to process" });
995
1073
  }
996
1074
  const step = await app.processes.checkHumanAction(processId, stepId);
@@ -1009,7 +1087,7 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
1009
1087
  throw new http_exception_1.HTTPException(404, { message: "Process not found" });
1010
1088
  }
1011
1089
  if (process.agentId !== agentInfo.id) {
1012
- console.log("Unauthorized access to process", process.agentId, agentInfo.id);
1090
+ debugLog("Unauthorized access to process", process.agentId, agentInfo.id);
1013
1091
  throw new http_exception_1.HTTPException(403, { message: "Unauthorized access to process" });
1014
1092
  }
1015
1093
  const body = await c.req.json();
@@ -1126,11 +1204,11 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
1126
1204
  const executeToolWithStreaming = async (c, tool, body, agentInfo, pluginsData, withContext = false) => {
1127
1205
  const wantsStream = c.req.header("Accept") === "text/event-stream";
1128
1206
  if (wantsStream) {
1129
- console.log(`[SSE] Tool ${tool.id} requested with streaming, params:`, Object.keys(body));
1207
+ debugLog(`[SSE] Tool ${tool.id} requested with streaming, params:`, Object.keys(body));
1130
1208
  return signedStreamSSE(c, privateKey, config, async (stream) => {
1131
1209
  try {
1132
1210
  // Execute the tool first
1133
- console.log(`[SSE] Executing tool ${tool.id} in streaming mode${withContext ? ' with context' : ''}`);
1211
+ debugLog(`[SSE] Executing tool ${tool.id} in streaming mode${withContext ? ' with context' : ''}`);
1134
1212
  const result = await tool.handler({ ...body, DAIN_EXTRA_DATA: undefined }, agentInfo, {
1135
1213
  app,
1136
1214
  oauth2Client: app.oauth2 ? app.oauth2.getClient() : undefined,
@@ -1175,7 +1253,7 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
1175
1253
  // If we need to include context data
1176
1254
  let response = result;
1177
1255
  if (withContext) {
1178
- console.log(`Tool ${tool.id} execution completed, gathering contexts`);
1256
+ debugLog(`Tool ${tool.id} execution completed, gathering contexts`);
1179
1257
  // Gather contexts with proper error handling
1180
1258
  let contextsNow = [];
1181
1259
  try {
@@ -1219,7 +1297,7 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
1219
1297
  // Continue with empty contexts rather than failing completely
1220
1298
  contextsNow = [];
1221
1299
  }
1222
- console.log(`Gathered ${contextsNow.length} contexts, sending final result`);
1300
+ debugLog(`Gathered ${contextsNow.length} contexts, sending final result`);
1223
1301
  // Create the complete response with context
1224
1302
  response = {
1225
1303
  toolResult: result,
@@ -1234,14 +1312,14 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
1234
1312
  }
1235
1313
  });
1236
1314
  // Send the final result
1237
- console.log(`[SSE] Sending final ${withContext ? 'context ' : ''}result for ${tool.id}`);
1238
- console.log(`[SSE] Result preview:`, JSON.stringify(processedResult).substring(0, 200));
1315
+ debugLog(`[SSE] Sending final ${withContext ? 'context ' : ''}result for ${tool.id}`);
1316
+ debugLog(`[SSE] Result preview:`, JSON.stringify(processedResult).substring(0, 200));
1239
1317
  await stream.writeSSE({
1240
1318
  event: 'result',
1241
1319
  data: JSON.stringify(processedResult),
1242
1320
  id: Date.now().toString(),
1243
1321
  });
1244
- console.log(`[SSE] Final result sent for ${tool.id}`);
1322
+ debugLog(`[SSE] Final result sent for ${tool.id}`);
1245
1323
  }
1246
1324
  catch (error) {
1247
1325
  console.error(`Error in stream for ${tool.id}:`, error);
@@ -1388,35 +1466,75 @@ function setupHttpServer(config, tools, services, toolboxes, metadata, privateKe
1388
1466
  };
1389
1467
  // Standard tool execution endpoint
1390
1468
  app.post(`/tools/${tool.id}`, async (c) => {
1469
+ debugLog(`[Tool ${tool.id}] ========== TOOL EXECUTION START ==========`);
1470
+ debugLog(`[Tool ${tool.id}] Path: ${c.req.path}`);
1471
+ debugLog(`[Tool ${tool.id}] Method: ${c.req.method}`);
1472
+ debugLog(`[Tool ${tool.id}] Auth Method: ${c.get('authMethod')}`);
1473
+ debugLog(`[Tool ${tool.id}] Headers:`, {
1474
+ authorization: c.req.header("Authorization") ? "Bearer ***" : undefined,
1475
+ apiKey: c.req.header("X-DAIN-API-KEY") ? "***" : undefined,
1476
+ smartAccountPDA: c.req.header("X-DAIN-SMART-ACCOUNT-PDA"),
1477
+ webhookUrl: c.req.header("X-DAIN-WEBHOOK-URL"),
1478
+ });
1391
1479
  try {
1480
+ debugLog(`[Tool ${tool.id}] Getting agent info...`);
1392
1481
  const agentInfo = await getAgentInfo(c);
1482
+ debugLog(`[Tool ${tool.id}] Agent info:`, agentInfo);
1483
+ debugLog(`[Tool ${tool.id}] Parsing request body...`);
1393
1484
  let body = await c.req.json();
1485
+ debugLog(`[Tool ${tool.id}] Request body keys:`, Object.keys(body));
1486
+ debugLog(`[Tool ${tool.id}] Request body:`, JSON.stringify(body, null, 2));
1394
1487
  // Process plugins for the request
1488
+ debugLog(`[Tool ${tool.id}] Processing plugins...`);
1395
1489
  body = await processPluginsForRequest(body, agentInfo);
1396
1490
  // Extract plugins data for the tool context
1397
1491
  const pluginsData = body.plugins || {};
1398
1492
  delete body.plugins;
1493
+ debugLog(`[Tool ${tool.id}] Plugins data:`, pluginsData);
1494
+ debugLog(`[Tool ${tool.id}] Executing tool handler...`);
1399
1495
  return executeToolWithStreaming(c, tool, body, agentInfo, pluginsData, false);
1400
1496
  }
1401
1497
  catch (error) {
1402
- console.error(`[Tool ${tool.id}] Error:`, error.message);
1498
+ console.error(`[Tool ${tool.id}] ========== ERROR ==========`);
1499
+ console.error(`[Tool ${tool.id}] Error:`, error);
1500
+ console.error(`[Tool ${tool.id}] Stack:`, error.stack);
1403
1501
  throw new http_exception_1.HTTPException(500, { message: "Internal server error" });
1404
1502
  }
1405
1503
  });
1406
1504
  // Tool execution with context endpoint
1407
1505
  app.post(`/tools/${tool.id}/executeAndGetNewContext`, async (c) => {
1506
+ debugLog(`[Tool ${tool.id} +Context] ========== TOOL EXECUTION START (WITH CONTEXT) ==========`);
1507
+ debugLog(`[Tool ${tool.id} +Context] Path: ${c.req.path}`);
1508
+ debugLog(`[Tool ${tool.id} +Context] Method: ${c.req.method}`);
1509
+ debugLog(`[Tool ${tool.id} +Context] Auth Method: ${c.get('authMethod')}`);
1510
+ debugLog(`[Tool ${tool.id} +Context] Headers:`, {
1511
+ authorization: c.req.header("Authorization") ? "Bearer ***" : undefined,
1512
+ apiKey: c.req.header("X-DAIN-API-KEY") ? "***" : undefined,
1513
+ smartAccountPDA: c.req.header("X-DAIN-SMART-ACCOUNT-PDA"),
1514
+ webhookUrl: c.req.header("X-DAIN-WEBHOOK-URL"),
1515
+ });
1408
1516
  try {
1517
+ debugLog(`[Tool ${tool.id} +Context] Getting agent info...`);
1409
1518
  const agentInfo = await getAgentInfo(c);
1519
+ debugLog(`[Tool ${tool.id} +Context] Agent info:`, agentInfo);
1520
+ debugLog(`[Tool ${tool.id} +Context] Parsing request body...`);
1410
1521
  let body = await c.req.json();
1522
+ debugLog(`[Tool ${tool.id} +Context] Request body keys:`, Object.keys(body));
1523
+ debugLog(`[Tool ${tool.id} +Context] Request body:`, JSON.stringify(body, null, 2));
1411
1524
  // Process plugins for the request
1525
+ debugLog(`[Tool ${tool.id} +Context] Processing plugins...`);
1412
1526
  body = await processPluginsForRequest(body, agentInfo);
1413
1527
  // Extract plugins data for the tool context
1414
1528
  const pluginsData = body.plugins || {};
1415
1529
  delete body.plugins;
1530
+ debugLog(`[Tool ${tool.id} +Context] Plugins data:`, pluginsData);
1531
+ debugLog(`[Tool ${tool.id} +Context] Executing tool handler with context...`);
1416
1532
  return executeToolWithStreaming(c, tool, body, agentInfo, pluginsData, true);
1417
1533
  }
1418
1534
  catch (error) {
1419
- console.error(`[Tool ${tool.id} +Context] Error:`, error.message);
1535
+ console.error(`[Tool ${tool.id} +Context] ========== ERROR ==========`);
1536
+ console.error(`[Tool ${tool.id} +Context] Error:`, error);
1537
+ console.error(`[Tool ${tool.id} +Context] Stack:`, error.stack);
1420
1538
  throw new http_exception_1.HTTPException(500, { message: "Internal server error" });
1421
1539
  }
1422
1540
  });