@genesislcap/ai-assistant 15.90.1-GENC-1829.2 → 15.90.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1161,6 +1161,155 @@ var GeminiProvider = class {
1161
1161
  }
1162
1162
  };
1163
1163
 
1164
+ // ../../foundation-ai/dist/esm/transports/budget-exhausted-error.js
1165
+ var BUDGET_EXCEEDED_CODE = "BUDGET_EXCEEDED";
1166
+ var VENDOR_LABELS = Object.freeze({
1167
+ anthropic: "Anthropic",
1168
+ gemini: "Gemini",
1169
+ openai: "OpenAI",
1170
+ chrome: "Chrome"
1171
+ });
1172
+ var BUDGETED_VENDORS = Object.freeze([
1173
+ "anthropic",
1174
+ "gemini"
1175
+ ]);
1176
+ var VENDOR_TYPE_BY_LABEL = new Map(Object.entries(VENDOR_LABELS).map(([type, label]) => [
1177
+ label.toLowerCase(),
1178
+ type
1179
+ ]));
1180
+ function vendorTypeOfLabel(label) {
1181
+ if (typeof label !== "string")
1182
+ return void 0;
1183
+ return VENDOR_TYPE_BY_LABEL.get(label.trim().toLowerCase());
1184
+ }
1185
+ var BUDGET_EXCEEDED_STATUS = 402;
1186
+ var DEFAULT_BUDGET_EXHAUSTED_MESSAGE = "You've reached your AI usage limit. Contact your administrator to raise it.";
1187
+ var BudgetExhaustedError = class extends Error {
1188
+ constructor(vendorLabel, budgetUsd, spentUsd, detail, extra) {
1189
+ 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.");
1190
+ this.vendorLabel = vendorLabel;
1191
+ this.budgetUsd = budgetUsd;
1192
+ this.spentUsd = spentUsd;
1193
+ this.detail = detail;
1194
+ this.name = "BudgetExhaustedError";
1195
+ this.otherVendorAvailable = extra === null || extra === void 0 ? void 0 : extra.otherVendorAvailable;
1196
+ this.serverVendor = extra === null || extra === void 0 ? void 0 : extra.serverVendor;
1197
+ }
1198
+ };
1199
+ var isBudgetRejection = (status, code) => status === BUDGET_EXCEEDED_STATUS || code === BUDGET_EXCEEDED_CODE;
1200
+ var parseJsonOrUndefined = (text) => {
1201
+ try {
1202
+ return JSON.parse(text);
1203
+ } catch (_a) {
1204
+ return void 0;
1205
+ }
1206
+ };
1207
+ var codeOf = (payload) => {
1208
+ const code = payload === null || payload === void 0 ? void 0 : payload.code;
1209
+ return typeof code === "string" ? code : void 0;
1210
+ };
1211
+ var numberOrUndefined = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1212
+ var booleanOrUndefined = (value) => typeof value === "boolean" ? value : void 0;
1213
+ var stringOrUndefined = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
1214
+ function budgetExhaustedFrom(vendorLabel, payload, fallbackDetail) {
1215
+ var _a, _b, _c, _d;
1216
+ const body = typeof payload === "object" && payload !== null ? payload : {};
1217
+ const details = typeof body.details === "object" && body.details !== null ? body.details : {};
1218
+ const detail = typeof body.error === "string" ? body.error : fallbackDetail;
1219
+ 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, {
1220
+ otherVendorAvailable: (_c = booleanOrUndefined(body.otherVendorAvailable)) !== null && _c !== void 0 ? _c : booleanOrUndefined(details.otherVendorAvailable),
1221
+ serverVendor: (_d = stringOrUndefined(body.vendor)) !== null && _d !== void 0 ? _d : stringOrUndefined(details.vendor)
1222
+ });
1223
+ }
1224
+
1225
+ // ../../foundation-ai/dist/esm/transports/provider-refused.js
1226
+ var PROVIDER_REFUSED_CODE = "PROVIDER_REFUSED";
1227
+ 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.";
1228
+ var ProviderRefusedError = class extends Error {
1229
+ constructor(vendorLabel, kind, upstreamStatus, upstreamType, detail) {
1230
+ 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.");
1231
+ this.vendorLabel = vendorLabel;
1232
+ this.kind = kind;
1233
+ this.upstreamStatus = upstreamStatus;
1234
+ this.upstreamType = upstreamType;
1235
+ this.detail = detail;
1236
+ this.name = "ProviderRefusedError";
1237
+ }
1238
+ };
1239
+ var ANTHROPIC_SPEND_PHRASES = Object.freeze([
1240
+ /credit balance/i,
1241
+ /usage limit/i,
1242
+ /spend limit/i,
1243
+ /insufficient (credit|funds|balance)/i
1244
+ ]);
1245
+ var ANTHROPIC_AUTH_TYPES = Object.freeze([
1246
+ "authentication_error",
1247
+ "permission_error"
1248
+ ]);
1249
+ function anthropicErrorBody(payload) {
1250
+ var _a;
1251
+ const outer = typeof payload === "object" && payload !== null ? payload : {};
1252
+ for (const candidate of [
1253
+ outer.error,
1254
+ (_a = outer.details) === null || _a === void 0 ? void 0 : _a.error
1255
+ ]) {
1256
+ if (typeof candidate === "object" && candidate !== null) {
1257
+ const { type, message } = candidate;
1258
+ return {
1259
+ type: typeof type === "string" ? type : void 0,
1260
+ message: typeof message === "string" ? message : void 0
1261
+ };
1262
+ }
1263
+ }
1264
+ return void 0;
1265
+ }
1266
+ function statedKind(payload) {
1267
+ const outer = typeof payload === "object" && payload !== null ? payload : {};
1268
+ const nested = typeof outer.details === "object" && outer.details !== null ? outer.details : {};
1269
+ for (const candidate of [outer.kind, nested.kind]) {
1270
+ if (candidate === "auth" || candidate === "spend")
1271
+ return candidate;
1272
+ }
1273
+ return void 0;
1274
+ }
1275
+ function kindFromEnvelopeType(payload) {
1276
+ const body = anthropicErrorBody(payload);
1277
+ if (!(body === null || body === void 0 ? void 0 : body.type))
1278
+ return void 0;
1279
+ if (ANTHROPIC_AUTH_TYPES.includes(body.type))
1280
+ return "auth";
1281
+ if (body.type === "billing_error")
1282
+ return "spend";
1283
+ return void 0;
1284
+ }
1285
+ function providerRefusalOf(vendor, code, payload) {
1286
+ var _a, _b;
1287
+ if (code === PROVIDER_REFUSED_CODE) {
1288
+ return (_b = (_a = statedKind(payload)) !== null && _a !== void 0 ? _a : kindFromEnvelopeType(payload)) !== null && _b !== void 0 ? _b : "spend";
1289
+ }
1290
+ if (vendor !== "anthropic")
1291
+ return void 0;
1292
+ const structural = kindFromEnvelopeType(payload);
1293
+ if (structural)
1294
+ return structural;
1295
+ const body = anthropicErrorBody(payload);
1296
+ if ((body === null || body === void 0 ? void 0 : body.type) === "invalid_request_error" && body.message) {
1297
+ const message = body.message;
1298
+ if (ANTHROPIC_SPEND_PHRASES.some((phrase) => phrase.test(message)))
1299
+ return "spend";
1300
+ }
1301
+ return void 0;
1302
+ }
1303
+ function providerRefusedFrom(vendorLabel, kind, upstreamStatus, payload, fallbackDetail) {
1304
+ var _a;
1305
+ const body = anthropicErrorBody(payload);
1306
+ 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);
1307
+ }
1308
+ function vendorOfTransportLabel(vendorLabel) {
1309
+ const entry = Object.entries(VENDOR_LABELS).find(([, label]) => label === vendorLabel);
1310
+ return entry === null || entry === void 0 ? void 0 : entry[0];
1311
+ }
1312
+
1164
1313
  // ../../foundation-ai/dist/esm/types/config.types.js
1165
1314
  var SUPPORTED_GEMINI_MODEL_IDS = [
1166
1315
  "gemini-2.5-pro",
@@ -1180,20 +1329,11 @@ var SUPPORTED_ANTHROPIC_MODEL_IDS = [
1180
1329
  "claude-sonnet-4-6",
1181
1330
  "claude-haiku-4-5-20251001"
1182
1331
  ];
1183
- var SUPPORTED_OPENAI_MODEL_IDS = [
1184
- "gpt-6-astra",
1185
- "gpt-6.1-sol",
1186
- "gpt-6.1-terra",
1187
- "gpt-6-sol",
1188
- "gpt-6-luna"
1189
- ];
1190
1332
  function vendorOfModel(modelId) {
1191
1333
  if (SUPPORTED_ANTHROPIC_MODEL_IDS.includes(modelId))
1192
1334
  return "anthropic";
1193
1335
  if (SUPPORTED_GEMINI_MODEL_IDS.includes(modelId))
1194
1336
  return "gemini";
1195
- if (SUPPORTED_OPENAI_MODEL_IDS.includes(modelId))
1196
- return "openai";
1197
1337
  return void 0;
1198
1338
  }
1199
1339
 
@@ -1342,52 +1482,6 @@ function geminiTokenCost(model, usage, at = /* @__PURE__ */ new Date()) {
1342
1482
  }
1343
1483
  };
1344
1484
  }
1345
- var OPENAI_PRICING = {
1346
- "gpt-6-astra": { promptPerMillion: 10, cachedPerMillion: 1, candidatePerMillion: 50 },
1347
- "gpt-6.1-sol": { promptPerMillion: 2, cachedPerMillion: 0.1, candidatePerMillion: 10 },
1348
- "gpt-6.1-terra": { promptPerMillion: 1, cachedPerMillion: 0.05, candidatePerMillion: 5 },
1349
- "gpt-6-sol": { promptPerMillion: 2, cachedPerMillion: 0.2, candidatePerMillion: 10 },
1350
- "gpt-6-luna": { promptPerMillion: 0.1, cachedPerMillion: 0.01, candidatePerMillion: 0.5 }
1351
- };
1352
- var OPENAI_LONG_CONTEXT_THRESHOLD = 272e3;
1353
- var OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER = 2;
1354
- var OPENAI_LONG_CONTEXT_OUTPUT_MULTIPLIER = 1.5;
1355
- var OPENAI_CACHE_WRITE_30M_MULTIPLIER = 1.25;
1356
- var OPENAI_CACHE_WRITE_12H_MULTIPLIER = 2.5;
1357
- function openaiRatesFor(model, promptTokens) {
1358
- const rate = OPENAI_PRICING[model];
1359
- if (promptTokens <= OPENAI_LONG_CONTEXT_THRESHOLD) {
1360
- return rate;
1361
- }
1362
- return {
1363
- promptPerMillion: rate.promptPerMillion * OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER,
1364
- cachedPerMillion: rate.cachedPerMillion * OPENAI_LONG_CONTEXT_INPUT_MULTIPLIER,
1365
- candidatePerMillion: rate.candidatePerMillion * OPENAI_LONG_CONTEXT_OUTPUT_MULTIPLIER
1366
- };
1367
- }
1368
- function openaiTokenCost(model, usage) {
1369
- const { promptPerMillion, cachedPerMillion, candidatePerMillion } = openaiRatesFor(model, usage.inputTokens);
1370
- const m = TOKENS_PER_MILLION;
1371
- const uncachedTokens = Math.max(0, usage.inputTokens - usage.cacheReadTokens - usage.cacheWriteTokens);
1372
- const write12hTokens = Math.min(usage.cacheWrite12hTokens, usage.cacheWriteTokens);
1373
- const write30mTokens = Math.max(0, usage.cacheWriteTokens - write12hTokens);
1374
- const promptCost = uncachedTokens / m * promptPerMillion;
1375
- const cacheReadCost = usage.cacheReadTokens / m * cachedPerMillion;
1376
- const cacheWriteCost = write30mTokens / m * promptPerMillion * OPENAI_CACHE_WRITE_30M_MULTIPLIER + write12hTokens / m * promptPerMillion * OPENAI_CACHE_WRITE_12H_MULTIPLIER;
1377
- const candidateCost = usage.outputTokens / m * candidatePerMillion;
1378
- const cacheReadFull = usage.cacheReadTokens / m * promptPerMillion;
1379
- const cacheWriteFull = usage.cacheWriteTokens / m * promptPerMillion;
1380
- return {
1381
- costUsd: promptCost + cacheReadCost + cacheWriteCost + candidateCost,
1382
- savedUsd: cacheReadFull - cacheReadCost + (cacheWriteFull - cacheWriteCost),
1383
- breakdown: {
1384
- promptUsd: promptCost,
1385
- cacheReadUsd: cacheReadCost,
1386
- cacheWriteUsd: cacheWriteCost,
1387
- candidateUsd: candidateCost
1388
- }
1389
- };
1390
- }
1391
1485
 
1392
1486
  // ../../foundation-ai/dist/esm/utils/tool-schema.js
1393
1487
  var SCHEMA_MAP_KEYS = ["properties", "patternProperties", "$defs", "definitions"];
@@ -1570,135 +1664,6 @@ function toGeminiSchema(parameters) {
1570
1664
  });
1571
1665
  return translated;
1572
1666
  }
1573
- var OPENAI_UNDROPPABLE_KEYWORDS = ["allOf", "not", "if", "then", "else", "oneOf"];
1574
- function withNull(node) {
1575
- if (typeof node.type === "string") {
1576
- const out = Object.assign(Object.assign({}, node), { type: node.type === "null" ? "null" : [node.type, "null"] });
1577
- if (Array.isArray(node.enum) && !node.enum.includes(null))
1578
- out.enum = [...node.enum, null];
1579
- return out;
1580
- }
1581
- if (Array.isArray(node.type)) {
1582
- if (node.type.includes("null"))
1583
- return node;
1584
- const out = Object.assign(Object.assign({}, node), { type: [...node.type, "null"] });
1585
- if (Array.isArray(node.enum) && !node.enum.includes(null))
1586
- out.enum = [...node.enum, null];
1587
- return out;
1588
- }
1589
- if (Array.isArray(node.anyOf)) {
1590
- return node.anyOf.some((b) => isPlainObject2(b) && b.type === "null") ? node : Object.assign(Object.assign({}, node), { anyOf: [...node.anyOf, { type: "null" }] });
1591
- }
1592
- return { anyOf: [node, { type: "null" }] };
1593
- }
1594
- function toOpenAIStrictSchema(parameters) {
1595
- const madeNullable = [];
1596
- const overridden = [];
1597
- const undroppable = [];
1598
- const schema = mapSchema(parameters, (node, path) => {
1599
- for (const keyword of OPENAI_UNDROPPABLE_KEYWORDS) {
1600
- if (keyword in node)
1601
- undroppable.push(`${path}/${keyword}`);
1602
- }
1603
- const isObjectNode = node.type === "object" || Array.isArray(node.type) && node.type.includes("object") || isPlainObject2(node.properties);
1604
- if (!isObjectNode)
1605
- return node;
1606
- if (node.additionalProperties !== false) {
1607
- if (node.additionalProperties !== void 0)
1608
- overridden.push(`${path}/additionalProperties`);
1609
- node.additionalProperties = false;
1610
- }
1611
- if (isPlainObject2(node.properties)) {
1612
- const names = Object.keys(node.properties);
1613
- const required = new Set(Array.isArray(node.required) ? node.required : []);
1614
- const properties = node.properties;
1615
- for (const name of names) {
1616
- if (required.has(name))
1617
- continue;
1618
- properties[name] = isPlainObject2(properties[name]) ? withNull(properties[name]) : { type: "null" };
1619
- madeNullable.push(`${path}/properties/${name}`);
1620
- }
1621
- node.required = names;
1622
- }
1623
- return node;
1624
- });
1625
- return { schema, madeNullable, overridden, undroppable };
1626
- }
1627
- function enforceOpenAIToolSchema(parameters, toolName) {
1628
- const { schema, madeNullable, overridden, undroppable } = toOpenAIStrictSchema(parameters);
1629
- if (madeNullable.length) {
1630
- 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(", ")}`);
1631
- }
1632
- if (overridden.length) {
1633
- logger.warn(`OpenAITransport: tool "${toolName}" is strict, which requires closed objects; \`additionalProperties\` was set to false at: ${overridden.join(", ")}.`);
1634
- }
1635
- if (undroppable.length) {
1636
- 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.`);
1637
- }
1638
- return schema;
1639
- }
1640
-
1641
- // ../../foundation-ai/dist/esm/transports/budget-exhausted-error.js
1642
- var BUDGET_EXCEEDED_CODE = "BUDGET_EXCEEDED";
1643
- var VENDOR_LABELS = Object.freeze({
1644
- anthropic: "Anthropic",
1645
- gemini: "Gemini",
1646
- openai: "OpenAI",
1647
- chrome: "Chrome"
1648
- });
1649
- var BUDGETED_VENDORS = Object.freeze([
1650
- "anthropic",
1651
- "gemini",
1652
- "openai"
1653
- ]);
1654
- var VENDOR_TYPE_BY_LABEL = new Map(Object.entries(VENDOR_LABELS).map(([type, label]) => [
1655
- label.toLowerCase(),
1656
- type
1657
- ]));
1658
- function vendorTypeOfLabel(label) {
1659
- if (typeof label !== "string")
1660
- return void 0;
1661
- return VENDOR_TYPE_BY_LABEL.get(label.trim().toLowerCase());
1662
- }
1663
- var BUDGET_EXCEEDED_STATUS = 402;
1664
- var DEFAULT_BUDGET_EXHAUSTED_MESSAGE = "You've reached your AI usage limit. Contact your administrator to raise it.";
1665
- var BudgetExhaustedError = class extends Error {
1666
- constructor(vendorLabel, budgetUsd, spentUsd, detail, extra) {
1667
- 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.");
1668
- this.vendorLabel = vendorLabel;
1669
- this.budgetUsd = budgetUsd;
1670
- this.spentUsd = spentUsd;
1671
- this.detail = detail;
1672
- this.name = "BudgetExhaustedError";
1673
- this.otherVendorAvailable = extra === null || extra === void 0 ? void 0 : extra.otherVendorAvailable;
1674
- this.serverVendor = extra === null || extra === void 0 ? void 0 : extra.serverVendor;
1675
- }
1676
- };
1677
- var isBudgetRejection = (status, code) => status === BUDGET_EXCEEDED_STATUS || code === BUDGET_EXCEEDED_CODE;
1678
- var parseJsonOrUndefined = (text) => {
1679
- try {
1680
- return JSON.parse(text);
1681
- } catch (_a) {
1682
- return void 0;
1683
- }
1684
- };
1685
- var codeOf = (payload) => {
1686
- const code = payload === null || payload === void 0 ? void 0 : payload.code;
1687
- return typeof code === "string" ? code : void 0;
1688
- };
1689
- var numberOrUndefined = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1690
- var booleanOrUndefined = (value) => typeof value === "boolean" ? value : void 0;
1691
- var stringOrUndefined = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
1692
- function budgetExhaustedFrom(vendorLabel, payload, fallbackDetail) {
1693
- var _a, _b, _c, _d;
1694
- const body = typeof payload === "object" && payload !== null ? payload : {};
1695
- const details = typeof body.details === "object" && body.details !== null ? body.details : {};
1696
- const detail = typeof body.error === "string" ? body.error : fallbackDetail;
1697
- 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, {
1698
- otherVendorAvailable: (_c = booleanOrUndefined(body.otherVendorAvailable)) !== null && _c !== void 0 ? _c : booleanOrUndefined(details.otherVendorAvailable),
1699
- serverVendor: (_d = stringOrUndefined(body.vendor)) !== null && _d !== void 0 ? _d : stringOrUndefined(details.vendor)
1700
- });
1701
- }
1702
1667
 
1703
1668
  // ../../foundation-ai/dist/esm/utils/abort-reason.js
1704
1669
  function authoritativeAbortReason(error, timeoutSignal, callerSignal) {
@@ -1833,8 +1798,6 @@ var CONTEXT_OVERFLOW_PHRASES = Object.freeze([
1833
1798
  /input token count .* exceeds/i,
1834
1799
  /maximum context length/i,
1835
1800
  /context[_ ]length[_ ]exceeded/i,
1836
- // OpenAI Responses: `Your input exceeds the context window of this model.`
1837
- /exceeds the context window/i,
1838
1801
  /too many (input )?tokens/i
1839
1802
  ]);
1840
1803
  var TOKEN_FIGURES = /(\d[\d,]{2,})\D{0,40}?(?:>|exceeds)\D{0,80}?(\d[\d,]{2,})/i;
@@ -1953,94 +1916,6 @@ function readFramedBody(stream, onChunk, vendorLabel, stallTimeout) {
1953
1916
  });
1954
1917
  }
1955
1918
 
1956
- // ../../foundation-ai/dist/esm/transports/provider-refused.js
1957
- var PROVIDER_REFUSED_CODE = "PROVIDER_REFUSED";
1958
- 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.";
1959
- var ProviderRefusedError = class extends Error {
1960
- constructor(vendorLabel, kind, upstreamStatus, upstreamType, detail) {
1961
- 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.");
1962
- this.vendorLabel = vendorLabel;
1963
- this.kind = kind;
1964
- this.upstreamStatus = upstreamStatus;
1965
- this.upstreamType = upstreamType;
1966
- this.detail = detail;
1967
- this.name = "ProviderRefusedError";
1968
- }
1969
- };
1970
- var ANTHROPIC_SPEND_PHRASES = Object.freeze([
1971
- /credit balance/i,
1972
- /usage limit/i,
1973
- /spend limit/i,
1974
- /insufficient (credit|funds|balance)/i
1975
- ]);
1976
- var ANTHROPIC_AUTH_TYPES = Object.freeze([
1977
- "authentication_error",
1978
- "permission_error"
1979
- ]);
1980
- function anthropicErrorBody(payload) {
1981
- var _a;
1982
- const outer = typeof payload === "object" && payload !== null ? payload : {};
1983
- for (const candidate of [
1984
- outer.error,
1985
- (_a = outer.details) === null || _a === void 0 ? void 0 : _a.error
1986
- ]) {
1987
- if (typeof candidate === "object" && candidate !== null) {
1988
- const { type, message } = candidate;
1989
- return {
1990
- type: typeof type === "string" ? type : void 0,
1991
- message: typeof message === "string" ? message : void 0
1992
- };
1993
- }
1994
- }
1995
- return void 0;
1996
- }
1997
- function statedKind(payload) {
1998
- const outer = typeof payload === "object" && payload !== null ? payload : {};
1999
- const nested = typeof outer.details === "object" && outer.details !== null ? outer.details : {};
2000
- for (const candidate of [outer.kind, nested.kind]) {
2001
- if (candidate === "auth" || candidate === "spend")
2002
- return candidate;
2003
- }
2004
- return void 0;
2005
- }
2006
- function kindFromEnvelopeType(payload) {
2007
- const body = anthropicErrorBody(payload);
2008
- if (!(body === null || body === void 0 ? void 0 : body.type))
2009
- return void 0;
2010
- if (ANTHROPIC_AUTH_TYPES.includes(body.type))
2011
- return "auth";
2012
- if (body.type === "billing_error")
2013
- return "spend";
2014
- return void 0;
2015
- }
2016
- function providerRefusalOf(vendor, code, payload) {
2017
- var _a, _b;
2018
- if (code === PROVIDER_REFUSED_CODE) {
2019
- return (_b = (_a = statedKind(payload)) !== null && _a !== void 0 ? _a : kindFromEnvelopeType(payload)) !== null && _b !== void 0 ? _b : "spend";
2020
- }
2021
- if (vendor !== "anthropic")
2022
- return void 0;
2023
- const structural = kindFromEnvelopeType(payload);
2024
- if (structural)
2025
- return structural;
2026
- const body = anthropicErrorBody(payload);
2027
- if ((body === null || body === void 0 ? void 0 : body.type) === "invalid_request_error" && body.message) {
2028
- const message = body.message;
2029
- if (ANTHROPIC_SPEND_PHRASES.some((phrase) => phrase.test(message)))
2030
- return "spend";
2031
- }
2032
- return void 0;
2033
- }
2034
- function providerRefusedFrom(vendorLabel, kind, upstreamStatus, payload, fallbackDetail) {
2035
- var _a;
2036
- const body = anthropicErrorBody(payload);
2037
- 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);
2038
- }
2039
- function vendorOfTransportLabel(vendorLabel) {
2040
- const entry = Object.entries(VENDOR_LABELS).find(([, label]) => label === vendorLabel);
2041
- return entry === null || entry === void 0 ? void 0 : entry[0];
2042
- }
2043
-
2044
1919
  // ../../foundation-ai/dist/esm/transports/retry-hints.js
2045
1920
  var MAX_SERVER_REQUESTED_BACKOFF_MS = 6e4;
2046
1921
  var MAX_TOTAL_SERVER_REQUESTED_BACKOFF_MS = 12e4;
@@ -2968,610 +2843,6 @@ AnthropicTransport.RETRYABLE_STATUSES = [
2968
2843
  ];
2969
2844
  AnthropicTransport.BACKOFF_BASE_MS = 1e3;
2970
2845
 
2971
- // ../../foundation-ai/dist/esm/transports/openai-transport.js
2972
- var OPENAI_DIRECT_URL = "https://api.openai.com/v1/responses";
2973
- var DEFAULT_MODEL2 = "gpt-6-luna";
2974
- var DEFAULT_TIMEOUT2 = 3e5;
2975
- var DEFAULT_STALL_TIMEOUT2 = 3e4;
2976
- var OPENAI_CONTEXT_LIMITS = {
2977
- "gpt-6-astra": 922e3,
2978
- "gpt-6.1-sol": 105e4,
2979
- "gpt-6.1-terra": 105e4,
2980
- "gpt-6-sol": 105e4,
2981
- "gpt-6-luna": 105e4
2982
- };
2983
- var OPENAI_DEFAULT_TEMPERATURE = 1;
2984
- var OPENAI_MAX_TEMPERATURE = 2;
2985
- var OPENAI_EFFORT_NONE_TIERS = ["gpt-6.1-terra", "gpt-6-luna"];
2986
- var OPENAI_EFFORT = {
2987
- minimal: "low",
2988
- low: "low",
2989
- medium: "medium",
2990
- high: "high",
2991
- max: "max"
2992
- };
2993
- function openaiEffortFor(model, policy) {
2994
- if (policy === void 0 || policy === "auto")
2995
- return void 0;
2996
- if (policy === "off")
2997
- return OPENAI_EFFORT_NONE_TIERS.includes(model) ? "none" : "low";
2998
- return OPENAI_EFFORT[policy];
2999
- }
3000
- function toOpenAIToolChoice(choice) {
3001
- if (!choice || choice === "auto")
3002
- return void 0;
3003
- if (choice === "required" || choice === "none")
3004
- return choice;
3005
- return { type: "function", name: choice.tool };
3006
- }
3007
- function toOpenAITool(tool) {
3008
- const parameters = tool.enforceSchema ? enforceOpenAIToolSchema(tool.parameters, tool.name) : tool.parameters;
3009
- return {
3010
- type: "function",
3011
- name: tool.name,
3012
- description: tool.description,
3013
- parameters,
3014
- strict: !!tool.enforceSchema
3015
- };
3016
- }
3017
- function assertSupportedOpenAIModel(model) {
3018
- if (!SUPPORTED_OPENAI_MODEL_IDS.includes(model)) {
3019
- throw new Error(`OpenAITransport: unsupported model "${model}". Use one of: ${SUPPORTED_OPENAI_MODEL_IDS.join(", ")}.`);
3020
- }
3021
- }
3022
- var OPENAI_MODEL_WARNINGS = {
3023
- "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.",
3024
- "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").',
3025
- "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."
3026
- };
3027
- var OPENAI_PROVIDER_KEY = "openai";
3028
- var CACHE_BREAKPOINT = Object.freeze({ mode: "explicit" });
3029
- function imagePart(att) {
3030
- const part = {
3031
- type: "input_image",
3032
- image_url: `data:${normalizeImageMime(att.mimeType)};base64,${stripImageDataUrl(att.data)}`
3033
- };
3034
- if (att.detail)
3035
- part.detail = att.detail === "medium" ? "auto" : att.detail;
3036
- return part;
3037
- }
3038
- function userContentParts(text, atts) {
3039
- const parts = [];
3040
- for (const att of atts) {
3041
- if (att.kind === "image")
3042
- parts.push(imagePart(att));
3043
- }
3044
- if (text)
3045
- parts.push({ type: "input_text", text });
3046
- for (const att of atts) {
3047
- if (att.kind !== "image")
3048
- parts.push({ type: "input_text", text: `[File: ${att.name}]
3049
- ${att.content}` });
3050
- }
3051
- return parts;
3052
- }
3053
- function turnStateOf(msg) {
3054
- var _a, _b, _c, _d, _e;
3055
- 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];
3056
- }
3057
- function replayableReasoning(item) {
3058
- const { status: _status } = item, rest = __rest(item, ["status"]);
3059
- return rest;
3060
- }
3061
- var OpenAITransport = class _OpenAITransport {
3062
- constructor(config = {}) {
3063
- var _a, _b, _c, _d;
3064
- this.lifetimeCostUsd = 0;
3065
- this.lifetimeSavingsUsd = 0;
3066
- this.warnedThinkingClamped = false;
3067
- const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL2;
3068
- assertSupportedOpenAIModel(model);
3069
- this.model = model;
3070
- const warning = OPENAI_MODEL_WARNINGS[model];
3071
- if (warning) {
3072
- logger.warn(warning);
3073
- }
3074
- this.timeout = (_b = config.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT2;
3075
- this.stallTimeout = (_c = config.stallTimeout) !== null && _c !== void 0 ? _c : DEFAULT_STALL_TIMEOUT2;
3076
- this.apiKey = config.apiKey;
3077
- this.serverEndpoint = config.serverEndpoint;
3078
- this.maxTokens = config.maxTokens;
3079
- this.reasoningSummary = (_d = config.reasoningSummary) !== null && _d !== void 0 ? _d : "none";
3080
- }
3081
- getConfig() {
3082
- return { provider: "openai", model: this.model, contextLimit: OPENAI_CONTEXT_LIMITS[this.model] };
3083
- }
3084
- getLifetimeCost() {
3085
- return this.lifetimeCostUsd;
3086
- }
3087
- getLifetimeSavings() {
3088
- return this.lifetimeSavingsUsd;
3089
- }
3090
- resetLifetimeCost() {
3091
- this.lifetimeCostUsd = 0;
3092
- this.lifetimeSavingsUsd = 0;
3093
- }
3094
- // ── AITransport (structured prompt) ────────────────────────────────────
3095
- sendStructuredPrompt(options) {
3096
- return __awaiter(this, void 0, void 0, function* () {
3097
- const { systemPrompt, userPrompt, responseSchema } = options;
3098
- const message = yield this.sendChatMessage([], userPrompt, {
3099
- systemPrompt,
3100
- responseSchema
3101
- });
3102
- return message.content;
3103
- });
3104
- }
3105
- // ── ChatTransport (multi-turn chat) ────────────────────────────────────
3106
- sendChatMessage(history, userMessage, options) {
3107
- return __awaiter(this, void 0, void 0, function* () {
3108
- const body = this.buildRequestBody(history, userMessage, options);
3109
- const response = yield this.post(body, options === null || options === void 0 ? void 0 : options.signal);
3110
- return this.fromResponse(response, body.max_output_tokens);
3111
- });
3112
- }
3113
- /**
3114
- * The Responses request body for a turn. Public for tests and for hosts that want to inspect the
3115
- * exact wire shape; not part of the stable contract.
3116
- *
3117
- * @internal
3118
- */
3119
- buildRequestBody(history, userMessage, options) {
3120
- var _a, _b;
3121
- const scope = (options === null || options === void 0 ? void 0 : options.cachePolicy) && options.cachePolicy.scope !== "default" ? options.cachePolicy.scope : void 0;
3122
- const input = [];
3123
- if (options === null || options === void 0 ? void 0 : options.systemPrompt) {
3124
- const part = { type: "input_text", text: options.systemPrompt };
3125
- if (scope)
3126
- part.prompt_cache_breakpoint = CACHE_BREAKPOINT;
3127
- input.push({ type: "message", role: "developer", content: [part] });
3128
- }
3129
- input.push(...this.toInputItems(history, userMessage, options === null || options === void 0 ? void 0 : options.attachments));
3130
- if (scope === "history")
3131
- this.markHistoryBreakpoint(input);
3132
- if (options === null || options === void 0 ? void 0 : options.tailContext) {
3133
- input.push({
3134
- type: "message",
3135
- role: "user",
3136
- content: [{ type: "input_text", text: options.tailContext }]
3137
- });
3138
- }
3139
- const body = {
3140
- model: this.model,
3141
- input,
3142
- store: false,
3143
- // Encrypted reasoning is what makes a stateless tool loop keep its chain of thought.
3144
- include: ["reasoning.encrypted_content"]
3145
- };
3146
- if (scope) {
3147
- body.prompt_cache_options = { mode: "explicit", ttl: "30m" };
3148
- }
3149
- if ((_a = options === null || options === void 0 ? void 0 : options.tools) === null || _a === void 0 ? void 0 : _a.length) {
3150
- body.tools = options.tools.map(toOpenAITool);
3151
- const toolChoice = toOpenAIToolChoice(options.toolChoice);
3152
- if (toolChoice)
3153
- body.tool_choice = toolChoice;
3154
- }
3155
- this.warnIfThinkingClamped(options === null || options === void 0 ? void 0 : options.thinkingPolicy);
3156
- const effort = openaiEffortFor(this.model, options === null || options === void 0 ? void 0 : options.thinkingPolicy);
3157
- if (effort) {
3158
- body.reasoning = effort === "none" || this.reasoningSummary === "none" ? { effort } : { effort, summary: this.reasoningSummary };
3159
- } else if (this.reasoningSummary !== "none") {
3160
- body.reasoning = { summary: this.reasoningSummary };
3161
- }
3162
- if ((options === null || options === void 0 ? void 0 : options.temperature) != null && effort === "none") {
3163
- body.temperature = scaleTemperature(options.temperature, {
3164
- defaultTemp: OPENAI_DEFAULT_TEMPERATURE,
3165
- maxTemp: OPENAI_MAX_TEMPERATURE
3166
- });
3167
- }
3168
- const maxTokens = (_b = options === null || options === void 0 ? void 0 : options.maxTokens) !== null && _b !== void 0 ? _b : this.maxTokens;
3169
- if (maxTokens != null)
3170
- body.max_output_tokens = maxTokens;
3171
- if (options === null || options === void 0 ? void 0 : options.responseSchema) {
3172
- body.text = {
3173
- format: {
3174
- type: "json_schema",
3175
- name: "response",
3176
- schema: toOpenAIStrictSchema(options.responseSchema).schema,
3177
- strict: true
3178
- }
3179
- };
3180
- }
3181
- return body;
3182
- }
3183
- // ── Private helpers ────────────────────────────────────────────────────
3184
- warnIfThinkingClamped(policy) {
3185
- if (this.warnedThinkingClamped)
3186
- return;
3187
- if (policy === "off" && !OPENAI_EFFORT_NONE_TIERS.includes(this.model)) {
3188
- this.warnedThinkingClamped = true;
3189
- 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.`);
3190
- } else if (policy === "minimal") {
3191
- this.warnedThinkingClamped = true;
3192
- logger.warn(`OpenAITransport: thinkingPolicy 'minimal' sent as effort 'low' \u2014 OpenAI has no 'minimal' effort.`);
3193
- }
3194
- }
3195
- toInputItems(history, userMessage, attachments) {
3196
- var _a, _b, _c, _d, _e;
3197
- const items = [];
3198
- const replayedReasoning = /* @__PURE__ */ new Set();
3199
- for (const msg of history) {
3200
- 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.
3201
- msg.excludeFromProvider || msg.thinking)
3202
- continue;
3203
- if (msg.toolResult) {
3204
- items.push(this.toFunctionCallOutput(msg));
3205
- continue;
3206
- }
3207
- if (msg.role === "user") {
3208
- const content2 = userContentParts(msg.content, (_a = msg.attachments) !== null && _a !== void 0 ? _a : []);
3209
- if (content2.length)
3210
- items.push({ type: "message", role: "user", content: content2 });
3211
- continue;
3212
- }
3213
- const state = turnStateOf(msg);
3214
- if ((state === null || state === void 0 ? void 0 : state.model) === this.model) {
3215
- for (const r of (_b = state.reasoning) !== null && _b !== void 0 ? _b : []) {
3216
- const key = (_c = r.id) !== null && _c !== void 0 ? _c : r.encrypted_content;
3217
- if (replayedReasoning.has(key))
3218
- continue;
3219
- replayedReasoning.add(key);
3220
- items.push(replayableReasoning(r));
3221
- }
3222
- }
3223
- if (msg.content) {
3224
- const item = {
3225
- type: "message",
3226
- role: "assistant",
3227
- content: [{ type: "output_text", text: msg.content }]
3228
- };
3229
- if (state === null || state === void 0 ? void 0 : state.phase)
3230
- item.phase = state.phase;
3231
- items.push(item);
3232
- }
3233
- for (const tc of (_d = msg.toolCalls) !== null && _d !== void 0 ? _d : []) {
3234
- items.push({
3235
- type: "function_call",
3236
- call_id: tc.id,
3237
- name: tc.name,
3238
- arguments: JSON.stringify((_e = tc.args) !== null && _e !== void 0 ? _e : {})
3239
- });
3240
- }
3241
- }
3242
- const content = userContentParts(userMessage, attachments !== null && attachments !== void 0 ? attachments : []);
3243
- if (content.length)
3244
- items.push({ type: "message", role: "user", content });
3245
- return items;
3246
- }
3247
- /**
3248
- * A tool result. Plain string output when there is only text, so a turn without images keeps the
3249
- * simplest wire shape; an array when the tool returned images (or when a cache breakpoint has to
3250
- * be placed on it later — see `markHistoryBreakpoint`).
3251
- */
3252
- toFunctionCallOutput(msg) {
3253
- var _a;
3254
- const result = msg.toolResult;
3255
- const images = (_a = result.attachments) !== null && _a !== void 0 ? _a : [];
3256
- if (!images.length) {
3257
- return { type: "function_call_output", call_id: result.toolCallId, output: result.content };
3258
- }
3259
- return {
3260
- type: "function_call_output",
3261
- call_id: result.toolCallId,
3262
- output: [{ type: "input_text", text: result.content }, ...images.map(imagePart)]
3263
- };
3264
- }
3265
- /**
3266
- * Put the history-scope breakpoint on the last stored item that can carry one: a user message's
3267
- * text part or a tool result. Assistant items cannot carry one, and a trailing assistant item is
3268
- * covered by the next request's breakpoint anyway.
3269
- */
3270
- markHistoryBreakpoint(input) {
3271
- for (let i = input.length - 1; i >= 0; i--) {
3272
- const item = input[i];
3273
- if (item.type === "function_call_output") {
3274
- const output = typeof item.output === "string" ? [{ type: "input_text", text: item.output }] : [...item.output];
3275
- const textIndex = output.findIndex((p) => p.type === "input_text");
3276
- if (textIndex < 0)
3277
- continue;
3278
- output[textIndex] = Object.assign(Object.assign({}, output[textIndex]), { prompt_cache_breakpoint: CACHE_BREAKPOINT });
3279
- input[i] = Object.assign(Object.assign({}, item), { output });
3280
- return;
3281
- }
3282
- if (item.type === "message" && item.role !== "assistant") {
3283
- const content = [...item.content];
3284
- let textIndex = -1;
3285
- for (let j = content.length - 1; j >= 0; j--) {
3286
- if (content[j].type === "input_text") {
3287
- textIndex = j;
3288
- break;
3289
- }
3290
- }
3291
- if (textIndex < 0)
3292
- continue;
3293
- content[textIndex] = Object.assign(Object.assign({}, content[textIndex]), { prompt_cache_breakpoint: CACHE_BREAKPOINT });
3294
- input[i] = Object.assign(Object.assign({}, item), { content });
3295
- return;
3296
- }
3297
- }
3298
- }
3299
- usageFromResponse(usage) {
3300
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
3301
- if (!usage)
3302
- return {};
3303
- const u = usage;
3304
- const cacheReadTokens = (_b = (_a = u.input_tokens_details) === null || _a === void 0 ? void 0 : _a.cached_tokens) !== null && _b !== void 0 ? _b : 0;
3305
- const cacheWriteTokens = (_c = u.cache_write_tokens) !== null && _c !== void 0 ? _c : 0;
3306
- const { costUsd, savedUsd } = openaiTokenCost(this.model, {
3307
- inputTokens: (_d = u.input_tokens) !== null && _d !== void 0 ? _d : 0,
3308
- outputTokens: (_e = u.output_tokens) !== null && _e !== void 0 ? _e : 0,
3309
- cacheReadTokens,
3310
- cacheWriteTokens,
3311
- cacheWrite12hTokens: (_g = (_f = u.cache_write_tokens_details) === null || _f === void 0 ? void 0 : _f.ttl_12h_tokens) !== null && _g !== void 0 ? _g : 0
3312
- });
3313
- this.lifetimeCostUsd += costUsd;
3314
- this.lifetimeSavingsUsd += savedUsd;
3315
- const dp = _OpenAITransport.COST_DECIMAL_PLACES;
3316
- console.log(`--- OpenAI Token Usage (${this.model}) ---`);
3317
- console.log(`Input Tokens: ${(_h = u.input_tokens) !== null && _h !== void 0 ? _h : 0} (${cacheReadTokens} cached, ${cacheWriteTokens} written)`);
3318
- console.log(`Output Tokens: ${(_j = u.output_tokens) !== null && _j !== void 0 ? _j : 0} (incl. ${(_l = (_k = u.output_tokens_details) === null || _k === void 0 ? void 0 : _k.reasoning_tokens) !== null && _l !== void 0 ? _l : 0} reasoning)`);
3319
- console.log(`Total Cost: $${costUsd.toFixed(dp)}`);
3320
- console.log(`Cache Saved: $${savedUsd.toFixed(dp)} (lifetime $${this.lifetimeSavingsUsd.toFixed(dp)})`);
3321
- console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(dp)}`);
3322
- console.log("--------------------------");
3323
- return {
3324
- // Responses' input_tokens already INCLUDES cached and written tokens, matching what
3325
- // ChatMessage.inputTokens means on Gemini (the whole prompt).
3326
- inputTokens: u.input_tokens,
3327
- // Reasoning tokens are already inside output_tokens — no folding needed (unlike Gemini).
3328
- outputTokens: u.output_tokens,
3329
- thoughtsTokens: (_m = u.output_tokens_details) === null || _m === void 0 ? void 0 : _m.reasoning_tokens,
3330
- cacheReadTokens: (_o = u.input_tokens_details) === null || _o === void 0 ? void 0 : _o.cached_tokens,
3331
- cacheWriteTokens: u.cache_write_tokens,
3332
- cost: costUsd
3333
- };
3334
- }
3335
- fromResponse(response, effectiveMaxTokens) {
3336
- var _a, _b, _c, _d, _e, _f;
3337
- const usage = this.usageFromResponse(response.usage);
3338
- const output = (_a = response.output) !== null && _a !== void 0 ? _a : [];
3339
- const reasoning = [];
3340
- const summaryParts = [];
3341
- const textParts = [];
3342
- const refusals = [];
3343
- const toolCalls = [];
3344
- let phase;
3345
- for (const item of output) {
3346
- if (item.type === "reasoning") {
3347
- reasoning.push(item);
3348
- for (const s of (_b = item.summary) !== null && _b !== void 0 ? _b : []) {
3349
- if (s.text)
3350
- summaryParts.push(s.text);
3351
- }
3352
- } else if (item.type === "message") {
3353
- if (typeof item.phase === "string" && phase !== "final_answer")
3354
- phase = item.phase;
3355
- for (const part of (_c = item.content) !== null && _c !== void 0 ? _c : []) {
3356
- if (part.type === "output_text" && typeof part.text === "string")
3357
- textParts.push(part.text);
3358
- if (part.type === "refusal" && typeof part.refusal === "string")
3359
- refusals.push(part.refusal);
3360
- }
3361
- } else if (item.type === "function_call") {
3362
- toolCalls.push({
3363
- id: String((_e = (_d = item.call_id) !== null && _d !== void 0 ? _d : item.id) !== null && _e !== void 0 ? _e : crypto.randomUUID()),
3364
- name: String(item.name),
3365
- args: parseArguments(item.arguments)
3366
- });
3367
- }
3368
- }
3369
- const state = { model: this.model };
3370
- if (reasoning.length)
3371
- state.reasoning = reasoning;
3372
- if (phase)
3373
- state.phase = phase;
3374
- const providerMetadata = { [OPENAI_PROVIDER_KEY]: state };
3375
- if (toolCalls.length)
3376
- toolCalls[0].providerMetadata = providerMetadata;
3377
- const narration = textParts.join("");
3378
- const summary = summaryParts.join("\n\n");
3379
- const base = Object.assign({ role: "assistant", content: narration, reasoning: summary || void 0, providerMetadata }, toolCalls.length ? { toolCalls } : {});
3380
- const status = response.status;
3381
- const incompleteReason = (_f = response.incomplete_details) === null || _f === void 0 ? void 0 : _f.reason;
3382
- const finishReason = refusals.length && !narration && !toolCalls.length ? "refusal" : status === "incomplete" ? incompleteReason !== null && incompleteReason !== void 0 ? incompleteReason : "incomplete" : status;
3383
- if (finishReason === "refusal") {
3384
- base.content = refusals.join("\n");
3385
- }
3386
- if (status === "incomplete" && incompleteReason === "max_output_tokens") {
3387
- if (toolCalls.length || !narration.trim()) {
3388
- throw new ResponseTruncatedError(this.model, effectiveMaxTokens, usage.outputTokens, toolCalls.map((tc) => tc.name));
3389
- }
3390
- }
3391
- if (!toolCalls.length && !narration && !summary && finishReason !== "refusal") {
3392
- logger.warn("OpenAITransport: blank response", {
3393
- model: this.model,
3394
- status,
3395
- incompleteReason,
3396
- outputTypes: output.map((o) => o.type),
3397
- usage: response.usage
3398
- });
3399
- }
3400
- if (usage.inputTokens != null)
3401
- base.inputTokens = usage.inputTokens;
3402
- if (usage.outputTokens != null)
3403
- base.outputTokens = usage.outputTokens;
3404
- if (usage.cacheReadTokens != null)
3405
- base.cacheReadTokens = usage.cacheReadTokens;
3406
- if (usage.cacheWriteTokens != null)
3407
- base.cacheWriteTokens = usage.cacheWriteTokens;
3408
- if (usage.cost != null)
3409
- base.cost = usage.cost;
3410
- base.model = this.model;
3411
- if (finishReason != null || usage.thoughtsTokens != null) {
3412
- base.responseMeta = {
3413
- finishReason,
3414
- thoughtsTokens: usage.thoughtsTokens,
3415
- parts: { functionCall: toolCalls.length, thought: summaryParts.length, text: textParts.length }
3416
- };
3417
- }
3418
- return base;
3419
- }
3420
- buildEndpoint(body) {
3421
- if (this.apiKey) {
3422
- return {
3423
- url: OPENAI_DIRECT_URL,
3424
- payload: body,
3425
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}` },
3426
- credentials: "omit"
3427
- };
3428
- }
3429
- if (this.serverEndpoint) {
3430
- return {
3431
- url: this.serverEndpoint,
3432
- payload: body,
3433
- // Opt in to the proxy's NDJSON heartbeat framing.
3434
- headers: { "Content-Type": "application/json", Accept: "application/x-ndjson" },
3435
- credentials: "include"
3436
- };
3437
- }
3438
- throw new Error("OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.");
3439
- }
3440
- post(body, signal) {
3441
- return __awaiter(this, void 0, void 0, function* () {
3442
- const { url, payload, headers, credentials } = this.buildEndpoint(body);
3443
- return yield postWithRetry({
3444
- url,
3445
- headers,
3446
- body: payload,
3447
- credentials,
3448
- vendorLabel: VENDOR_LABELS.openai,
3449
- retryableStatuses: _OpenAITransport.RETRYABLE_STATUSES,
3450
- timeout: this.timeout,
3451
- stallTimeout: this.stallTimeout,
3452
- backoffBaseMs: _OpenAITransport.BACKOFF_BASE_MS,
3453
- signal
3454
- });
3455
- });
3456
- }
3457
- };
3458
- OpenAITransport.COST_DECIMAL_PLACES = 6;
3459
- OpenAITransport.RETRYABLE_STATUSES = [429, 500, 502, 503];
3460
- OpenAITransport.BACKOFF_BASE_MS = 1e3;
3461
- function parseArguments(raw) {
3462
- if (raw && typeof raw === "object")
3463
- return raw;
3464
- if (typeof raw !== "string" || !raw.trim())
3465
- return {};
3466
- try {
3467
- const parsed = JSON.parse(raw);
3468
- return parsed && typeof parsed === "object" ? parsed : {};
3469
- } catch (_a) {
3470
- logger.warn("OpenAITransport: function_call arguments are not valid JSON", { raw });
3471
- return {};
3472
- }
3473
- }
3474
-
3475
- // ../../foundation-ai/dist/esm/transports/server-openai-transport.js
3476
- var AI_SERVER_PATH = "/gwf/ai-service/chat-completions";
3477
- var DEFAULT_MODEL3 = "gpt-4o-mini";
3478
- var DEFAULT_TIMEOUT3 = 3e4;
3479
- var OPENAI_CONTEXT_LIMITS2 = {
3480
- "gpt-4o": 128e3,
3481
- "gpt-4o-mini": 128e3,
3482
- "gpt-4-turbo": 128e3
3483
- };
3484
- var ServerOpenAITransport = class {
3485
- constructor(config = {}) {
3486
- var _a, _b;
3487
- this.model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL3;
3488
- this.timeout = (_b = config.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT3;
3489
- }
3490
- getConfig() {
3491
- return {
3492
- provider: "openai",
3493
- model: this.model,
3494
- contextLimit: OPENAI_CONTEXT_LIMITS2[this.model]
3495
- };
3496
- }
3497
- sendStructuredPrompt(options) {
3498
- return __awaiter(this, void 0, void 0, function* () {
3499
- var _a, _b;
3500
- const { systemPrompt, userPrompt, responseSchema } = options;
3501
- const controller = new AbortController();
3502
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
3503
- const response = yield fetch(AI_SERVER_PATH, {
3504
- method: "POST",
3505
- headers: {
3506
- "Content-Type": "application/json"
3507
- },
3508
- body: JSON.stringify({
3509
- provider: "openai",
3510
- model: this.model,
3511
- systemPrompt,
3512
- userPrompt,
3513
- responseSchema
3514
- }),
3515
- signal: controller.signal,
3516
- credentials: "include"
3517
- });
3518
- clearTimeout(timeoutId);
3519
- if (!response.ok) {
3520
- const err = yield response.text();
3521
- const parsed = parseJsonOrUndefined(err);
3522
- const refusal = providerRefusalOf("openai", codeOf(parsed), parsed);
3523
- if (refusal) {
3524
- throw providerRefusedFrom(VENDOR_LABELS.openai, refusal, response.status, parsed, err || void 0);
3525
- }
3526
- if (isBudgetRejection(response.status, codeOf(parsed))) {
3527
- throw budgetExhaustedFrom(VENDOR_LABELS.openai, parsed, err || void 0);
3528
- }
3529
- throw new Error(`AI proxy error ${response.status}: ${err}`);
3530
- }
3531
- const data = yield response.json();
3532
- return (_b = (_a = data === null || data === void 0 ? void 0 : data.content) !== null && _a !== void 0 ? _a : data === null || data === void 0 ? void 0 : data.CONTENT) !== null && _b !== void 0 ? _b : "";
3533
- });
3534
- }
3535
- };
3536
-
3537
- // ../../foundation-ai/dist/esm/providers/openai-provider.js
3538
- var OpenAIProvider = class {
3539
- constructor(config, transport) {
3540
- this.transport = transport;
3541
- this.criteriaInstructions = config.criteriaInstructions;
3542
- if (transport instanceof OpenAITransport) {
3543
- this.prompt = (message, options) => __awaiter(this, void 0, void 0, function* () {
3544
- return (yield transport.sendChatMessage([], message, options)).content;
3545
- });
3546
- this.chat = (history, userMessage, options) => transport.sendChatMessage(history, userMessage, options);
3547
- }
3548
- }
3549
- getStatus() {
3550
- return __awaiter(this, void 0, void 0, function* () {
3551
- const config = this.transport instanceof OpenAITransport || this.transport instanceof ServerOpenAITransport ? this.transport.getConfig() : { provider: "openai", model: "gpt-4o-mini", contextLimit: void 0 };
3552
- return { provider: "openai", model: config.model, contextLimit: config.contextLimit };
3553
- });
3554
- }
3555
- interpretCriteria(input, context) {
3556
- return __awaiter(this, void 0, void 0, function* () {
3557
- var _a;
3558
- const fields = (_a = context === null || context === void 0 ? void 0 : context.fields) !== null && _a !== void 0 ? _a : [];
3559
- const systemPrompt = buildCriteriaSystemPrompt(fields, this.criteriaInstructions);
3560
- const userPrompt = buildCriteriaUserPrompt(input);
3561
- try {
3562
- const raw = yield this.transport.sendStructuredPrompt({
3563
- systemPrompt,
3564
- userPrompt,
3565
- responseSchema: CRITERIA_JSON_SCHEMA
3566
- });
3567
- return parseCriteriaResponse(raw);
3568
- } catch (e) {
3569
- logger.error("OpenAIProvider interpretCriteria failed:", e);
3570
- }
3571
- });
3572
- }
3573
- };
3574
-
3575
2846
  // ../../foundation-ai/dist/esm/transports/gemini-malformed-call.js
3576
2847
  var MALFORMED_CALL_ANCHOR = "default_api.";
3577
2848
  var PRINT_WRAPPER_RE = /print\(\s*$/;
@@ -3780,9 +3051,9 @@ function repairMalformedFunctionCall(finishMessage, offeredToolNames) {
3780
3051
 
3781
3052
  // ../../foundation-ai/dist/esm/transports/gemini-transport.js
3782
3053
  var GEMINI_DIRECT_URL = (model) => `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
3783
- var DEFAULT_MODEL4 = "gemini-2.5-flash-lite";
3784
- var DEFAULT_TIMEOUT4 = 3e5;
3785
- var DEFAULT_STALL_TIMEOUT3 = 3e4;
3054
+ var DEFAULT_MODEL2 = "gemini-2.5-flash-lite";
3055
+ var DEFAULT_TIMEOUT2 = 3e5;
3056
+ var DEFAULT_STALL_TIMEOUT2 = 3e4;
3786
3057
  var GEMINI_CONTEXT_LIMITS = {
3787
3058
  "gemini-2.5-pro": 1048576,
3788
3059
  "gemini-2.5-flash": 1048576,
@@ -3968,15 +3239,15 @@ var GeminiTransport = class _GeminiTransport {
3968
3239
  this.lifetimeCostUsd = 0;
3969
3240
  this.lifetimeSavingsUsd = 0;
3970
3241
  this.warnedThinkingClamped = false;
3971
- const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL4;
3242
+ const model = (_a = config.model) !== null && _a !== void 0 ? _a : DEFAULT_MODEL2;
3972
3243
  assertSupportedGeminiModel(model);
3973
3244
  this.model = model;
3974
3245
  const warning = GEMINI_MODEL_WARNINGS[model];
3975
3246
  if (warning) {
3976
3247
  logger.warn(warning);
3977
3248
  }
3978
- this.timeout = (_b = config.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT4;
3979
- this.stallTimeout = (_c = config.stallTimeout) !== null && _c !== void 0 ? _c : DEFAULT_STALL_TIMEOUT3;
3249
+ this.timeout = (_b = config.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT2;
3250
+ this.stallTimeout = (_c = config.stallTimeout) !== null && _c !== void 0 ? _c : DEFAULT_STALL_TIMEOUT2;
3980
3251
  this.apiKey = config.apiKey;
3981
3252
  this.serverEndpoint = config.serverEndpoint;
3982
3253
  }
@@ -13517,17 +12788,11 @@ export {
13517
12788
  MALFORMED_CALL_NUDGE,
13518
12789
  MutableAIProviderRegistry,
13519
12790
  NOOP_ACTIVITY_BUS,
13520
- OPENAI_CACHE_WRITE_12H_MULTIPLIER,
13521
- OPENAI_CACHE_WRITE_30M_MULTIPLIER,
13522
- OPENAI_LONG_CONTEXT_THRESHOLD,
13523
- OpenAIProvider,
13524
- OpenAITransport,
13525
12791
  OrchestratingDriver,
13526
12792
  PROVIDER_REFUSED_CODE,
13527
12793
  ProviderRefusedError,
13528
12794
  SUPPORTED_ANTHROPIC_MODEL_IDS,
13529
12795
  SUPPORTED_GEMINI_MODEL_IDS,
13530
- SUPPORTED_OPENAI_MODEL_IDS,
13531
12796
  UNROUTABLE_INSTRUCTION,
13532
12797
  UNROUTABLE_PLACEHOLDER,
13533
12798
  addUsage,
@@ -13556,8 +12821,6 @@ export {
13556
12821
  isTerminalAIServiceRefusal,
13557
12822
  lifetimeDebugLog,
13558
12823
  messageUsage,
13559
- openaiRatesFor,
13560
- openaiTokenCost,
13561
12824
  resolveAITiers,
13562
12825
  restoreMachine,
13563
12826
  strictFallbackAgent,