@blazingagents/sdk 0.54.0 → 0.55.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/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
  }
@@ -0,0 +1,2 @@
1
+ /** Every `error.code` the API contract lists. */
2
+ export declare const apiErrorCodes: readonly ["invalid_request", "idempotency_conflict", "input_idempotency_conflict", "steer_not_available", "validation_failed", "unauthorized", "not_found", "model_spending_limit_exceeded", "subscription_required", "usage_credit_required", "rate_limited", "internal", "service_unavailable", "subscription_already_paid", "subscription_not_cancelled", "agent_disabled", "agent_busy", "agent_deleting", "admin_agent_managed", "agent_mcp_connection_not_found", "agent_mcp_connections_invalid", "provider_required", "api_key_limit_reached", "artifact_session_cap_reached", "invalid_cursor", "message_not_found", "prompt_variable_missing", "prompt_variable_unknown", "provider_in_use", "provider_historical_use", "provider_limit_reached", "provider_name_conflict", "provider_not_found", "model_discovery_unsupported", "model_not_found", "model_validation_unavailable", "mcp_connection_limit_reached", "mcp_connection_name_conflict", "mcp_connection_stale_credential_version", "mcp_connection_invalid", "mcp_connection_authentication_failed", "mcp_connection_in_use", "mcp_connection_unreachable", "mcp_connection_discovery_failed", "mcp_connection_needs_auth", "workspace_not_found", "workspace_in_use", "workspace_busy", "session_busy", "session_turn_unresponsive", "session_fork_unavailable", "session_fork_deleted", "message_id_conflict", "session_version_mismatch", "tool_approval_continuation_settled", "tool_approval_decision_conflict", "tool_approval_outdated", "function_call_conflict", "skill_invalid_archive", "skill_invalid_markdown", "skill_limit_reached", "skill_name_conflict", "skill_not_found", "skill_too_many_files", "skill_uncompressed_too_large", "task_active_run_exists", "chat_webhook_conflict", "chat_webhook_registration_failed", "merchant_connection_not_found", "merchant_connection_in_use", "merchant_credential_invalid", "merchant_provider_unavailable", "merchant_customer_not_found", "merchant_binding_not_found", "merchant_account_mismatch", "merchant_event_not_found", "merchant_event_state_conflict", "merchant_customer_unmapped", "forbidden", "insufficient_scope", "merchant_subscription_required", "merchant_balance_required", "merchant_eligibility_unavailable", "tenant_deleting", "tenant_deletion_in_progress", "tenant_deletion_not_ready", "tenant_not_deleting"];
@@ -0,0 +1,91 @@
1
+ // Generated by `npm run generate` from spec/openapi.json. Do not edit by hand.
2
+ /** Every `error.code` the API contract lists. */
3
+ export const apiErrorCodes = [
4
+ "invalid_request",
5
+ "idempotency_conflict",
6
+ "input_idempotency_conflict",
7
+ "steer_not_available",
8
+ "validation_failed",
9
+ "unauthorized",
10
+ "not_found",
11
+ "model_spending_limit_exceeded",
12
+ "subscription_required",
13
+ "usage_credit_required",
14
+ "rate_limited",
15
+ "internal",
16
+ "service_unavailable",
17
+ "subscription_already_paid",
18
+ "subscription_not_cancelled",
19
+ "agent_disabled",
20
+ "agent_busy",
21
+ "agent_deleting",
22
+ "admin_agent_managed",
23
+ "agent_mcp_connection_not_found",
24
+ "agent_mcp_connections_invalid",
25
+ "provider_required",
26
+ "api_key_limit_reached",
27
+ "artifact_session_cap_reached",
28
+ "invalid_cursor",
29
+ "message_not_found",
30
+ "prompt_variable_missing",
31
+ "prompt_variable_unknown",
32
+ "provider_in_use",
33
+ "provider_historical_use",
34
+ "provider_limit_reached",
35
+ "provider_name_conflict",
36
+ "provider_not_found",
37
+ "model_discovery_unsupported",
38
+ "model_not_found",
39
+ "model_validation_unavailable",
40
+ "mcp_connection_limit_reached",
41
+ "mcp_connection_name_conflict",
42
+ "mcp_connection_stale_credential_version",
43
+ "mcp_connection_invalid",
44
+ "mcp_connection_authentication_failed",
45
+ "mcp_connection_in_use",
46
+ "mcp_connection_unreachable",
47
+ "mcp_connection_discovery_failed",
48
+ "mcp_connection_needs_auth",
49
+ "workspace_not_found",
50
+ "workspace_in_use",
51
+ "workspace_busy",
52
+ "session_busy",
53
+ "session_turn_unresponsive",
54
+ "session_fork_unavailable",
55
+ "session_fork_deleted",
56
+ "message_id_conflict",
57
+ "session_version_mismatch",
58
+ "tool_approval_continuation_settled",
59
+ "tool_approval_decision_conflict",
60
+ "tool_approval_outdated",
61
+ "function_call_conflict",
62
+ "skill_invalid_archive",
63
+ "skill_invalid_markdown",
64
+ "skill_limit_reached",
65
+ "skill_name_conflict",
66
+ "skill_not_found",
67
+ "skill_too_many_files",
68
+ "skill_uncompressed_too_large",
69
+ "task_active_run_exists",
70
+ "chat_webhook_conflict",
71
+ "chat_webhook_registration_failed",
72
+ "merchant_connection_not_found",
73
+ "merchant_connection_in_use",
74
+ "merchant_credential_invalid",
75
+ "merchant_provider_unavailable",
76
+ "merchant_customer_not_found",
77
+ "merchant_binding_not_found",
78
+ "merchant_account_mismatch",
79
+ "merchant_event_not_found",
80
+ "merchant_event_state_conflict",
81
+ "merchant_customer_unmapped",
82
+ "forbidden",
83
+ "insufficient_scope",
84
+ "merchant_subscription_required",
85
+ "merchant_balance_required",
86
+ "merchant_eligibility_unavailable",
87
+ "tenant_deleting",
88
+ "tenant_deletion_in_progress",
89
+ "tenant_deletion_not_ready",
90
+ "tenant_not_deleting",
91
+ ];
@@ -87,6 +87,7 @@ export declare const apiErrorCodeSchema: z.ZodEnum<{
87
87
  tenant_not_deleting: "tenant_not_deleting";
88
88
  tool_approval_continuation_settled: "tool_approval_continuation_settled";
89
89
  tool_approval_decision_conflict: "tool_approval_decision_conflict";
90
+ tool_approval_outdated: "tool_approval_outdated";
90
91
  unauthorized: "unauthorized";
91
92
  usage_credit_required: "usage_credit_required";
92
93
  validation_failed: "validation_failed";
@@ -1,98 +1,12 @@
1
1
  import { z } from "zod";
2
+ import { apiErrorCodes } from "./api-error-codes.js";
2
3
  /**
3
4
  * `/v1` error envelope — see docs/adr/0003-ai-sdk-native-wire-protocol.md.
4
5
  * Closed producer code set; `code` is what SDKs switch on and `message` is
5
6
  * human-only. Resource-specific codes preserve stable product outcomes that
6
7
  * callers need to distinguish.
7
8
  */
8
- export const apiErrorCodeSchema = z.enum([
9
- "invalid_request",
10
- "idempotency_conflict",
11
- "session_fork_deleted",
12
- "session_fork_unavailable",
13
- "input_idempotency_conflict",
14
- "steer_not_available",
15
- "validation_failed",
16
- "unauthorized",
17
- "forbidden",
18
- "insufficient_scope",
19
- "not_found",
20
- "model_spending_limit_exceeded",
21
- "subscription_required",
22
- "usage_credit_required",
23
- "rate_limited",
24
- "internal",
25
- "service_unavailable",
26
- "subscription_already_paid",
27
- "subscription_not_cancelled",
28
- "agent_disabled",
29
- "agent_busy",
30
- "agent_deleting",
31
- "admin_agent_managed",
32
- "agent_mcp_connection_not_found",
33
- "agent_mcp_connections_invalid",
34
- "provider_required",
35
- "api_key_limit_reached",
36
- "artifact_session_cap_reached",
37
- "invalid_cursor",
38
- "message_not_found",
39
- "message_id_conflict",
40
- "prompt_variable_missing",
41
- "prompt_variable_unknown",
42
- "provider_in_use",
43
- "provider_historical_use",
44
- "provider_limit_reached",
45
- "provider_name_conflict",
46
- "provider_not_found",
47
- "model_discovery_unsupported",
48
- "model_not_found",
49
- "model_validation_unavailable",
50
- "mcp_connection_limit_reached",
51
- "mcp_connection_name_conflict",
52
- "mcp_connection_stale_credential_version",
53
- "mcp_connection_invalid",
54
- "mcp_connection_authentication_failed",
55
- "mcp_connection_in_use",
56
- "mcp_connection_unreachable",
57
- "mcp_connection_discovery_failed",
58
- "mcp_connection_needs_auth",
59
- "workspace_not_found",
60
- "workspace_in_use",
61
- "workspace_busy",
62
- "session_busy",
63
- "session_turn_unresponsive",
64
- "session_version_mismatch",
65
- "tool_approval_continuation_settled",
66
- "tool_approval_decision_conflict",
67
- "function_call_conflict",
68
- "skill_invalid_archive",
69
- "skill_invalid_markdown",
70
- "skill_limit_reached",
71
- "skill_name_conflict",
72
- "skill_not_found",
73
- "skill_too_many_files",
74
- "skill_uncompressed_too_large",
75
- "task_active_run_exists",
76
- "chat_webhook_conflict",
77
- "chat_webhook_registration_failed",
78
- "merchant_connection_not_found",
79
- "merchant_connection_in_use",
80
- "merchant_credential_invalid",
81
- "merchant_provider_unavailable",
82
- "merchant_customer_not_found",
83
- "merchant_binding_not_found",
84
- "merchant_account_mismatch",
85
- "merchant_event_not_found",
86
- "merchant_event_state_conflict",
87
- "merchant_customer_unmapped",
88
- "merchant_subscription_required",
89
- "merchant_balance_required",
90
- "merchant_eligibility_unavailable",
91
- "tenant_deleting",
92
- "tenant_deletion_in_progress",
93
- "tenant_deletion_not_ready",
94
- "tenant_not_deleting",
95
- ]);
9
+ export const apiErrorCodeSchema = z.enum(apiErrorCodes);
96
10
  /**
97
11
  * A code as received: any non-empty string, so a server newer than this SDK
98
12
  * can send a code the SDK does not list. The type keeps autocomplete for the
@@ -367,7 +367,8 @@ export declare const merchantUsageSummaryResponseSchema: z.ZodObject<{
367
367
  export type MerchantUsageSummaryResponse = z.infer<typeof merchantUsageSummaryResponseSchema>;
368
368
  /**
369
369
  * The action a Tenant takes on an event. `automaticDeliveryStopped` is true
370
- * when automatic delivery has given up on a `pending` event.
370
+ * when the delivery of a `pending` event stopped. Blazing Agents retries it on
371
+ * its own four times; after that the event waits for the Tenant's retry.
371
372
  */
372
373
  export declare function merchantUsageEventNextAction(event: {
373
374
  automaticDeliveryStopped: boolean;
@@ -190,7 +190,8 @@ export const merchantUsageSummaryResponseSchema = z
190
190
  .strip();
191
191
  /**
192
192
  * The action a Tenant takes on an event. `automaticDeliveryStopped` is true
193
- * when automatic delivery has given up on a `pending` event.
193
+ * when the delivery of a `pending` event stopped. Blazing Agents retries it on
194
+ * its own four times; after that the event waits for the Tenant's retry.
194
195
  */
195
196
  export function merchantUsageEventNextAction(event) {
196
197
  switch (event.status) {
@@ -356,7 +356,7 @@ export declare const turnStreamErrorEventSchema: z.ZodObject<{
356
356
  type: z.ZodLiteral<"data-ba-error">;
357
357
  transient: z.ZodLiteral<true>;
358
358
  data: z.ZodObject<{
359
- code: z.ZodCustom<"admin_agent_managed" | "agent_busy" | "agent_deleting" | "agent_disabled" | "agent_mcp_connection_not_found" | "agent_mcp_connections_invalid" | "api_key_limit_reached" | "artifact_session_cap_reached" | "chat_webhook_conflict" | "chat_webhook_registration_failed" | "forbidden" | "function_call_conflict" | "idempotency_conflict" | "input_idempotency_conflict" | "insufficient_scope" | "internal" | "invalid_cursor" | "invalid_request" | "mcp_connection_authentication_failed" | "mcp_connection_discovery_failed" | "mcp_connection_in_use" | "mcp_connection_invalid" | "mcp_connection_limit_reached" | "mcp_connection_name_conflict" | "mcp_connection_needs_auth" | "mcp_connection_stale_credential_version" | "mcp_connection_unreachable" | "merchant_account_mismatch" | "merchant_balance_required" | "merchant_binding_not_found" | "merchant_connection_in_use" | "merchant_connection_not_found" | "merchant_credential_invalid" | "merchant_customer_not_found" | "merchant_customer_unmapped" | "merchant_eligibility_unavailable" | "merchant_event_not_found" | "merchant_event_state_conflict" | "merchant_provider_unavailable" | "merchant_subscription_required" | "message_id_conflict" | "message_not_found" | "model_discovery_unsupported" | "model_not_found" | "model_spending_limit_exceeded" | "model_validation_unavailable" | "not_found" | "prompt_variable_missing" | "prompt_variable_unknown" | "provider_historical_use" | "provider_in_use" | "provider_limit_reached" | "provider_name_conflict" | "provider_not_found" | "provider_required" | "rate_limited" | "service_unavailable" | "session_busy" | "session_fork_deleted" | "session_fork_unavailable" | "session_turn_unresponsive" | "session_version_mismatch" | "skill_invalid_archive" | "skill_invalid_markdown" | "skill_limit_reached" | "skill_name_conflict" | "skill_not_found" | "skill_too_many_files" | "skill_uncompressed_too_large" | "steer_not_available" | "subscription_already_paid" | "subscription_not_cancelled" | "subscription_required" | "task_active_run_exists" | "tenant_deleting" | "tenant_deletion_in_progress" | "tenant_deletion_not_ready" | "tenant_not_deleting" | "tool_approval_continuation_settled" | "tool_approval_decision_conflict" | "turn_interrupted" | "unauthorized" | "usage_credit_required" | "validation_failed" | "workspace_busy" | "workspace_in_use" | "workspace_not_found" | (string & {}), "admin_agent_managed" | "agent_busy" | "agent_deleting" | "agent_disabled" | "agent_mcp_connection_not_found" | "agent_mcp_connections_invalid" | "api_key_limit_reached" | "artifact_session_cap_reached" | "chat_webhook_conflict" | "chat_webhook_registration_failed" | "forbidden" | "function_call_conflict" | "idempotency_conflict" | "input_idempotency_conflict" | "insufficient_scope" | "internal" | "invalid_cursor" | "invalid_request" | "mcp_connection_authentication_failed" | "mcp_connection_discovery_failed" | "mcp_connection_in_use" | "mcp_connection_invalid" | "mcp_connection_limit_reached" | "mcp_connection_name_conflict" | "mcp_connection_needs_auth" | "mcp_connection_stale_credential_version" | "mcp_connection_unreachable" | "merchant_account_mismatch" | "merchant_balance_required" | "merchant_binding_not_found" | "merchant_connection_in_use" | "merchant_connection_not_found" | "merchant_credential_invalid" | "merchant_customer_not_found" | "merchant_customer_unmapped" | "merchant_eligibility_unavailable" | "merchant_event_not_found" | "merchant_event_state_conflict" | "merchant_provider_unavailable" | "merchant_subscription_required" | "message_id_conflict" | "message_not_found" | "model_discovery_unsupported" | "model_not_found" | "model_spending_limit_exceeded" | "model_validation_unavailable" | "not_found" | "prompt_variable_missing" | "prompt_variable_unknown" | "provider_historical_use" | "provider_in_use" | "provider_limit_reached" | "provider_name_conflict" | "provider_not_found" | "provider_required" | "rate_limited" | "service_unavailable" | "session_busy" | "session_fork_deleted" | "session_fork_unavailable" | "session_turn_unresponsive" | "session_version_mismatch" | "skill_invalid_archive" | "skill_invalid_markdown" | "skill_limit_reached" | "skill_name_conflict" | "skill_not_found" | "skill_too_many_files" | "skill_uncompressed_too_large" | "steer_not_available" | "subscription_already_paid" | "subscription_not_cancelled" | "subscription_required" | "task_active_run_exists" | "tenant_deleting" | "tenant_deletion_in_progress" | "tenant_deletion_not_ready" | "tenant_not_deleting" | "tool_approval_continuation_settled" | "tool_approval_decision_conflict" | "turn_interrupted" | "unauthorized" | "usage_credit_required" | "validation_failed" | "workspace_busy" | "workspace_in_use" | "workspace_not_found" | (string & {})>;
359
+ code: z.ZodCustom<"admin_agent_managed" | "agent_busy" | "agent_deleting" | "agent_disabled" | "agent_mcp_connection_not_found" | "agent_mcp_connections_invalid" | "api_key_limit_reached" | "artifact_session_cap_reached" | "chat_webhook_conflict" | "chat_webhook_registration_failed" | "forbidden" | "function_call_conflict" | "idempotency_conflict" | "input_idempotency_conflict" | "insufficient_scope" | "internal" | "invalid_cursor" | "invalid_request" | "mcp_connection_authentication_failed" | "mcp_connection_discovery_failed" | "mcp_connection_in_use" | "mcp_connection_invalid" | "mcp_connection_limit_reached" | "mcp_connection_name_conflict" | "mcp_connection_needs_auth" | "mcp_connection_stale_credential_version" | "mcp_connection_unreachable" | "merchant_account_mismatch" | "merchant_balance_required" | "merchant_binding_not_found" | "merchant_connection_in_use" | "merchant_connection_not_found" | "merchant_credential_invalid" | "merchant_customer_not_found" | "merchant_customer_unmapped" | "merchant_eligibility_unavailable" | "merchant_event_not_found" | "merchant_event_state_conflict" | "merchant_provider_unavailable" | "merchant_subscription_required" | "message_id_conflict" | "message_not_found" | "model_discovery_unsupported" | "model_not_found" | "model_spending_limit_exceeded" | "model_validation_unavailable" | "not_found" | "prompt_variable_missing" | "prompt_variable_unknown" | "provider_historical_use" | "provider_in_use" | "provider_limit_reached" | "provider_name_conflict" | "provider_not_found" | "provider_required" | "rate_limited" | "service_unavailable" | "session_busy" | "session_fork_deleted" | "session_fork_unavailable" | "session_turn_unresponsive" | "session_version_mismatch" | "skill_invalid_archive" | "skill_invalid_markdown" | "skill_limit_reached" | "skill_name_conflict" | "skill_not_found" | "skill_too_many_files" | "skill_uncompressed_too_large" | "steer_not_available" | "subscription_already_paid" | "subscription_not_cancelled" | "subscription_required" | "task_active_run_exists" | "tenant_deleting" | "tenant_deletion_in_progress" | "tenant_deletion_not_ready" | "tenant_not_deleting" | "tool_approval_continuation_settled" | "tool_approval_decision_conflict" | "tool_approval_outdated" | "turn_interrupted" | "unauthorized" | "usage_credit_required" | "validation_failed" | "workspace_busy" | "workspace_in_use" | "workspace_not_found" | (string & {}), "admin_agent_managed" | "agent_busy" | "agent_deleting" | "agent_disabled" | "agent_mcp_connection_not_found" | "agent_mcp_connections_invalid" | "api_key_limit_reached" | "artifact_session_cap_reached" | "chat_webhook_conflict" | "chat_webhook_registration_failed" | "forbidden" | "function_call_conflict" | "idempotency_conflict" | "input_idempotency_conflict" | "insufficient_scope" | "internal" | "invalid_cursor" | "invalid_request" | "mcp_connection_authentication_failed" | "mcp_connection_discovery_failed" | "mcp_connection_in_use" | "mcp_connection_invalid" | "mcp_connection_limit_reached" | "mcp_connection_name_conflict" | "mcp_connection_needs_auth" | "mcp_connection_stale_credential_version" | "mcp_connection_unreachable" | "merchant_account_mismatch" | "merchant_balance_required" | "merchant_binding_not_found" | "merchant_connection_in_use" | "merchant_connection_not_found" | "merchant_credential_invalid" | "merchant_customer_not_found" | "merchant_customer_unmapped" | "merchant_eligibility_unavailable" | "merchant_event_not_found" | "merchant_event_state_conflict" | "merchant_provider_unavailable" | "merchant_subscription_required" | "message_id_conflict" | "message_not_found" | "model_discovery_unsupported" | "model_not_found" | "model_spending_limit_exceeded" | "model_validation_unavailable" | "not_found" | "prompt_variable_missing" | "prompt_variable_unknown" | "provider_historical_use" | "provider_in_use" | "provider_limit_reached" | "provider_name_conflict" | "provider_not_found" | "provider_required" | "rate_limited" | "service_unavailable" | "session_busy" | "session_fork_deleted" | "session_fork_unavailable" | "session_turn_unresponsive" | "session_version_mismatch" | "skill_invalid_archive" | "skill_invalid_markdown" | "skill_limit_reached" | "skill_name_conflict" | "skill_not_found" | "skill_too_many_files" | "skill_uncompressed_too_large" | "steer_not_available" | "subscription_already_paid" | "subscription_not_cancelled" | "subscription_required" | "task_active_run_exists" | "tenant_deleting" | "tenant_deletion_in_progress" | "tenant_deletion_not_ready" | "tenant_not_deleting" | "tool_approval_continuation_settled" | "tool_approval_decision_conflict" | "tool_approval_outdated" | "turn_interrupted" | "unauthorized" | "usage_credit_required" | "validation_failed" | "workspace_busy" | "workspace_in_use" | "workspace_not_found" | (string & {})>;
360
360
  details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
361
361
  message: z.ZodString;
362
362
  }, z.core.$strict>;
@@ -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
  }
@@ -37,7 +37,7 @@ export interface MerchantUsageEventsResource {
37
37
  */
38
38
  list(input?: MerchantUsageEventsListOptions): Promise<MerchantUsageEventsResponse>;
39
39
  /**
40
- * Sends a `failed` event, or a `pending` event whose automatic delivery gave up, to the provider again. Retrying is safe: the provider drops duplicates by the event ID.
40
+ * Sends a `failed` event, or a `pending` event whose delivery stopped, to the provider again. Blazing Agents retries a stopped delivery on its own after 5, 10, 20 and 40 minutes; after the fourth automatic retry the event stays `pending` until you retry it. Retrying is safe: the provider drops duplicates by the event ID.
41
41
  * @param input - `eventId`; optional abortSignal.
42
42
  * @returns The merchant usage event response.
43
43
  * @throws BlazingAgentsError - If the request fails, is aborted, or returns an invalid response.
@@ -2,24 +2,27 @@ import { type CreateSkillBody, type SkillArchiveType, type SkillCopyResults, typ
2
2
  import type { HttpConfig, ResourceRequestOptions } from "../types.ts";
3
3
  export interface AgentSkillsResource {
4
4
  /**
5
- * Copies the Skill to the selected Agents.
6
- * @param input - Source `skillId`, destination `to.agentIds`, and optional abortSignal.
5
+ * Copies the Skill to the selected Agents. Retry a lost answer with the same `idempotencyKey` and each destination returns the copy it already has.
6
+ * @param input - Source `skillId`, destination `to.agentIds`, optional `idempotencyKey` (1 to 200 characters, one Agent's key), and optional abortSignal.
7
7
  * @returns The skill copy results.
8
8
  * @throws BlazingAgentsError - If the request fails, is aborted, or returns an invalid response.
9
9
  */
10
10
  copy(input: {
11
+ idempotencyKey?: string;
11
12
  skillId: string;
12
13
  to: {
13
14
  agentIds: string[];
14
15
  };
15
16
  } & ResourceRequestOptions): Promise<SkillCopyResults>;
16
17
  /**
17
- * Creates the Skill.
18
- * @param input - creation fields; optional abortSignal.
18
+ * Creates the Skill. Retry a lost answer with the same `idempotencyKey` and the request returns the Skill the first one created.
19
+ * @param input - creation fields; optional `idempotencyKey` (1 to 200 characters, one Agent's key) and abortSignal.
19
20
  * @returns The skill detail.
20
21
  * @throws BlazingAgentsError - If the request fails, is aborted, or returns an invalid response.
21
22
  */
22
- create(input: CreateSkillBody & ResourceRequestOptions): Promise<SkillDetail>;
23
+ create(input: CreateSkillBody & {
24
+ idempotencyKey?: string;
25
+ } & ResourceRequestOptions): Promise<SkillDetail>;
23
26
  /**
24
27
  * Deletes the Skill.
25
28
  * @param input - `skillId`; optional abortSignal.
@@ -77,12 +80,13 @@ export interface AgentSkillsResource {
77
80
  skillId: string;
78
81
  } & ResourceRequestOptions): Promise<SkillDetail>;
79
82
  /**
80
- * Uploads a Skill archive as multipart form data.
81
- * @param input - Archive bytes in `source.file`, archive format in `source.type`, and optional abortSignal.
83
+ * Uploads a Skill archive as multipart form data. Retry a lost answer with the same `idempotencyKey` and the request returns the Skill the first one created.
84
+ * @param input - Archive bytes in `source.file`, archive format in `source.type`, optional `idempotencyKey` (1 to 200 characters, one Agent's key), and optional abortSignal.
82
85
  * @returns The skill detail.
83
86
  * @throws BlazingAgentsError - If the request fails, is aborted, or returns an invalid response.
84
87
  */
85
88
  upload(input: {
89
+ idempotencyKey?: string;
86
90
  source: {
87
91
  file: Blob | Uint8Array;
88
92
  type: SkillArchiveType;
@@ -1,5 +1,13 @@
1
1
  import { skillCopyResultsSchema, skillDetailSchema, skillsListResponseSchema, } from "../contracts/entities/skills.js";
2
2
  import { apiPath, isRequestAborted, requestAbortedError, requestJson, requestStream, } from "../http.js";
3
+ /**
4
+ * Builds the `Idempotency-Key` header, or none when the caller set no key.
5
+ */
6
+ function idempotencyHeaders(idempotencyKey) {
7
+ return idempotencyKey === undefined
8
+ ? undefined
9
+ : { "Idempotency-Key": idempotencyKey };
10
+ }
3
11
  /**
4
12
  * Builds a Skill file URL with encoded Agent, Skill, and file path values.
5
13
  */
@@ -13,11 +21,21 @@ function fileUrl(agentId, input) {
13
21
  */
14
22
  export function createAgentSkillsResource(config, agentId) {
15
23
  return {
16
- async copy({ skillId, to, abortSignal }) {
17
- return await requestJson(config, apiPath `/v1/agents/${agentId}/skills/${skillId}/copies`, { json: to, method: "POST", signal: abortSignal }, skillCopyResultsSchema);
24
+ async copy({ skillId, to, idempotencyKey, abortSignal }) {
25
+ return await requestJson(config, apiPath `/v1/agents/${agentId}/skills/${skillId}/copies`, {
26
+ headers: idempotencyHeaders(idempotencyKey),
27
+ json: to,
28
+ method: "POST",
29
+ signal: abortSignal,
30
+ }, skillCopyResultsSchema);
18
31
  },
19
- async create({ abortSignal, ...body }) {
20
- return await requestJson(config, apiPath `/v1/agents/${agentId}/skills`, { json: body, method: "POST", signal: abortSignal }, skillDetailSchema);
32
+ async create({ idempotencyKey, abortSignal, ...body }) {
33
+ return await requestJson(config, apiPath `/v1/agents/${agentId}/skills`, {
34
+ headers: idempotencyHeaders(idempotencyKey),
35
+ json: body,
36
+ method: "POST",
37
+ signal: abortSignal,
38
+ }, skillDetailSchema);
21
39
  },
22
40
  async delete({ skillId, abortSignal }) {
23
41
  await requestJson(config, apiPath `/v1/agents/${agentId}/skills/${skillId}`, { method: "DELETE", signal: abortSignal });
@@ -56,14 +74,19 @@ export function createAgentSkillsResource(config, agentId) {
56
74
  signal: abortSignal,
57
75
  }, skillDetailSchema);
58
76
  },
59
- async upload({ source, abortSignal }) {
77
+ async upload({ source, idempotencyKey, abortSignal }) {
60
78
  const form = new FormData();
61
79
  form.set("type", source.type);
62
80
  const file = source.file instanceof Blob
63
81
  ? source.file
64
82
  : new Blob([source.file]);
65
83
  form.set("file", file, `skill.${source.type}`);
66
- return await requestJson(config, apiPath `/v1/agents/${agentId}/skills/upload`, { body: form, method: "POST", signal: abortSignal }, skillDetailSchema);
84
+ return await requestJson(config, apiPath `/v1/agents/${agentId}/skills/upload`, {
85
+ body: form,
86
+ headers: idempotencyHeaders(idempotencyKey),
87
+ method: "POST",
88
+ signal: abortSignal,
89
+ }, skillDetailSchema);
67
90
  },
68
91
  };
69
92
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazingagents/sdk",
3
- "version": "0.54.0",
3
+ "version": "0.55.0",
4
4
  "description": "TypeScript SDK for the Blazing Agents API",
5
5
  "homepage": "https://docs.blazingagents.com",
6
6
  "bugs": {
@@ -39,8 +39,9 @@
39
39
  "scripts": {
40
40
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
41
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",
42
+ "check": "npm run generate -- --check && npm run typecheck && npm run test && npm run bundle-size && npm run lint && npm run unused",
43
43
  "fix": "ultracite fix",
44
+ "generate": "node scripts/generate-error-codes.ts",
44
45
  "lint": "ultracite check",
45
46
  "prepack": "npm run build",
46
47
  "test": "node scripts/check-test-imports.ts && vitest run --coverage",