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