@blazingagents/sdk 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,10 @@
1
1
  /**
2
- * The browser chat's policy as one pure function, `step(state, event)`. The
3
- * hook owns the only mutable copy of `ChatState`, feeds it events from `Chat`
4
- * and the transport, and runs the effects it returns. `Chat` owns the rendered
5
- * transcript and the transport owns the Session ID; this module owns what the
6
- * server is known to store, the phase, and the user messages not stored yet.
2
+ * The browser chat's policy as one pure function, `step(state, event)`.
3
+ * `BlazingAgentsChat` owns the only mutable copy of `ChatState`, feeds it
4
+ * events from its AI SDK chat and the transport, and runs the effects it
5
+ * returns. The AI SDK chat owns the rendered transcript and the transport owns
6
+ * the Session ID; this module owns what the server is known to store, the
7
+ * phase, and the user messages not stored yet.
7
8
  */
8
9
  import { isToolUIPart, lastAssistantMessageIsCompleteWithApprovalResponses, } from "ai";
9
10
  export const initialChatState = {
@@ -47,7 +48,7 @@ function apply(state, event, newId) {
47
48
  case "restore":
48
49
  return {
49
50
  state: { ...state, phase: { kind: "restoring", load: "running" } },
50
- effects: [{ type: "loadHistory" }],
51
+ effects: [{ type: "loadHistory", known: [] }],
51
52
  };
52
53
  case "credentialsChanged":
53
54
  if (phase.kind === "restoring" && phase.load !== "failed") {
@@ -83,7 +84,7 @@ function apply(state, event, newId) {
83
84
  ? noEffects({ ...state, phase: { kind: "starting", prompt: null } })
84
85
  : noEffects(state);
85
86
  case "turnStarted":
86
- // Outside `starting`, Chat sent an approval continuation on its own.
87
+ // Outside `starting`, the AI SDK chat sent an approval continuation on its own.
87
88
  return noEffects({
88
89
  ...state,
89
90
  phase: {
@@ -131,7 +132,7 @@ function apply(state, event, newId) {
131
132
  effects: [...ended, { type: "forgetSession" }],
132
133
  };
133
134
  }
134
- case "unmount":
135
+ case "dispose":
135
136
  return { state: initialChatState, effects: endConversation(state) };
136
137
  case "clearError":
137
138
  return restoreAgain({ ...state, error: undefined });
@@ -142,7 +143,7 @@ function restoreAgain(state) {
142
143
  return state.phase.kind === "restoring" && state.phase.load === "failed"
143
144
  ? {
144
145
  state: { ...state, phase: { kind: "restoring", load: "running" } },
145
- effects: [{ type: "loadHistory" }],
146
+ effects: [{ type: "loadHistory", known: [] }],
146
147
  }
147
148
  : noEffects(state);
148
149
  }
@@ -192,7 +193,7 @@ function historyFailed(state, { error, sessionGone }) {
192
193
  return phase.load === "stale"
193
194
  ? {
194
195
  state: { ...state, phase: { kind: "restoring", load: "running" } },
195
- effects: [{ type: "loadHistory" }],
196
+ effects: [{ type: "loadHistory", known: [] }],
196
197
  }
197
198
  : noEffects({
198
199
  ...state,
@@ -263,7 +264,7 @@ function turnEnded(state, result, newId) {
263
264
  },
264
265
  effects: [
265
266
  { type: "show", messages: state.completed },
266
- { type: "loadHistory" },
267
+ { type: "loadHistory", known: state.completed },
267
268
  ],
268
269
  };
269
270
  }
@@ -393,7 +394,7 @@ function drain({ effects, state }, newId) {
393
394
  if (state.outbox.some(placedByHistory)) {
394
395
  return {
395
396
  state: { ...state, phase: { kind: "reconciling" } },
396
- effects: [...effects, { type: "loadHistory" }],
397
+ effects: [...effects, { type: "loadHistory", known: state.completed }],
397
398
  };
398
399
  }
399
400
  const next = state.outbox.find((entry) => entry.stage === "waiting");
@@ -69,12 +69,17 @@ export declare class BlazingAgentsChatTransport<UI_MESSAGE extends UIMessage = U
69
69
  reconnectToStream(_input: Parameters<ChatTransport<UI_MESSAGE>["reconnectToStream"]>[0]): Promise<null>;
70
70
  /**
71
71
  * Reads the Session's stored transcript through the relay, oldest first.
72
- * @param options - Optional cancellation signal.
72
+ * Pages are read newest first. With `known`, the read stops at the first
73
+ * page whose oldest message is in `known`, and the known messages before
74
+ * that one complete the transcript, so a transcript that changed only near
75
+ * its end costs one request.
76
+ * @param options - `known`: messages already known to be stored, oldest first. Optional cancellation signal.
73
77
  * @returns The stored messages, validated as `UIMessage`s; empty without a Session.
74
78
  * @throws BlazingAgentsError - The relay's error, such as 404 `not_found` when the Session is gone or belongs to another End-user; `invalid_response` when a page or message is malformed; `network_error` or `request_aborted` when the request fails.
75
79
  */
76
80
  loadHistory(options?: {
77
81
  abortSignal?: AbortSignal;
82
+ known?: readonly UI_MESSAGE[];
78
83
  }): Promise<UI_MESSAGE[]>;
79
84
  /**
80
85
  * Sends one user message into the Turn running now. Retrying with the same
@@ -129,7 +129,11 @@ export class BlazingAgentsChatTransport {
129
129
  }
130
130
  /**
131
131
  * Reads the Session's stored transcript through the relay, oldest first.
132
- * @param options - Optional cancellation signal.
132
+ * Pages are read newest first. With `known`, the read stops at the first
133
+ * page whose oldest message is in `known`, and the known messages before
134
+ * that one complete the transcript, so a transcript that changed only near
135
+ * its end costs one request.
136
+ * @param options - `known`: messages already known to be stored, oldest first. Optional cancellation signal.
133
137
  * @returns The stored messages, validated as `UIMessage`s; empty without a Session.
134
138
  * @throws BlazingAgentsError - The relay's error, such as 404 `not_found` when the Session is gone or belongs to another End-user; `invalid_response` when a page or message is malformed; `network_error` or `request_aborted` when the request fails.
135
139
  */
@@ -138,32 +142,32 @@ export class BlazingAgentsChatTransport {
138
142
  if (sessionId === undefined) {
139
143
  return [];
140
144
  }
145
+ const { abortSignal, known = [] } = options;
141
146
  const pages = [];
142
147
  const cursors = new Set();
143
148
  let cursor;
149
+ let kept = [];
144
150
  do {
145
- const page = await this.#post({ op: "history", sessionId, cursor }, relayHistoryPageSchema, options.abortSignal);
146
- pages.unshift(page.data);
151
+ const page = await this.#post({ op: "history", sessionId, cursor }, relayHistoryPageSchema, abortSignal);
152
+ const messages = await validateHistory(page.data);
153
+ pages.unshift(messages);
154
+ const oldest = known.findIndex((message) => message.id === messages[0]?.id);
155
+ if (oldest !== -1) {
156
+ kept = known.slice(0, oldest);
157
+ break;
158
+ }
147
159
  if (page.nextCursor === null || cursors.has(page.nextCursor)) {
148
160
  break;
149
161
  }
150
162
  cursor = page.nextCursor;
151
163
  cursors.add(cursor);
152
164
  } while (pages.length < HISTORY_PAGE_LIMIT);
153
- const messages = pages.flat();
154
- if (messages.length === 0) {
155
- return [];
156
- }
157
- const validated = await safeValidateUIMessages({ messages });
158
- if (!validated.success) {
159
- throw new BlazingAgentsError({
160
- code: "invalid_response",
161
- message: "The relay returned a malformed history message.",
162
- }, { cause: validated.error });
163
- }
164
- // A Turn that commits while the pages are read can repeat a message on two pages.
165
+ const read = pages.flat();
166
+ const readIds = new Set(read.map((message) => message.id));
165
167
  return [
166
- ...new Map(validated.data.map((message) => [message.id, message])).values(),
168
+ ...kept.filter((message) => !readIds.has(message.id)),
169
+ // A Turn that commits while the pages are read can repeat a message on two pages.
170
+ ...new Map(read.map((message) => [message.id, message])).values(),
167
171
  ];
168
172
  }
169
173
  /**
@@ -226,6 +230,19 @@ export class BlazingAgentsChatTransport {
226
230
  }
227
231
  }
228
232
  }
233
+ async function validateHistory(messages) {
234
+ if (messages.length === 0) {
235
+ return [];
236
+ }
237
+ const validated = await safeValidateUIMessages({ messages });
238
+ if (!validated.success) {
239
+ throw new BlazingAgentsError({
240
+ code: "invalid_response",
241
+ message: "The relay returned a malformed history message.",
242
+ }, { cause: validated.error });
243
+ }
244
+ return validated.data;
245
+ }
229
246
  function resolveOption(value) {
230
247
  return Promise.resolve(typeof value === "function" ? value() : value);
231
248
  }
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  /**
3
- * Schedule kinds — discriminated union, Cohand's kinds with croner-forked
4
- * next-run math. `staggerMs` is an optional cron load-spreading offset.
3
+ * Schedule kinds — discriminated union. `staggerMs` is an optional cron
4
+ * load-spreading offset.
5
5
  */
6
6
  export declare const taskScheduleKindSchema: z.ZodEnum<{
7
7
  cron: "cron";
@@ -15,8 +15,10 @@ export declare const taskIntervalConfigSchema: z.ZodObject<{
15
15
  everyMs: z.ZodNumber;
16
16
  }, z.core.$strict>;
17
17
  /**
18
- * Croner validates the expression in the schedule's own timezone. The DBOS
19
- * schedule plan uses that validated expression and timezone unchanged.
18
+ * A cron schedule: five numeric fields in an IANA timezone. The schema checks
19
+ * only that shape. The API validates the expression's values in the
20
+ * schedule's own timezone, so an out-of-range field or an impossible date
21
+ * fails there.
20
22
  */
21
23
  export declare const taskCronConfigSchema: z.ZodObject<{
22
24
  expression: z.ZodString;
@@ -1,4 +1,3 @@
1
- import { Cron } from "croner";
2
1
  import { z } from "zod";
3
2
  import { paginatedResponseSchema, receivedApiErrorCodeSchema } from "../api.js";
4
3
  import { agentIdSchema, sessionIdSchema, taskIdSchema, taskRunIdSchema, tenantIdSchema, turnIdSchema, } from "../ids.js";
@@ -8,8 +7,8 @@ import { agentConfigSchema } from "./agents.js";
8
7
  import { metadataSchema, userIdSchema } from "./attribution.js";
9
8
  import { sessionMessagesResponseSchema } from "./sessions.js";
10
9
  /**
11
- * Schedule kinds — discriminated union, Cohand's kinds with croner-forked
12
- * next-run math. `staggerMs` is an optional cron load-spreading offset.
10
+ * Schedule kinds — discriminated union. `staggerMs` is an optional cron
11
+ * load-spreading offset.
13
12
  */
14
13
  export const taskScheduleKindSchema = z.enum(["once", "interval", "cron"]);
15
14
  export const taskOnceConfigSchema = z
@@ -24,7 +23,7 @@ export const taskIntervalConfigSchema = z
24
23
  .strict();
25
24
  const CRON_FIELDS_SEPARATOR = /\s+/;
26
25
  const NUMERIC_CRON_EXPRESSION = /^[\d*,/\-\s]+$/;
27
- /** Croner owns cron grammar; the product limits schedules to five numeric fields. */
26
+ /** The product limits schedules to five numeric fields. The API checks the values. */
28
27
  const cronExpressionSchema = z
29
28
  .string()
30
29
  .trim()
@@ -35,7 +34,7 @@ const cronExpressionSchema = z
35
34
  /**
36
35
  * Canonical IANA timezone: `UTC` or `Area/Location` (optionally
37
36
  * `Area/Location/Sublocation`). Rejects legacy abbreviations (`PST`, `GMT`)
38
- * that `Intl` quietly accepts but `croner` cannot resolve deterministically.
37
+ * that `Intl` quietly accepts but a scheduler cannot resolve deterministically.
39
38
  */
40
39
  const IANA_TIMEZONE_REGEX = /^(UTC|[A-Za-z_]+\/[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)?)$/;
41
40
  const ianaTimezoneSchema = z
@@ -54,8 +53,10 @@ const ianaTimezoneSchema = z
54
53
  }
55
54
  }, { message: "Unknown IANA timezone." });
56
55
  /**
57
- * Croner validates the expression in the schedule's own timezone. The DBOS
58
- * schedule plan uses that validated expression and timezone unchanged.
56
+ * A cron schedule: five numeric fields in an IANA timezone. The schema checks
57
+ * only that shape. The API validates the expression's values in the
58
+ * schedule's own timezone, so an out-of-range field or an impossible date
59
+ * fails there.
59
60
  */
60
61
  export const taskCronConfigSchema = z
61
62
  .object({
@@ -63,27 +64,7 @@ export const taskCronConfigSchema = z
63
64
  staggerMs: z.number().int().min(0).optional(),
64
65
  timezone: ianaTimezoneSchema.default("UTC"),
65
66
  })
66
- .strict()
67
- .superRefine((config, ctx) => {
68
- try {
69
- const cron = new Cron(config.expression, {
70
- paused: true,
71
- timezone: config.timezone,
72
- });
73
- // A five-field expression repeats, so a run after the epoch exists
74
- // exactly when one after now does; this keeps parsing off the clock.
75
- if (cron.nextRun(new Date(0)) === null) {
76
- throw new Error("no next run");
77
- }
78
- }
79
- catch {
80
- ctx.addIssue({
81
- code: "custom",
82
- message: "Invalid cron expression.",
83
- path: ["expression"],
84
- });
85
- }
86
- });
67
+ .strict();
87
68
  export const taskScheduleInputSchema = z.discriminatedUnion("kind", [
88
69
  z
89
70
  .object({
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * `UIMessage` is re-exported from `ai`, never redeclared.
5
5
  */
6
6
  export type { UIMessage } from "ai";
7
+ export { BlazingAgentsChat, type BlazingAgentsChatOptions, type BlazingAgentsChatSnapshot, } from "./chat-controller.ts";
7
8
  export { BlazingAgentsChatTransport, type BlazingAgentsChatTransportOptions, type SteerOutcome, } from "./chat-transport.ts";
8
9
  export { BlazingAgents } from "./client.ts";
9
10
  export type { ApprovalDecision, ApprovalPolicy, ToolExecutionReference, ToolReference, } from "./contracts/entities/agent-approval.ts";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * `UIMessage` is re-exported from `ai`, never redeclared.
5
5
  */
6
6
  // biome-ignore lint/performance/noBarrelFile: package entry point
7
+ export { BlazingAgentsChat, } from "./chat-controller.js";
7
8
  export { BlazingAgentsChatTransport, } from "./chat-transport.js";
8
9
  export { BlazingAgents } from "./client.js";
9
10
  export { AGENT_TOOL_FILE_ACCESS_TAGS, AGENT_TOOL_GROUPS, AGENT_TOOL_TAGS, AGENT_TOOLS, } from "./contracts/entities/agent-tools.js";
@@ -1,5 +1,5 @@
1
1
  /**
2
2
  * `@blazingagents/sdk/react`: the browser chat hook. The only entry that
3
- * imports `react` and `@ai-sdk/react`; `.` and `./rest` never load them.
3
+ * imports `react`; `.` and `./rest` never load it.
4
4
  */
5
- export { type BlazingAgentsChat, type UseBlazingAgentsChatOptions, useBlazingAgentsChat, } from "./use-blazing-agents-chat.ts";
5
+ export { type UseBlazingAgentsChatOptions, type UseBlazingAgentsChatResult, useBlazingAgentsChat, } from "./use-blazing-agents-chat.ts";
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `@blazingagents/sdk/react`: the browser chat hook. The only entry that
3
- * imports `react` and `@ai-sdk/react`; `.` and `./rest` never load them.
3
+ * imports `react`; `.` and `./rest` never load it.
4
4
  */
5
5
  // biome-ignore lint/performance/noBarrelFile: package entry point
6
6
  export { useBlazingAgentsChat, } from "./use-blazing-agents-chat.js";
@@ -1,76 +1,19 @@
1
- import { type FileUIPart, type UIMessage } from "ai";
1
+ import type { UIMessage } from "ai";
2
+ import { BlazingAgentsChat, type BlazingAgentsChatOptions, type BlazingAgentsChatSnapshot } from "../chat-controller.ts";
2
3
  import type { BlazingAgentsUIMessage } from "../types.ts";
3
- export interface UseBlazingAgentsChatOptions {
4
- /** The app's relay endpoint: `createChatRelay`, or a relay in another language. Default `/api/chat`. */
5
- api?: string;
6
- credentials?: RequestCredentials;
7
- fetch?: typeof globalThis.fetch;
8
- /**
9
- * Request headers, read at request time, so a new token applies to the next
10
- * request. When their values change while history could not be read, the
11
- * hook reads it again, as it does on the next `send` or `clearError`.
12
- */
4
+ export type UseBlazingAgentsChatOptions = Omit<BlazingAgentsChatOptions, "headers"> & {
5
+ /** Request headers, read at each request. */
13
6
  headers?: Record<string, string> | Headers;
14
- /**
15
- * localStorage key for the Session ID. Default `blazing-agents-session`;
16
- * `null` keeps the Session in memory only, as does storage that throws.
17
- * Read after mount, so server rendering never touches storage.
18
- */
19
- storageKey?: string | null;
20
- }
21
- export interface BlazingAgentsChat<M extends UIMessage = BlazingAgentsUIMessage> {
22
- /**
23
- * Answers a pending Tool approval. Once every approval of the round is
24
- * answered, the continuation streams like any Turn.
25
- * @param response - The approval ID, the decision, and an optional reason.
26
- */
27
- addToolApprovalResponse(response: {
28
- approved: boolean;
29
- id: string;
30
- reason?: string;
31
- }): void;
32
- /** True when idle with a stored assistant reply to replace. */
33
- readonly canRegenerate: boolean;
34
- /** Clears `error`. When history could not be read, also reads it again. */
35
- clearError(): void;
36
- /** The last failure: a failed Turn, steer, or history read. Cleared by the next send. */
37
- readonly error: Error | undefined;
38
- /** What to render, oldest first: the stored transcript, the streaming reply, and sent messages not stored yet. */
39
- readonly messages: readonly M[];
40
- /** Cancels any running Turn, forgets the stored Session, and clears the transcript. */
41
- newSession(): void;
42
- /** IDs in `messages` that are sent but not stored yet. */
43
- readonly pendingIds: ReadonlySet<string>;
44
- /** Replaces the last assistant reply. Does nothing unless `canRegenerate`. */
45
- regenerate(): void;
46
- /**
47
- * Sends a user message. Idle: starts a Turn. While a Turn runs: steers into
48
- * it, or sends it as the next Turn when this one cannot take it. Never sends
49
- * a message twice.
50
- * @param input - Text, or text with files.
51
- * @returns Resolves true once the message is stored in the Session, and false when it was rolled back by an error, Stop, or New Session. Never rejects.
52
- */
53
- send(input: string | {
54
- files?: FileUIPart[];
55
- text: string;
56
- }): Promise<boolean>;
57
- /** The Session, once restored or minted by the first reply. */
58
- readonly sessionId: string | undefined;
59
- /**
60
- * `restoring`: reading the stored transcript, or, after that read failed
61
- * (see `error`), waiting for new `headers`, a `send`, or `clearError` to
62
- * read it again. `running`: a Turn is starting, streaming, or being placed
63
- * in stored history. `send` works in every status.
64
- */
65
- readonly status: "restoring" | "idle" | "running";
66
- /** Cancels the running Turn and rolls back to the stored transcript. */
67
- stop(): void;
68
- }
7
+ };
8
+ /** The chat's snapshot and its actions; see `BlazingAgentsChat`. */
9
+ export type UseBlazingAgentsChatResult<M extends UIMessage = BlazingAgentsUIMessage> = BlazingAgentsChatSnapshot<M> & Pick<BlazingAgentsChat<M>, "addToolApprovalResponse" | "clearError" | "newSession" | "regenerate" | "send" | "stop">;
69
10
  /**
70
- * A Blazing Agents chat through the app's relay, with the Session kept in
71
- * localStorage, history restored after a reload, steering while a reply
72
- * streams, and rollback on failure.
11
+ * A Blazing Agents chat through the app's relay: one `BlazingAgentsChat` per
12
+ * component, started after mount and disposed on unmount. New `headers`, or
13
+ * new values in the same `Headers` object, apply to the next request, even one
14
+ * a child's effect sends in the same commit; the other options are read on the
15
+ * first render.
73
16
  * @param options - Relay endpoint, request options, and storage key.
74
- * @returns The chat; see `BlazingAgentsChat`.
17
+ * @returns The chat's snapshot and its actions.
75
18
  */
76
- export declare function useBlazingAgentsChat<M extends UIMessage = BlazingAgentsUIMessage>(options?: UseBlazingAgentsChatOptions): BlazingAgentsChat<M>;
19
+ export declare function useBlazingAgentsChat<M extends UIMessage = BlazingAgentsUIMessage>(options?: UseBlazingAgentsChatOptions): UseBlazingAgentsChatResult<M>;