@trigger.dev/sdk 0.0.0-chat-prerelease-20260419173457 → 0.0.0-chat-prerelease-20260501122331

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 (76) hide show
  1. package/dist/commonjs/v3/agentSkillsRuntime.d.ts +28 -0
  2. package/dist/commonjs/v3/agentSkillsRuntime.js +123 -0
  3. package/dist/commonjs/v3/agentSkillsRuntime.js.map +1 -0
  4. package/dist/commonjs/v3/ai-shared.d.ts +104 -0
  5. package/dist/commonjs/v3/ai-shared.js +25 -0
  6. package/dist/commonjs/v3/ai-shared.js.map +1 -0
  7. package/dist/commonjs/v3/ai.d.ts +77 -67
  8. package/dist/commonjs/v3/ai.js +498 -154
  9. package/dist/commonjs/v3/ai.js.map +1 -1
  10. package/dist/commonjs/v3/auth.d.ts +10 -0
  11. package/dist/commonjs/v3/auth.js.map +1 -1
  12. package/dist/commonjs/v3/chat-client.d.ts +30 -33
  13. package/dist/commonjs/v3/chat-client.js +167 -191
  14. package/dist/commonjs/v3/chat-client.js.map +1 -1
  15. package/dist/commonjs/v3/chat-react.d.ts +1 -1
  16. package/dist/commonjs/v3/chat-react.js +10 -10
  17. package/dist/commonjs/v3/chat-react.js.map +1 -1
  18. package/dist/commonjs/v3/chat.d.ts +206 -407
  19. package/dist/commonjs/v3/chat.js +348 -647
  20. package/dist/commonjs/v3/chat.js.map +1 -1
  21. package/dist/commonjs/v3/chat.test.js +559 -1736
  22. package/dist/commonjs/v3/chat.test.js.map +1 -1
  23. package/dist/commonjs/v3/index.d.ts +2 -1
  24. package/dist/commonjs/v3/index.js +4 -1
  25. package/dist/commonjs/v3/index.js.map +1 -1
  26. package/dist/commonjs/v3/runs.d.ts +4 -4
  27. package/dist/commonjs/v3/sessions.d.ts +188 -0
  28. package/dist/commonjs/v3/sessions.js +540 -0
  29. package/dist/commonjs/v3/sessions.js.map +1 -0
  30. package/dist/commonjs/v3/test/mock-chat-agent.js +81 -32
  31. package/dist/commonjs/v3/test/mock-chat-agent.js.map +1 -1
  32. package/dist/commonjs/v3/test/test-session-handle.d.ts +32 -0
  33. package/dist/commonjs/v3/test/test-session-handle.js +177 -0
  34. package/dist/commonjs/v3/test/test-session-handle.js.map +1 -0
  35. package/dist/commonjs/version.js +1 -1
  36. package/dist/esm/v3/agentSkillsRuntime.d.ts +28 -0
  37. package/dist/esm/v3/agentSkillsRuntime.js +96 -0
  38. package/dist/esm/v3/agentSkillsRuntime.js.map +1 -0
  39. package/dist/esm/v3/ai-shared.d.ts +104 -0
  40. package/dist/esm/v3/ai-shared.js +22 -0
  41. package/dist/esm/v3/ai-shared.js.map +1 -0
  42. package/dist/esm/v3/ai.d.ts +77 -67
  43. package/dist/esm/v3/ai.js +497 -131
  44. package/dist/esm/v3/ai.js.map +1 -1
  45. package/dist/esm/v3/auth.d.ts +10 -0
  46. package/dist/esm/v3/auth.js.map +1 -1
  47. package/dist/esm/v3/chat-client.d.ts +30 -33
  48. package/dist/esm/v3/chat-client.js +167 -191
  49. package/dist/esm/v3/chat-client.js.map +1 -1
  50. package/dist/esm/v3/chat-react.d.ts +1 -1
  51. package/dist/esm/v3/chat-react.js +8 -8
  52. package/dist/esm/v3/chat-react.js.map +1 -1
  53. package/dist/esm/v3/chat.d.ts +206 -407
  54. package/dist/esm/v3/chat.js +348 -647
  55. package/dist/esm/v3/chat.js.map +1 -1
  56. package/dist/esm/v3/chat.test.js +559 -1736
  57. package/dist/esm/v3/chat.test.js.map +1 -1
  58. package/dist/esm/v3/index.d.ts +2 -1
  59. package/dist/esm/v3/index.js +2 -1
  60. package/dist/esm/v3/index.js.map +1 -1
  61. package/dist/esm/v3/sessions.d.ts +188 -0
  62. package/dist/esm/v3/sessions.js +532 -0
  63. package/dist/esm/v3/sessions.js.map +1 -0
  64. package/dist/esm/v3/test/mock-chat-agent.js +81 -32
  65. package/dist/esm/v3/test/mock-chat-agent.js.map +1 -1
  66. package/dist/esm/v3/test/test-session-handle.d.ts +32 -0
  67. package/dist/esm/v3/test/test-session-handle.js +172 -0
  68. package/dist/esm/v3/test/test-session-handle.js.map +1 -0
  69. package/dist/esm/version.js +1 -1
  70. package/package.json +18 -5
  71. package/dist/commonjs/v3/chat-constants.d.ts +0 -7
  72. package/dist/commonjs/v3/chat-constants.js +0 -14
  73. package/dist/commonjs/v3/chat-constants.js.map +0 -1
  74. package/dist/esm/v3/chat-constants.d.ts +0 -7
  75. package/dist/esm/v3/chat-constants.js +0 -8
  76. package/dist/esm/v3/chat-constants.js.map +0 -1
@@ -0,0 +1,28 @@
1
+ export type BashSkillInput = {
2
+ /** Absolute path to the skill's root (used as `cwd`). */
3
+ skillPath: string;
4
+ /** The bash command to run. */
5
+ command: string;
6
+ /** Optional abort signal forwarded to `spawn()`. */
7
+ abortSignal?: AbortSignal;
8
+ };
9
+ export type BashSkillResult = {
10
+ exitCode: number | null;
11
+ stdout: string;
12
+ stderr: string;
13
+ } | {
14
+ error: string;
15
+ };
16
+ export type ReadFileInSkillInput = {
17
+ /** Absolute path to the skill's root — the relative path must resolve inside it. */
18
+ skillPath: string;
19
+ /** Relative path the tool caller supplied. */
20
+ relativePath: string;
21
+ };
22
+ export type ReadFileInSkillResult = {
23
+ content: string;
24
+ } | {
25
+ error: string;
26
+ };
27
+ export declare function readFileInSkill({ skillPath, relativePath, }: ReadFileInSkillInput): Promise<ReadFileInSkillResult>;
28
+ export declare function runBashInSkill({ skillPath, command, abortSignal, }: BashSkillInput): Promise<BashSkillResult>;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.readFileInSkill = readFileInSkill;
27
+ exports.runBashInSkill = runBashInSkill;
28
+ const node_child_process_1 = require("node:child_process");
29
+ const fs = __importStar(require("node:fs/promises"));
30
+ const nodePath = __importStar(require("node:path"));
31
+ /**
32
+ * Server-only runtime for the auto-injected skill tools
33
+ * (`loadSkill` / `readFile` / `bash`) that `chat.agent({ skills })`
34
+ * wires up. Split off from `./ai.ts` so the chat-agent surface in
35
+ * `@trigger.dev/sdk/ai` stays importable from client bundles —
36
+ * Next.js + Webpack reject top-level `node:*` imports anywhere in a
37
+ * client graph, even when a consumer only pulls in types.
38
+ *
39
+ * The SDK's `ai.ts` loads this module via a computed-string dynamic
40
+ * import inside each tool's `execute` — webpack treats the
41
+ * expression as an unknown dependency and skips static tracing, so
42
+ * the node-only symbols here never surface in a client build. The
43
+ * module resolves fine at runtime on a server worker because the
44
+ * relative path (`./agentSkillsRuntime.js`) lands next to `ai.js` in
45
+ * the emitted dist.
46
+ *
47
+ * Public subpath: `@trigger.dev/sdk/ai/skills-runtime`. Customers
48
+ * who want to eagerly bundle the runtime server-side (e.g. warming
49
+ * it on worker bootstrap) can import from there.
50
+ */
51
+ const DEFAULT_BASH_OUTPUT_BYTES = 64 * 1024;
52
+ const DEFAULT_READ_FILE_BYTES = 1024 * 1024;
53
+ function truncate(s, limit) {
54
+ if (s.length <= limit)
55
+ return s;
56
+ return s.slice(0, limit) + `\n…[truncated ${s.length - limit} bytes]`;
57
+ }
58
+ /**
59
+ * Path-traversal guard: confirm `relative` resolves inside `root`.
60
+ * Throws if it escapes via `..` or an absolute prefix. Returns the
61
+ * absolute resolved path.
62
+ */
63
+ function safeJoinInside(root, relative) {
64
+ if (nodePath.isAbsolute(relative)) {
65
+ throw new Error(`Path must be relative to the skill directory: ${relative}`);
66
+ }
67
+ const resolved = nodePath.resolve(root, relative);
68
+ const normalized = nodePath.resolve(root) + nodePath.sep;
69
+ if (resolved !== nodePath.resolve(root) && !resolved.startsWith(normalized)) {
70
+ throw new Error(`Path escapes the skill directory: ${relative}`);
71
+ }
72
+ return resolved;
73
+ }
74
+ async function readFileInSkill({ skillPath, relativePath, }) {
75
+ let absolute;
76
+ try {
77
+ absolute = safeJoinInside(skillPath, relativePath);
78
+ }
79
+ catch (err) {
80
+ return { error: err.message };
81
+ }
82
+ try {
83
+ const content = await fs.readFile(absolute, "utf8");
84
+ return { content: truncate(content, DEFAULT_READ_FILE_BYTES) };
85
+ }
86
+ catch (err) {
87
+ return { error: err.message };
88
+ }
89
+ }
90
+ async function runBashInSkill({ skillPath, command, abortSignal, }) {
91
+ return new Promise((resolvePromise) => {
92
+ let child;
93
+ try {
94
+ child = (0, node_child_process_1.spawn)("bash", ["-c", command], {
95
+ cwd: skillPath,
96
+ signal: abortSignal,
97
+ });
98
+ }
99
+ catch (err) {
100
+ resolvePromise({ error: err.message });
101
+ return;
102
+ }
103
+ let stdout = "";
104
+ let stderr = "";
105
+ child.stdout?.on("data", (chunk) => {
106
+ stdout += chunk.toString();
107
+ });
108
+ child.stderr?.on("data", (chunk) => {
109
+ stderr += chunk.toString();
110
+ });
111
+ child.once("close", (code) => {
112
+ resolvePromise({
113
+ exitCode: code,
114
+ stdout: truncate(stdout, DEFAULT_BASH_OUTPUT_BYTES),
115
+ stderr: truncate(stderr, DEFAULT_BASH_OUTPUT_BYTES),
116
+ });
117
+ });
118
+ child.once("error", (err) => {
119
+ resolvePromise({ error: err.message });
120
+ });
121
+ });
122
+ }
123
+ //# sourceMappingURL=agentSkillsRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agentSkillsRuntime.js","sourceRoot":"","sources":["../../../src/v3/agentSkillsRuntime.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Browser-safe primitives shared between `@trigger.dev/sdk/ai` (server) and
3
+ * `@trigger.dev/sdk/chat` / `@trigger.dev/sdk/chat/react` (client).
4
+ *
5
+ * This module exists to keep `ai.ts` reachable only from the server graph.
6
+ * `ai.ts` weighs in at ~7000 lines and statically imports the agent-skills
7
+ * runtime (which uses `node:child_process` / `node:fs/promises`). When a
8
+ * browser bundle imports a runtime value from `ai.ts` — historically the
9
+ * `PENDING_MESSAGE_INJECTED_TYPE` constant in `chat-react.ts` — the bundler
10
+ * traces `ai.ts`'s entire module graph into the client chunk and hits the
11
+ * `node:` builtins, which Turbopack rejects outright (and webpack flags as
12
+ * a "Critical dependency" warning).
13
+ *
14
+ * Anything in this file MUST stay free of `node:*` imports and free of any
15
+ * import from `ai.ts`.
16
+ */
17
+ import type { Task, AnyTask } from "@trigger.dev/core/v3";
18
+ import type { UIMessage } from "ai";
19
+ /**
20
+ * Message-part `type` value for the pending-message data part the agent
21
+ * injects when a follow-up message arrives mid-turn.
22
+ */
23
+ export declare const PENDING_MESSAGE_INJECTED_TYPE: "data-pending-message-injected";
24
+ /**
25
+ * The wire payload shape sent by `TriggerChatTransport`.
26
+ * Uses `metadata` to match the AI SDK's `ChatRequestOptions` field name.
27
+ */
28
+ export type ChatTaskWirePayload<TMessage extends UIMessage = UIMessage, TMetadata = unknown> = {
29
+ messages: TMessage[];
30
+ chatId: string;
31
+ trigger: "submit-message" | "regenerate-message" | "preload" | "close" | "action";
32
+ messageId?: string;
33
+ metadata?: TMetadata;
34
+ /** Custom action payload when `trigger` is `"action"`. Validated against `actionSchema` on the backend. */
35
+ action?: unknown;
36
+ /** Whether this run is continuing an existing chat whose previous run ended. */
37
+ continuation?: boolean;
38
+ /** The run ID of the previous run (only set when `continuation` is true). */
39
+ previousRunId?: string;
40
+ /** Override idle timeout for this run (seconds). Set by transport.preload(). */
41
+ idleTimeoutInSeconds?: number;
42
+ /**
43
+ * The friendlyId of the Session primitive backing this chat. The
44
+ * transport opens (or lazy-creates) the session with
45
+ * `externalId = chatId` on first message, then sends this friendlyId
46
+ * through to the run so the agent can attach to `.in` / `.out`
47
+ * without needing to round-trip through the control plane again.
48
+ * Optional for backward-compat while the migration is in flight;
49
+ * required once the legacy run-scoped stream path is removed.
50
+ */
51
+ sessionId?: string;
52
+ /**
53
+ * Client-side `chat.store` value sent by the transport. Applied at turn
54
+ * start before `run()` fires, overwriting any in-memory store value on the
55
+ * agent (last-write-wins).
56
+ *
57
+ * The transport queues this via `setStore` / `applyStorePatch` and flushes
58
+ * it with the next `sendMessage`. On the agent you typically don't read
59
+ * this directly — it's applied into `chat.store` transparently.
60
+ */
61
+ incomingStore?: unknown;
62
+ };
63
+ /**
64
+ * One chunk on the chat input stream. `kind` discriminates the variants —
65
+ * a single ordered stream now carries all the signals the old three-stream
66
+ * split did (`chat-messages`, `chat-stop`, plus action messages piggybacked
67
+ * on `chat-messages`).
68
+ */
69
+ export type ChatInputChunk<TMessage extends UIMessage = UIMessage, TMetadata = unknown> = {
70
+ kind: "message";
71
+ /**
72
+ * Full wire payload for a new user message or regeneration. Mirrors
73
+ * what the legacy `chat-messages` input stream carried.
74
+ */
75
+ payload: ChatTaskWirePayload<TMessage, TMetadata>;
76
+ } | {
77
+ kind: "stop";
78
+ /** Optional human-readable reason. Maps to the legacy `chat-stop` record. */
79
+ message?: string;
80
+ };
81
+ /**
82
+ * Extracts the client-data (`metadata`) type from a chat task.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * import type { InferChatClientData } from "@trigger.dev/sdk/ai";
87
+ * import type { myChat } from "@/trigger/chat";
88
+ *
89
+ * type MyClientData = InferChatClientData<typeof myChat>;
90
+ * ```
91
+ */
92
+ export type InferChatClientData<TTask extends AnyTask> = TTask extends Task<string, ChatTaskWirePayload<any, infer TMetadata>, any> ? TMetadata : unknown;
93
+ /**
94
+ * Extracts the UI message type from a chat task (wire payload `messages` items).
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * import type { InferChatUIMessage } from "@trigger.dev/sdk/ai";
99
+ * import type { myChat } from "@/trigger/chat";
100
+ *
101
+ * type Msg = InferChatUIMessage<typeof myChat>;
102
+ * ```
103
+ */
104
+ export type InferChatUIMessage<TTask extends AnyTask> = TTask extends Task<string, ChatTaskWirePayload<infer TUIM extends UIMessage, any>, any> ? TUIM : UIMessage;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ /**
3
+ * Browser-safe primitives shared between `@trigger.dev/sdk/ai` (server) and
4
+ * `@trigger.dev/sdk/chat` / `@trigger.dev/sdk/chat/react` (client).
5
+ *
6
+ * This module exists to keep `ai.ts` reachable only from the server graph.
7
+ * `ai.ts` weighs in at ~7000 lines and statically imports the agent-skills
8
+ * runtime (which uses `node:child_process` / `node:fs/promises`). When a
9
+ * browser bundle imports a runtime value from `ai.ts` — historically the
10
+ * `PENDING_MESSAGE_INJECTED_TYPE` constant in `chat-react.ts` — the bundler
11
+ * traces `ai.ts`'s entire module graph into the client chunk and hits the
12
+ * `node:` builtins, which Turbopack rejects outright (and webpack flags as
13
+ * a "Critical dependency" warning).
14
+ *
15
+ * Anything in this file MUST stay free of `node:*` imports and free of any
16
+ * import from `ai.ts`.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.PENDING_MESSAGE_INJECTED_TYPE = void 0;
20
+ /**
21
+ * Message-part `type` value for the pending-message data part the agent
22
+ * injects when a follow-up message arrives mid-turn.
23
+ */
24
+ exports.PENDING_MESSAGE_INJECTED_TYPE = "data-pending-message-injected";
25
+ //# sourceMappingURL=ai-shared.js.map
@@ -0,0 +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"}
@@ -1,13 +1,12 @@
1
- import { AnyTask, Task, type inferSchemaIn, type inferSchemaOut, type TaskIdentifier, type TaskOptions, type TaskSchema, type TaskRunContext, type TaskWithSchema } from "@trigger.dev/core/v3";
1
+ import { AnyTask, type RealtimeDefinedInputStream, type RealtimeDefinedStream, Task, type inferSchemaIn, type inferSchemaOut, type TaskIdentifier, type TaskOptions, type TaskSchema, type TaskRunContext, type TaskWithSchema } from "@trigger.dev/core/v3";
2
2
  import type { FinishReason, ModelMessage, ToolSet, UIMessage, UIMessageChunk, UIMessageStreamOptions, LanguageModelUsage } from "ai";
3
3
  import { Tool, ToolCallOptions } from "ai";
4
4
  import { locals } from "./locals.js";
5
5
  import type { ResolvedPrompt } from "./prompt.js";
6
6
  import type { ResolvedSkill } from "./skill.js";
7
- import type { TriggerChatTaskParams, TriggerChatTaskResult } from "./chat.js";
7
+ import { type SessionTriggerConfig } from "@trigger.dev/core/v3";
8
8
  /** Re-export for typing `ctx` in `chat.agent` hooks without importing `@trigger.dev/core`. */
9
9
  export type { TaskRunContext } from "@trigger.dev/core/v3";
10
- import { CHAT_MESSAGES_STREAM_ID, CHAT_STOP_STREAM_ID } from "./chat-constants.js";
11
10
  import { type ChatStorePatchOperation } from "@trigger.dev/core/v3/chat-client";
12
11
  export type ToolCallExecutionOptions = {
13
12
  toolCallId: string;
@@ -133,13 +132,6 @@ export declare const ai: {
133
132
  * ```
134
133
  */
135
134
  declare function createChatAccessToken<TTask extends AnyTask>(taskId: TaskIdentifier<TTask>): Promise<string>;
136
- /**
137
- * The default stream key used for chat transport communication.
138
- * Both `TriggerChatTransport` (frontend) and `pipeChat`/`chatAgent` (backend)
139
- * use this key by default.
140
- */
141
- export declare const CHAT_STREAM_KEY = "chat";
142
- export { CHAT_MESSAGES_STREAM_ID, CHAT_STOP_STREAM_ID };
143
135
  /**
144
136
  * Listener fired when the store value changes. `operations` is present for
145
137
  * `patch()` updates and absent for `set()` (which is a full snapshot).
@@ -188,35 +180,8 @@ export type ChatWriter = {
188
180
  /** Merge another stream's chunks into the chat stream. */
189
181
  merge(stream: ReadableStream<UIMessageChunk>): void;
190
182
  };
191
- /**
192
- * The wire payload shape sent by `TriggerChatTransport`.
193
- * Uses `metadata` to match the AI SDK's `ChatRequestOptions` field name.
194
- */
195
- export type ChatTaskWirePayload<TMessage extends UIMessage = UIMessage, TMetadata = unknown> = {
196
- messages: TMessage[];
197
- chatId: string;
198
- trigger: "submit-message" | "regenerate-message" | "preload" | "close" | "action";
199
- messageId?: string;
200
- metadata?: TMetadata;
201
- /** Custom action payload when `trigger` is `"action"`. Validated against `actionSchema` on the backend. */
202
- action?: unknown;
203
- /** Whether this run is continuing an existing chat whose previous run ended. */
204
- continuation?: boolean;
205
- /** The run ID of the previous run (only set when `continuation` is true). */
206
- previousRunId?: string;
207
- /** Override idle timeout for this run (seconds). Set by transport.preload(). */
208
- idleTimeoutInSeconds?: number;
209
- /**
210
- * Client-side `chat.store` value sent by the transport. Applied at turn
211
- * start before `run()` fires, overwriting any in-memory store value on the
212
- * agent (last-write-wins).
213
- *
214
- * The transport queues this via `setStore` / `applyStorePatch` and flushes
215
- * it with the next `sendMessage`. On the agent you typically don't read
216
- * this directly — it's applied into `chat.store` transparently.
217
- */
218
- incomingStore?: unknown;
219
- };
183
+ import type { ChatTaskWirePayload } from "./ai-shared.js";
184
+ export type { ChatTaskWirePayload, ChatInputChunk } from "./ai-shared.js";
220
185
  /**
221
186
  * The payload shape passed to the `chatAgent` run function.
222
187
  *
@@ -253,6 +218,14 @@ export type ChatTaskPayload<TClientData = unknown> = {
253
218
  previousRunId?: string;
254
219
  /** Whether this run was preloaded before the first message. */
255
220
  preloaded: boolean;
221
+ /**
222
+ * The friendlyId of the Session primitive backing this chat. Use with
223
+ * `sessions.open(sessionId)` when you need direct access to the session's
224
+ * `.in` / `.out` channels outside the hooks the agent already wires for
225
+ * you. Undefined only for legacy transports that predate the sessions
226
+ * migration.
227
+ */
228
+ sessionId?: string;
256
229
  };
257
230
  /**
258
231
  * Abort signals provided to the `chatAgent` run function.
@@ -468,7 +441,7 @@ export type PendingMessagesOptions<TUIM extends UIMessage = UIMessage> = {
468
441
  * between tool-call steps. The frontend can match on this to render
469
442
  * injection points inline in the assistant response.
470
443
  */
471
- export declare const PENDING_MESSAGE_INJECTED_TYPE: "data-pending-message-injected";
444
+ export { PENDING_MESSAGE_INJECTED_TYPE } from "./ai-shared.js";
472
445
  /**
473
446
  * Event passed to the `prepareMessages` hook.
474
447
  */
@@ -2309,32 +2282,58 @@ declare function chatLocal<T extends Record<string, unknown>>(options: {
2309
2282
  * // { model?: string; userId: string }
2310
2283
  * ```
2311
2284
  */
2312
- export type InferChatClientData<TTask extends AnyTask> = TTask extends Task<string, ChatTaskWirePayload<any, infer TMetadata>, any> ? TMetadata : unknown;
2285
+ import type { InferChatClientData } from "./ai-shared.js";
2286
+ export type { InferChatClientData, InferChatUIMessage } from "./ai-shared.js";
2313
2287
  /**
2314
- * Extracts the UI message type from a chat task (wire payload `messages` items).
2315
- *
2316
- * @example
2317
- * ```ts
2318
- * import type { InferChatUIMessage } from "@trigger.dev/sdk/ai";
2319
- * import type { myChat } from "@/trigger/chat";
2320
- *
2321
- * type Msg = InferChatUIMessage<typeof myChat>;
2322
- * ```
2288
+ * Options for {@link createChatStartSessionAction}.
2323
2289
  */
2324
- export type InferChatUIMessage<TTask extends AnyTask> = TTask extends Task<string, ChatTaskWirePayload<infer TUIM extends UIMessage, any>, any> ? TUIM : UIMessage;
2290
+ export type CreateChatStartSessionActionOptions = {
2291
+ /** TTL for the session-scoped public access token. @default "1h" */
2292
+ tokenTTL?: string | number | Date;
2293
+ /**
2294
+ * Default trigger config used when starting a new session for a chat.
2295
+ * Per-call `params.triggerConfig` shallow-merges on top.
2296
+ */
2297
+ triggerConfig?: Partial<SessionTriggerConfig>;
2298
+ };
2325
2299
  /**
2326
- * Options for {@link createChatTriggerAction}.
2300
+ * Params for the function returned by {@link createChatStartSessionAction}.
2327
2301
  */
2328
- export type CreateChatTriggerActionOptions = {
2329
- /** TTL for the run-scoped public access token. @default "1h" */
2330
- tokenTTL?: string | number | Date;
2302
+ export type ChatStartSessionParams = {
2303
+ /** Conversation id (mapped to the Session's `externalId`). */
2304
+ chatId: string;
2305
+ /**
2306
+ * Per-call trigger config. Shallow-merged over the action's default
2307
+ * `triggerConfig`. `basePayload` is the customer's wire payload (for
2308
+ * `chat.agent`: anything beyond `chatId`/`messages`/`trigger`/`metadata`,
2309
+ * which the runtime injects automatically).
2310
+ */
2311
+ triggerConfig?: Partial<SessionTriggerConfig>;
2312
+ /** Pass-through metadata folded into the session row. */
2313
+ metadata?: Record<string, unknown>;
2331
2314
  };
2332
2315
  /**
2333
- * Creates a function that triggers a chat task and returns a run-scoped session.
2316
+ * Result from {@link createChatStartSessionAction}'s returned function.
2317
+ */
2318
+ export type ChatStartSessionResult = {
2319
+ /**
2320
+ * Session-scoped public access token (`read:sessions:{chatId} +
2321
+ * write:sessions:{chatId}`). Pass this to the browser; the transport
2322
+ * uses it to call `.in/append`, `.out`, `end-and-continue`.
2323
+ */
2324
+ publicAccessToken: string;
2325
+ /** Friendly id of the run triggered alongside session create. */
2326
+ runId: string;
2327
+ /** Session friendlyId — informational. */
2328
+ sessionId: string;
2329
+ };
2330
+ /**
2331
+ * Creates a server-side helper that starts (or resumes) a Session for a
2332
+ * given chatId — atomically creating the row, triggering the first run,
2333
+ * and returning a session-scoped PAT for the browser to use.
2334
2334
  *
2335
- * Wrap the returned function in a Next.js server action (or any server-side handler)
2336
- * to keep task triggering on the server. The function calls `tasks.trigger()` with
2337
- * the secret key and mints a run-scoped PAT for stream subscription + input stream writes.
2335
+ * Wrap in a Next.js server action (or any server-side handler) so the
2336
+ * customer's secret key never crosses to the browser.
2338
2337
  *
2339
2338
  * @example
2340
2339
  * ```ts
@@ -2342,18 +2341,23 @@ export type CreateChatTriggerActionOptions = {
2342
2341
  * "use server";
2343
2342
  * import { chat } from "@trigger.dev/sdk/ai";
2344
2343
  *
2345
- * export const triggerChat = chat.createTriggerAction("my-chat");
2344
+ * export const startChatSession = chat.createStartSessionAction("my-chat", {
2345
+ * triggerConfig: { machine: "small-1x" },
2346
+ * });
2346
2347
  * ```
2347
2348
  *
2348
- * Then pass it to the transport:
2349
+ * Then in the browser:
2349
2350
  * ```tsx
2350
2351
  * const transport = useTriggerChatTransport({
2351
2352
  * task: "my-chat",
2352
- * triggerTask: triggerChat,
2353
+ * accessToken: async ({ chatId }) => {
2354
+ * const { publicAccessToken } = await startChatSession({ chatId });
2355
+ * return publicAccessToken;
2356
+ * },
2353
2357
  * });
2354
2358
  * ```
2355
2359
  */
2356
- declare function createChatTriggerAction(taskId: string, options?: CreateChatTriggerActionOptions): (params: TriggerChatTaskParams) => Promise<TriggerChatTaskResult>;
2360
+ declare function createChatStartSessionAction(taskId: string, options?: CreateChatStartSessionActionOptions): (params: ChatStartSessionParams) => Promise<ChatStartSessionResult>;
2357
2361
  export declare const chat: {
2358
2362
  /** Create a chat agent. See {@link chatAgent}. */
2359
2363
  agent: typeof chatAgent;
@@ -2363,8 +2367,8 @@ export declare const chat: {
2363
2367
  withUIMessage: typeof withUIMessage;
2364
2368
  /** Create a chat task with a fixed client data schema. See {@link withClientData}. */
2365
2369
  withClientData: typeof withClientData;
2366
- /** Create a server-side trigger action helper. See {@link createChatTriggerAction}. */
2367
- createTriggerAction: typeof createChatTriggerAction;
2370
+ /** Create a server-side helper for starting (or resuming) a Session for a chatId. See {@link createChatStartSessionAction}. */
2371
+ createStartSessionAction: typeof createChatStartSessionAction;
2368
2372
  /** Pipe a stream to the chat transport. See {@link pipeChat}. */
2369
2373
  pipe: typeof pipeChat;
2370
2374
  /** Create a per-run typed local. See {@link chatLocal}. */
@@ -2392,7 +2396,7 @@ export declare const chat: {
2392
2396
  /** Queue model messages for injection at the next `prepareStep` boundary. See {@link injectBackgroundContext}. */
2393
2397
  inject: typeof injectBackgroundContext;
2394
2398
  /** Typed chat output stream for writing custom chunks or piping from subtasks. */
2395
- stream: import("@trigger.dev/core/v3").RealtimeDefinedStream<UIMessageChunk>;
2399
+ stream: RealtimeDefinedStream<UIMessageChunk>;
2396
2400
  /** Write data parts that persist to the response message. See {@link chatResponse}. */
2397
2401
  response: {
2398
2402
  /**
@@ -2430,7 +2434,7 @@ export declare const chat: {
2430
2434
  onChange: typeof chatStoreOnChange;
2431
2435
  };
2432
2436
  /** Pre-built input stream for receiving messages from the transport. */
2433
- messages: import("@trigger.dev/core/v3").RealtimeDefinedInputStream<ChatTaskWirePayload<UIMessage<unknown, import("ai").UIDataTypes, import("ai").UITools>, unknown>>;
2437
+ messages: RealtimeDefinedInputStream<ChatTaskWirePayload>;
2434
2438
  /** Create a managed stop signal wired to the stop input stream. See {@link createStopSignal}. */
2435
2439
  createStopSignal: typeof createStopSignal;
2436
2440
  /** Signal the frontend that the current turn is complete. See {@link chatWriteTurnComplete}. */
@@ -2503,4 +2507,10 @@ export declare const chat: {
2503
2507
  compact: typeof chatCompact;
2504
2508
  /** Read the current compaction state (summary + base message count). */
2505
2509
  getCompactionState: typeof getCompactionState;
2510
+ /**
2511
+ * The friendlyId (`session_*`) of the backing Session for the current chat.agent run.
2512
+ * Useful for persisting alongside `runId` so reloads can resume the same session.
2513
+ * Throws if called outside a chat.agent `run()` or hook.
2514
+ */
2515
+ readonly sessionId: string;
2506
2516
  };