@genesislcap/ai-assistant 15.91.0 → 15.92.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-driver.cjs +931 -144
- package/dist/chat-driver.cjs.map +4 -4
- package/dist/chat-driver.mjs +923 -144
- package/dist/chat-driver.mjs.map +4 -4
- package/dist/custom-elements.json +744 -664
- 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.d.ts.map +1 -1
- package/dist/esm/chat-driver-node.js +6 -3
- package/dist/esm/components/chat-driver/chat-driver.js +3 -0
- package/package.json +17 -17
package/dist/chat-driver.cjs
CHANGED
|
@@ -43,11 +43,17 @@ __export(chat_driver_node_exports, {
|
|
|
43
43
|
MALFORMED_CALL_NUDGE: () => MALFORMED_CALL_NUDGE,
|
|
44
44
|
MutableAIProviderRegistry: () => MutableAIProviderRegistry,
|
|
45
45
|
NOOP_ACTIVITY_BUS: () => NOOP_ACTIVITY_BUS,
|
|
46
|
+
OPENAI_CACHE_WRITE_12H_MULTIPLIER: () => OPENAI_CACHE_WRITE_12H_MULTIPLIER,
|
|
47
|
+
OPENAI_CACHE_WRITE_30M_MULTIPLIER: () => OPENAI_CACHE_WRITE_30M_MULTIPLIER,
|
|
48
|
+
OPENAI_LONG_CONTEXT_THRESHOLD: () => OPENAI_LONG_CONTEXT_THRESHOLD,
|
|
49
|
+
OpenAIProvider: () => OpenAIProvider,
|
|
50
|
+
OpenAITransport: () => OpenAITransport,
|
|
46
51
|
OrchestratingDriver: () => OrchestratingDriver,
|
|
47
52
|
PROVIDER_REFUSED_CODE: () => PROVIDER_REFUSED_CODE,
|
|
48
53
|
ProviderRefusedError: () => ProviderRefusedError,
|
|
49
54
|
SUPPORTED_ANTHROPIC_MODEL_IDS: () => SUPPORTED_ANTHROPIC_MODEL_IDS,
|
|
50
55
|
SUPPORTED_GEMINI_MODEL_IDS: () => SUPPORTED_GEMINI_MODEL_IDS,
|
|
56
|
+
SUPPORTED_OPENAI_MODEL_IDS: () => SUPPORTED_OPENAI_MODEL_IDS,
|
|
51
57
|
UNROUTABLE_INSTRUCTION: () => UNROUTABLE_INSTRUCTION,
|
|
52
58
|
UNROUTABLE_PLACEHOLDER: () => UNROUTABLE_PLACEHOLDER,
|
|
53
59
|
addUsage: () => addUsage,
|
|
@@ -76,6 +82,8 @@ __export(chat_driver_node_exports, {
|
|
|
76
82
|
isTerminalAIServiceRefusal: () => isTerminalAIServiceRefusal,
|
|
77
83
|
lifetimeDebugLog: () => lifetimeDebugLog,
|
|
78
84
|
messageUsage: () => messageUsage,
|
|
85
|
+
openaiRatesFor: () => openaiRatesFor,
|
|
86
|
+
openaiTokenCost: () => openaiTokenCost,
|
|
79
87
|
resolveAITiers: () => resolveAITiers,
|
|
80
88
|
restoreMachine: () => restoreMachine,
|
|
81
89
|
strictFallbackAgent: () => strictFallbackAgent,
|
|
@@ -1250,154 +1258,49 @@ var GeminiProvider = class {
|
|
|
1250
1258
|
}
|
|
1251
1259
|
};
|
|
1252
1260
|
|
|
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";
|
|
1261
|
+
// ../../foundation-ai/dist/esm/providers/openai-provider.js
|
|
1262
|
+
var OpenAIProvider = class {
|
|
1263
|
+
constructor(config, transport) {
|
|
1264
|
+
this.transport = transport;
|
|
1265
|
+
this.criteriaInstructions = config.criteriaInstructions;
|
|
1326
1266
|
}
|
|
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
|
-
}
|
|
1267
|
+
getStatus() {
|
|
1268
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1269
|
+
const config = this.transport.getConfig();
|
|
1270
|
+
return { provider: "openai", model: config.model, contextLimit: config.contextLimit };
|
|
1271
|
+
});
|
|
1352
1272
|
}
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1273
|
+
interpretCriteria(input, context) {
|
|
1274
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1275
|
+
var _a;
|
|
1276
|
+
const fields = (_a = context === null || context === void 0 ? void 0 : context.fields) !== null && _a !== void 0 ? _a : [];
|
|
1277
|
+
const systemPrompt = buildCriteriaSystemPrompt(fields, this.criteriaInstructions);
|
|
1278
|
+
const userPrompt = buildCriteriaUserPrompt(input);
|
|
1279
|
+
try {
|
|
1280
|
+
const raw = yield this.transport.sendStructuredPrompt({
|
|
1281
|
+
systemPrompt,
|
|
1282
|
+
userPrompt,
|
|
1283
|
+
responseSchema: CRITERIA_JSON_SCHEMA
|
|
1284
|
+
});
|
|
1285
|
+
return parseCriteriaResponse(raw);
|
|
1286
|
+
} catch (e) {
|
|
1287
|
+
logger.error("OpenAIProvider interpretCriteria failed:", e);
|
|
1288
|
+
return null;
|
|
1289
|
+
}
|
|
1290
|
+
});
|
|
1361
1291
|
}
|
|
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";
|
|
1292
|
+
prompt(message, options) {
|
|
1293
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1294
|
+
const response = yield this.transport.sendChatMessage([], message, options);
|
|
1295
|
+
return response.content;
|
|
1296
|
+
});
|
|
1378
1297
|
}
|
|
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";
|
|
1298
|
+
chat(history, userMessage, options) {
|
|
1299
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1300
|
+
return this.transport.sendChatMessage(history, userMessage, options);
|
|
1301
|
+
});
|
|
1389
1302
|
}
|
|
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
|
-
}
|
|
1303
|
+
};
|
|
1401
1304
|
|
|
1402
1305
|
// ../../foundation-ai/dist/esm/types/config.types.js
|
|
1403
1306
|
var SUPPORTED_GEMINI_MODEL_IDS = [
|
|
@@ -1418,11 +1321,20 @@ var SUPPORTED_ANTHROPIC_MODEL_IDS = [
|
|
|
1418
1321
|
"claude-sonnet-4-6",
|
|
1419
1322
|
"claude-haiku-4-5-20251001"
|
|
1420
1323
|
];
|
|
1324
|
+
var SUPPORTED_OPENAI_MODEL_IDS = [
|
|
1325
|
+
"gpt-6-astra",
|
|
1326
|
+
"gpt-6.1-sol",
|
|
1327
|
+
"gpt-6.1-terra",
|
|
1328
|
+
"gpt-6-sol",
|
|
1329
|
+
"gpt-6-luna"
|
|
1330
|
+
];
|
|
1421
1331
|
function vendorOfModel(modelId) {
|
|
1422
1332
|
if (SUPPORTED_ANTHROPIC_MODEL_IDS.includes(modelId))
|
|
1423
1333
|
return "anthropic";
|
|
1424
1334
|
if (SUPPORTED_GEMINI_MODEL_IDS.includes(modelId))
|
|
1425
1335
|
return "gemini";
|
|
1336
|
+
if (SUPPORTED_OPENAI_MODEL_IDS.includes(modelId))
|
|
1337
|
+
return "openai";
|
|
1426
1338
|
return void 0;
|
|
1427
1339
|
}
|
|
1428
1340
|
|
|
@@ -1571,6 +1483,52 @@ function geminiTokenCost(model, usage, at = /* @__PURE__ */ new Date()) {
|
|
|
1571
1483
|
}
|
|
1572
1484
|
};
|
|
1573
1485
|
}
|
|
1486
|
+
var OPENAI_PRICING = {
|
|
1487
|
+
"gpt-6-astra": { promptPerMillion: 10, cachedPerMillion: 1, candidatePerMillion: 50 },
|
|
1488
|
+
"gpt-6.1-sol": { promptPerMillion: 2, cachedPerMillion: 0.1, candidatePerMillion: 10 },
|
|
1489
|
+
"gpt-6.1-terra": { promptPerMillion: 1, cachedPerMillion: 0.05, candidatePerMillion: 5 },
|
|
1490
|
+
"gpt-6-sol": { promptPerMillion: 2, cachedPerMillion: 0.2, candidatePerMillion: 10 },
|
|
1491
|
+
"gpt-6-luna": { promptPerMillion: 0.1, cachedPerMillion: 0.01, candidatePerMillion: 0.5 }
|
|
1492
|
+
};
|
|
1493
|
+
var OPENAI_LONG_CONTEXT_THRESHOLD = 272e3;
|
|
1494
|
+
var OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER = 2;
|
|
1495
|
+
var OPENAI_LONG_CONTEXT_OUTPUT_MULTIPLIER = 1.5;
|
|
1496
|
+
var OPENAI_CACHE_WRITE_30M_MULTIPLIER = 1.25;
|
|
1497
|
+
var OPENAI_CACHE_WRITE_12H_MULTIPLIER = 2.5;
|
|
1498
|
+
function openaiRatesFor(model, promptTokens) {
|
|
1499
|
+
const rate = OPENAI_PRICING[model];
|
|
1500
|
+
if (promptTokens <= OPENAI_LONG_CONTEXT_THRESHOLD) {
|
|
1501
|
+
return rate;
|
|
1502
|
+
}
|
|
1503
|
+
return {
|
|
1504
|
+
promptPerMillion: rate.promptPerMillion * OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER,
|
|
1505
|
+
cachedPerMillion: rate.cachedPerMillion * OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER,
|
|
1506
|
+
candidatePerMillion: rate.candidatePerMillion * OPENAI_LONG_CONTEXT_OUTPUT_MULTIPLIER
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1509
|
+
function openaiTokenCost(model, usage) {
|
|
1510
|
+
const { promptPerMillion, cachedPerMillion, candidatePerMillion } = openaiRatesFor(model, usage.inputTokens);
|
|
1511
|
+
const m = TOKENS_PER_MILLION;
|
|
1512
|
+
const uncachedTokens = Math.max(0, usage.inputTokens - usage.cacheReadTokens - usage.cacheWriteTokens);
|
|
1513
|
+
const write12hTokens = Math.min(usage.cacheWrite12hTokens, usage.cacheWriteTokens);
|
|
1514
|
+
const write30mTokens = Math.max(0, usage.cacheWriteTokens - write12hTokens);
|
|
1515
|
+
const promptCost = uncachedTokens / m * promptPerMillion;
|
|
1516
|
+
const cacheReadCost = usage.cacheReadTokens / m * cachedPerMillion;
|
|
1517
|
+
const cacheWriteCost = write30mTokens / m * promptPerMillion * OPENAI_CACHE_WRITE_30M_MULTIPLIER + write12hTokens / m * promptPerMillion * OPENAI_CACHE_WRITE_12H_MULTIPLIER;
|
|
1518
|
+
const candidateCost = usage.outputTokens / m * candidatePerMillion;
|
|
1519
|
+
const cacheReadFull = usage.cacheReadTokens / m * promptPerMillion;
|
|
1520
|
+
const cacheWriteFull = usage.cacheWriteTokens / m * promptPerMillion;
|
|
1521
|
+
return {
|
|
1522
|
+
costUsd: promptCost + cacheReadCost + cacheWriteCost + candidateCost,
|
|
1523
|
+
savedUsd: cacheReadFull - cacheReadCost + (cacheWriteFull - cacheWriteCost),
|
|
1524
|
+
breakdown: {
|
|
1525
|
+
promptUsd: promptCost,
|
|
1526
|
+
cacheReadUsd: cacheReadCost,
|
|
1527
|
+
cacheWriteUsd: cacheWriteCost,
|
|
1528
|
+
candidateUsd: candidateCost
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1574
1532
|
|
|
1575
1533
|
// ../../foundation-ai/dist/esm/utils/tool-schema.js
|
|
1576
1534
|
var SCHEMA_MAP_KEYS = ["properties", "patternProperties", "$defs", "definitions"];
|
|
@@ -1753,6 +1711,135 @@ function toGeminiSchema(parameters) {
|
|
|
1753
1711
|
});
|
|
1754
1712
|
return translated;
|
|
1755
1713
|
}
|
|
1714
|
+
var OPENAI_UNDROPPABLE_KEYWORDS = ["allOf", "not", "if", "then", "else", "oneOf"];
|
|
1715
|
+
function withNull(node) {
|
|
1716
|
+
if (typeof node.type === "string") {
|
|
1717
|
+
const out = Object.assign(Object.assign({}, node), { type: node.type === "null" ? "null" : [node.type, "null"] });
|
|
1718
|
+
if (Array.isArray(node.enum) && !node.enum.includes(null))
|
|
1719
|
+
out.enum = [...node.enum, null];
|
|
1720
|
+
return out;
|
|
1721
|
+
}
|
|
1722
|
+
if (Array.isArray(node.type)) {
|
|
1723
|
+
if (node.type.includes("null"))
|
|
1724
|
+
return node;
|
|
1725
|
+
const out = Object.assign(Object.assign({}, node), { type: [...node.type, "null"] });
|
|
1726
|
+
if (Array.isArray(node.enum) && !node.enum.includes(null))
|
|
1727
|
+
out.enum = [...node.enum, null];
|
|
1728
|
+
return out;
|
|
1729
|
+
}
|
|
1730
|
+
if (Array.isArray(node.anyOf)) {
|
|
1731
|
+
return node.anyOf.some((b) => isPlainObject2(b) && b.type === "null") ? node : Object.assign(Object.assign({}, node), { anyOf: [...node.anyOf, { type: "null" }] });
|
|
1732
|
+
}
|
|
1733
|
+
return { anyOf: [node, { type: "null" }] };
|
|
1734
|
+
}
|
|
1735
|
+
function toOpenAIStrictSchema(parameters) {
|
|
1736
|
+
const madeNullable = [];
|
|
1737
|
+
const overridden = [];
|
|
1738
|
+
const undroppable = [];
|
|
1739
|
+
const schema = mapSchema(parameters, (node, path) => {
|
|
1740
|
+
for (const keyword of OPENAI_UNDROPPABLE_KEYWORDS) {
|
|
1741
|
+
if (keyword in node)
|
|
1742
|
+
undroppable.push(`${path}/${keyword}`);
|
|
1743
|
+
}
|
|
1744
|
+
const isObjectNode = node.type === "object" || Array.isArray(node.type) && node.type.includes("object") || isPlainObject2(node.properties);
|
|
1745
|
+
if (!isObjectNode)
|
|
1746
|
+
return node;
|
|
1747
|
+
if (node.additionalProperties !== false) {
|
|
1748
|
+
if (node.additionalProperties !== void 0)
|
|
1749
|
+
overridden.push(`${path}/additionalProperties`);
|
|
1750
|
+
node.additionalProperties = false;
|
|
1751
|
+
}
|
|
1752
|
+
if (isPlainObject2(node.properties)) {
|
|
1753
|
+
const names = Object.keys(node.properties);
|
|
1754
|
+
const required = new Set(Array.isArray(node.required) ? node.required : []);
|
|
1755
|
+
const properties = node.properties;
|
|
1756
|
+
for (const name of names) {
|
|
1757
|
+
if (required.has(name))
|
|
1758
|
+
continue;
|
|
1759
|
+
properties[name] = isPlainObject2(properties[name]) ? withNull(properties[name]) : { type: "null" };
|
|
1760
|
+
madeNullable.push(`${path}/properties/${name}`);
|
|
1761
|
+
}
|
|
1762
|
+
node.required = names;
|
|
1763
|
+
}
|
|
1764
|
+
return node;
|
|
1765
|
+
});
|
|
1766
|
+
return { schema, madeNullable, overridden, undroppable };
|
|
1767
|
+
}
|
|
1768
|
+
function enforceOpenAIToolSchema(parameters, toolName) {
|
|
1769
|
+
const { schema, madeNullable, overridden, undroppable } = toOpenAIStrictSchema(parameters);
|
|
1770
|
+
if (madeNullable.length) {
|
|
1771
|
+
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(", ")}`);
|
|
1772
|
+
}
|
|
1773
|
+
if (overridden.length) {
|
|
1774
|
+
logger.warn(`OpenAITransport: tool "${toolName}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${overridden.join(", ")}.`);
|
|
1775
|
+
}
|
|
1776
|
+
if (undroppable.length) {
|
|
1777
|
+
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.`);
|
|
1778
|
+
}
|
|
1779
|
+
return schema;
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
// ../../foundation-ai/dist/esm/transports/budget-exhausted-error.js
|
|
1783
|
+
var BUDGET_EXCEEDED_CODE = "BUDGET_EXCEEDED";
|
|
1784
|
+
var VENDOR_LABELS = Object.freeze({
|
|
1785
|
+
anthropic: "Anthropic",
|
|
1786
|
+
gemini: "Gemini",
|
|
1787
|
+
openai: "OpenAI",
|
|
1788
|
+
chrome: "Chrome"
|
|
1789
|
+
});
|
|
1790
|
+
var BUDGETED_VENDORS = Object.freeze([
|
|
1791
|
+
"anthropic",
|
|
1792
|
+
"gemini",
|
|
1793
|
+
"openai"
|
|
1794
|
+
]);
|
|
1795
|
+
var VENDOR_TYPE_BY_LABEL = new Map(Object.entries(VENDOR_LABELS).map(([type, label]) => [
|
|
1796
|
+
label.toLowerCase(),
|
|
1797
|
+
type
|
|
1798
|
+
]));
|
|
1799
|
+
function vendorTypeOfLabel(label) {
|
|
1800
|
+
if (typeof label !== "string")
|
|
1801
|
+
return void 0;
|
|
1802
|
+
return VENDOR_TYPE_BY_LABEL.get(label.trim().toLowerCase());
|
|
1803
|
+
}
|
|
1804
|
+
var BUDGET_EXCEEDED_STATUS = 402;
|
|
1805
|
+
var DEFAULT_BUDGET_EXHAUSTED_MESSAGE = "You've reached your AI usage limit. Contact your administrator to raise it.";
|
|
1806
|
+
var BudgetExhaustedError = class extends Error {
|
|
1807
|
+
constructor(vendorLabel, budgetUsd, spentUsd, detail, extra) {
|
|
1808
|
+
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.");
|
|
1809
|
+
this.vendorLabel = vendorLabel;
|
|
1810
|
+
this.budgetUsd = budgetUsd;
|
|
1811
|
+
this.spentUsd = spentUsd;
|
|
1812
|
+
this.detail = detail;
|
|
1813
|
+
this.name = "BudgetExhaustedError";
|
|
1814
|
+
this.otherVendorAvailable = extra === null || extra === void 0 ? void 0 : extra.otherVendorAvailable;
|
|
1815
|
+
this.serverVendor = extra === null || extra === void 0 ? void 0 : extra.serverVendor;
|
|
1816
|
+
}
|
|
1817
|
+
};
|
|
1818
|
+
var isBudgetRejection = (status, code) => status === BUDGET_EXCEEDED_STATUS || code === BUDGET_EXCEEDED_CODE;
|
|
1819
|
+
var parseJsonOrUndefined = (text) => {
|
|
1820
|
+
try {
|
|
1821
|
+
return JSON.parse(text);
|
|
1822
|
+
} catch (_a) {
|
|
1823
|
+
return void 0;
|
|
1824
|
+
}
|
|
1825
|
+
};
|
|
1826
|
+
var codeOf = (payload) => {
|
|
1827
|
+
const code = payload === null || payload === void 0 ? void 0 : payload.code;
|
|
1828
|
+
return typeof code === "string" ? code : void 0;
|
|
1829
|
+
};
|
|
1830
|
+
var numberOrUndefined = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
1831
|
+
var booleanOrUndefined = (value) => typeof value === "boolean" ? value : void 0;
|
|
1832
|
+
var stringOrUndefined = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
1833
|
+
function budgetExhaustedFrom(vendorLabel, payload, fallbackDetail) {
|
|
1834
|
+
var _a, _b, _c, _d;
|
|
1835
|
+
const body = typeof payload === "object" && payload !== null ? payload : {};
|
|
1836
|
+
const details = typeof body.details === "object" && body.details !== null ? body.details : {};
|
|
1837
|
+
const detail = typeof body.error === "string" ? body.error : fallbackDetail;
|
|
1838
|
+
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, {
|
|
1839
|
+
otherVendorAvailable: (_c = booleanOrUndefined(body.otherVendorAvailable)) !== null && _c !== void 0 ? _c : booleanOrUndefined(details.otherVendorAvailable),
|
|
1840
|
+
serverVendor: (_d = stringOrUndefined(body.vendor)) !== null && _d !== void 0 ? _d : stringOrUndefined(details.vendor)
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1756
1843
|
|
|
1757
1844
|
// ../../foundation-ai/dist/esm/utils/abort-reason.js
|
|
1758
1845
|
function authoritativeAbortReason(error, timeoutSignal, callerSignal) {
|
|
@@ -1887,6 +1974,8 @@ var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
|
|
|
1887
1974
|
/input token count .* exceeds/i,
|
|
1888
1975
|
/maximum context length/i,
|
|
1889
1976
|
/context[_ ]length[_ ]exceeded/i,
|
|
1977
|
+
// OpenAI Responses: `Your input exceeds the context window of this model.`
|
|
1978
|
+
/exceeds the context window/i,
|
|
1890
1979
|
/too many (input )?tokens/i
|
|
1891
1980
|
]);
|
|
1892
1981
|
var TOKEN_FIGURES = /(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;
|
|
@@ -2005,6 +2094,94 @@ function readFramedBody(stream, onChunk, vendorLabel, stallTimeout) {
|
|
|
2005
2094
|
});
|
|
2006
2095
|
}
|
|
2007
2096
|
|
|
2097
|
+
// ../../foundation-ai/dist/esm/transports/provider-refused.js
|
|
2098
|
+
var PROVIDER_REFUSED_CODE = "PROVIDER_REFUSED";
|
|
2099
|
+
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.";
|
|
2100
|
+
var ProviderRefusedError = class extends Error {
|
|
2101
|
+
constructor(vendorLabel, kind, upstreamStatus, upstreamType, detail) {
|
|
2102
|
+
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.");
|
|
2103
|
+
this.vendorLabel = vendorLabel;
|
|
2104
|
+
this.kind = kind;
|
|
2105
|
+
this.upstreamStatus = upstreamStatus;
|
|
2106
|
+
this.upstreamType = upstreamType;
|
|
2107
|
+
this.detail = detail;
|
|
2108
|
+
this.name = "ProviderRefusedError";
|
|
2109
|
+
}
|
|
2110
|
+
};
|
|
2111
|
+
var ANTHROPIC_SPEND_PHRASES = Object.freeze([
|
|
2112
|
+
/credit balance/i,
|
|
2113
|
+
/usage limit/i,
|
|
2114
|
+
/spend limit/i,
|
|
2115
|
+
/insufficient (credit|funds|balance)/i
|
|
2116
|
+
]);
|
|
2117
|
+
var ANTHROPIC_AUTH_TYPES = Object.freeze([
|
|
2118
|
+
"authentication_error",
|
|
2119
|
+
"permission_error"
|
|
2120
|
+
]);
|
|
2121
|
+
function anthropicErrorBody(payload) {
|
|
2122
|
+
var _a;
|
|
2123
|
+
const outer = typeof payload === "object" && payload !== null ? payload : {};
|
|
2124
|
+
for (const candidate of [
|
|
2125
|
+
outer.error,
|
|
2126
|
+
(_a = outer.details) === null || _a === void 0 ? void 0 : _a.error
|
|
2127
|
+
]) {
|
|
2128
|
+
if (typeof candidate === "object" && candidate !== null) {
|
|
2129
|
+
const { type, message } = candidate;
|
|
2130
|
+
return {
|
|
2131
|
+
type: typeof type === "string" ? type : void 0,
|
|
2132
|
+
message: typeof message === "string" ? message : void 0
|
|
2133
|
+
};
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
return void 0;
|
|
2137
|
+
}
|
|
2138
|
+
function statedKind(payload) {
|
|
2139
|
+
const outer = typeof payload === "object" && payload !== null ? payload : {};
|
|
2140
|
+
const nested = typeof outer.details === "object" && outer.details !== null ? outer.details : {};
|
|
2141
|
+
for (const candidate of [outer.kind, nested.kind]) {
|
|
2142
|
+
if (candidate === "auth" || candidate === "spend")
|
|
2143
|
+
return candidate;
|
|
2144
|
+
}
|
|
2145
|
+
return void 0;
|
|
2146
|
+
}
|
|
2147
|
+
function kindFromEnvelopeType(payload) {
|
|
2148
|
+
const body = anthropicErrorBody(payload);
|
|
2149
|
+
if (!(body === null || body === void 0 ? void 0 : body.type))
|
|
2150
|
+
return void 0;
|
|
2151
|
+
if (ANTHROPIC_AUTH_TYPES.includes(body.type))
|
|
2152
|
+
return "auth";
|
|
2153
|
+
if (body.type === "billing_error")
|
|
2154
|
+
return "spend";
|
|
2155
|
+
return void 0;
|
|
2156
|
+
}
|
|
2157
|
+
function providerRefusalOf(vendor, code, payload) {
|
|
2158
|
+
var _a, _b;
|
|
2159
|
+
if (code === PROVIDER_REFUSED_CODE) {
|
|
2160
|
+
return (_b = (_a = statedKind(payload)) !== null && _a !== void 0 ? _a : kindFromEnvelopeType(payload)) !== null && _b !== void 0 ? _b : "spend";
|
|
2161
|
+
}
|
|
2162
|
+
if (vendor !== "anthropic")
|
|
2163
|
+
return void 0;
|
|
2164
|
+
const structural = kindFromEnvelopeType(payload);
|
|
2165
|
+
if (structural)
|
|
2166
|
+
return structural;
|
|
2167
|
+
const body = anthropicErrorBody(payload);
|
|
2168
|
+
if ((body === null || body === void 0 ? void 0 : body.type) === "invalid_request_error" && body.message) {
|
|
2169
|
+
const message = body.message;
|
|
2170
|
+
if (ANTHROPIC_SPEND_PHRASES.some((phrase) => phrase.test(message)))
|
|
2171
|
+
return "spend";
|
|
2172
|
+
}
|
|
2173
|
+
return void 0;
|
|
2174
|
+
}
|
|
2175
|
+
function providerRefusedFrom(vendorLabel, kind, upstreamStatus, payload, fallbackDetail) {
|
|
2176
|
+
var _a;
|
|
2177
|
+
const body = anthropicErrorBody(payload);
|
|
2178
|
+
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);
|
|
2179
|
+
}
|
|
2180
|
+
function vendorOfTransportLabel(vendorLabel) {
|
|
2181
|
+
const entry = Object.entries(VENDOR_LABELS).find(([, label]) => label === vendorLabel);
|
|
2182
|
+
return entry === null || entry === void 0 ? void 0 : entry[0];
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2008
2185
|
// ../../foundation-ai/dist/esm/transports/retry-hints.js
|
|
2009
2186
|
var MAX_SERVER_REQUESTED_BACKOFF_MS = 6e4;
|
|
2010
2187
|
var MAX_TOTAL_SERVER_REQUESTED_BACKOFF_MS = 12e4;
|
|
@@ -3748,6 +3925,605 @@ GeminiTransport.RETRYABLE_STATUSES = [
|
|
|
3748
3925
|
];
|
|
3749
3926
|
GeminiTransport.BACKOFF_BASE_MS = 1e3;
|
|
3750
3927
|
|
|
3928
|
+
// ../../foundation-ai/dist/esm/transports/openai-transport.js
|
|
3929
|
+
var OPENAI_DIRECT_URL = "https://api.openai.com/v1/responses";
|
|
3930
|
+
var DEFAULT_MODEL3 = "gpt-6-luna";
|
|
3931
|
+
var DEFAULT_TIMEOUT3 = 3e5;
|
|
3932
|
+
var DEFAULT_STALL_TIMEOUT3 = 3e4;
|
|
3933
|
+
var OPENAI_CONTEXT_LIMITS = {
|
|
3934
|
+
"gpt-6-astra": 922e3,
|
|
3935
|
+
"gpt-6.1-sol": 105e4,
|
|
3936
|
+
"gpt-6.1-terra": 105e4,
|
|
3937
|
+
"gpt-6-sol": 105e4,
|
|
3938
|
+
"gpt-6-luna": 105e4
|
|
3939
|
+
};
|
|
3940
|
+
var OPENAI_DEFAULT_TEMPERATURE = 1;
|
|
3941
|
+
var OPENAI_MAX_TEMPERATURE = 2;
|
|
3942
|
+
var OPENAI_EFFORT_NONE_TIERS = ["gpt-6.1-terra", "gpt-6-luna"];
|
|
3943
|
+
var OPENAI_EFFORT = {
|
|
3944
|
+
minimal: "low",
|
|
3945
|
+
low: "low",
|
|
3946
|
+
medium: "medium",
|
|
3947
|
+
high: "high",
|
|
3948
|
+
max: "max"
|
|
3949
|
+
};
|
|
3950
|
+
function openaiEffortFor(model, policy) {
|
|
3951
|
+
if (policy === void 0 || policy === "auto")
|
|
3952
|
+
return void 0;
|
|
3953
|
+
if (policy === "off")
|
|
3954
|
+
return OPENAI_EFFORT_NONE_TIERS.includes(model) ? "none" : "low";
|
|
3955
|
+
return OPENAI_EFFORT[policy];
|
|
3956
|
+
}
|
|
3957
|
+
function toOpenAIToolChoice(choice) {
|
|
3958
|
+
if (!choice || choice === "auto")
|
|
3959
|
+
return void 0;
|
|
3960
|
+
if (choice === "required" || choice === "none")
|
|
3961
|
+
return choice;
|
|
3962
|
+
return { type: "function", name: choice.tool };
|
|
3963
|
+
}
|
|
3964
|
+
function toOpenAITool(tool) {
|
|
3965
|
+
const parameters = tool.enforceSchema ? enforceOpenAIToolSchema(tool.parameters, tool.name) : tool.parameters;
|
|
3966
|
+
return {
|
|
3967
|
+
type: "function",
|
|
3968
|
+
name: tool.name,
|
|
3969
|
+
description: tool.description,
|
|
3970
|
+
parameters,
|
|
3971
|
+
strict: !!tool.enforceSchema
|
|
3972
|
+
};
|
|
3973
|
+
}
|
|
3974
|
+
function assertSupportedOpenAIModel(model) {
|
|
3975
|
+
if (!SUPPORTED_OPENAI_MODEL_IDS.includes(model)) {
|
|
3976
|
+
throw new Error(`OpenAITransport: unsupported model "${model}". Use one of: ${SUPPORTED_OPENAI_MODEL_IDS.join(", ")}.`);
|
|
3977
|
+
}
|
|
3978
|
+
}
|
|
3979
|
+
var OPENAI_MODEL_WARNINGS = {
|
|
3980
|
+
"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.",
|
|
3981
|
+
"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").',
|
|
3982
|
+
"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."
|
|
3983
|
+
};
|
|
3984
|
+
var OPENAI_PROVIDER_KEY = "openai";
|
|
3985
|
+
var CACHE_BREAKPOINT = Object.freeze({ mode: "explicit" });
|
|
3986
|
+
var MAX_HISTORY_BREAKPOINTS = 49;
|
|
3987
|
+
function collectOutput(output) {
|
|
3988
|
+
var _a, _b, _c, _d;
|
|
3989
|
+
const reasoning = [];
|
|
3990
|
+
const summaryParts = [];
|
|
3991
|
+
const textParts = [];
|
|
3992
|
+
const refusals = [];
|
|
3993
|
+
const toolCalls = [];
|
|
3994
|
+
let phase;
|
|
3995
|
+
for (const item of output) {
|
|
3996
|
+
if (item.type === "reasoning") {
|
|
3997
|
+
reasoning.push(item);
|
|
3998
|
+
for (const s of (_a = item.summary) !== null && _a !== void 0 ? _a : []) {
|
|
3999
|
+
if (s.text)
|
|
4000
|
+
summaryParts.push(s.text);
|
|
4001
|
+
}
|
|
4002
|
+
} else if (item.type === "message") {
|
|
4003
|
+
if (typeof item.phase === "string" && phase !== "final_answer")
|
|
4004
|
+
phase = item.phase;
|
|
4005
|
+
for (const part of (_b = item.content) !== null && _b !== void 0 ? _b : []) {
|
|
4006
|
+
if (part.type === "output_text" && typeof part.text === "string")
|
|
4007
|
+
textParts.push(part.text);
|
|
4008
|
+
if (part.type === "refusal" && typeof part.refusal === "string")
|
|
4009
|
+
refusals.push(part.refusal);
|
|
4010
|
+
}
|
|
4011
|
+
} else if (item.type === "function_call") {
|
|
4012
|
+
toolCalls.push({
|
|
4013
|
+
id: String((_d = (_c = item.call_id) !== null && _c !== void 0 ? _c : item.id) !== null && _d !== void 0 ? _d : crypto.randomUUID()),
|
|
4014
|
+
name: String(item.name),
|
|
4015
|
+
args: parseArguments(item.arguments)
|
|
4016
|
+
});
|
|
4017
|
+
}
|
|
4018
|
+
}
|
|
4019
|
+
return { reasoning, summaryParts, textParts, refusals, toolCalls, phase };
|
|
4020
|
+
}
|
|
4021
|
+
function imagePart(att) {
|
|
4022
|
+
const part = {
|
|
4023
|
+
type: "input_image",
|
|
4024
|
+
image_url: `data:${normalizeImageMime(att.mimeType)};base64,${stripImageDataUrl(att.data)}`
|
|
4025
|
+
};
|
|
4026
|
+
if (att.detail)
|
|
4027
|
+
part.detail = att.detail === "medium" ? "auto" : att.detail;
|
|
4028
|
+
return part;
|
|
4029
|
+
}
|
|
4030
|
+
function userContentParts(text, atts) {
|
|
4031
|
+
const parts = [];
|
|
4032
|
+
for (const att of atts) {
|
|
4033
|
+
if (att.kind === "image")
|
|
4034
|
+
parts.push(imagePart(att));
|
|
4035
|
+
}
|
|
4036
|
+
if (text)
|
|
4037
|
+
parts.push({ type: "input_text", text });
|
|
4038
|
+
for (const att of atts) {
|
|
4039
|
+
if (att.kind !== "image")
|
|
4040
|
+
parts.push({ type: "input_text", text: `[File: ${att.name}]
|
|
4041
|
+
${att.content}` });
|
|
4042
|
+
}
|
|
4043
|
+
return parts;
|
|
4044
|
+
}
|
|
4045
|
+
function turnStateOf(msg) {
|
|
4046
|
+
var _a, _b, _c, _d, _e;
|
|
4047
|
+
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];
|
|
4048
|
+
}
|
|
4049
|
+
function replayableReasoning(item) {
|
|
4050
|
+
const { status: _status } = item, rest = __rest(item, ["status"]);
|
|
4051
|
+
return rest;
|
|
4052
|
+
}
|
|
4053
|
+
var OpenAITransport = class _OpenAITransport {
|
|
4054
|
+
constructor(config = {}) {
|
|
4055
|
+
var _a, _b, _c, _d;
|
|
4056
|
+
this.lifetimeCostUsd = 0;
|
|
4057
|
+
this.lifetimeSavingsUsd = 0;
|
|
4058
|
+
this.warnedThinkingClamped = /* @__PURE__ */ new Set();
|
|
4059
|
+
const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL3;
|
|
4060
|
+
assertSupportedOpenAIModel(model);
|
|
4061
|
+
this.model = model;
|
|
4062
|
+
const warning = OPENAI_MODEL_WARNINGS[model];
|
|
4063
|
+
if (warning) {
|
|
4064
|
+
logger.warn(warning);
|
|
4065
|
+
}
|
|
4066
|
+
this.timeout = (_b = config.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT3;
|
|
4067
|
+
this.stallTimeout = (_c = config.stallTimeout) !== null && _c !== void 0 ? _c : DEFAULT_STALL_TIMEOUT3;
|
|
4068
|
+
this.apiKey = config.apiKey;
|
|
4069
|
+
this.serverEndpoint = config.serverEndpoint;
|
|
4070
|
+
this.maxTokens = config.maxTokens;
|
|
4071
|
+
this.reasoningSummary = (_d = config.reasoningSummary) !== null && _d !== void 0 ? _d : "none";
|
|
4072
|
+
}
|
|
4073
|
+
getConfig() {
|
|
4074
|
+
return {
|
|
4075
|
+
provider: "openai",
|
|
4076
|
+
model: this.model,
|
|
4077
|
+
contextLimit: OPENAI_CONTEXT_LIMITS[this.model]
|
|
4078
|
+
};
|
|
4079
|
+
}
|
|
4080
|
+
getLifetimeCost() {
|
|
4081
|
+
return this.lifetimeCostUsd;
|
|
4082
|
+
}
|
|
4083
|
+
getLifetimeSavings() {
|
|
4084
|
+
return this.lifetimeSavingsUsd;
|
|
4085
|
+
}
|
|
4086
|
+
resetLifetimeCost() {
|
|
4087
|
+
this.lifetimeCostUsd = 0;
|
|
4088
|
+
this.lifetimeSavingsUsd = 0;
|
|
4089
|
+
}
|
|
4090
|
+
// ── AITransport (structured prompt) ────────────────────────────────────
|
|
4091
|
+
sendStructuredPrompt(options) {
|
|
4092
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4093
|
+
const { systemPrompt, userPrompt, responseSchema } = options;
|
|
4094
|
+
const message = yield this.sendChatMessage([], userPrompt, {
|
|
4095
|
+
systemPrompt,
|
|
4096
|
+
responseSchema
|
|
4097
|
+
});
|
|
4098
|
+
return message.content;
|
|
4099
|
+
});
|
|
4100
|
+
}
|
|
4101
|
+
// ── ChatTransport (multi-turn chat) ────────────────────────────────────
|
|
4102
|
+
sendChatMessage(history, userMessage, options) {
|
|
4103
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4104
|
+
const body = this.buildRequestBody(history, userMessage, options);
|
|
4105
|
+
const response = yield this.post(body, options === null || options === void 0 ? void 0 : options.signal);
|
|
4106
|
+
const message = this.fromResponse(response, body.max_output_tokens);
|
|
4107
|
+
this.restoreOptionalFields(message, options);
|
|
4108
|
+
return message;
|
|
4109
|
+
});
|
|
4110
|
+
}
|
|
4111
|
+
/** Undo strict mode's absent-becomes-null, in tool arguments and in a `responseSchema` answer. */
|
|
4112
|
+
restoreOptionalFields(message, options) {
|
|
4113
|
+
var _a;
|
|
4114
|
+
const pointersByTool = strictNullPointersByTool(options === null || options === void 0 ? void 0 : options.tools);
|
|
4115
|
+
for (const call of (_a = message.toolCalls) !== null && _a !== void 0 ? _a : []) {
|
|
4116
|
+
const pointers = pointersByTool.get(call.name);
|
|
4117
|
+
if (pointers)
|
|
4118
|
+
stripStrictNulls(call.args, pointers);
|
|
4119
|
+
}
|
|
4120
|
+
if (!(options === null || options === void 0 ? void 0 : options.responseSchema) || !message.content)
|
|
4121
|
+
return;
|
|
4122
|
+
const { madeNullable } = toOpenAIStrictSchema(options.responseSchema);
|
|
4123
|
+
if (!madeNullable.length)
|
|
4124
|
+
return;
|
|
4125
|
+
try {
|
|
4126
|
+
const parsed = JSON.parse(message.content);
|
|
4127
|
+
stripStrictNulls(parsed, madeNullable);
|
|
4128
|
+
message.content = JSON.stringify(parsed);
|
|
4129
|
+
} catch (_b) {
|
|
4130
|
+
}
|
|
4131
|
+
}
|
|
4132
|
+
/**
|
|
4133
|
+
* The Responses request body for a turn. Public for tests and for hosts that want to inspect the
|
|
4134
|
+
* exact wire shape; not part of the stable contract.
|
|
4135
|
+
*
|
|
4136
|
+
* @internal
|
|
4137
|
+
*/
|
|
4138
|
+
buildRequestBody(history, userMessage, options) {
|
|
4139
|
+
var _a, _b;
|
|
4140
|
+
const scope = (options === null || options === void 0 ? void 0 : options.cachePolicy) && options.cachePolicy.scope !== "default" ? options.cachePolicy.scope : void 0;
|
|
4141
|
+
const input = [];
|
|
4142
|
+
if (options === null || options === void 0 ? void 0 : options.systemPrompt) {
|
|
4143
|
+
const part = { type: "input_text", text: options.systemPrompt };
|
|
4144
|
+
if (scope)
|
|
4145
|
+
part.prompt_cache_breakpoint = CACHE_BREAKPOINT;
|
|
4146
|
+
input.push({ type: "message", role: "developer", content: [part] });
|
|
4147
|
+
}
|
|
4148
|
+
input.push(...this.toInputItems(history, userMessage, options === null || options === void 0 ? void 0 : options.attachments));
|
|
4149
|
+
if (scope === "history")
|
|
4150
|
+
this.markHistoryBreakpoints(input);
|
|
4151
|
+
if (options === null || options === void 0 ? void 0 : options.tailContext) {
|
|
4152
|
+
input.push({
|
|
4153
|
+
type: "message",
|
|
4154
|
+
role: "user",
|
|
4155
|
+
content: [{ type: "input_text", text: options.tailContext }]
|
|
4156
|
+
});
|
|
4157
|
+
}
|
|
4158
|
+
const body = {
|
|
4159
|
+
model: this.model,
|
|
4160
|
+
input,
|
|
4161
|
+
store: false,
|
|
4162
|
+
// Encrypted reasoning is what makes a stateless tool loop keep its chain of thought.
|
|
4163
|
+
include: ["reasoning.encrypted_content"]
|
|
4164
|
+
};
|
|
4165
|
+
if (scope) {
|
|
4166
|
+
body.prompt_cache_options = { mode: "explicit", ttl: "30m" };
|
|
4167
|
+
}
|
|
4168
|
+
if ((_a = options === null || options === void 0 ? void 0 : options.tools) === null || _a === void 0 ? void 0 : _a.length) {
|
|
4169
|
+
body.tools = options.tools.map(toOpenAITool);
|
|
4170
|
+
const toolChoice = toOpenAIToolChoice(options.toolChoice);
|
|
4171
|
+
if (toolChoice)
|
|
4172
|
+
body.tool_choice = toolChoice;
|
|
4173
|
+
}
|
|
4174
|
+
this.warnIfThinkingClamped(options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
4175
|
+
const effort = openaiEffortFor(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
|
|
4176
|
+
if (effort) {
|
|
4177
|
+
body.reasoning = effort === "none" || this.reasoningSummary === "none" ? { effort } : { effort, summary: this.reasoningSummary };
|
|
4178
|
+
} else if (this.reasoningSummary !== "none") {
|
|
4179
|
+
body.reasoning = { summary: this.reasoningSummary };
|
|
4180
|
+
}
|
|
4181
|
+
if ((options === null || options === void 0 ? void 0 : options.temperature) != null && effort === "none") {
|
|
4182
|
+
body.temperature = scaleTemperature(options.temperature, {
|
|
4183
|
+
defaultTemp: OPENAI_DEFAULT_TEMPERATURE,
|
|
4184
|
+
maxTemp: OPENAI_MAX_TEMPERATURE
|
|
4185
|
+
});
|
|
4186
|
+
}
|
|
4187
|
+
const maxTokens = (_b = options === null || options === void 0 ? void 0 : options.maxTokens) !== null && _b !== void 0 ? _b : this.maxTokens;
|
|
4188
|
+
if (maxTokens != null)
|
|
4189
|
+
body.max_output_tokens = maxTokens;
|
|
4190
|
+
if (options === null || options === void 0 ? void 0 : options.responseSchema) {
|
|
4191
|
+
body.text = {
|
|
4192
|
+
format: {
|
|
4193
|
+
type: "json_schema",
|
|
4194
|
+
name: "response",
|
|
4195
|
+
schema: toOpenAIStrictSchema(options.responseSchema).schema,
|
|
4196
|
+
strict: true
|
|
4197
|
+
}
|
|
4198
|
+
};
|
|
4199
|
+
}
|
|
4200
|
+
return body;
|
|
4201
|
+
}
|
|
4202
|
+
// ── Private helpers ────────────────────────────────────────────────────
|
|
4203
|
+
warnIfThinkingClamped(policy) {
|
|
4204
|
+
if (!policy || this.warnedThinkingClamped.has(policy))
|
|
4205
|
+
return;
|
|
4206
|
+
if (policy === "off" && !OPENAI_EFFORT_NONE_TIERS.includes(this.model)) {
|
|
4207
|
+
this.warnedThinkingClamped.add(policy);
|
|
4208
|
+
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.`);
|
|
4209
|
+
} else if (policy === "minimal") {
|
|
4210
|
+
this.warnedThinkingClamped.add(policy);
|
|
4211
|
+
logger.warn(`OpenAITransport: thinkingPolicy 'minimal' sent as effort 'low' \u2014 OpenAI has no 'minimal' effort.`);
|
|
4212
|
+
}
|
|
4213
|
+
}
|
|
4214
|
+
toInputItems(history, userMessage, attachments) {
|
|
4215
|
+
var _a, _b, _c, _d, _e;
|
|
4216
|
+
const items = [];
|
|
4217
|
+
const replayedReasoning = /* @__PURE__ */ new Set();
|
|
4218
|
+
for (const msg of history) {
|
|
4219
|
+
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.
|
|
4220
|
+
msg.excludeFromProvider || msg.thinking)
|
|
4221
|
+
continue;
|
|
4222
|
+
if (msg.toolResult) {
|
|
4223
|
+
items.push(this.toFunctionCallOutput(msg));
|
|
4224
|
+
continue;
|
|
4225
|
+
}
|
|
4226
|
+
if (msg.role === "user") {
|
|
4227
|
+
const content2 = userContentParts(msg.content, (_a = msg.attachments) !== null && _a !== void 0 ? _a : []);
|
|
4228
|
+
if (content2.length)
|
|
4229
|
+
items.push({ type: "message", role: "user", content: content2 });
|
|
4230
|
+
continue;
|
|
4231
|
+
}
|
|
4232
|
+
const state = turnStateOf(msg);
|
|
4233
|
+
if ((state === null || state === void 0 ? void 0 : state.model) === this.model) {
|
|
4234
|
+
for (const r of (_b = state.reasoning) !== null && _b !== void 0 ? _b : []) {
|
|
4235
|
+
const key = (_c = r.id) !== null && _c !== void 0 ? _c : r.encrypted_content;
|
|
4236
|
+
if (replayedReasoning.has(key))
|
|
4237
|
+
continue;
|
|
4238
|
+
replayedReasoning.add(key);
|
|
4239
|
+
items.push(replayableReasoning(r));
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
if (msg.content) {
|
|
4243
|
+
const item = {
|
|
4244
|
+
type: "message",
|
|
4245
|
+
role: "assistant",
|
|
4246
|
+
content: [{ type: "output_text", text: msg.content }]
|
|
4247
|
+
};
|
|
4248
|
+
if (state === null || state === void 0 ? void 0 : state.phase)
|
|
4249
|
+
item.phase = state.phase;
|
|
4250
|
+
items.push(item);
|
|
4251
|
+
}
|
|
4252
|
+
for (const tc of (_d = msg.toolCalls) !== null && _d !== void 0 ? _d : []) {
|
|
4253
|
+
items.push({
|
|
4254
|
+
type: "function_call",
|
|
4255
|
+
call_id: tc.id,
|
|
4256
|
+
name: tc.name,
|
|
4257
|
+
arguments: JSON.stringify((_e = tc.args) !== null && _e !== void 0 ? _e : {})
|
|
4258
|
+
});
|
|
4259
|
+
}
|
|
4260
|
+
}
|
|
4261
|
+
const content = userContentParts(userMessage, attachments !== null && attachments !== void 0 ? attachments : []);
|
|
4262
|
+
if (content.length)
|
|
4263
|
+
items.push({ type: "message", role: "user", content });
|
|
4264
|
+
return items;
|
|
4265
|
+
}
|
|
4266
|
+
/**
|
|
4267
|
+
* A tool result, always as content parts — never the plain-string form. A cache hit needs the
|
|
4268
|
+
* whole rendered prefix to match, and a breakpoint can only sit on a part, so a string output
|
|
4269
|
+
* that became an array when it carried one would render differently on the next turn.
|
|
4270
|
+
*/
|
|
4271
|
+
toFunctionCallOutput(msg) {
|
|
4272
|
+
var _a;
|
|
4273
|
+
const result = msg.toolResult;
|
|
4274
|
+
const images = (_a = result.attachments) !== null && _a !== void 0 ? _a : [];
|
|
4275
|
+
return {
|
|
4276
|
+
type: "function_call_output",
|
|
4277
|
+
call_id: result.toolCallId,
|
|
4278
|
+
output: [{ type: "input_text", text: result.content }, ...images.map(imagePart)]
|
|
4279
|
+
};
|
|
4280
|
+
}
|
|
4281
|
+
/**
|
|
4282
|
+
* Put a history-scope breakpoint on every stored item that can carry one — a user message's last
|
|
4283
|
+
* text part or a tool result's — up to the latest `MAX_HISTORY_BREAKPOINTS`.
|
|
4284
|
+
*
|
|
4285
|
+
* One breakpoint on the last item (Anthropic's shape) never hits on OpenAI: lookup checks only the
|
|
4286
|
+
* breakpoints in this request, and the last item moves every turn, so the previous turn's boundary
|
|
4287
|
+
* was unmarked and every turn rewrote the whole history to cache. Marking each boundary keeps the
|
|
4288
|
+
* previous turn's in the request. Assistant items cannot carry one.
|
|
4289
|
+
*/
|
|
4290
|
+
markHistoryBreakpoints(input) {
|
|
4291
|
+
let marked = 0;
|
|
4292
|
+
for (let i = input.length - 1; i >= 0 && marked < MAX_HISTORY_BREAKPOINTS; i -= 1) {
|
|
4293
|
+
const item = input[i];
|
|
4294
|
+
if (item.role === "developer")
|
|
4295
|
+
continue;
|
|
4296
|
+
const key = item.type === "function_call_output" ? "output" : item.type === "message" && item.role !== "assistant" ? "content" : void 0;
|
|
4297
|
+
if (!key)
|
|
4298
|
+
continue;
|
|
4299
|
+
const parts = [...item[key]];
|
|
4300
|
+
let textIndex = -1;
|
|
4301
|
+
for (let j = parts.length - 1; j >= 0; j -= 1) {
|
|
4302
|
+
if (parts[j].type === "input_text") {
|
|
4303
|
+
textIndex = j;
|
|
4304
|
+
break;
|
|
4305
|
+
}
|
|
4306
|
+
}
|
|
4307
|
+
if (textIndex < 0)
|
|
4308
|
+
continue;
|
|
4309
|
+
parts[textIndex] = Object.assign(Object.assign({}, parts[textIndex]), { prompt_cache_breakpoint: CACHE_BREAKPOINT });
|
|
4310
|
+
input[i] = Object.assign(Object.assign({}, item), { [key]: parts });
|
|
4311
|
+
marked += 1;
|
|
4312
|
+
}
|
|
4313
|
+
}
|
|
4314
|
+
usageFromResponse(usage) {
|
|
4315
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
|
|
4316
|
+
if (!usage)
|
|
4317
|
+
return {};
|
|
4318
|
+
const u = usage;
|
|
4319
|
+
const cacheReadTokens = (_b = (_a = u.input_tokens_details) === null || _a === void 0 ? void 0 : _a.cached_tokens) !== null && _b !== void 0 ? _b : 0;
|
|
4320
|
+
const cacheWriteTokens = (_d = (_c = u.input_tokens_details) === null || _c === void 0 ? void 0 : _c.cache_write_tokens) !== null && _d !== void 0 ? _d : 0;
|
|
4321
|
+
const { costUsd, savedUsd } = openaiTokenCost(this.model, {
|
|
4322
|
+
inputTokens: (_e = u.input_tokens) !== null && _e !== void 0 ? _e : 0,
|
|
4323
|
+
outputTokens: (_f = u.output_tokens) !== null && _f !== void 0 ? _f : 0,
|
|
4324
|
+
cacheReadTokens,
|
|
4325
|
+
cacheWriteTokens,
|
|
4326
|
+
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
|
|
4327
|
+
});
|
|
4328
|
+
this.lifetimeCostUsd += costUsd;
|
|
4329
|
+
this.lifetimeSavingsUsd += savedUsd;
|
|
4330
|
+
const dp = _OpenAITransport.COST_DECIMAL_PLACES;
|
|
4331
|
+
console.log(`--- OpenAI Token Usage (${this.model}) ---`);
|
|
4332
|
+
console.log(`Input Tokens: ${(_k = u.input_tokens) !== null && _k !== void 0 ? _k : 0} (${cacheReadTokens} cached, ${cacheWriteTokens} written)`);
|
|
4333
|
+
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)`);
|
|
4334
|
+
console.log(`Total Cost: $${costUsd.toFixed(dp)}`);
|
|
4335
|
+
console.log(`Cache Saved: $${savedUsd.toFixed(dp)} (lifetime $${this.lifetimeSavingsUsd.toFixed(dp)})`);
|
|
4336
|
+
console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(dp)}`);
|
|
4337
|
+
console.log("--------------------------");
|
|
4338
|
+
return {
|
|
4339
|
+
// Responses' input_tokens already INCLUDES cached and written tokens, matching what
|
|
4340
|
+
// ChatMessage.inputTokens means on Gemini (the whole prompt).
|
|
4341
|
+
inputTokens: u.input_tokens,
|
|
4342
|
+
// Reasoning tokens are already inside output_tokens — no folding needed (unlike Gemini).
|
|
4343
|
+
outputTokens: u.output_tokens,
|
|
4344
|
+
thoughtsTokens: (_p = u.output_tokens_details) === null || _p === void 0 ? void 0 : _p.reasoning_tokens,
|
|
4345
|
+
cacheReadTokens: (_q = u.input_tokens_details) === null || _q === void 0 ? void 0 : _q.cached_tokens,
|
|
4346
|
+
cacheWriteTokens: (_r = u.input_tokens_details) === null || _r === void 0 ? void 0 : _r.cache_write_tokens,
|
|
4347
|
+
cost: costUsd
|
|
4348
|
+
};
|
|
4349
|
+
}
|
|
4350
|
+
fromResponse(response, effectiveMaxTokens) {
|
|
4351
|
+
var _a, _b;
|
|
4352
|
+
const usage = this.usageFromResponse(response.usage);
|
|
4353
|
+
const output = (_a = response.output) !== null && _a !== void 0 ? _a : [];
|
|
4354
|
+
const { reasoning, summaryParts, textParts, refusals, toolCalls, phase } = collectOutput(output);
|
|
4355
|
+
const state = { model: this.model };
|
|
4356
|
+
if (reasoning.length)
|
|
4357
|
+
state.reasoning = reasoning;
|
|
4358
|
+
if (phase)
|
|
4359
|
+
state.phase = phase;
|
|
4360
|
+
const providerMetadata = { [OPENAI_PROVIDER_KEY]: state };
|
|
4361
|
+
if (toolCalls.length)
|
|
4362
|
+
toolCalls[0].providerMetadata = providerMetadata;
|
|
4363
|
+
const narration = textParts.join("");
|
|
4364
|
+
const summary = summaryParts.join("\n\n");
|
|
4365
|
+
const base = Object.assign({ role: "assistant", content: narration, reasoning: summary || void 0 }, toolCalls.length ? { toolCalls } : { providerMetadata });
|
|
4366
|
+
const status = response.status;
|
|
4367
|
+
if (status === "failed")
|
|
4368
|
+
throw failedResponseError(this.model, response.error);
|
|
4369
|
+
const incompleteReason = (_b = response.incomplete_details) === null || _b === void 0 ? void 0 : _b.reason;
|
|
4370
|
+
const finishReason = refusals.length && !narration && !toolCalls.length ? "refusal" : status === "incomplete" ? incompleteReason !== null && incompleteReason !== void 0 ? incompleteReason : "incomplete" : status;
|
|
4371
|
+
if (finishReason === "refusal") {
|
|
4372
|
+
logger.warn("OpenAITransport: the model refused", {
|
|
4373
|
+
model: this.model,
|
|
4374
|
+
refusal: refusals.join("\n")
|
|
4375
|
+
});
|
|
4376
|
+
}
|
|
4377
|
+
if (status === "incomplete" && incompleteReason === "content_filter") {
|
|
4378
|
+
base.content = "";
|
|
4379
|
+
delete base.toolCalls;
|
|
4380
|
+
logger.warn("OpenAITransport: response stopped by the content filter; partial output dropped", {
|
|
4381
|
+
model: this.model,
|
|
4382
|
+
outputTypes: output.map((o) => o.type)
|
|
4383
|
+
});
|
|
4384
|
+
}
|
|
4385
|
+
if (status === "incomplete" && incompleteReason === "max_output_tokens") {
|
|
4386
|
+
if (toolCalls.length || !narration.trim()) {
|
|
4387
|
+
throw new ResponseTruncatedError(this.model, effectiveMaxTokens, usage.outputTokens, toolCalls.map((tc) => tc.name));
|
|
4388
|
+
}
|
|
4389
|
+
}
|
|
4390
|
+
if (!toolCalls.length && !narration && !summary && finishReason !== "refusal" && finishReason !== "content_filter") {
|
|
4391
|
+
logger.warn("OpenAITransport: blank response", {
|
|
4392
|
+
model: this.model,
|
|
4393
|
+
status,
|
|
4394
|
+
incompleteReason,
|
|
4395
|
+
outputTypes: output.map((o) => o.type),
|
|
4396
|
+
usage: response.usage
|
|
4397
|
+
});
|
|
4398
|
+
}
|
|
4399
|
+
if (usage.inputTokens != null)
|
|
4400
|
+
base.inputTokens = usage.inputTokens;
|
|
4401
|
+
if (usage.outputTokens != null)
|
|
4402
|
+
base.outputTokens = usage.outputTokens;
|
|
4403
|
+
if (usage.cacheReadTokens != null)
|
|
4404
|
+
base.cacheReadTokens = usage.cacheReadTokens;
|
|
4405
|
+
if (usage.cacheWriteTokens != null)
|
|
4406
|
+
base.cacheWriteTokens = usage.cacheWriteTokens;
|
|
4407
|
+
if (usage.cost != null)
|
|
4408
|
+
base.cost = usage.cost;
|
|
4409
|
+
base.model = this.model;
|
|
4410
|
+
if (finishReason != null || usage.thoughtsTokens != null) {
|
|
4411
|
+
base.responseMeta = {
|
|
4412
|
+
finishReason,
|
|
4413
|
+
thoughtsTokens: usage.thoughtsTokens,
|
|
4414
|
+
parts: {
|
|
4415
|
+
functionCall: toolCalls.length,
|
|
4416
|
+
thought: summaryParts.length,
|
|
4417
|
+
text: textParts.length
|
|
4418
|
+
}
|
|
4419
|
+
};
|
|
4420
|
+
}
|
|
4421
|
+
return base;
|
|
4422
|
+
}
|
|
4423
|
+
buildEndpoint(body) {
|
|
4424
|
+
if (this.apiKey) {
|
|
4425
|
+
return {
|
|
4426
|
+
url: OPENAI_DIRECT_URL,
|
|
4427
|
+
payload: body,
|
|
4428
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}` },
|
|
4429
|
+
credentials: "omit"
|
|
4430
|
+
};
|
|
4431
|
+
}
|
|
4432
|
+
if (this.serverEndpoint) {
|
|
4433
|
+
return {
|
|
4434
|
+
url: this.serverEndpoint,
|
|
4435
|
+
payload: body,
|
|
4436
|
+
// Opt in to the proxy's NDJSON heartbeat framing.
|
|
4437
|
+
headers: { "Content-Type": "application/json", Accept: "application/x-ndjson" },
|
|
4438
|
+
credentials: "include"
|
|
4439
|
+
};
|
|
4440
|
+
}
|
|
4441
|
+
throw new Error("OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.");
|
|
4442
|
+
}
|
|
4443
|
+
post(body, signal) {
|
|
4444
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4445
|
+
const { url, payload, headers, credentials } = this.buildEndpoint(body);
|
|
4446
|
+
return yield postWithRetry({
|
|
4447
|
+
url,
|
|
4448
|
+
headers,
|
|
4449
|
+
body: payload,
|
|
4450
|
+
credentials,
|
|
4451
|
+
vendorLabel: VENDOR_LABELS.openai,
|
|
4452
|
+
retryableStatuses: _OpenAITransport.RETRYABLE_STATUSES,
|
|
4453
|
+
timeout: this.timeout,
|
|
4454
|
+
stallTimeout: this.stallTimeout,
|
|
4455
|
+
backoffBaseMs: _OpenAITransport.BACKOFF_BASE_MS,
|
|
4456
|
+
signal
|
|
4457
|
+
});
|
|
4458
|
+
});
|
|
4459
|
+
}
|
|
4460
|
+
};
|
|
4461
|
+
OpenAITransport.COST_DECIMAL_PLACES = 6;
|
|
4462
|
+
OpenAITransport.RATE_LIMIT_STATUS = 429;
|
|
4463
|
+
OpenAITransport.SERVER_ERROR_STATUS = 500;
|
|
4464
|
+
OpenAITransport.BAD_GATEWAY_STATUS = 502;
|
|
4465
|
+
OpenAITransport.SERVICE_UNAVAILABLE_STATUS = 503;
|
|
4466
|
+
OpenAITransport.RETRYABLE_STATUSES = [
|
|
4467
|
+
OpenAITransport.RATE_LIMIT_STATUS,
|
|
4468
|
+
OpenAITransport.SERVER_ERROR_STATUS,
|
|
4469
|
+
OpenAITransport.BAD_GATEWAY_STATUS,
|
|
4470
|
+
OpenAITransport.SERVICE_UNAVAILABLE_STATUS
|
|
4471
|
+
];
|
|
4472
|
+
OpenAITransport.BACKOFF_BASE_MS = 1e3;
|
|
4473
|
+
function failedResponseError(model, error) {
|
|
4474
|
+
const { code, message } = error !== null && error !== void 0 ? error : {};
|
|
4475
|
+
return new Error(`OpenAITransport: ${model} response failed${code ? ` (${code})` : ""}: ${message !== null && message !== void 0 ? message : "no error detail"}`);
|
|
4476
|
+
}
|
|
4477
|
+
function stripStrictNulls(value, pointers) {
|
|
4478
|
+
for (const pointer of pointers) {
|
|
4479
|
+
deleteNullAt(value, pointer.split("/").slice(1));
|
|
4480
|
+
}
|
|
4481
|
+
}
|
|
4482
|
+
function deleteNullAt(value, segments) {
|
|
4483
|
+
if (!value || typeof value !== "object")
|
|
4484
|
+
return;
|
|
4485
|
+
const [head, ...rest] = segments;
|
|
4486
|
+
if (head === "items" && Array.isArray(value)) {
|
|
4487
|
+
for (const element of value)
|
|
4488
|
+
deleteNullAt(element, rest);
|
|
4489
|
+
return;
|
|
4490
|
+
}
|
|
4491
|
+
if (head !== "properties" || !rest.length || Array.isArray(value))
|
|
4492
|
+
return;
|
|
4493
|
+
const [name, ...below] = rest;
|
|
4494
|
+
const record = value;
|
|
4495
|
+
if (!below.length) {
|
|
4496
|
+
if (record[name] === null)
|
|
4497
|
+
delete record[name];
|
|
4498
|
+
return;
|
|
4499
|
+
}
|
|
4500
|
+
deleteNullAt(record[name], below);
|
|
4501
|
+
}
|
|
4502
|
+
function strictNullPointersByTool(tools) {
|
|
4503
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
4504
|
+
for (const tool of tools !== null && tools !== void 0 ? tools : []) {
|
|
4505
|
+
if (!tool.enforceSchema)
|
|
4506
|
+
continue;
|
|
4507
|
+
const { madeNullable } = toOpenAIStrictSchema(tool.parameters);
|
|
4508
|
+
if (madeNullable.length)
|
|
4509
|
+
byTool.set(tool.name, madeNullable);
|
|
4510
|
+
}
|
|
4511
|
+
return byTool;
|
|
4512
|
+
}
|
|
4513
|
+
function parseArguments(raw) {
|
|
4514
|
+
if (raw && typeof raw === "object")
|
|
4515
|
+
return raw;
|
|
4516
|
+
if (typeof raw !== "string" || !raw.trim())
|
|
4517
|
+
return {};
|
|
4518
|
+
try {
|
|
4519
|
+
const parsed = JSON.parse(raw);
|
|
4520
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
4521
|
+
} catch (_a) {
|
|
4522
|
+
logger.warn("OpenAITransport: function_call arguments are not valid JSON", { raw });
|
|
4523
|
+
return {};
|
|
4524
|
+
}
|
|
4525
|
+
}
|
|
4526
|
+
|
|
3751
4527
|
// ../../foundation-ai/dist/esm/ai-provider.js
|
|
3752
4528
|
function isObservableAIProviderRegistry(r) {
|
|
3753
4529
|
return typeof r.subscribe === "function";
|
|
@@ -9693,7 +10469,10 @@ ${tailBody}
|
|
|
9693
10469
|
inputTokens: void 0,
|
|
9694
10470
|
outputTokens: void 0,
|
|
9695
10471
|
cacheReadTokens: void 0,
|
|
9696
|
-
cacheWriteTokens: void 0
|
|
10472
|
+
cacheWriteTokens: void 0,
|
|
10473
|
+
// Round-trip state (OpenAI's encrypted reasoning) belongs to the message that is replayed;
|
|
10474
|
+
// a display copy is never sent, so a copy here is only stored and exported again.
|
|
10475
|
+
providerMetadata: void 0
|
|
9697
10476
|
};
|
|
9698
10477
|
if (reasoning) {
|
|
9699
10478
|
this.appendToHistory({
|
|
@@ -12878,11 +13657,17 @@ function collectRows(messages, depth, subAgentOf) {
|
|
|
12878
13657
|
MALFORMED_CALL_NUDGE,
|
|
12879
13658
|
MutableAIProviderRegistry,
|
|
12880
13659
|
NOOP_ACTIVITY_BUS,
|
|
13660
|
+
OPENAI_CACHE_WRITE_12H_MULTIPLIER,
|
|
13661
|
+
OPENAI_CACHE_WRITE_30M_MULTIPLIER,
|
|
13662
|
+
OPENAI_LONG_CONTEXT_THRESHOLD,
|
|
13663
|
+
OpenAIProvider,
|
|
13664
|
+
OpenAITransport,
|
|
12881
13665
|
OrchestratingDriver,
|
|
12882
13666
|
PROVIDER_REFUSED_CODE,
|
|
12883
13667
|
ProviderRefusedError,
|
|
12884
13668
|
SUPPORTED_ANTHROPIC_MODEL_IDS,
|
|
12885
13669
|
SUPPORTED_GEMINI_MODEL_IDS,
|
|
13670
|
+
SUPPORTED_OPENAI_MODEL_IDS,
|
|
12886
13671
|
UNROUTABLE_INSTRUCTION,
|
|
12887
13672
|
UNROUTABLE_PLACEHOLDER,
|
|
12888
13673
|
addUsage,
|
|
@@ -12911,6 +13696,8 @@ function collectRows(messages, depth, subAgentOf) {
|
|
|
12911
13696
|
isTerminalAIServiceRefusal,
|
|
12912
13697
|
lifetimeDebugLog,
|
|
12913
13698
|
messageUsage,
|
|
13699
|
+
openaiRatesFor,
|
|
13700
|
+
openaiTokenCost,
|
|
12914
13701
|
resolveAITiers,
|
|
12915
13702
|
restoreMachine,
|
|
12916
13703
|
strictFallbackAgent,
|