@blazingagents/sdk 0.50.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,246 @@
1
+ import { Chat, useChat } from "@ai-sdk/react";
2
+ import { generateId, lastAssistantMessageIsCompleteWithApprovalResponses, } from "ai";
3
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
4
+ import { BlazingAgentsChatTransport } from "../chat-transport.js";
5
+ import { sessionIdSchema } from "../contracts/ids.js";
6
+ import { BlazingAgentsError } from "../errors.js";
7
+ import { canRegenerate, initialChatState, pendingIds, step, } from "./chat-state.js";
8
+ const DEFAULT_STORAGE_KEY = "blazing-agents-session";
9
+ /**
10
+ * A Blazing Agents chat through the app's relay, with the Session kept in
11
+ * localStorage, history restored after a reload, steering while a reply
12
+ * streams, and rollback on failure.
13
+ * @param options - Relay endpoint, request options, and storage key.
14
+ * @returns The chat; see `BlazingAgentsChat`.
15
+ */
16
+ export function useBlazingAgentsChat(options = {}) {
17
+ const latest = useRef(options);
18
+ latest.current = options;
19
+ const [store] = useState(() => createChatStore(latest));
20
+ const { conversation, sessionId, state } = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
21
+ const { messages: shown } = useChat({ chat: conversation.chat });
22
+ const credentialsKey = headersKey(options.headers);
23
+ useEffect(() => {
24
+ store.mount();
25
+ return store.unmount;
26
+ }, [store]);
27
+ useEffect(() => {
28
+ store.credentialsChanged(credentialsKey);
29
+ }, [store, credentialsKey]);
30
+ const messages = useMemo(() => {
31
+ const ids = new Set(shown.map((message) => message.id));
32
+ return [
33
+ ...shown,
34
+ ...state.outbox
35
+ .map((entry) => entry.message)
36
+ .filter((message) => !ids.has(message.id)),
37
+ ];
38
+ }, [shown, state.outbox]);
39
+ const pending = useMemo(() => pendingIds(state), [state]);
40
+ return {
41
+ addToolApprovalResponse: store.addToolApprovalResponse,
42
+ canRegenerate: canRegenerate(state),
43
+ clearError: store.clearError,
44
+ error: state.error,
45
+ messages,
46
+ newSession: store.newSession,
47
+ pendingIds: pending,
48
+ regenerate: store.regenerate,
49
+ send: store.send,
50
+ sessionId,
51
+ status: statusOf(state),
52
+ stop: store.stop,
53
+ };
54
+ }
55
+ function statusOf(state) {
56
+ if (state.phase.kind === "restoring" || state.phase.kind === "idle") {
57
+ return state.phase.kind;
58
+ }
59
+ return "running";
60
+ }
61
+ /** Runs one localStorage call. Where storage throws, as when the browser blocks it or it is full, the Session lives in memory only. */
62
+ function tryStorage(use) {
63
+ try {
64
+ return use(localStorage);
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ }
70
+ /** Header values as one comparable string, so a re-created but equal object is no change. */
71
+ function headersKey(headers) {
72
+ return JSON.stringify([...new Headers(headers)]);
73
+ }
74
+ /**
75
+ * Holds `ChatState` and the current conversation, runs `step` synchronously
76
+ * (so two sends in one tick see different states), then runs its effects.
77
+ */
78
+ function createChatStore(options) {
79
+ const listeners = new Set();
80
+ const settlers = new Map();
81
+ let credentials = headersKey(options.current.headers);
82
+ let epoch = 0;
83
+ let state = initialChatState;
84
+ let conversation = open(undefined);
85
+ let snapshot = { conversation, sessionId: undefined, state };
86
+ function storageKey() {
87
+ return options.current.storageKey === undefined
88
+ ? DEFAULT_STORAGE_KEY
89
+ : options.current.storageKey;
90
+ }
91
+ function publish() {
92
+ snapshot = {
93
+ conversation,
94
+ sessionId: conversation.transport.sessionId,
95
+ state,
96
+ };
97
+ for (const listener of listeners) {
98
+ listener();
99
+ }
100
+ }
101
+ function open(sessionId) {
102
+ epoch += 1;
103
+ const opened = epoch;
104
+ const transport = new BlazingAgentsChatTransport({
105
+ api: options.current.api,
106
+ credentials: options.current.credentials,
107
+ fetch: options.current.fetch,
108
+ headers: () => options.current.headers ?? {},
109
+ onSessionId: (id) => {
110
+ const key = storageKey();
111
+ if (key !== null) {
112
+ tryStorage((storage) => storage.setItem(key, id));
113
+ }
114
+ publish();
115
+ },
116
+ onSteerConsumed: (requestId) => dispatch({ type: "steerConsumed", requestId }, opened),
117
+ onTurnFinish: () => dispatch({ type: "turnFinished" }, opened),
118
+ onTurnStart: () => dispatch({ type: "turnStarted" }, opened),
119
+ sessionId,
120
+ });
121
+ const chat = new Chat({
122
+ id: `blazing-agents-${opened}`,
123
+ onFinish: (event) => dispatch({ type: "turnEnded", result: turnResult(event, chat) }, opened),
124
+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
125
+ transport,
126
+ });
127
+ return { chat, epoch: opened, transport };
128
+ }
129
+ function dispatch(event, from = epoch) {
130
+ if (from !== epoch) {
131
+ return;
132
+ }
133
+ const next = step(state, event, generateId);
134
+ state = next.state;
135
+ publish();
136
+ for (const effect of next.effects) {
137
+ run(effect);
138
+ }
139
+ }
140
+ function run(effect) {
141
+ const { chat, transport, epoch: at } = conversation;
142
+ switch (effect.type) {
143
+ case "startTurn":
144
+ chat.sendMessage(effect.message);
145
+ return;
146
+ case "regenerate":
147
+ chat.regenerate();
148
+ return;
149
+ case "submitSteer":
150
+ transport
151
+ .steer({ message: effect.message, requestId: effect.requestId })
152
+ .then((outcome) => dispatch({ type: "steerAnswered", requestId: effect.requestId, outcome }, at), (error) => dispatch({
153
+ type: "steerFailed",
154
+ requestId: effect.requestId,
155
+ error,
156
+ answerLost: BlazingAgentsError.isInstance(error) &&
157
+ error.code === "network_error",
158
+ }, at));
159
+ return;
160
+ case "show":
161
+ chat.messages = effect.messages;
162
+ return;
163
+ case "loadHistory":
164
+ transport.loadHistory().then((messages) => dispatch({ type: "historyLoaded", messages }, at), (error) => dispatch({ type: "historyFailed", error, sessionGone: sessionGone(error) }, at));
165
+ return;
166
+ case "abort":
167
+ chat.stop();
168
+ return;
169
+ case "forgetSession": {
170
+ const key = storageKey();
171
+ if (key !== null) {
172
+ tryStorage((storage) => storage.removeItem(key));
173
+ }
174
+ conversation = open(undefined);
175
+ publish();
176
+ return;
177
+ }
178
+ case "settle":
179
+ settlers.get(effect.key)?.(effect.landed);
180
+ settlers.delete(effect.key);
181
+ return;
182
+ }
183
+ }
184
+ return {
185
+ subscribe(listener) {
186
+ listeners.add(listener);
187
+ return () => listeners.delete(listener);
188
+ },
189
+ getSnapshot: () => snapshot,
190
+ mount() {
191
+ const key = storageKey();
192
+ const stored = sessionIdSchema.safeParse(key === null ? null : tryStorage((storage) => storage.getItem(key)));
193
+ // A remount keeps the Session in memory when storage holds none.
194
+ conversation = open(stored.success ? stored.data : conversation.transport.sessionId);
195
+ publish();
196
+ dispatch({ type: "restore" });
197
+ },
198
+ unmount: () => dispatch({ type: "unmount" }),
199
+ credentialsChanged(key) {
200
+ if (key !== credentials) {
201
+ credentials = key;
202
+ dispatch({ type: "credentialsChanged" });
203
+ }
204
+ },
205
+ send(input) {
206
+ const { files = [], text } = typeof input === "string" ? { text: input } : input;
207
+ const message = {
208
+ id: generateId(),
209
+ role: "user",
210
+ parts: [...files, { type: "text", text }],
211
+ };
212
+ return new Promise((resolve) => {
213
+ settlers.set(message.id, resolve);
214
+ dispatch({ type: "send", sent: { key: message.id, message } });
215
+ });
216
+ },
217
+ regenerate: () => dispatch({ type: "regenerate" }),
218
+ stop: () => dispatch({ type: "stop" }),
219
+ newSession: () => dispatch({ type: "newSession" }),
220
+ clearError: () => dispatch({ type: "clearError" }),
221
+ addToolApprovalResponse(response) {
222
+ const { chat, epoch: at } = conversation;
223
+ Promise.resolve(chat.addToolApprovalResponse(response)).then(() => {
224
+ if (lastAssistantMessageIsCompleteWithApprovalResponses({
225
+ messages: chat.messages,
226
+ })) {
227
+ dispatch({ type: "approvalAnswered" }, at);
228
+ }
229
+ });
230
+ },
231
+ };
232
+ }
233
+ function turnResult({ finishReason, isAbort, isError, messages, }, chat) {
234
+ if (isAbort) {
235
+ return { outcome: "stopped" };
236
+ }
237
+ if (isError || finishReason === "error") {
238
+ const error = chat.error ?? new Error("The reply failed.");
239
+ return { outcome: "failed", error, sessionGone: sessionGone(error) };
240
+ }
241
+ return { outcome: "closed", messages };
242
+ }
243
+ /** The relay answers 404 for a deleted Session or another End-user's. */
244
+ function sessionGone(error) {
245
+ return BlazingAgentsError.isInstance(error) && error.status === 404;
246
+ }
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) {
@@ -149,7 +195,7 @@ function safeErrorResponse(error) {
149
195
  if (requestId) {
150
196
  headers.set("x-request-id", requestId);
151
197
  }
152
- return errorResponse(status, error.code, error.message.slice(`[${error.code}] `.length), headers);
198
+ return errorResponse(status, error.code, error.message, headers);
153
199
  }
154
200
  return errorResponse(500, "internal_error", "Request failed.");
155
201
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazingagents/sdk",
3
- "version": "0.50.0",
3
+ "version": "0.52.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",
@@ -47,21 +51,38 @@
47
51
  "croner": "10.0.1"
48
52
  },
49
53
  "devDependencies": {
54
+ "@ai-sdk/react": "^4.0.90",
50
55
  "@biomejs/biome": "^2.5.8",
56
+ "@testing-library/react": "^16.3.3",
51
57
  "@types/json-schema": "7.0.15",
52
58
  "@types/node": "^26.4.0",
59
+ "@types/react": "^19.2.7",
60
+ "@types/react-dom": "^19.2.3",
53
61
  "@vitest/coverage-v8": "^4.1.10",
54
62
  "ai": "^7.0.84",
63
+ "happy-dom": "^20.14.6",
55
64
  "knip": "^6.41.0",
65
+ "react": "^19.2.4",
66
+ "react-dom": "^19.2.4",
56
67
  "typescript": "^7.0.2",
57
68
  "ultracite": "^7.10.2",
58
69
  "vitest": "^4.1.10",
59
70
  "zod": "4.5.4"
60
71
  },
61
72
  "peerDependencies": {
73
+ "@ai-sdk/react": "^4.0.87",
62
74
  "ai": "^7.0.84",
75
+ "react": "^18 || ^19",
63
76
  "zod": "^4.5.4"
64
77
  },
78
+ "peerDependenciesMeta": {
79
+ "@ai-sdk/react": {
80
+ "optional": true
81
+ },
82
+ "react": {
83
+ "optional": true
84
+ }
85
+ },
65
86
  "engines": {
66
87
  "node": ">=24"
67
88
  },