Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
c6c35d5
test: cover the head-start accumulator seed without hydrateMessages
ericallam Aug 20, 2026
5fef13f
fix(chat): put injected steering messages into the accumulator
ericallam Aug 20, 2026
4b0f52a
fix(chat): persist history an action rolled back
ericallam Aug 20, 2026
e399b60
fix(chat): make a response streamed from onAction part of the convers…
ericallam Aug 20, 2026
52bd98d
fix(chat): route a system-role injection to the instructions lane
ericallam Aug 20, 2026
47f2f8f
fix(chat): address review on the accumulator, instructions and action…
ericallam Aug 28, 2026
52772b5
fix(chat): report a failed action stream instead of committing it as …
ericallam Aug 28, 2026
c6b0dbd
docs(chat): note the instructions delivery path and one-shot injectio…
ericallam Aug 29, 2026
e3318cf
docs(ai-chat): say what an action persists under each persistence model
ericallam Aug 29, 2026
02e0a70
docs(ai-chat): delete the replaced answer in the regenerate example
ericallam Sep 3, 2026
e6618cf
docs(ai-chat): style-guide pass on the injection and action sections
ericallam Sep 3, 2026
1f7fb5e
docs(ai-chat): drop em dashes from the docs and changesets
ericallam Sep 3, 2026
3246d12
docs(ai-chat): drop the remaining em dashes from the actions and inje…
ericallam Sep 3, 2026
86d67fa
docs(chat): warn about the two upgrade hazards in the changesets
ericallam Sep 3, 2026
e2737f6
fix(chat): consume injected instructions per turn, not per options build
ericallam Sep 3, 2026
692c060
fix(chat): keep an injection made during the turn that consumed the lane
ericallam Sep 3, 2026
900418d
fix(chat): rebuild the model messages after a steering injection
ericallam Sep 4, 2026
83fe5ef
test(chat): cover the model-lane rebuild on a turn that captures no r…
ericallam Sep 4, 2026
6683e4b
fix(chat): keep a steer in the lanes on the createSession surface
ericallam Sep 4, 2026
bf82221
fix(chat): append a steer to the model lane instead of rebuilding it
ericallam Sep 4, 2026
dd06745
fix(chat): report a drained steer from a turn that fails
ericallam Sep 4, 2026
a0a07bb
test(chat): pin a one-shot instruction across an action
ericallam Sep 4, 2026
c9fe897
test(chat): use the spread form in the action-instruction test
ericallam Sep 4, 2026
4f535ac
fix(chat): keep a steer's prepared form for later turns
ericallam Sep 4, 2026
39ea541
fix(chat): reconcile a steer into the model lane when the turn fails
ericallam Sep 4, 2026
920c76d
fix(chat): keep a failed action from counting as a turn
ericallam Sep 4, 2026
e348d61
fix(chat): move the snapshot cursor on a failed turn
ericallam Sep 4, 2026
0ef1caa
docs(chat): cover the second review round in the changesets
ericallam Sep 4, 2026
ae72c70
fix(chat): report a steer in the turn delta, and once after a history…
ericallam Sep 4, 2026
62fd77c
fix(chat): keep a prepared steer through a history edit and a failed …
ericallam Sep 4, 2026
6482650
fix(chat): deliver plain onAction replies, and keep compaction throug…
ericallam Sep 4, 2026
472eaf4
fix(chat): keep an instruction injected after an action for the next …
ericallam Sep 4, 2026
023432d
feat(chat): send actions through useChat so their turns render
ericallam Sep 4, 2026
d332a2a
feat(chat): let an action become a turn with chat.turn()
ericallam Sep 4, 2026
0cf59a2
fix(chat): persist an action's edit before its turn, and label that turn
ericallam Sep 5, 2026
8d5d466
fix(chat): merge an action's metadata over the transport's clientData
ericallam Sep 5, 2026
ee8f449
docs(chat): correct three changesets after the chat.turn() redesign
ericallam Sep 5, 2026
cd39f8b
feat(chat): hand run() a streamText that already has the managed options
ericallam Sep 3, 2026
447c910
fix(sdk): fall back to the agent's tools in the managed streamText
ericallam Sep 4, 2026
53b588e
fix(chat): apply agent-level options in chat.toStreamTextOptions
ericallam Sep 4, 2026
977c22a
refactor(chat): drop the streamText handed to onAction
ericallam Sep 4, 2026
0b66e8d
docs(chat): describe actions as edits that can become turns
ericallam Sep 4, 2026
d4458ea
docs(chat): the turn an action requests carries trigger action-turn
ericallam Sep 5, 2026
5728314
fix(chat): publish the agent options for hydrateMessages agents, and …
ericallam Sep 5, 2026
6db5dcb
docs(chat): describe the action-turn branch, and fix two Head Start t…
ericallam Sep 5, 2026
bf66457
docs(chat): list prompt among the Head Start owned options in the cha…
ericallam Sep 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/action-stream-into-conversation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
"@trigger.dev/sdk": minor
---

Actions can now become turns. `onAction` edits history with `chat.history`; to answer after the edit, return `chat.turn()` and a turn runs on the edited history with everything a turn has: the agent's system prompt and tools, steering, compaction, injected instructions, `onTurnStart` and `onTurnComplete`, and persistence. A regenerate is `chat.history.slice(0, -1); return chat.turn();`.

```ts
onAction: async ({ action }) => {
if (action.type === "regenerate") {
chat.history.slice(0, -1);
return chat.turn();
}
if (action.type === "undo") chat.history.slice(0, -2); // edit only
},
```

Returning a `StreamTextResult`, `string` or `UIMessage` from `onAction` is no longer supported and now fails with an error pointing to `chat.turn()`. A response produced that way skipped every turn guarantee, and its delivery to the browser was unreliable: the frontend never read the stream `transport.sendAction` returned, so a regenerate that appeared to work on the server did not render.

History edits made by an action are still persisted as before: platform-managed snapshots are written after the edit, and apps with their own store mirror the edit themselves.
5 changes: 5 additions & 0 deletions .changeset/createsession-steering-lanes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@trigger.dev/sdk": patch
---

Steering messages are now kept in the conversation when you drive turns yourself with `chat.createSession()` or `chat.MessageAccumulator`. Previously a message that arrived mid-answer shaped that answer and then existed nowhere: it was missing from `turn.uiMessages`, so an app persisting from there never stored it, missing from `turn.messages`, so every later turn answered as though it had never been sent, and it was not queued as its own turn either. It now lands in both, the same way it does on `chat.agent`.
5 changes: 5 additions & 0 deletions .changeset/inject-instructions-shape.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@trigger.dev/sdk": patch
---

Injected system context is merged into a single instruction block, so it works on every supported AI SDK version. Note that a cached system prompt gives up its cache entry for as long as an injection is live, since the cached prefix has changed.
7 changes: 7 additions & 0 deletions .changeset/inject-system-to-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@trigger.dev/sdk": patch
---

`chat.inject()` with `role: "system"` now works. It previously put the system message into the conversation, which AI SDK 7 rejects for every provider: the next turn died with a generic "An error occurred." and persisted an empty assistant message, so the agent looked like it had stopped answering. System-role context is now appended to the model's instructions, which is also the only way to inject context the agent treats as trusted.

Two things to know. Instructions are delivered by `chat.toStreamTextOptions()`, so a `run()` that calls `streamText` without spreading it does not receive a system-role injection. The conversational lane has no such requirement. And an injection applies to the next turn only, rather than repeating on every turn that follows it. Every inference call in that turn sees it, so a `run()` that builds options more than once gets the same instructions each time. An instruction injected after an action has run, and before the next message, reaches that next turn rather than the one after it.
18 changes: 18 additions & 0 deletions .changeset/managed-streamtext-in-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
"@trigger.dev/sdk": minor
---

`run()` now receives a `streamText` with your agent's managed options already applied, so they cannot be lost by leaving out the spread:

```ts
run: async ({ messages, signal, streamText }) =>
streamText({ model, messages, abortSignal: signal });
```

Spreading `chat.toStreamTextOptions()` still works and is equivalent. The difference is what happens when your options collide with the managed ones. Passing `tools` after the spread replaces the skill tools, and passing your own `prepareStep` replaces the managed one, which silently switches off steering, compaction and injected context. The managed `streamText` merges tools and composes `prepareStep` instead, so neither can be turned off by accident.

`system` can be set at the call site, on `chat.agent({ system })`, or through `chat.prompt.set()`, but only in one of them: setting it in two places throws, because no single shape merges two system values across every supported AI SDK version, and dropping one silently is the failure this seam exists to prevent. Injected instructions append to whichever one is in play.

`chat.agent()` also takes `registry`, `cacheControl` and `systemProviderOptions` now, so a managed prompt's model and its cache breakpoint no longer have to be passed at the call site. `chat.toStreamTextOptions()` applies them as well, so spreading it into the `streamText` imported from `ai` stays equivalent to the one `run()` receives.

`chat.headStart` and `chat.startHeadStart` hand their `run` the same thing, carrying the options the handover protocol depends on. There it matters more: re-setting `messages`, `prompt`, `stopWhen` or `abortSignal` after a spread breaks the handover rather than degrading a feature, and nothing caught it. On the managed one those four keys are a type error; `tools` is yours to pass.
5 changes: 5 additions & 0 deletions .changeset/persist-action-history-mutations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@trigger.dev/sdk": patch
---

Undo, edit and regenerate now survive a run ending. History rolled back from `onAction` was only kept in the running worker's memory, so the rollback held while that worker stayed warm and then reverted on the next continuation. The undone messages came back, minutes later, with no error. This also holds when the turn before the action failed: the rollback used to be written against the cursor from before that turn, so a continuation could replay output the failed turn had already superseded.
9 changes: 9 additions & 0 deletions .changeset/steering-messages-accumulator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@trigger.dev/sdk": patch
---

Steering messages injected mid-answer are now part of the conversation, both for your hooks and for the model on later turns. Previously they reached the model for the answer they steered and reached the browser, but nothing else: `onTurnComplete` never saw them, so an app storing its own transcript lost the instruction the answer was shaped by, and it vanished from the conversation on reload. The model also forgot the instruction from the next turn onwards, answering as though the message had never been sent, while the chat UI still showed it. This holds when the steered turn fails part-way, and when `pendingMessages.prepare` reshapes the message: later turns now see the same form the steered turn did, not the original message.

Approving a tool call no longer undoes compaction. A tool-approval continuation used to rebuild the model's context from the full conversation, so a chat that had been summarised to fit the context window was sent the whole transcript again on the next call, and could go over the limit it had just been compacted to avoid.

If you worked around this by saving steering messages as they arrive, in `pendingMessages.onReceived` for example, that write now duplicates the one you get from `newUIMessages`. Drop it, or skip messages you have already stored.
13 changes: 13 additions & 0 deletions .changeset/use-chat-actions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@trigger.dev/sdk": minor
---

Actions are sent through `useChat` so a turn that follows one renders like any turn. `TriggerChatTransport` recognises `body.action` on a `useChat` request and sends it as an action, so `sendMessage(undefined, { body: { action } })` or `regenerate({ body: { action } })` sends the action and `useChat` owns the response: it streams into the message list, `status` and `error` behave as for a message, and `stop` works. `useChatActions({ sendMessage })` in `@trigger.dev/sdk/chat/react` is a two-line convenience over that.

```tsx
const { sendMessage } = useChat({ id: chatId, transport });
const { sendAction } = useChatActions({ sendMessage });
sendAction({ type: "regenerate" });
```

Previously the frontend docs said `useChat` consumed the stream `transport.sendAction` returns; it never did, so an action's answer was never rendered by an app following them. `transport.sendAction` still returns a stream that callers outside `useChat` must read, and now accepts `{ abortSignal, metadata }`, with per-action metadata merged over the transport's `clientData`.
78 changes: 55 additions & 23 deletions docs/ai-chat/actions.mdx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "Actions"
sidebarTitle: "Actions"
description: "Custom commands sent from the frontend that mutate chat state without consuming a turn undo, rollback, edit, regenerate."
description: "Custom commands sent from the frontend that mutate chat state without consuming a turn: undo, rollback, edit, regenerate."
---

## Overview
Expand Down Expand Up @@ -44,55 +44,87 @@ export const myChat = chat.agent({
// returning void → side-effect-only, no model call
},

run: async ({ messages, signal }) => {
run: async ({ messages, signal, streamText }) => {
return streamText({ model: anthropic("claude-sonnet-4-5"), messages, abortSignal: signal });
},
});
```

**Lifecycle flow:** Wake → parse action against `actionSchema` → `hydrateMessages` (if set) → **`onAction`** → apply `chat.history` mutations → emit `trigger:turn-complete` → wait for next message.

## Returning a model response from an action
When `onAction` returns `chat.turn()`, the flow continues instead of emitting `trigger:turn-complete`: the edit is snapshotted, then a turn runs on the edited history with `trigger: "action-turn"`, so `onTurnStart`, `run()`, `onBeforeTurnComplete` and `onTurnComplete` all fire and the answer is persisted like any turn's. See [Answering after an action](#answering-after-an-action).

`onAction` can return a `StreamTextResult`, `string`, or `UIMessage` to produce a response. The returned stream is auto-piped to the frontend just like a normal turn, but the rest of the turn machinery (`onTurnStart`, `onTurnComplete`, etc.) still does not fire.
## Answering after an action

An action is a state edit. To answer after the edit, return `chat.turn()`: the edit is applied and snapshotted, then a turn runs on the edited history exactly as a message turn does. `onTurnStart`, `run()`, `onBeforeTurnComplete` and `onTurnComplete` fire, the turn counter advances, and the answer gets everything a turn has: the agent's system prompt and tools, steering, compaction, injected instructions and persistence.
Comment thread
ericallam marked this conversation as resolved.

```ts
onAction: async ({ action, messages }) => {
if (action.type === "regenerate") {
chat.history.slice(0, -1); // drop the last assistant
return streamText({
model: anthropic("claude-sonnet-4-5"),
messages,
stopWhen: stepCountIs(15),
});
onAction: async ({ action }) => {
switch (action.type) {
case "undo":
chat.history.slice(0, -2);
return; // edit only, no turn

case "regenerate":
chat.history.slice(0, -1);
return chat.turn(); // answer the edited history

case "retry-formal":
chat.history.slice(0, -1);
chat.inject([{ role: "system", content: "Answer formally this time." }]);
return chat.turn(); // with a one-shot instruction
}
// other actions return void → side-effect only
}
```

This is useful for actions that both mutate state and want a fresh model response (regenerate-from-here, retry-with-different-style). Persistence is your responsibility inside `onAction` itself; you have access to the streamed response object.
`run()` receives the edited history with no incoming user message, the same shape as a `regenerate-message` turn, and its `trigger` is `"action-turn"`, so a `run()` that returns early on `"action"` (the pre-May behaviour, when actions invoked `run()` directly) still answers. Returning anything other than `chat.turn()` or nothing is an error; a response can no longer be returned from `onAction` directly.

### Actions and persistence

An action that returns nothing does not fire `onTurnComplete`, and that is where an app that owns its own transcript normally writes. What that means depends on which persistence model you use.

**Platform-managed** (no `hydrateMessages`): nothing to do. After an action that changed the conversation, the runtime writes the snapshot, so the edit survives the run ending. An action that returns `chat.turn()` is followed by a turn, which persists its answer the way every turn does.

**Your own store** (`hydrateMessages` registered): the runtime deliberately does not write, because your store is the source of truth. A history edit lives only in the running worker until you persist it, and a continuation rehydrates from your store, not from what the worker had in memory. Mirror each edit in your store, not only additions: a regenerate is a delete *and* an insert. The answer that follows `chat.turn()` reaches your store through `onTurnComplete`, like any turn's answer.

```ts
onAction: async ({ action, chatId }) => {
if (action.type === "undo") {
chat.history.slice(0, -2);
await db.deleteLastExchange(chatId); // the rollback is yours to persist
}
if (action.type === "regenerate") {
chat.history.slice(0, -1);
await db.deleteLastAssistant(chatId); // the delete half
return chat.turn(); // the insert half arrives in onTurnComplete
}
},
onTurnComplete: async ({ chatId, newUIMessages }) => {
await db.saveMessages(chatId, newUIMessages);
},
```

## Gating actions on HITL state

If you have a [human-in-the-loop](/ai-chat/patterns/human-in-the-loop) tool waiting on `addToolOutput`, you usually want to refuse competing actions like `regenerate` until the answer arrives. [`chat.history.getPendingToolCalls()`](/ai-chat/backend#chat-history) gives you exactly that signal:

```ts
onAction: async ({ action, messages, signal }) => {
onAction: async ({ action }) => {
if (action.type === "regenerate") {
if (chat.history.getPendingToolCalls().length > 0) return; // gated
chat.history.slice(0, -1);
return streamText({ model: anthropic("claude-sonnet-4-5"), messages, abortSignal: signal });
return chat.turn();
}
},
```

## Sending actions from the frontend

```ts
// Browser TriggerChatTransport
// Browser: TriggerChatTransport
const stream = await transport.sendAction(chatId, { type: "undo" });

// Server AgentChat
// Server: AgentChat
const stream = await agentChat.sendAction({ type: "rollback", targetMessageId: "msg-3" });
```

Expand All @@ -104,8 +136,8 @@ The action payload is validated against `actionSchema` on the backend; invalid a

## See also

- [`chat.history`](/ai-chat/backend#chat-history) the imperative API actions use to mutate state
- [Sending actions from the frontend](/ai-chat/frontend#sending-actions) — `transport.sendAction` ergonomics
- [`hydrateMessages`](/ai-chat/lifecycle-hooks#hydratemessages) fires before `onAction` when set
- [Branching conversations](/ai-chat/patterns/branching-conversations) pairs action handlers with backend-controlled history
- [Human-in-the-loop](/ai-chat/patterns/human-in-the-loop) gating fresh actions while a tool is waiting
- [`chat.history`](/ai-chat/backend#chat-history): the imperative API actions use to mutate state
- [Sending actions from the frontend](/ai-chat/frontend#sending-actions): sending actions through `useChat` so a turn that follows one renders like any turn
- [`hydrateMessages`](/ai-chat/lifecycle-hooks#hydratemessages): fires before `onAction` when set
- [Branching conversations](/ai-chat/patterns/branching-conversations): pairs action handlers with backend-controlled history
- [Human-in-the-loop](/ai-chat/patterns/human-in-the-loop): gating fresh actions while a tool is waiting
6 changes: 3 additions & 3 deletions docs/ai-chat/anatomy.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Everything below maps onto one annotated agent:

```ts trigger/my-agent.ts
import { chat } from "@trigger.dev/sdk/ai";
import { streamText, stepCountIs } from "ai";
import { stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export const myAgent = chat.agent({
Expand All @@ -36,9 +36,9 @@ export const myAgent = chat.agent({

// The turn loop. Messages arrive accumulated; you stream back.
// Options, levels, and alternatives — see Backend.
run: async ({ messages, tools, signal }) =>
run: async ({ messages, tools, signal, streamText }) =>
streamText({
...chat.toStreamTextOptions({ tools }),
tools,
model: anthropic("claude-sonnet-4-5"),
messages,
abortSignal: signal,
Expand Down
Loading
Loading