@trigger.dev/sdk 0.0.0-prerelease-streamfix-20260909094302 → 0.0.0-prerelease-20260909121655

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 (142) 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 +275 -25
  7. package/dist/commonjs/v3/ai.js +1336 -340
  8. package/dist/commonjs/v3/ai.js.map +1 -1
  9. package/dist/commonjs/v3/chat-client.d.ts +11 -2
  10. package/dist/commonjs/v3/chat-client.js +227 -111
  11. package/dist/commonjs/v3/chat-client.js.map +1 -1
  12. package/dist/commonjs/v3/chat-react.d.ts +88 -0
  13. package/dist/commonjs/v3/chat-react.js +130 -1
  14. package/dist/commonjs/v3/chat-react.js.map +1 -1
  15. package/dist/commonjs/v3/chat-server.d.ts +42 -6
  16. package/dist/commonjs/v3/chat-server.js +52 -7
  17. package/dist/commonjs/v3/chat-server.js.map +1 -1
  18. package/dist/commonjs/v3/chat.d.ts +92 -10
  19. package/dist/commonjs/v3/chat.js +328 -73
  20. package/dist/commonjs/v3/chat.js.map +1 -1
  21. package/dist/commonjs/v3/chatSnapshotIo.d.ts +2 -0
  22. package/dist/commonjs/v3/chatSnapshotIo.js +174 -0
  23. package/dist/commonjs/v3/chatSnapshotIo.js.map +1 -0
  24. package/dist/commonjs/v3/chatVersionSkew.d.ts +12 -0
  25. package/dist/commonjs/v3/chatVersionSkew.js +30 -0
  26. package/dist/commonjs/v3/chatVersionSkew.js.map +1 -0
  27. package/dist/commonjs/v3/externalDeploymentId.d.ts +23 -0
  28. package/dist/commonjs/v3/externalDeploymentId.js +43 -0
  29. package/dist/commonjs/v3/externalDeploymentId.js.map +1 -0
  30. package/dist/commonjs/v3/sessions.d.ts +15 -2
  31. package/dist/commonjs/v3/sessions.js +12 -1
  32. package/dist/commonjs/v3/sessions.js.map +1 -1
  33. package/dist/commonjs/v3/shared.js +30 -36
  34. package/dist/commonjs/v3/shared.js.map +1 -1
  35. package/dist/commonjs/v3/test/index.d.ts +1 -0
  36. package/dist/commonjs/v3/test/index.js +3 -1
  37. package/dist/commonjs/v3/test/index.js.map +1 -1
  38. package/dist/commonjs/v3/test/mock-chat-agent.d.ts +47 -4
  39. package/dist/commonjs/v3/test/mock-chat-agent.js +116 -10
  40. package/dist/commonjs/v3/test/mock-chat-agent.js.map +1 -1
  41. package/dist/commonjs/v3/test/test-session-handle.js +6 -0
  42. package/dist/commonjs/v3/test/test-session-handle.js.map +1 -1
  43. package/dist/commonjs/v3/test/transcript-storage-tests.d.ts +40 -0
  44. package/dist/commonjs/v3/test/transcript-storage-tests.js +258 -0
  45. package/dist/commonjs/v3/test/transcript-storage-tests.js.map +1 -0
  46. package/dist/commonjs/v3/transcriptStorage.d.ts +224 -0
  47. package/dist/commonjs/v3/transcriptStorage.js +291 -0
  48. package/dist/commonjs/v3/transcriptStorage.js.map +1 -0
  49. package/dist/commonjs/version.js +1 -1
  50. package/dist/esm/imports/ai-runtime.d.ts +2 -2
  51. package/dist/esm/imports/ai-runtime.js +2 -2
  52. package/dist/esm/imports/ai-runtime.js.map +1 -1
  53. package/dist/esm/v3/ai-shared.d.ts +15 -0
  54. package/dist/esm/v3/ai-shared.js +33 -0
  55. package/dist/esm/v3/ai-shared.js.map +1 -1
  56. package/dist/esm/v3/ai.d.ts +275 -25
  57. package/dist/esm/v3/ai.js +1328 -337
  58. package/dist/esm/v3/ai.js.map +1 -1
  59. package/dist/esm/v3/chat-client.d.ts +11 -2
  60. package/dist/esm/v3/chat-client.js +228 -112
  61. package/dist/esm/v3/chat-client.js.map +1 -1
  62. package/dist/esm/v3/chat-react.d.ts +88 -0
  63. package/dist/esm/v3/chat-react.js +127 -1
  64. package/dist/esm/v3/chat-react.js.map +1 -1
  65. package/dist/esm/v3/chat-server.d.ts +42 -6
  66. package/dist/esm/v3/chat-server.js +53 -8
  67. package/dist/esm/v3/chat-server.js.map +1 -1
  68. package/dist/esm/v3/chat.d.ts +92 -10
  69. package/dist/esm/v3/chat.js +329 -74
  70. package/dist/esm/v3/chat.js.map +1 -1
  71. package/dist/esm/v3/chatSnapshotIo.d.ts +2 -0
  72. package/dist/esm/v3/chatSnapshotIo.js +166 -0
  73. package/dist/esm/v3/chatSnapshotIo.js.map +1 -0
  74. package/dist/esm/v3/chatVersionSkew.d.ts +12 -0
  75. package/dist/esm/v3/chatVersionSkew.js +27 -0
  76. package/dist/esm/v3/chatVersionSkew.js.map +1 -0
  77. package/dist/esm/v3/externalDeploymentId.d.ts +23 -0
  78. package/dist/esm/v3/externalDeploymentId.js +38 -0
  79. package/dist/esm/v3/externalDeploymentId.js.map +1 -0
  80. package/dist/esm/v3/sessions.d.ts +15 -2
  81. package/dist/esm/v3/sessions.js +11 -1
  82. package/dist/esm/v3/sessions.js.map +1 -1
  83. package/dist/esm/v3/shared.js +17 -23
  84. package/dist/esm/v3/shared.js.map +1 -1
  85. package/dist/esm/v3/test/index.d.ts +1 -0
  86. package/dist/esm/v3/test/index.js +1 -0
  87. package/dist/esm/v3/test/index.js.map +1 -1
  88. package/dist/esm/v3/test/mock-chat-agent.d.ts +47 -4
  89. package/dist/esm/v3/test/mock-chat-agent.js +118 -12
  90. package/dist/esm/v3/test/mock-chat-agent.js.map +1 -1
  91. package/dist/esm/v3/test/test-session-handle.js +6 -0
  92. package/dist/esm/v3/test/test-session-handle.js.map +1 -1
  93. package/dist/esm/v3/test/transcript-storage-tests.d.ts +40 -0
  94. package/dist/esm/v3/test/transcript-storage-tests.js +255 -0
  95. package/dist/esm/v3/test/transcript-storage-tests.js.map +1 -0
  96. package/dist/esm/v3/transcriptStorage.d.ts +224 -0
  97. package/dist/esm/v3/transcriptStorage.js +280 -0
  98. package/dist/esm/v3/transcriptStorage.js.map +1 -0
  99. package/dist/esm/version.js +1 -1
  100. package/docs/ai-chat/actions.mdx +55 -23
  101. package/docs/ai-chat/anatomy.mdx +3 -3
  102. package/docs/ai-chat/backend.mdx +125 -48
  103. package/docs/ai-chat/background-injection.mdx +69 -19
  104. package/docs/ai-chat/client-protocol.mdx +5 -4
  105. package/docs/ai-chat/compaction.mdx +13 -7
  106. package/docs/ai-chat/custom-agents.mdx +23 -0
  107. package/docs/ai-chat/fast-starts.mdx +27 -20
  108. package/docs/ai-chat/frontend.mdx +19 -14
  109. package/docs/ai-chat/lifecycle-hooks.mdx +6 -2
  110. package/docs/ai-chat/migrating-from-a-route-handler.mdx +16 -14
  111. package/docs/ai-chat/patterns/database-persistence.mdx +6 -2
  112. package/docs/ai-chat/patterns/native-compaction.mdx +310 -0
  113. package/docs/ai-chat/patterns/persistence-and-replay.mdx +34 -23
  114. package/docs/ai-chat/patterns/skills.mdx +7 -10
  115. package/docs/ai-chat/patterns/version-upgrades.mdx +79 -6
  116. package/docs/ai-chat/pending-messages.mdx +3 -3
  117. package/docs/ai-chat/prompt-caching.mdx +23 -25
  118. package/docs/ai-chat/quick-start.mdx +11 -11
  119. package/docs/ai-chat/reference.mdx +67 -9
  120. package/docs/ai-chat/sessions.mdx +6 -1
  121. package/docs/ai-chat/testing.mdx +2 -1
  122. package/docs/ai-chat/tools.mdx +18 -13
  123. package/docs/ai-chat/transcript-storage.mdx +233 -0
  124. package/docs/ai-chat/upgrade-guide.mdx +2 -2
  125. package/docs/apikeys.mdx +27 -45
  126. package/docs/config/extensions/syncEnvVars.mdx +6 -0
  127. package/docs/deploy-environment-variables.mdx +23 -2
  128. package/docs/deployment/overview.mdx +4 -8
  129. package/docs/deployment/preview-branches.mdx +4 -4
  130. package/docs/deployment/version-skew-protection.mdx +62 -0
  131. package/docs/manual-setup.mdx +7 -7
  132. package/docs/mcp-tools.mdx +9 -0
  133. package/docs/quick-start.mdx +3 -3
  134. package/docs/realtime/auth.mdx +1 -1
  135. package/docs/reports.mdx +157 -0
  136. package/docs/self-hosting/security.mdx +5 -0
  137. package/docs/tasks/scheduled.mdx +24 -0
  138. package/docs/triggering.mdx +1 -1
  139. package/docs/troubleshooting-zod.mdx +158 -0
  140. package/package.json +4 -4
  141. package/skills/trigger-authoring-chat-agent/SKILL.md +41 -29
  142. package/skills/trigger-chat-agent-advanced/SKILL.md +31 -12
@@ -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,CAAC,OAAO,CAAC,YAAY,GAAG,EAAE,CAAC,YAAY,CAAC;AAC9C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,UAAU,GAAG,EAAE,CAAC,UAAU,CAAC;AAC1C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,mBAAmB,GAAG,EAAE,CAAC,mBAAmB,CAAC;AAC5D,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,WAAW,GAAG,EAAE,CAAC,WAAW,CAAC;AAC5C,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"}
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,CAAC,OAAO,CAAC,YAAY,GAAG,EAAE,CAAC,YAAY,CAAC;AAC9C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,UAAU,GAAG,EAAE,CAAC,UAAU,CAAC;AAC1C,aAAa;AACb,MAAM,CAAC,OAAO,CAAC,mBAAmB,GAAG,EAAE,CAAC,mBAAmB,CAAC;AAC5D,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,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":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;;;AAKH;;;GAGG;AACU,QAAA,6BAA6B,GAAG,+BAAwC,CAAC;AA0DtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,+BACE,MAAc,EACd,KAGC;IAED,IAAI,KAAK,CAAC,OAAO,KAAK,gBAAgB;QAAE,OAAO,KAAK,CAAC;IACrD,IAAI,KAAK,CAAC,gBAAgB,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,KAAK,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAA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atSnapshotV1, 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>>;
@@ -201,7 +203,7 @@ export type ChatTaskPayload<TClientData = unknown> = {
201
203
  * to short-circuit the LLM call when an action doesn't need a response.
202
204
  * - `"close"`: The chat session is being closed (internal; `run()` is not called).
203
205
  */
204
- trigger: "submit-message" | "regenerate-message" | "preload" | "action" | "close";
206
+ trigger: "submit-message" | "regenerate-message" | "preload" | "action" | "action-turn" | "close";
205
207
  /** The ID of the message to regenerate (only for `"regenerate-message"`) */
206
208
  messageId?: string;
207
209
  /** Custom data from the frontend (passed via `metadata` on `sendMessage()` or the transport). */
@@ -242,6 +244,16 @@ export type ChatTaskRunPayload<TClientData = unknown, TTools extends ToolSet = T
242
244
  * Use for tags, metadata, parent run links, or any API that needs the full run record.
243
245
  */
244
246
  ctx: TaskRunContext;
247
+ /**
248
+ * `streamText` with this agent's managed options already applied: the
249
+ * prompt from `chat.prompt.set()`, the skill tools, telemetry, and the
250
+ * `prepareStep` that delivers steering, compaction and injected context.
251
+ *
252
+ * Prefer it over importing `streamText` from `ai`. The imported one takes
253
+ * none of that unless you spread `chat.toStreamTextOptions()` yourself, and
254
+ * forgetting the spread fails silently.
255
+ */
256
+ streamText: AiStreamTextFn;
245
257
  /** Token usage from the previous turn. Undefined on turn 0. */
246
258
  previousTurnUsage?: LanguageModelUsage;
247
259
  /** Cumulative token usage across all completed turns so far. */
@@ -838,6 +850,12 @@ export declare function buildSkillTools(skills: ResolvedSkill[]): Record<string,
838
850
  * Options for {@link toStreamTextOptions}.
839
851
  */
840
852
  export type ToStreamTextOptionsOptions = {
853
+ /**
854
+ * A base system prompt, used when `chat.prompt.set()` has not supplied one.
855
+ * `chat.agent({ system })` and a `system` passed to the managed `streamText`
856
+ * both arrive here.
857
+ */
858
+ system?: string | SystemModelMessage;
841
859
  /** Additional telemetry metadata merged into `experimental_telemetry.metadata`. */
842
860
  telemetry?: Record<string, string>;
843
861
  /**
@@ -908,6 +926,23 @@ export type SystemCacheControl = {
908
926
  *
909
927
  * If no prompt has been set, returns `{}` (no-op spread).
910
928
  */
929
+ /**
930
+ * The AI SDK's own `streamText` signature, borrowed rather than restated.
931
+ *
932
+ * The peer range spans `ai` v5, v6 and v7, whose `streamText` options differ.
933
+ * Describing the shape here would drift against all three; `typeof` resolves to
934
+ * whichever version the user installed, so generics, overloads and tool
935
+ * inference are exactly theirs.
936
+ */
937
+ type AiStreamTextFn = typeof aiStreamTextSignature;
938
+ /**
939
+ * The `streamText` handed to a `chat.agent` `run()`, carrying the agent's
940
+ * managed options.
941
+ *
942
+ * Exported so a loop factored out of `run` can take it as a parameter and keep
943
+ * them: `function loop(messages: ModelMessage[], streamText: ChatStreamText)`.
944
+ */
945
+ export type ChatStreamText = AiStreamTextFn;
911
946
  declare function toStreamTextOptions(options?: ToStreamTextOptionsOptions): Record<string, unknown>;
912
947
  /**
913
948
  * Options for `pipeChat`.
@@ -953,6 +988,37 @@ export type ChatUIMessageStreamOptions<TUIM extends UIMessage = UIMessage> = Omi
953
988
  type UIMessageStreamable = {
954
989
  toUIMessageStream: (...args: any[]) => AsyncIterable<unknown> | ReadableStream<unknown>;
955
990
  };
991
+ declare const actionTurnBrand: unique symbol;
992
+ /**
993
+ * The marker `onAction` returns to have a turn run on the history it just
994
+ * edited. Produce it with {@link chat.turn}.
995
+ */
996
+ export type ActionTurn = {
997
+ readonly [actionTurnBrand]: true;
998
+ };
999
+ /**
1000
+ * Turn the current action into a turn.
1001
+ *
1002
+ * Return it from `onAction` after editing history. The action's own work is
1003
+ * finished first (the edit is applied and snapshotted), then a turn runs on the
1004
+ * result exactly as a message turn does: `onTurnStart`, `run()` with the edited
1005
+ * history, `onBeforeTurnComplete`, `onTurnComplete`, and the turn counter
1006
+ * advances. That gives the answer everything a turn has, the system prompt,
1007
+ * tools, steering, compaction, injected instructions and persistence, with no
1008
+ * action-specific handling.
1009
+ *
1010
+ * @example
1011
+ * ```ts
1012
+ * onAction: async ({ action }) => {
1013
+ * if (action.type === "regenerate") {
1014
+ * chat.history.slice(0, -1);
1015
+ * return chat.turn();
1016
+ * }
1017
+ * if (action.type === "undo") chat.history.slice(0, -2); // no turn
1018
+ * },
1019
+ * ```
1020
+ */
1021
+ declare function chatTurn(): ActionTurn;
956
1022
  /**
957
1023
  * Pipes a chat stream to the realtime stream, making it available to the
958
1024
  * `TriggerChatTransport` on the frontend.
@@ -1097,8 +1163,9 @@ export type RecoveryPendingToolCall = {
1097
1163
  * `chat.endRun()` with no buffered user messages, fresh chat, OOM retry
1098
1164
  * after a successful turn-complete with no in-flight tail).
1099
1165
  *
1100
- * Does NOT fire when `hydrateMessages` is registered (the customer owns
1101
- * persistence; recovery decisions live in their own DB query).
1166
+ * Fires regardless of who owns the model's context. With `hydrateMessages`
1167
+ * or a storage `loadContext`, the recovered tail reaches that hook in
1168
+ * `previousMessages` on the next turn.
1102
1169
  */
1103
1170
  export type RecoveryBootEvent<TUIM extends UIMessage = UIMessage> = {
1104
1171
  /** Task run context — same as `task({ run })` second-argument `ctx`. */
@@ -1167,8 +1234,9 @@ export type RecoveryBootResult<TUIM extends UIMessage = UIMessage> = {
1167
1234
  * context, mutate its tool parts to inject synthesized results,
1168
1235
  * collapse history, etc.
1169
1236
  *
1170
- * Ignored when `hydrateMessages` is registered (the hydrate hook
1171
- * runs per-turn and overwrites the chain).
1237
+ * With `hydrateMessages` or a storage `loadContext`, this chain is what
1238
+ * the hook receives as `previousMessages` on the next turn; the hook's
1239
+ * return value is the chain the model sees.
1172
1240
  */
1173
1241
  chain?: TUIM[];
1174
1242
  /**
@@ -1545,6 +1613,17 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1545
1613
  * ```
1546
1614
  */
1547
1615
  oomMachine?: MachinePresetName;
1616
+ /**
1617
+ * What to do when the session's `externalDeploymentId` no longer names the deployment
1618
+ * this run is on — after a redeploy re-pins the session, say.
1619
+ *
1620
+ * - `"follow"` (default) hands the conversation to the pinned deployment at the next
1621
+ * turn boundary, so no `chat.requestUpgrade()` of your own is needed.
1622
+ * - `"hold"` stays put until you ask to move. Manual `chat.requestUpgrade()` works either way.
1623
+ *
1624
+ * Ignored for sessions with no pin, and for sessions using `lockToVersion`.
1625
+ */
1626
+ versionSkew?: ChatVersionSkewPolicy;
1548
1627
  /**
1549
1628
  * Schema for validating `clientData` from the frontend.
1550
1629
  * Accepts Zod, ArkType, Valibot, or any supported schema library.
@@ -1599,13 +1678,14 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1599
1678
  * `onBeforeTurnComplete` / `onTurnComplete`, no `run()`. Use
1600
1679
  * `chat.history.*` inside `onAction` to mutate state.
1601
1680
  *
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.
1681
+ * To answer after the edit, return `chat.turn()`: the edit is applied and
1682
+ * snapshotted, then a turn runs on the result with every turn guarantee. An
1683
+ * action that returns nothing is a state edit only. Returning anything else
1684
+ * is an error; a response can no longer be returned directly.
1605
1685
  */
1606
1686
  onAction?: (event: ActionEvent<[
1607
1687
  TActionSchema
1608
- ] extends [TaskSchema] ? inferSchemaOut<TActionSchema> : unknown, inferSchemaOut<TClientDataSchema>, TUIMessage>) => Promise<unknown> | unknown;
1688
+ ] extends [TaskSchema] ? inferSchemaOut<TActionSchema> : unknown, inferSchemaOut<TClientDataSchema>, TUIMessage>) => Promise<void | ActionTurn> | void | ActionTurn;
1609
1689
  /**
1610
1690
  * The tools available to this agent.
1611
1691
  *
@@ -1691,9 +1771,9 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1691
1771
  * continuation after `chat.endRun()` with no buffered user, a fresh
1692
1772
  * chat, or an OOM retry on top of a complete snapshot.
1693
1773
  *
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.
1774
+ * Fires regardless of who owns the model's context; a `hydrateMessages`
1775
+ * hook or a storage `loadContext` receives the recovered tail in
1776
+ * `previousMessages` on the next turn.
1697
1777
  *
1698
1778
  * Defaults (returned when the hook is omitted or returns no field):
1699
1779
  * - With two or more in-flight users, the partial and the user it
@@ -1823,6 +1903,32 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1823
1903
  * ```
1824
1904
  */
1825
1905
  hydrateMessages?: (event: HydrateMessagesEvent<inferSchemaOut<TClientDataSchema>, TUIMessage>) => TUIMessage[] | Promise<TUIMessage[]>;
1906
+ /**
1907
+ * Where the conversation is persisted. The runtime calls `save` after
1908
+ * every turn, failed turn and history-changing action with the changes
1909
+ * since the last save, and `load` once when a new run boots to continue
1910
+ * the conversation.
1911
+ *
1912
+ * Defaults to `defaultStorage`, the platform's snapshot in object storage
1913
+ * that the Sessions dashboard renders. Bring your own to write each change
1914
+ * to your database; `memoryTranscriptStorage()` is the reference
1915
+ * implementation and `runTranscriptStorageTests` from
1916
+ * `@trigger.dev/sdk/ai/test` checks yours against the contract.
1917
+ *
1918
+ * A storage with `loadContext` also owns the model's context on every
1919
+ * turn, which is what `hydrateMessages` did. The two cannot be combined.
1920
+ *
1921
+ * @example
1922
+ * ```ts
1923
+ * chat.agent({
1924
+ * id: "my-chat",
1925
+ * storage: myPostgresTranscriptStorage,
1926
+ * run: async ({ messages, signal, streamText }) =>
1927
+ * streamText({ model, messages, abortSignal: signal }),
1928
+ * });
1929
+ * ```
1930
+ */
1931
+ storage?: TranscriptStorage<inferSchemaOut<TClientDataSchema>>;
1826
1932
  /**
1827
1933
  * Called at the start of every turn, after message accumulation and `onChatStart` (turn 0),
1828
1934
  * but before the `run` function executes.
@@ -1897,6 +2003,31 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1897
2003
  * });
1898
2004
  * ```
1899
2005
  */
2006
+ /**
2007
+ * A provider registry, so the runtime can resolve the managed prompt's model
2008
+ * for the `streamText` it hands to `run()`. Only needed when you set a model
2009
+ * through `chat.prompt.set()` and want the bound `streamText` to honour it.
2010
+ */
2011
+ registry?: ToStreamTextOptionsOptions["registry"];
2012
+ /**
2013
+ * The agent's system prompt. Injected instructions append to it, and the
2014
+ * `streamText` handed to `run()` carries it without a spread.
2015
+ *
2016
+ * Set it here, at the call site, or through `chat.prompt.set()` for versioned
2017
+ * config, but only in one of them.
2018
+ */
2019
+ system?: ToStreamTextOptionsOptions["system"];
2020
+ /**
2021
+ * Mark the system prompt for provider-side caching, the same sugar
2022
+ * `chat.toStreamTextOptions({ cacheControl })` takes. See
2023
+ * [prompt caching](/ai-chat/prompt-caching).
2024
+ */
2025
+ cacheControl?: ToStreamTextOptionsOptions["cacheControl"];
2026
+ /**
2027
+ * Provider options for the system block, when `cacheControl` is not enough.
2028
+ * Takes precedence over `cacheControl`.
2029
+ */
2030
+ systemProviderOptions?: ToStreamTextOptionsOptions["systemProviderOptions"];
1900
2031
  compaction?: ChatAgentCompactionOptions<TUIMessage>;
1901
2032
  /**
1902
2033
  * Configure how messages that arrive during streaming are handled.
@@ -2390,15 +2521,22 @@ declare function setUIMessageStreamOptions(options: ChatUIMessageStreamOptions<U
2390
2521
  */
2391
2522
  declare function isStopped(): boolean;
2392
2523
  /**
2393
- * Request that the current run exits so the next message starts on the latest
2394
- * deployed version (via the standard continuation mechanism).
2524
+ * Hand the conversation over to another deployment.
2525
+ *
2526
+ * The handover happens immediately and server-side: a successor run is created
2527
+ * and picks the conversation up from `session.in`. The transport keeps reading
2528
+ * the same session output, so no client action is needed and nothing waits for
2529
+ * the next message.
2530
+ *
2531
+ * Without a target the session's pin is cleared, so the successor lands on the
2532
+ * latest deployed version; with `externalDeploymentId` the session is re-pinned
2533
+ * to that deployment.
2395
2534
  *
2396
2535
  * 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.
2536
+ * entirely and the successor answers the message that opened the turn.
2399
2537
  *
2400
2538
  * 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.
2539
+ * normally and the handover happens afterward.
2402
2540
  *
2403
2541
  * Call from `onTurnStart`, `onValidateMessages`, `onChatResume`, `run()`,
2404
2542
  * or inside `chat.defer()`.
@@ -2418,7 +2556,9 @@ declare function isStopped(): boolean;
2418
2556
  * });
2419
2557
  * ```
2420
2558
  */
2421
- declare function requestUpgrade(): void;
2559
+ declare function requestUpgrade(options?: {
2560
+ externalDeploymentId?: string;
2561
+ }): void;
2422
2562
  /**
2423
2563
  * Hand off the current custom agent Session to a fresh run.
2424
2564
  *
@@ -2477,6 +2617,50 @@ declare function endAndContinue(): Promise<void>;
2477
2617
  * ```
2478
2618
  */
2479
2619
  declare function endRun(): void;
2620
+ /**
2621
+ * End the whole conversation, permanently. The session row is closed, further
2622
+ * appends are refused, and the run exits without scheduling a continuation.
2623
+ *
2624
+ * This is the session-level stop. {@link endRun} ends the current run and lets
2625
+ * the next message start a fresh one; `chat.close()` ends the session itself,
2626
+ * so there is no next message. Use it for a budget cap, a completed goal,
2627
+ * abuse detection, or a user signing out.
2628
+ *
2629
+ * In a `chat.agent`, call it from `run()`, `prepareStep`, or
2630
+ * `onBeforeTurnComplete`. Called mid-step, it aborts the in-flight
2631
+ * `streamText` the same way the stop signal does, so the partial response is
2632
+ * still captured and streamed. The turn then completes normally, a terminal
2633
+ * `session-closed` record carrying `reason` is written to the response stream,
2634
+ * and the loop exits.
2635
+ *
2636
+ * Prefer `onBeforeTurnComplete` over `onTurnComplete`. It carries the same
2637
+ * fields but still runs while the stream is open, so the closed state rides
2638
+ * out on the turn's final record. `onTurnComplete` runs after that record, so
2639
+ * a close decided there does not reach a reader that has already finished the
2640
+ * turn, and the user only finds out when their next message is refused.
2641
+ *
2642
+ * In a `chat.customAgent`, call it anywhere in your own loop. The close is
2643
+ * performed when `run()` returns, so it lands whether you break out of a
2644
+ * `chat.createSession` loop, return early, or hand-roll the loop entirely.
2645
+ *
2646
+ * Closing is one-way: a closed session cannot be reopened. Its transcript
2647
+ * stays readable.
2648
+ *
2649
+ * @example
2650
+ * ```ts
2651
+ * chat.agent({
2652
+ * id: "budgeted-agent",
2653
+ * onBeforeTurnComplete: async ({ usage }) => {
2654
+ * if (await overBudget(usage)) {
2655
+ * chat.close({ reason: "Monthly budget reached" });
2656
+ * }
2657
+ * },
2658
+ * });
2659
+ * ```
2660
+ */
2661
+ declare function close(options?: {
2662
+ reason?: string;
2663
+ }): void;
2480
2664
  /**
2481
2665
  * Register a promise that runs in the background during the current turn.
2482
2666
  *
@@ -2746,6 +2930,20 @@ declare class ChatMessageAccumulator {
2746
2930
  * Queue a message for injection, converting to model messages automatically.
2747
2931
  */
2748
2932
  steerAsync(message: UIMessage): Promise<void>;
2933
+ /**
2934
+ * Record the messages a steering drain consumed.
2935
+ *
2936
+ * The drain only puts them in this step's prompt, so without this they
2937
+ * shape one answer and then exist in neither lane: not in `uiMessages`,
2938
+ * which is what an app persists from, and not in `modelMessages`, which is
2939
+ * what every later turn sends.
2940
+ *
2941
+ * Both lanes are appended to. The model lane is never reconverted from the
2942
+ * UI lane, because `compactIfNeeded` replaces it with a summary and leaves
2943
+ * the UI lane whole: a reconversion would restore everything the summary
2944
+ * replaced.
2945
+ */
2946
+ absorbSteering(claimed: UIMessage[], injected?: ModelMessage[]): Promise<void>;
2749
2947
  /**
2750
2948
  * Get and clear unconsumed steering messages.
2751
2949
  */
@@ -2783,6 +2981,11 @@ export type ChatSessionOptions = {
2783
2981
  timeout?: string;
2784
2982
  /** Max turns before ending. @default 100 */
2785
2983
  maxTurns?: number;
2984
+ /**
2985
+ * What to do when the session's `externalDeploymentId` no longer names this deployment.
2986
+ * `"follow"` (default) hands over at the next turn boundary; `"hold"` stays put.
2987
+ */
2988
+ versionSkew?: ChatVersionSkewPolicy;
2786
2989
  /** Automatic context compaction — same options as `chat.agent({ compaction })`. */
2787
2990
  compaction?: ChatAgentCompactionOptions;
2788
2991
  /** Configure mid-execution message injection — same options as `chat.agent({ pendingMessages })`. */
@@ -2994,7 +3197,7 @@ export type CreateChatStartSessionActionOptions = {
2994
3197
  * Default trigger config used when starting a new session for a chat.
2995
3198
  * Per-call `params.triggerConfig` shallow-merges on top.
2996
3199
  */
2997
- triggerConfig?: Partial<SessionTriggerConfig>;
3200
+ triggerConfig?: Partial<SessionTriggerConfigInput>;
2998
3201
  /**
2999
3202
  * Override the Trigger.dev API base URL. String applies to both
3000
3203
  * `/api/v1/sessions` and `/api/v1/auth/jwt/claims`; function picks per
@@ -3037,7 +3240,7 @@ export type ChatStartSessionParams<TChat extends AnyTask = AnyTask> = {
3037
3240
  * `chat.agent`: anything beyond `chatId`/`messages`/`trigger`/`metadata`,
3038
3241
  * which the runtime injects automatically).
3039
3242
  */
3040
- triggerConfig?: Partial<SessionTriggerConfig>;
3243
+ triggerConfig?: Partial<SessionTriggerConfigInput>;
3041
3244
  /**
3042
3245
  * Opaque session-level metadata stored on the Session row. Separate from
3043
3246
  * the per-turn `clientData` above. Use this when you want to attach
@@ -3059,6 +3262,11 @@ export type ChatStartSessionResult = {
3059
3262
  runId: string;
3060
3263
  /** Session friendlyId — informational. */
3061
3264
  sessionId: string;
3265
+ /**
3266
+ * The session's run is parked waiting for its deployment. Messages sent meanwhile are durable
3267
+ * and delivered once it lands; surface this so the wait reads as a deploy in progress.
3268
+ */
3269
+ pendingVersion?: boolean;
3062
3270
  };
3063
3271
  /**
3064
3272
  * Creates a server-side helper that starts (or resumes) a Session for a
@@ -3095,6 +3303,42 @@ export type ChatStartSessionResult = {
3095
3303
  * ```
3096
3304
  */
3097
3305
  declare function createChatStartSessionAction<TChat extends AnyTask = AnyTask>(taskId: string, options?: CreateChatStartSessionActionOptions): (params: ChatStartSessionParams<TChat>) => Promise<ChatStartSessionResult>;
3306
+ export type CreateChatLoadTranscriptActionOptions = {
3307
+ /**
3308
+ * Scope the action to a specific API client configuration (secret key,
3309
+ * base URL) instead of the process-wide one. The default storage reads
3310
+ * through this client.
3311
+ */
3312
+ apiClient?: ApiClientConfiguration;
3313
+ /** Page size when the caller passes none. */
3314
+ limit?: number;
3315
+ };
3316
+ export type ChatLoadTranscriptParams<TClientData = unknown> = {
3317
+ chatId: string;
3318
+ clientData?: TClientData;
3319
+ limit?: number;
3320
+ before?: string;
3321
+ };
3322
+ /**
3323
+ * Creates a server-side helper that reads a conversation from a transcript
3324
+ * storage, for rendering history before the chat connects. Works the same
3325
+ * for every storage, the platform default included, so the browser never
3326
+ * reads a store directly and the secret key stays on the server.
3327
+ *
3328
+ * Wrap it in a Next.js server action (or any server-side handler), scope it
3329
+ * to the authenticated user through `clientData`, and pass the result to
3330
+ * `useLoadTranscript` in the browser.
3331
+ *
3332
+ * @example
3333
+ * ```ts
3334
+ * // actions.ts
3335
+ * "use server";
3336
+ * import { chat, defaultStorage } from "@trigger.dev/sdk/ai";
3337
+ *
3338
+ * export const loadTranscript = chat.createLoadTranscriptAction(defaultStorage, { limit: 50 });
3339
+ * ```
3340
+ */
3341
+ declare function createChatLoadTranscriptAction<TClientData = unknown>(storage: TranscriptStorage<TClientData>, options?: CreateChatLoadTranscriptActionOptions): (params: ChatLoadTranscriptParams<TClientData>) => Promise<TranscriptLoadResult>;
3098
3342
  export declare const chat: {
3099
3343
  /** Create a chat agent. See {@link chatAgent}. */
3100
3344
  agent: typeof chatAgent;
@@ -3106,8 +3350,12 @@ export declare const chat: {
3106
3350
  withClientData: typeof withClientData;
3107
3351
  /** Create a server-side helper for starting (or resuming) a Session for a chatId. See {@link createChatStartSessionAction}. */
3108
3352
  createStartSessionAction: typeof createChatStartSessionAction;
3353
+ /** Returns a server-side helper that reads a conversation from a transcript storage. */
3354
+ createLoadTranscriptAction: typeof createChatLoadTranscriptAction;
3109
3355
  /** Pipe a stream to the chat transport. See {@link pipeChat}. */
3110
3356
  pipe: typeof pipeChat;
3357
+ /** Return from `onAction` to run a turn on the edited history. See {@link chatTurn}. */
3358
+ turn: typeof chatTurn;
3111
3359
  /** Create a per-run typed local. See {@link chatLocal}. */
3112
3360
  local: typeof chatLocal;
3113
3361
  /** Create a public access token for a chat task. See {@link createChatAccessToken}. */
@@ -3128,6 +3376,8 @@ export declare const chat: {
3128
3376
  endAndContinue: typeof endAndContinue;
3129
3377
  /** Exit the run after the current turn completes, without any upgrade signal. See {@link endRun}. */
3130
3378
  endRun: typeof endRun;
3379
+ /** End the conversation permanently: close the session and exit the run. See {@link close}. */
3380
+ close: typeof close;
3131
3381
  /** Clean up aborted parts from a UIMessage. See {@link cleanupAbortedParts}. */
3132
3382
  cleanupAbortedParts: typeof cleanupAbortedParts;
3133
3383
  /** Register background work that runs in parallel with streaming. See {@link chatDefer}. */