@nick3/copilot-api 1.3.1 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +59 -32
  2. package/dist/account-DhQb2A6q.js +17 -0
  3. package/dist/account-DhQb2A6q.js.map +1 -0
  4. package/dist/{accounts-manager-BeKvbv0T.js → accounts-manager-DjGzZIcp.js} +23 -567
  5. package/dist/accounts-manager-DjGzZIcp.js.map +1 -0
  6. package/dist/accounts-registry-c7rs5Ed9.js +180 -0
  7. package/dist/accounts-registry-c7rs5Ed9.js.map +1 -0
  8. package/dist/admin/assets/index-BB9SaCFS.js +57 -0
  9. package/dist/admin/assets/{index-D-pIr-q0.css → index-CvffOmW7.css} +1 -1
  10. package/dist/admin/index.html +2 -2
  11. package/dist/auth-CYJuRbDb.js +241 -0
  12. package/dist/auth-CYJuRbDb.js.map +1 -0
  13. package/dist/check-usage-CVF7i8yX.js +82 -0
  14. package/dist/check-usage-CVF7i8yX.js.map +1 -0
  15. package/dist/debug-hQJWwXtC.js +82 -0
  16. package/dist/debug-hQJWwXtC.js.map +1 -0
  17. package/dist/get-copilot-token-BwP_PxV5.js +13 -0
  18. package/dist/get-copilot-token-BwP_PxV5.js.map +1 -0
  19. package/dist/main.js +25 -735
  20. package/dist/main.js.map +1 -1
  21. package/dist/paths-DoT4SZ8f.js +49 -0
  22. package/dist/paths-DoT4SZ8f.js.map +1 -0
  23. package/dist/poll-access-token-CN92flJy.js +52 -0
  24. package/dist/poll-access-token-CN92flJy.js.map +1 -0
  25. package/dist/{server-D3A61KAx.js → server-CM_0PrbK.js} +197 -21
  26. package/dist/server-CM_0PrbK.js.map +1 -0
  27. package/dist/start-KYMwXUvr.js +302 -0
  28. package/dist/start-KYMwXUvr.js.map +1 -0
  29. package/dist/utils-BUJfM1V2.js +335 -0
  30. package/dist/utils-BUJfM1V2.js.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/accounts-manager-BeKvbv0T.js.map +0 -1
  33. package/dist/admin/assets/index-C9gbhsHu.js +0 -56
  34. package/dist/server-D3A61KAx.js.map +0 -1
package/README.md CHANGED
@@ -52,9 +52,9 @@ Compared with routing everything through plain Chat Completions compatibility, t
52
52
  - **Flexible Authentication**: Authenticate interactively or provide a GitHub token directly, suitable for CI/CD environments.
53
53
  - **Support for Different Account Types**: Works with individual, business, and enterprise GitHub Copilot plans.
54
54
  - **Multi-Account Support**: Use multiple GitHub Copilot accounts with automatic routing: premium models use accounts in order and fall back on quota exhaustion; free models are distributed round-robin across accounts by default (configurable in config.json).
55
- - **Opencode OAuth Support**: Use opencode GitHub Copilot authentication by setting `COPILOT_API_OAUTH_APP=opencode` environment variable.
56
- - **GitHub Enterprise Support**: Connect to GHE.com by setting `COPILOT_API_ENTERPRISE_URL` environment variable (e.g., `company.ghe.com`).
57
- - **Custom Data Directory**: Change the default data directory (where tokens and config are stored) by setting `COPILOT_API_HOME` environment variable.
55
+ - **Opencode OAuth Support**: Use opencode GitHub Copilot authentication by setting `COPILOT_API_OAUTH_APP=opencode` environment variable or using `--oauth-app=opencode` command line option.
56
+ - **GitHub Enterprise Support**: Connect to GHE.com by setting `COPILOT_API_ENTERPRISE_URL` environment variable (e.g., `company.ghe.com`) or using `--enterprise-url=company.ghe.com` command line option.
57
+ - **Custom Data Directory**: Change the default data directory (where tokens and config are stored) by setting `COPILOT_API_HOME` environment variable or using `--api-home=/path/to/dir` command line option.
58
58
  - **Multi-Provider Anthropic Proxy Routes**: Add global provider configs and call external Anthropic-compatible APIs via `/:provider/v1/messages` and `/:provider/v1/models`.
59
59
 
60
60
  ## Better Agent Semantics
@@ -237,6 +237,16 @@ Copilot API now uses a subcommand structure with these main commands:
237
237
 
238
238
  ## Command Line Options
239
239
 
240
+ ### Global Options
241
+
242
+ The following options can be used with any subcommand. When passing them before the subcommand, use the `--key=value` form:
243
+
244
+ | Option | Description | Default | Alias |
245
+ | ----------------- | ------------------------------------------------------ | ------- | ----- |
246
+ | --api-home | Path to the API home directory (sets COPILOT_API_HOME) | none | none |
247
+ | --oauth-app | OAuth app identifier (sets COPILOT_API_OAUTH_APP) | none | none |
248
+ | --enterprise-url | Enterprise URL for GitHub (sets COPILOT_API_ENTERPRISE_URL) | none | none |
249
+
240
250
  ### Start Command Options
241
251
 
242
252
  The following command line options are available for the `start` command:
@@ -315,14 +325,15 @@ The `<target>` can be either the account ID (GitHub username) or a 1-based index
315
325
  "gpt-5-mini": "<built-in exploration prompt>",
316
326
  "gpt-5.3-codex": "<built-in commentary prompt>",
317
327
  "gpt-5.4": "<built-in commentary prompt>"
318
- },
319
- "smallModel": "gpt-5-mini",
320
- "freeModelLoadBalancing": true,
321
- "responsesApiContextManagementModels": [],
322
- "modelReasoningEfforts": {
323
- "gpt-5-mini": "low",
324
- "gpt-5.3-codex": "xhigh",
325
- "gpt-5.4": "xhigh"
328
+ "useMessagesApi": true
329
+ },
330
+ "smallModel": "gpt-5-mini",
331
+ "freeModelLoadBalancing": true,
332
+ "responsesApiContextManagementModels": [],
333
+ "modelReasoningEfforts": {
334
+ "gpt-5-mini": "low",
335
+ "gpt-5.3-codex": "xhigh",
336
+ "gpt-5.4": "xhigh"
326
337
  },
327
338
  "modelAliases": {
328
339
  "fast": { "target": "gpt-5-mini", "allowOriginal": false },
@@ -331,29 +342,31 @@ The `<target>` can be either the account ID (GitHub username) or a 1-based index
331
342
  "allowOriginalModelNamesForAliases": false,
332
343
  "useFunctionApplyPatch": true,
333
344
  "forceAgent": false,
334
- "compactUseSmallModel": true
345
+ "compactUseSmallModel": true,
346
+ "useMessagesApi": true
335
347
  }
336
348
  ```
337
349
  - **auth.apiKeys:** API keys used for request authentication. Supports multiple keys for rotation. Requests can authenticate with either `x-api-key: <key>` or `Authorization: Bearer <key>`. If empty or omitted, authentication is disabled.
338
- - **extraPrompts:** Map of `model -> prompt` appended to the first system prompt when translating Anthropic-style requests to Copilot. Use this to inject guardrails or guidance per model. Missing default entries are auto-added without overwriting your custom prompts. The built-in prompts for `gpt-5.3-codex` and `gpt-5.4` enable phase-aware commentary, which lets the model emit a short user-facing progress update before tools or deeper reasoning.
339
- - **providers:** Global upstream provider map. Each provider key (for example `custom`) becomes a route prefix (`/custom/v1/messages`). Currently only `type: "anthropic"` is supported.
340
- - `enabled` defaults to `true` if omitted.
341
- - `baseUrl` should be provider API base URL without trailing `/v1/messages`.
342
- - `apiKey` is used as upstream `x-api-key`.
343
- - `models` (optional): Per-model configuration map. Each key is a model ID (matching the model name in requests), and the value is:
344
- - `temperature` (optional): Default temperature value used when the request does not specify one.
345
- - `topP` (optional): Default top_p value used when the request does not specify one.
346
- - `topK` (optional): Default top_k value used when the request does not specify one.
347
- - **responsesApiContextManagementModels:** List of model IDs that should receive Responses API `context_management` compaction instructions. Use this when a model supports server-side context management and you want the proxy to keep only the latest compaction carrier on follow-up turns.
348
- - **smallModel:** Fallback model used for tool-less warmup messages, compact/background requests, and other short housekeeping turns (for example from Claude Code or OpenCode) to avoid spending premium requests; defaults to `gpt-5-mini`. If original names are blocked and this points to an aliased target, it resolves to the preferred alias.
349
- - **freeModelLoadBalancing:** Enable round-robin routing for free-model requests across multiple accounts. Defaults to `true`. Set to `false` to route free-model requests sequentially (same ordering strategy as premium models).
350
- - **apiKey (deprecated):** Legacy single-key field kept for migration compatibility. Prefer `auth.apiKeys`. When `auth.apiKeys` is empty, the server falls back to `COPILOT_API_KEY` and then `apiKey`.
351
- - **modelReasoningEfforts:** Per-model `reasoning.effort` sent to the Copilot Responses API. Allowed values are `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. If a model isn’t listed, `high` is used by default.
352
- - **modelAliases:** Map of `alias -> { target, allowOriginal? }` (legacy string values are still accepted). Alias keys are normalized (trim + lowercase) and must be non-empty; aliases cannot map to themselves (case-insensitive), and conflicting normalized aliases are rejected. `allowOriginal` overrides the global default per alias. If multiple aliases map to the same target, original names are allowed when any alias sets `allowOriginal: true` (allow-wins). Admin UI/API rejects blocked keys (`__proto__`, `constructor`, `prototype`). Aliases can be used in downstream requests.
353
- - **allowOriginalModelNamesForAliases:** Global default for aliases that omit `allowOriginal`. When `false` (default), targets are blocked unless an alias explicitly allows them; when `true`, targets are allowed unless all aliases explicitly block them.
350
+ - **extraPrompts:** Map of `model -> prompt` appended to the first system prompt when translating Anthropic-style requests to Copilot. Use this to inject guardrails or guidance per model. Missing default entries are auto-added without overwriting your custom prompts. The built-in prompts for `gpt-5.3-codex` and `gpt-5.4` enable phase-aware commentary, which lets the model emit a short user-facing progress update before tools or deeper reasoning.
351
+ - **providers:** Global upstream provider map. Each provider key (for example `custom`) becomes a route prefix (`/custom/v1/messages`). Currently only `type: "anthropic"` is supported.
352
+ - `enabled` defaults to `true` if omitted.
353
+ - `baseUrl` should be provider API base URL without trailing `/v1/messages`.
354
+ - `apiKey` is used as upstream `x-api-key`.
355
+ - `models` (optional): Per-model configuration map. Each key is a model ID (matching the model name in requests), and the value is:
356
+ - `temperature` (optional): Default temperature value used when the request does not specify one.
357
+ - `topP` (optional): Default top_p value used when the request does not specify one.
358
+ - `topK` (optional): Default top_k value used when the request does not specify one.
359
+ - **responsesApiContextManagementModels:** List of model IDs that should receive Responses API `context_management` compaction instructions. Use this when a model supports server-side context management and you want the proxy to keep only the latest compaction carrier on follow-up turns.
360
+ - **smallModel:** Fallback model used for tool-less warmup messages, compact/background requests, and other short housekeeping turns (for example from Claude Code or OpenCode) to avoid spending premium requests; defaults to `gpt-5-mini`. If original names are blocked and this points to an aliased target, it resolves to the preferred alias.
361
+ - **freeModelLoadBalancing:** Enable round-robin routing for free-model requests across multiple accounts. Defaults to `true`. Set to `false` to route free-model requests sequentially (same ordering strategy as premium models).
362
+ - **apiKey (deprecated):** Legacy single-key field kept for migration compatibility. Prefer `auth.apiKeys`. When `auth.apiKeys` is empty, the server falls back to `COPILOT_API_KEY` and then `apiKey`.
363
+ - **modelReasoningEfforts:** Per-model `reasoning.effort` sent to the Copilot Responses API. Allowed values are `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. If a model isn’t listed, `high` is used by default.
364
+ - **modelAliases:** Map of `alias -> { target, allowOriginal? }` (legacy string values are still accepted). Alias keys are normalized (trim + lowercase) and must be non-empty; aliases cannot map to themselves (case-insensitive), and conflicting normalized aliases are rejected. `allowOriginal` overrides the global default per alias. If multiple aliases map to the same target, original names are allowed when any alias sets `allowOriginal: true` (allow-wins). Admin UI/API rejects blocked keys (`__proto__`, `constructor`, `prototype`). Aliases can be used in downstream requests.
365
+ - **allowOriginalModelNamesForAliases:** Global default for aliases that omit `allowOriginal`. When `false` (default), targets are blocked unless an alias explicitly allows them; when `true`, targets are allowed unless all aliases explicitly block them.
354
366
  - **useFunctionApplyPatch:** When `true` (default), `POST /v1/responses` converts a `tools` entry with `{ "type": "custom", "name": "apply_patch" }` into an OpenAI-style `function` tool (with a parameter schema) for upstream compatibility. Set to `false` to leave custom tools untouched.
355
367
  - **forceAgent:** When `true`, `POST /v1/responses` treats a request as agent-initiated if **any** input item has `role: "assistant"`. When `false` (default), only the **last** input item is checked.
356
368
  - **compactUseSmallModel:** When `true`, detected "compact" requests (e.g., from Claude Code or opencode compact mode) will automatically use the configured `smallModel` to avoid consuming premium usage for short/background tasks. Defaults to `true`.
369
+ - **useMessagesApi:** When `true` (default), Claude-family models that support Copilot's native `/v1/messages` endpoint may use the Messages API path. Set to `false` to skip the Messages API candidate and fall back to `/responses` (if supported) or `/chat/completions`.
357
370
 
358
371
  Edit this file to customize prompts or swap in your own fast model. If you edit it manually, restart the server (or call `GET /api/admin/config`) so the cached config is refreshed. Changes made through the Admin UI/API are validated, written to disk, and applied immediately; unknown keys are rejected.
359
372
 
@@ -530,6 +543,18 @@ npx @nick3/copilot-api@latest start --proxy-env
530
543
 
531
544
  # Use opencode GitHub Copilot authentication
532
545
  COPILOT_API_OAUTH_APP=opencode npx @nick3/copilot-api@latest start
546
+
547
+ # Set custom API home directory via command line
548
+ npx @nick3/copilot-api@latest --api-home=/path/to/custom/dir start
549
+
550
+ # Use GitHub Enterprise via command line
551
+ npx @nick3/copilot-api@latest --enterprise-url=company.ghe.com start
552
+
553
+ # Use opencode OAuth via command line
554
+ npx @nick3/copilot-api@latest --oauth-app=opencode start
555
+
556
+ # Combine multiple global options
557
+ npx @nick3/copilot-api@latest --api-home=/custom/path --oauth-app=opencode --enterprise-url=company.ghe.com start
533
558
  ```
534
559
 
535
560
  ### Opencode OAuth Authentication
@@ -757,12 +782,14 @@ Here is an example `.claude/settings.json` file:
757
782
  }
758
783
  ```
759
784
 
760
- ### CLAUDE.md / AGENTS.md (Optional)
785
+ ### CLAUDE.md or AGENTS.md Recommended Content
761
786
 
762
- If you're using Claude Code (or another agent runner) and want stricter “ask before acting” behavior, you may choose to add rules like:
787
+ Please include the following in `CLAUDE.md` or `AGENTS.md`:
763
788
 
764
- - Prefer using the runner's dedicated question tool for user-facing questions.
765
- - Ask the user to confirm completion before ending the task.
789
+ ```
790
+ - Prohibited from directly asking questions to users, MUST use question tool.
791
+ - Once you can confirm that the task is complete, MUST use question tool to make user confirm. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again, after try again, MUST use question tool to make user confirm again.
792
+ ```
766
793
 
767
794
  You can find more options here: [Claude Code settings](https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables)
768
795
 
@@ -0,0 +1,17 @@
1
+ //#region src/lib/types/account.ts
2
+ const ACCOUNT_TYPE_VALUES = [
3
+ "individual",
4
+ "business",
5
+ "enterprise"
6
+ ];
7
+ function isAccountType(value) {
8
+ return typeof value === "string" && ACCOUNT_TYPE_VALUES.includes(value);
9
+ }
10
+ function parseAccountType(value) {
11
+ if (!isAccountType(value)) throw new Error(`Invalid account type: ${String(value)}. Valid values: ${ACCOUNT_TYPE_VALUES.join(", ")}`);
12
+ return value;
13
+ }
14
+
15
+ //#endregion
16
+ export { parseAccountType };
17
+ //# sourceMappingURL=account-DhQb2A6q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-DhQb2A6q.js","names":["ACCOUNT_TYPE_VALUES: ReadonlyArray<AccountType>"],"sources":["../src/lib/types/account.ts"],"sourcesContent":["import type { ModelsResponse } from \"~/services/copilot/get-models\"\n\n/**\n * Account type for GitHub Copilot subscription.\n */\nexport type AccountType = \"individual\" | \"business\" | \"enterprise\"\n\nexport const ACCOUNT_TYPE_VALUES: ReadonlyArray<AccountType> = [\n \"individual\",\n \"business\",\n \"enterprise\",\n]\n\nexport function isAccountType(value: unknown): value is AccountType {\n return (\n typeof value === \"string\"\n && (ACCOUNT_TYPE_VALUES as ReadonlyArray<string>).includes(value)\n )\n}\n\nexport function parseAccountType(value: unknown): AccountType {\n if (!isAccountType(value)) {\n throw new Error(\n `Invalid account type: ${String(value)}. Valid values: ${ACCOUNT_TYPE_VALUES.join(\n \", \",\n )}`,\n )\n }\n return value\n}\n\n/**\n * Metadata for a registered account, stored in the registry file.\n */\nexport interface AccountMeta {\n /** GitHub login (username) */\n id: string\n /** Account subscription type */\n accountType: AccountType\n /** Timestamp when the account was added */\n addedAt: number\n}\n\n/**\n * Registry file structure for storing account metadata.\n */\nexport interface AccountRegistry {\n /** Schema version for future migrations */\n version: 1\n /** Ordered list of accounts (order = priority) */\n accounts: Array<AccountMeta>\n}\n\n/**\n * Runtime state for an account, including tokens and quota information.\n */\nexport interface AccountRuntime extends AccountMeta {\n /** GitHub personal access token */\n githubToken: string\n /** Copilot API token (obtained from GitHub) */\n copilotToken?: string\n /** VS Code version for API headers */\n vsCodeVersion?: string\n /** Cached available models for this account */\n models?: ModelsResponse\n /** Timestamp of last models fetch */\n lastModelsFetch?: number\n /** Whether models refresh is in progress */\n isRefreshingModels?: boolean\n /** Promise for an in-flight models refresh */\n modelsRefreshPromise?: Promise<void>\n /** Total premium interactions quota entitlement */\n premiumEntitlement?: number\n /** Remaining premium interactions quota */\n premiumRemaining?: number\n /** Reserved premium interaction units for in-flight requests */\n premiumReserved?: number\n /** Internal reservation map for idempotent release */\n premiumReservations?: Map<symbol, number>\n /** Whether this account has unlimited quota */\n unlimited?: boolean\n /** Whether this account allows overage billing (enterprise feature) */\n overagePermitted?: boolean\n /** Timestamp of last quota fetch */\n lastQuotaFetch?: number\n /** Token refresh timer reference */\n refreshTimer?: ReturnType<typeof setInterval>\n /** Whether this account has failed (e.g., 401 error) */\n failed?: boolean\n /** Failure reason if failed */\n failureReason?: string\n /** Whether quota refresh is in progress (prevents concurrent refreshes) */\n isRefreshingQuota?: boolean\n /** Promise for an in-flight quota refresh (allows concurrent callers to await the same refresh) */\n quotaRefreshPromise?: Promise<void>\n}\n\n/**\n * Context required for making API calls on behalf of an account.\n * This is a subset of AccountRuntime used by service functions.\n */\nexport interface AccountContext {\n /** GitHub personal access token */\n githubToken: string\n /** Copilot API token */\n copilotToken?: string\n /** Account subscription type */\n accountType: AccountType\n /** VS Code version for API headers */\n vsCodeVersion?: string\n}\n"],"mappings":";AAOA,MAAaA,sBAAkD;CAC7D;CACA;CACA;CACD;AAED,SAAgB,cAAc,OAAsC;AAClE,QACE,OAAO,UAAU,YACb,oBAA8C,SAAS,MAAM;;AAIrE,SAAgB,iBAAiB,OAA6B;AAC5D,KAAI,CAAC,cAAc,MAAM,CACvB,OAAM,IAAI,MACR,yBAAyB,OAAO,MAAM,CAAC,kBAAkB,oBAAoB,KAC3E,KACD,GACF;AAEH,QAAO"}