@base44-preview/sdk 0.8.32-pr.205.168e407 → 0.8.32-pr.205.36088fe

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/dist/client.js CHANGED
@@ -6,8 +6,7 @@ import { createSsoModule } from "./modules/sso.js";
6
6
  import { createConnectorsModule, createUserConnectorsModule, } from "./modules/connectors.js";
7
7
  import { getAccessToken } from "./utils/auth-utils.js";
8
8
  import { createFunctionsModule } from "./modules/functions.js";
9
- import { createAgentsModule } from "./modules/agents.js";
10
- import { createDynamicAgentsModule } from "./modules/dynamic-agents.js";
9
+ import { createAgentsModule } from "./modules/agents/index.js";
11
10
  import { createAppLogsModule } from "./modules/app-logs.js";
12
11
  import { createUsersModule } from "./modules/users.js";
13
12
  import { RoomsSocket } from "./utils/socket-utils.js";
@@ -150,9 +149,6 @@ export function createClient(config) {
150
149
  appId,
151
150
  serverUrl,
152
151
  token,
153
- }),
154
- dynamicAgents: createDynamicAgentsModule({
155
- serverUrl,
156
152
  getToken: () => token || getAccessToken() || undefined,
157
153
  }),
158
154
  appLogs: createAppLogsModule(axiosClient, appId),
@@ -196,9 +192,6 @@ export function createClient(config) {
196
192
  appId,
197
193
  serverUrl,
198
194
  token,
199
- }),
200
- dynamicAgents: createDynamicAgentsModule({
201
- serverUrl,
202
195
  getToken: () => serviceToken,
203
196
  }),
204
197
  appLogs: createAppLogsModule(serviceRoleAxiosClient, appId),
@@ -4,10 +4,9 @@ import type { AuthModule } from "./modules/auth.types.js";
4
4
  import type { SsoModule } from "./modules/sso.types.js";
5
5
  import type { ConnectorsModule, UserConnectorsModule } from "./modules/connectors.types.js";
6
6
  import type { FunctionsModule } from "./modules/functions.types.js";
7
- import type { AgentsModule } from "./modules/agents.types.js";
7
+ import type { AgentsModule } from "./modules/agents/agents.types.js";
8
8
  import type { AppLogsModule } from "./modules/app-logs.types.js";
9
9
  import type { AnalyticsModule } from "./modules/analytics.types.js";
10
- import type { DynamicAgentsModule } from "./modules/dynamic-agents.types.js";
11
10
  /**
12
11
  * Options for creating a Base44 client.
13
12
  */
@@ -86,8 +85,6 @@ export interface Base44Client {
86
85
  analytics: AnalyticsModule;
87
86
  /** {@link AppLogsModule | App logs module} for tracking app usage. */
88
87
  appLogs: AppLogsModule;
89
- /** {@link DynamicAgentsModule | Dynamic agents module} for code-defined AI agents and tool loops. */
90
- dynamicAgents: DynamicAgentsModule;
91
88
  /** {@link AuthModule | Auth module} for user authentication and management. */
92
89
  auth: AuthModule;
93
90
  /** {@link UserConnectorsModule | Connectors module} for app-user OAuth flows. */
@@ -129,8 +126,6 @@ export interface Base44Client {
129
126
  agents: AgentsModule;
130
127
  /** {@link AppLogsModule | App logs module} with elevated permissions. */
131
128
  appLogs: AppLogsModule;
132
- /** {@link DynamicAgentsModule | Dynamic agents module} with elevated permissions. */
133
- dynamicAgents: DynamicAgentsModule;
134
129
  /** {@link ConnectorsModule | Connectors module} for OAuth token retrieval. */
135
130
  connectors: ConnectorsModule;
136
131
  /** {@link EntitiesModule | Entities module} with elevated permissions. */
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createClient, createClientFromRequest, type Base44Client, type CreateClientConfig, type CreateClientOptions } from "./client.js";
2
2
  import { Base44Error, type Base44ErrorJSON } from "./utils/axios-client.js";
3
3
  import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl } from "./utils/auth-utils.js";
4
- import { tool } from "./modules/dynamic-agents.js";
4
+ import { tool } from "./modules/agents/tool.js";
5
5
  export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, tool, };
6
6
  export type { Base44Client, CreateClientConfig, CreateClientOptions, Base44ErrorJSON, };
7
7
  export * from "./types.js";
@@ -9,10 +9,10 @@ export type { DeleteManyResult, DeleteResult, EntitiesModule, EntityFilterOperat
9
9
  export type { AuthModule, LoginResponse, RegisterParams, VerifyOtpParams, ChangePasswordParams, ResetPasswordParams, User, } from "./modules/auth.types.js";
10
10
  export type { IntegrationsModule, IntegrationEndpointFunction, CoreIntegrations, InvokeLLMParams, GenerateImageParams, GenerateImageResult, UploadFileParams, UploadFileResult, SendEmailParams, SendEmailResult, ExtractDataFromUploadedFileParams, ExtractDataFromUploadedFileResult, UploadPrivateFileParams, UploadPrivateFileResult, CreateFileSignedUrlParams, CreateFileSignedUrlResult, } from "./modules/integrations.types.js";
11
11
  export type { FunctionsModule, FunctionName, FunctionNameRegistry, } from "./modules/functions.types.js";
12
- export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
12
+ export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents/agents.types.js";
13
13
  export type { AppLogsModule } from "./modules/app-logs.types.js";
14
14
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
15
15
  export type { ConnectorsModule, UserConnectorsModule, } from "./modules/connectors.types.js";
16
16
  export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
17
- export type { Tool, JSONSchema, ChatMessage, Step, RunUsage, RunResult, RunInput, RunOptions, ToolChoice, AgentConfig, Agent, DynamicAgentsModule, } from "./modules/dynamic-agents.types.js";
17
+ export type { Tool, JSONSchema, ChatMessage, Step, RunUsage, RunResult, RunInput, RunOptions, ToolChoice, AgentConfig, Agent, } from "./modules/agents/agents.types.js";
18
18
  export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createClient, createClientFromRequest, } from "./client.js";
2
2
  import { Base44Error } from "./utils/axios-client.js";
3
3
  import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, } from "./utils/auth-utils.js";
4
- import { tool } from "./modules/dynamic-agents.js";
4
+ import { tool } from "./modules/agents/tool.js";
5
5
  export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, tool, };
6
6
  export * from "./types.js";
@@ -1,6 +1,305 @@
1
1
  import { AxiosInstance } from "axios";
2
- import { RoomsSocket } from "../utils/socket-utils.js";
3
- import { ModelFilterParams } from "../types.js";
2
+ import { RoomsSocket } from "../../utils/socket-utils.js";
3
+ import { ModelFilterParams } from "../../types.js";
4
+ /**
5
+ * A JSON Schema object describing a tool's input parameters.
6
+ * Use the standard JSON Schema `object` shape: `{ type: "object", properties: {...}, required: [...] }`.
7
+ */
8
+ export type JSONSchema = Record<string, unknown>;
9
+ /**
10
+ * A tool an agent can call. Create one with {@linkcode tool | tool()}, or derive it from a
11
+ * resource with `.asTool()`.
12
+ */
13
+ export interface Tool {
14
+ /** Natural-language description the model uses to decide when to call the tool. */
15
+ description: string;
16
+ /** JSON Schema for the tool's arguments. */
17
+ parameters: JSONSchema;
18
+ /** Runs the tool. Receives parsed arguments; returns any JSON-serializable value (or a string). */
19
+ execute: (args: any) => Promise<unknown> | unknown;
20
+ }
21
+ /** An OpenAI-shaped chat message used internally and accepted by {@linkcode Agent.run}. */
22
+ export interface ChatMessage {
23
+ role: "system" | "user" | "assistant" | "tool";
24
+ content?: string | null;
25
+ tool_calls?: Array<{
26
+ id: string;
27
+ type: "function";
28
+ function: {
29
+ name: string;
30
+ arguments: string;
31
+ };
32
+ }>;
33
+ tool_call_id?: string;
34
+ }
35
+ /** One iteration of the agent loop: the tool calls the model made and their results. */
36
+ export interface Step {
37
+ toolResults: Array<{
38
+ toolCallId: string;
39
+ toolName: string;
40
+ args: unknown;
41
+ result: string;
42
+ }>;
43
+ /** Token/credit usage of the model call that produced this step's tool calls. */
44
+ usage?: RunUsage;
45
+ }
46
+ /** Token/credit usage for a single model call or a sum across calls. `credits` is the Base44 gateway's `base44_credits`. */
47
+ export interface RunUsage {
48
+ inputTokens?: number;
49
+ outputTokens?: number;
50
+ totalTokens?: number;
51
+ credits?: number;
52
+ }
53
+ /** Result of {@linkcode Agent.run}. */
54
+ export interface RunResult {
55
+ /** The model's final text output. */
56
+ text: string;
57
+ /** The loop history (one entry per step that made tool calls). */
58
+ steps: Step[];
59
+ /** Why the run ended: `"stop"` (model finished), `"tool_calls"`, or `"max_steps"`. */
60
+ finishReason: string;
61
+ /** Token and credit usage from the final completion. */
62
+ usage: RunUsage;
63
+ /** Summed across all model calls in the loop; `usage` is the final call only. */
64
+ totalUsage: RunUsage;
65
+ /** The raw final completion body, for advanced use. */
66
+ raw: unknown;
67
+ }
68
+ /** Input to {@linkcode Agent.run}: either a single prompt or a full message list. */
69
+ export type RunInput = {
70
+ prompt: string;
71
+ } | {
72
+ messages: ChatMessage[];
73
+ };
74
+ /**
75
+ * Per-run options passed as the second argument to {@linkcode Agent.run}.
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * const controller = new AbortController();
80
+ * setTimeout(() => controller.abort(), 10_000);
81
+ *
82
+ * const result = await agent.run(
83
+ * { prompt: "Summarize last month's sales." },
84
+ * { abortSignal: controller.signal },
85
+ * );
86
+ * ```
87
+ */
88
+ export interface RunOptions {
89
+ /** Abort the run (and the in-flight gateway request). */
90
+ abortSignal?: AbortSignal;
91
+ }
92
+ /** OpenAI-compatible tool choice. */
93
+ export type ToolChoice = "auto" | "none" | "required" | {
94
+ type: "function";
95
+ function: {
96
+ name: string;
97
+ };
98
+ };
99
+ /**
100
+ * Configuration for a code-defined agent passed to {@linkcode AgentsModule.create}.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * const agent = base44.agents.create({
105
+ * model: "claude_sonnet_4_6",
106
+ * system: "You are a concise travel planner.",
107
+ * tools: { getWeather, searchFlights },
108
+ * maxSteps: 5,
109
+ * });
110
+ * ```
111
+ */
112
+ export interface AgentConfig {
113
+ /**
114
+ * Model alias or vendor model ID to use for this agent.
115
+ *
116
+ * Use a Base44 model alias (e.g. `"claude_sonnet_4_6"`, `"gpt_4o"`, `"gpt_5_mini"`) or a
117
+ * fully-qualified vendor ID. Available aliases are listed in the Base44 console.
118
+ */
119
+ model: string;
120
+ /**
121
+ * System prompt prepended to every run.
122
+ *
123
+ * Provide instructions, persona, or constraints for the model.
124
+ * Omit to let the model run without a system message.
125
+ */
126
+ system?: string;
127
+ /**
128
+ * Tools the agent may call, keyed by their function name.
129
+ *
130
+ * Each value must be a {@linkcode Tool} object — use the {@linkcode tool | tool()} factory
131
+ * to create one, or use `.asTool()` on a resource such as an entity or function.
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * import { tool } from "@base44/sdk";
136
+ *
137
+ * const getWeather = tool({
138
+ * description: "Get the current weather for a city.",
139
+ * parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
140
+ * execute: async ({ city }) => fetch(`/weather?city=${city}`).then(r => r.json()),
141
+ * });
142
+ *
143
+ * const agent = base44.agents.create({ model: "claude_sonnet_4_6", tools: { getWeather } });
144
+ * ```
145
+ */
146
+ tools?: Record<string, Tool>;
147
+ /**
148
+ * Maximum number of tool-calling loop iterations before the run stops.
149
+ *
150
+ * Each iteration is one round-trip to the model. If the model keeps calling tools
151
+ * and this limit is reached, the run ends with `finishReason: "max_steps"`.
152
+ * Defaults to `8`.
153
+ */
154
+ maxSteps?: number;
155
+ /**
156
+ * Sampling temperature passed to the model.
157
+ *
158
+ * Controls output randomness: lower values (e.g. `0`) produce more deterministic
159
+ * responses; higher values (e.g. `1`) increase variety. Omit to use the model default.
160
+ *
161
+ * Note: GPT-5 series models only accept `temperature: 1`.
162
+ */
163
+ temperature?: number;
164
+ /**
165
+ * JSON Schema to constrain the model's output to structured JSON.
166
+ *
167
+ * When set, the request is sent with `response_format: { type: "json_schema", … }`.
168
+ * The model's response will be valid JSON matching the schema; access it by parsing
169
+ * `RunResult.text`.
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * const agent = base44.agents.create({
174
+ * model: "claude_sonnet_4_6",
175
+ * responseFormat: {
176
+ * type: "object",
177
+ * properties: { summary: { type: "string" }, score: { type: "number" } },
178
+ * required: ["summary", "score"],
179
+ * },
180
+ * });
181
+ * const { text } = await agent.run({ prompt: "Rate this product description." });
182
+ * const { summary, score } = JSON.parse(text);
183
+ * ```
184
+ */
185
+ responseFormat?: JSONSchema;
186
+ /**
187
+ * Controls whether and which tool the model must call.
188
+ *
189
+ * - `"auto"` (default when tools are provided): the model decides.
190
+ * - `"none"`: the model must not call any tool.
191
+ * - `"required"`: the model must call at least one tool.
192
+ * - `{ type: "function", function: { name } }`: force a specific tool.
193
+ */
194
+ toolChoice?: ToolChoice;
195
+ }
196
+ /**
197
+ * A reusable code-defined agent returned by {@linkcode AgentsModule.create}.
198
+ *
199
+ * An agent runs a multi-step tool-calling loop: it sends messages to the model,
200
+ * executes any tool calls the model requests, feeds the results back, and repeats
201
+ * until the model produces a final answer or `maxSteps` is reached.
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * const agent = base44.agents.create({
206
+ * model: "claude_sonnet_4_6",
207
+ * system: "You are a concise travel planner.",
208
+ * tools: { getWeather },
209
+ * });
210
+ *
211
+ * const { text } = await agent.run({ prompt: "What's the weather like in Tel Aviv?" });
212
+ * console.log(text);
213
+ * ```
214
+ */
215
+ export interface Agent {
216
+ /**
217
+ * Runs the agent's tool-calling loop to completion and returns the final result.
218
+ *
219
+ * Builds an initial message list from `input`, then repeatedly calls the model,
220
+ * executes any tool calls, and feeds results back until the model stops or
221
+ * `maxSteps` (from {@linkcode AgentConfig}) is reached.
222
+ *
223
+ * Tool errors are fed back to the model as tool results rather than thrown, so
224
+ * the model can recover or explain the failure.
225
+ *
226
+ * @param input - The run input: either `{ prompt: string }` for a simple user
227
+ * message, or `{ messages: ChatMessage[] }` to supply a full conversation history.
228
+ * @param options - Optional {@linkcode RunOptions} (e.g. an `AbortSignal`).
229
+ * @returns Promise resolving to a {@linkcode RunResult} containing the model's
230
+ * final text, per-step tool call history, finish reason, and token/credit usage.
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * // Simple prompt
235
+ * const { text, usage } = await agent.run({ prompt: "Plan a one-day trip to Haifa." });
236
+ * console.log(text);
237
+ * console.log(`Credits used: ${usage.credits}`);
238
+ * ```
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * // Supply a full message history
243
+ * const { text } = await agent.run({
244
+ * messages: [
245
+ * { role: "user", content: "What is the capital of France?" },
246
+ * { role: "assistant", content: "Paris." },
247
+ * { role: "user", content: "And what is the population?" },
248
+ * ],
249
+ * });
250
+ * ```
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * // Cancel a long-running run
255
+ * const controller = new AbortController();
256
+ * setTimeout(() => controller.abort(), 15_000);
257
+ * const { text } = await agent.run(
258
+ * { prompt: "Summarize all open support tickets." },
259
+ * { abortSignal: controller.signal },
260
+ * );
261
+ * ```
262
+ */
263
+ run(input: RunInput, options?: RunOptions): Promise<RunResult>;
264
+ /**
265
+ * Wraps this agent as a {@linkcode Tool} so another agent can call it as a sub-agent.
266
+ *
267
+ * The returned tool exposes a single `prompt` parameter. When called, it invokes
268
+ * {@linkcode Agent.run | run()} with that prompt and returns the text result.
269
+ * Use this to build agent hierarchies where a coordinator agent delegates tasks
270
+ * to specialized sub-agents.
271
+ *
272
+ * @param opts - Options for the tool wrapper.
273
+ * @param opts.description - Required. Natural-language description the calling
274
+ * model uses to decide when to invoke this sub-agent.
275
+ * @param opts.name - Optional display name for the tool. Defaults to the
276
+ * agent config's model alias when omitted.
277
+ * @returns A {@linkcode Tool} that can be passed in another agent's `tools` map.
278
+ *
279
+ * @example
280
+ * ```typescript
281
+ * const researchAgent = base44.agents.create({
282
+ * model: "claude_sonnet_4_6",
283
+ * tools: { webSearch },
284
+ * });
285
+ *
286
+ * const writerAgent = base44.agents.create({
287
+ * model: "claude_sonnet_4_6",
288
+ * tools: {
289
+ * research: researchAgent.asTool({
290
+ * description: "Search the web and return a research summary.",
291
+ * }),
292
+ * },
293
+ * });
294
+ *
295
+ * const { text } = await writerAgent.run({ prompt: "Write a blog post about coral reefs." });
296
+ * ```
297
+ */
298
+ asTool(opts: {
299
+ name?: string;
300
+ description: string;
301
+ }): Tool;
302
+ }
4
303
  /**
5
304
  * Registry of agent names. The [`types generate`](/developers/references/cli/commands/types-generate) command fills this registry, then [`AgentName`](#agentname) resolves to a union of the keys.
6
305
  */
@@ -162,6 +461,8 @@ export interface AgentsModuleConfig {
162
461
  serverUrl?: string;
163
462
  /** Authentication token */
164
463
  token?: string;
464
+ /** Returns the current bearer token at call time (thunk — never a captured string). Used by `create()`. */
465
+ getToken?: () => string | undefined;
165
466
  }
166
467
  /**
167
468
  * Agents module for managing AI agent conversations.
@@ -356,6 +657,27 @@ export interface AgentsModule {
356
657
  * ```
357
658
  */
358
659
  subscribeToConversation(conversationId: string, onUpdate?: (conversation: AgentConversation) => void): () => void;
660
+ /**
661
+ * Creates a code-defined agent: you specify the model, system prompt, and tools in code,
662
+ * and the SDK runs the tool-calling loop against the Base44 AI Gateway.
663
+ *
664
+ * Returns a reusable {@linkcode Agent} you can {@linkcode Agent.run | run} or expose to
665
+ * another agent as a tool with {@linkcode Agent.asTool | asTool}.
666
+ *
667
+ * @param config - Model alias, optional system prompt, tools, and step limit.
668
+ * @returns A reusable {@linkcode Agent} with {@linkcode Agent.run | run()} and {@linkcode Agent.asTool | asTool()}.
669
+ *
670
+ * @example
671
+ * ```typescript
672
+ * const agent = base44.agents.create({
673
+ * model: "claude_sonnet_4_6",
674
+ * system: "You plan trips.",
675
+ * tools: { getWeather },
676
+ * });
677
+ * const { text } = await agent.run({ prompt: "Plan a day in Haifa." });
678
+ * ```
679
+ */
680
+ create(config: AgentConfig): Agent;
359
681
  /**
360
682
  * Gets WhatsApp connection URL for an agent.
361
683
  *
@@ -0,0 +1,24 @@
1
+ /** @internal */
2
+ export interface GatewayConfig {
3
+ serverUrl: string;
4
+ /** Returns the current bearer token at call time (thunk — never a captured string). */
5
+ getToken: () => string | undefined;
6
+ }
7
+ /**
8
+ * Resolves the AI Gateway connection from a client config.
9
+ * @internal
10
+ */
11
+ export declare function resolveConnection(config: GatewayConfig): {
12
+ baseURL: string;
13
+ apiKey: string;
14
+ };
15
+ /**
16
+ * Creates the gateway transport — owns the single HTTP call to the OpenAI-compatible
17
+ * `/chat/completions` endpoint.
18
+ * @internal
19
+ */
20
+ export declare function createGatewayTransport(config: GatewayConfig): {
21
+ complete(body: Record<string, unknown>, opts?: {
22
+ signal?: AbortSignal;
23
+ }): Promise<unknown>;
24
+ };
@@ -1,4 +1,4 @@
1
- import { Base44Error } from "../utils/axios-client.js";
1
+ import { Base44Error } from "../../utils/axios-client.js";
2
2
  /**
3
3
  * Resolves the AI Gateway connection from a client config.
4
4
  * @internal
@@ -13,9 +13,8 @@ export function resolveConnection(config) {
13
13
  };
14
14
  }
15
15
  /**
16
- * Creates the gateway transport. Owns the single HTTP call to the OpenAI-compatible
17
- * `/chat/completions` endpoint. Shaped so a streaming `.stream()` method can be added
18
- * later without changing callers of `.complete()`.
16
+ * Creates the gateway transport owns the single HTTP call to the OpenAI-compatible
17
+ * `/chat/completions` endpoint.
19
18
  * @internal
20
19
  */
21
20
  export function createGatewayTransport(config) {
@@ -1,2 +1,2 @@
1
1
  import { AgentsModule, AgentsModuleConfig } from "./agents.types.js";
2
- export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }: AgentsModuleConfig): AgentsModule;
2
+ export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token, getToken, }: AgentsModuleConfig): AgentsModule;
@@ -1,5 +1,12 @@
1
- import { getAccessToken } from "../utils/auth-utils.js";
2
- export function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }) {
1
+ import { getAccessToken } from "../../utils/auth-utils.js";
2
+ import { createGatewayTransport } from "./gateway.js";
3
+ import { openAICompatibleProvider } from "./providers/openai-compatible.js";
4
+ import { createAgent } from "./loop.js";
5
+ export function createAgentsModule({ axios, getSocket, appId, serverUrl, token, getToken, }) {
6
+ const model = openAICompatibleProvider(createGatewayTransport({
7
+ serverUrl: serverUrl !== null && serverUrl !== void 0 ? serverUrl : "",
8
+ getToken: getToken !== null && getToken !== void 0 ? getToken : (() => token),
9
+ }));
3
10
  const baseURL = `/apps/${appId}/agents`;
4
11
  // Track active conversations
5
12
  const currentConversations = {};
@@ -85,5 +92,6 @@ export function createAgentsModule({ axios, getSocket, appId, serverUrl, token,
85
92
  subscribeToConversation,
86
93
  getWhatsAppConnectURL,
87
94
  getTelegramConnectURL,
95
+ create(config) { return createAgent(config, model); },
88
96
  };
89
97
  }
@@ -0,0 +1,4 @@
1
+ import type { Agent, AgentConfig } from "./agents.types.js";
2
+ import type { LanguageModel } from "./provider.js";
3
+ /** Creates an Agent from a config and a language model. @internal */
4
+ export declare function createAgent(agentConfig: AgentConfig, model: LanguageModel): Agent;
@@ -0,0 +1,146 @@
1
+ const DEFAULT_MAX_STEPS = 8;
2
+ function safeParseJson(json) {
3
+ try {
4
+ return JSON.parse(json || "{}");
5
+ }
6
+ catch (_a) {
7
+ return {};
8
+ }
9
+ }
10
+ function inputToMessages(input) {
11
+ if (!("messages" in input)) {
12
+ return [{ role: "user", content: input.prompt }];
13
+ }
14
+ // Map the public ChatMessage[] 1:1 to neutral ModelMessage[] by role.
15
+ return input.messages.map((message) => {
16
+ var _a, _b, _c;
17
+ if (message.role === "system") {
18
+ return { role: "system", content: typeof message.content === "string" ? message.content : "" };
19
+ }
20
+ if (message.role === "user") {
21
+ return { role: "user", content: typeof message.content === "string" ? message.content : "" };
22
+ }
23
+ if (message.role === "assistant") {
24
+ const toolCalls = (_a = message.tool_calls) === null || _a === void 0 ? void 0 : _a.map((call) => ({
25
+ id: call.id,
26
+ name: call.function.name,
27
+ args: safeParseJson(call.function.arguments),
28
+ }));
29
+ return {
30
+ role: "assistant",
31
+ content: (_b = message.content) !== null && _b !== void 0 ? _b : undefined,
32
+ toolCalls: (toolCalls === null || toolCalls === void 0 ? void 0 : toolCalls.length) ? toolCalls : undefined,
33
+ };
34
+ }
35
+ // tool
36
+ return {
37
+ role: "tool",
38
+ toolCallId: (_c = message.tool_call_id) !== null && _c !== void 0 ? _c : "",
39
+ result: typeof message.content === "string" ? message.content : "",
40
+ };
41
+ });
42
+ }
43
+ function stringifyToolResult(value) {
44
+ return typeof value === "string" ? value : JSON.stringify(value);
45
+ }
46
+ function sumUsage(accumulated, next) {
47
+ var _a, _b, _c, _d, _e, _f, _g, _h;
48
+ return {
49
+ inputTokens: ((_a = accumulated.inputTokens) !== null && _a !== void 0 ? _a : 0) + ((_b = next.inputTokens) !== null && _b !== void 0 ? _b : 0),
50
+ outputTokens: ((_c = accumulated.outputTokens) !== null && _c !== void 0 ? _c : 0) + ((_d = next.outputTokens) !== null && _d !== void 0 ? _d : 0),
51
+ totalTokens: ((_e = accumulated.totalTokens) !== null && _e !== void 0 ? _e : 0) + ((_f = next.totalTokens) !== null && _f !== void 0 ? _f : 0),
52
+ credits: ((_g = accumulated.credits) !== null && _g !== void 0 ? _g : 0) + ((_h = next.credits) !== null && _h !== void 0 ? _h : 0),
53
+ };
54
+ }
55
+ /** Creates an Agent from a config and a language model. @internal */
56
+ export function createAgent(agentConfig, model) {
57
+ var _a;
58
+ const maxSteps = (_a = agentConfig.maxSteps) !== null && _a !== void 0 ? _a : DEFAULT_MAX_STEPS;
59
+ const tools = agentConfig.tools;
60
+ const agent = {
61
+ async run(input, options = {}) {
62
+ var _a, _b, _c, _d;
63
+ const messages = [
64
+ ...(agentConfig.system ? [{ role: "system", content: agentConfig.system }] : []),
65
+ ...inputToMessages(input),
66
+ ];
67
+ const steps = [];
68
+ let totalUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, credits: 0 };
69
+ // The most recent model call; referenced after the loop for the max-steps return.
70
+ let modelResult = null;
71
+ for (let step = 0; step < maxSteps; step++) {
72
+ modelResult = await model.generate({
73
+ model: agentConfig.model,
74
+ messages,
75
+ tools,
76
+ temperature: agentConfig.temperature,
77
+ toolChoice: agentConfig.toolChoice,
78
+ responseFormat: agentConfig.responseFormat,
79
+ signal: options.abortSignal,
80
+ });
81
+ totalUsage = sumUsage(totalUsage, (_a = modelResult.usage) !== null && _a !== void 0 ? _a : {});
82
+ messages.push({
83
+ role: "assistant",
84
+ content: modelResult.text || undefined,
85
+ toolCalls: modelResult.toolCalls.length ? modelResult.toolCalls : undefined,
86
+ });
87
+ // No tool calls: the model is done — return its final answer.
88
+ if (modelResult.toolCalls.length === 0) {
89
+ return {
90
+ text: modelResult.text,
91
+ steps,
92
+ finishReason: modelResult.finishReason,
93
+ usage: modelResult.usage,
94
+ totalUsage,
95
+ raw: modelResult.raw,
96
+ };
97
+ }
98
+ // Execute each requested tool and feed the result back for the next turn.
99
+ const toolResults = [];
100
+ for (const call of modelResult.toolCalls) {
101
+ const matchedTool = tools === null || tools === void 0 ? void 0 : tools[call.name];
102
+ let resultContent;
103
+ if (!matchedTool) {
104
+ resultContent = `Error: tool "${call.name}" is not available.`;
105
+ }
106
+ else {
107
+ try {
108
+ resultContent = stringifyToolResult(await matchedTool.execute(call.args));
109
+ }
110
+ catch (error) {
111
+ const message = error === null || error === void 0 ? void 0 : error.message;
112
+ resultContent = `Error: ${message !== null && message !== void 0 ? message : String(error)}`;
113
+ }
114
+ }
115
+ messages.push({ role: "tool", toolCallId: call.id, toolName: call.name, result: resultContent });
116
+ toolResults.push({ toolCallId: call.id, toolName: call.name, args: call.args, result: resultContent });
117
+ }
118
+ steps.push({ toolResults, usage: modelResult.usage });
119
+ }
120
+ // Loop exhausted without a final (tool-free) answer.
121
+ return {
122
+ text: (_b = modelResult === null || modelResult === void 0 ? void 0 : modelResult.text) !== null && _b !== void 0 ? _b : "",
123
+ steps,
124
+ finishReason: "max_steps",
125
+ usage: (_c = modelResult === null || modelResult === void 0 ? void 0 : modelResult.usage) !== null && _c !== void 0 ? _c : {},
126
+ totalUsage,
127
+ raw: (_d = modelResult === null || modelResult === void 0 ? void 0 : modelResult.raw) !== null && _d !== void 0 ? _d : null,
128
+ };
129
+ },
130
+ asTool(toolOpts) {
131
+ return {
132
+ description: toolOpts.description,
133
+ parameters: {
134
+ type: "object",
135
+ properties: { prompt: { type: "string", description: "What to ask the sub-agent." } },
136
+ required: ["prompt"],
137
+ },
138
+ execute: async (args) => {
139
+ const result = await agent.run({ prompt: args.prompt });
140
+ return result.text;
141
+ },
142
+ };
143
+ },
144
+ };
145
+ return agent;
146
+ }