@blazingagents/sdk 0.15.0 → 0.16.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.
@@ -0,0 +1,15 @@
1
+ import { type UIMessage } from "ai";
2
+ import type { BlazingAgents } from "./client.ts";
3
+ interface ApprovalTarget {
4
+ abortSignal?: AbortSignal;
5
+ agentId: string;
6
+ sessionId: string;
7
+ }
8
+ /**
9
+ * Records each approval response in the assistant message's last step and
10
+ * returns the continuation they decide, or `undefined` when there are none.
11
+ */
12
+ export declare function decideApprovalResponses(client: Pick<BlazingAgents, "sessions">, { message, ...target }: ApprovalTarget & {
13
+ message: UIMessage;
14
+ }): Promise<string | undefined>;
15
+ export {};
@@ -0,0 +1,20 @@
1
+ import { isToolUIPart } from "ai";
2
+ /**
3
+ * Records each approval response in the assistant message's last step and
4
+ * returns the continuation they decide, or `undefined` when there are none.
5
+ */
6
+ export async function decideApprovalResponses(client, { message, ...target }) {
7
+ const lastStep = message.parts.findLastIndex((part) => part.type === "step-start");
8
+ let continuationId;
9
+ for (const part of message.parts.slice(lastStep + 1)) {
10
+ if (isToolUIPart(part) && part.state === "approval-responded") {
11
+ ({ continuationId } = await client.sessions.decideToolApproval({
12
+ ...target,
13
+ approvalId: part.approval.id,
14
+ approved: part.approval.approved,
15
+ reason: part.approval.reason,
16
+ }));
17
+ }
18
+ }
19
+ return continuationId;
20
+ }
@@ -1,4 +1,4 @@
1
- import { DefaultChatTransport, } from "ai";
1
+ import { DefaultChatTransport, lastAssistantMessageIsCompleteWithApprovalResponses, } from "ai";
2
2
  import { sessionIdSchema } from "./contracts/ids.js";
3
3
  /**
4
4
  * Adapts AI SDK chat requests to the Blazing Agents backend-relay shape and
@@ -31,7 +31,14 @@ export class BlazingAgentsChatTransport {
31
31
  return response;
32
32
  },
33
33
  prepareSendMessagesRequest: ({ body, messageId, messages, trigger }) => {
34
- const message = messages.findLast((candidate) => candidate.role === "user");
34
+ const approvals = messages.at(-1)?.role === "assistant" &&
35
+ lastAssistantMessageIsCompleteWithApprovalResponses({ messages });
36
+ if (approvals && this.#sessionId === undefined) {
37
+ throw new Error("Tool approval requires an existing Session.");
38
+ }
39
+ const message = approvals
40
+ ? messages.at(-1)
41
+ : messages.findLast((candidate) => candidate.role === "user");
35
42
  if (!message) {
36
43
  throw new Error("Chat submission requires a user message.");
37
44
  }
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AgentClient, AgentsResource, ArtifactsResource, BlazingAgentsOptions, BlazingAgentsRequestOptions, ChatConnectionsResource, ChatDeliveriesResource, ChatInput, ChatResult, CompletionInput, CompletionResult, McpConnectionsResource, MemoriesResource, MerchantBindingsResource, MerchantConnectionResource, MerchantUsageEventsResource, ObjectInput, ObjectResult, PromptsResource, ProvidersResource, SessionsResource, TasksResource, TenantResource, UsageResource, UserClient, WorkspacesResource } from "./types.ts";
1
+ import type { AgentClient, AgentsResource, ArtifactsResource, BlazingAgentsOptions, BlazingAgentsRequestOptions, ChatConnectionsResource, ChatDeliveriesResource, ChatInput, ChatResult, CompletionInput, CompletionResult, McpConnectionsResource, MemoriesResource, MerchantBindingsResource, MerchantConnectionResource, MerchantUsageEventsResource, ObjectInput, ObjectResult, PromptsResource, ProvidersResource, ResumeChatInput, SessionsResource, TasksResource, TenantResource, UsageResource, UserClient, WorkspacesResource } from "./types.ts";
2
2
  export declare class BlazingAgents {
3
3
  private readonly config;
4
4
  readonly chatConnections: ChatConnectionsResource;
@@ -29,6 +29,11 @@ export declare class BlazingAgents {
29
29
  * session id and a byte-compatible SSE relay for `useChat`.
30
30
  */
31
31
  chat(input: ChatInput): Promise<ChatResult>;
32
+ /**
33
+ * Reattaches function handlers after human tool approval and starts or
34
+ * joins the Session's continuation. Returns the continuation SSE relay.
35
+ */
36
+ resumeChat(input: ResumeChatInput): Promise<ChatResult>;
32
37
  /**
33
38
  * `POST /v1/agents/:agentId/generation` — stateless one-shot text
34
39
  * stream. Returns `textStream` + `await result.text` + `toResponse()`.
package/dist/client.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { chat, completion, objectGeneration } from "./generation.js";
2
+ import { chat, completion, objectGeneration, resumeChat, } from "./generation.js";
3
3
  import { createAgentsResource } from "./resources/agents.js";
4
4
  import { createArtifactsResource } from "./resources/artifacts.js";
5
5
  import { createChatConnectionsResource } from "./resources/chat-connections.js";
@@ -40,6 +40,7 @@ function createUserClient(config) {
40
40
  chat: (input) => chat(config, input),
41
41
  completion: (input) => completion(config, input),
42
42
  object: (input) => objectGeneration(config, input),
43
+ resumeChat: (input) => resumeChat(config, input),
43
44
  withOptions: (options) => createUserClient({ ...config, clientRequestId: options.clientRequestId }),
44
45
  };
45
46
  }
@@ -106,6 +107,13 @@ export class BlazingAgents {
106
107
  chat(input) {
107
108
  return chat(this.config, input);
108
109
  }
110
+ /**
111
+ * Reattaches function handlers after human tool approval and starts or
112
+ * joins the Session's continuation. Returns the continuation SSE relay.
113
+ */
114
+ resumeChat(input) {
115
+ return resumeChat(this.config, input);
116
+ }
109
117
  /**
110
118
  * `POST /v1/agents/:agentId/generation` — stateless one-shot text
111
119
  * stream. Returns `textStream` + `await result.text` + `toResponse()`.
@@ -30,6 +30,7 @@ export declare const apiErrorCodeSchema: z.ZodEnum<{
30
30
  chat_webhook_registration_failed: "chat_webhook_registration_failed";
31
31
  checkout_evidence_mismatch: "checkout_evidence_mismatch";
32
32
  forbidden: "forbidden";
33
+ function_call_conflict: "function_call_conflict";
33
34
  idempotency_conflict: "idempotency_conflict";
34
35
  internal: "internal";
35
36
  invalid_cursor: "invalid_cursor";
@@ -108,6 +109,7 @@ export declare const apiErrorSchema: z.ZodObject<{
108
109
  chat_webhook_registration_failed: "chat_webhook_registration_failed";
109
110
  checkout_evidence_mismatch: "checkout_evidence_mismatch";
110
111
  forbidden: "forbidden";
112
+ function_call_conflict: "function_call_conflict";
111
113
  idempotency_conflict: "idempotency_conflict";
112
114
  internal: "internal";
113
115
  invalid_cursor: "invalid_cursor";
@@ -191,6 +193,7 @@ export declare const apiErrorResponseSchema: z.ZodObject<{
191
193
  chat_webhook_registration_failed: "chat_webhook_registration_failed";
192
194
  checkout_evidence_mismatch: "checkout_evidence_mismatch";
193
195
  forbidden: "forbidden";
196
+ function_call_conflict: "function_call_conflict";
194
197
  idempotency_conflict: "idempotency_conflict";
195
198
  internal: "internal";
196
199
  invalid_cursor: "invalid_cursor";
@@ -65,6 +65,7 @@ export const apiErrorCodeSchema = z.enum([
65
65
  "session_version_mismatch",
66
66
  "tool_approval_continuation_not_found",
67
67
  "tool_approval_decision_conflict",
68
+ "function_call_conflict",
68
69
  "skill_invalid_archive",
69
70
  "skill_invalid_markdown",
70
71
  "skill_limit_reached",
@@ -28,6 +28,37 @@ export declare const toolReferenceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
28
28
  connectionId: z.ZodString;
29
29
  name: z.ZodString;
30
30
  }, z.core.$strict>], "type">;
31
+ /**
32
+ * Identifies the tool behind one execution or approval record. Caller-local
33
+ * functions appear here for display and audit only; approval policies keep
34
+ * `toolReferenceSchema`, so function names never become Agent configuration.
35
+ */
36
+ export declare const toolExecutionReferenceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
37
+ type: z.ZodLiteral<"builtin">;
38
+ name: z.ZodEnum<{
39
+ activate_skill: "activate_skill";
40
+ bash: "bash";
41
+ delete_memory: "delete_memory";
42
+ edit: "edit";
43
+ get_memory: "get_memory";
44
+ glob: "glob";
45
+ grep: "grep";
46
+ publish_artifacts: "publish_artifacts";
47
+ read: "read";
48
+ save_memory: "save_memory";
49
+ search_memories: "search_memories";
50
+ update_memory: "update_memory";
51
+ write: "write";
52
+ write_todos: "write_todos";
53
+ }>;
54
+ }, z.core.$strict>, z.ZodObject<{
55
+ type: z.ZodLiteral<"mcp">;
56
+ connectionId: z.ZodString;
57
+ name: z.ZodString;
58
+ }, z.core.$strict>, z.ZodObject<{
59
+ type: z.ZodLiteral<"function">;
60
+ name: z.ZodString;
61
+ }, z.core.$strict>], "type">;
31
62
  export declare const approvalPolicySchema: z.ZodObject<{
32
63
  default: z.ZodEnum<{
33
64
  auto: "auto";
@@ -69,4 +100,5 @@ export declare const approvalPolicySchema: z.ZodObject<{
69
100
  }, z.core.$strict>;
70
101
  export type ApprovalPolicy = z.infer<typeof approvalPolicySchema>;
71
102
  export type ToolReference = z.infer<typeof toolReferenceSchema>;
103
+ export type ToolExecutionReference = z.infer<typeof toolExecutionReferenceSchema>;
72
104
  export type ApprovalDecision = z.infer<typeof approvalDecisionSchema>;
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { mcpConnectionIdSchema } from "../ids.js";
3
- import { AGENT_TOOL_CATALOG } from "./agent-tools.js";
3
+ import { AGENT_TOOL_CATALOG, chatFunctionNameSchema } from "./agent-tools.js";
4
4
  export const approvalDecisionSchema = z.enum([
5
5
  "full",
6
6
  "deny",
@@ -25,6 +25,17 @@ export const toolReferenceSchema = z.discriminatedUnion("type", [
25
25
  })
26
26
  .strict(),
27
27
  ]);
28
+ /**
29
+ * Identifies the tool behind one execution or approval record. Caller-local
30
+ * functions appear here for display and audit only; approval policies keep
31
+ * `toolReferenceSchema`, so function names never become Agent configuration.
32
+ */
33
+ export const toolExecutionReferenceSchema = z.discriminatedUnion("type", [
34
+ ...toolReferenceSchema.options,
35
+ z
36
+ .object({ type: z.literal("function"), name: chatFunctionNameSchema })
37
+ .strict(),
38
+ ]);
28
39
  export const approvalPolicySchema = z
29
40
  .object({
30
41
  default: approvalDecisionSchema,
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  /** Tool groups an Agent can attach. File operations use its durable Workspace. */
2
3
  export declare const agentToolGroupIds: readonly ["workspace", "write_todos", "memory"];
3
4
  export type AgentToolGroupId = (typeof agentToolGroupIds)[number];
@@ -24,3 +25,8 @@ export declare const AGENT_TOOL_CATALOG: readonly [{
24
25
  readonly tools: readonly ["save_memory", "get_memory", "search_memories", "update_memory", "delete_memory"];
25
26
  }];
26
27
  export declare function expandToolGroups(ids: Iterable<string>): Set<string>;
28
+ /**
29
+ * A model-facing tool name. Built-in tool names and the `mcp__` prefix used
30
+ * for MCP tools are reserved so a caller function never shadows them.
31
+ */
32
+ export declare const chatFunctionNameSchema: z.ZodString;
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  /** Tool groups an Agent can attach. File operations use its durable Workspace. */
2
3
  export const agentToolGroupIds = [
3
4
  "workspace",
@@ -50,3 +51,15 @@ export function expandToolGroups(ids) {
50
51
  }
51
52
  return result;
52
53
  }
54
+ const RESERVED_CHAT_FUNCTION_NAMES = new Set([
55
+ ...AGENT_TOOL_CATALOG.flatMap((group) => group.tools),
56
+ "activate_skill",
57
+ ]);
58
+ /**
59
+ * A model-facing tool name. Built-in tool names and the `mcp__` prefix used
60
+ * for MCP tools are reserved so a caller function never shadows them.
61
+ */
62
+ export const chatFunctionNameSchema = z
63
+ .string()
64
+ .regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/)
65
+ .refine((name) => !(RESERVED_CHAT_FUNCTION_NAMES.has(name) || name.startsWith("mcp__")), { message: "Function name is reserved for a built-in or MCP tool." });
@@ -97,6 +97,75 @@ type ExclusivePromptInput<Literal extends object> = (Literal & {
97
97
  promptId: string;
98
98
  variables?: z.infer<typeof promptVariablesSchema>;
99
99
  });
100
+ /**
101
+ * The JSON Schema accepted by structured generation. Zod's JSON Schema
102
+ * compiler (`z.fromJSONSchema`) is the single authority for the supported
103
+ * feature set: anything it can convert is accepted, anything it cannot
104
+ * (unresolvable references, unsupported keywords, …) is rejected at this
105
+ * untrusted boundary. The only product restriction on top is the documented
106
+ * "at least a schema root" rule, which keeps the empty match-anything schema
107
+ * out of object mode. Composition roots are needed for schemas derived from
108
+ * unions (for example, Pydantic's `int | None` TypeAdapter schema), and local
109
+ * `$ref` roots are needed for recursive Pydantic models.
110
+ */
111
+ export declare const jsonSchemaShapeSchema: z.ZodCustom<z.core.JSONSchema.JSONSchema, z.core.JSONSchema.JSONSchema>;
112
+ export declare const MAX_CHAT_FUNCTIONS = 32;
113
+ export declare const MAX_CHAT_FUNCTION_DEFINITIONS_BYTES: number;
114
+ export declare const MAX_CHAT_FUNCTION_PAYLOAD_BYTES: number;
115
+ export declare const jsonByteLength: (value: unknown) => number;
116
+ /** One caller-local function as sent to Blazing Agents: description and JSON Schema only. */
117
+ export declare const chatFunctionDefinitionSchema: z.ZodObject<{
118
+ description: z.ZodString;
119
+ inputSchema: z.ZodCustom<z.core.JSONSchema.JSONSchema, z.core.JSONSchema.JSONSchema>;
120
+ }, z.core.$strict>;
121
+ export declare const chatFunctionDefinitionsSchema: z.ZodRecord<z.ZodString, z.ZodObject<{
122
+ description: z.ZodString;
123
+ inputSchema: z.ZodCustom<z.core.JSONSchema.JSONSchema, z.core.JSONSchema.JSONSchema>;
124
+ }, z.core.$strict>>;
125
+ /**
126
+ * Transient UI data part that authorizes one claim attempt for a function
127
+ * call. The SDK consumes it and never forwards it to the browser.
128
+ */
129
+ export declare const chatFunctionCallEventSchema: z.ZodObject<{
130
+ type: z.ZodLiteral<"data-ba-function-call">;
131
+ data: z.ZodObject<{
132
+ id: z.ZodString;
133
+ name: z.ZodString;
134
+ input: z.ZodJSONSchema;
135
+ deadlineAt: z.ZodISODateTime;
136
+ }, z.core.$strip>;
137
+ transient: z.ZodLiteral<true>;
138
+ }, z.core.$strip>;
139
+ export declare const chatFunctionOutcomeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
140
+ kind: z.ZodLiteral<"output">;
141
+ value: z.ZodJSONSchema;
142
+ }, z.core.$strict>, z.ZodObject<{
143
+ kind: z.ZodLiteral<"error">;
144
+ message: z.ZodString;
145
+ }, z.core.$strict>], "kind">;
146
+ /** `POST .../function-calls/{functionCallId}/claim` body. */
147
+ export declare const claimChatFunctionBodySchema: z.ZodObject<{
148
+ claimRequestId: z.ZodUUID;
149
+ }, z.core.$strict>;
150
+ export declare const claimChatFunctionResponseSchema: z.ZodObject<{
151
+ claimed: z.ZodLiteral<true>;
152
+ }, z.core.$strip>;
153
+ /** `POST .../function-calls/{functionCallId}/result` body. */
154
+ export declare const resolveChatFunctionBodySchema: z.ZodObject<{
155
+ claimRequestId: z.ZodUUID;
156
+ outcome: z.ZodDiscriminatedUnion<[z.ZodObject<{
157
+ kind: z.ZodLiteral<"output">;
158
+ value: z.ZodJSONSchema;
159
+ }, z.core.$strict>, z.ZodObject<{
160
+ kind: z.ZodLiteral<"error">;
161
+ message: z.ZodString;
162
+ }, z.core.$strict>], "kind">;
163
+ }, z.core.$strict>;
164
+ export declare const resolveChatFunctionResponseSchema: z.ZodObject<{
165
+ accepted: z.ZodLiteral<true>;
166
+ }, z.core.$strip>;
167
+ /** `POST .../tool-approval-continuations/{continuationId}/resume` body. */
168
+ export declare const resumeToolApprovalContinuationBodySchema: z.ZodObject<{}, z.core.$strict>;
100
169
  /**
101
170
  * `POST /v1/agents/{agentId}/sessions` (create) and
102
171
  * `POST /v1/agents/{agentId}/sessions/{sessionId}` (resume) request body.
@@ -117,6 +186,10 @@ export declare const chatRequestBodySchema: z.ZodObject<{
117
186
  version: z.ZodOptional<z.ZodNumber>;
118
187
  userId: z.ZodDefault<z.ZodString>;
119
188
  metadata: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
189
+ functions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
190
+ description: z.ZodString;
191
+ inputSchema: z.ZodCustom<z.core.JSONSchema.JSONSchema, z.core.JSONSchema.JSONSchema>;
192
+ }, z.core.$strict>>>;
120
193
  }, z.core.$strict> & z.ZodType<{
121
194
  message?: unknown;
122
195
  promptId?: string | undefined;
@@ -126,6 +199,10 @@ export declare const chatRequestBodySchema: z.ZodObject<{
126
199
  version?: number | undefined;
127
200
  userId: string;
128
201
  metadata: Record<string, unknown>;
202
+ functions?: Record<string, {
203
+ description: string;
204
+ inputSchema: z.core.JSONSchema.JSONSchema;
205
+ }> | undefined;
129
206
  } & ExclusivePromptInput<{
130
207
  message: null | NonNullable<unknown>;
131
208
  }>, {
@@ -137,6 +214,10 @@ export declare const chatRequestBodySchema: z.ZodObject<{
137
214
  version?: number | undefined;
138
215
  userId?: string | undefined;
139
216
  metadata?: Record<string, unknown> | undefined;
217
+ functions?: Record<string, {
218
+ description: string;
219
+ inputSchema: z.core.JSONSchema.JSONSchema;
220
+ }> | undefined;
140
221
  }, z.core.$ZodTypeInternals<{
141
222
  message?: unknown;
142
223
  promptId?: string | undefined;
@@ -146,6 +227,10 @@ export declare const chatRequestBodySchema: z.ZodObject<{
146
227
  version?: number | undefined;
147
228
  userId: string;
148
229
  metadata: Record<string, unknown>;
230
+ functions?: Record<string, {
231
+ description: string;
232
+ inputSchema: z.core.JSONSchema.JSONSchema;
233
+ }> | undefined;
149
234
  } & ExclusivePromptInput<{
150
235
  message: null | NonNullable<unknown>;
151
236
  }>, {
@@ -157,19 +242,11 @@ export declare const chatRequestBodySchema: z.ZodObject<{
157
242
  version?: number | undefined;
158
243
  userId?: string | undefined;
159
244
  metadata?: Record<string, unknown> | undefined;
245
+ functions?: Record<string, {
246
+ description: string;
247
+ inputSchema: z.core.JSONSchema.JSONSchema;
248
+ }> | undefined;
160
249
  }>>;
161
- /**
162
- * The JSON Schema accepted by structured generation. Zod's JSON Schema
163
- * compiler (`z.fromJSONSchema`) is the single authority for the supported
164
- * feature set: anything it can convert is accepted, anything it cannot
165
- * (unresolvable references, unsupported keywords, …) is rejected at this
166
- * untrusted boundary. The only product restriction on top is the documented
167
- * "at least a schema root" rule, which keeps the empty match-anything schema
168
- * out of object mode. Composition roots are needed for schemas derived from
169
- * unions (for example, Pydantic's `int | None` TypeAdapter schema), and local
170
- * `$ref` roots are needed for recursive Pydantic models.
171
- */
172
- export declare const jsonSchemaShapeSchema: z.ZodCustom<z.core.JSONSchema.JSONSchema, z.core.JSONSchema.JSONSchema>;
173
250
  /**
174
251
  * `POST /v1/agents/{agentId}/generation` — the single stateless generation
175
252
  * boundary. Output selection is explicit on the wire while prompt selection
@@ -264,3 +341,9 @@ export type ChatRequestBody = z.infer<typeof chatRequestBodySchema>;
264
341
  export type GenerationRequestBody = z.infer<typeof generationRequestBodySchema>;
265
342
  export type ChatStreamErrorChunk = z.infer<typeof chatStreamErrorChunkSchema>;
266
343
  export type PromptVariables = z.infer<typeof promptVariablesSchema>;
344
+ export type ChatFunctionDefinition = z.infer<typeof chatFunctionDefinitionSchema>;
345
+ export type ChatFunctionDefinitions = z.infer<typeof chatFunctionDefinitionsSchema>;
346
+ export type ChatFunctionCallEvent = z.infer<typeof chatFunctionCallEventSchema>;
347
+ export type ChatFunctionOutcome = z.infer<typeof chatFunctionOutcomeSchema>;
348
+ export type ClaimChatFunctionBody = z.infer<typeof claimChatFunctionBodySchema>;
349
+ export type ResolveChatFunctionBody = z.infer<typeof resolveChatFunctionBodySchema>;
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
- import { agentIdSchema, promptIdSchema, sessionIdSchema, tenantIdSchema, turnIdSchema, } from "../ids.js";
2
+ import { agentIdSchema, functionCallIdSchema, promptIdSchema, sessionIdSchema, tenantIdSchema, turnIdSchema, } from "../ids.js";
3
+ import { chatFunctionNameSchema } from "./agent-tools.js";
3
4
  import { agentModelIdSchema, agentVersionNumberSchema } from "./agents.js";
4
5
  import { metadataSchema, userIdSchema } from "./attribution.js";
5
6
  export const chatModeSchema = z.enum(["create", "resume"]);
@@ -60,41 +61,6 @@ export const blazingAgentsChatMessageMetadataSchema = z
60
61
  * against the template (missing or unknown variable → 400 invalid_request).
61
62
  */
62
63
  export const promptVariablesSchema = z.record(z.string(), z.string());
63
- /**
64
- * `POST /v1/agents/{agentId}/sessions` (create) and
65
- * `POST /v1/agents/{agentId}/sessions/{sessionId}` (resume) request body.
66
- * The URL selects the mode; on create the platform mints the `ss_` id and
67
- * returns it in `Location`. Exactly one of `message` or `promptId` is
68
- * required, and `variables` requires `promptId`. Regenerate is resume-only,
69
- * enforced by the route layer rather than this schema.
70
- */
71
- export const chatRequestBodySchema = z
72
- .object({
73
- /**
74
- * AI SDK owns the runtime UIMessage schema. Core keeps this wire field
75
- * unknown; the HTTP boundary validates it with `safeValidateUIMessages`
76
- * before treating it as a UIMessage.
77
- */
78
- message: z.unknown().optional(),
79
- promptId: promptIdSchema.optional(),
80
- variables: promptVariablesSchema.optional(),
81
- trigger: chatTriggerSchema.default("submit-message"),
82
- messageId: z.string().min(1).optional(),
83
- version: agentVersionNumberSchema.optional(),
84
- /**
85
- * End-user attribution (ADR-0001), stamped on the Session at lazy
86
- * materialization and on every usage row this Turn records.
87
- */
88
- userId: userIdSchema.default(""),
89
- metadata: metadataSchema.default({}),
90
- })
91
- .strict()
92
- .refine((body) => body.message === undefined
93
- ? body.promptId !== undefined
94
- : body.promptId === undefined && body.variables === undefined, {
95
- message: "Provide either `message` or `promptId` (+`variables`); they are mutually exclusive, and `variables` is only allowed with `promptId`.",
96
- path: ["message"],
97
- });
98
64
  const JSON_SCHEMA_COMPOSITION_KEYS = ["allOf", "anyOf", "oneOf"];
99
65
  function hasMeaningfulSchemaRoot(value, definitions, seenReferences) {
100
66
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -152,6 +118,109 @@ export const jsonSchemaShapeSchema = z.custom((value) => {
152
118
  return false;
153
119
  }
154
120
  }, { message: "schema contains an unsupported or invalid JSON Schema feature" });
121
+ export const MAX_CHAT_FUNCTIONS = 32;
122
+ export const MAX_CHAT_FUNCTION_DEFINITIONS_BYTES = 64 * 1024;
123
+ export const MAX_CHAT_FUNCTION_PAYLOAD_BYTES = 256 * 1024;
124
+ export const jsonByteLength = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
125
+ /** One caller-local function as sent to Blazing Agents: description and JSON Schema only. */
126
+ export const chatFunctionDefinitionSchema = z
127
+ .object({
128
+ description: z.string().trim().min(1),
129
+ inputSchema: jsonSchemaShapeSchema.refine((schema) => typeof schema === "object" && schema.type === "object", { message: "Function input schema must describe a JSON object." }),
130
+ })
131
+ .strict();
132
+ export const chatFunctionDefinitionsSchema = z
133
+ .record(chatFunctionNameSchema, chatFunctionDefinitionSchema)
134
+ .refine((functions) => Object.keys(functions).length <= MAX_CHAT_FUNCTIONS, {
135
+ message: `At most ${MAX_CHAT_FUNCTIONS} functions are allowed.`,
136
+ })
137
+ .refine((functions) => jsonByteLength(functions) <= MAX_CHAT_FUNCTION_DEFINITIONS_BYTES, {
138
+ message: `Function definitions must not exceed ${MAX_CHAT_FUNCTION_DEFINITIONS_BYTES} bytes.`,
139
+ });
140
+ /**
141
+ * Transient UI data part that authorizes one claim attempt for a function
142
+ * call. The SDK consumes it and never forwards it to the browser.
143
+ */
144
+ export const chatFunctionCallEventSchema = z
145
+ .object({
146
+ type: z.literal("data-ba-function-call"),
147
+ data: z
148
+ .object({
149
+ id: functionCallIdSchema,
150
+ name: chatFunctionNameSchema,
151
+ input: z.json(),
152
+ deadlineAt: z.iso.datetime({ offset: true }),
153
+ })
154
+ .strip(),
155
+ transient: z.literal(true),
156
+ })
157
+ .strip();
158
+ export const chatFunctionOutcomeSchema = z
159
+ .discriminatedUnion("kind", [
160
+ z.object({ kind: z.literal("output"), value: z.json() }).strict(),
161
+ z
162
+ .object({
163
+ kind: z.literal("error"),
164
+ message: z.string().min(1).max(4096),
165
+ })
166
+ .strict(),
167
+ ])
168
+ .refine((outcome) => jsonByteLength(outcome) <= MAX_CHAT_FUNCTION_PAYLOAD_BYTES, {
169
+ message: `Function outcome must not exceed ${MAX_CHAT_FUNCTION_PAYLOAD_BYTES} bytes.`,
170
+ });
171
+ /** `POST .../function-calls/{functionCallId}/claim` body. */
172
+ export const claimChatFunctionBodySchema = z
173
+ .object({ claimRequestId: z.uuid() })
174
+ .strict();
175
+ export const claimChatFunctionResponseSchema = z
176
+ .object({ claimed: z.literal(true) })
177
+ .strip();
178
+ /** `POST .../function-calls/{functionCallId}/result` body. */
179
+ export const resolveChatFunctionBodySchema = z
180
+ .object({ claimRequestId: z.uuid(), outcome: chatFunctionOutcomeSchema })
181
+ .strict();
182
+ export const resolveChatFunctionResponseSchema = z
183
+ .object({ accepted: z.literal(true) })
184
+ .strip();
185
+ /** `POST .../tool-approval-continuations/{continuationId}/resume` body. */
186
+ export const resumeToolApprovalContinuationBodySchema = z.object({}).strict();
187
+ /**
188
+ * `POST /v1/agents/{agentId}/sessions` (create) and
189
+ * `POST /v1/agents/{agentId}/sessions/{sessionId}` (resume) request body.
190
+ * The URL selects the mode; on create the platform mints the `ss_` id and
191
+ * returns it in `Location`. Exactly one of `message` or `promptId` is
192
+ * required, and `variables` requires `promptId`. Regenerate is resume-only,
193
+ * enforced by the route layer rather than this schema.
194
+ */
195
+ export const chatRequestBodySchema = z
196
+ .object({
197
+ /**
198
+ * AI SDK owns the runtime UIMessage schema. Core keeps this wire field
199
+ * unknown; the HTTP boundary validates it with `safeValidateUIMessages`
200
+ * before treating it as a UIMessage.
201
+ */
202
+ message: z.unknown().optional(),
203
+ promptId: promptIdSchema.optional(),
204
+ variables: promptVariablesSchema.optional(),
205
+ trigger: chatTriggerSchema.default("submit-message"),
206
+ messageId: z.string().min(1).optional(),
207
+ version: agentVersionNumberSchema.optional(),
208
+ /**
209
+ * End-user attribution (ADR-0001), stamped on the Session at lazy
210
+ * materialization and on every usage row this Turn records.
211
+ */
212
+ userId: userIdSchema.default(""),
213
+ metadata: metadataSchema.default({}),
214
+ /** Caller-local functions for this invocation; handlers stay in the caller's backend. */
215
+ functions: chatFunctionDefinitionsSchema.optional(),
216
+ })
217
+ .strict()
218
+ .refine((body) => body.message === undefined
219
+ ? body.promptId !== undefined
220
+ : body.promptId === undefined && body.variables === undefined, {
221
+ message: "Provide either `message` or `promptId` (+`variables`); they are mutually exclusive, and `variables` is only allowed with `promptId`.",
222
+ path: ["message"],
223
+ });
155
224
  /**
156
225
  * `POST /v1/agents/{agentId}/generation` — the single stateless generation
157
226
  * boundary. Output selection is explicit on the wire while prompt selection
@@ -151,6 +151,9 @@ export declare const toolApprovalStateSchema: z.ZodObject<{
151
151
  type: z.ZodLiteral<"mcp">;
152
152
  connectionId: z.ZodString;
153
153
  name: z.ZodString;
154
+ }, z.core.$strict>, z.ZodObject<{
155
+ type: z.ZodLiteral<"function">;
156
+ name: z.ZodString;
154
157
  }, z.core.$strict>], "type">>>;
155
158
  assistantMessageId: z.ZodOptional<z.ZodString>;
156
159
  createdAt: z.ZodOptional<z.ZodISODateTime>;
@@ -200,6 +203,9 @@ export declare const toolApprovalsResponseSchema: z.ZodObject<{
200
203
  type: z.ZodLiteral<"mcp">;
201
204
  connectionId: z.ZodString;
202
205
  name: z.ZodString;
206
+ }, z.core.$strict>, z.ZodObject<{
207
+ type: z.ZodLiteral<"function">;
208
+ name: z.ZodString;
203
209
  }, z.core.$strict>], "type">>>;
204
210
  assistantMessageId: z.ZodOptional<z.ZodString>;
205
211
  createdAt: z.ZodOptional<z.ZodISODateTime>;
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { paginatedResponseSchema } from "../api.js";
3
3
  import { agentIdSchema, sessionIdSchema } from "../ids.js";
4
4
  import { DEFAULT_SESSION_MESSAGES_LIMIT, MAX_SESSION_MESSAGES_LIMIT, } from "../limitations.js";
5
- import { toolReferenceSchema } from "./agent-approval.js";
5
+ import { toolExecutionReferenceSchema } from "./agent-approval.js";
6
6
  import { agentSchema, agentVersionNumberSchema } from "./agents.js";
7
7
  import { metadataSchema, userIdSchema } from "./attribution.js";
8
8
  /**
@@ -104,7 +104,7 @@ export const toolApprovalContinuationStateSchema = z.enum([
104
104
  ]);
105
105
  export const toolApprovalStateSchema = z
106
106
  .object({
107
- tool: toolReferenceSchema.nullable().optional(),
107
+ tool: toolExecutionReferenceSchema.nullable().optional(),
108
108
  assistantMessageId: z.string().min(1).optional(),
109
109
  createdAt: z.iso.datetime({ offset: true }).optional(),
110
110
  decidedAt: z.iso.datetime({ offset: true }).nullable().optional(),
@@ -46,6 +46,7 @@ export declare const promptIdSchema: z.ZodString;
46
46
  export declare const requestIdSchema: z.ZodString;
47
47
  export declare const checkoutAttemptIdSchema: z.ZodString;
48
48
  export declare const turnIdSchema: z.ZodString;
49
+ export declare const functionCallIdSchema: z.ZodString;
49
50
  export declare const skillIdSchema: z.ZodString;
50
51
  /**
51
52
  * API key token + digest helpers. The digest is sha256 hex (64 chars); the
@@ -72,6 +72,7 @@ export const promptIdSchema = z.string().regex(/^prompt_[0-9A-Za-z]{16}$/);
72
72
  export const requestIdSchema = z.string().regex(/^req_[0-9A-Za-z]{16}$/);
73
73
  export const checkoutAttemptIdSchema = z.string().regex(/^ca_[0-9A-Za-z]{16}$/);
74
74
  export const turnIdSchema = z.string().regex(/^turn_[0-9A-Za-z]{16}$/);
75
+ export const functionCallIdSchema = z.string().regex(/^fc_[0-9A-Za-z]{16}$/);
75
76
  export const skillIdSchema = z.string().regex(/^skill_[0-9A-Za-z]{16}$/);
76
77
  /**
77
78
  * API key token + digest helpers. The digest is sha256 hex (64 chars); the
@@ -1,12 +1,13 @@
1
1
  /** Public runtime schemas for the Blazing Agents HTTP API. */
2
2
  export { receivedApiErrorResponseSchema } from "./api.ts";
3
- export type { ApprovalDecision, ApprovalPolicy, ToolReference, } from "./entities/agent-approval.ts";
4
- export { approvalDecisionSchema, approvalPolicySchema, toolReferenceSchema, } from "./entities/agent-approval.ts";
3
+ export type { ApprovalDecision, ApprovalPolicy, ToolExecutionReference, ToolReference, } from "./entities/agent-approval.ts";
4
+ export { approvalDecisionSchema, approvalPolicySchema, toolExecutionReferenceSchema, toolReferenceSchema, } from "./entities/agent-approval.ts";
5
+ export { chatFunctionNameSchema } from "./entities/agent-tools.ts";
5
6
  export { agentResponseSchema, agentSchema, agentStatusSchema, agentsListQuerySchema, agentsResponseSchema, agentVersionSchema, agentVersionsResponseSchema, createAgentBodySchema, updateAgentBodySchema, } from "./entities/agents.ts";
6
7
  export { artifactDownloadUrlResponseSchema, artifactListItemSchema, artifactsListResponseSchema, } from "./entities/artifacts.ts";
7
8
  export { attributionCreateInputSchema, metadataSchema, } from "./entities/attribution.ts";
8
- export type { PromptVariables, UsageSummary } from "./entities/chat.ts";
9
- export { blazingAgentsChatMessageMetadataSchema, chatModeSchema, chatRequestBodySchema, chatTriggerSchema, generationRequestBodySchema, jsonSchemaShapeSchema, promptVariablesSchema, usageSummarySchema, } from "./entities/chat.ts";
9
+ export type { ChatFunctionCallEvent, ChatFunctionDefinition, ChatFunctionDefinitions, ChatFunctionOutcome, ClaimChatFunctionBody, PromptVariables, ResolveChatFunctionBody, UsageSummary, } from "./entities/chat.ts";
10
+ export { blazingAgentsChatMessageMetadataSchema, chatFunctionCallEventSchema, chatFunctionDefinitionSchema, chatFunctionDefinitionsSchema, chatFunctionOutcomeSchema, chatModeSchema, chatRequestBodySchema, chatTriggerSchema, claimChatFunctionBodySchema, claimChatFunctionResponseSchema, generationRequestBodySchema, jsonSchemaShapeSchema, MAX_CHAT_FUNCTION_DEFINITIONS_BYTES, MAX_CHAT_FUNCTION_PAYLOAD_BYTES, MAX_CHAT_FUNCTIONS, promptVariablesSchema, resolveChatFunctionBodySchema, resolveChatFunctionResponseSchema, resumeToolApprovalContinuationBodySchema, usageSummarySchema, } from "./entities/chat.ts";
10
11
  export { chatConfigurationSchema, chatConnectionSchema, chatConnectionsResponseSchema, chatCredentialsSchema, chatDeliveriesResponseSchema, chatDeliveryListStatusSchema, chatDeliverySchema, chatDeliveryStatusSchema, chatHealthCheckSchema, chatHealthSchema, chatIdentitySchema, createChatConnectionBodySchema, rotateChatConnectionBodySchema, tenantChatDeliverySchema, updateChatConnectionBodySchema, } from "./entities/chat-connections.ts";
11
12
  export { approveMcpOauthAuthorizationBodySchema, createMcpConnectionBodySchema, mcpAttachmentResponseSchema, mcpAttachmentsResponseSchema, mcpConnectionAuthTypeSchema, mcpConnectionOauthConnectResponseSchema, mcpConnectionReconnectResultSchema, mcpConnectionResponseSchema, mcpConnectionStatusSchema, mcpConnectionsResponseSchema, mcpConnectionTestErrorCodeSchema, mcpConnectionTestResponseSchema, mcpOauthAuthorizationLaunchResponseSchema, reconnectMcpConnectionBodySchema, updateMcpAttachmentBodySchema, updateMcpConnectionBodySchema, } from "./entities/mcp-connections.ts";
12
13
  export { createMemoryBodySchema, memoriesListResponseSchema, memoryResponseSchema, memorySchema, updateMemoryBodySchema, } from "./entities/memories.ts";
@@ -21,4 +22,4 @@ export { quotaSchema, subscriptionStatusSchema, tenantDeletionSchema, tenantResp
21
22
  export type { SessionUsageQuery, SessionUsageResponse, UsageBucket, UsageOverviewQuery, UsageOverviewResponse, UsageResponse, UsageTotals, } from "./entities/usage.ts";
22
23
  export { sessionUsageQuerySchema, sessionUsageResponseSchema, usageOverviewQuerySchema, usageOverviewResponseSchema, usageResponseSchema, } from "./entities/usage.ts";
23
24
  export { createWorkspaceBodySchema, updateWorkspaceBodySchema, workspaceSchema, workspacesListResponseSchema, } from "./entities/workspaces.ts";
24
- export { agentIdSchema, apiKeyTokenSchema, isAdminAgentId, promptIdSchema, sessionIdSchema, } from "./ids.ts";
25
+ export { agentIdSchema, apiKeyTokenSchema, functionCallIdSchema, isAdminAgentId, promptIdSchema, sessionIdSchema, } from "./ids.ts";