@blazingagents/sdk 0.30.0 → 0.32.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
@@ -86,6 +86,9 @@ npm run check
86
86
  npm run test:consumer
87
87
  ```
88
88
 
89
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the changelog convention and how
90
+ to release.
91
+
89
92
  ## License
90
93
 
91
94
  [MIT](LICENSE)
@@ -61,9 +61,7 @@ export class BlazingAgentsChatTransport {
61
61
  ...body,
62
62
  message,
63
63
  messageId,
64
- ...(this.#sessionId === undefined
65
- ? { sessionId: undefined }
66
- : { sessionId: this.#sessionId }),
64
+ sessionId: this.#sessionId,
67
65
  trigger,
68
66
  },
69
67
  };
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { chat, completion, continueChat, objectGeneration, } from "./generation.js";
3
- import { createAgentsResource } from "./resources/agents.js";
3
+ import { createAgentsResource, createUserAgentsResource, } from "./resources/agents.js";
4
4
  import { createArtifactsResource } from "./resources/artifacts.js";
5
5
  import { createChatConnectionsResource } from "./resources/chat-connections.js";
6
6
  import { createChatDeliveriesResource } from "./resources/chat-deliveries.js";
@@ -29,7 +29,7 @@ const scopedUserIdSchema = z
29
29
  function createUserClient(config) {
30
30
  const usage = createUsageResource(config);
31
31
  return {
32
- agents: createAgentsResource(config),
32
+ agents: createUserAgentsResource(config),
33
33
  sessions: createSessionsResource(config),
34
34
  prompts: createPromptsResource(config),
35
35
  tasks: createTasksResource(config),
@@ -286,3 +286,54 @@ export declare const chatDeliveriesResponseSchema: z.ZodObject<{
286
286
  nextCursor: z.ZodNullable<z.ZodString>;
287
287
  }, z.core.$strip>;
288
288
  export type ChatDeliveriesResponse = z.infer<typeof chatDeliveriesResponseSchema>;
289
+ export declare const chatDeliveryListSchema: z.ZodObject<{
290
+ data: z.ZodArray<z.ZodObject<{
291
+ id: z.ZodString;
292
+ kind: z.ZodEnum<{
293
+ card: "card";
294
+ reply: "reply";
295
+ }>;
296
+ status: z.ZodEnum<{
297
+ ambiguous: "ambiguous";
298
+ confirmed: "confirmed";
299
+ failed: "failed";
300
+ pending: "pending";
301
+ }>;
302
+ attempt: z.ZodNumber;
303
+ credentialVersion: z.ZodNumber;
304
+ representation: z.ZodString;
305
+ diagnostic: z.ZodNullable<z.ZodString>;
306
+ receipts: z.ZodOptional<z.ZodUnknown>;
307
+ sessionId: z.ZodString;
308
+ messageId: z.ZodNullable<z.ZodString>;
309
+ approvalId: z.ZodNullable<z.ZodString>;
310
+ threadId: z.ZodString;
311
+ createdAt: z.ZodString;
312
+ updatedAt: z.ZodString;
313
+ }, z.core.$strip>>;
314
+ nextCursor: z.ZodNullable<z.ZodString>;
315
+ }, z.core.$strip>;
316
+ export type ChatDeliveryList = z.infer<typeof chatDeliveryListSchema>;
317
+ export declare const repairChatDeliveryBodySchema: z.ZodObject<{
318
+ expectedAttempt: z.ZodNumber;
319
+ previousSenderStopped: z.ZodLiteral<true>;
320
+ acceptDuplicateRisk: z.ZodLiteral<true>;
321
+ }, z.core.$strict>;
322
+ export type RepairChatDeliveryBody = z.input<typeof repairChatDeliveryBodySchema>;
323
+ export declare const chatDeliveryResultSchema: z.ZodObject<{
324
+ id: z.ZodString;
325
+ sessionId: z.ZodString;
326
+ threadId: z.ZodString;
327
+ connectionId: z.ZodString;
328
+ kind: z.ZodEnum<{
329
+ card: "card";
330
+ reply: "reply";
331
+ }>;
332
+ status: z.ZodEnum<{
333
+ ambiguous: "ambiguous";
334
+ confirmed: "confirmed";
335
+ failed: "failed";
336
+ }>;
337
+ attempt: z.ZodNumber;
338
+ }, z.core.$strip>;
339
+ export type ChatDeliveryResult = z.infer<typeof chatDeliveryResultSchema>;
@@ -173,3 +173,27 @@ export const chatDeliveriesResponseSchema = z
173
173
  nextCursor: z.string().nullable(),
174
174
  })
175
175
  .strip();
176
+ export const chatDeliveryListSchema = z
177
+ .object({
178
+ data: z.array(chatDeliverySchema),
179
+ nextCursor: z.string().nullable(),
180
+ })
181
+ .strip();
182
+ export const repairChatDeliveryBodySchema = z
183
+ .object({
184
+ expectedAttempt: z.number().int().min(0).max(99),
185
+ previousSenderStopped: z.literal(true),
186
+ acceptDuplicateRisk: z.literal(true),
187
+ })
188
+ .strict();
189
+ export const chatDeliveryResultSchema = z
190
+ .object({
191
+ id: chatDeliveryIdSchema,
192
+ sessionId: z.string(),
193
+ threadId: z.string(),
194
+ connectionId: chatConnectionIdSchema,
195
+ kind: z.enum(["reply", "card"]),
196
+ status: z.enum(["confirmed", "failed", "ambiguous"]),
197
+ attempt: z.number().int().nonnegative(),
198
+ })
199
+ .strip();
@@ -317,6 +317,8 @@ export type ChatFunctionDefinition = z.infer<typeof chatFunctionDefinitionSchema
317
317
  export type ChatFunctionDefinitions = z.infer<typeof chatFunctionDefinitionsSchema>;
318
318
  export type ChatFunctionCallEvent = z.infer<typeof chatFunctionCallEventSchema>;
319
319
  export type ChatFunctionOutcome = z.infer<typeof chatFunctionOutcomeSchema>;
320
+ export type ChatRequestBody = z.input<typeof chatRequestBodySchema>;
321
+ export type GenerationRequestBody = z.input<typeof generationRequestBodySchema>;
320
322
  export type ClaimChatFunctionBody = z.infer<typeof claimChatFunctionBodySchema>;
321
323
  export type ResolveChatFunctionBody = z.infer<typeof resolveChatFunctionBodySchema>;
322
324
  export {};
@@ -9,7 +9,7 @@ export { artifactDownloadUrlResponseSchema, artifactListItemSchema, artifactsLis
9
9
  export { attributionCreateInputSchema, metadataSchema, } from "./entities/attribution.ts";
10
10
  export type { ChatFunctionCallEvent, ChatFunctionDefinition, ChatFunctionDefinitions, ChatFunctionOutcome, ClaimChatFunctionBody, PromptVariables, ResolveChatFunctionBody, UsageSummary, } from "./entities/chat.ts";
11
11
  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, usageSummarySchema, } from "./entities/chat.ts";
12
- export { chatConfigurationSchema, chatConnectionSchema, chatConnectionsResponseSchema, chatCredentialsSchema, chatDeliveriesResponseSchema, chatDeliveryListStatusSchema, chatDeliverySchema, chatDeliveryStatusSchema, chatHealthCheckSchema, chatHealthSchema, chatIdentitySchema, createChatConnectionBodySchema, rotateChatConnectionBodySchema, tenantChatDeliverySchema, updateChatConnectionBodySchema, } from "./entities/chat-connections.ts";
12
+ export { chatConfigurationSchema, chatConnectionSchema, chatConnectionsResponseSchema, chatCredentialsSchema, chatDeliveriesResponseSchema, chatDeliveryListSchema, chatDeliveryListStatusSchema, chatDeliveryResultSchema, chatDeliverySchema, chatDeliveryStatusSchema, chatHealthCheckSchema, chatHealthSchema, chatIdentitySchema, createChatConnectionBodySchema, repairChatDeliveryBodySchema, rotateChatConnectionBodySchema, tenantChatDeliverySchema, updateChatConnectionBodySchema, } from "./entities/chat-connections.ts";
13
13
  export { approveMcpOauthAuthorizationBodySchema, createMcpConnectionBodySchema, mcpAttachmentResponseSchema, mcpAttachmentsResponseSchema, mcpConnectionAuthTypeSchema, mcpConnectionOauthConnectResponseSchema, mcpConnectionReconnectResultSchema, mcpConnectionResponseSchema, mcpConnectionStatusSchema, mcpConnectionsResponseSchema, mcpConnectionTestErrorCodeSchema, mcpConnectionTestResponseSchema, mcpOauthAuthorizationLaunchResponseSchema, reconnectMcpConnectionBodySchema, updateMcpAttachmentBodySchema, updateMcpConnectionBodySchema, } from "./entities/mcp-connections.ts";
14
14
  export { createMemoryBodySchema, memoriesListResponseSchema, memoryResponseSchema, memorySchema, updateMemoryBodySchema, } from "./entities/memories.ts";
15
15
  export { createMerchantConnectionBodySchema, merchantBindingResponseSchema, merchantBindingsResponseSchema, merchantConnectionResponseSchema, merchantConnectionSchema, merchantConnectionStatusSchema, merchantCustomerBindingSchema, merchantEnvironmentSchema, merchantGuardSchema, merchantProviderSchema, merchantUsageEventNextAction, merchantUsageEventNextActionSchema, merchantUsageEventSchema, merchantUsageEventStatusSchema, merchantUsageEventsResponseSchema, merchantUsageSummaryQuerySchema, merchantUsageSummaryResponseSchema, merchantUsageSummarySchema, merchantWorkflowIssueSchema, updateMerchantConnectionBodySchema, upsertMerchantBindingBodySchema, } from "./entities/merchant.ts";
@@ -7,7 +7,7 @@ export { agentConfigSchema, agentResponseSchema, agentStatusSchema, agentsListQu
7
7
  export { artifactDownloadUrlResponseSchema, artifactListItemSchema, artifactsListResponseSchema, } from "./entities/artifacts.js";
8
8
  export { attributionCreateInputSchema, metadataSchema, } from "./entities/attribution.js";
9
9
  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, usageSummarySchema, } from "./entities/chat.js";
10
- export { chatConfigurationSchema, chatConnectionSchema, chatConnectionsResponseSchema, chatCredentialsSchema, chatDeliveriesResponseSchema, chatDeliveryListStatusSchema, chatDeliverySchema, chatDeliveryStatusSchema, chatHealthCheckSchema, chatHealthSchema, chatIdentitySchema, createChatConnectionBodySchema, rotateChatConnectionBodySchema, tenantChatDeliverySchema, updateChatConnectionBodySchema, } from "./entities/chat-connections.js";
10
+ export { chatConfigurationSchema, chatConnectionSchema, chatConnectionsResponseSchema, chatCredentialsSchema, chatDeliveriesResponseSchema, chatDeliveryListSchema, chatDeliveryListStatusSchema, chatDeliveryResultSchema, chatDeliverySchema, chatDeliveryStatusSchema, chatHealthCheckSchema, chatHealthSchema, chatIdentitySchema, createChatConnectionBodySchema, repairChatDeliveryBodySchema, rotateChatConnectionBodySchema, tenantChatDeliverySchema, updateChatConnectionBodySchema, } from "./entities/chat-connections.js";
11
11
  export { approveMcpOauthAuthorizationBodySchema, createMcpConnectionBodySchema, mcpAttachmentResponseSchema, mcpAttachmentsResponseSchema, mcpConnectionAuthTypeSchema, mcpConnectionOauthConnectResponseSchema, mcpConnectionReconnectResultSchema, mcpConnectionResponseSchema, mcpConnectionStatusSchema, mcpConnectionsResponseSchema, mcpConnectionTestErrorCodeSchema, mcpConnectionTestResponseSchema, mcpOauthAuthorizationLaunchResponseSchema, reconnectMcpConnectionBodySchema, updateMcpAttachmentBodySchema, updateMcpConnectionBodySchema, } from "./entities/mcp-connections.js";
12
12
  export { createMemoryBodySchema, memoriesListResponseSchema, memoryResponseSchema, memorySchema, updateMemoryBodySchema, } from "./entities/memories.js";
13
13
  export { createMerchantConnectionBodySchema, merchantBindingResponseSchema, merchantBindingsResponseSchema, merchantConnectionResponseSchema, merchantConnectionSchema, merchantConnectionStatusSchema, merchantCustomerBindingSchema, merchantEnvironmentSchema, merchantGuardSchema, merchantProviderSchema, merchantUsageEventNextAction, merchantUsageEventNextActionSchema, merchantUsageEventSchema, merchantUsageEventStatusSchema, merchantUsageEventsResponseSchema, merchantUsageSummaryQuerySchema, merchantUsageSummaryResponseSchema, merchantUsageSummarySchema, merchantWorkflowIssueSchema, updateMerchantConnectionBodySchema, upsertMerchantBindingBodySchema, } from "./entities/merchant.js";
@@ -59,38 +59,31 @@ export class BlazingAgentsDirectChatTransport extends ChatStreamTransport {
59
59
  abortSignal: input.abortSignal,
60
60
  };
61
61
  let result;
62
- if (this.#sessionId === undefined) {
63
- const create = {
62
+ if (this.#sessionId !== undefined) {
63
+ result = await client.chat({
64
+ ...common,
65
+ message: lastUserMessage(input.messages),
66
+ sessionId: this.#sessionId,
67
+ trigger: input.trigger,
68
+ });
69
+ }
70
+ else if (this.#options.promptId === undefined) {
71
+ result = await client.chat({
64
72
  ...common,
65
73
  trigger: "submit-message",
66
74
  userId: this.#options.userId,
67
75
  metadata: this.#options.metadata,
68
- };
69
- if (this.#options.promptId === undefined) {
70
- const message = input.messages.findLast((item) => item.role === "user");
71
- if (!message) {
72
- throw new Error("Chat submission requires a user message.");
73
- }
74
- result = await client.chat({ ...create, message });
75
- }
76
- else {
77
- result = await client.chat({
78
- ...create,
79
- promptId: this.#options.promptId,
80
- variables: this.#options.variables,
81
- });
82
- }
76
+ message: lastUserMessage(input.messages),
77
+ });
83
78
  }
84
79
  else {
85
- const message = input.messages.findLast((item) => item.role === "user");
86
- if (!message) {
87
- throw new Error("Chat submission requires a user message.");
88
- }
89
80
  result = await client.chat({
90
81
  ...common,
91
- message,
92
- sessionId: this.#sessionId,
93
- trigger: input.trigger,
82
+ trigger: "submit-message",
83
+ userId: this.#options.userId,
84
+ metadata: this.#options.metadata,
85
+ promptId: this.#options.promptId,
86
+ variables: this.#options.variables,
94
87
  });
95
88
  }
96
89
  return this.#processChatResult(result);
@@ -107,7 +100,10 @@ export class BlazingAgentsDirectChatTransport extends ChatStreamTransport {
107
100
  this.#sessionId = sessionId;
108
101
  await this.#options.onSessionId?.(sessionId);
109
102
  }
110
- await this.#reportTurnId(result);
103
+ const turnId = await result.turnId.catch(() => undefined);
104
+ if (turnId !== undefined) {
105
+ await this.#options.onTurnId?.(turnId);
106
+ }
111
107
  }
112
108
  catch (error) {
113
109
  await stream.cancel(error).catch(() => undefined);
@@ -143,21 +139,13 @@ export class BlazingAgentsDirectChatTransport extends ChatStreamTransport {
143
139
  decisions,
144
140
  functions: this.#options.functions ?? {},
145
141
  });
146
- const stream = continuation.toStream();
147
- try {
148
- await this.#reportTurnId(continuation);
149
- }
150
- catch (error) {
151
- await stream.cancel(error).catch(() => undefined);
152
- throw error;
153
- }
154
- return this.processResponseStream(stream);
142
+ return this.#processChatResult(continuation);
155
143
  }
156
- /** Reports the Turn ID when the response names one. */
157
- async #reportTurnId(result) {
158
- const turnId = await result.turnId.catch(() => undefined);
159
- if (turnId !== undefined) {
160
- await this.#options.onTurnId?.(turnId);
161
- }
144
+ }
145
+ function lastUserMessage(messages) {
146
+ const message = messages.findLast((item) => item.role === "user");
147
+ if (!message) {
148
+ throw new Error("Chat submission requires a user message.");
162
149
  }
150
+ return message;
163
151
  }
package/dist/errors.js CHANGED
@@ -18,7 +18,6 @@ export class BlazingAgentsError extends Error {
18
18
  responseBody;
19
19
  responseBodyTruncated;
20
20
  status;
21
- // Stryker disable BooleanLiteral: cross-realm identity depends on marker presence, not its value.
22
21
  /**
23
22
  * Marker property used by `isInstance` for cross-realm `instanceof`
24
23
  * checks — the symbol is checked via `in`, not direct property access,
@@ -26,7 +25,6 @@ export class BlazingAgentsError extends Error {
26
25
  * biome-ignore lint/correctness/noUnusedPrivateClassMembers: marker pattern
27
26
  */
28
27
  [BLAZING_AGENTS_ERROR_SYMBOL] = true;
29
- // Stryker restore BooleanLiteral
30
28
  /**
31
29
  * Creates an SDK error with its code, diagnostics, and optional cause.
32
30
  * @param options - Configuration for this operation.
package/dist/functions.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { chatFunctionCallEventSchema, chatFunctionDefinitionsSchema, chatFunctionOutcomeSchema, claimChatFunctionResponseSchema, resolveChatFunctionResponseSchema, } from "./contracts/entities/chat.js";
3
3
  import { BlazingAgentsError } from "./errors.js";
4
- import { requestJson } from "./http.js";
4
+ import { apiPath, requestJson } from "./http.js";
5
5
  /**
6
6
  * Declares a caller-local function whose handler input is inferred from its Zod schema.
7
7
  * @param definition - Description, input schema, and local handler.
@@ -313,7 +313,7 @@ export function dispatchChatFunctions(config, target, body) {
313
313
  * Claims a function call, runs its handler, and posts the result within its retry budget.
314
314
  */
315
315
  const runCall = async (call) => {
316
- const path = `/v1/agents/${target.agentId}/sessions/${target.sessionId}/function-calls/${call.id}`;
316
+ const path = apiPath `/v1/agents/${target.agentId}/sessions/${target.sessionId}/function-calls/${call.id}`;
317
317
  const claimRequestId = crypto.randomUUID();
318
318
  const deadline = Date.parse(call.deadlineAt);
319
319
  const claim = await postWithRetry(config, `${path}/claim`, { claimRequestId }, claimChatFunctionResponseSchema, deadline, handlers.signal);
@@ -24,9 +24,8 @@ export declare function withFilteredBody(response: Response, filter: (body: Read
24
24
  * Creates single-owner SSE response and byte-stream accessors.
25
25
  * @param response - Upstream HTTP response.
26
26
  * @param resourceName - Resource label used in stream errors.
27
- * @param filter - Transforms upstream SSE bytes before exposing them to the caller.
28
27
  */
29
- export declare function buildTerminalStreamResult(response: Response, resourceName: string, filter?: (body: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>): TerminalStreamResult;
28
+ export declare function buildTerminalStreamResult(response: Response, resourceName: string): TerminalStreamResult;
30
29
  /**
31
30
  * Starts stateless text generation with independent final, incremental, and response outputs.
32
31
  * @param config - Authentication, base URL, and transport configuration.
@@ -2,7 +2,7 @@ import { createTextStreamResponse, parsePartialJson } from "ai";
2
2
  import { sessionIdSchema, turnIdSchema } from "./contracts/ids.js";
3
3
  import { BlazingAgentsError } from "./errors.js";
4
4
  import { dispatchChatFunctions, toChatFunctionDefinitions, } from "./functions.js";
5
- import { requestStream } from "./http.js";
5
+ import { apiPath, requestStream } from "./http.js";
6
6
  /**
7
7
  * Creates or resumes a Session and returns its SSE stream and Session ID.
8
8
  * @param config - Authentication, base URL, and transport configuration.
@@ -21,8 +21,8 @@ export async function chat(config, input) {
21
21
  * (`POST /v1/agents/:agentId/sessions/:sessionId`).
22
22
  */
23
23
  const path = input.sessionId === undefined
24
- ? `/v1/agents/${input.agentId}/sessions`
25
- : `/v1/agents/${input.agentId}/sessions/${input.sessionId}`;
24
+ ? apiPath `/v1/agents/${input.agentId}/sessions`
25
+ : apiPath `/v1/agents/${input.agentId}/sessions/${input.sessionId}`;
26
26
  const response = await requestStream(config, path, {
27
27
  json: body,
28
28
  method: "POST",
@@ -42,7 +42,7 @@ export async function chat(config, input) {
42
42
  * @returns The Session ID promise and continuation SSE accessors.
43
43
  */
44
44
  export async function continueChat(config, input) {
45
- const response = await requestStream(config, `/v1/agents/${input.agentId}/sessions/${input.sessionId}/tool-approvals/continue`, {
45
+ const response = await requestStream(config, apiPath `/v1/agents/${input.agentId}/sessions/${input.sessionId}/tool-approvals/continue`, {
46
46
  json: {
47
47
  decisions: input.decisions,
48
48
  ...(input.functions === undefined
@@ -79,37 +79,23 @@ export function withFilteredBody(response, filter) {
79
79
  * Builds a chat request body from messages or a stored Prompt.
80
80
  */
81
81
  function buildChatBody(input) {
82
- const base = {};
83
- // Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined trigger.
84
- if (input.trigger !== undefined) {
85
- base.trigger = input.trigger;
86
- }
87
- // Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined message id.
88
- if (input.messageId !== undefined) {
89
- base.messageId = input.messageId;
90
- }
82
+ const body = {
83
+ trigger: input.trigger,
84
+ messageId: input.messageId,
85
+ };
91
86
  if ("message" in input) {
92
- base.messages = [input.message];
87
+ body.messages = [input.message];
93
88
  }
94
89
  else if ("messages" in input) {
95
- base.messages = input.messages;
90
+ body.messages = input.messages;
96
91
  }
97
92
  else {
98
- base.promptId = input.promptId;
99
- // Stryker disable next-line ConditionalExpression: JSON serialization omits undefined variables.
100
- if (input.variables !== undefined) {
101
- base.variables = input.variables;
102
- }
103
- }
104
- // Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined user id.
105
- if (input.userId !== undefined) {
106
- base.userId = input.userId;
107
- }
108
- // Stryker disable next-line ConditionalExpression: JSON serialization omits undefined metadata.
109
- if (input.metadata !== undefined) {
110
- base.metadata = input.metadata;
93
+ body.promptId = input.promptId;
94
+ body.variables = input.variables;
111
95
  }
112
- return base;
96
+ body.userId = input.userId;
97
+ body.metadata = input.metadata;
98
+ return body;
113
99
  }
114
100
  /**
115
101
  * Extracts the server-minted `ss_` id from the `Location` header on the
@@ -190,9 +176,8 @@ function buildChatResult(config, response, resumeSessionId, dispatch) {
190
176
  * Creates single-owner SSE response and byte-stream accessors.
191
177
  * @param response - Upstream HTTP response.
192
178
  * @param resourceName - Resource label used in stream errors.
193
- * @param filter - Transforms upstream SSE bytes before exposing them to the caller.
194
179
  */
195
- export function buildTerminalStreamResult(response, resourceName, filter) {
180
+ export function buildTerminalStreamResult(response, resourceName) {
196
181
  const requestId = response.headers.get("x-request-id") ?? undefined;
197
182
  const location = response.headers.get("location");
198
183
  const turnId = response.headers.get("x-ba-turn-id");
@@ -203,17 +188,11 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
203
188
  */
204
189
  const claimBody = () => {
205
190
  if (bodyClaimed) {
206
- const message = `The ${resourceName} response body has already been claimed.`;
207
- const cause = new Error(message);
208
- throw new BlazingAgentsError({
209
- code: "stream_error",
210
- message,
211
- requestId,
212
- }, { cause });
191
+ throw alreadyClaimedError(resourceName, requestId);
213
192
  }
214
193
  bodyClaimed = true;
215
194
  const body = responseBodyStream(response, requestId, resourceName);
216
- return normalizeStreamErrors(filter ? filter(body) : body, requestId, `The ${resourceName} response stream failed.`);
195
+ return normalizeStreamErrors(body, requestId, `The ${resourceName} response stream failed.`);
217
196
  };
218
197
  return {
219
198
  requestId,
@@ -239,6 +218,25 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
239
218
  },
240
219
  };
241
220
  }
221
+ function alreadyClaimedError(resourceName, requestId) {
222
+ const message = `The ${resourceName} response body has already been claimed.`;
223
+ return new BlazingAgentsError({ code: "stream_error", message, requestId }, { cause: new Error(message) });
224
+ }
225
+ /**
226
+ * Parses the complete generated text, reporting malformed JSON as a stream error.
227
+ */
228
+ function parseFinalJson(text, requestId) {
229
+ try {
230
+ return JSON.parse(text);
231
+ }
232
+ catch (cause) {
233
+ throw new BlazingAgentsError({
234
+ code: "stream_error",
235
+ message: "The agent produced invalid JSON.",
236
+ requestId,
237
+ }, { cause });
238
+ }
239
+ }
242
240
  /**
243
241
  * Preserves a matching stream error or wraps a failure with request correlation.
244
242
  */
@@ -354,19 +352,10 @@ function buildStatelessGenerationBody(input, output) {
354
352
  }
355
353
  else {
356
354
  body.promptId = input.promptId;
357
- // Stryker disable next-line ConditionalExpression: JSON serialization omits undefined variables.
358
- if (input.variables !== undefined) {
359
- body.variables = input.variables;
360
- }
361
- }
362
- // Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined user id.
363
- if (input.userId !== undefined) {
364
- body.userId = input.userId;
365
- }
366
- // Stryker disable next-line ConditionalExpression: JSON serialization omits undefined metadata.
367
- if (input.metadata !== undefined) {
368
- body.metadata = input.metadata;
355
+ body.variables = input.variables;
369
356
  }
357
+ body.userId = input.userId;
358
+ body.metadata = input.metadata;
370
359
  return body;
371
360
  }
372
361
  /**
@@ -377,7 +366,7 @@ function buildStatelessGenerationBody(input, output) {
377
366
  */
378
367
  export async function completion(config, input) {
379
368
  const body = buildStatelessGenerationBody(input, { type: "text" });
380
- const path = `/v1/agents/${input.agentId}/generation`;
369
+ const path = apiPath `/v1/agents/${input.agentId}/generation`;
381
370
  const response = await requestStream(config, path, {
382
371
  json: body,
383
372
  method: "POST",
@@ -419,7 +408,7 @@ export async function objectGeneration(config, input) {
419
408
  type: "object",
420
409
  schema: input.schema,
421
410
  });
422
- const path = `/v1/agents/${input.agentId}/generation`;
411
+ const path = apiPath `/v1/agents/${input.agentId}/generation`;
423
412
  const response = await requestStream(config, path, {
424
413
  json: body,
425
414
  method: "POST",
@@ -449,16 +438,7 @@ function buildObjectResult(response) {
449
438
  * Rejects malformed final JSON when the text stream ends.
450
439
  */
451
440
  flush() {
452
- try {
453
- JSON.parse(accumulatedText);
454
- }
455
- catch (cause) {
456
- throw new BlazingAgentsError({
457
- code: "stream_error",
458
- message: "The agent produced invalid JSON.",
459
- requestId,
460
- }, { cause });
461
- }
441
+ parseFinalJson(accumulatedText, requestId);
462
442
  },
463
443
  }));
464
444
  const objectPromise = (async () => {
@@ -466,16 +446,7 @@ function buildObjectResult(response) {
466
446
  for await (const delta of finalStream) {
467
447
  text += delta;
468
448
  }
469
- try {
470
- return JSON.parse(text);
471
- }
472
- catch (cause) {
473
- throw new BlazingAgentsError({
474
- code: "stream_error",
475
- message: "The agent produced invalid JSON.",
476
- requestId,
477
- }, { cause });
478
- }
449
+ return parseFinalJson(text, requestId);
479
450
  })();
480
451
  objectPromise.catch(() => {
481
452
  /* no-op — prevents unhandled rejection if the caller never awaits */
@@ -509,12 +480,7 @@ function buildStatelessGenerationStreams(response, resourceName) {
509
480
  /** Claims the response relay once. */
510
481
  toResponse: () => {
511
482
  if (responseBodyClaimed) {
512
- const message = `The ${resourceName} response body has already been claimed.`;
513
- throw new BlazingAgentsError({
514
- code: "stream_error",
515
- message,
516
- requestId,
517
- }, { cause: new Error(message) });
483
+ throw alreadyClaimedError(resourceName, requestId);
518
484
  }
519
485
  responseBodyClaimed = true;
520
486
  const headers = replacementResponseHeaders(requestId, location, null);
package/dist/http.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import { BlazingAgentsError } from "./errors.ts";
2
2
  import type { HttpConfig, RequestOptions } from "./types.ts";
3
+ /**
4
+ * Builds an endpoint path, encoding each interpolated value so it stays inside
5
+ * one path segment or query value.
6
+ */
7
+ export declare function apiPath(template: TemplateStringsArray, ...values: string[]): string;
3
8
  /**
4
9
  * Performs a request and returns the parsed JSON body for success (status
5
10
  * 2xx). API errors preserve the tolerant wire envelope; malformed responses
@@ -37,13 +42,3 @@ export declare function isRequestAborted(cause: unknown, signal?: AbortSignal):
37
42
  * @returns A request_aborted error retaining the cause.
38
43
  */
39
44
  export declare function requestAbortedError(cause: unknown): BlazingAgentsError;
40
- /**
41
- * Decodes a response body with the tolerant consumer schema. Unknown future
42
- * codes and fields remain valid; malformed responses never infer a domain
43
- * code from HTTP status.
44
- * @param bodyText - Response body as text.
45
- * @param status - HTTP response status.
46
- * @param headers - Response headers to preserve or inspect.
47
- * @returns The server error, or invalid_response when the envelope is malformed.
48
- */
49
- export declare function parseErrorEnvelope(bodyText: string, status: number, headers: Headers): BlazingAgentsError;
package/dist/http.js CHANGED
@@ -4,6 +4,13 @@ const DIAGNOSTIC_BODY_LIMIT_BYTES = 64 * 1024;
4
4
  const INVALID_RESPONSE_MESSAGE = "The server returned an invalid response.";
5
5
  const NETWORK_ERROR_MESSAGE = "Network request failed (fetch threw before any HTTP exchange).";
6
6
  const REQUEST_ABORTED_MESSAGE = "The request was aborted before any HTTP response.";
7
+ /**
8
+ * Builds an endpoint path, encoding each interpolated value so it stays inside
9
+ * one path segment or query value.
10
+ */
11
+ export function apiPath(template, ...values) {
12
+ return String.raw({ raw: template }, ...values.map(encodeURIComponent));
13
+ }
7
14
  /**
8
15
  * Appends query values while omitting null and undefined entries.
9
16
  */
@@ -305,7 +312,7 @@ function decodeChunks(chunks, byteLength, truncated) {
305
312
  * @param headers - Response headers to preserve or inspect.
306
313
  * @returns The server error, or invalid_response when the envelope is malformed.
307
314
  */
308
- export function parseErrorEnvelope(bodyText, status, headers) {
315
+ function parseErrorEnvelope(bodyText, status, headers) {
309
316
  let parsed;
310
317
  if (bodyText.length === 0) {
311
318
  parsed = null;
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export { AGENT_TOOL_FILE_ACCESS_TAGS, AGENT_TOOL_GROUPS, AGENT_TOOL_TAGS, AGENT_
11
11
  export type { Agent, AgentConfig, AgentResponse, AgentsListQuery, AgentsResponse, CreateAgentBody, UpdateAgentBody, } from "./contracts/entities/agents.ts";
12
12
  export { agentConfigSchema } from "./contracts/entities/agents.ts";
13
13
  export type { ArtifactDownloadUrlResponse, ArtifactListItem, ArtifactsListResponse, } from "./contracts/entities/artifacts.ts";
14
- export type { ChatConfiguration, ChatConnection, ChatConnectionsResponse, ChatCredentials, ChatDeliveriesResponse, ChatDelivery, ChatDeliveryListStatus, ChatDeliveryStatus, ChatHealth, ChatIdentity, CreateChatConnectionBody, RotateChatConnectionBody, TenantChatDelivery, UpdateChatConnectionBody, } from "./contracts/entities/chat-connections.ts";
14
+ export type { ChatConfiguration, ChatConnection, ChatConnectionsResponse, ChatCredentials, ChatDeliveriesResponse, ChatDelivery, ChatDeliveryList, ChatDeliveryListStatus, ChatDeliveryResult, ChatDeliveryStatus, ChatHealth, ChatIdentity, CreateChatConnectionBody, RepairChatDeliveryBody, RotateChatConnectionBody, TenantChatDelivery, UpdateChatConnectionBody, } from "./contracts/entities/chat-connections.ts";
15
15
  export type { CreateMcpConnectionBody, McpAttachmentResponse, McpAttachmentsResponse, McpConnectionAuthType, McpConnectionOauthConnectResponse, McpConnectionReconnectResult, McpConnectionResponse, McpConnectionStatus, McpConnectionTestResponse, ReconnectMcpConnectionBody, UpdateMcpAttachmentBody, UpdateMcpConnectionBody, } from "./contracts/entities/mcp-connections.ts";
16
16
  export type { CreateMerchantConnectionBody, MerchantBindingResponse, MerchantBindingsResponse, MerchantConnection, MerchantConnectionResponse, MerchantCustomerBinding, MerchantGuard, MerchantProviderKind, MerchantUsageEvent, MerchantUsageEventResponse, MerchantUsageEventStatus, MerchantUsageEventsResponse, MerchantUsageSummary, MerchantUsageSummaryResponse, UpdateMerchantConnectionBody, UpsertMerchantBindingBody, } from "./contracts/entities/merchant.ts";
17
17
  export type { CreatePromptBody, PromptResponse, PromptsListQuery, PromptsResponse, UpdatePromptBody, } from "./contracts/entities/prompts.ts";
@@ -1,7 +1,13 @@
1
- import type { AgentsResource, HttpConfig } from "../types.ts";
1
+ import type { AgentsResource, HttpConfig, UserAgentsResource } from "../types.ts";
2
2
  /**
3
- * Builds the Agents operations using the shared HTTP configuration.
3
+ * Builds the Agents operations, including the spending limits that need tenant authority.
4
4
  * @param config - Shared authentication and transport configuration.
5
5
  * @returns The configured resource client.
6
6
  */
7
7
  export declare function createAgentsResource(config: HttpConfig): AgentsResource;
8
+ /**
9
+ * Builds the Agents operations a user-scoped client may call.
10
+ * @param config - Shared authentication and transport configuration.
11
+ * @returns The configured resource client.
12
+ */
13
+ export declare function createUserAgentsResource(config: HttpConfig): UserAgentsResource;