@trigger.dev/sdk 4.5.16 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/commonjs/imports/ai-runtime-cjs.cjs.map +1 -1
  2. package/dist/commonjs/imports/ai-runtime.js +2 -0
  3. package/dist/commonjs/v3/ai-shared.d.ts +15 -0
  4. package/dist/commonjs/v3/ai-shared.js +35 -1
  5. package/dist/commonjs/v3/ai-shared.js.map +1 -1
  6. package/dist/commonjs/v3/ai.d.ts +311 -25
  7. package/dist/commonjs/v3/ai.js +1633 -380
  8. package/dist/commonjs/v3/ai.js.map +1 -1
  9. package/dist/commonjs/v3/auth.d.ts +10 -4
  10. package/dist/commonjs/v3/auth.js.map +1 -1
  11. package/dist/commonjs/v3/chat-client.d.ts +11 -2
  12. package/dist/commonjs/v3/chat-client.js +227 -111
  13. package/dist/commonjs/v3/chat-client.js.map +1 -1
  14. package/dist/commonjs/v3/chat-react.d.ts +88 -0
  15. package/dist/commonjs/v3/chat-react.js +130 -1
  16. package/dist/commonjs/v3/chat-react.js.map +1 -1
  17. package/dist/commonjs/v3/chat-server.d.ts +42 -6
  18. package/dist/commonjs/v3/chat-server.js +52 -7
  19. package/dist/commonjs/v3/chat-server.js.map +1 -1
  20. package/dist/commonjs/v3/chat.d.ts +92 -10
  21. package/dist/commonjs/v3/chat.js +328 -73
  22. package/dist/commonjs/v3/chat.js.map +1 -1
  23. package/dist/commonjs/v3/chatSnapshotIo.d.ts +2 -0
  24. package/dist/commonjs/v3/chatSnapshotIo.js +173 -0
  25. package/dist/commonjs/v3/chatSnapshotIo.js.map +1 -0
  26. package/dist/commonjs/v3/chatVersionSkew.d.ts +12 -0
  27. package/dist/commonjs/v3/chatVersionSkew.js +30 -0
  28. package/dist/commonjs/v3/chatVersionSkew.js.map +1 -0
  29. package/dist/commonjs/v3/externalDeploymentId.d.ts +23 -0
  30. package/dist/commonjs/v3/externalDeploymentId.js +43 -0
  31. package/dist/commonjs/v3/externalDeploymentId.js.map +1 -0
  32. package/dist/commonjs/v3/retry.d.ts +4 -0
  33. package/dist/commonjs/v3/retry.js +22 -13
  34. package/dist/commonjs/v3/retry.js.map +1 -1
  35. package/dist/commonjs/v3/sessions.d.ts +15 -2
  36. package/dist/commonjs/v3/sessions.js +12 -1
  37. package/dist/commonjs/v3/sessions.js.map +1 -1
  38. package/dist/commonjs/v3/shared.js +30 -36
  39. package/dist/commonjs/v3/shared.js.map +1 -1
  40. package/dist/commonjs/v3/test/index.d.ts +1 -0
  41. package/dist/commonjs/v3/test/index.js +3 -1
  42. package/dist/commonjs/v3/test/index.js.map +1 -1
  43. package/dist/commonjs/v3/test/mock-chat-agent.d.ts +47 -4
  44. package/dist/commonjs/v3/test/mock-chat-agent.js +116 -10
  45. package/dist/commonjs/v3/test/mock-chat-agent.js.map +1 -1
  46. package/dist/commonjs/v3/test/test-session-handle.js +6 -0
  47. package/dist/commonjs/v3/test/test-session-handle.js.map +1 -1
  48. package/dist/commonjs/v3/test/transcript-storage-tests.d.ts +40 -0
  49. package/dist/commonjs/v3/test/transcript-storage-tests.js +258 -0
  50. package/dist/commonjs/v3/test/transcript-storage-tests.js.map +1 -0
  51. package/dist/commonjs/v3/transcriptStorage.d.ts +261 -0
  52. package/dist/commonjs/v3/transcriptStorage.js +374 -0
  53. package/dist/commonjs/v3/transcriptStorage.js.map +1 -0
  54. package/dist/commonjs/version.js +1 -1
  55. package/dist/esm/imports/ai-runtime.d.ts +2 -2
  56. package/dist/esm/imports/ai-runtime.js +2 -2
  57. package/dist/esm/imports/ai-runtime.js.map +1 -1
  58. package/dist/esm/v3/ai-shared.d.ts +15 -0
  59. package/dist/esm/v3/ai-shared.js +33 -0
  60. package/dist/esm/v3/ai-shared.js.map +1 -1
  61. package/dist/esm/v3/ai.d.ts +311 -25
  62. package/dist/esm/v3/ai.js +1625 -377
  63. package/dist/esm/v3/ai.js.map +1 -1
  64. package/dist/esm/v3/auth.d.ts +10 -4
  65. package/dist/esm/v3/auth.js.map +1 -1
  66. package/dist/esm/v3/chat-client.d.ts +11 -2
  67. package/dist/esm/v3/chat-client.js +228 -112
  68. package/dist/esm/v3/chat-client.js.map +1 -1
  69. package/dist/esm/v3/chat-react.d.ts +88 -0
  70. package/dist/esm/v3/chat-react.js +127 -1
  71. package/dist/esm/v3/chat-react.js.map +1 -1
  72. package/dist/esm/v3/chat-server.d.ts +42 -6
  73. package/dist/esm/v3/chat-server.js +53 -8
  74. package/dist/esm/v3/chat-server.js.map +1 -1
  75. package/dist/esm/v3/chat.d.ts +92 -10
  76. package/dist/esm/v3/chat.js +329 -74
  77. package/dist/esm/v3/chat.js.map +1 -1
  78. package/dist/esm/v3/chatSnapshotIo.d.ts +2 -0
  79. package/dist/esm/v3/chatSnapshotIo.js +165 -0
  80. package/dist/esm/v3/chatSnapshotIo.js.map +1 -0
  81. package/dist/esm/v3/chatVersionSkew.d.ts +12 -0
  82. package/dist/esm/v3/chatVersionSkew.js +27 -0
  83. package/dist/esm/v3/chatVersionSkew.js.map +1 -0
  84. package/dist/esm/v3/externalDeploymentId.d.ts +23 -0
  85. package/dist/esm/v3/externalDeploymentId.js +38 -0
  86. package/dist/esm/v3/externalDeploymentId.js.map +1 -0
  87. package/dist/esm/v3/retry.d.ts +4 -0
  88. package/dist/esm/v3/retry.js +14 -8
  89. package/dist/esm/v3/retry.js.map +1 -1
  90. package/dist/esm/v3/sessions.d.ts +15 -2
  91. package/dist/esm/v3/sessions.js +11 -1
  92. package/dist/esm/v3/sessions.js.map +1 -1
  93. package/dist/esm/v3/shared.js +17 -23
  94. package/dist/esm/v3/shared.js.map +1 -1
  95. package/dist/esm/v3/test/index.d.ts +1 -0
  96. package/dist/esm/v3/test/index.js +1 -0
  97. package/dist/esm/v3/test/index.js.map +1 -1
  98. package/dist/esm/v3/test/mock-chat-agent.d.ts +47 -4
  99. package/dist/esm/v3/test/mock-chat-agent.js +118 -12
  100. package/dist/esm/v3/test/mock-chat-agent.js.map +1 -1
  101. package/dist/esm/v3/test/test-session-handle.js +6 -0
  102. package/dist/esm/v3/test/test-session-handle.js.map +1 -1
  103. package/dist/esm/v3/test/transcript-storage-tests.d.ts +40 -0
  104. package/dist/esm/v3/test/transcript-storage-tests.js +255 -0
  105. package/dist/esm/v3/test/transcript-storage-tests.js.map +1 -0
  106. package/dist/esm/v3/transcriptStorage.d.ts +261 -0
  107. package/dist/esm/v3/transcriptStorage.js +360 -0
  108. package/dist/esm/v3/transcriptStorage.js.map +1 -0
  109. package/dist/esm/version.js +1 -1
  110. package/docs/ai-chat/actions.mdx +55 -23
  111. package/docs/ai-chat/anatomy.mdx +47 -27
  112. package/docs/ai-chat/backend.mdx +125 -48
  113. package/docs/ai-chat/background-injection.mdx +122 -19
  114. package/docs/ai-chat/client-protocol.mdx +5 -4
  115. package/docs/ai-chat/compaction.mdx +13 -7
  116. package/docs/ai-chat/custom-agents.mdx +23 -0
  117. package/docs/ai-chat/fast-starts.mdx +27 -20
  118. package/docs/ai-chat/frontend.mdx +19 -14
  119. package/docs/ai-chat/how-it-works.mdx +1 -1
  120. package/docs/ai-chat/lifecycle-hooks.mdx +6 -2
  121. package/docs/ai-chat/migrating-from-a-route-handler.mdx +16 -14
  122. package/docs/ai-chat/migrating-from-hydrate-messages.mdx +299 -0
  123. package/docs/ai-chat/patterns/database-persistence.mdx +24 -9
  124. package/docs/ai-chat/patterns/native-compaction.mdx +310 -0
  125. package/docs/ai-chat/patterns/persistence-and-replay.mdx +34 -23
  126. package/docs/ai-chat/patterns/skills.mdx +7 -10
  127. package/docs/ai-chat/patterns/version-upgrades.mdx +79 -6
  128. package/docs/ai-chat/pending-messages.mdx +3 -3
  129. package/docs/ai-chat/prompt-caching.mdx +23 -25
  130. package/docs/ai-chat/quick-start.mdx +11 -11
  131. package/docs/ai-chat/reference.mdx +69 -10
  132. package/docs/ai-chat/sessions.mdx +6 -1
  133. package/docs/ai-chat/side-channels.mdx +1 -1
  134. package/docs/ai-chat/testing.mdx +2 -1
  135. package/docs/ai-chat/tools.mdx +18 -13
  136. package/docs/ai-chat/transcript-storage.mdx +247 -0
  137. package/docs/ai-chat/upgrade-guide.mdx +2 -2
  138. package/docs/apikeys.mdx +27 -45
  139. package/docs/config/extensions/syncEnvVars.mdx +6 -0
  140. package/docs/deploy-environment-variables.mdx +23 -2
  141. package/docs/deployment/overview.mdx +4 -8
  142. package/docs/deployment/preview-branches.mdx +4 -4
  143. package/docs/deployment/version-skew-protection.mdx +62 -0
  144. package/docs/introduction.mdx +58 -152
  145. package/docs/manual-setup.mdx +7 -7
  146. package/docs/mcp-tools.mdx +9 -0
  147. package/docs/quick-start.mdx +3 -3
  148. package/docs/realtime/auth.mdx +1 -1
  149. package/docs/reports.mdx +157 -0
  150. package/docs/self-hosting/security.mdx +17 -0
  151. package/docs/tasks/scheduled.mdx +24 -0
  152. package/docs/triggering.mdx +1 -1
  153. package/docs/troubleshooting-zod.mdx +158 -0
  154. package/package.json +4 -4
  155. package/skills/trigger-authoring-chat-agent/SKILL.md +41 -29
  156. package/skills/trigger-chat-agent-advanced/SKILL.md +54 -19
@@ -1 +1 @@
1
- {"version":3,"file":"ai-runtime-cjs.cjs","sourceRoot":"","sources":["../../../src/imports/ai-runtime-cjs.cts"],"names":[],"mappings":";AAAA,8EAA8E;AAC9E,iFAAiF;;AAEjF,aAAa;AACb,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzB,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,sBAAsB,GAAG,EAAE,CAAC,sBAAsB,CAAC;AAClE,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,WAAW,GAAG,EAAE,CAAC,WAAW,CAAC;AAC5C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,UAAU,GAAG,EAAE,CAAC,UAAU,CAAC;AAC1C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,WAAW,GAAG,EAAE,CAAC,WAAW,CAAC;AAC5C,aAAa;AACb,MAAM,CA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AAC,WAAW,GAAG,EAAE,CAAC,WAAW,CAAC;AAC5C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,UAAU,GAAG,EAAE,CAAC,UAAU,CAAC;AAC1C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC;AAC9B,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,SAAS,GAAG,EAAE,CAAC,SAAS,CAAC"}
@@ -21,6 +21,8 @@ module.exports.readUIMessageStream = ai.readUIMessageStream;
21
21
  // @ts-ignore
22
22
  module.exports.stepCountIs = ai.stepCountIs;
23
23
  // @ts-ignore
24
+ module.exports.streamText = ai.streamText;
25
+ // @ts-ignore
24
26
  module.exports.tool = ai.tool;
25
27
  // @ts-ignore
26
28
  module.exports.zodSchema = ai.zodSchema;
@@ -139,3 +139,18 @@ export declare function slimSubmitMessageForWire<TMsg extends UIMessage | undefi
139
139
  * long ID degrades to "not filterable by chat" rather than failing to start.
140
140
  */
141
141
  export declare function chatRunTags(chatId: string, userTags?: string[]): string[];
142
+ /**
143
+ * A session body that ends without a turn-complete is only terminal when the
144
+ * server says the session settled — otherwise the turn is still running and
145
+ * the connection was lost (long-poll window closed, proxy restarted). Both
146
+ * transports resubscribe from the last event id, bounded so a permanently
147
+ * empty stream can't spin.
148
+ */
149
+ export declare const MAX_EOF_RESUBSCRIBES = 5;
150
+ /**
151
+ * Backoff before the nth (1-based) EOF resubscribe, jittered so many clients
152
+ * dropped by the same window don't reconnect in lockstep. Resolves early on
153
+ * abort — otherwise a stop landing mid-backoff leaves the stream open for the
154
+ * rest of it.
155
+ */
156
+ export declare function waitBeforeEofResubscribe(attempt: number, signal: AbortSignal): Promise<void>;
@@ -16,10 +16,11 @@
16
16
  * import from `ai.ts`.
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.PENDING_MESSAGE_INJECTED_TYPE = void 0;
19
+ exports.MAX_EOF_RESUBSCRIBES = exports.PENDING_MESSAGE_INJECTED_TYPE = void 0;
20
20
  exports.upsertIncomingMessage = upsertIncomingMessage;
21
21
  exports.slimSubmitMessageForWire = slimSubmitMessageForWire;
22
22
  exports.chatRunTags = chatRunTags;
23
+ exports.waitBeforeEofResubscribe = waitBeforeEofResubscribe;
23
24
  /**
24
25
  * Message-part `type` value for the pending-message data part the agent
25
26
  * injects when a follow-up message arrives mid-turn.
@@ -178,4 +179,37 @@ function chatRunTags(chatId, userTags = []) {
178
179
  const tags = chatTag.length <= MAX_RUN_TAG_LENGTH ? [chatTag, ...userTags] : [...userTags];
179
180
  return tags.slice(0, MAX_RUN_TAGS);
180
181
  }
182
+ /**
183
+ * A session body that ends without a turn-complete is only terminal when the
184
+ * server says the session settled — otherwise the turn is still running and
185
+ * the connection was lost (long-poll window closed, proxy restarted). Both
186
+ * transports resubscribe from the last event id, bounded so a permanently
187
+ * empty stream can't spin.
188
+ */
189
+ exports.MAX_EOF_RESUBSCRIBES = 5;
190
+ /**
191
+ * Backoff before the nth (1-based) EOF resubscribe, jittered so many clients
192
+ * dropped by the same window don't reconnect in lockstep. Resolves early on
193
+ * abort — otherwise a stop landing mid-backoff leaves the stream open for the
194
+ * rest of it.
195
+ */
196
+ function waitBeforeEofResubscribe(attempt, signal) {
197
+ // An already-aborted signal never fires `abort` again, so a listener added
198
+ // here would wait out the whole backoff.
199
+ if (signal.aborted)
200
+ return Promise.resolve();
201
+ return new Promise((resolve) => {
202
+ let timer;
203
+ const done = () => {
204
+ clearTimeout(timer);
205
+ signal.removeEventListener("abort", done);
206
+ resolve();
207
+ };
208
+ const backoff = Math.min(100 * 2 ** (attempt - 1), 5_000);
209
+ timer = setTimeout(done, backoff * (0.5 + Math.random() * 0.5));
210
+ signal.addEventListener("abort", done);
211
+ if (signal.aborted)
212
+ done();
213
+ });
214
+ }
181
215
  //# sourceMappingURL=ai-shared.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ai-shared.js","sourceRoot":"","sources":["../../../src/v3/ai-shared.ts"],"names":[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AG,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QAC1D,KAAK,GAAG,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;QAChE,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACvC,IAAI,MAAM,CAAC,OAAO;YAAE,IAAI,EAAE,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,5 +1,6 @@
1
- import { type AnyTask, type Task, type ChatSnapshotV1, type ApiClientConfiguration, type inferSchemaIn, type inferSchemaOut, type MachinePresetName, type RealtimeDefinedInputStream, type RealtimeDefinedStream, type SessionTriggerConfig, type TaskIdentifier, type TaskOptions, type TaskRunContext, type TaskSchema, type TaskWithSchema, type AnySessionChannel, type SessionChannelName } from "@trigger.dev/core/v3";
2
- import type { FinishReason, LanguageModelUsage, ModelMessage, ProviderMetadata, Tool, ToolSet, UIMessage, UIMessageChunk, UIMessageStreamOptions } from "ai";
1
+ import { type AnyTask, type Task, type ApiClientConfiguration, type inferSchemaIn, type inferSchemaOut, type MachinePresetName, type RealtimeDefinedInputStream, type RealtimeDefinedStream, type TaskIdentifier, type TaskOptions, type TaskRunContext, type TaskSchema, type TaskWithSchema, type AnySessionChannel, type SessionChannelName } from "@trigger.dev/core/v3";
2
+ import type { streamText as aiStreamTextSignature, FinishReason, LanguageModelUsage, ModelMessage, SystemModelMessage, ProviderMetadata, Tool, ToolSet, UIMessage, UIMessageChunk, UIMessageStreamOptions } from "ai";
3
+ import { type TranscriptLoadResult, type TranscriptStorage } from "./transcriptStorage.js";
3
4
  import { type ChatInputChunk, type ChatTaskWirePayload, type InferChatClientData, type InferChatUIMessage, type InferChatUIMessageFromTools, PENDING_MESSAGE_INJECTED_TYPE, upsertIncomingMessage } from "./ai-shared.js";
4
5
  import { locals } from "./locals.js";
5
6
  import type { ResolvedPrompt } from "./prompt.js";
@@ -11,7 +12,8 @@ type ToolCallOptions = {
11
12
  experimental_context?: unknown;
12
13
  context?: unknown;
13
14
  };
14
- import { type SessionChannelHandleFor } from "./sessions.js";
15
+ import { type ChatVersionSkewPolicy } from "./chatVersionSkew.js";
16
+ import { type SessionChannelHandleFor, type SessionTriggerConfigInput } from "./sessions.js";
15
17
  /** Re-export for typing `ctx` in `chat.agent` hooks without importing `@trigger.dev/core`. */
16
18
  export type { TaskRunContext } from "@trigger.dev/core/v3";
17
19
  export type ToolCallExecutionOptions = {
@@ -32,8 +34,8 @@ type ChatTurnContext<TClientData = unknown> = {
32
34
  continuation: boolean;
33
35
  clientData?: TClientData;
34
36
  };
35
- export declare function __setReadChatSnapshotImplForTests(impl: ReadChatSnapshotImpl | undefined): void;
36
- export declare function __setWriteChatSnapshotImplForTests(impl: WriteChatSnapshotImpl | undefined): void;
37
+ export { __readChatSnapshotProductionPathForTests, __setReadChatSnapshotImplForTests, __setWriteChatSnapshotImplForTests, __writeChatSnapshotProductionPathForTests, } from "./chatSnapshotIo.js";
38
+ export { defaultStorage, memoryTranscriptStorage, reduceTranscriptChanges, snapshotTranscriptStorage, type LoadContextEvent, type MemoryTranscriptStorage, type TranscriptChange, type TranscriptChangeReason, type TranscriptChangeset, type TranscriptCursors, type TranscriptLoadOptions, type TranscriptLoadResult, type TranscriptScope, type TranscriptState, type TranscriptStorage, type TranscriptStorageContext, } from "./transcriptStorage.js";
37
39
  type ReplaySessionOutTailImpl = <TUIMessage extends UIMessage>(sessionId: string, options?: {
38
40
  lastEventId?: string;
39
41
  }) => Promise<ReplaySessionOutTailResult<TUIMessage>>;
@@ -147,6 +149,41 @@ export declare const ai: {
147
149
  * ```
148
150
  */
149
151
  declare function createChatAccessToken<TTask extends AnyTask>(taskId: TaskIdentifier<TTask>): Promise<string>;
152
+ /**
153
+ * Register work that must land before anything from this turn reaches the
154
+ * frontend.
155
+ *
156
+ * Like {@link chatDefer} the work starts immediately and is never awaited by
157
+ * the hook that registered it, so it runs alongside the model and costs no
158
+ * time to first token. Unlike `chat.defer`, the output stream waits for it:
159
+ * no chunk of the answer is written to the session until it settles. That
160
+ * makes it the right home for a write the next page load has to see (a
161
+ * conversation row, a message insert), because a reader that can see the
162
+ * answer can also see what the write persisted.
163
+ *
164
+ * Reach for `chat.defer` instead when the timing does not matter for a
165
+ * reload: analytics, audit logs, search-index updates.
166
+ *
167
+ * This is not a consistency barrier for the turn. The work is still in flight
168
+ * while the model runs, so a tool, a `prepareStep`, or anything else executing
169
+ * during the turn can still read the state as it was before the write. It
170
+ * orders the write against what the frontend can see, nothing more. When the
171
+ * turn's own code has to read the write back, `await` it instead and accept
172
+ * the cost.
173
+ *
174
+ * A write registered here that fails, or outlasts the internal timeout, lets
175
+ * the stream through rather than stalling the conversation.
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * onTurnStart: async ({ chatId, uiMessages }) => {
180
+ * chat.deferBeforeOutput(
181
+ * db.chat.update({ where: { id: chatId }, data: { messages: uiMessages } })
182
+ * );
183
+ * },
184
+ * ```
185
+ */
186
+ declare function chatDeferBeforeOutput(promiseOrFn: Promise<unknown> | (() => Promise<unknown>)): void;
150
187
  /**
151
188
  * A stream writer passed to chat lifecycle callbacks (`onPreload`, `onChatStart`,
152
189
  * `onTurnStart`, `onTurnComplete`, `onCompacted`).
@@ -201,7 +238,7 @@ export type ChatTaskPayload<TClientData = unknown> = {
201
238
  * to short-circuit the LLM call when an action doesn't need a response.
202
239
  * - `"close"`: The chat session is being closed (internal; `run()` is not called).
203
240
  */
204
- trigger: "submit-message" | "regenerate-message" | "preload" | "action" | "close";
241
+ trigger: "submit-message" | "regenerate-message" | "preload" | "action" | "action-turn" | "close";
205
242
  /** The ID of the message to regenerate (only for `"regenerate-message"`) */
206
243
  messageId?: string;
207
244
  /** Custom data from the frontend (passed via `metadata` on `sendMessage()` or the transport). */
@@ -242,6 +279,16 @@ export type ChatTaskRunPayload<TClientData = unknown, TTools extends ToolSet = T
242
279
  * Use for tags, metadata, parent run links, or any API that needs the full run record.
243
280
  */
244
281
  ctx: TaskRunContext;
282
+ /**
283
+ * `streamText` with this agent's managed options already applied: the
284
+ * prompt from `chat.prompt.set()`, the skill tools, telemetry, and the
285
+ * `prepareStep` that delivers steering, compaction and injected context.
286
+ *
287
+ * Prefer it over importing `streamText` from `ai`. The imported one takes
288
+ * none of that unless you spread `chat.toStreamTextOptions()` yourself, and
289
+ * forgetting the spread fails silently.
290
+ */
291
+ streamText: AiStreamTextFn;
245
292
  /** Token usage from the previous turn. Undefined on turn 0. */
246
293
  previousTurnUsage?: LanguageModelUsage;
247
294
  /** Cumulative token usage across all completed turns so far. */
@@ -838,6 +885,12 @@ export declare function buildSkillTools(skills: ResolvedSkill[]): Record<string,
838
885
  * Options for {@link toStreamTextOptions}.
839
886
  */
840
887
  export type ToStreamTextOptionsOptions = {
888
+ /**
889
+ * A base system prompt, used when `chat.prompt.set()` has not supplied one.
890
+ * `chat.agent({ system })` and a `system` passed to the managed `streamText`
891
+ * both arrive here.
892
+ */
893
+ system?: string | SystemModelMessage;
841
894
  /** Additional telemetry metadata merged into `experimental_telemetry.metadata`. */
842
895
  telemetry?: Record<string, string>;
843
896
  /**
@@ -908,6 +961,23 @@ export type SystemCacheControl = {
908
961
  *
909
962
  * If no prompt has been set, returns `{}` (no-op spread).
910
963
  */
964
+ /**
965
+ * The AI SDK's own `streamText` signature, borrowed rather than restated.
966
+ *
967
+ * The peer range spans `ai` v5, v6 and v7, whose `streamText` options differ.
968
+ * Describing the shape here would drift against all three; `typeof` resolves to
969
+ * whichever version the user installed, so generics, overloads and tool
970
+ * inference are exactly theirs.
971
+ */
972
+ type AiStreamTextFn = typeof aiStreamTextSignature;
973
+ /**
974
+ * The `streamText` handed to a `chat.agent` `run()`, carrying the agent's
975
+ * managed options.
976
+ *
977
+ * Exported so a loop factored out of `run` can take it as a parameter and keep
978
+ * them: `function loop(messages: ModelMessage[], streamText: ChatStreamText)`.
979
+ */
980
+ export type ChatStreamText = AiStreamTextFn;
911
981
  declare function toStreamTextOptions(options?: ToStreamTextOptionsOptions): Record<string, unknown>;
912
982
  /**
913
983
  * Options for `pipeChat`.
@@ -953,6 +1023,37 @@ export type ChatUIMessageStreamOptions<TUIM extends UIMessage = UIMessage> = Omi
953
1023
  type UIMessageStreamable = {
954
1024
  toUIMessageStream: (...args: any[]) => AsyncIterable<unknown> | ReadableStream<unknown>;
955
1025
  };
1026
+ declare const actionTurnBrand: unique symbol;
1027
+ /**
1028
+ * The marker `onAction` returns to have a turn run on the history it just
1029
+ * edited. Produce it with {@link chat.turn}.
1030
+ */
1031
+ export type ActionTurn = {
1032
+ readonly [actionTurnBrand]: true;
1033
+ };
1034
+ /**
1035
+ * Turn the current action into a turn.
1036
+ *
1037
+ * Return it from `onAction` after editing history. The action's own work is
1038
+ * finished first (the edit is applied and snapshotted), then a turn runs on the
1039
+ * result exactly as a message turn does: `onTurnStart`, `run()` with the edited
1040
+ * history, `onBeforeTurnComplete`, `onTurnComplete`, and the turn counter
1041
+ * advances. That gives the answer everything a turn has, the system prompt,
1042
+ * tools, steering, compaction, injected instructions and persistence, with no
1043
+ * action-specific handling.
1044
+ *
1045
+ * @example
1046
+ * ```ts
1047
+ * onAction: async ({ action }) => {
1048
+ * if (action.type === "regenerate") {
1049
+ * chat.history.slice(0, -1);
1050
+ * return chat.turn();
1051
+ * }
1052
+ * if (action.type === "undo") chat.history.slice(0, -2); // no turn
1053
+ * },
1054
+ * ```
1055
+ */
1056
+ declare function chatTurn(): ActionTurn;
956
1057
  /**
957
1058
  * Pipes a chat stream to the realtime stream, making it available to the
958
1059
  * `TriggerChatTransport` on the frontend.
@@ -1097,8 +1198,9 @@ export type RecoveryPendingToolCall = {
1097
1198
  * `chat.endRun()` with no buffered user messages, fresh chat, OOM retry
1098
1199
  * after a successful turn-complete with no in-flight tail).
1099
1200
  *
1100
- * Does NOT fire when `hydrateMessages` is registered (the customer owns
1101
- * persistence; recovery decisions live in their own DB query).
1201
+ * Fires regardless of who owns the model's context. With `hydrateMessages`
1202
+ * or a storage `loadContext`, the recovered tail reaches that hook in
1203
+ * `previousMessages` on the next turn.
1102
1204
  */
1103
1205
  export type RecoveryBootEvent<TUIM extends UIMessage = UIMessage> = {
1104
1206
  /** Task run context — same as `task({ run })` second-argument `ctx`. */
@@ -1167,8 +1269,9 @@ export type RecoveryBootResult<TUIM extends UIMessage = UIMessage> = {
1167
1269
  * context, mutate its tool parts to inject synthesized results,
1168
1270
  * collapse history, etc.
1169
1271
  *
1170
- * Ignored when `hydrateMessages` is registered (the hydrate hook
1171
- * runs per-turn and overwrites the chain).
1272
+ * With `hydrateMessages` or a storage `loadContext`, this chain is what
1273
+ * the hook receives as `previousMessages` on the next turn; the hook's
1274
+ * return value is the chain the model sees.
1172
1275
  */
1173
1276
  chain?: TUIM[];
1174
1277
  /**
@@ -1545,6 +1648,17 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1545
1648
  * ```
1546
1649
  */
1547
1650
  oomMachine?: MachinePresetName;
1651
+ /**
1652
+ * What to do when the session's `externalDeploymentId` no longer names the deployment
1653
+ * this run is on — after a redeploy re-pins the session, say.
1654
+ *
1655
+ * - `"follow"` (default) hands the conversation to the pinned deployment at the next
1656
+ * turn boundary, so no `chat.requestUpgrade()` of your own is needed.
1657
+ * - `"hold"` stays put until you ask to move. Manual `chat.requestUpgrade()` works either way.
1658
+ *
1659
+ * Ignored for sessions with no pin, and for sessions using `lockToVersion`.
1660
+ */
1661
+ versionSkew?: ChatVersionSkewPolicy;
1548
1662
  /**
1549
1663
  * Schema for validating `clientData` from the frontend.
1550
1664
  * Accepts Zod, ArkType, Valibot, or any supported schema library.
@@ -1599,13 +1713,14 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1599
1713
  * `onBeforeTurnComplete` / `onTurnComplete`, no `run()`. Use
1600
1714
  * `chat.history.*` inside `onAction` to mutate state.
1601
1715
  *
1602
- * To produce a model response from an action, return a
1603
- * `StreamTextResult` (auto-piped), `string`, or `UIMessage`. Returning
1604
- * `void` or nothing is the side-effect-only default.
1716
+ * To answer after the edit, return `chat.turn()`: the edit is applied and
1717
+ * snapshotted, then a turn runs on the result with every turn guarantee. An
1718
+ * action that returns nothing is a state edit only. Returning anything else
1719
+ * is an error; a response can no longer be returned directly.
1605
1720
  */
1606
1721
  onAction?: (event: ActionEvent<[
1607
1722
  TActionSchema
1608
- ] extends [TaskSchema] ? inferSchemaOut<TActionSchema> : unknown, inferSchemaOut<TClientDataSchema>, TUIMessage>) => Promise<unknown> | unknown;
1723
+ ] extends [TaskSchema] ? inferSchemaOut<TActionSchema> : unknown, inferSchemaOut<TClientDataSchema>, TUIMessage>) => Promise<void | ActionTurn> | void | ActionTurn;
1609
1724
  /**
1610
1725
  * The tools available to this agent.
1611
1726
  *
@@ -1691,9 +1806,9 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1691
1806
  * continuation after `chat.endRun()` with no buffered user, a fresh
1692
1807
  * chat, or an OOM retry on top of a complete snapshot.
1693
1808
  *
1694
- * Does NOT fire when `hydrateMessages` is registered that hook owns
1695
- * the per-turn chain and overlapping recovery decisions belong in the
1696
- * customer's DB.
1809
+ * Fires regardless of who owns the model's context; a `hydrateMessages`
1810
+ * hook or a storage `loadContext` receives the recovered tail in
1811
+ * `previousMessages` on the next turn.
1697
1812
  *
1698
1813
  * Defaults (returned when the hook is omitted or returns no field):
1699
1814
  * - With two or more in-flight users, the partial and the user it
@@ -1823,6 +1938,32 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1823
1938
  * ```
1824
1939
  */
1825
1940
  hydrateMessages?: (event: HydrateMessagesEvent<inferSchemaOut<TClientDataSchema>, TUIMessage>) => TUIMessage[] | Promise<TUIMessage[]>;
1941
+ /**
1942
+ * Where the conversation is persisted. The runtime calls `save` after
1943
+ * every turn, failed turn and history-changing action with the changes
1944
+ * since the last save, and `load` once when a new run boots to continue
1945
+ * the conversation.
1946
+ *
1947
+ * Defaults to `defaultStorage`, the platform's snapshot in object storage
1948
+ * that the Sessions dashboard renders. Bring your own to write each change
1949
+ * to your database; `memoryTranscriptStorage()` is the reference
1950
+ * implementation and `runTranscriptStorageTests` from
1951
+ * `@trigger.dev/sdk/ai/test` checks yours against the contract.
1952
+ *
1953
+ * A storage with `loadContext` also owns the model's context on every
1954
+ * turn, which is what `hydrateMessages` did. The two cannot be combined.
1955
+ *
1956
+ * @example
1957
+ * ```ts
1958
+ * chat.agent({
1959
+ * id: "my-chat",
1960
+ * storage: myPostgresTranscriptStorage,
1961
+ * run: async ({ messages, signal, streamText }) =>
1962
+ * streamText({ model, messages, abortSignal: signal }),
1963
+ * });
1964
+ * ```
1965
+ */
1966
+ storage?: TranscriptStorage<inferSchemaOut<TClientDataSchema>>;
1826
1967
  /**
1827
1968
  * Called at the start of every turn, after message accumulation and `onChatStart` (turn 0),
1828
1969
  * but before the `run` function executes.
@@ -1897,6 +2038,31 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1897
2038
  * });
1898
2039
  * ```
1899
2040
  */
2041
+ /**
2042
+ * A provider registry, so the runtime can resolve the managed prompt's model
2043
+ * for the `streamText` it hands to `run()`. Only needed when you set a model
2044
+ * through `chat.prompt.set()` and want the bound `streamText` to honour it.
2045
+ */
2046
+ registry?: ToStreamTextOptionsOptions["registry"];
2047
+ /**
2048
+ * The agent's system prompt. Injected instructions append to it, and the
2049
+ * `streamText` handed to `run()` carries it without a spread.
2050
+ *
2051
+ * Set it here, at the call site, or through `chat.prompt.set()` for versioned
2052
+ * config, but only in one of them.
2053
+ */
2054
+ system?: ToStreamTextOptionsOptions["system"];
2055
+ /**
2056
+ * Mark the system prompt for provider-side caching, the same sugar
2057
+ * `chat.toStreamTextOptions({ cacheControl })` takes. See
2058
+ * [prompt caching](/ai-chat/prompt-caching).
2059
+ */
2060
+ cacheControl?: ToStreamTextOptionsOptions["cacheControl"];
2061
+ /**
2062
+ * Provider options for the system block, when `cacheControl` is not enough.
2063
+ * Takes precedence over `cacheControl`.
2064
+ */
2065
+ systemProviderOptions?: ToStreamTextOptionsOptions["systemProviderOptions"];
1900
2066
  compaction?: ChatAgentCompactionOptions<TUIMessage>;
1901
2067
  /**
1902
2068
  * Configure how messages that arrive during streaming are handled.
@@ -2390,15 +2556,22 @@ declare function setUIMessageStreamOptions(options: ChatUIMessageStreamOptions<U
2390
2556
  */
2391
2557
  declare function isStopped(): boolean;
2392
2558
  /**
2393
- * Request that the current run exits so the next message starts on the latest
2394
- * deployed version (via the standard continuation mechanism).
2559
+ * Hand the conversation over to another deployment.
2560
+ *
2561
+ * The handover happens immediately and server-side: a successor run is created
2562
+ * and picks the conversation up from `session.in`. The transport keeps reading
2563
+ * the same session output, so no client action is needed and nothing waits for
2564
+ * the next message.
2565
+ *
2566
+ * Without a target the session's pin is cleared, so the successor lands on the
2567
+ * latest deployed version; with `externalDeploymentId` the session is re-pinned
2568
+ * to that deployment.
2395
2569
  *
2396
2570
  * When called from `onTurnStart` or `onValidateMessages`, `run()` is skipped
2397
- * entirely the run exits immediately and the transport re-triggers the
2398
- * same message on the new version.
2571
+ * entirely and the successor answers the message that opened the turn.
2399
2572
  *
2400
2573
  * When called from `run()` or `chat.defer()`, the current turn completes
2401
- * normally and the run exits afterward instead of waiting for the next message.
2574
+ * normally and the handover happens afterward.
2402
2575
  *
2403
2576
  * Call from `onTurnStart`, `onValidateMessages`, `onChatResume`, `run()`,
2404
2577
  * or inside `chat.defer()`.
@@ -2418,7 +2591,9 @@ declare function isStopped(): boolean;
2418
2591
  * });
2419
2592
  * ```
2420
2593
  */
2421
- declare function requestUpgrade(): void;
2594
+ declare function requestUpgrade(options?: {
2595
+ externalDeploymentId?: string;
2596
+ }): void;
2422
2597
  /**
2423
2598
  * Hand off the current custom agent Session to a fresh run.
2424
2599
  *
@@ -2477,6 +2652,50 @@ declare function endAndContinue(): Promise<void>;
2477
2652
  * ```
2478
2653
  */
2479
2654
  declare function endRun(): void;
2655
+ /**
2656
+ * End the whole conversation, permanently. The session row is closed, further
2657
+ * appends are refused, and the run exits without scheduling a continuation.
2658
+ *
2659
+ * This is the session-level stop. {@link endRun} ends the current run and lets
2660
+ * the next message start a fresh one; `chat.close()` ends the session itself,
2661
+ * so there is no next message. Use it for a budget cap, a completed goal,
2662
+ * abuse detection, or a user signing out.
2663
+ *
2664
+ * In a `chat.agent`, call it from `run()`, `prepareStep`, or
2665
+ * `onBeforeTurnComplete`. Called mid-step, it aborts the in-flight
2666
+ * `streamText` the same way the stop signal does, so the partial response is
2667
+ * still captured and streamed. The turn then completes normally, a terminal
2668
+ * `session-closed` record carrying `reason` is written to the response stream,
2669
+ * and the loop exits.
2670
+ *
2671
+ * Prefer `onBeforeTurnComplete` over `onTurnComplete`. It carries the same
2672
+ * fields but still runs while the stream is open, so the closed state rides
2673
+ * out on the turn's final record. `onTurnComplete` runs after that record, so
2674
+ * a close decided there does not reach a reader that has already finished the
2675
+ * turn, and the user only finds out when their next message is refused.
2676
+ *
2677
+ * In a `chat.customAgent`, call it anywhere in your own loop. The close is
2678
+ * performed when `run()` returns, so it lands whether you break out of a
2679
+ * `chat.createSession` loop, return early, or hand-roll the loop entirely.
2680
+ *
2681
+ * Closing is one-way: a closed session cannot be reopened. Its transcript
2682
+ * stays readable.
2683
+ *
2684
+ * @example
2685
+ * ```ts
2686
+ * chat.agent({
2687
+ * id: "budgeted-agent",
2688
+ * onBeforeTurnComplete: async ({ usage }) => {
2689
+ * if (await overBudget(usage)) {
2690
+ * chat.close({ reason: "Monthly budget reached" });
2691
+ * }
2692
+ * },
2693
+ * });
2694
+ * ```
2695
+ */
2696
+ declare function close(options?: {
2697
+ reason?: string;
2698
+ }): void;
2480
2699
  /**
2481
2700
  * Register a promise that runs in the background during the current turn.
2482
2701
  *
@@ -2746,6 +2965,20 @@ declare class ChatMessageAccumulator {
2746
2965
  * Queue a message for injection, converting to model messages automatically.
2747
2966
  */
2748
2967
  steerAsync(message: UIMessage): Promise<void>;
2968
+ /**
2969
+ * Record the messages a steering drain consumed.
2970
+ *
2971
+ * The drain only puts them in this step's prompt, so without this they
2972
+ * shape one answer and then exist in neither lane: not in `uiMessages`,
2973
+ * which is what an app persists from, and not in `modelMessages`, which is
2974
+ * what every later turn sends.
2975
+ *
2976
+ * Both lanes are appended to. The model lane is never reconverted from the
2977
+ * UI lane, because `compactIfNeeded` replaces it with a summary and leaves
2978
+ * the UI lane whole: a reconversion would restore everything the summary
2979
+ * replaced.
2980
+ */
2981
+ absorbSteering(claimed: UIMessage[], injected?: ModelMessage[]): Promise<void>;
2749
2982
  /**
2750
2983
  * Get and clear unconsumed steering messages.
2751
2984
  */
@@ -2783,6 +3016,11 @@ export type ChatSessionOptions = {
2783
3016
  timeout?: string;
2784
3017
  /** Max turns before ending. @default 100 */
2785
3018
  maxTurns?: number;
3019
+ /**
3020
+ * What to do when the session's `externalDeploymentId` no longer names this deployment.
3021
+ * `"follow"` (default) hands over at the next turn boundary; `"hold"` stays put.
3022
+ */
3023
+ versionSkew?: ChatVersionSkewPolicy;
2786
3024
  /** Automatic context compaction — same options as `chat.agent({ compaction })`. */
2787
3025
  compaction?: ChatAgentCompactionOptions;
2788
3026
  /** Configure mid-execution message injection — same options as `chat.agent({ pendingMessages })`. */
@@ -2994,7 +3232,7 @@ export type CreateChatStartSessionActionOptions = {
2994
3232
  * Default trigger config used when starting a new session for a chat.
2995
3233
  * Per-call `params.triggerConfig` shallow-merges on top.
2996
3234
  */
2997
- triggerConfig?: Partial<SessionTriggerConfig>;
3235
+ triggerConfig?: Partial<SessionTriggerConfigInput>;
2998
3236
  /**
2999
3237
  * Override the Trigger.dev API base URL. String applies to both
3000
3238
  * `/api/v1/sessions` and `/api/v1/auth/jwt/claims`; function picks per
@@ -3037,7 +3275,7 @@ export type ChatStartSessionParams<TChat extends AnyTask = AnyTask> = {
3037
3275
  * `chat.agent`: anything beyond `chatId`/`messages`/`trigger`/`metadata`,
3038
3276
  * which the runtime injects automatically).
3039
3277
  */
3040
- triggerConfig?: Partial<SessionTriggerConfig>;
3278
+ triggerConfig?: Partial<SessionTriggerConfigInput>;
3041
3279
  /**
3042
3280
  * Opaque session-level metadata stored on the Session row. Separate from
3043
3281
  * the per-turn `clientData` above. Use this when you want to attach
@@ -3059,6 +3297,11 @@ export type ChatStartSessionResult = {
3059
3297
  runId: string;
3060
3298
  /** Session friendlyId — informational. */
3061
3299
  sessionId: string;
3300
+ /**
3301
+ * The session's run is parked waiting for its deployment. Messages sent meanwhile are durable
3302
+ * and delivered once it lands; surface this so the wait reads as a deploy in progress.
3303
+ */
3304
+ pendingVersion?: boolean;
3062
3305
  };
3063
3306
  /**
3064
3307
  * Creates a server-side helper that starts (or resumes) a Session for a
@@ -3095,6 +3338,42 @@ export type ChatStartSessionResult = {
3095
3338
  * ```
3096
3339
  */
3097
3340
  declare function createChatStartSessionAction<TChat extends AnyTask = AnyTask>(taskId: string, options?: CreateChatStartSessionActionOptions): (params: ChatStartSessionParams<TChat>) => Promise<ChatStartSessionResult>;
3341
+ export type CreateChatLoadTranscriptActionOptions = {
3342
+ /**
3343
+ * Scope the action to a specific API client configuration (secret key,
3344
+ * base URL) instead of the process-wide one. The default storage reads
3345
+ * through this client.
3346
+ */
3347
+ apiClient?: ApiClientConfiguration;
3348
+ /** Page size when the caller passes none. */
3349
+ limit?: number;
3350
+ };
3351
+ export type ChatLoadTranscriptParams<TClientData = unknown> = {
3352
+ chatId: string;
3353
+ clientData?: TClientData;
3354
+ limit?: number;
3355
+ before?: string;
3356
+ };
3357
+ /**
3358
+ * Creates a server-side helper that reads a conversation from a transcript
3359
+ * storage, for rendering history before the chat connects. Works the same
3360
+ * for every storage, the platform default included, so the browser never
3361
+ * reads a store directly and the secret key stays on the server.
3362
+ *
3363
+ * Wrap it in a Next.js server action (or any server-side handler), scope it
3364
+ * to the authenticated user through `clientData`, and pass the result to
3365
+ * `useLoadTranscript` in the browser.
3366
+ *
3367
+ * @example
3368
+ * ```ts
3369
+ * // actions.ts
3370
+ * "use server";
3371
+ * import { chat, defaultStorage } from "@trigger.dev/sdk/ai";
3372
+ *
3373
+ * export const loadTranscript = chat.createLoadTranscriptAction(defaultStorage, { limit: 50 });
3374
+ * ```
3375
+ */
3376
+ declare function createChatLoadTranscriptAction<TClientData = unknown>(storage: TranscriptStorage<TClientData>, options?: CreateChatLoadTranscriptActionOptions): (params: ChatLoadTranscriptParams<TClientData>) => Promise<TranscriptLoadResult>;
3098
3377
  export declare const chat: {
3099
3378
  /** Create a chat agent. See {@link chatAgent}. */
3100
3379
  agent: typeof chatAgent;
@@ -3106,8 +3385,12 @@ export declare const chat: {
3106
3385
  withClientData: typeof withClientData;
3107
3386
  /** Create a server-side helper for starting (or resuming) a Session for a chatId. See {@link createChatStartSessionAction}. */
3108
3387
  createStartSessionAction: typeof createChatStartSessionAction;
3388
+ /** Returns a server-side helper that reads a conversation from a transcript storage. */
3389
+ createLoadTranscriptAction: typeof createChatLoadTranscriptAction;
3109
3390
  /** Pipe a stream to the chat transport. See {@link pipeChat}. */
3110
3391
  pipe: typeof pipeChat;
3392
+ /** Return from `onAction` to run a turn on the edited history. See {@link chatTurn}. */
3393
+ turn: typeof chatTurn;
3111
3394
  /** Create a per-run typed local. See {@link chatLocal}. */
3112
3395
  local: typeof chatLocal;
3113
3396
  /** Create a public access token for a chat task. See {@link createChatAccessToken}. */
@@ -3128,10 +3411,13 @@ export declare const chat: {
3128
3411
  endAndContinue: typeof endAndContinue;
3129
3412
  /** Exit the run after the current turn completes, without any upgrade signal. See {@link endRun}. */
3130
3413
  endRun: typeof endRun;
3414
+ /** End the conversation permanently: close the session and exit the run. See {@link close}. */
3415
+ close: typeof close;
3131
3416
  /** Clean up aborted parts from a UIMessage. See {@link cleanupAbortedParts}. */
3132
3417
  cleanupAbortedParts: typeof cleanupAbortedParts;
3133
3418
  /** Register background work that runs in parallel with streaming. See {@link chatDefer}. */
3134
3419
  defer: typeof chatDefer;
3420
+ deferBeforeOutput: typeof chatDeferBeforeOutput;
3135
3421
  /** Queue model messages for injection at the next `prepareStep` boundary. See {@link injectBackgroundContext}. */
3136
3422
  inject: typeof injectBackgroundContext;
3137
3423
  /** Typed chat output stream for writing custom chunks or piping from subtasks. */