Skip to content

Commit 77fb02d

Browse files
adrien2pTrigger.dev RepoOps
authored andcommitted
fix(sdk): answer each AgentChat send with its own turn
Mono-RevId: 873a736d1c57b2a5189dbd132d19cc71f674b3b9
1 parent 4ed63d4 commit 77fb02d

26 files changed

Lines changed: 4051 additions & 217 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@trigger.dev/sdk": patch
3+
"@trigger.dev/core": patch
4+
---
5+
6+
Fix `AgentChat` returning another turn's reply, or several replies joined together, instead of the answer to the message you sent: for example when continuing a chat without a saved `lastEventId`, sending two messages in a row, or when a run answers earlier messages first. Agents now mark where each turn starts and where steered messages join one on the output stream, so redeploy them on this version; with an older agent, a reply `AgentChat` can't match to your message is delivered when its turn completes instead of streamed. Custom readers of the session output stream must skip control records they don't recognise. A send aborted before its stream starts now asks the agent to stop.

‎apps/webapp/test/sessionRunCompletionContinuation.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,25 @@ async function pushTurnComplete(
431431
]);
432432
}
433433

434+
/**
435+
* A `turn-start` marker on `.out`, written ahead of a turn's first chunk: what a run leaves when it
436+
* dies after starting a turn and before writing anything of the answer.
437+
*/
438+
async function pushTurnStart(ctx: Ctx, inSeq: number | undefined) {
439+
await appendRecords(ctx, "out", [
440+
{
441+
body: "",
442+
headers: [
443+
["trigger-control", "turn-start"],
444+
...(inSeq !== undefined
445+
? ([["turn-start-in-seq", String(inSeq)]] as Array<[string, string]>)
446+
: []),
447+
],
448+
timestamp: Date.now(),
449+
},
450+
]);
451+
}
452+
434453
/** A partial chunk of an answer on `.out`: what a run leaves when it dies mid-turn. */
435454
async function pushChunk(ctx: Ctx, timestamp: number = Date.now()) {
436455
await appendRecords(ctx, "out", [
@@ -1122,6 +1141,49 @@ describe("a run that failed", () => {
11221141
}
11231142
);
11241143

1144+
// Catches: a run that died right after it began a turn (its `turn-start` marker is the last record
1145+
// on `.out`, no chunk written yet) being continued as if it had finished, so the message it was
1146+
// answering is re-run and can crash the same way. The marker leaves the tail a record that is not a
1147+
// turn-complete, which is how every mid-turn death is told apart.
1148+
postgresTest(
1149+
"starts nothing when it died right after its turn-start marker",
1150+
async ({ prisma }) => {
1151+
const ctx = await setup(prisma as unknown as PrismaClient);
1152+
const { run } = await sessionWithLiveRun(prisma as unknown as PrismaClient, ctx);
1153+
await pushIn(ctx, message("previous"));
1154+
await pushTurnComplete(ctx, 0);
1155+
await pushIn(ctx, message("answering"));
1156+
await pushTurnStart(ctx, 1);
1157+
await finish(prisma as unknown as PrismaClient, run.id, "CRASHED");
1158+
1159+
expect(await runEnded(ctx, { ...run, sessionInSeq: 1 }, "failed")).toBe("failed-mid-turn");
1160+
expect(triggerState.calls).toHaveLength(0);
1161+
}
1162+
);
1163+
1164+
// Catches: a replacement run's first `.in` seq being taken from the marker's seq. The marker names
1165+
// the message the dead turn was answering, but an earlier message can still be unanswered (the
1166+
// turn-complete cursor is held behind it), so the marker's seq would start the new run past it and
1167+
// that message would be lost. The first seq stays the earliest message known to be unread. Also: a
1168+
// succeeded run is continued whatever its `.out` ends on, a turn-start marker included.
1169+
postgresTest(
1170+
"continues a succeeded run whose `.out` ends on a turn-start marker, from the earliest unread message",
1171+
async ({ prisma }) => {
1172+
const ctx = await setup(prisma as unknown as PrismaClient);
1173+
const { run } = await sessionWithLiveRun(prisma as unknown as PrismaClient, ctx);
1174+
await pushIn(ctx, message("m0"));
1175+
await pushTurnComplete(ctx, 0);
1176+
await pushIn(ctx, message("m1, never answered"));
1177+
await pushIn(ctx, message("m2, the turn that was started"));
1178+
await pushTurnStart(ctx, 2);
1179+
await finish(prisma as unknown as PrismaClient, run.id);
1180+
1181+
expect(await runEnded(ctx, { ...run, sessionInSeq: 1 }, "succeeded")).toBe("continued");
1182+
expect(triggerState.calls).toHaveLength(1);
1183+
expect(triggerState.calls[0]!.options.sessionInFirstSeq).toBe(1);
1184+
}
1185+
);
1186+
11251187
// Catches: a run that died at boot, before writing anything of its own, being judged by the
11261188
// previous run's turn-complete: that record is stored with a newer timestamp than the run here
11271189
// (S2's clock ahead), and carries a cursor below the run's `.in` start, so by seq it is not its own.

‎docs/ai-chat/backend.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ await waitUntilComplete();
195195
| `chat.stream.append(value, options?)` | Append raw data |
196196
| `chat.stream.read(runId, options?)` | Read the stream by run ID |
197197

198+
The first write a turn makes to the stream also marks where the turn starts, so an `await chat.stream.append()` in `onTurnStart` or `onChatStart` takes one extra append to return (it writes that marker first).
199+
198200
For piping streams from subtasks to the parent chat (via `target: "root"`), see the [Sub-agents pattern](/ai-chat/patterns/sub-agents).
199201

200202
### Backed by a Session

‎docs/ai-chat/client-protocol.mdx‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,10 @@ if (controlValue === "upgrade-required") {
398398
// by the time this arrives — subsequent chunks are from the new run...
399399
continue;
400400
}
401+
// Any other control record (`turn-start`, `turn-join`, and subtypes added
402+
// later): its body is empty, so never parse it. Ignore it, or use it as
403+
// described under "Which turn a record belongs to".
404+
if (controlValue) continue;
401405
402406
// Otherwise: data record. Parse the body, dispatch the UIMessageChunk.
403407
const { data: chunk } = JSON.parse(record.body);
@@ -627,6 +631,31 @@ When you receive this record:
627631
628632
The built-in clients handle this transparently.
629633
634+
### Which turn a record belongs to
635+
636+
`session.out` can carry more than one turn: a replacement run answering several unanswered messages in order, a message another client sent just before yours, or the retained tail of an earlier turn when you read without a cursor. Two control records say whose turn the records after them belong to. A custom reader that doesn't need this can ignore both (they have empty bodies, like every control record), as the built-in clients did before them.
637+
638+
```
639+
headers:
640+
["trigger-control", "turn-start"]
641+
["turn-start-in-seq", "<seq>"] // optional
642+
body: ""
643+
```
644+
645+
`turn-start` is the first record the agent writes for a turn. `turn-start-in-seq` is the `.in` seq of the message that turn answers, the same number your `.in/append` returned for it. It is absent for a turn that answers no `.in` message (one started from the run's start payload, such as a head start), which is nobody's own turn. A reader waiting on its own send keeps the records after a `turn-start` whose seq equals its own and drops the records after any other, up to the next `turn-complete`.
646+
647+
```
648+
headers:
649+
["trigger-control", "turn-join"]
650+
["turn-start-in-seq", "<seq>,<seq>"]
651+
["turn-join-injection-id", "<id>"] // optional
652+
body: ""
653+
```
654+
655+
`turn-join` is written in the middle of a turn when [pending messages](/ai-chat/pending-messages) are folded into it: those messages get no turn of their own, and what the turn writes from here on answers them. The header lists their `.in` seqs. The previous step's last records can still arrive just after it, `start-step` included, because the record is appended directly while the step's chunks are batched. `turn-join-injection-id` is the `id` of the `data-pending-message-injected` chunk the agent writes into the turn for those messages, between the previous step and the one that follows the injection. When the turn's output goes out through the agent's managed response (a `streamText` result returned from `run`, or from a `chat.createSession` turn), that chunk is ordered with the step's own chunks, so a reader that takes the rest of the turn should start right after it. The agent writes the header only then. With `chat.pipe`, or an agent that pipes the model output itself, the chunk goes out on a separate pipe and can land after the step it should precede, so the header is absent: start at the next `start-step` chunk instead, as you do for an older agent's join. The turn's `turn-complete` is the reader's boundary from then on, even when its `session-in-event-id` is below the joined seqs (an earlier input or a queued action is still owed): the turn answers the joined messages either way.
656+
657+
Only agents on a recent SDK version write these. Against an older agent a reader sees neither, and has to fall back to the `turn-complete` correlation described above.
658+
630659
### Resuming a stream
631660
632661
If the SSE connection drops, or the server sends an `error` event, reconnect with the `Last-Event-ID` header set to the **last `record.seq_num` you successfully processed** (decoded from the batch body, not the SSE `id:` line, which is a comma-list internal to S2):

‎docs/ai-chat/server-chat.mdx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,38 @@ export async function POST(req: Request) {
150150
}
151151
```
152152

153+
<Note>
154+
The stream a send returns carries exactly that send's reply, streamed live, and `onTurnComplete`
155+
fires once when it ends. Replies to other messages (another client's message just before yours, an
156+
earlier send from the same instance, or messages a replacement run answers first) are not in it.
157+
A message that [pending-message steering](/ai-chat/pending-messages) folds into a running turn gets
158+
the rest of that turn. That needs an agent deployed on a recent SDK version.
159+
160+
Persist and restore `lastEventId` when you continue an existing chat: without it, `AgentChat` reads
161+
the chat's retained output once to find where to start, which costs one extra request per send.
162+
163+
With an older agent, a reply streams live only when `AgentChat` can tell it is yours: on a send that
164+
follows one of this instance's own completed sends, or on the first send of a chat this instance
165+
just created, with nothing unanswered ahead of it. A `lastEventId` you restore from storage doesn't
166+
show that on its own, because a replacement run may have answered other messages after it. In
167+
every other case the reply arrives all at once when the turn completes, rather than as it is
168+
written, and so does a second send made while an earlier send from the same instance is still
169+
unread. If the run ends mid-turn while a reply is held back, you receive the part that was
170+
written, then the error. With an older agent, a custom `fetch` override takes this held path too
171+
(an agent on a recent version streams live through it).
172+
173+
`reconnect()` from a new process with no saved `lastEventId` can still start at an earlier turn
174+
that is still retained on the stream.
175+
176+
If the server, or a proxy in front of it, can't serve that read of the retained output, the stream
177+
starts from the beginning of it and `AgentChat` logs one warning per instance. An agent on a recent
178+
version still streams only its own reply live; with an older agent the reply is held until the turn
179+
completes.
180+
181+
If the `abortSignal` you pass to a send is aborted before its stream has started, `AgentChat` still
182+
asks the agent to stop, so a turn nobody is reading isn't run.
183+
</Note>
184+
153185
<Info>
154186
The Session row is the run manager — a chat that was active yesterday
155187
resumes against the same chatId today, even if the original run has

‎docs/ai-chat/testing.mdx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ Each turn returns:
244244
```ts
245245
type MockChatAgentTurn = {
246246
chunks: UIMessageChunk[]; // text-delta, tool-call, etc.
247-
rawChunks: unknown[]; // includes control chunks (turn-complete, errors)
247+
rawChunks: unknown[]; // includes control chunks (turn-complete, errors), not turn markers
248248
};
249249
```
250250

@@ -611,6 +611,9 @@ function mockChatAgent(
611611
| `previousRunId` | `string` | `undefined` | Set `payload.previousRunId` on the initial wire payload. Typically paired with `continuation: true`. |
612612
| `snapshot` | `ChatSnapshotV1` | `undefined` | Pre-seed the snapshot the agent reads at run boot (replaces the real S3 GET). Use to drive resume scenarios with prior history. See [Persistence and replay](/ai-chat/patterns/persistence-and-replay) for the production snapshot model. |
613613
| `setupLocals` | `({ set }) => void \| Promise<void>` | `undefined` | Callback invoked before `run()` starts. Use `set(key, value)` to inject server-side dependencies (DB clients, service stubs) that the agent reads via `locals.get()`. |
614+
| `outAppendLatencyMs` | `number` | `0` | Milliseconds each append to the output stream takes to be acknowledged (control records, one-shot appends and the first chunk of each piped stream). For testing timing, such as time to first chunk. |
615+
| `outPipeLingerMs` | `number` | `0` | Milliseconds each piped chunk lingers before it is acknowledged, modelling the writer's batching so a control record written while a step streams can land ahead of that step's tail. |
616+
| `omitTurnMarkers` | `boolean` | `false` | Write no `turn-start` or `turn-join` records, as an agent on an older SDK version does, to test how a client behaves against it. |
614617

615618
##### Boot modes
616619

@@ -643,7 +646,10 @@ The harness's initial wire payload depends on `mode`:
643646
| `getSnapshot()` | The most recently written snapshot, or `undefined` if no snapshot was written. |
644647
| `close()` | Send a `close` trigger, abort the signal, wait for `run()` to return. Always call at end of test. |
645648
| `allChunks` | Every `UIMessageChunk` emitted since the harness was created. |
646-
| `allRawChunks` | Every raw chunk emitted since creation, including control chunks (`trigger:turn-complete`, errors). |
649+
| `allRawChunks` | Every raw chunk emitted since creation, including control chunks (`trigger:turn-complete`, errors). The `turn-start` and `turn-join` markers the agent writes (see [Which turn a record belongs to](/ai-chat/client-protocol#which-turn-a-record-belongs-to)) are left out, so exact-sequence assertions don't see them; they are in `outRecords`. |
650+
| `outRecords` | The output stream as a reader sees it: every record with its 1-based `seqNum`, its `headers` (a `trigger-control` entry on control records, none on data records), its `chunk` (data records) and the `at` time it was acknowledged (`TestOutRecord`). |
651+
| `onOutRecord(listener)` | Call `listener(record)` for each record written to the output stream, after it is in `outRecords`. Returns an unsubscribe function. |
652+
| `deliverInput(chunk, seqNum)` | Put a record on `session.in` at an explicit seq, without waiting for a turn, the way the server does for an append from any client. Use it to drive several sends in flight, or to host a real `AgentChat` over a fake fetch. |
647653

648654
### runInMockTaskContext
649655

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import type { ApiClient } from "../apiClient/index.js";
3+
import { trimSessionStream, writeSessionControlRecord } from "./sessionStreamOneshot.js";
4+
5+
function apiClientStub() {
6+
const initializeSessionStream = vi.fn(async () => ({ headers: {} }));
7+
return { client: { initializeSessionStream } as unknown as ApiClient, initializeSessionStream };
8+
}
9+
10+
describe("one-shot session stream writes", () => {
11+
it("use credentials the caller already holds instead of asking the server again", async () => {
12+
// Catches: every control record (a turn marker, a boundary) and trim paying a
13+
// server round trip for credentials the channel's writers already hold.
14+
const { client, initializeSessionStream } = apiClientStub();
15+
const held = Promise.reject(new Error("held credentials used"));
16+
held.catch(() => {});
17+
18+
await expect(
19+
writeSessionControlRecord(client, "chat-1", "out", "turn-start", [], undefined, held)
20+
).rejects.toThrow("held credentials used");
21+
await expect(trimSessionStream(client, "chat-1", 3, undefined, held)).rejects.toThrow(
22+
"held credentials used"
23+
);
24+
expect(initializeSessionStream).not.toHaveBeenCalled();
25+
});
26+
27+
it("still fetch credentials when the caller holds none", async () => {
28+
// Catches: the shared-credentials path replacing the fetch for callers that
29+
// pass nothing.
30+
const { client, initializeSessionStream } = apiClientStub();
31+
32+
await expect(
33+
writeSessionControlRecord(client, "chat-1", "out", "turn-complete")
34+
).rejects.toThrow(/S2 credentials/);
35+
expect(initializeSessionStream).toHaveBeenCalledTimes(1);
36+
});
37+
});

‎packages/core/src/v3/realtimeStreams/sessionStreamOneshot.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,22 @@ import type { StreamWriteResult } from "./types.js";
2323

2424
type IO = "out" | "in";
2525

26-
async function getS2Stream(apiClient: ApiClient, sessionId: string, io: IO, channel?: string) {
27-
const response = await apiClient.initializeSessionStream(sessionId, io, undefined, channel);
26+
/**
27+
* The channel's already-initialized S2 credentials, when the caller holds them
28+
* (the SDK's output channel caches one per channel), so a one-shot write is a
29+
* single S2 append rather than a server round trip plus the append.
30+
*/
31+
export type SessionStreamInit = Promise<{ headers?: Record<string, string> }>;
32+
33+
async function getS2Stream(
34+
apiClient: ApiClient,
35+
sessionId: string,
36+
io: IO,
37+
channel?: string,
38+
init?: SessionStreamInit
39+
) {
40+
const response = await (init ??
41+
apiClient.initializeSessionStream(sessionId, io, undefined, channel));
2842
const headers = response.headers ?? {};
2943
const accessToken = headers["x-s2-access-token"];
3044
const basin = headers["x-s2-basin"];
@@ -66,9 +80,10 @@ export async function writeSessionControlRecord(
6680
io: IO,
6781
subtype: TriggerControlSubtype | string,
6882
extraHeaders?: ReadonlyArray<readonly [string, string]>,
69-
channel?: string
83+
channel?: string,
84+
init?: SessionStreamInit
7085
): Promise<StreamWriteResult> {
71-
const stream = await getS2Stream(apiClient, sessionId, io, channel);
86+
const stream = await getS2Stream(apiClient, sessionId, io, channel, init);
7287
const headers: ReadonlyArray<readonly [string, string]> = [
7388
[TRIGGER_CONTROL_HEADER, subtype],
7489
...(extraHeaders ?? []),
@@ -95,9 +110,10 @@ export async function trimSessionStream(
95110
apiClient: ApiClient,
96111
sessionId: string,
97112
earliestSeqNum: number,
98-
channel?: string
113+
channel?: string,
114+
init?: SessionStreamInit
99115
): Promise<void> {
100-
const stream = await getS2Stream(apiClient, sessionId, "out", channel);
116+
const stream = await getS2Stream(apiClient, sessionId, "out", channel, init);
101117
await stream.append(AppendInput.create([AppendRecord.trim(earliestSeqNum)]));
102118
}
103119

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
TRIGGER_CONTROL_SUBTYPE,
4+
TRIGGER_TURN_MARKER_SUBTYPE,
5+
type TriggerControlSubtype,
6+
} from "./wireProtocol.js";
7+
8+
describe("turn marker subtypes", () => {
9+
it("do not widen the public TriggerControlSubtype union", () => {
10+
// Catches: adding a subtype to `TRIGGER_CONTROL_SUBTYPE` in a patch release, which
11+
// breaks the type check of any caller switching over `TriggerControlSubtype`
12+
// exhaustively. The `@ts-expect-error` below stops compiling if it widens.
13+
// @ts-expect-error "turn-start" is not a TriggerControlSubtype
14+
const widened: TriggerControlSubtype = TRIGGER_TURN_MARKER_SUBTYPE.TURN_START;
15+
void widened;
16+
17+
expect(Object.values(TRIGGER_CONTROL_SUBTYPE)).not.toContain("turn-start");
18+
expect(TRIGGER_TURN_MARKER_SUBTYPE).toEqual({
19+
TURN_START: "turn-start",
20+
TURN_JOIN: "turn-join",
21+
});
22+
});
23+
});

0 commit comments

Comments
 (0)