@blazingagents/sdk 0.51.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.
- package/README.md +72 -6
- package/dist/chat-relay-wire.d.ts +53 -0
- package/dist/chat-relay-wire.js +60 -0
- package/dist/chat-transport.d.ts +57 -4
- package/dist/chat-transport.js +158 -17
- package/dist/contracts/entities/session-inputs.d.ts +4 -4
- package/dist/contracts/entities/session-inputs.js +1 -1
- package/dist/contracts/entities/session-messages.d.ts +20 -0
- package/dist/contracts/entities/session-messages.js +21 -0
- package/dist/contracts/entities/sessions.d.ts +0 -19
- package/dist/contracts/entities/sessions.js +1 -20
- package/dist/contracts/index.d.ts +3 -2
- package/dist/contracts/index.js +2 -1
- package/dist/http.d.ts +27 -1
- package/dist/http.js +42 -27
- package/dist/index.d.ts +1 -1
- package/dist/react/chat-state.d.ts +197 -0
- package/dist/react/chat-state.js +425 -0
- package/dist/react/index.d.ts +5 -0
- package/dist/react/index.js +6 -0
- package/dist/react/use-blazing-agents-chat.d.ts +76 -0
- package/dist/react/use-blazing-agents-chat.js +246 -0
- package/dist/relay.d.ts +10 -4
- package/dist/relay.js +99 -53
- package/package.json +22 -1
package/README.md
CHANGED
|
@@ -26,8 +26,9 @@ Node.js 24 or newer.
|
|
|
26
26
|
- End-user scoped clients through `forUser`.
|
|
27
27
|
- Cursor pagination, uploads, and downloads.
|
|
28
28
|
- Request IDs and typed errors.
|
|
29
|
-
- `
|
|
30
|
-
|
|
29
|
+
- `createChatRelay` serves browser chat from your backend, and
|
|
30
|
+
`useBlazingAgentsChat` from `@blazingagents/sdk/react` drives it from React:
|
|
31
|
+
history restore, steering, and rollback included.
|
|
31
32
|
|
|
32
33
|
## Installation
|
|
33
34
|
|
|
@@ -96,10 +97,75 @@ export async function chatAsUser(
|
|
|
96
97
|
|
|
97
98
|
Call `createAgentForUser` once per user and store the Agent ID with the user.
|
|
98
99
|
A scoped chat with an Agent created without the scope fails with `404`.
|
|
99
|
-
`chatAsUser` returns the chat as a streaming `Response`.
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
100
|
+
`chatAsUser` returns the chat as a streaming `Response`.
|
|
101
|
+
|
|
102
|
+
## Chat from a browser
|
|
103
|
+
|
|
104
|
+
The browser holds no API key, so it chats through your backend. Serve
|
|
105
|
+
`createChatRelay` on one route. It answers chat, history, and steer requests
|
|
106
|
+
as the End-user that your `resolveContext` returns:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { createChatRelay } from "@blazingagents/sdk";
|
|
110
|
+
|
|
111
|
+
export const relayChat = createChatRelay({
|
|
112
|
+
client,
|
|
113
|
+
resolveContext: async (request) => {
|
|
114
|
+
const user = await signedInUser(request);
|
|
115
|
+
return user ? { agentId: user.agentId, userId: user.id } : null;
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
app.post("/api/chat", (c) => relayChat(c.req.raw));
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`signedInUser` stands for your own session lookup. In React, install the
|
|
123
|
+
optional peers and call `useBlazingAgentsChat`:
|
|
124
|
+
|
|
125
|
+
```console
|
|
126
|
+
npm install react @ai-sdk/react
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
```tsx
|
|
130
|
+
import { useBlazingAgentsChat } from "@blazingagents/sdk/react";
|
|
131
|
+
import { useState } from "react";
|
|
132
|
+
|
|
133
|
+
export function Chat({ token }: { token: string }) {
|
|
134
|
+
const [text, setText] = useState("");
|
|
135
|
+
const chat = useBlazingAgentsChat({
|
|
136
|
+
headers: { authorization: `Bearer ${token}` },
|
|
137
|
+
});
|
|
138
|
+
return (
|
|
139
|
+
<form
|
|
140
|
+
onSubmit={(event) => {
|
|
141
|
+
event.preventDefault();
|
|
142
|
+
chat.send(text);
|
|
143
|
+
setText("");
|
|
144
|
+
}}
|
|
145
|
+
>
|
|
146
|
+
{chat.messages.map((message) => (
|
|
147
|
+
<p key={message.id}>
|
|
148
|
+
{message.role}:{" "}
|
|
149
|
+
{message.parts.map((part) => (part.type === "text" ? part.text : ""))}
|
|
150
|
+
</p>
|
|
151
|
+
))}
|
|
152
|
+
<input value={text} onChange={(event) => setText(event.target.value)} />
|
|
153
|
+
</form>
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The hook posts to `/api/chat` unless you pass `api`. It keeps the Session ID
|
|
159
|
+
in `localStorage` and restores the stored transcript after a reload. `send()`
|
|
160
|
+
starts a Turn when the chat is idle and steers the running Turn otherwise. It
|
|
161
|
+
resolves `true` once the message is stored, and `false` when an error, Stop,
|
|
162
|
+
or New Session rolled it back, so you can put the text back in the input. The
|
|
163
|
+
hook also returns `status`, `stop()`, `regenerate()`, `newSession()`,
|
|
164
|
+
`addToolApprovalResponse()`, `pendingIds`, and `error`.
|
|
165
|
+
|
|
166
|
+
`BlazingAgentsChatTransport` is the same browser side without React, for an
|
|
167
|
+
AI SDK `Chat` in another framework. A relay written in another language
|
|
168
|
+
follows the [browser relay contract](docs/relay-contract.md).
|
|
103
169
|
|
|
104
170
|
## Examples
|
|
105
171
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser-to-relay wire: one POST endpoint whose JSON body names its
|
|
3
|
+
* `op`. `relay.ts` parses requests with these schemas and builds responses
|
|
4
|
+
* that satisfy them; `chat-transport.ts` builds requests from the same types
|
|
5
|
+
* and parses the responses. No public entry exports this module.
|
|
6
|
+
* `docs/relay-contract.md` states the same contract for relays written in
|
|
7
|
+
* other languages; change both together.
|
|
8
|
+
*/
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
/** The relay asks the API for this many messages per history page, the API's maximum. */
|
|
11
|
+
export declare const RELAY_HISTORY_PAGE_SIZE = 200;
|
|
12
|
+
/**
|
|
13
|
+
* Inbound relay body. Unknown keys are stripped, so an app's own `body`
|
|
14
|
+
* extras, read by its `resolveContext`, never reach the API.
|
|
15
|
+
*/
|
|
16
|
+
export declare const relayRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
17
|
+
op: z.ZodLiteral<"chat">;
|
|
18
|
+
message: z.ZodUnknown;
|
|
19
|
+
messageId: z.ZodOptional<z.ZodString>;
|
|
20
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
21
|
+
trigger: z.ZodDefault<z.ZodEnum<{
|
|
22
|
+
"regenerate-message": "regenerate-message";
|
|
23
|
+
"submit-message": "submit-message";
|
|
24
|
+
}>>;
|
|
25
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
26
|
+
op: z.ZodLiteral<"history">;
|
|
27
|
+
sessionId: z.ZodString;
|
|
28
|
+
cursor: z.ZodOptional<z.ZodString>;
|
|
29
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
30
|
+
op: z.ZodLiteral<"steer">;
|
|
31
|
+
sessionId: z.ZodString;
|
|
32
|
+
requestId: z.ZodString;
|
|
33
|
+
message: z.ZodUnknown;
|
|
34
|
+
}, z.core.$strip>], "op">;
|
|
35
|
+
export type RelayRequest = z.output<typeof relayRequestSchema>;
|
|
36
|
+
export type RelayRequestBody = z.input<typeof relayRequestSchema>;
|
|
37
|
+
/**
|
|
38
|
+
* `history` 200 body: one API page, newest page first and chronological
|
|
39
|
+
* within it. The relay passes stored messages through unvalidated; the
|
|
40
|
+
* browser validates them.
|
|
41
|
+
*/
|
|
42
|
+
export declare const relayHistoryPageSchema: z.ZodObject<{
|
|
43
|
+
data: z.ZodArray<z.ZodUnknown>;
|
|
44
|
+
nextCursor: z.ZodNullable<z.ZodString>;
|
|
45
|
+
}, z.core.$strip>;
|
|
46
|
+
/** `steer` 202 body: the receipt's state when the relay answered. */
|
|
47
|
+
export declare const relaySteerReceiptSchema: z.ZodObject<{
|
|
48
|
+
state: z.ZodEnum<{
|
|
49
|
+
accepted: "accepted";
|
|
50
|
+
committed: "committed";
|
|
51
|
+
not_placed: "not_placed";
|
|
52
|
+
}>;
|
|
53
|
+
}, z.core.$strip>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser-to-relay wire: one POST endpoint whose JSON body names its
|
|
3
|
+
* `op`. `relay.ts` parses requests with these schemas and builds responses
|
|
4
|
+
* that satisfy them; `chat-transport.ts` builds requests from the same types
|
|
5
|
+
* and parses the responses. No public entry exports this module.
|
|
6
|
+
* `docs/relay-contract.md` states the same contract for relays written in
|
|
7
|
+
* other languages; change both together.
|
|
8
|
+
*/
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { sessionInputRequestIdSchema, sessionInputStateSchema, } from "./contracts/entities/session-inputs.js";
|
|
11
|
+
import { sessionIdSchema } from "./contracts/ids.js";
|
|
12
|
+
/** The relay asks the API for this many messages per history page, the API's maximum. */
|
|
13
|
+
export const RELAY_HISTORY_PAGE_SIZE = 200;
|
|
14
|
+
const chatRequestSchema = z.object({
|
|
15
|
+
op: z.literal("chat"),
|
|
16
|
+
/** The last user message, or the last assistant message holding a complete approval-response round. */
|
|
17
|
+
message: z.unknown(),
|
|
18
|
+
messageId: z.string().min(1).optional(),
|
|
19
|
+
sessionId: sessionIdSchema.optional(),
|
|
20
|
+
trigger: z
|
|
21
|
+
.enum(["submit-message", "regenerate-message"])
|
|
22
|
+
.default("submit-message"),
|
|
23
|
+
});
|
|
24
|
+
const historyRequestSchema = z.object({
|
|
25
|
+
op: z.literal("history"),
|
|
26
|
+
sessionId: sessionIdSchema,
|
|
27
|
+
/** `nextCursor` from the previous page; absent for the newest page. */
|
|
28
|
+
cursor: z.string().min(1).optional(),
|
|
29
|
+
});
|
|
30
|
+
const steerRequestSchema = z.object({
|
|
31
|
+
op: z.literal("steer"),
|
|
32
|
+
sessionId: sessionIdSchema,
|
|
33
|
+
/** Idempotency key: the same requestId and message replay the receipt. */
|
|
34
|
+
requestId: sessionInputRequestIdSchema,
|
|
35
|
+
message: z.unknown(),
|
|
36
|
+
});
|
|
37
|
+
/**
|
|
38
|
+
* Inbound relay body. Unknown keys are stripped, so an app's own `body`
|
|
39
|
+
* extras, read by its `resolveContext`, never reach the API.
|
|
40
|
+
*/
|
|
41
|
+
export const relayRequestSchema = z.discriminatedUnion("op", [
|
|
42
|
+
chatRequestSchema,
|
|
43
|
+
historyRequestSchema,
|
|
44
|
+
steerRequestSchema,
|
|
45
|
+
]);
|
|
46
|
+
/**
|
|
47
|
+
* `history` 200 body: one API page, newest page first and chronological
|
|
48
|
+
* within it. The relay passes stored messages through unvalidated; the
|
|
49
|
+
* browser validates them.
|
|
50
|
+
*/
|
|
51
|
+
export const relayHistoryPageSchema = z
|
|
52
|
+
.object({
|
|
53
|
+
data: z.array(z.unknown()),
|
|
54
|
+
nextCursor: z.string().min(1).nullable(),
|
|
55
|
+
})
|
|
56
|
+
.strip();
|
|
57
|
+
/** `steer` 202 body: the receipt's state when the relay answered. */
|
|
58
|
+
export const relaySteerReceiptSchema = z
|
|
59
|
+
.object({ state: sessionInputStateSchema })
|
|
60
|
+
.strip();
|
package/dist/chat-transport.d.ts
CHANGED
|
@@ -1,22 +1,50 @@
|
|
|
1
|
-
import { type ChatTransport, type HttpChatTransportInitOptions, type UIMessage } from "ai";
|
|
1
|
+
import { type ChatTransport, type HttpChatTransportInitOptions, type UIMessage, type UIMessageChunk } from "ai";
|
|
2
2
|
export type BlazingAgentsChatTransportOptions<UI_MESSAGE extends UIMessage = UIMessage> = Omit<HttpChatTransportInitOptions<UI_MESSAGE>, "prepareReconnectToStreamRequest" | "prepareSendMessagesRequest"> & {
|
|
3
3
|
/**
|
|
4
4
|
* Receives the Session ID minted by the first successful response.
|
|
5
5
|
* @param sessionId - Session to look up or record.
|
|
6
6
|
*/
|
|
7
7
|
onSessionId?: (sessionId: string) => Promise<void> | void;
|
|
8
|
+
/**
|
|
9
|
+
* Called when the running Turn reads a steered message, from the transient
|
|
10
|
+
* `data-ba-steer-consumed` chunk. The chunk still reaches `Chat` as a
|
|
11
|
+
* transient data part.
|
|
12
|
+
* @param requestId - The steer's request ID.
|
|
13
|
+
*/
|
|
14
|
+
onSteerConsumed?: (requestId: string) => void;
|
|
15
|
+
/**
|
|
16
|
+
* Called when the running Turn's stream carries its `finish` chunk. A
|
|
17
|
+
* stream that ends without one, by Stop, a server `abort`, an error, or a
|
|
18
|
+
* dropped connection, did not complete, though the Turn may have stored its
|
|
19
|
+
* messages before it ended.
|
|
20
|
+
*/
|
|
21
|
+
onTurnFinish?: () => void;
|
|
8
22
|
/**
|
|
9
23
|
* Receives the running Turn ID from each response that names one, before
|
|
10
24
|
* its stream is consumed. Pass it to Stop.
|
|
11
25
|
* @param turnId - Turn the response runs.
|
|
12
26
|
*/
|
|
13
27
|
onTurnId?: (turnId: string) => Promise<void> | void;
|
|
28
|
+
/**
|
|
29
|
+
* Called when the relay answers a chat request with a stream, before any
|
|
30
|
+
* chunk is read. From then on the Turn accepts steers.
|
|
31
|
+
*/
|
|
32
|
+
onTurnStart?: () => void;
|
|
14
33
|
/** An authorized Session ID used to resume after a remount or reload. */
|
|
15
34
|
sessionId?: string;
|
|
16
35
|
};
|
|
17
36
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
37
|
+
* What a steer did, folded into what the caller does next:
|
|
38
|
+
* - `accepted`: the running Turn holds it and may still read it.
|
|
39
|
+
* - `committed`: it is stored with that Turn's history.
|
|
40
|
+
* - `resend`: it will never reach this Turn (its receipt is `not_placed`, or
|
|
41
|
+
* the relay answered 409 `steer_not_available`); send it as ordinary chat.
|
|
42
|
+
*/
|
|
43
|
+
export type SteerOutcome = "accepted" | "committed" | "resend";
|
|
44
|
+
/**
|
|
45
|
+
* Adapts AI SDK chat requests to the Blazing Agents relay, resumes with the
|
|
46
|
+
* server-minted Session ID returned in `Location`, and reads history and
|
|
47
|
+
* steers through the same relay endpoint.
|
|
20
48
|
*/
|
|
21
49
|
export declare class BlazingAgentsChatTransport<UI_MESSAGE extends UIMessage = UIMessage> implements ChatTransport<UI_MESSAGE> {
|
|
22
50
|
#private;
|
|
@@ -25,16 +53,41 @@ export declare class BlazingAgentsChatTransport<UI_MESSAGE extends UIMessage = U
|
|
|
25
53
|
* @param options - Configuration for this operation.
|
|
26
54
|
*/
|
|
27
55
|
constructor(options?: BlazingAgentsChatTransportOptions<UI_MESSAGE>);
|
|
56
|
+
/** The Session this transport talks to: the supplied one, or the one the first chat minted. */
|
|
57
|
+
get sessionId(): string | undefined;
|
|
28
58
|
/**
|
|
29
59
|
* Submits the latest user message or complete assistant approval round to the chat.
|
|
30
60
|
* @param input - Operation input and optional cancellation signal.
|
|
31
61
|
* @returns The decoded AI SDK message-chunk stream.
|
|
32
62
|
*/
|
|
33
|
-
sendMessages(input: Parameters<ChatTransport<UI_MESSAGE>["sendMessages"]>[0]): Promise<ReadableStream<
|
|
63
|
+
sendMessages(input: Parameters<ChatTransport<UI_MESSAGE>["sendMessages"]>[0]): Promise<ReadableStream<UIMessageChunk>>;
|
|
34
64
|
/**
|
|
35
65
|
* Returns null because reconnecting to an existing stream is unsupported.
|
|
36
66
|
* @param _input - Unused reconnect request.
|
|
37
67
|
* @returns A promise resolving to null.
|
|
38
68
|
*/
|
|
39
69
|
reconnectToStream(_input: Parameters<ChatTransport<UI_MESSAGE>["reconnectToStream"]>[0]): Promise<null>;
|
|
70
|
+
/**
|
|
71
|
+
* Reads the Session's stored transcript through the relay, oldest first.
|
|
72
|
+
* @param options - Optional cancellation signal.
|
|
73
|
+
* @returns The stored messages, validated as `UIMessage`s; empty without a Session.
|
|
74
|
+
* @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
|
+
*/
|
|
76
|
+
loadHistory(options?: {
|
|
77
|
+
abortSignal?: AbortSignal;
|
|
78
|
+
}): Promise<UI_MESSAGE[]>;
|
|
79
|
+
/**
|
|
80
|
+
* Sends one user message into the Turn running now. Retrying with the same
|
|
81
|
+
* `requestId` and message replays the receipt.
|
|
82
|
+
* @param input - The user message, its steer request ID, and an optional cancellation signal.
|
|
83
|
+
* @returns What the steer did; see `SteerOutcome`.
|
|
84
|
+
* @throws BlazingAgentsError - `invalid_request` without a Session; the relay's error, such as 409 `input_idempotency_conflict`; `network_error` when the answer was lost.
|
|
85
|
+
*/
|
|
86
|
+
steer(input: {
|
|
87
|
+
abortSignal?: AbortSignal;
|
|
88
|
+
message: UI_MESSAGE & {
|
|
89
|
+
role: "user";
|
|
90
|
+
};
|
|
91
|
+
requestId: string;
|
|
92
|
+
}): Promise<SteerOutcome>;
|
|
40
93
|
}
|
package/dist/chat-transport.js
CHANGED
|
@@ -1,12 +1,25 @@
|
|
|
1
|
-
import { lastAssistantMessageIsCompleteWithApprovalResponses, } from "ai";
|
|
1
|
+
import { lastAssistantMessageIsCompleteWithApprovalResponses, safeValidateUIMessages, } from "ai";
|
|
2
|
+
import { relayHistoryPageSchema, relaySteerReceiptSchema, } from "./chat-relay-wire.js";
|
|
2
3
|
import { ChatStreamTransport } from "./chat-stream-transport.js";
|
|
4
|
+
import { chatSteerConsumedEventSchema } from "./contracts/entities/session-inputs.js";
|
|
3
5
|
import { sessionIdSchema, turnIdSchema } from "./contracts/ids.js";
|
|
4
|
-
import { parseClientInput } from "./errors.js";
|
|
6
|
+
import { BlazingAgentsError, parseClientInput } from "./errors.js";
|
|
7
|
+
import { errorFromResponse, invalidResponseError, sendRequest, } from "./http.js";
|
|
8
|
+
/** At most this many history pages (of 200 messages) are read. */
|
|
9
|
+
const HISTORY_PAGE_LIMIT = 50;
|
|
5
10
|
/**
|
|
6
|
-
* Adapts AI SDK chat requests to the Blazing Agents
|
|
7
|
-
*
|
|
11
|
+
* Adapts AI SDK chat requests to the Blazing Agents relay, resumes with the
|
|
12
|
+
* server-minted Session ID returned in `Location`, and reads history and
|
|
13
|
+
* steers through the same relay endpoint.
|
|
8
14
|
*/
|
|
9
15
|
export class BlazingAgentsChatTransport {
|
|
16
|
+
#api;
|
|
17
|
+
#body;
|
|
18
|
+
#credentials;
|
|
19
|
+
#fetch;
|
|
20
|
+
#headers;
|
|
21
|
+
#onSteerConsumed;
|
|
22
|
+
#onTurnFinish;
|
|
10
23
|
#transport;
|
|
11
24
|
#sessionId;
|
|
12
25
|
/**
|
|
@@ -14,19 +27,26 @@ export class BlazingAgentsChatTransport {
|
|
|
14
27
|
* @param options - Configuration for this operation.
|
|
15
28
|
*/
|
|
16
29
|
constructor(options = {}) {
|
|
17
|
-
const { onSessionId, onTurnId, sessionId, ...transportOptions } = options;
|
|
30
|
+
const { onSessionId, onSteerConsumed, onTurnFinish, onTurnId, onTurnStart, sessionId, ...transportOptions } = options;
|
|
18
31
|
const transportFetch = transportOptions.fetch ?? globalThis.fetch;
|
|
32
|
+
this.#api = transportOptions.api ?? "/api/chat";
|
|
33
|
+
this.#body = transportOptions.body;
|
|
34
|
+
this.#credentials = transportOptions.credentials;
|
|
35
|
+
this.#fetch = transportFetch;
|
|
36
|
+
this.#headers = transportOptions.headers;
|
|
37
|
+
this.#onSteerConsumed = onSteerConsumed;
|
|
38
|
+
this.#onTurnFinish = onTurnFinish;
|
|
19
39
|
this.#sessionId =
|
|
20
40
|
sessionId === undefined
|
|
21
41
|
? undefined
|
|
22
42
|
: parseClientInput(sessionIdSchema, sessionId, "sessionId");
|
|
23
43
|
this.#transport = new ChatStreamTransport({
|
|
24
44
|
...transportOptions,
|
|
25
|
-
/**
|
|
45
|
+
/** Throws a relay error as a `BlazingAgentsError`, and reads the first Session ID and each Turn ID before returning the response. */
|
|
26
46
|
fetch: async (input, init) => {
|
|
27
47
|
const response = await transportFetch(input, init);
|
|
28
48
|
if (!response.ok) {
|
|
29
|
-
|
|
49
|
+
throw await errorFromResponse(response, init?.signal ?? undefined);
|
|
30
50
|
}
|
|
31
51
|
try {
|
|
32
52
|
if (this.#sessionId === undefined) {
|
|
@@ -44,6 +64,7 @@ export class BlazingAgentsChatTransport {
|
|
|
44
64
|
await response.body?.cancel(error).catch(() => undefined);
|
|
45
65
|
throw error;
|
|
46
66
|
}
|
|
67
|
+
onTurnStart?.();
|
|
47
68
|
return response;
|
|
48
69
|
},
|
|
49
70
|
/** Selects the user message or complete approval round for the relay request. */
|
|
@@ -59,25 +80,44 @@ export class BlazingAgentsChatTransport {
|
|
|
59
80
|
if (!message) {
|
|
60
81
|
throw new Error("Chat submission requires a user message.");
|
|
61
82
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
trigger,
|
|
69
|
-
},
|
|
83
|
+
const request = {
|
|
84
|
+
op: "chat",
|
|
85
|
+
message,
|
|
86
|
+
messageId,
|
|
87
|
+
sessionId: this.#sessionId,
|
|
88
|
+
trigger,
|
|
70
89
|
};
|
|
90
|
+
return { body: { ...body, ...request } };
|
|
71
91
|
},
|
|
72
92
|
});
|
|
73
93
|
}
|
|
94
|
+
/** The Session this transport talks to: the supplied one, or the one the first chat minted. */
|
|
95
|
+
get sessionId() {
|
|
96
|
+
return this.#sessionId;
|
|
97
|
+
}
|
|
74
98
|
/**
|
|
75
99
|
* Submits the latest user message or complete assistant approval round to the chat.
|
|
76
100
|
* @param input - Operation input and optional cancellation signal.
|
|
77
101
|
* @returns The decoded AI SDK message-chunk stream.
|
|
78
102
|
*/
|
|
79
|
-
sendMessages(input) {
|
|
80
|
-
|
|
103
|
+
async sendMessages(input) {
|
|
104
|
+
const onSteerConsumed = this.#onSteerConsumed;
|
|
105
|
+
const onTurnFinish = this.#onTurnFinish;
|
|
106
|
+
const stream = await this.#transport.sendMessages(input);
|
|
107
|
+
return stream.pipeThrough(new TransformStream({
|
|
108
|
+
transform(chunk, controller) {
|
|
109
|
+
if (chunk.type === "finish") {
|
|
110
|
+
onTurnFinish?.();
|
|
111
|
+
}
|
|
112
|
+
if (chunk.type === "data-ba-steer-consumed") {
|
|
113
|
+
const steer = chatSteerConsumedEventSchema.safeParse(chunk);
|
|
114
|
+
if (steer.success) {
|
|
115
|
+
onSteerConsumed?.(steer.data.data.requestId);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
controller.enqueue(chunk);
|
|
119
|
+
},
|
|
120
|
+
}));
|
|
81
121
|
}
|
|
82
122
|
/**
|
|
83
123
|
* Returns null because reconnecting to an existing stream is unsupported.
|
|
@@ -87,4 +127,105 @@ export class BlazingAgentsChatTransport {
|
|
|
87
127
|
reconnectToStream(_input) {
|
|
88
128
|
return Promise.resolve(null);
|
|
89
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Reads the Session's stored transcript through the relay, oldest first.
|
|
132
|
+
* @param options - Optional cancellation signal.
|
|
133
|
+
* @returns The stored messages, validated as `UIMessage`s; empty without a Session.
|
|
134
|
+
* @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
|
+
*/
|
|
136
|
+
async loadHistory(options = {}) {
|
|
137
|
+
const sessionId = this.#sessionId;
|
|
138
|
+
if (sessionId === undefined) {
|
|
139
|
+
return [];
|
|
140
|
+
}
|
|
141
|
+
const pages = [];
|
|
142
|
+
const cursors = new Set();
|
|
143
|
+
let cursor;
|
|
144
|
+
do {
|
|
145
|
+
const page = await this.#post({ op: "history", sessionId, cursor }, relayHistoryPageSchema, options.abortSignal);
|
|
146
|
+
pages.unshift(page.data);
|
|
147
|
+
if (page.nextCursor === null || cursors.has(page.nextCursor)) {
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
cursor = page.nextCursor;
|
|
151
|
+
cursors.add(cursor);
|
|
152
|
+
} 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
|
+
return [
|
|
166
|
+
...new Map(validated.data.map((message) => [message.id, message])).values(),
|
|
167
|
+
];
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Sends one user message into the Turn running now. Retrying with the same
|
|
171
|
+
* `requestId` and message replays the receipt.
|
|
172
|
+
* @param input - The user message, its steer request ID, and an optional cancellation signal.
|
|
173
|
+
* @returns What the steer did; see `SteerOutcome`.
|
|
174
|
+
* @throws BlazingAgentsError - `invalid_request` without a Session; the relay's error, such as 409 `input_idempotency_conflict`; `network_error` when the answer was lost.
|
|
175
|
+
*/
|
|
176
|
+
async steer(input) {
|
|
177
|
+
const sessionId = this.#sessionId;
|
|
178
|
+
if (sessionId === undefined) {
|
|
179
|
+
throw new BlazingAgentsError({
|
|
180
|
+
code: "invalid_request",
|
|
181
|
+
message: "Steering requires an existing Session.",
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const receipt = await this.#post({
|
|
186
|
+
op: "steer",
|
|
187
|
+
sessionId,
|
|
188
|
+
requestId: input.requestId,
|
|
189
|
+
message: input.message,
|
|
190
|
+
}, relaySteerReceiptSchema, input.abortSignal);
|
|
191
|
+
return receipt.state === "not_placed" ? "resend" : receipt.state;
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (BlazingAgentsError.isInstance(error) &&
|
|
195
|
+
error.code === "steer_not_available") {
|
|
196
|
+
return "resend";
|
|
197
|
+
}
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/** POSTs one JSON op to the relay with the transport's headers, credentials, and body extras. */
|
|
202
|
+
async #post(request, schema, abortSignal) {
|
|
203
|
+
const [extras, headers, credentials] = await Promise.all([
|
|
204
|
+
resolveOption(this.#body),
|
|
205
|
+
resolveOption(this.#headers),
|
|
206
|
+
resolveOption(this.#credentials),
|
|
207
|
+
]);
|
|
208
|
+
const requestHeaders = new Headers(headers);
|
|
209
|
+
requestHeaders.set("content-type", "application/json");
|
|
210
|
+
const response = await sendRequest(this.#fetch, this.#api, {
|
|
211
|
+
body: JSON.stringify({ ...extras, ...request }),
|
|
212
|
+
credentials,
|
|
213
|
+
headers: requestHeaders,
|
|
214
|
+
method: "POST",
|
|
215
|
+
signal: abortSignal,
|
|
216
|
+
});
|
|
217
|
+
if (!response.ok) {
|
|
218
|
+
throw await errorFromResponse(response, abortSignal);
|
|
219
|
+
}
|
|
220
|
+
const text = await response.text();
|
|
221
|
+
try {
|
|
222
|
+
return schema.parse(JSON.parse(text));
|
|
223
|
+
}
|
|
224
|
+
catch (cause) {
|
|
225
|
+
throw invalidResponseError(response.headers, response.status, text, false, cause);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function resolveOption(value) {
|
|
230
|
+
return Promise.resolve(typeof value === "function" ? value() : value);
|
|
90
231
|
}
|
|
@@ -9,12 +9,12 @@ export declare const sessionInputSchema: z.ZodObject<{
|
|
|
9
9
|
requestId: z.ZodString;
|
|
10
10
|
sequence: z.ZodNumber;
|
|
11
11
|
message: z.ZodObject<{
|
|
12
|
-
role: z.ZodLiteral<"user">;
|
|
13
12
|
id: z.ZodString;
|
|
14
13
|
parts: z.ZodArray<z.ZodObject<{
|
|
15
14
|
type: z.ZodString;
|
|
16
15
|
}, z.core.$loose>>;
|
|
17
16
|
metadata: z.ZodOptional<z.ZodUnknown>;
|
|
17
|
+
role: z.ZodLiteral<"user">;
|
|
18
18
|
}, z.core.$loose>;
|
|
19
19
|
state: z.ZodEnum<{
|
|
20
20
|
accepted: "accepted";
|
|
@@ -45,12 +45,12 @@ export declare const sessionInputResponseSchema: z.ZodObject<{
|
|
|
45
45
|
requestId: z.ZodString;
|
|
46
46
|
sequence: z.ZodNumber;
|
|
47
47
|
message: z.ZodObject<{
|
|
48
|
-
role: z.ZodLiteral<"user">;
|
|
49
48
|
id: z.ZodString;
|
|
50
49
|
parts: z.ZodArray<z.ZodObject<{
|
|
51
50
|
type: z.ZodString;
|
|
52
51
|
}, z.core.$loose>>;
|
|
53
52
|
metadata: z.ZodOptional<z.ZodUnknown>;
|
|
53
|
+
role: z.ZodLiteral<"user">;
|
|
54
54
|
}, z.core.$loose>;
|
|
55
55
|
state: z.ZodEnum<{
|
|
56
56
|
accepted: "accepted";
|
|
@@ -82,12 +82,12 @@ export declare const sessionInputsResponseSchema: z.ZodObject<{
|
|
|
82
82
|
requestId: z.ZodString;
|
|
83
83
|
sequence: z.ZodNumber;
|
|
84
84
|
message: z.ZodObject<{
|
|
85
|
-
role: z.ZodLiteral<"user">;
|
|
86
85
|
id: z.ZodString;
|
|
87
86
|
parts: z.ZodArray<z.ZodObject<{
|
|
88
87
|
type: z.ZodString;
|
|
89
88
|
}, z.core.$loose>>;
|
|
90
89
|
metadata: z.ZodOptional<z.ZodUnknown>;
|
|
90
|
+
role: z.ZodLiteral<"user">;
|
|
91
91
|
}, z.core.$loose>;
|
|
92
92
|
state: z.ZodEnum<{
|
|
93
93
|
accepted: "accepted";
|
|
@@ -156,12 +156,12 @@ export declare const chatSteerConsumedEventSchema: z.ZodObject<{
|
|
|
156
156
|
requestId: z.ZodString;
|
|
157
157
|
sequence: z.ZodNumber;
|
|
158
158
|
message: z.ZodObject<{
|
|
159
|
-
role: z.ZodLiteral<"user">;
|
|
160
159
|
id: z.ZodString;
|
|
161
160
|
parts: z.ZodArray<z.ZodObject<{
|
|
162
161
|
type: z.ZodString;
|
|
163
162
|
}, z.core.$loose>>;
|
|
164
163
|
metadata: z.ZodOptional<z.ZodUnknown>;
|
|
164
|
+
role: z.ZodLiteral<"user">;
|
|
165
165
|
}, z.core.$loose>;
|
|
166
166
|
turnId: z.ZodString;
|
|
167
167
|
}, z.core.$strip>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
|
|
4
|
+
* `UIMessage[]` verbatim, paginated backwards (newest page first) with an
|
|
5
|
+
* optional forward `?after={cursor}` for the poll loop.
|
|
6
|
+
*/
|
|
7
|
+
export declare const sessionMessageSchema: z.ZodObject<{
|
|
8
|
+
id: z.ZodString;
|
|
9
|
+
role: z.ZodEnum<{
|
|
10
|
+
assistant: "assistant";
|
|
11
|
+
system: "system";
|
|
12
|
+
user: "user";
|
|
13
|
+
}>;
|
|
14
|
+
branchable: z.ZodBoolean;
|
|
15
|
+
parts: z.ZodArray<z.ZodObject<{
|
|
16
|
+
type: z.ZodString;
|
|
17
|
+
}, z.core.$loose>>;
|
|
18
|
+
metadata: z.ZodOptional<z.ZodUnknown>;
|
|
19
|
+
}, z.core.$loose>;
|
|
20
|
+
export type SessionMessage = z.infer<typeof sessionMessageSchema>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
|
|
4
|
+
* `UIMessage[]` verbatim, paginated backwards (newest page first) with an
|
|
5
|
+
* optional forward `?after={cursor}` for the poll loop.
|
|
6
|
+
*/
|
|
7
|
+
export const sessionMessageSchema = z
|
|
8
|
+
.object({
|
|
9
|
+
id: z.string().min(1),
|
|
10
|
+
role: z.enum(["system", "user", "assistant"]),
|
|
11
|
+
branchable: z.boolean(),
|
|
12
|
+
parts: z
|
|
13
|
+
.array(z
|
|
14
|
+
.object({
|
|
15
|
+
type: z.string().min(1),
|
|
16
|
+
})
|
|
17
|
+
.passthrough())
|
|
18
|
+
.min(1),
|
|
19
|
+
metadata: z.unknown().optional(),
|
|
20
|
+
})
|
|
21
|
+
.passthrough();
|
|
@@ -193,24 +193,6 @@ export declare const latestSessionsListResponseSchema: z.ZodObject<{
|
|
|
193
193
|
}, z.core.$strip>>;
|
|
194
194
|
nextCursor: z.ZodNullable<z.ZodString>;
|
|
195
195
|
}, z.core.$strip>;
|
|
196
|
-
/**
|
|
197
|
-
* `GET /v1/agents/{agentId}/sessions/{sessionId}/messages` — transcript as
|
|
198
|
-
* `UIMessage[]` verbatim, paginated backwards (newest page first) with an
|
|
199
|
-
* optional forward `?after={cursor}` for the poll loop.
|
|
200
|
-
*/
|
|
201
|
-
export declare const sessionMessageSchema: z.ZodObject<{
|
|
202
|
-
id: z.ZodString;
|
|
203
|
-
role: z.ZodEnum<{
|
|
204
|
-
assistant: "assistant";
|
|
205
|
-
system: "system";
|
|
206
|
-
user: "user";
|
|
207
|
-
}>;
|
|
208
|
-
branchable: z.ZodBoolean;
|
|
209
|
-
parts: z.ZodArray<z.ZodObject<{
|
|
210
|
-
type: z.ZodString;
|
|
211
|
-
}, z.core.$loose>>;
|
|
212
|
-
metadata: z.ZodOptional<z.ZodUnknown>;
|
|
213
|
-
}, z.core.$loose>;
|
|
214
196
|
/**
|
|
215
197
|
* The messages endpoint carries two cursors: `nextCursor` for continuing
|
|
216
198
|
* pagination in the requested direction (backward `?cursor=` walks older
|
|
@@ -382,7 +364,6 @@ export type TurnStreamErrorEvent = z.infer<typeof turnStreamErrorEventSchema>;
|
|
|
382
364
|
export type SessionForkedFrom = z.infer<typeof sessionForkedFromSchema>;
|
|
383
365
|
export type SessionListItem = z.infer<typeof sessionListItemSchema>;
|
|
384
366
|
export type LatestSessionListItem = z.infer<typeof latestSessionListItemSchema>;
|
|
385
|
-
export type SessionMessage = z.infer<typeof sessionMessageSchema>;
|
|
386
367
|
export type SessionResponse = z.infer<typeof sessionResponseSchema>;
|
|
387
368
|
export type SessionsListResponse = z.infer<typeof sessionsListResponseSchema>;
|
|
388
369
|
export type LatestSessionsListResponse = z.infer<typeof latestSessionsListResponseSchema>;
|