@ljoukov/llm 4.0.7 → 4.0.8

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/index.js CHANGED
@@ -329,6 +329,34 @@ function estimateCallCostUsd({
329
329
  import os2 from "os";
330
330
  import { TextDecoder } from "util";
331
331
 
332
+ // src/utils/runtimeSingleton.ts
333
+ var runtimeSingletonStoreKey = /* @__PURE__ */ Symbol.for("@ljoukov/llm.runtimeSingletonStore");
334
+ function getRuntimeSingletonStore() {
335
+ const globalObject = globalThis;
336
+ const existingStore = globalObject[runtimeSingletonStoreKey];
337
+ if (existingStore) {
338
+ return existingStore;
339
+ }
340
+ const store = /* @__PURE__ */ new Map();
341
+ Object.defineProperty(globalObject, runtimeSingletonStoreKey, {
342
+ value: store,
343
+ enumerable: false,
344
+ configurable: false,
345
+ writable: false
346
+ });
347
+ return store;
348
+ }
349
+ function getRuntimeSingleton(key, create) {
350
+ const store = getRuntimeSingletonStore();
351
+ const existingValue = store.get(key);
352
+ if (existingValue !== void 0) {
353
+ return existingValue;
354
+ }
355
+ const createdValue = create();
356
+ store.set(key, createdValue);
357
+ return createdValue;
358
+ }
359
+
332
360
  // src/openai/chatgpt-auth.ts
333
361
  import { Buffer as Buffer2 } from "buffer";
334
362
  import fs2 from "fs";
@@ -339,14 +367,16 @@ import { z } from "zod";
339
367
  // src/utils/env.ts
340
368
  import fs from "fs";
341
369
  import path from "path";
342
- var envLoaded = false;
370
+ var envState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.envState"), () => ({
371
+ envLoaded: false
372
+ }));
343
373
  function loadLocalEnv() {
344
- if (envLoaded) {
374
+ if (envState.envLoaded) {
345
375
  return;
346
376
  }
347
377
  const envPath = path.join(process.cwd(), ".env.local");
348
378
  loadEnvFromFile(envPath, { override: false });
349
- envLoaded = true;
379
+ envState.envLoaded = true;
350
380
  }
351
381
  function loadEnvFromFile(filePath, { override = false } = {}) {
352
382
  let content;
@@ -432,8 +462,10 @@ var ExchangeResponseSchema = z.object({
432
462
  expires_in: z.union([z.number(), z.string()]),
433
463
  id_token: z.string().optional()
434
464
  });
435
- var cachedProfile = null;
436
- var refreshPromise = null;
465
+ var chatGptAuthState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.chatGptAuthState"), () => ({
466
+ cachedProfile: null,
467
+ refreshPromise: null
468
+ }));
437
469
  async function fetchChatGptAuthProfileFromTokenProvider(options) {
438
470
  const base = options.baseUrl.replace(/\/+$/u, "");
439
471
  const store = options.store?.trim() ? options.store.trim() : "kv";
@@ -534,13 +566,13 @@ async function getChatGptAuthProfile() {
534
566
  const tokenProviderUrl = process.env[CHATGPT_AUTH_TOKEN_PROVIDER_URL_ENV];
535
567
  const tokenProviderKey = process.env[CHATGPT_AUTH_TOKEN_PROVIDER_API_KEY_ENV] ?? process.env[CHATGPT_AUTH_API_KEY_ENV];
536
568
  if (tokenProviderUrl && tokenProviderUrl.trim().length > 0 && tokenProviderKey && tokenProviderKey.trim().length > 0) {
537
- if (cachedProfile && !isExpired(cachedProfile)) {
538
- return cachedProfile;
569
+ if (chatGptAuthState.cachedProfile && !isExpired(chatGptAuthState.cachedProfile)) {
570
+ return chatGptAuthState.cachedProfile;
539
571
  }
540
- if (refreshPromise) {
541
- return refreshPromise;
572
+ if (chatGptAuthState.refreshPromise) {
573
+ return chatGptAuthState.refreshPromise;
542
574
  }
543
- refreshPromise = (async () => {
575
+ chatGptAuthState.refreshPromise = (async () => {
544
576
  try {
545
577
  const store = process.env[CHATGPT_AUTH_TOKEN_PROVIDER_STORE_ENV];
546
578
  const profile = await fetchChatGptAuthProfileFromTokenProvider({
@@ -548,31 +580,31 @@ async function getChatGptAuthProfile() {
548
580
  apiKey: tokenProviderKey,
549
581
  store: store ?? void 0
550
582
  });
551
- cachedProfile = profile;
583
+ chatGptAuthState.cachedProfile = profile;
552
584
  return profile;
553
585
  } finally {
554
- refreshPromise = null;
586
+ chatGptAuthState.refreshPromise = null;
555
587
  }
556
588
  })();
557
- return refreshPromise;
589
+ return chatGptAuthState.refreshPromise;
558
590
  }
559
- if (cachedProfile && !isExpired(cachedProfile)) {
560
- return cachedProfile;
591
+ if (chatGptAuthState.cachedProfile && !isExpired(chatGptAuthState.cachedProfile)) {
592
+ return chatGptAuthState.cachedProfile;
561
593
  }
562
- if (refreshPromise) {
563
- return refreshPromise;
594
+ if (chatGptAuthState.refreshPromise) {
595
+ return chatGptAuthState.refreshPromise;
564
596
  }
565
- refreshPromise = (async () => {
597
+ chatGptAuthState.refreshPromise = (async () => {
566
598
  try {
567
- const baseProfile = cachedProfile ?? loadAuthProfileFromCodexStore();
599
+ const baseProfile = chatGptAuthState.cachedProfile ?? loadAuthProfileFromCodexStore();
568
600
  const profile = isExpired(baseProfile) ? await refreshAndPersistCodexProfile(baseProfile) : baseProfile;
569
- cachedProfile = profile;
601
+ chatGptAuthState.cachedProfile = profile;
570
602
  return profile;
571
603
  } finally {
572
- refreshPromise = null;
604
+ chatGptAuthState.refreshPromise = null;
573
605
  }
574
606
  })();
575
- return refreshPromise;
607
+ return chatGptAuthState.refreshPromise;
576
608
  }
577
609
  function resolveCodexHome() {
578
610
  const codexHome = process.env.CODEX_HOME;
@@ -1304,8 +1336,10 @@ function createAbortError(reason) {
1304
1336
  // src/openai/chatgpt-codex.ts
1305
1337
  var CHATGPT_CODEX_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";
1306
1338
  var CHATGPT_RESPONSES_EXPERIMENTAL_HEADER = "responses=experimental";
1307
- var cachedResponsesWebSocketMode = null;
1308
- var chatGptResponsesWebSocketDisabled = false;
1339
+ var chatGptCodexState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.chatGptCodexState"), () => ({
1340
+ cachedResponsesWebSocketMode: null,
1341
+ chatGptResponsesWebSocketDisabled: false
1342
+ }));
1309
1343
  async function streamChatGptCodexResponse(options) {
1310
1344
  const { access, accountId } = await getChatGptAuthProfile();
1311
1345
  const mode = resolveChatGptResponsesWebSocketMode();
@@ -1331,7 +1365,7 @@ async function streamChatGptCodexResponse(options) {
1331
1365
  }
1332
1366
  };
1333
1367
  };
1334
- if (mode === "off" || chatGptResponsesWebSocketDisabled) {
1368
+ if (mode === "off" || chatGptCodexState.chatGptResponsesWebSocketDisabled) {
1335
1369
  return fallbackStreamFactory();
1336
1370
  }
1337
1371
  const websocketHeaders = buildChatGptCodexHeaders({
@@ -1350,7 +1384,7 @@ async function streamChatGptCodexResponse(options) {
1350
1384
  }),
1351
1385
  createFallbackStream: fallbackStreamFactory,
1352
1386
  onWebSocketFallback: () => {
1353
- chatGptResponsesWebSocketDisabled = true;
1387
+ chatGptCodexState.chatGptResponsesWebSocketDisabled = true;
1354
1388
  }
1355
1389
  });
1356
1390
  }
@@ -1380,14 +1414,14 @@ async function streamChatGptCodexResponseSse(options) {
1380
1414
  return parseEventStream(body);
1381
1415
  }
1382
1416
  function resolveChatGptResponsesWebSocketMode() {
1383
- if (cachedResponsesWebSocketMode) {
1384
- return cachedResponsesWebSocketMode;
1417
+ if (chatGptCodexState.cachedResponsesWebSocketMode) {
1418
+ return chatGptCodexState.cachedResponsesWebSocketMode;
1385
1419
  }
1386
- cachedResponsesWebSocketMode = resolveResponsesWebSocketMode(
1420
+ chatGptCodexState.cachedResponsesWebSocketMode = resolveResponsesWebSocketMode(
1387
1421
  process.env.CHATGPT_RESPONSES_WEBSOCKET_MODE ?? process.env.OPENAI_RESPONSES_WEBSOCKET_MODE,
1388
1422
  "auto"
1389
1423
  );
1390
- return cachedResponsesWebSocketMode;
1424
+ return chatGptCodexState.cachedResponsesWebSocketMode;
1391
1425
  }
1392
1426
  function buildChatGptCodexHeaders(options) {
1393
1427
  const openAiBeta = options.useWebSocket ? mergeOpenAiBetaHeader(
@@ -1425,8 +1459,8 @@ async function collectChatGptCodexResponse(options) {
1425
1459
  }
1426
1460
  });
1427
1461
  } catch (error) {
1428
- if (!sawAnyDelta && !retriedViaSseFallback && shouldRetryViaSseFallback(error) && !chatGptResponsesWebSocketDisabled) {
1429
- chatGptResponsesWebSocketDisabled = true;
1462
+ if (!sawAnyDelta && !retriedViaSseFallback && shouldRetryViaSseFallback(error) && !chatGptCodexState.chatGptResponsesWebSocketDisabled) {
1463
+ chatGptCodexState.chatGptResponsesWebSocketDisabled = true;
1430
1464
  retriedViaSseFallback = true;
1431
1465
  continue;
1432
1466
  }
@@ -1662,7 +1696,12 @@ var MODEL_CONCURRENCY_PROVIDERS = [
1662
1696
  "google",
1663
1697
  "fireworks"
1664
1698
  ];
1665
- var configuredModelConcurrency = normalizeModelConcurrencyConfig({});
1699
+ var modelConcurrencyState = getRuntimeSingleton(
1700
+ /* @__PURE__ */ Symbol.for("@ljoukov/llm.modelConcurrencyState"),
1701
+ () => ({
1702
+ configuredModelConcurrency: normalizeModelConcurrencyConfig({})
1703
+ })
1704
+ );
1666
1705
  function clampModelConcurrencyCap(value) {
1667
1706
  if (!Number.isFinite(value)) {
1668
1707
  return DEFAULT_MODEL_CONCURRENCY_CAP;
@@ -1736,14 +1775,14 @@ function resolveDefaultProviderCap(provider, modelId) {
1736
1775
  return DEFAULT_FIREWORKS_MODEL_CONCURRENCY_CAP;
1737
1776
  }
1738
1777
  function configureModelConcurrency(config = {}) {
1739
- configuredModelConcurrency = normalizeModelConcurrencyConfig(config);
1778
+ modelConcurrencyState.configuredModelConcurrency = normalizeModelConcurrencyConfig(config);
1740
1779
  }
1741
1780
  function resetModelConcurrencyConfig() {
1742
- configuredModelConcurrency = normalizeModelConcurrencyConfig({});
1781
+ modelConcurrencyState.configuredModelConcurrency = normalizeModelConcurrencyConfig({});
1743
1782
  }
1744
1783
  function resolveModelConcurrencyCap(options) {
1745
1784
  const modelId = options.modelId ? normalizeModelIdForConfig(options.modelId) : void 0;
1746
- const config = options.config ? normalizeModelConcurrencyConfig(options.config) : configuredModelConcurrency;
1785
+ const config = options.config ? normalizeModelConcurrencyConfig(options.config) : modelConcurrencyState.configuredModelConcurrency;
1747
1786
  const providerModelCap = modelId ? config.providerModelCaps[options.provider].get(modelId) : void 0;
1748
1787
  if (providerModelCap !== void 0) {
1749
1788
  return providerModelCap;
@@ -1977,32 +2016,37 @@ import OpenAI from "openai";
1977
2016
  import { Agent, fetch as undiciFetch } from "undici";
1978
2017
  var DEFAULT_FIREWORKS_BASE_URL = "https://api.fireworks.ai/inference/v1";
1979
2018
  var DEFAULT_FIREWORKS_TIMEOUT_MS = 15 * 6e4;
1980
- var cachedClient = null;
1981
- var cachedFetch = null;
1982
- var cachedBaseUrl = null;
1983
- var cachedApiKey = null;
1984
- var cachedTimeoutMs = null;
2019
+ var fireworksClientState = getRuntimeSingleton(
2020
+ /* @__PURE__ */ Symbol.for("@ljoukov/llm.fireworksClientState"),
2021
+ () => ({
2022
+ cachedClient: null,
2023
+ cachedFetch: null,
2024
+ cachedBaseUrl: null,
2025
+ cachedApiKey: null,
2026
+ cachedTimeoutMs: null
2027
+ })
2028
+ );
1985
2029
  function resolveTimeoutMs() {
1986
- if (cachedTimeoutMs !== null) {
1987
- return cachedTimeoutMs;
2030
+ if (fireworksClientState.cachedTimeoutMs !== null) {
2031
+ return fireworksClientState.cachedTimeoutMs;
1988
2032
  }
1989
2033
  const raw = process.env.FIREWORKS_TIMEOUT_MS;
1990
2034
  const parsed = raw ? Number(raw) : Number.NaN;
1991
- cachedTimeoutMs = Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_FIREWORKS_TIMEOUT_MS;
1992
- return cachedTimeoutMs;
2035
+ fireworksClientState.cachedTimeoutMs = Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_FIREWORKS_TIMEOUT_MS;
2036
+ return fireworksClientState.cachedTimeoutMs;
1993
2037
  }
1994
2038
  function resolveBaseUrl() {
1995
- if (cachedBaseUrl !== null) {
1996
- return cachedBaseUrl;
2039
+ if (fireworksClientState.cachedBaseUrl !== null) {
2040
+ return fireworksClientState.cachedBaseUrl;
1997
2041
  }
1998
2042
  loadLocalEnv();
1999
2043
  const raw = process.env.FIREWORKS_BASE_URL?.trim();
2000
- cachedBaseUrl = raw && raw.length > 0 ? raw : DEFAULT_FIREWORKS_BASE_URL;
2001
- return cachedBaseUrl;
2044
+ fireworksClientState.cachedBaseUrl = raw && raw.length > 0 ? raw : DEFAULT_FIREWORKS_BASE_URL;
2045
+ return fireworksClientState.cachedBaseUrl;
2002
2046
  }
2003
2047
  function resolveApiKey() {
2004
- if (cachedApiKey !== null) {
2005
- return cachedApiKey;
2048
+ if (fireworksClientState.cachedApiKey !== null) {
2049
+ return fireworksClientState.cachedApiKey;
2006
2050
  }
2007
2051
  loadLocalEnv();
2008
2052
  const raw = process.env.FIREWORKS_TOKEN ?? process.env.FIREWORKS_API_KEY;
@@ -2012,46 +2056,51 @@ function resolveApiKey() {
2012
2056
  "FIREWORKS_TOKEN (or FIREWORKS_API_KEY) must be provided to access Fireworks APIs."
2013
2057
  );
2014
2058
  }
2015
- cachedApiKey = token;
2016
- return cachedApiKey;
2059
+ fireworksClientState.cachedApiKey = token;
2060
+ return fireworksClientState.cachedApiKey;
2017
2061
  }
2018
2062
  function getFireworksFetch() {
2019
- if (cachedFetch) {
2020
- return cachedFetch;
2063
+ if (fireworksClientState.cachedFetch) {
2064
+ return fireworksClientState.cachedFetch;
2021
2065
  }
2022
2066
  const timeoutMs = resolveTimeoutMs();
2023
2067
  const dispatcher = new Agent({
2024
2068
  bodyTimeout: timeoutMs,
2025
2069
  headersTimeout: timeoutMs
2026
2070
  });
2027
- cachedFetch = ((input, init) => {
2071
+ fireworksClientState.cachedFetch = ((input, init) => {
2028
2072
  return undiciFetch(input, {
2029
2073
  ...init ?? {},
2030
2074
  dispatcher
2031
2075
  });
2032
2076
  });
2033
- return cachedFetch;
2077
+ return fireworksClientState.cachedFetch;
2034
2078
  }
2035
2079
  function getFireworksClient() {
2036
- if (cachedClient) {
2037
- return cachedClient;
2080
+ if (fireworksClientState.cachedClient) {
2081
+ return fireworksClientState.cachedClient;
2038
2082
  }
2039
- cachedClient = new OpenAI({
2083
+ fireworksClientState.cachedClient = new OpenAI({
2040
2084
  apiKey: resolveApiKey(),
2041
2085
  baseURL: resolveBaseUrl(),
2042
2086
  timeout: resolveTimeoutMs(),
2043
2087
  fetch: getFireworksFetch()
2044
2088
  });
2045
- return cachedClient;
2089
+ return fireworksClientState.cachedClient;
2046
2090
  }
2047
2091
 
2048
2092
  // src/fireworks/calls.ts
2049
2093
  var DEFAULT_SCHEDULER_KEY = "__default__";
2050
- var schedulerByModel = /* @__PURE__ */ new Map();
2094
+ var fireworksCallState = getRuntimeSingleton(
2095
+ /* @__PURE__ */ Symbol.for("@ljoukov/llm.fireworksCallState"),
2096
+ () => ({
2097
+ schedulerByModel: /* @__PURE__ */ new Map()
2098
+ })
2099
+ );
2051
2100
  function getSchedulerForModel(modelId) {
2052
2101
  const normalizedModelId = modelId?.trim();
2053
2102
  const schedulerKey = normalizedModelId && normalizedModelId.length > 0 ? normalizedModelId : DEFAULT_SCHEDULER_KEY;
2054
- const existing = schedulerByModel.get(schedulerKey);
2103
+ const existing = fireworksCallState.schedulerByModel.get(schedulerKey);
2055
2104
  if (existing) {
2056
2105
  return existing;
2057
2106
  }
@@ -2063,7 +2112,7 @@ function getSchedulerForModel(modelId) {
2063
2112
  minIntervalBetweenStartMs: 200,
2064
2113
  startJitterMs: 200
2065
2114
  });
2066
- schedulerByModel.set(schedulerKey, created);
2115
+ fireworksCallState.schedulerByModel.set(schedulerKey, created);
2067
2116
  return created;
2068
2117
  }
2069
2118
  async function runFireworksCall(fn, modelId, runOptions) {
@@ -2110,7 +2159,10 @@ var ServiceAccountSchema = z2.object({
2110
2159
  privateKey: private_key.replace(/\\n/g, "\n"),
2111
2160
  tokenUri: token_uri
2112
2161
  }));
2113
- var cachedServiceAccount = null;
2162
+ var googleAuthState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.googleAuthState"), () => ({
2163
+ cachedServiceAccount: null,
2164
+ authClientCache: /* @__PURE__ */ new Map()
2165
+ }));
2114
2166
  function parseGoogleServiceAccount(input) {
2115
2167
  let parsed;
2116
2168
  try {
@@ -2121,16 +2173,16 @@ function parseGoogleServiceAccount(input) {
2121
2173
  return ServiceAccountSchema.parse(parsed);
2122
2174
  }
2123
2175
  function getGoogleServiceAccount() {
2124
- if (cachedServiceAccount) {
2125
- return cachedServiceAccount;
2176
+ if (googleAuthState.cachedServiceAccount) {
2177
+ return googleAuthState.cachedServiceAccount;
2126
2178
  }
2127
2179
  loadLocalEnv();
2128
2180
  const raw = process.env.GOOGLE_SERVICE_ACCOUNT_JSON;
2129
2181
  if (!raw || raw.trim().length === 0) {
2130
2182
  throw new Error("GOOGLE_SERVICE_ACCOUNT_JSON must be provided for Google APIs access.");
2131
2183
  }
2132
- cachedServiceAccount = parseGoogleServiceAccount(raw);
2133
- return cachedServiceAccount;
2184
+ googleAuthState.cachedServiceAccount = parseGoogleServiceAccount(raw);
2185
+ return googleAuthState.cachedServiceAccount;
2134
2186
  }
2135
2187
  function normaliseScopes(scopes) {
2136
2188
  if (!scopes) {
@@ -2182,8 +2234,10 @@ function isGeminiImageModelId(value) {
2182
2234
  }
2183
2235
  var CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
2184
2236
  var DEFAULT_VERTEX_LOCATION = "global";
2185
- var geminiConfiguration = {};
2186
- var clientPromise;
2237
+ var geminiClientState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.geminiClientState"), () => ({
2238
+ geminiConfiguration: {},
2239
+ clientPromise: void 0
2240
+ }));
2187
2241
  function normaliseConfigValue(value) {
2188
2242
  if (value === void 0 || value === null) {
2189
2243
  return void 0;
@@ -2194,14 +2248,14 @@ function normaliseConfigValue(value) {
2194
2248
  function configureGemini(options = {}) {
2195
2249
  const nextProjectId = normaliseConfigValue(options.projectId);
2196
2250
  const nextLocation = normaliseConfigValue(options.location);
2197
- geminiConfiguration = {
2198
- projectId: nextProjectId !== void 0 ? nextProjectId : geminiConfiguration.projectId,
2199
- location: nextLocation !== void 0 ? nextLocation : geminiConfiguration.location
2251
+ geminiClientState.geminiConfiguration = {
2252
+ projectId: nextProjectId !== void 0 ? nextProjectId : geminiClientState.geminiConfiguration.projectId,
2253
+ location: nextLocation !== void 0 ? nextLocation : geminiClientState.geminiConfiguration.location
2200
2254
  };
2201
- clientPromise = void 0;
2255
+ geminiClientState.clientPromise = void 0;
2202
2256
  }
2203
2257
  function resolveProjectId() {
2204
- const override = geminiConfiguration.projectId;
2258
+ const override = geminiClientState.geminiConfiguration.projectId;
2205
2259
  if (override) {
2206
2260
  return override;
2207
2261
  }
@@ -2209,15 +2263,15 @@ function resolveProjectId() {
2209
2263
  return serviceAccount.projectId;
2210
2264
  }
2211
2265
  function resolveLocation() {
2212
- const override = geminiConfiguration.location;
2266
+ const override = geminiClientState.geminiConfiguration.location;
2213
2267
  if (override) {
2214
2268
  return override;
2215
2269
  }
2216
2270
  return DEFAULT_VERTEX_LOCATION;
2217
2271
  }
2218
2272
  async function getGeminiClient() {
2219
- if (!clientPromise) {
2220
- clientPromise = Promise.resolve().then(() => {
2273
+ if (!geminiClientState.clientPromise) {
2274
+ geminiClientState.clientPromise = Promise.resolve().then(() => {
2221
2275
  const projectId = resolveProjectId();
2222
2276
  const location = resolveLocation();
2223
2277
  const googleAuthOptions = getGoogleAuthOptions(CLOUD_PLATFORM_SCOPE);
@@ -2229,7 +2283,7 @@ async function getGeminiClient() {
2229
2283
  });
2230
2284
  });
2231
2285
  }
2232
- return clientPromise;
2286
+ return geminiClientState.clientPromise;
2233
2287
  }
2234
2288
 
2235
2289
  // src/google/calls.ts
@@ -2425,11 +2479,13 @@ function retryDelayMs(attempt) {
2425
2479
  return base + jitter;
2426
2480
  }
2427
2481
  var DEFAULT_SCHEDULER_KEY2 = "__default__";
2428
- var schedulerByModel2 = /* @__PURE__ */ new Map();
2482
+ var googleCallState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.googleCallState"), () => ({
2483
+ schedulerByModel: /* @__PURE__ */ new Map()
2484
+ }));
2429
2485
  function getSchedulerForModel2(modelId) {
2430
2486
  const normalizedModelId = modelId?.trim();
2431
2487
  const schedulerKey = normalizedModelId && normalizedModelId.length > 0 ? normalizedModelId : DEFAULT_SCHEDULER_KEY2;
2432
- const existing = schedulerByModel2.get(schedulerKey);
2488
+ const existing = googleCallState.schedulerByModel.get(schedulerKey);
2433
2489
  if (existing) {
2434
2490
  return existing;
2435
2491
  }
@@ -2452,7 +2508,7 @@ function getSchedulerForModel2(modelId) {
2452
2508
  }
2453
2509
  }
2454
2510
  });
2455
- schedulerByModel2.set(schedulerKey, created);
2511
+ googleCallState.schedulerByModel.set(schedulerKey, created);
2456
2512
  return created;
2457
2513
  }
2458
2514
  async function runGeminiCall(fn, modelId, runOptions) {
@@ -2462,53 +2518,55 @@ async function runGeminiCall(fn, modelId, runOptions) {
2462
2518
  // src/openai/client.ts
2463
2519
  import OpenAI2 from "openai";
2464
2520
  import { Agent as Agent2, fetch as undiciFetch2 } from "undici";
2465
- var cachedApiKey2 = null;
2466
- var cachedClient2 = null;
2467
- var cachedFetch2 = null;
2468
- var cachedTimeoutMs2 = null;
2469
- var openAiResponsesWebSocketMode = null;
2470
- var openAiResponsesWebSocketDisabled = false;
2521
+ var openAiClientState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.openAiClientState"), () => ({
2522
+ cachedApiKey: null,
2523
+ cachedClient: null,
2524
+ cachedFetch: null,
2525
+ cachedTimeoutMs: null,
2526
+ openAiResponsesWebSocketMode: null,
2527
+ openAiResponsesWebSocketDisabled: false
2528
+ }));
2471
2529
  var DEFAULT_OPENAI_TIMEOUT_MS = 15 * 6e4;
2472
2530
  function resolveOpenAiTimeoutMs() {
2473
- if (cachedTimeoutMs2 !== null) {
2474
- return cachedTimeoutMs2;
2531
+ if (openAiClientState.cachedTimeoutMs !== null) {
2532
+ return openAiClientState.cachedTimeoutMs;
2475
2533
  }
2476
2534
  const raw = process.env.OPENAI_STREAM_TIMEOUT_MS ?? process.env.OPENAI_TIMEOUT_MS;
2477
2535
  const parsed = raw ? Number(raw) : Number.NaN;
2478
- cachedTimeoutMs2 = Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_OPENAI_TIMEOUT_MS;
2479
- return cachedTimeoutMs2;
2536
+ openAiClientState.cachedTimeoutMs = Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_OPENAI_TIMEOUT_MS;
2537
+ return openAiClientState.cachedTimeoutMs;
2480
2538
  }
2481
2539
  function getOpenAiFetch() {
2482
- if (cachedFetch2) {
2483
- return cachedFetch2;
2540
+ if (openAiClientState.cachedFetch) {
2541
+ return openAiClientState.cachedFetch;
2484
2542
  }
2485
2543
  const timeoutMs = resolveOpenAiTimeoutMs();
2486
2544
  const dispatcher = new Agent2({
2487
2545
  bodyTimeout: timeoutMs,
2488
2546
  headersTimeout: timeoutMs
2489
2547
  });
2490
- cachedFetch2 = ((input, init) => {
2548
+ openAiClientState.cachedFetch = ((input, init) => {
2491
2549
  return undiciFetch2(input, {
2492
2550
  ...init ?? {},
2493
2551
  dispatcher
2494
2552
  });
2495
2553
  });
2496
- return cachedFetch2;
2554
+ return openAiClientState.cachedFetch;
2497
2555
  }
2498
2556
  function resolveOpenAiBaseUrl() {
2499
2557
  loadLocalEnv();
2500
2558
  return process.env.OPENAI_BASE_URL?.trim() || "https://api.openai.com/v1";
2501
2559
  }
2502
2560
  function resolveOpenAiResponsesWebSocketMode() {
2503
- if (openAiResponsesWebSocketMode) {
2504
- return openAiResponsesWebSocketMode;
2561
+ if (openAiClientState.openAiResponsesWebSocketMode) {
2562
+ return openAiClientState.openAiResponsesWebSocketMode;
2505
2563
  }
2506
2564
  loadLocalEnv();
2507
- openAiResponsesWebSocketMode = resolveResponsesWebSocketMode(
2565
+ openAiClientState.openAiResponsesWebSocketMode = resolveResponsesWebSocketMode(
2508
2566
  process.env.OPENAI_RESPONSES_WEBSOCKET_MODE,
2509
2567
  "auto"
2510
2568
  );
2511
- return openAiResponsesWebSocketMode;
2569
+ return openAiClientState.openAiResponsesWebSocketMode;
2512
2570
  }
2513
2571
  function wrapFallbackStream(stream) {
2514
2572
  return {
@@ -2561,7 +2619,7 @@ function installResponsesWebSocketTransport(client, apiKey) {
2561
2619
  responsesApi.stream = (request, options) => {
2562
2620
  const mode = resolveOpenAiResponsesWebSocketMode();
2563
2621
  const fallbackStreamFactory = () => wrapFallbackStream(originalStream(request, options));
2564
- if (mode === "off" || openAiResponsesWebSocketDisabled) {
2622
+ if (mode === "off" || openAiClientState.openAiResponsesWebSocketDisabled) {
2565
2623
  return fallbackStreamFactory();
2566
2624
  }
2567
2625
  const signal = options && typeof options === "object" ? options.signal ?? void 0 : void 0;
@@ -2580,15 +2638,15 @@ function installResponsesWebSocketTransport(client, apiKey) {
2580
2638
  createFallbackStream: fallbackStreamFactory,
2581
2639
  onWebSocketFallback: (error) => {
2582
2640
  if (isResponsesWebSocketUnsupportedError(error)) {
2583
- openAiResponsesWebSocketDisabled = true;
2641
+ openAiClientState.openAiResponsesWebSocketDisabled = true;
2584
2642
  }
2585
2643
  }
2586
2644
  });
2587
2645
  };
2588
2646
  }
2589
2647
  function getOpenAiApiKey() {
2590
- if (cachedApiKey2 !== null) {
2591
- return cachedApiKey2;
2648
+ if (openAiClientState.cachedApiKey !== null) {
2649
+ return openAiClientState.cachedApiKey;
2592
2650
  }
2593
2651
  loadLocalEnv();
2594
2652
  const raw = process.env.OPENAI_API_KEY;
@@ -2596,33 +2654,35 @@ function getOpenAiApiKey() {
2596
2654
  if (!value) {
2597
2655
  throw new Error("OPENAI_API_KEY must be provided to access OpenAI APIs.");
2598
2656
  }
2599
- cachedApiKey2 = value;
2600
- return cachedApiKey2;
2657
+ openAiClientState.cachedApiKey = value;
2658
+ return openAiClientState.cachedApiKey;
2601
2659
  }
2602
2660
  function getOpenAiClient() {
2603
- if (cachedClient2) {
2604
- return cachedClient2;
2661
+ if (openAiClientState.cachedClient) {
2662
+ return openAiClientState.cachedClient;
2605
2663
  }
2606
2664
  loadLocalEnv();
2607
2665
  const apiKey = getOpenAiApiKey();
2608
2666
  const timeoutMs = resolveOpenAiTimeoutMs();
2609
- cachedClient2 = new OpenAI2({
2667
+ openAiClientState.cachedClient = new OpenAI2({
2610
2668
  apiKey,
2611
2669
  fetch: getOpenAiFetch(),
2612
2670
  timeout: timeoutMs
2613
2671
  });
2614
- installResponsesWebSocketTransport(cachedClient2, apiKey);
2615
- return cachedClient2;
2672
+ installResponsesWebSocketTransport(openAiClientState.cachedClient, apiKey);
2673
+ return openAiClientState.cachedClient;
2616
2674
  }
2617
2675
 
2618
2676
  // src/openai/calls.ts
2619
2677
  var DEFAULT_OPENAI_REASONING_EFFORT = "medium";
2620
2678
  var DEFAULT_SCHEDULER_KEY3 = "__default__";
2621
- var schedulerByModel3 = /* @__PURE__ */ new Map();
2679
+ var openAiCallState = getRuntimeSingleton(/* @__PURE__ */ Symbol.for("@ljoukov/llm.openAiCallState"), () => ({
2680
+ schedulerByModel: /* @__PURE__ */ new Map()
2681
+ }));
2622
2682
  function getSchedulerForModel3(modelId) {
2623
2683
  const normalizedModelId = modelId?.trim();
2624
2684
  const schedulerKey = normalizedModelId && normalizedModelId.length > 0 ? normalizedModelId : DEFAULT_SCHEDULER_KEY3;
2625
- const existing = schedulerByModel3.get(schedulerKey);
2685
+ const existing = openAiCallState.schedulerByModel.get(schedulerKey);
2626
2686
  if (existing) {
2627
2687
  return existing;
2628
2688
  }
@@ -2634,7 +2694,7 @@ function getSchedulerForModel3(modelId) {
2634
2694
  minIntervalBetweenStartMs: 200,
2635
2695
  startJitterMs: 200
2636
2696
  });
2637
- schedulerByModel3.set(schedulerKey, created);
2697
+ openAiCallState.schedulerByModel.set(schedulerKey, created);
2638
2698
  return created;
2639
2699
  }
2640
2700
  async function runOpenAiCall(fn, modelId, runOptions) {
@@ -3120,7 +3180,10 @@ var AgentLoggingSessionImpl = class {
3120
3180
  }
3121
3181
  }
3122
3182
  };
3123
- var loggingSessionStorage = new AsyncLocalStorage();
3183
+ var loggingSessionStorage = getRuntimeSingleton(
3184
+ /* @__PURE__ */ Symbol.for("@ljoukov/llm.agentLogging.sessionStorage"),
3185
+ () => new AsyncLocalStorage()
3186
+ );
3124
3187
  function createAgentLoggingSession(config) {
3125
3188
  return new AgentLoggingSessionImpl(config);
3126
3189
  }
@@ -3135,7 +3198,10 @@ function getCurrentAgentLoggingSession() {
3135
3198
  }
3136
3199
 
3137
3200
  // src/llm.ts
3138
- var toolCallContextStorage = new AsyncLocalStorage2();
3201
+ var toolCallContextStorage = getRuntimeSingleton(
3202
+ /* @__PURE__ */ Symbol.for("@ljoukov/llm.toolCallContextStorage"),
3203
+ () => new AsyncLocalStorage2()
3204
+ );
3139
3205
  function getCurrentToolCallContext() {
3140
3206
  return toolCallContextStorage.getStore() ?? null;
3141
3207
  }
@@ -5803,7 +5869,10 @@ var DEFAULT_TOOL_LOOP_MAX_STEPS = 8;
5803
5869
  function resolveToolLoopContents(input) {
5804
5870
  return resolveTextContents(input);
5805
5871
  }
5806
- var toolLoopSteeringInternals = /* @__PURE__ */ new WeakMap();
5872
+ var toolLoopSteeringInternals = getRuntimeSingleton(
5873
+ /* @__PURE__ */ Symbol.for("@ljoukov/llm.toolLoopSteeringInternals"),
5874
+ () => /* @__PURE__ */ new WeakMap()
5875
+ );
5807
5876
  function createToolLoopSteeringChannel() {
5808
5877
  const pending = [];
5809
5878
  let closed = false;