@trigger.dev/sdk 4.8.3 → 4.8.4

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 (55) hide show
  1. package/dist/commonjs/v3/ai-shared.d.ts +3 -2
  2. package/dist/commonjs/v3/ai-shared.js +219 -28
  3. package/dist/commonjs/v3/ai-shared.js.map +1 -1
  4. package/dist/commonjs/v3/ai.d.ts +4 -0
  5. package/dist/commonjs/v3/ai.js +97 -87
  6. package/dist/commonjs/v3/ai.js.map +1 -1
  7. package/dist/commonjs/v3/auth.d.ts +1 -3
  8. package/dist/commonjs/v3/auth.js +1 -8
  9. package/dist/commonjs/v3/auth.js.map +1 -1
  10. package/dist/commonjs/v3/chat-server.js +3 -1
  11. package/dist/commonjs/v3/chat-server.js.map +1 -1
  12. package/dist/commonjs/v3/oidc/aws.d.ts +2 -0
  13. package/dist/commonjs/v3/oidc/aws.js +4 -1
  14. package/dist/commonjs/v3/oidc/aws.js.map +1 -1
  15. package/dist/commonjs/v3/oidc/infisical.d.ts +16 -0
  16. package/dist/commonjs/v3/oidc/infisical.js +43 -0
  17. package/dist/commonjs/v3/oidc/infisical.js.map +1 -0
  18. package/dist/commonjs/version.js +1 -1
  19. package/dist/esm/v3/ai-shared.d.ts +3 -2
  20. package/dist/esm/v3/ai-shared.js +214 -28
  21. package/dist/esm/v3/ai-shared.js.map +1 -1
  22. package/dist/esm/v3/ai.d.ts +4 -0
  23. package/dist/esm/v3/ai.js +98 -88
  24. package/dist/esm/v3/ai.js.map +1 -1
  25. package/dist/esm/v3/auth.d.ts +1 -3
  26. package/dist/esm/v3/auth.js +1 -8
  27. package/dist/esm/v3/auth.js.map +1 -1
  28. package/dist/esm/v3/chat-server.js +4 -2
  29. package/dist/esm/v3/chat-server.js.map +1 -1
  30. package/dist/esm/v3/oidc/aws.d.ts +2 -0
  31. package/dist/esm/v3/oidc/aws.js +4 -1
  32. package/dist/esm/v3/oidc/aws.js.map +1 -1
  33. package/dist/esm/v3/oidc/infisical.d.ts +16 -0
  34. package/dist/esm/v3/oidc/infisical.js +40 -0
  35. package/dist/esm/v3/oidc/infisical.js.map +1 -0
  36. package/dist/esm/version.js +1 -1
  37. package/docs/ai-chat/backend.mdx +2 -2
  38. package/docs/ai-chat/custom-agents.mdx +8 -1
  39. package/docs/ai-chat/lifecycle-hooks.mdx +4 -0
  40. package/docs/ai-chat/migrating-from-hydrate-messages.mdx +1 -1
  41. package/docs/ai-chat/transcript-storage.mdx +3 -1
  42. package/docs/apikeys/custom-access.mdx +209 -0
  43. package/docs/apikeys.mdx +50 -14
  44. package/docs/cli-preview-archive.mdx +8 -0
  45. package/docs/deployment/overview.mdx +2 -0
  46. package/docs/deployment/trusted-publishing.mdx +140 -0
  47. package/docs/github-actions.mdx +2 -2
  48. package/docs/oidc/anthropic.mdx +187 -0
  49. package/docs/oidc/aws.mdx +219 -0
  50. package/docs/oidc/custom.mdx +48 -0
  51. package/docs/oidc/infisical.mdx +59 -0
  52. package/docs/oidc.mdx +46 -233
  53. package/docs/self-hosting/env/webapp.mdx +7 -0
  54. package/docs/webhooks/public-beta.mdx +70 -0
  55. package/package.json +17 -2
package/dist/esm/v3/ai.js CHANGED
@@ -23,7 +23,7 @@ let transcriptStorageOverride;
23
23
  export function __setTranscriptStorageForTests(storage) {
24
24
  transcriptStorageOverride = storage;
25
25
  }
26
- import { BACKGROUND_INJECTION_TYPE, PENDING_MESSAGE_INJECTED_TYPE, upsertIncomingMessage, chatRunTags, } from "./ai-shared.js";
26
+ import { BACKGROUND_INJECTION_TYPE, PENDING_MESSAGE_INJECTED_TYPE, upsertIncomingMessage, chatRunTags, dropUnbackedToolResolutions, resolveClientToolResolution, sanitizeClientMessage, sanitizeClientWirePayload, } from "./ai-shared.js";
27
27
  import { auth } from "./auth.js";
28
28
  import { locals } from "./locals.js";
29
29
  import { metadata } from "./metadata.js";
@@ -409,8 +409,10 @@ async function replaySessionInTailWithChannels(sessionId, options) {
409
409
  const payload = chunk.payload;
410
410
  if (!payload || payload.trigger !== "submit-message")
411
411
  continue;
412
- const message = payload.message;
413
- if (!message || typeof message !== "object") {
412
+ const message = payload.message && typeof payload.message === "object"
413
+ ? sanitizeClientMessage(payload.message)
414
+ : undefined;
415
+ if (!message) {
414
416
  if (payload.channelEvent && typeof payload.channelEvent === "object") {
415
417
  channelEvents.push({
416
418
  channelEvent: payload.channelEvent,
@@ -1795,7 +1797,7 @@ async function installChatInputRouter(chatId, options) {
1795
1797
  // re-deliver below it and a replayable route would re-queue it.
1796
1798
  if (floor !== undefined && record.seqNum <= floor)
1797
1799
  return true;
1798
- router.ingest(record);
1800
+ router.ingest(sanitizeChatInputRecord(record));
1799
1801
  return true;
1800
1802
  });
1801
1803
  entry.attached = true;
@@ -1823,6 +1825,21 @@ function chatInputRouterEntry(chatId) {
1823
1825
  };
1824
1826
  return currentChatInputRouter;
1825
1827
  }
1828
+ /**
1829
+ * Reduce the client-supplied message on a `kind: "message"` record to what a client may send, before
1830
+ * any consumer sees it. See `sanitizeClientMessage`.
1831
+ * @internal
1832
+ */
1833
+ function sanitizeChatInputRecord(record) {
1834
+ const chunk = record.data;
1835
+ if (!chunk || typeof chunk !== "object" || chunk.kind !== "message")
1836
+ return record;
1837
+ const payload = chunk.payload;
1838
+ if (!payload || typeof payload !== "object")
1839
+ return record;
1840
+ const sanitized = sanitizeClientWirePayload(payload);
1841
+ return sanitized === payload ? record : { ...record, data: { ...chunk, payload: sanitized } };
1842
+ }
1826
1843
  /** Drop the router so the next boot attaches a fresh one. @internal */
1827
1844
  export function __resetChatInputRouterForTests() {
1828
1845
  currentChatInputRouter = undefined;
@@ -2020,54 +2037,6 @@ const chatChannelDownloadKey = locals.create("chat.channelDownload");
2020
2037
  const chatUIStreamStaticKey = locals.create("chat.uiMessageStreamOptions.static");
2021
2038
  /** Per-turn UIMessageStream options, set via chat.setUIMessageStreamOptions(). @internal */
2022
2039
  const chatUIStreamPerTurnKey = locals.create("chat.uiMessageStreamOptions.perTurn");
2023
- /**
2024
- * Run-scoped `toolCallId → assistant messageId` map. Records the head
2025
- * assistant id whenever the accumulator absorbs an assistant message
2026
- * containing tool parts. Used as a fallback in the id-merge for
2027
- * incoming tool-answer messages — if the AI SDK regenerates the
2028
- * assistant id on a HITL `addToolOutput` resume, we look up the
2029
- * original head id by `toolCallId` and rewrite it before the merge.
2030
- *
2031
- * Customer-side workaround for the same case is documented in Arena
2032
- * AI's chat-agent task; lifting it into the SDK so customers don't
2033
- * have to. See TRI-9137.
2034
- * @internal
2035
- */
2036
- const chatToolCallToMessageIdKey = locals.create("chat.toolCallToMessageId");
2037
- function recordToolCallIdsFromMessage(message) {
2038
- if (!message || message.role !== "assistant" || !message.id)
2039
- return;
2040
- let map = locals.get(chatToolCallToMessageIdKey);
2041
- if (!map) {
2042
- map = new Map();
2043
- locals.set(chatToolCallToMessageIdKey, map);
2044
- }
2045
- for (const part of message.parts ?? []) {
2046
- if (typeof part !== "object" || part == null)
2047
- continue;
2048
- const toolCallId = part.toolCallId;
2049
- if (typeof toolCallId === "string" && toolCallId.length > 0) {
2050
- map.set(toolCallId, message.id);
2051
- }
2052
- }
2053
- }
2054
- function rewriteIncomingIdViaToolCallMap(incoming) {
2055
- const map = locals.get(chatToolCallToMessageIdKey);
2056
- if (!map || map.size === 0)
2057
- return incoming;
2058
- for (const part of incoming.parts ?? []) {
2059
- if (typeof part !== "object" || part == null)
2060
- continue;
2061
- const toolCallId = part.toolCallId;
2062
- if (typeof toolCallId !== "string" || toolCallId.length === 0)
2063
- continue;
2064
- const headId = map.get(toolCallId);
2065
- if (headId && headId !== incoming.id) {
2066
- return { ...incoming, id: headId };
2067
- }
2068
- }
2069
- return incoming;
2070
- }
2071
2040
  function emptyUsage() {
2072
2041
  return {
2073
2042
  inputTokens: undefined,
@@ -2360,6 +2329,31 @@ function mergeIncomingIntoHydrated(hydrated, incoming) {
2360
2329
  return hydrated;
2361
2330
  return { ...hydrated, parts: mergedParts };
2362
2331
  }
2332
+ /**
2333
+ * Keep the incoming messages a client may add this turn: user messages, and tool resolutions that
2334
+ * answer a call in `history`, re-addressed to the stored message holding it. Anything else is dropped.
2335
+ *
2336
+ * @internal
2337
+ */
2338
+ function resolveIncomingAgainstHistory(incoming, history) {
2339
+ const out = [];
2340
+ for (const message of incoming) {
2341
+ const resolved = message.role === "user"
2342
+ ? message
2343
+ : message.role === "assistant"
2344
+ ? resolveClientToolResolution(message, history)
2345
+ : undefined;
2346
+ if (resolved) {
2347
+ out.push(resolved);
2348
+ continue;
2349
+ }
2350
+ logger.warn("chat.agent: dropped an incoming message that answers no pending tool call", {
2351
+ messageId: message.id,
2352
+ role: message.role,
2353
+ });
2354
+ }
2355
+ return out;
2356
+ }
2363
2357
  /**
2364
2358
  * Mirror of `slimSubmitMessageForWire`'s predicate. Kept here so the
2365
2359
  * agent runtime doesn't have to import from `ai-shared.ts` for a
@@ -4806,6 +4800,7 @@ function chatCustomAgent(options) {
4806
4800
  triggerSource: "agent",
4807
4801
  agentConfig: { type: "ai-sdk-chat" },
4808
4802
  run: async (payload, runOptions) => {
4803
+ payload = sanitizeClientWirePayload(payload);
4809
4804
  // Bind the run to its backing Session so module-level helpers
4810
4805
  // (chat.messages, chat.stream, chat.createStopSignal, chat.createSession)
4811
4806
  // resolve to this chat's `.in` / `.out` channels. Address
@@ -4951,6 +4946,7 @@ function chatAgent(options) {
4951
4946
  triggerSource: "agent",
4952
4947
  agentConfig: { type: "ai-sdk-chat" },
4953
4948
  run: async (payload, { signal: runSignal, ctx }) => {
4949
+ payload = sanitizeClientWirePayload(payload);
4954
4950
  locals.set(chatAgentRunContextKey, ctx);
4955
4951
  locals.set(chatCustomAgentRunKey, false);
4956
4952
  // On AI SDK 7, register the `@ai-sdk/otel` integration (once per process)
@@ -5585,6 +5581,7 @@ function chatAgent(options) {
5585
5581
  const oldestTailSeq = Math.min(...replayedInTail.map((r) => r.seqNum), ...replayedChannelInTail.map((r) => r.seqNum));
5586
5582
  const partialFollowsBrowserMessage = partialAssistant !== undefined &&
5587
5583
  inFlightUsers.length > 1 &&
5584
+ inFlightUsers[0].role === "user" &&
5588
5585
  (replayedChannelInTail.length === 0 || replayedInTail[0]?.seqNum === oldestTailSeq);
5589
5586
  if (hookChain !== undefined) {
5590
5587
  seedChain = hookChain;
@@ -6226,7 +6223,9 @@ function chatAgent(options) {
6226
6223
  const { metadata: wireMetadata, message: incomingMessage, headStartMessages: _hsm, channelEvent: wireChannelEvent, ...restWire } = currentWirePayload;
6227
6224
  void _hsm;
6228
6225
  channelWireEvent = wireChannelEvent;
6229
- let effectiveIncomingMessage = incomingMessage;
6226
+ let effectiveIncomingMessage = incomingMessage === undefined
6227
+ ? undefined
6228
+ : sanitizeClientMessage(incomingMessage);
6230
6229
  const clientData = (parseClientData ? await parseClientData(wireMetadata) : wireMetadata);
6231
6230
  turnClientData = clientData;
6232
6231
  turnIsActionTurn = false;
@@ -6684,7 +6683,7 @@ function chatAgent(options) {
6684
6683
  // with the new user message in `.message`, or no message
6685
6684
  // at all (regenerate / preload / close / handover-prepare).
6686
6685
  const lastUIMessage = (steeredChannel?.message ?? msg.message);
6687
- if (lastUIMessage) {
6686
+ if (lastUIMessage && lastUIMessage.role === "user") {
6688
6687
  if (pmConfig.onReceived) {
6689
6688
  try {
6690
6689
  await pmConfig.onReceived({
@@ -6892,6 +6891,9 @@ function chatAgent(options) {
6892
6891
  payload.headStartMessages.length > 0) {
6893
6892
  cleanedUIMessages = payload.headStartMessages;
6894
6893
  }
6894
+ if (!loadContextHook) {
6895
+ cleanedUIMessages = resolveIncomingAgainstHistory(cleanedUIMessages, accumulatedUIMessages);
6896
+ }
6895
6897
  // Validate/transform UIMessages before conversion — catches malformed
6896
6898
  // messages from storage or untrusted input before they reach the model.
6897
6899
  // Slim wire: triggers like `regenerate-message` carry no incoming
@@ -6961,8 +6963,10 @@ function chatAgent(options) {
6961
6963
  // copy to fit the .in/append cap (or drop fields they
6962
6964
  // re-source from their own DB) get the hydrated copy
6963
6965
  // through unchanged.
6964
- const merged = [...hydrated];
6965
- for (const incoming of cleanedUIMessages) {
6966
+ const hydratedChain = dropUnbackedToolResolutions(hydrated);
6967
+ const resolvedIncoming = resolveIncomingAgainstHistory(cleanedUIMessages, hydratedChain);
6968
+ const merged = [...hydratedChain];
6969
+ for (const incoming of resolvedIncoming) {
6966
6970
  if (!incoming.id)
6967
6971
  continue;
6968
6972
  const idx = merged.findIndex((m) => m.id === incoming.id);
@@ -6989,8 +6993,8 @@ function chatAgent(options) {
6989
6993
  // the same "push only on append" semantic via its
6990
6994
  // own append-vs-replace path.
6991
6995
  if (currentWirePayload.trigger === "submit-message" &&
6992
- cleanedUIMessages.length > 0) {
6993
- const lastUI = cleanedUIMessages[cleanedUIMessages.length - 1];
6996
+ resolvedIncoming.length > 0) {
6997
+ const lastUI = resolvedIncoming[resolvedIncoming.length - 1];
6994
6998
  const matchedExisting = lastUI.id !== undefined && previouslyKnownMessageIds.has(lastUI.id);
6995
6999
  if (!matchedExisting) {
6996
7000
  turnNewUIMessages.push(lastUI);
@@ -7033,21 +7037,10 @@ function chatAgent(options) {
7033
7037
  // in the accumulator — we merge the resolved tool-part
7034
7038
  // resolutions onto the existing entry, keeping text,
7035
7039
  // reasoning, and tool `input` from the prior snapshot.
7036
- // The fallback for HITL `addToolOutput` continuations
7037
- // where AI SDK regenerates the id (TRI-9137) still
7038
- // applies via `rewriteIncomingIdViaToolCallMap`.
7039
7040
  let replaced = false;
7040
7041
  const replacedPairs = [];
7041
- for (const raw of cleanedUIMessages) {
7042
- let incoming = raw;
7043
- let idx = accumulatedUIMessages.findIndex((m) => m.id === incoming.id);
7044
- if (idx === -1) {
7045
- const rewritten = rewriteIncomingIdViaToolCallMap(incoming);
7046
- if (rewritten.id !== incoming.id) {
7047
- incoming = rewritten;
7048
- idx = accumulatedUIMessages.findIndex((m) => m.id === incoming.id);
7049
- }
7050
- }
7042
+ for (const incoming of cleanedUIMessages) {
7043
+ const idx = accumulatedUIMessages.findIndex((m) => m.id === incoming.id);
7051
7044
  if (idx !== -1) {
7052
7045
  const previous = accumulatedUIMessages[idx];
7053
7046
  accumulatedUIMessages[idx] = mergeIncomingIntoHydrated(previous, incoming);
@@ -7058,7 +7051,6 @@ function chatAgent(options) {
7058
7051
  accumulatedUIMessages.push(incoming);
7059
7052
  turnNewUIMessages.push(incoming);
7060
7053
  }
7061
- recordToolCallIdsFromMessage(incoming);
7062
7054
  }
7063
7055
  if (replaced) {
7064
7056
  let inPlace = true;
@@ -7766,12 +7758,6 @@ function chatAgent(options) {
7766
7758
  }
7767
7759
  turnNewUIMessages.push(capturedResponseMessage);
7768
7760
  locals.set(chatCurrentUIMessagesKey, accumulatedUIMessages);
7769
- // Record toolCallId → head messageId so a HITL
7770
- // continuation next turn can recover the head id
7771
- // even if the AI SDK regenerates it. See
7772
- // `chatToolCallToMessageIdKey` for the full
7773
- // rationale (TRI-9137).
7774
- recordToolCallIdsFromMessage(capturedResponseMessage);
7775
7761
  try {
7776
7762
  const responseForModel = responseAfterCompaction(capturedResponseMessage, responseCompaction?.baseResponseStepCount, originalResponse);
7777
7763
  // Preserve the complete persistence response, including same-ID
@@ -9925,18 +9911,42 @@ class ChatMessageAccumulator {
9925
9911
  /**
9926
9912
  * Add incoming messages from the transport payload.
9927
9913
  * Returns the full accumulated model messages for `streamText`.
9914
+ *
9915
+ * A tool approval or tool output from the client (a tool part with no `input`) is merged onto the
9916
+ * stored call it answers, found in the accumulator or earlier in `messages`. One that answers no
9917
+ * pending call is dropped.
9928
9918
  */
9929
9919
  async addIncoming(messages, trigger, turn) {
9930
- const cleaned = messages.map((m) => (m.role === "assistant" ? cleanupAbortedParts(m) : m));
9931
- const model = await toModelMessages(cleaned);
9932
- if (turn === 0 || trigger === "regenerate-message") {
9933
- this.modelMessages = model;
9934
- this.uiMessages = [...cleaned];
9935
- }
9936
- else {
9937
- this.modelMessages.push(...model);
9938
- this.uiMessages.push(...cleaned);
9920
+ const replace = turn === 0 || trigger === "regenerate-message";
9921
+ const ui = replace ? [] : [...this.uiMessages];
9922
+ const lane = replace ? [] : [...this.modelMessages];
9923
+ let appendedModelCount = 0;
9924
+ let rebuild = replace;
9925
+ for (const raw of messages) {
9926
+ const message = raw.role === "assistant" ? cleanupAbortedParts(raw) : raw;
9927
+ const resolved = resolveClientToolResolution(message, ui);
9928
+ if (!resolved) {
9929
+ logger.warn("chat.MessageAccumulator: dropped an incoming message that answers no pending tool call", { messageId: message.id });
9930
+ continue;
9931
+ }
9932
+ if (resolved !== message) {
9933
+ const idx = ui.findIndex((m) => m.id === resolved.id);
9934
+ const previous = ui[idx];
9935
+ ui[idx] = mergeIncomingIntoHydrated(previous, resolved);
9936
+ if (!rebuild && !(await replaceModelRun(lane, previous, ui[idx], appendedModelCount))) {
9937
+ rebuild = true;
9938
+ }
9939
+ continue;
9940
+ }
9941
+ ui.push(message);
9942
+ if (!rebuild) {
9943
+ const converted = await toModelMessages([message]);
9944
+ lane.push(...converted);
9945
+ appendedModelCount += converted.length;
9946
+ }
9939
9947
  }
9948
+ this.uiMessages = ui;
9949
+ this.modelMessages = rebuild ? await toModelMessages(ui) : lane;
9940
9950
  return this.modelMessages;
9941
9951
  }
9942
9952
  /**
@@ -10458,7 +10468,7 @@ function createChatSession(payload, options) {
10458
10468
  */
10459
10469
  const handleSteeringMessage = async (msg, seqNum, isActive = () => true) => {
10460
10470
  const lastUIMessage = msg.message;
10461
- if (lastUIMessage) {
10471
+ if (lastUIMessage && lastUIMessage.role === "user") {
10462
10472
  if (sessionPendingMessages?.onReceived) {
10463
10473
  try {
10464
10474
  await sessionPendingMessages.onReceived({