@blazingagents/sdk 0.50.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,425 @@
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.
7
+ */
8
+ import { isToolUIPart, lastAssistantMessageIsCompleteWithApprovalResponses, } from "ai";
9
+ export const initialChatState = {
10
+ completed: [],
11
+ error: undefined,
12
+ outbox: [],
13
+ phase: { kind: "restoring", load: "running" },
14
+ };
15
+ /**
16
+ * Applies one event, then the `drain` rule. Pure and total: an event that
17
+ * does not apply to the current phase, such as a late steer answer after a
18
+ * rollback, leaves the state unchanged.
19
+ * @param state - Current state.
20
+ * @param event - What happened.
21
+ * @param newId - Mints steer request IDs and the fresh message ID a resend gets.
22
+ * @returns The next state and the effects to run, in order.
23
+ */
24
+ export function step(state, event, newId) {
25
+ return drain(apply(state, event, newId), newId);
26
+ }
27
+ /** True when idle with a stored assistant reply to replace. */
28
+ export function canRegenerate(state) {
29
+ return (state.phase.kind === "idle" &&
30
+ state.outbox.length === 0 &&
31
+ state.completed.at(-1)?.role === "assistant" &&
32
+ !awaitsApproval(state.completed));
33
+ }
34
+ /** IDs of the messages sent but not stored yet, the running prompt included. */
35
+ export function pendingIds(state) {
36
+ const ids = new Set(state.outbox.map((entry) => entry.message.id));
37
+ const { phase } = state;
38
+ if ((phase.kind === "starting" || phase.kind === "streaming") &&
39
+ phase.prompt) {
40
+ ids.add(phase.prompt.message.id);
41
+ }
42
+ return ids;
43
+ }
44
+ function apply(state, event, newId) {
45
+ const { phase } = state;
46
+ switch (event.type) {
47
+ case "restore":
48
+ return {
49
+ state: { ...state, phase: { kind: "restoring", load: "running" } },
50
+ effects: [{ type: "loadHistory" }],
51
+ };
52
+ case "credentialsChanged":
53
+ if (phase.kind === "restoring" && phase.load !== "failed") {
54
+ return noEffects({
55
+ ...state,
56
+ phase: { kind: "restoring", load: "stale" },
57
+ });
58
+ }
59
+ return restoreAgain(state);
60
+ case "historyLoaded":
61
+ return historyLoaded(state, event.messages);
62
+ case "historyFailed":
63
+ return historyFailed(state, event);
64
+ case "send":
65
+ return restoreAgain({
66
+ ...state,
67
+ error: undefined,
68
+ outbox: [...state.outbox, { ...event.sent, stage: "waiting" }],
69
+ });
70
+ case "regenerate":
71
+ return canRegenerate(state)
72
+ ? {
73
+ state: {
74
+ ...state,
75
+ error: undefined,
76
+ phase: { kind: "starting", prompt: null },
77
+ },
78
+ effects: [{ type: "regenerate" }],
79
+ }
80
+ : noEffects(state);
81
+ case "approvalAnswered":
82
+ return phase.kind === "idle"
83
+ ? noEffects({ ...state, phase: { kind: "starting", prompt: null } })
84
+ : noEffects(state);
85
+ case "turnStarted":
86
+ // Outside `starting`, Chat sent an approval continuation on its own.
87
+ return noEffects({
88
+ ...state,
89
+ phase: {
90
+ kind: "streaming",
91
+ prompt: phase.kind === "starting" ? phase.prompt : null,
92
+ finished: false,
93
+ },
94
+ });
95
+ case "turnFinished":
96
+ return phase.kind === "streaming"
97
+ ? noEffects({ ...state, phase: { ...phase, finished: true } })
98
+ : noEffects(state);
99
+ case "turnEnded":
100
+ return turnEnded(state, event.result, newId);
101
+ case "steerAnswered":
102
+ return noEffects({
103
+ ...state,
104
+ outbox: state.outbox.map((entry) => entry.stage === "steering" && entry.requestId === event.requestId
105
+ ? answered(entry, event.outcome, phase, newId)
106
+ : entry),
107
+ });
108
+ case "steerFailed":
109
+ return steerFailed(state, event, newId);
110
+ case "steerConsumed":
111
+ return noEffects({
112
+ ...state,
113
+ outbox: state.outbox.map((entry) => (entry.stage === "steering" || entry.stage === "accepted") &&
114
+ entry.requestId === event.requestId
115
+ ? { ...entry, stage: "consumed" }
116
+ : entry),
117
+ });
118
+ case "stop":
119
+ return phase.kind === "starting" || phase.kind === "streaming"
120
+ ? { state, effects: [{ type: "abort" }] }
121
+ : noEffects(state);
122
+ case "newSession": {
123
+ const ended = endConversation(state);
124
+ return {
125
+ state: {
126
+ completed: [],
127
+ error: undefined,
128
+ outbox: [],
129
+ phase: { kind: "idle" },
130
+ },
131
+ effects: [...ended, { type: "forgetSession" }],
132
+ };
133
+ }
134
+ case "unmount":
135
+ return { state: initialChatState, effects: endConversation(state) };
136
+ case "clearError":
137
+ return restoreAgain({ ...state, error: undefined });
138
+ }
139
+ }
140
+ /** Reads history again when the restore failed; otherwise changes nothing. */
141
+ function restoreAgain(state) {
142
+ return state.phase.kind === "restoring" && state.phase.load === "failed"
143
+ ? {
144
+ state: { ...state, phase: { kind: "restoring", load: "running" } },
145
+ effects: [{ type: "loadHistory" }],
146
+ }
147
+ : noEffects(state);
148
+ }
149
+ function historyLoaded(state, messages) {
150
+ if (state.phase.kind === "restoring") {
151
+ return {
152
+ state: {
153
+ ...state,
154
+ completed: messages,
155
+ error: undefined,
156
+ phase: { kind: "idle" },
157
+ },
158
+ effects: [{ type: "show", messages }],
159
+ };
160
+ }
161
+ if (state.phase.kind === "reconciling") {
162
+ const stored = new Set(messages.map((message) => message.id));
163
+ return {
164
+ state: {
165
+ ...state,
166
+ completed: messages,
167
+ outbox: state.outbox.filter((entry) => !placedByHistory(entry)),
168
+ phase: { kind: "idle" },
169
+ },
170
+ effects: [
171
+ { type: "show", messages },
172
+ ...settlePlaced(state, (entry) => stored.has(entry.message.id)),
173
+ ],
174
+ };
175
+ }
176
+ return noEffects(state);
177
+ }
178
+ function historyFailed(state, { error, sessionGone }) {
179
+ const { phase } = state;
180
+ if (phase.kind === "restoring") {
181
+ if (sessionGone) {
182
+ return {
183
+ state: {
184
+ ...state,
185
+ completed: [],
186
+ error: undefined,
187
+ phase: { kind: "idle" },
188
+ },
189
+ effects: [{ type: "forgetSession" }],
190
+ };
191
+ }
192
+ return phase.load === "stale"
193
+ ? {
194
+ state: { ...state, phase: { kind: "restoring", load: "running" } },
195
+ effects: [{ type: "loadHistory" }],
196
+ }
197
+ : noEffects({
198
+ ...state,
199
+ error,
200
+ phase: { kind: "restoring", load: "failed" },
201
+ });
202
+ }
203
+ if (phase.kind === "reconciling") {
204
+ // A completed Turn stored its steers, but where they sit is unknown; append
205
+ // them. What a Turn that ended without `finish` stored is unknown; roll it back.
206
+ const completed = [
207
+ ...state.completed,
208
+ ...state.outbox
209
+ .filter((entry) => entry.stage === "consumed")
210
+ .map((entry) => entry.message),
211
+ ];
212
+ return {
213
+ state: {
214
+ ...state,
215
+ completed,
216
+ error,
217
+ outbox: state.outbox.filter((entry) => !placedByHistory(entry)),
218
+ phase: { kind: "idle" },
219
+ },
220
+ effects: [
221
+ { type: "show", messages: completed },
222
+ ...settlePlaced(state, () => false),
223
+ ],
224
+ };
225
+ }
226
+ return noEffects(state);
227
+ }
228
+ function turnEnded(state, result, newId) {
229
+ const { phase } = state;
230
+ if (phase.kind !== "starting" && phase.kind !== "streaming") {
231
+ return noEffects(state);
232
+ }
233
+ const error = result.outcome === "failed" ? result.error : undefined;
234
+ if (result.outcome === "failed" && result.sessionGone) {
235
+ return {
236
+ state: { completed: [], error, outbox: [], phase: { kind: "idle" } },
237
+ effects: [...settlePending(state), { type: "forgetSession" }],
238
+ };
239
+ }
240
+ if (phase.kind === "starting") {
241
+ // The relay never answered with a stream, so the Turn stored nothing.
242
+ return {
243
+ state: { ...state, error, outbox: [], phase: { kind: "idle" } },
244
+ effects: [
245
+ { type: "show", messages: state.completed },
246
+ ...settlePending(state),
247
+ ],
248
+ };
249
+ }
250
+ if (result.outcome !== "closed" || !phase.finished) {
251
+ // The Turn may have stored its prompt and steers before the stream ended.
252
+ const outbox = [...(phase.prompt ? [phase.prompt] : []), ...state.outbox];
253
+ return {
254
+ state: {
255
+ ...state,
256
+ error,
257
+ outbox: outbox.map(({ key, message }) => ({
258
+ key,
259
+ message,
260
+ stage: "unconfirmed",
261
+ })),
262
+ phase: { kind: "reconciling" },
263
+ },
264
+ effects: [
265
+ { type: "show", messages: state.completed },
266
+ { type: "loadHistory" },
267
+ ],
268
+ };
269
+ }
270
+ // Accepted at the Turn's end without being read means the receipt is not_placed.
271
+ const outbox = state.outbox.map((entry) => entry.stage === "accepted" || entry.stage === "refused"
272
+ ? resend(entry, newId)
273
+ : entry);
274
+ return {
275
+ state: {
276
+ ...state,
277
+ completed: result.messages,
278
+ outbox,
279
+ // AI SDK sends a complete approval round itself right after onFinish.
280
+ phase: lastAssistantMessageIsCompleteWithApprovalResponses({
281
+ messages: result.messages,
282
+ })
283
+ ? { kind: "starting", prompt: null }
284
+ : { kind: "idle" },
285
+ },
286
+ effects: phase.prompt
287
+ ? [{ type: "settle", key: phase.prompt.key, landed: true }]
288
+ : [],
289
+ };
290
+ }
291
+ function steerFailed(state, { answerLost, error, requestId, }, newId) {
292
+ const failed = state.outbox.find((entry) => entry.stage === "steering" && entry.requestId === requestId);
293
+ if (!failed) {
294
+ return noEffects(state);
295
+ }
296
+ if (answerLost) {
297
+ // The relay may have taken it, so it counts as accepted.
298
+ return noEffects({
299
+ ...state,
300
+ outbox: state.outbox.map((entry) => entry === failed
301
+ ? answered({ ...failed, requestId }, "accepted", state.phase, newId)
302
+ : entry),
303
+ });
304
+ }
305
+ return {
306
+ state: {
307
+ ...state,
308
+ error,
309
+ outbox: state.outbox.filter((entry) => entry !== failed),
310
+ },
311
+ effects: [{ type: "settle", key: failed.key, landed: false }],
312
+ };
313
+ }
314
+ /**
315
+ * Where a steer goes once the relay answers. An accepted one waits while a
316
+ * Turn is starting or streaming, since that Turn may read it and its end
317
+ * decides. A refused one waits for the streaming Turn to end, since steering
318
+ * it again now would only be refused again. Otherwise it is resent.
319
+ */
320
+ function answered(entry, outcome, phase, newId) {
321
+ if (outcome === "committed") {
322
+ return { ...entry, stage: "consumed" };
323
+ }
324
+ if (outcome === "accepted" &&
325
+ (phase.kind === "starting" || phase.kind === "streaming")) {
326
+ return { ...entry, stage: "accepted" };
327
+ }
328
+ if (outcome === "resend" && phase.kind === "streaming") {
329
+ return { ...entry, stage: "refused" };
330
+ }
331
+ return resend(entry, newId);
332
+ }
333
+ function resend({ key, message }, newId) {
334
+ return { key, message: { ...message, id: newId() }, stage: "waiting" };
335
+ }
336
+ /** Aborts a live Turn and resolves every pending `send()` with false. */
337
+ function endConversation(state) {
338
+ const live = state.phase.kind === "starting" || state.phase.kind === "streaming";
339
+ return [
340
+ ...(live ? [{ type: "abort" }] : []),
341
+ ...settlePending(state),
342
+ ];
343
+ }
344
+ /** Resolves the running prompt's and every outbox entry's `send()` with false. */
345
+ function settlePending(state) {
346
+ const { phase } = state;
347
+ const prompt = (phase.kind === "starting" || phase.kind === "streaming") && phase.prompt
348
+ ? [phase.prompt]
349
+ : [];
350
+ return [...prompt, ...state.outbox].map(({ key }) => ({
351
+ type: "settle",
352
+ key,
353
+ landed: false,
354
+ }));
355
+ }
356
+ /** Entries a history read settles: steers a completed Turn read, and messages of a Turn that ended without `finish`. */
357
+ function placedByHistory(entry) {
358
+ return entry.stage === "consumed" || entry.stage === "unconfirmed";
359
+ }
360
+ /**
361
+ * Resolves each entry a history read settles: a read steer as landed, an
362
+ * unconfirmed message as `stored` says.
363
+ */
364
+ function settlePlaced(state, stored) {
365
+ return state.outbox.filter(placedByHistory).map((entry) => ({
366
+ type: "settle",
367
+ key: entry.key,
368
+ landed: entry.stage === "consumed" || stored(entry),
369
+ }));
370
+ }
371
+ /**
372
+ * Moves queued messages; runs after every event. Idle: read history again
373
+ * when it must settle an entry, else the oldest waiting message starts a
374
+ * Turn unless a manual approval is pending. Streaming: every waiting message
375
+ * steers. Any other phase: nothing moves.
376
+ */
377
+ function drain({ effects, state }, newId) {
378
+ if (state.phase.kind === "streaming") {
379
+ const steers = [];
380
+ const outbox = state.outbox.map((entry) => {
381
+ if (entry.stage !== "waiting") {
382
+ return entry;
383
+ }
384
+ const requestId = newId();
385
+ steers.push({ type: "submitSteer", message: entry.message, requestId });
386
+ return { ...entry, stage: "steering", requestId };
387
+ });
388
+ return { state: { ...state, outbox }, effects: [...effects, ...steers] };
389
+ }
390
+ if (state.phase.kind !== "idle") {
391
+ return { state, effects };
392
+ }
393
+ if (state.outbox.some(placedByHistory)) {
394
+ return {
395
+ state: { ...state, phase: { kind: "reconciling" } },
396
+ effects: [...effects, { type: "loadHistory" }],
397
+ };
398
+ }
399
+ const next = state.outbox.find((entry) => entry.stage === "waiting");
400
+ if (!next || awaitsApproval(state.completed)) {
401
+ return { state, effects };
402
+ }
403
+ return {
404
+ state: {
405
+ ...state,
406
+ outbox: state.outbox.filter((entry) => entry !== next),
407
+ phase: {
408
+ kind: "starting",
409
+ prompt: { key: next.key, message: next.message },
410
+ },
411
+ },
412
+ effects: [...effects, { type: "startTurn", message: next.message }],
413
+ };
414
+ }
415
+ /** A manual Tool approval blocks the Session until it is decided. */
416
+ function awaitsApproval(messages) {
417
+ return (messages
418
+ .findLast((message) => message.role === "assistant")
419
+ ?.parts.some((part) => isToolUIPart(part) &&
420
+ part.state === "approval-requested" &&
421
+ part.approval.isAutomatic !== true) === true);
422
+ }
423
+ function noEffects(state) {
424
+ return { state, effects: [] };
425
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * `@blazingagents/sdk/react`: the browser chat hook. The only entry that
3
+ * imports `react` and `@ai-sdk/react`; `.` and `./rest` never load them.
4
+ */
5
+ export { type BlazingAgentsChat, type UseBlazingAgentsChatOptions, useBlazingAgentsChat, } from "./use-blazing-agents-chat.ts";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@blazingagents/sdk/react`: the browser chat hook. The only entry that
3
+ * imports `react` and `@ai-sdk/react`; `.` and `./rest` never load them.
4
+ */
5
+ // biome-ignore lint/performance/noBarrelFile: package entry point
6
+ export { useBlazingAgentsChat, } from "./use-blazing-agents-chat.js";
@@ -0,0 +1,76 @@
1
+ import { type FileUIPart, type UIMessage } from "ai";
2
+ 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
+ */
13
+ 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
+ }
69
+ /**
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.
73
+ * @param options - Relay endpoint, request options, and storage key.
74
+ * @returns The chat; see `BlazingAgentsChat`.
75
+ */
76
+ export declare function useBlazingAgentsChat<M extends UIMessage = BlazingAgentsUIMessage>(options?: UseBlazingAgentsChatOptions): BlazingAgentsChat<M>;