@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.
@@ -0,0 +1,55 @@
1
+ import type { Tool, ToolChoice, JSONSchema, RunUsage } from "./agents.types.js";
2
+ /** A parsed tool call the model wants to make. Args are already parsed (object), never a JSON string. @internal */
3
+ export interface ModelToolCall {
4
+ id: string;
5
+ name: string;
6
+ args: unknown;
7
+ }
8
+ /**
9
+ * Neutral, provider-agnostic conversation message. `system` is a message role here;
10
+ * each provider adapter places it where its wire format expects. `content` is a string.
11
+ * @internal
12
+ */
13
+ export type ModelMessage = {
14
+ role: "system";
15
+ content: string;
16
+ } | {
17
+ role: "user";
18
+ content: string;
19
+ } | {
20
+ role: "assistant";
21
+ content?: string;
22
+ toolCalls?: ModelToolCall[];
23
+ } | {
24
+ role: "tool";
25
+ toolCallId: string;
26
+ toolName?: string;
27
+ result: string;
28
+ };
29
+ /** Finish reasons normalized across providers. @internal */
30
+ export type FinishReason = "stop" | "length" | "tool-calls" | "content-filter" | "error" | "other";
31
+ /** A request to a language model. @internal */
32
+ export interface GenerateRequest {
33
+ model: string;
34
+ messages: ModelMessage[];
35
+ tools?: Record<string, Tool>;
36
+ temperature?: number;
37
+ toolChoice?: ToolChoice;
38
+ responseFormat?: JSONSchema;
39
+ signal?: AbortSignal;
40
+ }
41
+ /** Normalized model output. @internal */
42
+ export interface GenerateResult {
43
+ text: string;
44
+ toolCalls: ModelToolCall[];
45
+ finishReason: FinishReason;
46
+ usage: RunUsage;
47
+ /** Opaque vendor-specific extras (cache control, reasoning, safety, …). @internal */
48
+ providerMetadata?: Record<string, unknown>;
49
+ /** The raw vendor response, for advanced use. */
50
+ raw: unknown;
51
+ }
52
+ /** The provider seam. Adapters translate neutral <-> vendor wire. @internal */
53
+ export interface LanguageModel {
54
+ generate(req: GenerateRequest): Promise<GenerateResult>;
55
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { LanguageModel } from "../provider.js";
2
+ interface GatewayTransport {
3
+ complete(body: Record<string, unknown>, opts?: {
4
+ signal?: AbortSignal;
5
+ }): Promise<any>;
6
+ }
7
+ /**
8
+ * OpenAI-compatible provider: speaks the Chat Completions wire format over the Base44
9
+ * gateway transport.
10
+ * @internal
11
+ */
12
+ export declare function openAICompatibleProvider(transport: GatewayTransport): LanguageModel;
13
+ export {};
@@ -0,0 +1,110 @@
1
+ function serializeTools(tools) {
2
+ if (!tools)
3
+ return undefined;
4
+ const entries = Object.entries(tools);
5
+ if (entries.length === 0)
6
+ return undefined;
7
+ return entries.map(([name, toolDef]) => ({
8
+ type: "function",
9
+ function: { name, description: toolDef.description, parameters: toolDef.parameters },
10
+ }));
11
+ }
12
+ /** Neutral messages -> Chat Completions messages. System role in the array is passed through. */
13
+ function toChatMessages(messages) {
14
+ var _a, _b;
15
+ const chatMessages = [];
16
+ for (const message of messages) {
17
+ if (message.role === "system") {
18
+ chatMessages.push({ role: "system", content: message.content });
19
+ }
20
+ else if (message.role === "user") {
21
+ chatMessages.push({ role: "user", content: message.content });
22
+ }
23
+ else if (message.role === "assistant") {
24
+ const assistantMessage = { role: "assistant", content: (_a = message.content) !== null && _a !== void 0 ? _a : null };
25
+ if ((_b = message.toolCalls) === null || _b === void 0 ? void 0 : _b.length) {
26
+ assistantMessage.tool_calls = message.toolCalls.map((call) => {
27
+ var _a;
28
+ return ({
29
+ id: call.id,
30
+ type: "function",
31
+ function: { name: call.name, arguments: JSON.stringify((_a = call.args) !== null && _a !== void 0 ? _a : {}) },
32
+ });
33
+ });
34
+ }
35
+ chatMessages.push(assistantMessage);
36
+ }
37
+ else {
38
+ chatMessages.push({ role: "tool", tool_call_id: message.toolCallId, content: message.result });
39
+ }
40
+ }
41
+ return chatMessages;
42
+ }
43
+ /** Build the Chat Completions body using the param whitelist (rejected params can never appear). */
44
+ function buildChatCompletionsBody(req) {
45
+ const body = { model: req.model, messages: toChatMessages(req.messages) };
46
+ if (req.temperature !== undefined)
47
+ body.temperature = req.temperature;
48
+ if (req.toolChoice !== undefined)
49
+ body.tool_choice = req.toolChoice;
50
+ if (req.responseFormat !== undefined) {
51
+ body.response_format = { type: "json_schema", json_schema: { name: "response", schema: req.responseFormat, strict: true } };
52
+ }
53
+ const tools = serializeTools(req.tools);
54
+ if (tools)
55
+ body.tools = tools;
56
+ return body;
57
+ }
58
+ const FINISH = {
59
+ stop: "stop", length: "length", tool_calls: "tool-calls", content_filter: "content-filter",
60
+ };
61
+ function normalizeFinish(raw, hasToolCalls) {
62
+ if (hasToolCalls)
63
+ return "tool-calls";
64
+ if (raw !== undefined && FINISH[raw])
65
+ return FINISH[raw];
66
+ return "other";
67
+ }
68
+ function parseChatCompletion(raw) {
69
+ var _a, _b, _c, _d, _e;
70
+ const choice = (_a = raw === null || raw === void 0 ? void 0 : raw.choices) === null || _a === void 0 ? void 0 : _a[0];
71
+ const message = (_b = choice === null || choice === void 0 ? void 0 : choice.message) !== null && _b !== void 0 ? _b : {};
72
+ const toolCalls = ((_c = message.tool_calls) !== null && _c !== void 0 ? _c : []).map((call) => {
73
+ var _a, _b;
74
+ let args = {};
75
+ try {
76
+ args = JSON.parse(((_a = call.function) === null || _a === void 0 ? void 0 : _a.arguments) || "{}");
77
+ }
78
+ catch (_c) {
79
+ args = {};
80
+ }
81
+ return { id: call.id, name: (_b = call.function) === null || _b === void 0 ? void 0 : _b.name, args };
82
+ });
83
+ const rawUsage = (_d = raw === null || raw === void 0 ? void 0 : raw.usage) !== null && _d !== void 0 ? _d : {};
84
+ const usage = {
85
+ inputTokens: rawUsage.prompt_tokens,
86
+ outputTokens: rawUsage.completion_tokens,
87
+ totalTokens: rawUsage.total_tokens,
88
+ credits: rawUsage.base44_credits,
89
+ };
90
+ return {
91
+ text: (_e = message.content) !== null && _e !== void 0 ? _e : "",
92
+ toolCalls,
93
+ finishReason: normalizeFinish(choice === null || choice === void 0 ? void 0 : choice.finish_reason, toolCalls.length > 0),
94
+ usage,
95
+ raw,
96
+ };
97
+ }
98
+ /**
99
+ * OpenAI-compatible provider: speaks the Chat Completions wire format over the Base44
100
+ * gateway transport.
101
+ * @internal
102
+ */
103
+ export function openAICompatibleProvider(transport) {
104
+ return {
105
+ async generate(req) {
106
+ const raw = await transport.complete(buildChatCompletionsBody(req), { signal: req.signal });
107
+ return parseChatCompletion(raw);
108
+ },
109
+ };
110
+ }
@@ -0,0 +1,37 @@
1
+ import type { Tool } from "./agents.types.js";
2
+ /**
3
+ * Defines a tool an agent can call.
4
+ *
5
+ * A tool combines a natural-language `description` (used by the model to decide
6
+ * when to call the tool), a JSON Schema for its `parameters`, and an `execute`
7
+ * function that runs when the model calls it.
8
+ *
9
+ * Pass the returned tool in the `tools` map of {@linkcode AgentsModule.create | base44.agents.create()}.
10
+ *
11
+ * @param t - The tool definition: `description`, `parameters` (JSON Schema), and `execute`.
12
+ * @returns The same tool object, typed as {@linkcode Tool}.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { tool } from "@base44/sdk";
17
+ *
18
+ * const getWeather = tool({
19
+ * description: "Get the current weather for a city.",
20
+ * parameters: {
21
+ * type: "object",
22
+ * properties: { city: { type: "string", description: "City name, e.g. 'Tel Aviv'" } },
23
+ * required: ["city"],
24
+ * },
25
+ * execute: async ({ city }) => {
26
+ * const data = await fetchWeatherAPI(city);
27
+ * return { city, tempC: data.temperature };
28
+ * },
29
+ * });
30
+ *
31
+ * const agent = base44.agents.create({
32
+ * model: "claude_sonnet_4_6",
33
+ * tools: { getWeather },
34
+ * });
35
+ * ```
36
+ */
37
+ export declare function tool(t: Tool): Tool;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Defines a tool an agent can call.
3
+ *
4
+ * A tool combines a natural-language `description` (used by the model to decide
5
+ * when to call the tool), a JSON Schema for its `parameters`, and an `execute`
6
+ * function that runs when the model calls it.
7
+ *
8
+ * Pass the returned tool in the `tools` map of {@linkcode AgentsModule.create | base44.agents.create()}.
9
+ *
10
+ * @param t - The tool definition: `description`, `parameters` (JSON Schema), and `execute`.
11
+ * @returns The same tool object, typed as {@linkcode Tool}.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { tool } from "@base44/sdk";
16
+ *
17
+ * const getWeather = tool({
18
+ * description: "Get the current weather for a city.",
19
+ * parameters: {
20
+ * type: "object",
21
+ * properties: { city: { type: "string", description: "City name, e.g. 'Tel Aviv'" } },
22
+ * required: ["city"],
23
+ * },
24
+ * execute: async ({ city }) => {
25
+ * const data = await fetchWeatherAPI(city);
26
+ * return { city, tempC: data.temperature };
27
+ * },
28
+ * });
29
+ *
30
+ * const agent = base44.agents.create({
31
+ * model: "claude_sonnet_4_6",
32
+ * tools: { getWeather },
33
+ * });
34
+ * ```
35
+ */
36
+ export function tool(t) {
37
+ return t;
38
+ }
@@ -53,7 +53,7 @@ function parseRealtimeMessage(dataStr) {
53
53
  */
54
54
  function createEntityHandler(axios, appId, entityName, getSocket) {
55
55
  const baseURL = `/apps/${appId}/entities/${entityName}`;
56
- return {
56
+ const handler = {
57
57
  // List entities with optional pagination and sorting
58
58
  async list(sort, limit, skip, fields) {
59
59
  const params = {};
@@ -159,5 +159,62 @@ function createEntityHandler(axios, appId, entityName, getSocket) {
159
159
  });
160
160
  return unsubscribe;
161
161
  },
162
+ asTool(opts = {}) {
163
+ var _a;
164
+ const operations = (_a = opts.operations) !== null && _a !== void 0 ? _a : ["read"];
165
+ const tools = {};
166
+ if (operations.includes("read")) {
167
+ tools[`read_${entityName}`] = {
168
+ description: `Read ${entityName} entities. For the query param, use MongoDB query syntax, e.g. { "status": "open", "price": { "$gt": 30 } }.`,
169
+ parameters: {
170
+ type: "object",
171
+ properties: {
172
+ query: { type: "object", description: `MongoDB-style filter over ${entityName} fields.`, additionalProperties: true },
173
+ sort: { type: "string", description: "Field to sort by; prefix with '-' for descending (e.g. '-created_date')." },
174
+ limit: { type: "number", description: "Maximum number of records to return." },
175
+ skip: { type: "number", description: "Number of records to skip (pagination)." },
176
+ fields: { type: "array", items: { type: "string" }, description: "Subset of fields to return." },
177
+ },
178
+ },
179
+ execute: (args = {}) => { var _a; return handler.filter(((_a = args.query) !== null && _a !== void 0 ? _a : {}), args.sort, args.limit, args.skip, args.fields); },
180
+ };
181
+ }
182
+ if (operations.includes("create")) {
183
+ tools[`create_${entityName}`] = {
184
+ description: `Create a new ${entityName} entity`,
185
+ // open object: the SDK has no runtime schema, so the model supplies fields directly
186
+ parameters: { type: "object", additionalProperties: true },
187
+ execute: (args = {}) => handler.create(args),
188
+ };
189
+ }
190
+ if (operations.includes("update")) {
191
+ tools[`update_${entityName}`] = {
192
+ description: `Update an existing ${entityName} entity`,
193
+ parameters: {
194
+ type: "object",
195
+ properties: { id: { type: "string", description: `The id of the ${entityName} to update.` } },
196
+ required: ["id"],
197
+ additionalProperties: true,
198
+ },
199
+ execute: (args) => {
200
+ const { id, ...data } = args !== null && args !== void 0 ? args : {};
201
+ return handler.update(id, data);
202
+ },
203
+ };
204
+ }
205
+ if (operations.includes("delete")) {
206
+ tools[`delete_${entityName}`] = {
207
+ description: `Delete an existing ${entityName} entity`,
208
+ parameters: {
209
+ type: "object",
210
+ properties: { id: { type: "string", description: `The id of the ${entityName} to delete.` } },
211
+ required: ["id"],
212
+ },
213
+ execute: (args) => handler.delete(args.id),
214
+ };
215
+ }
216
+ return tools;
217
+ },
162
218
  };
219
+ return handler;
163
220
  }
@@ -640,6 +640,25 @@ export interface EntityHandler<T = any> {
640
640
  * ```
641
641
  */
642
642
  subscribe(callback: RealtimeCallback<T>): () => void;
643
+ /**
644
+ * Turns this entity into a map of agent tools — one per allowed operation
645
+ * (`read_<Entity>`, `create_<Entity>`, `update_<Entity>`, `delete_<Entity>`).
646
+ * Read-only by default, pass `operations` to opt into writes. Spread the result into an agent's `tools`.
647
+ *
648
+ * @param opts - Optional `operations` (`"read" | "create" | "update" | "delete"`, default `["read"]`).
649
+ * @returns A map of tool-name -> {@linkcode Tool}.
650
+ *
651
+ * @example
652
+ * ```typescript
653
+ * const agent = base44.agents.create({
654
+ * model: "claude_sonnet_4_6",
655
+ * tools: { ...base44.entities.Order.asTool({ operations: ["read", "update"] }) },
656
+ * });
657
+ * ```
658
+ */
659
+ asTool(opts?: {
660
+ operations?: ("read" | "create" | "update" | "delete")[];
661
+ }): Record<string, import("./agents/agents.types.js").Tool>;
643
662
  }
644
663
  /**
645
664
  * Typed entities module - maps registry keys to typed handlers (full record type).
@@ -98,7 +98,7 @@ export interface FunctionsModule {
98
98
  asTool(name: FunctionName, opts: {
99
99
  description: string;
100
100
  parameters?: Record<string, unknown>;
101
- }): import("./dynamic-agents.types.js").Tool;
101
+ }): import("./agents/agents.types.js").Tool;
102
102
  /**
103
103
  * Performs a direct HTTP request to a backend function path and returns the native `Response`.
104
104
  *
@@ -1,4 +1,4 @@
1
1
  export * from "./app.types.js";
2
- export * from "./agents.types.js";
2
+ export * from "./agents/agents.types.js";
3
3
  export * from "./connectors.types.js";
4
4
  export * from "./analytics.types.js";
@@ -1,4 +1,4 @@
1
1
  export * from "./app.types.js";
2
- export * from "./agents.types.js";
2
+ export * from "./agents/agents.types.js";
3
3
  export * from "./connectors.types.js";
4
4
  export * from "./analytics.types.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.32-pr.205.168e407",
3
+ "version": "0.8.32-pr.205.36088fe",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,20 +0,0 @@
1
- import type { DynamicAgentsModuleConfig } from "./dynamic-agents.types.js";
2
- /**
3
- * Resolves the AI Gateway connection from a client config.
4
- * @internal
5
- */
6
- export declare function resolveConnection(config: DynamicAgentsModuleConfig): {
7
- baseURL: string;
8
- apiKey: string;
9
- };
10
- /**
11
- * Creates the gateway transport. Owns the single HTTP call to the OpenAI-compatible
12
- * `/chat/completions` endpoint. Shaped so a streaming `.stream()` method can be added
13
- * later without changing callers of `.complete()`.
14
- * @internal
15
- */
16
- export declare function createGatewayTransport(config: DynamicAgentsModuleConfig): {
17
- complete(body: Record<string, unknown>, opts?: {
18
- signal?: AbortSignal;
19
- }): Promise<any>;
20
- };
@@ -1,32 +0,0 @@
1
- import type { AgentConfig, ChatMessage, DynamicAgentsModule, DynamicAgentsModuleConfig, Tool } from "./dynamic-agents.types.js";
2
- /**
3
- * Defines a tool an agent can call.
4
- *
5
- * @example
6
- * ```typescript
7
- * const getWeather = tool({
8
- * description: "Get the current weather for a city.",
9
- * parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
10
- * execute: async ({ city }) => ({ city, tempC: 28 }),
11
- * });
12
- * ```
13
- */
14
- export declare function tool(t: Tool): Tool;
15
- /**
16
- * Maps a `{ name: Tool }` map to the OpenAI `tools[]` array. Returns `undefined`
17
- * when empty so the param is omitted from the request body.
18
- * @internal
19
- */
20
- export declare function serializeTools(tools?: Record<string, Tool>): any[] | undefined;
21
- /**
22
- * Builds the gateway request body from config + messages using an explicit whitelist.
23
- * Rejected params (max_tokens, stop, top_p, penalties, logit_bias, seed, n) can never
24
- * appear because only the supported keys are ever written.
25
- * @internal
26
- */
27
- export declare function buildRequestBody(config: AgentConfig, messages: ChatMessage[]): Record<string, unknown>;
28
- /**
29
- * Creates the `base44.dynamicAgents` module.
30
- * @internal
31
- */
32
- export declare function createDynamicAgentsModule(config: DynamicAgentsModuleConfig): DynamicAgentsModule;
@@ -1,176 +0,0 @@
1
- import { createGatewayTransport } from "./ai-gateway.js";
2
- /**
3
- * Defines a tool an agent can call.
4
- *
5
- * @example
6
- * ```typescript
7
- * const getWeather = tool({
8
- * description: "Get the current weather for a city.",
9
- * parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
10
- * execute: async ({ city }) => ({ city, tempC: 28 }),
11
- * });
12
- * ```
13
- */
14
- export function tool(t) {
15
- return t;
16
- }
17
- /**
18
- * Maps a `{ name: Tool }` map to the OpenAI `tools[]` array. Returns `undefined`
19
- * when empty so the param is omitted from the request body.
20
- * @internal
21
- */
22
- export function serializeTools(tools) {
23
- if (!tools)
24
- return undefined;
25
- const entries = Object.entries(tools);
26
- if (entries.length === 0)
27
- return undefined;
28
- return entries.map(([name, t]) => ({
29
- type: "function",
30
- function: { name, description: t.description, parameters: t.parameters },
31
- }));
32
- }
33
- /**
34
- * Builds the gateway request body from config + messages using an explicit whitelist.
35
- * Rejected params (max_tokens, stop, top_p, penalties, logit_bias, seed, n) can never
36
- * appear because only the supported keys are ever written.
37
- * @internal
38
- */
39
- export function buildRequestBody(config, messages) {
40
- const body = {
41
- model: config.model,
42
- messages,
43
- };
44
- if (config.temperature !== undefined)
45
- body.temperature = config.temperature;
46
- if (config.toolChoice !== undefined)
47
- body.tool_choice = config.toolChoice;
48
- if (config.responseFormat !== undefined) {
49
- body.response_format = {
50
- type: "json_schema",
51
- json_schema: { name: "response", schema: config.responseFormat, strict: true },
52
- };
53
- }
54
- const tools = serializeTools(config.tools);
55
- if (tools)
56
- body.tools = tools;
57
- return body;
58
- }
59
- const DEFAULT_MAX_STEPS = 8;
60
- function inputToMessages(input) {
61
- if ("messages" in input)
62
- return input.messages;
63
- return [{ role: "user", content: input.prompt }];
64
- }
65
- function stringifyResult(out) {
66
- return typeof out === "string" ? out : JSON.stringify(out);
67
- }
68
- function mapUsage(raw) {
69
- const u = (raw && raw.usage) || {};
70
- return {
71
- promptTokens: u.prompt_tokens,
72
- completionTokens: u.completion_tokens,
73
- totalTokens: u.total_tokens,
74
- credits: u.base44_credits,
75
- };
76
- }
77
- /**
78
- * Creates the `base44.dynamicAgents` module.
79
- * @internal
80
- */
81
- export function createDynamicAgentsModule(config) {
82
- const transport = createGatewayTransport(config);
83
- function create(agentConfig) {
84
- var _a;
85
- const maxSteps = (_a = agentConfig.maxSteps) !== null && _a !== void 0 ? _a : DEFAULT_MAX_STEPS;
86
- const tools = agentConfig.tools;
87
- const agent = {
88
- async run(input, options = {}) {
89
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
90
- const messages = [];
91
- if (agentConfig.system)
92
- messages.push({ role: "system", content: agentConfig.system });
93
- messages.push(...inputToMessages(input));
94
- const steps = [];
95
- let raw = null;
96
- for (let i = 0; i < maxSteps; i++) {
97
- const body = buildRequestBody(agentConfig, messages);
98
- raw = await transport.complete(body, { signal: options.abortSignal });
99
- const choice = (_a = raw === null || raw === void 0 ? void 0 : raw.choices) === null || _a === void 0 ? void 0 : _a[0];
100
- const message = (_b = choice === null || choice === void 0 ? void 0 : choice.message) !== null && _b !== void 0 ? _b : { role: "assistant", content: "" };
101
- messages.push(message);
102
- const toolCalls = message.tool_calls;
103
- if (!toolCalls || toolCalls.length === 0) {
104
- return {
105
- text: (_c = message.content) !== null && _c !== void 0 ? _c : "",
106
- steps,
107
- finishReason: (_d = choice === null || choice === void 0 ? void 0 : choice.finish_reason) !== null && _d !== void 0 ? _d : "stop",
108
- usage: mapUsage(raw),
109
- raw,
110
- };
111
- }
112
- const toolResults = [];
113
- for (const call of toolCalls) {
114
- const name = (_e = call.function) === null || _e === void 0 ? void 0 : _e.name;
115
- const t = tools === null || tools === void 0 ? void 0 : tools[name];
116
- let args = {};
117
- try {
118
- args = JSON.parse(((_f = call.function) === null || _f === void 0 ? void 0 : _f.arguments) || "{}");
119
- }
120
- catch (_l) {
121
- args = {};
122
- }
123
- let resultContent;
124
- if (!t) {
125
- resultContent = `Error: tool "${name}" is not available.`;
126
- }
127
- else {
128
- try {
129
- resultContent = stringifyResult(await t.execute(args));
130
- }
131
- catch (e) {
132
- resultContent = `Error: ${(_g = e === null || e === void 0 ? void 0 : e.message) !== null && _g !== void 0 ? _g : String(e)}`;
133
- }
134
- }
135
- messages.push({ role: "tool", tool_call_id: call.id, content: resultContent });
136
- toolResults.push({ toolCallId: call.id, toolName: name, args, result: resultContent });
137
- }
138
- steps.push({ toolResults });
139
- }
140
- // maxSteps exhausted
141
- const lastMessage = (_j = (_h = raw === null || raw === void 0 ? void 0 : raw.choices) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.message;
142
- return {
143
- text: (_k = lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.content) !== null && _k !== void 0 ? _k : "",
144
- steps,
145
- finishReason: "max_steps",
146
- usage: mapUsage(raw),
147
- raw,
148
- };
149
- },
150
- asTool(toolOpts) {
151
- return {
152
- description: toolOpts.description,
153
- parameters: {
154
- type: "object",
155
- properties: { prompt: { type: "string", description: "What to ask the sub-agent." } },
156
- required: ["prompt"],
157
- },
158
- execute: async (args) => {
159
- const result = await agent.run({ prompt: args.prompt });
160
- return result.text;
161
- },
162
- };
163
- },
164
- };
165
- return agent;
166
- }
167
- function run(runConfig, options) {
168
- if ("messages" in runConfig) {
169
- const { messages, ...agentConfig } = runConfig;
170
- return create(agentConfig).run({ messages }, options);
171
- }
172
- const { prompt, ...agentConfig } = runConfig;
173
- return create(agentConfig).run({ prompt }, options);
174
- }
175
- return { create, run };
176
- }