@blazingagents/sdk 0.51.0 → 0.53.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/dist/http.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { BlazingAgentsError } from "./errors.ts";
2
- import type { HttpConfig, RequestOptions } from "./types.ts";
2
+ import type { BlazingAgentsFetch, BlazingAgentsRequestInit, HttpConfig, RequestOptions } from "./types.ts";
3
3
  /**
4
4
  * Builds an endpoint path, encoding each interpolated value so it stays inside
5
5
  * one path segment. `encodeURIComponent` leaves `.` and `..` unchanged, and
@@ -31,6 +31,22 @@ export declare function requestJson<T>(config: HttpConfig, path: string, options
31
31
  * @param options - Configuration for this operation.
32
32
  */
33
33
  export declare function requestStream(config: HttpConfig, path: string, options?: RequestOptions): Promise<Response>;
34
+ /**
35
+ * Calls `fetch` and turns its rejection into a `request_aborted` or
36
+ * `network_error` SDK error.
37
+ * @param fetchImpl - The fetch to call.
38
+ * @param url - Request URL.
39
+ * @param init - Request options.
40
+ * @returns The response, whatever its status.
41
+ */
42
+ export declare function sendRequest(fetchImpl: BlazingAgentsFetch, url: string, init: BlazingAgentsRequestInit): Promise<Response>;
43
+ /**
44
+ * Reads bounded diagnostics and decodes a failed HTTP response.
45
+ * @param response - A response with a non-2xx status.
46
+ * @param signal - Signal that cancels the operation.
47
+ * @returns The decoded error, or `invalid_response` when the body is not an error envelope.
48
+ */
49
+ export declare function errorFromResponse(response: Response, signal?: AbortSignal): Promise<BlazingAgentsError>;
34
50
  /**
35
51
  * Checks whether the signal aborted or the cause names an AbortError.
36
52
  * @param cause - Original failure to retain.
@@ -44,3 +60,13 @@ export declare function isRequestAborted(cause: unknown, signal?: AbortSignal):
44
60
  * @returns A request_aborted error retaining the cause.
45
61
  */
46
62
  export declare function requestAbortedError(cause: unknown): BlazingAgentsError;
63
+ /**
64
+ * Builds an invalid_response error with bounded diagnostics and request correlation.
65
+ * @param headers - Response headers.
66
+ * @param status - HTTP response status.
67
+ * @param responseBody - Diagnostic body text.
68
+ * @param responseBodyTruncated - Whether the diagnostic body was cut short.
69
+ * @param cause - The parse or validation failure.
70
+ * @returns The invalid_response error.
71
+ */
72
+ export declare function invalidResponseError(headers: Headers, status: number, responseBody: string, responseBodyTruncated: boolean, cause?: unknown): BlazingAgentsError;
package/dist/http.js CHANGED
@@ -221,47 +221,56 @@ async function rawRequest(config, path, options) {
221
221
  headers["content-type"] = "application/json";
222
222
  body = JSON.stringify(options.json);
223
223
  }
224
+ const response = await sendRequest(fetchImpl, url, {
225
+ method,
226
+ headers,
227
+ body,
228
+ ...(options.signal ? { signal: options.signal } : {}),
229
+ });
224
230
  try {
225
- const response = await fetchImpl(url, {
231
+ config.onResponse?.({
226
232
  method,
227
- headers,
228
- body,
229
- ...(options.signal ? { signal: options.signal } : {}),
233
+ path,
234
+ status: response.status,
235
+ durationMs: performance.now() - startedAt,
236
+ requestId: response.headers.get("x-request-id") ?? undefined,
237
+ ...(clientRequestId === undefined ? {} : { clientRequestId }),
230
238
  });
231
- try {
232
- config.onResponse?.({
233
- method,
234
- path,
235
- status: response.status,
236
- durationMs: performance.now() - startedAt,
237
- requestId: response.headers.get("x-request-id") ?? undefined,
238
- ...(clientRequestId === undefined ? {} : { clientRequestId }),
239
- });
240
- }
241
- catch {
242
- /** Observation must not affect transport or response ownership. */
243
- }
244
- return response;
239
+ }
240
+ catch {
241
+ /** Observation must not affect transport or response ownership. */
242
+ }
243
+ return response;
244
+ }
245
+ /**
246
+ * Calls `fetch` and turns its rejection into a `request_aborted` or
247
+ * `network_error` SDK error.
248
+ * @param fetchImpl - The fetch to call.
249
+ * @param url - Request URL.
250
+ * @param init - Request options.
251
+ * @returns The response, whatever its status.
252
+ */
253
+ export async function sendRequest(fetchImpl, url, init) {
254
+ try {
255
+ return await fetchImpl(url, init);
245
256
  }
246
257
  catch (cause) {
247
- const requestAborted = isRequestAborted(cause, options.signal);
248
- if (requestAborted) {
258
+ if (isRequestAborted(cause, init.signal ?? undefined)) {
249
259
  throw requestAbortedError(cause);
250
260
  }
251
- let message = NETWORK_ERROR_MESSAGE;
252
- if (cause instanceof Error) {
253
- message = cause.message;
254
- }
255
261
  throw new BlazingAgentsError({
256
262
  code: "network_error",
257
- message,
263
+ message: cause instanceof Error ? cause.message : NETWORK_ERROR_MESSAGE,
258
264
  }, { cause });
259
265
  }
260
266
  }
261
267
  /**
262
268
  * Reads bounded diagnostics and decodes a failed HTTP response.
269
+ * @param response - A response with a non-2xx status.
270
+ * @param signal - Signal that cancels the operation.
271
+ * @returns The decoded error, or `invalid_response` when the body is not an error envelope.
263
272
  */
264
- async function errorFromResponse(response, signal) {
273
+ export async function errorFromResponse(response, signal) {
265
274
  const read = await readResponseBody(response, true);
266
275
  if (read.readFailed && isRequestAborted(read.cause, signal)) {
267
276
  return requestAbortedError(read.cause);
@@ -480,8 +489,14 @@ function parseErrorEnvelope(bodyText, status, headers) {
480
489
  }
481
490
  /**
482
491
  * Builds an invalid_response error with bounded diagnostics and request correlation.
492
+ * @param headers - Response headers.
493
+ * @param status - HTTP response status.
494
+ * @param responseBody - Diagnostic body text.
495
+ * @param responseBodyTruncated - Whether the diagnostic body was cut short.
496
+ * @param cause - The parse or validation failure.
497
+ * @returns The invalid_response error.
483
498
  */
484
- function invalidResponseError(headers, status, responseBody, responseBodyTruncated, cause) {
499
+ export function invalidResponseError(headers, status, responseBody, responseBodyTruncated, cause) {
485
500
  return new BlazingAgentsError({
486
501
  code: "invalid_response",
487
502
  headers,
package/dist/index.d.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * `UIMessage` is re-exported from `ai`, never redeclared.
5
5
  */
6
6
  export type { UIMessage } from "ai";
7
- export { BlazingAgentsChatTransport, type BlazingAgentsChatTransportOptions, } from "./chat-transport.ts";
7
+ export { BlazingAgentsChat, type BlazingAgentsChatOptions, type BlazingAgentsChatSnapshot, } from "./chat-controller.ts";
8
+ export { BlazingAgentsChatTransport, type BlazingAgentsChatTransportOptions, type SteerOutcome, } from "./chat-transport.ts";
8
9
  export { BlazingAgents } from "./client.ts";
9
10
  export type { ApprovalDecision, ApprovalPolicy, ToolExecutionReference, ToolReference, } from "./contracts/entities/agent-approval.ts";
10
11
  export { AGENT_TOOL_FILE_ACCESS_TAGS, AGENT_TOOL_GROUPS, AGENT_TOOL_TAGS, AGENT_TOOLS, type AgentToolDefinition, type AgentToolFileAccessTag, type AgentToolGroupTag, type AgentToolName, type AgentToolTag, type AgentToolTags, } from "./contracts/entities/agent-tools.ts";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * `UIMessage` is re-exported from `ai`, never redeclared.
5
5
  */
6
6
  // biome-ignore lint/performance/noBarrelFile: package entry point
7
+ export { BlazingAgentsChat, } from "./chat-controller.js";
7
8
  export { BlazingAgentsChatTransport, } from "./chat-transport.js";
8
9
  export { BlazingAgents } from "./client.js";
9
10
  export { AGENT_TOOL_FILE_ACCESS_TAGS, AGENT_TOOL_GROUPS, AGENT_TOOL_TAGS, AGENT_TOOLS, } from "./contracts/entities/agent-tools.js";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * `@blazingagents/sdk/react`: the browser chat hook. The only entry that
3
+ * imports `react`; `.` and `./rest` never load it.
4
+ */
5
+ export { type UseBlazingAgentsChatOptions, type UseBlazingAgentsChatResult, useBlazingAgentsChat, } from "./use-blazing-agents-chat.ts";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@blazingagents/sdk/react`: the browser chat hook. The only entry that
3
+ * imports `react`; `.` and `./rest` never load it.
4
+ */
5
+ // biome-ignore lint/performance/noBarrelFile: package entry point
6
+ export { useBlazingAgentsChat, } from "./use-blazing-agents-chat.js";
@@ -0,0 +1,19 @@
1
+ import type { UIMessage } from "ai";
2
+ import { BlazingAgentsChat, type BlazingAgentsChatOptions, type BlazingAgentsChatSnapshot } from "../chat-controller.ts";
3
+ import type { BlazingAgentsUIMessage } from "../types.ts";
4
+ export type UseBlazingAgentsChatOptions = Omit<BlazingAgentsChatOptions, "headers"> & {
5
+ /** Request headers, read at each request. */
6
+ headers?: Record<string, string> | Headers;
7
+ };
8
+ /** The chat's snapshot and its actions; see `BlazingAgentsChat`. */
9
+ export type UseBlazingAgentsChatResult<M extends UIMessage = BlazingAgentsUIMessage> = BlazingAgentsChatSnapshot<M> & Pick<BlazingAgentsChat<M>, "addToolApprovalResponse" | "clearError" | "newSession" | "regenerate" | "send" | "stop">;
10
+ /**
11
+ * A Blazing Agents chat through the app's relay: one `BlazingAgentsChat` per
12
+ * component, started after mount and disposed on unmount. New `headers`, or
13
+ * new values in the same `Headers` object, apply to the next request, even one
14
+ * a child's effect sends in the same commit; the other options are read on the
15
+ * first render.
16
+ * @param options - Relay endpoint, request options, and storage key.
17
+ * @returns The chat's snapshot and its actions.
18
+ */
19
+ export declare function useBlazingAgentsChat<M extends UIMessage = BlazingAgentsUIMessage>(options?: UseBlazingAgentsChatOptions): UseBlazingAgentsChatResult<M>;
@@ -0,0 +1,33 @@
1
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
2
+ import { BlazingAgentsChat, } from "../chat-controller.js";
3
+ /**
4
+ * A Blazing Agents chat through the app's relay: one `BlazingAgentsChat` per
5
+ * component, started after mount and disposed on unmount. New `headers`, or
6
+ * new values in the same `Headers` object, apply to the next request, even one
7
+ * a child's effect sends in the same commit; the other options are read on the
8
+ * first render.
9
+ * @param options - Relay endpoint, request options, and storage key.
10
+ * @returns The chat's snapshot and its actions.
11
+ */
12
+ export function useBlazingAgentsChat(options = {}) {
13
+ const headers = useRef(options.headers);
14
+ headers.current = options.headers;
15
+ const [readHeaders] = useState(() => () => headers.current ?? {});
16
+ const [chat] = useState(() => new BlazingAgentsChat({ ...options, headers: readHeaders }));
17
+ const snapshot = useSyncExternalStore(chat.subscribe, chat.getSnapshot, chat.getSnapshot);
18
+ useEffect(() => {
19
+ chat.start();
20
+ return chat.dispose;
21
+ }, [chat]);
22
+ // After every commit, since header values can change inside the same object.
23
+ useEffect(() => chat.setHeaders(readHeaders));
24
+ return useMemo(() => ({
25
+ ...snapshot,
26
+ addToolApprovalResponse: chat.addToolApprovalResponse,
27
+ clearError: chat.clearError,
28
+ newSession: chat.newSession,
29
+ regenerate: chat.regenerate,
30
+ send: chat.send,
31
+ stop: chat.stop,
32
+ }), [chat, snapshot]);
33
+ }
package/dist/relay.d.ts CHANGED
@@ -29,13 +29,19 @@ interface RelayOptions<Method extends keyof UserClient> {
29
29
  resolveContext(request: Request): Promise<RelayContext | null>;
30
30
  }
31
31
  /**
32
- * Relays useChat submissions as the signed-in End-user. An assistant message
33
- * carrying approval responses submits the complete round and streams the
34
- * continuation.
32
+ * The browser's one endpoint for a chat, answered as the signed-in End-user.
33
+ * The JSON body's `op` selects the operation: `chat` streams a Turn, `history`
34
+ * returns one page of the Session's stored messages, and `steer` sends a user
35
+ * message into the Turn running now.
36
+ *
37
+ * Every error body is `{ error: { code, message } }`: 400 `invalid_request`
38
+ * for a malformed body or an unknown `op`, 401 `unauthorized`, the API's own
39
+ * status and code (such as 404 `not_found` or 409 `steer_not_available`), 499
40
+ * when the browser aborts, 502 for other SDK failures, and 500 otherwise.
35
41
  * @param options - Configuration for this operation.
36
42
  * @returns An HTTP handler that runs each request through `client.forUser(context.userId)`, so the API answers 404 for a Session outside that End-user's scope.
37
43
  */
38
- export declare function createChatRelay(options: RelayOptions<"chat" | "continueChat">): (request: Request) => Promise<Response>;
44
+ export declare function createChatRelay(options: RelayOptions<"chat" | "continueChat" | "sessions">): (request: Request) => Promise<Response>;
39
45
  /**
40
46
  * Creates an authenticated HTTP handler that validates prompts and relays text generation as the signed-in End-user.
41
47
  * @param options - Configuration for this operation.
package/dist/relay.js CHANGED
@@ -1,21 +1,19 @@
1
1
  import { safeValidateUIMessages } from "ai";
2
2
  import { z } from "zod";
3
3
  import { extractApprovalDecisions } from "./approvals.js";
4
- import { sessionIdSchema } from "./contracts/ids.js";
4
+ import { RELAY_HISTORY_PAGE_SIZE, relayRequestSchema, } from "./chat-relay-wire.js";
5
5
  import { BlazingAgentsError } from "./errors.js";
6
- const chatBodySchema = z.object({
7
- message: z.unknown(),
8
- messageId: z.string().min(1).optional(),
9
- sessionId: sessionIdSchema.optional(),
10
- trigger: z
11
- .enum(["submit-message", "regenerate-message"])
12
- .default("submit-message"),
13
- });
14
6
  const completionBodySchema = z.object({ prompt: z.string().trim().min(1) });
15
7
  /**
16
- * Relays useChat submissions as the signed-in End-user. An assistant message
17
- * carrying approval responses submits the complete round and streams the
18
- * continuation.
8
+ * The browser's one endpoint for a chat, answered as the signed-in End-user.
9
+ * The JSON body's `op` selects the operation: `chat` streams a Turn, `history`
10
+ * returns one page of the Session's stored messages, and `steer` sends a user
11
+ * message into the Turn running now.
12
+ *
13
+ * Every error body is `{ error: { code, message } }`: 400 `invalid_request`
14
+ * for a malformed body or an unknown `op`, 401 `unauthorized`, the API's own
15
+ * status and code (such as 404 `not_found` or 409 `steer_not_available`), 499
16
+ * when the browser aborts, 502 for other SDK failures, and 500 otherwise.
19
17
  * @param options - Configuration for this operation.
20
18
  * @returns An HTTP handler that runs each request through `client.forUser(context.userId)`, so the API answers 404 for a Session outside that End-user's scope.
21
19
  */
@@ -27,62 +25,110 @@ export function createChatRelay(options) {
27
25
  return errorResponse(401, "unauthorized", "Authentication required.");
28
26
  }
29
27
  const client = scopeTo(options.client, context.userId);
30
- const body = chatBodySchema.parse(await request.json());
31
- const validated = await safeValidateUIMessages({
32
- messages: [body.message],
33
- });
34
- if (!validated.success) {
35
- return errorResponse(400, "invalid_request", "Invalid chat message.");
36
- }
37
- const message = validated.data[0];
38
- if (message.role === "assistant") {
39
- return await relayApprovalResponses(client, {
40
- agentId: context.agentId,
41
- functions: context.functions,
42
- message,
43
- request,
44
- sessionId: body.sessionId,
45
- });
46
- }
47
- if (message.role !== "user") {
48
- return errorResponse(400, "invalid_request", "Chat submission requires a user message.");
49
- }
50
- const chatInput = {
51
- agentId: context.agentId,
52
- functions: context.functions,
53
- message,
54
- messageId: body.messageId,
55
- metadata: context.metadata,
56
- abortSignal: request.signal,
57
- };
58
- const result = await client.chat(body.sessionId === undefined
59
- ? {
60
- ...chatInput,
61
- trigger: "submit-message",
62
- }
63
- : {
64
- ...chatInput,
65
- sessionId: body.sessionId,
66
- trigger: body.trigger,
67
- });
68
- return result.toResponse();
28
+ const body = relayRequestSchema.parse(await request.json());
29
+ return await answer(client, context, body, request.signal);
69
30
  }
70
31
  catch (error) {
71
32
  return safeErrorResponse(error);
72
33
  }
73
34
  };
74
35
  }
36
+ function answer(client, context, body, signal) {
37
+ switch (body.op) {
38
+ case "chat":
39
+ return relayChat(client, context, body, signal);
40
+ case "history":
41
+ return relayHistoryPage(client, context.agentId, body, signal);
42
+ case "steer":
43
+ return relaySteer(client, context.agentId, body, signal);
44
+ }
45
+ }
46
+ async function relayChat(client, context, body, signal) {
47
+ const validated = await safeValidateUIMessages({
48
+ messages: [body.message],
49
+ });
50
+ if (!validated.success) {
51
+ return errorResponse(400, "invalid_request", "Invalid chat message.");
52
+ }
53
+ const message = validated.data[0];
54
+ if (message.role === "assistant") {
55
+ return await relayApprovalResponses(client, {
56
+ agentId: context.agentId,
57
+ functions: context.functions,
58
+ message,
59
+ signal,
60
+ sessionId: body.sessionId,
61
+ });
62
+ }
63
+ if (message.role !== "user") {
64
+ return errorResponse(400, "invalid_request", "Chat submission requires a user message.");
65
+ }
66
+ const chatInput = {
67
+ agentId: context.agentId,
68
+ functions: context.functions,
69
+ message,
70
+ messageId: body.messageId,
71
+ metadata: context.metadata,
72
+ abortSignal: signal,
73
+ };
74
+ const result = await client.chat(body.sessionId === undefined
75
+ ? {
76
+ ...chatInput,
77
+ trigger: "submit-message",
78
+ }
79
+ : {
80
+ ...chatInput,
81
+ sessionId: body.sessionId,
82
+ trigger: body.trigger,
83
+ });
84
+ return result.toResponse();
85
+ }
86
+ /**
87
+ * One page of stored messages, passed through without paging or message
88
+ * validation, so a relay in any language stays a pass-through. The browser
89
+ * walks the pages and validates them.
90
+ */
91
+ async function relayHistoryPage(client, agentId, body, signal) {
92
+ const page = await client.sessions.messages({
93
+ agentId,
94
+ sessionId: body.sessionId,
95
+ cursor: body.cursor,
96
+ limit: RELAY_HISTORY_PAGE_SIZE,
97
+ abortSignal: signal,
98
+ });
99
+ return Response.json({
100
+ data: page.data,
101
+ nextCursor: page.nextCursor,
102
+ });
103
+ }
104
+ /** A 409 `steer_not_available` passes through; the browser resends the message as chat. */
105
+ async function relaySteer(client, agentId, body, signal) {
106
+ const validated = await safeValidateUIMessages({
107
+ messages: [body.message],
108
+ });
109
+ if (!validated.success || validated.data[0].role !== "user") {
110
+ return errorResponse(400, "invalid_request", "Steering requires a user message.");
111
+ }
112
+ const receipt = await client.sessions.submitInput({
113
+ agentId,
114
+ sessionId: body.sessionId,
115
+ requestId: body.requestId,
116
+ message: validated.data[0],
117
+ abortSignal: signal,
118
+ });
119
+ return Response.json({ state: receipt.data.state }, { status: 202 });
120
+ }
75
121
  /**
76
122
  * Forwards the last assistant approval round to its Session.
77
123
  */
78
- async function relayApprovalResponses(client, { functions, message, request, ...input }) {
124
+ async function relayApprovalResponses(client, { functions, message, signal, ...input }) {
79
125
  if (input.sessionId === undefined) {
80
126
  return errorResponse(400, "invalid_request", "Tool approval requires an existing Session.");
81
127
  }
82
128
  const target = {
83
129
  agentId: input.agentId,
84
130
  sessionId: input.sessionId,
85
- abortSignal: request.signal,
131
+ abortSignal: signal,
86
132
  };
87
133
  const decisions = extractApprovalDecisions(message);
88
134
  if (decisions.length === 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazingagents/sdk",
3
- "version": "0.51.0",
3
+ "version": "0.53.0",
4
4
  "description": "TypeScript SDK for the Blazing Agents API",
5
5
  "homepage": "https://docs.blazingagents.com",
6
6
  "bugs": {
@@ -25,6 +25,10 @@
25
25
  "./rest": {
26
26
  "types": "./dist/rest.d.ts",
27
27
  "import": "./dist/rest.js"
28
+ },
29
+ "./react": {
30
+ "types": "./dist/react/index.d.ts",
31
+ "import": "./dist/react/index.js"
28
32
  }
29
33
  },
30
34
  "types": "./dist/index.d.ts",
@@ -34,7 +38,8 @@
34
38
  ],
35
39
  "scripts": {
36
40
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
37
- "check": "npm run typecheck && npm run test && npm run lint && npm run unused",
41
+ "bundle-size": "node scripts/check-bundle-size.ts",
42
+ "check": "npm run typecheck && npm run test && npm run bundle-size && npm run lint && npm run unused",
38
43
  "fix": "ultracite fix",
39
44
  "lint": "ultracite check",
40
45
  "prepack": "npm run build",
@@ -43,16 +48,20 @@
43
48
  "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.tests.json",
44
49
  "unused": "knip && knip --production --include exports,types,duplicates"
45
50
  },
46
- "dependencies": {
47
- "croner": "10.0.1"
48
- },
49
51
  "devDependencies": {
50
52
  "@biomejs/biome": "^2.5.8",
53
+ "@testing-library/react": "^16.3.3",
51
54
  "@types/json-schema": "7.0.15",
52
55
  "@types/node": "^26.4.0",
56
+ "@types/react": "^19.2.7",
57
+ "@types/react-dom": "^19.2.3",
53
58
  "@vitest/coverage-v8": "^4.1.10",
54
59
  "ai": "^7.0.84",
60
+ "esbuild": "0.28.2",
61
+ "happy-dom": "^20.14.6",
55
62
  "knip": "^6.41.0",
63
+ "react": "^19.2.4",
64
+ "react-dom": "^19.2.4",
56
65
  "typescript": "^7.0.2",
57
66
  "ultracite": "^7.10.2",
58
67
  "vitest": "^4.1.10",
@@ -60,8 +69,14 @@
60
69
  },
61
70
  "peerDependencies": {
62
71
  "ai": "^7.0.84",
72
+ "react": "^18 || ^19",
63
73
  "zod": "^4.5.4"
64
74
  },
75
+ "peerDependenciesMeta": {
76
+ "react": {
77
+ "optional": true
78
+ }
79
+ },
65
80
  "engines": {
66
81
  "node": ">=24"
67
82
  },