@openserv-labs/sdk 1.0.1 → 1.2.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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # OpenServ Autonomous AI Agent Development Framework
1
+ # OpenServ TypeScript SDK, Autonomous AI Agent Development Framework
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/@openserv-labs%2Fsdk.svg)](https://www.npmjs.com/package/@openserv-labs/sdk)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -12,6 +12,7 @@ A powerful TypeScript framework for building non-deterministic AI agents with ad
12
12
  - [Table of Contents](#table-of-contents)
13
13
  - [Features](#features)
14
14
  - [Framework Architecture](#framework-architecture)
15
+ - [Framework \& Blockchain Compatibility](#framework--blockchain-compatibility)
15
16
  - [Shadow Agents](#shadow-agents)
16
17
  - [Control Levels](#control-levels)
17
18
  - [Developer Focus](#developer-focus)
@@ -38,6 +39,8 @@ A powerful TypeScript framework for building non-deterministic AI agents with ad
38
39
  - [Workspace Management](#workspace-management)
39
40
  - [Get Files](#get-files)
40
41
  - [Upload File](#upload-file)
42
+ - [Integration Management](#integration-management)
43
+ - [Call Integration](#call-integration)
41
44
  - [Advanced Usage](#advanced-usage)
42
45
  - [OpenAI Process Runtime](#openai-process-runtime)
43
46
  - [Error Handling](#error-handling)
@@ -51,6 +54,8 @@ A powerful TypeScript framework for building non-deterministic AI agents with ad
51
54
  - 🤝 Inter-agent collaboration and communication
52
55
  - 🔌 Extensible agent architecture with custom capabilities
53
56
  - 🔧 Fully autonomous agent runtime with shadow agents
57
+ - 🌐 Framework-agnostic - integrate agents from any AI framework
58
+ - ⛓️ Blockchain-agnostic - compatible with any chain implementation
54
59
  - 🤖 Task execution and chat message handling
55
60
  - 🔄 Asynchronous task management
56
61
  - 📁 File operations and management
@@ -61,6 +66,22 @@ A powerful TypeScript framework for building non-deterministic AI agents with ad
61
66
 
62
67
  ## Framework Architecture
63
68
 
69
+ ### Framework & Blockchain Compatibility
70
+
71
+ OpenServ is designed to be completely framework and blockchain agnostic, allowing you to:
72
+
73
+ - Integrate agents built with any AI framework (e.g., LangChain, BabyAGI, Eliza, G.A.M.E, etc.)
74
+ - Connect agents operating on any blockchain network
75
+ - Mix and match different framework agents in the same workspace
76
+ - Maintain full compatibility with your existing agent implementations
77
+
78
+ This flexibility ensures you can:
79
+
80
+ - Use your preferred AI frameworks and tools
81
+ - Leverage existing agent implementations
82
+ - Integrate with any blockchain ecosystem
83
+ - Build cross-framework agent collaborations
84
+
64
85
  ### Shadow Agents
65
86
 
66
87
  Each agent is supported by two "shadow agents":
@@ -498,6 +519,52 @@ await agent.uploadFile({
498
519
  })
499
520
  ```
500
521
 
522
+ ### Integration Management
523
+
524
+ #### Call Integration
525
+
526
+ ```typescript
527
+ const response = await agent.callIntegration({
528
+ workspaceId: number,
529
+ integrationId: string,
530
+ details: {
531
+ endpoint: string,
532
+ method: string,
533
+ data?: object
534
+ }
535
+ })
536
+ ```
537
+
538
+ Allows agents to interact with external services and APIs that are integrated with OpenServ. This method provides a secure way to make API calls to configured integrations within a workspace. Authentication is handled securely and automatically through the OpenServ platform. This is primarily useful for calling external APIs in a deterministic way.
539
+
540
+ **Parameters:**
541
+
542
+ - `workspaceId`: ID of the workspace where the integration is configured
543
+ - `integrationId`: ID of the integration to call (e.g., 'twitter-v2', 'github')
544
+ - `details`: Object containing:
545
+ - `endpoint`: The endpoint to call on the integration
546
+ - `method`: HTTP method (GET, POST, etc.)
547
+ - `data`: Optional payload for the request
548
+
549
+ **Returns:** The response from the integration endpoint
550
+
551
+ **Example:**
552
+
553
+ ```typescript
554
+ // Example: Sending a tweet using Twitter integration
555
+ const response = await agent.callIntegration({
556
+ workspaceId: 123,
557
+ integrationId: 'twitter-v2',
558
+ details: {
559
+ endpoint: '/2/tweets',
560
+ method: 'POST',
561
+ data: {
562
+ text: 'Hello from my AI agent!'
563
+ }
564
+ }
565
+ })
566
+ ```
567
+
501
568
  ## Advanced Usage
502
569
 
503
570
  ### OpenAI Process Runtime
package/dist/agent.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type AxiosInstance } from 'axios';
2
- import type { GetFilesParams, UploadFileParams, MarkTaskAsErroredParams, CompleteTaskParams, SendChatMessageParams, GetTaskDetailParams, GetAgentsParams, GetTasksParams, CreateTaskParams, AddLogToTaskParams, RequestHumanAssistanceParams, UpdateTaskStatusParams, ProcessParams } from './types';
3
- import { actionSchema, doTaskActionSchema, respondChatMessageActionSchema } from './types';
2
+ import type { GetFilesParams, GetSecretsParams, GetSecretValueParams, UploadFileParams, MarkTaskAsErroredParams, CompleteTaskParams, SendChatMessageParams, GetTaskDetailParams, GetAgentsParams, GetTasksParams, CreateTaskParams, AddLogToTaskParams, RequestHumanAssistanceParams, UpdateTaskStatusParams, ProcessParams, IntegrationCallRequest } from './types';
3
+ import type { doTaskActionSchema, respondChatMessageActionSchema } from './types';
4
+ import { actionSchema } from './types';
4
5
  import type { ChatCompletionMessageParam, ChatCompletion } from 'openai/resources/chat/completions';
5
6
  import OpenAI from 'openai';
6
7
  import type { z } from 'zod';
@@ -30,6 +31,13 @@ export interface AgentOptions {
30
31
  * Required when using the process() method.
31
32
  */
32
33
  openaiApiKey?: string;
34
+ /**
35
+ * Error handler function for all agent operations.
36
+ * Defaults to logging the error if not provided.
37
+ * @param error - The error that occurred
38
+ * @param context - Additional context about where the error occurred
39
+ */
40
+ onError?: (error: Error, context?: Record<string, unknown>) => void;
33
41
  }
34
42
  export declare class Agent {
35
43
  private options;
@@ -68,7 +76,7 @@ export declare class Agent {
68
76
  * Each capability is an instance of the Capability class with a name, description, schema, and run function.
69
77
  * @protected
70
78
  */
71
- protected tools: Array<Capability<any>>;
79
+ protected tools: Array<Capability<z.ZodTypeAny>>;
72
80
  /**
73
81
  * The OpenServ API key used for authentication.
74
82
  * Can be provided in options or via OPENSERV_API_KEY environment variable.
@@ -138,7 +146,7 @@ export declare class Agent {
138
146
  name: string;
139
147
  description: string;
140
148
  schema: S;
141
- run(params: {
149
+ run(this: Agent, params: {
142
150
  args: z.infer<S>;
143
151
  action?: z.infer<typeof actionSchema>;
144
152
  }, messages: ChatCompletionMessageParam[]): string | Promise<string>;
@@ -161,10 +169,10 @@ export declare class Agent {
161
169
  name: string;
162
170
  description: string;
163
171
  schema: T[K];
164
- run: (params: {
172
+ run(this: Agent, params: {
165
173
  args: z.infer<T[K]>;
166
174
  action?: z.infer<typeof actionSchema>;
167
- }, messages: ChatCompletionMessageParam[]) => string | Promise<string>;
175
+ }, messages: ChatCompletionMessageParam[]): string | Promise<string>;
168
176
  };
169
177
  }): this;
170
178
  /**
@@ -175,6 +183,20 @@ export declare class Agent {
175
183
  * @returns {Promise<any>} The files in the workspace
176
184
  */
177
185
  getFiles(params: GetFilesParams): Promise<any>;
186
+ /**
187
+ * Get all secrets for an agent in a workspace.
188
+ *
189
+ * @param {GetSecretsParams} params - Parameters for the secrets retrieval
190
+ * @returns {Promise<any>} List of agent secrets.
191
+ */
192
+ getSecrets(params: GetSecretsParams): Promise<any>;
193
+ /**
194
+ * Get the value of a secret for an agent in a workspace
195
+ *
196
+ * @param {GetSecretValueParams} params - Parameters for the secret value retrieval
197
+ * @returns {Promise<string>} The value of the secret.
198
+ */
199
+ getSecretValue(params: GetSecretValueParams): Promise<string>;
178
200
  /**
179
201
  * Uploads a file to a workspace.
180
202
  *
@@ -320,6 +342,7 @@ export declare class Agent {
320
342
  * @param {Object} req.body - Request body
321
343
  * @param {z.infer<z.ZodTypeAny>} [req.body.args] - Arguments for the tool
322
344
  * @param {z.infer<typeof actionSchema>} [req.body.action] - Action context
345
+ * @param {ChatCompletionMessageParam[]} [req.body.messages] - Message history
323
346
  * @returns {Promise<{result: string}>} The result of the tool execution
324
347
  * @throws {BadRequest} If tool name is missing or tool is not found
325
348
  * @throws {Error} If tool execution fails
@@ -331,6 +354,7 @@ export declare class Agent {
331
354
  body: {
332
355
  args?: z.infer<z.ZodTypeAny>;
333
356
  action?: z.infer<typeof actionSchema>;
357
+ messages?: ChatCompletionMessageParam[];
334
358
  };
335
359
  }): Promise<{
336
360
  result: string;
@@ -365,5 +389,25 @@ export declare class Agent {
365
389
  * @returns {Promise<void>} Resolves when the server has stopped
366
390
  */
367
391
  stop(): Promise<void>;
392
+ /**
393
+ * Default error handler that logs the error
394
+ * @private
395
+ */
396
+ private handleError;
397
+ /**
398
+ * Calls an integration endpoint through the OpenServ platform.
399
+ * This method allows agents to interact with external services and APIs that are integrated with OpenServ.
400
+ *
401
+ * @param {IntegrationCallRequest} integration - The integration request parameters
402
+ * @param {number} integration.workspaceId - ID of the workspace where the integration is configured
403
+ * @param {string} integration.integrationId - ID of the integration to call
404
+ * @param {Object} integration.details - Details of the integration call
405
+ * @param {string} integration.details.endpoint - The endpoint to call on the integration
406
+ * @param {string} integration.details.method - The HTTP method to use (GET, POST, etc.)
407
+ * @param {Object} [integration.details.data] - Optional data payload for the request
408
+ * @returns {Promise<any>} The response from the integration endpoint
409
+ * @throws {Error} If the integration call fails
410
+ */
411
+ callIntegration(integration: IntegrationCallRequest): Promise<any>;
368
412
  }
369
413
  //# sourceMappingURL=agent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,KAAK,aAAa,EAAE,MAAM,OAAO,CAAA;AASjD,OAAO,KAAK,EACV,cAAc,EACd,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,4BAA4B,EAC5B,sBAAsB,EACtB,aAAa,EACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,8BAA8B,EAAE,MAAM,SAAS,CAAA;AAE1F,OAAO,KAAK,EACV,0BAA0B,EAE1B,cAAc,EACf,M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,MAAM,EAAE,kBAAkB;IAY7C;;;;;;;;;;OAUG;IACG,sBAAsB,CAAC,MAAM,EAAE,4BAA4B;IA0BjE;;;;;;;;OAQG;IACG,gBAAgB,CAAC,MAAM,EAAE,sBAAsB;IAUrD;;;;;;;OAOG;IACG,OAAO,CAAC,EAAE,QAAQ,EAAE,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;IAoFnE;;;;OAIG;cACa,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC;IA6BjE;;;;OAIG;cACa,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,8BAA8B,CAAC;IA+BpF;;;;;;;;;;;;;OAaG;IACG,eAAe,CAAC,GAAG,EAAE;QACzB,MAAM,EAAE;YAAE,QAAQ,EAAE,MAAM,CAAA;SAAE,CAAA;QAC5B,IAAI,EAAE;YACJ,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,CAAA;YAC5B,MAAM,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAA;YACrC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAA;SACxC,CAAA;KACF;;;IAyBD;;;;;;;OAOG;IACG,eAAe,CAAC,GAAG,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE;IAgB5C;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAuBnB;;;;;OAKG;IACG,KAAK;IAUX;;;;OAIG;IACG,IAAI;IAQV;;;OAGG;IACH,OAAO,CAAC,WAAW;IAOnB;;;;;;;;;;;;;OAaG;IACG,eAAe,CAAC,WAAW,EAAE,sBAAsB;CAQ1D"}
package/dist/agent.js CHANGED
@@ -177,6 +177,7 @@ class Agent {
177
177
  if (this.tools.some(tool => tool.name === name)) {
178
178
  throw new Error(`Tool with name "${name}" already exists`);
179
179
  }
180
+ // Type assertion through unknown for safe conversion between compatible generic types
180
181
  this.tools.push(new capability_1.Capability(name, description, schema, run));
181
182
  return this;
182
183
  }
@@ -194,9 +195,9 @@ class Agent {
194
195
  * @throws {Error} If any capability has a name that already exists
195
196
  */
196
197
  addCapabilities(capabilities) {
197
- capabilities.forEach(capability => {
198
+ for (const capability of capabilities) {
198
199
  this.addCapability(capability);
199
- });
200
+ }
200
201
  return this;
201
202
  }
202
203
  /**
@@ -210,6 +211,26 @@ class Agent {
210
211
  const response = await this.apiClient.get(`/workspaces/${params.workspaceId}/files`);
211
212
  return response.data;
212
213
  }
214
+ /**
215
+ * Get all secrets for an agent in a workspace.
216
+ *
217
+ * @param {GetSecretsParams} params - Parameters for the secrets retrieval
218
+ * @returns {Promise<any>} List of agent secrets.
219
+ */
220
+ async getSecrets(params) {
221
+ const response = await this.apiClient.get(`/workspaces/${params.workspaceId}/agent-secrets`);
222
+ return response.data;
223
+ }
224
+ /**
225
+ * Get the value of a secret for an agent in a workspace
226
+ *
227
+ * @param {GetSecretValueParams} params - Parameters for the secret value retrieval
228
+ * @returns {Promise<string>} The value of the secret.
229
+ */
230
+ async getSecretValue(params) {
231
+ const response = await this.apiClient.get(`/workspaces/${params.workspaceId}/agent-secrets/${params.secretId}/value`);
232
+ return response.data;
233
+ }
213
234
  /**
214
235
  * Uploads a file to a workspace.
215
236
  *
@@ -376,9 +397,22 @@ class Agent {
376
397
  * @returns {Promise<any>} The created assistance request details
377
398
  */
378
399
  async requestHumanAssistance(params) {
400
+ let question = params.question;
401
+ if (typeof question === 'string') {
402
+ question = {
403
+ type: 'text',
404
+ question
405
+ };
406
+ }
407
+ else {
408
+ question = {
409
+ type: 'json',
410
+ ...question
411
+ };
412
+ }
379
413
  const response = await this.apiClient.post(`/workspaces/${params.workspaceId}/tasks/${params.taskId}/human-assistance`, {
380
414
  type: params.type,
381
- question: params.question,
415
+ question,
382
416
  agentDump: params.agentDump
383
417
  });
384
418
  return response.data;
@@ -407,58 +441,75 @@ class Agent {
407
441
  * @throws {Error} If no response is received from OpenAI or max iterations are reached
408
442
  */
409
443
  async process({ messages }) {
410
- const currentMessages = [...messages];
411
- let completion = null;
412
- let iterationCount = 0;
413
- const MAX_ITERATIONS = 10;
414
- while (iterationCount < MAX_ITERATIONS) {
415
- completion = await this.openai.chat.completions.create({
416
- model: 'gpt-4o',
417
- messages: currentMessages,
418
- tools: this.openAiTools
419
- });
420
- if (!completion.choices?.length || !completion.choices[0]?.message) {
421
- throw new Error('No response from OpenAI');
422
- }
423
- const lastMessage = completion.choices[0].message;
424
- // If there are no tool calls, we're done
425
- if (!lastMessage.tool_calls?.length) {
426
- return completion;
444
+ try {
445
+ const apiKey = this.options.openaiApiKey || process.env.OPENAI_API_KEY;
446
+ if (!apiKey) {
447
+ throw new Error('OpenAI API key is required for process(). Please provide it in options or set OPENAI_API_KEY environment variable.');
427
448
  }
428
- // Process each tool call
429
- const toolResults = await Promise.all(lastMessage.tool_calls.map(async (toolCall) => {
430
- // We know the function exists because we provided the tools
431
- const { name, arguments: args } = toolCall.function;
432
- const parsedArgs = JSON.parse(args);
433
- try {
434
- // Find the tool in our tools array
435
- const tool = this.tools.find(t => t.name === name);
436
- if (!tool) {
437
- throw new Error(`Tool "${name}" not found`);
438
- }
439
- // Call the tool's run method with the parsed arguments and bind this
440
- const result = await tool.run.bind(this)({ args: parsedArgs }, currentMessages);
441
- return {
442
- role: 'tool',
443
- content: JSON.stringify(result),
444
- tool_call_id: toolCall.id
445
- };
449
+ const currentMessages = [...messages];
450
+ let completion = null;
451
+ let iterationCount = 0;
452
+ const MAX_ITERATIONS = 10;
453
+ while (iterationCount < MAX_ITERATIONS) {
454
+ completion = await this.openai.chat.completions.create({
455
+ model: 'gpt-4o',
456
+ messages: currentMessages,
457
+ tools: this.tools.length ? this.openAiTools : undefined
458
+ });
459
+ if (!completion.choices?.length || !completion.choices[0]?.message) {
460
+ throw new Error('No response from OpenAI');
446
461
  }
447
- catch (error) {
448
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
449
- logger_1.logger.error({ error, toolCall }, 'Error executing tool call');
450
- return {
451
- role: 'tool',
452
- content: JSON.stringify({ error: errorMessage }),
453
- tool_call_id: toolCall.id
454
- };
462
+ const lastMessage = completion.choices[0].message;
463
+ // If there are no tool calls, we're done
464
+ if (!lastMessage.tool_calls?.length) {
465
+ return completion;
455
466
  }
456
- }));
457
- // Add the assistant's message and tool results to the conversation
458
- currentMessages.push(lastMessage, ...toolResults);
459
- iterationCount++;
467
+ // Process each tool call
468
+ const toolResults = await Promise.all(lastMessage.tool_calls.map(async (toolCall) => {
469
+ if (!toolCall.function) {
470
+ throw new Error('Tool call function is missing');
471
+ }
472
+ const { name, arguments: args } = toolCall.function;
473
+ const parsedArgs = JSON.parse(args);
474
+ try {
475
+ // Find the tool in our tools array
476
+ const tool = this.tools.find(t => t.name === name);
477
+ if (!tool) {
478
+ throw new Error(`Tool "${name}" not found`);
479
+ }
480
+ // Call the tool's run method with the parsed arguments and bind this
481
+ const result = await tool.run.bind(this)({ args: parsedArgs }, currentMessages);
482
+ return {
483
+ role: 'tool',
484
+ content: JSON.stringify(result),
485
+ tool_call_id: toolCall.id
486
+ };
487
+ }
488
+ catch (error) {
489
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
490
+ this.handleError(error instanceof Error ? error : new Error(errorMessage), {
491
+ toolCall,
492
+ context: 'tool_execution'
493
+ });
494
+ return {
495
+ role: 'tool',
496
+ content: JSON.stringify({ error: errorMessage }),
497
+ tool_call_id: toolCall.id
498
+ };
499
+ }
500
+ }));
501
+ // Add the assistant's message and tool results to the conversation
502
+ currentMessages.push(lastMessage, ...toolResults);
503
+ iterationCount++;
504
+ }
505
+ throw new Error('Max iterations reached without completion');
506
+ }
507
+ catch (error) {
508
+ this.handleError(error instanceof Error ? error : new Error(String(error)), {
509
+ context: 'process'
510
+ });
511
+ throw error;
460
512
  }
461
- throw new Error('Max iterations reached without completion');
462
513
  }
463
514
  /**
464
515
  * Handle a task execution request
@@ -486,15 +537,10 @@ class Agent {
486
537
  });
487
538
  }
488
539
  catch (error) {
489
- if (action.task) {
490
- await this.markTaskAsErrored({
491
- workspaceId: action.workspace.id,
492
- taskId: action.task.id,
493
- error: error instanceof Error ? error.message : 'Unknown error occurred'
494
- });
495
- }
496
- logger_1.logger.error({ error }, 'Failed to forward action to runtime agent');
497
- throw error;
540
+ this.handleError(error instanceof Error ? error : new Error(String(error)), {
541
+ action,
542
+ context: 'do_task'
543
+ });
498
544
  }
499
545
  }
500
546
  /**
@@ -510,12 +556,12 @@ class Agent {
510
556
  }
511
557
  ];
512
558
  if (action.messages) {
513
- action.messages.forEach((msg) => {
559
+ for (const msg of action.messages) {
514
560
  messages.push({
515
561
  role: msg.author === 'user' ? 'user' : 'assistant',
516
562
  content: msg.message
517
563
  });
518
- });
564
+ }
519
565
  }
520
566
  try {
521
567
  await this.runtimeClient.post('/chat', {
@@ -525,13 +571,10 @@ class Agent {
525
571
  });
526
572
  }
527
573
  catch (error) {
528
- await this.sendChatMessage({
529
- workspaceId: action.workspace.id,
530
- agentId: action.me.id,
531
- message: error instanceof Error ? error.message : 'Unknown error occurred'
574
+ this.handleError(error instanceof Error ? error : new Error(String(error)), {
575
+ action,
576
+ context: 'respond_to_chat'
532
577
  });
533
- logger_1.logger.error({ error }, 'Failed to forward action to runtime agent');
534
- throw error;
535
578
  }
536
579
  }
537
580
  /**
@@ -543,26 +586,31 @@ class Agent {
543
586
  * @param {Object} req.body - Request body
544
587
  * @param {z.infer<z.ZodTypeAny>} [req.body.args] - Arguments for the tool
545
588
  * @param {z.infer<typeof actionSchema>} [req.body.action] - Action context
589
+ * @param {ChatCompletionMessageParam[]} [req.body.messages] - Message history
546
590
  * @returns {Promise<{result: string}>} The result of the tool execution
547
591
  * @throws {BadRequest} If tool name is missing or tool is not found
548
592
  * @throws {Error} If tool execution fails
549
593
  */
550
594
  async handleToolRoute(req) {
551
- if (!('toolName' in req.params)) {
552
- throw new http_errors_1.BadRequest('Tool name is required');
553
- }
554
- const tool = this.tools.find(t => t.name === req.params.toolName);
555
- if (!tool) {
556
- throw new http_errors_1.BadRequest(`Tool "${req.params.toolName}" not found`);
557
- }
558
595
  try {
596
+ if (!('toolName' in req.params)) {
597
+ throw new http_errors_1.BadRequest('Tool name is required');
598
+ }
599
+ const tool = this.tools.find(t => t.name === req.params.toolName);
600
+ if (!tool) {
601
+ throw new http_errors_1.BadRequest(`Tool "${req.params.toolName}" not found`);
602
+ }
559
603
  const args = await tool.schema.parseAsync(req.body?.args);
560
- const result = await tool.run.call(this, { args, action: req.body.action }, []);
604
+ const messages = req.body.messages || [];
605
+ const result = await tool.run.call(this, { args, action: req.body.action }, messages);
561
606
  return { result };
562
607
  }
563
608
  catch (error) {
564
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
565
- throw new Error(errorMessage);
609
+ this.handleError(error instanceof Error ? error : new Error(String(error)), {
610
+ request: req,
611
+ context: 'handle_tool_route'
612
+ });
613
+ throw error;
566
614
  }
567
615
  }
568
616
  /**
@@ -574,15 +622,23 @@ class Agent {
574
622
  * @throws {Error} If action type is invalid
575
623
  */
576
624
  async handleRootRoute(req) {
577
- const action = await types_1.actionSchema.parseAsync(req.body);
578
- if (action.type === 'do-task') {
579
- this.doTask(action);
625
+ try {
626
+ const action = await types_1.actionSchema.parseAsync(req.body);
627
+ if (action.type === 'do-task') {
628
+ this.doTask(action);
629
+ }
630
+ else if (action.type === 'respond-chat-message') {
631
+ this.respondToChat(action);
632
+ }
633
+ else
634
+ throw new Error('Invalid action type');
580
635
  }
581
- else if (action.type === 'respond-chat-message') {
582
- this.respondToChat(action);
636
+ catch (error) {
637
+ this.handleError(error instanceof Error ? error : new Error(String(error)), {
638
+ request: req,
639
+ context: 'handle_root_route'
640
+ });
583
641
  }
584
- else
585
- throw new Error('Invalid action type');
586
642
  }
587
643
  /**
588
644
  * Sets up the Express routes for the agent's HTTP server.
@@ -635,6 +691,33 @@ class Agent {
635
691
  this.server?.close(() => resolve());
636
692
  });
637
693
  }
694
+ /**
695
+ * Default error handler that logs the error
696
+ * @private
697
+ */
698
+ handleError(error, context) {
699
+ const handler = this.options.onError ??
700
+ ((err, ctx) => logger_1.logger.error({ error: err, ...ctx }, 'Error in agent operation'));
701
+ handler(error, context);
702
+ }
703
+ /**
704
+ * Calls an integration endpoint through the OpenServ platform.
705
+ * This method allows agents to interact with external services and APIs that are integrated with OpenServ.
706
+ *
707
+ * @param {IntegrationCallRequest} integration - The integration request parameters
708
+ * @param {number} integration.workspaceId - ID of the workspace where the integration is configured
709
+ * @param {string} integration.integrationId - ID of the integration to call
710
+ * @param {Object} integration.details - Details of the integration call
711
+ * @param {string} integration.details.endpoint - The endpoint to call on the integration
712
+ * @param {string} integration.details.method - The HTTP method to use (GET, POST, etc.)
713
+ * @param {Object} [integration.details.data] - Optional data payload for the request
714
+ * @returns {Promise<any>} The response from the integration endpoint
715
+ * @throws {Error} If the integration call fails
716
+ */
717
+ async callIntegration(integration) {
718
+ const response = await this.apiClient.post(`/workspaces/${integration.workspaceId}/integration/${integration.integrationId}/proxy`, integration.details);
719
+ return response.data;
720
+ }
638
721
  }
639
722
  exports.Agent = Agent;
640
723
  function convertToolToJsonSchema(tool) {
@@ -1,11 +1,12 @@
1
- import { z } from 'zod';
1
+ import type { z } from 'zod';
2
2
  import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
3
3
  import type { CapabilityFuncParams } from './types';
4
+ import type { Agent } from './agent';
4
5
  export declare class Capability<Schema extends z.ZodTypeAny> {
5
6
  readonly name: string;
6
7
  readonly description: string;
7
8
  readonly schema: Schema;
8
- readonly run: (params: CapabilityFuncParams<Schema>, messages: ChatCompletionMessageParam[]) => string | Promise<string>;
9
- constructor(name: string, description: string, schema: Schema, run: (params: CapabilityFuncParams<Schema>, messages: ChatCompletionMessageParam[]) => string | Promise<string>);
9
+ readonly run: (this: Agent, params: CapabilityFuncParams<Schema>, messages: ChatCompletionMessageParam[]) => string | Promise<string>;
10
+ constructor(name: string, description: string, schema: Schema, run: (this: Agent, params: CapabilityFuncParams<Schema>, messages: ChatCompletionMessageParam[]) => string | Promise<string>);
10
11
  }
11
12
  //# sourceMappingURL=capability.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAA;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD,qBAAa,UAAU,CAAC,MAAM,SAAS,CAAC,CAAC,UAAU;aAE/B,IAAI,EAAE,MAAM;aACZ,WAAW,EAAE,MAAM;aACnB,MAAM,EAAE,MAAM;aACd,GAAG,EAAE,CACnB,MAAM,EAAE,oBAAoB,CAAC,MAAM,CAAC,EACpC,QAAQ,EAAE,0BAA0B,EAAE,KACnC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;gBANb,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,CACnB,MAAM,EAAE,oBAAoB,CAAC,MAAM,CAAC,EACpC,QAAQ,EAAE,0BAA0B,EAAE,KACnC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAEhC"}
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAC5B,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAA;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AACnD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEpC,qBAAa,UAAU,CAAC,MAAM,SAAS,CAAC,CAAC,UAAU;aAE/B,IAAI,EAAE,MAAM;aACZ,WAAW,EAAE,MAAM;aACnB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