@trigger.dev/sdk 4.8.1 → 4.8.3

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.
Files changed (107) hide show
  1. package/dist/commonjs/v3/ai-shared.d.ts +6 -0
  2. package/dist/commonjs/v3/ai-shared.js +7 -1
  3. package/dist/commonjs/v3/ai-shared.js.map +1 -1
  4. package/dist/commonjs/v3/ai.d.ts +45 -0
  5. package/dist/commonjs/v3/ai.js +110 -69
  6. package/dist/commonjs/v3/ai.js.map +1 -1
  7. package/dist/commonjs/v3/auth.d.ts +12 -2
  8. package/dist/commonjs/v3/auth.js +26 -12
  9. package/dist/commonjs/v3/auth.js.map +1 -1
  10. package/dist/commonjs/v3/chat-client.d.ts +11 -2
  11. package/dist/commonjs/v3/chat-client.js +28 -10
  12. package/dist/commonjs/v3/chat-client.js.map +1 -1
  13. package/dist/commonjs/v3/chat-react.d.ts +21 -0
  14. package/dist/commonjs/v3/chat-react.js +86 -30
  15. package/dist/commonjs/v3/chat-react.js.map +1 -1
  16. package/dist/commonjs/v3/chat.d.ts +1 -0
  17. package/dist/commonjs/v3/chat.js +30 -7
  18. package/dist/commonjs/v3/chat.js.map +1 -1
  19. package/dist/commonjs/v3/index.d.ts +1 -1
  20. package/dist/commonjs/v3/index.js +2 -1
  21. package/dist/commonjs/v3/index.js.map +1 -1
  22. package/dist/commonjs/v3/managedChatResponse.d.ts +13 -5
  23. package/dist/commonjs/v3/managedChatResponse.js +36 -18
  24. package/dist/commonjs/v3/managedChatResponse.js.map +1 -1
  25. package/dist/commonjs/v3/oidc/aws.d.ts +22 -0
  26. package/dist/commonjs/v3/oidc/aws.js +43 -0
  27. package/dist/commonjs/v3/oidc/aws.js.map +1 -0
  28. package/dist/commonjs/v3/steeringContext.d.ts +11 -0
  29. package/dist/commonjs/v3/steeringContext.js +44 -3
  30. package/dist/commonjs/v3/steeringContext.js.map +1 -1
  31. package/dist/commonjs/v3/subAgentStream.d.ts +50 -0
  32. package/dist/commonjs/v3/subAgentStream.js +154 -0
  33. package/dist/commonjs/v3/subAgentStream.js.map +1 -0
  34. package/dist/commonjs/v3/transcriptStorage.js +3 -0
  35. package/dist/commonjs/v3/transcriptStorage.js.map +1 -1
  36. package/dist/commonjs/v3/uiMessageChunks.js +5 -1
  37. package/dist/commonjs/v3/uiMessageChunks.js.map +1 -1
  38. package/dist/commonjs/version.js +1 -1
  39. package/dist/esm/v3/ai-shared.d.ts +6 -0
  40. package/dist/esm/v3/ai-shared.js +6 -0
  41. package/dist/esm/v3/ai-shared.js.map +1 -1
  42. package/dist/esm/v3/ai.d.ts +45 -0
  43. package/dist/esm/v3/ai.js +113 -72
  44. package/dist/esm/v3/ai.js.map +1 -1
  45. package/dist/esm/v3/auth.d.ts +12 -2
  46. package/dist/esm/v3/auth.js +27 -13
  47. package/dist/esm/v3/auth.js.map +1 -1
  48. package/dist/esm/v3/chat-client.d.ts +11 -2
  49. package/dist/esm/v3/chat-client.js +29 -11
  50. package/dist/esm/v3/chat-client.js.map +1 -1
  51. package/dist/esm/v3/chat-react.d.ts +21 -0
  52. package/dist/esm/v3/chat-react.js +81 -30
  53. package/dist/esm/v3/chat-react.js.map +1 -1
  54. package/dist/esm/v3/chat.d.ts +1 -0
  55. package/dist/esm/v3/chat.js +27 -6
  56. package/dist/esm/v3/chat.js.map +1 -1
  57. package/dist/esm/v3/index.d.ts +1 -1
  58. package/dist/esm/v3/index.js +1 -1
  59. package/dist/esm/v3/index.js.map +1 -1
  60. package/dist/esm/v3/managedChatResponse.d.ts +13 -5
  61. package/dist/esm/v3/managedChatResponse.js +36 -18
  62. package/dist/esm/v3/managedChatResponse.js.map +1 -1
  63. package/dist/esm/v3/oidc/aws.d.ts +22 -0
  64. package/dist/esm/v3/oidc/aws.js +40 -0
  65. package/dist/esm/v3/oidc/aws.js.map +1 -0
  66. package/dist/esm/v3/steeringContext.d.ts +11 -0
  67. package/dist/esm/v3/steeringContext.js +44 -4
  68. package/dist/esm/v3/steeringContext.js.map +1 -1
  69. package/dist/esm/v3/subAgentStream.d.ts +50 -0
  70. package/dist/esm/v3/subAgentStream.js +149 -0
  71. package/dist/esm/v3/subAgentStream.js.map +1 -0
  72. package/dist/esm/v3/transcriptStorage.js +3 -0
  73. package/dist/esm/v3/transcriptStorage.js.map +1 -1
  74. package/dist/esm/v3/uiMessageChunks.js +5 -1
  75. package/dist/esm/v3/uiMessageChunks.js.map +1 -1
  76. package/dist/esm/version.js +1 -1
  77. package/docs/ai-chat/background-injection.mdx +2 -0
  78. package/docs/ai-chat/client-protocol.mdx +1 -0
  79. package/docs/ai-chat/frontend.mdx +16 -1
  80. package/docs/ai-chat/overview.mdx +1 -1
  81. package/docs/ai-chat/patterns/sub-agents.mdx +81 -55
  82. package/docs/ai-chat/pending-messages.mdx +2 -0
  83. package/docs/ai-chat/quick-start.mdx +1 -1
  84. package/docs/ai-chat/reference.mdx +22 -0
  85. package/docs/ai-chat/server-chat.mdx +11 -7
  86. package/docs/apikeys.mdx +5 -0
  87. package/docs/cli-login-commands.mdx +7 -1
  88. package/docs/cli-webhooks-commands.mdx +115 -0
  89. package/docs/config/config-file.mdx +3 -3
  90. package/docs/github-integration.mdx +21 -0
  91. package/docs/how-to-reduce-your-spend.mdx +4 -0
  92. package/docs/limits.mdx +41 -0
  93. package/docs/observability/query.mdx +29 -0
  94. package/docs/oidc.mdx +262 -0
  95. package/docs/self-hosting/docker.mdx +62 -0
  96. package/docs/self-hosting/env/supervisor.mdx +3 -0
  97. package/docs/self-hosting/env/webapp.mdx +14 -0
  98. package/docs/self-hosting/kubernetes.mdx +2 -0
  99. package/docs/troubleshooting-alerts.mdx +39 -0
  100. package/docs/webhooks/connect.mdx +12 -0
  101. package/docs/webhooks/deliveries.mdx +4 -0
  102. package/docs/webhooks/overview.mdx +8 -0
  103. package/docs/webhooks/sources.mdx +3 -1
  104. package/docs/webhooks/waiters.mdx +3 -3
  105. package/package.json +22 -2
  106. package/skills/trigger-chat-agent-advanced/SKILL.md +17 -7
  107. package/skills/trigger-cost-savings/SKILL.md +1 -0
@@ -109,7 +109,7 @@ Every chat is backed by a durable Session — the row that owns the chat's runs,
109
109
  | Field | Type | Notes |
110
110
  | --- | --- | --- |
111
111
  | `publicAccessToken` | `string` | Session-scoped JWT (`read:sessions:{chatId} + write:sessions:{chatId}`). Refreshed automatically on 401/403 via `accessToken`. |
112
- | `lastEventId` | `string \| undefined` | Last SSE event received on `.out`. **Valid for the lifetime of the Session** — keep it across `endRun` / `requestUpgrade` / continuation-run boundaries; only clear when the Session itself closes. The cursor lets the next subscription open past the prior turn's stale `turn-complete` record. |
112
+ | `lastEventId` | `string \| undefined` | Resume cursor on `.out`: the last SSE event received, or while a turn is streaming, the cursor from when that turn started, so a reload replays the whole turn. **Valid for the lifetime of the Session**: keep it across `endRun` / `requestUpgrade` / continuation-run boundaries; only clear when the Session itself closes. The cursor lets the next subscription open past the prior turn's stale `turn-complete` record. |
113
113
  | `isStreaming` | `boolean \| undefined` | **Optional.** The transport sets it internally, but you don't have to persist it — the server decides "nothing is streaming" via the session's [`X-Session-Settled`](/ai-chat/client-protocol#x-session-settled-fast-close-on-idle-reconnects) signal on reconnect. If you do persist it, the transport keeps the fast-path short-circuit. If you drop it, reconnects open the SSE and close fast on settled sessions. |
114
114
 
115
115
  ### Session cleanup (frontend)
@@ -503,6 +503,21 @@ for await (const chunk of stream) {
503
503
  }
504
504
  ```
505
505
 
506
+ ## Sub-agents
507
+
508
+ When a tool delegates to a sub-agent with [`chat.forwardSubAgent`](/ai-chat/patterns/sub-agents), the parent's tool part has no output until the sub-agent finishes. `useSubAgentMessages` rebuilds the sub-agent's message from the chunks streamed so far:
509
+
510
+ ```tsx app/components/chat.tsx
511
+ import { useChat } from "@ai-sdk/react";
512
+ import { useSubAgentMessages } from "@trigger.dev/sdk/chat/react";
513
+
514
+ const subAgents = useSubAgentMessages();
515
+ const { messages } = useChat({ transport, onData: subAgents.onData });
516
+
517
+ // in the tool card: live while it runs, the tool output once it finishes
518
+ const message = subAgents.get(part.toolCallId) ?? part.output;
519
+ ```
520
+
506
521
  ## Multi-tab coordination
507
522
 
508
523
  When the same chat is open in multiple browser tabs, `multiTab: true` prevents duplicate messages and syncs conversation state across tabs. Only one tab can send at a time. Other tabs enter read-only mode with real-time message updates.
@@ -60,7 +60,7 @@ Four primitives, related but distinct:
60
60
 
61
61
  - **Chat agents** — the SDK surface you define with [`chat.agent()`](/ai-chat/backend#chat-agent). Owns the turn loop, lifecycle hooks, and the response stream.
62
62
  - **Sessions** — the durable, bi-directional channel keyed on `chatId` that holds the conversation across run boundaries. A chat agent runs *on top of* a [Session](/ai-chat/sessions).
63
- - **Sub-agents** — Delegate work from one agent to another via [`AgentChat`](/ai-chat/patterns/sub-agents). The sub-agent runs as its own durable agent on its own session; its response streams back through the parent as preliminary tool results, so the frontend sees the sub-agent working inside the parent's tool card.
63
+ - **Sub-agents**: delegate work from one agent to another via [`AgentChat`](/ai-chat/patterns/sub-agents). The sub-agent runs as its own durable agent on its own session; [`chat.forwardSubAgent`](/ai-chat/patterns/sub-agents) streams its reply through the parent's tool call, so the frontend sees the sub-agent working inside the parent's tool card.
64
64
  - **Channels** connect an agent to a surface other than your frontend. [`slack()`](/webhooks/slack) and [`linear()`](/webhooks/linear) turn an agent into a Slack or Linear agent, and [`chat.channels.custom()`](/webhooks/channels) connects any chat surface that sends webhooks. Each conversation there is still a durable session, and the reply posts back to the surface.
65
65
 
66
66
  ## Next steps
@@ -1,33 +1,36 @@
1
1
  ---
2
2
  title: "Sub-Agents"
3
3
  sidebarTitle: "Sub-Agents"
4
- description: "Delegate work to durable sub-agents from within a parent agent's tool calls, with streaming preliminary results."
4
+ description: "Delegate work to durable sub-agents from a parent agent's tool calls, and stream each sub-agent's work to the frontend as it happens."
5
5
  ---
6
6
 
7
- Sub-agents let a parent agent delegate work to other agents running as durable Trigger.dev tasks. The sub-agent's response streams back through the parent as preliminary tool results, so the frontend sees the sub-agent working inside the parent's tool call card.
7
+ **Sub-agents let a parent agent delegate work to other agents running as durable Trigger.dev tasks, and `chat.forwardSubAgent` streams each sub-agent's reply to the frontend inside the parent's tool call.**
8
8
 
9
- This builds on the AI SDK's [async generator tool pattern](https://ai-sdk.dev/docs/agents/subagents) and Trigger.dev's [AgentChat](/ai-chat/server-chat) for server-side agent interaction.
9
+ Every chunk the sub-agent streams is written to the parent chat once, so the cost of streaming a sub-agent grows with the length of its reply. When the sub-agent finishes, its final message becomes the tool's output and persists with the parent's history.
10
+
11
+ This builds on Trigger.dev's [AgentChat](/ai-chat/server-chat) for server-side agent interaction.
10
12
 
11
13
  ## How it works
12
14
 
13
- 1. The parent LLM calls a tool (e.g., `researchAgent`)
14
- 2. The tool's `execute` is an `async function*` (async generator)
15
- 3. Inside, it creates an `AgentChat` and sends a message to the sub-agent
16
- 4. `yield* stream.messages()` streams each accumulated `UIMessage` snapshot as a preliminary tool result
17
- 5. The frontend renders the sub-agent's response building up inside the parent's tool card
18
- 6. `toModelOutput` compresses the full output into a summary for the parent LLM
15
+ 1. The parent LLM calls a tool (for example `research`).
16
+ 2. The tool's `execute` creates an `AgentChat` and sends a message to the sub-agent.
17
+ 3. `chat.forwardSubAgent(stream, { toolCallId })` writes each sub-agent chunk to the parent chat as a transient `data-subagent` part.
18
+ 4. The frontend rebuilds the sub-agent's message from those chunks with `useSubAgentMessages` and renders it inside the parent's tool card.
19
+ 5. When the sub-agent finishes, `forwardSubAgent` resolves with its final `UIMessage`, which becomes the tool's output.
20
+ 6. `toModelOutput` compresses that output into a summary for the parent LLM.
19
21
 
20
22
  ```
21
23
  Parent LLM
22
24
  │
23
- ├─ calls researchAgent tool
25
+ ├─ calls research tool
24
26
  │ │
25
27
  │ ├─ AgentChat triggers sub-agent run
26
- │ ├─ sub-agent streams response (text, tool calls, etc.)
27
- │ ├─ yield* sends UIMessage snapshots as preliminary results
28
- │ └─ toModelOutput compresses for parent LLM
28
+ │ ├─ sub-agent streams its reply (text, tool calls, etc.)
29
+ │ ├─ forwardSubAgent writes each chunk once as a transient data-subagent part
30
+ │ ├─ the tool returns the sub-agent's final UIMessage
31
+ │ └─ toModelOutput compresses it for the parent LLM
29
32
  │
30
- └─ parent LLM reads compressed summary, continues reasoning
33
+ └─ parent LLM reads the summary and continues
31
34
  ```
32
35
 
33
36
  ## Single-turn sub-agent
@@ -35,7 +38,8 @@ Parent LLM
35
38
  The simplest pattern: one tool call, one sub-agent turn, conversation closes.
36
39
 
37
40
  ```ts
38
- import { tool, stepCountIs } from "ai";
41
+ import { tool } from "ai";
42
+ import { chat } from "@trigger.dev/sdk/ai";
39
43
  import { AgentChat } from "@trigger.dev/sdk/chat";
40
44
  import { z } from "zod";
41
45
  import type { prReviewAgent } from "./trigger/pr-review";
@@ -46,19 +50,20 @@ const prReviewTool = tool({
46
50
  prNumber: z.number().describe("The PR number to review"),
47
51
  repo: z.string().describe("The GitHub repo URL"),
48
52
  }),
49
- execute: async function* ({ prNumber, repo }, { abortSignal }) {
50
- const chat = new AgentChat<typeof prReviewAgent>({
53
+ execute: async ({ prNumber, repo }, { toolCallId, abortSignal }) => {
54
+ const reviewer = new AgentChat<typeof prReviewAgent>({
51
55
  agent: "pr-review",
52
56
  id: `review-${prNumber}`,
53
57
  clientData: { userId: "parent-agent", githubUrl: repo },
54
58
  });
55
59
 
56
- const stream = await chat.sendMessage(`Review PR #${prNumber}`, { abortSignal });
57
-
58
- // Each yield sends a UIMessage snapshot to the frontend
59
- yield* stream.messages();
60
-
61
- await chat.close();
60
+ try {
61
+ const stream = await reviewer.sendMessage(`Review PR #${prNumber}`, { abortSignal });
62
+ // Streams the review to the frontend and resolves with the final message
63
+ return await chat.forwardSubAgent(stream, { toolCallId });
64
+ } finally {
65
+ await reviewer.close();
66
+ }
62
67
  },
63
68
  // The parent LLM only sees this compressed summary
64
69
  toModelOutput: ({ output: message }) => {
@@ -70,26 +75,42 @@ const prReviewTool = tool({
70
75
  });
71
76
  ```
72
77
 
73
- Use this tool in a parent agent's `streamText` call:
78
+ `forwardSubAgent` needs the parent chat to write to, so call it from a tool that runs inside a `chat.agent` or `chat.customAgent` run. [Combining with chat.agent()](#combining-with-chat-agent) below shows the agent side.
74
79
 
75
- ```ts
76
- import { streamText } from "ai";
77
- import { anthropic } from "@ai-sdk/anthropic";
80
+ ## Render sub-agents in the frontend
78
81
 
79
- const result = streamText({
80
- model: anthropic("claude-sonnet-4-6"),
81
- tools: { prReview: prReviewTool },
82
- prompt: "Review PR #42 on triggerdotdev/trigger.dev",
83
- stopWhen: stepCountIs(15),
84
- });
82
+ While the sub-agent runs, the parent's tool part has no output yet. `useSubAgentMessages` collects the forwarded chunks and gives you the sub-agent's message so far for each tool call:
83
+
84
+ ```tsx app/components/chat.tsx
85
+ import { useChat } from "@ai-sdk/react";
86
+ import type { TriggerChatTransport } from "@trigger.dev/sdk/chat";
87
+ import { useSubAgentMessages } from "@trigger.dev/sdk/chat/react";
88
+ import { ReviewCard } from "./review-card";
89
+
90
+ export function Chat({ transport }: { transport: TriggerChatTransport }) {
91
+ const subAgents = useSubAgentMessages();
92
+ const { messages } = useChat({ transport, onData: subAgents.onData });
93
+
94
+ return messages.map((message) =>
95
+ message.parts.map((part) => {
96
+ if (part.type !== "tool-prReview") return null;
97
+ // Live while the sub-agent runs, the tool output once it finishes
98
+ const review = subAgents.get(part.toolCallId) ?? part.output;
99
+ return <ReviewCard key={part.toolCallId} message={review} />;
100
+ })
101
+ );
102
+ }
85
103
  ```
86
104
 
105
+ The hook rebuilds each message at most once per `throttleMs` (100ms by default), so a long reply costs a bounded number of rebuilds. After a reload mid-turn, the transport replays the current turn and the hook rebuilds the sub-agent's message from it; batches it has already seen are skipped. Outside React, `createSubAgentMessages()` from `@trigger.dev/sdk/chat` does the same job.
106
+
87
107
  ## Multi-turn sub-agent (LLM-driven)
88
108
 
89
109
  The parent LLM drives a persistent conversation with a sub-agent across multiple tool calls. Each call with the same `conversationId` hits the same durable agent run.
90
110
 
91
111
  ```ts
92
112
  import { tool } from "ai";
113
+ import { chat } from "@trigger.dev/sdk/ai";
93
114
  import { AgentChat } from "@trigger.dev/sdk/chat";
94
115
  import { z } from "zod";
95
116
 
@@ -106,7 +127,7 @@ const researchTool = tool({
106
127
  .describe("Unique ID for this research thread. Reuse to continue."),
107
128
  message: z.string().describe("Your message to the research agent"),
108
129
  }),
109
- execute: async function* ({ conversationId, message }, { abortSignal }) {
130
+ execute: async ({ conversationId, message }, { toolCallId, abortSignal }) => {
110
131
  let agent = subAgents.get(conversationId);
111
132
  if (!agent) {
112
133
  agent = new AgentChat({
@@ -117,7 +138,7 @@ const researchTool = tool({
117
138
  }
118
139
 
119
140
  const stream = await agent.sendMessage(message, { abortSignal });
120
- yield* stream.messages();
141
+ return await chat.forwardSubAgent(stream, { toolCallId });
121
142
  },
122
143
  toModelOutput: ({ output: message }) => {
123
144
  const lastText = message?.parts?.findLast(
@@ -209,13 +230,19 @@ For the multi-turn pattern, the parent should clean up sub-agents when it exits
209
230
 
210
231
  ## What the frontend sees
211
232
 
212
- Each `yield` from `stream.messages()` sends a complete `UIMessage` containing all the sub-agent's parts accumulated so far. The AI SDK delivers these as `tool-output-available` chunks with `preliminary: true`.
233
+ While the sub-agent runs, the parent's tool part stays in `state: "input-available"`, and the parent stream carries transient `data-subagent` parts. Each one holds a batch of the sub-agent's chunks, tagged with the parent's `toolCallId` and a sequence number:
213
234
 
214
- The frontend renders the tool part with:
215
- - `state: "output-available"` and `preliminary: true` while streaming
216
- - `state: "output-available"` and `preliminary: false` (or absent) when done
235
+ ```ts
236
+ {
237
+ type: "data-subagent",
238
+ transient: true,
239
+ data: { toolCallId: "toolu_01...", seq: 3, chunks: [/* UIMessageChunk[] */] },
240
+ }
241
+ ```
242
+
243
+ Transient parts reach `useChat`'s `onData` and are not added to `message.parts`, so they never persist. When the sub-agent finishes, the tool part moves to `state: "output-available"` with the full `UIMessage` as its output: text, the sub-agent's own tool calls and results, reasoning, and so on. That output is what reloaded history renders.
217
244
 
218
- The tool output contains the full `UIMessage` with nested parts — text, the sub-agent's own tool calls and results, reasoning, etc.
245
+ If the user stops the parent turn while a sub-agent is running, the tool call ends without an output, the same as any stopped tool. The sub-agent's work up to that point was only ever in the transient parts, so neither the parent's history nor the next turn's model context includes it.
219
246
 
220
247
  ### Controlling what the parent LLM sees
221
248
 
@@ -238,30 +265,27 @@ This is important for token efficiency: the sub-agent might use 100K tokens expl
238
265
  `toModelOutput` only runs when the SDK has your tools at conversion time. On a multi-turn parent, the SDK re-converts the persisted history at the start of each turn, so you must declare the sub-agent tool on the agent config (`chat.agent({ tools })`) for the compression to survive. Without it, the summary holds on turn 1 but turn 2 onward re-ingests the full sub-agent output. In a `chat.customAgent` loop you own the conversion, so pass the tools to `convertToModelMessages(uiMessages, { tools })` yourself. See [Tools: toModelOutput across turns](/ai-chat/tools#tomodeloutput-across-turns).
239
266
  </Warning>
240
267
 
241
- ## ChatStream.messages()
268
+ ## Snapshots with `stream.messages()`
242
269
 
243
- The `messages()` method on `ChatStream` wraps the AI SDK's `readUIMessageStream`. It reads the raw `UIMessageChunk` stream and yields complete `UIMessage` snapshots — each containing all parts received so far.
270
+ `ChatStream.messages()` wraps the AI SDK's `readUIMessageStream` and yields the whole accumulated `UIMessage` after almost every chunk. Yielding those snapshots from an `async function*` tool (`yield* stream.messages()`) turns each one into a preliminary tool result, which streams the sub-agent too, but every snapshot repeats the whole message so far. The bytes written grow with the square of the reply length:
244
271
 
245
- ```ts
246
- const stream = await chat.sendMessage("Research this topic");
272
+ | Sub-agent reply | `yield* stream.messages()` | `chat.forwardSubAgent` |
273
+ | --- | --- | --- |
274
+ | 500 text deltas, no tools | 1.1 MB | 0.07 MB |
275
+ | 5 tool results of 20 KB, then 2,000 deltas | 218 MB | 0.47 MB |
276
+ | 10 tool results of 50 KB, then 4,000 deltas | 2.1 GB | 1.5 MB |
277
+
278
+ Every one of those bytes goes to the chat's stream storage and to each browser watching the chat. Use `forwardSubAgent` for sub-agents, and keep `stream.messages()` for reading a short reply in server code:
247
279
 
248
- // Each yield is a complete UIMessage with all accumulated parts
280
+ ```ts
281
+ const stream = await agent.sendMessage("Summarize this ticket in one sentence");
249
282
  for await (const message of stream.messages()) {
250
283
  console.log(message.parts.length, "parts so far");
251
284
  }
252
285
  ```
253
286
 
254
- For the sub-agent pattern, use `yield*` to delegate all yields to the parent tool's generator:
255
-
256
- ```ts
257
- execute: async function* ({ topic }, { abortSignal }) {
258
- const stream = await chat.sendMessage(topic, { abortSignal });
259
- yield* stream.messages();
260
- },
261
- ```
262
-
263
287
  <Tip>
264
- `stream.messages()` consumes the stream. You can't also call `stream.text()` or iterate over chunks on the same stream. Pick one consumption mode.
288
+ A `ChatStream` can be consumed once: by `forwardSubAgent`, `stream.messages()`, `stream.text()`, or by iterating its chunks. Pick one.
265
289
  </Tip>
266
290
 
267
291
  ## Combining with chat.agent()
@@ -345,6 +369,8 @@ const research = tool({
345
369
  });
346
370
  ```
347
371
 
372
+ Keep a part you update this way small. The frontend replaces the part on each write, but the chat stream stores every version, so writing a growing payload under one `id` (a full message history, say) stores every copy. Mark progress updates that don't need to persist with `transient: true`, and use `chat.forwardSubAgent` when the thing you are streaming is a sub-agent's reply.
373
+
348
374
  On the frontend, render the custom data part:
349
375
 
350
376
  ```tsx
@@ -132,6 +132,8 @@ When messages are injected, the SDK automatically writes a `data-pending-message
132
132
  - Remove them from the pending overlay
133
133
  - Render them inline at the injection point in the assistant response
134
134
 
135
+ Background injections appear as a different data part (`data-background-injected`) that `usePendingMessages` ignores. It is not a user message.
136
+
135
137
  A "pending message injected" span also appears in the run trace.
136
138
 
137
139
  ## Backend: chat.createSession
@@ -159,5 +159,5 @@ Run your frontend and `pnpm exec trigger dev`, then send a message. You should s
159
159
  - [Frontend](/ai-chat/frontend) — Session management, client data, reconnection
160
160
  - [Types](/ai-chat/types) — `chat.withUIMessage`, `InferChatUIMessage`, and related typing
161
161
  - [`chat.local`](/ai-chat/chat-local) — Per-run typed state across hooks, run, tools, subtasks
162
- - [Sub-agents pattern](/ai-chat/patterns/sub-agents) — Subtask-as-tool, `target: "root"` streaming, `ai.toolExecute` helpers
162
+ - [Sub-agents pattern](/ai-chat/patterns/sub-agents): `chat.forwardSubAgent`, subtask-as-tool, `target: "root"` streaming, `ai.toolExecute` helpers
163
163
  - [Background injection](/ai-chat/background-injection) — `chat.inject()` and `chat.defer()` for between-turn work
@@ -565,6 +565,7 @@ All methods available on the `chat` object from `@trigger.dev/sdk/ai`.
565
565
  | `chat.isStopped()` | Check if the current turn was stopped by the user |
566
566
  | `chat.cleanupAbortedParts(message)` | Remove incomplete parts from a stopped response message |
567
567
  | `chat.response.write(chunk)` | Write a data part that streams to the frontend AND persists in `onTurnComplete`'s `responseMessage` |
568
+ | `chat.forwardSubAgent(stream, { toolCallId, flushIntervalMs? })` | Stream a sub-agent's reply through a parent tool call as transient `data-subagent` parts, and resolve with its final `UIMessage`. Call it inside a tool's `execute`. See [Sub-agents](/ai-chat/patterns/sub-agents) |
568
569
  | `chat.stream` | Raw chat output stream — use `.writer()`, `.pipe()`, `.append()`, `.read()`. Chunks are NOT accumulated into the response. |
569
570
  | `chat.history.all()` | Read the current accumulated UI messages (returns a copy). See [chat.history](/ai-chat/backend#chat-history) |
570
571
  | `chat.history.set(messages)` | Replace all accumulated messages (same as `chat.setMessages()`) |
@@ -837,6 +838,27 @@ const transport = useTriggerChatTransport({
837
838
 
838
839
  No-op when `BroadcastChannel` is unavailable (SSR, Node.js). See [Multi-tab coordination](/ai-chat/frontend#multi-tab-coordination).
839
840
 
841
+ ## useSubAgentMessages
842
+
843
+ React hook that rebuilds sub-agents streamed with [`chat.forwardSubAgent`](/ai-chat/patterns/sub-agents) while they run. Import from `@trigger.dev/sdk/chat/react`.
844
+
845
+ ```tsx
846
+ import { useSubAgentMessages } from "@trigger.dev/sdk/chat/react";
847
+
848
+ const subAgents = useSubAgentMessages();
849
+ const { messages } = useChat({ transport, onData: subAgents.onData });
850
+
851
+ const message = subAgents.get(part.toolCallId) ?? part.output;
852
+ ```
853
+
854
+ | Option | Type | Default | Description |
855
+ | ------------ | -------- | ------- | ------------------------------------------------------------------------ |
856
+ | `throttleMs` | `number` | `100` | Minimum time between rebuilds of a sub-agent's message while chunks stream in. |
857
+
858
+ **Returns:** `{ onData, get }`. Pass `onData` to `useChat`. `get(toolCallId)` returns the sub-agent's `UIMessage` so far, or `undefined` before its first chunk. Batches a resumed stream replays are skipped, so a reload mid-turn does not duplicate content.
859
+
860
+ `createSubAgentMessages({ throttleMs?, onChange? })` from `@trigger.dev/sdk/chat` is the same store without React: call its `onData` with every data part you receive, read with `get(toolCallId)`, and `dispose()` when you are done.
861
+
840
862
  ### Trigger configuration
841
863
 
842
864
  Trigger config (machine, queue, tags, maxAttempts, idleTimeoutInSeconds) lives server-side in `chat.createStartSessionAction(taskId, options?)`. The transport doesn't accept these options directly — pass them when wrapping the action:
@@ -161,21 +161,25 @@ export async function POST(req: Request) {
161
161
 
162
162
  ## Sub-agent tool pattern
163
163
 
164
- `AgentChat` can be used inside an AI SDK tool to delegate work to a durable sub-agent. The sub-agent's response streams as preliminary tool results:
164
+ `AgentChat` can be used inside an AI SDK tool to delegate work to a durable sub-agent. `chat.forwardSubAgent` streams the sub-agent's reply to the frontend inside the tool call and resolves with its final message:
165
165
 
166
166
  ```ts
167
167
  import { tool } from "ai";
168
+ import { chat } from "@trigger.dev/sdk/ai";
168
169
  import { AgentChat } from "@trigger.dev/sdk/chat";
169
170
  import { z } from "zod";
170
171
 
171
172
  const researchTool = tool({
172
173
  description: "Delegate research to a specialist agent.",
173
174
  inputSchema: z.object({ topic: z.string() }),
174
- execute: async function* ({ topic }, { abortSignal }) {
175
- const chat = new AgentChat({ agent: "research-agent" });
176
- const stream = await chat.sendMessage(topic, { abortSignal });
177
- yield* stream.messages();
178
- await chat.close();
175
+ execute: async ({ topic }, { toolCallId, abortSignal }) => {
176
+ const researcher = new AgentChat({ agent: "research-agent" });
177
+ try {
178
+ const stream = await researcher.sendMessage(topic, { abortSignal });
179
+ return await chat.forwardSubAgent(stream, { toolCallId });
180
+ } finally {
181
+ await researcher.close();
182
+ }
179
183
  },
180
184
  toModelOutput: ({ output: message }) => {
181
185
  const lastText = message?.parts?.findLast(
@@ -254,6 +258,6 @@ const stream = await chat.reconnect();
254
258
  |---|---|---|
255
259
  | `text()` | `Promise<string>` | Consume stream, return accumulated text |
256
260
  | `result()` | `Promise<ChatStreamResult>` | Consume stream, return `{ text, toolCalls, toolResults }` |
257
- | `messages()` | `AsyncGenerator<UIMessage>` | Yield accumulated UIMessage snapshots (sub-agent pattern) |
261
+ | `messages()` | `AsyncGenerator<UIMessage>` | Yield the accumulated UIMessage after each chunk. For sub-agents, pass the stream to `chat.forwardSubAgent` instead |
258
262
  | `[Symbol.asyncIterator]` | `UIMessageChunk` | Iterate over typed stream chunks |
259
263
  | `.stream` | `ReadableStream<UIMessageChunk>` | Raw stream for AI SDK utilities |
package/docs/apikeys.mdx CHANGED
@@ -10,6 +10,11 @@ description: "Authenticate backend requests with environment-specific API keys."
10
10
  environment variable, never commit them to source control, and never expose them in frontend code.
11
11
  </Warning>
12
12
 
13
+ <Tip>
14
+ To access AWS or another external service from a deployed task without stored cloud keys, use
15
+ [OpenID Connect (OIDC)](/oidc). Trigger.dev API keys cannot mint OIDC tokens.
16
+ </Tip>
17
+
13
18
  ## Create an API key
14
19
 
15
20
  Create a separate named key for each service or integration that accesses Trigger.dev.
@@ -24,10 +24,16 @@ yarn dlx trigger.dev@latest login
24
24
 
25
25
  </CodeGroup>
26
26
 
27
+ When the CLI opens your browser, approving the login sends you back to the CLI automatically. If the browser is on another machine, for example when you're connected over SSH, use `--no-browser`: after you approve, the page shows a code to paste into the terminal.
28
+
27
29
  ## Options
28
30
 
29
31
  <ParamField body="No browser" type="--no-browser">
30
- Do not open the browser. Print the URL only.
32
+ Do not open the browser. Print the URL only, and finish the login by pasting the code shown after you approve.
33
+ </ParamField>
34
+
35
+ <ParamField body="Code" type="--code <code>">
36
+ Finish a pending login with the code shown in your browser. Use this after `--no-wait`, or when the terminal can't prompt for the code.
31
37
  </ParamField>
32
38
 
33
39
  <ParamField body="Email" type="--email <email>">
@@ -0,0 +1,115 @@
1
+ ---
2
+ title: "CLI webhooks commands"
3
+ sidebarTitle: "webhooks"
4
+ description: "Set or generate the signing secret of a hosted webhook endpoint from your terminal, without printing it."
5
+ ---
6
+
7
+ import CommonOptions from "/snippets/cli-options-common.mdx";
8
+ import ConfigFileOptions from "/snippets/cli-options-config-file.mdx";
9
+ import ProjectRefOptions from "/snippets/cli-options-project-ref.mdx";
10
+
11
+ **These commands store a [webhook endpoint's](/webhooks/overview) signing secret without printing it, so the value stays out of your terminal history, logs and AI agent transcripts.** `endpoint` is the endpoint's declared id (the `id` passed to `webhooks.endpoint.define`) or its `wh_` id.
12
+
13
+ ## Replacing an existing secret
14
+
15
+ When the endpoint already has a secret, both commands ask how long the old one keeps working, with the same choices as the dashboard: stop immediately, 1 hour, 24 hours (the default) or 7 days. In a script or an AI agent, where there's no prompt, pass `--previous-secret-ttl` instead; the command refuses to replace the secret without it, so a rotation can't cut the provider off by accident:
16
+
17
+ ```bash
18
+ npx trigger.dev@latest webhooks set-secret stripe --env prod --from-env STRIPE_WEBHOOK_SECRET --previous-secret-ttl 24h
19
+ ```
20
+
21
+ ## webhooks set-secret
22
+
23
+ Stores the signing secret or public key a provider issued, such as the `whsec_` secret Stripe returns when you create a webhook endpoint. It replaces the endpoint's current secret.
24
+
25
+ Pipe the secret in from the provider's CLI or a file:
26
+
27
+ <CodeGroup>
28
+
29
+ ```bash npm
30
+ stripe webhook_endpoints create -d url="$WEBHOOK_URL" -d "enabled_events[]=checkout.session.completed" \
31
+ | jq -r .secret \
32
+ | npx trigger.dev@latest webhooks set-secret stripe --env prod
33
+ ```
34
+
35
+ ```bash pnpm
36
+ stripe webhook_endpoints create -d url="$WEBHOOK_URL" -d "enabled_events[]=checkout.session.completed" \
37
+ | jq -r .secret \
38
+ | pnpm dlx trigger.dev@latest webhooks set-secret stripe --env prod
39
+ ```
40
+
41
+ ```bash bun
42
+ stripe webhook_endpoints create -d url="$WEBHOOK_URL" -d "enabled_events[]=checkout.session.completed" \
43
+ | jq -r .secret \
44
+ | bunx trigger.dev@latest webhooks set-secret stripe --env prod
45
+ ```
46
+
47
+ </CodeGroup>
48
+
49
+ Or read it from an environment variable. Without `--from-file`, the command checks the shell environment, then the project's `.env`, `.env.development`, `.env.local` and `.env.development.local` files:
50
+
51
+ ```bash
52
+ npx trigger.dev@latest webhooks set-secret stripe --env prod --from-env STRIPE_WEBHOOK_SECRET
53
+ ```
54
+
55
+ Run it in a terminal without either option and it asks for the secret with a masked prompt.
56
+
57
+ <ParamField body="From env" type="--from-env">
58
+ Read the secret from this environment variable.
59
+ </ParamField>
60
+
61
+ <ParamField body="From file" type="--from-file">
62
+ With `--from-env`, read the variable from this `.env` file only.
63
+ </ParamField>
64
+
65
+ <ParamField body="Previous secret TTL" type="--previous-secret-ttl">
66
+ When the endpoint already has a secret, how long the old one keeps working while the provider switches to the new one: seconds (`3600`) or a duration (`1h`, `24h`, `7d`), at most 7 days. `0` stops it straight away, for a secret that leaked.
67
+ </ParamField>
68
+
69
+ ## webhooks generate-secret
70
+
71
+ Generates a new signing secret, for providers that accept a secret you choose, such as GitHub. It replaces the endpoint's current secret.
72
+
73
+ Save it to an env file, then hand it to the provider by variable name:
74
+
75
+ ```bash
76
+ npx trigger.dev@latest webhooks generate-secret github --env prod --to-env GITHUB_WEBHOOK_SECRET
77
+ ```
78
+
79
+ The command writes `GITHUB_WEBHOOK_SECRET` to `.env.local`, creating the file if needed, and prints only where it saved the value. Or pipe it straight into the provider's CLI with `--print`, which outputs the secret and nothing else.
80
+
81
+ When the output isn't a terminal, the command refuses to print the secret unless you pass `--to-env` or `--print`, so an AI agent running it doesn't capture the value by accident.
82
+
83
+ <ParamField body="To env" type="--to-env">
84
+ Save the secret as this variable in an env file.
85
+ </ParamField>
86
+
87
+ <ParamField body="To file" type="--to-file">
88
+ With `--to-env`, the file to save to. Defaults to `.env.local`.
89
+ </ParamField>
90
+
91
+ <ParamField body="Print" type="--print">
92
+ Print only the secret, for piping it into another command.
93
+ </ParamField>
94
+
95
+ <ParamField body="Previous secret TTL" type="--previous-secret-ttl">
96
+ When the endpoint already has a secret, how long the old one keeps working while the provider switches to the new one: seconds (`3600`) or a duration (`1h`, `24h`, `7d`), at most 7 days. `0` stops it straight away, for a secret that leaked.
97
+ </ParamField>
98
+
99
+ ## Options
100
+
101
+ <ParamField body="Environment" type="--env | -e">
102
+ The environment to use: `dev`, `prod`, `staging` or `preview`. Defaults to `prod`.
103
+ </ParamField>
104
+
105
+ <ConfigFileOptions />
106
+ <ProjectRefOptions />
107
+ <ParamField body="Branch" type="--branch | -b">
108
+ The branch to use. Required with `--env preview`.
109
+ </ParamField>
110
+
111
+ ### Common options
112
+
113
+ These options are available on most commands.
114
+
115
+ <CommonOptions />
@@ -329,7 +329,7 @@ After each call we restore the few attributes we use to link a span to its run,
329
329
 
330
330
  If you don't set a `runtime`, your tasks run on the current Node.js LTS. Setting `runtime: "node"` does the same thing — see the Node.js versions section below to pin a specific version instead.
331
331
 
332
- We currently only officially support the `node` runtime, but you can try our experimental `bun` runtime by setting the `runtime` option in your config file:
332
+ We currently only officially support the `node` runtime, but you can try our experimental Bun runtimes by setting the `runtime` option in your config file:
333
333
 
334
334
  ```ts trigger.config.ts
335
335
  import { defineConfig } from "@trigger.dev/sdk";
@@ -337,11 +337,11 @@ import { defineConfig } from "@trigger.dev/sdk";
337
337
  export default defineConfig({
338
338
  project: "<project ref>",
339
339
  // Your other config settings...
340
- runtime: "bun",
340
+ runtime: "bun-1.4",
341
341
  });
342
342
  ```
343
343
 
344
- See our [Bun guide](/guides/frameworks/bun) for more information.
344
+ `bun-1.4` runs on a Bun-only image with no Node.js binary. `bun` (Bun 1.3 with a Node.js binary alongside it) is deprecated, and deploys that use it will be rejected from January 5, 2027. See our [Bun guide](/guides/frameworks/bun) for the differences.
345
345
 
346
346
  ### Node.js versions
347
347
 
@@ -72,6 +72,27 @@ The name of the preview branch matches the branch name of the pull request.
72
72
  Preview branch deployments require the preview environment to be enabled on your project. Learn more about [preview branches](/deployment/preview-branches).
73
73
  </Note>
74
74
 
75
+ ## Ignored paths
76
+
77
+ Skip builds for pushes that only touch files your tasks do not depend on, such as docs or another app in a monorepo.
78
+
79
+ Open **Integrations** in your project settings and add the patterns in the git settings panel below the branch fields, one per line. A push builds unless every file changed by the pushed commits matches a pattern. A newly opened pull request compares every file it changes against its base branch in the same way. Some pushes build regardless of the patterns, such as force pushes or pushes that change 300 or more files. Use **Test a path** to check which pattern, if any, ignores a given file.
80
+
81
+ ```text
82
+ docs/**
83
+ **/*.md
84
+ apps/web/**
85
+ .github/**
86
+ ```
87
+
88
+ Patterns are globs relative to the repository root and match like `paths-ignore` in GitHub Actions. `**` matches across folders and also matches dotfiles, so `**/*.md` ignores `.github/PULL_REQUEST_TEMPLATE.md`. Negation (`!`), braces (`{a,b}`), extglob groups like `+(...)` and `[!...]` are not supported; use `[^...]` to exclude characters. You can add up to 100 patterns of up to 256 characters each.
89
+
90
+ When a build is skipped, no deployment is created and the commit's Trigger.dev check is marked as skipped, with the matched patterns in its summary. Re-run that check from GitHub to build the commit anyway.
91
+
92
+ <Note>
93
+ Projects connected to Vercel always build. See [production waits for your tasks](/vercel-integration#production-waits-for-your-tasks).
94
+ </Note>
95
+
75
96
  ## Version skew protection
76
97
 
77
98
  Every deployment the GitHub integration creates is tagged with the commit SHA it was built from. That is the deploy half of [version skew protection](/deployment/atomic-deployment) — you get it for free.
@@ -190,6 +190,10 @@ export const waitpointTask = task({
190
190
 
191
191
  Waiting saves you compute, but it doesn't always free up concurrency — see [Wait](/wait).
192
192
 
193
+ ## Filter webhooks before they start runs
194
+
195
+ Give each [webhook](/webhooks/overview) subscriber a [filter](/webhooks/filters) so it only runs for the events it handles. A delivery that no subscriber's filter matches starts no run for any subscriber, so you aren't charged for it. Filters only apply to subscribers: a run [waiting](/webhooks/waiters) for a matching webhook still resumes and uses compute. Receiving webhooks has no separate charge.
196
+
193
197
  ## Use debounce to consolidate multiple triggers
194
198
 
195
199
  When a task might be triggered multiple times in quick succession, use debounce to consolidate them into a single run. This is useful for document indexing, webhook aggregation, cache invalidation, and real-time sync scenarios.