@ykurilov/agent-chat-core 0.108.0 → 0.110.0
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 +26 -0
- package/README.md +2 -2
- package/dist/{chunk-FUIPWUAH.js → chunk-WMVDYLNE.js} +676 -539
- package/dist/chunk-WMVDYLNE.js.map +1 -0
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/storage-contract.js +1 -1
- package/dist/types/agent-run/run-agent-turn.d.ts +3 -1
- package/dist/types/agent-run/sealed-answer.d.ts +37 -0
- package/dist/types/agent-run/step-context.d.ts +13 -2
- package/dist/types/chat-service.d.ts +9 -2
- package/dist/types/index.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-FUIPWUAH.js.map +0 -1
|
@@ -1990,6 +1990,321 @@ function lengthCutForModel(part) {
|
|
|
1990
1990
|
return part.type === LENGTH_CUT_PART_TYPE ? { type: "text", text: LENGTH_CUT_NOTE } : void 0;
|
|
1991
1991
|
}
|
|
1992
1992
|
|
|
1993
|
+
// src/agent-run/turn-usage.ts
|
|
1994
|
+
import { asSchema } from "ai";
|
|
1995
|
+
|
|
1996
|
+
// src/conversation/token-usage.ts
|
|
1997
|
+
function emptyTokenUsage() {
|
|
1998
|
+
return { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningTokens: 0 };
|
|
1999
|
+
}
|
|
2000
|
+
function addTokenUsage(total, usage) {
|
|
2001
|
+
total.inputTokens += usage.inputTokens ?? 0;
|
|
2002
|
+
total.cachedInputTokens += usage.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
2003
|
+
total.outputTokens += usage.outputTokens ?? 0;
|
|
2004
|
+
total.reasoningTokens += usage.outputTokenDetails?.reasoningTokens ?? 0;
|
|
2005
|
+
const cacheWrite = usage.inputTokenDetails?.cacheWriteTokens ?? 0;
|
|
2006
|
+
if (cacheWrite > 0) total.cacheWriteTokens = (total.cacheWriteTokens ?? 0) + cacheWrite;
|
|
2007
|
+
}
|
|
2008
|
+
function isEmptyTokenUsage(usage) {
|
|
2009
|
+
return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.reasoningTokens === 0 && (usage.cacheWriteTokens ?? 0) === 0;
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
// src/agent-run/turn-usage.ts
|
|
2013
|
+
var SHARES_PER_TOKEN = 6;
|
|
2014
|
+
var FILE_SHARES = 1600 * SHARES_PER_TOKEN;
|
|
2015
|
+
var tokensOf = (shares) => Math.ceil(shares / SHARES_PER_TOKEN);
|
|
2016
|
+
function textShares(text) {
|
|
2017
|
+
let shares = 0;
|
|
2018
|
+
for (let index = 0; index < text.length; index++) shares += charShares(text.charCodeAt(index));
|
|
2019
|
+
return shares;
|
|
2020
|
+
}
|
|
2021
|
+
function charShares(code) {
|
|
2022
|
+
if (code < 128) return isLatinLetterDigitOrSpace(code) ? 2 : 3;
|
|
2023
|
+
return isDenseScript(code) ? 6 : 3;
|
|
2024
|
+
}
|
|
2025
|
+
function isLatinLetterDigitOrSpace(code) {
|
|
2026
|
+
const isLetterOrDigit = code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
|
|
2027
|
+
return isLetterOrDigit || code === 32 || code === 10 || code === 9 || code === 13;
|
|
2028
|
+
}
|
|
2029
|
+
function isDenseScript(code) {
|
|
2030
|
+
return code >= 11904 && code <= 40959 || code >= 44032 && code <= 57343 || code >= 63744 && code <= 64255 || code >= 65280 && code <= 65519;
|
|
2031
|
+
}
|
|
2032
|
+
function estimateTextTokens(text) {
|
|
2033
|
+
return tokensOf(textShares(text));
|
|
2034
|
+
}
|
|
2035
|
+
function createTurnUsage(now = () => /* @__PURE__ */ new Date()) {
|
|
2036
|
+
const steps = [];
|
|
2037
|
+
let providerId = "";
|
|
2038
|
+
let fixedShares = 0;
|
|
2039
|
+
let requestShares = [];
|
|
2040
|
+
let requestTimes = [];
|
|
2041
|
+
let startedSteps = 0;
|
|
2042
|
+
let finishedSteps = 0;
|
|
2043
|
+
let written = { shares: 0, reasoningShares: 0, content: false };
|
|
2044
|
+
let generationIds = [];
|
|
2045
|
+
let requestOpen = false;
|
|
2046
|
+
let streamedCalls = /* @__PURE__ */ new Set();
|
|
2047
|
+
function estimate(stepIndex, shares, reasoningShares) {
|
|
2048
|
+
const previous = steps.findLast((step) => !step.erased)?.usage;
|
|
2049
|
+
const inputTokens = Math.max(tokensOf(requestShares[stepIndex] ?? fixedShares), previous ? previous.inputTokens + previous.outputTokens : 0);
|
|
2050
|
+
const cachedInputTokens = previous && previous.cachedInputTokens > 0 ? Math.min(previous.inputTokens, inputTokens) : 0;
|
|
2051
|
+
return {
|
|
2052
|
+
inputTokens,
|
|
2053
|
+
cachedInputTokens,
|
|
2054
|
+
outputTokens: tokensOf(shares + reasoningShares),
|
|
2055
|
+
reasoningTokens: tokensOf(reasoningShares),
|
|
2056
|
+
estimated: true
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
function unfinishedStep() {
|
|
2060
|
+
const wroteSomething = startedSteps > finishedSteps && written.content;
|
|
2061
|
+
if (!wroteSomething && !requestOpen) return null;
|
|
2062
|
+
const index = wroteSomething ? startedSteps - 1 : finishedSteps;
|
|
2063
|
+
const usage = estimate(index, written.shares, written.reasoningShares);
|
|
2064
|
+
return { usage, providerId, generationIds, at: stepTime(index) };
|
|
2065
|
+
}
|
|
2066
|
+
function stepTime(index) {
|
|
2067
|
+
return requestTimes[index] ?? now().toISOString();
|
|
2068
|
+
}
|
|
2069
|
+
function nextStep() {
|
|
2070
|
+
written = { shares: 0, reasoningShares: 0, content: false };
|
|
2071
|
+
generationIds = [];
|
|
2072
|
+
requestOpen = false;
|
|
2073
|
+
}
|
|
2074
|
+
return {
|
|
2075
|
+
/** Новая попытка у провайдера `attemptProviderId`: инструкция и описания инструментов её запроса. */
|
|
2076
|
+
beginAttempt(request, attemptProviderId) {
|
|
2077
|
+
providerId = attemptProviderId;
|
|
2078
|
+
fixedShares = instructionsShares(request.instructions) + toolsShares(request.tools);
|
|
2079
|
+
requestShares = [];
|
|
2080
|
+
requestTimes = [];
|
|
2081
|
+
startedSteps = 0;
|
|
2082
|
+
finishedSteps = 0;
|
|
2083
|
+
nextStep();
|
|
2084
|
+
streamedCalls = /* @__PURE__ */ new Set();
|
|
2085
|
+
},
|
|
2086
|
+
/** Перед шагом попытки: сообщения его запроса. */
|
|
2087
|
+
beforeStep(stepNumber, messages) {
|
|
2088
|
+
requestShares[stepNumber] = fixedShares + messagesShares(messages);
|
|
2089
|
+
requestTimes[stepNumber] = now().toISOString();
|
|
2090
|
+
},
|
|
2091
|
+
/** Провайдер принял запрос идущего шага и начал поток: с этого мига вход оплачен (FR-051, FR-058). */
|
|
2092
|
+
requestOpened(request) {
|
|
2093
|
+
generationIds.push(request.generationId);
|
|
2094
|
+
requestOpen = true;
|
|
2095
|
+
},
|
|
2096
|
+
/** Провайдер сам отказал посреди потока: такой запрос не оплачивается. */
|
|
2097
|
+
requestRefused() {
|
|
2098
|
+
requestOpen = false;
|
|
2099
|
+
},
|
|
2100
|
+
/** Кусок UI-потока попытки: начала шагов и написанное. */
|
|
2101
|
+
observe(chunk) {
|
|
2102
|
+
if (chunk.type === "start-step") {
|
|
2103
|
+
startedSteps += 1;
|
|
2104
|
+
written = { shares: 0, reasoningShares: 0, content: false };
|
|
2105
|
+
return;
|
|
2106
|
+
}
|
|
2107
|
+
if (chunk.type === "text-delta") written.shares += textShares(chunk.delta);
|
|
2108
|
+
else if (chunk.type === "reasoning-delta") written.reasoningShares += textShares(chunk.delta);
|
|
2109
|
+
else if (chunk.type === "tool-input-delta") {
|
|
2110
|
+
streamedCalls.add(chunk.toolCallId);
|
|
2111
|
+
written.shares += textShares(chunk.inputTextDelta);
|
|
2112
|
+
} else if (chunk.type === "tool-input-available" && !streamedCalls.has(chunk.toolCallId)) {
|
|
2113
|
+
written.shares += textShares(JSON.stringify(chunk.input ?? null));
|
|
2114
|
+
} else if (!isWritten(chunk)) return;
|
|
2115
|
+
written.content = true;
|
|
2116
|
+
},
|
|
2117
|
+
/** Шаг завершён: числа провайдера или, если их нет, оценка. */
|
|
2118
|
+
finishStep(usage, content) {
|
|
2119
|
+
const index = finishedSteps;
|
|
2120
|
+
finishedSteps += 1;
|
|
2121
|
+
let stepUsage;
|
|
2122
|
+
if ((usage.inputTokens ?? 0) > 0 || (usage.outputTokens ?? 0) > 0) {
|
|
2123
|
+
stepUsage = emptyTokenUsage();
|
|
2124
|
+
addTokenUsage(stepUsage, usage);
|
|
2125
|
+
} else {
|
|
2126
|
+
const output = contentShares(content);
|
|
2127
|
+
stepUsage = estimate(index, output.shares, output.reasoningShares);
|
|
2128
|
+
}
|
|
2129
|
+
steps.push({ usage: stepUsage, providerId, generationIds, at: stepTime(index) });
|
|
2130
|
+
nextStep();
|
|
2131
|
+
},
|
|
2132
|
+
/** Шаг без запроса к провайдеру (готовый текст `endTurn`): в расход не идёт. */
|
|
2133
|
+
finishFreeStep() {
|
|
2134
|
+
finishedSteps += 1;
|
|
2135
|
+
nextStep();
|
|
2136
|
+
},
|
|
2137
|
+
/**
|
|
2138
|
+
* Попытка кончилась: недописанный шаг с написанным или с открытым запросом — в расход хода оценкой. `erased` — этот
|
|
2139
|
+
* шаг стёрт: оплачен, но следующий шаг его не видит.
|
|
2140
|
+
*/
|
|
2141
|
+
closeAttempt(options2 = {}) {
|
|
2142
|
+
const unfinished = unfinishedStep();
|
|
2143
|
+
if (unfinished) steps.push(options2.erased ? { ...unfinished, erased: true } : unfinished);
|
|
2144
|
+
finishedSteps = startedSteps;
|
|
2145
|
+
nextStep();
|
|
2146
|
+
},
|
|
2147
|
+
/** Расход каждого шага хода, без идущего. */
|
|
2148
|
+
steps() {
|
|
2149
|
+
return steps.map((step) => step.usage);
|
|
2150
|
+
},
|
|
2151
|
+
/** Шаги хода по провайдерам, в порядке первого шага у каждого: каждому — запись по его цене. */
|
|
2152
|
+
stepsByProvider() {
|
|
2153
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2154
|
+
for (const step of steps) groups.set(step.providerId, [...groups.get(step.providerId) ?? [], { ...step.usage, at: step.at }]);
|
|
2155
|
+
return [...groups].map(([id, usages]) => ({ providerId: id, steps: usages }));
|
|
2156
|
+
},
|
|
2157
|
+
/**
|
|
2158
|
+
* Шаги, расход которых стоит узнать у провайдера (FR-058): оценённый — все его генерации; оплаченный по числам —
|
|
2159
|
+
* генерации до последней (повторы, оборванные до первого куска). Шаг с генерацией без номера не узнать — его нет.
|
|
2160
|
+
*/
|
|
2161
|
+
stepsToSettle() {
|
|
2162
|
+
return steps.flatMap((step) => {
|
|
2163
|
+
const ids = step.usage.estimated ? step.generationIds : step.generationIds.slice(0, -1);
|
|
2164
|
+
if (ids.length === 0 || !ids.every((id) => id !== void 0)) return [];
|
|
2165
|
+
return [{ providerId: step.providerId, at: step.at, estimate: step.usage.estimated ? step.usage : null, generationIds: ids }];
|
|
2166
|
+
});
|
|
2167
|
+
},
|
|
2168
|
+
/** Шаги хода с провайдерами вместе с оценкой идущего — в идущий ответ для восстановления (FR-052). */
|
|
2169
|
+
pendingSteps() {
|
|
2170
|
+
const unfinished = unfinishedStep();
|
|
2171
|
+
return (unfinished ? [...steps, unfinished] : steps).map((step) => ({ ...step.usage, providerId: step.providerId, at: step.at }));
|
|
2172
|
+
},
|
|
2173
|
+
/** Расход хода на этот момент вместе с оценкой идущего шага; ничего не потрачено — `null`. */
|
|
2174
|
+
total() {
|
|
2175
|
+
const unfinished = unfinishedStep();
|
|
2176
|
+
return sumOfSteps((unfinished ? [...steps, unfinished] : steps).map((step) => step.usage));
|
|
2177
|
+
}
|
|
2178
|
+
};
|
|
2179
|
+
}
|
|
2180
|
+
function sumOfSteps(steps) {
|
|
2181
|
+
const last = steps.at(-1);
|
|
2182
|
+
if (!last) return null;
|
|
2183
|
+
const total = emptyTokenUsage();
|
|
2184
|
+
for (const step of steps) {
|
|
2185
|
+
total.inputTokens += step.inputTokens;
|
|
2186
|
+
total.cachedInputTokens += step.cachedInputTokens;
|
|
2187
|
+
total.outputTokens += step.outputTokens;
|
|
2188
|
+
total.reasoningTokens += step.reasoningTokens;
|
|
2189
|
+
if (step.cacheWriteTokens) total.cacheWriteTokens = (total.cacheWriteTokens ?? 0) + step.cacheWriteTokens;
|
|
2190
|
+
}
|
|
2191
|
+
const contextTokens = last.inputTokens + last.outputTokens;
|
|
2192
|
+
return { ...total, ...contextTokens > 0 && { contextTokens }, ...steps.some((step) => step.estimated) && { estimated: true } };
|
|
2193
|
+
}
|
|
2194
|
+
function isWritten(chunk) {
|
|
2195
|
+
return chunk.type.startsWith("source-") || chunk.type === "file" || chunk.type === "tool-approval-request" || chunk.type.startsWith("data-");
|
|
2196
|
+
}
|
|
2197
|
+
function instructionsShares(instructions) {
|
|
2198
|
+
if (typeof instructions === "string") return textShares(instructions);
|
|
2199
|
+
if (Array.isArray(instructions)) return instructions.reduce((sum, item) => sum + instructionsShares(item), 0);
|
|
2200
|
+
const content = instructions?.content;
|
|
2201
|
+
return typeof content === "string" ? textShares(content) : 0;
|
|
2202
|
+
}
|
|
2203
|
+
function toolsShares(tools) {
|
|
2204
|
+
let shares = 0;
|
|
2205
|
+
for (const [name, tool4] of Object.entries(tools ?? {})) {
|
|
2206
|
+
shares += textShares(name) + (typeof tool4.description === "string" ? textShares(tool4.description) : 0);
|
|
2207
|
+
const schema = tool4.inputSchema && asSchema(tool4.inputSchema).jsonSchema;
|
|
2208
|
+
if (schema && typeof schema.then !== "function") shares += textShares(JSON.stringify(schema));
|
|
2209
|
+
}
|
|
2210
|
+
return shares;
|
|
2211
|
+
}
|
|
2212
|
+
function messagesShares(messages) {
|
|
2213
|
+
let shares = 0;
|
|
2214
|
+
for (const message of messages) {
|
|
2215
|
+
if (typeof message.content === "string") shares += textShares(message.content);
|
|
2216
|
+
else for (const part of message.content) shares += partShares(part);
|
|
2217
|
+
}
|
|
2218
|
+
return shares;
|
|
2219
|
+
}
|
|
2220
|
+
function partShares(part) {
|
|
2221
|
+
switch (part.type) {
|
|
2222
|
+
case "text":
|
|
2223
|
+
case "reasoning":
|
|
2224
|
+
return textShares(part.text);
|
|
2225
|
+
case "image":
|
|
2226
|
+
case "file":
|
|
2227
|
+
return FILE_SHARES;
|
|
2228
|
+
case "tool-call":
|
|
2229
|
+
return textShares(part.toolName) + textShares(JSON.stringify(part.input ?? null));
|
|
2230
|
+
case "tool-result":
|
|
2231
|
+
return part.output.type === "content" ? part.output.value.reduce((sum, item) => sum + (item.type === "text" ? textShares(item.text) : FILE_SHARES), 0) : textShares(JSON.stringify(part.output));
|
|
2232
|
+
default:
|
|
2233
|
+
return textShares(JSON.stringify(part));
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
function contentShares(content) {
|
|
2237
|
+
let shares = 0;
|
|
2238
|
+
let reasoningShares = 0;
|
|
2239
|
+
for (const part of content) {
|
|
2240
|
+
if (part.type === "text") shares += textShares(part.text);
|
|
2241
|
+
else if (part.type === "reasoning") reasoningShares += textShares(part.text);
|
|
2242
|
+
else if (part.type === "tool-call") shares += textShares(JSON.stringify(part.input ?? null));
|
|
2243
|
+
}
|
|
2244
|
+
return { shares, reasoningShares };
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
// src/agent-run/step-context.ts
|
|
2248
|
+
var DEFAULT_STEP_CONTEXT_TIMEOUT_MS = 5e3;
|
|
2249
|
+
var STEP_CONTEXT_TAG = "step_context";
|
|
2250
|
+
var STEP_CONTEXT_LEAD = "\u0421\u043B\u0443\u0436\u0435\u0431\u043D\u044B\u0435 \u0441\u0442\u0440\u043E\u043A\u0438 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043A \u044D\u0442\u043E\u043C\u0443 \u0448\u0430\u0433\u0443 \u043E\u0442\u0432\u0435\u0442\u0430. \u042D\u0442\u043E \u043D\u0435 \u043D\u043E\u0432\u043E\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430: \u043E\u043D \u0438\u0445 \u043D\u0435 \u043F\u0438\u0441\u0430\u043B \u0438 \u043D\u0435 \u0432\u0438\u0434\u0438\u0442 \u0438 \u043E\u0442\u0432\u0435\u0442\u0430 \u043D\u0430 \u043D\u0438\u0445 \u043D\u0435 \u0436\u0434\u0451\u0442. \u0425\u043E\u0434 \u0442\u043E\u0442 \u0436\u0435: \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0430\u0439 \u043E\u0442\u0432\u0435\u0447\u0430\u0442\u044C \u043D\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0432\u044B\u0448\u0435.";
|
|
2251
|
+
function stepContextBlock(text) {
|
|
2252
|
+
return `<${STEP_CONTEXT_TAG}>
|
|
2253
|
+
${STEP_CONTEXT_LEAD}
|
|
2254
|
+
${text}
|
|
2255
|
+
</${STEP_CONTEXT_TAG}>`;
|
|
2256
|
+
}
|
|
2257
|
+
function createStepSnapshots(options2) {
|
|
2258
|
+
let previous;
|
|
2259
|
+
return {
|
|
2260
|
+
async messagesFor({ messages, trailing, context }) {
|
|
2261
|
+
const withoutPrevious = previous ? messages.filter((message) => message !== previous) : messages;
|
|
2262
|
+
previous = void 0;
|
|
2263
|
+
const own = await snapshotText(options2, context);
|
|
2264
|
+
if (!own) return { messages: withoutPrevious, tokens: 0 };
|
|
2265
|
+
const text = stepContextBlock(own);
|
|
2266
|
+
const snapshot = { role: "user", content: [{ type: "text", text }] };
|
|
2267
|
+
previous = snapshot;
|
|
2268
|
+
const at = withoutPrevious.length - Math.min(trailing, withoutPrevious.length);
|
|
2269
|
+
return { messages: [...withoutPrevious.slice(0, at), snapshot, ...withoutPrevious.slice(at)], tokens: estimateTextTokens(text) };
|
|
2270
|
+
}
|
|
2271
|
+
};
|
|
2272
|
+
}
|
|
2273
|
+
async function snapshotText(options2, context) {
|
|
2274
|
+
const timeoutMs = options2.timeoutMs ?? DEFAULT_STEP_CONTEXT_TIMEOUT_MS;
|
|
2275
|
+
const log = (message) => options2.logError(`[\u0441\u043D\u0438\u043C\u043E\u043A \u0448\u0430\u0433\u0430] \u0447\u0430\u0442=${options2.chatId} \u0448\u0430\u0433=${context.stepNumber} ${message}`);
|
|
2276
|
+
const stop = context.abortSignal;
|
|
2277
|
+
const ownAbort = new AbortController();
|
|
2278
|
+
let timer;
|
|
2279
|
+
let onStop;
|
|
2280
|
+
const cutOff = new Promise((resolve) => {
|
|
2281
|
+
if (Number.isFinite(timeoutMs)) timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
2282
|
+
onStop = () => resolve("stopped");
|
|
2283
|
+
if (stop.aborted) onStop();
|
|
2284
|
+
else stop.addEventListener("abort", onStop, { once: true });
|
|
2285
|
+
});
|
|
2286
|
+
try {
|
|
2287
|
+
const call = Promise.resolve().then(() => options2.stepContext({ ...context, abortSignal: AbortSignal.any([stop, ownAbort.signal]) }));
|
|
2288
|
+
const outcome = await Promise.race([call.then((text2) => ({ text: text2 })), cutOff]);
|
|
2289
|
+
if (outcome === "stopped") return null;
|
|
2290
|
+
if (outcome === "timeout") {
|
|
2291
|
+
ownAbort.abort(new Error(`stepContext \u043D\u0435 \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u0437\u0430 ${timeoutMs} \u043C\u0441`));
|
|
2292
|
+
log(`\u043D\u0435 \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u0437\u0430 ${timeoutMs} \u043C\u0441`);
|
|
2293
|
+
return null;
|
|
2294
|
+
}
|
|
2295
|
+
const { text } = outcome;
|
|
2296
|
+
if (text === null || text === void 0 || text === "") return null;
|
|
2297
|
+
if (typeof text !== "string") throw new TypeError(`stepContext \u0432\u0435\u0440\u043D\u0443\u043B ${typeof text}, \u0430 \u043D\u0435 \u0441\u0442\u0440\u043E\u043A\u0443`);
|
|
2298
|
+
return text;
|
|
2299
|
+
} catch (error) {
|
|
2300
|
+
log(error instanceof Error ? error.message : String(error));
|
|
2301
|
+
return null;
|
|
2302
|
+
} finally {
|
|
2303
|
+
clearTimeout(timer);
|
|
2304
|
+
stop.removeEventListener("abort", onStop);
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
|
|
1993
2308
|
// src/agent-run/unanswered-messages.ts
|
|
1994
2309
|
var UNANSWERED_NOTE = "[\u041E\u0442\u0432\u0435\u0442\u0430 \u043D\u0430 \u044D\u0442\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043D\u0435\u0442: \u0445\u043E\u0434 \u043E\u0431\u043E\u0440\u0432\u0430\u043B\u0441\u044F \u0434\u043E \u043F\u0435\u0440\u0432\u044B\u0445 \u0441\u043B\u043E\u0432]";
|
|
1995
2310
|
function withUnansweredMarked(messages) {
|
|
@@ -2010,6 +2325,7 @@ var CORE_SERVICE_BLOCKS = [
|
|
|
2010
2325
|
{ tag: "conversation_summary" },
|
|
2011
2326
|
{ tag: "answer_progress" },
|
|
2012
2327
|
{ tag: "screen_place" },
|
|
2328
|
+
{ tag: STEP_CONTEXT_TAG },
|
|
2013
2329
|
{ name: "service_note", line: "[\u0421\u043B\u0443\u0436\u0435\u0431\u043D\u0430\u044F \u043F\u043E\u043C\u0435\u0442\u043A\u0430 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F", match: /^\[Служебная пометка приложения, человек её не писал и не видит: .+\]$/ },
|
|
2014
2330
|
{ name: "context_gone", line: "[\u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0443\u0435\u0442: \xAB", match: /^\[Больше не действует: «[^»\n]+»(?:, «[^»\n]+»)*\]$/ },
|
|
2015
2331
|
{ name: "context_hidden", line: "[\u041D\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u043D\u043E \u0440\u0430\u0434\u0438 \u043C\u0435\u0441\u0442\u0430, \u043D\u043E \u043F\u043E-\u043F\u0440\u0435\u0436\u043D\u0435\u043C\u0443 \u0434\u0435\u0439\u0441\u0442\u0432\u0443\u0435\u0442: \xAB", match: /^\[Не показано ради места, но по-прежнему действует: «[^»\n]+»(?:, «[^»\n]+»)*\]$/ },
|
|
@@ -3139,6 +3455,299 @@ function isToolPart3(part) {
|
|
|
3139
3455
|
return part.type.startsWith("tool-") || part.type === "dynamic-tool";
|
|
3140
3456
|
}
|
|
3141
3457
|
|
|
3458
|
+
// src/widgets/basic-widgets.ts
|
|
3459
|
+
import { tool as tool2 } from "ai";
|
|
3460
|
+
import { z as z2 } from "zod";
|
|
3461
|
+
var BASIC_WIDGET_NAMES = ["ask_choice", "ask_form", "ask_multi_choice", "ask_rating", "suggest_replies"];
|
|
3462
|
+
var SUGGESTIONS_SHOWN = "\u043F\u043E\u043A\u0430\u0437\u0430\u043D\u043E";
|
|
3463
|
+
var FORM_TEXT_MAX = 2e3;
|
|
3464
|
+
var question = z2.string().min(1).max(300);
|
|
3465
|
+
var options = z2.array(z2.string().min(1).max(80)).min(2).max(8).refine((values) => new Set(values).size === values.length, "\u0412\u0430\u0440\u0438\u0430\u043D\u0442\u044B \u043D\u0435 \u0434\u043E\u043B\u0436\u043D\u044B \u043F\u043E\u0432\u0442\u043E\u0440\u044F\u0442\u044C\u0441\u044F");
|
|
3466
|
+
var choiceInput = z2.object({ question, options });
|
|
3467
|
+
var multiChoiceInput = z2.object({ question, options, min: z2.number().int().optional(), max: z2.number().int().optional() }).superRefine((input, context) => {
|
|
3468
|
+
const { min, max } = multiChoiceLimits(input);
|
|
3469
|
+
if (min < 1 || min > max || max > input.options.length) {
|
|
3470
|
+
context.addIssue({ code: "custom", message: "\u041D\u0443\u0436\u043D\u043E 1 \u2264 min \u2264 max \u2264 \u0447\u0438\u0441\u043B\u0430 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432", path: ["min"] });
|
|
3471
|
+
}
|
|
3472
|
+
});
|
|
3473
|
+
var ratingInput = z2.object({
|
|
3474
|
+
question,
|
|
3475
|
+
scale: z2.enum(["stars", "range"]),
|
|
3476
|
+
from: z2.union([z2.literal(0), z2.literal(1)]).optional(),
|
|
3477
|
+
to: z2.number().int().min(2).max(10).optional(),
|
|
3478
|
+
fromLabel: z2.string().min(1).max(40).optional(),
|
|
3479
|
+
toLabel: z2.string().min(1).max(40).optional()
|
|
3480
|
+
}).superRefine((input, context) => {
|
|
3481
|
+
const rangeFields = [input.from, input.to, input.fromLabel, input.toLabel].some((value) => value !== void 0);
|
|
3482
|
+
if (input.scale === "stars" && rangeFields) context.addIssue({ code: "custom", message: "\u0423 \u0437\u0432\u0451\u0437\u0434 \u043D\u0435\u0442 from, to \u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439", path: ["scale"] });
|
|
3483
|
+
if (input.scale === "range" && (input.from === void 0 || input.to === void 0)) {
|
|
3484
|
+
context.addIssue({ code: "custom", message: "\u0423 \u0448\u043A\u0430\u043B\u044B range \u043D\u0443\u0436\u043D\u044B from (0 \u0438\u043B\u0438 1) \u0438 to (2\u201310)", path: ["from"] });
|
|
3485
|
+
}
|
|
3486
|
+
});
|
|
3487
|
+
var formField = z2.object({
|
|
3488
|
+
name: z2.string().regex(/^[A-Za-z0-9_]+$/, "name \u2014 \u043B\u0430\u0442\u0438\u043D\u0438\u0446\u0430, \u0446\u0438\u0444\u0440\u044B \u0438 _").max(64),
|
|
3489
|
+
label: z2.string().min(1).max(80),
|
|
3490
|
+
kind: z2.enum(["text", "number", "date", "select"]),
|
|
3491
|
+
required: z2.boolean().optional(),
|
|
3492
|
+
min: z2.union([z2.number(), z2.string()]).optional(),
|
|
3493
|
+
max: z2.union([z2.number(), z2.string()]).optional(),
|
|
3494
|
+
options: options.optional(),
|
|
3495
|
+
multiline: z2.boolean().optional()
|
|
3496
|
+
}).superRefine((field, context) => {
|
|
3497
|
+
const issue = (message) => context.addIssue({ code: "custom", message, path: [field.name] });
|
|
3498
|
+
if (field.kind === "select" && !field.options) issue("\u0423 select \u043D\u0443\u0436\u043D\u044B options: 2\u20138 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432");
|
|
3499
|
+
if (field.kind !== "select" && field.options) issue("options \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0443 select");
|
|
3500
|
+
if (field.kind === "number") {
|
|
3501
|
+
if (field.min !== void 0 && typeof field.min !== "number" || field.max !== void 0 && typeof field.max !== "number") issue("\u0423 number min \u0438 max \u2014 \u0447\u0438\u0441\u043B\u0430");
|
|
3502
|
+
else if (field.min !== void 0 && field.max !== void 0 && field.min > field.max) issue("\u0423 number \u043D\u0443\u0436\u043D\u043E min \u2264 max");
|
|
3503
|
+
} else if (field.kind === "date") {
|
|
3504
|
+
const dates = [field.min, field.max].filter((value) => value !== void 0);
|
|
3505
|
+
if (dates.some((value) => typeof value !== "string" || !isCalendarDate(value))) issue("\u0423 date min \u0438 max \u2014 \u0434\u0430\u0442\u044B YYYY-MM-DD");
|
|
3506
|
+
else if (field.min !== void 0 && field.max !== void 0 && field.min > field.max) issue("\u0423 date \u043D\u0443\u0436\u043D\u043E min \u2264 max");
|
|
3507
|
+
} else if (field.min !== void 0 || field.max !== void 0) {
|
|
3508
|
+
issue("min \u0438 max \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0443 number \u0438 date");
|
|
3509
|
+
}
|
|
3510
|
+
});
|
|
3511
|
+
var formInput = z2.object({
|
|
3512
|
+
title: z2.string().min(1).max(300),
|
|
3513
|
+
fields: z2.array(formField).min(1).max(5).refine((fields) => new Set(fields.map((field) => field.name)).size === fields.length, "\u0418\u043C\u0435\u043D\u0430 \u043F\u043E\u043B\u0435\u0439 \u043D\u0435 \u0434\u043E\u043B\u0436\u043D\u044B \u043F\u043E\u0432\u0442\u043E\u0440\u044F\u0442\u044C\u0441\u044F")
|
|
3514
|
+
});
|
|
3515
|
+
var suggestInput = z2.object({ replies: z2.array(z2.string().min(1).max(60)).min(1).max(4) });
|
|
3516
|
+
var ANSWERED_BY_MESSAGE_NOTE = '\u0415\u0441\u043B\u0438 \u0447\u0435\u043B\u043E\u0432\u0435\u043A \u043E\u0442\u0432\u0435\u0442\u0438\u0442 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C, \u0430 \u043D\u0435 \u0432 \u0432\u0438\u0434\u0436\u0435\u0442\u0435, \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u0431\u0443\u0434\u0435\u0442 {"\u043E\u0442\u0432\u0435\u0442":"\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C"}, \u0430 \u0435\u0433\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043F\u0440\u0438\u0434\u0451\u0442 \u0441\u043B\u0435\u0434\u043E\u043C.';
|
|
3517
|
+
var ONE_QUESTION_NOTE = "\u0417\u0430\u0434\u0430\u0432\u0430\u0439 \u043E\u0434\u0438\u043D \u0432\u043E\u043F\u0440\u043E\u0441 \u0437\u0430 \u0440\u0430\u0437: \u043D\u0435 \u0431\u043E\u043B\u044C\u0448\u0435 \u043E\u0434\u043D\u043E\u0433\u043E \u0442\u0430\u043A\u043E\u0433\u043E \u0432\u044B\u0437\u043E\u0432\u0430 \u0432 \u0448\u0430\u0433\u0435.";
|
|
3518
|
+
var TOOLS = {
|
|
3519
|
+
ask_choice: tool2({
|
|
3520
|
+
description: `\u0421\u043F\u0440\u043E\u0441\u0438\u0442\u044C \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0438 \u0434\u0430\u0442\u044C \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043E\u0434\u0438\u043D \u0432\u0430\u0440\u0438\u0430\u043D\u0442 \u0438\u0437 2\u20138 \u043A\u043D\u043E\u043F\u043E\u043A. \u041E\u0442\u0432\u0435\u0442 \u0436\u0434\u0451\u0442 \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0438 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u0432\u044B\u0431\u0440\u0430\u043D\u043E":"<\u0432\u0430\u0440\u0438\u0430\u043D\u0442>"}. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
3521
|
+
inputSchema: choiceInput
|
|
3522
|
+
}),
|
|
3523
|
+
ask_multi_choice: tool2({
|
|
3524
|
+
description: `\u0421\u043F\u0440\u043E\u0441\u0438\u0442\u044C \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0438 \u0434\u0430\u0442\u044C \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432 \u0438\u0437 2\u20138 (min \u0438 max \u2014 \u0441\u043A\u043E\u043B\u044C\u043A\u043E \u043C\u043E\u0436\u043D\u043E \u0432\u044B\u0431\u0440\u0430\u0442\u044C). \u041E\u0442\u0432\u0435\u0442 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u0432\u044B\u0431\u0440\u0430\u043D\u043E":["<\u0432\u0430\u0440\u0438\u0430\u043D\u0442>",\u2026]} \u0432 \u043F\u043E\u0440\u044F\u0434\u043A\u0435 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
3525
|
+
inputSchema: multiChoiceInput
|
|
3526
|
+
}),
|
|
3527
|
+
ask_rating: tool2({
|
|
3528
|
+
description: `\u041F\u043E\u043F\u0440\u043E\u0441\u0438\u0442\u044C \u043E\u0446\u0435\u043D\u043A\u0443: \u0437\u0432\u0451\u0437\u0434\u044B 1\u20135 (scale "stars") \u0438\u043B\u0438 \u0448\u043A\u0430\u043B\u0430 \u043E\u0442 from (0 \u0438\u043B\u0438 1) \u0434\u043E to (2\u201310) \u0441 \u043F\u043E\u0434\u043F\u0438\u0441\u044F\u043C\u0438 \u043A\u0440\u0430\u0451\u0432 (scale "range"). \u041E\u0442\u0432\u0435\u0442 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u043E\u0446\u0435\u043D\u043A\u0430":<\u0446\u0435\u043B\u043E\u0435>}. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
3529
|
+
inputSchema: ratingInput
|
|
3530
|
+
}),
|
|
3531
|
+
ask_form: tool2({
|
|
3532
|
+
description: `\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043A\u043E\u0440\u043E\u0442\u043A\u0443\u044E \u0444\u043E\u0440\u043C\u0443 \u0438\u0437 1\u20135 \u043F\u043E\u043B\u0435\u0439: text, number (min, max), date (YYYY-MM-DD), select (2\u20138 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432). \u041E\u0442\u0432\u0435\u0442 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u043F\u043E\u043B\u044F":{"<name>":<\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435>}}; \u043F\u0443\u0441\u0442\u044B\u0435 \u043D\u0435\u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043F\u043E\u043B\u044F \u043D\u0435 \u043F\u0440\u0438\u0445\u043E\u0434\u044F\u0442. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
3533
|
+
inputSchema: formInput
|
|
3534
|
+
}),
|
|
3535
|
+
suggest_replies: tool2({
|
|
3536
|
+
description: `\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043F\u043E\u0434 \u043E\u0442\u0432\u0435\u0442\u043E\u043C 1\u20134 \u043A\u043E\u0440\u043E\u0442\u043A\u0438\u0445 \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0447\u0435\u043B\u043E\u0432\u0435\u043A \u043C\u043E\u0436\u0435\u0442 \u043E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C \u043E\u0434\u043D\u0438\u043C \u043D\u0430\u0436\u0430\u0442\u0438\u0435\u043C. \u0425\u043E\u0434 \u043D\u0435 \u0436\u0434\u0451\u0442: \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u0441\u0440\u0430\u0437\u0443 "${SUGGESTIONS_SHOWN}". \u041D\u0430\u0436\u0430\u0442\u0430\u044F \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0430 \u043F\u0440\u0438\u0434\u0451\u0442 \u043E\u0431\u044B\u0447\u043D\u044B\u043C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C.`,
|
|
3537
|
+
inputSchema: suggestInput,
|
|
3538
|
+
execute: () => SUGGESTIONS_SHOWN
|
|
3539
|
+
})
|
|
3540
|
+
};
|
|
3541
|
+
function basicWidgetTool(name) {
|
|
3542
|
+
return TOOLS[name];
|
|
3543
|
+
}
|
|
3544
|
+
function checkBasicWidgetAnswer(name, input, answer) {
|
|
3545
|
+
switch (name) {
|
|
3546
|
+
case "ask_choice":
|
|
3547
|
+
return checkChoice(input, answer);
|
|
3548
|
+
case "ask_multi_choice":
|
|
3549
|
+
return checkMultiChoice(input, answer);
|
|
3550
|
+
case "ask_rating":
|
|
3551
|
+
return checkRating(input, answer);
|
|
3552
|
+
case "ask_form":
|
|
3553
|
+
return checkForm(input, answer);
|
|
3554
|
+
case "suggest_replies":
|
|
3555
|
+
return REJECTED;
|
|
3556
|
+
}
|
|
3557
|
+
}
|
|
3558
|
+
var REJECTED = { ok: false };
|
|
3559
|
+
function checkChoice(input, answer) {
|
|
3560
|
+
const call = choiceInput.safeParse(input);
|
|
3561
|
+
const value = onlyField(answer, "\u0432\u044B\u0431\u0440\u0430\u043D\u043E");
|
|
3562
|
+
if (!call.success || typeof value !== "string" || !call.data.options.includes(value)) return REJECTED;
|
|
3563
|
+
return { ok: true, output: { \u0432\u044B\u0431\u0440\u0430\u043D\u043E: value } };
|
|
3564
|
+
}
|
|
3565
|
+
function checkMultiChoice(input, answer) {
|
|
3566
|
+
const call = multiChoiceInput.safeParse(input);
|
|
3567
|
+
const value = onlyField(answer, "\u0432\u044B\u0431\u0440\u0430\u043D\u043E");
|
|
3568
|
+
if (!call.success || !Array.isArray(value)) return REJECTED;
|
|
3569
|
+
const chosen = new Set(value);
|
|
3570
|
+
const { min, max } = multiChoiceLimits(call.data);
|
|
3571
|
+
const known = value.every((option) => typeof option === "string" && call.data.options.includes(option));
|
|
3572
|
+
if (!known || chosen.size !== value.length || value.length < min || value.length > max) return REJECTED;
|
|
3573
|
+
return { ok: true, output: { \u0432\u044B\u0431\u0440\u0430\u043D\u043E: call.data.options.filter((option) => chosen.has(option)) } };
|
|
3574
|
+
}
|
|
3575
|
+
function checkRating(input, answer) {
|
|
3576
|
+
const call = ratingInput.safeParse(input);
|
|
3577
|
+
const value = onlyField(answer, "\u043E\u0446\u0435\u043D\u043A\u0430");
|
|
3578
|
+
if (!call.success || typeof value !== "number" || !Number.isInteger(value)) return REJECTED;
|
|
3579
|
+
const { from, to } = ratingLimits(call.data);
|
|
3580
|
+
if (value < from || value > to) return REJECTED;
|
|
3581
|
+
return { ok: true, output: { \u043E\u0446\u0435\u043D\u043A\u0430: value } };
|
|
3582
|
+
}
|
|
3583
|
+
function checkForm(input, answer) {
|
|
3584
|
+
const call = formInput.safeParse(input);
|
|
3585
|
+
const values = onlyField(answer, "\u043F\u043E\u043B\u044F");
|
|
3586
|
+
if (!call.success || !isPlainObject(values)) return REJECTED;
|
|
3587
|
+
const fields = call.data.fields;
|
|
3588
|
+
if (Object.keys(values).some((key) => !fields.some((field) => field.name === key))) return REJECTED;
|
|
3589
|
+
const output = {};
|
|
3590
|
+
for (const field of fields) {
|
|
3591
|
+
const value = values[field.name];
|
|
3592
|
+
if (isEmptyValue(value)) {
|
|
3593
|
+
if (field.required) return REJECTED;
|
|
3594
|
+
continue;
|
|
3595
|
+
}
|
|
3596
|
+
if (!fieldValueFits(field, value)) return REJECTED;
|
|
3597
|
+
output[field.name] = value;
|
|
3598
|
+
}
|
|
3599
|
+
return { ok: true, output: { \u043F\u043E\u043B\u044F: output } };
|
|
3600
|
+
}
|
|
3601
|
+
function fieldValueFits(field, value) {
|
|
3602
|
+
switch (field.kind) {
|
|
3603
|
+
case "text":
|
|
3604
|
+
return typeof value === "string" && value.length <= FORM_TEXT_MAX;
|
|
3605
|
+
case "number":
|
|
3606
|
+
return typeof value === "number" && Number.isFinite(value) && (typeof field.min !== "number" || value >= field.min) && (typeof field.max !== "number" || value <= field.max);
|
|
3607
|
+
case "date":
|
|
3608
|
+
return typeof value === "string" && isCalendarDate(value) && (typeof field.min !== "string" || value >= field.min) && (typeof field.max !== "string" || value <= field.max);
|
|
3609
|
+
case "select":
|
|
3610
|
+
return typeof value === "string" && (field.options ?? []).includes(value);
|
|
3611
|
+
}
|
|
3612
|
+
}
|
|
3613
|
+
function isEmptyValue(value) {
|
|
3614
|
+
return value === void 0 || value === null || typeof value === "string" && value.trim() === "";
|
|
3615
|
+
}
|
|
3616
|
+
function multiChoiceLimits(input) {
|
|
3617
|
+
return { min: input.min ?? 1, max: input.max ?? input.options.length };
|
|
3618
|
+
}
|
|
3619
|
+
function ratingLimits(input) {
|
|
3620
|
+
return input.scale === "stars" ? { from: 1, to: 5 } : { from: input.from ?? 0, to: input.to ?? 10 };
|
|
3621
|
+
}
|
|
3622
|
+
function onlyField(answer, key) {
|
|
3623
|
+
if (!isPlainObject(answer)) return void 0;
|
|
3624
|
+
const keys = Object.keys(answer);
|
|
3625
|
+
return keys.length === 1 && keys[0] === key ? answer[key] : void 0;
|
|
3626
|
+
}
|
|
3627
|
+
function isPlainObject(value) {
|
|
3628
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3629
|
+
}
|
|
3630
|
+
function isCalendarDate(value) {
|
|
3631
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
3632
|
+
const date = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
|
|
3633
|
+
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
|
3634
|
+
}
|
|
3635
|
+
|
|
3636
|
+
// src/agent-run/sealed-answer.ts
|
|
3637
|
+
import { wrapLanguageModel as wrapLanguageModel4 } from "ai";
|
|
3638
|
+
var SUGGESTIONS_TOOL = "suggest_replies";
|
|
3639
|
+
var SUGGESTIONS_SHOWN_AFTER_ANSWER = `${SUGGESTIONS_SHOWN}. \u041E\u0442\u0432\u0435\u0442 \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0443 \u043D\u0430 \u044D\u0442\u043E\u043C \u0437\u0430\u043A\u043E\u043D\u0447\u0435\u043D: \u043D\u043E\u0432\u044B\u0439 \u0442\u0435\u043A\u0441\u0442 \u0432 \u044D\u0442\u043E\u043C \u0445\u043E\u0434\u0435 \u043E\u043D \u043D\u0435 \u0443\u0432\u0438\u0434\u0438\u0442. \u041D\u0443\u0436\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0432\u044B\u0437\u044B\u0432\u0430\u0439 \u043A\u0430\u043A \u043E\u0431\u044B\u0447\u043D\u043E.`;
|
|
3640
|
+
function newStep() {
|
|
3641
|
+
let end;
|
|
3642
|
+
const ended = new Promise((resolve) => {
|
|
3643
|
+
end = resolve;
|
|
3644
|
+
});
|
|
3645
|
+
return { text: false, calls: [], shown: false, ended, end };
|
|
3646
|
+
}
|
|
3647
|
+
function createSealedAnswerGuard(serviceTools = /* @__PURE__ */ new Set()) {
|
|
3648
|
+
let sealed = false;
|
|
3649
|
+
let droppedChars = 0;
|
|
3650
|
+
let step;
|
|
3651
|
+
const closes = (candidate) => candidate !== void 0 && candidate.text && candidate.shown && candidate.calls.every((name) => name === SUGGESTIONS_TOOL || serviceTools.has(name));
|
|
3652
|
+
return {
|
|
3653
|
+
/** Новая попытка хода: закрыт ли ответ, решают части, уже написанные этим ответом. */
|
|
3654
|
+
reset(parts) {
|
|
3655
|
+
sealed = sealedByParts(parts, closes);
|
|
3656
|
+
step = void 0;
|
|
3657
|
+
},
|
|
3658
|
+
/** Ответ закрыт подсказками (с учётом последнего шага). */
|
|
3659
|
+
sealed: () => sealed || closes(step),
|
|
3660
|
+
/** Сколько знаков текста не показано после закрытия ответа (за весь ход). */
|
|
3661
|
+
droppedChars: () => droppedChars,
|
|
3662
|
+
/**
|
|
3663
|
+
* Подсказки отмечают шаг показанными. Когда шаг закрывает ответ (или ответ уже закрыт), модель получает
|
|
3664
|
+
* `SUGGESTIONS_SHOWN_AFTER_ANSWER`: результат ждёт конца потока шага, чтобы знать все его вызовы.
|
|
3665
|
+
*/
|
|
3666
|
+
tools(tools) {
|
|
3667
|
+
const original = tools?.[SUGGESTIONS_TOOL];
|
|
3668
|
+
const execute = original?.execute;
|
|
3669
|
+
if (!tools || !original || !execute) return tools;
|
|
3670
|
+
return {
|
|
3671
|
+
...tools,
|
|
3672
|
+
[SUGGESTIONS_TOOL]: {
|
|
3673
|
+
...original,
|
|
3674
|
+
execute: async (input, options2) => {
|
|
3675
|
+
const own = step;
|
|
3676
|
+
const output = await execute(input, options2);
|
|
3677
|
+
if (!own) return output;
|
|
3678
|
+
own.shown = true;
|
|
3679
|
+
if (output !== SUGGESTIONS_SHOWN) return output;
|
|
3680
|
+
await Promise.race([own.ended, aborted(options2.abortSignal)]);
|
|
3681
|
+
return sealed || closes(own) ? SUGGESTIONS_SHOWN_AFTER_ANSWER : output;
|
|
3682
|
+
}
|
|
3683
|
+
}
|
|
3684
|
+
};
|
|
3685
|
+
},
|
|
3686
|
+
wrap(model) {
|
|
3687
|
+
if (typeof model === "string") return model;
|
|
3688
|
+
return wrapLanguageModel4({
|
|
3689
|
+
model,
|
|
3690
|
+
middleware: {
|
|
3691
|
+
specificationVersion: "v4",
|
|
3692
|
+
wrapStream: async ({ doStream }) => {
|
|
3693
|
+
if (closes(step)) sealed = true;
|
|
3694
|
+
step?.end();
|
|
3695
|
+
const current = newStep();
|
|
3696
|
+
step = current;
|
|
3697
|
+
const result = await doStream();
|
|
3698
|
+
const transform = (part, controller) => {
|
|
3699
|
+
if (part.type === "text-start" || part.type === "text-delta" || part.type === "text-end") {
|
|
3700
|
+
if (sealed) {
|
|
3701
|
+
if (part.type === "text-delta") droppedChars += part.delta.length;
|
|
3702
|
+
return;
|
|
3703
|
+
}
|
|
3704
|
+
if (part.type === "text-delta" && hasText2(part.delta)) current.text = true;
|
|
3705
|
+
} else if (part.type === "tool-call") {
|
|
3706
|
+
current.calls.push(part.toolName);
|
|
3707
|
+
} else if (part.type === "finish" || part.type === "error") {
|
|
3708
|
+
current.end();
|
|
3709
|
+
}
|
|
3710
|
+
controller.enqueue(part);
|
|
3711
|
+
};
|
|
3712
|
+
return { ...result, stream: result.stream.pipeThrough(new TransformStream({ transform, flush: () => current.end() })) };
|
|
3713
|
+
}
|
|
3714
|
+
}
|
|
3715
|
+
});
|
|
3716
|
+
}
|
|
3717
|
+
};
|
|
3718
|
+
}
|
|
3719
|
+
function sealedByParts(parts, closes) {
|
|
3720
|
+
let current = newStep();
|
|
3721
|
+
for (const part of parts) {
|
|
3722
|
+
if (part.type === "step-start") {
|
|
3723
|
+
if (closes(current)) return true;
|
|
3724
|
+
current = newStep();
|
|
3725
|
+
} else if (part.type === "text" && hasText2(part.text)) current.text = true;
|
|
3726
|
+
else if (isToolPart4(part)) {
|
|
3727
|
+
const name = part.type === "dynamic-tool" ? part.toolName : part.type.slice("tool-".length);
|
|
3728
|
+
current.calls.push(name);
|
|
3729
|
+
if (name === SUGGESTIONS_TOOL && part.state === "output-available") current.shown = true;
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
return closes(current);
|
|
3733
|
+
}
|
|
3734
|
+
function sealedAnswerEndsOnTool(parts) {
|
|
3735
|
+
const lastCall = parts.findLastIndex(isToolPart4);
|
|
3736
|
+
return lastCall !== -1 && !parts.slice(lastCall + 1).some((part) => part.type === "text" && hasText2(part.text));
|
|
3737
|
+
}
|
|
3738
|
+
function isToolPart4(part) {
|
|
3739
|
+
return part.type.startsWith("tool-") || part.type === "dynamic-tool";
|
|
3740
|
+
}
|
|
3741
|
+
function hasText2(text) {
|
|
3742
|
+
return text.replace(/[\s\p{Cf}\p{Default_Ignorable_Code_Point}]/gu, "").length > 0;
|
|
3743
|
+
}
|
|
3744
|
+
function aborted(signal) {
|
|
3745
|
+
if (!signal) return new Promise(() => {
|
|
3746
|
+
});
|
|
3747
|
+
if (signal.aborted) return Promise.resolve();
|
|
3748
|
+
return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
|
|
3749
|
+
}
|
|
3750
|
+
|
|
3142
3751
|
// src/agent-run/tool-timeout.ts
|
|
3143
3752
|
var DEFAULT_TOOL_TIMEOUT_MS = 12e4;
|
|
3144
3753
|
var TOOL_TIMEOUT_HINT = /* @__PURE__ */ Symbol.for("@ykurilov/agent-chat.toolTimeoutMs");
|
|
@@ -3156,8 +3765,8 @@ function resolveToolTimeout(setting) {
|
|
|
3156
3765
|
const all = resolveTimeoutMs(setting, DEFAULT_TOOL_TIMEOUT_MS, "agent.toolTimeoutMs");
|
|
3157
3766
|
return { forTool: (_toolName, declaredMs) => atLeastDeclared(all, declaredMs) };
|
|
3158
3767
|
}
|
|
3159
|
-
if (!
|
|
3160
|
-
if (setting.byTool !== void 0 && !
|
|
3768
|
+
if (!isPlainObject2(setting)) throw new TypeError("agent.toolTimeoutMs: \u0436\u0434\u0451\u043C \u0447\u0438\u0441\u043B\u043E \u043C\u0441 \u0438\u043B\u0438 \u043E\u0431\u044A\u0435\u043A\u0442 { default?, byTool? }");
|
|
3769
|
+
if (setting.byTool !== void 0 && !isPlainObject2(setting.byTool)) {
|
|
3161
3770
|
throw new TypeError("agent.toolTimeoutMs.byTool: \u0436\u0434\u0451\u043C \u043E\u0431\u044A\u0435\u043A\u0442 \xAB\u0438\u043C\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 \u2192 \u0441\u0440\u043E\u043A, \u043C\u0441\xBB");
|
|
3162
3771
|
}
|
|
3163
3772
|
const fallback = resolveTimeoutMs(setting.default, DEFAULT_TOOL_TIMEOUT_MS, "agent.toolTimeoutMs.default");
|
|
@@ -3169,7 +3778,7 @@ function resolveToolTimeout(setting) {
|
|
|
3169
3778
|
);
|
|
3170
3779
|
return { forTool: (toolName, declaredMs) => byTool.get(toolName) ?? atLeastDeclared(fallback, declaredMs) };
|
|
3171
3780
|
}
|
|
3172
|
-
function
|
|
3781
|
+
function isPlainObject2(value) {
|
|
3173
3782
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3174
3783
|
}
|
|
3175
3784
|
var toolTimeoutMessage = (timeoutMs) => `\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 \u043D\u0435 \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u0437\u0430 ${Math.max(1, Math.round(timeoutMs / 1e3))} \u0441 \u0438 \u043E\u0442\u043C\u0435\u043D\u0451\u043D. \u0412\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u043E \u043B\u0438 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435, \u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u043E; \u043D\u0435 \u043F\u043E\u0432\u0442\u043E\u0440\u044F\u0439 \u0435\u0433\u043E, \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0438\u0432`;
|
|
@@ -3426,22 +4035,6 @@ async function resolveViewerOutsideTurn(source, turn, signal) {
|
|
|
3426
4035
|
// src/helpers/run-helper.ts
|
|
3427
4036
|
import { generateText as generateText2, stepCountIs as stepCountIs2 } from "ai";
|
|
3428
4037
|
|
|
3429
|
-
// src/conversation/token-usage.ts
|
|
3430
|
-
function emptyTokenUsage() {
|
|
3431
|
-
return { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningTokens: 0 };
|
|
3432
|
-
}
|
|
3433
|
-
function addTokenUsage(total, usage) {
|
|
3434
|
-
total.inputTokens += usage.inputTokens ?? 0;
|
|
3435
|
-
total.cachedInputTokens += usage.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
3436
|
-
total.outputTokens += usage.outputTokens ?? 0;
|
|
3437
|
-
total.reasoningTokens += usage.outputTokenDetails?.reasoningTokens ?? 0;
|
|
3438
|
-
const cacheWrite = usage.inputTokenDetails?.cacheWriteTokens ?? 0;
|
|
3439
|
-
if (cacheWrite > 0) total.cacheWriteTokens = (total.cacheWriteTokens ?? 0) + cacheWrite;
|
|
3440
|
-
}
|
|
3441
|
-
function isEmptyTokenUsage(usage) {
|
|
3442
|
-
return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.reasoningTokens === 0 && (usage.cacheWriteTokens ?? 0) === 0;
|
|
3443
|
-
}
|
|
3444
|
-
|
|
3445
4038
|
// src/provider-errors/error-signs.ts
|
|
3446
4039
|
var signs = (patterns) => new RegExp(patterns.join("|"), "i");
|
|
3447
4040
|
var OVERFLOW_SIGNS = [
|
|
@@ -4002,13 +4595,13 @@ function usageMinusJournaled(usage, journaled) {
|
|
|
4002
4595
|
}
|
|
4003
4596
|
|
|
4004
4597
|
// src/agent-run/build-model-request.ts
|
|
4005
|
-
import { convertToModelMessages, wrapLanguageModel as
|
|
4598
|
+
import { convertToModelMessages, wrapLanguageModel as wrapLanguageModel7 } from "ai";
|
|
4006
4599
|
|
|
4007
4600
|
// src/conversation/hanging-tool-calls.ts
|
|
4008
4601
|
var PRELIMINARY_OUTPUT_MAX_LENGTH = 2e3;
|
|
4009
|
-
var
|
|
4602
|
+
var isToolPart5 = (part) => part.type.startsWith("tool-") || part.type === "dynamic-tool";
|
|
4010
4603
|
var isHangingToolCall = (part) => {
|
|
4011
|
-
if (!
|
|
4604
|
+
if (!isToolPart5(part)) return false;
|
|
4012
4605
|
const { state, preliminary } = part;
|
|
4013
4606
|
return state === "input-available" || state === "output-available" && preliminary === true;
|
|
4014
4607
|
};
|
|
@@ -4031,11 +4624,11 @@ function closeHangingToolCalls(parts, options2 = {}) {
|
|
|
4031
4624
|
});
|
|
4032
4625
|
}
|
|
4033
4626
|
var isFinished = (part) => {
|
|
4034
|
-
if (!
|
|
4627
|
+
if (!isToolPart5(part)) return false;
|
|
4035
4628
|
const { state, preliminary } = part;
|
|
4036
4629
|
return state === "output-available" && preliminary !== true || state === "output-error" || state === "output-denied";
|
|
4037
4630
|
};
|
|
4038
|
-
var isStreamingInput = (part) =>
|
|
4631
|
+
var isStreamingInput = (part) => isToolPart5(part) && part.state === "input-streaming";
|
|
4039
4632
|
function withoutProviderData(part) {
|
|
4040
4633
|
const { providerMetadata: _provider, callProviderMetadata: _call, resultProviderMetadata: _result, ...rest } = part;
|
|
4041
4634
|
return rest;
|
|
@@ -4110,10 +4703,10 @@ function autoContinuePauseMs(input) {
|
|
|
4110
4703
|
const requested = requestedRetryMs(input.error, (input.now ?? Date.now)()) ?? 0;
|
|
4111
4704
|
return Math.min(Math.max(requested, scheduled), MAX_REQUESTED_PAUSE_MS);
|
|
4112
4705
|
}
|
|
4113
|
-
var
|
|
4706
|
+
var isToolPart6 = (part) => part.type.startsWith("tool-") || part.type === "dynamic-tool";
|
|
4114
4707
|
function isFinished2(part) {
|
|
4115
4708
|
const { state, preliminary } = part;
|
|
4116
|
-
if (
|
|
4709
|
+
if (isToolPart6(part)) return state === "output-available" && preliminary !== true || state === "output-error" || state === "output-denied";
|
|
4117
4710
|
return state === "done";
|
|
4118
4711
|
}
|
|
4119
4712
|
function partsLeftOutOfAutoContinue(parts) {
|
|
@@ -4121,7 +4714,7 @@ function partsLeftOutOfAutoContinue(parts) {
|
|
|
4121
4714
|
const left = [];
|
|
4122
4715
|
parts.forEach((part, index) => {
|
|
4123
4716
|
const { state } = part;
|
|
4124
|
-
if (
|
|
4717
|
+
if (isToolPart6(part) && state === "input-streaming") left.push(index);
|
|
4125
4718
|
else if (part.type === "reasoning" && state === "streaming" && index > lastFinished) left.push(index);
|
|
4126
4719
|
});
|
|
4127
4720
|
return left;
|
|
@@ -4152,7 +4745,7 @@ var UNSENT_TOOL_CALL_REASON = "\u0412\u044B\u0437\u043E\u0432 \u043E\u0431\u043E
|
|
|
4152
4745
|
function closingChunksForHangingCalls(parts) {
|
|
4153
4746
|
const lastStep = parts.findLastIndex((part) => part.type === "step-start");
|
|
4154
4747
|
return parts.slice(lastStep + 1).flatMap((part) => {
|
|
4155
|
-
if (!
|
|
4748
|
+
if (!isToolPart6(part)) return [];
|
|
4156
4749
|
const { toolCallId, state, toolName } = part;
|
|
4157
4750
|
if (isHangingToolCall(part)) return [{ type: "tool-output-error", toolCallId, errorText: hangingToolCallText(part) }];
|
|
4158
4751
|
if (state !== "input-streaming") return [];
|
|
@@ -4222,7 +4815,7 @@ ${chunk.delta}` } : chunk];
|
|
|
4222
4815
|
}
|
|
4223
4816
|
|
|
4224
4817
|
// src/agent-run/observe-model-calls.ts
|
|
4225
|
-
import { wrapLanguageModel as
|
|
4818
|
+
import { wrapLanguageModel as wrapLanguageModel5 } from "ai";
|
|
4226
4819
|
function observeModelCalls(model, context) {
|
|
4227
4820
|
if (typeof model === "string") return model;
|
|
4228
4821
|
const now = context.now ?? Date.now;
|
|
@@ -4232,7 +4825,7 @@ function observeModelCalls(model, context) {
|
|
|
4232
4825
|
attempts.set(params.prompt, attempt);
|
|
4233
4826
|
return attempt;
|
|
4234
4827
|
};
|
|
4235
|
-
return
|
|
4828
|
+
return wrapLanguageModel5({
|
|
4236
4829
|
model,
|
|
4237
4830
|
middleware: {
|
|
4238
4831
|
specificationVersion: "v4",
|
|
@@ -4374,262 +4967,26 @@ function requestOf(params) {
|
|
|
4374
4967
|
function toolCallOf(part) {
|
|
4375
4968
|
return { toolCallId: part.toolCallId, toolName: part.toolName, input: parsedInput(part.input) };
|
|
4376
4969
|
}
|
|
4377
|
-
function parsedInput(input) {
|
|
4378
|
-
try {
|
|
4379
|
-
return JSON.parse(input);
|
|
4380
|
-
} catch {
|
|
4381
|
-
return input;
|
|
4382
|
-
}
|
|
4383
|
-
}
|
|
4384
|
-
function usageOf(usage) {
|
|
4385
|
-
return {
|
|
4386
|
-
inputTokens: usage.inputTokens.total ?? 0,
|
|
4387
|
-
cachedInputTokens: usage.inputTokens.cacheRead ?? 0,
|
|
4388
|
-
cacheWriteTokens: usage.inputTokens.cacheWrite ?? 0,
|
|
4389
|
-
outputTokens: usage.outputTokens.total ?? 0,
|
|
4390
|
-
reasoningTokens: usage.outputTokens.reasoning ?? 0
|
|
4391
|
-
};
|
|
4392
|
-
}
|
|
4393
|
-
function describeError(error) {
|
|
4394
|
-
if (error instanceof Error) return error.message;
|
|
4395
|
-
if (error === void 0) return "\u043E\u0431\u0440\u044B\u0432 \u0431\u0435\u0437 \u043F\u0440\u0438\u0447\u0438\u043D\u044B";
|
|
4396
|
-
return typeof error === "string" ? error : String(error);
|
|
4397
|
-
}
|
|
4398
|
-
|
|
4399
|
-
// src/agent-run/turn-usage.ts
|
|
4400
|
-
import { asSchema } from "ai";
|
|
4401
|
-
var SHARES_PER_TOKEN = 6;
|
|
4402
|
-
var FILE_SHARES = 1600 * SHARES_PER_TOKEN;
|
|
4403
|
-
var tokensOf = (shares) => Math.ceil(shares / SHARES_PER_TOKEN);
|
|
4404
|
-
function textShares(text) {
|
|
4405
|
-
let shares = 0;
|
|
4406
|
-
for (let index = 0; index < text.length; index++) shares += charShares(text.charCodeAt(index));
|
|
4407
|
-
return shares;
|
|
4408
|
-
}
|
|
4409
|
-
function charShares(code) {
|
|
4410
|
-
if (code < 128) return isLatinLetterDigitOrSpace(code) ? 2 : 3;
|
|
4411
|
-
return isDenseScript(code) ? 6 : 3;
|
|
4412
|
-
}
|
|
4413
|
-
function isLatinLetterDigitOrSpace(code) {
|
|
4414
|
-
const isLetterOrDigit = code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
|
|
4415
|
-
return isLetterOrDigit || code === 32 || code === 10 || code === 9 || code === 13;
|
|
4416
|
-
}
|
|
4417
|
-
function isDenseScript(code) {
|
|
4418
|
-
return code >= 11904 && code <= 40959 || code >= 44032 && code <= 57343 || code >= 63744 && code <= 64255 || code >= 65280 && code <= 65519;
|
|
4419
|
-
}
|
|
4420
|
-
function estimateTextTokens(text) {
|
|
4421
|
-
return tokensOf(textShares(text));
|
|
4422
|
-
}
|
|
4423
|
-
function createTurnUsage(now = () => /* @__PURE__ */ new Date()) {
|
|
4424
|
-
const steps = [];
|
|
4425
|
-
let providerId = "";
|
|
4426
|
-
let fixedShares = 0;
|
|
4427
|
-
let requestShares = [];
|
|
4428
|
-
let requestTimes = [];
|
|
4429
|
-
let startedSteps = 0;
|
|
4430
|
-
let finishedSteps = 0;
|
|
4431
|
-
let written = { shares: 0, reasoningShares: 0, content: false };
|
|
4432
|
-
let generationIds = [];
|
|
4433
|
-
let requestOpen = false;
|
|
4434
|
-
let streamedCalls = /* @__PURE__ */ new Set();
|
|
4435
|
-
function estimate(stepIndex, shares, reasoningShares) {
|
|
4436
|
-
const previous = steps.findLast((step) => !step.erased)?.usage;
|
|
4437
|
-
const inputTokens = Math.max(tokensOf(requestShares[stepIndex] ?? fixedShares), previous ? previous.inputTokens + previous.outputTokens : 0);
|
|
4438
|
-
const cachedInputTokens = previous && previous.cachedInputTokens > 0 ? Math.min(previous.inputTokens, inputTokens) : 0;
|
|
4439
|
-
return {
|
|
4440
|
-
inputTokens,
|
|
4441
|
-
cachedInputTokens,
|
|
4442
|
-
outputTokens: tokensOf(shares + reasoningShares),
|
|
4443
|
-
reasoningTokens: tokensOf(reasoningShares),
|
|
4444
|
-
estimated: true
|
|
4445
|
-
};
|
|
4446
|
-
}
|
|
4447
|
-
function unfinishedStep() {
|
|
4448
|
-
const wroteSomething = startedSteps > finishedSteps && written.content;
|
|
4449
|
-
if (!wroteSomething && !requestOpen) return null;
|
|
4450
|
-
const index = wroteSomething ? startedSteps - 1 : finishedSteps;
|
|
4451
|
-
const usage = estimate(index, written.shares, written.reasoningShares);
|
|
4452
|
-
return { usage, providerId, generationIds, at: stepTime(index) };
|
|
4453
|
-
}
|
|
4454
|
-
function stepTime(index) {
|
|
4455
|
-
return requestTimes[index] ?? now().toISOString();
|
|
4456
|
-
}
|
|
4457
|
-
function nextStep() {
|
|
4458
|
-
written = { shares: 0, reasoningShares: 0, content: false };
|
|
4459
|
-
generationIds = [];
|
|
4460
|
-
requestOpen = false;
|
|
4461
|
-
}
|
|
4462
|
-
return {
|
|
4463
|
-
/** Новая попытка у провайдера `attemptProviderId`: инструкция и описания инструментов её запроса. */
|
|
4464
|
-
beginAttempt(request, attemptProviderId) {
|
|
4465
|
-
providerId = attemptProviderId;
|
|
4466
|
-
fixedShares = instructionsShares(request.instructions) + toolsShares(request.tools);
|
|
4467
|
-
requestShares = [];
|
|
4468
|
-
requestTimes = [];
|
|
4469
|
-
startedSteps = 0;
|
|
4470
|
-
finishedSteps = 0;
|
|
4471
|
-
nextStep();
|
|
4472
|
-
streamedCalls = /* @__PURE__ */ new Set();
|
|
4473
|
-
},
|
|
4474
|
-
/** Перед шагом попытки: сообщения его запроса. */
|
|
4475
|
-
beforeStep(stepNumber, messages) {
|
|
4476
|
-
requestShares[stepNumber] = fixedShares + messagesShares(messages);
|
|
4477
|
-
requestTimes[stepNumber] = now().toISOString();
|
|
4478
|
-
},
|
|
4479
|
-
/** Провайдер принял запрос идущего шага и начал поток: с этого мига вход оплачен (FR-051, FR-058). */
|
|
4480
|
-
requestOpened(request) {
|
|
4481
|
-
generationIds.push(request.generationId);
|
|
4482
|
-
requestOpen = true;
|
|
4483
|
-
},
|
|
4484
|
-
/** Провайдер сам отказал посреди потока: такой запрос не оплачивается. */
|
|
4485
|
-
requestRefused() {
|
|
4486
|
-
requestOpen = false;
|
|
4487
|
-
},
|
|
4488
|
-
/** Кусок UI-потока попытки: начала шагов и написанное. */
|
|
4489
|
-
observe(chunk) {
|
|
4490
|
-
if (chunk.type === "start-step") {
|
|
4491
|
-
startedSteps += 1;
|
|
4492
|
-
written = { shares: 0, reasoningShares: 0, content: false };
|
|
4493
|
-
return;
|
|
4494
|
-
}
|
|
4495
|
-
if (chunk.type === "text-delta") written.shares += textShares(chunk.delta);
|
|
4496
|
-
else if (chunk.type === "reasoning-delta") written.reasoningShares += textShares(chunk.delta);
|
|
4497
|
-
else if (chunk.type === "tool-input-delta") {
|
|
4498
|
-
streamedCalls.add(chunk.toolCallId);
|
|
4499
|
-
written.shares += textShares(chunk.inputTextDelta);
|
|
4500
|
-
} else if (chunk.type === "tool-input-available" && !streamedCalls.has(chunk.toolCallId)) {
|
|
4501
|
-
written.shares += textShares(JSON.stringify(chunk.input ?? null));
|
|
4502
|
-
} else if (!isWritten(chunk)) return;
|
|
4503
|
-
written.content = true;
|
|
4504
|
-
},
|
|
4505
|
-
/** Шаг завершён: числа провайдера или, если их нет, оценка. */
|
|
4506
|
-
finishStep(usage, content) {
|
|
4507
|
-
const index = finishedSteps;
|
|
4508
|
-
finishedSteps += 1;
|
|
4509
|
-
let stepUsage;
|
|
4510
|
-
if ((usage.inputTokens ?? 0) > 0 || (usage.outputTokens ?? 0) > 0) {
|
|
4511
|
-
stepUsage = emptyTokenUsage();
|
|
4512
|
-
addTokenUsage(stepUsage, usage);
|
|
4513
|
-
} else {
|
|
4514
|
-
const output = contentShares(content);
|
|
4515
|
-
stepUsage = estimate(index, output.shares, output.reasoningShares);
|
|
4516
|
-
}
|
|
4517
|
-
steps.push({ usage: stepUsage, providerId, generationIds, at: stepTime(index) });
|
|
4518
|
-
nextStep();
|
|
4519
|
-
},
|
|
4520
|
-
/** Шаг без запроса к провайдеру (готовый текст `endTurn`): в расход не идёт. */
|
|
4521
|
-
finishFreeStep() {
|
|
4522
|
-
finishedSteps += 1;
|
|
4523
|
-
nextStep();
|
|
4524
|
-
},
|
|
4525
|
-
/**
|
|
4526
|
-
* Попытка кончилась: недописанный шаг с написанным или с открытым запросом — в расход хода оценкой. `erased` — этот
|
|
4527
|
-
* шаг стёрт: оплачен, но следующий шаг его не видит.
|
|
4528
|
-
*/
|
|
4529
|
-
closeAttempt(options2 = {}) {
|
|
4530
|
-
const unfinished = unfinishedStep();
|
|
4531
|
-
if (unfinished) steps.push(options2.erased ? { ...unfinished, erased: true } : unfinished);
|
|
4532
|
-
finishedSteps = startedSteps;
|
|
4533
|
-
nextStep();
|
|
4534
|
-
},
|
|
4535
|
-
/** Расход каждого шага хода, без идущего. */
|
|
4536
|
-
steps() {
|
|
4537
|
-
return steps.map((step) => step.usage);
|
|
4538
|
-
},
|
|
4539
|
-
/** Шаги хода по провайдерам, в порядке первого шага у каждого: каждому — запись по его цене. */
|
|
4540
|
-
stepsByProvider() {
|
|
4541
|
-
const groups = /* @__PURE__ */ new Map();
|
|
4542
|
-
for (const step of steps) groups.set(step.providerId, [...groups.get(step.providerId) ?? [], { ...step.usage, at: step.at }]);
|
|
4543
|
-
return [...groups].map(([id, usages]) => ({ providerId: id, steps: usages }));
|
|
4544
|
-
},
|
|
4545
|
-
/**
|
|
4546
|
-
* Шаги, расход которых стоит узнать у провайдера (FR-058): оценённый — все его генерации; оплаченный по числам —
|
|
4547
|
-
* генерации до последней (повторы, оборванные до первого куска). Шаг с генерацией без номера не узнать — его нет.
|
|
4548
|
-
*/
|
|
4549
|
-
stepsToSettle() {
|
|
4550
|
-
return steps.flatMap((step) => {
|
|
4551
|
-
const ids = step.usage.estimated ? step.generationIds : step.generationIds.slice(0, -1);
|
|
4552
|
-
if (ids.length === 0 || !ids.every((id) => id !== void 0)) return [];
|
|
4553
|
-
return [{ providerId: step.providerId, at: step.at, estimate: step.usage.estimated ? step.usage : null, generationIds: ids }];
|
|
4554
|
-
});
|
|
4555
|
-
},
|
|
4556
|
-
/** Шаги хода с провайдерами вместе с оценкой идущего — в идущий ответ для восстановления (FR-052). */
|
|
4557
|
-
pendingSteps() {
|
|
4558
|
-
const unfinished = unfinishedStep();
|
|
4559
|
-
return (unfinished ? [...steps, unfinished] : steps).map((step) => ({ ...step.usage, providerId: step.providerId, at: step.at }));
|
|
4560
|
-
},
|
|
4561
|
-
/** Расход хода на этот момент вместе с оценкой идущего шага; ничего не потрачено — `null`. */
|
|
4562
|
-
total() {
|
|
4563
|
-
const unfinished = unfinishedStep();
|
|
4564
|
-
return sumOfSteps((unfinished ? [...steps, unfinished] : steps).map((step) => step.usage));
|
|
4565
|
-
}
|
|
4566
|
-
};
|
|
4567
|
-
}
|
|
4568
|
-
function sumOfSteps(steps) {
|
|
4569
|
-
const last = steps.at(-1);
|
|
4570
|
-
if (!last) return null;
|
|
4571
|
-
const total = emptyTokenUsage();
|
|
4572
|
-
for (const step of steps) {
|
|
4573
|
-
total.inputTokens += step.inputTokens;
|
|
4574
|
-
total.cachedInputTokens += step.cachedInputTokens;
|
|
4575
|
-
total.outputTokens += step.outputTokens;
|
|
4576
|
-
total.reasoningTokens += step.reasoningTokens;
|
|
4577
|
-
if (step.cacheWriteTokens) total.cacheWriteTokens = (total.cacheWriteTokens ?? 0) + step.cacheWriteTokens;
|
|
4578
|
-
}
|
|
4579
|
-
const contextTokens = last.inputTokens + last.outputTokens;
|
|
4580
|
-
return { ...total, ...contextTokens > 0 && { contextTokens }, ...steps.some((step) => step.estimated) && { estimated: true } };
|
|
4581
|
-
}
|
|
4582
|
-
function isWritten(chunk) {
|
|
4583
|
-
return chunk.type.startsWith("source-") || chunk.type === "file" || chunk.type === "tool-approval-request" || chunk.type.startsWith("data-");
|
|
4584
|
-
}
|
|
4585
|
-
function instructionsShares(instructions) {
|
|
4586
|
-
if (typeof instructions === "string") return textShares(instructions);
|
|
4587
|
-
if (Array.isArray(instructions)) return instructions.reduce((sum, item) => sum + instructionsShares(item), 0);
|
|
4588
|
-
const content = instructions?.content;
|
|
4589
|
-
return typeof content === "string" ? textShares(content) : 0;
|
|
4590
|
-
}
|
|
4591
|
-
function toolsShares(tools) {
|
|
4592
|
-
let shares = 0;
|
|
4593
|
-
for (const [name, tool4] of Object.entries(tools ?? {})) {
|
|
4594
|
-
shares += textShares(name) + (typeof tool4.description === "string" ? textShares(tool4.description) : 0);
|
|
4595
|
-
const schema = tool4.inputSchema && asSchema(tool4.inputSchema).jsonSchema;
|
|
4596
|
-
if (schema && typeof schema.then !== "function") shares += textShares(JSON.stringify(schema));
|
|
4597
|
-
}
|
|
4598
|
-
return shares;
|
|
4599
|
-
}
|
|
4600
|
-
function messagesShares(messages) {
|
|
4601
|
-
let shares = 0;
|
|
4602
|
-
for (const message of messages) {
|
|
4603
|
-
if (typeof message.content === "string") shares += textShares(message.content);
|
|
4604
|
-
else for (const part of message.content) shares += partShares(part);
|
|
4605
|
-
}
|
|
4606
|
-
return shares;
|
|
4607
|
-
}
|
|
4608
|
-
function partShares(part) {
|
|
4609
|
-
switch (part.type) {
|
|
4610
|
-
case "text":
|
|
4611
|
-
case "reasoning":
|
|
4612
|
-
return textShares(part.text);
|
|
4613
|
-
case "image":
|
|
4614
|
-
case "file":
|
|
4615
|
-
return FILE_SHARES;
|
|
4616
|
-
case "tool-call":
|
|
4617
|
-
return textShares(part.toolName) + textShares(JSON.stringify(part.input ?? null));
|
|
4618
|
-
case "tool-result":
|
|
4619
|
-
return part.output.type === "content" ? part.output.value.reduce((sum, item) => sum + (item.type === "text" ? textShares(item.text) : FILE_SHARES), 0) : textShares(JSON.stringify(part.output));
|
|
4620
|
-
default:
|
|
4621
|
-
return textShares(JSON.stringify(part));
|
|
4622
|
-
}
|
|
4623
|
-
}
|
|
4624
|
-
function contentShares(content) {
|
|
4625
|
-
let shares = 0;
|
|
4626
|
-
let reasoningShares = 0;
|
|
4627
|
-
for (const part of content) {
|
|
4628
|
-
if (part.type === "text") shares += textShares(part.text);
|
|
4629
|
-
else if (part.type === "reasoning") reasoningShares += textShares(part.text);
|
|
4630
|
-
else if (part.type === "tool-call") shares += textShares(JSON.stringify(part.input ?? null));
|
|
4970
|
+
function parsedInput(input) {
|
|
4971
|
+
try {
|
|
4972
|
+
return JSON.parse(input);
|
|
4973
|
+
} catch {
|
|
4974
|
+
return input;
|
|
4631
4975
|
}
|
|
4632
|
-
|
|
4976
|
+
}
|
|
4977
|
+
function usageOf(usage) {
|
|
4978
|
+
return {
|
|
4979
|
+
inputTokens: usage.inputTokens.total ?? 0,
|
|
4980
|
+
cachedInputTokens: usage.inputTokens.cacheRead ?? 0,
|
|
4981
|
+
cacheWriteTokens: usage.inputTokens.cacheWrite ?? 0,
|
|
4982
|
+
outputTokens: usage.outputTokens.total ?? 0,
|
|
4983
|
+
reasoningTokens: usage.outputTokens.reasoning ?? 0
|
|
4984
|
+
};
|
|
4985
|
+
}
|
|
4986
|
+
function describeError(error) {
|
|
4987
|
+
if (error instanceof Error) return error.message;
|
|
4988
|
+
if (error === void 0) return "\u043E\u0431\u0440\u044B\u0432 \u0431\u0435\u0437 \u043F\u0440\u0438\u0447\u0438\u043D\u044B";
|
|
4989
|
+
return typeof error === "string" ? error : String(error);
|
|
4633
4990
|
}
|
|
4634
4991
|
|
|
4635
4992
|
// src/agent-run/step-cache-mark.ts
|
|
@@ -4865,7 +5222,7 @@ function withoutUndelivered(history) {
|
|
|
4865
5222
|
}
|
|
4866
5223
|
|
|
4867
5224
|
// src/agent-run/garbled-tail.ts
|
|
4868
|
-
import { wrapLanguageModel as
|
|
5225
|
+
import { wrapLanguageModel as wrapLanguageModel6 } from "ai";
|
|
4869
5226
|
var SIGN_ORDER = ["think", "role", "restart", "tool"];
|
|
4870
5227
|
var TOKEN_SOURCE = String.raw`<\/?think>|<\|[^|\n<>]{1,40}\|>|<|[^|\n<>]{1,40}|>`;
|
|
4871
5228
|
var TEMPLATE_TOKEN = new RegExp(TOKEN_SOURCE, "g");
|
|
@@ -5037,7 +5394,7 @@ function createGarbledTailGuard() {
|
|
|
5037
5394
|
/** Модель попытки под присмотром: каждый запрос — новый шаг. */
|
|
5038
5395
|
wrap(model) {
|
|
5039
5396
|
if (typeof model === "string") return model;
|
|
5040
|
-
return
|
|
5397
|
+
return wrapLanguageModel6({
|
|
5041
5398
|
model,
|
|
5042
5399
|
middleware: {
|
|
5043
5400
|
specificationVersion: "v4",
|
|
@@ -5059,7 +5416,7 @@ function createGarbledTailGuard() {
|
|
|
5059
5416
|
isDroppedCall: (part) => part === DROPPED_CALL
|
|
5060
5417
|
};
|
|
5061
5418
|
}
|
|
5062
|
-
var
|
|
5419
|
+
var isToolPart7 = (part) => part.type.startsWith("tool-") || part.type === "dynamic-tool";
|
|
5063
5420
|
function stepsOf(parts) {
|
|
5064
5421
|
const steps = [];
|
|
5065
5422
|
let current = { from: 0, to: 0, texts: [] };
|
|
@@ -5090,7 +5447,7 @@ function garbleInStep(parts, step, markers) {
|
|
|
5090
5447
|
if (roles.some(after)) others.add("restart");
|
|
5091
5448
|
if (role.bareRole.glued) {
|
|
5092
5449
|
if (gluedAfter()) others.add("restart");
|
|
5093
|
-
if (parts.slice(role.partIndex + 1, step.to).some(
|
|
5450
|
+
if (parts.slice(role.partIndex + 1, step.to).some(isToolPart7)) others.add("tool");
|
|
5094
5451
|
}
|
|
5095
5452
|
}
|
|
5096
5453
|
if (others.size === 0) return null;
|
|
@@ -5275,7 +5632,7 @@ function withoutLoneSurrogatesDeep(value) {
|
|
|
5275
5632
|
}
|
|
5276
5633
|
function withRequestWatch(model, provider, watch) {
|
|
5277
5634
|
if (!watch || typeof model === "string") return model;
|
|
5278
|
-
return
|
|
5635
|
+
return wrapLanguageModel7({
|
|
5279
5636
|
model,
|
|
5280
5637
|
middleware: {
|
|
5281
5638
|
specificationVersion: "v4",
|
|
@@ -5295,7 +5652,7 @@ function withRequestWatch(model, provider, watch) {
|
|
|
5295
5652
|
});
|
|
5296
5653
|
}
|
|
5297
5654
|
function withTransientRetries(model, context) {
|
|
5298
|
-
return typeof model === "string" ? model :
|
|
5655
|
+
return typeof model === "string" ? model : wrapLanguageModel7({ model, middleware: createTransientRetryMiddleware(context) });
|
|
5299
5656
|
}
|
|
5300
5657
|
function withLastMessageMark(messages, options2) {
|
|
5301
5658
|
if (!options2 || messages.length === 0) return messages;
|
|
@@ -6867,58 +7224,6 @@ async function* limitIterationResults(source, limited, reportCut, remember) {
|
|
|
6867
7224
|
reportCut(lastCutFrom);
|
|
6868
7225
|
}
|
|
6869
7226
|
|
|
6870
|
-
// src/agent-run/step-context.ts
|
|
6871
|
-
var DEFAULT_STEP_CONTEXT_TIMEOUT_MS = 5e3;
|
|
6872
|
-
function createStepSnapshots(options2) {
|
|
6873
|
-
let previous;
|
|
6874
|
-
return {
|
|
6875
|
-
async messagesFor({ messages, trailing, context }) {
|
|
6876
|
-
const withoutPrevious = previous ? messages.filter((message) => message !== previous) : messages;
|
|
6877
|
-
previous = void 0;
|
|
6878
|
-
const text = await snapshotText(options2, context);
|
|
6879
|
-
if (!text) return { messages: withoutPrevious, tokens: 0 };
|
|
6880
|
-
const snapshot = { role: "user", content: [{ type: "text", text }] };
|
|
6881
|
-
previous = snapshot;
|
|
6882
|
-
const at = withoutPrevious.length - Math.min(trailing, withoutPrevious.length);
|
|
6883
|
-
return { messages: [...withoutPrevious.slice(0, at), snapshot, ...withoutPrevious.slice(at)], tokens: estimateTextTokens(text) };
|
|
6884
|
-
}
|
|
6885
|
-
};
|
|
6886
|
-
}
|
|
6887
|
-
async function snapshotText(options2, context) {
|
|
6888
|
-
const timeoutMs = options2.timeoutMs ?? DEFAULT_STEP_CONTEXT_TIMEOUT_MS;
|
|
6889
|
-
const log = (message) => options2.logError(`[\u0441\u043D\u0438\u043C\u043E\u043A \u0448\u0430\u0433\u0430] \u0447\u0430\u0442=${options2.chatId} \u0448\u0430\u0433=${context.stepNumber} ${message}`);
|
|
6890
|
-
const stop = context.abortSignal;
|
|
6891
|
-
const ownAbort = new AbortController();
|
|
6892
|
-
let timer;
|
|
6893
|
-
let onStop;
|
|
6894
|
-
const cutOff = new Promise((resolve) => {
|
|
6895
|
-
if (Number.isFinite(timeoutMs)) timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
6896
|
-
onStop = () => resolve("stopped");
|
|
6897
|
-
if (stop.aborted) onStop();
|
|
6898
|
-
else stop.addEventListener("abort", onStop, { once: true });
|
|
6899
|
-
});
|
|
6900
|
-
try {
|
|
6901
|
-
const call = Promise.resolve().then(() => options2.stepContext({ ...context, abortSignal: AbortSignal.any([stop, ownAbort.signal]) }));
|
|
6902
|
-
const outcome = await Promise.race([call.then((text2) => ({ text: text2 })), cutOff]);
|
|
6903
|
-
if (outcome === "stopped") return null;
|
|
6904
|
-
if (outcome === "timeout") {
|
|
6905
|
-
ownAbort.abort(new Error(`stepContext \u043D\u0435 \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u0437\u0430 ${timeoutMs} \u043C\u0441`));
|
|
6906
|
-
log(`\u043D\u0435 \u043E\u0442\u0432\u0435\u0442\u0438\u043B \u0437\u0430 ${timeoutMs} \u043C\u0441`);
|
|
6907
|
-
return null;
|
|
6908
|
-
}
|
|
6909
|
-
const { text } = outcome;
|
|
6910
|
-
if (text === null || text === void 0 || text === "") return null;
|
|
6911
|
-
if (typeof text !== "string") throw new TypeError(`stepContext \u0432\u0435\u0440\u043D\u0443\u043B ${typeof text}, \u0430 \u043D\u0435 \u0441\u0442\u0440\u043E\u043A\u0443`);
|
|
6912
|
-
return text;
|
|
6913
|
-
} catch (error) {
|
|
6914
|
-
log(error instanceof Error ? error.message : String(error));
|
|
6915
|
-
return null;
|
|
6916
|
-
} finally {
|
|
6917
|
-
clearTimeout(timer);
|
|
6918
|
-
stop.removeEventListener("abort", onStop);
|
|
6919
|
-
}
|
|
6920
|
-
}
|
|
6921
|
-
|
|
6922
7227
|
// src/agent-run/turn-attempt.ts
|
|
6923
7228
|
var SERVICE_CHUNKS = /* @__PURE__ */ new Set(["start", "start-step"]);
|
|
6924
7229
|
function isContent(chunk) {
|
|
@@ -7239,6 +7544,7 @@ async function runTurn(turnInput, emitRaw) {
|
|
|
7239
7544
|
const turnUsage = createTurnUsage();
|
|
7240
7545
|
const garbledTail = createGarbledTailGuard();
|
|
7241
7546
|
const forgedBlocks = createForgedBlockGuard(turnInput.serviceBlocks ?? CORE_SERVICE_BLOCKS);
|
|
7547
|
+
const sealedAnswer = createSealedAnswerGuard(turnInput.serviceTools);
|
|
7242
7548
|
const turnBudget = createTurnBudget(input.turnRules, { catalog: input.catalog, modelId: input.modelId, turnUsage });
|
|
7243
7549
|
const messageUsage = () => {
|
|
7244
7550
|
const spent = turnUsage.total();
|
|
@@ -7455,6 +7761,7 @@ async function runTurn(turnInput, emitRaw) {
|
|
|
7455
7761
|
}
|
|
7456
7762
|
attemptAllowed = false;
|
|
7457
7763
|
if (attemptsOpened > 1) endTurns.nextAttempt(await saver.snapshot());
|
|
7764
|
+
sealedAnswer.reset((attemptsOpened > 1 ? await saver.snapshot() : resume?.message.parts ?? []).slice(resume && !resume.replay ? resume.message.parts.length : 0));
|
|
7458
7765
|
let provider;
|
|
7459
7766
|
const classify = (error2) => classifyProviderError(error2, provider);
|
|
7460
7767
|
let attempt;
|
|
@@ -7481,6 +7788,7 @@ async function runTurn(turnInput, emitRaw) {
|
|
|
7481
7788
|
turnBudget,
|
|
7482
7789
|
garbledTail,
|
|
7483
7790
|
forgedBlocks,
|
|
7791
|
+
sealedAnswer,
|
|
7484
7792
|
// Есть куда перейти при молчании — у того же провайдера оно не повторяется.
|
|
7485
7793
|
repeatSilence: () => silenceTarget() === void 0,
|
|
7486
7794
|
retryDelaysMs: () => !contentSeen && !fallbackUsed && remainingFallbacks().length > 0 && stepsDone < maxSteps ? (input.providerFallback || {}).retryDelaysMs ?? FALLBACK_RETRY_DELAYS_MS : void 0,
|
|
@@ -7689,7 +7997,9 @@ async function runTurn(turnInput, emitRaw) {
|
|
|
7689
7997
|
emitNow({ type: "tool-output-error", toolCallId, errorText: ONE_QUESTION_AT_A_TIME });
|
|
7690
7998
|
}
|
|
7691
7999
|
}
|
|
7692
|
-
if (
|
|
8000
|
+
if (sealedAnswer.droppedChars() > 0) logError(`[\u0434\u043E\u043F\u0438\u0441\u043A\u0430 \u043F\u043E\u0441\u043B\u0435 \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043E\u043A \u043D\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u043D\u0430] \u0447\u0430\u0442=${input.chatId} \u043C\u043E\u0434\u0435\u043B\u044C=${modelId} \u0437\u043D\u0430\u043A\u043E\u0432=${sealedAnswer.droppedChars()}`);
|
|
8001
|
+
const sealedOnTool = sealedAnswer.sealed() && sealedAnswerEndsOnTool(await saver.snapshot());
|
|
8002
|
+
if ((endTurns.endedWithoutText() || sealedOnTool) && !input.abortSignal.aborted && errors.length === 0) {
|
|
7693
8003
|
const parts2 = await saver.snapshot();
|
|
7694
8004
|
if (pendingHumanInput(parts2, input.waitingWidgets).length === 0) {
|
|
7695
8005
|
if (parts2.at(-1)?.type !== "step-start") saver.observe({ type: "start-step" });
|
|
@@ -7970,7 +8280,7 @@ async function openAttempt(input, attempt, attemptSignal) {
|
|
|
7970
8280
|
const providerId = found.provider.id;
|
|
7971
8281
|
const limit = input.toolResultLimit ?? DEFAULT_TOOL_RESULT_LIMIT;
|
|
7972
8282
|
const toolsModel = turnToolsModel(input, found, attempt);
|
|
7973
|
-
const appTools = attempt.endTurns.tools(onlyAllowedTools(typeof input.tools === "function" ? input.tools(toolsModel) : input.tools, input.group));
|
|
8283
|
+
const appTools = attempt.endTurns.tools(attempt.sealedAnswer.tools(onlyAllowedTools(typeof input.tools === "function" ? input.tools(toolsModel) : input.tools, input.group)));
|
|
7974
8284
|
const toolTimeout = input.toolTimeout ?? DEFAULT_TOOL_TIMEOUT;
|
|
7975
8285
|
const serverTools = withSequentialTools(
|
|
7976
8286
|
withToolTimeout(appTools, {
|
|
@@ -8016,6 +8326,7 @@ async function openAttempt(input, attempt, attemptSignal) {
|
|
|
8016
8326
|
toolTimeout: _toolTimeout,
|
|
8017
8327
|
repairToolInput: _repairToolInput,
|
|
8018
8328
|
sequentialTools: _sequentialTools,
|
|
8329
|
+
serviceTools: _serviceTools,
|
|
8019
8330
|
now: _now,
|
|
8020
8331
|
usageSource: _usageSource,
|
|
8021
8332
|
replyChecks: _replyChecks,
|
|
@@ -8081,8 +8392,8 @@ async function openAttempt(input, attempt, attemptSignal) {
|
|
|
8081
8392
|
attempt.forgedBlocks.reset(lastQuestionOf(attempt.history));
|
|
8082
8393
|
const result = streamText({
|
|
8083
8394
|
...modelRequest,
|
|
8084
|
-
// Сначала вырезка блоков, потом проверка на кашу: каша судит уже чистый текст.
|
|
8085
|
-
model: attempt.garbledTail.wrap(attempt.forgedBlocks.wrap(modelRequest.model)),
|
|
8395
|
+
// Сначала вырезка блоков, потом дописка после закрытого ответа, потом проверка на кашу: каша судит уже чистый текст.
|
|
8396
|
+
model: attempt.garbledTail.wrap(attempt.sealedAnswer.wrap(attempt.forgedBlocks.wrap(modelRequest.model))),
|
|
8086
8397
|
...approval.toolApproval && { toolApproval: gateToolApproval(approval.toolApproval, () => toolsClosed) },
|
|
8087
8398
|
// Попытке — остаток шагов хода.
|
|
8088
8399
|
// Помощник встал на подтверждении человека — ход ждёт, модель основного агента его незаконченным не видит.
|
|
@@ -8905,9 +9216,9 @@ function editAnswerParts(parts, edit, uneditable) {
|
|
|
8905
9216
|
return { ok: true, parts: textPlaced ? edited : [...edited, textPart] };
|
|
8906
9217
|
}
|
|
8907
9218
|
function toolCallIdOf(part) {
|
|
8908
|
-
return
|
|
9219
|
+
return isToolPart8(part) ? part.toolCallId : void 0;
|
|
8909
9220
|
}
|
|
8910
|
-
var
|
|
9221
|
+
var isToolPart8 = (part) => part.type.startsWith("tool-") || part.type === "dynamic-tool";
|
|
8911
9222
|
function toolNameOf2(part) {
|
|
8912
9223
|
return part.type === "dynamic-tool" ? part.toolName : part.type.slice("tool-".length);
|
|
8913
9224
|
}
|
|
@@ -9312,7 +9623,7 @@ var fireworksProvider = createFireworksProvider();
|
|
|
9312
9623
|
|
|
9313
9624
|
// src/models/providers/openrouter.ts
|
|
9314
9625
|
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
|
|
9315
|
-
import { wrapLanguageModel as
|
|
9626
|
+
import { wrapLanguageModel as wrapLanguageModel8 } from "ai";
|
|
9316
9627
|
|
|
9317
9628
|
// src/models/providers/openrouter-cache-mark-limit.ts
|
|
9318
9629
|
function openrouterCacheMarkLimit(providerModelId) {
|
|
@@ -9563,7 +9874,7 @@ function createOpenRouterProvider(options2 = {}) {
|
|
|
9563
9874
|
createLanguageModel: (providerModelId, apiKey, requestOptions) => {
|
|
9564
9875
|
const markLimit = openrouterCacheMarkLimit(providerModelId);
|
|
9565
9876
|
const fetch = markLimit === void 0 ? requestOptions?.fetch : fetchWithCacheMarkLimit(requestOptions?.fetch, markLimit);
|
|
9566
|
-
return
|
|
9877
|
+
return wrapLanguageModel8({
|
|
9567
9878
|
model: createOpenRouter({ apiKey, fetch, ...connection }).chat(providerModelId, routingOptions),
|
|
9568
9879
|
middleware: [
|
|
9569
9880
|
openrouterRoutingMiddleware(routing),
|
|
@@ -10192,15 +10503,15 @@ async function closeState(storage, messageId, state, appendParts, logError, wher
|
|
|
10192
10503
|
}
|
|
10193
10504
|
}
|
|
10194
10505
|
function pause(ms, signal) {
|
|
10195
|
-
const
|
|
10506
|
+
const aborted2 = whenAborted(signal);
|
|
10196
10507
|
return new Promise((resolve) => {
|
|
10197
10508
|
const timer = setTimeout(resolve, ms);
|
|
10198
10509
|
timer.unref?.();
|
|
10199
|
-
void
|
|
10510
|
+
void aborted2.promise.then(() => {
|
|
10200
10511
|
clearTimeout(timer);
|
|
10201
10512
|
resolve();
|
|
10202
10513
|
});
|
|
10203
|
-
}).finally(
|
|
10514
|
+
}).finally(aborted2.dispose);
|
|
10204
10515
|
}
|
|
10205
10516
|
function whenAborted(signal) {
|
|
10206
10517
|
let onAbort = () => {
|
|
@@ -11359,184 +11670,6 @@ function isHiddenChoice(catalog, choice) {
|
|
|
11359
11670
|
return catalog.providers.some((provider) => provider.id === choice.providerId && provider.hiddenFromMenu === true);
|
|
11360
11671
|
}
|
|
11361
11672
|
|
|
11362
|
-
// src/widgets/basic-widgets.ts
|
|
11363
|
-
import { tool as tool2 } from "ai";
|
|
11364
|
-
import { z as z2 } from "zod";
|
|
11365
|
-
var BASIC_WIDGET_NAMES = ["ask_choice", "ask_form", "ask_multi_choice", "ask_rating", "suggest_replies"];
|
|
11366
|
-
var SUGGESTIONS_SHOWN = "\u043F\u043E\u043A\u0430\u0437\u0430\u043D\u043E";
|
|
11367
|
-
var FORM_TEXT_MAX = 2e3;
|
|
11368
|
-
var question = z2.string().min(1).max(300);
|
|
11369
|
-
var options = z2.array(z2.string().min(1).max(80)).min(2).max(8).refine((values) => new Set(values).size === values.length, "\u0412\u0430\u0440\u0438\u0430\u043D\u0442\u044B \u043D\u0435 \u0434\u043E\u043B\u0436\u043D\u044B \u043F\u043E\u0432\u0442\u043E\u0440\u044F\u0442\u044C\u0441\u044F");
|
|
11370
|
-
var choiceInput = z2.object({ question, options });
|
|
11371
|
-
var multiChoiceInput = z2.object({ question, options, min: z2.number().int().optional(), max: z2.number().int().optional() }).superRefine((input, context) => {
|
|
11372
|
-
const { min, max } = multiChoiceLimits(input);
|
|
11373
|
-
if (min < 1 || min > max || max > input.options.length) {
|
|
11374
|
-
context.addIssue({ code: "custom", message: "\u041D\u0443\u0436\u043D\u043E 1 \u2264 min \u2264 max \u2264 \u0447\u0438\u0441\u043B\u0430 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432", path: ["min"] });
|
|
11375
|
-
}
|
|
11376
|
-
});
|
|
11377
|
-
var ratingInput = z2.object({
|
|
11378
|
-
question,
|
|
11379
|
-
scale: z2.enum(["stars", "range"]),
|
|
11380
|
-
from: z2.union([z2.literal(0), z2.literal(1)]).optional(),
|
|
11381
|
-
to: z2.number().int().min(2).max(10).optional(),
|
|
11382
|
-
fromLabel: z2.string().min(1).max(40).optional(),
|
|
11383
|
-
toLabel: z2.string().min(1).max(40).optional()
|
|
11384
|
-
}).superRefine((input, context) => {
|
|
11385
|
-
const rangeFields = [input.from, input.to, input.fromLabel, input.toLabel].some((value) => value !== void 0);
|
|
11386
|
-
if (input.scale === "stars" && rangeFields) context.addIssue({ code: "custom", message: "\u0423 \u0437\u0432\u0451\u0437\u0434 \u043D\u0435\u0442 from, to \u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439", path: ["scale"] });
|
|
11387
|
-
if (input.scale === "range" && (input.from === void 0 || input.to === void 0)) {
|
|
11388
|
-
context.addIssue({ code: "custom", message: "\u0423 \u0448\u043A\u0430\u043B\u044B range \u043D\u0443\u0436\u043D\u044B from (0 \u0438\u043B\u0438 1) \u0438 to (2\u201310)", path: ["from"] });
|
|
11389
|
-
}
|
|
11390
|
-
});
|
|
11391
|
-
var formField = z2.object({
|
|
11392
|
-
name: z2.string().regex(/^[A-Za-z0-9_]+$/, "name \u2014 \u043B\u0430\u0442\u0438\u043D\u0438\u0446\u0430, \u0446\u0438\u0444\u0440\u044B \u0438 _").max(64),
|
|
11393
|
-
label: z2.string().min(1).max(80),
|
|
11394
|
-
kind: z2.enum(["text", "number", "date", "select"]),
|
|
11395
|
-
required: z2.boolean().optional(),
|
|
11396
|
-
min: z2.union([z2.number(), z2.string()]).optional(),
|
|
11397
|
-
max: z2.union([z2.number(), z2.string()]).optional(),
|
|
11398
|
-
options: options.optional(),
|
|
11399
|
-
multiline: z2.boolean().optional()
|
|
11400
|
-
}).superRefine((field, context) => {
|
|
11401
|
-
const issue = (message) => context.addIssue({ code: "custom", message, path: [field.name] });
|
|
11402
|
-
if (field.kind === "select" && !field.options) issue("\u0423 select \u043D\u0443\u0436\u043D\u044B options: 2\u20138 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432");
|
|
11403
|
-
if (field.kind !== "select" && field.options) issue("options \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0443 select");
|
|
11404
|
-
if (field.kind === "number") {
|
|
11405
|
-
if (field.min !== void 0 && typeof field.min !== "number" || field.max !== void 0 && typeof field.max !== "number") issue("\u0423 number min \u0438 max \u2014 \u0447\u0438\u0441\u043B\u0430");
|
|
11406
|
-
else if (field.min !== void 0 && field.max !== void 0 && field.min > field.max) issue("\u0423 number \u043D\u0443\u0436\u043D\u043E min \u2264 max");
|
|
11407
|
-
} else if (field.kind === "date") {
|
|
11408
|
-
const dates = [field.min, field.max].filter((value) => value !== void 0);
|
|
11409
|
-
if (dates.some((value) => typeof value !== "string" || !isCalendarDate(value))) issue("\u0423 date min \u0438 max \u2014 \u0434\u0430\u0442\u044B YYYY-MM-DD");
|
|
11410
|
-
else if (field.min !== void 0 && field.max !== void 0 && field.min > field.max) issue("\u0423 date \u043D\u0443\u0436\u043D\u043E min \u2264 max");
|
|
11411
|
-
} else if (field.min !== void 0 || field.max !== void 0) {
|
|
11412
|
-
issue("min \u0438 max \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0443 number \u0438 date");
|
|
11413
|
-
}
|
|
11414
|
-
});
|
|
11415
|
-
var formInput = z2.object({
|
|
11416
|
-
title: z2.string().min(1).max(300),
|
|
11417
|
-
fields: z2.array(formField).min(1).max(5).refine((fields) => new Set(fields.map((field) => field.name)).size === fields.length, "\u0418\u043C\u0435\u043D\u0430 \u043F\u043E\u043B\u0435\u0439 \u043D\u0435 \u0434\u043E\u043B\u0436\u043D\u044B \u043F\u043E\u0432\u0442\u043E\u0440\u044F\u0442\u044C\u0441\u044F")
|
|
11418
|
-
});
|
|
11419
|
-
var suggestInput = z2.object({ replies: z2.array(z2.string().min(1).max(60)).min(1).max(4) });
|
|
11420
|
-
var ANSWERED_BY_MESSAGE_NOTE = '\u0415\u0441\u043B\u0438 \u0447\u0435\u043B\u043E\u0432\u0435\u043A \u043E\u0442\u0432\u0435\u0442\u0438\u0442 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C, \u0430 \u043D\u0435 \u0432 \u0432\u0438\u0434\u0436\u0435\u0442\u0435, \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u0431\u0443\u0434\u0435\u0442 {"\u043E\u0442\u0432\u0435\u0442":"\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C"}, \u0430 \u0435\u0433\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043F\u0440\u0438\u0434\u0451\u0442 \u0441\u043B\u0435\u0434\u043E\u043C.';
|
|
11421
|
-
var ONE_QUESTION_NOTE = "\u0417\u0430\u0434\u0430\u0432\u0430\u0439 \u043E\u0434\u0438\u043D \u0432\u043E\u043F\u0440\u043E\u0441 \u0437\u0430 \u0440\u0430\u0437: \u043D\u0435 \u0431\u043E\u043B\u044C\u0448\u0435 \u043E\u0434\u043D\u043E\u0433\u043E \u0442\u0430\u043A\u043E\u0433\u043E \u0432\u044B\u0437\u043E\u0432\u0430 \u0432 \u0448\u0430\u0433\u0435.";
|
|
11422
|
-
var TOOLS = {
|
|
11423
|
-
ask_choice: tool2({
|
|
11424
|
-
description: `\u0421\u043F\u0440\u043E\u0441\u0438\u0442\u044C \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0438 \u0434\u0430\u0442\u044C \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043E\u0434\u0438\u043D \u0432\u0430\u0440\u0438\u0430\u043D\u0442 \u0438\u0437 2\u20138 \u043A\u043D\u043E\u043F\u043E\u043A. \u041E\u0442\u0432\u0435\u0442 \u0436\u0434\u0451\u0442 \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0438 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u0432\u044B\u0431\u0440\u0430\u043D\u043E":"<\u0432\u0430\u0440\u0438\u0430\u043D\u0442>"}. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
11425
|
-
inputSchema: choiceInput
|
|
11426
|
-
}),
|
|
11427
|
-
ask_multi_choice: tool2({
|
|
11428
|
-
description: `\u0421\u043F\u0440\u043E\u0441\u0438\u0442\u044C \u0447\u0435\u043B\u043E\u0432\u0435\u043A\u0430 \u0438 \u0434\u0430\u0442\u044C \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432 \u0438\u0437 2\u20138 (min \u0438 max \u2014 \u0441\u043A\u043E\u043B\u044C\u043A\u043E \u043C\u043E\u0436\u043D\u043E \u0432\u044B\u0431\u0440\u0430\u0442\u044C). \u041E\u0442\u0432\u0435\u0442 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u0432\u044B\u0431\u0440\u0430\u043D\u043E":["<\u0432\u0430\u0440\u0438\u0430\u043D\u0442>",\u2026]} \u0432 \u043F\u043E\u0440\u044F\u0434\u043A\u0435 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
11429
|
-
inputSchema: multiChoiceInput
|
|
11430
|
-
}),
|
|
11431
|
-
ask_rating: tool2({
|
|
11432
|
-
description: `\u041F\u043E\u043F\u0440\u043E\u0441\u0438\u0442\u044C \u043E\u0446\u0435\u043D\u043A\u0443: \u0437\u0432\u0451\u0437\u0434\u044B 1\u20135 (scale "stars") \u0438\u043B\u0438 \u0448\u043A\u0430\u043B\u0430 \u043E\u0442 from (0 \u0438\u043B\u0438 1) \u0434\u043E to (2\u201310) \u0441 \u043F\u043E\u0434\u043F\u0438\u0441\u044F\u043C\u0438 \u043A\u0440\u0430\u0451\u0432 (scale "range"). \u041E\u0442\u0432\u0435\u0442 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u043E\u0446\u0435\u043D\u043A\u0430":<\u0446\u0435\u043B\u043E\u0435>}. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
11433
|
-
inputSchema: ratingInput
|
|
11434
|
-
}),
|
|
11435
|
-
ask_form: tool2({
|
|
11436
|
-
description: `\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043A\u043E\u0440\u043E\u0442\u043A\u0443\u044E \u0444\u043E\u0440\u043C\u0443 \u0438\u0437 1\u20135 \u043F\u043E\u043B\u0435\u0439: text, number (min, max), date (YYYY-MM-DD), select (2\u20138 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432). \u041E\u0442\u0432\u0435\u0442 \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442 \u043A\u0430\u043A {"\u043F\u043E\u043B\u044F":{"<name>":<\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435>}}; \u043F\u0443\u0441\u0442\u044B\u0435 \u043D\u0435\u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043F\u043E\u043B\u044F \u043D\u0435 \u043F\u0440\u0438\u0445\u043E\u0434\u044F\u0442. ${ONE_QUESTION_NOTE} ${ANSWERED_BY_MESSAGE_NOTE}`,
|
|
11437
|
-
inputSchema: formInput
|
|
11438
|
-
}),
|
|
11439
|
-
suggest_replies: tool2({
|
|
11440
|
-
description: `\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043F\u043E\u0434 \u043E\u0442\u0432\u0435\u0442\u043E\u043C 1\u20134 \u043A\u043E\u0440\u043E\u0442\u043A\u0438\u0445 \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u0447\u0435\u043B\u043E\u0432\u0435\u043A \u043C\u043E\u0436\u0435\u0442 \u043E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C \u043E\u0434\u043D\u0438\u043C \u043D\u0430\u0436\u0430\u0442\u0438\u0435\u043C. \u0425\u043E\u0434 \u043D\u0435 \u0436\u0434\u0451\u0442: \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u0441\u0440\u0430\u0437\u0443 "${SUGGESTIONS_SHOWN}". \u041D\u0430\u0436\u0430\u0442\u0430\u044F \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0430 \u043F\u0440\u0438\u0434\u0451\u0442 \u043E\u0431\u044B\u0447\u043D\u044B\u043C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C.`,
|
|
11441
|
-
inputSchema: suggestInput,
|
|
11442
|
-
execute: () => SUGGESTIONS_SHOWN
|
|
11443
|
-
})
|
|
11444
|
-
};
|
|
11445
|
-
function basicWidgetTool(name) {
|
|
11446
|
-
return TOOLS[name];
|
|
11447
|
-
}
|
|
11448
|
-
function checkBasicWidgetAnswer(name, input, answer) {
|
|
11449
|
-
switch (name) {
|
|
11450
|
-
case "ask_choice":
|
|
11451
|
-
return checkChoice(input, answer);
|
|
11452
|
-
case "ask_multi_choice":
|
|
11453
|
-
return checkMultiChoice(input, answer);
|
|
11454
|
-
case "ask_rating":
|
|
11455
|
-
return checkRating(input, answer);
|
|
11456
|
-
case "ask_form":
|
|
11457
|
-
return checkForm(input, answer);
|
|
11458
|
-
case "suggest_replies":
|
|
11459
|
-
return REJECTED;
|
|
11460
|
-
}
|
|
11461
|
-
}
|
|
11462
|
-
var REJECTED = { ok: false };
|
|
11463
|
-
function checkChoice(input, answer) {
|
|
11464
|
-
const call = choiceInput.safeParse(input);
|
|
11465
|
-
const value = onlyField(answer, "\u0432\u044B\u0431\u0440\u0430\u043D\u043E");
|
|
11466
|
-
if (!call.success || typeof value !== "string" || !call.data.options.includes(value)) return REJECTED;
|
|
11467
|
-
return { ok: true, output: { \u0432\u044B\u0431\u0440\u0430\u043D\u043E: value } };
|
|
11468
|
-
}
|
|
11469
|
-
function checkMultiChoice(input, answer) {
|
|
11470
|
-
const call = multiChoiceInput.safeParse(input);
|
|
11471
|
-
const value = onlyField(answer, "\u0432\u044B\u0431\u0440\u0430\u043D\u043E");
|
|
11472
|
-
if (!call.success || !Array.isArray(value)) return REJECTED;
|
|
11473
|
-
const chosen = new Set(value);
|
|
11474
|
-
const { min, max } = multiChoiceLimits(call.data);
|
|
11475
|
-
const known = value.every((option) => typeof option === "string" && call.data.options.includes(option));
|
|
11476
|
-
if (!known || chosen.size !== value.length || value.length < min || value.length > max) return REJECTED;
|
|
11477
|
-
return { ok: true, output: { \u0432\u044B\u0431\u0440\u0430\u043D\u043E: call.data.options.filter((option) => chosen.has(option)) } };
|
|
11478
|
-
}
|
|
11479
|
-
function checkRating(input, answer) {
|
|
11480
|
-
const call = ratingInput.safeParse(input);
|
|
11481
|
-
const value = onlyField(answer, "\u043E\u0446\u0435\u043D\u043A\u0430");
|
|
11482
|
-
if (!call.success || typeof value !== "number" || !Number.isInteger(value)) return REJECTED;
|
|
11483
|
-
const { from, to } = ratingLimits(call.data);
|
|
11484
|
-
if (value < from || value > to) return REJECTED;
|
|
11485
|
-
return { ok: true, output: { \u043E\u0446\u0435\u043D\u043A\u0430: value } };
|
|
11486
|
-
}
|
|
11487
|
-
function checkForm(input, answer) {
|
|
11488
|
-
const call = formInput.safeParse(input);
|
|
11489
|
-
const values = onlyField(answer, "\u043F\u043E\u043B\u044F");
|
|
11490
|
-
if (!call.success || !isPlainObject2(values)) return REJECTED;
|
|
11491
|
-
const fields = call.data.fields;
|
|
11492
|
-
if (Object.keys(values).some((key) => !fields.some((field) => field.name === key))) return REJECTED;
|
|
11493
|
-
const output = {};
|
|
11494
|
-
for (const field of fields) {
|
|
11495
|
-
const value = values[field.name];
|
|
11496
|
-
if (isEmptyValue(value)) {
|
|
11497
|
-
if (field.required) return REJECTED;
|
|
11498
|
-
continue;
|
|
11499
|
-
}
|
|
11500
|
-
if (!fieldValueFits(field, value)) return REJECTED;
|
|
11501
|
-
output[field.name] = value;
|
|
11502
|
-
}
|
|
11503
|
-
return { ok: true, output: { \u043F\u043E\u043B\u044F: output } };
|
|
11504
|
-
}
|
|
11505
|
-
function fieldValueFits(field, value) {
|
|
11506
|
-
switch (field.kind) {
|
|
11507
|
-
case "text":
|
|
11508
|
-
return typeof value === "string" && value.length <= FORM_TEXT_MAX;
|
|
11509
|
-
case "number":
|
|
11510
|
-
return typeof value === "number" && Number.isFinite(value) && (typeof field.min !== "number" || value >= field.min) && (typeof field.max !== "number" || value <= field.max);
|
|
11511
|
-
case "date":
|
|
11512
|
-
return typeof value === "string" && isCalendarDate(value) && (typeof field.min !== "string" || value >= field.min) && (typeof field.max !== "string" || value <= field.max);
|
|
11513
|
-
case "select":
|
|
11514
|
-
return typeof value === "string" && (field.options ?? []).includes(value);
|
|
11515
|
-
}
|
|
11516
|
-
}
|
|
11517
|
-
function isEmptyValue(value) {
|
|
11518
|
-
return value === void 0 || value === null || typeof value === "string" && value.trim() === "";
|
|
11519
|
-
}
|
|
11520
|
-
function multiChoiceLimits(input) {
|
|
11521
|
-
return { min: input.min ?? 1, max: input.max ?? input.options.length };
|
|
11522
|
-
}
|
|
11523
|
-
function ratingLimits(input) {
|
|
11524
|
-
return input.scale === "stars" ? { from: 1, to: 5 } : { from: input.from ?? 0, to: input.to ?? 10 };
|
|
11525
|
-
}
|
|
11526
|
-
function onlyField(answer, key) {
|
|
11527
|
-
if (!isPlainObject2(answer)) return void 0;
|
|
11528
|
-
const keys = Object.keys(answer);
|
|
11529
|
-
return keys.length === 1 && keys[0] === key ? answer[key] : void 0;
|
|
11530
|
-
}
|
|
11531
|
-
function isPlainObject2(value) {
|
|
11532
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11533
|
-
}
|
|
11534
|
-
function isCalendarDate(value) {
|
|
11535
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
11536
|
-
const date = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
|
|
11537
|
-
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
|
11538
|
-
}
|
|
11539
|
-
|
|
11540
11673
|
// src/widgets/define-widget.ts
|
|
11541
11674
|
var WIDGET_NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
11542
11675
|
var RESERVED_PREFIXES = ["ask_", "suggest_"];
|
|
@@ -11868,7 +12001,7 @@ function isPlainObject3(value) {
|
|
|
11868
12001
|
}
|
|
11869
12002
|
|
|
11870
12003
|
// src/memory/memory-after-answer.ts
|
|
11871
|
-
import { wrapLanguageModel as
|
|
12004
|
+
import { wrapLanguageModel as wrapLanguageModel9 } from "ai";
|
|
11872
12005
|
var DRAIN_WAIT_MS = 5e3;
|
|
11873
12006
|
function createMemoryAfterAnswer({ memory, storage, catalog, env, logError, turnObserver }) {
|
|
11874
12007
|
const running = /* @__PURE__ */ new Set();
|
|
@@ -11913,7 +12046,7 @@ function createMemoryAfterAnswer({ memory, storage, catalog, env, logError, turn
|
|
|
11913
12046
|
};
|
|
11914
12047
|
}
|
|
11915
12048
|
function withRetries(model, context) {
|
|
11916
|
-
return typeof model === "string" ? model :
|
|
12049
|
+
return typeof model === "string" ? model : wrapLanguageModel9({ model, middleware: createTransientRetryMiddleware(context) });
|
|
11917
12050
|
}
|
|
11918
12051
|
|
|
11919
12052
|
// src/conversation/to-agent-chat-message.ts
|
|
@@ -13186,10 +13319,10 @@ async function prepareTurnSafely(input) {
|
|
|
13186
13319
|
}, timeoutMs);
|
|
13187
13320
|
const fail = (reason) => logError(`[prepareTurn] \u0447\u0430\u0442=${context.chatId} \u0445\u043E\u0434 \u0431\u0435\u0437 \u0437\u0430\u043F\u0438\u0441\u0435\u0439: ${reason}`);
|
|
13188
13321
|
try {
|
|
13189
|
-
const
|
|
13322
|
+
const aborted2 = new Promise((resolve) => controller.signal.addEventListener("abort", () => resolve("aborted"), { once: true }));
|
|
13190
13323
|
const result = await Promise.race([
|
|
13191
13324
|
Promise.resolve().then(() => input.prepareTurn({ ...context, state: publicAppState(input.state), abortSignal: controller.signal })),
|
|
13192
|
-
|
|
13325
|
+
aborted2
|
|
13193
13326
|
]);
|
|
13194
13327
|
if (result === "aborted") {
|
|
13195
13328
|
if (timedOut) fail(`\u043D\u0435 \u0443\u043B\u043E\u0436\u0438\u043B\u0441\u044F \u0432 ${timeoutMs} \u043C\u0441`);
|
|
@@ -13486,6 +13619,7 @@ function createChatService(input) {
|
|
|
13486
13619
|
toolTimeoutMs: toolTimeoutSetting,
|
|
13487
13620
|
repairToolInput,
|
|
13488
13621
|
sequentialTools: sequentialToolsSetting,
|
|
13622
|
+
serviceTools: serviceToolsSetting,
|
|
13489
13623
|
timeZone: timeZoneSetting,
|
|
13490
13624
|
modelSilenceTimeout,
|
|
13491
13625
|
widgets: _widgets,
|
|
@@ -13509,6 +13643,7 @@ function createChatService(input) {
|
|
|
13509
13643
|
const toolResultLimit = resolveToolResultLimit(toolResultMaxLength);
|
|
13510
13644
|
const toolTimeout = resolveToolTimeout(toolTimeoutSetting);
|
|
13511
13645
|
const sequentialTools = resolveSequentialTools(sequentialToolsSetting);
|
|
13646
|
+
const serviceTools = new Set(serviceToolsSetting ?? []);
|
|
13512
13647
|
const sdkScreenToolNames = /* @__PURE__ */ new Set([...Object.keys(widgets.tools), ...Object.keys(browserToolDescriptions ?? {})]);
|
|
13513
13648
|
const isScreenTool = (toolName) => sdkScreenToolNames.has(toolName);
|
|
13514
13649
|
const hiddenStateKey = hiddenStateKeyOf(options2.privateStateKeys);
|
|
@@ -14303,6 +14438,7 @@ function createChatService(input) {
|
|
|
14303
14438
|
toolTimeout,
|
|
14304
14439
|
...repairToolInput && { repairToolInput },
|
|
14305
14440
|
sequentialTools,
|
|
14441
|
+
serviceTools,
|
|
14306
14442
|
toolQueue,
|
|
14307
14443
|
stepContextTimeoutMs,
|
|
14308
14444
|
contextBlocksTimeoutMs,
|
|
@@ -15978,6 +16114,9 @@ export {
|
|
|
15978
16114
|
STEP_RESET_PART_TYPE,
|
|
15979
16115
|
STEPS_MAY_RESET_PART_TYPE,
|
|
15980
16116
|
withoutResetSteps,
|
|
16117
|
+
BASIC_WIDGET_NAMES,
|
|
16118
|
+
SUGGESTIONS_SHOWN,
|
|
16119
|
+
SUGGESTIONS_SHOWN_AFTER_ANSWER,
|
|
15981
16120
|
DEFAULT_TOOL_TIMEOUT_MS,
|
|
15982
16121
|
TOOL_TIMEOUT_HINT,
|
|
15983
16122
|
declareToolTimeout,
|
|
@@ -16055,8 +16194,6 @@ export {
|
|
|
16055
16194
|
IMPORT_MAX_IMAGE_BYTES,
|
|
16056
16195
|
InvalidModelChoiceError,
|
|
16057
16196
|
buildModelMenu,
|
|
16058
|
-
BASIC_WIDGET_NAMES,
|
|
16059
|
-
SUGGESTIONS_SHOWN,
|
|
16060
16197
|
defineWidget,
|
|
16061
16198
|
WIDGET_ANSWER_MAX_BYTES,
|
|
16062
16199
|
WidgetAnswerRefusedError,
|
|
@@ -16072,4 +16209,4 @@ export {
|
|
|
16072
16209
|
InvalidWidgetAnswerError,
|
|
16073
16210
|
createChatService
|
|
16074
16211
|
};
|
|
16075
|
-
//# sourceMappingURL=chunk-
|
|
16212
|
+
//# sourceMappingURL=chunk-WMVDYLNE.js.map
|