@jeffreycao/copilot-api 2.7.6 → 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.
- package/dist/auth-BzYvzeW0.js +2 -0
- package/dist/{auth-MHYBC-Hj.js → auth-qC1GSLdS.js} +4 -4
- package/dist/{auth-MHYBC-Hj.js.map → auth-qC1GSLdS.js.map} +1 -1
- package/dist/{config-CZdq_04f.js → config-Cd0U5gXz.js} +8 -3
- package/dist/config-Cd0U5gXz.js.map +1 -0
- package/dist/{config-store-BD3_fWvY.js → config-store-C6GAtKLz.js} +11 -3
- package/dist/config-store-C6GAtKLz.js.map +1 -0
- package/dist/{copilot-runtime-D-_s8L_X.js → copilot-runtime-Dg3ywZkl.js} +3 -3
- package/dist/{copilot-runtime-D-_s8L_X.js.map → copilot-runtime-Dg3ywZkl.js.map} +1 -1
- package/dist/{debug-C8yoWFl7.js → debug-CmL-V7Ov.js} +3 -3
- package/dist/{debug-C8yoWFl7.js.map → debug-CmL-V7Ov.js.map} +1 -1
- package/dist/main.js +4 -4
- package/dist/{provider-BNOCmFw9.js → provider-CzziTLqX.js} +2 -2
- package/dist/{provider-BNOCmFw9.js.map → provider-CzziTLqX.js.map} +1 -1
- package/dist/{provider-management-Du98I_tf.js → provider-management-DOfLC7WX.js} +2 -2
- package/dist/{provider-management-Du98I_tf.js.map → provider-management-DOfLC7WX.js.map} +1 -1
- package/dist/{server-CB_RoZhM.js → server-CClOz6YS.js} +221 -38
- package/dist/server-CClOz6YS.js.map +1 -0
- package/dist/{start-oHifz6_B.js → start-y2hlYweN.js} +7 -7
- package/dist/{start-oHifz6_B.js.map → start-y2hlYweN.js.map} +1 -1
- package/dist/{token-D84GjiaE.js → token-kSGCOmTG.js} +3 -3
- package/dist/{token-D84GjiaE.js.map → token-kSGCOmTG.js.map} +1 -1
- package/package.json +1 -1
- package/dist/auth-u5nqh-_U.js +0 -2
- package/dist/config-CZdq_04f.js.map +0 -1
- package/dist/config-store-BD3_fWvY.js.map +0 -1
- package/dist/server-CB_RoZhM.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-runtime-D-_s8L_X.js","names":["getCopilotModels"],"sources":["../src/services/copilot/get-models.ts","../src/services/copilot/models-cache.ts","../src/lib/deviceid.ts","../src/services/get-vscode-version.ts","../src/services/vscode-env.ts","../src/lib/copilot-runtime.ts"],"sourcesContent":["import consola from \"consola\"\n\nimport { copilotBaseUrl, copilotModelsHeaders } from \"~/lib/api-config\"\n\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport type { ModelsResponse } from \"~/lib/types/models\"\n\nexport const getModels = async () => {\n consola.info(`Fetching models from ${copilotBaseUrl(state)}/models`)\n const response = await fetch(`${copilotBaseUrl(state)}/models`, {\n headers: copilotModelsHeaders(state),\n })\n\n if (!response.ok) {\n const errorText = await response.clone().text()\n\n consola.error(\"Failed to get models response body\", errorText)\n\n throw new HTTPError(\"Failed to get models\", response)\n }\n\n return (await response.json()) as ModelsResponse\n}\n","import consola from \"consola\"\n\nimport { state } from \"~/lib/state\"\nimport { getModels as getCopilotModels } from \"~/services/copilot/get-models\"\n\n// Periodically refresh models so long-running daemons pick up new SKUs.\nconst MODELS_REFRESH_BASE_MS = 30 * 60 * 1000\nlet modelsRefreshTimer: ReturnType<typeof setTimeout> | null = null\n// This loop runs on a plain timer that no AbortController owns, so stopping it\n// cannot cancel a response that is already on the wire. The generation lets a\n// stopped loop neither write state.models nor schedule itself again.\nlet refreshGeneration = 0\n\nconst cancelModelsRefreshTimer = () => {\n if (modelsRefreshTimer) {\n clearTimeout(modelsRefreshTimer)\n modelsRefreshTimer = null\n }\n}\n\nexport const stopModelsRefreshLoop = () => {\n // Bump before cancelling so a refresh already awaiting its response sees a\n // different generation and drops both its result and its next tick.\n refreshGeneration++\n cancelModelsRefreshTimer()\n}\n\ntype ModelsFetcher = typeof getCopilotModels\n\nconst refreshModels = async (fetcher: ModelsFetcher, generation: number) => {\n const prevIds = new Set(state.models?.data.map((m) => m.id) ?? [])\n const models = await fetcher()\n if (generation !== refreshGeneration) return\n\n state.models = {\n ...models,\n data: models.data.filter(\n (model) =>\n model.policy?.state !== \"disabled\"\n && (model.model_picker_enabled\n || model.capabilities.type === \"embeddings\"),\n ),\n }\n const nextIds = state.models.data.map((m) => m.id)\n const added = nextIds.filter((id) => !prevIds.has(id))\n if (added.length > 0) {\n consola.info(`Models refresh: ${added.length} new`)\n } else {\n consola.debug(`Models refresh: no changes (${nextIds.length} total)`)\n }\n}\n\nconst scheduleModelsRefresh = (fetcher: ModelsFetcher, intervalMs: number) => {\n const generation = refreshGeneration\n const jitter = Math.floor(Math.random() * (intervalMs / 6))\n const delay = intervalMs + jitter\n consola.debug(\n `Scheduling next models refresh in ${Math.round(delay / 1000)} seconds`,\n )\n\n cancelModelsRefreshTimer()\n modelsRefreshTimer = setTimeout(async () => {\n try {\n await refreshModels(fetcher, generation)\n } catch (error) {\n if (generation === refreshGeneration) {\n consola.warn(\"Failed to refresh models, keeping previous cache.\", error)\n }\n } finally {\n if (generation === refreshGeneration) {\n scheduleModelsRefresh(fetcher, intervalMs)\n }\n }\n }, delay)\n}\n\nexport async function cacheModels(\n fetcher: ModelsFetcher = getCopilotModels,\n intervalMs: number = MODELS_REFRESH_BASE_MS,\n): Promise<void> {\n // A fresh population supersedes whatever the previous loop was doing. This\n // is the path a config reload takes when the GitHub token changes, so a\n // request still in flight for the old account must not join this generation\n // and overwrite state.models once it comes back.\n refreshGeneration++\n const generation = refreshGeneration\n await refreshModels(fetcher, generation)\n if (generation !== refreshGeneration) return\n\n scheduleModelsRefresh(fetcher, intervalMs)\n}\n","import consola from \"consola\"\nimport { randomUUID } from \"node:crypto\"\nimport path from \"node:path\"\n\nconst WINDOWS_DEVICE_ID_KEY = String.raw`\\SOFTWARE\\Microsoft\\DeveloperTools`\nconst WINDOWS_DEVICE_ID_NAME = \"deviceid\"\n\ntype RegistryArch = \"x86\" | \"x64\"\n\ninterface WinregConstructor {\n new (options: {\n hive: string\n key: string\n arch?: RegistryArch\n }): WinregRegistry\n HKCU: string\n REG_SZ: string\n}\n\ninterface WinregRegistry {\n get(\n name: string,\n callback: (error: RegistryError | null, item: RegistryItem | null) => void,\n ): void\n set(\n name: string,\n type: string,\n value: string,\n callback: (error: RegistryError | null) => void,\n ): void\n}\n\ninterface RegistryItem {\n value?: string\n}\n\ninterface RegistryError extends Error {\n code?: number | string\n}\n\nconst windows64Architectures = new Set([\"AMD64\", \"ARM64\", \"IA64\"])\n\nconst getPosixHomeDir = (): string => {\n if (!process.env.HOME) {\n throw new Error(\"Home directory not found\")\n }\n\n return process.env.HOME\n}\n\nconst getDeviceIdFilePath = (): string => {\n let folder: string\n\n switch (process.platform) {\n case \"darwin\": {\n folder = path.posix.join(\n getPosixHomeDir(),\n \"Library\",\n \"Application Support\",\n )\n break\n }\n case \"linux\": {\n folder =\n process.env.XDG_CACHE_HOME\n ?? path.posix.join(getPosixHomeDir(), \".cache\")\n break\n }\n default: {\n throw new Error(\"Unsupported platform\")\n }\n }\n\n return path.posix.join(folder, \"Microsoft\", \"DeveloperTools\", \"deviceid\")\n}\n\nconst isMissingFileError = (error: unknown): error is NodeJS.ErrnoException => {\n return error instanceof Error && \"code\" in error && error.code === \"ENOENT\"\n}\n\nconst readStoredDeviceIdFile = async (\n filePath: string,\n): Promise<string | undefined> => {\n const { readFile } = await import(\"node:fs/promises\")\n\n try {\n return await readFile(filePath, \"utf8\")\n } catch (error) {\n if (isMissingFileError(error)) {\n return undefined\n }\n\n throw error\n }\n}\n\nconst writeStoredDeviceIdFile = async (\n filePath: string,\n deviceId: string,\n): Promise<void> => {\n const { mkdir, writeFile } = await import(\"node:fs/promises\")\n\n await mkdir(path.posix.dirname(filePath), { recursive: true })\n await writeFile(filePath, deviceId, \"utf8\")\n}\n\nconst getWindowsRegistryArch = (): RegistryArch | undefined => {\n const architecture = (\n process.env.PROCESSOR_ARCHITEW6432 ?? process.env.PROCESSOR_ARCHITECTURE\n )?.toUpperCase()\n\n return architecture && windows64Architectures.has(architecture) ?\n \"x64\"\n : undefined\n}\n\nconst loadWinreg = async (): Promise<WinregConstructor> => {\n const module = await import(\"winreg\")\n const winreg =\n \"default\" in module ? (module.default as unknown) : (module as unknown)\n\n return winreg as WinregConstructor\n}\n\nconst isMissingRegistryError = (error: RegistryError | null): boolean => {\n if (!error) {\n return false\n }\n\n const errorCode = Number(error.code)\n\n return Number.isFinite(errorCode) && errorCode === 1\n}\n\nconst createWindowsRegistry = async (): Promise<{\n registry: WinregRegistry\n regSz: string\n}> => {\n const Winreg = await loadWinreg()\n\n return {\n registry: new Winreg({\n hive: Winreg.HKCU,\n key: WINDOWS_DEVICE_ID_KEY,\n arch: getWindowsRegistryArch(),\n }),\n regSz: Winreg.REG_SZ,\n }\n}\n\nconst readRegistryString = async (\n registry: WinregRegistry,\n name: string,\n): Promise<string | undefined> => {\n return new Promise((resolve, reject) => {\n registry.get(name, (error, item) => {\n if (isMissingRegistryError(error)) {\n resolve(undefined)\n return\n }\n\n if (error) {\n reject(\n error instanceof Error ? error : new Error(\"Unknown registry error\"),\n )\n return\n }\n\n resolve(item?.value)\n })\n })\n}\n\nconst writeRegistryString = async ({\n registry,\n regSz,\n name,\n value,\n}: {\n registry: WinregRegistry\n regSz: string\n name: string\n value: string\n}): Promise<void> => {\n return new Promise((resolve, reject) => {\n registry.set(name, regSz, value, (error) => {\n if (error) {\n reject(\n error instanceof Error ? error : new Error(\"Unknown registry error\"),\n )\n return\n }\n\n resolve()\n })\n })\n}\n\nexport const getStoredVSCodeDeviceId = async (): Promise<\n string | undefined\n> => {\n switch (process.platform) {\n case \"win32\": {\n const { registry } = await createWindowsRegistry()\n\n return readRegistryString(registry, WINDOWS_DEVICE_ID_NAME)\n }\n case \"darwin\":\n case \"linux\": {\n return readStoredDeviceIdFile(getDeviceIdFilePath())\n }\n default: {\n throw new Error(\"Unsupported platform\")\n }\n }\n}\n\nconst setStoredVSCodeDeviceId = async (deviceId: string): Promise<void> => {\n switch (process.platform) {\n case \"win32\": {\n const { registry, regSz } = await createWindowsRegistry()\n\n await writeRegistryString({\n registry,\n regSz,\n name: WINDOWS_DEVICE_ID_NAME,\n value: deviceId,\n })\n return\n }\n case \"darwin\":\n case \"linux\": {\n await writeStoredDeviceIdFile(getDeviceIdFilePath(), deviceId)\n return\n }\n default: {\n throw new Error(\"Unsupported platform\")\n }\n }\n}\n\nconst createVSCodeDeviceId = (): string => randomUUID().toLowerCase()\n\nexport async function getVSCodeDeviceId(): Promise<string> {\n let deviceId: string | undefined\n\n try {\n deviceId = await getStoredVSCodeDeviceId()\n } catch (error) {\n consola.debug(\"Failed to read VSCode device id\", error)\n }\n\n if (deviceId) {\n return deviceId\n }\n\n const newDeviceId = createVSCodeDeviceId()\n\n try {\n await setStoredVSCodeDeviceId(newDeviceId)\n } catch (error) {\n consola.warn(\n \"Failed to persist VSCode device id, using ephemeral id\",\n error,\n )\n }\n\n return newDeviceId\n}\n","const FALLBACK = \"1.140.0\"\n\nexport async function getVSCodeVersion() {\n await Promise.resolve()\n return FALLBACK\n}\n","import consola from \"consola\"\nimport { createHash, randomUUID } from \"node:crypto\"\nimport { networkInterfaces } from \"node:os\"\n\nimport { getVSCodeDeviceId } from \"~/lib/deviceid\"\nimport { state } from \"~/lib/state\"\nimport { getVSCodeVersion } from \"~/services/get-vscode-version\"\n\nexport const cacheVSCodeVersion = async () => {\n const response = await getVSCodeVersion()\n state.vsCodeVersion = response\n\n consola.info(`Using VSCode version: ${response}`)\n}\n\nconst invalidMacAddresses = new Set([\n \"00:00:00:00:00:00\",\n \"ff:ff:ff:ff:ff:ff\",\n \"ac:de:48:00:11:22\",\n])\n\nfunction validateMacAddress(candidate: string): boolean {\n const tempCandidate = candidate.replaceAll(\"-\", \":\").toLowerCase()\n return !invalidMacAddresses.has(tempCandidate)\n}\n\nexport function getMac(): string | null {\n const ifaces = networkInterfaces()\n // eslint-disable-next-line guard-for-in\n for (const name in ifaces) {\n const networkInterface = ifaces[name]\n if (networkInterface) {\n for (const { mac } of networkInterface) {\n if (validateMacAddress(mac)) {\n return mac\n }\n }\n }\n }\n return null\n}\n\nexport const cacheMacMachineId = () => {\n const macAddress = getMac() ?? randomUUID()\n state.macMachineId = createHash(\"sha256\")\n .update(macAddress, \"utf8\")\n .digest(\"hex\")\n consola.debug(`Using machine ID: ${state.macMachineId}`)\n}\n\nexport const cacheVsCodeDeviceId = async () => {\n state.vsCodeDeviceId = await getVSCodeDeviceId()\n consola.debug(`Using VSCode device ID: ${state.vsCodeDeviceId}`)\n}\n\nconst SESSION_REFRESH_BASE_MS = 60 * 60 * 1000\nconst SESSION_REFRESH_JITTER_MS = 20 * 60 * 1000\nlet vsCodeSessionRefreshTimer: ReturnType<typeof setTimeout> | null = null\n\nconst generateSessionId = () => {\n state.vsCodeSessionId = randomUUID() + Date.now().toString()\n consola.debug(`Generated VSCode session ID: ${state.vsCodeSessionId}`)\n}\n\nexport const stopVsCodeSessionRefreshLoop = () => {\n if (vsCodeSessionRefreshTimer) {\n clearTimeout(vsCodeSessionRefreshTimer)\n vsCodeSessionRefreshTimer = null\n }\n}\n\nconst scheduleSessionIdRefresh = () => {\n const randomDelay = Math.floor(Math.random() * SESSION_REFRESH_JITTER_MS)\n const delay = SESSION_REFRESH_BASE_MS + randomDelay\n consola.debug(\n `Scheduling next VSCode session ID refresh in ${Math.round(\n delay / 1000,\n )} seconds`,\n )\n\n stopVsCodeSessionRefreshLoop()\n vsCodeSessionRefreshTimer = setTimeout(() => {\n try {\n generateSessionId()\n } catch (error) {\n consola.error(\"Failed to refresh session ID, rescheduling...\", error)\n } finally {\n scheduleSessionIdRefresh()\n }\n }, delay)\n}\n\nexport const cacheVsCodeSessionId = () => {\n stopVsCodeSessionRefreshLoop()\n generateSessionId()\n scheduleSessionIdRefresh()\n}\n","import { state } from \"~/lib/state\"\nimport { logUser, setupCopilotToken } from \"~/lib/token\"\nimport { cacheModels } from \"~/services/copilot/models-cache\"\nimport {\n cacheMacMachineId,\n cacheVSCodeVersion,\n cacheVsCodeSessionId,\n cacheVsCodeDeviceId,\n} from \"~/services/vscode-env\"\n\nexport async function setupCopilotRuntime(githubToken: string): Promise<void> {\n state.githubToken = githubToken\n await logUser()\n await cacheVSCodeVersion()\n cacheMacMachineId()\n cacheVsCodeSessionId()\n await cacheVsCodeDeviceId()\n await setupCopilotToken()\n await cacheModels()\n}\n"],"mappings":";;;;;;;AAQA,MAAa,YAAY,YAAY;CACnC,QAAQ,KAAK,wBAAwB,eAAe,KAAK,EAAE,QAAQ;CACnE,MAAM,WAAW,MAAM,MAAM,GAAG,eAAe,KAAK,EAAE,UAAU,EAC9D,SAAS,qBAAqB,KAAK,EACrC,CAAC;CAED,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,YAAY,MAAM,SAAS,MAAM,CAAC,CAAC,KAAK;EAE9C,QAAQ,MAAM,sCAAsC,SAAS;EAE7D,MAAM,IAAI,UAAU,wBAAwB,QAAQ;CACtD;CAEA,OAAQ,MAAM,SAAS,KAAK;AAC9B;;;ACjBA,MAAM,yBAAyB;AAC/B,IAAI,qBAA2D;AAI/D,IAAI,oBAAoB;AAExB,MAAM,iCAAiC;CACrC,IAAI,oBAAoB;EACtB,aAAa,kBAAkB;EAC/B,qBAAqB;CACvB;AACF;AAEA,MAAa,8BAA8B;CAGzC;CACA,yBAAyB;AAC3B;AAIA,MAAM,gBAAgB,OAAO,SAAwB,eAAuB;CAC1E,MAAM,UAAU,IAAI,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,EAAE,EAAE,KAAK,CAAC,CAAC;CACjE,MAAM,SAAS,MAAM,QAAQ;CAC7B,IAAI,eAAe,mBAAmB;CAEtC,MAAM,SAAS;EACb,GAAG;EACH,MAAM,OAAO,KAAK,QACf,UACC,MAAM,QAAQ,UAAU,eACpB,MAAM,wBACL,MAAM,aAAa,SAAS,aACrC;CACF;CACA,MAAM,UAAU,MAAM,OAAO,KAAK,KAAK,MAAM,EAAE,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W,IAAI,KAAK,IAAI,CAAC,CAAC,SAAS;CAC3D,QAAQ,MAAM,gCAAgC,MAAM,iBAAiB;AACvE;AAEA,MAAa,qCAAqC;CAChD,IAAI,2BAA2B;EAC7B,aAAa,yBAAyB;EACtC,4BAA4B;CAC9B;AACF;AAEA,MAAM,iCAAiC;CACrC,MAAM,cAAc,KAAK,MAAM,KAAK,OAAO,IAAI,yBAAyB;CACxE,MAAM,QAAQ,0BAA0B;CACxC,QAAQ,MACN,gDAAgD,KAAK,MACnD,QAAQ,GACV,EAAE,SACJ;CAEA,6BAA6B;CAC7B,4BAA4B,iBAAiB;EAC3C,IAAI;GACF,kBAAkB;EACpB,SAAS,OAAO;GACd,QAAQ,MAAM,iDAAiD,KAAK;EACtE,UAAU;GACR,yBAAyB;EAC3B;CACF,GAAG,KAAK;AACV;AAEA,MAAa,6BAA6B;CACxC,6BAA6B;CAC7B,kBAAkB;CAClB,yBAAyB;AAC3B;;;ACtFA,eAAsB,oBAAoB,aAAoC;CAC5E,MAAM,cAAc;CACpB,MAAM,QAAQ;CACd,MAAM,mBAAmB;CACzB,kBAAkB;CAClB,qBAAqB;CACrB,MAAM,oBAAoB;CAC1B,MAAM,kBAAkB;CACxB,MAAM,YAAY;AACpB"}
|
|
1
|
+
{"version":3,"file":"copilot-runtime-Dg3ywZkl.js","names":["getCopilotModels"],"sources":["../src/services/copilot/get-models.ts","../src/services/copilot/models-cache.ts","../src/lib/deviceid.ts","../src/services/get-vscode-version.ts","../src/services/vscode-env.ts","../src/lib/copilot-runtime.ts"],"sourcesContent":["import consola from \"consola\"\n\nimport { copilotBaseUrl, copilotModelsHeaders } from \"~/lib/api-config\"\n\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport type { ModelsResponse } from \"~/lib/types/models\"\n\nexport const getModels = async () => {\n consola.info(`Fetching models from ${copilotBaseUrl(state)}/models`)\n const response = await fetch(`${copilotBaseUrl(state)}/models`, {\n headers: copilotModelsHeaders(state),\n })\n\n if (!response.ok) {\n const errorText = await response.clone().text()\n\n consola.error(\"Failed to get models response body\", errorText)\n\n throw new HTTPError(\"Failed to get models\", response)\n }\n\n return (await response.json()) as ModelsResponse\n}\n","import consola from \"consola\"\n\nimport { state } from \"~/lib/state\"\nimport { getModels as getCopilotModels } from \"~/services/copilot/get-models\"\n\n// Periodically refresh models so long-running daemons pick up new SKUs.\nconst MODELS_REFRESH_BASE_MS = 30 * 60 * 1000\nlet modelsRefreshTimer: ReturnType<typeof setTimeout> | null = null\n// This loop runs on a plain timer that no AbortController owns, so stopping it\n// cannot cancel a response that is already on the wire. The generation lets a\n// stopped loop neither write state.models nor schedule itself again.\nlet refreshGeneration = 0\n\nconst cancelModelsRefreshTimer = () => {\n if (modelsRefreshTimer) {\n clearTimeout(modelsRefreshTimer)\n modelsRefreshTimer = null\n }\n}\n\nexport const stopModelsRefreshLoop = () => {\n // Bump before cancelling so a refresh already awaiting its response sees a\n // different generation and drops both its result and its next tick.\n refreshGeneration++\n cancelModelsRefreshTimer()\n}\n\ntype ModelsFetcher = typeof getCopilotModels\n\nconst refreshModels = async (fetcher: ModelsFetcher, generation: number) => {\n const prevIds = new Set(state.models?.data.map((m) => m.id) ?? [])\n const models = await fetcher()\n if (generation !== refreshGeneration) return\n\n state.models = {\n ...models,\n data: models.data.filter(\n (model) =>\n model.policy?.state !== \"disabled\"\n && (model.model_picker_enabled\n || model.capabilities.type === \"embeddings\"),\n ),\n }\n const nextIds = state.models.data.map((m) => m.id)\n const added = nextIds.filter((id) => !prevIds.has(id))\n if (added.length > 0) {\n consola.info(`Models refresh: ${added.length} new`)\n } else {\n consola.debug(`Models refresh: no changes (${nextIds.length} total)`)\n }\n}\n\nconst scheduleModelsRefresh = (fetcher: ModelsFetcher, intervalMs: number) => {\n const generation = refreshGeneration\n const jitter = Math.floor(Math.random() * (intervalMs / 6))\n const delay = intervalMs + jitter\n consola.debug(\n `Scheduling next models refresh in ${Math.round(delay / 1000)} seconds`,\n )\n\n cancelModelsRefreshTimer()\n modelsRefreshTimer = setTimeout(async () => {\n try {\n await refreshModels(fetcher, generation)\n } catch (error) {\n if (generation === refreshGeneration) {\n consola.warn(\"Failed to refresh models, keeping previous cache.\", error)\n }\n } finally {\n if (generation === refreshGeneration) {\n scheduleModelsRefresh(fetcher, intervalMs)\n }\n }\n }, delay)\n}\n\nexport async function cacheModels(\n fetcher: ModelsFetcher = getCopilotModels,\n intervalMs: number = MODELS_REFRESH_BASE_MS,\n): Promise<void> {\n // A fresh population supersedes whatever the previous loop was doing. This\n // is the path a config reload takes when the GitHub token changes, so a\n // request still in flight for the old account must not join this generation\n // and overwrite state.models once it comes back.\n refreshGeneration++\n const generation = refreshGeneration\n await refreshModels(fetcher, generation)\n if (generation !== refreshGeneration) return\n\n scheduleModelsRefresh(fetcher, intervalMs)\n}\n","import consola from \"consola\"\nimport { randomUUID } from \"node:crypto\"\nimport path from \"node:path\"\n\nconst WINDOWS_DEVICE_ID_KEY = String.raw`\\SOFTWARE\\Microsoft\\DeveloperTools`\nconst WINDOWS_DEVICE_ID_NAME = \"deviceid\"\n\ntype RegistryArch = \"x86\" | \"x64\"\n\ninterface WinregConstructor {\n new (options: {\n hive: string\n key: string\n arch?: RegistryArch\n }): WinregRegistry\n HKCU: string\n REG_SZ: string\n}\n\ninterface WinregRegistry {\n get(\n name: string,\n callback: (error: RegistryError | null, item: RegistryItem | null) => void,\n ): void\n set(\n name: string,\n type: string,\n value: string,\n callback: (error: RegistryError | null) => void,\n ): void\n}\n\ninterface RegistryItem {\n value?: string\n}\n\ninterface RegistryError extends Error {\n code?: number | string\n}\n\nconst windows64Architectures = new Set([\"AMD64\", \"ARM64\", \"IA64\"])\n\nconst getPosixHomeDir = (): string => {\n if (!process.env.HOME) {\n throw new Error(\"Home directory not found\")\n }\n\n return process.env.HOME\n}\n\nconst getDeviceIdFilePath = (): string => {\n let folder: string\n\n switch (process.platform) {\n case \"darwin\": {\n folder = path.posix.join(\n getPosixHomeDir(),\n \"Library\",\n \"Application Support\",\n )\n break\n }\n case \"linux\": {\n folder =\n process.env.XDG_CACHE_HOME\n ?? path.posix.join(getPosixHomeDir(), \".cache\")\n break\n }\n default: {\n throw new Error(\"Unsupported platform\")\n }\n }\n\n return path.posix.join(folder, \"Microsoft\", \"DeveloperTools\", \"deviceid\")\n}\n\nconst isMissingFileError = (error: unknown): error is NodeJS.ErrnoException => {\n return error instanceof Error && \"code\" in error && error.code === \"ENOENT\"\n}\n\nconst readStoredDeviceIdFile = async (\n filePath: string,\n): Promise<string | undefined> => {\n const { readFile } = await import(\"node:fs/promises\")\n\n try {\n return await readFile(filePath, \"utf8\")\n } catch (error) {\n if (isMissingFileError(error)) {\n return undefined\n }\n\n throw error\n }\n}\n\nconst writeStoredDeviceIdFile = async (\n filePath: string,\n deviceId: string,\n): Promise<void> => {\n const { mkdir, writeFile } = await import(\"node:fs/promises\")\n\n await mkdir(path.posix.dirname(filePath), { recursive: true })\n await writeFile(filePath, deviceId, \"utf8\")\n}\n\nconst getWindowsRegistryArch = (): RegistryArch | undefined => {\n const architecture = (\n process.env.PROCESSOR_ARCHITEW6432 ?? process.env.PROCESSOR_ARCHITECTURE\n )?.toUpperCase()\n\n return architecture && windows64Architectures.has(architecture) ?\n \"x64\"\n : undefined\n}\n\nconst loadWinreg = async (): Promise<WinregConstructor> => {\n const module = await import(\"winreg\")\n const winreg =\n \"default\" in module ? (module.default as unknown) : (module as unknown)\n\n return winreg as WinregConstructor\n}\n\nconst isMissingRegistryError = (error: RegistryError | null): boolean => {\n if (!error) {\n return false\n }\n\n const errorCode = Number(error.code)\n\n return Number.isFinite(errorCode) && errorCode === 1\n}\n\nconst createWindowsRegistry = async (): Promise<{\n registry: WinregRegistry\n regSz: string\n}> => {\n const Winreg = await loadWinreg()\n\n return {\n registry: new Winreg({\n hive: Winreg.HKCU,\n key: WINDOWS_DEVICE_ID_KEY,\n arch: getWindowsRegistryArch(),\n }),\n regSz: Winreg.REG_SZ,\n }\n}\n\nconst readRegistryString = async (\n registry: WinregRegistry,\n name: string,\n): Promise<string | undefined> => {\n return new Promise((resolve, reject) => {\n registry.get(name, (error, item) => {\n if (isMissingRegistryError(error)) {\n resolve(undefined)\n return\n }\n\n if (error) {\n reject(\n error instanceof Error ? error : new Error(\"Unknown registry error\"),\n )\n return\n }\n\n resolve(item?.value)\n })\n })\n}\n\nconst writeRegistryString = async ({\n registry,\n regSz,\n name,\n value,\n}: {\n registry: WinregRegistry\n regSz: string\n name: string\n value: string\n}): Promise<void> => {\n return new Promise((resolve, reject) => {\n registry.set(name, regSz, value, (error) => {\n if (error) {\n reject(\n error instanceof Error ? error : new Error(\"Unknown registry error\"),\n )\n return\n }\n\n resolve()\n })\n })\n}\n\nexport const getStoredVSCodeDeviceId = async (): Promise<\n string | undefined\n> => {\n switch (process.platform) {\n case \"win32\": {\n const { registry } = await createWindowsRegistry()\n\n return readRegistryString(registry, WINDOWS_DEVICE_ID_NAME)\n }\n case \"darwin\":\n case \"linux\": {\n return readStoredDeviceIdFile(getDeviceIdFilePath())\n }\n default: {\n throw new Error(\"Unsupported platform\")\n }\n }\n}\n\nconst setStoredVSCodeDeviceId = async (deviceId: string): Promise<void> => {\n switch (process.platform) {\n case \"win32\": {\n const { registry, regSz } = await createWindowsRegistry()\n\n await writeRegistryString({\n registry,\n regSz,\n name: WINDOWS_DEVICE_ID_NAME,\n value: deviceId,\n })\n return\n }\n case \"darwin\":\n case \"linux\": {\n await writeStoredDeviceIdFile(getDeviceIdFilePath(), deviceId)\n return\n }\n default: {\n throw new Error(\"Unsupported platform\")\n }\n }\n}\n\nconst createVSCodeDeviceId = (): string => randomUUID().toLowerCase()\n\nexport async function getVSCodeDeviceId(): Promise<string> {\n let deviceId: string | undefined\n\n try {\n deviceId = await getStoredVSCodeDeviceId()\n } catch (error) {\n consola.debug(\"Failed to read VSCode device id\", error)\n }\n\n if (deviceId) {\n return deviceId\n }\n\n const newDeviceId = createVSCodeDeviceId()\n\n try {\n await setStoredVSCodeDeviceId(newDeviceId)\n } catch (error) {\n consola.warn(\n \"Failed to persist VSCode device id, using ephemeral id\",\n error,\n )\n }\n\n return newDeviceId\n}\n","const FALLBACK = \"1.140.0\"\n\nexport async function getVSCodeVersion() {\n await Promise.resolve()\n return FALLBACK\n}\n","import consola from \"consola\"\nimport { createHash, randomUUID } from \"node:crypto\"\nimport { networkInterfaces } from \"node:os\"\n\nimport { getVSCodeDeviceId } from \"~/lib/deviceid\"\nimport { state } from \"~/lib/state\"\nimport { getVSCodeVersion } from \"~/services/get-vscode-version\"\n\nexport const cacheVSCodeVersion = async () => {\n const response = await getVSCodeVersion()\n state.vsCodeVersion = response\n\n consola.info(`Using VSCode version: ${response}`)\n}\n\nconst invalidMacAddresses = new Set([\n \"00:00:00:00:00:00\",\n \"ff:ff:ff:ff:ff:ff\",\n \"ac:de:48:00:11:22\",\n])\n\nfunction validateMacAddress(candidate: string): boolean {\n const tempCandidate = candidate.replaceAll(\"-\", \":\").toLowerCase()\n return !invalidMacAddresses.has(tempCandidate)\n}\n\nexport function getMac(): string | null {\n const ifaces = networkInterfaces()\n // eslint-disable-next-line guard-for-in\n for (const name in ifaces) {\n const networkInterface = ifaces[name]\n if (networkInterface) {\n for (const { mac } of networkInterface) {\n if (validateMacAddress(mac)) {\n return mac\n }\n }\n }\n }\n return null\n}\n\nexport const cacheMacMachineId = () => {\n const macAddress = getMac() ?? randomUUID()\n state.macMachineId = createHash(\"sha256\")\n .update(macAddress, \"utf8\")\n .digest(\"hex\")\n consola.debug(`Using machine ID: ${state.macMachineId}`)\n}\n\nexport const cacheVsCodeDeviceId = async () => {\n state.vsCodeDeviceId = await getVSCodeDeviceId()\n consola.debug(`Using VSCode device ID: ${state.vsCodeDeviceId}`)\n}\n\nconst SESSION_REFRESH_BASE_MS = 60 * 60 * 1000\nconst SESSION_REFRESH_JITTER_MS = 20 * 60 * 1000\nlet vsCodeSessionRefreshTimer: ReturnType<typeof setTimeout> | null = null\n\nconst generateSessionId = () => {\n state.vsCodeSessionId = randomUUID() + Date.now().toString()\n consola.debug(`Generated VSCode session ID: ${state.vsCodeSessionId}`)\n}\n\nexport const stopVsCodeSessionRefreshLoop = () => {\n if (vsCodeSessionRefreshTimer) {\n clearTimeout(vsCodeSessionRefreshTimer)\n vsCodeSessionRefreshTimer = null\n }\n}\n\nconst scheduleSessionIdRefresh = () => {\n const randomDelay = Math.floor(Math.random() * SESSION_REFRESH_JITTER_MS)\n const delay = SESSION_REFRESH_BASE_MS + randomDelay\n consola.debug(\n `Scheduling next VSCode session ID refresh in ${Math.round(\n delay / 1000,\n )} seconds`,\n )\n\n stopVsCodeSessionRefreshLoop()\n vsCodeSessionRefreshTimer = setTimeout(() => {\n try {\n generateSessionId()\n } catch (error) {\n consola.error(\"Failed to refresh session ID, rescheduling...\", error)\n } finally {\n scheduleSessionIdRefresh()\n }\n }, delay)\n}\n\nexport const cacheVsCodeSessionId = () => {\n stopVsCodeSessionRefreshLoop()\n generateSessionId()\n scheduleSessionIdRefresh()\n}\n","import { state } from \"~/lib/state\"\nimport { logUser, setupCopilotToken } from \"~/lib/token\"\nimport { cacheModels } from \"~/services/copilot/models-cache\"\nimport {\n cacheMacMachineId,\n cacheVSCodeVersion,\n cacheVsCodeSessionId,\n cacheVsCodeDeviceId,\n} from \"~/services/vscode-env\"\n\nexport async function setupCopilotRuntime(githubToken: string): Promise<void> {\n state.githubToken = githubToken\n await logUser()\n await cacheVSCodeVersion()\n cacheMacMachineId()\n cacheVsCodeSessionId()\n await cacheVsCodeDeviceId()\n await setupCopilotToken()\n await cacheModels()\n}\n"],"mappings":";;;;;;;AAQA,MAAa,YAAY,YAAY;CACnC,QAAQ,KAAK,wBAAwB,eAAe,KAAK,EAAE,QAAQ;CACnE,MAAM,WAAW,MAAM,MAAM,GAAG,eAAe,KAAK,EAAE,UAAU,EAC9D,SAAS,qBAAqB,KAAK,EACrC,CAAC;CAED,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,YAAY,MAAM,SAAS,MAAM,CAAC,CAAC,KAAK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;CACxC,6BAA6B;CAC7B,kBAAkB;CAClB,yBAAyB;AAC3B;;;ACtFA,eAAsB,oBAAoB,aAAoC;CAC5E,MAAM,cAAc;CACpB,MAAM,QAAQ;CACd,MAAM,mBAAmB;CACzB,kBAAkB;CAClB,qBAAqB;CACrB,MAAM,oBAAoB;CAC1B,MAAM,kBAAkB;CACxB,MAAM,YAAY;AACpB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as listEnabledProviders, n as getRawProviderConfig } from "./config-
|
|
1
|
+
import { S as PATHS } from "./config-store-C6GAtKLz.js";
|
|
2
|
+
import { i as listEnabledProviders, n as getRawProviderConfig } from "./config-Cd0U5gXz.js";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import consola from "consola";
|
|
5
5
|
import fs from "node:fs/promises";
|
|
@@ -90,4 +90,4 @@ const debug = defineCommand({
|
|
|
90
90
|
//#endregion
|
|
91
91
|
export { debug };
|
|
92
92
|
|
|
93
|
-
//# sourceMappingURL=debug-
|
|
93
|
+
//# sourceMappingURL=debug-CmL-V7Ov.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-
|
|
1
|
+
{"version":3,"file":"debug-CmL-V7Ov.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { getRawProviderConfig, listEnabledProviders } from \"./lib/config\"\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n providers: {\n codexConfigured: boolean\n enabled: Array<string>\n }\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n CONFIG_PATH: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = fileURLToPath(\n new URL(\"../package.json\", import.meta.url),\n )\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkFileExists(filePath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(filePath)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(filePath, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkFileExists(PATHS.GITHUB_TOKEN_PATH),\n ])\n\n return {\n providers: {\n codexConfigured: getRawProviderConfig(\"codex\") !== null,\n enabled: listEnabledProviders(),\n },\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n CONFIG_PATH: PATHS.CONFIG_PATH,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`copilot-api debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nProviders:\n- enabled: ${info.providers.enabled.join(\", \") || \"none\"}\n- codex configured: ${info.providers.codexConfigured ? \"Yes\" : \"No\"}\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- CONFIG_PATH: ${info.paths.CONFIG_PATH}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nGitHub token exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;;;AAmCA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,cACtB,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAC5C;EAMA,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,eAAe,CAG/C,CAAC,CAAC;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,CAAC;EACtD,UAAU,GAAG,SAAS;EACtB,MAAM,GAAG,KAAK;CAChB;AACF;AAEA,eAAe,gBAAgB,UAAoC;CACjE,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,QAAQ,EAAA,CACzB,OAAO,GAAG,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,UAAU,MAAM,EAAA,CACnC,KAAK,CAAC,CAAC,SAAS;CACjC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,kBAAkB,GAClB,gBAAgB,MAAM,iBAAiB,CACzC,CAAC;CAED,OAAO;EACL,WAAW;GACT,iBAAiB,qBAAqB,OAAO,MAAM;GACnD,SAAS,qBAAqB;EAChC;EACA;EACA,SAAS,eAAe;EACxB,OAAO;GACL,SAAS,MAAM;GACf,aAAa,MAAM;GACnB,mBAAmB,MAAM;EAC3B;EACA;CACF;AACF;AAEA,SAAS,oBAAoB,MAAuB;CAClD,QAAQ,KAAK;;WAEJ,KAAK,QAAQ;WACb,KAAK,QAAQ,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,QAAQ,KAAK;;;aAGvF,KAAK,UAAU,QAAQ,KAAK,IAAI,KAAK,OAAO;sBACnC,KAAK,UAAU,kBAAkB,QAAQ,KAAK;;;aAGvD,KAAK,MAAM,QAAQ;iBACf,KAAK,MAAM,YAAY;uBACjB,KAAK,MAAM,kBAAkB;;uBAE7B,KAAK,cAAc,QAAQ,MAAM;AACxD;AAEA,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAC3C;AAEA,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,aAAa;CAErC,IAAI,QAAQ,MACV,mBAAmB,SAAS;MAE5B,oBAAoB,SAAS;AAEjC;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
|
package/dist/main.js
CHANGED
|
@@ -27,11 +27,11 @@ if (isMcpFastPath(process.argv)) {
|
|
|
27
27
|
if (process.platform === "win32" && process.stdout.isTTY && !process.env.WT_SESSION) process.env.WT_SESSION = "copilot-api";
|
|
28
28
|
const { bindElectronFetch } = await import("./electron-fetch-DsMaRX6v.js");
|
|
29
29
|
bindElectronFetch();
|
|
30
|
-
const { auth } = await import("./auth-
|
|
31
|
-
const { debug } = await import("./debug-
|
|
30
|
+
const { auth } = await import("./auth-BzYvzeW0.js");
|
|
31
|
+
const { debug } = await import("./debug-CmL-V7Ov.js");
|
|
32
32
|
const { mcp } = await import("./mcp-Dd_hxxuG.js");
|
|
33
|
-
const { start } = await import("./start-
|
|
34
|
-
const { provider } = await import("./provider-
|
|
33
|
+
const { start } = await import("./start-y2hlYweN.js");
|
|
34
|
+
const { provider } = await import("./provider-CzziTLqX.js");
|
|
35
35
|
await runMain(defineCommand({
|
|
36
36
|
meta: {
|
|
37
37
|
name: "copilot-api",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as saveProviderManagementConfig } from "./provider-management-
|
|
1
|
+
import { r as saveProviderManagementConfig } from "./provider-management-DOfLC7WX.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
//#region src/provider.ts
|
|
4
4
|
function providerStateCommand(enabled) {
|
|
@@ -33,4 +33,4 @@ const provider = defineCommand({
|
|
|
33
33
|
//#endregion
|
|
34
34
|
export { provider };
|
|
35
35
|
|
|
36
|
-
//# sourceMappingURL=provider-
|
|
36
|
+
//# sourceMappingURL=provider-CzziTLqX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-
|
|
1
|
+
{"version":3,"file":"provider-CzziTLqX.js","names":[],"sources":["../src/provider.ts"],"sourcesContent":["import { defineCommand } from \"citty\"\n\nimport { saveProviderManagementConfig } from \"./lib/provider-management\"\n\nfunction providerStateCommand(enabled: boolean) {\n return defineCommand({\n meta: {\n description: `${enabled ? \"Enable\" : \"Disable\"} a configured provider`,\n },\n args: {\n name: {\n type: \"positional\",\n required: true,\n description: \"Provider name\",\n },\n },\n run({ args }) {\n try {\n saveProviderManagementConfig({\n providers: { [args.name]: { enabled } },\n })\n process.stdout.write(\n `Provider '${args.name}' ${enabled ? \"enabled\" : \"disabled\"}. Restart the running server to apply the change.\\n`,\n )\n } catch (error) {\n process.stderr.write(\n `${error instanceof Error ? error.message : String(error)}\\n`,\n )\n process.exitCode = 1\n }\n },\n })\n}\n\nexport const provider = defineCommand({\n meta: { name: \"provider\", description: \"Manage configured providers\" },\n subCommands: {\n enable: providerStateCommand(true),\n disable: providerStateCommand(false),\n },\n})\n"],"mappings":";;;AAIA,SAAS,qBAAqB,SAAkB;CAC9C,OAAO,cAAc;EACnB,MAAM,EACJ,aAAa,GAAG,UAAU,WAAW,UAAU,wBACjD;EACA,MAAM,EACJ,MAAM;GACJ,MAAM;GACN,UAAU;GACV,aAAa;EACf,EACF;EACA,IAAI,EAAE,QAAQ;GACZ,IAAI;IACF,6BAA6B,EAC3B,WAAW,GAAG,KAAK,OAAO,EAAE,QAAQ,EAAE,EACxC,CAAC;IACD,QAAQ,OAAO,MACb,aAAa,KAAK,KAAK,IAAI,UAAU,YAAY,WAAW,oDAC9D;GACF,SAAS,OAAO;IACd,QAAQ,OAAO,MACb,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAC5D;IACA,QAAQ,WAAW;GACrB;EACF;CACF,CAAC;AACH;AAEA,MAAa,WAAW,cAAc;CACpC,MAAM;EAAE,MAAM;EAAY,aAAa;CAA8B;CACrE,aAAa;EACX,QAAQ,qBAAqB,IAAI;EACjC,SAAS,qBAAqB,KAAK;CACrC;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as PATHS, f as invalidateConfigCache, v as readEditableConfigFromDisk, w as GITHUB_COPILOT_PROVIDER, x as writeConfigToDisk } from "./config-store-C6GAtKLz.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
//#region src/lib/provider-management.ts
|
|
4
4
|
const updateSchema = z.object({ providers: z.record(z.string(), z.object({
|
|
@@ -57,4 +57,4 @@ function saveProviderManagementConfig(input) {
|
|
|
57
57
|
//#endregion
|
|
58
58
|
export { isProviderAgentModelVisible as n, saveProviderManagementConfig as r, getProviderAgentModels as t };
|
|
59
59
|
|
|
60
|
-
//# sourceMappingURL=provider-management-
|
|
60
|
+
//# sourceMappingURL=provider-management-DOfLC7WX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-management-
|
|
1
|
+
{"version":3,"file":"provider-management-DOfLC7WX.js","names":[],"sources":["../src/lib/provider-management.ts"],"sourcesContent":["import { z } from \"zod\"\n\nimport { GITHUB_COPILOT_PROVIDER } from \"./github-copilot-provider\"\n\nimport {\n invalidateConfigCache,\n readEditableConfigFromDisk,\n writeConfigToDisk,\n type AppConfig,\n type ProviderConfig,\n} from \"./config-store\"\nimport { PATHS } from \"./paths\"\nimport type { ProviderManagementConfig } from \"./types/provider-management\"\nexport type {\n ProviderManagementConfig,\n ProviderManagementUpdate,\n} from \"./types/provider-management\"\n\nconst updateSchema = z\n .object({\n providers: z\n .record(\n z.string(),\n z\n .object({\n enabled: z.boolean().optional(),\n agentsModels: z\n .array(z.string().trim().min(1))\n .nullable()\n .optional(),\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n\nexport function getProviderAgentModels(\n provider: ProviderConfig | null | undefined,\n): Array<string> | undefined {\n const models = provider?.agentsModels\n if (!Array.isArray(models) || !models.every((id) => typeof id === \"string\")) {\n return undefined\n }\n return [...new Set(models.map((id) => id.trim()).filter(Boolean))]\n}\n\nexport function isProviderAgentModelVisible(\n provider: ProviderConfig | null | undefined,\n modelId: string,\n): boolean {\n if (provider?.enabled === false) return false\n const models = getProviderAgentModels(provider)\n return models === undefined || models.includes(modelId)\n}\n\nexport function getProviderManagementConfig(\n config: AppConfig = readEditableConfigFromDisk(),\n): ProviderManagementConfig {\n const providers: NonNullable<AppConfig[\"providers\"]> = {\n [GITHUB_COPILOT_PROVIDER]: {},\n ...config.providers,\n }\n return {\n configPath: PATHS.CONFIG_PATH,\n providers: Object.entries(providers)\n .filter(([name]) => name !== \"copilot\")\n .map(([name, provider]) => ({\n name,\n type:\n name === GITHUB_COPILOT_PROVIDER ? \"github-copilot\" : (\n (provider.type ?? \"anthropic\")\n ),\n enabled: provider.enabled !== false,\n agentsModels: getProviderAgentModels(provider),\n })),\n }\n}\n\nexport function applyProviderManagementUpdate(\n config: AppConfig,\n input: unknown,\n): AppConfig {\n const parsed = updateSchema.safeParse(input)\n if (!parsed.success) {\n throw new Error(\n parsed.error.issues[0]?.message ?? \"Invalid provider update\",\n )\n }\n const { providers: updates } = parsed.data\n const providers = { ...config.providers }\n for (const [name, update] of Object.entries(updates ?? {})) {\n if (\n name === \"copilot\"\n || (name !== GITHUB_COPILOT_PROVIDER && !Object.hasOwn(providers, name))\n ) {\n throw new Error(`Provider '${name}' is not configured`)\n }\n const provider = { ...providers[name] }\n if (update.enabled !== undefined) provider.enabled = update.enabled\n if (update.agentsModels === null) {\n delete provider.agentsModels\n } else if (update.agentsModels !== undefined) {\n provider.agentsModels = [...new Set(update.agentsModels)]\n }\n providers[name] = provider\n }\n return {\n ...config,\n ...(updates !== undefined ? { providers } : {}),\n }\n}\n\nexport function saveProviderManagementConfig(\n input: unknown,\n): ProviderManagementConfig {\n const updated = applyProviderManagementUpdate(\n readEditableConfigFromDisk(),\n input,\n )\n writeConfigToDisk(updated)\n invalidateConfigCache()\n return getProviderManagementConfig(updated)\n}\n"],"mappings":";;;AAkBA,MAAM,eAAe,EAClB,OAAO,EACN,WAAW,EACR,OACC,EAAE,OAAO,GACT,EACG,OAAO;CACN,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC9B,cAAc,EACX,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAC/B,SAAS,CAAC,CACV,SAAS;AACd,CAAC,CAAC,CACD,OAAO,CACZ,CAAC,CACA,SAAS,EACd,CAAC,CAAC,CACD,OAAO;AAEV,SAAgB,uBACd,UAC2B;CAC3B,MAAM,SAAS,UAAU;CACzB,IAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,CAAC,OAAO,OAAO,OAAO,OAAO,OAAO,QAAQ,GACxE;CAEF,OAAO,CAAC,GAAG,I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,GAAG,IAAI,IAAI,OAAO,YAAY,CAAC;EAE1D,UAAU,QAAQ;CACpB;CACA,OAAO;EACL,GAAG;EACH,GAAI,YAAY,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;CAC/C;AACF;AAEA,SAAgB,6BACd,OAC0B;CAC1B,MAAM,UAAU,8BACd,2BAA2B,GAC3B,KACF;CACA,kBAAkB,OAAO;CACzB,sBAAsB;CACtB,OAAO,4BAA4B,OAAO;AAC5C"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { C as
|
|
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-
|
|
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
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-
|
|
6
|
-
import { n as stopModelsRefreshLoop, t as setupCopilotRuntime } from "./copilot-runtime-
|
|
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";
|
|
7
7
|
import consola from "consola";
|
|
8
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
9
9
|
import fs, { createWriteStream, readFileSync, rmSync } from "node:fs";
|
|
@@ -638,6 +638,7 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
638
638
|
},
|
|
639
639
|
"deepseek-v4.1-flash": {
|
|
640
640
|
contextWindow: 1e6,
|
|
641
|
+
defaultReasoningEffort: "high",
|
|
641
642
|
inputModalities: ["text", "image"],
|
|
642
643
|
maxOutputTokens: 393216,
|
|
643
644
|
pricing: {
|
|
@@ -650,10 +651,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
650
651
|
},
|
|
651
652
|
output: 8,
|
|
652
653
|
peakWindows: dashscopePeakWindows
|
|
653
|
-
}
|
|
654
|
+
},
|
|
655
|
+
reasoningEfforts: [
|
|
656
|
+
"low",
|
|
657
|
+
"high",
|
|
658
|
+
"max"
|
|
659
|
+
]
|
|
654
660
|
},
|
|
655
661
|
"qwen3.8-max": {
|
|
656
662
|
contextWindow: 1e6,
|
|
663
|
+
defaultReasoningEffort: "xhigh",
|
|
657
664
|
inputModalities: ["text", "image"],
|
|
658
665
|
maxOutputTokens: 64e3,
|
|
659
666
|
pricing: {
|
|
@@ -662,10 +669,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
662
669
|
explicitCachedInput: 1,
|
|
663
670
|
input: 12,
|
|
664
671
|
output: 36
|
|
665
|
-
}
|
|
672
|
+
},
|
|
673
|
+
reasoningEfforts: [
|
|
674
|
+
"low",
|
|
675
|
+
"medium",
|
|
676
|
+
"xhigh"
|
|
677
|
+
]
|
|
666
678
|
},
|
|
667
679
|
"qwen3.8-max-0902": {
|
|
668
680
|
contextWindow: 1e6,
|
|
681
|
+
defaultReasoningEffort: "xhigh",
|
|
669
682
|
inputModalities: ["text", "image"],
|
|
670
683
|
maxOutputTokens: 131072,
|
|
671
684
|
pricing: {
|
|
@@ -674,10 +687,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
674
687
|
explicitCachedInput: 1,
|
|
675
688
|
input: 12,
|
|
676
689
|
output: 36
|
|
677
|
-
}
|
|
690
|
+
},
|
|
691
|
+
reasoningEfforts: [
|
|
692
|
+
"low",
|
|
693
|
+
"medium",
|
|
694
|
+
"xhigh"
|
|
695
|
+
]
|
|
678
696
|
},
|
|
679
697
|
"qwen3.8-flash": {
|
|
680
698
|
contextWindow: 1e6,
|
|
699
|
+
defaultReasoningEffort: "xhigh",
|
|
681
700
|
inputModalities: ["text", "image"],
|
|
682
701
|
maxOutputTokens: 131072,
|
|
683
702
|
pricing: {
|
|
@@ -686,10 +705,16 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
686
705
|
explicitCachedInput: .1,
|
|
687
706
|
input: .8,
|
|
688
707
|
output: 2.7
|
|
689
|
-
}
|
|
708
|
+
},
|
|
709
|
+
reasoningEfforts: [
|
|
710
|
+
"low",
|
|
711
|
+
"medium",
|
|
712
|
+
"xhigh"
|
|
713
|
+
]
|
|
690
714
|
},
|
|
691
715
|
"qwen3.7-plus": {
|
|
692
716
|
contextWindow: 1e6,
|
|
717
|
+
defaultReasoningEffort: "xhigh",
|
|
693
718
|
inputModalities: ["text", "image"],
|
|
694
719
|
maxOutputTokens: 64e3,
|
|
695
720
|
pricing: { tiers: [{
|
|
@@ -706,17 +731,24 @@ const builtinProviderModelRegistry = new class BuiltinProviderModelRegistry {
|
|
|
706
731
|
input: 6,
|
|
707
732
|
maxInputTokens: 1e6,
|
|
708
733
|
output: 24
|
|
709
|
-
}] }
|
|
734
|
+
}] },
|
|
735
|
+
reasoningEfforts: [
|
|
736
|
+
"low",
|
|
737
|
+
"medium",
|
|
738
|
+
"xhigh"
|
|
739
|
+
]
|
|
710
740
|
},
|
|
711
741
|
"kimi/kimi-k3": {
|
|
712
742
|
contextWindow: 1048576,
|
|
743
|
+
defaultReasoningEffort: "max",
|
|
713
744
|
inputModalities: ["text", "image"],
|
|
714
745
|
maxOutputTokens: 64e3,
|
|
715
746
|
pricing: {
|
|
716
747
|
cachedInput: 2,
|
|
717
748
|
input: 20,
|
|
718
749
|
output: 100
|
|
719
|
-
}
|
|
750
|
+
},
|
|
751
|
+
reasoningEfforts: ["max"]
|
|
720
752
|
},
|
|
721
753
|
"ZHIPU/GLM-5.3": {
|
|
722
754
|
contextWindow: 1048576,
|
|
@@ -9401,6 +9433,17 @@ function getStringField(model, field) {
|
|
|
9401
9433
|
const value = model[field];
|
|
9402
9434
|
return typeof value === "string" && value.trim() ? value : void 0;
|
|
9403
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
|
+
}
|
|
9404
9447
|
function getFallbackProviderModelRecords(provider, reason, details = {}) {
|
|
9405
9448
|
const fallbackModels = getBuiltinProviderModelRecords(provider);
|
|
9406
9449
|
logger$9.warn(`models.provider.fallback_${reason}`, {
|
|
@@ -9485,31 +9528,34 @@ async function getAggregatedModels(requestHeaders, selectors = {}) {
|
|
|
9485
9528
|
const providerModelsByProvider = await Promise.all(listEnabledProviders().map((provider) => getProviderModels(provider, requestHeaders, selectors.selectProviderModels)));
|
|
9486
9529
|
return deduplicateModels([...copilotModels, ...providerModelsByProvider.flat()], (model) => model.id);
|
|
9487
9530
|
}
|
|
9488
|
-
function
|
|
9489
|
-
return c.json({
|
|
9490
|
-
object: "list",
|
|
9491
|
-
data: models,
|
|
9492
|
-
has_more: false
|
|
9493
|
-
});
|
|
9494
|
-
}
|
|
9495
|
-
//#endregion
|
|
9496
|
-
//#region src/routes/models/claude-models.ts
|
|
9497
|
-
function selectClaudeCopilotModels(models) {
|
|
9531
|
+
function selectAgentCopilotModels(models) {
|
|
9498
9532
|
const selection = getProviderAgentModels(getRawProviderConfig(GITHUB_COPILOT_PROVIDER));
|
|
9499
9533
|
if (selection === void 0) return models;
|
|
9500
9534
|
return models.filter((model) => selection.includes(model.id) || selection.includes(toClientModelId(model.id)));
|
|
9501
9535
|
}
|
|
9502
|
-
function
|
|
9536
|
+
function selectAgentProviderModels(providerConfig, models) {
|
|
9503
9537
|
const selection = getProviderAgentModels(providerConfig);
|
|
9504
9538
|
if (selection === void 0) return models;
|
|
9505
9539
|
const modelsById = getModelsById(models);
|
|
9506
9540
|
return selection.map((id) => modelsById.get(id) ?? { id });
|
|
9507
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
|
|
9508
9557
|
async function handleClaudeModels(c) {
|
|
9509
|
-
return createModelListResponse(c, (await
|
|
9510
|
-
selectCopilotModels: selectClaudeCopilotModels,
|
|
9511
|
-
selectProviderModels: selectClaudeProviderModels
|
|
9512
|
-
})).map((model) => ({
|
|
9558
|
+
return createModelListResponse(c, (await getAgentModels(stripInternalRequestHeaders(c.req.raw.headers))).map((model) => ({
|
|
9513
9559
|
...model,
|
|
9514
9560
|
id: toClaudeDiscoveryModelId(model.id),
|
|
9515
9561
|
...typeof model.claude_model_id === "string" ? { claude_model_id: toClaudeDiscoveryModelId(model.claude_model_id) } : {}
|
|
@@ -9731,17 +9777,6 @@ function selectDefaultReasoningEffort(efforts, configured) {
|
|
|
9731
9777
|
function positiveNumber(value, fallback) {
|
|
9732
9778
|
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
|
|
9733
9779
|
}
|
|
9734
|
-
function getRecordField(model, field) {
|
|
9735
|
-
const value = model?.[field];
|
|
9736
|
-
return isRecord(value) ? value : void 0;
|
|
9737
|
-
}
|
|
9738
|
-
function getFirstPositiveNumber(model, fields) {
|
|
9739
|
-
if (!model) return void 0;
|
|
9740
|
-
for (const field of fields) {
|
|
9741
|
-
const value = model[field];
|
|
9742
|
-
if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
|
|
9743
|
-
}
|
|
9744
|
-
}
|
|
9745
9780
|
//#endregion
|
|
9746
9781
|
//#region src/routes/models/models.json
|
|
9747
9782
|
var models = [
|
|
@@ -11522,11 +11557,159 @@ async function handleDefaultModels(c) {
|
|
|
11522
11557
|
return createModelListResponse(c, await getAggregatedModels(stripInternalRequestHeaders(c.req.raw.headers)));
|
|
11523
11558
|
}
|
|
11524
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
|
|
11525
11707
|
//#region src/routes/models/route.ts
|
|
11526
11708
|
const modelRoutes = new Hono();
|
|
11527
11709
|
modelRoutes.get("/", async (c) => {
|
|
11528
11710
|
try {
|
|
11529
11711
|
const userAgent = c.req.header("user-agent");
|
|
11712
|
+
if (isOpencodeUserAgent(userAgent)) return await handleOpencodeModels(c);
|
|
11530
11713
|
if (isCodexUserAgent(userAgent)) return await handleCodexModels(c);
|
|
11531
11714
|
if (isClaudeUserAgent(userAgent)) return await handleClaudeModels(c);
|
|
11532
11715
|
return await handleDefaultModels(c);
|
|
@@ -13187,4 +13370,4 @@ createServer();
|
|
|
13187
13370
|
//#endregion
|
|
13188
13371
|
export { createServer };
|
|
13189
13372
|
|
|
13190
|
-
//# sourceMappingURL=server-
|
|
13373
|
+
//# sourceMappingURL=server-CClOz6YS.js.map
|