ai 7.0.165 → 7.0.168
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/CHANGELOG.md +31 -0
- package/dist/index.d.ts +42 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +211 -34
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +90 -10
- package/dist/internal/index.js.map +1 -1
- package/docs/02-foundations/02-providers-and-models.mdx +1 -0
- package/docs/03-ai-sdk-core/16-mcp-tools.mdx +13 -0
- package/docs/03-ai-sdk-core/60-telemetry.mdx +9 -0
- package/docs/03-ai-sdk-harnesses/02-harness-agent.mdx +4 -0
- package/docs/03-ai-sdk-harnesses/06-workflow-utilities.mdx +5 -0
- package/docs/04-ai-sdk-ui/02-chatbot.mdx +58 -0
- package/docs/06-advanced/11-secure-url-fetching.mdx +12 -0
- package/docs/07-reference/02-ai-sdk-ui/01-use-chat.mdx +24 -0
- package/package.json +11 -11
- package/src/telemetry/create-telemetry-dispatcher.ts +30 -3
- package/src/telemetry/redact-telemetry-credentials.ts +80 -0
- package/src/telemetry/tracing-channel-publisher.ts +7 -4
- package/src/ui/chat.ts +265 -4
- package/src/ui-message-stream/to-ui-message-stream.ts +27 -10
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { GatewayAuthenticationError, GatewayError, createGateway, gateway, gateway as gateway$1 } from "@ai-sdk/gateway";
|
|
3
|
-
import { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, tool as tool$1, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
|
|
3
|
+
import { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, redactTelemetryValue, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, tool as tool$1, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
|
|
4
4
|
import { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionRefusalError, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from "@ai-sdk/provider";
|
|
5
5
|
import { array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, lazy, literal, looseObject, never, null as null$1, number, object, record, string, union, unknown } from "zod/v4";
|
|
6
6
|
//#region src/telemetry/get-request-origin.ts
|
|
@@ -1241,7 +1241,7 @@ function cloneValue(value, seen) {
|
|
|
1241
1241
|
}
|
|
1242
1242
|
//#endregion
|
|
1243
1243
|
//#region src/version.ts
|
|
1244
|
-
const VERSION = "7.0.
|
|
1244
|
+
const VERSION = "7.0.168";
|
|
1245
1245
|
//#endregion
|
|
1246
1246
|
//#region src/util/download/download.ts
|
|
1247
1247
|
/**
|
|
@@ -4103,6 +4103,65 @@ function isNodeRuntime() {
|
|
|
4103
4103
|
return globalThis.process?.release?.name === "node";
|
|
4104
4104
|
}
|
|
4105
4105
|
//#endregion
|
|
4106
|
+
//#region src/telemetry/redact-telemetry-credentials.ts
|
|
4107
|
+
/**
|
|
4108
|
+
* Apply provider-owned credential redaction on telemetry-only copies. Only visit SDK
|
|
4109
|
+
* metadata containers, never arbitrary prompts, tool outputs, or user context.
|
|
4110
|
+
*/
|
|
4111
|
+
function redactTelemetryCredentials(value) {
|
|
4112
|
+
return replaceProperties(value, {
|
|
4113
|
+
args: redactTelemetryValue,
|
|
4114
|
+
tools: redactTools,
|
|
4115
|
+
stepTools: redactTools,
|
|
4116
|
+
request: redactMetadata,
|
|
4117
|
+
response: redactMetadata,
|
|
4118
|
+
steps: (steps) => mapArray(steps, redactTelemetryCredentials),
|
|
4119
|
+
finalStep: redactTelemetryCredentials,
|
|
4120
|
+
error: redactTelemetryCredentials,
|
|
4121
|
+
cause: redactTelemetryCredentials,
|
|
4122
|
+
errors: (errors) => mapArray(errors, redactTelemetryCredentials),
|
|
4123
|
+
lastError: redactTelemetryCredentials,
|
|
4124
|
+
requestBodyValues: redactBody
|
|
4125
|
+
});
|
|
4126
|
+
}
|
|
4127
|
+
function redactMetadata(value) {
|
|
4128
|
+
return Array.isArray(value) ? mapArray(value, redactMetadata) : replaceProperties(value, { body: redactBody });
|
|
4129
|
+
}
|
|
4130
|
+
function redactBody(value) {
|
|
4131
|
+
return replaceProperties(redactTelemetryValue(value), { tools: redactTools });
|
|
4132
|
+
}
|
|
4133
|
+
function redactTools(value) {
|
|
4134
|
+
if (Array.isArray(value)) return mapArray(value, redactTelemetryCredentials);
|
|
4135
|
+
if (!isRecord$2(value)) return value;
|
|
4136
|
+
return replaceProperties(value, Object.fromEntries(Object.keys(value).map((key) => [key, redactTelemetryCredentials])));
|
|
4137
|
+
}
|
|
4138
|
+
function isRecord$2(value) {
|
|
4139
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
4140
|
+
}
|
|
4141
|
+
function mapArray(value, redact) {
|
|
4142
|
+
if (!Array.isArray(value)) return value;
|
|
4143
|
+
const copy = value.map(redact);
|
|
4144
|
+
return copy.some((entry, index) => entry !== value[index]) ? copy : value;
|
|
4145
|
+
}
|
|
4146
|
+
/** Preserve result getters, streams, and property descriptors without mutation. */
|
|
4147
|
+
function replaceProperties(value, redactors) {
|
|
4148
|
+
if (!isRecord$2(value)) return value;
|
|
4149
|
+
let descriptors;
|
|
4150
|
+
for (const [key, redact] of Object.entries(redactors)) {
|
|
4151
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
4152
|
+
if (descriptor == null || !("value" in descriptor)) continue;
|
|
4153
|
+
const redacted = redact(descriptor.value);
|
|
4154
|
+
if (redacted !== descriptor.value) {
|
|
4155
|
+
descriptors ??= Object.getOwnPropertyDescriptors(value);
|
|
4156
|
+
descriptors[key] = {
|
|
4157
|
+
...descriptor,
|
|
4158
|
+
value: redacted
|
|
4159
|
+
};
|
|
4160
|
+
}
|
|
4161
|
+
}
|
|
4162
|
+
return descriptors == null ? value : Object.create(Object.getPrototypeOf(value), descriptors);
|
|
4163
|
+
}
|
|
4164
|
+
//#endregion
|
|
4106
4165
|
//#region src/telemetry/tracing-channel-publisher.ts
|
|
4107
4166
|
let diagnosticsChannelPromise;
|
|
4108
4167
|
/**
|
|
@@ -4156,7 +4215,9 @@ async function runWithTracingChannelSpan(message, execute, recordResult = true)
|
|
|
4156
4215
|
hasExecutionError = true;
|
|
4157
4216
|
throw error;
|
|
4158
4217
|
});
|
|
4159
|
-
return recordResult ? executePromise
|
|
4218
|
+
return recordResult ? executePromise.then(redactTelemetryCredentials, (error) => {
|
|
4219
|
+
throw redactTelemetryCredentials(error);
|
|
4220
|
+
}) : executePromise.then(() => void 0, () => {
|
|
4160
4221
|
throw new Error("AI SDK operation failed");
|
|
4161
4222
|
});
|
|
4162
4223
|
};
|
|
@@ -4198,10 +4259,10 @@ function openTelemetryChannelSpanContext({ message, completion, recordResult = t
|
|
|
4198
4259
|
if (asyncEndPublished) return;
|
|
4199
4260
|
asyncEndPublished = true;
|
|
4200
4261
|
if (error !== void 0) {
|
|
4201
|
-
context.error = recordResult ? error : /* @__PURE__ */ new Error("AI SDK operation failed");
|
|
4262
|
+
context.error = recordResult ? redactTelemetryCredentials(error) : /* @__PURE__ */ new Error("AI SDK operation failed");
|
|
4202
4263
|
safePublish(() => tracingChannel.error.publish(context));
|
|
4203
4264
|
}
|
|
4204
|
-
if (recordResult && result !== void 0) context.result = result;
|
|
4265
|
+
if (recordResult && result !== void 0) context.result = redactTelemetryCredentials(result);
|
|
4205
4266
|
safePublish(() => tracingChannel.asyncEnd.publish(context));
|
|
4206
4267
|
};
|
|
4207
4268
|
safePublish(() => {
|
|
@@ -4360,7 +4421,7 @@ function augmentEvent(event, telemetry, filterContext = false) {
|
|
|
4360
4421
|
includeToolsContext: telemetry.includeToolsContext
|
|
4361
4422
|
});
|
|
4362
4423
|
}
|
|
4363
|
-
return filterTelemetryEvent(augmentedEvent, telemetry);
|
|
4424
|
+
return redactTelemetryCredentials(filterTelemetryEvent(augmentedEvent, telemetry));
|
|
4364
4425
|
}
|
|
4365
4426
|
/**
|
|
4366
4427
|
* Creates a telemetry dispatcher that sends telemetry events
|
|
@@ -4447,10 +4508,29 @@ function createTelemetryDispatcher({ telemetry }) {
|
|
|
4447
4508
|
let wrappedExecute = execute;
|
|
4448
4509
|
for (const executeWrapper of executeLanguageModelCallWrappers) {
|
|
4449
4510
|
const innerExecute = wrappedExecute;
|
|
4450
|
-
wrappedExecute = () =>
|
|
4451
|
-
|
|
4452
|
-
|
|
4453
|
-
|
|
4511
|
+
wrappedExecute = async () => {
|
|
4512
|
+
const originals = /* @__PURE__ */ new Map();
|
|
4513
|
+
const redact = (original) => {
|
|
4514
|
+
const redacted = redactTelemetryCredentials(original);
|
|
4515
|
+
if (redacted !== original) originals.set(redacted, original);
|
|
4516
|
+
return redacted;
|
|
4517
|
+
};
|
|
4518
|
+
const restore = (value) => originals.has(value) ? originals.get(value) : value;
|
|
4519
|
+
try {
|
|
4520
|
+
return restore(await executeWrapper({
|
|
4521
|
+
...augmentedEvent,
|
|
4522
|
+
execute: async () => {
|
|
4523
|
+
try {
|
|
4524
|
+
return redact(await innerExecute());
|
|
4525
|
+
} catch (error) {
|
|
4526
|
+
throw redact(error);
|
|
4527
|
+
}
|
|
4528
|
+
}
|
|
4529
|
+
}));
|
|
4530
|
+
} catch (error) {
|
|
4531
|
+
throw restore(error);
|
|
4532
|
+
}
|
|
4533
|
+
};
|
|
4454
4534
|
}
|
|
4455
4535
|
return await runWithTracingChannelSpan({
|
|
4456
4536
|
type: "languageModelCall",
|
|
@@ -7724,6 +7804,7 @@ function convertUserMessageToUIParts(message) {
|
|
|
7724
7804
|
function toUIMessageStream({ stream, tools, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => "An error occurred.", messageMetadata, originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish }) {
|
|
7725
7805
|
let outcome = { status: "unknown" };
|
|
7726
7806
|
let hasFatalFailure = false;
|
|
7807
|
+
const invalidToolCallIds = /* @__PURE__ */ new Set();
|
|
7727
7808
|
const setSourceOutcome = (newOutcome) => {
|
|
7728
7809
|
if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) outcome = newOutcome;
|
|
7729
7810
|
};
|
|
@@ -7775,8 +7856,10 @@ function toUIMessageStream({ stream, tools, sendReasoning = true, sendSources =
|
|
|
7775
7856
|
}
|
|
7776
7857
|
}).pipeThrough(new TransformStream({ transform: async (part, controller) => {
|
|
7777
7858
|
try {
|
|
7859
|
+
if (part.type === "tool-call" && part.invalid) invalidToolCallIds.add(part.toolCallId);
|
|
7860
|
+
const isInvalidToolCallError = part.type === "tool-error" && !part.providerExecuted && invalidToolCallIds.delete(part.toolCallId);
|
|
7778
7861
|
const messageMetadataValue = messageMetadata?.({ part });
|
|
7779
|
-
const uiMessageChunk = toUIMessageChunk(part, {
|
|
7862
|
+
const uiMessageChunk = isInvalidToolCallError ? void 0 : toUIMessageChunk(part, {
|
|
7780
7863
|
tools,
|
|
7781
7864
|
sendReasoning,
|
|
7782
7865
|
sendSources,
|
|
@@ -21014,7 +21097,10 @@ var AbstractChat = class {
|
|
|
21014
21097
|
get id() {
|
|
21015
21098
|
return this._id ??= this.generateId();
|
|
21016
21099
|
}
|
|
21017
|
-
constructor({ generateId = generateId$1, id, transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {
|
|
21100
|
+
constructor({ generateId = generateId$1, id, transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, experimental_queue = false }) {
|
|
21101
|
+
this.queuedMessagesFallback = [];
|
|
21102
|
+
this.queuedMessageOptions = /* @__PURE__ */ new Map();
|
|
21103
|
+
this.isQueuePaused = false;
|
|
21018
21104
|
this.pendingMessagePreparations = /* @__PURE__ */ new Set();
|
|
21019
21105
|
this.interruptedMessageIds = /* @__PURE__ */ new Set();
|
|
21020
21106
|
this.activeResponse = void 0;
|
|
@@ -21023,6 +21109,17 @@ var AbstractChat = class {
|
|
|
21023
21109
|
this.jobExecutor = new SerialJobExecutor();
|
|
21024
21110
|
this.activeStopCount = 0;
|
|
21025
21111
|
this.stopGeneration = 0;
|
|
21112
|
+
this.experimental_removeQueuedMessage = (id) => {
|
|
21113
|
+
this.queuedMessageOptions.delete(id);
|
|
21114
|
+
this.setQueuedMessages(this.experimental_queuedMessages.filter((message) => message.id !== id));
|
|
21115
|
+
};
|
|
21116
|
+
this.experimental_sendQueuedMessageNow = async (id) => {
|
|
21117
|
+
const message = this.experimental_queuedMessages.find((message) => message.id === id);
|
|
21118
|
+
if (message == null) return;
|
|
21119
|
+
this.setQueuedMessages([message, ...this.experimental_queuedMessages.filter((queued) => queued.id !== id)]);
|
|
21120
|
+
await this.stop();
|
|
21121
|
+
await this.resumeQueue({ skipWaitForUser: true });
|
|
21122
|
+
};
|
|
21026
21123
|
this.sendMessage = async (message, options) => {
|
|
21027
21124
|
if (message == null) {
|
|
21028
21125
|
let messageId = this.pendingApprovalMessageId;
|
|
@@ -21060,7 +21157,20 @@ var AbstractChat = class {
|
|
|
21060
21157
|
text: message.text
|
|
21061
21158
|
}] : []] };
|
|
21062
21159
|
} else uiMessage = message;
|
|
21160
|
+
if (this.queueEnabled && message.messageId == null && (this.isRequestInProgress() || this.isWaitingForUser() || this.experimental_queuedMessages.length > 0)) {
|
|
21161
|
+
const queuedMessage = {
|
|
21162
|
+
...uiMessage,
|
|
21163
|
+
id: uiMessage.id ?? this.generateId(),
|
|
21164
|
+
role: uiMessage.role ?? "user",
|
|
21165
|
+
metadata: message.metadata
|
|
21166
|
+
};
|
|
21167
|
+
if (options != null) this.queuedMessageOptions.set(queuedMessage.id, options);
|
|
21168
|
+
this.setQueuedMessages([...this.experimental_queuedMessages, queuedMessage]);
|
|
21169
|
+
await this.resumeQueue({ skipWaitForUser: this.isQueuePaused });
|
|
21170
|
+
return;
|
|
21171
|
+
}
|
|
21063
21172
|
if (message.messageId != null) {
|
|
21173
|
+
await this.clearQueueForHistoryChange();
|
|
21064
21174
|
const messageIndex = this.state.messages.findIndex((m) => m.id === message.messageId);
|
|
21065
21175
|
if (messageIndex === -1) throw new InvalidArgumentError({
|
|
21066
21176
|
parameter: "message.messageId",
|
|
@@ -21085,6 +21195,7 @@ var AbstractChat = class {
|
|
|
21085
21195
|
role: uiMessage.role ?? "user",
|
|
21086
21196
|
metadata: message.metadata
|
|
21087
21197
|
});
|
|
21198
|
+
this.isQueuePaused = false;
|
|
21088
21199
|
await this.makeRequest({
|
|
21089
21200
|
trigger: "submit-message",
|
|
21090
21201
|
messageId: message.messageId,
|
|
@@ -21092,6 +21203,7 @@ var AbstractChat = class {
|
|
|
21092
21203
|
});
|
|
21093
21204
|
};
|
|
21094
21205
|
this.regenerate = async ({ messageId, ...options } = {}) => {
|
|
21206
|
+
await this.clearQueueForHistoryChange();
|
|
21095
21207
|
const messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);
|
|
21096
21208
|
if (messageIndex === -1) throw new InvalidArgumentError({
|
|
21097
21209
|
parameter: "messageId",
|
|
@@ -21126,6 +21238,7 @@ var AbstractChat = class {
|
|
|
21126
21238
|
}
|
|
21127
21239
|
};
|
|
21128
21240
|
this.addToolApprovalResponse = async ({ id, approved, reason, options }) => this.jobExecutor.run(async () => {
|
|
21241
|
+
const stopGeneration = this.stopGeneration;
|
|
21129
21242
|
const messages = this.state.messages;
|
|
21130
21243
|
const updatePart = (part) => isToolUIPart(part) && part.state === "approval-requested" && part.approval.id === id ? {
|
|
21131
21244
|
...part,
|
|
@@ -21149,17 +21262,22 @@ var AbstractChat = class {
|
|
|
21149
21262
|
if (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
|
|
21150
21263
|
if (messageIndex !== -1 && this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
|
|
21151
21264
|
const shouldSend = await this.shouldSendAutomatically(messages[messageIndex].id);
|
|
21152
|
-
if (shouldSend)
|
|
21153
|
-
|
|
21154
|
-
|
|
21155
|
-
|
|
21156
|
-
|
|
21157
|
-
|
|
21158
|
-
|
|
21159
|
-
|
|
21265
|
+
if (shouldSend) {
|
|
21266
|
+
this.runAutomaticRequest(() => {
|
|
21267
|
+
const messageId = messageIndex === -1 ? this.lastMessage?.id : messages[messageIndex].id;
|
|
21268
|
+
return this.makeRequestForToolApproval({
|
|
21269
|
+
messageId,
|
|
21270
|
+
messageIndex,
|
|
21271
|
+
...options
|
|
21272
|
+
});
|
|
21273
|
+
}, shouldSend);
|
|
21274
|
+
return;
|
|
21275
|
+
}
|
|
21160
21276
|
}
|
|
21277
|
+
this.settleQueue({ stopGeneration });
|
|
21161
21278
|
});
|
|
21162
21279
|
this.addToolOutput = async ({ state, toolCallId, output, errorText, options }) => this.jobExecutor.run(async () => {
|
|
21280
|
+
const stopGeneration = this.stopGeneration;
|
|
21163
21281
|
const messages = this.state.messages;
|
|
21164
21282
|
const updatePart = (part) => {
|
|
21165
21283
|
if (!isToolUIPart(part) || part.toolCallId !== toolCallId) return part;
|
|
@@ -21195,12 +21313,16 @@ var AbstractChat = class {
|
|
|
21195
21313
|
if (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
|
|
21196
21314
|
if (messageIndex !== -1 && this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
|
|
21197
21315
|
const shouldSend = await this.shouldSendAutomatically(messages[messageIndex].id);
|
|
21198
|
-
if (shouldSend)
|
|
21199
|
-
|
|
21200
|
-
|
|
21201
|
-
|
|
21202
|
-
|
|
21316
|
+
if (shouldSend) {
|
|
21317
|
+
this.runAutomaticRequest(() => this.makeRequest({
|
|
21318
|
+
trigger: "submit-message",
|
|
21319
|
+
messageId: messages[messageIndex].id,
|
|
21320
|
+
...options
|
|
21321
|
+
}), shouldSend);
|
|
21322
|
+
return;
|
|
21323
|
+
}
|
|
21203
21324
|
}
|
|
21325
|
+
this.settleQueue({ stopGeneration });
|
|
21204
21326
|
});
|
|
21205
21327
|
this.addToolResult = this.addToolOutput;
|
|
21206
21328
|
this.stop = async () => {
|
|
@@ -21214,6 +21336,7 @@ var AbstractChat = class {
|
|
|
21214
21336
|
activeResponse?.abortController.abort();
|
|
21215
21337
|
await Promise.all([activeResumeRequest?.completionPromise, activeResponse?.completionPromise]);
|
|
21216
21338
|
await this.jobExecutor.waitForIdle();
|
|
21339
|
+
this.isQueuePaused = true;
|
|
21217
21340
|
} finally {
|
|
21218
21341
|
this.activeStopCount--;
|
|
21219
21342
|
}
|
|
@@ -21233,6 +21356,7 @@ var AbstractChat = class {
|
|
|
21233
21356
|
this.onFinish = onFinish;
|
|
21234
21357
|
this.onData = onData;
|
|
21235
21358
|
this.sendAutomaticallyWhen = sendAutomaticallyWhen;
|
|
21359
|
+
this.queueEnabled = experimental_queue;
|
|
21236
21360
|
}
|
|
21237
21361
|
/**
|
|
21238
21362
|
* Hook status:
|
|
@@ -21262,6 +21386,54 @@ var AbstractChat = class {
|
|
|
21262
21386
|
get lastMessage() {
|
|
21263
21387
|
return this.state.messages[this.state.messages.length - 1];
|
|
21264
21388
|
}
|
|
21389
|
+
/**
|
|
21390
|
+
* Experimental. Messages that wait to be sent when `experimental_queue` is
|
|
21391
|
+
* enabled, in the order they will be sent.
|
|
21392
|
+
*/
|
|
21393
|
+
get experimental_queuedMessages() {
|
|
21394
|
+
return this.state.experimental_queuedMessages ?? this.queuedMessagesFallback;
|
|
21395
|
+
}
|
|
21396
|
+
setQueuedMessages(experimental_queuedMessages) {
|
|
21397
|
+
if ("experimental_queuedMessages" in this.state) this.state.experimental_queuedMessages = experimental_queuedMessages;
|
|
21398
|
+
else this.queuedMessagesFallback = experimental_queuedMessages;
|
|
21399
|
+
}
|
|
21400
|
+
async resumeQueue({ skipWaitForUser }) {
|
|
21401
|
+
this.isQueuePaused = false;
|
|
21402
|
+
if (!this.isRequestInProgress() && this.hasUnsentApprovalResponse()) {
|
|
21403
|
+
await this.sendMessage();
|
|
21404
|
+
return;
|
|
21405
|
+
}
|
|
21406
|
+
await this.settleQueue({ skipWaitForUser });
|
|
21407
|
+
}
|
|
21408
|
+
async clearQueueForHistoryChange() {
|
|
21409
|
+
if (!this.queueEnabled) return;
|
|
21410
|
+
this.queuedMessageOptions.clear();
|
|
21411
|
+
this.setQueuedMessages([]);
|
|
21412
|
+
if (this.isRequestInProgress()) await this.stop();
|
|
21413
|
+
}
|
|
21414
|
+
isRequestInProgress() {
|
|
21415
|
+
return this.activeResponse != null || this.status === "submitted" || this.status === "streaming";
|
|
21416
|
+
}
|
|
21417
|
+
isWaitingForUser() {
|
|
21418
|
+
const lastMessage = this.lastMessage;
|
|
21419
|
+
return lastMessage?.role === "assistant" && lastMessage.parts.some((part) => isToolUIPart(part) && (part.state === "approval-requested" || part.state === "approval-responded" || !part.providerExecuted && (part.state === "input-streaming" || part.state === "input-available")));
|
|
21420
|
+
}
|
|
21421
|
+
hasUnsentApprovalResponse() {
|
|
21422
|
+
const lastMessage = this.lastMessage;
|
|
21423
|
+
return lastMessage?.role === "assistant" && lastMessage.parts.some((part) => isToolUIPart(part) && part.state === "approval-responded") && !lastMessage.parts.some((part) => isToolUIPart(part) && (part.state === "approval-requested" || !part.providerExecuted && (part.state === "input-streaming" || part.state === "input-available")));
|
|
21424
|
+
}
|
|
21425
|
+
async settleQueue({ stopGeneration = this.stopGeneration, skipWaitForUser = false } = {}) {
|
|
21426
|
+
const [message, ...rest] = this.experimental_queuedMessages;
|
|
21427
|
+
if (message == null || this.isQueuePaused || this.isRequestInProgress() || this.activeStopCount > 0 || stopGeneration !== this.stopGeneration || !skipWaitForUser && this.isWaitingForUser()) return;
|
|
21428
|
+
const options = this.queuedMessageOptions.get(message.id);
|
|
21429
|
+
this.queuedMessageOptions.delete(message.id);
|
|
21430
|
+
this.setQueuedMessages(rest);
|
|
21431
|
+
this.state.pushMessage(message);
|
|
21432
|
+
await this.makeRequest({
|
|
21433
|
+
trigger: "submit-message",
|
|
21434
|
+
...options
|
|
21435
|
+
});
|
|
21436
|
+
}
|
|
21265
21437
|
set messages(messages) {
|
|
21266
21438
|
this.state.messages = messages;
|
|
21267
21439
|
}
|
|
@@ -21273,9 +21445,10 @@ var AbstractChat = class {
|
|
|
21273
21445
|
async runAutomaticRequest(request, shouldSend) {
|
|
21274
21446
|
const stopGeneration = this.stopGeneration;
|
|
21275
21447
|
const startedWhileStopping = this.activeStopCount > 0;
|
|
21276
|
-
if (!(shouldSend ?? await this.shouldSendAutomatically())) return;
|
|
21277
|
-
if (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return;
|
|
21448
|
+
if (!(shouldSend ?? await this.shouldSendAutomatically())) return false;
|
|
21449
|
+
if (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return false;
|
|
21278
21450
|
await request();
|
|
21451
|
+
return true;
|
|
21279
21452
|
}
|
|
21280
21453
|
async makeRequestForToolApproval({ messageId, messageIndex, ...options }) {
|
|
21281
21454
|
const consumesPendingApproval = messageId != null && messageId === this.pendingApprovalMessageId;
|
|
@@ -21481,17 +21654,21 @@ var AbstractChat = class {
|
|
|
21481
21654
|
});
|
|
21482
21655
|
}
|
|
21483
21656
|
} finally {
|
|
21657
|
+
if (isAbort || isError || activeResponse?.state.finishReason === "interrupted") this.isQueuePaused = true;
|
|
21484
21658
|
if (this.activeResponse === activeResponse) this.activeResponse = void 0;
|
|
21485
21659
|
clearActiveResumeRequest();
|
|
21486
21660
|
}
|
|
21487
21661
|
}
|
|
21488
|
-
if (!isAbort && !isError && activeResponse?.state.finishReason !== "interrupted")
|
|
21489
|
-
|
|
21490
|
-
|
|
21491
|
-
|
|
21492
|
-
|
|
21493
|
-
|
|
21494
|
-
|
|
21662
|
+
if (!isAbort && !isError && activeResponse?.state.finishReason !== "interrupted") {
|
|
21663
|
+
const stopGeneration = this.stopGeneration;
|
|
21664
|
+
if (!await this.runAutomaticRequest(() => this.makeRequest({
|
|
21665
|
+
trigger: "submit-message",
|
|
21666
|
+
messageId: this.lastMessage?.id,
|
|
21667
|
+
metadata,
|
|
21668
|
+
headers,
|
|
21669
|
+
body
|
|
21670
|
+
}))) await this.settleQueue({ stopGeneration });
|
|
21671
|
+
}
|
|
21495
21672
|
}
|
|
21496
21673
|
};
|
|
21497
21674
|
//#endregion
|