@blazingagents/sdk 0.53.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
  }
@@ -113,6 +113,7 @@ export declare const agentResponseSchema: z.ZodObject<{
113
113
  model: z.ZodNullable<z.ZodString>;
114
114
  thinkingLevel: z.ZodNullable<z.ZodString>;
115
115
  providerId: z.ZodNullable<z.ZodString>;
116
+ autoApprovalModel: z.ZodNullable<z.ZodString>;
116
117
  workspaceId: z.ZodString;
117
118
  autoCompaction: z.ZodBoolean;
118
119
  compactionReserveTokens: z.ZodNumber;
@@ -236,6 +237,7 @@ export declare const agentsResponseSchema: z.ZodObject<{
236
237
  model: z.ZodNullable<z.ZodString>;
237
238
  thinkingLevel: z.ZodNullable<z.ZodString>;
238
239
  providerId: z.ZodNullable<z.ZodString>;
240
+ autoApprovalModel: z.ZodNullable<z.ZodString>;
239
241
  workspaceId: z.ZodString;
240
242
  autoCompaction: z.ZodBoolean;
241
243
  compactionReserveTokens: z.ZodNumber;
@@ -364,6 +366,7 @@ export declare const agentConfigSchema: z.ZodObject<{
364
366
  model: z.ZodNullable<z.ZodString>;
365
367
  thinkingLevel: z.ZodNullable<z.ZodString>;
366
368
  providerId: z.ZodNullable<z.ZodString>;
369
+ autoApprovalModel: z.ZodNullable<z.ZodString>;
367
370
  autoCompaction: z.ZodBoolean;
368
371
  compactionReserveTokens: z.ZodNumber;
369
372
  memoryInjectionEnabled: z.ZodBoolean;
@@ -479,6 +482,7 @@ export declare const createAgentBodySchema: z.ZodObject<{
479
482
  model: z.ZodDefault<z.ZodNullable<z.ZodString>>;
480
483
  thinkingLevel: z.ZodDefault<z.ZodNullable<z.ZodString>>;
481
484
  providerId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
485
+ autoApprovalModel: z.ZodDefault<z.ZodNullable<z.ZodString>>;
482
486
  workspaceId: z.ZodOptional<z.ZodString>;
483
487
  autoCompaction: z.ZodDefault<z.ZodBoolean>;
484
488
  compactionReserveTokens: z.ZodDefault<z.ZodNumber>;
@@ -592,6 +596,7 @@ export declare const updateAgentBodySchema: z.ZodObject<{
592
596
  model: z.ZodOptional<z.ZodNullable<z.ZodString>>;
593
597
  thinkingLevel: z.ZodOptional<z.ZodNullable<z.ZodString>>;
594
598
  providerId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
599
+ autoApprovalModel: z.ZodOptional<z.ZodNullable<z.ZodString>>;
595
600
  workspaceId: z.ZodOptional<z.ZodString>;
596
601
  autoCompaction: z.ZodOptional<z.ZodBoolean>;
597
602
  compactionReserveTokens: z.ZodOptional<z.ZodNumber>;
@@ -36,12 +36,21 @@ export const agentMcpConnectionIdsSchema = z
36
36
  });
37
37
  export const agentStatusSchema = z.enum(["active", "disabled"]);
38
38
  const providerModelPairMessage = "Provider and model must either both be set or both be null.";
39
+ const autoApprovalModelMessage = "autoApprovalModel needs a provider and model on the agent.";
39
40
  /**
40
41
  * Checks that provider and model selections are both present or both absent.
41
42
  */
42
43
  function hasProviderModelPair(input) {
43
44
  return (input.model === null) === (input.providerId === null);
44
45
  }
46
+ /**
47
+ * Checks that an auto-approval model runs on a configured Provider and model.
48
+ */
49
+ function hasProviderForAutoApprovalModel(input) {
50
+ return (input.autoApprovalModel === undefined ||
51
+ input.autoApprovalModel === null ||
52
+ input.providerId !== null);
53
+ }
45
54
  export const agentResponseSchema = z
46
55
  .object({
47
56
  ...approvalFields,
@@ -51,6 +60,7 @@ export const agentResponseSchema = z
51
60
  model: agentModelIdSchema.nullable(),
52
61
  thinkingLevel: z.string().min(1).nullable(),
53
62
  providerId: providerIdSchema.nullable(),
63
+ autoApprovalModel: agentModelIdSchema.nullable(),
54
64
  workspaceId: workspaceIdSchema,
55
65
  autoCompaction: z.boolean(),
56
66
  compactionReserveTokens: z
@@ -74,6 +84,10 @@ export const agentResponseSchema = z
74
84
  .refine(hasProviderModelPair, {
75
85
  message: providerModelPairMessage,
76
86
  path: ["providerId"],
87
+ })
88
+ .refine(hasProviderForAutoApprovalModel, {
89
+ message: autoApprovalModelMessage,
90
+ path: ["autoApprovalModel"],
77
91
  });
78
92
  export const agentsResponseSchema = paginatedResponseSchema(agentResponseSchema);
79
93
  export const agentsListQuerySchema = z
@@ -103,6 +117,7 @@ export const agentConfigSchema = z
103
117
  model: agentResponseSchema.shape.model,
104
118
  thinkingLevel: agentResponseSchema.shape.thinkingLevel,
105
119
  providerId: agentResponseSchema.shape.providerId,
120
+ autoApprovalModel: agentResponseSchema.shape.autoApprovalModel,
106
121
  autoCompaction: agentResponseSchema.shape.autoCompaction,
107
122
  compactionReserveTokens: agentResponseSchema.shape.compactionReserveTokens,
108
123
  memoryInjectionEnabled: agentResponseSchema.shape.memoryInjectionEnabled,
@@ -115,6 +130,10 @@ export const agentConfigSchema = z
115
130
  .refine(hasProviderModelPair, {
116
131
  message: providerModelPairMessage,
117
132
  path: ["providerId"],
133
+ })
134
+ .refine(hasProviderForAutoApprovalModel, {
135
+ message: autoApprovalModelMessage,
136
+ path: ["autoApprovalModel"],
118
137
  });
119
138
  const agentFieldDescriptions = {
120
139
  approvalInChat: "Which tool calls need approval in sessions and stateless generation.",
@@ -123,6 +142,7 @@ const agentFieldDescriptions = {
123
142
  model: "The provider's own model ID, such as `openai/gpt-6-luna`. Send it together with `providerId`.",
124
143
  thinkingLevel: "How much reasoning to request from the model, such as `high`. Needs a provider and model, and must be a level the model supports.",
125
144
  providerId: "ID of the provider whose key runs the model. Send it together with `model`.",
145
+ autoApprovalModel: "Model ID, on the agent's provider, that reviews tool calls whose approval is `auto`. `null` uses the agent's model. Needs a provider and model. Changing `providerId` without sending this sets it to `null`.",
126
146
  workspaceId: "ID of the workspace the agent reads and writes files in.",
127
147
  autoCompaction: "Summarize older context automatically when a conversation nears the model's context limit.",
128
148
  compactionReserveTokens: "Tokens to keep free for the model's reply when deciding whether to compact.",
@@ -155,6 +175,10 @@ export const createAgentBodySchema = z
155
175
  .nullable()
156
176
  .default(null)
157
177
  .describe(agentFieldDescriptions.providerId),
178
+ autoApprovalModel: agentModelIdSchema
179
+ .nullable()
180
+ .default(null)
181
+ .describe(agentFieldDescriptions.autoApprovalModel),
158
182
  workspaceId: workspaceIdSchema
159
183
  .optional()
160
184
  .describe(`${agentFieldDescriptions.workspaceId} Leave it out to create a new workspace for the agent, or send an existing one to share it.`),
@@ -193,6 +217,10 @@ export const createAgentBodySchema = z
193
217
  .refine(hasProviderModelPair, {
194
218
  message: providerModelPairMessage,
195
219
  path: ["providerId"],
220
+ })
221
+ .refine(hasProviderForAutoApprovalModel, {
222
+ message: autoApprovalModelMessage,
223
+ path: ["autoApprovalModel"],
196
224
  });
197
225
  export const updateAgentBodySchema = z
198
226
  .object({
@@ -217,6 +245,10 @@ export const updateAgentBodySchema = z
217
245
  .nullable()
218
246
  .optional()
219
247
  .describe(agentFieldDescriptions.providerId),
248
+ autoApprovalModel: agentModelIdSchema
249
+ .nullable()
250
+ .optional()
251
+ .describe(agentFieldDescriptions.autoApprovalModel),
220
252
  workspaceId: workspaceIdSchema
221
253
  .optional()
222
254
  .describe(agentFieldDescriptions.workspaceId),
@@ -264,4 +296,8 @@ export const updateAgentBodySchema = z
264
296
  }, {
265
297
  message: providerModelPairMessage,
266
298
  path: ["providerId"],
299
+ })
300
+ .refine(hasProviderForAutoApprovalModel, {
301
+ message: autoApprovalModelMessage,
302
+ path: ["autoApprovalModel"],
267
303
  });
@@ -123,6 +123,7 @@ export declare const sessionResponseSchema: z.ZodObject<{
123
123
  model: z.ZodNullable<z.ZodString>;
124
124
  thinkingLevel: z.ZodNullable<z.ZodString>;
125
125
  providerId: z.ZodNullable<z.ZodString>;
126
+ autoApprovalModel: z.ZodNullable<z.ZodString>;
126
127
  autoCompaction: z.ZodBoolean;
127
128
  compactionReserveTokens: z.ZodNumber;
128
129
  memoryInjectionEnabled: z.ZodBoolean;
@@ -349,6 +349,7 @@ export declare const taskRunResponseSchema: z.ZodObject<{
349
349
  model: z.ZodNullable<z.ZodString>;
350
350
  thinkingLevel: z.ZodNullable<z.ZodString>;
351
351
  providerId: z.ZodNullable<z.ZodString>;
352
+ autoApprovalModel: z.ZodNullable<z.ZodString>;
352
353
  autoCompaction: z.ZodBoolean;
353
354
  compactionReserveTokens: z.ZodNumber;
354
355
  memoryInjectionEnabled: z.ZodBoolean;
@@ -487,6 +488,7 @@ export declare const taskRunsListResponseSchema: z.ZodObject<{
487
488
  model: z.ZodNullable<z.ZodString>;
488
489
  thinkingLevel: z.ZodNullable<z.ZodString>;
489
490
  providerId: z.ZodNullable<z.ZodString>;
491
+ autoApprovalModel: z.ZodNullable<z.ZodString>;
490
492
  autoCompaction: z.ZodBoolean;
491
493
  compactionReserveTokens: z.ZodNumber;
492
494
  memoryInjectionEnabled: z.ZodBoolean;
@@ -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.53.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": {