@blazingagents/sdk 0.54.0 → 0.54.1

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
@@ -219,6 +219,14 @@ snapshot also holds `status`, `pendingIds`, `sessionId`, `canRegenerate`, and
219
219
  `headers` as a function that returns the current ones, or pass new `headers`
220
220
  to the hook.
221
221
 
222
+ Every chat on an origin keeps its Session under the same `localStorage` key,
223
+ `blazing-agents-session`, unless you pass `storageKey`. An app with several
224
+ Agents, or with several End-users who sign in on the same browser, passes a
225
+ `storageKey` per Agent and End-user, such as `chat:${agentId}:${userId}`. When
226
+ the signed-in End-user changes, create a new chat: in React, remount the
227
+ component that calls the hook with `key={userId}`, since the hook reads
228
+ `storageKey` on the first render only.
229
+
222
230
  `BlazingAgentsChatTransport` is the transport alone, for an AI SDK `Chat` that
223
231
  you run yourself. A relay written in another language follows the
224
232
  [browser relay contract](docs/relay-contract.md).
@@ -11,7 +11,11 @@ export interface BlazingAgentsChatOptions {
11
11
  * localStorage key for the Session ID. Default `blazing-agents-session`;
12
12
  * `null` keeps the Session in memory only, as does storage that throws.
13
13
  * Read by `start()`, never by the constructor, so server rendering never
14
- * touches storage.
14
+ * touches storage. The default key is shared by every chat on the origin:
15
+ * an app with several Agents, or several End-users signing in on one
16
+ * browser, passes a key per Agent and End-user, such as
17
+ * `chat:${agentId}:${userId}`, and creates a new chat when the signed-in
18
+ * End-user changes.
15
19
  */
16
20
  storageKey?: string | null;
17
21
  }
@@ -32,9 +36,10 @@ export interface BlazingAgentsChatSnapshot<M extends UIMessage = BlazingAgentsUI
32
36
  readonly sessionId: string | undefined;
33
37
  /**
34
38
  * `restoring`: reading the stored transcript, or, after that read failed
35
- * (see `error`), waiting for new headers, a `send`, or `clearError` to read
36
- * it again. `running`: a Turn is starting, streaming, or being placed in
37
- * stored history. `send` works in every status.
39
+ * (see `error`) and rolled back the messages sent during it, waiting for new
40
+ * headers, a `send`, or `clearError` to read it again. `running`: a Turn is
41
+ * starting, streaming, or being placed in stored history. `send` works in
42
+ * every status.
38
43
  */
39
44
  readonly status: "restoring" | "idle" | "running";
40
45
  }
@@ -355,7 +355,13 @@ function turnResult({ finishReason, isAbort, isError, messages, }, chat) {
355
355
  }
356
356
  return { outcome: "closed", messages };
357
357
  }
358
- /** The relay answers 404 for a deleted Session or another End-user's. */
358
+ /**
359
+ * The relay answers 404 `not_found` for a deleted Session or another
360
+ * End-user's. Other 404 codes, such as `provider_not_found`, name a missing
361
+ * resource the Session still points at.
362
+ */
359
363
  function sessionGone(error) {
360
- return BlazingAgentsError.isInstance(error) && error.status === 404;
364
+ return (BlazingAgentsError.isInstance(error) &&
365
+ error.status === 404 &&
366
+ error.code === "not_found");
361
367
  }
@@ -79,7 +79,7 @@ export interface ChatState<M extends UIMessage> {
79
79
  /**
80
80
  * How the AI SDK chat's request ended. `closed`: without an error or a Stop; the Turn
81
81
  * completed only if its stream carried `finish`. `sessionGone`: the relay
82
- * answered 404, so the Session is deleted or another End-user's.
82
+ * answered 404 `not_found`, so the Session is deleted or another End-user's.
83
83
  */
84
84
  export type TurnResult<M extends UIMessage> = {
85
85
  outcome: "closed";
@@ -101,7 +101,7 @@ export type ChatEvent<M extends UIMessage> =
101
101
  type: "historyLoaded";
102
102
  messages: M[];
103
103
  }
104
- /** `sessionGone`: the relay answered 404, so the Session is deleted or another End-user's. */
104
+ /** `sessionGone`: the relay answered 404 `not_found`, so the Session is deleted or another End-user's. */
105
105
  | {
106
106
  type: "historyFailed";
107
107
  error: Error;
@@ -190,16 +190,22 @@ function historyFailed(state, { error, sessionGone }) {
190
190
  effects: [{ type: "forgetSession" }],
191
191
  };
192
192
  }
193
+ // Messages sent before the read failed roll back with it; otherwise a
194
+ // restore that keeps failing would leave their `send()` waiting forever.
193
195
  return phase.load === "stale"
194
196
  ? {
195
197
  state: { ...state, phase: { kind: "restoring", load: "running" } },
196
198
  effects: [{ type: "loadHistory", known: [] }],
197
199
  }
198
- : noEffects({
199
- ...state,
200
- error,
201
- phase: { kind: "restoring", load: "failed" },
202
- });
200
+ : {
201
+ state: {
202
+ ...state,
203
+ error,
204
+ outbox: [],
205
+ phase: { kind: "restoring", load: "failed" },
206
+ },
207
+ effects: settlePending(state),
208
+ };
203
209
  }
204
210
  if (phase.kind === "reconciling") {
205
211
  // A completed Turn stored its steers, but where they sit is unknown; append
@@ -238,13 +244,42 @@ function turnEnded(state, result, newId) {
238
244
  effects: [...settlePending(state), { type: "forgetSession" }],
239
245
  };
240
246
  }
247
+ if (phase.kind === "starting" && !phase.prompt) {
248
+ // A failed approval continuation or regenerate stored nothing, but the
249
+ // Session may have moved on without it, as when another client decided
250
+ // the approval (409), and steers the finished Turn read are still unplaced.
251
+ // Stored history decides; queued messages wait for it.
252
+ return {
253
+ state: {
254
+ ...state,
255
+ error,
256
+ outbox: state.outbox.map((entry) => entry.stage === "accepted" ? resend(entry, newId) : entry),
257
+ phase: { kind: "reconciling" },
258
+ },
259
+ effects: [
260
+ { type: "show", messages: state.completed },
261
+ { type: "loadHistory", known: state.completed },
262
+ ],
263
+ };
264
+ }
241
265
  if (phase.kind === "starting") {
242
- // The relay never answered with a stream, so the Turn stored nothing.
266
+ // The relay never answered with a stream, so the prompt and the messages
267
+ // queued behind it roll back. Steers sent into the Turn before it are not
268
+ // this request's: as at that Turn's end, an accepted one is resent, and a
269
+ // read one waits for stored history.
270
+ const unsent = state.outbox.filter((entry) => entry.stage === "waiting");
243
271
  return {
244
- state: { ...state, error, outbox: [], phase: { kind: "idle" } },
272
+ state: {
273
+ ...state,
274
+ error,
275
+ outbox: state.outbox
276
+ .filter((entry) => entry.stage !== "waiting")
277
+ .map((entry) => entry.stage === "accepted" ? resend(entry, newId) : entry),
278
+ phase: { kind: "idle" },
279
+ },
245
280
  effects: [
246
281
  { type: "show", messages: state.completed },
247
- ...settlePending(state),
282
+ ...settlePending({ ...state, outbox: unsent }),
248
283
  ],
249
284
  };
250
285
  }
@@ -12,7 +12,9 @@ export type UseBlazingAgentsChatResult<M extends UIMessage = BlazingAgentsUIMess
12
12
  * component, started after mount and disposed on unmount. New `headers`, or
13
13
  * new values in the same `Headers` object, apply to the next request, even one
14
14
  * a child's effect sends in the same commit; the other options are read on the
15
- * first render.
15
+ * first render. So pass a `storageKey` per Agent and End-user when the origin
16
+ * has more than one, and remount the component with `key={userId}` when the
17
+ * signed-in End-user changes.
16
18
  * @param options - Relay endpoint, request options, and storage key.
17
19
  * @returns The chat's snapshot and its actions.
18
20
  */
@@ -5,7 +5,9 @@ import { BlazingAgentsChat, } from "../chat-controller.js";
5
5
  * component, started after mount and disposed on unmount. New `headers`, or
6
6
  * new values in the same `Headers` object, apply to the next request, even one
7
7
  * a child's effect sends in the same commit; the other options are read on the
8
- * first render.
8
+ * first render. So pass a `storageKey` per Agent and End-user when the origin
9
+ * has more than one, and remount the component with `key={userId}` when the
10
+ * signed-in End-user changes.
9
11
  * @param options - Relay endpoint, request options, and storage key.
10
12
  * @returns The chat's snapshot and its actions.
11
13
  */
package/dist/relay.d.ts CHANGED
@@ -23,7 +23,7 @@ interface RelayOptions<Method extends keyof UserClient> {
23
23
  };
24
24
  /**
25
25
  * Resolves authenticated Agent and end-user context, or null for an unauthenticated request.
26
- * @param request - Incoming HTTP request.
26
+ * @param request - Incoming HTTP request. Its body is unread, so the resolver may read extras the browser sent in it; the relay parses its own copy.
27
27
  * @returns Authenticated context, or null when authentication fails.
28
28
  */
29
29
  resolveContext(request: Request): Promise<RelayContext | null>;
@@ -37,7 +37,8 @@ interface RelayOptions<Method extends keyof UserClient> {
37
37
  * Every error body is `{ error: { code, message } }`: 400 `invalid_request`
38
38
  * for a malformed body or an unknown `op`, 401 `unauthorized`, the API's own
39
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.
40
+ * when the browser aborts, 502 for other SDK failures (with a fixed message for
41
+ * `network_error` and `stream_error`), and 500 otherwise.
41
42
  * @param options - Configuration for this operation.
42
43
  * @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.
43
44
  */
package/dist/relay.js CHANGED
@@ -13,19 +13,22 @@ const completionBodySchema = z.object({ prompt: z.string().trim().min(1) });
13
13
  * Every error body is `{ error: { code, message } }`: 400 `invalid_request`
14
14
  * for a malformed body or an unknown `op`, 401 `unauthorized`, the API's own
15
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.
16
+ * when the browser aborts, 502 for other SDK failures (with a fixed message for
17
+ * `network_error` and `stream_error`), and 500 otherwise.
17
18
  * @param options - Configuration for this operation.
18
19
  * @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.
19
20
  */
20
21
  export function createChatRelay(options) {
21
22
  return async (request) => {
22
23
  try {
24
+ // The resolver may read the body too, so the relay reads its own copy.
25
+ const copy = request.clone();
23
26
  const context = await options.resolveContext(request);
24
27
  if (!context) {
25
28
  return errorResponse(401, "unauthorized", "Authentication required.");
26
29
  }
27
30
  const client = scopeTo(options.client, context.userId);
28
- const body = relayRequestSchema.parse(await request.json());
31
+ const body = relayRequestSchema.parse(await copy.json());
29
32
  return await answer(client, context, body, request.signal);
30
33
  }
31
34
  catch (error) {
@@ -149,12 +152,13 @@ async function relayApprovalResponses(client, { functions, message, signal, ...i
149
152
  export function createCompletionRelay(options) {
150
153
  return async (request) => {
151
154
  try {
155
+ const copy = request.clone();
152
156
  const context = await options.resolveContext(request);
153
157
  if (!context) {
154
158
  return errorResponse(401, "unauthorized", "Authentication required.");
155
159
  }
156
160
  const client = scopeTo(options.client, context.userId);
157
- const body = completionBodySchema.parse(await request.json());
161
+ const body = completionBodySchema.parse(await copy.json());
158
162
  const result = await client.completion({
159
163
  agentId: context.agentId,
160
164
  metadata: context.metadata,
@@ -181,6 +185,11 @@ function scopeTo(client, userId) {
181
185
  throw new Error("The relay context has an invalid userId.", { cause });
182
186
  }
183
187
  }
188
+ /** Fixed messages for failures whose SDK message can carry the transport's own text, such as an internal host name. */
189
+ const TRANSPORT_ERROR_MESSAGES = {
190
+ network_error: "The API could not be reached.",
191
+ stream_error: "The API response stream failed.",
192
+ };
184
193
  /**
185
194
  * Maps validation and SDK failures to safe public error responses.
186
195
  */
@@ -195,7 +204,7 @@ function safeErrorResponse(error) {
195
204
  if (requestId) {
196
205
  headers.set("x-request-id", requestId);
197
206
  }
198
- return errorResponse(status, error.code, error.message, headers);
207
+ return errorResponse(status, error.code, TRANSPORT_ERROR_MESSAGES[error.code] ?? error.message, headers);
199
208
  }
200
209
  return errorResponse(500, "internal_error", "Request failed.");
201
210
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazingagents/sdk",
3
- "version": "0.54.0",
3
+ "version": "0.54.1",
4
4
  "description": "TypeScript SDK for the Blazing Agents API",
5
5
  "homepage": "https://docs.blazingagents.com",
6
6
  "bugs": {