@jeffreycao/copilot-api 2.7.5 → 2.7.7

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 (39) hide show
  1. package/dist/auth-BzYvzeW0.js +2 -0
  2. package/dist/{auth-CJH114yD.js → auth-qC1GSLdS.js} +4 -4
  3. package/dist/{auth-CJH114yD.js.map → auth-qC1GSLdS.js.map} +1 -1
  4. package/dist/{config-D1F-TyTn.js → config-Cd0U5gXz.js} +8 -3
  5. package/dist/config-Cd0U5gXz.js.map +1 -0
  6. package/dist/{config-store-Bgmf82i_.js → config-store-C6GAtKLz.js} +105 -7
  7. package/dist/config-store-C6GAtKLz.js.map +1 -0
  8. package/dist/{copilot-runtime-DcUOmm60.js → copilot-runtime-Dg3ywZkl.js} +3 -3
  9. package/dist/{copilot-runtime-DcUOmm60.js.map → copilot-runtime-Dg3ywZkl.js.map} +1 -1
  10. package/dist/{debug-EkODckEE.js → debug-CmL-V7Ov.js} +3 -3
  11. package/dist/{debug-EkODckEE.js.map → debug-CmL-V7Ov.js.map} +1 -1
  12. package/dist/main.js +6 -6
  13. package/dist/{mcp-CuZyqwi8.js → mcp-Dd_hxxuG.js} +2 -2
  14. package/dist/{mcp-CuZyqwi8.js.map → mcp-Dd_hxxuG.js.map} +1 -1
  15. package/dist/mcp-server-CEfcUYiN.js +2 -0
  16. package/dist/{mcp-server-CKEydKaf.js → mcp-server-CTGaok8g.js} +2 -2
  17. package/dist/{mcp-server-CKEydKaf.js.map → mcp-server-CTGaok8g.js.map} +1 -1
  18. package/dist/{provider-DXivPd6W.js → provider-CzziTLqX.js} +2 -2
  19. package/dist/{provider-DXivPd6W.js.map → provider-CzziTLqX.js.map} +1 -1
  20. package/dist/{provider-management-DiQ92JMT.js → provider-management-DOfLC7WX.js} +2 -3
  21. package/dist/{provider-management-DiQ92JMT.js.map → provider-management-DOfLC7WX.js.map} +1 -1
  22. package/dist/{server-CrRNnmrV.js → server-CClOz6YS.js} +239 -44
  23. package/dist/server-CClOz6YS.js.map +1 -0
  24. package/dist/{start-Caypc0jJ.js → start-y2hlYweN.js} +7 -8
  25. package/dist/{start-Caypc0jJ.js.map → start-y2hlYweN.js.map} +1 -1
  26. package/dist/{token-ByHtI6Ox.js → token-kSGCOmTG.js} +4 -13
  27. package/dist/token-kSGCOmTG.js.map +1 -0
  28. package/dist/{tool-search-BgFcDbNQ.js → tool-search-CcvaqM03.js} +3 -1
  29. package/dist/tool-search-CcvaqM03.js.map +1 -0
  30. package/package.json +1 -1
  31. package/dist/auth-q4_lJtX6.js +0 -2
  32. package/dist/config-D1F-TyTn.js.map +0 -1
  33. package/dist/config-store-Bgmf82i_.js.map +0 -1
  34. package/dist/github-copilot-provider-Cx4Afaco.js +0 -79
  35. package/dist/github-copilot-provider-Cx4Afaco.js.map +0 -1
  36. package/dist/mcp-server-BH-SFdCD.js +0 -2
  37. package/dist/server-CrRNnmrV.js.map +0 -1
  38. package/dist/token-ByHtI6Ox.js.map +0 -1
  39. package/dist/tool-search-BgFcDbNQ.js.map +0 -1
@@ -1,10 +1,9 @@
1
- import { a as getAnthropicApiKey, c as getConfig, f as isAlphaSearchCodexPriorityEnabled, h as isResponsesApiWebSocketEnabled, i as getAlphaSearchModel, l as getMessageApiWebSearchModel, m as isResponsesApiWebSearchEnabled, o as getClaudeAutoModel, p as isMessagesApiEnabled, s as getClaudeTokenMultiplier, u as getUpstreamTransportConfig, v as reloadConfig, x as PATHS } from "./config-store-Bgmf82i_.js";
2
- import { C as isGpt56OrAbove, S as isContextManagementEnabledForResponses, T as setModelMappings, _ as getModelResponsesApiCompactThreshold$1, b as getSmallModelForProvider, d as getOpencodeGoModelIds, f as getOpencodeGoModelRecords, g as getModelMappings, h as getExtraPromptForModel, i as listEnabledProviders, l as getModelsDevModelMaxOutputTokens, n as getRawProviderConfig, o as resolveEffectiveProviderType, s as resolveProviderConfigForModel, t as getProviderConfig, u as getOpencodeGoModelConfig, v as getReasoningEffortForModel, w as resolveMappedModel, x as isContextManagementEnabledForMessages, y as getSmallModel } from "./config-D1F-TyTn.js";
3
- import { i as HTTPError, r as isGitHubCopilotEnabled, s as forwardError, t as GITHUB_COPILOT_PROVIDER } from "./github-copilot-provider-Cx4Afaco.js";
4
- import { $ as resolveTraceId$1, C as isOpencodeOauthApp, E as prepareMessageProxyHeaders, G as XAI_API_BASE_URL, J as CODEX_API_BASE_URL, L as getXaiAccessToken, M as compactTextOnlyGuard, N as createAuthMiddleware, O as compactAutoContinuePromptStarts, P as getConfiguredAdminApiKeys, Q as requestContext, S as copilotWebSocketHeaders, T as prepareInteractionHeaders, U as readGitHubToken, W as readGitHubTokenFromEnv, X as forwardCodexResponses, Y as buildCodexRequestHeaders, Z as generateTraceId, _ as parseUserIdMetadata, at as createPooledWebSocketStream, b as copilotHeaders, d as generateRequestIdFromPayload, et as fetchUpstreamWithLifecycle, f as getRootSessionId, g as isResponsesStream, h as isNullish, it as getResponsesStreamTerminalDisposition, j as compactSystemPromptStarts, k as compactMessageSections, lt as stripInternalRequestHeaders, m as isAsyncIterable, n as invalidateCodexRuntime, nt as createResponsesSafeStream, ot as createWebSocketUrl, p as getUUID, rt as encodePoolKeyPart, s as setupCodexToken, st as state, tt as createResponsesHttpEventStream, u as stopCopilotRefreshLoop, v as getCopilotUsage, w as prepareForCompact, y as copilotBaseUrl } from "./token-ByHtI6Ox.js";
5
- import { a as isDeferredToolName, c as parseMcpToolSearchSentinel, d as shouldEnableResponsesToolSearch, i as isBridgeToolSearchName, l as resolveBridgeToolSearchName, o as listDeferredToolNames, r as formatToolSearchBridgeArguments, s as normalizeToolSearchBridgeArguments, t as BRIDGE_TOOL_SEARCH_NAME, u as selectDeferredToolsByNames } from "./tool-search-BgFcDbNQ.js";
6
- import { n as isProviderAgentModelVisible, t as getProviderAgentModels } from "./provider-management-DiQ92JMT.js";
7
- import { n as stopModelsRefreshLoop, t as setupCopilotRuntime } from "./copilot-runtime-DcUOmm60.js";
1
+ import { D as state, E as isGitHubCopilotEnabled, O as HTTPError, S as PATHS, a as getAnthropicApiKey, c as getConfig, d as getUpstreamTransportConfig, g as isResponsesApiWebSocketEnabled, h as isResponsesApiWebSearchEnabled, i as getAlphaSearchModel, j as forwardError, l as getMessageApiWebSearchModel, m as isMessagesApiEnabled, o as getClaudeAutoModel, p as isAlphaSearchCodexPriorityEnabled, s as getClaudeTokenMultiplier, u as getOpencodeModelContextWindow, w as GITHUB_COPILOT_PROVIDER, y as reloadConfig } from "./config-store-C6GAtKLz.js";
2
+ import { C as isContextManagementEnabledForResponses, E as setModelMappings, S as isContextManagementEnabledForMessages, T as resolveMappedModel, _ as getModelMappings, b as getSmallModel, d as getOpencodeGoModelConfig, f as getOpencodeGoModelIds, g as getExtraPromptForModel, i as listEnabledProviders, l as getModelsDevModel, n as getRawProviderConfig, o as resolveEffectiveProviderType, p as getOpencodeGoModelRecords, s as resolveProviderConfigForModel, t as getProviderConfig, u as getModelsDevModelMaxOutputTokens, v as getModelResponsesApiCompactThreshold$1, w as isGpt56OrAbove, x as getSmallModelForProvider, y as getReasoningEffortForModel } from "./config-Cd0U5gXz.js";
3
+ import { $ as resolveTraceId$1, C as isOpencodeOauthApp, E as prepareMessageProxyHeaders, G as XAI_API_BASE_URL, J as CODEX_API_BASE_URL, L as getXaiAccessToken, M as compactTextOnlyGuard, N as createAuthMiddleware, O as compactAutoContinuePromptStarts, P as getConfiguredAdminApiKeys, Q as requestContext, S as copilotWebSocketHeaders, T as prepareInteractionHeaders, U as readGitHubToken, W as readGitHubTokenFromEnv, X as forwardCodexResponses, Y as buildCodexRequestHeaders, Z as generateTraceId, _ as parseUserIdMetadata, at as createPooledWebSocketStream, b as copilotHeaders, ct as stripInternalRequestHeaders, d as generateRequestIdFromPayload, et as fetchUpstreamWithLifecycle, f as getRootSessionId, g as isResponsesStream, h as isNullish, it as getResponsesStreamTerminalDisposition, j as compactSystemPromptStarts, k as compactMessageSections, m as isAsyncIterable, n as invalidateCodexRuntime, nt as createResponsesSafeStream, ot as createWebSocketUrl, p as getUUID, rt as encodePoolKeyPart, s as setupCodexToken, tt as createResponsesHttpEventStream, u as stopCopilotRefreshLoop, v as getCopilotUsage, w as prepareForCompact, y as copilotBaseUrl } from "./token-kSGCOmTG.js";
4
+ import { a as isDeferredToolName, c as parseMcpToolSearchSentinel, d as shouldEnableResponsesToolSearch, i as isBridgeToolSearchName, l as resolveBridgeToolSearchName, o as listDeferredToolNames, r as formatToolSearchBridgeArguments, s as normalizeToolSearchBridgeArguments, t as BRIDGE_TOOL_SEARCH_NAME, u as selectDeferredToolsByNames } from "./tool-search-CcvaqM03.js";
5
+ import { n as isProviderAgentModelVisible, t as getProviderAgentModels } from "./provider-management-DOfLC7WX.js";
6
+ import { n as stopModelsRefreshLoop, t as setupCopilotRuntime } from "./copilot-runtime-Dg3ywZkl.js";
8
7
  import consola from "consola";
9
8
  import { createHash, randomUUID } from "node:crypto";
10
9
  import fs, { createWriteStream, readFileSync, rmSync } from "node:fs";
@@ -639,6 +638,7 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
639
638
  },
640
639
  "deepseek-v4.1-flash": {
641
640
  contextWindow: 1e6,
641
+ defaultReasoningEffort: "high",
642
642
  inputModalities: ["text", "image"],
643
643
  maxOutputTokens: 393216,
644
644
  pricing: {
@@ -651,10 +651,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
651
651
  },
652
652
  output: 8,
653
653
  peakWindows: dashscopePeakWindows
654
- }
654
+ },
655
+ reasoningEfforts: [
656
+ "low",
657
+ "high",
658
+ "max"
659
+ ]
655
660
  },
656
661
  "qwen3.8-max": {
657
662
  contextWindow: 1e6,
663
+ defaultReasoningEffort: "xhigh",
658
664
  inputModalities: ["text", "image"],
659
665
  maxOutputTokens: 64e3,
660
666
  pricing: {
@@ -663,10 +669,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
663
669
  explicitCachedInput: 1,
664
670
  input: 12,
665
671
  output: 36
666
- }
672
+ },
673
+ reasoningEfforts: [
674
+ "low",
675
+ "medium",
676
+ "xhigh"
677
+ ]
667
678
  },
668
679
  "qwen3.8-max-0902": {
669
680
  contextWindow: 1e6,
681
+ defaultReasoningEffort: "xhigh",
670
682
  inputModalities: ["text", "image"],
671
683
  maxOutputTokens: 131072,
672
684
  pricing: {
@@ -675,10 +687,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
675
687
  explicitCachedInput: 1,
676
688
  input: 12,
677
689
  output: 36
678
- }
690
+ },
691
+ reasoningEfforts: [
692
+ "low",
693
+ "medium",
694
+ "xhigh"
695
+ ]
679
696
  },
680
697
  "qwen3.8-flash": {
681
698
  contextWindow: 1e6,
699
+ defaultReasoningEffort: "xhigh",
682
700
  inputModalities: ["text", "image"],
683
701
  maxOutputTokens: 131072,
684
702
  pricing: {
@@ -687,10 +705,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
687
705
  explicitCachedInput: .1,
688
706
  input: .8,
689
707
  output: 2.7
690
- }
708
+ },
709
+ reasoningEfforts: [
710
+ "low",
711
+ "medium",
712
+ "xhigh"
713
+ ]
691
714
  },
692
715
  "qwen3.7-plus": {
693
716
  contextWindow: 1e6,
717
+ defaultReasoningEffort: "xhigh",
694
718
  inputModalities: ["text", "image"],
695
719
  maxOutputTokens: 64e3,
696
720
  pricing: { tiers: [{
@@ -707,17 +731,24 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
707
731
  input: 6,
708
732
  maxInputTokens: 1e6,
709
733
  output: 24
710
- }] }
734
+ }] },
735
+ reasoningEfforts: [
736
+ "low",
737
+ "medium",
738
+ "xhigh"
739
+ ]
711
740
  },
712
741
  "kimi/kimi-k3": {
713
742
  contextWindow: 1048576,
743
+ defaultReasoningEffort: "max",
714
744
  inputModalities: ["text", "image"],
715
745
  maxOutputTokens: 64e3,
716
746
  pricing: {
717
747
  cachedInput: 2,
718
748
  input: 20,
719
749
  output: 100
720
- }
750
+ },
751
+ reasoningEfforts: ["max"]
721
752
  },
722
753
  "ZHIPU/GLM-5.3": {
723
754
  contextWindow: 1048576,
@@ -4809,6 +4840,13 @@ const getCompactType = (anthropicPayload) => {
4809
4840
  if (system.some((msg) => typeof msg.text === "string" && compactSystemPromptStarts.some((promptStart) => msg.text.startsWith(promptStart)))) return 1;
4810
4841
  return 0;
4811
4842
  };
4843
+ const applyClaudeNoToolsEffort = (payload, userAgent) => {
4844
+ if (!isClaudeUserAgent(userAgent) || (payload.tools?.length ?? 0) > 0) return;
4845
+ payload.output_config = {
4846
+ ...payload.output_config,
4847
+ effort: "low"
4848
+ };
4849
+ };
4812
4850
  /**
4813
4851
  * True for Claude Code background security-monitor requests: no tools,
4814
4852
  * `stop_sequences: ["</block>"]`, and a system prompt starting with the
@@ -5083,7 +5121,10 @@ const prepareMessagesApiPayload = (payload, selectedModel) => {
5083
5121
  if (effort === "none" || effort === "minimal") effort = "low";
5084
5122
  const reasoningEffort = selectedModel.capabilities.supports.reasoning_effort;
5085
5123
  if (reasoningEffort && !reasoningEffort.includes(effort)) effort = reasoningEffort.at(-1);
5086
- payload.output_config = { effort };
5124
+ payload.output_config = {
5125
+ ...payload.output_config,
5126
+ effort
5127
+ };
5087
5128
  }
5088
5129
  const modelSupports = selectedModel?.capabilities.supports;
5089
5130
  if (!modelSupports?.adaptive_thinking) {
@@ -8173,6 +8214,7 @@ async function handleProviderMessages(c) {
8173
8214
  const provider = c.req.param("provider");
8174
8215
  const payload = await c.req.json();
8175
8216
  payload.model = fromClaudeDiscoveryModelId(payload.model);
8217
+ applyClaudeNoToolsEffort(payload, c.req.header("user-agent"));
8176
8218
  const claudeAutoModel = getClaudeAutoModel();
8177
8219
  if (claudeAutoModel && isClaudeAutoModelRequest(payload)) {
8178
8220
  consola.debug(`Claude auto model override (${provider}): ${payload.model} -> ${claudeAutoModel}`);
@@ -9232,6 +9274,7 @@ const messagesFlowHandlers = {
9232
9274
  async function handleCompletion(c) {
9233
9275
  const anthropicPayload = await c.req.json();
9234
9276
  anthropicPayload.model = fromClaudeDiscoveryModelId(anthropicPayload.model);
9277
+ applyClaudeNoToolsEffort(anthropicPayload, c.req.header("user-agent"));
9235
9278
  return await handleCompletionPayload(c, anthropicPayload);
9236
9279
  }
9237
9280
  async function handleCompletionPayload(c, anthropicPayload, dispatchOptions = {}) {
@@ -9248,11 +9291,12 @@ async function handleCompletionPayload(c, anthropicPayload, dispatchOptions = {}
9248
9291
  });
9249
9292
  if (webSearchResult) return webSearchResult;
9250
9293
  }
9251
- const claudeAutoModel = getClaudeAutoModel();
9294
+ const claudeAutoModel = getClaudeAutoModel(true);
9252
9295
  const shouldUseClaudeAutoModel = Boolean(!dispatchOptions.skipClaudeAutoModel && claudeAutoModel && isClaudeAutoModelRequest(anthropicPayload));
9253
9296
  if (claudeAutoModel && shouldUseClaudeAutoModel) {
9254
- consola.debug(`Claude auto model override: ${anthropicPayload.model} -> ${claudeAutoModel}`);
9255
- anthropicPayload.model = claudeAutoModel;
9297
+ const resolvedClaudeAutoModel = dispatchOptions.skipModelMapping ? claudeAutoModel : resolveMappedModel(claudeAutoModel);
9298
+ consola.debug(`Claude auto model override: ${anthropicPayload.model} -> ${resolvedClaudeAutoModel}`);
9299
+ anthropicPayload.model = resolvedClaudeAutoModel;
9256
9300
  }
9257
9301
  const providerModelAlias = await resolveConfiguredProviderModelAlias(anthropicPayload.model, providerMessagesHandlerDependencies.resolveProviderConfig);
9258
9302
  if (providerModelAlias) {
@@ -9389,6 +9433,17 @@ function getStringField(model, field) {
9389
9433
  const value = model[field];
9390
9434
  return typeof value === "string" && value.trim() ? value : void 0;
9391
9435
  }
9436
+ function getRecordField(model, field) {
9437
+ const value = model?.[field];
9438
+ return isRecord(value) ? value : void 0;
9439
+ }
9440
+ function getFirstPositiveNumber(model, fields) {
9441
+ if (!model) return void 0;
9442
+ for (const field of fields) {
9443
+ const value = model[field];
9444
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
9445
+ }
9446
+ }
9392
9447
  function getFallbackProviderModelRecords(provider, reason, details = {}) {
9393
9448
  const fallbackModels = getBuiltinProviderModelRecords(provider);
9394
9449
  logger$9.warn(`models.provider.fallback_${reason}`, {
@@ -9473,31 +9528,34 @@ async function getAggregatedModels(requestHeaders, selectors = {}) {
9473
9528
  const providerModelsByProvider = await Promise.all(listEnabledProviders().map((provider) => getProviderModels(provider, requestHeaders, selectors.selectProviderModels)));
9474
9529
  return deduplicateModels([...copilotModels, ...providerModelsByProvider.flat()], (model) => model.id);
9475
9530
  }
9476
- function createModelListResponse(c, models) {
9477
- return c.json({
9478
- object: "list",
9479
- data: models,
9480
- has_more: false
9481
- });
9482
- }
9483
- //#endregion
9484
- //#region src/routes/models/claude-models.ts
9485
- function selectClaudeCopilotModels(models) {
9531
+ function selectAgentCopilotModels(models) {
9486
9532
  const selection = getProviderAgentModels(getRawProviderConfig(GITHUB_COPILOT_PROVIDER));
9487
9533
  if (selection === void 0) return models;
9488
9534
  return models.filter((model) => selection.includes(model.id) || selection.includes(toClientModelId(model.id)));
9489
9535
  }
9490
- function selectClaudeProviderModels(providerConfig, models) {
9536
+ function selectAgentProviderModels(providerConfig, models) {
9491
9537
  const selection = getProviderAgentModels(providerConfig);
9492
9538
  if (selection === void 0) return models;
9493
9539
  const modelsById = getModelsById(models);
9494
9540
  return selection.map((id) => modelsById.get(id) ?? { id });
9495
9541
  }
9542
+ async function getAgentModels(requestHeaders) {
9543
+ return getAggregatedModels(requestHeaders, {
9544
+ selectCopilotModels: selectAgentCopilotModels,
9545
+ selectProviderModels: selectAgentProviderModels
9546
+ });
9547
+ }
9548
+ function createModelListResponse(c, models) {
9549
+ return c.json({
9550
+ object: "list",
9551
+ data: models,
9552
+ has_more: false
9553
+ });
9554
+ }
9555
+ //#endregion
9556
+ //#region src/routes/models/claude-models.ts
9496
9557
  async function handleClaudeModels(c) {
9497
- return createModelListResponse(c, (await getAggregatedModels(stripInternalRequestHeaders(c.req.raw.headers), {
9498
- selectCopilotModels: selectClaudeCopilotModels,
9499
- selectProviderModels: selectClaudeProviderModels
9500
- })).map((model) => ({
9558
+ return createModelListResponse(c, (await getAgentModels(stripInternalRequestHeaders(c.req.raw.headers))).map((model) => ({
9501
9559
  ...model,
9502
9560
  id: toClaudeDiscoveryModelId(model.id),
9503
9561
  ...typeof model.claude_model_id === "string" ? { claude_model_id: toClaudeDiscoveryModelId(model.claude_model_id) } : {}
@@ -9719,17 +9777,6 @@ function selectDefaultReasoningEffort(efforts, configured) {
9719
9777
  function positiveNumber(value, fallback) {
9720
9778
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
9721
9779
  }
9722
- function getRecordField(model, field) {
9723
- const value = model?.[field];
9724
- return isRecord(value) ? value : void 0;
9725
- }
9726
- function getFirstPositiveNumber(model, fields) {
9727
- if (!model) return void 0;
9728
- for (const field of fields) {
9729
- const value = model[field];
9730
- if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
9731
- }
9732
- }
9733
9780
  //#endregion
9734
9781
  //#region src/routes/models/models.json
9735
9782
  var models = [
@@ -11510,11 +11557,159 @@ async function handleDefaultModels(c) {
11510
11557
  return createModelListResponse(c, await getAggregatedModels(stripInternalRequestHeaders(c.req.raw.headers)));
11511
11558
  }
11512
11559
  //#endregion
11560
+ //#region src/routes/models/opencode-models.ts
11561
+ const RESPONSES_PACKAGE = "@opencode/ai/providers/openai/responses";
11562
+ const CNY_PER_USD = 6.7;
11563
+ const COST_DECIMALS = 6;
11564
+ function isOpencodeUserAgent(userAgent) {
11565
+ return /opencode/iu.test(userAgent ?? "");
11566
+ }
11567
+ function resolveUsdRate(currency) {
11568
+ if (currency === "USD") return 1;
11569
+ if (currency === "CNY") return 1 / CNY_PER_USD;
11570
+ }
11571
+ function roundCost(value) {
11572
+ const factor = 10 ** COST_DECIMALS;
11573
+ return Math.round(value * factor) / factor;
11574
+ }
11575
+ function mapCost(value, rate, tier) {
11576
+ return {
11577
+ input: roundCost(value.input * rate),
11578
+ output: roundCost(value.output * rate),
11579
+ cache: {
11580
+ read: roundCost((value.cache_read ?? 0) * rate),
11581
+ write: roundCost((value.cache_write ?? 0) * rate)
11582
+ },
11583
+ ...tier && { tier }
11584
+ };
11585
+ }
11586
+ function mapCatalogCost(cost) {
11587
+ if (!cost) return [];
11588
+ const tiers = Array.isArray(cost.tiers) ? cost.tiers : [];
11589
+ return [
11590
+ mapCost(cost, 1),
11591
+ ...tiers.map((tier) => mapCost(tier, 1, tier.tier)),
11592
+ ...tiers.length === 0 && cost.context_over_200k ? [mapCost(cost.context_over_200k, 1, {
11593
+ type: "context",
11594
+ size: 200001
11595
+ })] : []
11596
+ ];
11597
+ }
11598
+ function mapConfiguredCost(pricing, rate) {
11599
+ const tiers = [...pricing.tiers?.length ? pricing.tiers : [pricing]].sort((a, b) => (a.maxInputTokens ?? Infinity) - (b.maxInputTokens ?? Infinity));
11600
+ return tiers.map((tier, index) => mapCost({
11601
+ input: tier.input ?? pricing.input ?? 0,
11602
+ output: tier.output ?? pricing.output ?? 0,
11603
+ cache_read: tier.cachedInput ?? pricing.cachedInput,
11604
+ cache_write: tier.cacheCreationInput ?? pricing.cacheCreationInput
11605
+ }, rate, index > 0 ? {
11606
+ type: "context",
11607
+ size: (tiers[index - 1].maxInputTokens ?? 0) + 1
11608
+ } : void 0));
11609
+ }
11610
+ function positiveInteger(...values) {
11611
+ const value = values.find((value) => typeof value === "number" && Number.isFinite(value) && value >= 1);
11612
+ return Math.floor(value ?? 0);
11613
+ }
11614
+ function stringList(value) {
11615
+ if (!Array.isArray(value)) return void 0;
11616
+ const strings = [...new Set(value.filter((item) => typeof item === "string"))];
11617
+ return strings.length > 0 ? strings : void 0;
11618
+ }
11619
+ const RESPONSES_EFFORTS = /* @__PURE__ */ new Set([
11620
+ "none",
11621
+ "minimal",
11622
+ "low",
11623
+ "medium",
11624
+ "high",
11625
+ "xhigh",
11626
+ "max"
11627
+ ]);
11628
+ function normalizeEffortValues(values) {
11629
+ const efforts = (values ?? []).filter((value) => RESPONSES_EFFORTS.has(value));
11630
+ return [...new Set(efforts)];
11631
+ }
11632
+ function catalogEffortValues(catalog) {
11633
+ const options = catalog?.reasoning_options;
11634
+ if (!Array.isArray(options)) return void 0;
11635
+ const values = [];
11636
+ for (const option of options) {
11637
+ if (!isRecord(option) || option.type !== "effort") continue;
11638
+ const optionValues = option.values;
11639
+ if (!Array.isArray(optionValues)) continue;
11640
+ for (const value of optionValues) if (typeof value === "string") values.push(value);
11641
+ }
11642
+ return stringList(values);
11643
+ }
11644
+ function toOpencodeModel(model, contextWindow) {
11645
+ const separator = model.id.indexOf("/");
11646
+ const provider = separator < 0 ? GITHUB_COPILOT_PROVIDER : model.id.slice(0, separator);
11647
+ const rawId = separator < 0 ? findEndpointModel(model.id)?.id ?? model.id : model.id.slice(separator + 1);
11648
+ const config = getRawProviderConfig(provider);
11649
+ const modelConfig = config?.models?.[rawId] ?? config?.models?.[model.id];
11650
+ const builtin = builtinProviderModelRegistry.getModelConfig(provider, rawId);
11651
+ const catalogProvider = config?.modelsDevProviderId || provider;
11652
+ const catalog = getModelsDevModel(catalogProvider, rawId) ?? getModelsDevModel(catalogProvider, model.id);
11653
+ const capabilities = getRecordField(model, "capabilities");
11654
+ const supports = getRecordField(capabilities, "supports");
11655
+ const limits = getRecordField(capabilities, "limits");
11656
+ const context = positiveInteger(modelConfig?.contextWindow, getFirstPositiveNumber(limits, ["max_context_window_tokens", "max_prompt_tokens"]), getFirstPositiveNumber(model, [
11657
+ "context_window",
11658
+ "context_length",
11659
+ "max_context_length",
11660
+ "max_model_len"
11661
+ ]), catalog?.limit?.context, builtin?.contextWindow, 2e5);
11662
+ const inputLimit = positiveInteger(getFirstPositiveNumber(limits, ["max_prompt_tokens"]), catalog?.limit?.input);
11663
+ const supportedMediaTypes = stringList(getRecordField(limits, "vision")?.supported_media_types);
11664
+ const supportPdf = modelConfig?.supportPdf ?? (provider === "codex" || provider === "xai" || provider === "github-copilot" && supportedMediaTypes?.includes("application/pdf") === true || stringList(catalog?.modalities?.input)?.includes("pdf") === true);
11665
+ const input = [...stringList(modelConfig?.inputModalities) ?? stringList(model.input_modalities ?? getRecordField(model, "modalities")?.input ?? model.modalities ?? getRecordField(model, "architecture")?.input_modalities) ?? (typeof supports?.vision === "boolean" ? ["text", ...supports.vision ? ["image"] : []] : void 0) ?? catalog?.modalities?.input ?? builtin?.inputModalities ?? ["text"]].filter((modality) => modality !== "pdf" || supportPdf);
11666
+ if (supportPdf && !input.includes("pdf")) input.push("pdf");
11667
+ const efforts = normalizeEffortValues(stringList(modelConfig?.reasoningEfforts ?? model.reasoning_efforts ?? supports?.reasoning_effort) ?? catalogEffortValues(catalog) ?? builtin?.reasoningEfforts);
11668
+ const configuredRate = resolveUsdRate(resolveProviderCurrency(provider, config?.pricingCurrency));
11669
+ const builtinRate = resolveUsdRate(resolveProviderCurrency(provider, void 0));
11670
+ const cost = modelConfig?.pricing && configuredRate !== void 0 ? mapConfiguredCost(modelConfig.pricing, configuredRate) : catalog?.cost ? mapCatalogCost(catalog.cost) : builtin?.pricing && builtinRate !== void 0 ? mapConfiguredCost(builtin.pricing, builtinRate) : [];
11671
+ const released = Date.parse(catalog?.release_date ?? "");
11672
+ return {
11673
+ id: model.id,
11674
+ modelID: model.id,
11675
+ providerID: "local",
11676
+ name: getStringField(model, "display_name") ?? catalog?.name ?? model.id,
11677
+ family: catalog?.family ?? getStringField(capabilities ?? {}, "family"),
11678
+ package: RESPONSES_PACKAGE,
11679
+ capabilities: {
11680
+ tools: typeof supports?.tool_calls === "boolean" ? supports.tool_calls : catalog?.tool_call ?? true,
11681
+ input: [...input],
11682
+ output: [...catalog?.modalities?.output ?? ["text"]]
11683
+ },
11684
+ variants: efforts.map((effort) => ({
11685
+ id: effort,
11686
+ body: { reasoning: { effort } }
11687
+ })),
11688
+ time: { released: Number.isFinite(released) ? released : 0 },
11689
+ cost,
11690
+ status: catalog?.status ?? (model.preview ? "beta" : "active"),
11691
+ enabled: true,
11692
+ limit: {
11693
+ context: Math.min(context, contextWindow),
11694
+ ...inputLimit > 0 && { input: Math.min(inputLimit, context, contextWindow) },
11695
+ output: Math.min(context, positiveInteger(modelConfig?.maxOutputTokens, getFirstPositiveNumber(limits, ["max_output_tokens"]), getFirstPositiveNumber(model, ["max_output_tokens"]), catalog?.limit?.output, builtin?.maxOutputTokens, 32e3))
11696
+ }
11697
+ };
11698
+ }
11699
+ async function handleOpencodeModels(c) {
11700
+ const models = await getAgentModels(stripInternalRequestHeaders(c.req.raw.headers));
11701
+ const contextWindow = getOpencodeModelContextWindow();
11702
+ c.header("Cache-Control", "private, no-store");
11703
+ c.header("Vary", "User-Agent");
11704
+ return createModelListResponse(c, models.map((model) => toOpencodeModel(model, contextWindow)));
11705
+ }
11706
+ //#endregion
11513
11707
  //#region src/routes/models/route.ts
11514
11708
  const modelRoutes = new Hono();
11515
11709
  modelRoutes.get("/", async (c) => {
11516
11710
  try {
11517
11711
  const userAgent = c.req.header("user-agent");
11712
+ if (isOpencodeUserAgent(userAgent)) return await handleOpencodeModels(c);
11518
11713
  if (isCodexUserAgent(userAgent)) return await handleCodexModels(c);
11519
11714
  if (isClaudeUserAgent(userAgent)) return await handleClaudeModels(c);
11520
11715
  return await handleDefaultModels(c);
@@ -13175,4 +13370,4 @@ createServer();
13175
13370
  //#endregion
13176
13371
  export { createServer };
13177
13372
 
13178
- //# sourceMappingURL=server-CrRNnmrV.js.map
13373
+ //# sourceMappingURL=server-CClOz6YS.js.map