@trigger.dev/sdk 4.8.0 → 4.8.2
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.
- package/dist/commonjs/v3/ai-shared.d.ts +6 -0
- package/dist/commonjs/v3/ai-shared.js +7 -1
- package/dist/commonjs/v3/ai-shared.js.map +1 -1
- package/dist/commonjs/v3/ai.d.ts +45 -0
- package/dist/commonjs/v3/ai.js +110 -69
- package/dist/commonjs/v3/ai.js.map +1 -1
- package/dist/commonjs/v3/auth.d.ts +2 -1
- package/dist/commonjs/v3/auth.js +18 -12
- package/dist/commonjs/v3/auth.js.map +1 -1
- package/dist/commonjs/v3/chat-client.d.ts +11 -2
- package/dist/commonjs/v3/chat-client.js +28 -10
- package/dist/commonjs/v3/chat-client.js.map +1 -1
- package/dist/commonjs/v3/chat-react.d.ts +21 -0
- package/dist/commonjs/v3/chat-react.js +86 -30
- package/dist/commonjs/v3/chat-react.js.map +1 -1
- package/dist/commonjs/v3/chat.d.ts +1 -0
- package/dist/commonjs/v3/chat.js +4 -1
- package/dist/commonjs/v3/chat.js.map +1 -1
- package/dist/commonjs/v3/managedChatResponse.d.ts +13 -5
- package/dist/commonjs/v3/managedChatResponse.js +36 -18
- package/dist/commonjs/v3/managedChatResponse.js.map +1 -1
- package/dist/commonjs/v3/steeringContext.d.ts +11 -0
- package/dist/commonjs/v3/steeringContext.js +44 -3
- package/dist/commonjs/v3/steeringContext.js.map +1 -1
- package/dist/commonjs/v3/subAgentStream.d.ts +50 -0
- package/dist/commonjs/v3/subAgentStream.js +154 -0
- package/dist/commonjs/v3/subAgentStream.js.map +1 -0
- package/dist/commonjs/v3/transcriptStorage.js +3 -0
- package/dist/commonjs/v3/transcriptStorage.js.map +1 -1
- package/dist/commonjs/v3/uiMessageChunks.js +5 -1
- package/dist/commonjs/v3/uiMessageChunks.js.map +1 -1
- package/dist/commonjs/version.js +1 -1
- package/dist/esm/v3/ai-shared.d.ts +6 -0
- package/dist/esm/v3/ai-shared.js +6 -0
- package/dist/esm/v3/ai-shared.js.map +1 -1
- package/dist/esm/v3/ai.d.ts +45 -0
- package/dist/esm/v3/ai.js +113 -72
- package/dist/esm/v3/ai.js.map +1 -1
- package/dist/esm/v3/auth.d.ts +2 -1
- package/dist/esm/v3/auth.js +19 -13
- package/dist/esm/v3/auth.js.map +1 -1
- package/dist/esm/v3/chat-client.d.ts +11 -2
- package/dist/esm/v3/chat-client.js +29 -11
- package/dist/esm/v3/chat-client.js.map +1 -1
- package/dist/esm/v3/chat-react.d.ts +21 -0
- package/dist/esm/v3/chat-react.js +81 -30
- package/dist/esm/v3/chat-react.js.map +1 -1
- package/dist/esm/v3/chat.d.ts +1 -0
- package/dist/esm/v3/chat.js +1 -0
- package/dist/esm/v3/chat.js.map +1 -1
- package/dist/esm/v3/managedChatResponse.d.ts +13 -5
- package/dist/esm/v3/managedChatResponse.js +36 -18
- package/dist/esm/v3/managedChatResponse.js.map +1 -1
- package/dist/esm/v3/steeringContext.d.ts +11 -0
- package/dist/esm/v3/steeringContext.js +44 -4
- package/dist/esm/v3/steeringContext.js.map +1 -1
- package/dist/esm/v3/subAgentStream.d.ts +50 -0
- package/dist/esm/v3/subAgentStream.js +149 -0
- package/dist/esm/v3/subAgentStream.js.map +1 -0
- package/dist/esm/v3/transcriptStorage.js +3 -0
- package/dist/esm/v3/transcriptStorage.js.map +1 -1
- package/dist/esm/v3/uiMessageChunks.js +5 -1
- package/dist/esm/v3/uiMessageChunks.js.map +1 -1
- package/dist/esm/version.js +1 -1
- package/docs/ai/prompts.mdx +9 -6
- package/docs/ai-chat/background-injection.mdx +2 -0
- package/docs/ai-chat/chat-local.mdx +4 -4
- package/docs/ai-chat/client-protocol.mdx +1 -0
- package/docs/ai-chat/fast-starts.mdx +1 -1
- package/docs/ai-chat/frontend.mdx +15 -0
- package/docs/ai-chat/overview.mdx +5 -4
- package/docs/ai-chat/patterns/database-persistence.mdx +3 -3
- package/docs/ai-chat/patterns/native-compaction.mdx +6 -6
- package/docs/ai-chat/patterns/sub-agents.mdx +82 -56
- package/docs/ai-chat/patterns/version-upgrades.mdx +3 -3
- package/docs/ai-chat/pending-messages.mdx +2 -0
- package/docs/ai-chat/quick-start.mdx +1 -1
- package/docs/ai-chat/reference.mdx +22 -0
- package/docs/ai-chat/server-chat.mdx +11 -7
- package/docs/ai-chat/side-channels.mdx +2 -2
- package/docs/ai-chat/types.mdx +5 -5
- package/docs/config/config-file.mdx +2 -2
- package/docs/database-connections.mdx +2 -2
- package/docs/how-to-reduce-your-spend.mdx +4 -0
- package/docs/introduction.mdx +104 -24
- package/docs/limits.mdx +41 -0
- package/docs/mcp-tools.mdx +5 -0
- package/docs/observability/query.mdx +29 -0
- package/docs/self-hosting/docker.mdx +62 -0
- package/docs/self-hosting/env/supervisor.mdx +4 -0
- package/docs/self-hosting/env/webapp.mdx +38 -0
- package/docs/self-hosting/kubernetes.mdx +2 -0
- package/docs/self-hosting/overview.mdx +2 -0
- package/docs/troubleshooting-alerts.mdx +39 -0
- package/docs/webhooks/deliveries.mdx +4 -0
- package/docs/webhooks/overview.mdx +8 -0
- package/docs/webhooks/sources.mdx +3 -1
- package/docs/webhooks/waiters.mdx +3 -3
- package/package.json +2 -2
- package/skills/trigger-chat-agent-advanced/SKILL.md +17 -7
- package/skills/trigger-cost-savings/SKILL.md +1 -0
|
@@ -21,6 +21,12 @@ import type { InferUITools, ToolSet, UIDataTypes, UIMessage } from "ai";
|
|
|
21
21
|
* injects when a follow-up message arrives mid-turn.
|
|
22
22
|
*/
|
|
23
23
|
export declare const PENDING_MESSAGE_INJECTED_TYPE: "data-pending-message-injected";
|
|
24
|
+
/**
|
|
25
|
+
* Message-part `type` value marking where `chat.inject` messages drained
|
|
26
|
+
* mid-turn reached the model. Separate from the pending-message type so
|
|
27
|
+
* clients that render injection markers do not render these.
|
|
28
|
+
*/
|
|
29
|
+
export declare const BACKGROUND_INJECTION_TYPE: "data-background-injected";
|
|
24
30
|
import type { ChatTaskWirePayload } from "./chat.js";
|
|
25
31
|
export type { ChatTaskWirePayload, ChatInputChunk } from "./chat.js";
|
|
26
32
|
/**
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* import from `ai.ts`.
|
|
17
17
|
*/
|
|
18
18
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
19
|
-
exports.MAX_EOF_RESUBSCRIBES = exports.PENDING_MESSAGE_INJECTED_TYPE = void 0;
|
|
19
|
+
exports.MAX_EOF_RESUBSCRIBES = exports.BACKGROUND_INJECTION_TYPE = exports.PENDING_MESSAGE_INJECTED_TYPE = void 0;
|
|
20
20
|
exports.upsertIncomingMessage = upsertIncomingMessage;
|
|
21
21
|
exports.slimSubmitMessageForWire = slimSubmitMessageForWire;
|
|
22
22
|
exports.chatRunTags = chatRunTags;
|
|
@@ -26,6 +26,12 @@ exports.waitBeforeEofResubscribe = waitBeforeEofResubscribe;
|
|
|
26
26
|
* injects when a follow-up message arrives mid-turn.
|
|
27
27
|
*/
|
|
28
28
|
exports.PENDING_MESSAGE_INJECTED_TYPE = "data-pending-message-injected";
|
|
29
|
+
/**
|
|
30
|
+
* Message-part `type` value marking where `chat.inject` messages drained
|
|
31
|
+
* mid-turn reached the model. Separate from the pending-message type so
|
|
32
|
+
* clients that render injection markers do not render these.
|
|
33
|
+
*/
|
|
34
|
+
exports.BACKGROUND_INJECTION_TYPE = "data-background-injected";
|
|
29
35
|
/**
|
|
30
36
|
* Upsert an incoming wire message into the customer's DB-backed chain
|
|
31
37
|
* inside a `hydrateMessages` hook. Returns `true` iff the chain was
|
|
@@ -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;
|
|
1
|
+
{"version":3,"file":"ai-shared.js","sourceRoot":"","sources":["../../../src/v3/ai-shared.ts"],"names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O,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QACnC,IAAI,KAAoC,CAAC;QACzC,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;YAC1C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QAC1D,KAAK,GAAG,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;QAChE,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACvC,IAAI,MAAM,CAAC,OAAO;YAAE,IAAI,EAAE,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC"}
|
package/dist/commonjs/v3/ai.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type AnyTask, type Task, type ApiClientConfiguration, type inferSchemaI
|
|
|
2
2
|
import type { streamText as aiStreamTextSignature, FinishReason, LanguageModelUsage, ModelMessage, SystemModelMessage, ProviderMetadata, Tool, ToolSet, UIMessage, UIMessageChunk, UIMessageStreamOptions } from "ai";
|
|
3
3
|
import { chatEvent } from "./webhooks.js";
|
|
4
4
|
import { type TranscriptLoadResult, type TranscriptChannelBinding, type TranscriptStorage } from "./transcriptStorage.js";
|
|
5
|
+
import type { ChatStream } from "./chat-client.js";
|
|
5
6
|
import { type ChatInputChunk, type ChatTaskWirePayload, type InferChatClientData, type InferChatUIMessage, type InferChatUIMessageFromTools, PENDING_MESSAGE_INJECTED_TYPE, upsertIncomingMessage } from "./ai-shared.js";
|
|
6
7
|
import { locals } from "./locals.js";
|
|
7
8
|
import type { ResolvedPrompt } from "./prompt.js";
|
|
@@ -211,6 +212,48 @@ declare function createChatWatchToken(externalId: string, options?: {
|
|
|
211
212
|
* ```
|
|
212
213
|
*/
|
|
213
214
|
declare function chatDeferBeforeOutput(promiseOrFn: Promise<unknown> | (() => Promise<unknown>)): void;
|
|
215
|
+
/** Options for {@link forwardSubAgent}. */
|
|
216
|
+
export type ForwardSubAgentOptions = {
|
|
217
|
+
/** The parent tool call the sub-agent runs inside: `toolCallId` from the tool's `execute` options. */
|
|
218
|
+
toolCallId: string;
|
|
219
|
+
/**
|
|
220
|
+
* How long chunks are held so they are written together. `0` writes each
|
|
221
|
+
* chunk on its own.
|
|
222
|
+
* @default 50
|
|
223
|
+
*/
|
|
224
|
+
flushIntervalMs?: number;
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Stream a sub-agent's reply to the frontend from inside a parent tool call,
|
|
228
|
+
* and resolve with the sub-agent's final message once it finishes.
|
|
229
|
+
*
|
|
230
|
+
* Each chunk the sub-agent streams is written once to the parent chat as a
|
|
231
|
+
* transient `data-subagent` part, so the bytes written grow with the length of
|
|
232
|
+
* the reply. Render it while it runs with `useSubAgentMessages` from
|
|
233
|
+
* `@trigger.dev/sdk/chat/react`. The tool's output is the final message, which
|
|
234
|
+
* persists with the parent's history the way a tool result always does.
|
|
235
|
+
*
|
|
236
|
+
* Prefer this over yielding `stream.messages()` snapshots as preliminary tool
|
|
237
|
+
* results: every snapshot repeats the whole message so far, so that pattern
|
|
238
|
+
* writes bytes in proportion to the square of the reply length.
|
|
239
|
+
*
|
|
240
|
+
* Call it inside a `chat.agent` (or `chat.customAgent`) run.
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* ```ts
|
|
244
|
+
* const research = tool({
|
|
245
|
+
* description: "Delegate research to the research agent.",
|
|
246
|
+
* inputSchema: z.object({ topic: z.string() }),
|
|
247
|
+
* execute: async ({ topic }, { toolCallId, abortSignal }) => {
|
|
248
|
+
* const agent = new AgentChat<typeof researchAgent>({ agent: "research-agent" });
|
|
249
|
+
* const stream = await agent.sendMessage(topic, { abortSignal });
|
|
250
|
+
* return await chat.forwardSubAgent(stream, { toolCallId });
|
|
251
|
+
* },
|
|
252
|
+
* toModelOutput: ({ output }) => ({ type: "text", value: lastText(output) }),
|
|
253
|
+
* });
|
|
254
|
+
* ```
|
|
255
|
+
*/
|
|
256
|
+
declare function forwardSubAgent<TUIMessage extends UIMessage = UIMessage>(stream: ChatStream | ReadableStream<UIMessageChunk>, options: ForwardSubAgentOptions): Promise<TUIMessage | undefined>;
|
|
214
257
|
/**
|
|
215
258
|
* A stream writer passed to chat lifecycle callbacks (`onPreload`, `onChatStart`,
|
|
216
259
|
* `onTurnStart`, `onTurnComplete`, `onCompacted`).
|
|
@@ -4078,6 +4121,8 @@ export declare const chat: {
|
|
|
4078
4121
|
*/
|
|
4079
4122
|
write(part: UIMessageChunk): void;
|
|
4080
4123
|
};
|
|
4124
|
+
/** Stream a sub-agent's reply through a parent tool call. See {@link forwardSubAgent}. */
|
|
4125
|
+
forwardSubAgent: typeof forwardSubAgent;
|
|
4081
4126
|
/** Pre-built input stream for receiving messages from the transport. */
|
|
4082
4127
|
messages: ChatMessages;
|
|
4083
4128
|
/** The current chat.agent run's Session handle. See {@link SessionHandle}. */
|
package/dist/commonjs/v3/ai.js
CHANGED
|
@@ -32,6 +32,7 @@ const compactionResponse_js_1 = require("./compactionResponse.js");
|
|
|
32
32
|
const toolResultOrder_js_1 = require("./toolResultOrder.js");
|
|
33
33
|
const managedChatResponse_js_1 = require("./managedChatResponse.js");
|
|
34
34
|
const uiMessageChunks_js_1 = require("./uiMessageChunks.js");
|
|
35
|
+
const subAgentStream_js_1 = require("./subAgentStream.js");
|
|
35
36
|
const steeringContext_js_1 = require("./steeringContext.js");
|
|
36
37
|
let transcriptStorageOverride;
|
|
37
38
|
/**
|
|
@@ -954,6 +955,64 @@ const chatResponse = {
|
|
|
954
955
|
managedResponse().writeData(part);
|
|
955
956
|
},
|
|
956
957
|
};
|
|
958
|
+
/**
|
|
959
|
+
* Stream a sub-agent's reply to the frontend from inside a parent tool call,
|
|
960
|
+
* and resolve with the sub-agent's final message once it finishes.
|
|
961
|
+
*
|
|
962
|
+
* Each chunk the sub-agent streams is written once to the parent chat as a
|
|
963
|
+
* transient `data-subagent` part, so the bytes written grow with the length of
|
|
964
|
+
* the reply. Render it while it runs with `useSubAgentMessages` from
|
|
965
|
+
* `@trigger.dev/sdk/chat/react`. The tool's output is the final message, which
|
|
966
|
+
* persists with the parent's history the way a tool result always does.
|
|
967
|
+
*
|
|
968
|
+
* Prefer this over yielding `stream.messages()` snapshots as preliminary tool
|
|
969
|
+
* results: every snapshot repeats the whole message so far, so that pattern
|
|
970
|
+
* writes bytes in proportion to the square of the reply length.
|
|
971
|
+
*
|
|
972
|
+
* Call it inside a `chat.agent` (or `chat.customAgent`) run.
|
|
973
|
+
*
|
|
974
|
+
* @example
|
|
975
|
+
* ```ts
|
|
976
|
+
* const research = tool({
|
|
977
|
+
* description: "Delegate research to the research agent.",
|
|
978
|
+
* inputSchema: z.object({ topic: z.string() }),
|
|
979
|
+
* execute: async ({ topic }, { toolCallId, abortSignal }) => {
|
|
980
|
+
* const agent = new AgentChat<typeof researchAgent>({ agent: "research-agent" });
|
|
981
|
+
* const stream = await agent.sendMessage(topic, { abortSignal });
|
|
982
|
+
* return await chat.forwardSubAgent(stream, { toolCallId });
|
|
983
|
+
* },
|
|
984
|
+
* toModelOutput: ({ output }) => ({ type: "text", value: lastText(output) }),
|
|
985
|
+
* });
|
|
986
|
+
* ```
|
|
987
|
+
*/
|
|
988
|
+
async function forwardSubAgent(stream, options) {
|
|
989
|
+
const source = isReadableStream(stream)
|
|
990
|
+
? stream
|
|
991
|
+
: stream.stream;
|
|
992
|
+
let outcome = { message: undefined };
|
|
993
|
+
const { waitUntilComplete } = chatStream.writer({
|
|
994
|
+
spanName: "forward sub-agent",
|
|
995
|
+
collapsed: true,
|
|
996
|
+
execute: async ({ write }) => {
|
|
997
|
+
try {
|
|
998
|
+
outcome = {
|
|
999
|
+
message: await (0, subAgentStream_js_1.forwardSubAgentChunks)(source, {
|
|
1000
|
+
toolCallId: options.toolCallId,
|
|
1001
|
+
flushIntervalMs: options.flushIntervalMs ?? 50,
|
|
1002
|
+
write,
|
|
1003
|
+
}),
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
catch (error) {
|
|
1007
|
+
outcome = { error };
|
|
1008
|
+
}
|
|
1009
|
+
},
|
|
1010
|
+
});
|
|
1011
|
+
await waitUntilComplete();
|
|
1012
|
+
if ("error" in outcome)
|
|
1013
|
+
throw outcome.error;
|
|
1014
|
+
return outcome.message;
|
|
1015
|
+
}
|
|
957
1016
|
/**
|
|
958
1017
|
* Creates a lazy ChatWriter that only opens a realtime stream on first use.
|
|
959
1018
|
* Call `flush()` after the callback returns to await stream completion.
|
|
@@ -1948,12 +2007,6 @@ function spliceHandoverPartial(modelMessages, uiMessages, signal) {
|
|
|
1948
2007
|
* @internal
|
|
1949
2008
|
*/
|
|
1950
2009
|
const chatBackgroundQueueKey = locals_js_1.locals.create("chat.backgroundQueue");
|
|
1951
|
-
/**
|
|
1952
|
-
* Background injections a step-boundary drain handed to the model this turn,
|
|
1953
|
-
* with the transcript message they followed. Reconciled into the model lane
|
|
1954
|
-
* and the persisted injections once the turn's response is in.
|
|
1955
|
-
*/
|
|
1956
|
-
const chatPendingBackgroundKey = locals_js_1.locals.create("chat.pendingBackground");
|
|
1957
2010
|
/**
|
|
1958
2011
|
* System-role context injected mid-conversation, held for the instructions lane.
|
|
1959
2012
|
*
|
|
@@ -2906,6 +2959,25 @@ const EMPTY_DRAIN = { injected: [], claimed: [] };
|
|
|
2906
2959
|
function modelFormOf(m, batch, injected) {
|
|
2907
2960
|
return batch[0] === m ? injected : [];
|
|
2908
2961
|
}
|
|
2962
|
+
/**
|
|
2963
|
+
* Record a prepared injection and write its marker into the response, so the
|
|
2964
|
+
* model lane rebuilds it at the step boundary where the model received it.
|
|
2965
|
+
*/
|
|
2966
|
+
function markInjection(steps, messageIds, messages, markerMessages, kind) {
|
|
2967
|
+
const id = (0, ai_runtime_js_1.generateId)();
|
|
2968
|
+
const injections = locals_js_1.locals.get(chatSteeringInjectionsKey) ?? new Map();
|
|
2969
|
+
injections.set(id, { id, messageIds, messages, ...(kind ? { kind } : {}) });
|
|
2970
|
+
locals_js_1.locals.set(chatSteeringInjectionsKey, injections);
|
|
2971
|
+
const response = managedResponse();
|
|
2972
|
+
// prepareStep can run ahead of the UI consumer. Admit the marker only
|
|
2973
|
+
// once the actual preceding finish-step chunk has entered this stream.
|
|
2974
|
+
response.afterToolStep(steps.at(-1)?.content.flatMap((part) => (part.toolCallId ? [part.toolCallId] : [])) ?? []);
|
|
2975
|
+
response.writeData({
|
|
2976
|
+
type: kind === "background" ? ai_shared_js_1.BACKGROUND_INJECTION_TYPE : ai_shared_js_1.PENDING_MESSAGE_INJECTED_TYPE,
|
|
2977
|
+
id,
|
|
2978
|
+
data: { messageIds, messages: markerMessages },
|
|
2979
|
+
});
|
|
2980
|
+
}
|
|
2909
2981
|
/**
|
|
2910
2982
|
* Drain the steering queue as a batch. Calls `shouldInject` once with all
|
|
2911
2983
|
* pending messages. If it returns true, calls `prepareMessages` once to
|
|
@@ -2919,8 +2991,6 @@ function modelFormOf(m, batch, injected) {
|
|
|
2919
2991
|
* @internal
|
|
2920
2992
|
*/
|
|
2921
2993
|
async function drainSteeringQueue(config, messages, steps, queueOverride) {
|
|
2922
|
-
if (steps.length === 0)
|
|
2923
|
-
managedResponse().beginGeneration();
|
|
2924
2994
|
const queue = queueOverride ?? locals_js_1.locals.get(chatSteeringQueueKey);
|
|
2925
2995
|
if (!queue || queue.length === 0)
|
|
2926
2996
|
return EMPTY_DRAIN;
|
|
@@ -3053,23 +3123,7 @@ async function drainSteeringQueue(config, messages, steps, queueOverride) {
|
|
|
3053
3123
|
locals_js_1.locals.set(chatPendingSteerKey, pendingSteer);
|
|
3054
3124
|
}
|
|
3055
3125
|
if (injected.length > 0) {
|
|
3056
|
-
|
|
3057
|
-
const messageIds = claimedUIMessages.map((m) => m.id);
|
|
3058
|
-
const injections = locals_js_1.locals.get(chatSteeringInjectionsKey) ?? new Map();
|
|
3059
|
-
injections.set(id, { id, messageIds, messages: injected });
|
|
3060
|
-
locals_js_1.locals.set(chatSteeringInjectionsKey, injections);
|
|
3061
|
-
const response = managedResponse();
|
|
3062
|
-
// prepareStep can run ahead of the UI consumer. Admit the marker only
|
|
3063
|
-
// once the actual preceding finish-step chunk has entered this stream.
|
|
3064
|
-
response.afterStep(steps.length);
|
|
3065
|
-
response.writeData({
|
|
3066
|
-
type: ai_shared_js_1.PENDING_MESSAGE_INJECTED_TYPE,
|
|
3067
|
-
id,
|
|
3068
|
-
data: {
|
|
3069
|
-
messageIds,
|
|
3070
|
-
messages: claimedUIMessages.map((m) => ({ id: m.id, text: textOfUIMessage(m) })),
|
|
3071
|
-
},
|
|
3072
|
-
});
|
|
3126
|
+
markInjection(steps, claimedUIMessages.map((m) => m.id), injected, claimedUIMessages.map((m) => ({ id: m.id, text: textOfUIMessage(m) })));
|
|
3073
3127
|
}
|
|
3074
3128
|
// Fire onInjected callback
|
|
3075
3129
|
if (config.onInjected && injected.length > 0) {
|
|
@@ -3634,12 +3688,7 @@ function toStreamTextOptions(options, retain = true) {
|
|
|
3634
3688
|
if (bgQueue && bgQueue.length > 0) {
|
|
3635
3689
|
const injected = bgQueue.splice(0); // drain
|
|
3636
3690
|
resultMessages = [...(resultMessages ?? messages), ...injected];
|
|
3637
|
-
|
|
3638
|
-
pendingBackground.push({
|
|
3639
|
-
afterId: locals_js_1.locals.get(chatCurrentUIMessagesKey)?.at(-1)?.id ?? "",
|
|
3640
|
-
messages: injected,
|
|
3641
|
-
});
|
|
3642
|
-
locals_js_1.locals.set(chatPendingBackgroundKey, pendingBackground);
|
|
3691
|
+
markInjection(steps, [], injected, [], "background");
|
|
3643
3692
|
}
|
|
3644
3693
|
// 4. Parallel tool results in call order, the order the next turn's history
|
|
3645
3694
|
// will list them in. See `withToolResultsInCallOrder`.
|
|
@@ -4988,24 +5037,6 @@ function chatAgent(options) {
|
|
|
4988
5037
|
// durable snapshot + `session.out` replay (or `hydrateMessages` if
|
|
4989
5038
|
// registered) — the wire is delta-only now, no longer a seed.
|
|
4990
5039
|
let accumulatedMessages = [];
|
|
4991
|
-
/**
|
|
4992
|
-
* Give the model accumulator the background injections a step-boundary
|
|
4993
|
-
* drain handed to the model this turn, and record them for persistence.
|
|
4994
|
-
* Returns how many model messages were appended.
|
|
4995
|
-
*/
|
|
4996
|
-
const reconcilePendingBackground = () => {
|
|
4997
|
-
const pending = locals_js_1.locals.get(chatPendingBackgroundKey);
|
|
4998
|
-
if (!pending || pending.length === 0)
|
|
4999
|
-
return 0;
|
|
5000
|
-
locals_js_1.locals.set(chatPendingBackgroundKey, []);
|
|
5001
|
-
let appended = 0;
|
|
5002
|
-
for (const entry of pending) {
|
|
5003
|
-
accumulatedMessages.push(...entry.messages);
|
|
5004
|
-
laneInjections.push(entry);
|
|
5005
|
-
appended += entry.messages.length;
|
|
5006
|
-
}
|
|
5007
|
-
return appended;
|
|
5008
|
-
};
|
|
5009
5040
|
/**
|
|
5010
5041
|
* Give the model accumulator the steering messages a drain consumed,
|
|
5011
5042
|
* in the form the model actually received. Appended, never reconverted
|
|
@@ -5029,6 +5060,15 @@ function chatAgent(options) {
|
|
|
5029
5060
|
// Accumulated UI messages for persistence. Mirrors the model accumulator
|
|
5030
5061
|
// but in frontend-friendly UIMessage format (with parts, id, etc.).
|
|
5031
5062
|
let accumulatedUIMessages = [];
|
|
5063
|
+
const cleanIncomingMessage = (msg) => {
|
|
5064
|
+
if (msg.role !== "assistant")
|
|
5065
|
+
return (0, steeringContext_js_1.withoutInjectionMarkers)(msg);
|
|
5066
|
+
const cleaned = cleanupAbortedParts(msg);
|
|
5067
|
+
// Markers are the agent's own; only a known assistant message keeps them.
|
|
5068
|
+
return accumulatedUIMessages.some((m) => m.id === msg.id)
|
|
5069
|
+
? cleaned
|
|
5070
|
+
: (0, steeringContext_js_1.withoutInjectionMarkers)(cleaned);
|
|
5071
|
+
};
|
|
5032
5072
|
// ── Snapshot + replay (gated on prior-state signals) ─────────────
|
|
5033
5073
|
//
|
|
5034
5074
|
// With `hydrateMessages` registered the customer owns history — the
|
|
@@ -6545,7 +6585,7 @@ function chatAgent(options) {
|
|
|
6545
6585
|
// Cleaning happens once here so `extractLastUserMessageText` and
|
|
6546
6586
|
// every downstream consumer see the same message shape — and
|
|
6547
6587
|
// `cleanupAbortedParts` no longer has to be re-applied below.
|
|
6548
|
-
const cleanedIncomingMessages = incomingMessages.map(
|
|
6588
|
+
const cleanedIncomingMessages = incomingMessages.map(cleanIncomingMessage);
|
|
6549
6589
|
const lastUserMessage = extractLastUserMessageText(cleanedIncomingMessages);
|
|
6550
6590
|
channelTurnRan =
|
|
6551
6591
|
!!channelConn &&
|
|
@@ -6606,7 +6646,6 @@ function chatAgent(options) {
|
|
|
6606
6646
|
locals_js_1.locals.set(chatOutGateKey, createChatOutGate());
|
|
6607
6647
|
locals_js_1.locals.set(chatCompactionStateKey, undefined);
|
|
6608
6648
|
locals_js_1.locals.set(chatSteeringQueueKey, []);
|
|
6609
|
-
locals_js_1.locals.set(chatPendingBackgroundKey, []);
|
|
6610
6649
|
await locals_js_1.locals.get(chatManagedResponseKey)?.close();
|
|
6611
6650
|
locals_js_1.locals.set(chatManagedResponseKey, undefined);
|
|
6612
6651
|
locals_js_1.locals.set(chatManagedResponseActiveKey, true);
|
|
@@ -7705,7 +7744,7 @@ function chatAgent(options) {
|
|
|
7705
7744
|
const steerTailThisTurn = reconcilePendingSteer({
|
|
7706
7745
|
turnNew: turnNewModelMessages,
|
|
7707
7746
|
response: capturedResponseMessage,
|
|
7708
|
-
}).reduce((n, e) => n + e.model.length, 0)
|
|
7747
|
+
}).reduce((n, e) => n + e.model.length, 0);
|
|
7709
7748
|
// Append the assistant's response (partial or complete) to the accumulator.
|
|
7710
7749
|
// The onFinish callback fires even on abort/stop, so partial responses
|
|
7711
7750
|
// from stopped generation are captured correctly.
|
|
@@ -8588,7 +8627,8 @@ function chatAgent(options) {
|
|
|
8588
8627
|
// yet (a pre-run hook threw), so fold the wire message in for the
|
|
8589
8628
|
// error event + snapshot — the cursor has already advanced past it,
|
|
8590
8629
|
// so otherwise it survives in neither the snapshot nor the `.in` tail.
|
|
8591
|
-
const
|
|
8630
|
+
const rawWireMessage = currentWirePayload.message;
|
|
8631
|
+
const erroredWireMessage = rawWireMessage && cleanIncomingMessage(rawWireMessage);
|
|
8592
8632
|
const erroredUIMessages = erroredWireMessage &&
|
|
8593
8633
|
!accumulatedUIMessages.some((m) => m.id === erroredWireMessage.id)
|
|
8594
8634
|
? [...accumulatedUIMessages, erroredWireMessage]
|
|
@@ -8645,7 +8685,6 @@ function chatAgent(options) {
|
|
|
8645
8685
|
let erroredNewUIMessages = buildErroredNew();
|
|
8646
8686
|
let erroredNewModelMessages = [];
|
|
8647
8687
|
const reconciledSteer = reconcilePendingSteer({ response: partialResponse });
|
|
8648
|
-
const backgroundTailThisTurn = reconcilePendingBackground();
|
|
8649
8688
|
if (!responseCommitted) {
|
|
8650
8689
|
try {
|
|
8651
8690
|
if (erroredNewUIMessages.length > 0) {
|
|
@@ -8663,8 +8702,7 @@ function chatAgent(options) {
|
|
|
8663
8702
|
accumulatedMessages.push(...(await toModelMessages(appended.map((m) => stripProviderMetadata(m)))));
|
|
8664
8703
|
}
|
|
8665
8704
|
else {
|
|
8666
|
-
const ok = await replaceModelRun(accumulatedMessages, erroredUIMessages[partialIdx], partialResponse, reconciledSteer.reduce((n, e) => n + e.model.length, 0)
|
|
8667
|
-
backgroundTailThisTurn);
|
|
8705
|
+
const ok = await replaceModelRun(accumulatedMessages, erroredUIMessages[partialIdx], partialResponse, reconciledSteer.reduce((n, e) => n + e.model.length, 0));
|
|
8668
8706
|
if (!ok) {
|
|
8669
8707
|
v3_1.logger.warn("chat.agent: replaced partial not found at the model lane tail; reconverting the lane");
|
|
8670
8708
|
accumulatedMessages = await toModelMessages(erroredUIMessagesWithPartial, erroredUIMessagesWithPartial);
|
|
@@ -11064,10 +11102,10 @@ function resolveChatStartBaseURL(endpoint, chatId, option) {
|
|
|
11064
11102
|
const raw = typeof option === "function" ? option({ endpoint, chatId }) : (option ?? fallback);
|
|
11065
11103
|
return raw.replace(/\/$/, "");
|
|
11066
11104
|
}
|
|
11067
|
-
function overrideRequestHeaders(
|
|
11105
|
+
function overrideRequestHeaders(authHeaders) {
|
|
11068
11106
|
const headers = {
|
|
11069
11107
|
"Content-Type": "application/json",
|
|
11070
|
-
|
|
11108
|
+
...authHeaders,
|
|
11071
11109
|
"x-trigger-source": "sdk",
|
|
11072
11110
|
};
|
|
11073
11111
|
// Forward the preview-branch hint so override-mode requests land on the
|
|
@@ -11080,15 +11118,16 @@ function overrideRequestHeaders(accessToken) {
|
|
|
11080
11118
|
return headers;
|
|
11081
11119
|
}
|
|
11082
11120
|
async function callSessionsCreateWithOverride(args) {
|
|
11083
|
-
const
|
|
11084
|
-
if (!
|
|
11121
|
+
const apiClient = v3_1.apiClientManager.client;
|
|
11122
|
+
if (!apiClient) {
|
|
11085
11123
|
throw new Error("chat.createStartSessionAction: no API access token configured. Set TRIGGER_SECRET_KEY or call apiClientManager.setGlobalAPIClientConfiguration before invoking the action.");
|
|
11086
11124
|
}
|
|
11125
|
+
const authHeaders = apiClient.getAuthenticationHeaders("createSession");
|
|
11087
11126
|
const ctx = { endpoint: "sessions", chatId: args.chatId };
|
|
11088
11127
|
const url = `${resolveChatStartBaseURL("sessions", args.chatId, args.baseURLOption)}/api/v1/sessions`;
|
|
11089
11128
|
const init = {
|
|
11090
11129
|
method: "POST",
|
|
11091
|
-
headers: overrideRequestHeaders(
|
|
11130
|
+
headers: overrideRequestHeaders(authHeaders),
|
|
11092
11131
|
// This path bypasses `sessions.start`, so it resolves the pin itself.
|
|
11093
11132
|
body: JSON.stringify((0, externalDeploymentId_js_1.withResolvedExternalDeploymentId)(args.body)),
|
|
11094
11133
|
};
|
|
@@ -11103,18 +11142,20 @@ async function callSessionsCreateWithOverride(args) {
|
|
|
11103
11142
|
return json;
|
|
11104
11143
|
}
|
|
11105
11144
|
async function mintPublicTokenWithOverride(args) {
|
|
11106
|
-
const
|
|
11107
|
-
if (!
|
|
11145
|
+
const apiClient = v3_1.apiClientManager.client;
|
|
11146
|
+
if (!apiClient) {
|
|
11108
11147
|
throw new Error("chat.createStartSessionAction: no API access token configured for JWT mint.");
|
|
11109
11148
|
}
|
|
11149
|
+
const authHeaders = apiClient.getAuthenticationHeaders("createPublicToken");
|
|
11150
|
+
const accessToken = authHeaders.Authorization.slice("Bearer ".length);
|
|
11110
11151
|
const ctx = { endpoint: "auth", chatId: args.chatId };
|
|
11111
11152
|
const scopes = [`read:sessions:${args.chatId}`, `write:sessions:${args.chatId}`];
|
|
11112
|
-
const serverMint = (0, v3_1.isAdditionalApiKey)(accessToken);
|
|
11153
|
+
const serverMint = (0, v3_1.isAdditionalApiKey)(accessToken) || (0, v3_1.isRunToken)(accessToken);
|
|
11113
11154
|
const endpoint = serverMint ? "/api/v1/auth/public-tokens" : "/api/v1/auth/jwt/claims";
|
|
11114
11155
|
const url = `${resolveChatStartBaseURL("auth", args.chatId, args.baseURLOption)}${endpoint}`;
|
|
11115
11156
|
const init = {
|
|
11116
11157
|
method: "POST",
|
|
11117
|
-
headers: overrideRequestHeaders(
|
|
11158
|
+
headers: overrideRequestHeaders(authHeaders),
|
|
11118
11159
|
...(serverMint
|
|
11119
11160
|
? {
|
|
11120
11161
|
body: JSON.stringify({
|
|
@@ -11130,11 +11171,9 @@ async function mintPublicTokenWithOverride(args) {
|
|
|
11130
11171
|
? await args.fetchOverride(url, init, ctx)
|
|
11131
11172
|
: await fetch(url, init);
|
|
11132
11173
|
if (!response.ok) {
|
|
11133
|
-
// An additional API key cannot self-sign, so it must use the server mint
|
|
11134
|
-
// endpoint. On a server too old to expose it, explain the recovery path
|
|
11135
|
-
// instead of surfacing a bare 404 (mirrors auth.createServerPublicToken).
|
|
11136
11174
|
if (serverMint && response.status === 404) {
|
|
11137
|
-
|
|
11175
|
+
const credentialType = (0, v3_1.isRunToken)(accessToken) ? "run token" : "additional API key";
|
|
11176
|
+
throw new Error(`This ${credentialType} cannot self-sign public tokens, and the server does not support public-token minting. Upgrade the server or use the root API key.`);
|
|
11138
11177
|
}
|
|
11139
11178
|
const text = await response.text().catch(() => "");
|
|
11140
11179
|
throw new Error(`auth.createPublicToken failed: ${response.status} ${text}`);
|
|
@@ -11248,6 +11287,8 @@ exports.chat = {
|
|
|
11248
11287
|
stream: chatStream,
|
|
11249
11288
|
/** Write data parts that persist to the response message. See {@link chatResponse}. */
|
|
11250
11289
|
response: chatResponse,
|
|
11290
|
+
/** Stream a sub-agent's reply through a parent tool call. See {@link forwardSubAgent}. */
|
|
11291
|
+
forwardSubAgent,
|
|
11251
11292
|
/** Pre-built input stream for receiving messages from the transport. */
|
|
11252
11293
|
messages: messagesInput,
|
|
11253
11294
|
/** The current chat.agent run's Session handle. See {@link SessionHandle}. */
|