@jeffreycao/copilot-api 2.7.18 → 2.7.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/dist/main.js +1 -1
- package/dist/{server-D8LzQcmu.js → server-DneVQ_F8.js} +53 -33
- package/dist/server-DneVQ_F8.js.map +1 -0
- package/dist/{start-Xf1MJrNI.js → start-BiKN2HN7.js} +2 -2
- package/dist/{start-Xf1MJrNI.js.map → start-BiKN2HN7.js.map} +1 -1
- package/package.json +1 -1
- package/pages/index.html +189 -19
- package/dist/server-D8LzQcmu.js.map +0 -1
|
@@ -181,7 +181,7 @@ async function runServer(options) {
|
|
|
181
181
|
if (resolvedGitHubToken && isGitHubCopilotEnabled()) await setupCopilotMode(resolvedGitHubToken.token, resolvedGitHubToken.source);
|
|
182
182
|
else await setupProviderMode();
|
|
183
183
|
consola.box(`🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`);
|
|
184
|
-
const { createServer } = await import("./server-
|
|
184
|
+
const { createServer } = await import("./server-DneVQ_F8.js");
|
|
185
185
|
const server = createServer({ networkExposed: binding.networkExposed });
|
|
186
186
|
serve({
|
|
187
187
|
fetch: server.fetch,
|
|
@@ -243,4 +243,4 @@ const start = defineCommand({
|
|
|
243
243
|
//#endregion
|
|
244
244
|
export { start };
|
|
245
245
|
|
|
246
|
-
//# sourceMappingURL=start-
|
|
246
|
+
//# sourceMappingURL=start-BiKN2HN7.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-Xf1MJrNI.js","names":["get"],"sources":["../src/lib/proxy.ts","../src/lib/server-host-shared.ts","../src/lib/server-host.ts","../src/start.ts"],"sourcesContent":["import consola from \"consola\"\nimport { getProxyForUrl } from \"proxy-from-env\"\nimport { Agent, ProxyAgent, setGlobalDispatcher, type Dispatcher } from \"undici\"\n\nlet proxyEnvDispatcher: Dispatcher | undefined\n\nexport function getProxyEnvDispatcher(): Dispatcher | undefined {\n return proxyEnvDispatcher\n}\n\nexport function initProxyFromEnv(): void {\n try {\n const direct = new Agent()\n const proxies = new Map<string, ProxyAgent>()\n\n // We only need a minimal dispatcher that implements `dispatch` at runtime.\n // Typing the object as `Dispatcher` forces TypeScript to require many\n // additional methods. Instead, keep a plain object and cast when passing\n // to `setGlobalDispatcher`.\n const dispatcher = {\n dispatch(\n options: Dispatcher.DispatchOptions,\n handler: Dispatcher.DispatchHandler,\n ) {\n try {\n const origin =\n typeof options.origin === \"string\" ?\n new URL(options.origin)\n : (options.origin as URL)\n const get = getProxyForUrl as unknown as (\n u: string,\n ) => string | undefined\n const raw = get(origin.toString())\n const proxyUrl = raw && raw.length > 0 ? raw : undefined\n if (!proxyUrl) {\n consola.debug(`HTTP proxy bypass: ${origin.hostname}`)\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n let agent = proxies.get(proxyUrl)\n if (!agent) {\n agent = new ProxyAgent(proxyUrl)\n proxies.set(proxyUrl, agent)\n }\n let label = proxyUrl\n try {\n const u = new URL(proxyUrl)\n label = `${u.protocol}//${u.host}`\n } catch {\n /* noop */\n }\n consola.debug(`HTTP proxy route: ${origin.hostname} via ${label}`)\n return (agent as unknown as Dispatcher).dispatch(options, handler)\n } catch {\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n },\n close() {\n return direct.close()\n },\n destroy() {\n return direct.destroy()\n },\n }\n\n proxyEnvDispatcher = dispatcher as unknown as Dispatcher\n\n if (typeof Bun !== \"undefined\") {\n consola.debug(\"WebSocket proxy configured from environment (per-URL)\")\n return\n }\n\n setGlobalDispatcher(proxyEnvDispatcher)\n consola.debug(\"HTTP proxy configured from environment (per-URL)\")\n } catch (err) {\n consola.debug(\"Proxy setup skipped:\", err)\n }\n}\n","// Pure hostname helpers shared by the gateway server (Node) and the desktop\n// app (including the renderer bundle). This module must stay free of\n// `node:*` imports because the renderer cannot use `node:net`; all\n// address-family checks live in `server-host.ts`.\nexport const INVALID_HOST_CHARACTERS = /[\\s/?#]/\n\n// Bind hosts that listen on every interface, in normalized form (no\n// brackets, so \"[::]\" is covered via `stripIpv6Brackets`).\nexport const NORMALIZED_WILDCARD_HOSTS = new Set([\"0.0.0.0\", \"::\"])\n\nexport function stripIpv6Brackets(hostname: string): string {\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n return hostname.slice(1, -1)\n }\n return hostname\n}\n\nexport function normalizeHostnameBase(hostname: string): string {\n const normalized = stripIpv6Brackets(hostname.trim())\n if (!normalized || INVALID_HOST_CHARACTERS.test(normalized)) {\n throw new Error(`Invalid server host: ${JSON.stringify(hostname)}`)\n }\n return normalized\n}\n\nexport function isWildcardHostname(hostname: string): boolean {\n return NORMALIZED_WILDCARD_HOSTS.has(stripIpv6Brackets(hostname.trim()))\n}\n","import { isIP } from \"node:net\"\n\nimport { isWildcardHostname, normalizeHostnameBase } from \"./server-host-shared\"\n\nexport const DEFAULT_SERVER_HOST = \"127.0.0.1\"\n\n// Listen failures that mean the hostname itself cannot be bound, as opposed\n// to the port being occupied (EADDRINUSE) or forbidden (EACCES). ENOTFOUND\n// covers unresolvable names such as typos, EADDRNOTAVAIL covers valid IPs\n// that are not assigned to this machine.\nconst INVALID_BIND_ERROR_CODES = new Set([\n \"ENOTFOUND\",\n \"EADDRNOTAVAIL\",\n \"EINVAL\",\n \"EAFNOSUPPORT\",\n \"ENXIO\",\n])\n\nexport function isInvalidBindErrorCode(code?: string): boolean {\n return !!code && INVALID_BIND_ERROR_CODES.has(code)\n}\n\nexport interface ServerBinding {\n hostname: string\n clientHostname: string\n networkExposed: boolean\n}\n\nfunction isLoopbackIpv4(hostname: string): boolean {\n return isIP(hostname) === 4 && hostname.split(\".\", 1)[0] === \"127\"\n}\n\nfunction isLoopbackMappedIpv4(hostname: string): boolean {\n try {\n const canonicalHostname = new URL(`http://[${hostname}]/`).hostname.slice(\n 1,\n -1,\n )\n const mappedIpv4 = canonicalHostname.match(\n /^::ffff:([\\da-f]{1,4}):[\\da-f]{1,4}$/,\n )\n if (!mappedIpv4) {\n return false\n }\n\n return (Number.parseInt(mappedIpv4[1], 16) & 0xff00) === 0x7f00\n } catch {\n return false\n }\n}\n\nexport function normalizeServerHostname(hostname: string): string {\n return normalizeHostnameBase(hostname)\n}\n\nexport function isLoopbackHostname(hostname: string): boolean {\n const normalized = normalizeServerHostname(hostname).toLowerCase()\n if (normalized === \"localhost\" || normalized === \"localhost.\") {\n return true\n }\n if (isLoopbackIpv4(normalized)) {\n return true\n }\n if (isIP(normalized) !== 6) {\n return false\n }\n\n if (normalized === \"::1\" || normalized === \"0:0:0:0:0:0:0:1\") {\n return true\n }\n\n return isLoopbackMappedIpv4(normalized)\n}\n\nexport function resolveServerBinding(\n hostname: string,\n hasApiKeys: boolean,\n): ServerBinding {\n const normalizedHostname = normalizeServerHostname(hostname)\n const networkExposed = !isLoopbackHostname(normalizedHostname)\n\n if (networkExposed && !hasApiKeys) {\n throw new Error(\n `Refusing to listen on non-loopback host ${JSON.stringify(normalizedHostname)} without gateway API keys. Run \\`npx @jeffreycao/copilot-api@latest auth keys --add <key>\\` first, or use \\`--host ${DEFAULT_SERVER_HOST}\\`.`,\n )\n }\n\n return {\n hostname: normalizedHostname,\n clientHostname: resolveClientHostname(normalizedHostname),\n networkExposed,\n }\n}\n\nexport function resolveClientHostname(hostname: string): string {\n const normalizedHostname = normalizeServerHostname(hostname)\n // Wildcard binds listen on every interface, which clients cannot dial\n // directly (0.0.0.0 is not a routable destination).\n return isWildcardHostname(normalizedHostname) ? DEFAULT_SERVER_HOST : (\n normalizedHostname.toLowerCase()\n )\n}\n\nexport function resolveClientHostnameOrDefault(\n hostname: string | null | undefined,\n): string {\n const normalizedHostname = hostname?.trim()\n return normalizedHostname ?\n resolveClientHostname(normalizedHostname)\n : DEFAULT_SERVER_HOST\n}\n\nexport function formatServerUrl(hostname: string, port: number): string {\n const urlHostname =\n isIP(hostname) === 6 ? `[${hostname.replace(\"%\", \"%25\")}]` : hostname\n return `http://${urlHostname}:${port}`\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport { serve, type ServerHandler } from \"srvx\"\n\nimport { runProviderSetup } from \"./auth\"\nimport { isGitHubCopilotEnabled } from \"./lib/github-copilot-provider\"\nimport { listEnabledProviders, mergeConfigWithDefaults } from \"./lib/config\"\nimport { setupCopilotRuntime } from \"~/lib/copilot-runtime\"\nimport {\n GITHUB_TOKEN_ENV,\n readGitHubToken,\n readGitHubTokenFromEnv,\n} from \"./lib/credential-store\"\nimport { startModelsDevCache } from \"./lib/models-dev-cache\"\nimport { initOpencodeVersion } from \"./lib/opencode\"\nimport { ensurePaths } from \"./lib/paths\"\nimport { initProxyFromEnv } from \"./lib/proxy\"\nimport {\n getConfiguredApiKeys,\n getMissingApiKeysMessage,\n} from \"./lib/request-auth\"\nimport {\n DEFAULT_SERVER_HOST,\n formatServerUrl,\n resolveServerBinding,\n} from \"./lib/server-host\"\nimport { state } from \"./lib/state\"\n\ninterface RunServerOptions {\n host: string\n port: number\n verbose: boolean\n githubToken?: string\n showToken: boolean\n proxyEnv: boolean\n}\n\ntype GitHubTokenSource = \"cli\" | \"env\" | \"file\"\n\n// The environment is preferred over the token file so the token never has to\n// travel through the process list; --github-token stays first for callers that\n// opt in explicitly.\nasync function resolveGitHubToken(\n cliToken: string | undefined,\n): Promise<{ token: string; source: GitHubTokenSource } | null> {\n if (cliToken) return { token: cliToken, source: \"cli\" }\n\n const envToken = readGitHubTokenFromEnv()\n if (envToken) return { token: envToken, source: \"env\" }\n\n const fileToken = await readGitHubToken()\n if (fileToken) return { token: fileToken, source: \"file\" }\n\n return null\n}\n\nasync function setupCopilotMode(\n githubToken: string,\n source: GitHubTokenSource,\n): Promise<void> {\n state.githubTokenSource = source\n consola.info(\n source === \"cli\" ? \"Using provided GitHub token\"\n : source === \"env\" ?\n `Using GitHub token from the ${GITHUB_TOKEN_ENV} environment variable`\n : \"Using GitHub token from local file\",\n )\n\n await setupCopilotRuntime(githubToken)\n}\n\nasync function setupProviderMode(): Promise<void> {\n const enabledProviders = listEnabledProviders()\n\n if (enabledProviders.length > 0) {\n consola.info(`Using enabled providers: ${enabledProviders.join(\", \")}`)\n return\n }\n\n if (!isGitHubCopilotEnabled()) {\n throw new Error(\n \"No enabled providers found. Enable GitHub Copilot with `copilot-api provider enable github-copilot`, or enable another configured provider.\",\n )\n }\n\n consola.info(\"No enabled providers found. Setting one up...\")\n await runProviderSetup()\n\n if (state.githubToken && isGitHubCopilotEnabled()) {\n // The setup flow persisted the token with the credential store.\n await setupCopilotMode(state.githubToken, \"file\")\n return\n }\n\n const providersAfterSetup = listEnabledProviders()\n if (providersAfterSetup.length === 0) {\n throw new Error(\n \"Failed to configure any provider. Run `copilot-api auth login` to set one up.\",\n )\n }\n consola.info(`Configured providers: ${providersAfterSetup.join(\", \")}`)\n}\n\nexport async function runServer(options: RunServerOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n consola.options.throttle = 0\n\n mergeConfigWithDefaults()\n\n const configuredApiKeys = getConfiguredApiKeys()\n const binding = resolveServerBinding(\n options.host,\n configuredApiKeys.length > 0,\n )\n\n const missingApiKeysMessage = getMissingApiKeysMessage()\n if (missingApiKeysMessage) {\n consola.info(missingApiKeysMessage)\n }\n\n await initOpencodeVersion()\n\n if (options.proxyEnv) {\n initProxyFromEnv()\n }\n\n state.verbose = options.verbose\n if (options.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = options.showToken\n\n await ensurePaths()\n await startModelsDevCache()\n\n const serverUrl = formatServerUrl(binding.clientHostname, options.port)\n\n const resolvedGitHubToken =\n isGitHubCopilotEnabled() ?\n await resolveGitHubToken(options.githubToken)\n : null\n if (resolvedGitHubToken && isGitHubCopilotEnabled()) {\n await setupCopilotMode(\n resolvedGitHubToken.token,\n resolvedGitHubToken.source,\n )\n } else {\n await setupProviderMode()\n }\n\n consola.box(\n `🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`,\n )\n\n const { createServer } = await import(\"./server\")\n const server = createServer({ networkExposed: binding.networkExposed })\n\n serve({\n fetch: server.fetch as ServerHandler,\n hostname: binding.hostname,\n port: options.port,\n bun: {\n idleTimeout: 0,\n },\n })\n}\n\nexport const start = defineCommand({\n meta: {\n name: \"start\",\n description: \"Start the Copilot API server\",\n },\n args: {\n host: {\n type: \"string\",\n default: process.env.HOST?.trim() || DEFAULT_SERVER_HOST,\n description: \"Host to listen on\",\n },\n port: {\n alias: \"p\",\n type: \"string\",\n default: \"4141\",\n description: \"Port to listen on\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"github-token\": {\n alias: \"g\",\n type: \"string\",\n description:\n \"Provide GitHub token directly (must be generated using the `auth` subcommand)\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub and Copilot tokens on fetch and refresh\",\n },\n \"proxy-env\": {\n type: \"boolean\",\n default: false,\n description: \"Initialize proxy from environment variables\",\n },\n },\n run({ args }) {\n return runServer({\n host: args.host,\n port: Number.parseInt(args.port, 10),\n verbose: args.verbose,\n githubToken: args[\"github-token\"],\n showToken: args[\"show-token\"],\n proxyEnv: args[\"proxy-env\"],\n })\n },\n})\n"],"mappings":";;;;;;;;;;;;AAIA,IAAI;AAMJ,SAAgB,mBAAyB;CACvC,IAAI;EACF,MAAM,SAAS,IAAI,MAAM;EACzB,MAAM,0BAAU,IAAI,IAAwB;EAmD5C,qBAAqB;GA5CnB,SACE,SACA,SACA;IACA,IAAI;KACF,MAAM,SACJ,OAAO,QAAQ,WAAW,WACxB,IAAI,IAAI,QAAQ,MAAM,IACrB,QAAQ;KAIb,MAAM,MAAMA,eAAI,OAAO,SAAS,CAAC;KACjC,MAAM,WAAW,OAAO,IAAI,SAAS,IAAI,MAAM,KAAA;KAC/C,IAAI,CAA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;CACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,UAAU;GACf,MAAM,KAAK;GACX,MAAM,OAAO,SAAS,KAAK,MAAM,EAAE;GACnC,SAAS,KAAK;GACd,aAAa,KAAK;GAClB,WAAW,KAAK;GAChB,UAAU,KAAK;EACjB,CAAC;CACH;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"start-BiKN2HN7.js","names":["get"],"sources":["../src/lib/proxy.ts","../src/lib/server-host-shared.ts","../src/lib/server-host.ts","../src/start.ts"],"sourcesContent":["import consola from \"consola\"\nimport { getProxyForUrl } from \"proxy-from-env\"\nimport { Agent, ProxyAgent, setGlobalDispatcher, type Dispatcher } from \"undici\"\n\nlet proxyEnvDispatcher: Dispatcher | undefined\n\nexport function getProxyEnvDispatcher(): Dispatcher | undefined {\n return proxyEnvDispatcher\n}\n\nexport function initProxyFromEnv(): void {\n try {\n const direct = new Agent()\n const proxies = new Map<string, ProxyAgent>()\n\n // We only need a minimal dispatcher that implements `dispatch` at runtime.\n // Typing the object as `Dispatcher` forces TypeScript to require many\n // additional methods. Instead, keep a plain object and cast when passing\n // to `setGlobalDispatcher`.\n const dispatcher = {\n dispatch(\n options: Dispatcher.DispatchOptions,\n handler: Dispatcher.DispatchHandler,\n ) {\n try {\n const origin =\n typeof options.origin === \"string\" ?\n new URL(options.origin)\n : (options.origin as URL)\n const get = getProxyForUrl as unknown as (\n u: string,\n ) => string | undefined\n const raw = get(origin.toString())\n const proxyUrl = raw && raw.length > 0 ? raw : undefined\n if (!proxyUrl) {\n consola.debug(`HTTP proxy bypass: ${origin.hostname}`)\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n let agent = proxies.get(proxyUrl)\n if (!agent) {\n agent = new ProxyAgent(proxyUrl)\n proxies.set(proxyUrl, agent)\n }\n let label = proxyUrl\n try {\n const u = new URL(proxyUrl)\n label = `${u.protocol}//${u.host}`\n } catch {\n /* noop */\n }\n consola.debug(`HTTP proxy route: ${origin.hostname} via ${label}`)\n return (agent as unknown as Dispatcher).dispatch(options, handler)\n } catch {\n return (direct as unknown as Dispatcher).dispatch(options, handler)\n }\n },\n close() {\n return direct.close()\n },\n destroy() {\n return direct.destroy()\n },\n }\n\n proxyEnvDispatcher = dispatcher as unknown as Dispatcher\n\n if (typeof Bun !== \"undefined\") {\n consola.debug(\"WebSocket proxy configured from environment (per-URL)\")\n return\n }\n\n setGlobalDispatcher(proxyEnvDispatcher)\n consola.debug(\"HTTP proxy configured from environment (per-URL)\")\n } catch (err) {\n consola.debug(\"Proxy setup skipped:\", err)\n }\n}\n","// Pure hostname helpers shared by the gateway server (Node) and the desktop\n// app (including the renderer bundle). This module must stay free of\n// `node:*` imports because the renderer cannot use `node:net`; all\n// address-family checks live in `server-host.ts`.\nexport const INVALID_HOST_CHARACTERS = /[\\s/?#]/\n\n// Bind hosts that listen on every interface, in normalized form (no\n// brackets, so \"[::]\" is covered via `stripIpv6Brackets`).\nexport const NORMALIZED_WILDCARD_HOSTS = new Set([\"0.0.0.0\", \"::\"])\n\nexport function stripIpv6Brackets(hostname: string): string {\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n return hostname.slice(1, -1)\n }\n return hostname\n}\n\nexport function normalizeHostnameBase(hostname: string): string {\n const normalized = stripIpv6Brackets(hostname.trim())\n if (!normalized || INVALID_HOST_CHARACTERS.test(normalized)) {\n throw new Error(`Invalid server host: ${JSON.stringify(hostname)}`)\n }\n return normalized\n}\n\nexport function isWildcardHostname(hostname: string): boolean {\n return NORMALIZED_WILDCARD_HOSTS.has(stripIpv6Brackets(hostname.trim()))\n}\n","import { isIP } from \"node:net\"\n\nimport { isWildcardHostname, normalizeHostnameBase } from \"./server-host-shared\"\n\nexport const DEFAULT_SERVER_HOST = \"127.0.0.1\"\n\n// Listen failures that mean the hostname itself cannot be bound, as opposed\n// to the port being occupied (EADDRINUSE) or forbidden (EACCES). ENOTFOUND\n// covers unresolvable names such as typos, EADDRNOTAVAIL covers valid IPs\n// that are not assigned to this machine.\nconst INVALID_BIND_ERROR_CODES = new Set([\n \"ENOTFOUND\",\n \"EADDRNOTAVAIL\",\n \"EINVAL\",\n \"EAFNOSUPPORT\",\n \"ENXIO\",\n])\n\nexport function isInvalidBindErrorCode(code?: string): boolean {\n return !!code && INVALID_BIND_ERROR_CODES.has(code)\n}\n\nexport interface ServerBinding {\n hostname: string\n clientHostname: string\n networkExposed: boolean\n}\n\nfunction isLoopbackIpv4(hostname: string): boolean {\n return isIP(hostname) === 4 && hostname.split(\".\", 1)[0] === \"127\"\n}\n\nfunction isLoopbackMappedIpv4(hostname: string): boolean {\n try {\n const canonicalHostname = new URL(`http://[${hostname}]/`).hostname.slice(\n 1,\n -1,\n )\n const mappedIpv4 = canonicalHostname.match(\n /^::ffff:([\\da-f]{1,4}):[\\da-f]{1,4}$/,\n )\n if (!mappedIpv4) {\n return false\n }\n\n return (Number.parseInt(mappedIpv4[1], 16) & 0xff00) === 0x7f00\n } catch {\n return false\n }\n}\n\nexport function normalizeServerHostname(hostname: string): string {\n return normalizeHostnameBase(hostname)\n}\n\nexport function isLoopbackHostname(hostname: string): boolean {\n const normalized = normalizeServerHostname(hostname).toLowerCase()\n if (normalized === \"localhost\" || normalized === \"localhost.\") {\n return true\n }\n if (isLoopbackIpv4(normalized)) {\n return true\n }\n if (isIP(normalized) !== 6) {\n return false\n }\n\n if (normalized === \"::1\" || normalized === \"0:0:0:0:0:0:0:1\") {\n return true\n }\n\n return isLoopbackMappedIpv4(normalized)\n}\n\nexport function resolveServerBinding(\n hostname: string,\n hasApiKeys: boolean,\n): ServerBinding {\n const normalizedHostname = normalizeServerHostname(hostname)\n const networkExposed = !isLoopbackHostname(normalizedHostname)\n\n if (networkExposed && !hasApiKeys) {\n throw new Error(\n `Refusing to listen on non-loopback host ${JSON.stringify(normalizedHostname)} without gateway API keys. Run \\`npx @jeffreycao/copilot-api@latest auth keys --add <key>\\` first, or use \\`--host ${DEFAULT_SERVER_HOST}\\`.`,\n )\n }\n\n return {\n hostname: normalizedHostname,\n clientHostname: resolveClientHostname(normalizedHostname),\n networkExposed,\n }\n}\n\nexport function resolveClientHostname(hostname: string): string {\n const normalizedHostname = normalizeServerHostname(hostname)\n // Wildcard binds listen on every interface, which clients cannot dial\n // directly (0.0.0.0 is not a routable destination).\n return isWildcardHostname(normalizedHostname) ? DEFAULT_SERVER_HOST : (\n normalizedHostname.toLowerCase()\n )\n}\n\nexport function resolveClientHostnameOrDefault(\n hostname: string | null | undefined,\n): string {\n const normalizedHostname = hostname?.trim()\n return normalizedHostname ?\n resolveClientHostname(normalizedHostname)\n : DEFAULT_SERVER_HOST\n}\n\nexport function formatServerUrl(hostname: string, port: number): string {\n const urlHostname =\n isIP(hostname) === 6 ? `[${hostname.replace(\"%\", \"%25\")}]` : hostname\n return `http://${urlHostname}:${port}`\n}\n","#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport { serve, type ServerHandler } from \"srvx\"\n\nimport { runProviderSetup } from \"./auth\"\nimport { isGitHubCopilotEnabled } from \"./lib/github-copilot-provider\"\nimport { listEnabledProviders, mergeConfigWithDefaults } from \"./lib/config\"\nimport { setupCopilotRuntime } from \"~/lib/copilot-runtime\"\nimport {\n GITHUB_TOKEN_ENV,\n readGitHubToken,\n readGitHubTokenFromEnv,\n} from \"./lib/credential-store\"\nimport { startModelsDevCache } from \"./lib/models-dev-cache\"\nimport { initOpencodeVersion } from \"./lib/opencode\"\nimport { ensurePaths } from \"./lib/paths\"\nimport { initProxyFromEnv } from \"./lib/proxy\"\nimport {\n getConfiguredApiKeys,\n getMissingApiKeysMessage,\n} from \"./lib/request-auth\"\nimport {\n DEFAULT_SERVER_HOST,\n formatServerUrl,\n resolveServerBinding,\n} from \"./lib/server-host\"\nimport { state } from \"./lib/state\"\n\ninterface RunServerOptions {\n host: string\n port: number\n verbose: boolean\n githubToken?: string\n showToken: boolean\n proxyEnv: boolean\n}\n\ntype GitHubTokenSource = \"cli\" | \"env\" | \"file\"\n\n// The environment is preferred over the token file so the token never has to\n// travel through the process list; --github-token stays first for callers that\n// opt in explicitly.\nasync function resolveGitHubToken(\n cliToken: string | undefined,\n): Promise<{ token: string; source: GitHubTokenSource } | null> {\n if (cliToken) return { token: cliToken, source: \"cli\" }\n\n const envToken = readGitHubTokenFromEnv()\n if (envToken) return { token: envToken, source: \"env\" }\n\n const fileToken = await readGitHubToken()\n if (fileToken) return { token: fileToken, source: \"file\" }\n\n return null\n}\n\nasync function setupCopilotMode(\n githubToken: string,\n source: GitHubTokenSource,\n): Promise<void> {\n state.githubTokenSource = source\n consola.info(\n source === \"cli\" ? \"Using provided GitHub token\"\n : source === \"env\" ?\n `Using GitHub token from the ${GITHUB_TOKEN_ENV} environment variable`\n : \"Using GitHub token from local file\",\n )\n\n await setupCopilotRuntime(githubToken)\n}\n\nasync function setupProviderMode(): Promise<void> {\n const enabledProviders = listEnabledProviders()\n\n if (enabledProviders.length > 0) {\n consola.info(`Using enabled providers: ${enabledProviders.join(\", \")}`)\n return\n }\n\n if (!isGitHubCopilotEnabled()) {\n throw new Error(\n \"No enabled providers found. Enable GitHub Copilot with `copilot-api provider enable github-copilot`, or enable another configured provider.\",\n )\n }\n\n consola.info(\"No enabled providers found. Setting one up...\")\n await runProviderSetup()\n\n if (state.githubToken && isGitHubCopilotEnabled()) {\n // The setup flow persisted the token with the credential store.\n await setupCopilotMode(state.githubToken, \"file\")\n return\n }\n\n const providersAfterSetup = listEnabledProviders()\n if (providersAfterSetup.length === 0) {\n throw new Error(\n \"Failed to configure any provider. Run `copilot-api auth login` to set one up.\",\n )\n }\n consola.info(`Configured providers: ${providersAfterSetup.join(\", \")}`)\n}\n\nexport async function runServer(options: RunServerOptions): Promise<void> {\n const tlsModule = await import(\"./lib/tls\")\n tlsModule.enableSystemCACompat()\n\n consola.options.throttle = 0\n\n mergeConfigWithDefaults()\n\n const configuredApiKeys = getConfiguredApiKeys()\n const binding = resolveServerBinding(\n options.host,\n configuredApiKeys.length > 0,\n )\n\n const missingApiKeysMessage = getMissingApiKeysMessage()\n if (missingApiKeysMessage) {\n consola.info(missingApiKeysMessage)\n }\n\n await initOpencodeVersion()\n\n if (options.proxyEnv) {\n initProxyFromEnv()\n }\n\n state.verbose = options.verbose\n if (options.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = options.showToken\n\n await ensurePaths()\n await startModelsDevCache()\n\n const serverUrl = formatServerUrl(binding.clientHostname, options.port)\n\n const resolvedGitHubToken =\n isGitHubCopilotEnabled() ?\n await resolveGitHubToken(options.githubToken)\n : null\n if (resolvedGitHubToken && isGitHubCopilotEnabled()) {\n await setupCopilotMode(\n resolvedGitHubToken.token,\n resolvedGitHubToken.source,\n )\n } else {\n await setupProviderMode()\n }\n\n consola.box(\n `🌐 Dashboard Viewer: ${serverUrl}/usage-viewer?endpoint=${serverUrl}/usage`,\n )\n\n const { createServer } = await import(\"./server\")\n const server = createServer({ networkExposed: binding.networkExposed })\n\n serve({\n fetch: server.fetch as ServerHandler,\n hostname: binding.hostname,\n port: options.port,\n bun: {\n idleTimeout: 0,\n },\n })\n}\n\nexport const start = defineCommand({\n meta: {\n name: \"start\",\n description: \"Start the Copilot API server\",\n },\n args: {\n host: {\n type: \"string\",\n default: process.env.HOST?.trim() || DEFAULT_SERVER_HOST,\n description: \"Host to listen on\",\n },\n port: {\n alias: \"p\",\n type: \"string\",\n default: \"4141\",\n description: \"Port to listen on\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"github-token\": {\n alias: \"g\",\n type: \"string\",\n description:\n \"Provide GitHub token directly (must be generated using the `auth` subcommand)\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub and Copilot tokens on fetch and refresh\",\n },\n \"proxy-env\": {\n type: \"boolean\",\n default: false,\n description: \"Initialize proxy from environment variables\",\n },\n },\n run({ args }) {\n return runServer({\n host: args.host,\n port: Number.parseInt(args.port, 10),\n verbose: args.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AK,EACH,aAAa,EACf;CACF,CAAC;AACH;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,MAAM;GACJ,MAAM;GACN,SAAS,QAAQ,IAAI,MAAM,KAAK,KAAA;GAChC,aAAa;EACf;EACA,MAAM;GACJ,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,aACE;EACJ;EACA,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;EACf;EACA,aAAa;GACX,MAAM;GACN,SAAS;GACT,aAAa;EACf;CACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,UAAU;GACf,MAAM,KAAK;GACX,MAAM,OAAO,SAAS,KAAK,MAAM,EAAE;GACnC,SAAS,KAAK;GACd,aAAa,KAAK;GAClB,WAAW,KAAK;GAChB,UAAU,KAAK;EACjB,CAAC;CACH;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@jeffreycao/copilot-api",
|
|
4
|
-
"version": "2.7.
|
|
4
|
+
"version": "2.7.19",
|
|
5
5
|
"description": "GitHub Copilot, OpenAI Codex, OpenCode Go, and third-party AI provider gateway with OpenAI and Anthropic API compatibility.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"github-copilot",
|
package/pages/index.html
CHANGED
|
@@ -306,6 +306,44 @@
|
|
|
306
306
|
font-weight: 750;
|
|
307
307
|
}
|
|
308
308
|
|
|
309
|
+
.collapse-toggle {
|
|
310
|
+
display: inline-flex;
|
|
311
|
+
align-items: center;
|
|
312
|
+
gap: 6px;
|
|
313
|
+
padding: 0;
|
|
314
|
+
border: 0;
|
|
315
|
+
background: none;
|
|
316
|
+
color: inherit;
|
|
317
|
+
font: inherit;
|
|
318
|
+
text-align: left;
|
|
319
|
+
cursor: pointer;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
.collapse-toggle:focus-visible {
|
|
323
|
+
outline: 2px solid var(--color-blue);
|
|
324
|
+
outline-offset: 2px;
|
|
325
|
+
border-radius: 4px;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
.collapse-chevron {
|
|
329
|
+
width: 16px;
|
|
330
|
+
height: 16px;
|
|
331
|
+
flex-shrink: 0;
|
|
332
|
+
color: var(--color-gray);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
.collapse-toggle[aria-expanded="false"] .collapse-chevron {
|
|
336
|
+
transform: rotate(-90deg);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
.collapse-body[hidden] {
|
|
340
|
+
display: none !important;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
.panel-header:has(+ .collapse-body[hidden]) {
|
|
344
|
+
border-bottom-color: transparent;
|
|
345
|
+
}
|
|
346
|
+
|
|
309
347
|
.section-subtitle {
|
|
310
348
|
margin-top: -4px;
|
|
311
349
|
margin-bottom: 8px;
|
|
@@ -700,6 +738,7 @@
|
|
|
700
738
|
tokenUsageTrendDay: null,
|
|
701
739
|
tokenUsageTrendMetric: ALL_METRICS_VALUE,
|
|
702
740
|
tokenUsageTrendModel: ALL_MODELS_VALUE,
|
|
741
|
+
collapsedSections: {},
|
|
703
742
|
};
|
|
704
743
|
|
|
705
744
|
// --- Rendering Logic ---
|
|
@@ -1230,6 +1269,110 @@
|
|
|
1230
1269
|
createIcons();
|
|
1231
1270
|
}
|
|
1232
1271
|
|
|
1272
|
+
// --- Collapsible Sections ---
|
|
1273
|
+
const COLLAPSED_SECTIONS_STORAGE_KEY =
|
|
1274
|
+
"copilot-api:usage-viewer:collapsed";
|
|
1275
|
+
const COLLAPSIBLE_SECTION_KEYS = new Set([
|
|
1276
|
+
"tokenUsage",
|
|
1277
|
+
"modelBreakdown",
|
|
1278
|
+
"sessionBreakdown",
|
|
1279
|
+
"requestEvents",
|
|
1280
|
+
"copilotQuotas",
|
|
1281
|
+
"usageApiResponse",
|
|
1282
|
+
]);
|
|
1283
|
+
|
|
1284
|
+
function readCollapsedSections() {
|
|
1285
|
+
try {
|
|
1286
|
+
const raw = window.localStorage.getItem(
|
|
1287
|
+
COLLAPSED_SECTIONS_STORAGE_KEY
|
|
1288
|
+
);
|
|
1289
|
+
const parsed = raw ? JSON.parse(raw) : null;
|
|
1290
|
+
const collapsed = {};
|
|
1291
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1292
|
+
for (const key of COLLAPSIBLE_SECTION_KEYS) {
|
|
1293
|
+
if (parsed[key] === true) {
|
|
1294
|
+
collapsed[key] = true;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
return collapsed;
|
|
1299
|
+
} catch (error) {
|
|
1300
|
+
console.warn(
|
|
1301
|
+
"Could not read collapsed sections:",
|
|
1302
|
+
getErrorMessage(error)
|
|
1303
|
+
);
|
|
1304
|
+
return {};
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
function writeCollapsedSections() {
|
|
1309
|
+
try {
|
|
1310
|
+
window.localStorage.setItem(
|
|
1311
|
+
COLLAPSED_SECTIONS_STORAGE_KEY,
|
|
1312
|
+
JSON.stringify(state.collapsedSections)
|
|
1313
|
+
);
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
console.warn(
|
|
1316
|
+
"Could not store collapsed sections:",
|
|
1317
|
+
getErrorMessage(error)
|
|
1318
|
+
);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
function isSectionCollapsed(key) {
|
|
1323
|
+
return state.collapsedSections[key] === true;
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
function getCollapseBodyId(key) {
|
|
1327
|
+
return `collapse-body-${key}`;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/**
|
|
1331
|
+
* Renders the toggle button (chevron + label) shown in a section header.
|
|
1332
|
+
* @param {string} key - A COLLAPSIBLE_SECTION_KEYS entry.
|
|
1333
|
+
* @param {string} labelHtml - Trusted HTML for the toggle label.
|
|
1334
|
+
*/
|
|
1335
|
+
function renderCollapseToggle(key, labelHtml) {
|
|
1336
|
+
return `<button type="button" class="collapse-toggle" data-collapse-toggle="${key}" aria-expanded="${!isSectionCollapsed(key)}" aria-controls="${getCollapseBodyId(key)}"><i data-lucide="chevron-down" class="collapse-chevron"></i>${labelHtml}</button>`;
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/**
|
|
1340
|
+
* Opens a section body wrapper that is hidden while the section is
|
|
1341
|
+
* collapsed. Pair with renderCollapseBodyEnd() for multi-part bodies.
|
|
1342
|
+
* @param {string} key - A COLLAPSIBLE_SECTION_KEYS entry.
|
|
1343
|
+
* @param {string} className - Optional extra classes for the wrapper.
|
|
1344
|
+
*/
|
|
1345
|
+
function renderCollapseBodyStart(key, className = "") {
|
|
1346
|
+
return `<div id="${getCollapseBodyId(key)}" class="collapse-body ${className}" ${isSectionCollapsed(key) ? "hidden" : ""}>`;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
function renderCollapseBodyEnd() {
|
|
1350
|
+
return "</div>";
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
function renderCollapseBody(key, bodyHtml, className = "") {
|
|
1354
|
+
return `${renderCollapseBodyStart(key, className)}${bodyHtml}${renderCollapseBodyEnd()}`;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
function toggleCollapsedSection(button) {
|
|
1358
|
+
const key = button.dataset.collapseToggle;
|
|
1359
|
+
if (!COLLAPSIBLE_SECTION_KEYS.has(key)) {
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
const collapsed = !isSectionCollapsed(key);
|
|
1363
|
+
if (collapsed) {
|
|
1364
|
+
state.collapsedSections[key] = true;
|
|
1365
|
+
} else {
|
|
1366
|
+
delete state.collapsedSections[key];
|
|
1367
|
+
}
|
|
1368
|
+
const body = document.getElementById(getCollapseBodyId(key));
|
|
1369
|
+
if (body) {
|
|
1370
|
+
body.hidden = collapsed;
|
|
1371
|
+
}
|
|
1372
|
+
button.setAttribute("aria-expanded", String(!collapsed));
|
|
1373
|
+
writeCollapsedSections();
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1233
1376
|
function getModelField(model, fields) {
|
|
1234
1377
|
for (const field of fields) {
|
|
1235
1378
|
if (typeof model?.[field] === "string" && model[field].trim()) {
|
|
@@ -1464,12 +1607,12 @@
|
|
|
1464
1607
|
return `
|
|
1465
1608
|
<section id="usage-quotas" class="dashboard-section">
|
|
1466
1609
|
<h2 class="section-heading">
|
|
1467
|
-
|
|
1468
|
-
|
|
1610
|
+
${renderCollapseToggle(
|
|
1611
|
+
"copilotQuotas",
|
|
1612
|
+
`<i data-lucide="gauge" class="h-5 w-5" style="color: var(--color-blue);"></i><span>Copilot Quotas</span>`
|
|
1613
|
+
)}
|
|
1469
1614
|
</h2>
|
|
1470
|
-
|
|
1471
|
-
${quotaCards}
|
|
1472
|
-
</div>
|
|
1615
|
+
${renderCollapseBody("copilotQuotas", quotaCards, "metric-grid")}
|
|
1473
1616
|
</section>
|
|
1474
1617
|
`;
|
|
1475
1618
|
}
|
|
@@ -1482,10 +1625,15 @@
|
|
|
1482
1625
|
return `
|
|
1483
1626
|
<section id="usage-quotas" class="dashboard-section">
|
|
1484
1627
|
<h2 class="section-heading">
|
|
1485
|
-
|
|
1486
|
-
|
|
1628
|
+
${renderCollapseToggle(
|
|
1629
|
+
"copilotQuotas",
|
|
1630
|
+
`<i data-lucide="gauge" class="h-5 w-5" style="color: var(--color-blue);"></i><span>Copilot Quotas</span>`
|
|
1631
|
+
)}
|
|
1487
1632
|
</h2>
|
|
1488
|
-
${
|
|
1633
|
+
${renderCollapseBody(
|
|
1634
|
+
"copilotQuotas",
|
|
1635
|
+
renderError(state.error, "Usage request failed")
|
|
1636
|
+
)}
|
|
1489
1637
|
</section>
|
|
1490
1638
|
`;
|
|
1491
1639
|
}
|
|
@@ -1620,12 +1768,17 @@
|
|
|
1620
1768
|
return `
|
|
1621
1769
|
<section id="detailed-data" class="dashboard-section">
|
|
1622
1770
|
<h2 class="section-heading">
|
|
1623
|
-
|
|
1624
|
-
|
|
1771
|
+
${renderCollapseToggle(
|
|
1772
|
+
"usageApiResponse",
|
|
1773
|
+
`<i data-lucide="file-text" class="h-5 w-5" style="color: var(--color-blue);"></i><span>Copilot Usage API Response</span>`
|
|
1774
|
+
)}
|
|
1625
1775
|
</h2>
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1776
|
+
${renderCollapseBody(
|
|
1777
|
+
"usageApiResponse",
|
|
1778
|
+
`<div class="panel p-4 relative font-mono text-xs code-block overflow-auto" style="max-height: 420px;">
|
|
1779
|
+
${formattedDetails}
|
|
1780
|
+
</div>`
|
|
1781
|
+
)}
|
|
1629
1782
|
</section>
|
|
1630
1783
|
`;
|
|
1631
1784
|
}
|
|
@@ -1665,8 +1818,10 @@
|
|
|
1665
1818
|
<div class="mb-2 flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
|
1666
1819
|
<div>
|
|
1667
1820
|
<h2 class="section-heading mb-1">
|
|
1668
|
-
|
|
1669
|
-
|
|
1821
|
+
${renderCollapseToggle(
|
|
1822
|
+
"tokenUsage",
|
|
1823
|
+
`<i data-lucide="database" class="h-5 w-5" style="color: var(--color-blue);"></i><span>Token Usage</span>`
|
|
1824
|
+
)}
|
|
1670
1825
|
</h2>
|
|
1671
1826
|
<p class="section-subtitle mb-0">${escapeHtml(
|
|
1672
1827
|
renderTokenUsageRangeText(state.tokenUsagePeriod, activeRange)
|
|
@@ -1686,6 +1841,7 @@
|
|
|
1686
1841
|
</div>
|
|
1687
1842
|
</div>
|
|
1688
1843
|
|
|
1844
|
+
${renderCollapseBodyStart("tokenUsage")}
|
|
1689
1845
|
${
|
|
1690
1846
|
state.tokenUsageSummaryError
|
|
1691
1847
|
? renderError(
|
|
@@ -1791,17 +1947,20 @@
|
|
|
1791
1947
|
<div class="panel">
|
|
1792
1948
|
<div class="panel-header">
|
|
1793
1949
|
<div>
|
|
1794
|
-
<p class="panel-title">Model Breakdown</p>
|
|
1950
|
+
<p class="panel-title">${renderCollapseToggle("modelBreakdown", "<span>Model Breakdown</span>")}</p>
|
|
1795
1951
|
<p class="panel-meta">${summary ? `${formatNumber(summary.byModel.length)} models` : "No summary rows loaded."}</p>
|
|
1796
1952
|
</div>
|
|
1797
1953
|
</div>
|
|
1798
|
-
${
|
|
1954
|
+
${renderCollapseBody(
|
|
1955
|
+
"modelBreakdown",
|
|
1956
|
+
renderTokenUsageModelBreakdown(summary)
|
|
1957
|
+
)}
|
|
1799
1958
|
</div>
|
|
1800
1959
|
|
|
1801
1960
|
<div class="panel">
|
|
1802
1961
|
<div class="panel-header">
|
|
1803
1962
|
<div>
|
|
1804
|
-
<p class="panel-title">Session Breakdown</p>
|
|
1963
|
+
<p class="panel-title">${renderCollapseToggle("sessionBreakdown", "<span>Session Breakdown</span>")}</p>
|
|
1805
1964
|
<p class="panel-meta">${sessionsPage ? `Page ${sessionsPage.page} / ${sessionsPage.total_pages} - ${formatNumber(sessionsPage.total)} sessions` : "No session rows loaded."}</p>
|
|
1806
1965
|
</div>
|
|
1807
1966
|
<div class="flex items-center gap-2">
|
|
@@ -1809,6 +1968,7 @@
|
|
|
1809
1968
|
<button type="button" data-session-page="1" class="pill-button px-3 py-1.5 text-xs font-semibold" ${!sessionsPage || state.isSessionsLoading || sessionsPage.page >= sessionsPage.total_pages ? "disabled" : ""}>Next</button>
|
|
1810
1969
|
</div>
|
|
1811
1970
|
</div>
|
|
1971
|
+
${renderCollapseBodyStart("sessionBreakdown")}
|
|
1812
1972
|
${
|
|
1813
1973
|
state.tokenUsageSessionsError
|
|
1814
1974
|
? `<div class="p-4">${renderError(
|
|
@@ -1818,12 +1978,13 @@
|
|
|
1818
1978
|
: ""
|
|
1819
1979
|
}
|
|
1820
1980
|
${renderTokenUsageModelBreakdown({ bySession: sessionsPage?.items }, "session")}
|
|
1981
|
+
${renderCollapseBodyEnd()}
|
|
1821
1982
|
</div>
|
|
1822
1983
|
|
|
1823
1984
|
<div class="panel">
|
|
1824
1985
|
<div class="panel-header flex-col items-start sm:flex-row sm:items-center">
|
|
1825
1986
|
<div>
|
|
1826
|
-
<p class="panel-title">Request Events</p>
|
|
1987
|
+
<p class="panel-title">${renderCollapseToggle("requestEvents", "<span>Request Events</span>")}</p>
|
|
1827
1988
|
<p class="panel-meta">${escapeHtml(eventsMeta)}</p>
|
|
1828
1989
|
</div>
|
|
1829
1990
|
<div class="flex items-center gap-2">
|
|
@@ -1841,6 +2002,7 @@
|
|
|
1841
2002
|
)}
|
|
1842
2003
|
</div>
|
|
1843
2004
|
</div>
|
|
2005
|
+
${renderCollapseBodyStart("requestEvents")}
|
|
1844
2006
|
${
|
|
1845
2007
|
state.tokenUsageEventsError
|
|
1846
2008
|
? `<div class="p-4">${renderError(
|
|
@@ -1850,8 +2012,10 @@
|
|
|
1850
2012
|
: ""
|
|
1851
2013
|
}
|
|
1852
2014
|
${renderTokenUsageEventsTable(eventsPage)}
|
|
2015
|
+
${renderCollapseBodyEnd()}
|
|
1853
2016
|
</div>
|
|
1854
2017
|
</div>
|
|
2018
|
+
${renderCollapseBodyEnd()}
|
|
1855
2019
|
</section>
|
|
1856
2020
|
`;
|
|
1857
2021
|
}
|
|
@@ -2817,6 +2981,11 @@
|
|
|
2817
2981
|
void copyModelId(copyButton.dataset.modelCopy);
|
|
2818
2982
|
return;
|
|
2819
2983
|
}
|
|
2984
|
+
const collapseToggle = event.target.closest("[data-collapse-toggle]");
|
|
2985
|
+
if (collapseToggle) {
|
|
2986
|
+
toggleCollapsedSection(collapseToggle);
|
|
2987
|
+
return;
|
|
2988
|
+
}
|
|
2820
2989
|
const detailsButton = event.target.closest("[data-model-details]");
|
|
2821
2990
|
if (detailsButton) {
|
|
2822
2991
|
const details = document.getElementById(
|
|
@@ -2945,6 +3114,7 @@
|
|
|
2945
3114
|
endpointUrlInput.value = initialEndpoint;
|
|
2946
3115
|
migrateLegacyApiKey(initialEndpoint);
|
|
2947
3116
|
syncEndpointCredential();
|
|
3117
|
+
state.collapsedSections = readCollapsedSections();
|
|
2948
3118
|
|
|
2949
3119
|
if (endpointFromUrl) {
|
|
2950
3120
|
void fetchData();
|