@austinthesing/magic-shell 0.2.17 → 0.2.19

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.
Files changed (5) hide show
  1. package/README.md +8 -7
  2. package/dist/cli.js +11752 -8339
  3. package/dist/index.js +1927 -647
  4. package/dist/tui.js +11752 -8339
  5. package/package.json +11 -10
package/dist/index.js CHANGED
@@ -6,25 +6,43 @@ var __getProtoOf = Object.getPrototypeOf;
6
6
  var __defProp = Object.defineProperty;
7
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ function __accessProp(key) {
10
+ return this[key];
11
+ }
12
+ var __toESMCache_node;
13
+ var __toESMCache_esm;
9
14
  var __toESM = (mod, isNodeMode, target) => {
15
+ var canCache = mod != null && typeof mod === "object";
16
+ if (canCache) {
17
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
18
+ var cached = cache.get(mod);
19
+ if (cached)
20
+ return cached;
21
+ }
10
22
  target = mod != null ? __create(__getProtoOf(mod)) : {};
11
23
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
12
24
  for (let key of __getOwnPropNames(mod))
13
25
  if (!__hasOwnProp.call(to, key))
14
26
  __defProp(to, key, {
15
- get: () => mod[key],
27
+ get: __accessProp.bind(mod, key),
16
28
  enumerable: true
17
29
  });
30
+ if (canCache)
31
+ cache.set(mod, to);
18
32
  return to;
19
33
  };
20
34
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
+ var __returnValue = (v) => v;
36
+ function __exportSetter(name, newValue) {
37
+ this[name] = __returnValue.bind(null, newValue);
38
+ }
21
39
  var __export = (target, all) => {
22
40
  for (var name in all)
23
41
  __defProp(target, name, {
24
42
  get: all[name],
25
43
  enumerable: true,
26
44
  configurable: true,
27
- set: (newValue) => all[name] = () => newValue
45
+ set: __exportSetter.bind(all, name)
28
46
  });
29
47
  };
30
48
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
@@ -230,13 +248,14 @@ var require_auth_config = __commonJS((exports, module) => {
230
248
  }
231
249
  fs.writeFileSync(authPath, JSON.stringify(config2, null, 2), { mode: 384 });
232
250
  }
233
- function isValidAccessToken(authConfig) {
251
+ function isValidAccessToken(authConfig, expirationBufferMs = 0) {
234
252
  if (!authConfig.token)
235
253
  return false;
236
254
  if (typeof authConfig.expiresAt !== "number")
237
255
  return true;
238
256
  const nowInSeconds = Math.floor(Date.now() / 1000);
239
- return authConfig.expiresAt >= nowInSeconds;
257
+ const bufferInSeconds = expirationBufferMs / 1000;
258
+ return authConfig.expiresAt >= nowInSeconds + bufferInSeconds;
240
259
  }
241
260
  });
242
261
 
@@ -326,6 +345,47 @@ var require_oauth = __commonJS((exports, module) => {
326
345
  }
327
346
  });
328
347
 
348
+ // node_modules/@vercel/oidc/dist/auth-errors.js
349
+ var require_auth_errors = __commonJS((exports, module) => {
350
+ var __defProp2 = Object.defineProperty;
351
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
352
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
353
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
354
+ var __export2 = (target, all) => {
355
+ for (var name15 in all)
356
+ __defProp2(target, name15, { get: all[name15], enumerable: true });
357
+ };
358
+ var __copyProps = (to, from, except, desc) => {
359
+ if (from && typeof from === "object" || typeof from === "function") {
360
+ for (let key of __getOwnPropNames2(from))
361
+ if (!__hasOwnProp2.call(to, key) && key !== except)
362
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
363
+ }
364
+ return to;
365
+ };
366
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
367
+ var auth_errors_exports = {};
368
+ __export2(auth_errors_exports, {
369
+ AccessTokenMissingError: () => AccessTokenMissingError2,
370
+ RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError2
371
+ });
372
+ module.exports = __toCommonJS(auth_errors_exports);
373
+
374
+ class AccessTokenMissingError2 extends Error {
375
+ constructor() {
376
+ super("No authentication found. Please log in with the Vercel CLI (vercel login).");
377
+ this.name = "AccessTokenMissingError";
378
+ }
379
+ }
380
+
381
+ class RefreshAccessTokenFailedError2 extends Error {
382
+ constructor(cause) {
383
+ super("Failed to refresh authentication token.", { cause });
384
+ this.name = "RefreshAccessTokenFailedError";
385
+ }
386
+ }
387
+ });
388
+
329
389
  // node_modules/@vercel/oidc/dist/token-util.js
330
390
  var require_token_util = __commonJS((exports, module) => {
331
391
  var __create2 = Object.create;
@@ -353,9 +413,9 @@ var require_token_util = __commonJS((exports, module) => {
353
413
  assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse,
354
414
  findProjectInfo: () => findProjectInfo,
355
415
  getTokenPayload: () => getTokenPayload,
356
- getVercelCliToken: () => getVercelCliToken,
357
416
  getVercelDataDir: () => getVercelDataDir,
358
417
  getVercelOidcToken: () => getVercelOidcToken2,
418
+ getVercelToken: () => getVercelToken2,
359
419
  isExpired: () => isExpired,
360
420
  loadToken: () => loadToken,
361
421
  saveToken: () => saveToken
@@ -367,6 +427,7 @@ var require_token_util = __commonJS((exports, module) => {
367
427
  var import_token_io = require_token_io();
368
428
  var import_auth_config = require_auth_config();
369
429
  var import_oauth = require_oauth();
430
+ var import_auth_errors = require_auth_errors();
370
431
  function getVercelDataDir() {
371
432
  const vercelFolder = "com.vercel.cli";
372
433
  const dataDir = (0, import_token_io.getUserDataDir)();
@@ -375,17 +436,17 @@ var require_token_util = __commonJS((exports, module) => {
375
436
  }
376
437
  return path.join(dataDir, vercelFolder);
377
438
  }
378
- async function getVercelCliToken() {
439
+ async function getVercelToken2(options) {
379
440
  const authConfig = (0, import_auth_config.readAuthConfig)();
380
- if (!authConfig) {
381
- return null;
441
+ if (!authConfig?.token) {
442
+ throw new import_auth_errors.AccessTokenMissingError;
382
443
  }
383
- if ((0, import_auth_config.isValidAccessToken)(authConfig)) {
384
- return authConfig.token || null;
444
+ if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) {
445
+ return authConfig.token;
385
446
  }
386
447
  if (!authConfig.refreshToken) {
387
448
  (0, import_auth_config.writeAuthConfig)({});
388
- return null;
449
+ throw new import_auth_errors.RefreshAccessTokenFailedError("No refresh token available");
389
450
  }
390
451
  try {
391
452
  const tokenResponse = await (0, import_oauth.refreshTokenRequest)({
@@ -394,7 +455,7 @@ var require_token_util = __commonJS((exports, module) => {
394
455
  const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse);
395
456
  if (tokensError || !tokens) {
396
457
  (0, import_auth_config.writeAuthConfig)({});
397
- return null;
458
+ throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError);
398
459
  }
399
460
  const updatedConfig = {
400
461
  token: tokens.access_token,
@@ -404,10 +465,13 @@ var require_token_util = __commonJS((exports, module) => {
404
465
  updatedConfig.refreshToken = tokens.refresh_token;
405
466
  }
406
467
  (0, import_auth_config.writeAuthConfig)(updatedConfig);
407
- return updatedConfig.token ?? null;
468
+ return updatedConfig.token;
408
469
  } catch (error40) {
409
470
  (0, import_auth_config.writeAuthConfig)({});
410
- return null;
471
+ if (error40 instanceof import_auth_errors.AccessTokenMissingError || error40 instanceof import_auth_errors.RefreshAccessTokenFailedError) {
472
+ throw error40;
473
+ }
474
+ throw new import_auth_errors.RefreshAccessTokenFailedError(error40);
411
475
  }
412
476
  }
413
477
  async function getVercelOidcToken2(authToken, projectId, teamId) {
@@ -482,8 +546,8 @@ var require_token_util = __commonJS((exports, module) => {
482
546
  const padded = base643.padEnd(base643.length + (4 - base643.length % 4) % 4, "=");
483
547
  return JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
484
548
  }
485
- function isExpired(token) {
486
- return token.exp * 1000 < Date.now();
549
+ function isExpired(token, bufferMs = 0) {
550
+ return token.exp * 1000 < Date.now() + bufferMs;
487
551
  }
488
552
  });
489
553
 
@@ -513,17 +577,26 @@ var require_token = __commonJS((exports, module) => {
513
577
  module.exports = __toCommonJS(token_exports);
514
578
  var import_token_error = require_token_error();
515
579
  var import_token_util = require_token_util();
516
- async function refreshToken() {
517
- const { projectId, teamId } = (0, import_token_util.findProjectInfo)();
580
+ async function refreshToken(options) {
581
+ let projectId = options?.project;
582
+ let teamId = options?.team;
583
+ if (!projectId && !teamId) {
584
+ const projectInfo = (0, import_token_util.findProjectInfo)();
585
+ projectId = projectInfo.projectId;
586
+ teamId = projectInfo.teamId;
587
+ } else if (!projectId || !teamId) {
588
+ const projectInfo = (0, import_token_util.findProjectInfo)();
589
+ projectId = projectId ?? projectInfo.projectId;
590
+ teamId = teamId ?? projectInfo.teamId;
591
+ }
592
+ if (!projectId) {
593
+ throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");
594
+ }
518
595
  let maybeToken = (0, import_token_util.loadToken)(projectId);
519
- if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token))) {
520
- const authToken = await (0, import_token_util.getVercelCliToken)();
521
- if (!authToken) {
522
- throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");
523
- }
524
- if (!projectId) {
525
- throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");
526
- }
596
+ if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token), options?.expirationBufferMs)) {
597
+ const authToken = await (0, import_token_util.getVercelToken)({
598
+ expirationBufferMs: options?.expirationBufferMs
599
+ });
527
600
  maybeToken = await (0, import_token_util.getVercelOidcToken)(authToken, projectId, teamId);
528
601
  if (!maybeToken) {
529
602
  throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token");
@@ -562,7 +635,7 @@ var require_get_vercel_oidc_token = __commonJS((exports, module) => {
562
635
  module.exports = __toCommonJS(get_vercel_oidc_token_exports);
563
636
  var import_get_context = require_get_context();
564
637
  var import_token_error = require_token_error();
565
- async function getVercelOidcToken2() {
638
+ async function getVercelOidcToken2(options) {
566
639
  let token = "";
567
640
  let err;
568
641
  try {
@@ -575,8 +648,8 @@ var require_get_vercel_oidc_token = __commonJS((exports, module) => {
575
648
  await Promise.resolve().then(() => __toESM(require_token_util())),
576
649
  await Promise.resolve().then(() => __toESM(require_token()))
577
650
  ]);
578
- if (!token || isExpired(getTokenPayload(token))) {
579
- await refreshToken();
651
+ if (!token || isExpired(getTokenPayload(token), options?.expirationBufferMs)) {
652
+ await refreshToken(options);
580
653
  token = getVercelOidcTokenSync2();
581
654
  }
582
655
  } catch (error40) {
@@ -622,13 +695,18 @@ var require_dist = __commonJS((exports, module) => {
622
695
  var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
623
696
  var src_exports = {};
624
697
  __export2(src_exports, {
698
+ AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError,
699
+ RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError,
625
700
  getContext: () => import_get_context.getContext,
626
701
  getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
627
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
702
+ getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync,
703
+ getVercelToken: () => import_token_util.getVercelToken
628
704
  });
629
705
  module.exports = __toCommonJS(src_exports);
630
706
  var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
631
707
  var import_get_context = require_get_context();
708
+ var import_auth_errors = require_auth_errors();
709
+ var import_token_util = require_token_util();
632
710
  });
633
711
 
634
712
  // node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js
@@ -2038,15 +2116,6 @@ import { cwd as getCwd } from "process";
2038
2116
 
2039
2117
  // src/lib/types.ts
2040
2118
  var OPENROUTER_MODELS = [
2041
- {
2042
- id: "minimax/minimax-m2.5:free",
2043
- name: "MiniMax M2.5 Free",
2044
- description: "Free MiniMax model for trying out open-source generation",
2045
- category: "smart",
2046
- provider: "openrouter",
2047
- contextLength: 196608,
2048
- free: true
2049
- },
2050
2119
  {
2051
2120
  id: "xiaomi/mimo-v2.5",
2052
2121
  name: "MiMo V2.5",
@@ -2079,6 +2148,38 @@ var OPENROUTER_MODELS = [
2079
2148
  provider: "openrouter",
2080
2149
  contextLength: 202752
2081
2150
  },
2151
+ {
2152
+ id: "openai/gpt-latest",
2153
+ name: "OpenAI GPT Latest",
2154
+ description: "OpenRouter alias that redirects to the latest OpenAI GPT model",
2155
+ category: "smart",
2156
+ provider: "openrouter",
2157
+ contextLength: 1050000
2158
+ },
2159
+ {
2160
+ id: "openai/gpt-5.5",
2161
+ name: "GPT 5.5",
2162
+ description: "OpenAI's latest flagship GPT model",
2163
+ category: "smart",
2164
+ provider: "openrouter",
2165
+ contextLength: 1050000
2166
+ },
2167
+ {
2168
+ id: "anthropic/claude-sonnet-latest",
2169
+ name: "Claude Sonnet Latest",
2170
+ description: "OpenRouter alias that redirects to the latest Claude Sonnet model",
2171
+ category: "smart",
2172
+ provider: "openrouter",
2173
+ contextLength: 1e6
2174
+ },
2175
+ {
2176
+ id: "anthropic/claude-sonnet-4.6",
2177
+ name: "Claude Sonnet 4.6",
2178
+ description: "Anthropic's latest Sonnet model",
2179
+ category: "smart",
2180
+ provider: "openrouter",
2181
+ contextLength: 1e6
2182
+ },
2082
2183
  {
2083
2184
  id: "moonshotai/kimi-k2.6",
2084
2185
  name: "Kimi K2.6",
@@ -2111,6 +2212,30 @@ var OPENROUTER_MODELS = [
2111
2212
  provider: "openrouter",
2112
2213
  contextLength: 196608
2113
2214
  },
2215
+ {
2216
+ id: "anthropic/claude-opus-latest",
2217
+ name: "Claude Opus Latest",
2218
+ description: "OpenRouter alias that redirects to the latest Claude Opus model",
2219
+ category: "reasoning",
2220
+ provider: "openrouter",
2221
+ contextLength: 1e6
2222
+ },
2223
+ {
2224
+ id: "anthropic/claude-opus-4.7",
2225
+ name: "Claude Opus 4.7",
2226
+ description: "Anthropic's latest Opus model",
2227
+ category: "reasoning",
2228
+ provider: "openrouter",
2229
+ contextLength: 1e6
2230
+ },
2231
+ {
2232
+ id: "openai/gpt-5.5-pro",
2233
+ name: "GPT 5.5 Pro",
2234
+ description: "OpenAI's latest high-capability reasoning model",
2235
+ category: "reasoning",
2236
+ provider: "openrouter",
2237
+ contextLength: 1050000
2238
+ },
2114
2239
  {
2115
2240
  id: "moonshotai/kimi-k2-thinking",
2116
2241
  name: "Kimi K2 Thinking",
@@ -2120,16 +2245,109 @@ var OPENROUTER_MODELS = [
2120
2245
  contextLength: 262144
2121
2246
  }
2122
2247
  ];
2123
- var OPENCODE_ZEN_MODELS = [
2248
+ var VERCEL_AI_GATEWAY_MODELS = [
2124
2249
  {
2125
- id: "minimax-m2.5-free",
2126
- name: "MiniMax M2.5 Free",
2127
- description: "MiniMax's free model (limited time)",
2250
+ id: "openai/gpt-latest",
2251
+ name: "OpenAI GPT Latest",
2252
+ description: "Vercel AI Gateway alias that redirects to the latest OpenAI GPT model",
2253
+ category: "smart",
2254
+ provider: "vercel-ai-gateway",
2255
+ contextLength: 1050000
2256
+ },
2257
+ {
2258
+ id: "openai/gpt-5.5",
2259
+ name: "GPT 5.5",
2260
+ description: "OpenAI's latest flagship GPT model",
2261
+ category: "smart",
2262
+ provider: "vercel-ai-gateway",
2263
+ contextLength: 1050000
2264
+ },
2265
+ {
2266
+ id: "anthropic/claude-sonnet-4.6",
2267
+ name: "Claude Sonnet 4.6",
2268
+ description: "Anthropic's latest Sonnet model",
2269
+ category: "smart",
2270
+ provider: "vercel-ai-gateway",
2271
+ contextLength: 1e6
2272
+ },
2273
+ {
2274
+ id: "anthropic/claude-opus-4.7",
2275
+ name: "Claude Opus 4.7",
2276
+ description: "Anthropic's latest Opus model",
2277
+ category: "reasoning",
2278
+ provider: "vercel-ai-gateway",
2279
+ contextLength: 1e6
2280
+ },
2281
+ {
2282
+ id: "openai/gpt-5.5-pro",
2283
+ name: "GPT 5.5 Pro",
2284
+ description: "OpenAI's latest high-capability reasoning model",
2285
+ category: "reasoning",
2286
+ provider: "vercel-ai-gateway",
2287
+ contextLength: 1050000
2288
+ }
2289
+ ];
2290
+ var CLOUDFLARE_AI_GATEWAY_MODELS = [
2291
+ {
2292
+ id: "openai/gpt-5.5",
2293
+ name: "GPT 5.5",
2294
+ description: "OpenAI's latest flagship GPT model through Cloudflare AI Gateway",
2295
+ category: "smart",
2296
+ provider: "cloudflare-ai-gateway",
2297
+ contextLength: 1050000
2298
+ },
2299
+ {
2300
+ id: "anthropic/claude-sonnet-4-6",
2301
+ name: "Claude Sonnet 4.6",
2302
+ description: "Anthropic's latest Sonnet model through Cloudflare AI Gateway",
2303
+ category: "smart",
2304
+ provider: "cloudflare-ai-gateway",
2305
+ contextLength: 1e6
2306
+ },
2307
+ {
2308
+ id: "anthropic/claude-opus-4-7",
2309
+ name: "Claude Opus 4.7",
2310
+ description: "Anthropic's latest Opus model through Cloudflare AI Gateway",
2311
+ category: "reasoning",
2312
+ provider: "cloudflare-ai-gateway",
2313
+ contextLength: 1e6
2314
+ },
2315
+ {
2316
+ id: "workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast",
2317
+ name: "Workers AI Llama 3.3 70B Fast",
2318
+ description: "Cloudflare Workers AI fast Llama model routed through AI Gateway",
2319
+ category: "smart",
2320
+ provider: "cloudflare-ai-gateway",
2321
+ contextLength: 24000
2322
+ }
2323
+ ];
2324
+ var WORKERS_AI_MODELS = [
2325
+ {
2326
+ id: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
2327
+ name: "Llama 3.3 70B Fast",
2328
+ description: "Cloudflare Workers AI fast Llama instruct model",
2329
+ category: "smart",
2330
+ provider: "workers-ai",
2331
+ contextLength: 24000
2332
+ },
2333
+ {
2334
+ id: "@cf/meta/llama-3.1-8b-instruct",
2335
+ name: "Llama 3.1 8B Instruct",
2336
+ description: "Cloudflare Workers AI lightweight Llama instruct model",
2128
2337
  category: "fast",
2129
- provider: "opencode-zen",
2130
- contextLength: 196608,
2131
- free: true
2338
+ provider: "workers-ai",
2339
+ contextLength: 8000
2132
2340
  },
2341
+ {
2342
+ id: "@cf/openai/gpt-oss-120b",
2343
+ name: "GPT OSS 120B",
2344
+ description: "OpenAI open-weight model hosted by Cloudflare Workers AI",
2345
+ category: "reasoning",
2346
+ provider: "workers-ai",
2347
+ contextLength: 32000
2348
+ }
2349
+ ];
2350
+ var OPENCODE_ZEN_MODELS = [
2133
2351
  {
2134
2352
  id: "kimi-k2.6-free",
2135
2353
  name: "Kimi K2.6 Free",
@@ -2156,23 +2374,6 @@ var OPENCODE_ZEN_MODELS = [
2156
2374
  provider: "opencode-zen",
2157
2375
  contextLength: 1048576
2158
2376
  },
2159
- {
2160
- id: "gpt-5-nano",
2161
- name: "GPT 5 Nano",
2162
- description: "OpenAI's fastest GPT model (free)",
2163
- category: "fast",
2164
- provider: "opencode-zen",
2165
- contextLength: 200000,
2166
- free: true
2167
- },
2168
- {
2169
- id: "claude-3-5-haiku",
2170
- name: "Claude Haiku 3.5",
2171
- description: "Anthropic's fast and efficient model",
2172
- category: "fast",
2173
- provider: "opencode-zen",
2174
- contextLength: 200000
2175
- },
2176
2377
  {
2177
2378
  id: "claude-haiku-4-5",
2178
2379
  name: "Claude Haiku 4.5",
@@ -2190,84 +2391,68 @@ var OPENCODE_ZEN_MODELS = [
2190
2391
  contextLength: 200000
2191
2392
  },
2192
2393
  {
2193
- id: "gpt-5.1-codex-mini",
2194
- name: "GPT 5.1 Codex Mini",
2195
- description: "OpenAI's fast codex model",
2394
+ id: "gpt-5.4-mini",
2395
+ name: "GPT 5.4 Mini",
2396
+ description: "OpenAI's latest fast GPT mini model",
2196
2397
  category: "fast",
2197
2398
  provider: "opencode-zen",
2198
- contextLength: 200000
2399
+ contextLength: 400000
2199
2400
  },
2200
2401
  {
2201
- id: "deepseek-v4-flash",
2202
- name: "DeepSeek V4 Flash",
2203
- description: "DeepSeek's latest fast open-source model",
2402
+ id: "gpt-5.4-nano",
2403
+ name: "GPT 5.4 Nano",
2404
+ description: "OpenAI's latest lightweight GPT model",
2204
2405
  category: "fast",
2205
2406
  provider: "opencode-zen",
2206
- contextLength: 1048576
2407
+ contextLength: 400000
2207
2408
  },
2208
2409
  {
2209
- id: "claude-sonnet-4",
2210
- name: "Claude Sonnet 4",
2211
- description: "Anthropic's balanced model for complex tasks",
2410
+ id: "claude-sonnet-4-6",
2411
+ name: "Claude Sonnet 4.6",
2412
+ description: "Anthropic's latest Sonnet model",
2212
2413
  category: "smart",
2213
2414
  provider: "opencode-zen",
2214
- contextLength: 200000
2415
+ contextLength: 1e6
2215
2416
  },
2216
2417
  {
2217
- id: "gemini-3-pro",
2218
- name: "Gemini 3 Pro",
2418
+ id: "gemini-3.1-pro",
2419
+ name: "Gemini 3.1 Pro",
2219
2420
  description: "Google's high-end Gemini model",
2220
2421
  category: "smart",
2221
2422
  provider: "opencode-zen",
2222
2423
  contextLength: 200000
2223
2424
  },
2224
2425
  {
2225
- id: "gpt-5.2",
2226
- name: "GPT 5.2",
2227
- description: "OpenAI's flagship GPT model",
2228
- category: "smart",
2229
- provider: "opencode-zen",
2230
- contextLength: 200000
2231
- },
2232
- {
2233
- id: "gpt-5.2-codex",
2234
- name: "GPT 5.2 Codex",
2235
- description: "OpenAI's coding-focused GPT model",
2426
+ id: "gpt-5.5",
2427
+ name: "GPT 5.5",
2428
+ description: "OpenAI's latest flagship GPT model",
2236
2429
  category: "smart",
2237
2430
  provider: "opencode-zen",
2238
- contextLength: 200000
2431
+ contextLength: 1050000
2239
2432
  },
2240
2433
  {
2241
- id: "gpt-5.1",
2242
- name: "GPT 5.1",
2243
- description: "OpenAI's balanced GPT model",
2434
+ id: "gpt-5.5-pro",
2435
+ name: "GPT 5.5 Pro",
2436
+ description: "OpenAI's latest high-capability reasoning model",
2244
2437
  category: "smart",
2245
2438
  provider: "opencode-zen",
2246
- contextLength: 200000
2439
+ contextLength: 1050000
2247
2440
  },
2248
2441
  {
2249
- id: "gpt-5.1-codex",
2250
- name: "GPT 5.1 Codex",
2251
- description: "OpenAI's coding model",
2442
+ id: "gpt-5.3-codex",
2443
+ name: "GPT 5.3 Codex",
2444
+ description: "OpenAI's latest coding-focused GPT model",
2252
2445
  category: "smart",
2253
2446
  provider: "opencode-zen",
2254
- contextLength: 200000
2447
+ contextLength: 400000
2255
2448
  },
2256
2449
  {
2257
- id: "gpt-5",
2258
- name: "GPT 5",
2259
- description: "OpenAI's prior generation GPT model",
2450
+ id: "gpt-5.3-codex-spark",
2451
+ name: "GPT 5.3 Codex Spark",
2452
+ description: "OpenAI's latest fast coding-focused GPT model",
2260
2453
  category: "smart",
2261
2454
  provider: "opencode-zen",
2262
- contextLength: 200000
2263
- },
2264
- {
2265
- id: "gpt-5-codex",
2266
- name: "GPT 5 Codex",
2267
- description: "OpenAI's prior generation codex model",
2268
- category: "smart",
2269
- provider: "opencode-zen",
2270
- contextLength: 200000
2455
+ contextLength: 400000
2271
2456
  },
2272
2457
  {
2273
2458
  id: "minimax-m2.7",
@@ -2310,44 +2495,12 @@ var OPENCODE_ZEN_MODELS = [
2310
2495
  contextLength: 202752
2311
2496
  },
2312
2497
  {
2313
- id: "claude-sonnet-4-5",
2314
- name: "Claude Sonnet 4.5",
2315
- description: "Anthropic's hybrid reasoning model",
2316
- category: "reasoning",
2317
- provider: "opencode-zen",
2318
- contextLength: 200000
2319
- },
2320
- {
2321
- id: "claude-opus-4-6",
2322
- name: "Claude Opus 4.6",
2323
- description: "Anthropic's newest Opus model",
2498
+ id: "claude-opus-4-7",
2499
+ name: "Claude Opus 4.7",
2500
+ description: "Anthropic's latest Opus model",
2324
2501
  category: "reasoning",
2325
2502
  provider: "opencode-zen",
2326
- contextLength: 200000
2327
- },
2328
- {
2329
- id: "claude-opus-4-5",
2330
- name: "Claude Opus 4.5",
2331
- description: "Anthropic's most capable model",
2332
- category: "reasoning",
2333
- provider: "opencode-zen",
2334
- contextLength: 200000
2335
- },
2336
- {
2337
- id: "claude-opus-4-1",
2338
- name: "Claude Opus 4.1",
2339
- description: "Anthropic's powerful reasoning model",
2340
- category: "reasoning",
2341
- provider: "opencode-zen",
2342
- contextLength: 200000
2343
- },
2344
- {
2345
- id: "gpt-5.1-codex-max",
2346
- name: "GPT 5.1 Codex Max",
2347
- description: "OpenAI's largest coding model",
2348
- category: "reasoning",
2349
- provider: "opencode-zen",
2350
- contextLength: 200000
2503
+ contextLength: 1e6
2351
2504
  },
2352
2505
  {
2353
2506
  id: "kimi-k2-thinking",
@@ -2358,7 +2511,45 @@ var OPENCODE_ZEN_MODELS = [
2358
2511
  contextLength: 262144
2359
2512
  }
2360
2513
  ];
2361
- var ALL_MODELS = [...OPENCODE_ZEN_MODELS, ...OPENROUTER_MODELS];
2514
+ var ALL_MODELS = [
2515
+ ...OPENCODE_ZEN_MODELS,
2516
+ ...OPENROUTER_MODELS,
2517
+ ...VERCEL_AI_GATEWAY_MODELS,
2518
+ ...CLOUDFLARE_AI_GATEWAY_MODELS,
2519
+ ...WORKERS_AI_MODELS
2520
+ ];
2521
+ function getProviderModels(provider) {
2522
+ switch (provider) {
2523
+ case "opencode-zen":
2524
+ return OPENCODE_ZEN_MODELS;
2525
+ case "openrouter":
2526
+ return OPENROUTER_MODELS;
2527
+ case "vercel-ai-gateway":
2528
+ return VERCEL_AI_GATEWAY_MODELS;
2529
+ case "cloudflare-ai-gateway":
2530
+ return CLOUDFLARE_AI_GATEWAY_MODELS;
2531
+ case "workers-ai":
2532
+ return WORKERS_AI_MODELS;
2533
+ case "custom":
2534
+ return [];
2535
+ }
2536
+ }
2537
+ function getProviderDisplayName(provider) {
2538
+ switch (provider) {
2539
+ case "opencode-zen":
2540
+ return "OpenCode Zen";
2541
+ case "openrouter":
2542
+ return "OpenRouter";
2543
+ case "vercel-ai-gateway":
2544
+ return "Vercel AI Gateway";
2545
+ case "cloudflare-ai-gateway":
2546
+ return "Cloudflare AI Gateway";
2547
+ case "workers-ai":
2548
+ return "Cloudflare Workers AI";
2549
+ case "custom":
2550
+ return "Custom";
2551
+ }
2552
+ }
2362
2553
 
2363
2554
  // src/lib/config.ts
2364
2555
  import { homedir } from "os";
@@ -2726,10 +2917,18 @@ var CONFIG_FILE = join(CONFIG_DIR, "config.json");
2726
2917
  var HISTORY_FILE = join(CONFIG_DIR, "history.json");
2727
2918
  var KEYCHAIN_OPENROUTER = "openrouter-api-key";
2728
2919
  var KEYCHAIN_OPENCODE_ZEN = "opencode-zen-api-key";
2920
+ var KEYCHAIN_VERCEL_AI_GATEWAY = "vercel-ai-gateway-api-key";
2921
+ var KEYCHAIN_CLOUDFLARE_AI_GATEWAY = "cloudflare-ai-gateway-api-key";
2922
+ var KEYCHAIN_WORKERS_AI = "workers-ai-api-key";
2729
2923
  var DEFAULT_CONFIG = {
2730
2924
  provider: "opencode-zen",
2731
2925
  openrouterApiKey: "",
2732
2926
  opencodeZenApiKey: "",
2927
+ vercelAiGatewayApiKey: "",
2928
+ cloudflareAiGatewayApiKey: "",
2929
+ workersAiApiKey: "",
2930
+ cloudflareAccountId: "",
2931
+ cloudflareAiGatewayId: "default",
2733
2932
  defaultModel: "kimi-k2.6-free",
2734
2933
  safetyLevel: "moderate",
2735
2934
  dryRunByDefault: false,
@@ -2769,6 +2968,9 @@ function saveConfig(config) {
2769
2968
  if (isSecureStorageAvailable()) {
2770
2969
  configToSave.openrouterApiKey = "";
2771
2970
  configToSave.opencodeZenApiKey = "";
2971
+ configToSave.vercelAiGatewayApiKey = "";
2972
+ configToSave.cloudflareAiGatewayApiKey = "";
2973
+ configToSave.workersAiApiKey = "";
2772
2974
  }
2773
2975
  writeFileSync(CONFIG_FILE, JSON.stringify(configToSave, null, 2));
2774
2976
  }
@@ -2781,28 +2983,83 @@ async function getApiKey(provider) {
2781
2983
  const envKey = process.env.OPENCODE_ZEN_API_KEY;
2782
2984
  if (envKey)
2783
2985
  return envKey;
2986
+ } else if (provider === "vercel-ai-gateway") {
2987
+ const envKey = process.env.AI_GATEWAY_API_KEY || process.env.VERCEL_AI_GATEWAY_API_KEY;
2988
+ if (envKey)
2989
+ return envKey;
2990
+ } else if (provider === "cloudflare-ai-gateway") {
2991
+ const envKey = process.env.CLOUDFLARE_AI_GATEWAY_API_KEY || process.env.CF_AIG_TOKEN;
2992
+ if (envKey)
2993
+ return envKey;
2994
+ } else if (provider === "workers-ai") {
2995
+ const envKey = process.env.CLOUDFLARE_API_TOKEN || process.env.CLOUDFLARE_API_KEY;
2996
+ if (envKey)
2997
+ return envKey;
2784
2998
  }
2785
- const keychainKey = provider === "openrouter" ? KEYCHAIN_OPENROUTER : KEYCHAIN_OPENCODE_ZEN;
2999
+ const keychainKey = getKeychainKey(provider);
2786
3000
  const secureKey = await getSecret(keychainKey);
2787
3001
  if (secureKey)
2788
3002
  return secureKey;
2789
3003
  const config = loadConfig();
2790
- return provider === "openrouter" ? config.openrouterApiKey : config.opencodeZenApiKey;
3004
+ switch (provider) {
3005
+ case "openrouter":
3006
+ return config.openrouterApiKey;
3007
+ case "opencode-zen":
3008
+ return config.opencodeZenApiKey;
3009
+ case "vercel-ai-gateway":
3010
+ return config.vercelAiGatewayApiKey || "";
3011
+ case "cloudflare-ai-gateway":
3012
+ return config.cloudflareAiGatewayApiKey || "";
3013
+ case "workers-ai":
3014
+ return config.workersAiApiKey || "";
3015
+ case "custom":
3016
+ return "";
3017
+ }
2791
3018
  }
2792
3019
  async function setApiKey(provider, key) {
2793
3020
  const config = loadConfig();
2794
3021
  config.provider = provider;
2795
- const keychainKey = provider === "openrouter" ? KEYCHAIN_OPENROUTER : KEYCHAIN_OPENCODE_ZEN;
3022
+ const keychainKey = getKeychainKey(provider);
2796
3023
  const stored = await setSecret(keychainKey, key);
2797
3024
  if (!stored) {
2798
- if (provider === "openrouter") {
2799
- config.openrouterApiKey = key;
2800
- } else {
2801
- config.opencodeZenApiKey = key;
3025
+ switch (provider) {
3026
+ case "openrouter":
3027
+ config.openrouterApiKey = key;
3028
+ break;
3029
+ case "opencode-zen":
3030
+ config.opencodeZenApiKey = key;
3031
+ break;
3032
+ case "vercel-ai-gateway":
3033
+ config.vercelAiGatewayApiKey = key;
3034
+ break;
3035
+ case "cloudflare-ai-gateway":
3036
+ config.cloudflareAiGatewayApiKey = key;
3037
+ break;
3038
+ case "workers-ai":
3039
+ config.workersAiApiKey = key;
3040
+ break;
3041
+ case "custom":
3042
+ break;
2802
3043
  }
2803
3044
  }
2804
3045
  saveConfig(config);
2805
3046
  }
3047
+ function getKeychainKey(provider) {
3048
+ switch (provider) {
3049
+ case "openrouter":
3050
+ return KEYCHAIN_OPENROUTER;
3051
+ case "opencode-zen":
3052
+ return KEYCHAIN_OPENCODE_ZEN;
3053
+ case "vercel-ai-gateway":
3054
+ return KEYCHAIN_VERCEL_AI_GATEWAY;
3055
+ case "cloudflare-ai-gateway":
3056
+ return KEYCHAIN_CLOUDFLARE_AI_GATEWAY;
3057
+ case "workers-ai":
3058
+ return KEYCHAIN_WORKERS_AI;
3059
+ case "custom":
3060
+ return "custom-api-key";
3061
+ }
3062
+ }
2806
3063
  function loadHistory() {
2807
3064
  ensureConfigDir();
2808
3065
  if (!existsSync(HISTORY_FILE)) {
@@ -18382,43 +18639,114 @@ class ParseError extends Error {
18382
18639
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
18383
18640
  }
18384
18641
  }
18642
+ var LF = 10;
18643
+ var CR = 13;
18644
+ var SPACE = 32;
18385
18645
  function noop(_arg) {}
18386
18646
  function createParser(callbacks) {
18387
18647
  if (typeof callbacks == "function")
18388
18648
  throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
18389
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
18390
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
18391
- function feed(newChunk) {
18392
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
18393
- for (const line of complete)
18394
- parseLine(line);
18395
- incompleteLine = incomplete, isFirstChunk = false;
18396
- }
18397
- function parseLine(line) {
18398
- if (line === "") {
18649
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
18650
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
18651
+ function feed(chunk) {
18652
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
18653
+ const trailing2 = processLines(chunk);
18654
+ trailing2 !== "" && pendingFragments.push(trailing2);
18655
+ return;
18656
+ }
18657
+ if (chunk.indexOf(`
18658
+ `) === -1 && chunk.indexOf("\r") === -1) {
18659
+ pendingFragments.push(chunk);
18660
+ return;
18661
+ }
18662
+ pendingFragments.push(chunk);
18663
+ const input = pendingFragments.join("");
18664
+ pendingFragments.length = 0;
18665
+ const trailing = processLines(input);
18666
+ trailing !== "" && pendingFragments.push(trailing);
18667
+ }
18668
+ function processLines(chunk) {
18669
+ let searchIndex = 0;
18670
+ if (chunk.indexOf("\r") === -1) {
18671
+ let lfIndex = chunk.indexOf(`
18672
+ `, searchIndex);
18673
+ for (;lfIndex !== -1; ) {
18674
+ if (searchIndex === lfIndex) {
18675
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = undefined, data = "", dataLines = 0, eventType = undefined, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
18676
+ `, searchIndex);
18677
+ continue;
18678
+ }
18679
+ const firstCharCode = chunk.charCodeAt(searchIndex);
18680
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
18681
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
18682
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
18683
+ onEvent({ id, event: eventType, data: value }), id = undefined, data = "", eventType = undefined, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
18684
+ `, searchIndex);
18685
+ continue;
18686
+ }
18687
+ data = dataLines === 0 ? value : `${data}
18688
+ ${value}`, dataLines++;
18689
+ } else
18690
+ isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined : parseLine(chunk, searchIndex, lfIndex);
18691
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
18692
+ `, searchIndex);
18693
+ }
18694
+ return chunk.slice(searchIndex);
18695
+ }
18696
+ for (;searchIndex < chunk.length; ) {
18697
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
18698
+ `, searchIndex);
18699
+ let lineEnd = -1;
18700
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
18701
+ break;
18702
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
18703
+ }
18704
+ return chunk.slice(searchIndex);
18705
+ }
18706
+ function parseLine(chunk, start, end) {
18707
+ if (start === end) {
18399
18708
  dispatchEvent();
18400
18709
  return;
18401
18710
  }
18402
- if (line.startsWith(":")) {
18403
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
18711
+ const firstCharCode = chunk.charCodeAt(start);
18712
+ if (isDataPrefix(chunk, start, firstCharCode)) {
18713
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
18714
+ data = dataLines === 0 ? value2 : `${data}
18715
+ ${value2}`, dataLines++;
18404
18716
  return;
18405
18717
  }
18406
- const fieldSeparatorIndex = line.indexOf(":");
18407
- if (fieldSeparatorIndex !== -1) {
18408
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
18409
- processField(field, value, line);
18718
+ if (isEventPrefix(chunk, start, firstCharCode)) {
18719
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;
18410
18720
  return;
18411
18721
  }
18412
- processField(line, "", line);
18722
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
18723
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
18724
+ id = value2.includes("\x00") ? undefined : value2;
18725
+ return;
18726
+ }
18727
+ if (firstCharCode === 58) {
18728
+ if (onComment) {
18729
+ const line2 = chunk.slice(start, end);
18730
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
18731
+ }
18732
+ return;
18733
+ }
18734
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
18735
+ if (fieldSeparatorIndex === -1) {
18736
+ processField(line, "", line);
18737
+ return;
18738
+ }
18739
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
18740
+ processField(field, value, line);
18413
18741
  }
18414
18742
  function processField(field, value, line) {
18415
18743
  switch (field) {
18416
18744
  case "event":
18417
- eventType = value;
18745
+ eventType = value || undefined;
18418
18746
  break;
18419
18747
  case "data":
18420
- data = `${data}${value}
18421
- `;
18748
+ data = dataLines === 0 ? value : `${data}
18749
+ ${value}`, dataLines++;
18422
18750
  break;
18423
18751
  case "id":
18424
18752
  id = value.includes("\x00") ? undefined : value;
@@ -18436,35 +18764,26 @@ function createParser(callbacks) {
18436
18764
  }
18437
18765
  }
18438
18766
  function dispatchEvent() {
18439
- data.length > 0 && onEvent({
18767
+ dataLines > 0 && onEvent({
18440
18768
  id,
18441
- event: eventType || undefined,
18442
- data: data.endsWith(`
18443
- `) ? data.slice(0, -1) : data
18444
- }), id = undefined, data = "", eventType = "";
18769
+ event: eventType,
18770
+ data
18771
+ }), id = undefined, data = "", dataLines = 0, eventType = undefined;
18445
18772
  }
18446
18773
  function reset(options = {}) {
18447
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = undefined, data = "", eventType = "", incompleteLine = "";
18774
+ if (options.consume && pendingFragments.length > 0) {
18775
+ const incompleteLine = pendingFragments.join("");
18776
+ parseLine(incompleteLine, 0, incompleteLine.length);
18777
+ }
18778
+ isFirstChunk = true, id = undefined, data = "", dataLines = 0, eventType = undefined, pendingFragments.length = 0;
18448
18779
  }
18449
18780
  return { feed, reset };
18450
18781
  }
18451
- function splitLines(chunk) {
18452
- const lines = [];
18453
- let incompleteLine = "", searchIndex = 0;
18454
- for (;searchIndex < chunk.length; ) {
18455
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
18456
- `, searchIndex);
18457
- let lineEnd = -1;
18458
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
18459
- incompleteLine = chunk.slice(searchIndex);
18460
- break;
18461
- } else {
18462
- const line = chunk.slice(searchIndex, lineEnd);
18463
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
18464
- ` && searchIndex++;
18465
- }
18466
- }
18467
- return [lines, incompleteLine];
18782
+ function isDataPrefix(chunk, i, firstCharCode) {
18783
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
18784
+ }
18785
+ function isEventPrefix(chunk, i, firstCharCode) {
18786
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
18468
18787
  }
18469
18788
 
18470
18789
  // node_modules/eventsource-parser/dist/stream.js
@@ -18946,7 +19265,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
18946
19265
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
18947
19266
  return Object.fromEntries(normalizedHeaders.entries());
18948
19267
  }
18949
- var VERSION = "4.0.22";
19268
+ var VERSION = "4.0.26";
18950
19269
  var getOriginalFetch = () => globalThis.fetch;
18951
19270
  var getFromApi = async ({
18952
19271
  url: url2,
@@ -19042,7 +19361,7 @@ function loadApiKey({
19042
19361
  }
19043
19362
  if (typeof process === "undefined") {
19044
19363
  throw new LoadAPIKeyError({
19045
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
19364
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`
19046
19365
  });
19047
19366
  }
19048
19367
  apiKey = process.env[environmentVariableName];
@@ -20678,7 +20997,7 @@ async function* executeTool({
20678
20997
  }
20679
20998
 
20680
20999
  // node_modules/@ai-sdk/anthropic/dist/index.mjs
20681
- var VERSION2 = "3.0.66";
21000
+ var VERSION2 = "3.0.74";
20682
21001
  var anthropicErrorDataSchema = lazySchema(() => zodSchema(exports_external.object({
20683
21002
  type: exports_external.literal("error"),
20684
21003
  error: exports_external.object({
@@ -21367,7 +21686,8 @@ var anthropicLanguageModelOptions = exports_external.object({
21367
21686
  structuredOutputMode: exports_external.enum(["outputFormat", "jsonTool", "auto"]).optional(),
21368
21687
  thinking: exports_external.discriminatedUnion("type", [
21369
21688
  exports_external.object({
21370
- type: exports_external.literal("adaptive")
21689
+ type: exports_external.literal("adaptive"),
21690
+ display: exports_external.enum(["omitted", "summarized"]).optional()
21371
21691
  }),
21372
21692
  exports_external.object({
21373
21693
  type: exports_external.literal("enabled"),
@@ -21404,8 +21724,14 @@ var anthropicLanguageModelOptions = exports_external.object({
21404
21724
  })).optional()
21405
21725
  }).optional(),
21406
21726
  toolStreaming: exports_external.boolean().optional(),
21407
- effort: exports_external.enum(["low", "medium", "high", "max"]).optional(),
21727
+ effort: exports_external.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
21728
+ taskBudget: exports_external.object({
21729
+ type: exports_external.literal("tokens"),
21730
+ total: exports_external.number().int().min(20000),
21731
+ remaining: exports_external.number().int().min(0).optional()
21732
+ }).optional(),
21408
21733
  speed: exports_external.enum(["fast", "standard"]).optional(),
21734
+ inferenceGeo: exports_external.enum(["us", "global"]).optional(),
21409
21735
  anthropicBeta: exports_external.array(exports_external.string()).optional(),
21410
21736
  contextManagement: exports_external.object({
21411
21737
  edits: exports_external.array(exports_external.discriminatedUnion("type", [
@@ -21664,9 +21990,10 @@ async function prepareTools({
21664
21990
  disableParallelToolUse,
21665
21991
  cacheControlValidator,
21666
21992
  supportsStructuredOutput,
21667
- supportsStrictTools
21993
+ supportsStrictTools,
21994
+ defaultEagerInputStreaming = false
21668
21995
  }) {
21669
- var _a16;
21996
+ var _a16, _b16;
21670
21997
  tools = (tools == null ? undefined : tools.length) ? tools : undefined;
21671
21998
  const toolWarnings = [];
21672
21999
  const betas = /* @__PURE__ */ new Set;
@@ -21683,7 +22010,7 @@ async function prepareTools({
21683
22010
  canCache: true
21684
22011
  });
21685
22012
  const anthropicOptions = (_a16 = tool2.providerOptions) == null ? undefined : _a16.anthropic;
21686
- const eagerInputStreaming = anthropicOptions == null ? undefined : anthropicOptions.eagerInputStreaming;
22013
+ const eagerInputStreaming = (_b16 = anthropicOptions == null ? undefined : anthropicOptions.eagerInputStreaming) != null ? _b16 : defaultEagerInputStreaming;
21687
22014
  const deferLoading = anthropicOptions == null ? undefined : anthropicOptions.deferLoading;
21688
22015
  const allowedCallers = anthropicOptions == null ? undefined : anthropicOptions.allowedCallers;
21689
22016
  if (!supportsStrictTools && tool2.strict != null) {
@@ -23061,6 +23388,144 @@ function mapAnthropicStopReason({
23061
23388
  return "other";
23062
23389
  }
23063
23390
  }
23391
+ var SUPPORTED_STRING_FORMATS = /* @__PURE__ */ new Set([
23392
+ "date-time",
23393
+ "time",
23394
+ "date",
23395
+ "duration",
23396
+ "email",
23397
+ "hostname",
23398
+ "uri",
23399
+ "ipv4",
23400
+ "ipv6",
23401
+ "uuid"
23402
+ ]);
23403
+ var DESCRIPTION_CONSTRAINT_KEYS = [
23404
+ "minimum",
23405
+ "maximum",
23406
+ "exclusiveMinimum",
23407
+ "exclusiveMaximum",
23408
+ "multipleOf",
23409
+ "minLength",
23410
+ "maxLength",
23411
+ "pattern",
23412
+ "minItems",
23413
+ "maxItems",
23414
+ "uniqueItems",
23415
+ "minProperties",
23416
+ "maxProperties",
23417
+ "not"
23418
+ ];
23419
+ function sanitizeJsonSchema(schema) {
23420
+ return sanitizeSchema(schema);
23421
+ }
23422
+ function sanitizeDefinition(definition) {
23423
+ if (typeof definition === "boolean" || !isPlainObject2(definition)) {
23424
+ return definition;
23425
+ }
23426
+ return sanitizeSchema(definition);
23427
+ }
23428
+ function sanitizeSchema(schema) {
23429
+ const result = {};
23430
+ const schemaWithDefs = schema;
23431
+ if (schema.$ref != null) {
23432
+ return { $ref: schema.$ref };
23433
+ }
23434
+ if (schema.$schema != null) {
23435
+ result.$schema = schema.$schema;
23436
+ }
23437
+ if (schema.$id != null) {
23438
+ result.$id = schema.$id;
23439
+ }
23440
+ if (schema.title != null) {
23441
+ result.title = schema.title;
23442
+ }
23443
+ if (schema.description != null) {
23444
+ result.description = schema.description;
23445
+ }
23446
+ if (schema.default !== undefined) {
23447
+ result.default = schema.default;
23448
+ }
23449
+ if (schema.const !== undefined) {
23450
+ result.const = schema.const;
23451
+ }
23452
+ if (schema.enum != null) {
23453
+ result.enum = schema.enum;
23454
+ }
23455
+ if (schema.type != null) {
23456
+ result.type = schema.type;
23457
+ }
23458
+ if (schema.anyOf != null) {
23459
+ result.anyOf = schema.anyOf.map(sanitizeDefinition);
23460
+ } else if (schema.oneOf != null) {
23461
+ result.anyOf = schema.oneOf.map(sanitizeDefinition);
23462
+ }
23463
+ if (schema.allOf != null) {
23464
+ result.allOf = schema.allOf.map(sanitizeDefinition);
23465
+ }
23466
+ if (schema.definitions != null) {
23467
+ result.definitions = Object.fromEntries(Object.entries(schema.definitions).map(([name15, definition]) => [
23468
+ name15,
23469
+ sanitizeDefinition(definition)
23470
+ ]));
23471
+ }
23472
+ if (schemaWithDefs.$defs != null) {
23473
+ const resultWithDefs = result;
23474
+ resultWithDefs.$defs = Object.fromEntries(Object.entries(schemaWithDefs.$defs).map(([name15, definition]) => [
23475
+ name15,
23476
+ sanitizeDefinition(definition)
23477
+ ]));
23478
+ }
23479
+ if (schema.type === "object" || schema.properties != null) {
23480
+ if (schema.properties != null) {
23481
+ result.properties = Object.fromEntries(Object.entries(schema.properties).map(([name15, definition]) => [
23482
+ name15,
23483
+ sanitizeDefinition(definition)
23484
+ ]));
23485
+ }
23486
+ result.additionalProperties = false;
23487
+ if (schema.required != null) {
23488
+ result.required = schema.required;
23489
+ }
23490
+ }
23491
+ if (schema.items != null) {
23492
+ result.items = Array.isArray(schema.items) ? schema.items.map(sanitizeDefinition) : sanitizeDefinition(schema.items);
23493
+ }
23494
+ if (typeof schema.format === "string" && SUPPORTED_STRING_FORMATS.has(schema.format)) {
23495
+ result.format = schema.format;
23496
+ }
23497
+ const constraintDescription = getConstraintDescription(schema);
23498
+ if (constraintDescription != null) {
23499
+ result.description = result.description == null ? constraintDescription : `${result.description}
23500
+ ${constraintDescription}`;
23501
+ }
23502
+ return result;
23503
+ }
23504
+ function getConstraintDescription(schema) {
23505
+ const descriptions = DESCRIPTION_CONSTRAINT_KEYS.flatMap((key) => {
23506
+ const value = schema[key];
23507
+ if (value == null || value === false) {
23508
+ return [];
23509
+ }
23510
+ return `${formatConstraintName(key)}: ${formatConstraintValue(value)}`;
23511
+ });
23512
+ if (typeof schema.format === "string" && !SUPPORTED_STRING_FORMATS.has(schema.format)) {
23513
+ descriptions.push(`format: ${schema.format}`);
23514
+ }
23515
+ return descriptions.length === 0 ? undefined : `${descriptions.join("; ")}.`;
23516
+ }
23517
+ function formatConstraintName(key) {
23518
+ return key.replace(/[A-Z]/g, (match) => ` ${match.toLowerCase()}`);
23519
+ }
23520
+ function formatConstraintValue(value) {
23521
+ if (typeof value === "string") {
23522
+ return value;
23523
+ }
23524
+ return JSON.stringify(value);
23525
+ }
23526
+ function isPlainObject2(value) {
23527
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23528
+ }
23064
23529
  function createCitationSource(citation, citationDocuments, generateId3) {
23065
23530
  var _a16;
23066
23531
  if (citation.type === "web_search_result_location") {
@@ -23145,7 +23610,7 @@ var AnthropicMessagesLanguageModel = class {
23145
23610
  providerOptions,
23146
23611
  stream
23147
23612
  }) {
23148
- var _a16, _b16, _c, _d, _e, _f, _g, _h, _i;
23613
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j;
23149
23614
  const warnings = [];
23150
23615
  if (frequencyPenalty != null) {
23151
23616
  warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
@@ -23196,8 +23661,35 @@ var AnthropicMessagesLanguageModel = class {
23196
23661
  const {
23197
23662
  maxOutputTokens: maxOutputTokensForModel,
23198
23663
  supportsStructuredOutput: modelSupportsStructuredOutput,
23664
+ rejectsSamplingParameters,
23199
23665
  isKnownModel
23200
23666
  } = getModelCapabilities(this.modelId);
23667
+ if (rejectsSamplingParameters) {
23668
+ if (temperature != null) {
23669
+ warnings.push({
23670
+ type: "unsupported",
23671
+ feature: "temperature",
23672
+ details: `temperature is not supported by ${this.modelId} and will be ignored`
23673
+ });
23674
+ temperature = undefined;
23675
+ }
23676
+ if (topK != null) {
23677
+ warnings.push({
23678
+ type: "unsupported",
23679
+ feature: "topK",
23680
+ details: `topK is not supported by ${this.modelId} and will be ignored`
23681
+ });
23682
+ topK = undefined;
23683
+ }
23684
+ if (topP != null) {
23685
+ warnings.push({
23686
+ type: "unsupported",
23687
+ feature: "topP",
23688
+ details: `topP is not supported by ${this.modelId} and will be ignored`
23689
+ });
23690
+ topP = undefined;
23691
+ }
23692
+ }
23201
23693
  const isAnthropicModel = isKnownModel || this.modelId.startsWith("claude-");
23202
23694
  const supportsStructuredOutput = ((_a16 = this.config.supportsNativeStructuredOutput) != null ? _a16 : true) && modelSupportsStructuredOutput;
23203
23695
  const supportsStrictTools = ((_b16 = this.config.supportsStrictTools) != null ? _b16 : true) && modelSupportsStructuredOutput;
@@ -23244,6 +23736,7 @@ var AnthropicMessagesLanguageModel = class {
23244
23736
  const thinkingType = (_e = anthropicOptions == null ? undefined : anthropicOptions.thinking) == null ? undefined : _e.type;
23245
23737
  const isThinking = thinkingType === "enabled" || thinkingType === "adaptive";
23246
23738
  let thinkingBudget = thinkingType === "enabled" ? (_f = anthropicOptions == null ? undefined : anthropicOptions.thinking) == null ? undefined : _f.budgetTokens : undefined;
23739
+ const thinkingDisplay = thinkingType === "adaptive" ? (_g = anthropicOptions == null ? undefined : anthropicOptions.thinking) == null ? undefined : _g.display : undefined;
23247
23740
  const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;
23248
23741
  const baseArgs = {
23249
23742
  model: this.modelId,
@@ -23255,18 +23748,28 @@ var AnthropicMessagesLanguageModel = class {
23255
23748
  ...isThinking && {
23256
23749
  thinking: {
23257
23750
  type: thinkingType,
23258
- ...thinkingBudget != null && { budget_tokens: thinkingBudget }
23751
+ ...thinkingBudget != null && { budget_tokens: thinkingBudget },
23752
+ ...thinkingDisplay != null && { display: thinkingDisplay }
23259
23753
  }
23260
23754
  },
23261
- ...((anthropicOptions == null ? undefined : anthropicOptions.effort) || useStructuredOutput && (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null) && {
23755
+ ...((anthropicOptions == null ? undefined : anthropicOptions.effort) || (anthropicOptions == null ? undefined : anthropicOptions.taskBudget) || useStructuredOutput && (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null) && {
23262
23756
  output_config: {
23263
23757
  ...(anthropicOptions == null ? undefined : anthropicOptions.effort) && {
23264
23758
  effort: anthropicOptions.effort
23265
23759
  },
23760
+ ...(anthropicOptions == null ? undefined : anthropicOptions.taskBudget) && {
23761
+ task_budget: {
23762
+ type: anthropicOptions.taskBudget.type,
23763
+ total: anthropicOptions.taskBudget.total,
23764
+ ...anthropicOptions.taskBudget.remaining != null && {
23765
+ remaining: anthropicOptions.taskBudget.remaining
23766
+ }
23767
+ }
23768
+ },
23266
23769
  ...useStructuredOutput && (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && {
23267
23770
  format: {
23268
23771
  type: "json_schema",
23269
- schema: responseFormat.schema
23772
+ schema: sanitizeJsonSchema(responseFormat.schema)
23270
23773
  }
23271
23774
  }
23272
23775
  }
@@ -23274,10 +23777,13 @@ var AnthropicMessagesLanguageModel = class {
23274
23777
  ...(anthropicOptions == null ? undefined : anthropicOptions.speed) && {
23275
23778
  speed: anthropicOptions.speed
23276
23779
  },
23780
+ ...(anthropicOptions == null ? undefined : anthropicOptions.inferenceGeo) && {
23781
+ inference_geo: anthropicOptions.inferenceGeo
23782
+ },
23277
23783
  ...(anthropicOptions == null ? undefined : anthropicOptions.cacheControl) && {
23278
23784
  cache_control: anthropicOptions.cacheControl
23279
23785
  },
23280
- ...((_g = anthropicOptions == null ? undefined : anthropicOptions.metadata) == null ? undefined : _g.userId) != null && {
23786
+ ...((_h = anthropicOptions == null ? undefined : anthropicOptions.metadata) == null ? undefined : _h.userId) != null && {
23281
23787
  metadata: { user_id: anthropicOptions.metadata.userId }
23282
23788
  },
23283
23789
  ...(anthropicOptions == null ? undefined : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && {
@@ -23436,12 +23942,13 @@ var AnthropicMessagesLanguageModel = class {
23436
23942
  if (anthropicOptions == null ? undefined : anthropicOptions.effort) {
23437
23943
  betas.add("effort-2025-11-24");
23438
23944
  }
23945
+ if (anthropicOptions == null ? undefined : anthropicOptions.taskBudget) {
23946
+ betas.add("task-budgets-2026-03-13");
23947
+ }
23439
23948
  if ((anthropicOptions == null ? undefined : anthropicOptions.speed) === "fast") {
23440
23949
  betas.add("fast-mode-2026-02-01");
23441
23950
  }
23442
- if (stream && ((_h = anthropicOptions == null ? undefined : anthropicOptions.toolStreaming) != null ? _h : true)) {
23443
- betas.add("fine-grained-tool-streaming-2025-05-14");
23444
- }
23951
+ const defaultEagerInputStreaming = stream && ((_i = anthropicOptions == null ? undefined : anthropicOptions.toolStreaming) != null ? _i : true);
23445
23952
  const {
23446
23953
  tools: anthropicTools2,
23447
23954
  toolChoice: anthropicToolChoice,
@@ -23453,14 +23960,16 @@ var AnthropicMessagesLanguageModel = class {
23453
23960
  disableParallelToolUse: true,
23454
23961
  cacheControlValidator,
23455
23962
  supportsStructuredOutput: false,
23456
- supportsStrictTools
23963
+ supportsStrictTools,
23964
+ defaultEagerInputStreaming
23457
23965
  } : {
23458
23966
  tools: tools != null ? tools : [],
23459
23967
  toolChoice,
23460
23968
  disableParallelToolUse: anthropicOptions == null ? undefined : anthropicOptions.disableParallelToolUse,
23461
23969
  cacheControlValidator,
23462
23970
  supportsStructuredOutput,
23463
- supportsStrictTools
23971
+ supportsStrictTools,
23972
+ defaultEagerInputStreaming
23464
23973
  });
23465
23974
  const cacheWarnings = cacheControlValidator.getWarnings();
23466
23975
  return {
@@ -23475,7 +23984,7 @@ var AnthropicMessagesLanguageModel = class {
23475
23984
  ...betas,
23476
23985
  ...toolsBetas,
23477
23986
  ...userSuppliedBetas,
23478
- ...(_i = anthropicOptions == null ? undefined : anthropicOptions.anthropicBeta) != null ? _i : []
23987
+ ...(_j = anthropicOptions == null ? undefined : anthropicOptions.anthropicBeta) != null ? _j : []
23479
23988
  ]),
23480
23989
  usesJsonResponseTool: jsonResponseTool != null,
23481
23990
  toolNameMapping,
@@ -24679,46 +25188,60 @@ var AnthropicMessagesLanguageModel = class {
24679
25188
  }
24680
25189
  };
24681
25190
  function getModelCapabilities(modelId) {
24682
- if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) {
25191
+ if (modelId.includes("claude-opus-4-7")) {
24683
25192
  return {
24684
25193
  maxOutputTokens: 128000,
24685
25194
  supportsStructuredOutput: true,
25195
+ rejectsSamplingParameters: true,
25196
+ isKnownModel: true
25197
+ };
25198
+ } else if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) {
25199
+ return {
25200
+ maxOutputTokens: 128000,
25201
+ supportsStructuredOutput: true,
25202
+ rejectsSamplingParameters: false,
24686
25203
  isKnownModel: true
24687
25204
  };
24688
25205
  } else if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) {
24689
25206
  return {
24690
25207
  maxOutputTokens: 64000,
24691
25208
  supportsStructuredOutput: true,
25209
+ rejectsSamplingParameters: false,
24692
25210
  isKnownModel: true
24693
25211
  };
24694
25212
  } else if (modelId.includes("claude-opus-4-1")) {
24695
25213
  return {
24696
25214
  maxOutputTokens: 32000,
24697
25215
  supportsStructuredOutput: true,
25216
+ rejectsSamplingParameters: false,
24698
25217
  isKnownModel: true
24699
25218
  };
24700
25219
  } else if (modelId.includes("claude-sonnet-4-")) {
24701
25220
  return {
24702
25221
  maxOutputTokens: 64000,
24703
25222
  supportsStructuredOutput: false,
25223
+ rejectsSamplingParameters: false,
24704
25224
  isKnownModel: true
24705
25225
  };
24706
25226
  } else if (modelId.includes("claude-opus-4-")) {
24707
25227
  return {
24708
25228
  maxOutputTokens: 32000,
24709
25229
  supportsStructuredOutput: false,
25230
+ rejectsSamplingParameters: false,
24710
25231
  isKnownModel: true
24711
25232
  };
24712
25233
  } else if (modelId.includes("claude-3-haiku")) {
24713
25234
  return {
24714
25235
  maxOutputTokens: 4096,
24715
25236
  supportsStructuredOutput: false,
25237
+ rejectsSamplingParameters: false,
24716
25238
  isKnownModel: true
24717
25239
  };
24718
25240
  } else {
24719
25241
  return {
24720
25242
  maxOutputTokens: 4096,
24721
25243
  supportsStructuredOutput: false,
25244
+ rejectsSamplingParameters: false,
24722
25245
  isKnownModel: false
24723
25246
  };
24724
25247
  }
@@ -25050,7 +25573,7 @@ function createAnthropic(options = {}) {
25050
25573
  var anthropic = createAnthropic();
25051
25574
 
25052
25575
  // node_modules/@ai-sdk/google/dist/index.mjs
25053
- var VERSION3 = "3.0.57";
25576
+ var VERSION3 = "3.0.67";
25054
25577
  var googleErrorDataSchema = lazySchema(() => zodSchema(exports_external.object({
25055
25578
  error: exports_external.object({
25056
25579
  code: exports_external.number().nullable(),
@@ -25692,8 +26215,14 @@ var googleLanguageModelOptions = lazySchema(() => zodSchema(exports_external.obj
25692
26215
  longitude: exports_external.number()
25693
26216
  }).optional()
25694
26217
  }).optional(),
26218
+ streamFunctionCallArguments: exports_external.boolean().optional(),
25695
26219
  serviceTier: exports_external.enum(["standard", "flex", "priority"]).optional()
25696
26220
  })));
26221
+ var VertexServiceTierMap = {
26222
+ standard: "SERVICE_TIER_STANDARD",
26223
+ flex: "SERVICE_TIER_FLEX",
26224
+ priority: "SERVICE_TIER_PRIORITY"
26225
+ };
25697
26226
  function prepareTools2({
25698
26227
  tools,
25699
26228
  toolChoice,
@@ -25766,7 +26295,7 @@ function prepareTools2({
25766
26295
  toolWarnings.push({
25767
26296
  type: "unsupported",
25768
26297
  feature: `provider-defined tool ${tool2.id}`,
25769
- details: "The code execution tools is not supported with other Gemini models than Gemini 2."
26298
+ details: "The code execution tool is not supported with other Gemini models than Gemini 2."
25770
26299
  });
25771
26300
  }
25772
26301
  break;
@@ -25941,6 +26470,172 @@ function prepareTools2({
25941
26470
  }
25942
26471
  }
25943
26472
  }
26473
+ var GoogleJSONAccumulator = class {
26474
+ constructor() {
26475
+ this.accumulatedArgs = {};
26476
+ this.jsonText = "";
26477
+ this.pathStack = [];
26478
+ this.stringOpen = false;
26479
+ }
26480
+ processPartialArgs(partialArgs) {
26481
+ let delta = "";
26482
+ for (const arg of partialArgs) {
26483
+ const rawPath = arg.jsonPath.replace(/^\$\./, "");
26484
+ if (!rawPath)
26485
+ continue;
26486
+ const segments = parsePath(rawPath);
26487
+ const existingValue = getNestedValue(this.accumulatedArgs, segments);
26488
+ const isStringContinuation = arg.stringValue != null && existingValue !== undefined;
26489
+ if (isStringContinuation) {
26490
+ const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
26491
+ setNestedValue(this.accumulatedArgs, segments, existingValue + arg.stringValue);
26492
+ delta += escaped;
26493
+ continue;
26494
+ }
26495
+ const resolved = resolvePartialArgValue(arg);
26496
+ if (resolved == null)
26497
+ continue;
26498
+ setNestedValue(this.accumulatedArgs, segments, resolved.value);
26499
+ delta += this.emitNavigationTo(segments, arg, resolved.json);
26500
+ }
26501
+ this.jsonText += delta;
26502
+ return {
26503
+ currentJSON: this.accumulatedArgs,
26504
+ textDelta: delta
26505
+ };
26506
+ }
26507
+ finalize() {
26508
+ const finalArgs = JSON.stringify(this.accumulatedArgs);
26509
+ const closingDelta = finalArgs.slice(this.jsonText.length);
26510
+ return { finalJSON: finalArgs, closingDelta };
26511
+ }
26512
+ ensureRoot() {
26513
+ if (this.pathStack.length === 0) {
26514
+ this.pathStack.push({ segment: "", isArray: false, childCount: 0 });
26515
+ return "{";
26516
+ }
26517
+ return "";
26518
+ }
26519
+ emitNavigationTo(targetSegments, arg, valueJson) {
26520
+ let fragment = "";
26521
+ if (this.stringOpen) {
26522
+ fragment += '"';
26523
+ this.stringOpen = false;
26524
+ }
26525
+ fragment += this.ensureRoot();
26526
+ const targetContainerSegments = targetSegments.slice(0, -1);
26527
+ const leafSegment = targetSegments[targetSegments.length - 1];
26528
+ const commonDepth = this.findCommonStackDepth(targetContainerSegments);
26529
+ fragment += this.closeDownTo(commonDepth);
26530
+ fragment += this.openDownTo(targetContainerSegments, leafSegment);
26531
+ fragment += this.emitLeaf(leafSegment, arg, valueJson);
26532
+ return fragment;
26533
+ }
26534
+ findCommonStackDepth(targetContainer) {
26535
+ const maxDepth = Math.min(this.pathStack.length - 1, targetContainer.length);
26536
+ let common = 0;
26537
+ for (let i = 0;i < maxDepth; i++) {
26538
+ if (this.pathStack[i + 1].segment === targetContainer[i]) {
26539
+ common++;
26540
+ } else {
26541
+ break;
26542
+ }
26543
+ }
26544
+ return common + 1;
26545
+ }
26546
+ closeDownTo(targetDepth) {
26547
+ let fragment = "";
26548
+ while (this.pathStack.length > targetDepth) {
26549
+ const entry = this.pathStack.pop();
26550
+ fragment += entry.isArray ? "]" : "}";
26551
+ }
26552
+ return fragment;
26553
+ }
26554
+ openDownTo(targetContainer, leafSegment) {
26555
+ let fragment = "";
26556
+ const startIdx = this.pathStack.length - 1;
26557
+ for (let i = startIdx;i < targetContainer.length; i++) {
26558
+ const seg = targetContainer[i];
26559
+ const parentEntry = this.pathStack[this.pathStack.length - 1];
26560
+ if (parentEntry.childCount > 0) {
26561
+ fragment += ",";
26562
+ }
26563
+ parentEntry.childCount++;
26564
+ if (typeof seg === "string") {
26565
+ fragment += `${JSON.stringify(seg)}:`;
26566
+ }
26567
+ const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment;
26568
+ const isArray = typeof childSeg === "number";
26569
+ fragment += isArray ? "[" : "{";
26570
+ this.pathStack.push({ segment: seg, isArray, childCount: 0 });
26571
+ }
26572
+ return fragment;
26573
+ }
26574
+ emitLeaf(leafSegment, arg, valueJson) {
26575
+ let fragment = "";
26576
+ const container = this.pathStack[this.pathStack.length - 1];
26577
+ if (container.childCount > 0) {
26578
+ fragment += ",";
26579
+ }
26580
+ container.childCount++;
26581
+ if (typeof leafSegment === "string") {
26582
+ fragment += `${JSON.stringify(leafSegment)}:`;
26583
+ }
26584
+ if (arg.stringValue != null && arg.willContinue) {
26585
+ fragment += valueJson.slice(0, -1);
26586
+ this.stringOpen = true;
26587
+ } else {
26588
+ fragment += valueJson;
26589
+ }
26590
+ return fragment;
26591
+ }
26592
+ };
26593
+ function parsePath(rawPath) {
26594
+ const segments = [];
26595
+ for (const part of rawPath.split(".")) {
26596
+ const bracketIdx = part.indexOf("[");
26597
+ if (bracketIdx === -1) {
26598
+ segments.push(part);
26599
+ } else {
26600
+ if (bracketIdx > 0)
26601
+ segments.push(part.slice(0, bracketIdx));
26602
+ for (const m of part.matchAll(/\[(\d+)\]/g)) {
26603
+ segments.push(parseInt(m[1], 10));
26604
+ }
26605
+ }
26606
+ }
26607
+ return segments;
26608
+ }
26609
+ function getNestedValue(obj, segments) {
26610
+ let current = obj;
26611
+ for (const seg of segments) {
26612
+ if (current == null || typeof current !== "object")
26613
+ return;
26614
+ current = current[seg];
26615
+ }
26616
+ return current;
26617
+ }
26618
+ function setNestedValue(obj, segments, value) {
26619
+ let current = obj;
26620
+ for (let i = 0;i < segments.length - 1; i++) {
26621
+ const seg = segments[i];
26622
+ const nextSeg = segments[i + 1];
26623
+ if (current[seg] == null) {
26624
+ current[seg] = typeof nextSeg === "number" ? [] : {};
26625
+ }
26626
+ current = current[seg];
26627
+ }
26628
+ current[segments[segments.length - 1]] = value;
26629
+ }
26630
+ function resolvePartialArgValue(arg) {
26631
+ var _a16, _b16;
26632
+ const value = (_b16 = (_a16 = arg.stringValue) != null ? _a16 : arg.numberValue) != null ? _b16 : arg.boolValue;
26633
+ if (value != null)
26634
+ return { value, json: JSON.stringify(value) };
26635
+ if ("nullValue" in arg)
26636
+ return { value: null, json: "null" };
26637
+ return;
26638
+ }
25944
26639
  function mapGoogleGenerativeAIFinishReason({
25945
26640
  finishReason,
25946
26641
  hasToolCalls
@@ -25994,8 +26689,8 @@ var GoogleGenerativeAILanguageModel = class {
25994
26689
  tools,
25995
26690
  toolChoice,
25996
26691
  providerOptions
25997
- }) {
25998
- var _a16;
26692
+ }, { isStreaming = false } = {}) {
26693
+ var _a16, _b16;
25999
26694
  const warnings = [];
26000
26695
  const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
26001
26696
  let googleOptions = await parseProviderOptions({
@@ -26010,12 +26705,23 @@ var GoogleGenerativeAILanguageModel = class {
26010
26705
  schema: googleLanguageModelOptions
26011
26706
  });
26012
26707
  }
26013
- if ((tools == null ? undefined : tools.some((tool2) => tool2.type === "provider" && tool2.id === "google.vertex_rag_store")) && !this.config.provider.startsWith("google.vertex.")) {
26708
+ const isVertexProvider = this.config.provider.startsWith("google.vertex.");
26709
+ if ((tools == null ? undefined : tools.some((tool2) => tool2.type === "provider" && tool2.id === "google.vertex_rag_store")) && !isVertexProvider) {
26014
26710
  warnings.push({
26015
26711
  type: "other",
26016
26712
  message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`
26017
26713
  });
26018
26714
  }
26715
+ if ((googleOptions == null ? undefined : googleOptions.streamFunctionCallArguments) && !isVertexProvider) {
26716
+ warnings.push({
26717
+ type: "other",
26718
+ message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`
26719
+ });
26720
+ }
26721
+ let sanitizedServiceTier = googleOptions == null ? undefined : googleOptions.serviceTier;
26722
+ if ((googleOptions == null ? undefined : googleOptions.serviceTier) && isVertexProvider) {
26723
+ sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier];
26724
+ }
26019
26725
  const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
26020
26726
  const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3");
26021
26727
  const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt, {
@@ -26032,6 +26738,19 @@ var GoogleGenerativeAILanguageModel = class {
26032
26738
  toolChoice,
26033
26739
  modelId: this.modelId
26034
26740
  });
26741
+ const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a16 = googleOptions == null ? undefined : googleOptions.streamFunctionCallArguments) != null ? _a16 : false : undefined;
26742
+ const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? undefined : googleOptions.retrievalConfig) ? {
26743
+ ...googleToolConfig,
26744
+ ...streamFunctionCallArguments && {
26745
+ functionCallingConfig: {
26746
+ ...googleToolConfig == null ? undefined : googleToolConfig.functionCallingConfig,
26747
+ streamFunctionCallArguments: true
26748
+ }
26749
+ },
26750
+ ...(googleOptions == null ? undefined : googleOptions.retrievalConfig) && {
26751
+ retrievalConfig: googleOptions.retrievalConfig
26752
+ }
26753
+ } : undefined;
26035
26754
  return {
26036
26755
  args: {
26037
26756
  generationConfig: {
@@ -26044,7 +26763,7 @@ var GoogleGenerativeAILanguageModel = class {
26044
26763
  stopSequences,
26045
26764
  seed,
26046
26765
  responseMimeType: (responseFormat == null ? undefined : responseFormat.type) === "json" ? "application/json" : undefined,
26047
- responseSchema: (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && ((_a16 = googleOptions == null ? undefined : googleOptions.structuredOutputs) != null ? _a16 : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : undefined,
26766
+ responseSchema: (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && ((_b16 = googleOptions == null ? undefined : googleOptions.structuredOutputs) != null ? _b16 : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : undefined,
26048
26767
  ...(googleOptions == null ? undefined : googleOptions.audioTimestamp) && {
26049
26768
  audioTimestamp: googleOptions.audioTimestamp
26050
26769
  },
@@ -26061,13 +26780,10 @@ var GoogleGenerativeAILanguageModel = class {
26061
26780
  systemInstruction: isGemmaModel ? undefined : systemInstruction,
26062
26781
  safetySettings: googleOptions == null ? undefined : googleOptions.safetySettings,
26063
26782
  tools: googleTools2,
26064
- toolConfig: (googleOptions == null ? undefined : googleOptions.retrievalConfig) ? {
26065
- ...googleToolConfig,
26066
- retrievalConfig: googleOptions.retrievalConfig
26067
- } : googleToolConfig,
26783
+ toolConfig,
26068
26784
  cachedContent: googleOptions == null ? undefined : googleOptions.cachedContent,
26069
26785
  labels: googleOptions == null ? undefined : googleOptions.labels,
26070
- serviceTier: googleOptions == null ? undefined : googleOptions.serviceTier
26786
+ serviceTier: sanitizedServiceTier
26071
26787
  },
26072
26788
  warnings: [...warnings, ...toolWarnings],
26073
26789
  providerOptionsName
@@ -26136,7 +26852,7 @@ var GoogleGenerativeAILanguageModel = class {
26136
26852
  providerMetadata: thoughtSignatureMetadata
26137
26853
  });
26138
26854
  }
26139
- } else if ("functionCall" in part) {
26855
+ } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
26140
26856
  content.push({
26141
26857
  type: "tool-call",
26142
26858
  toolCallId: this.config.generateId(),
@@ -26245,7 +26961,7 @@ var GoogleGenerativeAILanguageModel = class {
26245
26961
  };
26246
26962
  }
26247
26963
  async doStream(options) {
26248
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
26964
+ const { args, warnings, providerOptionsName } = await this.getArgs(options, { isStreaming: true });
26249
26965
  const headers = combineHeaders(await resolve(this.config.headers), options.headers);
26250
26966
  const { responseHeaders, value: response } = await postJsonToApi({
26251
26967
  url: `${this.config.baseURL}/${getModelPath(this.modelId)}:streamGenerateContent?alt=sse`,
@@ -26273,13 +26989,14 @@ var GoogleGenerativeAILanguageModel = class {
26273
26989
  const emittedSourceUrls = /* @__PURE__ */ new Set;
26274
26990
  let lastCodeExecutionToolCallId;
26275
26991
  let lastServerToolCallId;
26992
+ const activeStreamingToolCalls = [];
26276
26993
  return {
26277
26994
  stream: response.pipeThrough(new TransformStream({
26278
26995
  start(controller) {
26279
26996
  controller.enqueue({ type: "stream-start", warnings });
26280
26997
  },
26281
26998
  transform(chunk, controller) {
26282
- var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k;
26999
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
26283
27000
  if (options.includeRawChunks) {
26284
27001
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
26285
27002
  }
@@ -26472,36 +27189,107 @@ var GoogleGenerativeAILanguageModel = class {
26472
27189
  lastServerToolCallId = undefined;
26473
27190
  }
26474
27191
  }
26475
- const toolCallDeltas = getToolCallsFromParts({
26476
- parts: content.parts,
26477
- generateId: generateId3,
26478
- providerOptionsName
26479
- });
26480
- if (toolCallDeltas != null) {
26481
- for (const toolCall of toolCallDeltas) {
27192
+ for (const part of parts) {
27193
+ if (!("functionCall" in part))
27194
+ continue;
27195
+ const providerMeta = part.thoughtSignature ? {
27196
+ [providerOptionsName]: {
27197
+ thoughtSignature: part.thoughtSignature
27198
+ }
27199
+ } : undefined;
27200
+ const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
27201
+ const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
27202
+ const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
27203
+ if (isStreamingChunk) {
27204
+ if (part.functionCall.name != null && part.functionCall.willContinue === true) {
27205
+ const toolCallId = generateId3();
27206
+ const accumulator = new GoogleJSONAccumulator;
27207
+ activeStreamingToolCalls.push({
27208
+ toolCallId,
27209
+ toolName: part.functionCall.name,
27210
+ accumulator,
27211
+ providerMetadata: providerMeta
27212
+ });
27213
+ controller.enqueue({
27214
+ type: "tool-input-start",
27215
+ id: toolCallId,
27216
+ toolName: part.functionCall.name,
27217
+ providerMetadata: providerMeta
27218
+ });
27219
+ if (part.functionCall.partialArgs != null) {
27220
+ const { textDelta } = accumulator.processPartialArgs(part.functionCall.partialArgs);
27221
+ if (textDelta.length > 0) {
27222
+ controller.enqueue({
27223
+ type: "tool-input-delta",
27224
+ id: toolCallId,
27225
+ delta: textDelta,
27226
+ providerMetadata: providerMeta
27227
+ });
27228
+ }
27229
+ }
27230
+ } else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
27231
+ const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
27232
+ const { textDelta } = active.accumulator.processPartialArgs(part.functionCall.partialArgs);
27233
+ if (textDelta.length > 0) {
27234
+ controller.enqueue({
27235
+ type: "tool-input-delta",
27236
+ id: active.toolCallId,
27237
+ delta: textDelta,
27238
+ providerMetadata: providerMeta
27239
+ });
27240
+ }
27241
+ }
27242
+ } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) {
27243
+ const active = activeStreamingToolCalls.pop();
27244
+ const { finalJSON, closingDelta } = active.accumulator.finalize();
27245
+ if (closingDelta.length > 0) {
27246
+ controller.enqueue({
27247
+ type: "tool-input-delta",
27248
+ id: active.toolCallId,
27249
+ delta: closingDelta,
27250
+ providerMetadata: active.providerMetadata
27251
+ });
27252
+ }
27253
+ controller.enqueue({
27254
+ type: "tool-input-end",
27255
+ id: active.toolCallId,
27256
+ providerMetadata: active.providerMetadata
27257
+ });
27258
+ controller.enqueue({
27259
+ type: "tool-call",
27260
+ toolCallId: active.toolCallId,
27261
+ toolName: active.toolName,
27262
+ input: finalJSON,
27263
+ providerMetadata: active.providerMetadata
27264
+ });
27265
+ hasToolCalls = true;
27266
+ } else if (isCompleteCall) {
27267
+ const toolCallId = generateId3();
27268
+ const toolName = part.functionCall.name;
27269
+ const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {});
26482
27270
  controller.enqueue({
26483
27271
  type: "tool-input-start",
26484
- id: toolCall.toolCallId,
26485
- toolName: toolCall.toolName,
26486
- providerMetadata: toolCall.providerMetadata
27272
+ id: toolCallId,
27273
+ toolName,
27274
+ providerMetadata: providerMeta
26487
27275
  });
26488
27276
  controller.enqueue({
26489
27277
  type: "tool-input-delta",
26490
- id: toolCall.toolCallId,
26491
- delta: toolCall.args,
26492
- providerMetadata: toolCall.providerMetadata
27278
+ id: toolCallId,
27279
+ delta: args2,
27280
+ providerMetadata: providerMeta
26493
27281
  });
26494
27282
  controller.enqueue({
26495
27283
  type: "tool-input-end",
26496
- id: toolCall.toolCallId,
26497
- providerMetadata: toolCall.providerMetadata
27284
+ id: toolCallId,
27285
+ providerMetadata: providerMeta
26498
27286
  });
26499
27287
  controller.enqueue({
26500
27288
  type: "tool-call",
26501
- toolCallId: toolCall.toolCallId,
26502
- toolName: toolCall.toolName,
26503
- input: toolCall.args,
26504
- providerMetadata: toolCall.providerMetadata
27289
+ toolCallId,
27290
+ toolName,
27291
+ input: args2,
27292
+ providerMetadata: providerMeta
26505
27293
  });
26506
27294
  hasToolCalls = true;
26507
27295
  }
@@ -26517,12 +27305,12 @@ var GoogleGenerativeAILanguageModel = class {
26517
27305
  };
26518
27306
  providerMetadata = {
26519
27307
  [providerOptionsName]: {
26520
- promptFeedback: (_i = value.promptFeedback) != null ? _i : null,
27308
+ promptFeedback: (_j = value.promptFeedback) != null ? _j : null,
26521
27309
  groundingMetadata: lastGroundingMetadata,
26522
27310
  urlContextMetadata: lastUrlContextMetadata,
26523
- safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null,
27311
+ safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null,
26524
27312
  usageMetadata: usageMetadata != null ? usageMetadata : null,
26525
- finishMessage: (_k = candidate.finishMessage) != null ? _k : null,
27313
+ finishMessage: (_l = candidate.finishMessage) != null ? _l : null,
26526
27314
  serviceTier
26527
27315
  }
26528
27316
  };
@@ -26554,24 +27342,6 @@ var GoogleGenerativeAILanguageModel = class {
26554
27342
  };
26555
27343
  }
26556
27344
  };
26557
- function getToolCallsFromParts({
26558
- parts,
26559
- generateId: generateId3,
26560
- providerOptionsName
26561
- }) {
26562
- const functionCallParts = parts == null ? undefined : parts.filter((part) => ("functionCall" in part));
26563
- return functionCallParts == null || functionCallParts.length === 0 ? undefined : functionCallParts.map((part) => ({
26564
- type: "tool-call",
26565
- toolCallId: generateId3(),
26566
- toolName: part.functionCall.name,
26567
- args: JSON.stringify(part.functionCall.args),
26568
- providerMetadata: part.thoughtSignature ? {
26569
- [providerOptionsName]: {
26570
- thoughtSignature: part.thoughtSignature
26571
- }
26572
- } : undefined
26573
- }));
26574
- }
26575
27345
  function extractSources({
26576
27346
  groundingMetadata,
26577
27347
  generateId: generateId3
@@ -26709,12 +27479,22 @@ var getGroundingMetadataSchema = () => exports_external.object({
26709
27479
  exports_external.object({})
26710
27480
  ]).nullish()
26711
27481
  });
27482
+ var partialArgSchema = exports_external.object({
27483
+ jsonPath: exports_external.string(),
27484
+ stringValue: exports_external.string().nullish(),
27485
+ numberValue: exports_external.number().nullish(),
27486
+ boolValue: exports_external.boolean().nullish(),
27487
+ nullValue: exports_external.unknown().nullish(),
27488
+ willContinue: exports_external.boolean().nullish()
27489
+ });
26712
27490
  var getContentSchema = () => exports_external.object({
26713
27491
  parts: exports_external.array(exports_external.union([
26714
27492
  exports_external.object({
26715
27493
  functionCall: exports_external.object({
26716
- name: exports_external.string(),
26717
- args: exports_external.unknown()
27494
+ name: exports_external.string().nullish(),
27495
+ args: exports_external.unknown().nullish(),
27496
+ partialArgs: exports_external.array(partialArgSchema).nullish(),
27497
+ willContinue: exports_external.boolean().nullish()
26718
27498
  }),
26719
27499
  thoughtSignature: exports_external.string().nullish()
26720
27500
  }),
@@ -26765,13 +27545,19 @@ var getSafetyRatingSchema = () => exports_external.object({
26765
27545
  severityScore: exports_external.number().nullish(),
26766
27546
  blocked: exports_external.boolean().nullish()
26767
27547
  });
27548
+ var tokenDetailsSchema = exports_external.array(exports_external.object({
27549
+ modality: exports_external.string(),
27550
+ tokenCount: exports_external.number()
27551
+ })).nullish();
26768
27552
  var usageSchema = exports_external.object({
26769
27553
  cachedContentTokenCount: exports_external.number().nullish(),
26770
27554
  thoughtsTokenCount: exports_external.number().nullish(),
26771
27555
  promptTokenCount: exports_external.number().nullish(),
26772
27556
  candidatesTokenCount: exports_external.number().nullish(),
26773
27557
  totalTokenCount: exports_external.number().nullish(),
26774
- trafficType: exports_external.string().nullish()
27558
+ trafficType: exports_external.string().nullish(),
27559
+ promptTokensDetails: tokenDetailsSchema,
27560
+ candidatesTokensDetails: tokenDetailsSchema
26775
27561
  });
26776
27562
  var getUrlContextMetadataSchema = () => exports_external.object({
26777
27563
  urlMetadata: exports_external.array(exports_external.object({
@@ -27457,6 +28243,9 @@ function convertOpenAIChatUsage(usage) {
27457
28243
  raw: usage
27458
28244
  };
27459
28245
  }
28246
+ function serializeToolCallArguments(input) {
28247
+ return JSON.stringify(input === undefined ? {} : input);
28248
+ }
27460
28249
  function convertToOpenAIChatMessages({
27461
28250
  prompt,
27462
28251
  systemMessageMode = "system"
@@ -27584,7 +28373,7 @@ function convertToOpenAIChatMessages({
27584
28373
  type: "function",
27585
28374
  function: {
27586
28375
  name: part.toolName,
27587
- arguments: JSON.stringify(part.input)
28376
+ arguments: serializeToolCallArguments(part.input)
27588
28377
  }
27589
28378
  });
27590
28379
  break;
@@ -27593,7 +28382,7 @@ function convertToOpenAIChatMessages({
27593
28382
  }
27594
28383
  messages.push({
27595
28384
  role: "assistant",
27596
- content: text,
28385
+ content: text || null,
27597
28386
  tool_calls: toolCalls.length > 0 ? toolCalls : undefined
27598
28387
  });
27599
28388
  break;
@@ -28808,17 +29597,34 @@ var modelMaxImagesPerCall = {
28808
29597
  "gpt-image-1": 10,
28809
29598
  "gpt-image-1-mini": 10,
28810
29599
  "gpt-image-1.5": 10,
29600
+ "gpt-image-2": 10,
28811
29601
  "chatgpt-image-latest": 10
28812
29602
  };
28813
29603
  var defaultResponseFormatPrefixes = [
28814
29604
  "chatgpt-image-",
28815
29605
  "gpt-image-1-mini",
28816
29606
  "gpt-image-1.5",
28817
- "gpt-image-1"
29607
+ "gpt-image-1",
29608
+ "gpt-image-2"
28818
29609
  ];
28819
29610
  function hasDefaultResponseFormat(modelId) {
28820
29611
  return defaultResponseFormatPrefixes.some((prefix) => modelId.startsWith(prefix));
28821
29612
  }
29613
+ var baseImageModelOptionsObject = exports_external.object({
29614
+ quality: exports_external.enum(["standard", "hd", "low", "medium", "high", "auto"]).optional(),
29615
+ background: exports_external.enum(["transparent", "opaque", "auto"]).optional(),
29616
+ outputFormat: exports_external.enum(["png", "jpeg", "webp"]).optional(),
29617
+ outputCompression: exports_external.number().int().min(0).max(100).optional(),
29618
+ user: exports_external.string().optional()
29619
+ });
29620
+ var openaiImageModelOptions = lazySchema(() => zodSchema(baseImageModelOptionsObject));
29621
+ var openaiImageModelGenerationOptions = lazySchema(() => zodSchema(baseImageModelOptionsObject.extend({
29622
+ style: exports_external.enum(["vivid", "natural"]).optional(),
29623
+ moderation: exports_external.enum(["auto", "low"]).optional()
29624
+ })));
29625
+ var openaiImageModelEditOptions = lazySchema(() => zodSchema(baseImageModelOptionsObject.extend({
29626
+ inputFidelity: exports_external.enum(["high", "low"]).optional()
29627
+ })));
28822
29628
  var OpenAIImageModel = class {
28823
29629
  constructor(modelId, config2) {
28824
29630
  this.modelId = modelId;
@@ -28858,6 +29664,11 @@ var OpenAIImageModel = class {
28858
29664
  }
28859
29665
  const currentDate = (_c = (_b16 = (_a16 = this.config._internal) == null ? undefined : _a16.currentDate) == null ? undefined : _b16.call(_a16)) != null ? _c : /* @__PURE__ */ new Date;
28860
29666
  if (files != null) {
29667
+ const openaiOptions2 = (_d = await parseProviderOptions({
29668
+ provider: "openai",
29669
+ providerOptions,
29670
+ schema: openaiImageModelEditOptions
29671
+ })) != null ? _d : {};
28861
29672
  const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({
28862
29673
  url: this.config.url({
28863
29674
  path: "/images/edits",
@@ -28877,7 +29688,12 @@ var OpenAIImageModel = class {
28877
29688
  mask: mask != null ? await fileToBlob(mask) : undefined,
28878
29689
  n,
28879
29690
  size,
28880
- ...(_d = providerOptions.openai) != null ? _d : {}
29691
+ quality: openaiOptions2.quality,
29692
+ background: openaiOptions2.background,
29693
+ output_format: openaiOptions2.outputFormat,
29694
+ output_compression: openaiOptions2.outputCompression,
29695
+ input_fidelity: openaiOptions2.inputFidelity,
29696
+ user: openaiOptions2.user
28881
29697
  }),
28882
29698
  failedResponseHandler: openaiFailedResponseHandler,
28883
29699
  successfulResponseHandler: createJsonResponseHandler(openaiImageResponseSchema),
@@ -28915,6 +29731,11 @@ var OpenAIImageModel = class {
28915
29731
  }
28916
29732
  };
28917
29733
  }
29734
+ const openaiOptions = (_h = await parseProviderOptions({
29735
+ provider: "openai",
29736
+ providerOptions,
29737
+ schema: openaiImageModelGenerationOptions
29738
+ })) != null ? _h : {};
28918
29739
  const { value: response, responseHeaders } = await postJsonToApi({
28919
29740
  url: this.config.url({
28920
29741
  path: "/images/generations",
@@ -28926,7 +29747,13 @@ var OpenAIImageModel = class {
28926
29747
  prompt,
28927
29748
  n,
28928
29749
  size,
28929
- ...(_h = providerOptions.openai) != null ? _h : {},
29750
+ quality: openaiOptions.quality,
29751
+ style: openaiOptions.style,
29752
+ background: openaiOptions.background,
29753
+ moderation: openaiOptions.moderation,
29754
+ output_format: openaiOptions.outputFormat,
29755
+ output_compression: openaiOptions.outputCompression,
29756
+ user: openaiOptions.user,
28930
29757
  ...!hasDefaultResponseFormat(this.modelId) ? { response_format: "b64_json" } : {}
28931
29758
  },
28932
29759
  failedResponseHandler: openaiFailedResponseHandler,
@@ -29402,6 +30229,9 @@ function convertOpenAIResponsesUsage(usage) {
29402
30229
  raw: usage
29403
30230
  };
29404
30231
  }
30232
+ function serializeToolCallArguments2(input) {
30233
+ return JSON.stringify(input === undefined ? {} : input);
30234
+ }
29405
30235
  function isFileId(data, prefixes) {
29406
30236
  if (!prefixes)
29407
30237
  return false;
@@ -29622,7 +30452,7 @@ async function convertToOpenAIResponsesInput({
29622
30452
  type: "function_call",
29623
30453
  call_id: part.toolCallId,
29624
30454
  name: resolvedToolName,
29625
- arguments: JSON.stringify(part.input),
30455
+ arguments: serializeToolCallArguments2(part.input),
29626
30456
  id
29627
30457
  });
29628
30458
  break;
@@ -30090,7 +30920,8 @@ var openaiResponsesChunkSchema = lazySchema(() => zodSchema(exports_external.uni
30090
30920
  id: exports_external.string(),
30091
30921
  call_id: exports_external.string(),
30092
30922
  name: exports_external.string(),
30093
- arguments: exports_external.string()
30923
+ arguments: exports_external.string(),
30924
+ namespace: exports_external.string().nullish()
30094
30925
  }),
30095
30926
  exports_external.object({
30096
30927
  type: exports_external.literal("web_search_call"),
@@ -30228,7 +31059,8 @@ var openaiResponsesChunkSchema = lazySchema(() => zodSchema(exports_external.uni
30228
31059
  call_id: exports_external.string(),
30229
31060
  name: exports_external.string(),
30230
31061
  arguments: exports_external.string(),
30231
- status: exports_external.literal("completed")
31062
+ status: exports_external.literal("completed"),
31063
+ namespace: exports_external.string().nullish()
30232
31064
  }),
30233
31065
  exports_external.object({
30234
31066
  type: exports_external.literal("custom_tool_call"),
@@ -30652,7 +31484,8 @@ var openaiResponsesResponseSchema = lazySchema(() => zodSchema(exports_external.
30652
31484
  call_id: exports_external.string(),
30653
31485
  name: exports_external.string(),
30654
31486
  arguments: exports_external.string(),
30655
- id: exports_external.string()
31487
+ id: exports_external.string(),
31488
+ namespace: exports_external.string().nullish()
30656
31489
  }),
30657
31490
  exports_external.object({
30658
31491
  type: exports_external.literal("custom_tool_call"),
@@ -31682,7 +32515,8 @@ var OpenAIResponsesLanguageModel = class {
31682
32515
  input: part.arguments,
31683
32516
  providerMetadata: {
31684
32517
  [providerOptionsName]: {
31685
- itemId: part.id
32518
+ itemId: part.id,
32519
+ ...part.namespace != null && { namespace: part.namespace }
31686
32520
  }
31687
32521
  }
31688
32522
  });
@@ -32146,7 +32980,14 @@ var OpenAIResponsesLanguageModel = class {
32146
32980
  hasFunctionCall = true;
32147
32981
  controller.enqueue({
32148
32982
  type: "tool-input-end",
32149
- id: value.item.call_id
32983
+ id: value.item.call_id,
32984
+ ...value.item.namespace != null && {
32985
+ providerMetadata: {
32986
+ [providerOptionsName]: {
32987
+ namespace: value.item.namespace
32988
+ }
32989
+ }
32990
+ }
32150
32991
  });
32151
32992
  controller.enqueue({
32152
32993
  type: "tool-call",
@@ -32155,7 +32996,10 @@ var OpenAIResponsesLanguageModel = class {
32155
32996
  input: value.item.arguments,
32156
32997
  providerMetadata: {
32157
32998
  [providerOptionsName]: {
32158
- itemId: value.item.id
32999
+ itemId: value.item.id,
33000
+ ...value.item.namespace != null && {
33001
+ namespace: value.item.namespace
33002
+ }
32159
33003
  }
32160
33004
  }
32161
33005
  });
@@ -33085,7 +33929,7 @@ var OpenAITranscriptionModel = class {
33085
33929
  };
33086
33930
  }
33087
33931
  };
33088
- var VERSION4 = "3.0.50";
33932
+ var VERSION4 = "3.0.58";
33089
33933
  function createOpenAI(options = {}) {
33090
33934
  var _a16, _b16;
33091
33935
  const baseURL = (_a16 = withoutTrailingSlash(loadOptionalSetting({
@@ -33178,6 +34022,16 @@ function createOpenAI(options = {}) {
33178
34022
  var openai = createOpenAI();
33179
34023
 
33180
34024
  // node_modules/@ai-sdk/openai-compatible/dist/index.mjs
34025
+ function toCamelCase(str) {
34026
+ return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
34027
+ }
34028
+ function resolveProviderOptionsKey(rawName, providerOptions) {
34029
+ const camelName = toCamelCase(rawName);
34030
+ if (camelName !== rawName && (providerOptions == null ? undefined : providerOptions[camelName]) != null) {
34031
+ return camelName;
34032
+ }
34033
+ return rawName;
34034
+ }
33181
34035
  var openaiCompatibleErrorDataSchema = exports_external.object({
33182
34036
  error: exports_external.object({
33183
34037
  message: exports_external.string(),
@@ -33374,7 +34228,7 @@ function convertToOpenAICompatibleChatMessages(prompt) {
33374
34228
  }
33375
34229
  messages.push({
33376
34230
  role: "assistant",
33377
- content: text,
34231
+ content: text || null,
33378
34232
  ...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
33379
34233
  tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
33380
34234
  ...metadata
@@ -33531,6 +34385,10 @@ var OpenAICompatibleChatLanguageModel = class {
33531
34385
  var _a16, _b16, _c;
33532
34386
  return (_c = (_b16 = (_a16 = this.config).transformRequestBody) == null ? undefined : _b16.call(_a16, args)) != null ? _c : args;
33533
34387
  }
34388
+ convertUsage(usage) {
34389
+ var _a16, _b16, _c;
34390
+ return (_c = (_b16 = (_a16 = this.config).convertUsage) == null ? undefined : _b16.call(_a16, usage)) != null ? _c : convertOpenAICompatibleChatUsage(usage);
34391
+ }
33534
34392
  async getArgs({
33535
34393
  prompt,
33536
34394
  maxOutputTokens,
@@ -33567,8 +34425,12 @@ var OpenAICompatibleChatLanguageModel = class {
33567
34425
  provider: this.providerOptionsName,
33568
34426
  providerOptions,
33569
34427
  schema: openaiCompatibleLanguageModelChatOptions
33570
- })) != null ? _b16 : {});
33571
- const strictJsonSchema = (_c = compatibleOptions == null ? undefined : compatibleOptions.strictJsonSchema) != null ? _c : true;
34428
+ })) != null ? _b16 : {}, (_c = await parseProviderOptions({
34429
+ provider: toCamelCase(this.providerOptionsName),
34430
+ providerOptions,
34431
+ schema: openaiCompatibleLanguageModelChatOptions
34432
+ })) != null ? _c : {});
34433
+ const strictJsonSchema = (_d = compatibleOptions == null ? undefined : compatibleOptions.strictJsonSchema) != null ? _d : true;
33572
34434
  if (topK != null) {
33573
34435
  warnings.push({ type: "unsupported", feature: "topK" });
33574
34436
  }
@@ -33587,7 +34449,9 @@ var OpenAICompatibleChatLanguageModel = class {
33587
34449
  tools,
33588
34450
  toolChoice
33589
34451
  });
34452
+ const metadataKey = resolveProviderOptionsKey(this.providerOptionsName, providerOptions);
33590
34453
  return {
34454
+ metadataKey,
33591
34455
  args: {
33592
34456
  model: this.modelId,
33593
34457
  user: compatibleOptions.user,
@@ -33601,13 +34465,16 @@ var OpenAICompatibleChatLanguageModel = class {
33601
34465
  json_schema: {
33602
34466
  schema: responseFormat.schema,
33603
34467
  strict: strictJsonSchema,
33604
- name: (_d = responseFormat.name) != null ? _d : "response",
34468
+ name: (_e = responseFormat.name) != null ? _e : "response",
33605
34469
  description: responseFormat.description
33606
34470
  }
33607
34471
  } : { type: "json_object" } : undefined,
33608
34472
  stop: stopSequences,
33609
34473
  seed,
33610
- ...Object.fromEntries(Object.entries((_e = providerOptions == null ? undefined : providerOptions[this.providerOptionsName]) != null ? _e : {}).filter(([key]) => !Object.keys(openaiCompatibleLanguageModelChatOptions.shape).includes(key))),
34474
+ ...Object.fromEntries(Object.entries({
34475
+ ...providerOptions == null ? undefined : providerOptions[this.providerOptionsName],
34476
+ ...providerOptions == null ? undefined : providerOptions[toCamelCase(this.providerOptionsName)]
34477
+ }).filter(([key]) => !Object.keys(openaiCompatibleLanguageModelChatOptions.shape).includes(key))),
33611
34478
  reasoning_effort: compatibleOptions.reasoningEffort,
33612
34479
  verbosity: compatibleOptions.textVerbosity,
33613
34480
  messages: convertToOpenAICompatibleChatMessages(prompt),
@@ -33619,7 +34486,7 @@ var OpenAICompatibleChatLanguageModel = class {
33619
34486
  }
33620
34487
  async doGenerate(options) {
33621
34488
  var _a16, _b16, _c, _d, _e, _f, _g, _h;
33622
- const { args, warnings } = await this.getArgs({ ...options });
34489
+ const { args, warnings, metadataKey } = await this.getArgs({ ...options });
33623
34490
  const transformedBody = this.transformRequestBody(args);
33624
34491
  const body = JSON.stringify(transformedBody);
33625
34492
  const {
@@ -33661,24 +34528,24 @@ var OpenAICompatibleChatLanguageModel = class {
33661
34528
  input: toolCall.function.arguments,
33662
34529
  ...thoughtSignature ? {
33663
34530
  providerMetadata: {
33664
- [this.providerOptionsName]: { thoughtSignature }
34531
+ [metadataKey]: { thoughtSignature }
33665
34532
  }
33666
34533
  } : {}
33667
34534
  });
33668
34535
  }
33669
34536
  }
33670
34537
  const providerMetadata = {
33671
- [this.providerOptionsName]: {},
34538
+ [metadataKey]: {},
33672
34539
  ...await ((_f = (_e = this.config.metadataExtractor) == null ? undefined : _e.extractMetadata) == null ? undefined : _f.call(_e, {
33673
34540
  parsedBody: rawResponse
33674
34541
  }))
33675
34542
  };
33676
34543
  const completionTokenDetails = (_g = responseBody.usage) == null ? undefined : _g.completion_tokens_details;
33677
34544
  if ((completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens) != null) {
33678
- providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens;
34545
+ providerMetadata[metadataKey].acceptedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens;
33679
34546
  }
33680
34547
  if ((completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens) != null) {
33681
- providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens;
34548
+ providerMetadata[metadataKey].rejectedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens;
33682
34549
  }
33683
34550
  return {
33684
34551
  content,
@@ -33686,7 +34553,7 @@ var OpenAICompatibleChatLanguageModel = class {
33686
34553
  unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
33687
34554
  raw: (_h = choice.finish_reason) != null ? _h : undefined
33688
34555
  },
33689
- usage: convertOpenAICompatibleChatUsage(responseBody.usage),
34556
+ usage: this.convertUsage(responseBody.usage),
33690
34557
  providerMetadata,
33691
34558
  request: { body },
33692
34559
  response: {
@@ -33699,7 +34566,7 @@ var OpenAICompatibleChatLanguageModel = class {
33699
34566
  }
33700
34567
  async doStream(options) {
33701
34568
  var _a16;
33702
- const { args, warnings } = await this.getArgs({ ...options });
34569
+ const { args, warnings, metadataKey } = await this.getArgs({ ...options });
33703
34570
  const body = this.transformRequestBody({
33704
34571
  ...args,
33705
34572
  stream: true,
@@ -33725,9 +34592,10 @@ var OpenAICompatibleChatLanguageModel = class {
33725
34592
  };
33726
34593
  let usage = undefined;
33727
34594
  let isFirstChunk = true;
33728
- const providerOptionsName = this.providerOptionsName;
34595
+ const providerOptionsName = metadataKey;
33729
34596
  let isActiveReasoning = false;
33730
34597
  let isActiveText = false;
34598
+ const convertUsage = (usage2) => this.convertUsage(usage2);
33731
34599
  return {
33732
34600
  stream: response.pipeThrough(new TransformStream({
33733
34601
  start(controller) {
@@ -33952,7 +34820,7 @@ var OpenAICompatibleChatLanguageModel = class {
33952
34820
  controller.enqueue({
33953
34821
  type: "finish",
33954
34822
  finishReason,
33955
- usage: convertOpenAICompatibleChatUsage(usage),
34823
+ usage: convertUsage(usage),
33956
34824
  providerMetadata
33957
34825
  });
33958
34826
  }
@@ -34205,13 +35073,17 @@ var OpenAICompatibleCompletionLanguageModel = class {
34205
35073
  tools,
34206
35074
  toolChoice
34207
35075
  }) {
34208
- var _a16;
35076
+ var _a16, _b16;
34209
35077
  const warnings = [];
34210
- const completionOptions = (_a16 = await parseProviderOptions({
35078
+ const completionOptions = Object.assign((_a16 = await parseProviderOptions({
34211
35079
  provider: this.providerOptionsName,
34212
35080
  providerOptions,
34213
35081
  schema: openaiCompatibleLanguageModelCompletionOptions
34214
- })) != null ? _a16 : {};
35082
+ })) != null ? _a16 : {}, (_b16 = await parseProviderOptions({
35083
+ provider: toCamelCase(this.providerOptionsName),
35084
+ providerOptions,
35085
+ schema: openaiCompatibleLanguageModelCompletionOptions
35086
+ })) != null ? _b16 : {});
34215
35087
  if (topK != null) {
34216
35088
  warnings.push({ type: "unsupported", feature: "topK" });
34217
35089
  }
@@ -34244,6 +35116,7 @@ var OpenAICompatibleCompletionLanguageModel = class {
34244
35116
  presence_penalty: presencePenalty,
34245
35117
  seed,
34246
35118
  ...providerOptions == null ? undefined : providerOptions[this.providerOptionsName],
35119
+ ...providerOptions == null ? undefined : providerOptions[toCamelCase(this.providerOptionsName)],
34247
35120
  prompt: completionPrompt,
34248
35121
  stop: stop.length > 0 ? stop : undefined
34249
35122
  },
@@ -34621,10 +35494,7 @@ async function fileToBlob2(file2) {
34621
35494
  const data = file2.data instanceof Uint8Array ? file2.data : convertBase64ToUint8Array(file2.data);
34622
35495
  return new Blob([data], { type: file2.mediaType });
34623
35496
  }
34624
- function toCamelCase(str) {
34625
- return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
34626
- }
34627
- var VERSION5 = "2.0.38";
35497
+ var VERSION5 = "2.0.45";
34628
35498
  function createOpenAICompatible(options) {
34629
35499
  const baseURL = withoutTrailingSlash(options.baseURL);
34630
35500
  const providerName = options.name;
@@ -34650,8 +35520,10 @@ function createOpenAICompatible(options) {
34650
35520
  ...getCommonModelConfig("chat"),
34651
35521
  includeUsage: options.includeUsage,
34652
35522
  supportsStructuredOutputs: options.supportsStructuredOutputs,
35523
+ supportedUrls: options.supportedUrls,
34653
35524
  transformRequestBody: options.transformRequestBody,
34654
- metadataExtractor: options.metadataExtractor
35525
+ metadataExtractor: options.metadataExtractor,
35526
+ convertUsage: options.convertUsage
34655
35527
  });
34656
35528
  const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, {
34657
35529
  ...getCommonModelConfig("completion"),
@@ -34959,6 +35831,19 @@ var gatewayErrorResponseSchema = lazySchema(() => zodSchema(exports_external.obj
34959
35831
  }),
34960
35832
  generationId: exports_external.string().nullish()
34961
35833
  })));
35834
+ function extractApiCallResponse(error40) {
35835
+ if (error40.data !== undefined) {
35836
+ return error40.data;
35837
+ }
35838
+ if (error40.responseBody != null) {
35839
+ try {
35840
+ return JSON.parse(error40.responseBody);
35841
+ } catch (e) {
35842
+ return error40.responseBody;
35843
+ }
35844
+ }
35845
+ return {};
35846
+ }
34962
35847
  var name72 = "GatewayTimeoutError";
34963
35848
  var marker82 = `vercel.ai.gateway.error.${name72}`;
34964
35849
  var symbol82 = Symbol.for(marker82);
@@ -35045,19 +35930,6 @@ async function asGatewayError(error40, authMethod) {
35045
35930
  authMethod
35046
35931
  });
35047
35932
  }
35048
- function extractApiCallResponse(error40) {
35049
- if (error40.data !== undefined) {
35050
- return error40.data;
35051
- }
35052
- if (error40.responseBody != null) {
35053
- try {
35054
- return JSON.parse(error40.responseBody);
35055
- } catch (e) {
35056
- return error40.responseBody;
35057
- }
35058
- }
35059
- return {};
35060
- }
35061
35933
  var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
35062
35934
  async function parseAuthMethod(headers) {
35063
35935
  const result = await safeValidateTypes({
@@ -35067,6 +35939,13 @@ async function parseAuthMethod(headers) {
35067
35939
  return result.success ? result.value : undefined;
35068
35940
  }
35069
35941
  var gatewayAuthMethodSchema = lazySchema(() => zodSchema(exports_external.union([exports_external.literal("api-key"), exports_external.literal("oidc")])));
35942
+ var KNOWN_MODEL_TYPES = [
35943
+ "embedding",
35944
+ "image",
35945
+ "language",
35946
+ "reranking",
35947
+ "video"
35948
+ ];
35070
35949
  var GatewayFetchMetadata = class {
35071
35950
  constructor(config2) {
35072
35951
  this.config = config2;
@@ -35128,8 +36007,8 @@ var gatewayAvailableModelsResponseSchema = lazySchema(() => zodSchema(exports_ex
35128
36007
  provider: exports_external.string(),
35129
36008
  modelId: exports_external.string()
35130
36009
  }),
35131
- modelType: exports_external.enum(["embedding", "image", "language", "video"]).nullish()
35132
- }))
36010
+ modelType: exports_external.string().nullish()
36011
+ })).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)))
35133
36012
  })));
35134
36013
  var gatewayCreditsResponseSchema = lazySchema(() => zodSchema(exports_external.object({
35135
36014
  balance: exports_external.string(),
@@ -35801,6 +36680,73 @@ var gatewayVideoEventSchema = exports_external.discriminatedUnion("type", [
35801
36680
  param: exports_external.unknown().nullable()
35802
36681
  })
35803
36682
  ]);
36683
+ var GatewayRerankingModel = class {
36684
+ constructor(modelId, config2) {
36685
+ this.modelId = modelId;
36686
+ this.config = config2;
36687
+ this.specificationVersion = "v3";
36688
+ }
36689
+ get provider() {
36690
+ return this.config.provider;
36691
+ }
36692
+ async doRerank({
36693
+ documents,
36694
+ query,
36695
+ topN,
36696
+ headers,
36697
+ abortSignal,
36698
+ providerOptions
36699
+ }) {
36700
+ const resolvedHeaders = await resolve(this.config.headers());
36701
+ try {
36702
+ const {
36703
+ responseHeaders,
36704
+ value: responseBody,
36705
+ rawValue
36706
+ } = await postJsonToApi({
36707
+ url: this.getUrl(),
36708
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
36709
+ body: {
36710
+ documents,
36711
+ query,
36712
+ ...topN != null ? { topN } : {},
36713
+ ...providerOptions ? { providerOptions } : {}
36714
+ },
36715
+ successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
36716
+ failedResponseHandler: createJsonErrorResponseHandler({
36717
+ errorSchema: exports_external.any(),
36718
+ errorToMessage: (data) => data
36719
+ }),
36720
+ ...abortSignal && { abortSignal },
36721
+ fetch: this.config.fetch
36722
+ });
36723
+ return {
36724
+ ranking: responseBody.ranking,
36725
+ providerMetadata: responseBody.providerMetadata,
36726
+ response: { headers: responseHeaders, body: rawValue },
36727
+ warnings: []
36728
+ };
36729
+ } catch (error40) {
36730
+ throw await asGatewayError(error40, await parseAuthMethod(resolvedHeaders));
36731
+ }
36732
+ }
36733
+ getUrl() {
36734
+ return `${this.config.baseURL}/reranking-model`;
36735
+ }
36736
+ getModelConfigHeaders() {
36737
+ return {
36738
+ "ai-reranking-model-specification-version": "3",
36739
+ "ai-model-id": this.modelId
36740
+ };
36741
+ }
36742
+ };
36743
+ var gatewayRerankingResponseSchema = lazySchema(() => zodSchema(exports_external.object({
36744
+ ranking: exports_external.array(exports_external.object({
36745
+ index: exports_external.number(),
36746
+ relevanceScore: exports_external.number()
36747
+ })),
36748
+ providerMetadata: exports_external.record(exports_external.string(), exports_external.record(exports_external.string(), exports_external.unknown())).optional()
36749
+ })));
35804
36750
  var parallelSearchInputSchema = lazySchema(() => zodSchema(exports_external2.object({
35805
36751
  objective: exports_external2.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),
35806
36752
  search_queries: exports_external2.array(exports_external2.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),
@@ -35900,7 +36846,7 @@ async function getVercelRequestId() {
35900
36846
  var _a92;
35901
36847
  return (_a92 = import_oidc.getContext().headers) == null ? undefined : _a92["x-vercel-id"];
35902
36848
  }
35903
- var VERSION6 = "3.0.87";
36849
+ var VERSION6 = "3.0.109";
35904
36850
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
35905
36851
  function createGatewayProvider(options = {}) {
35906
36852
  var _a92, _b92;
@@ -36050,6 +36996,17 @@ function createGatewayProvider(options = {}) {
36050
36996
  o11yHeaders: createO11yHeaders()
36051
36997
  });
36052
36998
  };
36999
+ const createRerankingModel = (modelId) => {
37000
+ return new GatewayRerankingModel(modelId, {
37001
+ provider: "gateway",
37002
+ baseURL,
37003
+ headers: getHeaders,
37004
+ fetch: options.fetch,
37005
+ o11yHeaders: createO11yHeaders()
37006
+ });
37007
+ };
37008
+ provider.rerankingModel = createRerankingModel;
37009
+ provider.reranking = createRerankingModel;
36053
37010
  provider.chat = provider.languageModel;
36054
37011
  provider.embedding = provider.embeddingModel;
36055
37012
  provider.image = provider.imageModel;
@@ -36647,7 +37604,7 @@ function detectMediaType({
36647
37604
  }
36648
37605
  return;
36649
37606
  }
36650
- var VERSION7 = "6.0.145";
37607
+ var VERSION7 = "6.0.174";
36651
37608
  var download = async ({
36652
37609
  url: url2,
36653
37610
  maxBytes,
@@ -37401,33 +38358,35 @@ var modelMessageSchema = exports_external.union([
37401
38358
  assistantModelMessageSchema,
37402
38359
  toolModelMessageSchema
37403
38360
  ]);
37404
- async function standardizePrompt(prompt) {
37405
- if (prompt.prompt == null && prompt.messages == null) {
38361
+ async function standardizePrompt({
38362
+ allowSystemInMessages,
38363
+ system,
38364
+ prompt,
38365
+ messages
38366
+ }) {
38367
+ if (prompt == null && messages == null) {
37406
38368
  throw new InvalidPromptError({
37407
38369
  prompt,
37408
38370
  message: "prompt or messages must be defined"
37409
38371
  });
37410
38372
  }
37411
- if (prompt.prompt != null && prompt.messages != null) {
38373
+ if (prompt != null && messages != null) {
37412
38374
  throw new InvalidPromptError({
37413
38375
  prompt,
37414
38376
  message: "prompt and messages cannot be defined at the same time"
37415
38377
  });
37416
38378
  }
37417
- if (prompt.system != null && typeof prompt.system !== "string" && !asArray(prompt.system).every((message) => typeof message === "object" && message !== null && ("role" in message) && message.role === "system")) {
38379
+ if (typeof system !== "string" && !asArray(system).every((message) => message.role === "system")) {
37418
38380
  throw new InvalidPromptError({
37419
38381
  prompt,
37420
38382
  message: "system must be a string, SystemModelMessage, or array of SystemModelMessage"
37421
38383
  });
37422
38384
  }
37423
- let messages;
37424
- if (prompt.prompt != null && typeof prompt.prompt === "string") {
37425
- messages = [{ role: "user", content: prompt.prompt }];
37426
- } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {
37427
- messages = prompt.prompt;
37428
- } else if (prompt.messages != null) {
37429
- messages = prompt.messages;
37430
- } else {
38385
+ if (prompt != null && typeof prompt === "string") {
38386
+ messages = [{ role: "user", content: prompt }];
38387
+ } else if (prompt != null && Array.isArray(prompt)) {
38388
+ messages = prompt;
38389
+ } else if (messages == null) {
37431
38390
  throw new InvalidPromptError({
37432
38391
  prompt,
37433
38392
  message: "prompt or messages must be defined"
@@ -37439,6 +38398,17 @@ async function standardizePrompt(prompt) {
37439
38398
  message: "messages must not be empty"
37440
38399
  });
37441
38400
  }
38401
+ if (messages.some((message) => message.role === "system")) {
38402
+ if (allowSystemInMessages === false) {
38403
+ throw new InvalidPromptError({
38404
+ prompt,
38405
+ message: "System messages are not allowed in the prompt or messages fields. Use the system option instead."
38406
+ });
38407
+ }
38408
+ if (allowSystemInMessages === undefined) {
38409
+ console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.");
38410
+ }
38411
+ }
37442
38412
  const validationResult = await safeValidateTypes({
37443
38413
  value: messages,
37444
38414
  schema: exports_external.array(modelMessageSchema)
@@ -37450,10 +38420,7 @@ async function standardizePrompt(prompt) {
37450
38420
  cause: validationResult.error
37451
38421
  });
37452
38422
  }
37453
- return {
37454
- messages,
37455
- system: prompt.system
37456
- };
38423
+ return { messages, system };
37457
38424
  }
37458
38425
  function wrapGatewayError(error40) {
37459
38426
  if (!GatewayAuthenticationError.isInstance(error40))
@@ -37755,6 +38722,9 @@ function mergeObjects(base, overrides) {
37755
38722
  }
37756
38723
  const result = { ...base };
37757
38724
  for (const key in overrides) {
38725
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
38726
+ continue;
38727
+ }
37758
38728
  if (Object.prototype.hasOwnProperty.call(overrides, key)) {
37759
38729
  const overridesValue = overrides[key];
37760
38730
  if (overridesValue === undefined)
@@ -38785,6 +39755,15 @@ var json2 = ({
38785
39755
  }
38786
39756
  };
38787
39757
  };
39758
+ function mergeToolProviderMetadata(toolMetadata, callMetadata) {
39759
+ if (toolMetadata == null) {
39760
+ return callMetadata;
39761
+ }
39762
+ if (callMetadata == null) {
39763
+ return toolMetadata;
39764
+ }
39765
+ return { ...toolMetadata, ...callMetadata };
39766
+ }
38788
39767
  async function parseToolCall({
38789
39768
  toolCall,
38790
39769
  tools,
@@ -38792,7 +39771,7 @@ async function parseToolCall({
38792
39771
  system,
38793
39772
  messages
38794
39773
  }) {
38795
- var _a21;
39774
+ var _a21, _b16;
38796
39775
  try {
38797
39776
  if (tools == null) {
38798
39777
  if (toolCall.providerExecuted && toolCall.dynamic) {
@@ -38843,7 +39822,7 @@ async function parseToolCall({
38843
39822
  error: error40,
38844
39823
  title: (_a21 = tools == null ? undefined : tools[toolCall.toolName]) == null ? undefined : _a21.title,
38845
39824
  providerExecuted: toolCall.providerExecuted,
38846
- providerMetadata: toolCall.providerMetadata
39825
+ providerMetadata: mergeToolProviderMetadata((_b16 = tools == null ? undefined : tools[toolCall.toolName]) == null ? undefined : _b16.providerMetadata, toolCall.providerMetadata)
38847
39826
  };
38848
39827
  }
38849
39828
  }
@@ -38890,13 +39869,14 @@ async function doParseToolCall({
38890
39869
  cause: parseResult.error
38891
39870
  });
38892
39871
  }
39872
+ const mergedProviderMetadata = mergeToolProviderMetadata(tool2.providerMetadata, toolCall.providerMetadata);
38893
39873
  return tool2.type === "dynamic" ? {
38894
39874
  type: "tool-call",
38895
39875
  toolCallId: toolCall.toolCallId,
38896
39876
  toolName: toolCall.toolName,
38897
39877
  input: parseResult.value,
38898
39878
  providerExecuted: toolCall.providerExecuted,
38899
- providerMetadata: toolCall.providerMetadata,
39879
+ providerMetadata: mergedProviderMetadata,
38900
39880
  dynamic: true,
38901
39881
  title: tool2.title
38902
39882
  } : {
@@ -38905,7 +39885,7 @@ async function doParseToolCall({
38905
39885
  toolName,
38906
39886
  input: parseResult.value,
38907
39887
  providerExecuted: toolCall.providerExecuted,
38908
- providerMetadata: toolCall.providerMetadata,
39888
+ providerMetadata: mergedProviderMetadata,
38909
39889
  title: tool2.title
38910
39890
  };
38911
39891
  }
@@ -39026,7 +40006,7 @@ async function toResponseMessages({
39026
40006
  type: "tool-call",
39027
40007
  toolCallId: part.toolCallId,
39028
40008
  toolName: part.toolName,
39029
- input: part.input,
40009
+ input: part.invalid && typeof part.input !== "object" ? {} : part.input,
39030
40010
  providerExecuted: part.providerExecuted,
39031
40011
  providerOptions: part.providerMetadata
39032
40012
  });
@@ -39139,6 +40119,7 @@ async function generateText({
39139
40119
  system,
39140
40120
  prompt,
39141
40121
  messages,
40122
+ allowSystemInMessages,
39142
40123
  maxRetries: maxRetriesArg,
39143
40124
  abortSignal,
39144
40125
  timeout,
@@ -39188,7 +40169,8 @@ async function generateText({
39188
40169
  const initialPrompt = await standardizePrompt({
39189
40170
  system,
39190
40171
  prompt,
39191
- messages
40172
+ messages,
40173
+ allowSystemInMessages
39192
40174
  });
39193
40175
  const globalTelemetry = createGlobalTelemetry(telemetry == null ? undefined : telemetry.integrations);
39194
40176
  await notify({
@@ -39310,22 +40292,6 @@ async function generateText({
39310
40292
  content: toolContent
39311
40293
  });
39312
40294
  }
39313
- const providerExecutedToolApprovals = [
39314
- ...approvedToolApprovals,
39315
- ...deniedToolApprovals
39316
- ].filter((toolApproval) => toolApproval.toolCall.providerExecuted);
39317
- if (providerExecutedToolApprovals.length > 0) {
39318
- responseMessages.push({
39319
- role: "tool",
39320
- content: providerExecutedToolApprovals.map((toolApproval) => ({
39321
- type: "tool-approval-response",
39322
- approvalId: toolApproval.approvalResponse.approvalId,
39323
- approved: toolApproval.approvalResponse.approved,
39324
- reason: toolApproval.approvalResponse.reason,
39325
- providerExecuted: true
39326
- }))
39327
- });
39328
- }
39329
40295
  const callSettings2 = prepareCallSettings(settings);
39330
40296
  let currentModelResponse;
39331
40297
  let clientToolCalls = [];
@@ -40396,15 +41362,6 @@ var defaultDownload2 = createDownload();
40396
41362
 
40397
41363
  // src/lib/types.ts
40398
41364
  var OPENROUTER_MODELS2 = [
40399
- {
40400
- id: "minimax/minimax-m2.5:free",
40401
- name: "MiniMax M2.5 Free",
40402
- description: "Free MiniMax model for trying out open-source generation",
40403
- category: "smart",
40404
- provider: "openrouter",
40405
- contextLength: 196608,
40406
- free: true
40407
- },
40408
41365
  {
40409
41366
  id: "xiaomi/mimo-v2.5",
40410
41367
  name: "MiMo V2.5",
@@ -40437,6 +41394,38 @@ var OPENROUTER_MODELS2 = [
40437
41394
  provider: "openrouter",
40438
41395
  contextLength: 202752
40439
41396
  },
41397
+ {
41398
+ id: "openai/gpt-latest",
41399
+ name: "OpenAI GPT Latest",
41400
+ description: "OpenRouter alias that redirects to the latest OpenAI GPT model",
41401
+ category: "smart",
41402
+ provider: "openrouter",
41403
+ contextLength: 1050000
41404
+ },
41405
+ {
41406
+ id: "openai/gpt-5.5",
41407
+ name: "GPT 5.5",
41408
+ description: "OpenAI's latest flagship GPT model",
41409
+ category: "smart",
41410
+ provider: "openrouter",
41411
+ contextLength: 1050000
41412
+ },
41413
+ {
41414
+ id: "anthropic/claude-sonnet-latest",
41415
+ name: "Claude Sonnet Latest",
41416
+ description: "OpenRouter alias that redirects to the latest Claude Sonnet model",
41417
+ category: "smart",
41418
+ provider: "openrouter",
41419
+ contextLength: 1e6
41420
+ },
41421
+ {
41422
+ id: "anthropic/claude-sonnet-4.6",
41423
+ name: "Claude Sonnet 4.6",
41424
+ description: "Anthropic's latest Sonnet model",
41425
+ category: "smart",
41426
+ provider: "openrouter",
41427
+ contextLength: 1e6
41428
+ },
40440
41429
  {
40441
41430
  id: "moonshotai/kimi-k2.6",
40442
41431
  name: "Kimi K2.6",
@@ -40469,6 +41458,30 @@ var OPENROUTER_MODELS2 = [
40469
41458
  provider: "openrouter",
40470
41459
  contextLength: 196608
40471
41460
  },
41461
+ {
41462
+ id: "anthropic/claude-opus-latest",
41463
+ name: "Claude Opus Latest",
41464
+ description: "OpenRouter alias that redirects to the latest Claude Opus model",
41465
+ category: "reasoning",
41466
+ provider: "openrouter",
41467
+ contextLength: 1e6
41468
+ },
41469
+ {
41470
+ id: "anthropic/claude-opus-4.7",
41471
+ name: "Claude Opus 4.7",
41472
+ description: "Anthropic's latest Opus model",
41473
+ category: "reasoning",
41474
+ provider: "openrouter",
41475
+ contextLength: 1e6
41476
+ },
41477
+ {
41478
+ id: "openai/gpt-5.5-pro",
41479
+ name: "GPT 5.5 Pro",
41480
+ description: "OpenAI's latest high-capability reasoning model",
41481
+ category: "reasoning",
41482
+ provider: "openrouter",
41483
+ contextLength: 1050000
41484
+ },
40472
41485
  {
40473
41486
  id: "moonshotai/kimi-k2-thinking",
40474
41487
  name: "Kimi K2 Thinking",
@@ -40478,16 +41491,109 @@ var OPENROUTER_MODELS2 = [
40478
41491
  contextLength: 262144
40479
41492
  }
40480
41493
  ];
40481
- var OPENCODE_ZEN_MODELS2 = [
41494
+ var VERCEL_AI_GATEWAY_MODELS2 = [
41495
+ {
41496
+ id: "openai/gpt-latest",
41497
+ name: "OpenAI GPT Latest",
41498
+ description: "Vercel AI Gateway alias that redirects to the latest OpenAI GPT model",
41499
+ category: "smart",
41500
+ provider: "vercel-ai-gateway",
41501
+ contextLength: 1050000
41502
+ },
41503
+ {
41504
+ id: "openai/gpt-5.5",
41505
+ name: "GPT 5.5",
41506
+ description: "OpenAI's latest flagship GPT model",
41507
+ category: "smart",
41508
+ provider: "vercel-ai-gateway",
41509
+ contextLength: 1050000
41510
+ },
40482
41511
  {
40483
- id: "minimax-m2.5-free",
40484
- name: "MiniMax M2.5 Free",
40485
- description: "MiniMax's free model (limited time)",
41512
+ id: "anthropic/claude-sonnet-4.6",
41513
+ name: "Claude Sonnet 4.6",
41514
+ description: "Anthropic's latest Sonnet model",
41515
+ category: "smart",
41516
+ provider: "vercel-ai-gateway",
41517
+ contextLength: 1e6
41518
+ },
41519
+ {
41520
+ id: "anthropic/claude-opus-4.7",
41521
+ name: "Claude Opus 4.7",
41522
+ description: "Anthropic's latest Opus model",
41523
+ category: "reasoning",
41524
+ provider: "vercel-ai-gateway",
41525
+ contextLength: 1e6
41526
+ },
41527
+ {
41528
+ id: "openai/gpt-5.5-pro",
41529
+ name: "GPT 5.5 Pro",
41530
+ description: "OpenAI's latest high-capability reasoning model",
41531
+ category: "reasoning",
41532
+ provider: "vercel-ai-gateway",
41533
+ contextLength: 1050000
41534
+ }
41535
+ ];
41536
+ var CLOUDFLARE_AI_GATEWAY_MODELS2 = [
41537
+ {
41538
+ id: "openai/gpt-5.5",
41539
+ name: "GPT 5.5",
41540
+ description: "OpenAI's latest flagship GPT model through Cloudflare AI Gateway",
41541
+ category: "smart",
41542
+ provider: "cloudflare-ai-gateway",
41543
+ contextLength: 1050000
41544
+ },
41545
+ {
41546
+ id: "anthropic/claude-sonnet-4-6",
41547
+ name: "Claude Sonnet 4.6",
41548
+ description: "Anthropic's latest Sonnet model through Cloudflare AI Gateway",
41549
+ category: "smart",
41550
+ provider: "cloudflare-ai-gateway",
41551
+ contextLength: 1e6
41552
+ },
41553
+ {
41554
+ id: "anthropic/claude-opus-4-7",
41555
+ name: "Claude Opus 4.7",
41556
+ description: "Anthropic's latest Opus model through Cloudflare AI Gateway",
41557
+ category: "reasoning",
41558
+ provider: "cloudflare-ai-gateway",
41559
+ contextLength: 1e6
41560
+ },
41561
+ {
41562
+ id: "workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast",
41563
+ name: "Workers AI Llama 3.3 70B Fast",
41564
+ description: "Cloudflare Workers AI fast Llama model routed through AI Gateway",
41565
+ category: "smart",
41566
+ provider: "cloudflare-ai-gateway",
41567
+ contextLength: 24000
41568
+ }
41569
+ ];
41570
+ var WORKERS_AI_MODELS2 = [
41571
+ {
41572
+ id: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
41573
+ name: "Llama 3.3 70B Fast",
41574
+ description: "Cloudflare Workers AI fast Llama instruct model",
41575
+ category: "smart",
41576
+ provider: "workers-ai",
41577
+ contextLength: 24000
41578
+ },
41579
+ {
41580
+ id: "@cf/meta/llama-3.1-8b-instruct",
41581
+ name: "Llama 3.1 8B Instruct",
41582
+ description: "Cloudflare Workers AI lightweight Llama instruct model",
40486
41583
  category: "fast",
40487
- provider: "opencode-zen",
40488
- contextLength: 196608,
40489
- free: true
41584
+ provider: "workers-ai",
41585
+ contextLength: 8000
40490
41586
  },
41587
+ {
41588
+ id: "@cf/openai/gpt-oss-120b",
41589
+ name: "GPT OSS 120B",
41590
+ description: "OpenAI open-weight model hosted by Cloudflare Workers AI",
41591
+ category: "reasoning",
41592
+ provider: "workers-ai",
41593
+ contextLength: 32000
41594
+ }
41595
+ ];
41596
+ var OPENCODE_ZEN_MODELS2 = [
40491
41597
  {
40492
41598
  id: "kimi-k2.6-free",
40493
41599
  name: "Kimi K2.6 Free",
@@ -40514,23 +41620,6 @@ var OPENCODE_ZEN_MODELS2 = [
40514
41620
  provider: "opencode-zen",
40515
41621
  contextLength: 1048576
40516
41622
  },
40517
- {
40518
- id: "gpt-5-nano",
40519
- name: "GPT 5 Nano",
40520
- description: "OpenAI's fastest GPT model (free)",
40521
- category: "fast",
40522
- provider: "opencode-zen",
40523
- contextLength: 200000,
40524
- free: true
40525
- },
40526
- {
40527
- id: "claude-3-5-haiku",
40528
- name: "Claude Haiku 3.5",
40529
- description: "Anthropic's fast and efficient model",
40530
- category: "fast",
40531
- provider: "opencode-zen",
40532
- contextLength: 200000
40533
- },
40534
41623
  {
40535
41624
  id: "claude-haiku-4-5",
40536
41625
  name: "Claude Haiku 4.5",
@@ -40548,84 +41637,68 @@ var OPENCODE_ZEN_MODELS2 = [
40548
41637
  contextLength: 200000
40549
41638
  },
40550
41639
  {
40551
- id: "gpt-5.1-codex-mini",
40552
- name: "GPT 5.1 Codex Mini",
40553
- description: "OpenAI's fast codex model",
41640
+ id: "gpt-5.4-mini",
41641
+ name: "GPT 5.4 Mini",
41642
+ description: "OpenAI's latest fast GPT mini model",
40554
41643
  category: "fast",
40555
41644
  provider: "opencode-zen",
40556
- contextLength: 200000
41645
+ contextLength: 400000
40557
41646
  },
40558
41647
  {
40559
- id: "deepseek-v4-flash",
40560
- name: "DeepSeek V4 Flash",
40561
- description: "DeepSeek's latest fast open-source model",
41648
+ id: "gpt-5.4-nano",
41649
+ name: "GPT 5.4 Nano",
41650
+ description: "OpenAI's latest lightweight GPT model",
40562
41651
  category: "fast",
40563
41652
  provider: "opencode-zen",
40564
- contextLength: 1048576
41653
+ contextLength: 400000
40565
41654
  },
40566
41655
  {
40567
- id: "claude-sonnet-4",
40568
- name: "Claude Sonnet 4",
40569
- description: "Anthropic's balanced model for complex tasks",
41656
+ id: "claude-sonnet-4-6",
41657
+ name: "Claude Sonnet 4.6",
41658
+ description: "Anthropic's latest Sonnet model",
40570
41659
  category: "smart",
40571
41660
  provider: "opencode-zen",
40572
- contextLength: 200000
41661
+ contextLength: 1e6
40573
41662
  },
40574
41663
  {
40575
- id: "gemini-3-pro",
40576
- name: "Gemini 3 Pro",
41664
+ id: "gemini-3.1-pro",
41665
+ name: "Gemini 3.1 Pro",
40577
41666
  description: "Google's high-end Gemini model",
40578
41667
  category: "smart",
40579
41668
  provider: "opencode-zen",
40580
41669
  contextLength: 200000
40581
41670
  },
40582
41671
  {
40583
- id: "gpt-5.2",
40584
- name: "GPT 5.2",
40585
- description: "OpenAI's flagship GPT model",
41672
+ id: "gpt-5.5",
41673
+ name: "GPT 5.5",
41674
+ description: "OpenAI's latest flagship GPT model",
40586
41675
  category: "smart",
40587
41676
  provider: "opencode-zen",
40588
- contextLength: 200000
40589
- },
40590
- {
40591
- id: "gpt-5.2-codex",
40592
- name: "GPT 5.2 Codex",
40593
- description: "OpenAI's coding-focused GPT model",
40594
- category: "smart",
40595
- provider: "opencode-zen",
40596
- contextLength: 200000
40597
- },
40598
- {
40599
- id: "gpt-5.1",
40600
- name: "GPT 5.1",
40601
- description: "OpenAI's balanced GPT model",
40602
- category: "smart",
40603
- provider: "opencode-zen",
40604
- contextLength: 200000
41677
+ contextLength: 1050000
40605
41678
  },
40606
41679
  {
40607
- id: "gpt-5.1-codex",
40608
- name: "GPT 5.1 Codex",
40609
- description: "OpenAI's coding model",
41680
+ id: "gpt-5.5-pro",
41681
+ name: "GPT 5.5 Pro",
41682
+ description: "OpenAI's latest high-capability reasoning model",
40610
41683
  category: "smart",
40611
41684
  provider: "opencode-zen",
40612
- contextLength: 200000
41685
+ contextLength: 1050000
40613
41686
  },
40614
41687
  {
40615
- id: "gpt-5",
40616
- name: "GPT 5",
40617
- description: "OpenAI's prior generation GPT model",
41688
+ id: "gpt-5.3-codex",
41689
+ name: "GPT 5.3 Codex",
41690
+ description: "OpenAI's latest coding-focused GPT model",
40618
41691
  category: "smart",
40619
41692
  provider: "opencode-zen",
40620
- contextLength: 200000
41693
+ contextLength: 400000
40621
41694
  },
40622
41695
  {
40623
- id: "gpt-5-codex",
40624
- name: "GPT 5 Codex",
40625
- description: "OpenAI's prior generation codex model",
41696
+ id: "gpt-5.3-codex-spark",
41697
+ name: "GPT 5.3 Codex Spark",
41698
+ description: "OpenAI's latest fast coding-focused GPT model",
40626
41699
  category: "smart",
40627
41700
  provider: "opencode-zen",
40628
- contextLength: 200000
41701
+ contextLength: 400000
40629
41702
  },
40630
41703
  {
40631
41704
  id: "minimax-m2.7",
@@ -40668,44 +41741,12 @@ var OPENCODE_ZEN_MODELS2 = [
40668
41741
  contextLength: 202752
40669
41742
  },
40670
41743
  {
40671
- id: "claude-sonnet-4-5",
40672
- name: "Claude Sonnet 4.5",
40673
- description: "Anthropic's hybrid reasoning model",
41744
+ id: "claude-opus-4-7",
41745
+ name: "Claude Opus 4.7",
41746
+ description: "Anthropic's latest Opus model",
40674
41747
  category: "reasoning",
40675
41748
  provider: "opencode-zen",
40676
- contextLength: 200000
40677
- },
40678
- {
40679
- id: "claude-opus-4-6",
40680
- name: "Claude Opus 4.6",
40681
- description: "Anthropic's newest Opus model",
40682
- category: "reasoning",
40683
- provider: "opencode-zen",
40684
- contextLength: 200000
40685
- },
40686
- {
40687
- id: "claude-opus-4-5",
40688
- name: "Claude Opus 4.5",
40689
- description: "Anthropic's most capable model",
40690
- category: "reasoning",
40691
- provider: "opencode-zen",
40692
- contextLength: 200000
40693
- },
40694
- {
40695
- id: "claude-opus-4-1",
40696
- name: "Claude Opus 4.1",
40697
- description: "Anthropic's powerful reasoning model",
40698
- category: "reasoning",
40699
- provider: "opencode-zen",
40700
- contextLength: 200000
40701
- },
40702
- {
40703
- id: "gpt-5.1-codex-max",
40704
- name: "GPT 5.1 Codex Max",
40705
- description: "OpenAI's largest coding model",
40706
- category: "reasoning",
40707
- provider: "opencode-zen",
40708
- contextLength: 200000
41749
+ contextLength: 1e6
40709
41750
  },
40710
41751
  {
40711
41752
  id: "kimi-k2-thinking",
@@ -40716,22 +41757,257 @@ var OPENCODE_ZEN_MODELS2 = [
40716
41757
  contextLength: 262144
40717
41758
  }
40718
41759
  ];
40719
- var ALL_MODELS2 = [...OPENCODE_ZEN_MODELS2, ...OPENROUTER_MODELS2];
41760
+ var ALL_MODELS2 = [
41761
+ ...OPENCODE_ZEN_MODELS2,
41762
+ ...OPENROUTER_MODELS2,
41763
+ ...VERCEL_AI_GATEWAY_MODELS2,
41764
+ ...CLOUDFLARE_AI_GATEWAY_MODELS2,
41765
+ ...WORKERS_AI_MODELS2
41766
+ ];
41767
+ function getProviderModels2(provider) {
41768
+ switch (provider) {
41769
+ case "opencode-zen":
41770
+ return OPENCODE_ZEN_MODELS2;
41771
+ case "openrouter":
41772
+ return OPENROUTER_MODELS2;
41773
+ case "vercel-ai-gateway":
41774
+ return VERCEL_AI_GATEWAY_MODELS2;
41775
+ case "cloudflare-ai-gateway":
41776
+ return CLOUDFLARE_AI_GATEWAY_MODELS2;
41777
+ case "workers-ai":
41778
+ return WORKERS_AI_MODELS2;
41779
+ case "custom":
41780
+ return [];
41781
+ }
41782
+ }
41783
+ function getProviderDisplayName2(provider) {
41784
+ switch (provider) {
41785
+ case "opencode-zen":
41786
+ return "OpenCode Zen";
41787
+ case "openrouter":
41788
+ return "OpenRouter";
41789
+ case "vercel-ai-gateway":
41790
+ return "Vercel AI Gateway";
41791
+ case "cloudflare-ai-gateway":
41792
+ return "Cloudflare AI Gateway";
41793
+ case "workers-ai":
41794
+ return "Cloudflare Workers AI";
41795
+ case "custom":
41796
+ return "Custom";
41797
+ }
41798
+ }
40720
41799
  function isCustomModel(model) {
40721
41800
  return "baseUrl" in model;
40722
41801
  }
40723
41802
 
41803
+ // src/lib/config.ts
41804
+ import { homedir as homedir2 } from "os";
41805
+ import { join as join2 } from "path";
41806
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
41807
+ var CONFIG_DIR2 = join2(homedir2(), ".magic-shell");
41808
+ var CONFIG_FILE2 = join2(CONFIG_DIR2, "config.json");
41809
+ var HISTORY_FILE2 = join2(CONFIG_DIR2, "history.json");
41810
+ var KEYCHAIN_OPENROUTER2 = "openrouter-api-key";
41811
+ var KEYCHAIN_OPENCODE_ZEN2 = "opencode-zen-api-key";
41812
+ var KEYCHAIN_VERCEL_AI_GATEWAY2 = "vercel-ai-gateway-api-key";
41813
+ var KEYCHAIN_CLOUDFLARE_AI_GATEWAY2 = "cloudflare-ai-gateway-api-key";
41814
+ var KEYCHAIN_WORKERS_AI2 = "workers-ai-api-key";
41815
+ var DEFAULT_CONFIG2 = {
41816
+ provider: "opencode-zen",
41817
+ openrouterApiKey: "",
41818
+ opencodeZenApiKey: "",
41819
+ vercelAiGatewayApiKey: "",
41820
+ cloudflareAiGatewayApiKey: "",
41821
+ workersAiApiKey: "",
41822
+ cloudflareAccountId: "",
41823
+ cloudflareAiGatewayId: "default",
41824
+ defaultModel: "kimi-k2.6-free",
41825
+ safetyLevel: "moderate",
41826
+ dryRunByDefault: false,
41827
+ blockedCommands: [
41828
+ ":(){ :|:& };:",
41829
+ "> /dev/sda",
41830
+ "mkfs",
41831
+ "dd if=/dev/zero",
41832
+ "chmod -R 777 /",
41833
+ "chown -R"
41834
+ ],
41835
+ confirmedDangerousPatterns: [],
41836
+ repoContext: false,
41837
+ customModels: []
41838
+ };
41839
+ function ensureConfigDir2() {
41840
+ if (!existsSync2(CONFIG_DIR2)) {
41841
+ mkdirSync2(CONFIG_DIR2, { recursive: true });
41842
+ }
41843
+ }
41844
+ function loadConfig2() {
41845
+ ensureConfigDir2();
41846
+ if (!existsSync2(CONFIG_FILE2)) {
41847
+ return { ...DEFAULT_CONFIG2 };
41848
+ }
41849
+ try {
41850
+ const data = readFileSync2(CONFIG_FILE2, "utf-8");
41851
+ const loaded = JSON.parse(data);
41852
+ return { ...DEFAULT_CONFIG2, ...loaded };
41853
+ } catch {
41854
+ return { ...DEFAULT_CONFIG2 };
41855
+ }
41856
+ }
41857
+ function saveConfig2(config2) {
41858
+ ensureConfigDir2();
41859
+ const configToSave = { ...config2 };
41860
+ if (isSecureStorageAvailable()) {
41861
+ configToSave.openrouterApiKey = "";
41862
+ configToSave.opencodeZenApiKey = "";
41863
+ configToSave.vercelAiGatewayApiKey = "";
41864
+ configToSave.cloudflareAiGatewayApiKey = "";
41865
+ configToSave.workersAiApiKey = "";
41866
+ }
41867
+ writeFileSync2(CONFIG_FILE2, JSON.stringify(configToSave, null, 2));
41868
+ }
41869
+ async function getApiKey2(provider) {
41870
+ if (provider === "openrouter") {
41871
+ const envKey = process.env.OPENROUTER_API_KEY;
41872
+ if (envKey)
41873
+ return envKey;
41874
+ } else if (provider === "opencode-zen") {
41875
+ const envKey = process.env.OPENCODE_ZEN_API_KEY;
41876
+ if (envKey)
41877
+ return envKey;
41878
+ } else if (provider === "vercel-ai-gateway") {
41879
+ const envKey = process.env.AI_GATEWAY_API_KEY || process.env.VERCEL_AI_GATEWAY_API_KEY;
41880
+ if (envKey)
41881
+ return envKey;
41882
+ } else if (provider === "cloudflare-ai-gateway") {
41883
+ const envKey = process.env.CLOUDFLARE_AI_GATEWAY_API_KEY || process.env.CF_AIG_TOKEN;
41884
+ if (envKey)
41885
+ return envKey;
41886
+ } else if (provider === "workers-ai") {
41887
+ const envKey = process.env.CLOUDFLARE_API_TOKEN || process.env.CLOUDFLARE_API_KEY;
41888
+ if (envKey)
41889
+ return envKey;
41890
+ }
41891
+ const keychainKey = getKeychainKey2(provider);
41892
+ const secureKey = await getSecret(keychainKey);
41893
+ if (secureKey)
41894
+ return secureKey;
41895
+ const config2 = loadConfig2();
41896
+ switch (provider) {
41897
+ case "openrouter":
41898
+ return config2.openrouterApiKey;
41899
+ case "opencode-zen":
41900
+ return config2.opencodeZenApiKey;
41901
+ case "vercel-ai-gateway":
41902
+ return config2.vercelAiGatewayApiKey || "";
41903
+ case "cloudflare-ai-gateway":
41904
+ return config2.cloudflareAiGatewayApiKey || "";
41905
+ case "workers-ai":
41906
+ return config2.workersAiApiKey || "";
41907
+ case "custom":
41908
+ return "";
41909
+ }
41910
+ }
41911
+ async function setApiKey2(provider, key) {
41912
+ const config2 = loadConfig2();
41913
+ config2.provider = provider;
41914
+ const keychainKey = getKeychainKey2(provider);
41915
+ const stored = await setSecret(keychainKey, key);
41916
+ if (!stored) {
41917
+ switch (provider) {
41918
+ case "openrouter":
41919
+ config2.openrouterApiKey = key;
41920
+ break;
41921
+ case "opencode-zen":
41922
+ config2.opencodeZenApiKey = key;
41923
+ break;
41924
+ case "vercel-ai-gateway":
41925
+ config2.vercelAiGatewayApiKey = key;
41926
+ break;
41927
+ case "cloudflare-ai-gateway":
41928
+ config2.cloudflareAiGatewayApiKey = key;
41929
+ break;
41930
+ case "workers-ai":
41931
+ config2.workersAiApiKey = key;
41932
+ break;
41933
+ case "custom":
41934
+ break;
41935
+ }
41936
+ }
41937
+ saveConfig2(config2);
41938
+ }
41939
+ function getKeychainKey2(provider) {
41940
+ switch (provider) {
41941
+ case "openrouter":
41942
+ return KEYCHAIN_OPENROUTER2;
41943
+ case "opencode-zen":
41944
+ return KEYCHAIN_OPENCODE_ZEN2;
41945
+ case "vercel-ai-gateway":
41946
+ return KEYCHAIN_VERCEL_AI_GATEWAY2;
41947
+ case "cloudflare-ai-gateway":
41948
+ return KEYCHAIN_CLOUDFLARE_AI_GATEWAY2;
41949
+ case "workers-ai":
41950
+ return KEYCHAIN_WORKERS_AI2;
41951
+ case "custom":
41952
+ return "custom-api-key";
41953
+ }
41954
+ }
41955
+ function loadHistory2() {
41956
+ ensureConfigDir2();
41957
+ if (!existsSync2(HISTORY_FILE2)) {
41958
+ return [];
41959
+ }
41960
+ try {
41961
+ const data = readFileSync2(HISTORY_FILE2, "utf-8");
41962
+ return JSON.parse(data);
41963
+ } catch {
41964
+ return [];
41965
+ }
41966
+ }
41967
+ function saveHistory(history) {
41968
+ ensureConfigDir2();
41969
+ const trimmed = history.slice(-100);
41970
+ writeFileSync2(HISTORY_FILE2, JSON.stringify(trimmed, null, 2));
41971
+ }
41972
+ function addToHistory(entry) {
41973
+ const history = loadHistory2();
41974
+ history.push(entry);
41975
+ saveHistory(history);
41976
+ }
41977
+ function getCustomModels2() {
41978
+ const config2 = loadConfig2();
41979
+ return config2.customModels || [];
41980
+ }
41981
+ async function getCustomModel2(id) {
41982
+ const customModels = getCustomModels2();
41983
+ const model = customModels.find((m) => m.id === id);
41984
+ if (!model) {
41985
+ return;
41986
+ }
41987
+ const keychainKey = `customModel:${model.id}:apiKey`;
41988
+ try {
41989
+ const apiKey = await getSecret(keychainKey);
41990
+ return apiKey ? { ...model, apiKey } : model;
41991
+ } catch (error40) {
41992
+ if (process.env.DEBUG_API === "1") {
41993
+ const message = error40 instanceof Error ? error40.message : String(error40);
41994
+ console.error(`[DEBUG] Custom model keychain get error: ${message}`);
41995
+ }
41996
+ return model;
41997
+ }
41998
+ }
41999
+
40724
42000
  // src/lib/shell.ts
40725
42001
  import { execSync } from "child_process";
40726
- import { existsSync as existsSync2 } from "fs";
40727
- import { homedir as homedir2 } from "os";
42002
+ import { existsSync as existsSync3 } from "fs";
42003
+ import { homedir as homedir3 } from "os";
40728
42004
  function detectShell() {
40729
42005
  const platform = detectPlatform();
40730
42006
  const isWSL = detectWSL();
40731
42007
  const shellPath = getShellPath();
40732
42008
  const shell2 = parseShellType(shellPath);
40733
42009
  const terminalEmulator = detectTerminalEmulator();
40734
- const homeDir = homedir2();
42010
+ const homeDir = homedir3();
40735
42011
  return {
40736
42012
  shell: shell2,
40737
42013
  shellPath,
@@ -40761,7 +42037,7 @@ function detectWSL() {
40761
42037
  if (release.includes("microsoft") || release.includes("wsl")) {
40762
42038
  return true;
40763
42039
  }
40764
- if (existsSync2("/proc/sys/fs/binfmt_misc/WSLInterop")) {
42040
+ if (existsSync3("/proc/sys/fs/binfmt_misc/WSLInterop")) {
40765
42041
  return true;
40766
42042
  }
40767
42043
  return false;
@@ -40921,34 +42197,34 @@ function getPlatformPaths(platform) {
40921
42197
  }
40922
42198
 
40923
42199
  // src/lib/repo-context.ts
40924
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
40925
- import { join as join2 } from "path";
42200
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
42201
+ import { join as join3 } from "path";
40926
42202
  function detectRepoContext(cwd) {
40927
42203
  const context2 = {
40928
42204
  type: "unknown"
40929
42205
  };
40930
42206
  let detected = false;
40931
- if (existsSync3(join2(cwd, ".git"))) {
42207
+ if (existsSync4(join3(cwd, ".git"))) {
40932
42208
  context2.hasGit = true;
40933
42209
  detected = true;
40934
42210
  }
40935
- if (existsSync3(join2(cwd, "Dockerfile")) || existsSync3(join2(cwd, "docker-compose.yml")) || existsSync3(join2(cwd, "docker-compose.yaml"))) {
42211
+ if (existsSync4(join3(cwd, "Dockerfile")) || existsSync4(join3(cwd, "docker-compose.yml")) || existsSync4(join3(cwd, "docker-compose.yaml"))) {
40936
42212
  context2.hasDocker = true;
40937
42213
  detected = true;
40938
42214
  }
40939
- const packageJsonPath = join2(cwd, "package.json");
40940
- if (existsSync3(packageJsonPath)) {
42215
+ const packageJsonPath = join3(cwd, "package.json");
42216
+ if (existsSync4(packageJsonPath)) {
40941
42217
  detected = true;
40942
42218
  context2.type = "node";
40943
42219
  try {
40944
- const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
40945
- if (existsSync3(join2(cwd, "bun.lockb")) || existsSync3(join2(cwd, "bun.lock"))) {
42220
+ const packageJson = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
42221
+ if (existsSync4(join3(cwd, "bun.lockb")) || existsSync4(join3(cwd, "bun.lock"))) {
40946
42222
  context2.packageManager = "bun";
40947
- } else if (existsSync3(join2(cwd, "pnpm-lock.yaml"))) {
42223
+ } else if (existsSync4(join3(cwd, "pnpm-lock.yaml"))) {
40948
42224
  context2.packageManager = "pnpm";
40949
- } else if (existsSync3(join2(cwd, "yarn.lock"))) {
42225
+ } else if (existsSync4(join3(cwd, "yarn.lock"))) {
40950
42226
  context2.packageManager = "yarn";
40951
- } else if (existsSync3(join2(cwd, "package-lock.json"))) {
42227
+ } else if (existsSync4(join3(cwd, "package-lock.json"))) {
40952
42228
  context2.packageManager = "npm";
40953
42229
  } else if (packageJson.packageManager) {
40954
42230
  const pm = packageJson.packageManager.split("@")[0];
@@ -40959,13 +42235,13 @@ function detectRepoContext(cwd) {
40959
42235
  }
40960
42236
  } catch {}
40961
42237
  }
40962
- const makefilePath = join2(cwd, "Makefile");
40963
- if (existsSync3(makefilePath)) {
42238
+ const makefilePath = join3(cwd, "Makefile");
42239
+ if (existsSync4(makefilePath)) {
40964
42240
  detected = true;
40965
42241
  if (context2.type === "unknown")
40966
42242
  context2.type = "make";
40967
42243
  try {
40968
- const makefile = readFileSync2(makefilePath, "utf-8");
42244
+ const makefile = readFileSync3(makefilePath, "utf-8");
40969
42245
  const targetRegex = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:/gm;
40970
42246
  const targets = [];
40971
42247
  let match;
@@ -40979,17 +42255,17 @@ function detectRepoContext(cwd) {
40979
42255
  }
40980
42256
  } catch {}
40981
42257
  }
40982
- if (existsSync3(join2(cwd, "Cargo.toml"))) {
42258
+ if (existsSync4(join3(cwd, "Cargo.toml"))) {
40983
42259
  detected = true;
40984
42260
  context2.type = "rust";
40985
42261
  context2.cargoCommands = ["build", "run", "test", "check", "clippy", "fmt", "doc"];
40986
42262
  }
40987
- if (existsSync3(join2(cwd, "pyproject.toml")) || existsSync3(join2(cwd, "setup.py")) || existsSync3(join2(cwd, "requirements.txt"))) {
42263
+ if (existsSync4(join3(cwd, "pyproject.toml")) || existsSync4(join3(cwd, "setup.py")) || existsSync4(join3(cwd, "requirements.txt"))) {
40988
42264
  detected = true;
40989
42265
  if (context2.type === "unknown")
40990
42266
  context2.type = "python";
40991
42267
  }
40992
- if (existsSync3(join2(cwd, "go.mod"))) {
42268
+ if (existsSync4(join3(cwd, "go.mod"))) {
40993
42269
  detected = true;
40994
42270
  if (context2.type === "unknown")
40995
42271
  context2.type = "go";
@@ -41027,9 +42303,6 @@ function formatRepoContext(context2) {
41027
42303
 
41028
42304
  // src/lib/api.ts
41029
42305
  function getZenApiType(modelId) {
41030
- if (modelId === "minimax-m2.5-free") {
41031
- return "anthropic";
41032
- }
41033
42306
  if (modelId.startsWith("gpt-")) {
41034
42307
  return "openai-responses";
41035
42308
  }
@@ -41159,6 +42432,81 @@ async function callOpenRouter(apiKey, modelId, systemPrompt, userInput) {
41159
42432
  }
41160
42433
  return data.choices[0]?.message?.content?.trim() || "";
41161
42434
  }
42435
+ async function callOpenAICompatibleFetch(baseURL, apiKey, modelId, systemPrompt, userInput, headers = {}, includeAuthorization = true) {
42436
+ const requestHeaders = {
42437
+ "Content-Type": "application/json",
42438
+ ...headers
42439
+ };
42440
+ if (includeAuthorization) {
42441
+ requestHeaders.Authorization = `Bearer ${apiKey}`;
42442
+ }
42443
+ const response = await fetch(`${baseURL.replace(/\/$/, "")}/chat/completions`, {
42444
+ method: "POST",
42445
+ headers: requestHeaders,
42446
+ body: JSON.stringify({
42447
+ model: modelId,
42448
+ messages: [
42449
+ { role: "system", content: systemPrompt },
42450
+ { role: "user", content: userInput }
42451
+ ],
42452
+ max_tokens: 500,
42453
+ temperature: 0.1,
42454
+ stream: false
42455
+ })
42456
+ });
42457
+ if (!response.ok) {
42458
+ const errorText = await response.text();
42459
+ let errorMessage = `API request failed: ${response.status}`;
42460
+ try {
42461
+ const errorData = JSON.parse(errorText);
42462
+ if (errorData.error?.message) {
42463
+ errorMessage = errorData.error.message;
42464
+ } else if (errorData.errors?.[0]?.message) {
42465
+ errorMessage = errorData.errors[0].message;
42466
+ }
42467
+ } catch {}
42468
+ throw new Error(errorMessage);
42469
+ }
42470
+ const data = await response.json();
42471
+ if (data.error) {
42472
+ throw new Error(data.error.message);
42473
+ }
42474
+ if (data.errors?.[0]?.message) {
42475
+ throw new Error(data.errors[0].message);
42476
+ }
42477
+ const choices = data.choices || data.result?.choices;
42478
+ return choices?.[0]?.message?.content?.trim() || "";
42479
+ }
42480
+ function getCloudflareAccountId(config2) {
42481
+ return config2.cloudflareAccountId || process.env.CLOUDFLARE_ACCOUNT_ID || process.env.CF_ACCOUNT_ID || "";
42482
+ }
42483
+ function getCloudflareGatewayId(config2) {
42484
+ return config2.cloudflareAiGatewayId || process.env.CLOUDFLARE_AI_GATEWAY_ID || process.env.CF_AIG_GATEWAY_ID || "default";
42485
+ }
42486
+ async function callGatewayProvider(provider, apiKey, modelId, systemPrompt, userInput) {
42487
+ const config2 = loadConfig2();
42488
+ switch (provider) {
42489
+ case "vercel-ai-gateway":
42490
+ return await callOpenAICompatibleFetch("https://ai-gateway.vercel.sh/v1", apiKey, modelId, systemPrompt, userInput);
42491
+ case "cloudflare-ai-gateway": {
42492
+ const accountId = getCloudflareAccountId(config2);
42493
+ if (!accountId) {
42494
+ throw new Error("Cloudflare account ID is required. Set cloudflareAccountId in config or CLOUDFLARE_ACCOUNT_ID.");
42495
+ }
42496
+ const gatewayId = getCloudflareGatewayId(config2);
42497
+ return await callOpenAICompatibleFetch(`https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/compat`, apiKey, modelId, systemPrompt, userInput, { "cf-aig-authorization": `Bearer ${apiKey}` }, false);
42498
+ }
42499
+ case "workers-ai": {
42500
+ const accountId = getCloudflareAccountId(config2);
42501
+ if (!accountId) {
42502
+ throw new Error("Cloudflare account ID is required. Set cloudflareAccountId in config or CLOUDFLARE_ACCOUNT_ID.");
42503
+ }
42504
+ return await callOpenAICompatibleFetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/v1`, apiKey, modelId, systemPrompt, userInput);
42505
+ }
42506
+ default:
42507
+ throw new Error(`Unsupported gateway provider: ${provider}`);
42508
+ }
42509
+ }
41162
42510
  var DEBUG_API = process.env.DEBUG_API === "1";
41163
42511
  async function generateZenText(model, systemPrompt, userInput) {
41164
42512
  const { text: text2 } = await generateText({
@@ -41285,6 +42633,8 @@ async function translateToCommand(apiKey, model, userInput, cwd, history = [], r
41285
42633
  rawCommand = await callCustomModel(model, systemPrompt, userInput);
41286
42634
  } else if (model.provider === "openrouter") {
41287
42635
  rawCommand = await callOpenRouter(apiKey, model.id, systemPrompt, userInput);
42636
+ } else if (model.provider === "vercel-ai-gateway" || model.provider === "cloudflare-ai-gateway" || model.provider === "workers-ai") {
42637
+ rawCommand = await callGatewayProvider(model.provider, apiKey, model.id, systemPrompt, userInput);
41288
42638
  } else {
41289
42639
  const apiType = getZenApiType(model.id);
41290
42640
  switch (apiType) {
@@ -41309,137 +42659,6 @@ async function translateToCommand(apiKey, model, userInput, cwd, history = [], r
41309
42659
  return cleaned;
41310
42660
  }
41311
42661
 
41312
- // src/lib/config.ts
41313
- import { homedir as homedir3 } from "os";
41314
- import { join as join3 } from "path";
41315
- import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
41316
- var CONFIG_DIR2 = join3(homedir3(), ".magic-shell");
41317
- var CONFIG_FILE2 = join3(CONFIG_DIR2, "config.json");
41318
- var HISTORY_FILE2 = join3(CONFIG_DIR2, "history.json");
41319
- var KEYCHAIN_OPENROUTER2 = "openrouter-api-key";
41320
- var KEYCHAIN_OPENCODE_ZEN2 = "opencode-zen-api-key";
41321
- var DEFAULT_CONFIG2 = {
41322
- provider: "opencode-zen",
41323
- openrouterApiKey: "",
41324
- opencodeZenApiKey: "",
41325
- defaultModel: "kimi-k2.6-free",
41326
- safetyLevel: "moderate",
41327
- dryRunByDefault: false,
41328
- blockedCommands: [
41329
- ":(){ :|:& };:",
41330
- "> /dev/sda",
41331
- "mkfs",
41332
- "dd if=/dev/zero",
41333
- "chmod -R 777 /",
41334
- "chown -R"
41335
- ],
41336
- confirmedDangerousPatterns: [],
41337
- repoContext: false,
41338
- customModels: []
41339
- };
41340
- function ensureConfigDir2() {
41341
- if (!existsSync4(CONFIG_DIR2)) {
41342
- mkdirSync2(CONFIG_DIR2, { recursive: true });
41343
- }
41344
- }
41345
- function loadConfig2() {
41346
- ensureConfigDir2();
41347
- if (!existsSync4(CONFIG_FILE2)) {
41348
- return { ...DEFAULT_CONFIG2 };
41349
- }
41350
- try {
41351
- const data = readFileSync3(CONFIG_FILE2, "utf-8");
41352
- const loaded = JSON.parse(data);
41353
- return { ...DEFAULT_CONFIG2, ...loaded };
41354
- } catch {
41355
- return { ...DEFAULT_CONFIG2 };
41356
- }
41357
- }
41358
- function saveConfig2(config2) {
41359
- ensureConfigDir2();
41360
- const configToSave = { ...config2 };
41361
- if (isSecureStorageAvailable()) {
41362
- configToSave.openrouterApiKey = "";
41363
- configToSave.opencodeZenApiKey = "";
41364
- }
41365
- writeFileSync2(CONFIG_FILE2, JSON.stringify(configToSave, null, 2));
41366
- }
41367
- async function getApiKey2(provider) {
41368
- if (provider === "openrouter") {
41369
- const envKey = process.env.OPENROUTER_API_KEY;
41370
- if (envKey)
41371
- return envKey;
41372
- } else if (provider === "opencode-zen") {
41373
- const envKey = process.env.OPENCODE_ZEN_API_KEY;
41374
- if (envKey)
41375
- return envKey;
41376
- }
41377
- const keychainKey = provider === "openrouter" ? KEYCHAIN_OPENROUTER2 : KEYCHAIN_OPENCODE_ZEN2;
41378
- const secureKey = await getSecret(keychainKey);
41379
- if (secureKey)
41380
- return secureKey;
41381
- const config2 = loadConfig2();
41382
- return provider === "openrouter" ? config2.openrouterApiKey : config2.opencodeZenApiKey;
41383
- }
41384
- async function setApiKey2(provider, key) {
41385
- const config2 = loadConfig2();
41386
- config2.provider = provider;
41387
- const keychainKey = provider === "openrouter" ? KEYCHAIN_OPENROUTER2 : KEYCHAIN_OPENCODE_ZEN2;
41388
- const stored = await setSecret(keychainKey, key);
41389
- if (!stored) {
41390
- if (provider === "openrouter") {
41391
- config2.openrouterApiKey = key;
41392
- } else {
41393
- config2.opencodeZenApiKey = key;
41394
- }
41395
- }
41396
- saveConfig2(config2);
41397
- }
41398
- function loadHistory2() {
41399
- ensureConfigDir2();
41400
- if (!existsSync4(HISTORY_FILE2)) {
41401
- return [];
41402
- }
41403
- try {
41404
- const data = readFileSync3(HISTORY_FILE2, "utf-8");
41405
- return JSON.parse(data);
41406
- } catch {
41407
- return [];
41408
- }
41409
- }
41410
- function saveHistory(history) {
41411
- ensureConfigDir2();
41412
- const trimmed = history.slice(-100);
41413
- writeFileSync2(HISTORY_FILE2, JSON.stringify(trimmed, null, 2));
41414
- }
41415
- function addToHistory(entry) {
41416
- const history = loadHistory2();
41417
- history.push(entry);
41418
- saveHistory(history);
41419
- }
41420
- function getCustomModels2() {
41421
- const config2 = loadConfig2();
41422
- return config2.customModels || [];
41423
- }
41424
- async function getCustomModel2(id) {
41425
- const customModels = getCustomModels2();
41426
- const model = customModels.find((m) => m.id === id);
41427
- if (!model) {
41428
- return;
41429
- }
41430
- const keychainKey = `customModel:${model.id}:apiKey`;
41431
- try {
41432
- const apiKey = await getSecret(keychainKey);
41433
- return apiKey ? { ...model, apiKey } : model;
41434
- } catch (error40) {
41435
- if (process.env.DEBUG_API === "1") {
41436
- const message = error40 instanceof Error ? error40.message : String(error40);
41437
- console.error(`[DEBUG] Custom model keychain get error: ${message}`);
41438
- }
41439
- return model;
41440
- }
41441
- }
41442
-
41443
42662
  // src/lib/theme.ts
41444
42663
  var opencode = {
41445
42664
  name: "opencode",
@@ -41808,7 +43027,7 @@ ${colors.bold}USAGE${colors.reset}
41808
43027
  msh --add-model Add custom model (LM Studio, Ollama, etc.)
41809
43028
  msh --list-custom List custom models
41810
43029
  msh --remove-model <id> Remove custom model
41811
- msh --provider <name> Set provider (opencode-zen or openrouter)
43030
+ msh --provider <name> Set provider
41812
43031
  msh --themes List available themes
41813
43032
  msh --theme <name> Set color theme
41814
43033
  msh --repo-context Enable project context detection
@@ -41843,6 +43062,10 @@ ${colors.bold}THEMES${colors.reset}
41843
43062
  ${colors.bold}ENVIRONMENT${colors.reset}
41844
43063
  OPENCODE_ZEN_API_KEY API key for OpenCode Zen
41845
43064
  OPENROUTER_API_KEY API key for OpenRouter
43065
+ AI_GATEWAY_API_KEY API key for Vercel AI Gateway
43066
+ CLOUDFLARE_API_TOKEN API token for Cloudflare Workers AI
43067
+ CLOUDFLARE_ACCOUNT_ID Account ID for Cloudflare providers
43068
+ CLOUDFLARE_AI_GATEWAY_API_KEY API key/token for Cloudflare AI Gateway
41846
43069
 
41847
43070
  ${colors.bold}CONFIG${colors.reset}
41848
43071
  ~/.magic-shell/config.json
@@ -41888,6 +43111,24 @@ ${colors.bold}OpenRouter Models${colors.reset}
41888
43111
  console.log(` ${colors.dim}${model.description}${colors.reset}`);
41889
43112
  }
41890
43113
  }
43114
+ const providerSections = [
43115
+ ["Vercel AI Gateway Models", VERCEL_AI_GATEWAY_MODELS, "vercel-ai-gateway"],
43116
+ ["Cloudflare AI Gateway Models", CLOUDFLARE_AI_GATEWAY_MODELS, "cloudflare-ai-gateway"],
43117
+ ["Cloudflare Workers AI Models", WORKERS_AI_MODELS, "workers-ai"]
43118
+ ];
43119
+ for (const [title, models, provider] of providerSections) {
43120
+ console.log(`
43121
+ ${colors.bold}${title}${colors.reset}
43122
+ `);
43123
+ const sortedModels = [...models].sort((a, b) => a.name.localeCompare(b.name));
43124
+ for (const model of sortedModels) {
43125
+ const isCurrent = config2.provider === provider && config2.defaultModel === model.id;
43126
+ const marker21 = isCurrent ? colors.success + "\u2192 " : " ";
43127
+ const category = colors.dim + `[${model.category}]` + colors.reset;
43128
+ console.log(`${marker21}${model.id} ${category}`);
43129
+ console.log(` ${colors.dim}${model.description}${colors.reset}`);
43130
+ }
43131
+ }
41891
43132
  if (customModels.length > 0) {
41892
43133
  console.log(`
41893
43134
  ${colors.bold}Custom Models${colors.reset} ${colors.info}(custom)${colors.reset}
@@ -41911,8 +43152,8 @@ function validateApiKey(key, provider) {
41911
43152
  if (trimmed.length < 20) {
41912
43153
  return "API key seems too short (expected at least 20 characters)";
41913
43154
  }
41914
- if (!trimmed.startsWith("sk-")) {
41915
- const providerName = provider === "opencode-zen" ? "OpenCode Zen" : "OpenRouter";
43155
+ if ((provider === "opencode-zen" || provider === "openrouter") && !trimmed.startsWith("sk-")) {
43156
+ const providerName = getProviderDisplayName(provider);
41916
43157
  return `${providerName} API keys typically start with 'sk-'`;
41917
43158
  }
41918
43159
  if (trimmed.includes(" ")) {
@@ -41924,6 +43165,22 @@ function validateApiKey(key, provider) {
41924
43165
  }
41925
43166
  return null;
41926
43167
  }
43168
+ function getApiKeyUrl(provider) {
43169
+ switch (provider) {
43170
+ case "opencode-zen":
43171
+ return "https://opencode.ai/auth";
43172
+ case "openrouter":
43173
+ return "https://openrouter.ai/keys";
43174
+ case "vercel-ai-gateway":
43175
+ return "https://vercel.com/docs/ai-gateway";
43176
+ case "cloudflare-ai-gateway":
43177
+ return "https://developers.cloudflare.com/ai-gateway/";
43178
+ case "workers-ai":
43179
+ return "https://dash.cloudflare.com/profile/api-tokens";
43180
+ case "custom":
43181
+ return "";
43182
+ }
43183
+ }
41927
43184
  async function setup() {
41928
43185
  const readline = await import("readline");
41929
43186
  const rl = readline.createInterface({
@@ -41941,9 +43198,18 @@ ${colors.bold}${colors.cyan}Magic Shell Setup${colors.reset}
41941
43198
  console.log("Select provider:");
41942
43199
  console.log(" 1. OpenCode Zen (recommended, has free models)");
41943
43200
  console.log(" 2. OpenRouter");
43201
+ console.log(" 3. Vercel AI Gateway");
43202
+ console.log(" 4. Cloudflare AI Gateway");
43203
+ console.log(" 5. Cloudflare Workers AI");
41944
43204
  const providerChoice = await question(`
41945
43205
  Choice [1]: `);
41946
- const provider = providerChoice === "2" ? "openrouter" : "opencode-zen";
43206
+ const providerChoices = {
43207
+ "2": "openrouter",
43208
+ "3": "vercel-ai-gateway",
43209
+ "4": "cloudflare-ai-gateway",
43210
+ "5": "workers-ai"
43211
+ };
43212
+ const provider = providerChoices[providerChoice] || "opencode-zen";
41947
43213
  const existingKey = await getApiKey(provider);
41948
43214
  if (existingKey) {
41949
43215
  const useExisting = await question(`
@@ -41951,7 +43217,7 @@ API key already configured. Keep it? [Y/n]: `);
41951
43217
  if (useExisting.toLowerCase() !== "n") {
41952
43218
  console.log(`${colors.green}\u2713 Using existing API key${colors.reset}`);
41953
43219
  } else {
41954
- const url2 = provider === "opencode-zen" ? "https://opencode.ai/auth" : "https://openrouter.ai/keys";
43220
+ const url2 = getApiKeyUrl(provider);
41955
43221
  console.log(`
41956
43222
  Get your API key from: ${colors.cyan}${url2}${colors.reset}`);
41957
43223
  let validKey = false;
@@ -41975,7 +43241,7 @@ Get your API key from: ${colors.cyan}${url2}${colors.reset}`);
41975
43241
  }
41976
43242
  }
41977
43243
  } else {
41978
- const url2 = provider === "opencode-zen" ? "https://opencode.ai/auth" : "https://openrouter.ai/keys";
43244
+ const url2 = getApiKeyUrl(provider);
41979
43245
  console.log(`
41980
43246
  Get your API key from: ${colors.cyan}${url2}${colors.reset}`);
41981
43247
  let validKey = false;
@@ -41999,7 +43265,20 @@ Get your API key from: ${colors.cyan}${url2}${colors.reset}`);
41999
43265
  validKey = true;
42000
43266
  }
42001
43267
  }
42002
- const models = provider === "opencode-zen" ? OPENCODE_ZEN_MODELS : OPENROUTER_MODELS;
43268
+ const config2 = loadConfig();
43269
+ if (provider === "cloudflare-ai-gateway" || provider === "workers-ai") {
43270
+ const existingAccountId = config2.cloudflareAccountId || process.env.CLOUDFLARE_ACCOUNT_ID || "";
43271
+ if (!existingAccountId) {
43272
+ const accountId = await question(`
43273
+ Cloudflare account ID: `);
43274
+ config2.cloudflareAccountId = accountId.trim();
43275
+ }
43276
+ }
43277
+ if (provider === "cloudflare-ai-gateway") {
43278
+ const gatewayId = await question(`Cloudflare AI Gateway ID [${config2.cloudflareAiGatewayId || "default"}]: `);
43279
+ config2.cloudflareAiGatewayId = gatewayId.trim() || config2.cloudflareAiGatewayId || "default";
43280
+ }
43281
+ const models = getProviderModels(provider);
42003
43282
  const freeModels = models.filter((m) => m.free);
42004
43283
  console.log(`
42005
43284
  Recommended models:`);
@@ -42012,13 +43291,12 @@ Recommended models:`);
42012
43291
  Choice [1]: `);
42013
43292
  const modelIndex = parseInt(modelChoice || "1") - 1;
42014
43293
  const selectedModel = displayModels[modelIndex] || displayModels[0];
42015
- const config2 = loadConfig();
42016
43294
  config2.provider = provider;
42017
43295
  config2.defaultModel = selectedModel.id;
42018
43296
  saveConfig(config2);
42019
43297
  console.log(`
42020
43298
  ${colors.green}\u2713 Setup complete!${colors.reset}`);
42021
- console.log(` Provider: ${provider === "opencode-zen" ? "OpenCode Zen" : "OpenRouter"}`);
43299
+ console.log(` Provider: ${getProviderDisplayName(provider)}`);
42022
43300
  console.log(` Model: ${selectedModel.name}`);
42023
43301
  console.log(`
42024
43302
  Try: ${colors.cyan}msh "list all files"${colors.reset}
@@ -42162,7 +43440,8 @@ async function translate(query, options) {
42162
43440
  const apiKey = await getApiKey(config2.provider);
42163
43441
  const customModel = await getCustomModel(config2.defaultModel);
42164
43442
  const builtInModel = ALL_MODELS.find((m) => m.id === config2.defaultModel);
42165
- const model = customModel || builtInModel || (config2.provider === "opencode-zen" ? OPENCODE_ZEN_MODELS[0] : OPENROUTER_MODELS[0]);
43443
+ const fallbackModels = getProviderModels(config2.provider);
43444
+ const model = customModel || builtInModel || fallbackModels[0] || OPENCODE_ZEN_MODELS[0];
42166
43445
  if (!customModel && !apiKey) {
42167
43446
  console.error(`${colors.red}Error: No API key configured.${colors.reset}`);
42168
43447
  console.error(`Run: ${colors.cyan}msh --setup${colors.reset}`);
@@ -42341,14 +43620,15 @@ ${colors.bold}Custom Models${colors.reset}
42341
43620
  }
42342
43621
  if (args[0] === "--provider" && args[1]) {
42343
43622
  const provider = args[1];
42344
- if (provider !== "opencode-zen" && provider !== "openrouter") {
43623
+ const validProviders = ["opencode-zen", "openrouter", "vercel-ai-gateway", "cloudflare-ai-gateway", "workers-ai"];
43624
+ if (!validProviders.includes(provider)) {
42345
43625
  console.error(`${colors.error}Unknown provider: ${provider}${colors.reset}`);
42346
- console.error(`Valid providers: opencode-zen, openrouter`);
43626
+ console.error(`Valid providers: ${validProviders.join(", ")}`);
42347
43627
  process.exit(1);
42348
43628
  }
42349
43629
  const config2 = loadConfig();
42350
43630
  config2.provider = provider;
42351
- const models = provider === "opencode-zen" ? OPENCODE_ZEN_MODELS : OPENROUTER_MODELS;
43631
+ const models = getProviderModels(provider);
42352
43632
  const firstAvailable = models.find((m) => !m.disabled) || models[0];
42353
43633
  config2.defaultModel = firstAvailable.id;
42354
43634
  saveConfig(config2);