Skip to content

Commit 9e84cbb

Browse files
adrien2pTrigger.dev RepoOps
authored andcommitted
refactor(sdk): steer, run actions and stop through the session client
Mono-RevId: 5855f7f239c8a35b8d1b01a357a9f9e9ab94d65a
1 parent cb60133 commit 9e84cbb

5 files changed

Lines changed: 628 additions & 253 deletions

File tree

‎packages/trigger-sdk/src/v3/chat-session-ports.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ export function serializeInputChunk(chunk: ChatInputChunk): string {
123123
return JSON.stringify(chunk);
124124
}
125125

126+
/** The size of a serialized record's body on the wire, for the send events. */
127+
export function byteLength(body: string): number {
128+
return new TextEncoder().encode(body).byteLength;
129+
}
130+
126131
/** The ports a `TriggerChatTransport` gives its sessions: its `accessToken`, `startSession` and `clientData` callbacks and its `fetch`, each read live on every call. */
127132
export function browserSessionPorts(host: BrowserSessionHost): SessionPorts {
128133
return {

‎packages/trigger-sdk/src/v3/chat-session-stream.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,42 @@ export type SessionStreamHost = {
150150
) => ReturnType<typeof drainOutRecordsPage>;
151151
};
152152

153+
/** Where a send's turn starts on `.out`, as found by the lookup that precedes its subscription. */
154+
export type LocatedTurnStart = {
155+
holdUntilBoundary: boolean;
156+
startCursor: string | undefined;
157+
abortedWhileLocating: boolean;
158+
};
159+
160+
/**
161+
* One signal that aborts when either input does, without `AbortSignal.any`, which
162+
* keeps a listener on the caller's long-lived signal for as long as that lives.
163+
* `dispose` removes ours once the work it covered has settled.
164+
*/
165+
export function linkSignals(
166+
callerSignal: AbortSignal | undefined,
167+
own: AbortSignal
168+
): { signal: AbortSignal; dispose: () => void } {
169+
if (!callerSignal) return { signal: own, dispose: () => {} };
170+
const linked = new AbortController();
171+
const abortFrom = (source: AbortSignal) => () => linked.abort(source.reason);
172+
const onCaller = abortFrom(callerSignal);
173+
const onOwn = abortFrom(own);
174+
if (callerSignal.aborted) onCaller();
175+
else if (own.aborted) onOwn();
176+
else {
177+
callerSignal.addEventListener("abort", onCaller, { once: true });
178+
own.addEventListener("abort", onOwn, { once: true });
179+
}
180+
return {
181+
signal: linked.signal,
182+
dispose: () => {
183+
callerSignal.removeEventListener("abort", onCaller);
184+
own.removeEventListener("abort", onOwn);
185+
},
186+
};
187+
}
188+
153189
/** A stream that is already done: what a superseded or stopped send hands back. */
154190
export function closedStream(): ReadableStream<UIMessageChunk> {
155191
return new ReadableStream<UIMessageChunk>({

‎packages/trigger-sdk/src/v3/chat-session.ts‎

Lines changed: 286 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,18 @@
1-
import type { ChatSessionPersistedState } from "./chat.js";
1+
import type { UIMessage, UIMessageChunk } from "ai";
2+
import { byteLength, serializeInputChunk } from "./chat-session-ports.js";
3+
import {
4+
closedStream,
5+
linkSignals,
6+
subscribeToSessionStream,
7+
type LocatedTurnStart,
8+
type SessionStreamHost,
9+
} from "./chat-session-stream.js";
10+
import type {
11+
ChatActionOptions,
12+
ChatSessionPersistedState,
13+
ChatTaskWirePayload,
14+
ChatTransportSendSource,
15+
} from "./chat.js";
216

317
/**
418
* Internal state for tracking one chat session. Sessions are task-bound and the
@@ -121,6 +135,84 @@ function stateFromRecord(
121135
return state;
122136
}
123137

138+
/**
139+
* Counts a send that writes a user record to `.in` (a message, an action or a steering
140+
* message; `ChatSessionState.turnSends`) before its append goes out: a stop's renewal
141+
* that finishes between the append landing and the count would otherwise still see the
142+
* older turn and fire into the new one (or into the steered one).
143+
* The count never goes back, whatever becomes of the send: a failure status can
144+
* follow an attempt that landed (the app's `fetch` may have retried after losing a
145+
* response, and the append route answers 413 for a request with no length as well
146+
* as for a body over its limit), so no status proves that no turn started.
147+
*/
148+
export function countTurnSend(state: ChatSessionState): void {
149+
state.turnSends = (state.turnSends ?? 0) + 1;
150+
}
151+
152+
/**
153+
* Whether a send now replaces a turn that is still outstanding and was not
154+
* stopped: a resumed reply the user stopped reading (which writes no stop), or
155+
* a reader the send itself supersedes. That turn keeps writing to `.out`, and
156+
* the session's cursor sits partway into it, past its `turn-start` marker, so
157+
* its remaining chunks would reach the send's answer. The send's stream holds
158+
* them until that turn's boundary instead (`holdUntilBoundary`). A stream error
159+
* leaves the turn's `.in` seq set (it may still be running), so a send after
160+
* one is held too. A stop arms the gate, which skips them already, and an
161+
* abandoned turn is not coming back. With no cursor the send's own lookup
162+
* decides (`findTurnStart`), so this is for a send that reads on from one.
163+
* Without the send's `.in` seq (an older webapp reports none) a stream can't
164+
* tell the turns apart, so holding would only delay the answer. Call before the
165+
* send overwrites `activeInputSeq`.
166+
*/
167+
export function replacesUnfinishedTurn(
168+
state: ChatSessionState,
169+
inSeq: number | undefined
170+
): boolean {
171+
return (
172+
inSeq !== undefined &&
173+
state.lastEventId !== undefined &&
174+
!state.skipToTurnComplete &&
175+
!state.outstandingTurnAbandoned &&
176+
(state.isStreaming === true || state.activeInputSeq !== undefined)
177+
);
178+
}
179+
180+
/**
181+
* The resume point persisted for a send's turn. A send that replaces an
182+
* unfinished turn reads from partway into it, which a reload must not resume
183+
* from: with no cursor it finds where the turn starts the way a cursorless send
184+
* does, and drops the earlier turn's records.
185+
*/
186+
export function sendTurnStart(
187+
state: ChatSessionState,
188+
replacesUnfinished: boolean
189+
): { lastEventId: string | undefined } {
190+
return { lastEventId: replacesUnfinished ? undefined : state.lastEventId };
191+
}
192+
193+
/**
194+
* What the session's commands read from the transport that owns the client, on top
195+
* of what its `.out` read loop does. Read live on each call.
196+
*/
197+
export type SessionCommandHost = SessionStreamHost & {
198+
/** The transport's `clientData`, merged under a send's own metadata. */
199+
clientData(): Record<string, unknown> | undefined;
200+
/** Runs a send op, emitting its terminal `message-sent` / `message-send-failed` event. */
201+
sendWithEvents<T>(
202+
chatId: string,
203+
source: ChatTransportSendSource,
204+
extras: { messageId?: string; partId?: string; bodyBytes?: number },
205+
op: () => Promise<T>
206+
): Promise<T>;
207+
/** Finds where the turn a send opened starts on `.out`, when the session has no cursor. */
208+
locateTurnStart(
209+
chatId: string,
210+
state: ChatSessionState,
211+
inSeq: number | undefined,
212+
abortSignal: AbortSignal | undefined
213+
): Promise<LocatedTurnStart>;
214+
};
215+
124216
/**
125217
* One chat's session state: the live internal record the transport reads and
126218
* writes as records arrive, and a snapshot of it that changes only on `commit`.
@@ -132,6 +224,7 @@ export class ChatSessionClient {
132224

133225
constructor(
134226
readonly chatId: string,
227+
private readonly host: SessionCommandHost,
135228
record: ChatSessionPersistedState,
136229
cursor?: TranscriptCursor
137230
) {
@@ -215,4 +308,196 @@ export class ChatSessionClient {
215308
this.snapshot = { chatId: this.chatId, persisted: persistedStateOf(state) };
216309
for (const listener of [...this.listeners]) listener();
217310
}
311+
312+
/**
313+
* Send a steering message during an active stream without disrupting
314+
* it. The agent's `pendingMessages` config decides whether to inject
315+
* between tool-call steps or buffer for the next turn. Appends only: never
316+
* starts a session, and resolves to whether the append landed. Rejects when the
317+
* message body can't be serialised (a `BigInt` in `metadata`, say), appending nothing.
318+
*/
319+
async steer(message: UIMessage, metadata?: Record<string, unknown>): Promise<boolean> {
320+
const state = this.current;
321+
const chatId = this.chatId;
322+
countTurnSend(state);
323+
324+
const clientData = this.host.clientData();
325+
const mergedMetadata =
326+
clientData || metadata ? { ...(clientData ?? {}), ...(metadata ?? {}) } : undefined;
327+
328+
const wirePayload: ChatTaskWirePayload = {
329+
message,
330+
chatId,
331+
trigger: "submit-message" as const,
332+
metadata: mergedMetadata,
333+
};
334+
335+
const partId = crypto.randomUUID();
336+
const serializedBody = serializeInputChunk({ kind: "message", payload: wirePayload });
337+
const send = async (token: string) => {
338+
await this.host.ports.endpoint.appendInput({ chatId, token, body: serializedBody, partId });
339+
};
340+
341+
try {
342+
await this.host.sendWithEvents(
343+
chatId,
344+
"steer",
345+
{ messageId: message.id, partId, bodyBytes: byteLength(serializedBody) },
346+
() => this.host.callWithAuthRetry(chatId, state, send)
347+
);
348+
return true;
349+
} catch {
350+
return false;
351+
}
352+
}
353+
354+
/**
355+
* Stop the current generation. Sends `{kind:"stop"}` on `.in`; the
356+
* agent aborts its `streamText` call but stays alive for the next
357+
* message. Stops reading the stream at once.
358+
*/
359+
async stop(): Promise<boolean> {
360+
const state = this.current;
361+
const chatId = this.chatId;
362+
363+
const partId = crypto.randomUUID();
364+
const serializedBody = serializeInputChunk({ kind: "stop" });
365+
const send = async (token: string) => {
366+
await this.host.ports.endpoint.appendInput({ chatId, token, body: serializedBody, partId });
367+
};
368+
369+
try {
370+
await this.host.sendWithEvents(
371+
chatId,
372+
"stop",
373+
{ partId, bodyBytes: byteLength(serializedBody) },
374+
() => this.host.callWithAuthRetry(chatId, state, send)
375+
);
376+
} catch {
377+
return false;
378+
}
379+
380+
// Only gate when a sent turn is still outstanding. A stop at a boundary has
381+
// nothing to supersede, and gating it would swallow the next turn.
382+
if (
383+
!state.outstandingTurnAbandoned &&
384+
(state.isStreaming || state.activeInputSeq !== undefined)
385+
) {
386+
state.skipToTurnComplete = true;
387+
state.supersededInputSeq = state.activeInputSeq;
388+
}
389+
390+
this.host.streams.abortAndForget(chatId);
391+
// Release here, not in the stream teardown: that only releases while it
392+
// still owns the map entry, and we just deleted it. Unlike a supersede,
393+
// no successor stream follows a stop, so the claim would never be freed
394+
// and other tabs would stay read-only until this one closes.
395+
this.host.ports.tabs.release(chatId);
396+
397+
// The turn won't reach its turn-complete on this client (we just
398+
// aborted the reader), so clear the streaming flag here and persist —
399+
// otherwise a reload resumes mid-turn and replays the chunks the user
400+
// explicitly stopped.
401+
state.isStreaming = false;
402+
state.turnStart = undefined;
403+
this.commit(state);
404+
return true;
405+
}
406+
407+
/**
408+
* Clear the supersede gate armed by a stop. Call this when the stopped
409+
* turn died without ever writing its `trigger:turn-complete` boundary,
410+
* otherwise the next turn stays gated forever.
411+
*/
412+
clearStopGate(): void {
413+
const state = this.current;
414+
state.skipToTurnComplete = false;
415+
state.supersededInputSeq = undefined;
416+
state.outstandingTurnAbandoned = true;
417+
}
418+
}
419+
420+
/**
421+
* Send a custom action chunk (for `chat.agent`'s `actionSchema` /
422+
* `onAction` hook). An action is an edit: only `hydrateMessages` and
423+
* `onAction` fire on the agent side, and the returned stream completes
424+
* with `trigger:turn-complete` once the edit is persisted. When `onAction`
425+
* returns `chat.turn()` the turn's response follows on the same stream.
426+
* Per-action `metadata` is merged over the client's `clientData`.
427+
*
428+
* Acts on the state `statePromise` resolves to, not on the client's live one: the
429+
* transport starts the session and hands that start in, so a `setSession` that
430+
* lands while it resolves does not move the action onto the new session. One async
431+
* function holds all three awaits, so the action settles on the same microtask
432+
* turns as the transport's `sendAction` did when it ran them itself. A function,
433+
* not a client method, because a first send has no session client until the
434+
* start registers one.
435+
*/
436+
export async function runAction(
437+
host: SessionCommandHost,
438+
chatId: string,
439+
statePromise: Promise<ChatSessionState>,
440+
action: unknown,
441+
options?: ChatActionOptions
442+
): Promise<ReadableStream<UIMessageChunk>> {
443+
const state = await statePromise;
444+
countTurnSend(state);
445+
446+
const clientData = host.clientData();
447+
const wirePayload: ChatTaskWirePayload = {
448+
chatId,
449+
trigger: "action" as const,
450+
action,
451+
metadata:
452+
clientData || options?.metadata
453+
? { ...(clientData ?? {}), ...(options?.metadata ?? {}) }
454+
: undefined,
455+
};
456+
457+
const body = serializeInputChunk({ kind: "message", payload: wirePayload });
458+
const partId = crypto.randomUUID();
459+
const send = (token: string) => host.ports.endpoint.appendInput({ chatId, token, body, partId });
460+
461+
const inSeq = await host.sendWithEvents(
462+
chatId,
463+
"action",
464+
{ partId, bodyBytes: byteLength(body) },
465+
() => host.callWithAuthRetry(chatId, state, send)
466+
);
467+
468+
// Supersede any in-flight reader before subscribing, as `sendMessages` does.
469+
// Two concurrent readers both write `state.lastEventId` and the slower one can
470+
// regress the cursor, replaying records on the next reconnect.
471+
// Registered before the lookup below, so a stop or reconnect in that window
472+
// finds this action's stream.
473+
const turnAbort = host.streams.supersede(chatId);
474+
475+
// Mark streaming + persist so a reload mid-action resumes (reconnectToStream
476+
// no-ops when the persisted session says isStreaming: false).
477+
const replacesUnfinished = replacesUnfinishedTurn(state, inSeq);
478+
state.activeInputSeq = inSeq;
479+
state.isStreaming = true;
480+
state.turnStart = sendTurnStart(state, replacesUnfinished);
481+
state.outstandingTurnAbandoned = false;
482+
host.notifySessionChange(chatId, state);
483+
484+
const lookup = linkSignals(options?.abortSignal, turnAbort.signal);
485+
let located: LocatedTurnStart;
486+
try {
487+
located = await host.locateTurnStart(chatId, state, inSeq, lookup.signal);
488+
} finally {
489+
lookup.dispose();
490+
}
491+
// Same as `sendMessages`: a stop or a newer send already ended this stream.
492+
if (turnAbort.signal.aborted) return closedStream();
493+
494+
// Owning action: aborting this send stops the turn the user drives.
495+
return subscribeToSessionStream(host, state, options?.abortSignal, chatId, {
496+
streamAbort: turnAbort,
497+
sinceInSeq: inSeq,
498+
sendStopOnAbort: true,
499+
onSettled: options?.onSettled,
500+
...located,
501+
holdUntilBoundary: located.holdUntilBoundary || replacesUnfinished,
502+
});
218503
}

0 commit comments

Comments
 (0)