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

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.
@@ -1,12 +1,14 @@
1
1
  import { AnyTask, Task, type inferSchemaIn, type inferSchemaOut, type TaskIdentifier, type TaskOptions, type TaskSchema, type TaskRunContext, type TaskWithSchema } from "@trigger.dev/core/v3";
2
- import type { ModelMessage, ToolSet, UIMessage, UIMessageChunk, UIMessageStreamOptions, LanguageModelUsage } from "ai";
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
+ import type { ResolvedSkill } from "./skill.js";
6
7
  import type { TriggerChatTaskParams, TriggerChatTaskResult } from "./chat.js";
7
8
  /** Re-export for typing `ctx` in `chat.agent` hooks without importing `@trigger.dev/core`. */
8
9
  export type { TaskRunContext } from "@trigger.dev/core/v3";
9
10
  import { CHAT_MESSAGES_STREAM_ID, CHAT_STOP_STREAM_ID } from "./chat-constants.js";
11
+ import { type ChatStorePatchOperation } from "@trigger.dev/core/v3/chat-client";
10
12
  export type ToolCallExecutionOptions = {
11
13
  toolCallId: string;
12
14
  experimental_context?: unknown;
@@ -138,6 +140,29 @@ declare function createChatAccessToken<TTask extends AnyTask>(taskId: TaskIdenti
138
140
  */
139
141
  export declare const CHAT_STREAM_KEY = "chat";
140
142
  export { CHAT_MESSAGES_STREAM_ID, CHAT_STOP_STREAM_ID };
143
+ /**
144
+ * Listener fired when the store value changes. `operations` is present for
145
+ * `patch()` updates and absent for `set()` (which is a full snapshot).
146
+ */
147
+ export type ChatStoreChangeListener<TStore = unknown> = (value: TStore, operations?: ChatStorePatchOperation[]) => void;
148
+ /**
149
+ * Replace the entire store value with `value`. Emits a `store-snapshot`
150
+ * chunk on the chat output stream and fires all `onChange` listeners.
151
+ */
152
+ declare function chatStoreSet<TStore = unknown>(value: TStore): void;
153
+ /**
154
+ * Apply RFC 6902 JSON Patch operations to the current store value.
155
+ * Emits a `store-delta` chunk on the chat output stream and fires all
156
+ * `onChange` listeners with the new value and the operations.
157
+ */
158
+ declare function chatStorePatch(operations: ChatStorePatchOperation[]): void;
159
+ /** Get the current store value. Returns `undefined` if no value has been set. */
160
+ declare function chatStoreGet<TStore = unknown>(): TStore | undefined;
161
+ /**
162
+ * Subscribe to store changes for the current run. Returns an
163
+ * unsubscribe function.
164
+ */
165
+ declare function chatStoreOnChange<TStore = unknown>(listener: ChatStoreChangeListener<TStore>): () => void;
141
166
  /**
142
167
  * A stream writer passed to chat lifecycle callbacks (`onPreload`, `onChatStart`,
143
168
  * `onTurnStart`, `onTurnComplete`, `onCompacted`).
@@ -181,6 +206,16 @@ export type ChatTaskWirePayload<TMessage extends UIMessage = UIMessage, TMetadat
181
206
  previousRunId?: string;
182
207
  /** Override idle timeout for this run (seconds). Set by transport.preload(). */
183
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;
184
219
  };
185
220
  /**
186
221
  * The payload shape passed to the `chatAgent` run function.
@@ -202,8 +237,12 @@ export type ChatTaskPayload<TClientData = unknown> = {
202
237
  * - `"submit-message"`: A new user message
203
238
  * - `"regenerate-message"`: Regenerate the last assistant response
204
239
  * - `"preload"`: Run was preloaded before the first message (only on turn 0)
240
+ * - `"action"`: A typed action from the frontend (see `actionSchema` + `onAction`).
241
+ * The action has already been applied before `run()` fires — check `trigger === "action"`
242
+ * to short-circuit the LLM call when an action doesn't need a response.
243
+ * - `"close"`: The chat session is being closed (internal; `run()` is not called).
205
244
  */
206
- trigger: "submit-message" | "regenerate-message" | "preload" | "close";
245
+ trigger: "submit-message" | "regenerate-message" | "preload" | "action" | "close";
207
246
  /** The ID of the message to regenerate (only for `"regenerate-message"`) */
208
247
  messageId?: string;
209
248
  /** Custom data from the frontend (passed via `metadata` on `sendMessage()` or the transport). */
@@ -669,6 +708,21 @@ declare function setChatPrompt(resolved: ResolvedPrompt | string): void;
669
708
  * Read the stored prompt. Throws if `chat.prompt.set()` has not been called.
670
709
  */
671
710
  declare function getChatPrompt(): ChatPromptValue;
711
+ /**
712
+ * Store resolved skills for the current run. Call from any hook
713
+ * (`onPreload`, `onChatStart`, `onTurnStart`) or `run()`.
714
+ */
715
+ declare function setChatSkills(skills: ResolvedSkill[]): void;
716
+ /** Read the stored skills. Returns `undefined` if none set. */
717
+ declare function getChatSkills(): ResolvedSkill[] | undefined;
718
+ /**
719
+ * Build the three tools we auto-inject into `streamText` when skills are
720
+ * set: `loadSkill`, `readFile`, `bash`. Scoped per-skill by name.
721
+ *
722
+ * Exported so callers can use the same tools outside the auto-wired path
723
+ * (e.g. in a `chat.createSession` loop with custom streamText).
724
+ */
725
+ export declare function buildSkillTools(skills: ResolvedSkill[]): Record<string, Tool>;
672
726
  /**
673
727
  * Options for {@link toStreamTextOptions}.
674
728
  */
@@ -687,6 +741,16 @@ export type ToStreamTextOptionsOptions = {
687
741
  registry?: {
688
742
  languageModel(modelId: string): unknown;
689
743
  };
744
+ /**
745
+ * User-defined tools to merge alongside the auto-injected skill tools
746
+ * (`loadSkill`, `readFile`, `bash`). User tools win on name conflicts.
747
+ *
748
+ * If you don't pass `tools` here and skills are set, the returned options
749
+ * will include just the skill tools — spread after any `tools` you pass
750
+ * directly to `streamText` and they'll be replaced. Easiest: pass all
751
+ * your tools here.
752
+ */
753
+ tools?: Record<string, Tool>;
690
754
  };
691
755
  /**
692
756
  * Returns an options object ready to spread into `streamText()`.
@@ -861,6 +925,37 @@ export type HydrateMessagesEvent<TClientData = unknown, TUIM extends UIMessage =
861
925
  /** The ID of the previous run (if continuation). */
862
926
  previousRunId?: string;
863
927
  };
928
+ /**
929
+ * Event passed to the `hydrateStore` callback.
930
+ *
931
+ * Called at turn start — before `run()` fires and before any incoming store
932
+ * from the wire payload is applied. Return the authoritative store value
933
+ * for this turn; it becomes the initial value `chat.store.get()` sees.
934
+ */
935
+ export type HydrateStoreEvent<TClientData = unknown, TStore = unknown> = {
936
+ /** The unique identifier for the chat session. */
937
+ chatId: string;
938
+ /** The turn number (0-indexed). */
939
+ turn: number;
940
+ /** The trigger type for this turn. */
941
+ trigger: "submit-message" | "regenerate-message" | "action" | "preload";
942
+ /**
943
+ * The in-memory store value from the previous turn of this run
944
+ * (`undefined` on turn 0 and after continuations).
945
+ */
946
+ previousStore: TStore | undefined;
947
+ /**
948
+ * The store value the transport sent with this turn, if any.
949
+ * Usually set by client-side `setStore` / `applyStorePatch`.
950
+ */
951
+ incomingStore: TStore | undefined;
952
+ /** Parsed client data from the transport metadata. */
953
+ clientData?: TClientData;
954
+ /** Whether this run is continuing from a previous run. */
955
+ continuation: boolean;
956
+ /** The ID of the previous run (if continuation). */
957
+ previousRunId?: string;
958
+ };
864
959
  /**
865
960
  * Event passed to the `onValidateMessages` callback.
866
961
  */
@@ -979,6 +1074,22 @@ export type TurnCompleteEvent<TClientData = unknown, TUIM extends UIMessage = UI
979
1074
  usage?: LanguageModelUsage;
980
1075
  /** Cumulative token usage across all turns in this run (including this turn). */
981
1076
  totalUsage: LanguageModelUsage;
1077
+ /**
1078
+ * Why the LLM stopped generating this turn:
1079
+ * - `"stop"` — model generated a stop sequence (normal completion)
1080
+ * - `"tool-calls"` — model stopped on one or more tool calls. If any tool
1081
+ * has no `execute` function (e.g. an `ask_user` HITL tool), the turn is
1082
+ * paused awaiting user input; inspect `responseMessage.parts` for tool
1083
+ * parts in `input-available` state to distinguish.
1084
+ * - `"length"` — max tokens reached
1085
+ * - `"content-filter"` — content filter stopped the model
1086
+ * - `"error"` — model errored
1087
+ * - `"other"` — provider-specific reason
1088
+ *
1089
+ * Undefined if the underlying stream didn't provide a finish reason (e.g.
1090
+ * manual `pipeChat()` or an aborted stream).
1091
+ */
1092
+ finishReason?: FinishReason;
982
1093
  };
983
1094
  /**
984
1095
  * Event passed to the `onBeforeTurnComplete` callback.
@@ -1212,6 +1323,43 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1212
1323
  * ```
1213
1324
  */
1214
1325
  hydrateMessages?: (event: HydrateMessagesEvent<inferSchemaOut<TClientDataSchema>, TUIMessage>) => TUIMessage[] | Promise<TUIMessage[]>;
1326
+ /**
1327
+ * Load the `chat.store` value for this turn from your backend.
1328
+ *
1329
+ * The store lives in memory on the agent instance for the lifetime of
1330
+ * the run. After a continuation (idle timeout, `chat.requestUpgrade`,
1331
+ * max turns), a new run starts with an empty store — this hook lets
1332
+ * you restore it from your own persistence layer.
1333
+ *
1334
+ * Runs at turn start, before `run()` fires. The returned value replaces
1335
+ * the in-memory store and is emitted as a `store-snapshot` chunk so the
1336
+ * frontend sees the initial value.
1337
+ *
1338
+ * If both `hydrateStore` and `incomingStore` (from the wire payload) are
1339
+ * present, `incomingStore` wins — it represents the client's latest
1340
+ * local state and follows AG-UI's last-write-wins policy.
1341
+ *
1342
+ * @example
1343
+ * ```ts
1344
+ * chat.agent({
1345
+ * id: "my-chat",
1346
+ * hydrateStore: async ({ chatId, previousRunId }) => {
1347
+ * return db.chatStore.findUnique({ where: { chatId } })?.value;
1348
+ * },
1349
+ * onTurnComplete: async ({ chatId }) => {
1350
+ * await db.chatStore.upsert({
1351
+ * where: { chatId },
1352
+ * update: { value: chat.store.get() },
1353
+ * create: { chatId, value: chat.store.get() },
1354
+ * });
1355
+ * },
1356
+ * run: async ({ messages, signal }) => {
1357
+ * return streamText({ model: openai("gpt-4o"), messages, abortSignal: signal });
1358
+ * },
1359
+ * });
1360
+ * ```
1361
+ */
1362
+ hydrateStore?: (event: HydrateStoreEvent<inferSchemaOut<TClientDataSchema>>) => unknown | Promise<unknown>;
1215
1363
  /**
1216
1364
  * Called at the start of every turn, after message accumulation and `onChatStart` (turn 0),
1217
1365
  * but before the `run` function executes.
@@ -1744,6 +1892,33 @@ declare function isStopped(): boolean;
1744
1892
  * ```
1745
1893
  */
1746
1894
  declare function requestUpgrade(): void;
1895
+ /**
1896
+ * Exit the run after the current turn completes, without waiting for the
1897
+ * next message. Unlike {@link requestUpgrade}, no upgrade-required signal
1898
+ * is sent to the client — the turn finishes normally, `onTurnComplete`
1899
+ * fires, and the loop exits instead of going idle.
1900
+ *
1901
+ * Call from `run()`, `chat.defer()`, `onBeforeTurnComplete`, or
1902
+ * `onTurnComplete` to end the run on your own terms (budget exhausted,
1903
+ * task complete, goal achieved, etc.).
1904
+ *
1905
+ * The next user message on the same `chatId` starts a fresh run via the
1906
+ * normal continuation mechanism.
1907
+ *
1908
+ * @example
1909
+ * ```ts
1910
+ * chat.agent({
1911
+ * id: "one-shot-agent",
1912
+ * run: async ({ messages, signal }) => {
1913
+ * const result = streamText({ model: openai("gpt-4o"), messages, abortSignal: signal });
1914
+ * // Single-response agent — exit after this turn.
1915
+ * chat.endRun();
1916
+ * return result;
1917
+ * },
1918
+ * });
1919
+ * ```
1920
+ */
1921
+ declare function endRun(): void;
1747
1922
  /**
1748
1923
  * Register a promise that runs in the background during the current turn.
1749
1924
  *
@@ -2208,6 +2383,8 @@ export declare const chat: {
2208
2383
  isStopped: typeof isStopped;
2209
2384
  /** Request that the run exits after the current turn so the next message starts on the latest version. See {@link requestUpgrade}. */
2210
2385
  requestUpgrade: typeof requestUpgrade;
2386
+ /** Exit the run after the current turn completes, without any upgrade signal. See {@link endRun}. */
2387
+ endRun: typeof endRun;
2211
2388
  /** Clean up aborted parts from a UIMessage. See {@link cleanupAbortedParts}. */
2212
2389
  cleanupAbortedParts: typeof cleanupAbortedParts;
2213
2390
  /** Register background work that runs in parallel with streaming. See {@link chatDefer}. */
@@ -2224,6 +2401,34 @@ export declare const chat: {
2224
2401
  */
2225
2402
  write(part: UIMessageChunk): void;
2226
2403
  };
2404
+ /**
2405
+ * Typed, bidirectional shared data slot for the chat.
2406
+ *
2407
+ * Use from `chat.agent` hooks and `run()` to share state with the client.
2408
+ * Setting emits a `store-snapshot` chunk; patching emits `store-delta`.
2409
+ * The value persists across turns within the same run, and can be
2410
+ * restored after continuations via the `hydrateStore` config option.
2411
+ *
2412
+ * ```ts
2413
+ * chat.store.set({ plan: ["research", "draft", "review"] });
2414
+ * chat.store.patch([{ op: "replace", path: "/status", value: "done" }]);
2415
+ * const current = chat.store.get();
2416
+ * const off = chat.store.onChange((value, ops) => { ... });
2417
+ * ```
2418
+ */
2419
+ store: {
2420
+ /** Replace the store value. Emits a `store-snapshot` chunk. */
2421
+ set: typeof chatStoreSet;
2422
+ /**
2423
+ * Apply RFC 6902 JSON Patch operations to the current value.
2424
+ * Emits a `store-delta` chunk.
2425
+ */
2426
+ patch: typeof chatStorePatch;
2427
+ /** Read the current store value. Returns `undefined` if never set. */
2428
+ get: typeof chatStoreGet;
2429
+ /** Subscribe to store changes. Returns an unsubscribe function. */
2430
+ onChange: typeof chatStoreOnChange;
2431
+ };
2227
2432
  /** Pre-built input stream for receiving messages from the transport. */
2228
2433
  messages: import("@trigger.dev/core/v3").RealtimeDefinedInputStream<ChatTaskWirePayload<UIMessage<unknown, import("ai").UIDataTypes, import("ai").UITools>, unknown>>;
2229
2434
  /** Create a managed stop signal wired to the stop input stream. See {@link createStopSignal}. */
@@ -2245,6 +2450,20 @@ export declare const chat: {
2245
2450
  prompt: typeof getChatPrompt & {
2246
2451
  set: typeof setChatPrompt;
2247
2452
  };
2453
+ /**
2454
+ * Store and retrieve resolved agent skills for the current run.
2455
+ *
2456
+ * - `chat.skills.set([...])` — store an array of `ResolvedSkill`s
2457
+ * - `chat.skills()` — read the stored skills (returns undefined if none)
2458
+ *
2459
+ * Skills set here are automatically injected into `streamText` by
2460
+ * `chat.toStreamTextOptions()`: skill descriptions land in the system
2461
+ * prompt and `loadSkill` / `readFile` / `bash` tools are added to the
2462
+ * tool set.
2463
+ */
2464
+ skills: typeof getChatSkills & {
2465
+ set: typeof setChatSkills;
2466
+ };
2248
2467
  /**
2249
2468
  * Returns an options object ready to spread into `streamText()`.
2250
2469
  * Reads the stored prompt and returns `{ system, experimental_telemetry, ...config }`.