@trigger.dev/sdk 0.0.0-chat-prerelease-20260519091352 → 0.0.0-chat-prerelease-20260521151946

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 (38) hide show
  1. package/dist/commonjs/v3/ai.d.ts +183 -12
  2. package/dist/commonjs/v3/ai.js +484 -136
  3. package/dist/commonjs/v3/ai.js.map +1 -1
  4. package/dist/commonjs/v3/auth.d.ts +1 -2
  5. package/dist/commonjs/v3/auth.js.map +1 -1
  6. package/dist/commonjs/v3/chat.js +20 -8
  7. package/dist/commonjs/v3/chat.js.map +1 -1
  8. package/dist/commonjs/v3/createStartSessionAction.test.d.ts +1 -0
  9. package/dist/commonjs/v3/createStartSessionAction.test.js +113 -0
  10. package/dist/commonjs/v3/createStartSessionAction.test.js.map +1 -0
  11. package/dist/commonjs/v3/runs.d.ts +1 -1
  12. package/dist/commonjs/v3/sessions.js +28 -3
  13. package/dist/commonjs/v3/sessions.js.map +1 -1
  14. package/dist/commonjs/v3/shared.js +1 -1
  15. package/dist/commonjs/v3/shared.js.map +1 -1
  16. package/dist/commonjs/v3/test/mock-chat-agent.d.ts +19 -0
  17. package/dist/commonjs/v3/test/mock-chat-agent.js +37 -5
  18. package/dist/commonjs/v3/test/mock-chat-agent.js.map +1 -1
  19. package/dist/commonjs/version.js +1 -1
  20. package/dist/esm/v3/ai.d.ts +183 -12
  21. package/dist/esm/v3/ai.js +482 -136
  22. package/dist/esm/v3/ai.js.map +1 -1
  23. package/dist/esm/v3/auth.d.ts +1 -2
  24. package/dist/esm/v3/auth.js.map +1 -1
  25. package/dist/esm/v3/chat.js +20 -8
  26. package/dist/esm/v3/chat.js.map +1 -1
  27. package/dist/esm/v3/createStartSessionAction.test.d.ts +1 -0
  28. package/dist/esm/v3/createStartSessionAction.test.js +111 -0
  29. package/dist/esm/v3/createStartSessionAction.test.js.map +1 -0
  30. package/dist/esm/v3/sessions.js +28 -3
  31. package/dist/esm/v3/sessions.js.map +1 -1
  32. package/dist/esm/v3/shared.js +1 -1
  33. package/dist/esm/v3/shared.js.map +1 -1
  34. package/dist/esm/v3/test/mock-chat-agent.d.ts +19 -0
  35. package/dist/esm/v3/test/mock-chat-agent.js +38 -6
  36. package/dist/esm/v3/test/mock-chat-agent.js.map +1 -1
  37. package/dist/esm/version.js +1 -1
  38. package/package.json +2 -2
@@ -25,7 +25,11 @@ type ChatTurnContext<TClientData = unknown> = {
25
25
  };
26
26
  export declare function __setReadChatSnapshotImplForTests(impl: ReadChatSnapshotImpl | undefined): void;
27
27
  export declare function __setWriteChatSnapshotImplForTests(impl: WriteChatSnapshotImpl | undefined): void;
28
+ type ReplaySessionOutTailImpl = <TUIMessage extends UIMessage>(sessionId: string, options?: {
29
+ lastEventId?: string;
30
+ }) => Promise<ReplaySessionOutTailResult<TUIMessage>>;
28
31
  export declare function __setReplaySessionOutTailImplForTests(impl: ReplaySessionOutTailImpl | undefined): void;
32
+ export declare function __setReplaySessionInTailImplForTests(impl: ReplaySessionInTailImpl | undefined): void;
29
33
  type ToolResultContent = Array<{
30
34
  type: "text";
31
35
  text: string;
@@ -896,6 +900,123 @@ export type BootEvent<TClientData = unknown> = {
896
900
  /** Whether this run was triggered as a preload. */
897
901
  preloaded: boolean;
898
902
  };
903
+ /**
904
+ * A tool call extracted from the partial assistant message of a dead run.
905
+ * Surfaced on `RecoveryBootEvent.pendingToolCalls` so the customer can
906
+ * decide how to repair the chain (synthesize a result, drop the partial,
907
+ * etc.).
908
+ */
909
+ export type RecoveryPendingToolCall = {
910
+ /** The AI SDK tool call id. */
911
+ toolCallId: string;
912
+ /** The tool name (the `tool-${name}` suffix). */
913
+ toolName: string;
914
+ /** The input the model produced for the tool call. */
915
+ input: unknown;
916
+ /** The part index inside `partialAssistant.parts` for in-place edits. */
917
+ partIndex: number;
918
+ };
919
+ /**
920
+ * Event passed to the `onRecoveryBoot` callback.
921
+ *
922
+ * Fires once at boot when a continuation run inherits in-flight state from
923
+ * a dead predecessor (cancel / crash / OOM / deploy eviction / graceful
924
+ * `chat.requestUpgrade`). The runtime reads both `session.in` and
925
+ * `session.out` past the last `turn-complete` cursor and surfaces the
926
+ * recovered pieces here so the customer can shape the conversational
927
+ * chain before the first turn fires.
928
+ *
929
+ * Does NOT fire when there's nothing to recover (clean continuation after
930
+ * `chat.endRun()` with no buffered user messages, fresh chat, OOM retry
931
+ * after a successful turn-complete with no in-flight tail).
932
+ *
933
+ * Does NOT fire when `hydrateMessages` is registered (the customer owns
934
+ * persistence; recovery decisions live in their own DB query).
935
+ */
936
+ export type RecoveryBootEvent<TUIM extends UIMessage = UIMessage> = {
937
+ /** Task run context — same as `task({ run })` second-argument `ctx`. */
938
+ ctx: TaskRunContext;
939
+ /** The unique identifier for the chat session. */
940
+ chatId: string;
941
+ /** The Trigger.dev run ID for this run boot. */
942
+ runId: string;
943
+ /** Public id of the prior run that died. */
944
+ previousRunId: string;
945
+ /**
946
+ * Best-effort cause of the predecessor's death. Currently always
947
+ * `"unknown"` — the run engine doesn't yet plumb the real reason
948
+ * into the continuation payload. Future SDK versions will narrow
949
+ * this. Don't branch behavior on it yet.
950
+ */
951
+ cause: "cancelled" | "crashed" | "unknown";
952
+ /**
953
+ * The conversation chain that was successfully persisted by the
954
+ * predecessor's last `onTurnComplete`. Empty if the predecessor died
955
+ * before turn 1 ever completed.
956
+ */
957
+ settledMessages: TUIM[];
958
+ /**
959
+ * User messages that arrived on `session.in` past the cursor — i.e.
960
+ * the message(s) the predecessor was processing or had queued when
961
+ * it died. The runtime's default is to re-dispatch each as a fresh
962
+ * turn after the chain is restored. Return a different list via
963
+ * `recoveredTurns` to skip / reorder / collapse them.
964
+ */
965
+ inFlightUsers: TUIM[];
966
+ /**
967
+ * The trailing assistant message the predecessor was streaming when
968
+ * it died — the orphan whose `turn-complete` never fired. Undefined
969
+ * if the predecessor died before any assistant output reached
970
+ * `session.out` (cancel-before-first-token, snapshot-only path).
971
+ */
972
+ partialAssistant: TUIM | undefined;
973
+ /**
974
+ * Tool calls extracted from `partialAssistant.parts` that the model
975
+ * had started but the tool runtime never resolved. Empty when
976
+ * `partialAssistant` is undefined or carries no `input-available`
977
+ * tool parts.
978
+ */
979
+ pendingToolCalls: RecoveryPendingToolCall[];
980
+ /**
981
+ * Lazy session.out writer — identical to the `writer` passed to
982
+ * `onTurnStart` / `onTurnComplete` / `onChatStart`. Use this to emit
983
+ * a recovery signal (e.g. a `data-chat-recovery` UIMessage chunk)
984
+ * BEFORE the first recovered turn fires so the bridge can render a
985
+ * "recovering..." banner. Lazy: no overhead if unused.
986
+ */
987
+ writer: ChatWriter;
988
+ };
989
+ /**
990
+ * Return shape for the `onRecoveryBoot` callback. Every field is optional —
991
+ * omit one to accept the default.
992
+ */
993
+ export type RecoveryBootResult<TUIM extends UIMessage = UIMessage> = {
994
+ /**
995
+ * The chain the new run boots with. Replaces the default
996
+ * (`settledMessages`). Use this to keep the partial assistant in
997
+ * context, mutate its tool parts to inject synthesized results,
998
+ * collapse history, etc.
999
+ *
1000
+ * Ignored when `hydrateMessages` is registered (the hydrate hook
1001
+ * runs per-turn and overwrites the chain).
1002
+ */
1003
+ chain?: TUIM[];
1004
+ /**
1005
+ * The user messages to re-dispatch as fresh turns after the chain is
1006
+ * restored. Default: `inFlightUsers` (re-process every in-flight
1007
+ * user). Return `[]` to suppress all of them; return a filtered /
1008
+ * reordered subset to skip specific ones.
1009
+ */
1010
+ recoveredTurns?: TUIM[];
1011
+ /**
1012
+ * Awaitable run AFTER the writer flushes and BEFORE the first
1013
+ * recovered turn fires. Use for blocking persistence (e.g. write the
1014
+ * partial assistant to your DB so a follow-up turn can reference
1015
+ * it). Errors bubble — wrap your own try/catch if you want to soft-
1016
+ * fail.
1017
+ */
1018
+ beforeBoot?: () => Promise<void>;
1019
+ };
899
1020
  /**
900
1021
  * Event passed to the `onChatStart` callback.
901
1022
  *
@@ -1337,6 +1458,40 @@ export type ChatAgentOptions<TIdentifier extends string, TClientDataSchema exten
1337
1458
  * ```
1338
1459
  */
1339
1460
  onBoot?: (event: BootEvent<inferSchemaOut<TClientDataSchema>>) => Promise<void> | void;
1461
+ /**
1462
+ * Recovery boot hook — fires once on a continuation run that inherited
1463
+ * in-flight state from a dead predecessor (cancel / crash / OOM /
1464
+ * deploy eviction / `chat.requestUpgrade()`). The runtime reads both
1465
+ * stream tails past the last `turn-complete` cursor and hands the
1466
+ * customer the recovered pieces (settled chain, in-flight users,
1467
+ * partial assistant, pending tool calls) so the chain can be shaped
1468
+ * before the first recovered turn fires.
1469
+ *
1470
+ * Does NOT fire when there's nothing to recover — e.g. a clean
1471
+ * continuation after `chat.endRun()` with no buffered user, a fresh
1472
+ * chat, or an OOM retry on top of a complete snapshot.
1473
+ *
1474
+ * Does NOT fire when `hydrateMessages` is registered — that hook owns
1475
+ * the per-turn chain and overlapping recovery decisions belong in the
1476
+ * customer's DB.
1477
+ *
1478
+ * Defaults (returned when the hook is omitted or returns no field):
1479
+ * - `chain` = `settledMessages` (drop the orphan partial)
1480
+ * - `recoveredTurns` = `inFlightUsers` (re-dispatch every user)
1481
+ *
1482
+ * @example
1483
+ * ```ts
1484
+ * onRecoveryBoot: async ({ partialAssistant, inFlightUsers, writer, cause }) => {
1485
+ * writer.write({
1486
+ * type: "data-chat-recovery",
1487
+ * id: generateId(),
1488
+ * data: { cause, partial: partialAssistant?.id },
1489
+ * });
1490
+ * return {}; // accept defaults: drop partial, re-dispatch users
1491
+ * }
1492
+ * ```
1493
+ */
1494
+ onRecoveryBoot?: (event: RecoveryBootEvent<TUIMessage>) => Promise<RecoveryBootResult<TUIMessage> | void> | RecoveryBootResult<TUIMessage> | void;
1340
1495
  /**
1341
1496
  * Called when a preloaded run starts, before the first message arrives.
1342
1497
  *
@@ -2436,9 +2591,17 @@ export type CreateChatStartSessionActionOptions = {
2436
2591
  /**
2437
2592
  * Params for the function returned by {@link createChatStartSessionAction}.
2438
2593
  */
2439
- export type ChatStartSessionParams = {
2594
+ export type ChatStartSessionParams<TChat extends AnyTask = AnyTask> = {
2440
2595
  /** Conversation id (mapped to the Session's `externalId`). */
2441
2596
  chatId: string;
2597
+ /**
2598
+ * Typed client data — folded into the first run's `payload.metadata` so
2599
+ * `onPreload`, `onChatStart`, etc. see the same `clientData` shape on the
2600
+ * first turn as subsequent turns get via the transport's `clientData`
2601
+ * option. Typed via the agent's `clientDataSchema` when the action is
2602
+ * parameterised with `createStartSessionAction<typeof myChat>(...)`.
2603
+ */
2604
+ clientData?: InferChatClientData<TChat>;
2442
2605
  /**
2443
2606
  * Per-call trigger config. Shallow-merged over the action's default
2444
2607
  * `triggerConfig`. `basePayload` is the customer's wire payload (for
@@ -2446,7 +2609,11 @@ export type ChatStartSessionParams = {
2446
2609
  * which the runtime injects automatically).
2447
2610
  */
2448
2611
  triggerConfig?: Partial<SessionTriggerConfig>;
2449
- /** Pass-through metadata folded into the session row. */
2612
+ /**
2613
+ * Opaque session-level metadata stored on the Session row. Separate from
2614
+ * the per-turn `clientData` above. Use this when you want to attach
2615
+ * server-side metadata that doesn't go through the agent's `clientDataSchema`.
2616
+ */
2450
2617
  metadata?: Record<string, unknown>;
2451
2618
  };
2452
2619
  /**
@@ -2472,29 +2639,33 @@ export type ChatStartSessionResult = {
2472
2639
  * Wrap in a Next.js server action (or any server-side handler) so the
2473
2640
  * customer's secret key never crosses to the browser.
2474
2641
  *
2642
+ * Parameterise the action with `<typeof yourChatAgent>` to type the
2643
+ * `clientData` field against your agent's `clientDataSchema`.
2644
+ *
2475
2645
  * @example
2476
2646
  * ```ts
2477
2647
  * // actions.ts
2478
2648
  * "use server";
2479
2649
  * import { chat } from "@trigger.dev/sdk/ai";
2650
+ * import type { myChat } from "@/trigger/chat";
2480
2651
  *
2481
- * export const startChatSession = chat.createStartSessionAction("my-chat", {
2482
- * triggerConfig: { machine: "small-1x" },
2483
- * });
2652
+ * export const startChatSession = chat.createStartSessionAction<typeof myChat>(
2653
+ * "my-chat",
2654
+ * { triggerConfig: { machine: "small-1x" } }
2655
+ * );
2484
2656
  * ```
2485
2657
  *
2486
- * Then in the browser:
2658
+ * Then in the browser, threading the typed `clientData` from the transport:
2487
2659
  * ```tsx
2488
- * const transport = useTriggerChatTransport({
2660
+ * const transport = useTriggerChatTransport<typeof myChat>({
2489
2661
  * task: "my-chat",
2490
- * accessToken: async ({ chatId }) => {
2491
- * const { publicAccessToken } = await startChatSession({ chatId });
2492
- * return publicAccessToken;
2493
- * },
2662
+ * accessToken: ({ chatId }) => mintChatAccessToken(chatId),
2663
+ * startSession: ({ chatId, clientData }) =>
2664
+ * startChatSession({ chatId, clientData }),
2494
2665
  * });
2495
2666
  * ```
2496
2667
  */
2497
- declare function createChatStartSessionAction(taskId: string, options?: CreateChatStartSessionActionOptions): (params: ChatStartSessionParams) => Promise<ChatStartSessionResult>;
2668
+ declare function createChatStartSessionAction<TChat extends AnyTask = AnyTask>(taskId: string, options?: CreateChatStartSessionActionOptions): (params: ChatStartSessionParams<TChat>) => Promise<ChatStartSessionResult>;
2498
2669
  export declare const chat: {
2499
2670
  /** Create a chat agent. See {@link chatAgent}. */
2500
2671
  agent: typeof chatAgent;