@bitkyc08/opencodex 2.99.0 → 2.100.1
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/AGENTS_INSTALL.md +19 -1
- package/README.md +37 -33
- package/SPONSORS.md +5 -1
- package/bin/ocx.mjs +1 -1
- package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
- package/gui/dist/assets/App-g3Cm2xhZ.js +59 -0
- package/gui/dist/assets/Tray-BMDkAiXy.js +1 -0
- package/gui/dist/assets/brand-mark-nr3ziR-T.js +1 -0
- package/gui/dist/assets/index-Bziu8gTy.css +2 -0
- package/gui/dist/assets/index-OYzhQUNP.js +94 -0
- package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-DKCVUUTi.js} +1 -1
- package/gui/dist/classic/assets/App-CgPBKUP-.js +58 -0
- package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-BedmOsE7.js} +1 -1
- package/gui/dist/classic/assets/index-BR-HhNrp.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/Cargo.lock +215 -0
- package/native/ocx-child/Cargo.toml +31 -0
- package/native/ocx-child/src/cli.rs +1901 -0
- package/native/ocx-child/src/codex_home.rs +429 -0
- package/native/ocx-child/src/codex_settings.rs +231 -0
- package/native/ocx-child/src/daemon.rs +363 -0
- package/native/ocx-child/src/http_wire.rs +619 -0
- package/native/ocx-child/src/journal.rs +977 -0
- package/native/ocx-child/src/lib.rs +22 -0
- package/native/ocx-child/src/main.rs +9 -0
- package/native/ocx-child/src/parity.rs +102 -0
- package/native/ocx-child/src/platform.rs +1487 -0
- package/native/ocx-child/src/relay.rs +1288 -0
- package/native/ocx-child/src/relay_auth.rs +166 -0
- package/native/ocx-child/src/routes.rs +236 -0
- package/native/ocx-child/src/state.rs +190 -0
- package/native/ocx-child/src/test_hooks.rs +58 -0
- package/native/ocx-child/src/toml_surgeon.rs +1156 -0
- package/package.json +8 -2
- package/src/adapters/anthropic-image-normalize.ts +1 -1
- package/src/adapters/anthropic.ts +28 -2
- package/src/adapters/claude-cli/adapter.ts +5 -25
- package/src/adapters/claude-cli/instruction-images.ts +31 -0
- package/src/adapters/claude-cli/stable-replay.ts +42 -14
- package/src/adapters/claude-cli/usage-admission.ts +53 -64
- package/src/adapters/client-fingerprint.ts +1 -1
- package/src/adapters/coding-agent/protocol.ts +1 -1
- package/src/adapters/devin/live-models.ts +3 -0
- package/src/adapters/google-http.ts +3 -0
- package/src/adapters/google-vertex-key-project.ts +10 -2
- package/src/adapters/google.ts +40 -8
- package/src/adapters/kiro/usage.ts +3 -13
- package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
- package/src/adapters/openai-chat-images.ts +100 -0
- package/src/adapters/openai-chat.ts +6 -9
- package/src/adapters/openai-responses/passthrough.ts +5 -2
- package/src/adapters/openai-responses/request-strips.ts +32 -0
- package/src/adapters/openai-responses/tool-schema.ts +9 -4
- package/src/chat/inbound.ts +1 -1
- package/src/claude/auth-detect.ts +26 -8
- package/src/claude/inbound-content-options.ts +18 -3
- package/src/claude/inbound.ts +5 -2
- package/src/cli/bundled-bun-diagnostic.ts +91 -0
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-observe-system.ts +60 -0
- package/src/cli/combo-input.ts +6 -0
- package/src/cli/combo-result.ts +1 -1
- package/src/cli/combo.ts +4 -0
- package/src/cli/config-command.ts +16 -2
- package/src/cli/connect.ts +12 -10
- package/src/cli/dispatch.ts +4 -0
- package/src/cli/doctor.ts +11 -0
- package/src/cli/help.ts +1 -0
- package/src/cli/init.ts +4 -0
- package/src/cli/link-enrollment.ts +152 -25
- package/src/cli/link-local-control.ts +49 -0
- package/src/cli/link.ts +37 -10
- package/src/cli/provider-lifecycle-runtime.ts +4 -2
- package/src/cli/registry.ts +13 -0
- package/src/cli/star-prompt.ts +2 -0
- package/src/cli/status.ts +1 -1
- package/src/cli/telemetry-profile.ts +206 -0
- package/src/cli/telemetry.ts +260 -0
- package/src/client/hub-relay.ts +26 -0
- package/src/client/machine-api.ts +3 -0
- package/src/clients/config-export/t3code.ts +44 -5
- package/src/clients/omo-role-models.ts +1 -1
- package/src/codex/catalog/bundled.ts +44 -2
- package/src/codex/runtime.ts +12 -0
- package/src/codex/shim-restore-lock.ts +67 -30
- package/src/combos/types.ts +21 -1
- package/src/config/atomic-write.ts +24 -1
- package/src/config/diagnostics.ts +15 -0
- package/src/config/live-reconcile.ts +17 -0
- package/src/config/load-degrade.ts +16 -0
- package/src/config/provider-validation.ts +29 -0
- package/src/config/schema/config-schema.ts +24 -0
- package/src/config/schema/leaf-validators.ts +17 -0
- package/src/config/telemetry-carry.ts +30 -0
- package/src/config.ts +13 -1
- package/src/generated/compatibility-version.json +422 -170
- package/src/generated/model-metadata.ts +3 -3
- package/src/integrations/aside-profiles.ts +7 -1
- package/src/integrations/owned-refresh.ts +9 -2
- package/src/lab/artifacts/secure-fs.ts +12 -11
- package/src/lab/fabric/scratch.ts +11 -9
- package/src/lab/public/community.ts +2 -3
- package/src/lab/public/file-safety.ts +18 -20
- package/src/lab/public/mutation-lock.ts +109 -337
- package/src/lab/public/private-file.ts +4 -3
- package/src/lib/bun-runtime-preflight.ts +1 -1
- package/src/lib/codex-catalog-read-only.ts +122 -0
- package/src/lib/config-ownership.ts +56 -18
- package/src/lib/errors.ts +11 -0
- package/src/lib/gcp-adc.ts +167 -48
- package/src/lib/jsonc.ts +4 -2
- package/src/lib/local-control-socket.ts +88 -0
- package/src/lib/privacy.ts +15 -0
- package/src/lib/provider-client-headers.ts +3 -0
- package/src/lib/token-estimate.ts +13 -2
- package/src/link/child-binary-source.ts +228 -0
- package/src/link/ephemeral-child.ts +45 -0
- package/src/link/remote-plant.ts +306 -0
- package/src/link/remote-windows.ts +59 -5
- package/src/link/ssh-argv.ts +71 -8
- package/src/link/status-projection.ts +2 -0
- package/src/link/store.ts +5 -1
- package/src/oauth/anthropic-model-quota.ts +12 -0
- package/src/oauth/anthropic-routing.ts +11 -4
- package/src/oauth/claude-keychain-read.ts +165 -0
- package/src/oauth/kiro-iam-identity-center.ts +4 -1
- package/src/oauth/local-token-detect.ts +14 -17
- package/src/protocols/envelope.ts +20 -2
- package/src/providers/api-key-selection.ts +8 -2
- package/src/providers/claude-cli-identity.ts +9 -3
- package/src/providers/claude-cli-usage-state.ts +93 -0
- package/src/providers/claude-cli-usage.ts +3 -2
- package/src/providers/github-copilot-auto.ts +25 -5
- package/src/providers/meta-muse-plan-refusal.ts +94 -0
- package/src/providers/model-rename-fields.ts +3 -0
- package/src/providers/quota/anthropic-family-headers.ts +8 -1
- package/src/providers/quota/anthropic-usage-windows.ts +49 -2
- package/src/providers/quota/vendor-probes-key.ts +23 -4
- package/src/providers/quota/vendor-probes-oauth.ts +59 -0
- package/src/providers/quota/workbuddy.ts +2 -2
- package/src/providers/quota-types.ts +7 -0
- package/src/providers/quota.ts +25 -18
- package/src/providers/registry/entries-core.ts +7 -4
- package/src/providers/registry/entries-extended.ts +42 -8
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/model-seeds.ts +10 -2
- package/src/providers/registry/types.ts +6 -0
- package/src/providers/resolved-model-policy.ts +4 -0
- package/src/providers/routed-config.ts +30 -3
- package/src/providers/stale-no-vision-seed-migration.ts +7 -0
- package/src/providers/vertex-environment-authority.ts +50 -0
- package/src/providers/workbuddy-credit-balance.ts +38 -6
- package/src/quota-pool/assemble.ts +14 -6
- package/src/responses/retained-compaction.ts +31 -5
- package/src/router.ts +1 -0
- package/src/server/adapter-resolve.ts +11 -6
- package/src/server/audio-dictation.ts +21 -7
- package/src/server/auth-cors.ts +19 -0
- package/src/server/background-lifecycle.ts +71 -0
- package/src/server/chat-completions.ts +2 -0
- package/src/server/claude-messages.ts +30 -3
- package/src/server/index/live-sideband.ts +15 -1
- package/src/server/index/local-control-listener.ts +515 -0
- package/src/server/index/optional-listeners.ts +21 -1
- package/src/server/index/serve-options.ts +4 -3
- package/src/server/index/websocket-handler.ts +2 -0
- package/src/server/index.ts +3 -0
- package/src/server/management/combo-routes.ts +6 -1
- package/src/server/management/context.ts +1 -0
- package/src/server/management/link-child-preflight.ts +74 -0
- package/src/server/management/link-enrollment.ts +190 -25
- package/src/server/management/link-route-state.ts +6 -1
- package/src/server/management/link-routes.ts +27 -9
- package/src/server/management/model-rows.ts +4 -0
- package/src/server/management/oauth-account-routes.ts +9 -4
- package/src/server/management/provider-overwrite-carry.ts +9 -2
- package/src/server/management/provider-routes.ts +14 -0
- package/src/server/management/provider-thinking-display-patch.ts +54 -0
- package/src/server/management/route-registry.ts +7 -0
- package/src/server/management/session-routes.ts +4 -1
- package/src/server/management/telemetry-routes.ts +37 -0
- package/src/server/management/usage-aggregate-cache.ts +290 -67
- package/src/server/management-api.ts +11 -2
- package/src/server/messages-native-preflight.ts +166 -0
- package/src/server/messages-native.ts +143 -43
- package/src/server/messages-shared.ts +14 -0
- package/src/server/proxy-liveness.ts +99 -6
- package/src/server/request-log-conversation.ts +18 -2
- package/src/server/request-log.ts +7 -2
- package/src/server/responses/adapter-continuation.ts +1 -0
- package/src/server/responses/adapter-dispatch.ts +11 -28
- package/src/server/responses/adapter-failure-message.ts +68 -0
- package/src/server/responses/combo-stream-preflight.ts +14 -2
- package/src/server/responses/compact.ts +13 -1
- package/src/server/responses/core-auth.ts +26 -5
- package/src/server/responses/core-codex-account.ts +8 -1
- package/src/server/responses/core-combo-failure.ts +6 -1
- package/src/server/responses/core-combo-native.ts +150 -37
- package/src/server/responses/core-combo.ts +15 -9
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +7 -1
- package/src/server/responses/core-pipeline.ts +21 -1
- package/src/server/responses/fetch-helpers.ts +5 -0
- package/src/server/responses/opengateway-completion-guard.ts +7 -3
- package/src/server/responses/passthrough-delivery.ts +8 -1
- package/src/server/responses/passthrough-error.ts +22 -0
- package/src/server/responses/request-prepare.ts +7 -1
- package/src/server/responses/request-transport.ts +28 -5
- package/src/server/responses/run-turn-execution.ts +13 -0
- package/src/server/sse-frame-buffer.ts +5 -0
- package/src/server/ws-bridge.ts +10 -0
- package/src/service/launchd.ts +78 -4
- package/src/telemetry/aggregate.ts +348 -0
- package/src/telemetry/consent.ts +128 -0
- package/src/telemetry/contract.ts +403 -0
- package/src/telemetry/disclosure.ts +19 -0
- package/src/telemetry/install-id.ts +226 -0
- package/src/telemetry/payload.ts +129 -0
- package/src/telemetry/profile/client.ts +150 -0
- package/src/telemetry/profile/contract.ts +288 -0
- package/src/telemetry/profile/disclosure.ts +14 -0
- package/src/telemetry/profile/paths.ts +13 -0
- package/src/telemetry/profile/routes.ts +99 -0
- package/src/telemetry/profile/service.ts +234 -0
- package/src/telemetry/profile/state.ts +189 -0
- package/src/telemetry/profile/sync.ts +276 -0
- package/src/telemetry/routes.ts +183 -0
- package/src/telemetry/scheduler.ts +386 -0
- package/src/telemetry/sender.ts +97 -0
- package/src/telemetry/state.ts +334 -0
- package/src/types/combo-jev-effort-mode.ts +11 -0
- package/src/types/config.ts +3 -0
- package/src/types/provider.ts +11 -1
- package/src/types/request.ts +2 -0
- package/src/types/telemetry.ts +15 -0
- package/src/types/wire.ts +10 -0
- package/src/types.ts +5 -0
- package/src/update/index.ts +7 -1
- package/src/update/minisign.d.mts +17 -0
- package/src/update/minisign.mjs +88 -0
- package/src/update/signed-supply.d.mts +59 -0
- package/src/update/signed-supply.mjs +289 -0
- package/src/update/trust-root.json +38 -0
- package/src/update/update-bounded-json.d.mts +4 -0
- package/src/update/update-bounded-json.mjs +113 -0
- package/src/update/update-bytes.d.mts +2 -0
- package/src/update/update-bytes.mjs +23 -0
- package/src/update/update-candidate-id.d.mts +2 -0
- package/src/update/update-candidate-id.mjs +23 -0
- package/src/update/update-checkpoint-codec.d.mts +33 -0
- package/src/update/update-checkpoint-codec.mjs +217 -0
- package/src/update/update-contracts.d.mts +24 -0
- package/src/update/update-contracts.mjs +207 -0
- package/src/update/update-signature-threshold.d.mts +12 -0
- package/src/update/update-signature-threshold.mjs +47 -0
- package/src/update/update-signed-version.d.mts +5 -0
- package/src/update/update-signed-version.mjs +25 -0
- package/src/update/update-trust-anchor.d.mts +2 -0
- package/src/update/update-trust-anchor.mjs +2 -0
- package/src/usage/cache-diagnostic.ts +195 -50
- package/src/usage/expected-prices.ts +20 -2
- package/src/usage/filter-index.ts +1469 -0
- package/src/usage/ledger-scanner.ts +245 -4
- package/src/usage/source-filter.ts +10 -2
- package/src/usage/summary.ts +16 -0
- package/src/web-search/parse.ts +265 -38
- package/gui/dist/assets/App-BepstgEN.js +0 -59
- package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
- package/gui/dist/assets/brand-mark-wzPe3R-J.js +0 -1
- package/gui/dist/assets/index-C-9X2yaI.js +0 -94
- package/gui/dist/assets/index-bnUWypyz.css +0 -2
- package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
- package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
- package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code Keychain reads that never kill a blocked `security` child.
|
|
3
|
+
*
|
|
4
|
+
* With a locked login keychain, `security find-generic-password -w` blocks on the
|
|
5
|
+
* SecurityAgent unlock prompt. Killing it while that prompt is pending hits a race in
|
|
6
|
+
* Apple's `securityd`, which aborts and re-locks the keychain, so the next read prompts
|
|
7
|
+
* again (#8161). This reader gives up on a slow read without signalling the child, keeps
|
|
8
|
+
* at most one child per process, and backs off after a timeout so a locked keychain does
|
|
9
|
+
* not get one prompt per request.
|
|
10
|
+
*/
|
|
11
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
12
|
+
|
|
13
|
+
export const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials";
|
|
14
|
+
export const CLAUDE_KEYCHAIN_TIMEOUT_MS = 5_000;
|
|
15
|
+
export const CLAUDE_KEYCHAIN_BACKOFF_MS = 60_000;
|
|
16
|
+
const SECURITY_ARGS = ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-w"] as const;
|
|
17
|
+
/** The credential is a small JSON blob; anything larger is not a credential. */
|
|
18
|
+
const MAX_STDOUT_BYTES = 1024 * 1024;
|
|
19
|
+
|
|
20
|
+
interface UnrefHandle { unref?(): unknown }
|
|
21
|
+
|
|
22
|
+
/** The subset of a spawned child the reader relies on. */
|
|
23
|
+
export interface KeychainChild extends UnrefHandle {
|
|
24
|
+
/** Set once the process exists; undefined when the spawn itself failed. */
|
|
25
|
+
pid?: number | undefined;
|
|
26
|
+
stdout: (UnrefHandle & { on(event: "data", listener: (chunk: Buffer | string) => void): unknown }) | null;
|
|
27
|
+
once(event: "close", listener: (code: number | null, signal: string | null) => void): unknown;
|
|
28
|
+
once(event: "error", listener: (error: Error) => void): unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ClaudeKeychainReaderDeps {
|
|
32
|
+
platform: string;
|
|
33
|
+
spawn(command: string, args: readonly string[]): KeychainChild;
|
|
34
|
+
/** Synchronous run with a timeout; returns stdout and throws on a nonzero exit or a timeout. */
|
|
35
|
+
execSync(command: string, args: readonly string[], timeoutMs: number): string;
|
|
36
|
+
now(): number;
|
|
37
|
+
/** Runs `fn` after `ms`; returns a cancel function. */
|
|
38
|
+
schedule(ms: number, fn: () => void): () => void;
|
|
39
|
+
timeoutMs?: number;
|
|
40
|
+
backoffMs?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ClaudeKeychainReader {
|
|
44
|
+
/** Resolves the item's secret, or null on absence, failure, timeout, backoff or a non-darwin host. */
|
|
45
|
+
readAsync(): Promise<string | null>;
|
|
46
|
+
/**
|
|
47
|
+
* Synchronous read. It cannot time out without killing its child, so it does not run while a
|
|
48
|
+
* child is still running or a backoff is active, and its own timeout starts the backoff.
|
|
49
|
+
*/
|
|
50
|
+
readSync(): string | null;
|
|
51
|
+
/** True while a child is still running or a timeout backoff is active. */
|
|
52
|
+
syncReadBlocked(): boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Record a timeout of another synchronous Keychain lookup (the metadata probe), so it starts
|
|
55
|
+
* the same backoff and no read or probe spawns again inside that window.
|
|
56
|
+
*/
|
|
57
|
+
noteSyncTimeout(): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createClaudeKeychainReader(deps: ClaudeKeychainReaderDeps): ClaudeKeychainReader {
|
|
61
|
+
const timeoutMs = deps.timeoutMs ?? CLAUDE_KEYCHAIN_TIMEOUT_MS;
|
|
62
|
+
const backoffMs = deps.backoffMs ?? CLAUDE_KEYCHAIN_BACKOFF_MS;
|
|
63
|
+
let backoffUntil = 0;
|
|
64
|
+
// Held until the child exits, not until the caller's promise settles: a child that
|
|
65
|
+
// outlives its deadline is still blocked on the prompt and must not get a sibling. Only the
|
|
66
|
+
// owning child may release it, so a late event from an earlier child cannot free the slot.
|
|
67
|
+
let runningChild: KeychainChild | undefined;
|
|
68
|
+
let pending: Promise<string | null> | undefined;
|
|
69
|
+
|
|
70
|
+
const backingOff = (): boolean => deps.now() < backoffUntil;
|
|
71
|
+
const startBackoff = (): void => { backoffUntil = deps.now() + backoffMs; };
|
|
72
|
+
|
|
73
|
+
function readAsync(): Promise<string | null> {
|
|
74
|
+
if (deps.platform !== "darwin") return Promise.resolve(null);
|
|
75
|
+
if (pending) return pending;
|
|
76
|
+
if (runningChild || backingOff()) return Promise.resolve(null);
|
|
77
|
+
|
|
78
|
+
let child: KeychainChild;
|
|
79
|
+
try {
|
|
80
|
+
child = deps.spawn("security", SECURITY_ARGS);
|
|
81
|
+
} catch {
|
|
82
|
+
return Promise.resolve(null);
|
|
83
|
+
}
|
|
84
|
+
runningChild = child;
|
|
85
|
+
const release = (): void => { if (runningChild === child) runningChild = undefined; };
|
|
86
|
+
const read = new Promise<string | null>(resolve => {
|
|
87
|
+
let settled = false;
|
|
88
|
+
const chunks: Buffer[] = [];
|
|
89
|
+
let stdoutBytes = 0;
|
|
90
|
+
const settle = (value: string | null): void => {
|
|
91
|
+
if (settled) return;
|
|
92
|
+
settled = true;
|
|
93
|
+
cancelDeadline();
|
|
94
|
+
pending = undefined;
|
|
95
|
+
resolve(value);
|
|
96
|
+
};
|
|
97
|
+
const cancelDeadline = deps.schedule(timeoutMs, () => {
|
|
98
|
+
// Give up without signalling the child, and let it exit on its own once the
|
|
99
|
+
// prompt is answered or dismissed. Unref it so it cannot hold this process open.
|
|
100
|
+
startBackoff();
|
|
101
|
+
child.unref?.();
|
|
102
|
+
child.stdout?.unref?.();
|
|
103
|
+
settle(null);
|
|
104
|
+
});
|
|
105
|
+
child.stdout?.on("data", chunk => {
|
|
106
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
107
|
+
stdoutBytes += bytes.length;
|
|
108
|
+
if (stdoutBytes <= MAX_STDOUT_BYTES) chunks.push(bytes);
|
|
109
|
+
});
|
|
110
|
+
child.once("error", () => {
|
|
111
|
+
// Once a process exists, an error event does not prove it ended; only its own close may
|
|
112
|
+
// release the slot, or a second child could start beside one still blocked on the prompt.
|
|
113
|
+
if (child.pid === undefined) release();
|
|
114
|
+
settle(null);
|
|
115
|
+
});
|
|
116
|
+
// `close`, not `exit`: `exit` can fire before stdout is drained, which would truncate
|
|
117
|
+
// the credential. Decode once so a multi-byte character split across chunks survives.
|
|
118
|
+
child.once("close", code => {
|
|
119
|
+
release();
|
|
120
|
+
if (code !== 0 || stdoutBytes > MAX_STDOUT_BYTES) return settle(null);
|
|
121
|
+
settle(Buffer.concat(chunks).toString("utf8").trim() || null);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
pending = read;
|
|
125
|
+
return read;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function readSync(): string | null {
|
|
129
|
+
if (deps.platform !== "darwin" || runningChild || backingOff()) return null;
|
|
130
|
+
try {
|
|
131
|
+
return deps.execSync("security", SECURITY_ARGS, timeoutMs).trim() || null;
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (isSyncTimeout(error)) startBackoff();
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
readAsync,
|
|
140
|
+
readSync,
|
|
141
|
+
syncReadBlocked: () => runningChild !== undefined || backingOff(),
|
|
142
|
+
noteSyncTimeout: startBackoff,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `execFileSync` reports its own timeout as ETIMEDOUT or a kill signal; a nonzero exit is not one. */
|
|
147
|
+
export function isSyncTimeout(error: unknown): boolean {
|
|
148
|
+
if (!error || typeof error !== "object") return false;
|
|
149
|
+
const { code, signal } = error as { code?: unknown; signal?: unknown };
|
|
150
|
+
return code === "ETIMEDOUT" || (typeof signal === "string" && signal.length > 0);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The process-wide reader: one Keychain child and one backoff window per process. */
|
|
154
|
+
export const claudeKeychainReader = createClaudeKeychainReader({
|
|
155
|
+
platform: process.platform,
|
|
156
|
+
spawn: (command, args) => spawn(command, [...args], { stdio: ["ignore", "pipe", "ignore"] }),
|
|
157
|
+
execSync: (command, args, timeoutMs) =>
|
|
158
|
+
execFileSync(command, [...args], { encoding: "utf8", timeout: timeoutMs, stdio: ["pipe", "pipe", "pipe"] }),
|
|
159
|
+
now: () => Date.now(),
|
|
160
|
+
schedule(ms, fn) {
|
|
161
|
+
const timer = setTimeout(fn, ms);
|
|
162
|
+
timer.unref?.();
|
|
163
|
+
return () => clearTimeout(timer);
|
|
164
|
+
},
|
|
165
|
+
});
|
|
@@ -55,7 +55,10 @@ async function listProfilesInRegion(reply: KiroIamReply, access: string, region:
|
|
|
55
55
|
const tokens = new Set<string>();
|
|
56
56
|
let nextToken: string | undefined;
|
|
57
57
|
for (let page = 0; page < 8; page++) {
|
|
58
|
-
|
|
58
|
+
// No maxResults: AWS answers maxResults above 10 with 400 ValidationException, and other
|
|
59
|
+
// Kiro clients report 400 REQUEST_BODY_INVALID for any maxResults; the default page plus
|
|
60
|
+
// nextToken pagination works for both.
|
|
61
|
+
const data = await call(reply, access, region, "ListAvailableProfiles", nextToken ? { nextToken } : {});
|
|
59
62
|
if (!Array.isArray(data.profiles)) throw new Error("Kiro IAM profiles unavailable");
|
|
60
63
|
for (const item of data.profiles) {
|
|
61
64
|
const profile = record(item);
|
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
* Read-only: never writes to external credential stores.
|
|
4
4
|
* Ported from jawcode packages/ai/src/utils/oauth/local-token-detect.ts (xAI portion).
|
|
5
5
|
*/
|
|
6
|
-
import { execFile, execSync } from "node:child_process";
|
|
7
6
|
import { existsSync, readFileSync } from "node:fs";
|
|
8
7
|
import { homedir } from "node:os";
|
|
9
8
|
import { join } from "node:path";
|
|
9
|
+
import { claudeKeychainReader } from "./claude-keychain-read";
|
|
10
10
|
import type { OAuthCredentials } from "./types";
|
|
11
11
|
|
|
12
12
|
const XAI_AUTH_KEY_PREFIX = "https://auth.x.ai::";
|
|
13
|
-
const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials";
|
|
14
13
|
|
|
15
14
|
export function detectGrokCliToken(): OAuthCredentials | null {
|
|
16
15
|
const authPath = join(process.env.HOME ?? homedir(), ".grok", "auth.json");
|
|
@@ -73,16 +72,14 @@ function claudeConfigDir(): string {
|
|
|
73
72
|
return explicit ? explicit : join(homedir(), ".claude");
|
|
74
73
|
}
|
|
75
74
|
|
|
76
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* Read the Claude Code OAuth credential from the macOS Keychain (darwin only). A synchronous
|
|
77
|
+
* read cannot time out without killing `security`, which can crash `securityd` while an unlock
|
|
78
|
+
* prompt is pending (#8161), so it does not spawn while a read is still running or backing off,
|
|
79
|
+
* and its own timeout starts that backoff (`claude-keychain-read.ts`).
|
|
80
|
+
*/
|
|
77
81
|
function readClaudeKeychain(): string | null {
|
|
78
|
-
|
|
79
|
-
try {
|
|
80
|
-
return execSync(`security find-generic-password -s "${CLAUDE_KEYCHAIN_SERVICE}" -w`, {
|
|
81
|
-
encoding: "utf8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"],
|
|
82
|
-
}).trim();
|
|
83
|
-
} catch {
|
|
84
|
-
return null;
|
|
85
|
-
}
|
|
82
|
+
return claudeKeychainReader.readSync();
|
|
86
83
|
}
|
|
87
84
|
|
|
88
85
|
/**
|
|
@@ -109,13 +106,13 @@ function readClaudeSecureStorage(): string | null {
|
|
|
109
106
|
return readClaudeKeychain() ?? readClaudeCredentialsFile();
|
|
110
107
|
}
|
|
111
108
|
|
|
112
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Non-blocking Keychain read for request paths; same item and deadline as the sync reader. A
|
|
111
|
+
* timed-out child is left to exit on its own, concurrent reads share one child, and a timeout
|
|
112
|
+
* backs off before the next spawn (`claude-keychain-read.ts`).
|
|
113
|
+
*/
|
|
113
114
|
function readClaudeKeychainAsync(): Promise<string | null> {
|
|
114
|
-
|
|
115
|
-
return new Promise(resolve => {
|
|
116
|
-
execFile("security", ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-w"], { encoding: "utf8", timeout: 5000 },
|
|
117
|
-
(error, stdout) => resolve(error ? null : stdout.trim() || null));
|
|
118
|
-
});
|
|
115
|
+
return claudeKeychainReader.readAsync();
|
|
119
116
|
}
|
|
120
117
|
|
|
121
118
|
/**
|
|
@@ -17,8 +17,12 @@ export interface ProtocolEnvelope {
|
|
|
17
17
|
readonly inbound: Protocol;
|
|
18
18
|
/** The request features, scanned from the source body on the first call and cached. */
|
|
19
19
|
features(): ReadonlySet<ProtocolFeature>;
|
|
20
|
+
/** The source body itself, uncharged, for checks that only read it; a rewrite takes `freshBody()`. */
|
|
21
|
+
readBody(): Readonly<Record<string, unknown>>;
|
|
20
22
|
/** A structured clone of the source body, charged to the translator budget. */
|
|
21
23
|
freshBody(): Record<string, unknown>;
|
|
24
|
+
/** Hand back the charge of a `freshBody()` copy no longer needed; later calls are no-ops. */
|
|
25
|
+
releaseBody(copy: Record<string, unknown>): void;
|
|
22
26
|
}
|
|
23
27
|
|
|
24
28
|
export function createProtocolEnvelope(input: {
|
|
@@ -28,16 +32,30 @@ export function createProtocolEnvelope(input: {
|
|
|
28
32
|
}): ProtocolEnvelope {
|
|
29
33
|
const { inbound, body, translatorBudget } = input;
|
|
30
34
|
let features: ReadonlySet<ProtocolFeature> | undefined;
|
|
35
|
+
// The copy's own size may change once its holder rewrites it, so the charge is remembered.
|
|
36
|
+
const charged = new WeakMap<object, number>();
|
|
31
37
|
return {
|
|
32
38
|
inbound,
|
|
33
39
|
features() {
|
|
34
40
|
features ??= featuresFromBody(inbound, body);
|
|
35
41
|
return features;
|
|
36
42
|
},
|
|
43
|
+
readBody() {
|
|
44
|
+
return body;
|
|
45
|
+
},
|
|
37
46
|
freshBody() {
|
|
38
47
|
// Charged before the copy exists, so an over-budget request fails without allocating it.
|
|
39
|
-
|
|
40
|
-
|
|
48
|
+
const bytes = jsonUtf8Bytes(body);
|
|
49
|
+
translatorBudget.chargeRetained(bytes, { kind: "request_copies" });
|
|
50
|
+
const copy = structuredClone(body);
|
|
51
|
+
charged.set(copy, bytes);
|
|
52
|
+
return copy;
|
|
53
|
+
},
|
|
54
|
+
releaseBody(copy) {
|
|
55
|
+
const bytes = charged.get(copy);
|
|
56
|
+
if (bytes === undefined) return;
|
|
57
|
+
charged.delete(copy);
|
|
58
|
+
translatorBudget.releaseRetained(bytes, { kind: "request_copies" });
|
|
41
59
|
},
|
|
42
60
|
};
|
|
43
61
|
}
|
|
@@ -9,6 +9,7 @@ import { routedProviderConfig } from "./routed-config";
|
|
|
9
9
|
import { OPENCODE_GO_SESSION_HEADER } from "./opencode-go-transport";
|
|
10
10
|
import { resolveProviderTransport, XAI_GROK_COMPATIBILITY, type OcxProviderTransport } from "./xai-transport";
|
|
11
11
|
import { captureProviderApiKeySelection } from "./api-key-selection-capture";
|
|
12
|
+
import { vertexEnvironmentKeyIsCurrent } from "./vertex-environment-authority";
|
|
12
13
|
|
|
13
14
|
export { captureProviderApiKeySelection } from "./api-key-selection-capture";
|
|
14
15
|
|
|
@@ -35,7 +36,8 @@ function currentKeyProvider(config: OcxConfig, name: string, selection?: Provide
|
|
|
35
36
|
|| row.apiKeyPool?.length && row.apiKeyPool.every(entry => entry.disabled)) return null;
|
|
36
37
|
const current = routedProviderConfig(name, { ...row, _apiKeyAttempt: selection?.distributed ? selection : undefined });
|
|
37
38
|
if (current.authMode === "oauth" || current.authMode === "forward") return null;
|
|
38
|
-
if (current.authMode === "key" && !current.keyOptional && !current.apiKey?.trim()
|
|
39
|
+
if (current.authMode === "key" && !current.keyOptional && !current.apiKey?.trim()
|
|
40
|
+
&& !(current.adapter === "google" && current.googleMode === "vertex")) return null;
|
|
39
41
|
return current;
|
|
40
42
|
}
|
|
41
43
|
|
|
@@ -61,10 +63,14 @@ function matchesConfiguredSelection(
|
|
|
61
63
|
const expected = routedProvider._apiKeyAttempt;
|
|
62
64
|
const current = currentKeyProvider(config, name, expected, allowCooling);
|
|
63
65
|
return current !== null && expected !== undefined
|
|
66
|
+
&& vertexEnvironmentKeyIsCurrent(expected, current)
|
|
64
67
|
&& (expected.distributed === true || matchesSelection(config.providers[name]!, expected))
|
|
65
68
|
&& current.apiKey === routedProvider.apiKey
|
|
66
69
|
&& current.authMode === routedProvider.authMode
|
|
67
|
-
&& current.baseUrl === routedProvider.baseUrl
|
|
70
|
+
&& current.baseUrl === routedProvider.baseUrl
|
|
71
|
+
&& (current.googleMode !== "vertex" && routedProvider.googleMode !== "vertex"
|
|
72
|
+
|| current.googleMode === routedProvider.googleMode && current.project === routedProvider.project
|
|
73
|
+
&& current.location === routedProvider.location);
|
|
68
74
|
}
|
|
69
75
|
|
|
70
76
|
/** Rebuild transport from the already committed choice; never allocate or publish a selection. */
|
|
@@ -7,8 +7,14 @@
|
|
|
7
7
|
* "cli_version"`; `claude-code/<ver>` is answered with `"surface"`. Only the
|
|
8
8
|
* `claude-cli/<ver> (external, cli)` form of a current release is treated as the
|
|
9
9
|
* Claude Code CLI surface. Bump the version together with a live GET check.
|
|
10
|
+
*
|
|
11
|
+
* Model access is gated on it too: Anthropic answers claude-fable-5-2 with
|
|
12
|
+
* "Claude Code 2.1.280 does not support this model; version 2.1.290 or newer is required".
|
|
13
|
+
* The three values below are one coherent client: Claude Code 2.1.321 sends @anthropic-ai/sdk 0.128.0 on
|
|
14
|
+
* runtime v26.12.1 (mitmproxy capture in router-for-me/CLIProxyAPI#7392; the locally installed 2.1.319
|
|
15
|
+
* binary carries the same SDK and runtime strings).
|
|
10
16
|
*/
|
|
11
|
-
export const CLAUDE_CLI_VERSION = "2.1.
|
|
17
|
+
export const CLAUDE_CLI_VERSION = "2.1.321";
|
|
12
18
|
export const CLAUDE_CLI_USER_AGENT = `claude-cli/${CLAUDE_CLI_VERSION} (external, cli)`;
|
|
13
|
-
export const CLAUDE_CLI_SDK_PACKAGE_VERSION = "0.
|
|
14
|
-
export const CLAUDE_CLI_RUNTIME_VERSION = "v26.
|
|
19
|
+
export const CLAUDE_CLI_SDK_PACKAGE_VERSION = "0.128.0";
|
|
20
|
+
export const CLAUDE_CLI_RUNTIME_VERSION = "v26.12.1";
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The last Claude Code subscription observation, persisted beside the proxy's other state.
|
|
3
|
+
*
|
|
4
|
+
* The read model lives here rather than in `src/adapters/claude-cli/usage-admission.ts` because
|
|
5
|
+
* `/api/provider-quotas` reads it as well, and `src/providers/quota.ts` is statically reachable
|
|
6
|
+
* from `src/server/responses/core.ts`: importing the adapter would drag its token/Keychain and
|
|
7
|
+
* child-process layer into every install. The adapter owns identity resolution and gating; this
|
|
8
|
+
* module owns only the file.
|
|
9
|
+
*/
|
|
10
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import { getConfigDir } from "../config/paths";
|
|
13
|
+
import type { ProviderQuota } from "./quota-types";
|
|
14
|
+
|
|
15
|
+
export type ClaudeUsageSnapshot = {
|
|
16
|
+
identity: string;
|
|
17
|
+
checkedAt: number;
|
|
18
|
+
quota?: ProviderQuota;
|
|
19
|
+
refusalUntil?: number;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type ClaudeUsageObservation = Readonly<ClaudeUsageSnapshot>;
|
|
23
|
+
|
|
24
|
+
const memory = new Map<string, ClaudeUsageSnapshot>();
|
|
25
|
+
let signedInIdentity: string | null = null;
|
|
26
|
+
|
|
27
|
+
/** The adapter records every sign-in read here, so a published report can tell it was superseded. */
|
|
28
|
+
export function recordClaudeSignedInIdentity(identity: string | null): void { signedInIdentity = identity; }
|
|
29
|
+
|
|
30
|
+
/** The hashed key of the last sign-in read, or null when signed out, unreadable or not yet read. */
|
|
31
|
+
export function claudeSignedInIdentity(): string | null { return signedInIdentity; }
|
|
32
|
+
|
|
33
|
+
export function claudeUsageStatePath(statePath?: string): string {
|
|
34
|
+
return statePath ?? join(getConfigDir(), "claude-usage-admission.json");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function finite(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value); }
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The admission file, or undefined when it is missing or any field fails validation. A rejected
|
|
41
|
+
* file reads as "never checked", so a corrupt cache can neither admit nor refuse a launch.
|
|
42
|
+
*/
|
|
43
|
+
export function loadClaudeUsageSnapshot(path: string): ClaudeUsageSnapshot | undefined {
|
|
44
|
+
try {
|
|
45
|
+
const saved = JSON.parse(readFileSync(path, "utf8"));
|
|
46
|
+
if (typeof saved.identity !== "string" || !Number.isFinite(saved.checkedAt)) return;
|
|
47
|
+
if (saved.refusalUntil !== undefined && !finite(saved.refusalUntil)) return;
|
|
48
|
+
if (saved.quota !== undefined) {
|
|
49
|
+
const q = saved.quota;
|
|
50
|
+
if (!q || typeof q !== "object" || !finite(q.updatedAt)) return;
|
|
51
|
+
for (const field of ["fiveHourPercent", "fiveHourResetAt", "weeklyPercent", "weeklyResetAt"])
|
|
52
|
+
if (q[field] !== undefined && !finite(q[field])) return;
|
|
53
|
+
if (q.customWindows !== undefined && (!Array.isArray(q.customWindows) || !q.customWindows.every((w: unknown) => {
|
|
54
|
+
if (!w || typeof w !== "object") return false;
|
|
55
|
+
const row = w as Record<string, unknown>;
|
|
56
|
+
return typeof row.label === "string" && finite(row.percent) && (row.resetAt === undefined || finite(row.resetAt));
|
|
57
|
+
}))) return;
|
|
58
|
+
}
|
|
59
|
+
return saved;
|
|
60
|
+
} catch { /* Missing or malformed cache is unknown, never proof of capacity. */ }
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Records the snapshot in memory first, then atomically on disk (temp file plus rename, mode 0600).
|
|
66
|
+
* A failed disk write is swallowed: the in-memory copy still gates this process's launches.
|
|
67
|
+
*/
|
|
68
|
+
export function saveClaudeUsageSnapshot(path: string, snapshot: ClaudeUsageSnapshot): void {
|
|
69
|
+
memory.set(path, snapshot);
|
|
70
|
+
try {
|
|
71
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
72
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
73
|
+
writeFileSync(temp, JSON.stringify(snapshot) + "\n", { mode: 0o600 });
|
|
74
|
+
renameSync(temp, path);
|
|
75
|
+
} catch { /* Memory still suppresses launches; no secrets or upstream text are persisted. */ }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Every snapshot this process can see for the path: the admission file and the in-memory write. */
|
|
79
|
+
export function readClaudeUsageSnapshots(path: string): ClaudeUsageSnapshot[] {
|
|
80
|
+
return [loadClaudeUsageSnapshot(path), memory.get(path)]
|
|
81
|
+
.filter((snapshot): snapshot is ClaudeUsageSnapshot => snapshot !== undefined);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The newest recorded usage snapshot, from memory or the admission file, optionally only for one
|
|
86
|
+
* account. Read-only: it resolves no sign-in (no Keychain read), runs no probe and writes nothing.
|
|
87
|
+
* `identity` is the admission's own SHA-256 account key, never the account uuid itself.
|
|
88
|
+
*/
|
|
89
|
+
export function peekClaudeUsageObservation(deps: { statePath?: string; identity?: string } = {}): ClaudeUsageObservation | null {
|
|
90
|
+
const rows = readClaudeUsageSnapshots(claudeUsageStatePath(deps.statePath))
|
|
91
|
+
.filter(row => deps.identity === undefined || row.identity === deps.identity);
|
|
92
|
+
return rows.sort((a, b) => b.checkedAt - a.checkedAt)[0] ?? null;
|
|
93
|
+
}
|
|
@@ -40,7 +40,7 @@ export async function probeAnthropicUsageQuota(accessToken: string): Promise<Ant
|
|
|
40
40
|
const { buckets, familyEnumeration } = anthropicUsageBuckets(body);
|
|
41
41
|
const shared: Partial<ProviderQuota> = {};
|
|
42
42
|
const customWindows: ProviderQuotaWindow[] = [];
|
|
43
|
-
for (const { window, row, percentField } of buckets) {
|
|
43
|
+
for (const { window, row, percentField, weeklyAllowancePercent } of buckets) {
|
|
44
44
|
const percent = normalizePercent(row[percentField]);
|
|
45
45
|
const resetAt = normalizeResetAt(row.resets_at);
|
|
46
46
|
if (window === "5h" || window === "weekly") {
|
|
@@ -48,7 +48,8 @@ export async function probeAnthropicUsageQuota(accessToken: string): Promise<Ant
|
|
|
48
48
|
if (resetAt !== undefined) shared[window === "5h" ? "fiveHourResetAt" : "weeklyResetAt"] = resetAt;
|
|
49
49
|
} else if (percent !== undefined) {
|
|
50
50
|
const label = { fable: "Fable", opus: "Opus", sonnet: "Sonnet" }[window];
|
|
51
|
-
customWindows.push({ label, scope: "model", percent, ...(resetAt !== undefined ? { resetAt } : {})
|
|
51
|
+
customWindows.push({ label, scope: "model", percent, ...(resetAt !== undefined ? { resetAt } : {}),
|
|
52
|
+
...(weeklyAllowancePercent !== undefined ? { weeklyAllowancePercent } : {}) });
|
|
52
53
|
}
|
|
53
54
|
}
|
|
54
55
|
const quota: ProviderQuota = {
|
|
@@ -130,15 +130,32 @@ export async function resolveCopilotAuto(provider: OcxProviderConfig, requestedM
|
|
|
130
130
|
let models: CopilotModel[];
|
|
131
131
|
try { models = await fetchCopilotAutoModels(transport, signal, beforeSend, 60_000, concurrency); }
|
|
132
132
|
catch (error) {
|
|
133
|
-
if (signal?.aborted
|
|
133
|
+
if (signal?.aborted) throw error;
|
|
134
|
+
// A manual account switch makes `beforeSend` return false, which cancels this
|
|
135
|
+
// control-plane send. That is not a client abort: fall back to the requested model
|
|
136
|
+
// so the dispatch path revalidates the selection and rebuilds on the new account.
|
|
137
|
+
if (error instanceof ProviderOutboundSendCancelledError) {
|
|
138
|
+
return { provider: transport, modelId: requestedModel, auto: false };
|
|
139
|
+
}
|
|
134
140
|
// Permission discovery is additive for legacy paid configurations. A temporary
|
|
135
141
|
// discovery outage must not turn a previously usable named route into a refusal.
|
|
136
142
|
return { provider: transport, modelId: requestedModel, auto: false };
|
|
137
143
|
}
|
|
138
144
|
if (!copilotRequiresAuto(provider, models))
|
|
139
145
|
return { provider: transport, modelId: requestedModel, auto: false };
|
|
140
|
-
|
|
141
|
-
|
|
146
|
+
// The same authority fence guards the later control-plane sends: a manual switch that
|
|
147
|
+
// lands during the session or intent step falls back too, so dispatch rebuilds on the
|
|
148
|
+
// new account instead of failing the whole negotiation. A client abort still rejects.
|
|
149
|
+
const fallBackOnSwitch = (error: unknown) => {
|
|
150
|
+
if (!signal?.aborted && error instanceof ProviderOutboundSendCancelledError)
|
|
151
|
+
return { provider: transport, modelId: requestedModel, auto: false } as const;
|
|
152
|
+
throw error;
|
|
153
|
+
};
|
|
154
|
+
let session: Awaited<ReturnType<typeof requestJson>>;
|
|
155
|
+
try {
|
|
156
|
+
session = await requestJson(transport, "/models/session", signal,
|
|
157
|
+
{ auto_mode: { model_hints: ["auto"] } }, undefined, beforeSend, concurrency);
|
|
158
|
+
} catch (error) { return fallBackOnSwitch(error); }
|
|
142
159
|
const pool = strings(session.available_models);
|
|
143
160
|
if (typeof session.session_token !== "string" || !session.session_token || session.session_token.length > 32_768 || !/^[\x21-\x7e]+$/.test(session.session_token) || !pool.length)
|
|
144
161
|
throw new Error("GitHub Copilot Auto session omitted its routing credentials");
|
|
@@ -153,8 +170,11 @@ export async function resolveCopilotAuto(provider: OcxProviderConfig, requestedM
|
|
|
153
170
|
? typeof lastUser.content === "string" ? lastUser.content : lastUser.content.flatMap(/** Extract text parts for intent negotiation without forwarding image or other multimodal payloads. */
|
|
154
171
|
part => part.type === "text" ? [part.text] : []).join("\n")
|
|
155
172
|
: "";
|
|
156
|
-
|
|
157
|
-
|
|
173
|
+
let intent: Awaited<ReturnType<typeof requestJson>>;
|
|
174
|
+
try {
|
|
175
|
+
intent = await requestJson(transport, "/models/session/intent", signal,
|
|
176
|
+
{ prompt: prompt.slice(0, 32_768), available_models: pool }, session.session_token, beforeSend, concurrency);
|
|
177
|
+
} catch (error) { return fallBackOnSwitch(error); }
|
|
158
178
|
const modelId = strings(intent.candidate_models).find(/** Choose the first server-ranked candidate that belongs to this credential-bound session pool. */
|
|
159
179
|
candidate => pool.includes(candidate));
|
|
160
180
|
if (!modelId) throw new Error("GitHub Copilot Auto intent returned no eligible model");
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { RequestFailureCause } from "../usage/telemetry-contract";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Meta's Muse Code subscription refusal (#8352).
|
|
5
|
+
*
|
|
6
|
+
* A Muse Code subscription key is valid, and Meta scopes it to the Muse Code client. Every request
|
|
7
|
+
* from another client is refused with HTTP 403 and one fixed sentence, so the credential is not
|
|
8
|
+
* rejected and no login can lift the restriction. Classifying it as `permission_denied` /
|
|
9
|
+
* `credential-rejected` sent operators to re-authenticate a key that works exactly as Meta sold it;
|
|
10
|
+
* the refusal is a plan restriction whose only remedy is a pay-as-you-go key.
|
|
11
|
+
*
|
|
12
|
+
* The match is deliberately narrow, in the shape of `anthropic-billing-refusal.ts`: a 403, an
|
|
13
|
+
* OpenAI-compatible `error` envelope, and that whole sentence. A missed match leaves the turn
|
|
14
|
+
* failing with Meta's own text, which is already legible; a loose match would relabel an unrelated
|
|
15
|
+
* permission denial that the operator fixes another way.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** The envelope and message are upstream-controlled input; this bounds what is read. */
|
|
19
|
+
const MAX_REFUSAL_CHARS = 8 * 1024;
|
|
20
|
+
|
|
21
|
+
/** Meta's two sentences, whole. A suffix, prefix, or reworded copy is a different refusal. */
|
|
22
|
+
const PLAN_REFUSAL = /^This API key is billed to a Muse Code subscription\. Muse Code subscriptions cover requests from the Muse Code client only\. Use it in Muse Code, or use a pay-as-you-go API key for other clients\.?$/i;
|
|
23
|
+
|
|
24
|
+
/** Classes Meta has been observed to put on this refusal; anything else is a different verdict. */
|
|
25
|
+
const PERMISSION_TYPES = new Set(["permission_error", "permission_denied", "invalid_request_error"]);
|
|
26
|
+
const PERMISSION_CODES = new Set(["permission_denied", "permission_error", "subscription_required", "forbidden"]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The one sentence a client sees instead of Meta's refusal.
|
|
30
|
+
*
|
|
31
|
+
* It names the restriction, the fact that no retry or re-login changes it, and the supported path.
|
|
32
|
+
* It is also a proxy literal that later classification passes recognize verbatim, so the Chat and
|
|
33
|
+
* Anthropic formatters cannot fold it back into `permission_denied`.
|
|
34
|
+
*/
|
|
35
|
+
export const META_MUSE_PLAN_REFUSAL_MESSAGE = "Meta rejected this request because the configured key is billed to a Muse Code subscription, and Meta restricts Muse Code subscription keys to the Muse Code client. This is a plan restriction on a valid credential, not an expired one, so a new login cannot lift it. Use a pay-as-you-go Meta API key with the meta-model provider instead (export it as META_MODEL_API_KEY); OpenCodex cannot serve this request with a Muse Code subscription key.";
|
|
36
|
+
|
|
37
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
38
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Only a 403 error envelope carrying Meta's whole sentence is evidence. */
|
|
42
|
+
export function isMetaMusePlanRefusal(status: number, payload: unknown): boolean {
|
|
43
|
+
if (status !== 403 || !record(payload) || !record(payload.error)) return false;
|
|
44
|
+
const error = payload.error;
|
|
45
|
+
if (typeof error.message !== "string" || error.message.length > MAX_REFUSAL_CHARS) return false;
|
|
46
|
+
if (error.type != null && (typeof error.type !== "string" || !PERMISSION_TYPES.has(error.type))) return false;
|
|
47
|
+
if (error.code != null && (typeof error.code !== "string" || !PERMISSION_CODES.has(error.code))) return false;
|
|
48
|
+
return PLAN_REFUSAL.test(error.message.trim());
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The same evidence after HTTP error formatting, which frames the body as `Provider error 403: …`.
|
|
53
|
+
* A bare sentence body is accepted too: the refusal is the whole payload either way, and the
|
|
54
|
+
* sentence is the only thing that grants the verdict.
|
|
55
|
+
*/
|
|
56
|
+
export function isMetaMusePlanFailure(status: number, message: string): boolean {
|
|
57
|
+
if (status !== 403 || typeof message !== "string" || message.length > MAX_REFUSAL_CHARS) return false;
|
|
58
|
+
let text = message.trim();
|
|
59
|
+
// This proxy's own copy re-enters later formatters; keep it in the same class without re-reading
|
|
60
|
+
// upstream bytes.
|
|
61
|
+
if (text === META_MUSE_PLAN_REFUSAL_MESSAGE) return true;
|
|
62
|
+
const prefix = `Provider error ${status}: `;
|
|
63
|
+
if (text.startsWith(prefix)) text = text.slice(prefix.length).trim();
|
|
64
|
+
if (text === META_MUSE_PLAN_REFUSAL_MESSAGE) return true;
|
|
65
|
+
try {
|
|
66
|
+
const payload: unknown = JSON.parse(text);
|
|
67
|
+
if (isMetaMusePlanRefusal(status, payload)) return true;
|
|
68
|
+
// The proxy's own error envelope carrying its own sentence: a later pass that re-parses the
|
|
69
|
+
// rewritten body keeps the class.
|
|
70
|
+
if (record(payload) && record(payload.error) && payload.error.message === META_MUSE_PLAN_REFUSAL_MESSAGE) return true;
|
|
71
|
+
} catch {
|
|
72
|
+
// A non-JSON body falls through to the whole-sentence test below.
|
|
73
|
+
}
|
|
74
|
+
return PLAN_REFUSAL.test(text);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Stamp the plan-restriction cause on a request row and return the client sentence, or undefined
|
|
79
|
+
* for any other failure.
|
|
80
|
+
*
|
|
81
|
+
* The cause is stamped at the site that proved it: the status alone cannot tell this 403 from a
|
|
82
|
+
* rejected credential, and `quota-exhausted` is the closed roster's plan/entitlement class, whose
|
|
83
|
+
* resend verdict is `refused-futile`. `causeHint` outranks the status table in
|
|
84
|
+
* `deriveRequestFailureCause`, so both the row and the attempt report the plan class.
|
|
85
|
+
*/
|
|
86
|
+
export function stampMetaMusePlanRefusal(
|
|
87
|
+
logCtx: { causeHint?: RequestFailureCause },
|
|
88
|
+
status: number,
|
|
89
|
+
bodyText: string,
|
|
90
|
+
): string | undefined {
|
|
91
|
+
if (!isMetaMusePlanFailure(status, bodyText)) return undefined;
|
|
92
|
+
logCtx.causeHint = "quota-exhausted";
|
|
93
|
+
return META_MUSE_PLAN_REFUSAL_MESSAGE;
|
|
94
|
+
}
|
|
@@ -103,6 +103,8 @@ export const PROVIDER_MODEL_RENAME_ROLES = {
|
|
|
103
103
|
modelSupportsVerbosity: "record",
|
|
104
104
|
supportsVerbosity: "none",
|
|
105
105
|
modelReasoningSummaryDelivery: "record",
|
|
106
|
+
thinkingDisplay: "none",
|
|
107
|
+
modelThinkingDisplay: "record",
|
|
106
108
|
modelPreferHostedTools: "record",
|
|
107
109
|
supportsOpenAiWebSearchToolFields: "none",
|
|
108
110
|
xaiResponsesXSearch: "none",
|
|
@@ -119,6 +121,7 @@ export const PROVIDER_MODEL_RENAME_ROLES = {
|
|
|
119
121
|
noTemperatureModels: "list",
|
|
120
122
|
noTopPModels: "list",
|
|
121
123
|
noStopModels: "list",
|
|
124
|
+
arkKimiResponsesModels: "list",
|
|
122
125
|
noPenaltyModels: "list",
|
|
123
126
|
noStructuredOutputModels: "list",
|
|
124
127
|
noJsonSchemaModels: "list",
|
|
@@ -14,7 +14,14 @@ export function parseAnthropicFamilyHeaders(headers: Headers, now: number, statu
|
|
|
14
14
|
...(resetAt !== undefined && resetAt > 0 && Number.isFinite(new Date(resetAt).getTime()) ? { resetAt } : {}) }];
|
|
15
15
|
}
|
|
16
16
|
export function mergeAnthropicFamilyWindows(previous: ProviderQuotaWindow[] = [], observed: ProviderQuotaWindow[] = []): ProviderQuotaWindow[] {
|
|
17
|
-
|
|
17
|
+
const same = (a: ProviderQuotaWindow, b: ProviderQuotaWindow) => a.label === b.label && a.scope === b.scope;
|
|
18
|
+
// Headers carry no allowance; the share is a seat policy the last usage probe already read.
|
|
19
|
+
// A probe window (no passiveObservedAt) is itself that reading, so a missing share stays missing.
|
|
20
|
+
return [...previous.filter(window => !observed.some(update => same(update, window))), ...observed.map(update => {
|
|
21
|
+
const allowance = update.weeklyAllowancePercent === undefined && update.passiveObservedAt !== undefined
|
|
22
|
+
? previous.find(window => same(window, update))?.weeklyAllowancePercent : undefined;
|
|
23
|
+
return allowance === undefined ? update : { ...update, weeklyAllowancePercent: allowance };
|
|
24
|
+
})];
|
|
18
25
|
}
|
|
19
26
|
|
|
20
27
|
const enumerated = new WeakSet<object>();
|