@nick3/copilot-api 1.4.9 → 1.5.2
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/account-CipKmikF.js.map +1 -1
- package/dist/{accounts-manager-Cjrd_el_.js → accounts-manager-DhwGrhHF.js} +21 -9
- package/dist/accounts-manager-DhwGrhHF.js.map +1 -0
- package/dist/admin/assets/{index-BFvCJZIK.js → index-B-G_GrPI.js} +7 -7
- package/dist/admin/index.html +1 -1
- package/dist/{auth-1gAffrpI.js → auth-BtUQnU2m.js} +3 -3
- package/dist/{auth-1gAffrpI.js.map → auth-BtUQnU2m.js.map} +1 -1
- package/dist/{check-usage-CsRu467P.js → check-usage-DiomC9Dl.js} +5 -4
- package/dist/check-usage-DiomC9Dl.js.map +1 -0
- package/dist/{get-copilot-token-BbpphnmV.js → get-copilot-token-DN1P6qll.js} +2 -2
- package/dist/{get-copilot-token-BbpphnmV.js.map → get-copilot-token-DN1P6qll.js.map} +1 -1
- package/dist/main.js +3 -3
- package/dist/{poll-access-token-CGfLFzMq.js → poll-access-token-BrRUFB1F.js} +2 -2
- package/dist/{poll-access-token-CGfLFzMq.js.map → poll-access-token-BrRUFB1F.js.map} +1 -1
- package/dist/{server-DqwhClJ-.js → server-D9M_wFyO.js} +22 -15
- package/dist/server-D9M_wFyO.js.map +1 -0
- package/dist/{start-B1_Ols5Z.js → start-D3yEfZnW.js} +6 -6
- package/dist/{start-B1_Ols5Z.js.map → start-D3yEfZnW.js.map} +1 -1
- package/dist/{utils-DY-jLXwO.js → utils-53JWve7i.js} +19 -10
- package/dist/utils-53JWve7i.js.map +1 -0
- package/package.json +1 -1
- package/dist/accounts-manager-Cjrd_el_.js.map +0 -1
- package/dist/check-usage-CsRu467P.js.map +0 -1
- package/dist/server-DqwhClJ-.js.map +0 -1
- package/dist/utils-DY-jLXwO.js.map +0 -1
package/dist/admin/index.html
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
}
|
|
19
19
|
})()
|
|
20
20
|
</script>
|
|
21
|
-
<script type="module" crossorigin src="/admin/assets/index-
|
|
21
|
+
<script type="module" crossorigin src="/admin/assets/index-B-G_GrPI.js"></script>
|
|
22
22
|
<link rel="stylesheet" crossorigin href="/admin/assets/index-CsAeel_7.css">
|
|
23
23
|
</head>
|
|
24
24
|
<body>
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { r as ensurePaths } from "./paths-Cvzy-eLX.js";
|
|
2
2
|
import { a as loadAccountToken, c as removeAccountToken, i as listAccountsFromRegistry, l as saveAccountToken, s as removeAccountFromRegistry, t as addAccountToRegistry, u as saveRegistry } from "./accounts-registry-CQYvRe65.js";
|
|
3
|
-
import { D as state, f as getGitHubUser, p as getCopilotUsage } from "./utils-
|
|
3
|
+
import { D as state, f as getGitHubUser, p as getCopilotUsage } from "./utils-53JWve7i.js";
|
|
4
4
|
import { t as parseAccountType } from "./account-CipKmikF.js";
|
|
5
|
-
import { n as getDeviceCode, t as pollAccessToken } from "./poll-access-token-
|
|
5
|
+
import { n as getDeviceCode, t as pollAccessToken } from "./poll-access-token-BrRUFB1F.js";
|
|
6
6
|
import { defineCommand } from "citty";
|
|
7
7
|
import consola from "consola";
|
|
8
8
|
|
|
@@ -238,4 +238,4 @@ const auth = defineCommand({
|
|
|
238
238
|
|
|
239
239
|
//#endregion
|
|
240
240
|
export { auth };
|
|
241
|
-
//# sourceMappingURL=auth-
|
|
241
|
+
//# sourceMappingURL=auth-BtUQnU2m.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-1gAffrpI.js","names":["accountType: AccountType","accountToRemove: { id: string; index: number } | undefined"],"sources":["../src/auth.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport {\n addAccountToRegistry,\n listAccountsFromRegistry,\n loadAccountToken,\n removeAccountFromRegistry,\n removeAccountToken,\n saveAccountToken,\n saveRegistry,\n} from \"./lib/accounts-registry\"\nimport { ensurePaths } from \"./lib/paths\"\nimport { state } from \"./lib/state\"\nimport {\n parseAccountType,\n type AccountMeta,\n type AccountType,\n} from \"./lib/types/account\"\nimport { getCopilotUsage } from \"./services/github/get-copilot-usage\"\nimport { getDeviceCode } from \"./services/github/get-device-code\"\nimport { getGitHubUser } from \"./services/github/get-user\"\nimport { pollAccessToken } from \"./services/github/poll-access-token\"\n\n/**\n * Fetch quota info for an account (used by auth ls -q)\n */\nasync function fetchQuotaInfo(account: AccountMeta): Promise<string> {\n try {\n const token = await loadAccountToken(account.id)\n if (!token) {\n return \" | Quota: (no token)\"\n }\n\n const usage = await getCopilotUsage({\n githubToken: token,\n accountType: account.accountType,\n })\n const premium = usage.quota_snapshots.premium_interactions\n\n return premium.unlimited ?\n \" | Quota: unlimited\"\n : ` | Quota: ${premium.remaining}/${premium.entitlement}`\n } catch (error) {\n consola.debug(`Failed to fetch quota for ${account.id}:`, error)\n return \" | Quota: (failed to fetch)\"\n }\n}\n\n/**\n * auth add - Add a new GitHub Copilot account\n */\nconst authAdd = defineCommand({\n meta: {\n name: \"add\",\n description: \"Add a new GitHub Copilot account\",\n },\n args: {\n \"account-type\": {\n alias: \"a\",\n type: \"string\",\n default: \"individual\",\n description: \"Account type (individual, business, enterprise)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub token after auth\",\n },\n },\n async run({ args }) {\n if (args.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = args[\"show-token\"]\n\n let accountType: AccountType\n try {\n accountType = parseAccountType(args[\"account-type\"])\n } catch (error) {\n consola.error(error instanceof Error ? error.message : String(error))\n process.exit(1)\n }\n\n await ensurePaths()\n\n // Start device code flow\n consola.info(\"Starting GitHub device code authentication...\")\n const deviceResponse = await getDeviceCode()\n consola.debug(\"Device code response:\", deviceResponse)\n\n consola.info(\n `Please enter the code \"${deviceResponse.user_code}\" at ${deviceResponse.verification_uri}`,\n )\n\n // Poll for access token\n const token = await pollAccessToken(deviceResponse)\n\n if (state.showToken) {\n consola.info(\"GitHub token:\", token)\n }\n\n // Get user info to determine account ID\n const user = await getGitHubUser({ githubToken: token, accountType })\n const accountId = user.login\n\n // Save token and check if account already exists\n await saveAccountToken(accountId, token)\n const existingAccounts = await listAccountsFromRegistry()\n const alreadyExists = existingAccounts.some((acc) => acc.id === accountId)\n\n if (alreadyExists) {\n // Touch registry file so a running server can hot-reload updated tokens.\n await saveRegistry({ version: 1, accounts: existingAccounts })\n\n consola.success(\n `Account \"${accountId}\" already exists. Token has been updated.`,\n )\n } else {\n await addAccountToRegistry({\n id: accountId,\n accountType,\n addedAt: Date.now(),\n })\n consola.success(`Account \"${accountId}\" added successfully!`)\n }\n\n consola.info(`Account type: ${accountType}`)\n },\n})\n\n/**\n * auth ls - List all registered accounts\n */\nconst authLs = defineCommand({\n meta: {\n name: \"ls\",\n description: \"List all registered accounts\",\n },\n args: {\n \"show-quota\": {\n alias: \"q\",\n type: \"boolean\",\n default: false,\n description: \"Show quota information (requires API call)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n },\n async run({ args }) {\n if (args.verbose) {\n consola.level = 5\n }\n\n await ensurePaths()\n\n const accounts = await listAccountsFromRegistry()\n\n if (accounts.length === 0) {\n consola.info(\"No accounts registered. Use 'auth add' to add an account.\")\n return\n }\n\n consola.info(`Found ${accounts.length} account(s):\\n`)\n\n for (const [i, account] of accounts.entries()) {\n const addedDate = new Date(account.addedAt).toLocaleString()\n\n const quotaInfo = args[\"show-quota\"] ? await fetchQuotaInfo(account) : \"\"\n\n console.log(\n ` ${i + 1}. ${account.id} (${account.accountType})${quotaInfo}`,\n )\n console.log(` Added: ${addedDate}\\n`)\n }\n },\n})\n\n/**\n * auth rm - Remove an account\n */\nconst authRm = defineCommand({\n meta: {\n name: \"rm\",\n description: \"Remove an account\",\n },\n args: {\n target: {\n type: \"positional\",\n description: \"Account ID or index (1-based)\",\n required: true,\n },\n force: {\n alias: \"f\",\n type: \"boolean\",\n default: false,\n description: \"Skip confirmation prompt\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n },\n async run({ args }) {\n if (args.verbose) {\n consola.level = 5\n }\n\n await ensurePaths()\n\n const target = args.target\n const accounts = await listAccountsFromRegistry()\n\n if (accounts.length === 0) {\n consola.error(\"No accounts to remove.\")\n return\n }\n\n // Determine account to remove (by ID or index)\n let accountToRemove: { id: string; index: number } | undefined\n\n // Try parsing as index (1-based)\n const index = Number.parseInt(target, 10)\n if (!Number.isNaN(index) && index >= 1 && index <= accounts.length) {\n accountToRemove = { id: accounts[index - 1].id, index: index - 1 }\n } else {\n // Try finding by ID\n const foundIndex = accounts.findIndex((acc) => acc.id === target)\n if (foundIndex !== -1) {\n accountToRemove = { id: accounts[foundIndex].id, index: foundIndex }\n }\n }\n\n if (!accountToRemove) {\n consola.error(`Account \"${target}\" not found.`)\n consola.info(\"Use 'auth ls' to see available accounts.\")\n return\n }\n\n // Confirmation\n if (!args.force) {\n const confirmed = await consola.prompt(\n `Are you sure you want to remove account \"${accountToRemove.id}\"?`,\n { type: \"confirm\" },\n )\n if (!confirmed) {\n consola.info(\"Cancelled.\")\n return\n }\n }\n\n // Remove token file and registry entry\n await removeAccountToken(accountToRemove.id)\n await removeAccountFromRegistry(accountToRemove.id)\n\n consola.success(`Account \"${accountToRemove.id}\" removed.`)\n },\n})\n\n/**\n * Main auth command with subcommands\n */\nexport const auth = defineCommand({\n meta: {\n name: \"auth\",\n description: \"Manage GitHub Copilot accounts\",\n },\n subCommands: {\n add: authAdd,\n ls: authLs,\n rm: authRm,\n },\n args: {\n // Legacy args for backward compatibility (when no subcommand)\n \"account-type\": {\n alias: \"a\",\n type: \"string\",\n default: \"individual\",\n description: \"Account type (individual, business, enterprise)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub token after auth\",\n },\n },\n async run(ctx) {\n // Check if a subcommand was specified in rawArgs.\n // Only treat the *first* raw arg as a subcommand to avoid false positives\n // when flags accept values like \"add\"/\"ls\"/\"rm\".\n const firstArg = ctx.rawArgs[0]\n const hasSubCommand =\n firstArg === \"add\" || firstArg === \"ls\" || firstArg === \"rm\"\n\n // Backward compatibility: if no subcommand, run 'add'\n if (!hasSubCommand && authAdd.run) {\n await authAdd.run(ctx)\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;AA6BA,eAAe,eAAe,SAAuC;AACnE,KAAI;EACF,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,GAAG;AAChD,MAAI,CAAC,MACH,QAAO;EAOT,MAAM,WAJQ,MAAM,gBAAgB;GAClC,aAAa;GACb,aAAa,QAAQ;GACtB,CAAC,EACoB,gBAAgB;AAEtC,SAAO,QAAQ,YACX,wBACA,aAAa,QAAQ,UAAU,GAAG,QAAQ;UACvC,OAAO;AACd,UAAQ,MAAM,6BAA6B,QAAQ,GAAG,IAAI,MAAM;AAChE,SAAO;;;;;;AAOX,MAAM,UAAU,cAAc;CAC5B,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,MAAM;EACJ,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACF;CACD,MAAM,IAAI,EAAE,QAAQ;AAClB,MAAI,KAAK,SAAS;AAChB,WAAQ,QAAQ;AAChB,WAAQ,KAAK,0BAA0B;;AAGzC,QAAM,YAAY,KAAK;EAEvB,IAAIA;AACJ,MAAI;AACF,iBAAc,iBAAiB,KAAK,gBAAgB;WAC7C,OAAO;AACd,WAAQ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MAAI,CAAC,KAAK,OAKR;OAAI,CAJc,MAAM,QAAQ,OAC9B,4CAA4C,gBAAgB,GAAG,KAC/D,EAAE,MAAM,WAAW,CACpB,EACe;AACd,YAAQ,KAAK,aAAa;AAC1B;;;AAKJ,QAAM,mBAAmB,gBAAgB,GAAG;AAC5C,QAAM,0BAA0B,gBAAgB,GAAG;AAEnD,UAAQ,QAAQ,YAAY,gBAAgB,GAAG,YAAY;;CAE9D,CAAC;;;;AAKF,MAAa,OAAO,cAAc;CAChC,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,aAAa;EACX,KAAK;EACL,IAAI;EACJ,IAAI;EACL;CACD,MAAM;EAEJ,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACF;CACD,MAAM,IAAI,KAAK;EAIb,MAAM,WAAW,IAAI,QAAQ;AAK7B,MAAI,EAHF,aAAa,SAAS,aAAa,QAAQ,aAAa,SAGpC,QAAQ,IAC5B,OAAM,QAAQ,IAAI,IAAI;;CAG3B,CAAC"}
|
|
1
|
+
{"version":3,"file":"auth-BtUQnU2m.js","names":["accountType: AccountType","accountToRemove: { id: string; index: number } | undefined"],"sources":["../src/auth.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport {\n addAccountToRegistry,\n listAccountsFromRegistry,\n loadAccountToken,\n removeAccountFromRegistry,\n removeAccountToken,\n saveAccountToken,\n saveRegistry,\n} from \"./lib/accounts-registry\"\nimport { ensurePaths } from \"./lib/paths\"\nimport { state } from \"./lib/state\"\nimport {\n parseAccountType,\n type AccountMeta,\n type AccountType,\n} from \"./lib/types/account\"\nimport { getCopilotUsage } from \"./services/github/get-copilot-usage\"\nimport { getDeviceCode } from \"./services/github/get-device-code\"\nimport { getGitHubUser } from \"./services/github/get-user\"\nimport { pollAccessToken } from \"./services/github/poll-access-token\"\n\n/**\n * Fetch quota info for an account (used by auth ls -q)\n */\nasync function fetchQuotaInfo(account: AccountMeta): Promise<string> {\n try {\n const token = await loadAccountToken(account.id)\n if (!token) {\n return \" | Quota: (no token)\"\n }\n\n const usage = await getCopilotUsage({\n githubToken: token,\n accountType: account.accountType,\n })\n const premium = usage.quota_snapshots.premium_interactions\n\n return premium.unlimited ?\n \" | Quota: unlimited\"\n : ` | Quota: ${premium.remaining}/${premium.entitlement}`\n } catch (error) {\n consola.debug(`Failed to fetch quota for ${account.id}:`, error)\n return \" | Quota: (failed to fetch)\"\n }\n}\n\n/**\n * auth add - Add a new GitHub Copilot account\n */\nconst authAdd = defineCommand({\n meta: {\n name: \"add\",\n description: \"Add a new GitHub Copilot account\",\n },\n args: {\n \"account-type\": {\n alias: \"a\",\n type: \"string\",\n default: \"individual\",\n description: \"Account type (individual, business, enterprise)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub token after auth\",\n },\n },\n async run({ args }) {\n if (args.verbose) {\n consola.level = 5\n consola.info(\"Verbose logging enabled\")\n }\n\n state.showToken = args[\"show-token\"]\n\n let accountType: AccountType\n try {\n accountType = parseAccountType(args[\"account-type\"])\n } catch (error) {\n consola.error(error instanceof Error ? error.message : String(error))\n process.exit(1)\n }\n\n await ensurePaths()\n\n // Start device code flow\n consola.info(\"Starting GitHub device code authentication...\")\n const deviceResponse = await getDeviceCode()\n consola.debug(\"Device code response:\", deviceResponse)\n\n consola.info(\n `Please enter the code \"${deviceResponse.user_code}\" at ${deviceResponse.verification_uri}`,\n )\n\n // Poll for access token\n const token = await pollAccessToken(deviceResponse)\n\n if (state.showToken) {\n consola.info(\"GitHub token:\", token)\n }\n\n // Get user info to determine account ID\n const user = await getGitHubUser({ githubToken: token, accountType })\n const accountId = user.login\n\n // Save token and check if account already exists\n await saveAccountToken(accountId, token)\n const existingAccounts = await listAccountsFromRegistry()\n const alreadyExists = existingAccounts.some((acc) => acc.id === accountId)\n\n if (alreadyExists) {\n // Touch registry file so a running server can hot-reload updated tokens.\n await saveRegistry({ version: 1, accounts: existingAccounts })\n\n consola.success(\n `Account \"${accountId}\" already exists. Token has been updated.`,\n )\n } else {\n await addAccountToRegistry({\n id: accountId,\n accountType,\n addedAt: Date.now(),\n })\n consola.success(`Account \"${accountId}\" added successfully!`)\n }\n\n consola.info(`Account type: ${accountType}`)\n },\n})\n\n/**\n * auth ls - List all registered accounts\n */\nconst authLs = defineCommand({\n meta: {\n name: \"ls\",\n description: \"List all registered accounts\",\n },\n args: {\n \"show-quota\": {\n alias: \"q\",\n type: \"boolean\",\n default: false,\n description: \"Show quota information (requires API call)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n },\n async run({ args }) {\n if (args.verbose) {\n consola.level = 5\n }\n\n await ensurePaths()\n\n const accounts = await listAccountsFromRegistry()\n\n if (accounts.length === 0) {\n consola.info(\"No accounts registered. Use 'auth add' to add an account.\")\n return\n }\n\n consola.info(`Found ${accounts.length} account(s):\\n`)\n\n for (const [i, account] of accounts.entries()) {\n const addedDate = new Date(account.addedAt).toLocaleString()\n\n const quotaInfo = args[\"show-quota\"] ? await fetchQuotaInfo(account) : \"\"\n\n console.log(\n ` ${i + 1}. ${account.id} (${account.accountType})${quotaInfo}`,\n )\n console.log(` Added: ${addedDate}\\n`)\n }\n },\n})\n\n/**\n * auth rm - Remove an account\n */\nconst authRm = defineCommand({\n meta: {\n name: \"rm\",\n description: \"Remove an account\",\n },\n args: {\n target: {\n type: \"positional\",\n description: \"Account ID or index (1-based)\",\n required: true,\n },\n force: {\n alias: \"f\",\n type: \"boolean\",\n default: false,\n description: \"Skip confirmation prompt\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n },\n async run({ args }) {\n if (args.verbose) {\n consola.level = 5\n }\n\n await ensurePaths()\n\n const target = args.target\n const accounts = await listAccountsFromRegistry()\n\n if (accounts.length === 0) {\n consola.error(\"No accounts to remove.\")\n return\n }\n\n // Determine account to remove (by ID or index)\n let accountToRemove: { id: string; index: number } | undefined\n\n // Try parsing as index (1-based)\n const index = Number.parseInt(target, 10)\n if (!Number.isNaN(index) && index >= 1 && index <= accounts.length) {\n accountToRemove = { id: accounts[index - 1].id, index: index - 1 }\n } else {\n // Try finding by ID\n const foundIndex = accounts.findIndex((acc) => acc.id === target)\n if (foundIndex !== -1) {\n accountToRemove = { id: accounts[foundIndex].id, index: foundIndex }\n }\n }\n\n if (!accountToRemove) {\n consola.error(`Account \"${target}\" not found.`)\n consola.info(\"Use 'auth ls' to see available accounts.\")\n return\n }\n\n // Confirmation\n if (!args.force) {\n const confirmed = await consola.prompt(\n `Are you sure you want to remove account \"${accountToRemove.id}\"?`,\n { type: \"confirm\" },\n )\n if (!confirmed) {\n consola.info(\"Cancelled.\")\n return\n }\n }\n\n // Remove token file and registry entry\n await removeAccountToken(accountToRemove.id)\n await removeAccountFromRegistry(accountToRemove.id)\n\n consola.success(`Account \"${accountToRemove.id}\" removed.`)\n },\n})\n\n/**\n * Main auth command with subcommands\n */\nexport const auth = defineCommand({\n meta: {\n name: \"auth\",\n description: \"Manage GitHub Copilot accounts\",\n },\n subCommands: {\n add: authAdd,\n ls: authLs,\n rm: authRm,\n },\n args: {\n // Legacy args for backward compatibility (when no subcommand)\n \"account-type\": {\n alias: \"a\",\n type: \"string\",\n default: \"individual\",\n description: \"Account type (individual, business, enterprise)\",\n },\n verbose: {\n alias: \"v\",\n type: \"boolean\",\n default: false,\n description: \"Enable verbose logging\",\n },\n \"show-token\": {\n type: \"boolean\",\n default: false,\n description: \"Show GitHub token after auth\",\n },\n },\n async run(ctx) {\n // Check if a subcommand was specified in rawArgs.\n // Only treat the *first* raw arg as a subcommand to avoid false positives\n // when flags accept values like \"add\"/\"ls\"/\"rm\".\n const firstArg = ctx.rawArgs[0]\n const hasSubCommand =\n firstArg === \"add\" || firstArg === \"ls\" || firstArg === \"rm\"\n\n // Backward compatibility: if no subcommand, run 'add'\n if (!hasSubCommand && authAdd.run) {\n await authAdd.run(ctx)\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;AA6BA,eAAe,eAAe,SAAuC;AACnE,KAAI;EACF,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,GAAG;AAChD,MAAI,CAAC,MACH,QAAO;EAOT,MAAM,WAJQ,MAAM,gBAAgB;GAClC,aAAa;GACb,aAAa,QAAQ;GACtB,CAAC,EACoB,gBAAgB;AAEtC,SAAO,QAAQ,YACX,wBACA,aAAa,QAAQ,UAAU,GAAG,QAAQ;UACvC,OAAO;AACd,UAAQ,MAAM,6BAA6B,QAAQ,GAAG,IAAI,MAAM;AAChE,SAAO;;;;;;AAOX,MAAM,UAAU,cAAc;CAC5B,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,MAAM;EACJ,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACF;CACD,MAAM,IAAI,EAAE,QAAQ;AAClB,MAAI,KAAK,SAAS;AAChB,WAAQ,QAAQ;AAChB,WAAQ,KAAK,0BAA0B;;AAGzC,QAAM,YAAY,KAAK;EAEvB,IAAIA;AACJ,MAAI;AACF,iBAAc,iBAAiB,KAAK,gBAAgB;WAC7C,OAAO;AACd,WAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CAAC;AACrE,WAAQ,KAAK,EAAE;;AAGjB,QAAM,aAAa;AAGnB,UAAQ,KAAK,gDAAgD;EAC7D,MAAM,iBAAiB,MAAM,eAAe;AAC5C,UAAQ,MAAM,yBAAyB,eAAe;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M,0BAA0B,gBAAgB,GAAG;AAEnD,UAAQ,QAAQ,YAAY,gBAAgB,GAAG,YAAY;;CAE9D,CAAC;;;;AAKF,MAAa,OAAO,cAAc;CAChC,MAAM;EACJ,MAAM;EACN,aAAa;EACd;CACD,aAAa;EACX,KAAK;EACL,IAAI;EACJ,IAAI;EACL;CACD,MAAM;EAEJ,gBAAgB;GACd,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,SAAS;GACP,OAAO;GACP,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACD,cAAc;GACZ,MAAM;GACN,SAAS;GACT,aAAa;GACd;EACF;CACD,MAAM,IAAI,KAAK;EAIb,MAAM,WAAW,IAAI,QAAQ;AAK7B,MAAI,EAHF,aAAa,SAAS,aAAa,QAAQ,aAAa,SAGpC,QAAQ,IAC5B,OAAM,QAAQ,IAAI,IAAI;;CAG3B,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { r as ensurePaths, t as PATHS } from "./paths-Cvzy-eLX.js";
|
|
2
|
-
import { D as state, f as getGitHubUser, m as HTTPError, p as getCopilotUsage } from "./utils-
|
|
3
|
-
import { n as getDeviceCode, t as pollAccessToken } from "./poll-access-token-
|
|
4
|
-
import "./get-copilot-token-
|
|
2
|
+
import { D as state, f as getGitHubUser, m as HTTPError, p as getCopilotUsage } from "./utils-53JWve7i.js";
|
|
3
|
+
import { n as getDeviceCode, t as pollAccessToken } from "./poll-access-token-BrRUFB1F.js";
|
|
4
|
+
import "./get-copilot-token-DN1P6qll.js";
|
|
5
5
|
import { defineCommand } from "citty";
|
|
6
6
|
import consola from "consola";
|
|
7
7
|
import fs from "node:fs/promises";
|
|
@@ -39,6 +39,7 @@ async function setupGitHubToken(options) {
|
|
|
39
39
|
async function logUser() {
|
|
40
40
|
const user = await getGitHubUser();
|
|
41
41
|
consola.info(`Logged in as ${user.login}`);
|
|
42
|
+
state.copilotApiUrl = (await getCopilotUsage()).endpoints.api;
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
//#endregion
|
|
@@ -79,4 +80,4 @@ const checkUsage = defineCommand({
|
|
|
79
80
|
|
|
80
81
|
//#endregion
|
|
81
82
|
export { checkUsage };
|
|
82
|
-
//# sourceMappingURL=check-usage-
|
|
83
|
+
//# sourceMappingURL=check-usage-DiomC9Dl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"check-usage-DiomC9Dl.js","names":[],"sources":["../src/lib/token.ts","../src/check-usage.ts"],"sourcesContent":["import consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport { setTimeout as delay } from \"node:timers/promises\"\n\nimport { isOpencodeOauthApp } from \"~/lib/api-config\"\nimport { PATHS } from \"~/lib/paths\"\nimport { getCopilotToken } from \"~/services/github/get-copilot-token\"\nimport { getCopilotUsage } from \"~/services/github/get-copilot-usage\"\nimport { getDeviceCode } from \"~/services/github/get-device-code\"\nimport { getGitHubUser } from \"~/services/github/get-user\"\nimport { pollAccessToken } from \"~/services/github/poll-access-token\"\n\nimport { HTTPError } from \"./error\"\nimport { state } from \"./state\"\n\nlet copilotRefreshLoopController: AbortController | null = null\n\nexport const stopCopilotRefreshLoop = () => {\n if (!copilotRefreshLoopController) {\n return\n }\n\n copilotRefreshLoopController.abort()\n copilotRefreshLoopController = null\n}\n\nconst readGithubToken = () => fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n\nconst writeGithubToken = (token: string) =>\n fs.writeFile(PATHS.GITHUB_TOKEN_PATH, token)\n\nexport const setupCopilotToken = async () => {\n if (isOpencodeOauthApp()) {\n if (!state.githubToken) throw new Error(`opencode token not found`)\n\n state.copilotToken = state.githubToken\n\n consola.debug(\"GitHub Copilot token set from opencode auth token\")\n if (state.showToken) {\n consola.info(\"Copilot token:\", state.copilotToken)\n }\n\n stopCopilotRefreshLoop()\n return\n }\n\n const { token, refresh_in } = await getCopilotToken()\n state.copilotToken = token\n\n // Display the Copilot token to the screen\n consola.debug(\"GitHub Copilot Token fetched successfully!\")\n if (state.showToken) {\n consola.info(\"Copilot token:\", token)\n }\n\n stopCopilotRefreshLoop()\n\n const controller = new AbortController()\n copilotRefreshLoopController = controller\n\n runCopilotRefreshLoop(refresh_in, controller.signal)\n .catch(() => {\n consola.warn(\"Copilot token refresh loop stopped\")\n })\n .finally(() => {\n if (copilotRefreshLoopController === controller) {\n copilotRefreshLoopController = null\n }\n })\n}\n\nconst runCopilotRefreshLoop = async (\n refreshIn: number,\n signal: AbortSignal,\n) => {\n let nextRefreshDelayMs = (refreshIn - 60) * 1000\n\n while (!signal.aborted) {\n await delay(nextRefreshDelayMs, undefined, { signal })\n\n consola.debug(\"Refreshing Copilot token\")\n\n try {\n const { token, refresh_in } = await getCopilotToken()\n state.copilotToken = token\n consola.debug(\"Copilot token refreshed\")\n if (state.showToken) {\n consola.info(\"Refreshed Copilot token:\", token)\n }\n\n nextRefreshDelayMs = (refresh_in - 60) * 1000\n } catch (error) {\n consola.error(\"Failed to refresh Copilot token:\", error)\n nextRefreshDelayMs = 15_000\n consola.warn(`Retrying Copilot token refresh in ${nextRefreshDelayMs}ms`)\n }\n }\n}\n\ninterface SetupGitHubTokenOptions {\n force?: boolean\n}\n\nexport async function setupGitHubToken(\n options?: SetupGitHubTokenOptions,\n): Promise<void> {\n try {\n const githubToken = await readGithubToken()\n\n if (githubToken && !options?.force) {\n state.githubToken = githubToken\n if (state.showToken) {\n consola.info(\"GitHub token:\", githubToken)\n }\n await logUser()\n\n return\n }\n\n consola.info(\"Not logged in, getting new access token\")\n const response = await getDeviceCode()\n consola.debug(\"Device code response:\", response)\n\n consola.info(\n `Please enter the code \"${response.user_code}\" in ${response.verification_uri}`,\n )\n\n const token = await pollAccessToken(response)\n await writeGithubToken(token)\n state.githubToken = token\n\n if (state.showToken) {\n consola.info(\"GitHub token:\", token)\n }\n await logUser()\n } catch (error) {\n if (error instanceof HTTPError) {\n consola.error(\"Failed to get GitHub token:\", await error.response.json())\n throw error\n }\n\n consola.error(\"Failed to get GitHub token:\", error)\n throw error\n }\n}\n\nexport async function logUser() {\n const user = await getGitHubUser()\n consola.info(`Logged in as ${user.login}`)\n\n const copilotUser = await getCopilotUsage()\n state.copilotApiUrl = copilotUser.endpoints.api\n}\n","import { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { ensurePaths } from \"./lib/paths\"\nimport { setupGitHubToken } from \"./lib/token\"\nimport {\n getCopilotUsage,\n type QuotaDetail,\n} from \"./services/github/get-copilot-usage\"\n\nexport const checkUsage = defineCommand({\n meta: {\n name: \"check-usage\",\n description: \"Show current GitHub Copilot usage/quota information\",\n },\n async run() {\n await ensurePaths()\n await setupGitHubToken()\n try {\n const usage = await getCopilotUsage()\n const premium = usage.quota_snapshots.premium_interactions\n const premiumTotal = premium.entitlement\n const premiumUsed = premiumTotal - premium.remaining\n const premiumPercentUsed =\n premiumTotal > 0 ? (premiumUsed / premiumTotal) * 100 : 0\n const premiumPercentRemaining = premium.percent_remaining\n\n // Helper to summarize a quota snapshot\n function summarizeQuota(name: string, snap: QuotaDetail | undefined) {\n if (!snap) return `${name}: N/A`\n const total = snap.entitlement\n const used = total - snap.remaining\n const percentUsed = total > 0 ? (used / total) * 100 : 0\n const percentRemaining = snap.percent_remaining\n return `${name}: ${used}/${total} used (${percentUsed.toFixed(1)}% used, ${percentRemaining.toFixed(1)}% remaining)`\n }\n\n const premiumLine = `Premium: ${premiumUsed}/${premiumTotal} used (${premiumPercentUsed.toFixed(1)}% used, ${premiumPercentRemaining.toFixed(1)}% remaining)`\n const chatLine = summarizeQuota(\"Chat\", usage.quota_snapshots.chat)\n const completionsLine = summarizeQuota(\n \"Completions\",\n usage.quota_snapshots.completions,\n )\n\n consola.box(\n `Copilot Usage (plan: ${usage.copilot_plan})\\n`\n + `Quota resets: ${usage.quota_reset_date}\\n`\n + `\\nQuotas:\\n`\n + ` ${premiumLine}\\n`\n + ` ${chatLine}\\n`\n + ` ${completionsLine}`,\n )\n } catch (err) {\n consola.error(\"Failed to f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Q;GAC3C,MAAM,qBACJ,eAAe,IAAK,cAAc,eAAgB,MAAM;GAC1D,MAAM,0BAA0B,QAAQ;GAGxC,SAAS,eAAe,MAAc,MAA+B;AACnE,QAAI,CAAC,KAAM,QAAO,GAAG,KAAK;IAC1B,MAAM,QAAQ,KAAK;IACnB,MAAM,OAAO,QAAQ,KAAK;IAC1B,MAAM,cAAc,QAAQ,IAAK,OAAO,QAAS,MAAM;IACvD,MAAM,mBAAmB,KAAK;AAC9B,WAAO,GAAG,KAAK,IAAI,KAAK,GAAG,MAAM,SAAS,YAAY,QAAQ,EAAE,CAAC,UAAU,iBAAiB,QAAQ,EAAE,CAAC;;GAGzG,MAAM,cAAc,YAAY,YAAY,GAAG,aAAa,SAAS,mBAAmB,QAAQ,EAAE,CAAC,UAAU,wBAAwB,QAAQ,EAAE,CAAC;GAChJ,MAAM,WAAW,eAAe,QAAQ,MAAM,gBAAgB,KAAK;GACnE,MAAM,kBAAkB,eACtB,eACA,MAAM,gBAAgB,YACvB;AAED,WAAQ,IACN,wBAAwB,MAAM,aAAa,mBACtB,MAAM,iBAAiB,iBAEnC,YAAY,MACZ,SAAS,MACT,kBACV;WACM,KAAK;AACZ,WAAQ,MAAM,kCAAkC,IAAI;AACpD,WAAQ,KAAK,EAAE;;;CAGpB,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as accountFromState, m as HTTPError, v as getGitHubApiBaseUrl, x as githubHeaders } from "./utils-
|
|
1
|
+
import { E as accountFromState, m as HTTPError, v as getGitHubApiBaseUrl, x as githubHeaders } from "./utils-53JWve7i.js";
|
|
2
2
|
|
|
3
3
|
//#region src/services/github/get-copilot-token.ts
|
|
4
4
|
const getCopilotToken = async (account) => {
|
|
@@ -10,4 +10,4 @@ const getCopilotToken = async (account) => {
|
|
|
10
10
|
|
|
11
11
|
//#endregion
|
|
12
12
|
export { getCopilotToken as t };
|
|
13
|
-
//# sourceMappingURL=get-copilot-token-
|
|
13
|
+
//# sourceMappingURL=get-copilot-token-DN1P6qll.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-copilot-token-
|
|
1
|
+
{"version":3,"file":"get-copilot-token-DN1P6qll.js","names":[],"sources":["../src/services/github/get-copilot-token.ts"],"sourcesContent":["import type { AccountContext } from \"~/lib/types/account\"\n\nimport { getGitHubApiBaseUrl, githubHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { accountFromState } from \"~/lib/state\"\n\nexport const getCopilotToken = async (account?: AccountContext) => {\n const ctx = account ?? accountFromState()\n const response = await fetch(\n `${getGitHubApiBaseUrl()}/copilot_internal/v2/token`,\n {\n headers: githubHeaders(ctx),\n },\n )\n\n if (!response.ok) throw new HTTPError(\"Failed to get Copilot token\", response)\n\n return (await response.json()) as GetCopilotTokenResponse\n}\n\n// Trimmed for the sake of simplicity\nexport interface GetCopilotTokenResponse {\n expires_at: number\n refresh_in: number\n token: string\n}\n"],"mappings":";;;AAMA,MAAa,kBAAkB,OAAO,YAA6B;CACjE,MAAM,MAAM,WAAW,kBAAkB;CACzC,MAAM,WAAW,MAAM,MACrB,GAAG,qBAAqB,CAAC,6BACzB,EACE,SAAS,cAAc,IAAI,EAC5B,CACF;AAED,KAAI,CAAC,SAAS,GAAI,OAAM,IAAI,UAAU,+BAA+B,SAAS;AAE9E,QAAQ,MAAM,SAAS,MAAM"}
|
package/dist/main.js
CHANGED
|
@@ -20,10 +20,10 @@ const args = parseArgs(process.argv, cliArgs);
|
|
|
20
20
|
if (typeof args["api-home"] === "string") process.env.COPILOT_API_HOME = args["api-home"];
|
|
21
21
|
if (typeof args["oauth-app"] === "string") process.env.COPILOT_API_OAUTH_APP = args["oauth-app"];
|
|
22
22
|
if (typeof args["enterprise-url"] === "string") process.env.COPILOT_API_ENTERPRISE_URL = args["enterprise-url"];
|
|
23
|
-
const { auth } = await import("./auth-
|
|
24
|
-
const { checkUsage } = await import("./check-usage-
|
|
23
|
+
const { auth } = await import("./auth-BtUQnU2m.js");
|
|
24
|
+
const { checkUsage } = await import("./check-usage-DiomC9Dl.js");
|
|
25
25
|
const { debug } = await import("./debug-BzR5ZQUk.js");
|
|
26
|
-
const { start } = await import("./start-
|
|
26
|
+
const { start } = await import("./start-D3yEfZnW.js");
|
|
27
27
|
await runMain(defineCommand({
|
|
28
28
|
meta: {
|
|
29
29
|
name: "copilot-api",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as getOauthUrls, m as HTTPError, u as sleep, y as getOauthAppConfig } from "./utils-
|
|
1
|
+
import { b as getOauthUrls, m as HTTPError, u as sleep, y as getOauthAppConfig } from "./utils-53JWve7i.js";
|
|
2
2
|
import consola from "consola";
|
|
3
3
|
|
|
4
4
|
//#region src/services/github/get-device-code.ts
|
|
@@ -49,4 +49,4 @@ async function pollAccessToken(deviceCode) {
|
|
|
49
49
|
|
|
50
50
|
//#endregion
|
|
51
51
|
export { getDeviceCode as n, pollAccessToken as t };
|
|
52
|
-
//# sourceMappingURL=poll-access-token-
|
|
52
|
+
//# sourceMappingURL=poll-access-token-BrRUFB1F.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"poll-access-token-
|
|
1
|
+
{"version":3,"file":"poll-access-token-BrRUFB1F.js","names":[],"sources":["../src/services/github/get-device-code.ts","../src/services/github/poll-access-token.ts"],"sourcesContent":["import { getOauthAppConfig, getOauthUrls } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\n\nexport async function getDeviceCode(): Promise<DeviceCodeResponse> {\n const { clientId, headers, scope } = getOauthAppConfig()\n const { deviceCodeUrl } = getOauthUrls()\n\n const response = await fetch(deviceCodeUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n client_id: clientId,\n scope,\n }),\n })\n\n if (!response.ok) throw new HTTPError(\"Failed to get device code\", response)\n\n return (await response.json()) as DeviceCodeResponse\n}\n\nexport interface DeviceCodeResponse {\n device_code: string\n user_code: string\n verification_uri: string\n expires_in: number\n interval: number\n}\n","import consola from \"consola\"\n\nimport { getOauthAppConfig, getOauthUrls } from \"~/lib/api-config\"\nimport { sleep } from \"~/lib/utils\"\n\nimport type { DeviceCodeResponse } from \"./get-device-code\"\n\nexport async function pollAccessToken(\n deviceCode: DeviceCodeResponse,\n): Promise<string> {\n const { clientId, headers } = getOauthAppConfig()\n const { accessTokenUrl } = getOauthUrls()\n\n // Interval is in seconds, we need to multiply by 1000 to get milliseconds\n // I'm also adding another second, just to be safe\n const sleepDuration = (deviceCode.interval + 1) * 1000\n consola.debug(`Polling access token with interval of ${sleepDuration}ms`)\n\n while (true) {\n const response = await fetch(accessTokenUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n client_id: clientId,\n device_code: deviceCode.device_code,\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n }),\n })\n\n if (!response.ok) {\n await sleep(sleepDuration)\n consola.error(\"Failed to poll access token:\", await response.text())\n\n continue\n }\n\n const json = await response.json()\n consola.debug(\"Polling access token response:\", json)\n\n const { access_token } = json as AccessTokenResponse\n\n if (access_token) {\n return access_token\n } else {\n await sleep(sleepDuration)\n }\n }\n}\n\ninterface AccessTokenResponse {\n access_token: string\n token_type: string\n scope: string\n}\n"],"mappings":";;;;AAGA,eAAsB,gBAA6C;CACjE,MAAM,EAAE,UAAU,SAAS,UAAU,mBAAmB;CACxD,MAAM,EAAE,kBAAkB,cAAc;CAExC,MAAM,WAAW,MAAM,MAAM,eAAe;EAC1C,QAAQ;EACR;EACA,MAAM,KAAK,UAAU;GACnB,WAAW;GACX;GACD,CAAC;EACH,CAAC;AAEF,KAAI,CAAC,SAAS,GAAI,OAAM,IAAI,UAAU,6BAA6B,SAAS;AAE5E,QAAQ,MAAM,SAAS,MAAM;;;;;ACX/B,eAAsB,gBACpB,YACiB;CACjB,MAAM,EAAE,UAAU,YAAY,mBAAmB;CACjD,MAAM,EAAE,mBAAmB,cAAc;CAIzC,MAAM,iBAAiB,WAAW,WAAW,KAAK;AAClD,SAAQ,MAAM,yCAAyC,cAAc,IAAI;AAEzE,QAAO,MAAM;EACX,MAAM,WAAW,MAAM,MAAM,gBAAgB;GAC3C,QAAQ;GACR;GACA,MAAM,KAAK,UAAU;IACnB,WAAW;IACX,aAAa,WAAW;IACxB,YAAY;IACb,CAAC;GACH,CAAC;AAEF,MAAI,CAAC,SAAS,IAAI;AAChB,SAAM,MAAM,cAAc;AAC1B,WAAQ,MAAM,gCAAgC,MAAM,SAAS,MAAM,CAAC;AAEpE;;EAGF,MAAM,OAAO,MAAM,SAAS,MAAM;AAClC,UAAQ,MAAM,kCAAkC,KAAK;EAErD,MAAM,EAAE,iBAAiB;AAEzB,MAAI,aACF,QAAO;MAEP,OAAM,MAAM,cAAc"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as PATHS } from "./paths-Cvzy-eLX.js";
|
|
2
2
|
import { i as listAccountsFromRegistry } from "./accounts-registry-CQYvRe65.js";
|
|
3
|
-
import { C as prepareInteractionHeaders, D as state, E as accountFromState, S as prepareForCompact, T as resolveTraceId, _ as copilotHeaders, a as generateRequestIdFromPayload, c as isNullish, g as copilotBaseUrl, h as forwardError, l as parseUserIdMetadata, m as HTTPError, n as cacheModels, o as getRootSessionId, p as getCopilotUsage, s as getUUID, u as sleep, w as requestContext } from "./utils-
|
|
4
|
-
import "./get-copilot-token-
|
|
5
|
-
import { _ as isMessagesApiEnabled, a as getClaudeTokenMultiplier, b as mergeConfigWithDefaults, c as getModelAliases, d as getProviderConfig, f as getReasoningEffortForModel, g as isMessageStartInputTokensFallbackEnabled, h as isForceAgentEnabled, i as getAnthropicApiKey, l as getModelAliasesInfo, m as isAccountAffinityEnabled, n as PROVIDER_TYPE_ANTHROPIC, o as getConfig, p as getSmallModel, r as getAliasTargetSet, s as getExtraPromptForModel, t as accountsManager, u as getModelRefreshIntervalMs, v as isResponsesApiContextManagementModel, x as shouldCompactUseSmallModel, y as isResponsesApiWebSearchEnabled } from "./accounts-manager-
|
|
3
|
+
import { C as prepareInteractionHeaders, D as state, E as accountFromState, S as prepareForCompact, T as resolveTraceId, _ as copilotHeaders, a as generateRequestIdFromPayload, c as isNullish, g as copilotBaseUrl, h as forwardError, l as parseUserIdMetadata, m as HTTPError, n as cacheModels, o as getRootSessionId, p as getCopilotUsage, s as getUUID, u as sleep, w as requestContext } from "./utils-53JWve7i.js";
|
|
4
|
+
import "./get-copilot-token-DN1P6qll.js";
|
|
5
|
+
import { _ as isMessagesApiEnabled, a as getClaudeTokenMultiplier, b as mergeConfigWithDefaults, c as getModelAliases, d as getProviderConfig, f as getReasoningEffortForModel, g as isMessageStartInputTokensFallbackEnabled, h as isForceAgentEnabled, i as getAnthropicApiKey, l as getModelAliasesInfo, m as isAccountAffinityEnabled, n as PROVIDER_TYPE_ANTHROPIC, o as getConfig, p as getSmallModel, r as getAliasTargetSet, s as getExtraPromptForModel, t as accountsManager, u as getModelRefreshIntervalMs, v as isResponsesApiContextManagementModel, x as shouldCompactUseSmallModel, y as isResponsesApiWebSearchEnabled } from "./accounts-manager-DhwGrhHF.js";
|
|
6
6
|
import consola from "consola";
|
|
7
7
|
import fs, { readFile } from "node:fs/promises";
|
|
8
8
|
import * as path$1 from "node:path";
|
|
@@ -2055,6 +2055,7 @@ function toAccountContext(account) {
|
|
|
2055
2055
|
return {
|
|
2056
2056
|
githubToken: account.githubToken,
|
|
2057
2057
|
copilotToken: account.copilotToken,
|
|
2058
|
+
...account.copilotApiUrl !== void 0 ? { copilotApiUrl: account.copilotApiUrl } : {},
|
|
2058
2059
|
accountType: account.accountType,
|
|
2059
2060
|
vsCodeVersion: account.vsCodeVersion
|
|
2060
2061
|
};
|
|
@@ -3255,19 +3256,26 @@ const maybeBlockOriginalModelName = (context) => {
|
|
|
3255
3256
|
});
|
|
3256
3257
|
};
|
|
3257
3258
|
const compactSystemPromptStart = "You are a helpful AI assistant tasked with summarizing conversations";
|
|
3258
|
-
const
|
|
3259
|
-
const
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
if (
|
|
3263
|
-
if (
|
|
3264
|
-
return
|
|
3259
|
+
const compactTextOnlyGuard = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.";
|
|
3260
|
+
const compactSummaryPromptStart = "Your task is to create a detailed summary of the conversation so far";
|
|
3261
|
+
const compactMessageSections = ["Pending Tasks:", "Current Work:"];
|
|
3262
|
+
const getCompactCandidateText = (message) => {
|
|
3263
|
+
if (message.role !== "user") return "";
|
|
3264
|
+
if (typeof message.content === "string") return message.content;
|
|
3265
|
+
return message.content.filter((block) => block.type === "text").map((block) => block.text.startsWith("<system-reminder>") ? "" : block.text).filter((text) => text.length > 0).join("\n\n");
|
|
3266
|
+
};
|
|
3267
|
+
const isCompactMessage = (lastMessage) => {
|
|
3268
|
+
const text = getCompactCandidateText(lastMessage);
|
|
3269
|
+
if (!text) return false;
|
|
3270
|
+
return text.includes(compactTextOnlyGuard) && text.includes(compactSummaryPromptStart) && compactMessageSections.some((section) => text.includes(section));
|
|
3265
3271
|
};
|
|
3266
3272
|
const isCompactRequest = (anthropicPayload) => {
|
|
3273
|
+
const lastMessage = anthropicPayload.messages.at(-1);
|
|
3274
|
+
if (lastMessage && isCompactMessage(lastMessage)) return true;
|
|
3267
3275
|
const system = anthropicPayload.system;
|
|
3268
3276
|
if (typeof system === "string" && system.startsWith(compactSystemPromptStart)) return true;
|
|
3269
3277
|
if (Array.isArray(system) && system.some((msg) => typeof msg.text === "string" && msg.text.startsWith(compactSystemPromptStart))) return true;
|
|
3270
|
-
return
|
|
3278
|
+
return false;
|
|
3271
3279
|
};
|
|
3272
3280
|
|
|
3273
3281
|
//#endregion
|
|
@@ -3600,7 +3608,7 @@ const translateAnthropicMessagesToResponsesPayload = (payload, modelOverride) =>
|
|
|
3600
3608
|
for (const message of payload.messages) input.push(...translateMessage(message, payload.model, applyPhase));
|
|
3601
3609
|
const translatedTools = convertAnthropicTools(payload.tools);
|
|
3602
3610
|
const toolChoice = convertAnthropicToolChoice(payload.tool_choice);
|
|
3603
|
-
const {
|
|
3611
|
+
const { sessionId: promptCacheKey } = parseUserIdMetadata(payload.metadata?.user_id);
|
|
3604
3612
|
return {
|
|
3605
3613
|
model,
|
|
3606
3614
|
input,
|
|
@@ -3611,7 +3619,6 @@ const translateAnthropicMessagesToResponsesPayload = (payload, modelOverride) =>
|
|
|
3611
3619
|
tools: translatedTools,
|
|
3612
3620
|
tool_choice: toolChoice,
|
|
3613
3621
|
metadata: payload.metadata ? { ...payload.metadata } : null,
|
|
3614
|
-
safety_identifier: safetyIdentifier,
|
|
3615
3622
|
prompt_cache_key: promptCacheKey,
|
|
3616
3623
|
stream: payload.stream ?? null,
|
|
3617
3624
|
store: false,
|
|
@@ -3803,7 +3810,7 @@ const translateSystemPrompt = (system, model) => {
|
|
|
3803
3810
|
const extraPrompt = getExtraPromptForModel(model);
|
|
3804
3811
|
if (typeof system === "string") return system + extraPrompt;
|
|
3805
3812
|
const text = system.map((block, index) => {
|
|
3806
|
-
if (index === 0) return block.text + extraPrompt;
|
|
3813
|
+
if (index === 0) return block.text + "\n\n" + extraPrompt + "\n\n";
|
|
3807
3814
|
return block.text;
|
|
3808
3815
|
}).join(" ");
|
|
3809
3816
|
return text.length > 0 ? text : null;
|
|
@@ -6469,4 +6476,4 @@ server.route("/:provider/v1/models", providerModelRoutes);
|
|
|
6469
6476
|
|
|
6470
6477
|
//#endregion
|
|
6471
6478
|
export { server };
|
|
6472
|
-
//# sourceMappingURL=server-
|
|
6479
|
+
//# sourceMappingURL=server-D9M_wFyO.js.map
|