@genesislcap/ai-assistant 15.90.4 → 15.92.0-GENC-1665.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-driver.cjs +1143 -183
- package/dist/chat-driver.cjs.map +4 -4
- package/dist/chat-driver.mjs +1133 -183
- package/dist/chat-driver.mjs.map +4 -4
- package/dist/custom-elements.json +114 -1
- package/dist/dts/chat-driver-node.d.ts +2 -2
- package/dist/dts/chat-driver-node.d.ts.map +1 -1
- package/dist/dts/components/chat-driver/chat-driver.constants.d.ts +10 -0
- package/dist/dts/components/chat-driver/chat-driver.constants.d.ts.map +1 -1
- package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
- package/dist/esm/chat-driver-node.js +6 -3
- package/dist/esm/components/chat-driver/chat-driver.constants.js +10 -0
- package/dist/esm/components/chat-driver/chat-driver.js +42 -6
- package/dist/esm/state/debug-event-log.js +1 -1
- package/package.json +17 -17
package/dist/chat-driver.cjs
CHANGED
|
@@ -27,6 +27,7 @@ __export(chat_driver_node_exports, {
|
|
|
27
27
|
ANTHROPIC_CACHE_READ_MULTIPLIER: () => ANTHROPIC_CACHE_READ_MULTIPLIER,
|
|
28
28
|
ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER: () => ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER,
|
|
29
29
|
ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER: () => ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER,
|
|
30
|
+
ANTHROPIC_LONG_CONTEXT_THRESHOLD: () => ANTHROPIC_LONG_CONTEXT_THRESHOLD,
|
|
30
31
|
AgenticActivityBus: () => AgenticActivityBus,
|
|
31
32
|
AnthropicProvider: () => AnthropicProvider,
|
|
32
33
|
AnthropicTransport: () => AnthropicTransport,
|
|
@@ -43,17 +44,24 @@ __export(chat_driver_node_exports, {
|
|
|
43
44
|
MALFORMED_CALL_NUDGE: () => MALFORMED_CALL_NUDGE,
|
|
44
45
|
MutableAIProviderRegistry: () => MutableAIProviderRegistry,
|
|
45
46
|
NOOP_ACTIVITY_BUS: () => NOOP_ACTIVITY_BUS,
|
|
47
|
+
OPENAI_CACHE_WRITE_12H_MULTIPLIER: () => OPENAI_CACHE_WRITE_12H_MULTIPLIER,
|
|
48
|
+
OPENAI_CACHE_WRITE_30M_MULTIPLIER: () => OPENAI_CACHE_WRITE_30M_MULTIPLIER,
|
|
49
|
+
OPENAI_LONG_CONTEXT_THRESHOLD: () => OPENAI_LONG_CONTEXT_THRESHOLD,
|
|
50
|
+
OpenAIProvider: () => OpenAIProvider,
|
|
51
|
+
OpenAITransport: () => OpenAITransport,
|
|
46
52
|
OrchestratingDriver: () => OrchestratingDriver,
|
|
47
53
|
PROVIDER_REFUSED_CODE: () => PROVIDER_REFUSED_CODE,
|
|
48
54
|
ProviderRefusedError: () => ProviderRefusedError,
|
|
49
55
|
SUPPORTED_ANTHROPIC_MODEL_IDS: () => SUPPORTED_ANTHROPIC_MODEL_IDS,
|
|
50
56
|
SUPPORTED_GEMINI_MODEL_IDS: () => SUPPORTED_GEMINI_MODEL_IDS,
|
|
57
|
+
SUPPORTED_OPENAI_MODEL_IDS: () => SUPPORTED_OPENAI_MODEL_IDS,
|
|
51
58
|
UNROUTABLE_INSTRUCTION: () => UNROUTABLE_INSTRUCTION,
|
|
52
59
|
UNROUTABLE_PLACEHOLDER: () => UNROUTABLE_PLACEHOLDER,
|
|
53
60
|
addUsage: () => addUsage,
|
|
54
61
|
agenticActivityBus: () => agenticActivityBus,
|
|
55
62
|
aiServiceAccessRefusalOf: () => aiServiceAccessRefusalOf,
|
|
56
63
|
aiServiceErrorCodeOf: () => aiServiceErrorCodeOf,
|
|
64
|
+
anthropicCacheReadMultiplierFor: () => anthropicCacheReadMultiplierFor,
|
|
57
65
|
anthropicRatesFor: () => anthropicRatesFor,
|
|
58
66
|
anthropicTokenCost: () => anthropicTokenCost,
|
|
59
67
|
assembleDebugLog: () => assembleDebugLog,
|
|
@@ -76,6 +84,8 @@ __export(chat_driver_node_exports, {
|
|
|
76
84
|
isTerminalAIServiceRefusal: () => isTerminalAIServiceRefusal,
|
|
77
85
|
lifetimeDebugLog: () => lifetimeDebugLog,
|
|
78
86
|
messageUsage: () => messageUsage,
|
|
87
|
+
openaiRatesFor: () => openaiRatesFor,
|
|
88
|
+
openaiTokenCost: () => openaiTokenCost,
|
|
79
89
|
resolveAITiers: () => resolveAITiers,
|
|
80
90
|
restoreMachine: () => restoreMachine,
|
|
81
91
|
strictFallbackAgent: () => strictFallbackAgent,
|
|
@@ -1250,154 +1260,49 @@ var GeminiProvider = class {
|
|
|
1250
1260
|
}
|
|
1251
1261
|
};
|
|
1252
1262
|
|
|
1253
|
-
// ../../foundation-ai/dist/esm/
|
|
1254
|
-
var
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
openai: "OpenAI",
|
|
1259
|
-
chrome: "Chrome"
|
|
1260
|
-
});
|
|
1261
|
-
var BUDGETED_VENDORS = Object.freeze([
|
|
1262
|
-
"anthropic",
|
|
1263
|
-
"gemini"
|
|
1264
|
-
]);
|
|
1265
|
-
var VENDOR_TYPE_BY_LABEL = new Map(Object.entries(VENDOR_LABELS).map(([type, label]) => [
|
|
1266
|
-
label.toLowerCase(),
|
|
1267
|
-
type
|
|
1268
|
-
]));
|
|
1269
|
-
function vendorTypeOfLabel(label) {
|
|
1270
|
-
if (typeof label !== "string")
|
|
1271
|
-
return void 0;
|
|
1272
|
-
return VENDOR_TYPE_BY_LABEL.get(label.trim().toLowerCase());
|
|
1273
|
-
}
|
|
1274
|
-
var BUDGET_EXCEEDED_STATUS = 402;
|
|
1275
|
-
var DEFAULT_BUDGET_EXHAUSTED_MESSAGE = "You've reached your AI usage limit. Contact your administrator to raise it.";
|
|
1276
|
-
var BudgetExhaustedError = class extends Error {
|
|
1277
|
-
constructor(vendorLabel, budgetUsd, spentUsd, detail, extra) {
|
|
1278
|
-
super(`${vendorLabel} request refused: the AI usage budget is exhausted` + (budgetUsd != null ? ` (spent ${spentUsd != null ? `$${spentUsd}` : "an unknown amount"} of a $${budgetUsd} budget)` : "") + (detail ? `: ${detail}` : "") + ". Retrying will not clear this \u2014 the budget must be raised.");
|
|
1279
|
-
this.vendorLabel = vendorLabel;
|
|
1280
|
-
this.budgetUsd = budgetUsd;
|
|
1281
|
-
this.spentUsd = spentUsd;
|
|
1282
|
-
this.detail = detail;
|
|
1283
|
-
this.name = "BudgetExhaustedError";
|
|
1284
|
-
this.otherVendorAvailable = extra === null || extra === void 0 ? void 0 : extra.otherVendorAvailable;
|
|
1285
|
-
this.serverVendor = extra === null || extra === void 0 ? void 0 : extra.serverVendor;
|
|
1286
|
-
}
|
|
1287
|
-
};
|
|
1288
|
-
var isBudgetRejection = (status, code) => status === BUDGET_EXCEEDED_STATUS || code === BUDGET_EXCEEDED_CODE;
|
|
1289
|
-
var parseJsonOrUndefined = (text) => {
|
|
1290
|
-
try {
|
|
1291
|
-
return JSON.parse(text);
|
|
1292
|
-
} catch (_a) {
|
|
1293
|
-
return void 0;
|
|
1294
|
-
}
|
|
1295
|
-
};
|
|
1296
|
-
var codeOf = (payload) => {
|
|
1297
|
-
const code = payload === null || payload === void 0 ? void 0 : payload.code;
|
|
1298
|
-
return typeof code === "string" ? code : void 0;
|
|
1299
|
-
};
|
|
1300
|
-
var numberOrUndefined = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
1301
|
-
var booleanOrUndefined = (value) => typeof value === "boolean" ? value : void 0;
|
|
1302
|
-
var stringOrUndefined = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
1303
|
-
function budgetExhaustedFrom(vendorLabel, payload, fallbackDetail) {
|
|
1304
|
-
var _a, _b, _c, _d;
|
|
1305
|
-
const body = typeof payload === "object" && payload !== null ? payload : {};
|
|
1306
|
-
const details = typeof body.details === "object" && body.details !== null ? body.details : {};
|
|
1307
|
-
const detail = typeof body.error === "string" ? body.error : fallbackDetail;
|
|
1308
|
-
return new BudgetExhaustedError(vendorLabel, (_a = numberOrUndefined(body.budgetUsd)) !== null && _a !== void 0 ? _a : numberOrUndefined(details.budgetUsd), (_b = numberOrUndefined(body.spentUsd)) !== null && _b !== void 0 ? _b : numberOrUndefined(details.spentUsd), detail, {
|
|
1309
|
-
otherVendorAvailable: (_c = booleanOrUndefined(body.otherVendorAvailable)) !== null && _c !== void 0 ? _c : booleanOrUndefined(details.otherVendorAvailable),
|
|
1310
|
-
serverVendor: (_d = stringOrUndefined(body.vendor)) !== null && _d !== void 0 ? _d : stringOrUndefined(details.vendor)
|
|
1311
|
-
});
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
// ../../foundation-ai/dist/esm/transports/provider-refused.js
|
|
1315
|
-
var PROVIDER_REFUSED_CODE = "PROVIDER_REFUSED";
|
|
1316
|
-
var DEFAULT_PROVIDER_REFUSED_MESSAGE = "AI requests are currently being refused by the provider. This isn't related to your account or your usage and needs no action from you \u2014 please contact your support team so it can be restored.";
|
|
1317
|
-
var ProviderRefusedError = class extends Error {
|
|
1318
|
-
constructor(vendorLabel, kind, upstreamStatus, upstreamType, detail) {
|
|
1319
|
-
super(`${vendorLabel} refused the request (${kind})` + (upstreamStatus != null ? ` \u2014 HTTP ${upstreamStatus}` : "") + (upstreamType ? ` ${upstreamType}` : "") + (detail ? `: ${detail}` : "") + ". Retrying will not clear this \u2014 the provider account must be fixed.");
|
|
1320
|
-
this.vendorLabel = vendorLabel;
|
|
1321
|
-
this.kind = kind;
|
|
1322
|
-
this.upstreamStatus = upstreamStatus;
|
|
1323
|
-
this.upstreamType = upstreamType;
|
|
1324
|
-
this.detail = detail;
|
|
1325
|
-
this.name = "ProviderRefusedError";
|
|
1263
|
+
// ../../foundation-ai/dist/esm/providers/openai-provider.js
|
|
1264
|
+
var OpenAIProvider = class {
|
|
1265
|
+
constructor(config, transport) {
|
|
1266
|
+
this.transport = transport;
|
|
1267
|
+
this.criteriaInstructions = config.criteriaInstructions;
|
|
1326
1268
|
}
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
/insufficient (credit|funds|balance)/i
|
|
1333
|
-
]);
|
|
1334
|
-
var ANTHROPIC_AUTH_TYPES = Object.freeze([
|
|
1335
|
-
"authentication_error",
|
|
1336
|
-
"permission_error"
|
|
1337
|
-
]);
|
|
1338
|
-
function anthropicErrorBody(payload) {
|
|
1339
|
-
var _a;
|
|
1340
|
-
const outer = typeof payload === "object" && payload !== null ? payload : {};
|
|
1341
|
-
for (const candidate of [
|
|
1342
|
-
outer.error,
|
|
1343
|
-
(_a = outer.details) === null || _a === void 0 ? void 0 : _a.error
|
|
1344
|
-
]) {
|
|
1345
|
-
if (typeof candidate === "object" && candidate !== null) {
|
|
1346
|
-
const { type, message } = candidate;
|
|
1347
|
-
return {
|
|
1348
|
-
type: typeof type === "string" ? type : void 0,
|
|
1349
|
-
message: typeof message === "string" ? message : void 0
|
|
1350
|
-
};
|
|
1351
|
-
}
|
|
1269
|
+
getStatus() {
|
|
1270
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1271
|
+
const config = this.transport.getConfig();
|
|
1272
|
+
return { provider: "openai", model: config.model, contextLimit: config.contextLimit };
|
|
1273
|
+
});
|
|
1352
1274
|
}
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1275
|
+
interpretCriteria(input, context) {
|
|
1276
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1277
|
+
var _a;
|
|
1278
|
+
const fields = (_a = context === null || context === void 0 ? void 0 : context.fields) !== null && _a !== void 0 ? _a : [];
|
|
1279
|
+
const systemPrompt = buildCriteriaSystemPrompt(fields, this.criteriaInstructions);
|
|
1280
|
+
const userPrompt = buildCriteriaUserPrompt(input);
|
|
1281
|
+
try {
|
|
1282
|
+
const raw = yield this.transport.sendStructuredPrompt({
|
|
1283
|
+
systemPrompt,
|
|
1284
|
+
userPrompt,
|
|
1285
|
+
responseSchema: CRITERIA_JSON_SCHEMA
|
|
1286
|
+
});
|
|
1287
|
+
return parseCriteriaResponse(raw);
|
|
1288
|
+
} catch (e) {
|
|
1289
|
+
logger.error("OpenAIProvider interpretCriteria failed:", e);
|
|
1290
|
+
return null;
|
|
1291
|
+
}
|
|
1292
|
+
});
|
|
1361
1293
|
}
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
return void 0;
|
|
1368
|
-
if (ANTHROPIC_AUTH_TYPES.includes(body.type))
|
|
1369
|
-
return "auth";
|
|
1370
|
-
if (body.type === "billing_error")
|
|
1371
|
-
return "spend";
|
|
1372
|
-
return void 0;
|
|
1373
|
-
}
|
|
1374
|
-
function providerRefusalOf(vendor, code, payload) {
|
|
1375
|
-
var _a, _b;
|
|
1376
|
-
if (code === PROVIDER_REFUSED_CODE) {
|
|
1377
|
-
return (_b = (_a = statedKind(payload)) !== null && _a !== void 0 ? _a : kindFromEnvelopeType(payload)) !== null && _b !== void 0 ? _b : "spend";
|
|
1294
|
+
prompt(message, options) {
|
|
1295
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1296
|
+
const response = yield this.transport.sendChatMessage([], message, options);
|
|
1297
|
+
return response.content;
|
|
1298
|
+
});
|
|
1378
1299
|
}
|
|
1379
|
-
|
|
1380
|
-
return void 0
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
return structural;
|
|
1384
|
-
const body = anthropicErrorBody(payload);
|
|
1385
|
-
if ((body === null || body === void 0 ? void 0 : body.type) === "invalid_request_error" && body.message) {
|
|
1386
|
-
const message = body.message;
|
|
1387
|
-
if (ANTHROPIC_SPEND_PHRASES.some((phrase) => phrase.test(message)))
|
|
1388
|
-
return "spend";
|
|
1300
|
+
chat(history, userMessage, options) {
|
|
1301
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1302
|
+
return this.transport.sendChatMessage(history, userMessage, options);
|
|
1303
|
+
});
|
|
1389
1304
|
}
|
|
1390
|
-
|
|
1391
|
-
}
|
|
1392
|
-
function providerRefusedFrom(vendorLabel, kind, upstreamStatus, payload, fallbackDetail) {
|
|
1393
|
-
var _a;
|
|
1394
|
-
const body = anthropicErrorBody(payload);
|
|
1395
|
-
return new ProviderRefusedError(vendorLabel, kind, upstreamStatus, body === null || body === void 0 ? void 0 : body.type, (_a = body === null || body === void 0 ? void 0 : body.message) !== null && _a !== void 0 ? _a : fallbackDetail);
|
|
1396
|
-
}
|
|
1397
|
-
function vendorOfTransportLabel(vendorLabel) {
|
|
1398
|
-
const entry = Object.entries(VENDOR_LABELS).find(([, label]) => label === vendorLabel);
|
|
1399
|
-
return entry === null || entry === void 0 ? void 0 : entry[0];
|
|
1400
|
-
}
|
|
1305
|
+
};
|
|
1401
1306
|
|
|
1402
1307
|
// ../../foundation-ai/dist/esm/types/config.types.js
|
|
1403
1308
|
var SUPPORTED_GEMINI_MODEL_IDS = [
|
|
@@ -1412,17 +1317,29 @@ var SUPPORTED_GEMINI_MODEL_IDS = [
|
|
|
1412
1317
|
];
|
|
1413
1318
|
var SUPPORTED_ANTHROPIC_MODEL_IDS = [
|
|
1414
1319
|
"claude-fable-5",
|
|
1320
|
+
"claude-opus-5-5",
|
|
1415
1321
|
"claude-opus-4-8",
|
|
1416
1322
|
"claude-opus-4-7",
|
|
1323
|
+
"claude-sonnet-5-5",
|
|
1417
1324
|
"claude-sonnet-5",
|
|
1418
1325
|
"claude-sonnet-4-6",
|
|
1326
|
+
"claude-haiku-5-5",
|
|
1419
1327
|
"claude-haiku-4-5-20251001"
|
|
1420
1328
|
];
|
|
1329
|
+
var SUPPORTED_OPENAI_MODEL_IDS = [
|
|
1330
|
+
"gpt-6-astra",
|
|
1331
|
+
"gpt-6.1-sol",
|
|
1332
|
+
"gpt-6.1-terra",
|
|
1333
|
+
"gpt-6-sol",
|
|
1334
|
+
"gpt-6-luna"
|
|
1335
|
+
];
|
|
1421
1336
|
function vendorOfModel(modelId) {
|
|
1422
1337
|
if (SUPPORTED_ANTHROPIC_MODEL_IDS.includes(modelId))
|
|
1423
1338
|
return "anthropic";
|
|
1424
1339
|
if (SUPPORTED_GEMINI_MODEL_IDS.includes(modelId))
|
|
1425
1340
|
return "gemini";
|
|
1341
|
+
if (SUPPORTED_OPENAI_MODEL_IDS.includes(modelId))
|
|
1342
|
+
return "openai";
|
|
1426
1343
|
return void 0;
|
|
1427
1344
|
}
|
|
1428
1345
|
|
|
@@ -1443,14 +1360,35 @@ function scaleTemperature(normalized, { defaultTemp, maxTemp }) {
|
|
|
1443
1360
|
|
|
1444
1361
|
// ../../foundation-ai/dist/esm/utils/token-cost.js
|
|
1445
1362
|
var TOKENS_PER_MILLION = 1e6;
|
|
1363
|
+
var ANTHROPIC_LONG_CONTEXT_THRESHOLD = 1e5;
|
|
1446
1364
|
var ANTHROPIC_PRICING = {
|
|
1447
|
-
"claude-haiku-4-5-20251001": {
|
|
1365
|
+
"claude-haiku-4-5-20251001": {
|
|
1366
|
+
kind: "flat",
|
|
1367
|
+
rate: { promptPerMillion: 1, candidatePerMillion: 5 }
|
|
1368
|
+
},
|
|
1369
|
+
// Haiku 5.5 has two rate cards chosen by prompt length; cache reads are 0.1× the input rate of
|
|
1370
|
+
// whichever card applies, like every other model here.
|
|
1371
|
+
"claude-haiku-5-5": {
|
|
1372
|
+
kind: "tiered",
|
|
1373
|
+
standard: { promptPerMillion: 0.1, candidatePerMillion: 0.5 },
|
|
1374
|
+
longContext: { promptPerMillion: 0.5, candidatePerMillion: 2.5 }
|
|
1375
|
+
},
|
|
1448
1376
|
// Fable 5 — Anthropic's most capable widely-released model; priced above Opus tier.
|
|
1449
|
-
"claude-fable-5": { promptPerMillion: 10, candidatePerMillion: 50 },
|
|
1377
|
+
"claude-fable-5": { kind: "flat", rate: { promptPerMillion: 10, candidatePerMillion: 50 } },
|
|
1378
|
+
// Opus 5.5 — $4 / $20, cheaper than Opus 4.8. Its cache reads are $0.20 / MTok, i.e. 0.05× the
|
|
1379
|
+
// input rate, NOT the 0.1× every older model reads at: the global multiplier would bill its
|
|
1380
|
+
// cache reads at double.
|
|
1381
|
+
"claude-opus-5-5": {
|
|
1382
|
+
kind: "flat",
|
|
1383
|
+
rate: { promptPerMillion: 4, candidatePerMillion: 20 },
|
|
1384
|
+
cacheReadMultiplier: 0.05
|
|
1385
|
+
},
|
|
1450
1386
|
// Opus 4.7 / 4.8 — same $5 / $25 per MTok. Stated per model rather than shared through a
|
|
1451
1387
|
// fall-through, so neither is ever "whatever was left over".
|
|
1452
|
-
"claude-opus-4-8": { promptPerMillion: 5, candidatePerMillion: 25 },
|
|
1453
|
-
"claude-opus-4-7": { promptPerMillion: 5, candidatePerMillion: 25 },
|
|
1388
|
+
"claude-opus-4-8": { kind: "flat", rate: { promptPerMillion: 5, candidatePerMillion: 25 } },
|
|
1389
|
+
"claude-opus-4-7": { kind: "flat", rate: { promptPerMillion: 5, candidatePerMillion: 25 } },
|
|
1390
|
+
// Sonnet 5.5 — same $2 / $10 as Sonnet 5, cache reads $0.20 (0.1×).
|
|
1391
|
+
"claude-sonnet-5-5": { kind: "flat", rate: { promptPerMillion: 2, candidatePerMillion: 10 } },
|
|
1454
1392
|
// Sonnet 5 is $2 / $10 — its OWN tier, and CHEAPER than the older Sonnet 4.6 below.
|
|
1455
1393
|
//
|
|
1456
1394
|
// This launched as an introductory rate through 2026-08-31, and an earlier version of this
|
|
@@ -1459,22 +1397,32 @@ var ANTHROPIC_PRICING = {
|
|
|
1459
1397
|
// standard price and cancelled the scheduled increase, so that reasoning is dead and the old
|
|
1460
1398
|
// figure over-charged every Sonnet 5 request by 50%.
|
|
1461
1399
|
// https://platform.claude.com/docs/en/about-claude/pricing#model-pricing
|
|
1462
|
-
"claude-sonnet-5": { promptPerMillion: 2, candidatePerMillion: 10 },
|
|
1400
|
+
"claude-sonnet-5": { kind: "flat", rate: { promptPerMillion: 2, candidatePerMillion: 10 } },
|
|
1463
1401
|
// Sonnet 4.6 remains on the older $3 / $15 Sonnet tier — the newer model is the cheaper one.
|
|
1464
|
-
"claude-sonnet-4-6": { promptPerMillion: 3, candidatePerMillion: 15 }
|
|
1402
|
+
"claude-sonnet-4-6": { kind: "flat", rate: { promptPerMillion: 3, candidatePerMillion: 15 } }
|
|
1465
1403
|
};
|
|
1466
|
-
function anthropicRatesFor(model) {
|
|
1467
|
-
|
|
1404
|
+
function anthropicRatesFor(model, promptTokens = 0) {
|
|
1405
|
+
const pricing = ANTHROPIC_PRICING[model];
|
|
1406
|
+
if (pricing.kind === "flat") {
|
|
1407
|
+
return pricing.rate;
|
|
1408
|
+
}
|
|
1409
|
+
return promptTokens > ANTHROPIC_LONG_CONTEXT_THRESHOLD ? pricing.longContext : pricing.standard;
|
|
1468
1410
|
}
|
|
1469
1411
|
var ANTHROPIC_CACHE_READ_MULTIPLIER = 0.1;
|
|
1412
|
+
function anthropicCacheReadMultiplierFor(model) {
|
|
1413
|
+
var _a;
|
|
1414
|
+
return (_a = ANTHROPIC_PRICING[model].cacheReadMultiplier) !== null && _a !== void 0 ? _a : ANTHROPIC_CACHE_READ_MULTIPLIER;
|
|
1415
|
+
}
|
|
1470
1416
|
var ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER = 1.25;
|
|
1471
1417
|
var ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER = 2;
|
|
1472
1418
|
function anthropicTokenCost(model, usage) {
|
|
1473
|
-
const
|
|
1419
|
+
const promptTokens = usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
|
|
1420
|
+
const { promptPerMillion, candidatePerMillion } = anthropicRatesFor(model, promptTokens);
|
|
1421
|
+
const cacheReadMultiplier = anthropicCacheReadMultiplierFor(model);
|
|
1474
1422
|
const m = TOKENS_PER_MILLION;
|
|
1475
1423
|
const cacheWrite5mTokens = Math.max(0, usage.cacheWriteTokens - usage.cacheWrite1hTokens);
|
|
1476
1424
|
const promptCost = usage.uncachedInputTokens / m * promptPerMillion;
|
|
1477
|
-
const cacheReadCost = usage.cacheReadTokens / m * promptPerMillion *
|
|
1425
|
+
const cacheReadCost = usage.cacheReadTokens / m * promptPerMillion * cacheReadMultiplier;
|
|
1478
1426
|
const cacheWriteCost = cacheWrite5mTokens / m * promptPerMillion * ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER + usage.cacheWrite1hTokens / m * promptPerMillion * ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER;
|
|
1479
1427
|
const candidateCost = usage.outputTokens / m * candidatePerMillion;
|
|
1480
1428
|
const cacheReadFull = usage.cacheReadTokens / m * promptPerMillion;
|
|
@@ -1571,6 +1519,52 @@ function geminiTokenCost(model, usage, at = /* @__PURE__ */ new Date()) {
|
|
|
1571
1519
|
}
|
|
1572
1520
|
};
|
|
1573
1521
|
}
|
|
1522
|
+
var OPENAI_PRICING = {
|
|
1523
|
+
"gpt-6-astra": { promptPerMillion: 10, cachedPerMillion: 1, candidatePerMillion: 50 },
|
|
1524
|
+
"gpt-6.1-sol": { promptPerMillion: 2, cachedPerMillion: 0.1, candidatePerMillion: 10 },
|
|
1525
|
+
"gpt-6.1-terra": { promptPerMillion: 1, cachedPerMillion: 0.05, candidatePerMillion: 5 },
|
|
1526
|
+
"gpt-6-sol": { promptPerMillion: 2, cachedPerMillion: 0.2, candidatePerMillion: 10 },
|
|
1527
|
+
"gpt-6-luna": { promptPerMillion: 0.1, cachedPerMillion: 0.01, candidatePerMillion: 0.5 }
|
|
1528
|
+
};
|
|
1529
|
+
var OPENAI_LONG_CONTEXT_THRESHOLD = 272e3;
|
|
1530
|
+
var OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER = 2;
|
|
1531
|
+
var OPENAI_LONG_CONTEXT_OUTPUT_MULTIPLIER = 1.5;
|
|
1532
|
+
var OPENAI_CACHE_WRITE_30M_MULTIPLIER = 1.25;
|
|
1533
|
+
var OPENAI_CACHE_WRITE_12H_MULTIPLIER = 2.5;
|
|
1534
|
+
function openaiRatesFor(model, promptTokens) {
|
|
1535
|
+
const rate = OPENAI_PRICING[model];
|
|
1536
|
+
if (promptTokens <= OPENAI_LONG_CONTEXT_THRESHOLD) {
|
|
1537
|
+
return rate;
|
|
1538
|
+
}
|
|
1539
|
+
return {
|
|
1540
|
+
promptPerMillion: rate.promptPerMillion * OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER,
|
|
1541
|
+
cachedPerMillion: rate.cachedPerMillion * OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER,
|
|
1542
|
+
candidatePerMillion: rate.candidatePerMillion * OPENAI_LONG_CONTEXT_OUTPUT_MULTIPLIER
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
function openaiTokenCost(model, usage) {
|
|
1546
|
+
const { promptPerMillion, cachedPerMillion, candidatePerMillion } = openaiRatesFor(model, usage.inputTokens);
|
|
1547
|
+
const m = TOKENS_PER_MILLION;
|
|
1548
|
+
const uncachedTokens = Math.max(0, usage.inputTokens - usage.cacheReadTokens - usage.cacheWriteTokens);
|
|
1549
|
+
const write12hTokens = Math.min(usage.cacheWrite12hTokens, usage.cacheWriteTokens);
|
|
1550
|
+
const write30mTokens = Math.max(0, usage.cacheWriteTokens - write12hTokens);
|
|
1551
|
+
const promptCost = uncachedTokens / m * promptPerMillion;
|
|
1552
|
+
const cacheReadCost = usage.cacheReadTokens / m * cachedPerMillion;
|
|
1553
|
+
const cacheWriteCost = write30mTokens / m * promptPerMillion * OPENAI_CACHE_WRITE_30M_MULTIPLIER + write12hTokens / m * promptPerMillion * OPENAI_CACHE_WRITE_12H_MULTIPLIER;
|
|
1554
|
+
const candidateCost = usage.outputTokens / m * candidatePerMillion;
|
|
1555
|
+
const cacheReadFull = usage.cacheReadTokens / m * promptPerMillion;
|
|
1556
|
+
const cacheWriteFull = usage.cacheWriteTokens / m * promptPerMillion;
|
|
1557
|
+
return {
|
|
1558
|
+
costUsd: promptCost + cacheReadCost + cacheWriteCost + candidateCost,
|
|
1559
|
+
savedUsd: cacheReadFull - cacheReadCost + (cacheWriteFull - cacheWriteCost),
|
|
1560
|
+
breakdown: {
|
|
1561
|
+
promptUsd: promptCost,
|
|
1562
|
+
cacheReadUsd: cacheReadCost,
|
|
1563
|
+
cacheWriteUsd: cacheWriteCost,
|
|
1564
|
+
candidateUsd: candidateCost
|
|
1565
|
+
}
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1574
1568
|
|
|
1575
1569
|
// ../../foundation-ai/dist/esm/utils/tool-schema.js
|
|
1576
1570
|
var SCHEMA_MAP_KEYS = ["properties", "patternProperties", "$defs", "definitions"];
|
|
@@ -1753,6 +1747,135 @@ function toGeminiSchema(parameters) {
|
|
|
1753
1747
|
});
|
|
1754
1748
|
return translated;
|
|
1755
1749
|
}
|
|
1750
|
+
var OPENAI_UNDROPPABLE_KEYWORDS = ["allOf", "not", "if", "then", "else", "oneOf"];
|
|
1751
|
+
function withNull(node) {
|
|
1752
|
+
if (typeof node.type === "string") {
|
|
1753
|
+
const out = Object.assign(Object.assign({}, node), { type: node.type === "null" ? "null" : [node.type, "null"] });
|
|
1754
|
+
if (Array.isArray(node.enum) && !node.enum.includes(null))
|
|
1755
|
+
out.enum = [...node.enum, null];
|
|
1756
|
+
return out;
|
|
1757
|
+
}
|
|
1758
|
+
if (Array.isArray(node.type)) {
|
|
1759
|
+
if (node.type.includes("null"))
|
|
1760
|
+
return node;
|
|
1761
|
+
const out = Object.assign(Object.assign({}, node), { type: [...node.type, "null"] });
|
|
1762
|
+
if (Array.isArray(node.enum) && !node.enum.includes(null))
|
|
1763
|
+
out.enum = [...node.enum, null];
|
|
1764
|
+
return out;
|
|
1765
|
+
}
|
|
1766
|
+
if (Array.isArray(node.anyOf)) {
|
|
1767
|
+
return node.anyOf.some((b) => isPlainObject2(b) && b.type === "null") ? node : Object.assign(Object.assign({}, node), { anyOf: [...node.anyOf, { type: "null" }] });
|
|
1768
|
+
}
|
|
1769
|
+
return { anyOf: [node, { type: "null" }] };
|
|
1770
|
+
}
|
|
1771
|
+
function toOpenAIStrictSchema(parameters) {
|
|
1772
|
+
const madeNullable = [];
|
|
1773
|
+
const overridden = [];
|
|
1774
|
+
const undroppable = [];
|
|
1775
|
+
const schema = mapSchema(parameters, (node, path) => {
|
|
1776
|
+
for (const keyword of OPENAI_UNDROPPABLE_KEYWORDS) {
|
|
1777
|
+
if (keyword in node)
|
|
1778
|
+
undroppable.push(`${path}/${keyword}`);
|
|
1779
|
+
}
|
|
1780
|
+
const isObjectNode = node.type === "object" || Array.isArray(node.type) && node.type.includes("object") || isPlainObject2(node.properties);
|
|
1781
|
+
if (!isObjectNode)
|
|
1782
|
+
return node;
|
|
1783
|
+
if (node.additionalProperties !== false) {
|
|
1784
|
+
if (node.additionalProperties !== void 0)
|
|
1785
|
+
overridden.push(`${path}/additionalProperties`);
|
|
1786
|
+
node.additionalProperties = false;
|
|
1787
|
+
}
|
|
1788
|
+
if (isPlainObject2(node.properties)) {
|
|
1789
|
+
const names = Object.keys(node.properties);
|
|
1790
|
+
const required = new Set(Array.isArray(node.required) ? node.required : []);
|
|
1791
|
+
const properties = node.properties;
|
|
1792
|
+
for (const name of names) {
|
|
1793
|
+
if (required.has(name))
|
|
1794
|
+
continue;
|
|
1795
|
+
properties[name] = isPlainObject2(properties[name]) ? withNull(properties[name]) : { type: "null" };
|
|
1796
|
+
madeNullable.push(`${path}/properties/${name}`);
|
|
1797
|
+
}
|
|
1798
|
+
node.required = names;
|
|
1799
|
+
}
|
|
1800
|
+
return node;
|
|
1801
|
+
});
|
|
1802
|
+
return { schema, madeNullable, overridden, undroppable };
|
|
1803
|
+
}
|
|
1804
|
+
function enforceOpenAIToolSchema(parameters, toolName) {
|
|
1805
|
+
const { schema, madeNullable, overridden, undroppable } = toOpenAIStrictSchema(parameters);
|
|
1806
|
+
if (madeNullable.length) {
|
|
1807
|
+
logger.debug(`OpenAITransport: tool "${toolName}" is strict, which has no optional properties; these are now required and nullable, so an absent value arrives as null: ${madeNullable.join(", ")}`);
|
|
1808
|
+
}
|
|
1809
|
+
if (overridden.length) {
|
|
1810
|
+
logger.warn(`OpenAITransport: tool "${toolName}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${overridden.join(", ")}.`);
|
|
1811
|
+
}
|
|
1812
|
+
if (undroppable.length) {
|
|
1813
|
+
logger.warn(`OpenAITransport: tool "${toolName}" uses schema keywords strict mode cannot express (${undroppable.join(", ")}). They are left in place, so the request will be rejected. Rewrite them or drop enforceSchema for this tool.`);
|
|
1814
|
+
}
|
|
1815
|
+
return schema;
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
// ../../foundation-ai/dist/esm/transports/budget-exhausted-error.js
|
|
1819
|
+
var BUDGET_EXCEEDED_CODE = "BUDGET_EXCEEDED";
|
|
1820
|
+
var VENDOR_LABELS = Object.freeze({
|
|
1821
|
+
anthropic: "Anthropic",
|
|
1822
|
+
gemini: "Gemini",
|
|
1823
|
+
openai: "OpenAI",
|
|
1824
|
+
chrome: "Chrome"
|
|
1825
|
+
});
|
|
1826
|
+
var BUDGETED_VENDORS = Object.freeze([
|
|
1827
|
+
"anthropic",
|
|
1828
|
+
"gemini",
|
|
1829
|
+
"openai"
|
|
1830
|
+
]);
|
|
1831
|
+
var VENDOR_TYPE_BY_LABEL = new Map(Object.entries(VENDOR_LABELS).map(([type, label]) => [
|
|
1832
|
+
label.toLowerCase(),
|
|
1833
|
+
type
|
|
1834
|
+
]));
|
|
1835
|
+
function vendorTypeOfLabel(label) {
|
|
1836
|
+
if (typeof label !== "string")
|
|
1837
|
+
return void 0;
|
|
1838
|
+
return VENDOR_TYPE_BY_LABEL.get(label.trim().toLowerCase());
|
|
1839
|
+
}
|
|
1840
|
+
var BUDGET_EXCEEDED_STATUS = 402;
|
|
1841
|
+
var DEFAULT_BUDGET_EXHAUSTED_MESSAGE = "You've reached your AI usage limit. Contact your administrator to raise it.";
|
|
1842
|
+
var BudgetExhaustedError = class extends Error {
|
|
1843
|
+
constructor(vendorLabel, budgetUsd, spentUsd, detail, extra) {
|
|
1844
|
+
super(`${vendorLabel} request refused: the AI usage budget is exhausted` + (budgetUsd != null ? ` (spent ${spentUsd != null ? `$${spentUsd}` : "an unknown amount"} of a $${budgetUsd} budget)` : "") + (detail ? `: ${detail}` : "") + ". Retrying will not clear this \u2014 the budget must be raised.");
|
|
1845
|
+
this.vendorLabel = vendorLabel;
|
|
1846
|
+
this.budgetUsd = budgetUsd;
|
|
1847
|
+
this.spentUsd = spentUsd;
|
|
1848
|
+
this.detail = detail;
|
|
1849
|
+
this.name = "BudgetExhaustedError";
|
|
1850
|
+
this.otherVendorAvailable = extra === null || extra === void 0 ? void 0 : extra.otherVendorAvailable;
|
|
1851
|
+
this.serverVendor = extra === null || extra === void 0 ? void 0 : extra.serverVendor;
|
|
1852
|
+
}
|
|
1853
|
+
};
|
|
1854
|
+
var isBudgetRejection = (status, code) => status === BUDGET_EXCEEDED_STATUS || code === BUDGET_EXCEEDED_CODE;
|
|
1855
|
+
var parseJsonOrUndefined = (text) => {
|
|
1856
|
+
try {
|
|
1857
|
+
return JSON.parse(text);
|
|
1858
|
+
} catch (_a) {
|
|
1859
|
+
return void 0;
|
|
1860
|
+
}
|
|
1861
|
+
};
|
|
1862
|
+
var codeOf = (payload) => {
|
|
1863
|
+
const code = payload === null || payload === void 0 ? void 0 : payload.code;
|
|
1864
|
+
return typeof code === "string" ? code : void 0;
|
|
1865
|
+
};
|
|
1866
|
+
var numberOrUndefined = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
1867
|
+
var booleanOrUndefined = (value) => typeof value === "boolean" ? value : void 0;
|
|
1868
|
+
var stringOrUndefined = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
1869
|
+
function budgetExhaustedFrom(vendorLabel, payload, fallbackDetail) {
|
|
1870
|
+
var _a, _b, _c, _d;
|
|
1871
|
+
const body = typeof payload === "object" && payload !== null ? payload : {};
|
|
1872
|
+
const details = typeof body.details === "object" && body.details !== null ? body.details : {};
|
|
1873
|
+
const detail = typeof body.error === "string" ? body.error : fallbackDetail;
|
|
1874
|
+
return new BudgetExhaustedError(vendorLabel, (_a = numberOrUndefined(body.budgetUsd)) !== null && _a !== void 0 ? _a : numberOrUndefined(details.budgetUsd), (_b = numberOrUndefined(body.spentUsd)) !== null && _b !== void 0 ? _b : numberOrUndefined(details.spentUsd), detail, {
|
|
1875
|
+
otherVendorAvailable: (_c = booleanOrUndefined(body.otherVendorAvailable)) !== null && _c !== void 0 ? _c : booleanOrUndefined(details.otherVendorAvailable),
|
|
1876
|
+
serverVendor: (_d = stringOrUndefined(body.vendor)) !== null && _d !== void 0 ? _d : stringOrUndefined(details.vendor)
|
|
1877
|
+
});
|
|
1878
|
+
}
|
|
1756
1879
|
|
|
1757
1880
|
// ../../foundation-ai/dist/esm/utils/abort-reason.js
|
|
1758
1881
|
function authoritativeAbortReason(error, timeoutSignal, callerSignal) {
|
|
@@ -1887,6 +2010,8 @@ var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
|
|
|
1887
2010
|
/input token count .* exceeds/i,
|
|
1888
2011
|
/maximum context length/i,
|
|
1889
2012
|
/context[_ ]length[_ ]exceeded/i,
|
|
2013
|
+
// OpenAI Responses: `Your input exceeds the context window of this model.`
|
|
2014
|
+
/exceeds the context window/i,
|
|
1890
2015
|
/too many (input )?tokens/i
|
|
1891
2016
|
]);
|
|
1892
2017
|
var TOKEN_FIGURES = /(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;
|
|
@@ -2005,6 +2130,94 @@ function readFramedBody(stream, onChunk, vendorLabel, stallTimeout) {
|
|
|
2005
2130
|
});
|
|
2006
2131
|
}
|
|
2007
2132
|
|
|
2133
|
+
// ../../foundation-ai/dist/esm/transports/provider-refused.js
|
|
2134
|
+
var PROVIDER_REFUSED_CODE = "PROVIDER_REFUSED";
|
|
2135
|
+
var DEFAULT_PROVIDER_REFUSED_MESSAGE = "AI requests are currently being refused by the provider. This isn't related to your account or your usage and needs no action from you \u2014 please contact your support team so it can be restored.";
|
|
2136
|
+
var ProviderRefusedError = class extends Error {
|
|
2137
|
+
constructor(vendorLabel, kind, upstreamStatus, upstreamType, detail) {
|
|
2138
|
+
super(`${vendorLabel} refused the request (${kind})` + (upstreamStatus != null ? ` \u2014 HTTP ${upstreamStatus}` : "") + (upstreamType ? ` ${upstreamType}` : "") + (detail ? `: ${detail}` : "") + ". Retrying will not clear this \u2014 the provider account must be fixed.");
|
|
2139
|
+
this.vendorLabel = vendorLabel;
|
|
2140
|
+
this.kind = kind;
|
|
2141
|
+
this.upstreamStatus = upstreamStatus;
|
|
2142
|
+
this.upstreamType = upstreamType;
|
|
2143
|
+
this.detail = detail;
|
|
2144
|
+
this.name = "ProviderRefusedError";
|
|
2145
|
+
}
|
|
2146
|
+
};
|
|
2147
|
+
var ANTHROPIC_SPEND_PHRASES = Object.freeze([
|
|
2148
|
+
/credit balance/i,
|
|
2149
|
+
/usage limit/i,
|
|
2150
|
+
/spend limit/i,
|
|
2151
|
+
/insufficient (credit|funds|balance)/i
|
|
2152
|
+
]);
|
|
2153
|
+
var ANTHROPIC_AUTH_TYPES = Object.freeze([
|
|
2154
|
+
"authentication_error",
|
|
2155
|
+
"permission_error"
|
|
2156
|
+
]);
|
|
2157
|
+
function anthropicErrorBody(payload) {
|
|
2158
|
+
var _a;
|
|
2159
|
+
const outer = typeof payload === "object" && payload !== null ? payload : {};
|
|
2160
|
+
for (const candidate of [
|
|
2161
|
+
outer.error,
|
|
2162
|
+
(_a = outer.details) === null || _a === void 0 ? void 0 : _a.error
|
|
2163
|
+
]) {
|
|
2164
|
+
if (typeof candidate === "object" && candidate !== null) {
|
|
2165
|
+
const { type, message } = candidate;
|
|
2166
|
+
return {
|
|
2167
|
+
type: typeof type === "string" ? type : void 0,
|
|
2168
|
+
message: typeof message === "string" ? message : void 0
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
return void 0;
|
|
2173
|
+
}
|
|
2174
|
+
function statedKind(payload) {
|
|
2175
|
+
const outer = typeof payload === "object" && payload !== null ? payload : {};
|
|
2176
|
+
const nested = typeof outer.details === "object" && outer.details !== null ? outer.details : {};
|
|
2177
|
+
for (const candidate of [outer.kind, nested.kind]) {
|
|
2178
|
+
if (candidate === "auth" || candidate === "spend")
|
|
2179
|
+
return candidate;
|
|
2180
|
+
}
|
|
2181
|
+
return void 0;
|
|
2182
|
+
}
|
|
2183
|
+
function kindFromEnvelopeType(payload) {
|
|
2184
|
+
const body = anthropicErrorBody(payload);
|
|
2185
|
+
if (!(body === null || body === void 0 ? void 0 : body.type))
|
|
2186
|
+
return void 0;
|
|
2187
|
+
if (ANTHROPIC_AUTH_TYPES.includes(body.type))
|
|
2188
|
+
return "auth";
|
|
2189
|
+
if (body.type === "billing_error")
|
|
2190
|
+
return "spend";
|
|
2191
|
+
return void 0;
|
|
2192
|
+
}
|
|
2193
|
+
function providerRefusalOf(vendor, code, payload) {
|
|
2194
|
+
var _a, _b;
|
|
2195
|
+
if (code === PROVIDER_REFUSED_CODE) {
|
|
2196
|
+
return (_b = (_a = statedKind(payload)) !== null && _a !== void 0 ? _a : kindFromEnvelopeType(payload)) !== null && _b !== void 0 ? _b : "spend";
|
|
2197
|
+
}
|
|
2198
|
+
if (vendor !== "anthropic")
|
|
2199
|
+
return void 0;
|
|
2200
|
+
const structural = kindFromEnvelopeType(payload);
|
|
2201
|
+
if (structural)
|
|
2202
|
+
return structural;
|
|
2203
|
+
const body = anthropicErrorBody(payload);
|
|
2204
|
+
if ((body === null || body === void 0 ? void 0 : body.type) === "invalid_request_error" && body.message) {
|
|
2205
|
+
const message = body.message;
|
|
2206
|
+
if (ANTHROPIC_SPEND_PHRASES.some((phrase) => phrase.test(message)))
|
|
2207
|
+
return "spend";
|
|
2208
|
+
}
|
|
2209
|
+
return void 0;
|
|
2210
|
+
}
|
|
2211
|
+
function providerRefusedFrom(vendorLabel, kind, upstreamStatus, payload, fallbackDetail) {
|
|
2212
|
+
var _a;
|
|
2213
|
+
const body = anthropicErrorBody(payload);
|
|
2214
|
+
return new ProviderRefusedError(vendorLabel, kind, upstreamStatus, body === null || body === void 0 ? void 0 : body.type, (_a = body === null || body === void 0 ? void 0 : body.message) !== null && _a !== void 0 ? _a : fallbackDetail);
|
|
2215
|
+
}
|
|
2216
|
+
function vendorOfTransportLabel(vendorLabel) {
|
|
2217
|
+
const entry = Object.entries(VENDOR_LABELS).find(([, label]) => label === vendorLabel);
|
|
2218
|
+
return entry === null || entry === void 0 ? void 0 : entry[0];
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2008
2221
|
// ../../foundation-ai/dist/esm/transports/retry-hints.js
|
|
2009
2222
|
var MAX_SERVER_REQUESTED_BACKOFF_MS = 6e4;
|
|
2010
2223
|
var MAX_TOTAL_SERVER_REQUESTED_BACKOFF_MS = 12e4;
|
|
@@ -2217,38 +2430,60 @@ function toAnthropicToolChoice(choice) {
|
|
|
2217
2430
|
}
|
|
2218
2431
|
var ANTHROPIC_CONTEXT_LIMITS = {
|
|
2219
2432
|
"claude-fable-5": 1e6,
|
|
2433
|
+
"claude-opus-5-5": 1e6,
|
|
2220
2434
|
"claude-opus-4-8": 1e6,
|
|
2221
2435
|
"claude-opus-4-7": 1e6,
|
|
2436
|
+
"claude-sonnet-5-5": 1e6,
|
|
2222
2437
|
"claude-sonnet-5": 1e6,
|
|
2223
2438
|
"claude-sonnet-4-6": 1e6,
|
|
2439
|
+
"claude-haiku-5-5": 1e6,
|
|
2224
2440
|
"claude-haiku-4-5-20251001": 2e5
|
|
2225
2441
|
};
|
|
2226
2442
|
var STRUCTURED_OUTPUT_TOOL_NAME = "emit_structured_response";
|
|
2227
2443
|
var SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-06-01";
|
|
2444
|
+
var THINKING_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
|
|
2228
2445
|
function assertSupportedAnthropicModel(model) {
|
|
2229
2446
|
if (!SUPPORTED_ANTHROPIC_MODEL_IDS.includes(model)) {
|
|
2230
2447
|
throw new Error(`AnthropicTransport: unsupported model "${model}". Use one of: ${SUPPORTED_ANTHROPIC_MODEL_IDS.join(", ")}.`);
|
|
2231
2448
|
}
|
|
2232
2449
|
}
|
|
2450
|
+
function isClaude55(model) {
|
|
2451
|
+
return model === "claude-opus-5-5" || model === "claude-sonnet-5-5" || model === "claude-haiku-5-5";
|
|
2452
|
+
}
|
|
2233
2453
|
function rejectsSamplingParams(model) {
|
|
2234
|
-
return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-opus-4-7" || model === "claude-sonnet-5";
|
|
2454
|
+
return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-opus-4-7" || model === "claude-sonnet-5" || isClaude55(model);
|
|
2455
|
+
}
|
|
2456
|
+
function supportsForcedToolChoice(model) {
|
|
2457
|
+
return model !== "claude-opus-5-5" && model !== "claude-sonnet-5-5";
|
|
2235
2458
|
}
|
|
2236
2459
|
function supportsNativeStructuredOutput(model) {
|
|
2237
|
-
return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5" || model === "claude-haiku-4-5-20251001";
|
|
2460
|
+
return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5" || model === "claude-haiku-4-5-20251001" || isClaude55(model);
|
|
2238
2461
|
}
|
|
2239
2462
|
function supportsAdaptiveThinking(model) {
|
|
2240
2463
|
return model !== "claude-haiku-4-5-20251001";
|
|
2241
2464
|
}
|
|
2242
2465
|
function thinkingIsMandatory(model) {
|
|
2243
|
-
return model === "claude-fable-5";
|
|
2466
|
+
return model === "claude-fable-5" || model === "claude-opus-5-5";
|
|
2467
|
+
}
|
|
2468
|
+
function defaultsToThinking(model) {
|
|
2469
|
+
return model === "claude-sonnet-5" || model === "claude-sonnet-5-5" || model === "claude-haiku-5-5" || thinkingIsMandatory(model);
|
|
2470
|
+
}
|
|
2471
|
+
function thinkingOff(model) {
|
|
2472
|
+
return model === "claude-sonnet-5-5" ? { type: "between_tools" } : { type: "disabled" };
|
|
2473
|
+
}
|
|
2474
|
+
var POLICY_EFFORT = {
|
|
2475
|
+
"claude-opus-5-5": { auto: "high", off: "low" }
|
|
2476
|
+
};
|
|
2477
|
+
function sendsBlockBinding(model) {
|
|
2478
|
+
return isClaude55(model);
|
|
2244
2479
|
}
|
|
2245
2480
|
function anthropicThinking(model, policy) {
|
|
2246
|
-
const
|
|
2481
|
+
const thinksByDefault = defaultsToThinking(model);
|
|
2247
2482
|
const adaptive = { type: "adaptive", display: "summarized" };
|
|
2248
2483
|
if (policy === "off") {
|
|
2249
2484
|
if (thinkingIsMandatory(model))
|
|
2250
2485
|
return adaptive;
|
|
2251
|
-
return
|
|
2486
|
+
return thinksByDefault ? thinkingOff(model) : void 0;
|
|
2252
2487
|
}
|
|
2253
2488
|
if (policy === "auto") {
|
|
2254
2489
|
return supportsAdaptiveThinking(model) ? adaptive : void 0;
|
|
@@ -2256,10 +2491,10 @@ function anthropicThinking(model, policy) {
|
|
|
2256
2491
|
if (policy !== void 0) {
|
|
2257
2492
|
return supportsAdaptiveThinking(model) ? adaptive : void 0;
|
|
2258
2493
|
}
|
|
2259
|
-
return
|
|
2494
|
+
return thinksByDefault ? adaptive : void 0;
|
|
2260
2495
|
}
|
|
2261
2496
|
function supportsEffort(model) {
|
|
2262
|
-
return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5";
|
|
2497
|
+
return model === "claude-fable-5" || model === "claude-opus-4-8" || model === "claude-sonnet-5" || isClaude55(model);
|
|
2263
2498
|
}
|
|
2264
2499
|
var ANTHROPIC_EFFORT = {
|
|
2265
2500
|
minimal: "low",
|
|
@@ -2269,8 +2504,11 @@ var ANTHROPIC_EFFORT = {
|
|
|
2269
2504
|
max: "max"
|
|
2270
2505
|
};
|
|
2271
2506
|
function anthropicEffort(model, policy) {
|
|
2272
|
-
|
|
2507
|
+
var _a;
|
|
2508
|
+
if (policy === void 0)
|
|
2273
2509
|
return void 0;
|
|
2510
|
+
if (policy === "auto" || policy === "off")
|
|
2511
|
+
return (_a = POLICY_EFFORT[model]) === null || _a === void 0 ? void 0 : _a[policy];
|
|
2274
2512
|
if (!supportsEffort(model) || !supportsAdaptiveThinking(model))
|
|
2275
2513
|
return void 0;
|
|
2276
2514
|
return ANTHROPIC_EFFORT[policy];
|
|
@@ -2314,11 +2552,14 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2314
2552
|
* outcome the type's own docs promise callers never happens.
|
|
2315
2553
|
*/
|
|
2316
2554
|
clampWarning(policy) {
|
|
2555
|
+
var _a, _b;
|
|
2317
2556
|
switch (policy) {
|
|
2318
2557
|
case void 0:
|
|
2319
2558
|
return void 0;
|
|
2320
2559
|
case "off":
|
|
2321
|
-
|
|
2560
|
+
if (!thinkingIsMandatory(this.model))
|
|
2561
|
+
return void 0;
|
|
2562
|
+
return ((_a = POLICY_EFFORT[this.model]) === null || _a === void 0 ? void 0 : _a.off) ? `AnthropicTransport: thinkingPolicy 'off' approximated \u2014 ${this.model} always thinks and rejects an explicit disable, so the turn runs at effort '${(_b = POLICY_EFFORT[this.model]) === null || _b === void 0 ? void 0 : _b.off}' instead. It may still think a little, billed as output.` : `AnthropicTransport: thinkingPolicy 'off' ignored \u2014 ${this.model} always thinks and rejects an explicit disable. Reasoning tokens are still billed as output; switch model if you need them gone.`;
|
|
2322
2563
|
case "auto":
|
|
2323
2564
|
return supportsAdaptiveThinking(this.model) ? void 0 : `AnthropicTransport: thinkingPolicy 'auto' ignored \u2014 ${this.model} does not support adaptive thinking, so this turn runs without reasoning. Use a Sonnet or Opus tier if the agent needs it.`;
|
|
2324
2565
|
case "minimal":
|
|
@@ -2327,7 +2568,7 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2327
2568
|
case "high":
|
|
2328
2569
|
case "max":
|
|
2329
2570
|
if (!supportsAdaptiveThinking(this.model) || !supportsEffort(this.model)) {
|
|
2330
|
-
return `AnthropicTransport: thinkingPolicy '${policy}' ignored \u2014 ${this.model} predates output_config.effort, so this turn runs at its default posture. Use Opus 4.8, Sonnet 5, or Fable 5 to set reasoning depth.`;
|
|
2571
|
+
return `AnthropicTransport: thinkingPolicy '${policy}' ignored \u2014 ${this.model} predates output_config.effort, so this turn runs at its default posture. Use Opus 4.8 or later, Sonnet 5 or later, Haiku 5.5, or Fable 5 to set reasoning depth.`;
|
|
2331
2572
|
}
|
|
2332
2573
|
return void 0;
|
|
2333
2574
|
default: {
|
|
@@ -2337,10 +2578,11 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2337
2578
|
}
|
|
2338
2579
|
}
|
|
2339
2580
|
constructor(config = {}) {
|
|
2340
|
-
var _a, _b, _c, _d;
|
|
2581
|
+
var _a, _b, _c, _d, _e;
|
|
2341
2582
|
this.lifetimeCostUsd = 0;
|
|
2342
2583
|
this.lifetimeSavingsUsd = 0;
|
|
2343
2584
|
this.warnedThinkingClamped = false;
|
|
2585
|
+
this.warnedToolChoiceDowngraded = false;
|
|
2344
2586
|
this.warnedUnknownServingModels = /* @__PURE__ */ new Set();
|
|
2345
2587
|
const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL;
|
|
2346
2588
|
assertSupportedAnthropicModel(model);
|
|
@@ -2351,6 +2593,10 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2351
2593
|
logger.warn("AnthropicTransport: using claude-sonnet-4-6 \u2014 higher cost than Haiku; use for stronger reasoning or agent tasks.");
|
|
2352
2594
|
} else if (model === "claude-opus-4-7" || model === "claude-opus-4-8") {
|
|
2353
2595
|
logger.warn(`AnthropicTransport: using ${model} \u2014 significantly higher cost; reserve for tasks where Sonnet reliability is insufficient.`);
|
|
2596
|
+
} else if (model === "claude-opus-5-5") {
|
|
2597
|
+
logger.warn("AnthropicTransport: using claude-opus-5-5 \u2014 Opus tier ($4 / $20 per MTok) with thinking always on (effort defaults to medium). Reserve for tasks where Sonnet reliability is insufficient.");
|
|
2598
|
+
} else if (model === "claude-sonnet-5-5") {
|
|
2599
|
+
logger.warn("AnthropicTransport: using claude-sonnet-5-5 \u2014 standard Sonnet tier ($2 / $10 per MTok), higher cost than Haiku, and adaptive thinking runs by default so reasoning tokens add to output cost. Use for stronger reasoning or agent tasks.");
|
|
2354
2600
|
} else if (model === "claude-fable-5") {
|
|
2355
2601
|
logger.warn(`AnthropicTransport: using claude-fable-5 \u2014 Anthropic's most capable model, priced above Opus tier ($10 / $50 per MTok) with thinking always on. Reserve for the hardest reasoning/long-horizon work. Requires \u226530-day data retention (unavailable under ZDR) and may return stop_reason "refusal"; pair with an Opus 4.8 fallback.`);
|
|
2356
2602
|
}
|
|
@@ -2359,6 +2605,7 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2359
2605
|
this.apiKey = config.apiKey;
|
|
2360
2606
|
this.serverEndpoint = config.serverEndpoint;
|
|
2361
2607
|
this.maxTokens = (_d = config.maxTokens) !== null && _d !== void 0 ? _d : DEFAULT_MAX_TOKENS;
|
|
2608
|
+
this.thinkingBlockBinding = (_e = config.thinkingBlockBinding) !== null && _e !== void 0 ? _e : "drop_block";
|
|
2362
2609
|
}
|
|
2363
2610
|
getConfig() {
|
|
2364
2611
|
return {
|
|
@@ -2398,6 +2645,9 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2398
2645
|
if (useNative) {
|
|
2399
2646
|
body.output_config = Object.assign(Object.assign({}, body.output_config), { format: { type: "json_schema", schema: responseSchema } });
|
|
2400
2647
|
} else if (useForcedTool) {
|
|
2648
|
+
if (!supportsForcedToolChoice(this.model)) {
|
|
2649
|
+
throw new Error(`AnthropicTransport: ${this.model} rejects forced tool_choice and must be listed in supportsNativeStructuredOutput.`);
|
|
2650
|
+
}
|
|
2401
2651
|
body.tools = [
|
|
2402
2652
|
{
|
|
2403
2653
|
name: STRUCTURED_OUTPUT_TOOL_NAME,
|
|
@@ -2407,8 +2657,9 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2407
2657
|
];
|
|
2408
2658
|
body.tool_choice = { type: "tool", name: STRUCTURED_OUTPUT_TOOL_NAME };
|
|
2409
2659
|
}
|
|
2410
|
-
if (this.model
|
|
2411
|
-
body.thinking =
|
|
2660
|
+
if (defaultsToThinking(this.model) && !thinkingIsMandatory(this.model)) {
|
|
2661
|
+
body.thinking = thinkingOff(this.model);
|
|
2662
|
+
}
|
|
2412
2663
|
const response = yield this.post(body);
|
|
2413
2664
|
if (useForcedTool) {
|
|
2414
2665
|
const toolUse = ((_a = response.content) !== null && _a !== void 0 ? _a : []).find((b) => b.type === "tool_use" && b.name === STRUCTURED_OUTPUT_TOOL_NAME);
|
|
@@ -2420,7 +2671,7 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2420
2671
|
// ── ChatTransport (multi-turn chat) ────────────────────────────────────
|
|
2421
2672
|
sendChatMessage(history, userMessage, options) {
|
|
2422
2673
|
return __awaiter(this, void 0, void 0, function* () {
|
|
2423
|
-
var _a, _b, _c, _d, _e;
|
|
2674
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2424
2675
|
const reachableModels = /* @__PURE__ */ new Set([
|
|
2425
2676
|
this.model,
|
|
2426
2677
|
...((_a = options === null || options === void 0 ? void 0 : options.fallbacks) !== null && _a !== void 0 ? _a : []).map((f) => f.model)
|
|
@@ -2437,15 +2688,11 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2437
2688
|
if ((_c = options === null || options === void 0 ? void 0 : options.tools) === null || _c === void 0 ? void 0 : _c.length) {
|
|
2438
2689
|
body.tools = options.tools.map((t) => Object.assign({ name: t.name, description: t.description, input_schema: t.enforceSchema ? enforceAnthropicToolSchema(t.parameters, t.name) : t.parameters }, t.enforceSchema ? { strict: true } : {}));
|
|
2439
2690
|
}
|
|
2440
|
-
|
|
2441
|
-
const toolChoice = toAnthropicToolChoice(options === null || options === void 0 ? void 0 : options.toolChoice);
|
|
2442
|
-
if (toolChoice)
|
|
2443
|
-
body.tool_choice = toolChoice;
|
|
2444
|
-
}
|
|
2691
|
+
const forcedToolNote = ((_d = body.tools) === null || _d === void 0 ? void 0 : _d.length) ? this.applyToolChoice(body, options === null || options === void 0 ? void 0 : options.toolChoice, (_e = options === null || options === void 0 ? void 0 : options.tools) !== null && _e !== void 0 ? _e : []) : void 0;
|
|
2445
2692
|
this.warnIfThinkingUnclampable(options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
2446
2693
|
const thinking = anthropicThinking(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
2447
2694
|
if (thinking)
|
|
2448
|
-
body.thinking = thinking;
|
|
2695
|
+
body.thinking = this.withBlockBinding(thinking);
|
|
2449
2696
|
const effort = anthropicEffort(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
2450
2697
|
if (effort)
|
|
2451
2698
|
body.output_config = Object.assign(Object.assign({}, body.output_config), { effort });
|
|
@@ -2459,19 +2706,83 @@ var AnthropicTransport = class _AnthropicTransport {
|
|
|
2459
2706
|
if ((options === null || options === void 0 ? void 0 : options.responseSchema) && supportsNativeStructuredOutput(this.model)) {
|
|
2460
2707
|
body.output_config = Object.assign(Object.assign({}, body.output_config), { format: { type: "json_schema", schema: options.responseSchema } });
|
|
2461
2708
|
}
|
|
2462
|
-
if ((
|
|
2709
|
+
if ((_f = options === null || options === void 0 ? void 0 : options.fallbacks) === null || _f === void 0 ? void 0 : _f.length) {
|
|
2463
2710
|
body.fallbacks = options.fallbacks.map((f) => f.maxTokens != null ? { model: f.model, max_tokens: f.maxTokens } : { model: f.model });
|
|
2464
2711
|
}
|
|
2465
2712
|
if (options === null || options === void 0 ? void 0 : options.cachePolicy) {
|
|
2466
2713
|
this.applyCacheControl(body, options.cachePolicy);
|
|
2467
2714
|
}
|
|
2468
|
-
|
|
2469
|
-
|
|
2715
|
+
const tail = [options === null || options === void 0 ? void 0 : options.tailContext, forcedToolNote].filter(Boolean).join("\n\n");
|
|
2716
|
+
if (tail) {
|
|
2717
|
+
this.appendTailContext(body, tail);
|
|
2470
2718
|
}
|
|
2471
2719
|
const response = yield this.post(body, options === null || options === void 0 ? void 0 : options.signal);
|
|
2472
|
-
|
|
2720
|
+
const message = this.fromAnthropicResponse(response, body.max_tokens);
|
|
2721
|
+
if (forcedToolNote && message.responseMeta) {
|
|
2722
|
+
message.responseMeta.toolChoiceDowngraded = true;
|
|
2723
|
+
}
|
|
2724
|
+
return message;
|
|
2473
2725
|
});
|
|
2474
2726
|
}
|
|
2727
|
+
/**
|
|
2728
|
+
* Set `tool_choice` from the caller's {@link ChatToolChoice}. `'required'`/`{ tool }` force a
|
|
2729
|
+
* tool call so a turn can only end via one (e.g. a sub-agent's completion tool); on a model that
|
|
2730
|
+
* rejects forcing they are downgraded (see `downgradeForcedToolChoice`), and the instruction
|
|
2731
|
+
* that replaces them is returned for the tail.
|
|
2732
|
+
*/
|
|
2733
|
+
applyToolChoice(body, choice, tools) {
|
|
2734
|
+
const toolChoice = toAnthropicToolChoice(choice);
|
|
2735
|
+
if (!toolChoice)
|
|
2736
|
+
return void 0;
|
|
2737
|
+
const forced = toolChoice.type === "any" || toolChoice.type === "tool";
|
|
2738
|
+
if (forced && !supportsForcedToolChoice(this.model)) {
|
|
2739
|
+
return this.downgradeForcedToolChoice(body, toolChoice, tools);
|
|
2740
|
+
}
|
|
2741
|
+
body.tool_choice = toolChoice;
|
|
2742
|
+
return void 0;
|
|
2743
|
+
}
|
|
2744
|
+
/**
|
|
2745
|
+
* Preserved thinking (5.5 family): say what a changed history does to replayed thinking, rather
|
|
2746
|
+
* than inheriting the account default (a 400 on accounts created on or after 2026-08-31).
|
|
2747
|
+
* Adaptive only — `between_tools` and `disabled` reject the field — and a fresh object, so the
|
|
2748
|
+
* shared `adaptive` constant in `anthropicThinking` is never mutated.
|
|
2749
|
+
*/
|
|
2750
|
+
withBlockBinding(thinking) {
|
|
2751
|
+
if (thinking.type !== "adaptive" || !sendsBlockBinding(this.model) || this.thinkingBlockBinding === "omit") {
|
|
2752
|
+
return thinking;
|
|
2753
|
+
}
|
|
2754
|
+
return Object.assign(Object.assign({}, thinking), { block_binding: { prefix_mismatch_behavior: this.thinkingBlockBinding } });
|
|
2755
|
+
}
|
|
2756
|
+
/**
|
|
2757
|
+
* Stand-in for a forced tool call on a model that rejects `tool_choice` `any`/`tool` with a 400
|
|
2758
|
+
* (Opus 5.5, Sonnet 5.5). The request goes out with `tool_choice` omitted (`auto`), and:
|
|
2759
|
+
*
|
|
2760
|
+
* - for a NAMED tool, that tool's schema is enforced (`strict: true`), so a call that does
|
|
2761
|
+
* happen has valid arguments — the half of forcing that `auto` can still guarantee. Not done
|
|
2762
|
+
* for `'required'`: enforcing every tool in a large surface can exceed the provider's
|
|
2763
|
+
* per-request compilation limits, and a tool the caller enforced already carries it;
|
|
2764
|
+
* - an instruction naming the tool is returned for the caller to append to the tail.
|
|
2765
|
+
*
|
|
2766
|
+
* `auto` lets the model answer in text instead, so the caller is told: a one-time warning here,
|
|
2767
|
+
* and `responseMeta.toolChoiceDowngraded` on every affected response, which a driver uses to
|
|
2768
|
+
* nudge and retry once when no tool was called.
|
|
2769
|
+
*/
|
|
2770
|
+
downgradeForcedToolChoice(body, toolChoice, tools) {
|
|
2771
|
+
var _a, _b;
|
|
2772
|
+
if (!this.warnedToolChoiceDowngraded) {
|
|
2773
|
+
this.warnedToolChoiceDowngraded = true;
|
|
2774
|
+
logger.warn(`AnthropicTransport: ${this.model} rejects a forced tool_choice; sending 'auto' with an instruction to call the tool instead. A reply may still come back without a tool call \u2014 check responseMeta.toolChoiceDowngraded.`);
|
|
2775
|
+
}
|
|
2776
|
+
if (toolChoice.type === "tool" && toolChoice.name) {
|
|
2777
|
+
const index = (_b = (_a = body.tools) === null || _a === void 0 ? void 0 : _a.findIndex((t) => t.name === toolChoice.name)) !== null && _b !== void 0 ? _b : -1;
|
|
2778
|
+
const source = tools.find((t) => t.name === toolChoice.name);
|
|
2779
|
+
if (index >= 0 && source && body.tools && !body.tools[index].strict) {
|
|
2780
|
+
body.tools[index] = Object.assign(Object.assign({}, body.tools[index]), { input_schema: enforceAnthropicToolSchema(source.parameters, source.name), strict: true });
|
|
2781
|
+
}
|
|
2782
|
+
return `<system-reminder>Respond to this turn by calling the \`${toolChoice.name}\` tool. Do not reply with text alone.</system-reminder>`;
|
|
2783
|
+
}
|
|
2784
|
+
return "<system-reminder>Respond to this turn by calling one of your tools. Do not reply with text alone.</system-reminder>";
|
|
2785
|
+
}
|
|
2475
2786
|
/**
|
|
2476
2787
|
* Place prompt-cache breakpoints on the outgoing request per the resolved {@link CachePolicy}.
|
|
2477
2788
|
* A breakpoint is `cache_control: {type:'ephemeral'}` on a content block / tool / system block;
|
|
@@ -2771,7 +3082,7 @@ ${att.content}` });
|
|
|
2771
3082
|
return this.logTokenUsage(model, (_e = usage.input_tokens) !== null && _e !== void 0 ? _e : 0, (_f = usage.output_tokens) !== null && _f !== void 0 ? _f : 0, cacheRead, cacheCreation, cacheCreation1h);
|
|
2772
3083
|
}
|
|
2773
3084
|
fromAnthropicResponse(response, effectiveMaxTokens = this.maxTokens) {
|
|
2774
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
3085
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
2775
3086
|
let inputTokens;
|
|
2776
3087
|
let outputTokens;
|
|
2777
3088
|
let cacheReadTokens;
|
|
@@ -2871,6 +3182,16 @@ ${att.content}` });
|
|
|
2871
3182
|
};
|
|
2872
3183
|
if (response.stop_reason)
|
|
2873
3184
|
responseMeta.finishReason = response.stop_reason;
|
|
3185
|
+
if ((_h = response.input_transformations) === null || _h === void 0 ? void 0 : _h.length) {
|
|
3186
|
+
responseMeta.inputTransformations = response.input_transformations.map((t) => Object.assign(Object.assign({ type: t.type }, t.path != null ? { path: t.path } : {}), t.reason != null ? { reason: t.reason } : {}));
|
|
3187
|
+
const dropped = response.input_transformations.filter((t) => t.type === "thinking_dropped");
|
|
3188
|
+
if (dropped.length) {
|
|
3189
|
+
logger.debug(`AnthropicTransport: ${dropped.length} thinking block(s) dropped by ${(_j = response.model) !== null && _j !== void 0 ? _j : this.model}: ${dropped.map((t) => {
|
|
3190
|
+
var _a2, _b2;
|
|
3191
|
+
return `${(_a2 = t.path) !== null && _a2 !== void 0 ? _a2 : "?"} (${(_b2 = t.reason) !== null && _b2 !== void 0 ? _b2 : "unknown"})`;
|
|
3192
|
+
}).join(", ")}`);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
2874
3195
|
base.responseMeta = responseMeta;
|
|
2875
3196
|
return base;
|
|
2876
3197
|
}
|
|
@@ -2902,9 +3223,13 @@ ${att.content}` });
|
|
|
2902
3223
|
}
|
|
2903
3224
|
post(body, signal) {
|
|
2904
3225
|
return __awaiter(this, void 0, void 0, function* () {
|
|
2905
|
-
var _a;
|
|
3226
|
+
var _a, _b;
|
|
2906
3227
|
const { url, headers, credentials } = this.buildEndpoint();
|
|
2907
|
-
const
|
|
3228
|
+
const betas = [
|
|
3229
|
+
((_a = body.fallbacks) === null || _a === void 0 ? void 0 : _a.length) ? SERVER_SIDE_FALLBACK_BETA : void 0,
|
|
3230
|
+
((_b = body.thinking) === null || _b === void 0 ? void 0 : _b.type) === "adaptive" && body.thinking.block_binding ? THINKING_BINDING_CONTROLS_BETA : void 0
|
|
3231
|
+
].filter((b) => Boolean(b));
|
|
3232
|
+
const requestHeaders = betas.length ? Object.assign(Object.assign({}, headers), { "anthropic-beta": [headers["anthropic-beta"], ...betas].filter(Boolean).join(",") }) : headers;
|
|
2908
3233
|
return yield postWithRetry({
|
|
2909
3234
|
url,
|
|
2910
3235
|
headers: requestHeaders,
|
|
@@ -3748,6 +4073,605 @@ GeminiTransport.RETRYABLE_STATUSES = [
|
|
|
3748
4073
|
];
|
|
3749
4074
|
GeminiTransport.BACKOFF_BASE_MS = 1e3;
|
|
3750
4075
|
|
|
4076
|
+
// ../../foundation-ai/dist/esm/transports/openai-transport.js
|
|
4077
|
+
var OPENAI_DIRECT_URL = "https://api.openai.com/v1/responses";
|
|
4078
|
+
var DEFAULT_MODEL3 = "gpt-6-luna";
|
|
4079
|
+
var DEFAULT_TIMEOUT3 = 3e5;
|
|
4080
|
+
var DEFAULT_STALL_TIMEOUT3 = 3e4;
|
|
4081
|
+
var OPENAI_CONTEXT_LIMITS = {
|
|
4082
|
+
"gpt-6-astra": 922e3,
|
|
4083
|
+
"gpt-6.1-sol": 105e4,
|
|
4084
|
+
"gpt-6.1-terra": 105e4,
|
|
4085
|
+
"gpt-6-sol": 105e4,
|
|
4086
|
+
"gpt-6-luna": 105e4
|
|
4087
|
+
};
|
|
4088
|
+
var OPENAI_DEFAULT_TEMPERATURE = 1;
|
|
4089
|
+
var OPENAI_MAX_TEMPERATURE = 2;
|
|
4090
|
+
var OPENAI_EFFORT_NONE_TIERS = ["gpt-6.1-terra", "gpt-6-luna"];
|
|
4091
|
+
var OPENAI_EFFORT = {
|
|
4092
|
+
minimal: "low",
|
|
4093
|
+
low: "low",
|
|
4094
|
+
medium: "medium",
|
|
4095
|
+
high: "high",
|
|
4096
|
+
max: "max"
|
|
4097
|
+
};
|
|
4098
|
+
function openaiEffortFor(model, policy) {
|
|
4099
|
+
if (policy === void 0 || policy === "auto")
|
|
4100
|
+
return void 0;
|
|
4101
|
+
if (policy === "off")
|
|
4102
|
+
return OPENAI_EFFORT_NONE_TIERS.includes(model) ? "none" : "low";
|
|
4103
|
+
return OPENAI_EFFORT[policy];
|
|
4104
|
+
}
|
|
4105
|
+
function toOpenAIToolChoice(choice) {
|
|
4106
|
+
if (!choice || choice === "auto")
|
|
4107
|
+
return void 0;
|
|
4108
|
+
if (choice === "required" || choice === "none")
|
|
4109
|
+
return choice;
|
|
4110
|
+
return { type: "function", name: choice.tool };
|
|
4111
|
+
}
|
|
4112
|
+
function toOpenAITool(tool) {
|
|
4113
|
+
const parameters = tool.enforceSchema ? enforceOpenAIToolSchema(tool.parameters, tool.name) : tool.parameters;
|
|
4114
|
+
return {
|
|
4115
|
+
type: "function",
|
|
4116
|
+
name: tool.name,
|
|
4117
|
+
description: tool.description,
|
|
4118
|
+
parameters,
|
|
4119
|
+
strict: !!tool.enforceSchema
|
|
4120
|
+
};
|
|
4121
|
+
}
|
|
4122
|
+
function assertSupportedOpenAIModel(model) {
|
|
4123
|
+
if (!SUPPORTED_OPENAI_MODEL_IDS.includes(model)) {
|
|
4124
|
+
throw new Error(`OpenAITransport: unsupported model "${model}". Use one of: ${SUPPORTED_OPENAI_MODEL_IDS.join(", ")}.`);
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
var OPENAI_MODEL_WARNINGS = {
|
|
4128
|
+
"gpt-6-astra": "OpenAITransport: using gpt-6-astra \u2014 flagship model at $10/$50 per MTok; reserve for tasks where the cheaper tiers are insufficient.",
|
|
4129
|
+
"gpt-6.1-sol": 'OpenAITransport: using gpt-6.1-sol \u2014 materially higher cost than terra/luna, and it cannot turn reasoning off (thinkingPolicy "off" runs at effort "low").',
|
|
4130
|
+
"gpt-6-sol": "OpenAITransport: using gpt-6-sol \u2014 superseded by gpt-6.1-sol at the same price, and it cannot turn reasoning off."
|
|
4131
|
+
};
|
|
4132
|
+
var OPENAI_PROVIDER_KEY = "openai";
|
|
4133
|
+
var CACHE_BREAKPOINT = Object.freeze({ mode: "explicit" });
|
|
4134
|
+
var MAX_HISTORY_BREAKPOINTS = 49;
|
|
4135
|
+
function collectOutput(output) {
|
|
4136
|
+
var _a, _b, _c, _d;
|
|
4137
|
+
const reasoning = [];
|
|
4138
|
+
const summaryParts = [];
|
|
4139
|
+
const textParts = [];
|
|
4140
|
+
const refusals = [];
|
|
4141
|
+
const toolCalls = [];
|
|
4142
|
+
let phase;
|
|
4143
|
+
for (const item of output) {
|
|
4144
|
+
if (item.type === "reasoning") {
|
|
4145
|
+
reasoning.push(item);
|
|
4146
|
+
for (const s of (_a = item.summary) !== null && _a !== void 0 ? _a : []) {
|
|
4147
|
+
if (s.text)
|
|
4148
|
+
summaryParts.push(s.text);
|
|
4149
|
+
}
|
|
4150
|
+
} else if (item.type === "message") {
|
|
4151
|
+
if (typeof item.phase === "string" && phase !== "final_answer")
|
|
4152
|
+
phase = item.phase;
|
|
4153
|
+
for (const part of (_b = item.content) !== null && _b !== void 0 ? _b : []) {
|
|
4154
|
+
if (part.type === "output_text" && typeof part.text === "string")
|
|
4155
|
+
textParts.push(part.text);
|
|
4156
|
+
if (part.type === "refusal" && typeof part.refusal === "string")
|
|
4157
|
+
refusals.push(part.refusal);
|
|
4158
|
+
}
|
|
4159
|
+
} else if (item.type === "function_call") {
|
|
4160
|
+
toolCalls.push({
|
|
4161
|
+
id: String((_d = (_c = item.call_id) !== null && _c !== void 0 ? _c : item.id) !== null && _d !== void 0 ? _d : crypto.randomUUID()),
|
|
4162
|
+
name: String(item.name),
|
|
4163
|
+
args: parseArguments(item.arguments)
|
|
4164
|
+
});
|
|
4165
|
+
}
|
|
4166
|
+
}
|
|
4167
|
+
return { reasoning, summaryParts, textParts, refusals, toolCalls, phase };
|
|
4168
|
+
}
|
|
4169
|
+
function imagePart(att) {
|
|
4170
|
+
const part = {
|
|
4171
|
+
type: "input_image",
|
|
4172
|
+
image_url: `data:${normalizeImageMime(att.mimeType)};base64,${stripImageDataUrl(att.data)}`
|
|
4173
|
+
};
|
|
4174
|
+
if (att.detail)
|
|
4175
|
+
part.detail = att.detail === "medium" ? "auto" : att.detail;
|
|
4176
|
+
return part;
|
|
4177
|
+
}
|
|
4178
|
+
function userContentParts(text, atts) {
|
|
4179
|
+
const parts = [];
|
|
4180
|
+
for (const att of atts) {
|
|
4181
|
+
if (att.kind === "image")
|
|
4182
|
+
parts.push(imagePart(att));
|
|
4183
|
+
}
|
|
4184
|
+
if (text)
|
|
4185
|
+
parts.push({ type: "input_text", text });
|
|
4186
|
+
for (const att of atts) {
|
|
4187
|
+
if (att.kind !== "image")
|
|
4188
|
+
parts.push({ type: "input_text", text: `[File: ${att.name}]
|
|
4189
|
+
${att.content}` });
|
|
4190
|
+
}
|
|
4191
|
+
return parts;
|
|
4192
|
+
}
|
|
4193
|
+
function turnStateOf(msg) {
|
|
4194
|
+
var _a, _b, _c, _d, _e;
|
|
4195
|
+
return (_b = (_a = msg.providerMetadata) === null || _a === void 0 ? void 0 : _a[OPENAI_PROVIDER_KEY]) !== null && _b !== void 0 ? _b : (_e = (_d = (_c = msg.toolCalls) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.providerMetadata) === null || _e === void 0 ? void 0 : _e[OPENAI_PROVIDER_KEY];
|
|
4196
|
+
}
|
|
4197
|
+
function replayableReasoning(item) {
|
|
4198
|
+
const { status: _status } = item, rest = __rest(item, ["status"]);
|
|
4199
|
+
return rest;
|
|
4200
|
+
}
|
|
4201
|
+
var OpenAITransport = class _OpenAITransport {
|
|
4202
|
+
constructor(config = {}) {
|
|
4203
|
+
var _a, _b, _c, _d;
|
|
4204
|
+
this.lifetimeCostUsd = 0;
|
|
4205
|
+
this.lifetimeSavingsUsd = 0;
|
|
4206
|
+
this.warnedThinkingClamped = /* @__PURE__ */ new Set();
|
|
4207
|
+
const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL3;
|
|
4208
|
+
assertSupportedOpenAIModel(model);
|
|
4209
|
+
this.model = model;
|
|
4210
|
+
const warning = OPENAI_MODEL_WARNINGS[model];
|
|
4211
|
+
if (warning) {
|
|
4212
|
+
logger.warn(warning);
|
|
4213
|
+
}
|
|
4214
|
+
this.timeout = (_b = config.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT3;
|
|
4215
|
+
this.stallTimeout = (_c = config.stallTimeout) !== null && _c !== void 0 ? _c : DEFAULT_STALL_TIMEOUT3;
|
|
4216
|
+
this.apiKey = config.apiKey;
|
|
4217
|
+
this.serverEndpoint = config.serverEndpoint;
|
|
4218
|
+
this.maxTokens = config.maxTokens;
|
|
4219
|
+
this.reasoningSummary = (_d = config.reasoningSummary) !== null && _d !== void 0 ? _d : "none";
|
|
4220
|
+
}
|
|
4221
|
+
getConfig() {
|
|
4222
|
+
return {
|
|
4223
|
+
provider: "openai",
|
|
4224
|
+
model: this.model,
|
|
4225
|
+
contextLimit: OPENAI_CONTEXT_LIMITS[this.model]
|
|
4226
|
+
};
|
|
4227
|
+
}
|
|
4228
|
+
getLifetimeCost() {
|
|
4229
|
+
return this.lifetimeCostUsd;
|
|
4230
|
+
}
|
|
4231
|
+
getLifetimeSavings() {
|
|
4232
|
+
return this.lifetimeSavingsUsd;
|
|
4233
|
+
}
|
|
4234
|
+
resetLifetimeCost() {
|
|
4235
|
+
this.lifetimeCostUsd = 0;
|
|
4236
|
+
this.lifetimeSavingsUsd = 0;
|
|
4237
|
+
}
|
|
4238
|
+
// ── AITransport (structured prompt) ────────────────────────────────────
|
|
4239
|
+
sendStructuredPrompt(options) {
|
|
4240
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4241
|
+
const { systemPrompt, userPrompt, responseSchema } = options;
|
|
4242
|
+
const message = yield this.sendChatMessage([], userPrompt, {
|
|
4243
|
+
systemPrompt,
|
|
4244
|
+
responseSchema
|
|
4245
|
+
});
|
|
4246
|
+
return message.content;
|
|
4247
|
+
});
|
|
4248
|
+
}
|
|
4249
|
+
// ── ChatTransport (multi-turn chat) ────────────────────────────────────
|
|
4250
|
+
sendChatMessage(history, userMessage, options) {
|
|
4251
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4252
|
+
const body = this.buildRequestBody(history, userMessage, options);
|
|
4253
|
+
const response = yield this.post(body, options === null || options === void 0 ? void 0 : options.signal);
|
|
4254
|
+
const message = this.fromResponse(response, body.max_output_tokens);
|
|
4255
|
+
this.restoreOptionalFields(message, options);
|
|
4256
|
+
return message;
|
|
4257
|
+
});
|
|
4258
|
+
}
|
|
4259
|
+
/** Undo strict mode's absent-becomes-null, in tool arguments and in a `responseSchema` answer. */
|
|
4260
|
+
restoreOptionalFields(message, options) {
|
|
4261
|
+
var _a;
|
|
4262
|
+
const pointersByTool = strictNullPointersByTool(options === null || options === void 0 ? void 0 : options.tools);
|
|
4263
|
+
for (const call of (_a = message.toolCalls) !== null && _a !== void 0 ? _a : []) {
|
|
4264
|
+
const pointers = pointersByTool.get(call.name);
|
|
4265
|
+
if (pointers)
|
|
4266
|
+
stripStrictNulls(call.args, pointers);
|
|
4267
|
+
}
|
|
4268
|
+
if (!(options === null || options === void 0 ? void 0 : options.responseSchema) || !message.content)
|
|
4269
|
+
return;
|
|
4270
|
+
const { madeNullable } = toOpenAIStrictSchema(options.responseSchema);
|
|
4271
|
+
if (!madeNullable.length)
|
|
4272
|
+
return;
|
|
4273
|
+
try {
|
|
4274
|
+
const parsed = JSON.parse(message.content);
|
|
4275
|
+
stripStrictNulls(parsed, madeNullable);
|
|
4276
|
+
message.content = JSON.stringify(parsed);
|
|
4277
|
+
} catch (_b) {
|
|
4278
|
+
}
|
|
4279
|
+
}
|
|
4280
|
+
/**
|
|
4281
|
+
* The Responses request body for a turn. Public for tests and for hosts that want to inspect the
|
|
4282
|
+
* exact wire shape; not part of the stable contract.
|
|
4283
|
+
*
|
|
4284
|
+
* @internal
|
|
4285
|
+
*/
|
|
4286
|
+
buildRequestBody(history, userMessage, options) {
|
|
4287
|
+
var _a, _b;
|
|
4288
|
+
const scope = (options === null || options === void 0 ? void 0 : options.cachePolicy) && options.cachePolicy.scope !== "default" ? options.cachePolicy.scope : void 0;
|
|
4289
|
+
const input = [];
|
|
4290
|
+
if (options === null || options === void 0 ? void 0 : options.systemPrompt) {
|
|
4291
|
+
const part = { type: "input_text", text: options.systemPrompt };
|
|
4292
|
+
if (scope)
|
|
4293
|
+
part.prompt_cache_breakpoint = CACHE_BREAKPOINT;
|
|
4294
|
+
input.push({ type: "message", role: "developer", content: [part] });
|
|
4295
|
+
}
|
|
4296
|
+
input.push(...this.toInputItems(history, userMessage, options === null || options === void 0 ? void 0 : options.attachments));
|
|
4297
|
+
if (scope === "history")
|
|
4298
|
+
this.markHistoryBreakpoints(input);
|
|
4299
|
+
if (options === null || options === void 0 ? void 0 : options.tailContext) {
|
|
4300
|
+
input.push({
|
|
4301
|
+
type: "message",
|
|
4302
|
+
role: "user",
|
|
4303
|
+
content: [{ type: "input_text", text: options.tailContext }]
|
|
4304
|
+
});
|
|
4305
|
+
}
|
|
4306
|
+
const body = {
|
|
4307
|
+
model: this.model,
|
|
4308
|
+
input,
|
|
4309
|
+
store: false,
|
|
4310
|
+
// Encrypted reasoning is what makes a stateless tool loop keep its chain of thought.
|
|
4311
|
+
include: ["reasoning.encrypted_content"]
|
|
4312
|
+
};
|
|
4313
|
+
if (scope) {
|
|
4314
|
+
body.prompt_cache_options = { mode: "explicit", ttl: "30m" };
|
|
4315
|
+
}
|
|
4316
|
+
if ((_a = options === null || options === void 0 ? void 0 : options.tools) === null || _a === void 0 ? void 0 : _a.length) {
|
|
4317
|
+
body.tools = options.tools.map(toOpenAITool);
|
|
4318
|
+
const toolChoice = toOpenAIToolChoice(options.toolChoice);
|
|
4319
|
+
if (toolChoice)
|
|
4320
|
+
body.tool_choice = toolChoice;
|
|
4321
|
+
}
|
|
4322
|
+
this.warnIfThinkingClamped(options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
4323
|
+
const effort = openaiEffortFor(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
4324
|
+
if (effort) {
|
|
4325
|
+
body.reasoning = effort === "none" || this.reasoningSummary === "none" ? { effort } : { effort, summary: this.reasoningSummary };
|
|
4326
|
+
} else if (this.reasoningSummary !== "none") {
|
|
4327
|
+
body.reasoning = { summary: this.reasoningSummary };
|
|
4328
|
+
}
|
|
4329
|
+
if ((options === null || options === void 0 ? void 0 : options.temperature) != null && effort === "none") {
|
|
4330
|
+
body.temperature = scaleTemperature(options.temperature, {
|
|
4331
|
+
defaultTemp: OPENAI_DEFAULT_TEMPERATURE,
|
|
4332
|
+
maxTemp: OPENAI_MAX_TEMPERATURE
|
|
4333
|
+
});
|
|
4334
|
+
}
|
|
4335
|
+
const maxTokens = (_b = options === null || options === void 0 ? void 0 : options.maxTokens) !== null && _b !== void 0 ? _b : this.maxTokens;
|
|
4336
|
+
if (maxTokens != null)
|
|
4337
|
+
body.max_output_tokens = maxTokens;
|
|
4338
|
+
if (options === null || options === void 0 ? void 0 : options.responseSchema) {
|
|
4339
|
+
body.text = {
|
|
4340
|
+
format: {
|
|
4341
|
+
type: "json_schema",
|
|
4342
|
+
name: "response",
|
|
4343
|
+
schema: toOpenAIStrictSchema(options.responseSchema).schema,
|
|
4344
|
+
strict: true
|
|
4345
|
+
}
|
|
4346
|
+
};
|
|
4347
|
+
}
|
|
4348
|
+
return body;
|
|
4349
|
+
}
|
|
4350
|
+
// ── Private helpers ────────────────────────────────────────────────────
|
|
4351
|
+
warnIfThinkingClamped(policy) {
|
|
4352
|
+
if (!policy || this.warnedThinkingClamped.has(policy))
|
|
4353
|
+
return;
|
|
4354
|
+
if (policy === "off" && !OPENAI_EFFORT_NONE_TIERS.includes(this.model)) {
|
|
4355
|
+
this.warnedThinkingClamped.add(policy);
|
|
4356
|
+
logger.warn(`OpenAITransport: thinkingPolicy 'off' sent as effort 'low' \u2014 ${this.model} does not accept effort 'none'. Reasoning tokens are billed as output; use gpt-6.1-terra or gpt-6-luna if you need them gone.`);
|
|
4357
|
+
} else if (policy === "minimal") {
|
|
4358
|
+
this.warnedThinkingClamped.add(policy);
|
|
4359
|
+
logger.warn(`OpenAITransport: thinkingPolicy 'minimal' sent as effort 'low' \u2014 OpenAI has no 'minimal' effort.`);
|
|
4360
|
+
}
|
|
4361
|
+
}
|
|
4362
|
+
toInputItems(history, userMessage, attachments) {
|
|
4363
|
+
var _a, _b, _c, _d, _e;
|
|
4364
|
+
const items = [];
|
|
4365
|
+
const replayedReasoning = /* @__PURE__ */ new Set();
|
|
4366
|
+
for (const msg of history) {
|
|
4367
|
+
if (msg.role === "system" || msg.role === "system-event" || msg.role === "synthetic-user" || msg.role === "compacted-summary" || msg.category === "reasoning" || msg.category === "narration" || // Driver-authored prose no model produced — see ChatMessage.excludeFromProvider.
|
|
4368
|
+
msg.excludeFromProvider || msg.thinking)
|
|
4369
|
+
continue;
|
|
4370
|
+
if (msg.toolResult) {
|
|
4371
|
+
items.push(this.toFunctionCallOutput(msg));
|
|
4372
|
+
continue;
|
|
4373
|
+
}
|
|
4374
|
+
if (msg.role === "user") {
|
|
4375
|
+
const content2 = userContentParts(msg.content, (_a = msg.attachments) !== null && _a !== void 0 ? _a : []);
|
|
4376
|
+
if (content2.length)
|
|
4377
|
+
items.push({ type: "message", role: "user", content: content2 });
|
|
4378
|
+
continue;
|
|
4379
|
+
}
|
|
4380
|
+
const state = turnStateOf(msg);
|
|
4381
|
+
if ((state === null || state === void 0 ? void 0 : state.model) === this.model) {
|
|
4382
|
+
for (const r of (_b = state.reasoning) !== null && _b !== void 0 ? _b : []) {
|
|
4383
|
+
const key = (_c = r.id) !== null && _c !== void 0 ? _c : r.encrypted_content;
|
|
4384
|
+
if (replayedReasoning.has(key))
|
|
4385
|
+
continue;
|
|
4386
|
+
replayedReasoning.add(key);
|
|
4387
|
+
items.push(replayableReasoning(r));
|
|
4388
|
+
}
|
|
4389
|
+
}
|
|
4390
|
+
if (msg.content) {
|
|
4391
|
+
const item = {
|
|
4392
|
+
type: "message",
|
|
4393
|
+
role: "assistant",
|
|
4394
|
+
content: [{ type: "output_text", text: msg.content }]
|
|
4395
|
+
};
|
|
4396
|
+
if (state === null || state === void 0 ? void 0 : state.phase)
|
|
4397
|
+
item.phase = state.phase;
|
|
4398
|
+
items.push(item);
|
|
4399
|
+
}
|
|
4400
|
+
for (const tc of (_d = msg.toolCalls) !== null && _d !== void 0 ? _d : []) {
|
|
4401
|
+
items.push({
|
|
4402
|
+
type: "function_call",
|
|
4403
|
+
call_id: tc.id,
|
|
4404
|
+
name: tc.name,
|
|
4405
|
+
arguments: JSON.stringify((_e = tc.args) !== null && _e !== void 0 ? _e : {})
|
|
4406
|
+
});
|
|
4407
|
+
}
|
|
4408
|
+
}
|
|
4409
|
+
const content = userContentParts(userMessage, attachments !== null && attachments !== void 0 ? attachments : []);
|
|
4410
|
+
if (content.length)
|
|
4411
|
+
items.push({ type: "message", role: "user", content });
|
|
4412
|
+
return items;
|
|
4413
|
+
}
|
|
4414
|
+
/**
|
|
4415
|
+
* A tool result, always as content parts — never the plain-string form. A cache hit needs the
|
|
4416
|
+
* whole rendered prefix to match, and a breakpoint can only sit on a part, so a string output
|
|
4417
|
+
* that became an array when it carried one would render differently on the next turn.
|
|
4418
|
+
*/
|
|
4419
|
+
toFunctionCallOutput(msg) {
|
|
4420
|
+
var _a;
|
|
4421
|
+
const result = msg.toolResult;
|
|
4422
|
+
const images = (_a = result.attachments) !== null && _a !== void 0 ? _a : [];
|
|
4423
|
+
return {
|
|
4424
|
+
type: "function_call_output",
|
|
4425
|
+
call_id: result.toolCallId,
|
|
4426
|
+
output: [{ type: "input_text", text: result.content }, ...images.map(imagePart)]
|
|
4427
|
+
};
|
|
4428
|
+
}
|
|
4429
|
+
/**
|
|
4430
|
+
* Put a history-scope breakpoint on every stored item that can carry one — a user message's last
|
|
4431
|
+
* text part or a tool result's — up to the latest `MAX_HISTORY_BREAKPOINTS`.
|
|
4432
|
+
*
|
|
4433
|
+
* One breakpoint on the last item (Anthropic's shape) never hits on OpenAI: lookup checks only the
|
|
4434
|
+
* breakpoints in this request, and the last item moves every turn, so the previous turn's boundary
|
|
4435
|
+
* was unmarked and every turn rewrote the whole history to cache. Marking each boundary keeps the
|
|
4436
|
+
* previous turn's in the request. Assistant items cannot carry one.
|
|
4437
|
+
*/
|
|
4438
|
+
markHistoryBreakpoints(input) {
|
|
4439
|
+
let marked = 0;
|
|
4440
|
+
for (let i = input.length - 1; i >= 0 && marked < MAX_HISTORY_BREAKPOINTS; i -= 1) {
|
|
4441
|
+
const item = input[i];
|
|
4442
|
+
if (item.role === "developer")
|
|
4443
|
+
continue;
|
|
4444
|
+
const key = item.type === "function_call_output" ? "output" : item.type === "message" && item.role !== "assistant" ? "content" : void 0;
|
|
4445
|
+
if (!key)
|
|
4446
|
+
continue;
|
|
4447
|
+
const parts = [...item[key]];
|
|
4448
|
+
let textIndex = -1;
|
|
4449
|
+
for (let j = parts.length - 1; j >= 0; j -= 1) {
|
|
4450
|
+
if (parts[j].type === "input_text") {
|
|
4451
|
+
textIndex = j;
|
|
4452
|
+
break;
|
|
4453
|
+
}
|
|
4454
|
+
}
|
|
4455
|
+
if (textIndex < 0)
|
|
4456
|
+
continue;
|
|
4457
|
+
parts[textIndex] = Object.assign(Object.assign({}, parts[textIndex]), { prompt_cache_breakpoint: CACHE_BREAKPOINT });
|
|
4458
|
+
input[i] = Object.assign(Object.assign({}, item), { [key]: parts });
|
|
4459
|
+
marked += 1;
|
|
4460
|
+
}
|
|
4461
|
+
}
|
|
4462
|
+
usageFromResponse(usage) {
|
|
4463
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
|
|
4464
|
+
if (!usage)
|
|
4465
|
+
return {};
|
|
4466
|
+
const u = usage;
|
|
4467
|
+
const cacheReadTokens = (_b = (_a = u.input_tokens_details) === null || _a === void 0 ? void 0 : _a.cached_tokens) !== null && _b !== void 0 ? _b : 0;
|
|
4468
|
+
const cacheWriteTokens = (_d = (_c = u.input_tokens_details) === null || _c === void 0 ? void 0 : _c.cache_write_tokens) !== null && _d !== void 0 ? _d : 0;
|
|
4469
|
+
const { costUsd, savedUsd } = openaiTokenCost(this.model, {
|
|
4470
|
+
inputTokens: (_e = u.input_tokens) !== null && _e !== void 0 ? _e : 0,
|
|
4471
|
+
outputTokens: (_f = u.output_tokens) !== null && _f !== void 0 ? _f : 0,
|
|
4472
|
+
cacheReadTokens,
|
|
4473
|
+
cacheWriteTokens,
|
|
4474
|
+
cacheWrite12hTokens: (_j = (_h = (_g = u.input_tokens_details) === null || _g === void 0 ? void 0 : _g.cache_write_tokens_details) === null || _h === void 0 ? void 0 : _h.ttl_12h_tokens) !== null && _j !== void 0 ? _j : 0
|
|
4475
|
+
});
|
|
4476
|
+
this.lifetimeCostUsd += costUsd;
|
|
4477
|
+
this.lifetimeSavingsUsd += savedUsd;
|
|
4478
|
+
const dp = _OpenAITransport.COST_DECIMAL_PLACES;
|
|
4479
|
+
console.log(`--- OpenAI Token Usage (${this.model}) ---`);
|
|
4480
|
+
console.log(`Input Tokens: ${(_k = u.input_tokens) !== null && _k !== void 0 ? _k : 0} (${cacheReadTokens} cached, ${cacheWriteTokens} written)`);
|
|
4481
|
+
console.log(`Output Tokens: ${(_l = u.output_tokens) !== null && _l !== void 0 ? _l : 0} (incl. ${(_o = (_m = u.output_tokens_details) === null || _m === void 0 ? void 0 : _m.reasoning_tokens) !== null && _o !== void 0 ? _o : 0} reasoning)`);
|
|
4482
|
+
console.log(`Total Cost: $${costUsd.toFixed(dp)}`);
|
|
4483
|
+
console.log(`Cache Saved: $${savedUsd.toFixed(dp)} (lifetime $${this.lifetimeSavingsUsd.toFixed(dp)})`);
|
|
4484
|
+
console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(dp)}`);
|
|
4485
|
+
console.log("--------------------------");
|
|
4486
|
+
return {
|
|
4487
|
+
// Responses' input_tokens already INCLUDES cached and written tokens, matching what
|
|
4488
|
+
// ChatMessage.inputTokens means on Gemini (the whole prompt).
|
|
4489
|
+
inputTokens: u.input_tokens,
|
|
4490
|
+
// Reasoning tokens are already inside output_tokens — no folding needed (unlike Gemini).
|
|
4491
|
+
outputTokens: u.output_tokens,
|
|
4492
|
+
thoughtsTokens: (_p = u.output_tokens_details) === null || _p === void 0 ? void 0 : _p.reasoning_tokens,
|
|
4493
|
+
cacheReadTokens: (_q = u.input_tokens_details) === null || _q === void 0 ? void 0 : _q.cached_tokens,
|
|
4494
|
+
cacheWriteTokens: (_r = u.input_tokens_details) === null || _r === void 0 ? void 0 : _r.cache_write_tokens,
|
|
4495
|
+
cost: costUsd
|
|
4496
|
+
};
|
|
4497
|
+
}
|
|
4498
|
+
fromResponse(response, effectiveMaxTokens) {
|
|
4499
|
+
var _a, _b;
|
|
4500
|
+
const usage = this.usageFromResponse(response.usage);
|
|
4501
|
+
const output = (_a = response.output) !== null && _a !== void 0 ? _a : [];
|
|
4502
|
+
const { reasoning, summaryParts, textParts, refusals, toolCalls, phase } = collectOutput(output);
|
|
4503
|
+
const state = { model: this.model };
|
|
4504
|
+
if (reasoning.length)
|
|
4505
|
+
state.reasoning = reasoning;
|
|
4506
|
+
if (phase)
|
|
4507
|
+
state.phase = phase;
|
|
4508
|
+
const providerMetadata = { [OPENAI_PROVIDER_KEY]: state };
|
|
4509
|
+
if (toolCalls.length)
|
|
4510
|
+
toolCalls[0].providerMetadata = providerMetadata;
|
|
4511
|
+
const narration = textParts.join("");
|
|
4512
|
+
const summary = summaryParts.join("\n\n");
|
|
4513
|
+
const base = Object.assign({ role: "assistant", content: narration, reasoning: summary || void 0 }, toolCalls.length ? { toolCalls } : { providerMetadata });
|
|
4514
|
+
const status = response.status;
|
|
4515
|
+
if (status === "failed")
|
|
4516
|
+
throw failedResponseError(this.model, response.error);
|
|
4517
|
+
const incompleteReason = (_b = response.incomplete_details) === null || _b === void 0 ? void 0 : _b.reason;
|
|
4518
|
+
const finishReason = refusals.length && !narration && !toolCalls.length ? "refusal" : status === "incomplete" ? incompleteReason !== null && incompleteReason !== void 0 ? incompleteReason : "incomplete" : status;
|
|
4519
|
+
if (finishReason === "refusal") {
|
|
4520
|
+
logger.warn("OpenAITransport: the model refused", {
|
|
4521
|
+
model: this.model,
|
|
4522
|
+
refusal: refusals.join("\n")
|
|
4523
|
+
});
|
|
4524
|
+
}
|
|
4525
|
+
if (status === "incomplete" && incompleteReason === "content_filter") {
|
|
4526
|
+
base.content = "";
|
|
4527
|
+
delete base.toolCalls;
|
|
4528
|
+
logger.warn("OpenAITransport: response stopped by the content filter; partial output dropped", {
|
|
4529
|
+
model: this.model,
|
|
4530
|
+
outputTypes: output.map((o) => o.type)
|
|
4531
|
+
});
|
|
4532
|
+
}
|
|
4533
|
+
if (status === "incomplete" && incompleteReason === "max_output_tokens") {
|
|
4534
|
+
if (toolCalls.length || !narration.trim()) {
|
|
4535
|
+
throw new ResponseTruncatedError(this.model, effectiveMaxTokens, usage.outputTokens, toolCalls.map((tc) => tc.name));
|
|
4536
|
+
}
|
|
4537
|
+
}
|
|
4538
|
+
if (!toolCalls.length && !narration && !summary && finishReason !== "refusal" && finishReason !== "content_filter") {
|
|
4539
|
+
logger.warn("OpenAITransport: blank response", {
|
|
4540
|
+
model: this.model,
|
|
4541
|
+
status,
|
|
4542
|
+
incompleteReason,
|
|
4543
|
+
outputTypes: output.map((o) => o.type),
|
|
4544
|
+
usage: response.usage
|
|
4545
|
+
});
|
|
4546
|
+
}
|
|
4547
|
+
if (usage.inputTokens != null)
|
|
4548
|
+
base.inputTokens = usage.inputTokens;
|
|
4549
|
+
if (usage.outputTokens != null)
|
|
4550
|
+
base.outputTokens = usage.outputTokens;
|
|
4551
|
+
if (usage.cacheReadTokens != null)
|
|
4552
|
+
base.cacheReadTokens = usage.cacheReadTokens;
|
|
4553
|
+
if (usage.cacheWriteTokens != null)
|
|
4554
|
+
base.cacheWriteTokens = usage.cacheWriteTokens;
|
|
4555
|
+
if (usage.cost != null)
|
|
4556
|
+
base.cost = usage.cost;
|
|
4557
|
+
base.model = this.model;
|
|
4558
|
+
if (finishReason != null || usage.thoughtsTokens != null) {
|
|
4559
|
+
base.responseMeta = {
|
|
4560
|
+
finishReason,
|
|
4561
|
+
thoughtsTokens: usage.thoughtsTokens,
|
|
4562
|
+
parts: {
|
|
4563
|
+
functionCall: toolCalls.length,
|
|
4564
|
+
thought: summaryParts.length,
|
|
4565
|
+
text: textParts.length
|
|
4566
|
+
}
|
|
4567
|
+
};
|
|
4568
|
+
}
|
|
4569
|
+
return base;
|
|
4570
|
+
}
|
|
4571
|
+
buildEndpoint(body) {
|
|
4572
|
+
if (this.apiKey) {
|
|
4573
|
+
return {
|
|
4574
|
+
url: OPENAI_DIRECT_URL,
|
|
4575
|
+
payload: body,
|
|
4576
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}` },
|
|
4577
|
+
credentials: "omit"
|
|
4578
|
+
};
|
|
4579
|
+
}
|
|
4580
|
+
if (this.serverEndpoint) {
|
|
4581
|
+
return {
|
|
4582
|
+
url: this.serverEndpoint,
|
|
4583
|
+
payload: body,
|
|
4584
|
+
// Opt in to the proxy's NDJSON heartbeat framing.
|
|
4585
|
+
headers: { "Content-Type": "application/json", Accept: "application/x-ndjson" },
|
|
4586
|
+
credentials: "include"
|
|
4587
|
+
};
|
|
4588
|
+
}
|
|
4589
|
+
throw new Error("OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.");
|
|
4590
|
+
}
|
|
4591
|
+
post(body, signal) {
|
|
4592
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4593
|
+
const { url, payload, headers, credentials } = this.buildEndpoint(body);
|
|
4594
|
+
return yield postWithRetry({
|
|
4595
|
+
url,
|
|
4596
|
+
headers,
|
|
4597
|
+
body: payload,
|
|
4598
|
+
credentials,
|
|
4599
|
+
vendorLabel: VENDOR_LABELS.openai,
|
|
4600
|
+
retryableStatuses: _OpenAITransport.RETRYABLE_STATUSES,
|
|
4601
|
+
timeout: this.timeout,
|
|
4602
|
+
stallTimeout: this.stallTimeout,
|
|
4603
|
+
backoffBaseMs: _OpenAITransport.BACKOFF_BASE_MS,
|
|
4604
|
+
signal
|
|
4605
|
+
});
|
|
4606
|
+
});
|
|
4607
|
+
}
|
|
4608
|
+
};
|
|
4609
|
+
OpenAITransport.COST_DECIMAL_PLACES = 6;
|
|
4610
|
+
OpenAITransport.RATE_LIMIT_STATUS = 429;
|
|
4611
|
+
OpenAITransport.SERVER_ERROR_STATUS = 500;
|
|
4612
|
+
OpenAITransport.BAD_GATEWAY_STATUS = 502;
|
|
4613
|
+
OpenAITransport.SERVICE_UNAVAILABLE_STATUS = 503;
|
|
4614
|
+
OpenAITransport.RETRYABLE_STATUSES = [
|
|
4615
|
+
OpenAITransport.RATE_LIMIT_STATUS,
|
|
4616
|
+
OpenAITransport.SERVER_ERROR_STATUS,
|
|
4617
|
+
OpenAITransport.BAD_GATEWAY_STATUS,
|
|
4618
|
+
OpenAITransport.SERVICE_UNAVAILABLE_STATUS
|
|
4619
|
+
];
|
|
4620
|
+
OpenAITransport.BACKOFF_BASE_MS = 1e3;
|
|
4621
|
+
function failedResponseError(model, error) {
|
|
4622
|
+
const { code, message } = error !== null && error !== void 0 ? error : {};
|
|
4623
|
+
return new Error(`OpenAITransport: ${model} response failed${code ? ` (${code})` : ""}: ${message !== null && message !== void 0 ? message : "no error detail"}`);
|
|
4624
|
+
}
|
|
4625
|
+
function stripStrictNulls(value, pointers) {
|
|
4626
|
+
for (const pointer of pointers) {
|
|
4627
|
+
deleteNullAt(value, pointer.split("/").slice(1));
|
|
4628
|
+
}
|
|
4629
|
+
}
|
|
4630
|
+
function deleteNullAt(value, segments) {
|
|
4631
|
+
if (!value || typeof value !== "object")
|
|
4632
|
+
return;
|
|
4633
|
+
const [head, ...rest] = segments;
|
|
4634
|
+
if (head === "items" && Array.isArray(value)) {
|
|
4635
|
+
for (const element of value)
|
|
4636
|
+
deleteNullAt(element, rest);
|
|
4637
|
+
return;
|
|
4638
|
+
}
|
|
4639
|
+
if (head !== "properties" || !rest.length || Array.isArray(value))
|
|
4640
|
+
return;
|
|
4641
|
+
const [name, ...below] = rest;
|
|
4642
|
+
const record = value;
|
|
4643
|
+
if (!below.length) {
|
|
4644
|
+
if (record[name] === null)
|
|
4645
|
+
delete record[name];
|
|
4646
|
+
return;
|
|
4647
|
+
}
|
|
4648
|
+
deleteNullAt(record[name], below);
|
|
4649
|
+
}
|
|
4650
|
+
function strictNullPointersByTool(tools) {
|
|
4651
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
4652
|
+
for (const tool of tools !== null && tools !== void 0 ? tools : []) {
|
|
4653
|
+
if (!tool.enforceSchema)
|
|
4654
|
+
continue;
|
|
4655
|
+
const { madeNullable } = toOpenAIStrictSchema(tool.parameters);
|
|
4656
|
+
if (madeNullable.length)
|
|
4657
|
+
byTool.set(tool.name, madeNullable);
|
|
4658
|
+
}
|
|
4659
|
+
return byTool;
|
|
4660
|
+
}
|
|
4661
|
+
function parseArguments(raw) {
|
|
4662
|
+
if (raw && typeof raw === "object")
|
|
4663
|
+
return raw;
|
|
4664
|
+
if (typeof raw !== "string" || !raw.trim())
|
|
4665
|
+
return {};
|
|
4666
|
+
try {
|
|
4667
|
+
const parsed = JSON.parse(raw);
|
|
4668
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
4669
|
+
} catch (_a) {
|
|
4670
|
+
logger.warn("OpenAITransport: function_call arguments are not valid JSON", { raw });
|
|
4671
|
+
return {};
|
|
4672
|
+
}
|
|
4673
|
+
}
|
|
4674
|
+
|
|
3751
4675
|
// ../../foundation-ai/dist/esm/ai-provider.js
|
|
3752
4676
|
function isObservableAIProviderRegistry(r) {
|
|
3753
4677
|
return typeof r.subscribe === "function";
|
|
@@ -4282,7 +5206,7 @@ var DEBUG_LOG_README = [
|
|
|
4282
5206
|
"kind:'turn'.`agentSnapshot` \u2014 the active agent's own view of its internal state, captured at that turn. An agent opts into this by exposing a `getDebugSnapshot()` that returns JSON-serializable per-state info; stateful/flow agents wire it automatically, so you can watch a flow advance turn-by-turn (e.g. current step, cursor, collected fields, pending changes). Absent for agents that don't expose one.",
|
|
4283
5207
|
"kind:'event' \u2014 a meta/lifecycle event. `type` names it (see below); `detail` carries structured data. `detail.placement` is the emitting UI instance: 'bubble' (collapsed), 'panel' (popped-out), or 'standalone'.",
|
|
4284
5208
|
"Each 'event' also has an `importance`: 'high' (failures/limits \u2014 turn.error, tool.failed, subagent.failed, file.read-failed, suggestions.failed, context.threshold-crossed), 'normal' (session flow \u2014 connects, turns, retries, handoffs, agent/provider changes, interactions, sub-agent start/complete), or 'low' (skippable UI/bookkeeping noise \u2014 panel.toggled, attachment.added, driver.wired/unwired, context.updated, context.condensed). To skim, ignore importance:'low'; to triage a failure, filter to importance:'high' then read the nearby messages and turns. A 'high' turn.error is often preceded by one or more 'normal' turn.retry events for the same reason \u2014 read them together to see how many attempts were made before bailing. 'message' and 'turn' entries carry no importance \u2014 they are the substance, always read them.",
|
|
4285
|
-
"Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle\u2194loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry \u2014 detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.error (a turn failed or hit a guardrail \u2014 detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted/provider-refused/context-exhausted/ai-service-error, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools \u2014 real earlier this activation but retired by the current state or hidden behind an open exclusive fold \u2014 and hallucinatedTools \u2014 never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, for provider-refused the kind (spend|auth) plus the upstream status and error type \u2014 the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached \u2014 the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with \u2014 its own text goes to the browser console only, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched \u2014 detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation \u2014 detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted/provider_refused/context_exhausted/ai_service_error; budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls \u2014 the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION \u2014 see its own paragraph below), provider.selected (the resolved provider for the upcoming turns \u2014 detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets \u2014 explain quiet gaps; note that when a sub-agent opens a widget, detail.agent \u2014 and the agentName on the interaction message \u2014 is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered \u2014 the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) \u2014 absent when it closed unanswered (a timeout or a stop), and absent too when it settled by itself other than through the hold of a claimant \u2014 a widget registered resolvesItself (one that does its work and settles on its own, asking the person nothing, such as a generation run), or one outcome its controller said settled itself (ctx.resolve with resolvedItself, such as a generation phase that failed outright before its review gate ever asked anything) \u2014 which then carries detail.resolvedItself: true instead, as the interaction message does \u2014 nobody answered it, and the platform cannot tell it finishing from the person interrupting it (a Skip), so only the result of the widget itself can say which; the same value is stamped on the interaction message as answeredBy and on the result the asking tool handler receives (absent there in the same cases), and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead \u2014 the framing and those choice texts \u2014 so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself \u2014 detail.heldBy is the new holder, detail.claimant the interceptor; detail.late: true is an interceptor that declined it when it opened claiming it afterwards, such as the autopilot resumed while it was open; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person \u2014 detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user \u2014 autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; one declined as paused that is still open when the person resumes the autopilot is looked at again, and the autopilot.claimed or autopilot.declined recorded for it then carries detail.onResume: true (a decline then can also be claimed-elsewhere, another interceptor having claimed it first); a restored mode looks at nothing; autopilot.decision-sent is what it was sent (detail.chars; detail.nothingEnabled: true when every action on the widget was unavailable \u2014 a gate whose controller said it was asking, such as a failed build the autopilot may not cancel \u2014 so it could only hand it back, which it may then do even after the person asked it to decide it itself; a widget whose controller says it is working (ctx.setWorking) is never sent a decision until it says it is asking, even when an action is enabled or the person resumes the autopilot); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.carried is the mode, running or paused, going with the task to the agent that took it over, rather than ending with the flow as on any other change of flow owner: to the target of a hand-off, or back to its caller on the hand-back (detail.from, detail.to, detail.mode); a pause the person chose goes with it, and Stop and Clear still end it; a mode restored for the target of a hand-off applies to its caller when the reload hands back; autopilot.error is the wrapper itself failing; autopilot.refinement counts a refining action against its step \u2014 a written answer (reply) or a widget action declared refines, such as a regenerate with instructions, counted together (detail.action, detail.stepKey, detail.count, detail.limitReached, after which every refining action is withdrawn for that step: not listed, and refused; the decision and every relisting of its actions say how many are left at the step, as a line Refinements left at this step: N, wherever the widget has a refining action); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short \u2014 detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for \u2014 stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere \u2014 or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs \u2014 detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf; the person's own programmatic action, from a host with no DOM to click, carries detail.by: user in place of detail.claimant, and is not recorded as an edit nor as a decision on their behalf, so what it settles is answered by user), interaction.step (a long action run as named steps through runSteps, which survive a reload \u2014 detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the checkpoints a conversation keeps for its long actions: the one in flight, and each one a reload cut, held apart until a request of its own widget type takes it over, so a resumed flow that opens other long widgets first, which save their own, loses nothing \u2014 detail.action: resumed when a reload cut the work and a request of the same widget type that the registration sameWork agrees is the same work took it over, refused when sameWork said a new request is different work (detail.saved is the identity it kept; detail.kept: true, since it stays for a later request of that type, and is offered to every one until one agrees) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended, once per checkpoint, with detail.cut: true for one a reload cut that nothing took over), context.updated/threshold-crossed (token + cost), headless.attached (a HeadlessSession attached, for a host that drives the assistant with no screen \u2014 detail.label, what the host called itself, when it gave one) and headless.raw-resolved (that host settled an interaction raw, bypassing the widget's own actions: detail.interactionId and detail.component; the result went to the tool as given, so check what the widget would have enforced), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool \u2014 detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.",
|
|
5209
|
+
"Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle\u2194loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry \u2014 detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown; reason no-tool-call is a sub-agent on a model that rejects forced tool use (Opus 5.5 / Sonnet 5.5) answering its forced turn in text, retried once with a nudge), turn.error (a turn failed or hit a guardrail \u2014 detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted/provider-refused/context-exhausted/ai-service-error, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools \u2014 real earlier this activation but retired by the current state or hidden behind an open exclusive fold \u2014 and hallucinatedTools \u2014 never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, for provider-refused the kind (spend|auth) plus the upstream status and error type \u2014 the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached \u2014 the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with \u2014 its own text goes to the browser console only, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched \u2014 detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation \u2014 detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted/provider_refused/context_exhausted/ai_service_error; budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls \u2014 the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION \u2014 see its own paragraph below), provider.selected (the resolved provider for the upcoming turns \u2014 detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets \u2014 explain quiet gaps; note that when a sub-agent opens a widget, detail.agent \u2014 and the agentName on the interaction message \u2014 is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered \u2014 the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) \u2014 absent when it closed unanswered (a timeout or a stop), and absent too when it settled by itself other than through the hold of a claimant \u2014 a widget registered resolvesItself (one that does its work and settles on its own, asking the person nothing, such as a generation run), or one outcome its controller said settled itself (ctx.resolve with resolvedItself, such as a generation phase that failed outright before its review gate ever asked anything) \u2014 which then carries detail.resolvedItself: true instead, as the interaction message does \u2014 nobody answered it, and the platform cannot tell it finishing from the person interrupting it (a Skip), so only the result of the widget itself can say which; the same value is stamped on the interaction message as answeredBy and on the result the asking tool handler receives (absent there in the same cases), and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead \u2014 the framing and those choice texts \u2014 so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself \u2014 detail.heldBy is the new holder, detail.claimant the interceptor; detail.late: true is an interceptor that declined it when it opened claiming it afterwards, such as the autopilot resumed while it was open; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person \u2014 detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user \u2014 autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; one declined as paused that is still open when the person resumes the autopilot is looked at again, and the autopilot.claimed or autopilot.declined recorded for it then carries detail.onResume: true (a decline then can also be claimed-elsewhere, another interceptor having claimed it first); a restored mode looks at nothing; autopilot.decision-sent is what it was sent (detail.chars; detail.nothingEnabled: true when every action on the widget was unavailable \u2014 a gate whose controller said it was asking, such as a failed build the autopilot may not cancel \u2014 so it could only hand it back, which it may then do even after the person asked it to decide it itself; a widget whose controller says it is working (ctx.setWorking) is never sent a decision until it says it is asking, even when an action is enabled or the person resumes the autopilot); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.carried is the mode, running or paused, going with the task to the agent that took it over, rather than ending with the flow as on any other change of flow owner: to the target of a hand-off, or back to its caller on the hand-back (detail.from, detail.to, detail.mode); a pause the person chose goes with it, and Stop and Clear still end it; a mode restored for the target of a hand-off applies to its caller when the reload hands back; autopilot.error is the wrapper itself failing; autopilot.refinement counts a refining action against its step \u2014 a written answer (reply) or a widget action declared refines, such as a regenerate with instructions, counted together (detail.action, detail.stepKey, detail.count, detail.limitReached, after which every refining action is withdrawn for that step: not listed, and refused; the decision and every relisting of its actions say how many are left at the step, as a line Refinements left at this step: N, wherever the widget has a refining action); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short \u2014 detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for \u2014 stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere \u2014 or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs \u2014 detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf; the person's own programmatic action, from a host with no DOM to click, carries detail.by: user in place of detail.claimant, and is not recorded as an edit nor as a decision on their behalf, so what it settles is answered by user), interaction.step (a long action run as named steps through runSteps, which survive a reload \u2014 detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the checkpoints a conversation keeps for its long actions: the one in flight, and each one a reload cut, held apart until a request of its own widget type takes it over, so a resumed flow that opens other long widgets first, which save their own, loses nothing \u2014 detail.action: resumed when a reload cut the work and a request of the same widget type that the registration sameWork agrees is the same work took it over, refused when sameWork said a new request is different work (detail.saved is the identity it kept; detail.kept: true, since it stays for a later request of that type, and is offered to every one until one agrees) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended, once per checkpoint, with detail.cut: true for one a reload cut that nothing took over), context.updated/threshold-crossed (token + cost), headless.attached (a HeadlessSession attached, for a host that drives the assistant with no screen \u2014 detail.label, what the host called itself, when it gave one) and headless.raw-resolved (that host settled an interaction raw, bypassing the widget's own actions: detail.interactionId and detail.component; the result went to the tool as given, so check what the widget would have enforced), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool \u2014 detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.",
|
|
4286
5210
|
"Sub-agent meta events: a sub-agent's own turn.retry/turn.error/tool.failed/tool.unresolved events are merged into this same timeline, tagged with `detail.subAgent` \u2014 a `\"<parent> \u203A <sub-agent>\"` breadcrumb that composes when nested (e.g. `\"UI Builder \u203A Planner \u203A Grounding\"`) \u2014 and interleaved by their original timestamps within the subagent.started\u2192completed/failed bracket. These are the per-attempt/per-failure signals that do NOT appear among the sub-agent's (hoisted) messages: a malformed/empty attempt that gets retried produces no message, and the stale-vs-hallucinated split and streak counts live only on the event. A sub-agent's high-volume, message-derivable events (turn.start/turn.end, provider.selected, context.updated) are intentionally NOT merged \u2014 read its hoisted messages for model/tokens/cost and turn-by-turn activity, and the bracketing subagent.* events for the run's span.",
|
|
4287
5211
|
"`meta` holds context captured at export time: agentSummary (full agent configs), context (active model, contextTokens/contextLimit/contextUsagePercent for the last call, and the session totals \u2014 sessionCostUsd, sessionTokensConsumed, and the four-bucket sessionUsage lifted to the top of this log), activeDebugSnapshot (the active agent's `getDebugSnapshot()` taken fresh at export \u2014 reflects state NOW, which may have advanced beyond the last turn's agentSnapshot), debug (optional host-supplied debug state), host, and the export timestamp.",
|
|
4288
5212
|
"Note the two different scopes in `meta.context`: `contextTokens` is the prompt size of the LAST call (against `contextLimit`, the model context window), while `sessionUsage`/`sessionTokensConsumed` are cumulative BILLED throughput. Every turn resends the conversation, so the cumulative figure counts each turn\u2019s prompt again in the next turn\u2019s and is expected to dwarf the context size \u2014 that is not double-counting.",
|
|
@@ -5376,6 +6300,7 @@ var HARVESTED_SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
|
|
|
5376
6300
|
"tool.failed",
|
|
5377
6301
|
"tool.unresolved"
|
|
5378
6302
|
]);
|
|
6303
|
+
var NO_TOOL_CALL_NUDGE = "IMPORTANT: Your previous reply ended without calling a tool, but this task can only be finished by calling one. Call the tool now; do not reply with text alone.";
|
|
5379
6304
|
|
|
5380
6305
|
// src/utils/tool-fold.ts
|
|
5381
6306
|
var TOOL_FOLD_SYMBOL = Symbol("toolFold");
|
|
@@ -9313,6 +10238,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
|
|
|
9313
10238
|
let iterations = 0;
|
|
9314
10239
|
let malformedAttempts = 0;
|
|
9315
10240
|
let emptyResponseAttempts = 0;
|
|
10241
|
+
let noToolCallRetried = false;
|
|
10242
|
+
let noToolCallNudgePending = false;
|
|
9316
10243
|
let setupTransportAttempts = 0;
|
|
9317
10244
|
let firstLlmCall = !!currentInput;
|
|
9318
10245
|
let pinnedThinkingPolicy;
|
|
@@ -9365,7 +10292,9 @@ var ChatDriver = class _ChatDriver extends EventTarget {
|
|
|
9365
10292
|
|
|
9366
10293
|
${MALFORMED_CALL_NUDGE}` : emptyResponseAttempts > 0 ? `
|
|
9367
10294
|
|
|
9368
|
-
${EMPTY_RESPONSE_NUDGE}` :
|
|
10295
|
+
${EMPTY_RESPONSE_NUDGE}` : noToolCallNudgePending ? `
|
|
10296
|
+
|
|
10297
|
+
${NO_TOOL_CALL_NUDGE}` : "";
|
|
9369
10298
|
const firstCallNote = tailNote && iterations === 1 ? `
|
|
9370
10299
|
|
|
9371
10300
|
${tailNote}` : "";
|
|
@@ -9693,7 +10622,10 @@ ${tailBody}
|
|
|
9693
10622
|
inputTokens: void 0,
|
|
9694
10623
|
outputTokens: void 0,
|
|
9695
10624
|
cacheReadTokens: void 0,
|
|
9696
|
-
cacheWriteTokens: void 0
|
|
10625
|
+
cacheWriteTokens: void 0,
|
|
10626
|
+
// Round-trip state (OpenAI's encrypted reasoning) belongs to the message that is replayed;
|
|
10627
|
+
// a display copy is never sent, so a copy here is only stored and exported again.
|
|
10628
|
+
providerMetadata: void 0
|
|
9697
10629
|
};
|
|
9698
10630
|
if (reasoning) {
|
|
9699
10631
|
this.appendToHistory({
|
|
@@ -9719,10 +10651,28 @@ ${tailBody}
|
|
|
9719
10651
|
emptyResponseAttempts = 0;
|
|
9720
10652
|
malformedAttempts = 0;
|
|
9721
10653
|
setupTransportAttempts = 0;
|
|
10654
|
+
noToolCallNudgePending = false;
|
|
9722
10655
|
if (closing) return turnDone();
|
|
9723
10656
|
if (!response.toolCalls?.length) {
|
|
10657
|
+
if (this.isSubAgent && !this.subAgentCompletion && response.responseMeta?.toolChoiceDowngraded && !noToolCallRetried) {
|
|
10658
|
+
noToolCallRetried = true;
|
|
10659
|
+
noToolCallNudgePending = true;
|
|
10660
|
+
logger2.warn(
|
|
10661
|
+
"ChatDriver: sub-agent replied without the tool call its forced turn needed, retrying once"
|
|
10662
|
+
);
|
|
10663
|
+
recordMetaEvent(this.sessionKey, "turn.retry", {
|
|
10664
|
+
reason: "no-tool-call",
|
|
10665
|
+
agent: this.activeAgentName,
|
|
10666
|
+
provider: this.lastResolvedProviderName,
|
|
10667
|
+
attempt: 1,
|
|
10668
|
+
maxAttempts: 1
|
|
10669
|
+
});
|
|
10670
|
+
iterations -= 1;
|
|
10671
|
+
continue;
|
|
10672
|
+
}
|
|
9724
10673
|
break;
|
|
9725
10674
|
}
|
|
10675
|
+
noToolCallRetried = false;
|
|
9726
10676
|
const toolCalls = response.toolCalls;
|
|
9727
10677
|
const executedById = /* @__PURE__ */ new Map();
|
|
9728
10678
|
const unknownToolIds = /* @__PURE__ */ new Set();
|
|
@@ -12862,6 +13812,7 @@ function collectRows(messages, depth, subAgentOf) {
|
|
|
12862
13812
|
ANTHROPIC_CACHE_READ_MULTIPLIER,
|
|
12863
13813
|
ANTHROPIC_CACHE_WRITE_1H_MULTIPLIER,
|
|
12864
13814
|
ANTHROPIC_CACHE_WRITE_5M_MULTIPLIER,
|
|
13815
|
+
ANTHROPIC_LONG_CONTEXT_THRESHOLD,
|
|
12865
13816
|
AgenticActivityBus,
|
|
12866
13817
|
AnthropicProvider,
|
|
12867
13818
|
AnthropicTransport,
|
|
@@ -12878,17 +13829,24 @@ function collectRows(messages, depth, subAgentOf) {
|
|
|
12878
13829
|
MALFORMED_CALL_NUDGE,
|
|
12879
13830
|
MutableAIProviderRegistry,
|
|
12880
13831
|
NOOP_ACTIVITY_BUS,
|
|
13832
|
+
OPENAI_CACHE_WRITE_12H_MULTIPLIER,
|
|
13833
|
+
OPENAI_CACHE_WRITE_30M_MULTIPLIER,
|
|
13834
|
+
OPENAI_LONG_CONTEXT_THRESHOLD,
|
|
13835
|
+
OpenAIProvider,
|
|
13836
|
+
OpenAITransport,
|
|
12881
13837
|
OrchestratingDriver,
|
|
12882
13838
|
PROVIDER_REFUSED_CODE,
|
|
12883
13839
|
ProviderRefusedError,
|
|
12884
13840
|
SUPPORTED_ANTHROPIC_MODEL_IDS,
|
|
12885
13841
|
SUPPORTED_GEMINI_MODEL_IDS,
|
|
13842
|
+
SUPPORTED_OPENAI_MODEL_IDS,
|
|
12886
13843
|
UNROUTABLE_INSTRUCTION,
|
|
12887
13844
|
UNROUTABLE_PLACEHOLDER,
|
|
12888
13845
|
addUsage,
|
|
12889
13846
|
agenticActivityBus,
|
|
12890
13847
|
aiServiceAccessRefusalOf,
|
|
12891
13848
|
aiServiceErrorCodeOf,
|
|
13849
|
+
anthropicCacheReadMultiplierFor,
|
|
12892
13850
|
anthropicRatesFor,
|
|
12893
13851
|
anthropicTokenCost,
|
|
12894
13852
|
assembleDebugLog,
|
|
@@ -12911,6 +13869,8 @@ function collectRows(messages, depth, subAgentOf) {
|
|
|
12911
13869
|
isTerminalAIServiceRefusal,
|
|
12912
13870
|
lifetimeDebugLog,
|
|
12913
13871
|
messageUsage,
|
|
13872
|
+
openaiRatesFor,
|
|
13873
|
+
openaiTokenCost,
|
|
12914
13874
|
resolveAITiers,
|
|
12915
13875
|
restoreMachine,
|
|
12916
13876
|
strictFallbackAgent,
|