@blazingagents/sdk 0.20.0 → 0.22.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.
Files changed (88) hide show
  1. package/dist/approvals.d.ts +4 -0
  2. package/dist/approvals.js +4 -0
  3. package/dist/chat-stream-transport.d.ts +5 -0
  4. package/dist/chat-stream-transport.js +15 -0
  5. package/dist/chat-transport.d.ts +18 -1
  6. package/dist/chat-transport.js +19 -2
  7. package/dist/client.d.ts +24 -1
  8. package/dist/client.js +33 -1
  9. package/dist/contracts/api.d.ts +37 -0
  10. package/dist/contracts/api.js +29 -0
  11. package/dist/contracts/entities/agent-tools.d.ts +5 -2
  12. package/dist/contracts/entities/agent-tools.js +5 -2
  13. package/dist/contracts/entities/agents.d.ts +4 -0
  14. package/dist/contracts/entities/agents.js +9 -0
  15. package/dist/contracts/entities/chat.d.ts +3 -0
  16. package/dist/contracts/entities/chat.js +6 -0
  17. package/dist/contracts/entities/mcp-connections.d.ts +3 -1
  18. package/dist/contracts/entities/mcp-connections.js +3 -1
  19. package/dist/contracts/entities/prompts.d.ts +13 -0
  20. package/dist/contracts/entities/prompts.js +13 -0
  21. package/dist/contracts/entities/session-inputs.js +3 -1
  22. package/dist/contracts/entities/sessions.d.ts +11 -0
  23. package/dist/contracts/entities/sessions.js +11 -1
  24. package/dist/contracts/entities/skills.d.ts +3 -0
  25. package/dist/contracts/entities/skills.js +3 -0
  26. package/dist/contracts/entities/spending-limits.d.ts +103 -0
  27. package/dist/contracts/entities/spending-limits.js +81 -0
  28. package/dist/contracts/entities/tasks.d.ts +1 -0
  29. package/dist/contracts/entities/usage.d.ts +4 -1
  30. package/dist/contracts/entities/usage.js +7 -1
  31. package/dist/contracts/entities/workspaces.d.ts +17 -6
  32. package/dist/contracts/entities/workspaces.js +3 -7
  33. package/dist/contracts/ids.d.ts +31 -0
  34. package/dist/contracts/ids.js +34 -0
  35. package/dist/contracts/index.d.ts +6 -3
  36. package/dist/contracts/index.js +3 -2
  37. package/dist/contracts/utils.d.ts +10 -0
  38. package/dist/contracts/utils.js +10 -0
  39. package/dist/direct-chat-transport.d.ts +32 -5
  40. package/dist/direct-chat-transport.js +29 -2
  41. package/dist/errors.d.ts +9 -0
  42. package/dist/errors.js +9 -0
  43. package/dist/functions.d.ts +35 -2
  44. package/dist/functions.js +60 -4
  45. package/dist/generation.d.ts +32 -0
  46. package/dist/generation.js +83 -0
  47. package/dist/http.d.ts +26 -0
  48. package/dist/http.js +43 -0
  49. package/dist/index.d.ts +5 -3
  50. package/dist/index.js +1 -0
  51. package/dist/relay.d.ts +23 -0
  52. package/dist/relay.js +16 -0
  53. package/dist/resources/agents.d.ts +5 -0
  54. package/dist/resources/agents.js +47 -0
  55. package/dist/resources/artifacts.d.ts +2 -0
  56. package/dist/resources/artifacts.js +14 -0
  57. package/dist/resources/chat-connections.d.ts +5 -0
  58. package/dist/resources/chat-connections.js +32 -0
  59. package/dist/resources/chat-deliveries.d.ts +2 -0
  60. package/dist/resources/chat-deliveries.js +5 -0
  61. package/dist/resources/mcp-connections.d.ts +5 -0
  62. package/dist/resources/mcp-connections.js +26 -0
  63. package/dist/resources/memories.d.ts +2 -0
  64. package/dist/resources/memories.js +17 -0
  65. package/dist/resources/merchant-bindings.d.ts +2 -0
  66. package/dist/resources/merchant-bindings.js +11 -0
  67. package/dist/resources/merchant-connection.d.ts +2 -0
  68. package/dist/resources/merchant-connection.js +14 -0
  69. package/dist/resources/merchant-usage-events.d.ts +2 -0
  70. package/dist/resources/merchant-usage-events.js +20 -0
  71. package/dist/resources/prompts.d.ts +5 -0
  72. package/dist/resources/prompts.js +20 -0
  73. package/dist/resources/providers.d.ts +2 -0
  74. package/dist/resources/providers.js +23 -0
  75. package/dist/resources/sessions.d.ts +2 -0
  76. package/dist/resources/sessions.js +40 -0
  77. package/dist/resources/skills.d.ts +5 -0
  78. package/dist/resources/skills.js +35 -0
  79. package/dist/resources/tasks.d.ts +2 -0
  80. package/dist/resources/tasks.js +32 -0
  81. package/dist/resources/tenant.d.ts +2 -0
  82. package/dist/resources/tenant.js +17 -0
  83. package/dist/resources/usage.d.ts +2 -0
  84. package/dist/resources/usage.js +14 -0
  85. package/dist/resources/workspaces.d.ts +5 -0
  86. package/dist/resources/workspaces.js +20 -0
  87. package/dist/types.d.ts +696 -13
  88. package/package.json +1 -1
@@ -3,6 +3,12 @@ import { sessionIdSchema } from "./contracts/ids.js";
3
3
  import { BlazingAgentsError } from "./errors.js";
4
4
  import { dispatchChatFunctions, toChatFunctionDefinitions, } from "./functions.js";
5
5
  import { requestStream } from "./http.js";
6
+ /**
7
+ * Creates or resumes a Session and returns its SSE stream and Session ID.
8
+ * @param config - Authentication, base URL, and transport configuration.
9
+ * @param input - Agent, message or stored Prompt, and optional existing Session.
10
+ * @returns The Session ID promise and single-owner SSE accessors.
11
+ */
6
12
  export async function chat(config, input) {
7
13
  const body = buildChatBody(input);
8
14
  if (input.functions && Object.keys(input.functions).length > 0) {
@@ -29,6 +35,12 @@ export async function chat(config, input) {
29
35
  abortSignal: input.abortSignal,
30
36
  });
31
37
  }
38
+ /**
39
+ * Submits a complete Tool approval round and streams its continuation.
40
+ * @param config - Authentication, base URL, and transport configuration.
41
+ * @param input - Agent, Session, and decisions for the complete approval round.
42
+ * @returns The Session ID promise and continuation SSE accessors.
43
+ */
32
44
  export async function continueChat(config, input) {
33
45
  const response = await requestStream(config, `/v1/agents/${input.agentId}/sessions/${input.sessionId}/tool-approvals/continue`, {
34
46
  json: {
@@ -50,6 +62,8 @@ export async function continueChat(config, input) {
50
62
  /**
51
63
  * Keeps status and headers while filtering the SSE body. Missing or locked
52
64
  * bodies pass through so the stream result reports them as `stream_error`.
65
+ * @param response - Upstream HTTP response.
66
+ * @param filter - Transforms upstream SSE bytes before exposing them to the caller.
53
67
  */
54
68
  export function withFilteredBody(response, filter) {
55
69
  if (!response.body || response.body.locked) {
@@ -61,6 +75,9 @@ export function withFilteredBody(response, filter) {
61
75
  statusText: response.statusText,
62
76
  });
63
77
  }
78
+ /**
79
+ * Builds a chat request body from messages or a stored Prompt.
80
+ */
64
81
  function buildChatBody(input) {
65
82
  const base = {};
66
83
  // Stryker disable next-line ConditionalExpression: JSON serialization omits an undefined trigger.
@@ -122,6 +139,9 @@ function sessionIdFromLocation(response, requestId) {
122
139
  }
123
140
  return parsed.data;
124
141
  }
142
+ /**
143
+ * Combines the Session ID promise with a single-owner SSE result.
144
+ */
125
145
  function buildChatResult(config, response, resumeSessionId, dispatch) {
126
146
  /**
127
147
  * `sessionId` resolves from the `Location` header on create, or to the
@@ -154,10 +174,20 @@ function buildChatResult(config, response, resumeSessionId, dispatch) {
154
174
  ...buildTerminalStreamResult(streamResponse, "chat"),
155
175
  };
156
176
  }
177
+ /**
178
+ * Creates single-owner SSE response and byte-stream accessors.
179
+ * @param response - Upstream HTTP response.
180
+ * @param resourceName - Resource label used in stream errors.
181
+ * @param filter - Transforms upstream SSE bytes before exposing them to the caller.
182
+ */
157
183
  export function buildTerminalStreamResult(response, resourceName, filter) {
158
184
  const requestId = response.headers.get("x-request-id") ?? undefined;
159
185
  const location = response.headers.get("location");
160
186
  let bodyClaimed = false;
187
+ /**
188
+ * Claims the response body once and normalizes stream failures.
189
+ * @throws BlazingAgentsError - If the response body has already been claimed.
190
+ */
161
191
  const claimBody = () => {
162
192
  if (bodyClaimed) {
163
193
  const message = `The ${resourceName} response body has already been claimed.`;
@@ -175,6 +205,7 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
175
205
  return {
176
206
  requestId,
177
207
  toStream: claimBody,
208
+ /** Claims the response relay once. */
178
209
  toResponse: () => {
179
210
  const headers = replacementResponseHeaders(requestId, location);
180
211
  headers.set("content-type", "text/event-stream");
@@ -195,6 +226,9 @@ export function buildTerminalStreamResult(response, resourceName, filter) {
195
226
  },
196
227
  };
197
228
  }
229
+ /**
230
+ * Preserves a matching stream error or wraps a failure with request correlation.
231
+ */
198
232
  function toStreamError(cause, requestId, fallbackMessage) {
199
233
  if (BlazingAgentsError.isInstance(cause) &&
200
234
  cause.code === "stream_error" &&
@@ -217,6 +251,9 @@ function toStreamError(cause, requestId, fallbackMessage) {
217
251
  requestId,
218
252
  }, { cause });
219
253
  }
254
+ /**
255
+ * Wraps reads and cancellation failures as correlated SDK stream errors.
256
+ */
220
257
  function normalizeStreamErrors(stream, requestId, fallbackMessage) {
221
258
  let reader;
222
259
  try {
@@ -226,6 +263,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
226
263
  throw toStreamError(cause, requestId, fallbackMessage);
227
264
  }
228
265
  return new ReadableStream({
266
+ /**
267
+ * Reads one upstream chunk and normalizes stream failures.
268
+ */
229
269
  async pull(controller) {
230
270
  try {
231
271
  const { done, value } = await reader.read();
@@ -239,6 +279,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
239
279
  controller.error(toStreamError(cause, requestId, fallbackMessage));
240
280
  }
241
281
  },
282
+ /**
283
+ * Cancels the upstream reader with the consumer reason.
284
+ */
242
285
  async cancel(reason) {
243
286
  try {
244
287
  await reader.cancel(reason);
@@ -249,6 +292,9 @@ function normalizeStreamErrors(stream, requestId, fallbackMessage) {
249
292
  },
250
293
  });
251
294
  }
295
+ /**
296
+ * Returns the response body or a stream that fails when the body is missing.
297
+ */
252
298
  function responseBodyStream(response, requestId, resourceName) {
253
299
  if (response.body) {
254
300
  return response.body;
@@ -261,11 +307,17 @@ function responseBodyStream(response, requestId, resourceName) {
261
307
  requestId,
262
308
  }, { cause });
263
309
  return new ReadableStream({
310
+ /**
311
+ * Initializes the stream controller.
312
+ */
264
313
  start(controller) {
265
314
  controller.error(error);
266
315
  },
267
316
  });
268
317
  }
318
+ /**
319
+ * Copies request correlation and Session location into relay response headers.
320
+ */
269
321
  function replacementResponseHeaders(requestId, location) {
270
322
  const headers = new Headers();
271
323
  if (requestId !== undefined) {
@@ -276,6 +328,9 @@ function replacementResponseHeaders(requestId, location) {
276
328
  }
277
329
  return headers;
278
330
  }
331
+ /**
332
+ * Builds a stateless prompt request with the selected output format.
333
+ */
279
334
  function buildStatelessGenerationBody(input, output) {
280
335
  const body = { output };
281
336
  if ("prompt" in input) {
@@ -298,6 +353,12 @@ function buildStatelessGenerationBody(input, output) {
298
353
  }
299
354
  return body;
300
355
  }
356
+ /**
357
+ * Starts stateless text generation with independent final, incremental, and response outputs.
358
+ * @param config - Authentication, base URL, and transport configuration.
359
+ * @param input - Agent and literal prompt or stored Prompt reference.
360
+ * @returns Independent text stream, final text promise, and response relay.
361
+ */
301
362
  export async function completion(config, input) {
302
363
  const body = buildStatelessGenerationBody(input, { type: "text" });
303
364
  const path = `/v1/agents/${input.agentId}/generation`;
@@ -309,6 +370,9 @@ export async function completion(config, input) {
309
370
  });
310
371
  return buildCompletionResult(response);
311
372
  }
373
+ /**
374
+ * Splits text output into a final promise, incremental stream, and response relay.
375
+ */
312
376
  function buildCompletionResult(response) {
313
377
  const { finalStream, outputStream, requestId, toResponse } = buildStatelessGenerationStreams(response, "completion");
314
378
  const textPromise = (async () => {
@@ -328,6 +392,12 @@ function buildCompletionResult(response) {
328
392
  toResponse,
329
393
  };
330
394
  }
395
+ /**
396
+ * Starts stateless JSON generation with partial objects and a final parsed value.
397
+ * @param config - Authentication, base URL, and transport configuration.
398
+ * @param input - Agent, prompt source, and JSON output schema.
399
+ * @returns Partial JSON objects, a final JSON promise, and a text response relay.
400
+ */
331
401
  export async function objectGeneration(config, input) {
332
402
  const body = buildStatelessGenerationBody(input, {
333
403
  type: "object",
@@ -342,10 +412,16 @@ export async function objectGeneration(config, input) {
342
412
  });
343
413
  return buildObjectResult(response);
344
414
  }
415
+ /**
416
+ * Parses partial and final JSON from independent text-stream branches.
417
+ */
345
418
  function buildObjectResult(response) {
346
419
  const { finalStream, outputStream, requestId, toResponse } = buildStatelessGenerationStreams(response, "object");
347
420
  let accumulatedText = "";
348
421
  const partialObjectStream = outputStream.pipeThrough(new TransformStream({
422
+ /**
423
+ * Accumulates generated text and emits each available partial JSON value.
424
+ */
349
425
  async transform(chunk, controller) {
350
426
  accumulatedText += chunk;
351
427
  const { value } = await parsePartialJson(accumulatedText);
@@ -353,6 +429,9 @@ function buildObjectResult(response) {
353
429
  controller.enqueue(value);
354
430
  }
355
431
  },
432
+ /**
433
+ * Rejects malformed final JSON when the text stream ends.
434
+ */
356
435
  flush() {
357
436
  try {
358
437
  JSON.parse(accumulatedText);
@@ -392,6 +471,9 @@ function buildObjectResult(response) {
392
471
  toResponse,
393
472
  };
394
473
  }
474
+ /**
475
+ * Splits decoded text into final, public, and response-relay branches.
476
+ */
395
477
  function buildStatelessGenerationStreams(response, resourceName) {
396
478
  const requestId = response.headers.get("x-request-id") ?? undefined;
397
479
  const location = response.headers.get("location");
@@ -408,6 +490,7 @@ function buildStatelessGenerationStreams(response, resourceName) {
408
490
  finalStream,
409
491
  outputStream,
410
492
  requestId,
493
+ /** Claims the response relay once. */
411
494
  toResponse: () => {
412
495
  if (responseBodyClaimed) {
413
496
  const message = `The ${resourceName} response body has already been claimed.`;
package/dist/http.d.ts CHANGED
@@ -4,20 +4,46 @@ import type { HttpConfig, RequestOptions } from "./types.ts";
4
4
  * Performs a request and returns the parsed JSON body for success (status
5
5
  * 2xx). API errors preserve the tolerant wire envelope; malformed responses
6
6
  * become `invalid_response`.
7
+ * @param config - Authentication, base URL, and transport configuration.
8
+ * @param path - Endpoint path relative to the base URL.
9
+ * @param options - Configuration for this operation.
10
+ * @param schema - Schema used to validate the value.
7
11
  */
8
12
  export declare function requestJson<T>(config: HttpConfig, path: string, options?: RequestOptions, schema?: {
13
+ /**
14
+ * Validates the decoded response value.
15
+ * @param value - Value to inspect.
16
+ */
9
17
  parse(value: unknown): T;
10
18
  }): Promise<T>;
11
19
  /**
12
20
  * Performs a request and returns the raw `Response` for streaming paths.
13
21
  * Non-2xx bodies are decoded before a caller can observe a streaming body.
22
+ * @param config - Authentication, base URL, and transport configuration.
23
+ * @param path - Endpoint path relative to the base URL.
24
+ * @param options - Configuration for this operation.
14
25
  */
15
26
  export declare function requestStream(config: HttpConfig, path: string, options?: RequestOptions): Promise<Response>;
27
+ /**
28
+ * Checks whether the signal aborted or the cause names an AbortError.
29
+ * @param cause - Original failure to retain.
30
+ * @param signal - Signal that cancels the operation.
31
+ * @returns Whether the request signal or cause indicates cancellation.
32
+ */
16
33
  export declare function isRequestAborted(cause: unknown, signal?: AbortSignal): boolean;
34
+ /**
35
+ * Wraps an abort cause as a request_aborted SDK error.
36
+ * @param cause - Original failure to retain.
37
+ * @returns A request_aborted error retaining the cause.
38
+ */
17
39
  export declare function requestAbortedError(cause: unknown): BlazingAgentsError;
18
40
  /**
19
41
  * Decodes a response body with the tolerant consumer schema. Unknown future
20
42
  * codes and fields remain valid; malformed responses never infer a domain
21
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.
22
48
  */
23
49
  export declare function parseErrorEnvelope(bodyText: string, status: number, headers?: Headers): BlazingAgentsError;
package/dist/http.js CHANGED
@@ -4,6 +4,9 @@ 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
+ * Appends query values while omitting null and undefined entries.
9
+ */
7
10
  function buildUrl(baseUrl, path, query) {
8
11
  const url = `${baseUrl}${path}`;
9
12
  if (!query) {
@@ -23,6 +26,10 @@ function buildUrl(baseUrl, path, query) {
23
26
  * Performs a request and returns the parsed JSON body for success (status
24
27
  * 2xx). API errors preserve the tolerant wire envelope; malformed responses
25
28
  * become `invalid_response`.
29
+ * @param config - Authentication, base URL, and transport configuration.
30
+ * @param path - Endpoint path relative to the base URL.
31
+ * @param options - Configuration for this operation.
32
+ * @param schema - Schema used to validate the value.
26
33
  */
27
34
  export async function requestJson(config, path, options = {}, schema) {
28
35
  const response = await rawRequest(config, path, options);
@@ -56,6 +63,9 @@ export async function requestJson(config, path, options = {}, schema) {
56
63
  /**
57
64
  * Performs a request and returns the raw `Response` for streaming paths.
58
65
  * Non-2xx bodies are decoded before a caller can observe a streaming body.
66
+ * @param config - Authentication, base URL, and transport configuration.
67
+ * @param path - Endpoint path relative to the base URL.
68
+ * @param options - Configuration for this operation.
59
69
  */
60
70
  export async function requestStream(config, path, options = {}) {
61
71
  const response = await rawRequest(config, path, options);
@@ -64,6 +74,9 @@ export async function requestStream(config, path, options = {}) {
64
74
  }
65
75
  throw await errorFromResponse(response, options.signal);
66
76
  }
77
+ /**
78
+ * Sends an authenticated request and reports response metadata to the observer.
79
+ */
67
80
  async function rawRequest(config, path, options) {
68
81
  const fetchImpl = config.fetch ?? globalThis.fetch;
69
82
  const url = buildUrl(config.baseUrl, path, options.query);
@@ -122,6 +135,9 @@ async function rawRequest(config, path, options) {
122
135
  }, { cause });
123
136
  }
124
137
  }
138
+ /**
139
+ * Reads bounded diagnostics and decodes a failed HTTP response.
140
+ */
125
141
  async function errorFromResponse(response, signal) {
126
142
  const read = await readResponseBody(response, true);
127
143
  if (read.readFailed && isRequestAborted(read.cause, signal)) {
@@ -133,6 +149,12 @@ async function errorFromResponse(response, signal) {
133
149
  }
134
150
  return parseErrorEnvelope(read.diagnosticBody, response.status, headers);
135
151
  }
152
+ /**
153
+ * Checks whether the signal aborted or the cause names an AbortError.
154
+ * @param cause - Original failure to retain.
155
+ * @param signal - Signal that cancels the operation.
156
+ * @returns Whether the request signal or cause indicates cancellation.
157
+ */
136
158
  export function isRequestAborted(cause, signal) {
137
159
  return (signal?.aborted === true ||
138
160
  (cause !== null &&
@@ -140,6 +162,11 @@ export function isRequestAborted(cause, signal) {
140
162
  "name" in cause &&
141
163
  cause.name === "AbortError"));
142
164
  }
165
+ /**
166
+ * Wraps an abort cause as a request_aborted SDK error.
167
+ * @param cause - Original failure to retain.
168
+ * @returns A request_aborted error retaining the cause.
169
+ */
143
170
  export function requestAbortedError(cause) {
144
171
  return new BlazingAgentsError({
145
172
  code: "request_aborted",
@@ -215,6 +242,9 @@ async function readResponseBody(response, stopAtDiagnosticLimit) {
215
242
  byteLength += chunk.byteLength;
216
243
  }
217
244
  }
245
+ /**
246
+ * Cancels an oversized error body and retains its bounded diagnostic prefix.
247
+ */
218
248
  async function cancelTruncatedBody(reader, chunks, byteLength) {
219
249
  const diagnosticBody = decodeDiagnosticChunks(chunks, byteLength, true).body;
220
250
  try {
@@ -236,6 +266,9 @@ async function cancelTruncatedBody(reader, chunks, byteLength) {
236
266
  };
237
267
  }
238
268
  }
269
+ /**
270
+ * Decodes diagnostics without exceeding the UTF-8 byte limit.
271
+ */
239
272
  function decodeDiagnosticChunks(chunks, byteLength, sourceTruncated) {
240
273
  const body = decodeChunks(chunks, byteLength, sourceTruncated);
241
274
  const encoded = new TextEncoder().encode(body);
@@ -247,6 +280,9 @@ function decodeDiagnosticChunks(chunks, byteLength, sourceTruncated) {
247
280
  truncated: true,
248
281
  };
249
282
  }
283
+ /**
284
+ * Joins retained bytes and omits an incomplete trailing character when truncated.
285
+ */
250
286
  function decodeChunks(chunks, byteLength, truncated) {
251
287
  const bytes = new Uint8Array(byteLength);
252
288
  let offset = 0;
@@ -264,6 +300,10 @@ function decodeChunks(chunks, byteLength, truncated) {
264
300
  * Decodes a response body with the tolerant consumer schema. Unknown future
265
301
  * codes and fields remain valid; malformed responses never infer a domain
266
302
  * code from HTTP status.
303
+ * @param bodyText - Response body as text.
304
+ * @param status - HTTP response status.
305
+ * @param headers - Response headers to preserve or inspect.
306
+ * @returns The server error, or invalid_response when the envelope is malformed.
267
307
  */
268
308
  export function parseErrorEnvelope(bodyText, status, headers = new Headers()) {
269
309
  let parsed;
@@ -292,6 +332,9 @@ export function parseErrorEnvelope(bodyText, status, headers = new Headers()) {
292
332
  }
293
333
  return invalidResponseError(headers, status, bodyText, false);
294
334
  }
335
+ /**
336
+ * Builds an invalid_response error with bounded diagnostics and request correlation.
337
+ */
295
338
  function invalidResponseError(headers, status, responseBody, responseBodyTruncated, cause) {
296
339
  return new BlazingAgentsError({
297
340
  code: "invalid_response",
package/dist/index.d.ts CHANGED
@@ -16,13 +16,15 @@ export type { CreateMerchantConnectionBody, MerchantBindingResponse, MerchantBin
16
16
  export type { CreatePromptBody, PromptResponse, PromptsListQuery, PromptsResponse, UpdatePromptBody, } from "./contracts/entities/prompts.ts";
17
17
  export type { CreateProviderBody, ProviderListItem, ProviderModel, ProviderModelsResponse, ProviderResponse, ProvidersResponse, ProviderType, ThinkingLevelsResponse, UpdateProviderBody, } from "./contracts/entities/providers.ts";
18
18
  export type { ChatSteerConsumedEvent, SessionActivity, SessionInput, SessionInputResponse, SessionInputState, SessionInputsQuery, SessionInputsResponse, StopSessionBody, StopSessionResponse, SubmitSessionInputBody, } from "./contracts/entities/session-inputs.ts";
19
- export type { ContinueToolApprovalsBody, SessionResponse, ToolApprovalDecision, ToolApprovalState, ToolApprovalsResponse, } from "./contracts/entities/sessions.ts";
19
+ export type { ContinueToolApprovalsBody, SessionForkedFrom, SessionResponse, ToolApprovalDecision, ToolApprovalState, ToolApprovalsResponse, } from "./contracts/entities/sessions.ts";
20
20
  export { sessionResponseSchema } from "./contracts/entities/sessions.ts";
21
21
  export type { CreateSkillBody, Skill, SkillArchiveType, SkillCopyResult, SkillCopyResults, SkillDetail, SkillFile, SkillsListResponse, } from "./contracts/entities/skills.ts";
22
+ export type { SpendingLimit, SpendingLimitResponse, SpendingLimitStopDetails, SpendingLimitStopEvent, UpdateSpendingLimitBody, } from "./contracts/entities/spending-limits.ts";
23
+ export { nextSpendingLimitReset } from "./contracts/entities/spending-limits.ts";
22
24
  export type { SessionUsageQuery, SessionUsageResponse, UsageBucket, UsageOverviewQuery, UsageOverviewResponse, UsageTotals, } from "./contracts/entities/usage.ts";
23
- export type { CreateWorkspaceBody, UpdateWorkspaceBody, Workspace, WorkspaceNetworkPolicy, WorkspacesListResponse, } from "./contracts/entities/workspaces.ts";
25
+ export type { CreateWorkspaceBody, UpdateWorkspaceBody, Workspace, WorkspaceNetworkPolicy, WorkspacesListResponse, WorkspaceTier, } from "./contracts/entities/workspaces.ts";
24
26
  export { BlazingAgentsDirectChatTransport, type BlazingAgentsDirectChatTransportOptions, } from "./direct-chat-transport.ts";
25
27
  export { BlazingAgentsError } from "./errors.ts";
26
28
  export { type ChatFunction, type ChatFunctionContext, type ChatFunctions, defineFunction, } from "./functions.ts";
27
29
  export { createChatRelay, createCompletionRelay, type RelayContext, type SessionOwnershipStore, } from "./relay.ts";
28
- export type { AgentClient, AgentSkillsResource, AgentsListOptions, AgentsResource, ArtifactsResource, AttributionInput, BlazingAgentsErrorCode, BlazingAgentsOptions, BlazingAgentsRequestOptions, BlazingAgentsUIMessage, BlazingAgentsUIMessageChunk, ChatConnectionsResource, ChatDeliveriesListOptions, ChatDeliveriesResource, ChatInput, ChatMessageInput, ChatMessagesInput, ChatPromptInput, ChatResult, ChatTrigger, CompletionInput, CompletionPromptIdInput, CompletionPromptInput, CompletionResult, ContinueChatInput, KnownBlazingAgentsErrorCode, LatestSessionsListOptions, McpConnectionsResource, MemoriesListOptions, MemoriesResource, MerchantBindingsListOptions, MerchantBindingsResource, MerchantConnectionResource, MerchantUsageEventsListOptions, MerchantUsageEventsResource, ObjectInput, ObjectPromptIdInput, ObjectPromptInput, ObjectResult, PromptsResource, ProvidersResource, ResourceRequestOptions, ResponseObservation, SessionsResource, SkillsListOptions, TasksResource, TenantResource, TerminalStreamResult, UsageResource, UserClient, WorkspacesListOptions, WorkspacesResource, } from "./types.ts";
30
+ export type { AgentClient, AgentSkillsResource, AgentsListOptions, AgentsResource, ArtifactsResource, AttributionInput, BlazingAgentsErrorCode, BlazingAgentsOptions, BlazingAgentsRequestOptions, BlazingAgentsUIMessage, BlazingAgentsUIMessageChunk, BlazingAgentsUIMessageData, ChatConnectionsResource, ChatDeliveriesListOptions, ChatDeliveriesResource, ChatInput, ChatMessageInput, ChatMessagesInput, ChatPromptInput, ChatResult, ChatTrigger, CompletionInput, CompletionPromptIdInput, CompletionPromptInput, CompletionResult, ContinueChatInput, KnownBlazingAgentsErrorCode, LatestSessionsListOptions, McpConnectionsResource, MemoriesListOptions, MemoriesResource, MerchantBindingsListOptions, MerchantBindingsResource, MerchantConnectionResource, MerchantUsageEventsListOptions, MerchantUsageEventsResource, ObjectInput, ObjectPromptIdInput, ObjectPromptInput, ObjectResult, PromptsResource, ProvidersResource, ResourceRequestOptions, ResponseObservation, SessionsResource, SkillsListOptions, TasksResource, TenantResource, TerminalStreamResult, UsageResource, UserClient, WorkspacesListOptions, WorkspacesResource, } from "./types.ts";
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ export { BlazingAgentsChatTransport, } from "./chat-transport.js";
8
8
  export { BlazingAgents } from "./client.js";
9
9
  export { agentConfigSchema } from "./contracts/entities/agents.js";
10
10
  export { sessionResponseSchema } from "./contracts/entities/sessions.js";
11
+ export { nextSpendingLimitReset } from "./contracts/entities/spending-limits.js";
11
12
  export { BlazingAgentsDirectChatTransport, } from "./direct-chat-transport.js";
12
13
  export { BlazingAgentsError } from "./errors.js";
13
14
  export { defineFunction, } from "./functions.js";
package/dist/relay.d.ts CHANGED
@@ -8,19 +8,42 @@ export interface RelayContext {
8
8
  userId: string;
9
9
  }
10
10
  export interface SessionOwnershipStore {
11
+ /**
12
+ * Looks up the end user who owns the Session.
13
+ * @param sessionId - Session to look up or record.
14
+ * @returns The owner ID, or undefined when no owner is recorded.
15
+ */
11
16
  ownerOf(sessionId: string): Promise<string | undefined>;
17
+ /**
18
+ * Records ownership of a newly created Session.
19
+ * @param sessionId - Session to look up or record.
20
+ * @param userId - End-user ID for request scope.
21
+ * @returns Resolves after ownership is stored.
22
+ */
12
23
  recordOwner(sessionId: string, userId: string): Promise<void>;
13
24
  }
14
25
  interface RelayOptions<Method extends keyof BlazingAgents> {
15
26
  client: Pick<BlazingAgents, Method>;
27
+ /**
28
+ * Resolves authenticated Agent and end-user context, or null for an unauthenticated request.
29
+ * @param request - Incoming HTTP request.
30
+ * @returns Authenticated context, or null when authentication fails.
31
+ */
16
32
  resolveContext(request: Request): Promise<RelayContext | null>;
17
33
  }
18
34
  /**
19
35
  * Relays useChat submissions. An assistant message carrying approval
20
36
  * responses submits the complete round and streams the continuation.
37
+ * @param options - Configuration for this operation.
38
+ * @returns An HTTP handler that checks Session ownership before resuming.
21
39
  */
22
40
  export declare function createChatRelay(options: RelayOptions<"chat" | "continueChat"> & {
23
41
  sessions: SessionOwnershipStore;
24
42
  }): (request: Request) => Promise<Response>;
43
+ /**
44
+ * Creates an authenticated HTTP handler that validates prompts and relays text generation.
45
+ * @param options - Configuration for this operation.
46
+ * @returns An HTTP handler that validates prompts and relays text generation.
47
+ */
25
48
  export declare function createCompletionRelay(options: RelayOptions<"completion">): (request: Request) => Promise<Response>;
26
49
  export {};
package/dist/relay.js CHANGED
@@ -15,6 +15,8 @@ const completionBodySchema = z.object({ prompt: z.string().trim().min(1) });
15
15
  /**
16
16
  * Relays useChat submissions. An assistant message carrying approval
17
17
  * responses submits the complete round and streams the continuation.
18
+ * @param options - Configuration for this operation.
19
+ * @returns An HTTP handler that checks Session ownership before resuming.
18
20
  */
19
21
  export function createChatRelay(options) {
20
22
  return async (request) => {
@@ -86,6 +88,9 @@ export function createChatRelay(options) {
86
88
  }
87
89
  };
88
90
  }
91
+ /**
92
+ * Validates the Session and forwards the last assistant approval round.
93
+ */
89
94
  async function relayApprovalResponses(client, { functions, message, request, ...input }) {
90
95
  if (input.sessionId === undefined) {
91
96
  return errorResponse(400, "invalid_request", "Tool approval requires an existing Session.");
@@ -106,6 +111,11 @@ async function relayApprovalResponses(client, { functions, message, request, ...
106
111
  });
107
112
  return continuation.toResponse();
108
113
  }
114
+ /**
115
+ * Creates an authenticated HTTP handler that validates prompts and relays text generation.
116
+ * @param options - Configuration for this operation.
117
+ * @returns An HTTP handler that validates prompts and relays text generation.
118
+ */
109
119
  export function createCompletionRelay(options) {
110
120
  return async (request) => {
111
121
  try {
@@ -128,6 +138,9 @@ export function createCompletionRelay(options) {
128
138
  }
129
139
  };
130
140
  }
141
+ /**
142
+ * Maps validation and SDK failures to safe public error responses.
143
+ */
131
144
  function safeErrorResponse(error) {
132
145
  if (error instanceof z.ZodError || error instanceof SyntaxError) {
133
146
  return errorResponse(400, "invalid_request", "Invalid request body.");
@@ -143,6 +156,9 @@ function safeErrorResponse(error) {
143
156
  }
144
157
  return errorResponse(500, "internal_error", "Request failed.");
145
158
  }
159
+ /**
160
+ * Builds a JSON error envelope with the selected HTTP status.
161
+ */
146
162
  function errorResponse(status, code, message, headers) {
147
163
  const responseHeaders = new Headers(headers);
148
164
  responseHeaders.set("content-type", "application/json");
@@ -1,2 +1,7 @@
1
1
  import type { AgentsResource, HttpConfig } from "../types.ts";
2
+ /**
3
+ * Builds the Agents operations using the shared HTTP configuration.
4
+ * @param config - Shared authentication and transport configuration.
5
+ * @returns The configured resource client.
6
+ */
2
7
  export declare function createAgentsResource(config: HttpConfig): AgentsResource;
@@ -1,13 +1,33 @@
1
1
  import { agentResponseSchema, agentsResponseSchema, } from "../contracts/entities/agents.js";
2
2
  import { mcpAttachmentResponseSchema, mcpAttachmentsResponseSchema, } from "../contracts/entities/mcp-connections.js";
3
+ import { spendingLimitResponseSchema } from "../contracts/entities/spending-limits.js";
3
4
  import { requestJson } from "../http.js";
5
+ /**
6
+ * Builds the Agents operations using the shared HTTP configuration.
7
+ * @param config - Shared authentication and transport configuration.
8
+ * @returns The configured resource client.
9
+ */
4
10
  export function createAgentsResource(config) {
11
+ /**
12
+ * Updates agents.
13
+ */
5
14
  const update = async ({ agentId, abortSignal, ...body }) => requestJson(config, `/v1/agents/${agentId}`, {
6
15
  json: body,
7
16
  signal: abortSignal,
8
17
  method: "PUT",
9
18
  }, agentResponseSchema);
10
19
  return {
20
+ /** Retrieves the model spending limit using tenant authority. */
21
+ async getSpendingLimit({ agentId, abortSignal }) {
22
+ return await requestJson(config, `/v1/agents/${agentId}/spending-limit`, { signal: abortSignal }, spendingLimitResponseSchema);
23
+ },
24
+ /** Sets the model spending limit. Null disables it. Requires tenant authority. */
25
+ async updateSpendingLimit({ agentId, abortSignal, ...body }) {
26
+ return await requestJson(config, `/v1/agents/${agentId}/spending-limit`, { method: "PUT", json: body, signal: abortSignal }, spendingLimitResponseSchema);
27
+ },
28
+ /**
29
+ * Creates agents.
30
+ */
11
31
  async create({ abortSignal, ...body }) {
12
32
  return await requestJson(config, "/v1/agents", {
13
33
  json: body,
@@ -15,6 +35,9 @@ export function createAgentsResource(config) {
15
35
  method: "POST",
16
36
  }, agentResponseSchema);
17
37
  },
38
+ /**
39
+ * Lists one page of agents.
40
+ */
18
41
  async list(options = {}) {
19
42
  return await requestJson(config, "/v1/agents", {
20
43
  signal: options.abortSignal,
@@ -26,22 +49,40 @@ export function createAgentsResource(config) {
26
49
  },
27
50
  }, agentsResponseSchema);
28
51
  },
52
+ /**
53
+ * Retrieves agents.
54
+ */
29
55
  async get({ agentId, abortSignal }) {
30
56
  return await requestJson(config, `/v1/agents/${agentId}`, { signal: abortSignal }, agentResponseSchema);
31
57
  },
58
+ /**
59
+ * Disables agents.
60
+ */
32
61
  async disable({ agentId, abortSignal }) {
33
62
  return await requestJson(config, `/v1/agents/${agentId}/disable`, { method: "POST", signal: abortSignal }, agentResponseSchema);
34
63
  },
64
+ /**
65
+ * Enables agents.
66
+ */
35
67
  async enable({ agentId, abortSignal }) {
36
68
  return await requestJson(config, `/v1/agents/${agentId}/enable`, { method: "POST", signal: abortSignal }, agentResponseSchema);
37
69
  },
70
+ /**
71
+ * Lists the Agent MCP attachments.
72
+ */
38
73
  async listMcpAttachments({ agentId, abortSignal }) {
39
74
  return await requestJson(config, `/v1/agents/${agentId}/mcp-attachments`, { signal: abortSignal }, mcpAttachmentsResponseSchema);
40
75
  },
41
76
  update,
77
+ /**
78
+ * Updates one Agent MCP attachment.
79
+ */
42
80
  async updateMcpAttachment({ agentId, mcpConnectionId, abortSignal, ...body }) {
43
81
  return await requestJson(config, `/v1/agents/${agentId}/mcp-attachments/${mcpConnectionId}`, { json: body, method: "PATCH", signal: abortSignal }, mcpAttachmentResponseSchema);
44
82
  },
83
+ /**
84
+ * Deletes agents.
85
+ */
45
86
  async delete({ agentId, includeArtifacts, abortSignal }) {
46
87
  await requestJson(config, `/v1/agents/${agentId}`, {
47
88
  method: "DELETE",
@@ -49,6 +90,9 @@ export function createAgentsResource(config) {
49
90
  signal: abortSignal,
50
91
  });
51
92
  },
93
+ /**
94
+ * Uploads an Agent avatar as multipart form data.
95
+ */
52
96
  async uploadAvatar({ agentId, file, abortSignal }) {
53
97
  const form = new FormData();
54
98
  form.append("file", file);
@@ -58,6 +102,9 @@ export function createAgentsResource(config) {
58
102
  method: "POST",
59
103
  }, agentResponseSchema);
60
104
  },
105
+ /**
106
+ * Removes the Agent avatar.
107
+ */
61
108
  async removeAvatar({ agentId, abortSignal }) {
62
109
  return await requestJson(config, `/v1/agents/${agentId}/avatar`, { method: "DELETE", signal: abortSignal }, agentResponseSchema);
63
110
  },
@@ -1,5 +1,7 @@
1
1
  import type { ArtifactsResource, HttpConfig } from "../types.ts";
2
2
  /**
3
3
  * `client.artifacts` — Tenant-level metadata and direct download URLs.
4
+ * @param config - Shared authentication and transport configuration.
5
+ * @returns The configured resource client.
4
6
  */
5
7
  export declare function createArtifactsResource(config: HttpConfig): ArtifactsResource;