@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.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 +23 -1
- package/bin/ocx.mjs +8 -1
- package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
- package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
- package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
- package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
- package/gui/dist/assets/index-DJxM-imn.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
- package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
- package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
- package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
- package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/src/cli.rs +5 -3
- package/native/ocx-child/src/codex_home.rs +1 -0
- package/native/ocx-child/src/link_ws.rs +24 -19
- package/native/ocx-child/src/link_ws_frame.rs +136 -50
- package/package.json +3 -3
- package/src/adapters/anthropic/per-message-effort.ts +296 -0
- package/src/adapters/anthropic-input-schema.ts +270 -0
- package/src/adapters/anthropic.ts +4 -63
- package/src/adapters/claude-cli/adapter.ts +1 -0
- package/src/adapters/command-code-tool-text.ts +9 -1
- package/src/adapters/command-code.ts +18 -2
- package/src/adapters/devin/cloud-direct/chat.ts +95 -14
- package/src/adapters/devin/live-models.ts +11 -1
- package/src/adapters/google-errors.ts +14 -2
- package/src/adapters/kiro/reasoning.ts +3 -0
- package/src/adapters/kiro-tools.ts +14 -9
- package/src/adapters/openai-responses/passthrough.ts +3 -1
- package/src/adapters/openai-responses/request-strips.ts +1 -0
- package/src/adapters/qoder/adapter.ts +9 -1
- package/src/adapters/tool-catalog-nudge.ts +1 -1
- package/src/adapters/zed.ts +4 -2
- package/src/claude/chat-tool-dispatch.ts +4 -1
- package/src/claude/desktop-remote-store.ts +60 -10
- package/src/cli/account-api.ts +4 -0
- package/src/cli/account-auth.ts +30 -2
- package/src/cli/account-extended.ts +33 -2
- package/src/cli/capabilities-access-remote.ts +3 -3
- package/src/cli/capabilities-accounts.ts +3 -3
- package/src/cli/capabilities-base.ts +11 -6
- package/src/cli/capabilities-observe-system.ts +2 -2
- package/src/cli/claude.ts +3 -3
- package/src/cli/disconnect-runtime.ts +16 -6
- package/src/cli/dispatch.ts +7 -1
- package/src/cli/index.ts +2 -2
- package/src/cli/link-apply-restart.ts +4 -2
- package/src/cli/link-routes.ts +4 -1
- package/src/cli/link.ts +5 -4
- package/src/cli/logout-command.ts +23 -4
- package/src/cli/preflight-exemptions.ts +3 -0
- package/src/cli/provider.ts +3 -2
- package/src/cli/registry.ts +5 -2
- package/src/cli/resolve.ts +23 -8
- package/src/cli/restart-failure.ts +11 -1
- package/src/cli/runtime-api.ts +4 -0
- package/src/cli/status.ts +4 -1
- package/src/cli/system-command.ts +1 -1
- package/src/cli/system-restart-client.ts +9 -3
- package/src/cli/system-settings-parity.ts +2 -1
- package/src/client/connect.ts +73 -11
- package/src/client/desktop-refusal.ts +38 -0
- package/src/client/lifecycle-lock.ts +29 -4
- package/src/client/runtime-restart.ts +27 -15
- package/src/client/runtime.ts +4 -2
- package/src/client/state.ts +14 -0
- package/src/clients/config-export.ts +12 -7
- package/src/codex/account-lifecycle.ts +3 -1
- package/src/codex/account-pause.ts +4 -0
- package/src/codex/account-runtime-state.ts +4 -0
- package/src/codex/auth-api/main-account-probe.ts +3 -1
- package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
- package/src/codex/auth-context.ts +40 -2
- package/src/codex/catalog/build-entries.ts +10 -0
- package/src/codex/catalog/derive-entry.ts +7 -0
- package/src/codex/catalog/metadata.ts +8 -0
- package/src/codex/catalog/native-models.ts +16 -6
- package/src/codex/catalog/pinned-models.ts +1 -0
- package/src/codex/catalog/provider-models.ts +5 -5
- package/src/codex/catalog/reserve-warn.ts +7 -5
- package/src/codex/catalog/reserve.ts +4 -3
- package/src/codex/catalog/retained-sync.ts +2 -0
- package/src/codex/catalog/routed-defaults.ts +35 -0
- package/src/codex/catalog-auto-refresh.ts +13 -2
- package/src/codex/config-drift-heal.ts +40 -12
- package/src/codex/config-write-lock.ts +39 -1
- package/src/codex/convergence.ts +2 -0
- package/src/codex/data/roster-pinned-models.json +346 -1
- package/src/codex/inject/config-write-section.ts +39 -1
- package/src/codex/inject/plan.ts +10 -8
- package/src/codex/inject/remove.ts +21 -19
- package/src/codex/inject/restore.ts +5 -1
- package/src/codex/inject-coordination.ts +58 -7
- package/src/codex/inject.ts +10 -12
- package/src/codex/journal-config-restore.ts +42 -0
- package/src/codex/journal.ts +62 -8
- package/src/codex/loopback-target.ts +22 -8
- package/src/codex/main-account.ts +94 -30
- package/src/codex/native-main-auth-file.ts +14 -0
- package/src/codex/native-main-credentials.ts +276 -0
- package/src/codex/native-main-owner.ts +3 -0
- package/src/codex/native-main-refresh-mode.ts +14 -1
- package/src/codex/quota.ts +63 -14
- package/src/combos/failover.ts +195 -1
- package/src/combos/index.ts +5 -0
- package/src/combos/resolve.ts +115 -19
- package/src/config/diagnostics.ts +3 -0
- package/src/config/live-reconcile.ts +6 -3
- package/src/config/load-degrade.ts +2 -0
- package/src/config/persisted-mutation.ts +2 -2
- package/src/config/persisted-projections.ts +18 -0
- package/src/config/process-state.ts +4 -3
- package/src/config/reserve-capability.ts +96 -0
- package/src/config/schema/config-schema.ts +6 -0
- package/src/config/schema/leaf-validators.ts +2 -0
- package/src/config/schema/routed-catalog-defaults.ts +49 -0
- package/src/config/subagent-models.ts +20 -12
- package/src/config.ts +7 -7
- package/src/desktop-update/acquire.ts +202 -0
- package/src/desktop-update/cli.ts +168 -0
- package/src/desktop-update/drain.ts +40 -0
- package/src/desktop-update/headless.ts +285 -0
- package/src/desktop-update/image.ts +85 -0
- package/src/desktop-update/install.ts +53 -0
- package/src/desktop-update/msi.ts +72 -0
- package/src/desktop-update/release.ts +128 -0
- package/src/desktop-update/runtime.ts +155 -0
- package/src/desktop-update/staging.ts +118 -0
- package/src/desktop-update/trust.ts +45 -0
- package/src/generated/compatibility-version.json +327 -195
- package/src/generated/model-metadata.ts +3 -3
- package/src/images/fulfill-video.ts +3 -3
- package/src/images/loop.ts +6 -2
- package/src/images/plan.ts +147 -11
- package/src/images/types.ts +13 -4
- package/src/images/xai-video-client.ts +72 -10
- package/src/lib/client-error-body.ts +6 -0
- package/src/lib/developer-role-rejection.ts +15 -0
- package/src/lib/gcp-adc.ts +48 -4
- package/src/lib/offline-resend.ts +150 -0
- package/src/lib/paced-stream.ts +3 -3
- package/src/lib/provider-outbound.ts +17 -6
- package/src/lib/request-failure-model.ts +2 -0
- package/src/lib/response-body-inactivity.ts +23 -1
- package/src/lib/upstream-retry.ts +39 -6
- package/src/link/explicit-route.ts +4 -4
- package/src/link/remote-windows.ts +79 -31
- package/src/link/residual-recovery.ts +20 -8
- package/src/messaging/budget.ts +23 -5
- package/src/messaging/remote-ports.ts +22 -10
- package/src/messaging/rpc.ts +4 -4
- package/src/oauth/antigravity-risk.ts +126 -0
- package/src/oauth/credential-siblings.ts +32 -0
- package/src/oauth/generic-account-failover.ts +113 -30
- package/src/oauth/generic-session-affinity.ts +10 -3
- package/src/oauth/index.ts +22 -14
- package/src/oauth/login-cli.ts +35 -1
- package/src/oauth/pool-kernel.ts +3 -3
- package/src/oauth/store.ts +38 -7
- package/src/providers/anthropic-billing-refusal.ts +27 -3
- package/src/providers/anthropic-reset-grants.ts +4 -0
- package/src/providers/claude-cli-usage.ts +2 -0
- package/src/providers/codebuddy-models.ts +11 -0
- package/src/providers/google-vertex-model-discovery.ts +49 -15
- package/src/providers/kiro-models.ts +5 -0
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/quota/workbuddy.ts +6 -2
- package/src/providers/registry/entries-core.ts +9 -3
- package/src/providers/registry/entries-extended.ts +20 -9
- package/src/providers/registry/model-seeds.ts +4 -1
- package/src/providers/stale-context-window-migration.ts +2 -0
- package/src/providers/workbuddy-credit-balance.ts +125 -16
- package/src/responses/citation-markers.ts +26 -23
- package/src/responses/effort-history.ts +732 -0
- package/src/routing/history/integrity.ts +41 -4
- package/src/server/auth-cors.ts +13 -3
- package/src/server/codex-model-list.ts +2 -1
- package/src/server/direct-local-http.ts +26 -3
- package/src/server/index/link-listener.ts +20 -14
- package/src/server/index/serve-options.ts +1 -0
- package/src/server/index.ts +3 -2
- package/src/server/link-turn.ts +17 -5
- package/src/server/management/config-routes.ts +39 -3
- package/src/server/management/link-child-preflight.ts +1 -1
- package/src/server/management/link-enrollment.ts +3 -3
- package/src/server/management/link-route-edit.ts +20 -1
- package/src/server/management/link-route-request.ts +11 -5
- package/src/server/management/oauth-account-routes.ts +43 -13
- package/src/server/management/provider-credential-release.ts +44 -0
- package/src/server/management/provider-overwrite-carry.ts +3 -0
- package/src/server/management/provider-routes.ts +12 -12
- package/src/server/management/static-catalog-probe.ts +33 -0
- package/src/server/management/usage-aggregate-cache.ts +6 -3
- package/src/server/messages-native.ts +16 -2
- package/src/server/proxy-liveness.ts +54 -9
- package/src/server/relay.ts +6 -1
- package/src/server/request-log-conversation.ts +8 -4
- package/src/server/request-log-failure-detail.ts +26 -9
- package/src/server/request-log.ts +5 -1
- package/src/server/reserve-capability-startup.ts +32 -0
- package/src/server/responses/adapter-continuation.ts +59 -25
- package/src/server/responses/adapter-delivery.ts +2 -0
- package/src/server/responses/adapter-dispatch.ts +39 -18
- package/src/server/responses/antigravity-fault-rotation.ts +24 -0
- package/src/server/responses/antigravity-validation-refusal.ts +43 -6
- package/src/server/responses/codex-tool-catalog.ts +47 -10
- package/src/server/responses/combo-selection-keepalive.ts +254 -0
- package/src/server/responses/combo-session-recall.ts +26 -1
- package/src/server/responses/combo-stream-preflight.ts +35 -26
- package/src/server/responses/core-combo-failure.ts +6 -0
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +67 -28
- package/src/server/responses/core-errors.ts +9 -6
- package/src/server/responses/core-options.ts +10 -0
- package/src/server/responses/core.ts +21 -0
- package/src/server/responses/estimated-usage.ts +115 -0
- package/src/server/responses/input-admission.ts +41 -3
- package/src/server/responses/jev-model-invoke.ts +7 -2
- package/src/server/responses/passthrough-completion.ts +6 -3
- package/src/server/responses/passthrough-delivery.ts +47 -8
- package/src/server/responses/passthrough-dispatch.ts +3 -0
- package/src/server/responses/request-prepare.ts +9 -5
- package/src/server/responses/request-send-budget.ts +1 -1
- package/src/server/responses/request-transport.ts +10 -2
- package/src/server/responses/sidecar-execution.ts +11 -4
- package/src/service/desktop-supervision.d.mts +2 -0
- package/src/service/desktop-supervision.mjs +5 -0
- package/src/service/windows-checked-stop-live.ts +28 -5
- package/src/stall-timeout.ts +11 -0
- package/src/types/config.ts +15 -92
- package/src/types/provider.ts +13 -0
- package/src/types/request.ts +23 -3
- package/src/types/routed-catalog-defaults.ts +17 -0
- package/src/types/routing-profile.ts +90 -0
- package/src/types.ts +1 -0
- package/src/update/index.ts +1 -1
- package/src/usage/expected-prices.ts +35 -0
- package/src/usage/ledger-scanner.ts +44 -10
- package/src/usage/log.ts +14 -4
- package/src/usage/telemetry-contract.ts +1 -0
- package/src/web-search/loop.ts +20 -2
- package/src/web-search/parse.ts +2 -12
- package/src/web-search/passthrough-bridge.ts +7 -0
- package/src/web-search/sources.ts +13 -0
- package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
- package/gui/dist/assets/index-DQtCRNAw.css +0 -2
- package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
|
@@ -38,6 +38,14 @@ import {
|
|
|
38
38
|
waitForLoginSettled,
|
|
39
39
|
} from "../../oauth";
|
|
40
40
|
import { OAuthMutationBusyError, removeCredential } from "../../oauth/store";
|
|
41
|
+
import { isOAuthCredentialSiblingOf, oauthCredentialSiblingsOf, oauthCredentialSlot } from "../../oauth/credential-siblings";
|
|
42
|
+
import {
|
|
43
|
+
ANTIGRAVITY_RISK_PROVIDER,
|
|
44
|
+
ANTIGRAVITY_RISK_REFUSAL_CODE,
|
|
45
|
+
antigravityRiskRefusalBody,
|
|
46
|
+
hasAntigravityRiskAcknowledgement,
|
|
47
|
+
requiresAntigravityRiskAcknowledgement,
|
|
48
|
+
} from "../../oauth/antigravity-risk";
|
|
41
49
|
import { cancelKiroDeviceLogin, kiroDeviceConfigBaseline, selectKiroDeviceProfile, startKiroDeviceLogin, statusKiroDeviceLogin, type KiroDeviceMethod } from "../../oauth/kiro-device-login";
|
|
42
50
|
import { parseKiroIamOptions } from "../../oauth/kiro-iam-identity-center";
|
|
43
51
|
import { providerDestinationResolvedError } from "../../lib/destination-policy";
|
|
@@ -265,9 +273,18 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
265
273
|
// the provider's loopback callback server (inside this process) captures the redirect in the
|
|
266
274
|
// background, then the credential is persisted. The GUI opens the URL and polls /api/oauth/status.
|
|
267
275
|
if (url.pathname === "/api/oauth/login" && req.method === "POST") {
|
|
268
|
-
const body = await readManagementJsonBodyOr(req, {}) as { provider?: string; addAccount?: boolean; accountId?: string; reauth?: boolean; openBrowser?: unknown; method?: unknown; mode?: unknown; device?: unknown; startUrl?: unknown; region?: unknown; flowId?: unknown; profileArn?: unknown };
|
|
276
|
+
const body = await readManagementJsonBodyOr(req, {}) as { provider?: string; row?: unknown; addAccount?: boolean; accountId?: string; reauth?: boolean; openBrowser?: unknown; method?: unknown; mode?: unknown; device?: unknown; startUrl?: unknown; region?: unknown; flowId?: unknown; profileArn?: unknown };
|
|
269
277
|
const provider = (body.provider ?? "").trim().toLowerCase();
|
|
270
278
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
279
|
+
// `row`: the sibling provider row this login publishes (Kimi (Responses) through the Kimi login).
|
|
280
|
+
if (body.row !== undefined && (typeof body.row !== "string" || !isOAuthCredentialSiblingOf(body.row, provider))) {
|
|
281
|
+
return jsonResponse({ error: "row must be a provider that shares this login" }, 400);
|
|
282
|
+
}
|
|
283
|
+
// Antigravity sign-in can get the Google account disabled. Every client asks first; this is
|
|
284
|
+
// the check none of them can skip, and it runs before any flow state is created.
|
|
285
|
+
if (requiresAntigravityRiskAcknowledgement(provider) && !hasAntigravityRiskAcknowledgement(body)) {
|
|
286
|
+
return jsonResponse(antigravityRiskRefusalBody(), 403);
|
|
287
|
+
}
|
|
271
288
|
// Omitted mode is the localhost-callback flow this route has always run.
|
|
272
289
|
if (body.mode !== undefined && body.mode !== "callback" && body.mode !== "code") {
|
|
273
290
|
return jsonResponse({ error: "mode must be \"callback\" or \"code\"" }, 400);
|
|
@@ -340,6 +357,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
340
357
|
...(accountId ? { reauthAccountId: accountId } : {}),
|
|
341
358
|
...(codeMode ? { codeMode: true } : {}),
|
|
342
359
|
...(device ? { flow: "device" as const } : {}),
|
|
360
|
+
...(typeof body.row === "string" ? { publishRow: body.row } : {}),
|
|
343
361
|
}, {
|
|
344
362
|
...(flowId ? { flowId } : {}),
|
|
345
363
|
// startLoginFlow returns the authorization URL before background persistence completes.
|
|
@@ -467,7 +485,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
467
485
|
}
|
|
468
486
|
|
|
469
487
|
if (url.pathname === "/api/oauth/status" && req.method === "GET") {
|
|
470
|
-
const provider = (url.searchParams.get("provider") ?? "").trim().toLowerCase();
|
|
488
|
+
const provider = oauthCredentialSlot((url.searchParams.get("provider") ?? "").trim().toLowerCase());
|
|
471
489
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
472
490
|
if (provider === "kiro" && url.searchParams.has("flowId")) {
|
|
473
491
|
const flowId = url.searchParams.get("flowId") ?? "";
|
|
@@ -488,7 +506,9 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
488
506
|
}
|
|
489
507
|
|
|
490
508
|
if (url.pathname === "/api/oauth/logout" && req.method === "POST") {
|
|
491
|
-
|
|
509
|
+
// A sibling row (kimi-responses) has no login of its own: logging out of it removes the
|
|
510
|
+
// active account of the shared slot, exactly as the neighbouring account routes map it.
|
|
511
|
+
const provider = oauthCredentialSlot((url.searchParams.get("provider") ?? "").trim().toLowerCase());
|
|
492
512
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
493
513
|
await removeCredential(provider);
|
|
494
514
|
reconcileLiveStateStores();
|
|
@@ -496,6 +516,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
496
516
|
const { clearModelCache } = await import("../../codex/model-cache");
|
|
497
517
|
const { clearGatherRoutedModelsInflight } = await import("../../codex/catalog");
|
|
498
518
|
clearModelCache(provider);
|
|
519
|
+
for (const row of oauthCredentialSiblingsOf(provider)) clearModelCache(row);
|
|
499
520
|
clearGatherRoutedModelsInflight();
|
|
500
521
|
// Drop cached/last-good quota rows tied to the removed credential.
|
|
501
522
|
clearQuotaCachesAfterAccountMutation(provider, true);
|
|
@@ -512,7 +533,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
512
533
|
// one, or remove one. Emails and accountLabel follow privacy.maskEmails, maskedLabel is always
|
|
513
534
|
// masked, and tokens never leave the store.
|
|
514
535
|
if (url.pathname === "/api/oauth/accounts" && req.method === "GET") {
|
|
515
|
-
const provider = (url.searchParams.get("provider") ?? "").trim().toLowerCase();
|
|
536
|
+
const provider = oauthCredentialSlot((url.searchParams.get("provider") ?? "").trim().toLowerCase());
|
|
516
537
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
517
538
|
const quotaMode = providerOAuthAccountQuotaMode(provider);
|
|
518
539
|
const quotaProvider = config.providers[provider];
|
|
@@ -606,7 +627,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
606
627
|
}
|
|
607
628
|
if (url.pathname === "/api/oauth/accounts/active" && req.method === "PUT") {
|
|
608
629
|
const body = await readManagementJsonBodyOr(req, {}) as { provider?: string; accountId?: string };
|
|
609
|
-
const provider = (body.provider ?? "").trim().toLowerCase();
|
|
630
|
+
const provider = oauthCredentialSlot((body.provider ?? "").trim().toLowerCase());
|
|
610
631
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
611
632
|
if (provider === "anthropic2" && !configuredAnthropicInstance(config, provider)) return jsonResponse({ error: "Anthropic pool instance is not configured" }, 409);
|
|
612
633
|
if (!body.accountId) return jsonResponse({ error: "missing accountId" }, 400);
|
|
@@ -619,14 +640,13 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
619
640
|
if (!latest) return jsonResponse({ error: "account not found" }, 404);
|
|
620
641
|
return jsonResponse({ error: latest.paused ? "account is paused" : "account selection changed" }, 409);
|
|
621
642
|
}
|
|
622
|
-
const { forgetGenericFailoverRoster } = await import("../../oauth/generic-account-failover");
|
|
643
|
+
const { forgetGenericFailoverRoster, seedGenericPoolSelection } = await import("../../oauth/generic-account-failover");
|
|
623
644
|
forgetGenericFailoverRoster(provider);
|
|
624
645
|
// Seed the rotation cursor on the operator's pick, or a sticky round-robin ring hands the
|
|
625
646
|
// very next dispatch back to whatever the pool had chosen. forgetGenericFailoverRoster
|
|
626
647
|
// only drops the presence count; it has never touched the cursor. Same defect the Codex
|
|
627
648
|
// side carries resetCodexRoutingForManualSelection for.
|
|
628
|
-
|
|
629
|
-
seedPoolRotationAccount(genericPoolKey(provider), body.accountId);
|
|
649
|
+
seedGenericPoolSelection(provider, body.accountId);
|
|
630
650
|
const anthropicRouting = isAnthropicOAuthInstance(provider)
|
|
631
651
|
? (await import("../../oauth/anthropic-routing")).anthropicRoutingFor(provider) : undefined;
|
|
632
652
|
anthropicRouting?.resetAnthropicRoutingForManualSelection(body.accountId);
|
|
@@ -634,6 +654,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
634
654
|
const { clearModelCache } = await import("../../codex/model-cache");
|
|
635
655
|
const { clearGatherRoutedModelsInflight } = await import("../../codex/catalog");
|
|
636
656
|
clearModelCache(provider);
|
|
657
|
+
// A shared-login row (kimi-responses) caches its roster under its own name.
|
|
658
|
+
for (const row of oauthCredentialSiblingsOf(provider)) clearModelCache(row);
|
|
637
659
|
clearGatherRoutedModelsInflight();
|
|
638
660
|
clearQuotaCachesAfterAccountMutation(provider, false);
|
|
639
661
|
if (affinityReset && !await affinityReset) {
|
|
@@ -648,7 +670,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
648
670
|
if (url.pathname === "/api/oauth/accounts/pause" && req.method === "PUT") {
|
|
649
671
|
const body = await readManagementJsonBodyOr(req, {});
|
|
650
672
|
if (!isPlainRecord(body)) return jsonResponse({ error: "body must be an object" }, 400);
|
|
651
|
-
const provider = typeof body.provider === "string" ? body.provider.trim().toLowerCase() : "";
|
|
673
|
+
const provider = oauthCredentialSlot(typeof body.provider === "string" ? body.provider.trim().toLowerCase() : "");
|
|
652
674
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
653
675
|
if (typeof body.accountId !== "string" || body.accountId.length === 0) {
|
|
654
676
|
return jsonResponse({ error: "missing accountId" }, 400);
|
|
@@ -710,12 +732,13 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
710
732
|
}
|
|
711
733
|
if (result.activeAccountChanged) {
|
|
712
734
|
if (!anthropicRouting) {
|
|
713
|
-
const {
|
|
714
|
-
|
|
735
|
+
const { seedGenericPoolSelection } = await import("../../oauth/generic-account-failover");
|
|
736
|
+
seedGenericPoolSelection(provider, result.activeAccountId);
|
|
715
737
|
}
|
|
716
738
|
const { clearModelCache } = await import("../../codex/model-cache");
|
|
717
739
|
const { clearGatherRoutedModelsInflight } = await import("../../codex/catalog");
|
|
718
740
|
clearModelCache(provider);
|
|
741
|
+
for (const row of oauthCredentialSiblingsOf(provider)) clearModelCache(row);
|
|
719
742
|
clearGatherRoutedModelsInflight();
|
|
720
743
|
clearQuotaCachesAfterAccountMutation(provider, false);
|
|
721
744
|
}
|
|
@@ -1073,6 +1096,12 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
1073
1096
|
if (!isPlainRecord(rawBody)) return jsonResponse({ code: "invalid_document" }, 400);
|
|
1074
1097
|
const provider = typeof rawBody.provider === "string" ? rawBody.provider : "";
|
|
1075
1098
|
const format = typeof rawBody.format === "string" ? rawBody.format : "";
|
|
1099
|
+
// An imported Antigravity credential carries the same account risk as a fresh login. Import
|
|
1100
|
+
// admits only the exact provider id, so the gate matches it exactly too; other spellings
|
|
1101
|
+
// keep their unsupported_provider answer.
|
|
1102
|
+
if (provider === ANTIGRAVITY_RISK_PROVIDER && !hasAntigravityRiskAcknowledgement(rawBody)) {
|
|
1103
|
+
return jsonResponse({ code: ANTIGRAVITY_RISK_REFUSAL_CODE }, 403);
|
|
1104
|
+
}
|
|
1076
1105
|
const { importAccounts } = await import("../../oauth/account-import");
|
|
1077
1106
|
const imported = await importAccounts({
|
|
1078
1107
|
provider,
|
|
@@ -1101,7 +1130,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
1101
1130
|
|
|
1102
1131
|
if (url.pathname === "/api/oauth/accounts/alias" && req.method === "PUT") {
|
|
1103
1132
|
const body = await readManagementJsonBodyOr(req, {}) as { provider?: unknown; accountId?: unknown; alias?: unknown };
|
|
1104
|
-
const provider = typeof body.provider === "string" ? body.provider.trim().toLowerCase() : "";
|
|
1133
|
+
const provider = oauthCredentialSlot(typeof body.provider === "string" ? body.provider.trim().toLowerCase() : "");
|
|
1105
1134
|
const accountId = typeof body.accountId === "string" ? body.accountId.trim() : "";
|
|
1106
1135
|
const alias = typeof body.alias === "string" ? body.alias.trim() : "";
|
|
1107
1136
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
@@ -1114,7 +1143,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
1114
1143
|
return jsonResponse({ ok: true, provider, accountId, alias: alias || null });
|
|
1115
1144
|
}
|
|
1116
1145
|
if (url.pathname === "/api/oauth/accounts" && req.method === "DELETE") {
|
|
1117
|
-
const provider = (url.searchParams.get("provider") ?? "").trim().toLowerCase();
|
|
1146
|
+
const provider = oauthCredentialSlot((url.searchParams.get("provider") ?? "").trim().toLowerCase());
|
|
1118
1147
|
const id = url.searchParams.get("id") ?? "";
|
|
1119
1148
|
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
|
|
1120
1149
|
if (!id) return jsonResponse({ error: "missing id" }, 400);
|
|
@@ -1141,6 +1170,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
|
|
|
1141
1170
|
const { clearModelCache } = await import("../../codex/model-cache");
|
|
1142
1171
|
const { clearGatherRoutedModelsInflight } = await import("../../codex/catalog");
|
|
1143
1172
|
clearModelCache(provider);
|
|
1173
|
+
for (const row of oauthCredentialSiblingsOf(provider)) clearModelCache(row);
|
|
1144
1174
|
clearGatherRoutedModelsInflight();
|
|
1145
1175
|
clearQuotaCachesAfterAccountMutation(provider, true);
|
|
1146
1176
|
// Same reasoning as logout. Removing the last account for a provider used to
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { OcxConfig, OcxProviderConfig } from "../../types";
|
|
2
|
+
import { oauthCredentialSlot } from "../../oauth/credential-siblings";
|
|
3
|
+
import { releaseProviderAccountSetUnlessRetained } from "../../oauth/store";
|
|
4
|
+
import { getProviderRegistryEntry } from "../../providers/registry";
|
|
5
|
+
import { providerUsesKeyAuthOverride } from "../../providers/key-store";
|
|
6
|
+
import { readConfigFileSnapshot } from "../../config/diagnostics";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Whether a configured row signs in through its OAuth login, decided the way routing decides it
|
|
10
|
+
* (src/providers/routed-config.ts): a registry OAuth entry is OAuth whatever `authMode` says
|
|
11
|
+
* (including omitted), unless the entry allows a key override and the row selects it.
|
|
12
|
+
*/
|
|
13
|
+
export function rowUsesOAuthLogin(row: string, provider: OcxProviderConfig): boolean {
|
|
14
|
+
const entry = getProviderRegistryEntry(row);
|
|
15
|
+
if (entry?.authKind === "oauth") return !providerUsesKeyAuthOverride(entry, provider);
|
|
16
|
+
return provider.authMode === "oauth";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Release the OAuth login a removed provider row used, unless another remaining OAuth row
|
|
21
|
+
* still signs in through the same login. `config` must already be without the removed row.
|
|
22
|
+
*
|
|
23
|
+
* Kimi and Kimi (Responses) share one login (src/oauth/credential-siblings.ts): removing one of
|
|
24
|
+
* the two rows keeps the login the other still uses, and removing the last one releases it, so
|
|
25
|
+
* neither row is left on a credential it no longer owns. The "still used" check runs inside the
|
|
26
|
+
* serialized store write and reads both the live `config` and the persisted config.json, so a
|
|
27
|
+
* row published while the release waited (by this process or another, including a re-created row
|
|
28
|
+
* of the removed name) keeps the login instead of losing it.
|
|
29
|
+
*/
|
|
30
|
+
export async function releaseRemovedProviderCredentials(
|
|
31
|
+
config: OcxConfig,
|
|
32
|
+
name: string,
|
|
33
|
+
release: typeof releaseProviderAccountSetUnlessRetained = releaseProviderAccountSetUnlessRetained,
|
|
34
|
+
): Promise<"released" | "retained"> {
|
|
35
|
+
const slot = oauthCredentialSlot(name);
|
|
36
|
+
// `config` no longer holds the removed row, so any row named `name` here was re-created.
|
|
37
|
+
const usesSlot = (providers: OcxConfig["providers"]): boolean => Object.entries(providers).some(([row, provider]) =>
|
|
38
|
+
oauthCredentialSlot(row) === slot && rowUsesOAuthLogin(row, provider));
|
|
39
|
+
return release(name, () => {
|
|
40
|
+
if (usesSlot(config.providers)) return true;
|
|
41
|
+
const persisted = readConfigFileSnapshot({ passive: true }).diagnostics;
|
|
42
|
+
return persisted.source === "file" && usesSlot(persisted.config.providers);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -75,6 +75,9 @@ export const PROVIDER_DISPLAY_CARRY_FIELDS = [
|
|
|
75
75
|
// cannot send either, so an unrelated save must not silently return the model to the default.
|
|
76
76
|
"thinkingDisplay",
|
|
77
77
|
"modelThinkingDisplay",
|
|
78
|
+
// The experimental Anthropic per-message effort switch (#6895) is operator configuration the form
|
|
79
|
+
// cannot send; an unrelated save must not silently turn it off.
|
|
80
|
+
"perMessageEffort",
|
|
78
81
|
] as const satisfies readonly (keyof OcxProviderConfig)[];
|
|
79
82
|
|
|
80
83
|
export type ProviderCompatCarryField = typeof PROVIDER_COMPAT_CARRY_FIELDS[number];
|
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
import { commitProviderPatch } from "./provider-patch-transaction";
|
|
43
43
|
import { captureConfigTopLevelRollback } from "../../config/rebase-provenance";
|
|
44
44
|
import { canonicalAutoReviewModelKey, mergeModelPinnedEfforts, modelPinnedEffortsConfigError, pinnedReasoningEffortConfigError } from "../../config/provider-validation";
|
|
45
|
-
import {
|
|
45
|
+
import { releaseRemovedProviderCredentials } from "./provider-credential-release";
|
|
46
46
|
import { captureModelsOAuthTarget, mayResolveModelsOAuth, modelsOAuthTargetMatches } from "../../oauth/model-discovery-auth";
|
|
47
47
|
import { providerDestinationResolvedError } from "../../lib/destination-policy";
|
|
48
48
|
import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
|
|
@@ -1651,10 +1651,10 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
|
|
|
1651
1651
|
return jsonResponse(await probeJevDecisionProvider(config, name, { signal: req.signal }));
|
|
1652
1652
|
}
|
|
1653
1653
|
if (prov.liveModels === false) {
|
|
1654
|
-
//
|
|
1655
|
-
//
|
|
1656
|
-
|
|
1657
|
-
return jsonResponse(
|
|
1654
|
+
// No live discovery endpoint. Only Vertex ADC still has a credential to verify; every other
|
|
1655
|
+
// static catalog must stay before credential resolution/network access (e.g. Antigravity).
|
|
1656
|
+
const { staticCatalogConnectionTest } = await import("./static-catalog-probe");
|
|
1657
|
+
return jsonResponse(await staticCatalogConnectionTest(name, prov, req.signal));
|
|
1658
1658
|
}
|
|
1659
1659
|
const { buildModelsRequest, getModelsOAuthAccessSnapshot, resolveModelsAuthToken } = await import("../../oauth");
|
|
1660
1660
|
const antigravity = effectiveGoogleMode(name, prov) === "cloud-code-assist";
|
|
@@ -1732,21 +1732,21 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
|
|
|
1732
1732
|
// Same canonical-URL TUN transparency as catalog discovery: the registry's
|
|
1733
1733
|
// own fixed discovery URL survives purely-benchmark (Clash/Surge/Mihomo
|
|
1734
1734
|
// fake-IP) DNS without proxy env.
|
|
1735
|
-
const outboundDependencies = { isCanonicalUrl: isRegistryModelDiscoveryUrl,
|
|
1736
|
-
beforeSend: () => (!vertexAuth || vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers))
|
|
1735
|
+
const outboundDependencies = (requestUrl: string) => ({ isCanonicalUrl: isRegistryModelDiscoveryUrl,
|
|
1736
|
+
beforeSend: () => (!vertexAuth || vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers, requestUrl))
|
|
1737
1737
|
&& (prov.authMode !== "oauth" || (mayResolveModelsOAuth(name, config.providers[name])
|
|
1738
1738
|
&& modelsOAuthTargetMatches(name, config.providers[name], authorizedTarget)
|
|
1739
|
-
&& (name !== "anthropic2" || new URL(
|
|
1739
|
+
&& (name !== "anthropic2" || new URL(requestUrl).href === authorizedTarget))) });
|
|
1740
1740
|
const res = method === "POST"
|
|
1741
1741
|
? await providerOutboundPost(name, prov, modelsUrl, {
|
|
1742
1742
|
headers,
|
|
1743
1743
|
body: JSON.stringify({ project }),
|
|
1744
1744
|
signal: AbortSignal.timeout(8000),
|
|
1745
|
-
}, outboundDependencies)
|
|
1745
|
+
}, outboundDependencies(modelsUrl))
|
|
1746
1746
|
: await providerOutboundGet(name, prov, modelsUrl, {
|
|
1747
1747
|
headers,
|
|
1748
1748
|
signal: vertexDeadline ?? AbortSignal.timeout(8000),
|
|
1749
|
-
}, outboundDependencies);
|
|
1749
|
+
}, outboundDependencies(modelsUrl));
|
|
1750
1750
|
const latencyMs = Date.now() - started;
|
|
1751
1751
|
const redirectError = await providerRedirectError(res, modelsUrl);
|
|
1752
1752
|
if (redirectError) {
|
|
@@ -1782,7 +1782,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
|
|
|
1782
1782
|
const listing = !ccaModels && vertexDeadline
|
|
1783
1783
|
? await collectVertexPublisherModelPages(modelsUrl, bounded.value,
|
|
1784
1784
|
{ ...discovery, firstPageBytes: vertexFirstPage?.bytes(), signal: vertexDeadline },
|
|
1785
|
-
(pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies))
|
|
1785
|
+
(pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies(pageUrl)))
|
|
1786
1786
|
: { ok: true as const, value: bounded.value };
|
|
1787
1787
|
if (!listing.ok) return jsonResponse({ ok: false, latencyMs, error: `upstream Vertex model listing is incomplete: ${listing.diagnostic}` });
|
|
1788
1788
|
// OpenAI-style lists (and Together top-level arrays) use the same validation/dedupe/filter
|
|
@@ -1861,7 +1861,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
|
|
|
1861
1861
|
// Deleting still succeeds; the response names the shadow-call target left without a provider.
|
|
1862
1862
|
const shadowDependency = shadowInterceptProviderDependency(config, name);
|
|
1863
1863
|
const droppedCustomModels = removeProviderWithGcpCredentials(config, name, fallbackDefault, save);
|
|
1864
|
-
await
|
|
1864
|
+
await releaseRemovedProviderCredentials(config, name);
|
|
1865
1865
|
reconcileLiveStateStores();
|
|
1866
1866
|
const { clearModelCache: clearCache } = await import("../../codex/model-cache");
|
|
1867
1867
|
clearCache(name);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { OcxProviderConfig } from "../../types";
|
|
2
|
+
import { vertexConfiguredCredentialKind } from "../../lib/gcp-adc";
|
|
3
|
+
import { resolveVertexDiscoveryAuth, selectVertexDiscoveryCredential, vertexDiscoveryDeadline } from "../../providers/google-vertex-model-discovery";
|
|
4
|
+
import { effectiveGoogleMode } from "../../providers/registry";
|
|
5
|
+
|
|
6
|
+
export type StaticCatalogProbeResult =
|
|
7
|
+
| { applicable: false; reason: "static_catalog"; latencyMs: 0 }
|
|
8
|
+
| { ok: boolean; latencyMs: number; message?: string; error?: string };
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Connection test for a provider without live model discovery. There is no models endpoint to
|
|
12
|
+
* call, so most such providers have nothing to test. Vertex on Application Default Credentials
|
|
13
|
+
* (or a `gcp-sa:` marker) still has a credential: minting an access token proves it, needs no
|
|
14
|
+
* model list, and is the same exchange the first real request performs. The probe forces a new
|
|
15
|
+
* exchange: a cached token would keep reporting ok for up to an hour after the credential is revoked.
|
|
16
|
+
*/
|
|
17
|
+
export async function staticCatalogConnectionTest(name: string, provider: OcxProviderConfig, signal?: AbortSignal): Promise<StaticCatalogProbeResult> {
|
|
18
|
+
if (effectiveGoogleMode(name, provider) !== "vertex") {
|
|
19
|
+
return { applicable: false, reason: "static_catalog", latencyMs: 0 };
|
|
20
|
+
}
|
|
21
|
+
// A literal key or a keychain:/${ENV} reference is an API key: answer before anything is resolved,
|
|
22
|
+
// so this probe never reads the credential store for a row it cannot test.
|
|
23
|
+
const configured = vertexConfiguredCredentialKind(provider.apiKey);
|
|
24
|
+
if (configured === "api-key" || configured === "reference" || selectVertexDiscoveryCredential(provider).kind === "api-key") {
|
|
25
|
+
return { applicable: false, reason: "static_catalog", latencyMs: 0 };
|
|
26
|
+
}
|
|
27
|
+
const started = Date.now();
|
|
28
|
+
const auth = await resolveVertexDiscoveryAuth(provider, vertexDiscoveryDeadline(signal), { forceExchange: true });
|
|
29
|
+
const latencyMs = Date.now() - started;
|
|
30
|
+
return auth
|
|
31
|
+
? { ok: true, latencyMs, message: "Google Cloud credentials verified (access token issued). Static model catalog; no live model list." }
|
|
32
|
+
: { ok: false, latencyMs, error: "Google Cloud credentials could not issue an access token. Check `gcloud auth application-default login` or GOOGLE_APPLICATION_CREDENTIALS." };
|
|
33
|
+
}
|
|
@@ -477,14 +477,18 @@ async function accumulateCandidates(
|
|
|
477
477
|
try {
|
|
478
478
|
let first = true;
|
|
479
479
|
for (;;) {
|
|
480
|
-
// Candidate selection
|
|
481
|
-
//
|
|
480
|
+
// Candidate selection is synchronous and bounded. Row decoding and accumulation also
|
|
481
|
+
// yield within each page; keep the page-boundary yield for cheap rows and SQL work.
|
|
482
482
|
if (!first) await new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
483
483
|
const offsets = read.nextPage();
|
|
484
484
|
if (!first && offsets.length === 0) break;
|
|
485
485
|
first = false;
|
|
486
486
|
const rows = await readUsageLedgerRowsAtOffsets({
|
|
487
487
|
offsets,
|
|
488
|
+
// This accumulator is private to the rebuild/append attempt and is discarded if the
|
|
489
|
+
// reader's final validation fails. Fold inside its time slice instead of retaining a
|
|
490
|
+
// page of parsed rows and then aggregating all of them in one synchronous turn.
|
|
491
|
+
onEntry: entry => accumulator.add(entry),
|
|
488
492
|
expectedIdentityKey: read.snapshot.identityKey,
|
|
489
493
|
// The offsets belong to this index snapshot. If the ledger moved since the snapshot,
|
|
490
494
|
// the reader re-validates the boundary before trusting any of them, and a rewrite of
|
|
@@ -499,7 +503,6 @@ async function accumulateCandidates(
|
|
|
499
503
|
// Serving only the rows that happened to parse would silently under-report the filter.
|
|
500
504
|
throw new UsageFilterIndexCorruptError();
|
|
501
505
|
}
|
|
502
|
-
for (const entry of rows.entries) accumulator.add(entry);
|
|
503
506
|
if (offsets.length === 0) break;
|
|
504
507
|
}
|
|
505
508
|
} finally {
|
|
@@ -6,7 +6,8 @@ import { boundedMessagesDisplayCount, ownedAnthropicErrorPayload, ownedAnthropic
|
|
|
6
6
|
import { attachComboFailureEvidence, isProxyError, markProxyError } from "../lib/client-error-body";
|
|
7
7
|
import { captureAccountAutoPauseAttempt, wasAccountAutoPaused } from "../oauth/account-auto-pause";
|
|
8
8
|
import { createPhysicalSendReporter, reportDispatchSends, type RequestExecutionBudget, type SingleUseDispatchPermit } from "../lib/request-execution-budget";
|
|
9
|
-
import { createInferenceSendBudget } from "./inference/context";
|
|
9
|
+
import { createInferenceSendBudget, expandInferenceOAuthSendBudget } from "./inference/context";
|
|
10
|
+
import { GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST } from "../oauth/generic-account-failover";
|
|
10
11
|
/**
|
|
11
12
|
* Managed native Messages lane (PF-08, behind `protocols.rollout.managedMessagesNative`).
|
|
12
13
|
*
|
|
@@ -566,7 +567,15 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp
|
|
|
566
567
|
if (oauthBinding) logCtx.provider = formatAnthropicProviderForLog(route.providerName, oauthBinding.snapshot.accountId, config);
|
|
567
568
|
const spendTracker = options.sendBudget ? undefined : attachRequestSpendTracker(req, logCtx);
|
|
568
569
|
const physicalBudget = options.sendBudget ?? createInferenceSendBudget(req, logCtx);
|
|
570
|
+
// Freeze funding before any refusal cools an account; selection still checks live eligibility.
|
|
571
|
+
const fundedAccounts = oauthBinding ? Math.min(new Set([
|
|
572
|
+
oauthBinding.snapshot.accountId,
|
|
573
|
+
...anthropicRoutingFor(oauthBinding.instance).getEligibleAnthropicAccounts(Date.now(), route.modelId),
|
|
574
|
+
]).size, GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST) : 0;
|
|
575
|
+
const oauthFailoverLimit = Math.max(ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST, fundedAccounts - 1);
|
|
576
|
+
if (oauthBinding) expandInferenceOAuthSendBudget(physicalBudget, fundedAccounts);
|
|
569
577
|
// Observe-only spend is already booked by the tracker; count billing sends without booking again.
|
|
578
|
+
const priorSends = Math.max(0, physicalBudget.used - (options.comboDispatchPermit ? 1 : 0));
|
|
570
579
|
let physicalSendsUsed = 0;
|
|
571
580
|
let activeRequest: AnthropicMessagesPassthroughRequest;
|
|
572
581
|
let retainedRequestBytes = 0;
|
|
@@ -638,6 +647,10 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp
|
|
|
638
647
|
options.sendBudget ? Math.min(sharedSendCap, options.sendBudget.remainingBaseSends(sharedSendCap)
|
|
639
648
|
+ (!initialSendStarted && options.comboDispatchPermit ? 1 : 0)) : Number.POSITIVE_INFINITY,
|
|
640
649
|
);
|
|
650
|
+
const oauthPhysicalSendAvailable = (): boolean =>
|
|
651
|
+
Math.max(priorSends + physicalSendsUsed, physicalBudget.used, physicalBudget.physicalStarted ?? 0)
|
|
652
|
+
< Math.min(physicalBudget.policy.maxTotalModelSends, physicalBudget.physicalLimit ?? Number.POSITIVE_INFINITY)
|
|
653
|
+
+ (!initialSendStarted && options.comboDispatchPermit ? 1 : 0);
|
|
641
654
|
const transientSendAvailable = (): boolean => remainingTransientSends() > 0;
|
|
642
655
|
const selector: NativeMessagesSelector = options.selector ?? {};
|
|
643
656
|
const nativeOAuthRouteIsCurrent = (binding: NativeOAuthBinding): boolean => {
|
|
@@ -662,6 +675,7 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp
|
|
|
662
675
|
/** Send the native Messages request under the transient retry policy, re-validating the selected OAuth account or API key at the dispatch boundary. */
|
|
663
676
|
const send = async (recovery?: "rate-limit-429" | "oauth-401" | "oauth-account-403" | "key-429" | "key-401"): Promise<Response> => {
|
|
664
677
|
const remaining = remainingTransientSends();
|
|
678
|
+
if (oauthBinding && !oauthPhysicalSendAvailable()) throw new SendBudgetExhaustedError();
|
|
665
679
|
if (options.sendBudget && remaining <= 0) throw new SendBudgetExhaustedError();
|
|
666
680
|
if (requestTransientPolicy && remaining <= 0) {
|
|
667
681
|
throw markProxyError(new Error("native Messages transient send budget exhausted before recovery dispatch"));
|
|
@@ -937,7 +951,7 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp
|
|
|
937
951
|
return resolved.decision;
|
|
938
952
|
},
|
|
939
953
|
signal: upstream.signal, requestKey: oauthRetryKey,
|
|
940
|
-
canRetry: transientSendAvailable() && oauthFailovers <
|
|
954
|
+
canRetry: transientSendAvailable() && oauthFailovers < oauthFailoverLimit && oauthPhysicalSendAvailable(),
|
|
941
955
|
});
|
|
942
956
|
if (!nextAccountId) break;
|
|
943
957
|
const recovery = response.status === 401 ? "oauth-401" : response.status === 403 ? "oauth-account-403" : "rate-limit-429";
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
runtimeOwnerScope, sameRuntimeOwnerScope, verifyPidIdentity, type RuntimeOwnerScope,
|
|
18
18
|
} from "../config/process-state";
|
|
19
19
|
import { createServer, isIP } from "node:net";
|
|
20
|
+
import { networkInterfaces } from "node:os";
|
|
20
21
|
import { loopbackFamilyAvailability } from "../lib/loopback-family";
|
|
21
22
|
import {
|
|
22
23
|
LOCAL_ATTESTATION_CHALLENGE_HEADER,
|
|
@@ -24,7 +25,7 @@ import {
|
|
|
24
25
|
createLocalAttestationChallenge,
|
|
25
26
|
verifyLocalAttestationProof,
|
|
26
27
|
} from "../lib/local-management-attestation";
|
|
27
|
-
import { directLocalHttpFetch } from "./direct-local-http";
|
|
28
|
+
import { directLocalHttpFetch, isConnectPhaseTimeout } from "./direct-local-http";
|
|
28
29
|
|
|
29
30
|
export interface HealthzIdentity {
|
|
30
31
|
service?: unknown;
|
|
@@ -397,14 +398,36 @@ export async function classifyHealthz(
|
|
|
397
398
|
fetchFn: LivenessFetch,
|
|
398
399
|
timeoutMs: number,
|
|
399
400
|
): Promise<EndpointLiveness> {
|
|
401
|
+
return (await classifyHealthzDetailed(url, fetchFn, timeoutMs)).verdict;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** {@link classifyHealthz} plus whether an unknown verdict was a connect that timed out (#8318). */
|
|
405
|
+
async function classifyHealthzDetailed(
|
|
406
|
+
url: string,
|
|
407
|
+
fetchFn: LivenessFetch,
|
|
408
|
+
timeoutMs: number,
|
|
409
|
+
): Promise<{ verdict: EndpointLiveness; connectTimeout: boolean }> {
|
|
410
|
+
const answer = (verdict: EndpointLiveness, connectTimeout = false) => ({ verdict, connectTimeout });
|
|
400
411
|
try {
|
|
401
412
|
const response = await fetchFn(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
402
|
-
if (response.status !== 200) return "unknown";
|
|
413
|
+
if (response.status !== 200) return answer("unknown");
|
|
403
414
|
const body = (await response.json().catch(() => undefined)) as HealthzIdentity | null | undefined;
|
|
404
|
-
if (body === undefined) return "unknown";
|
|
405
|
-
return isOpencodexHealthz(body) ? "live" : "dead";
|
|
415
|
+
if (body === undefined) return answer("unknown");
|
|
416
|
+
return answer(isOpencodexHealthz(body) ? "live" : "dead");
|
|
406
417
|
} catch (error) {
|
|
407
|
-
return isConnectionRefused(error) ? "dead" : "unknown";
|
|
418
|
+
return isConnectionRefused(error) ? answer("dead") : answer("unknown", isConnectPhaseTimeout(error));
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Whether `address` (unbracketed) is assigned to one of this machine's network interfaces. */
|
|
423
|
+
export function isLocalInterfaceAddress(address: string): boolean {
|
|
424
|
+
const canonical = (value: string) => isIP(value) === 6 ? new URL(`http://[${value.split("%")[0]}]/`).hostname.slice(1, -1) : value;
|
|
425
|
+
const wanted = canonical(address);
|
|
426
|
+
try {
|
|
427
|
+
return Object.values(networkInterfaces()).some(entries =>
|
|
428
|
+
(entries ?? []).some(entry => canonical(entry.address) === wanted));
|
|
429
|
+
} catch {
|
|
430
|
+
return false;
|
|
408
431
|
}
|
|
409
432
|
}
|
|
410
433
|
|
|
@@ -417,24 +440,46 @@ export async function classifyHealthz(
|
|
|
417
440
|
*/
|
|
418
441
|
export async function probeEndpointLiveness(
|
|
419
442
|
endpoint: { port: number; hostname?: string },
|
|
420
|
-
io: Pick<LivenessIo, "fetchFn" | "timeoutMs">
|
|
443
|
+
io: Pick<LivenessIo, "fetchFn" | "timeoutMs" | "bindProofFn"> & {
|
|
444
|
+
/** Test seam for {@link isLocalInterfaceAddress}. */
|
|
445
|
+
localAddressFn?: (address: string) => boolean;
|
|
446
|
+
} = {},
|
|
421
447
|
): Promise<EndpointLiveness> {
|
|
422
448
|
if (!Number.isFinite(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535) return "dead";
|
|
423
449
|
const fetchFn = io.fetchFn ?? directLocalHttpFetch;
|
|
424
450
|
const timeoutMs = io.timeoutMs ?? 1500;
|
|
425
451
|
let sawUnknown = false;
|
|
426
452
|
for (const hostname of loopbackProbeHosts(endpoint.hostname)) {
|
|
427
|
-
const
|
|
453
|
+
const { verdict, connectTimeout } = await classifyHealthzDetailed(
|
|
428
454
|
`http://${hostname}:${endpoint.port}/healthz`,
|
|
429
455
|
fetchFn,
|
|
430
456
|
timeoutMs,
|
|
431
457
|
);
|
|
432
|
-
if (
|
|
433
|
-
if (
|
|
458
|
+
if (verdict === "live") return "live";
|
|
459
|
+
if (verdict === "unknown" && !(connectTimeout && await provenFreeByBind(hostname, endpoint.port, io))) sawUnknown = true;
|
|
434
460
|
}
|
|
435
461
|
return sawUnknown ? "unknown" : "dead";
|
|
436
462
|
}
|
|
437
463
|
|
|
464
|
+
/**
|
|
465
|
+
* #8318: a connect to this machine's own non-loopback address (a Tailscale IP) with nothing
|
|
466
|
+
* listening can time out instead of being refused, which left `ocx resolve` unknown forever. Only
|
|
467
|
+
* a connect-phase timeout on a specific address of a local interface qualifies, and only an
|
|
468
|
+
* exclusive bind that succeeds (and is released at once) proves absence; EADDRINUSE or any other
|
|
469
|
+
* bind error keeps the verdict unknown. Loopback and wildcard binds keep their refusal-only rule,
|
|
470
|
+
* because a wildcard listener can share the port with a specific bind on some platforms.
|
|
471
|
+
*/
|
|
472
|
+
async function provenFreeByBind(
|
|
473
|
+
probeHost: string,
|
|
474
|
+
port: number,
|
|
475
|
+
io: { bindProofFn?: LivenessIo["bindProofFn"]; localAddressFn?: (address: string) => boolean },
|
|
476
|
+
): Promise<boolean> {
|
|
477
|
+
const address = probeHost.replace(/^\[(.*)\]$/, "$1");
|
|
478
|
+
if (isIP(address) === 0 || recoveryLoopbackFamily(address) !== null || isWildcardHostname(address)) return false;
|
|
479
|
+
if (!(io.localAddressFn ?? isLocalInterfaceAddress)(address)) return false;
|
|
480
|
+
return await (io.bindProofFn ?? canBindAddress)(address, port, BIND_PROOF_TIMEOUT_MS);
|
|
481
|
+
}
|
|
482
|
+
|
|
438
483
|
/** Identity-checked /healthz probe; null when unreachable, non-OK, or not our proxy. */
|
|
439
484
|
export async function proxyIdentityAt(
|
|
440
485
|
port: number,
|
package/src/server/relay.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
} from "../lib/errors";
|
|
12
12
|
import { redactSecretString } from "../lib/redact";
|
|
13
13
|
import { isTranslatorBudgetExceededError } from "../lib/translator-budget";
|
|
14
|
+
import { ExplicitBodyStallError } from "../lib/response-body-inactivity";
|
|
14
15
|
import { carryPacedStream, pacedQueuingStrategy } from "../lib/paced-stream";
|
|
15
16
|
import { carryReplayRefusal, isReplayRefusalResponse } from "../lib/upstream-retry";
|
|
16
17
|
import { isUsageDebugEnabled } from "../usage/debug";
|
|
@@ -133,14 +134,18 @@ export function relayWithAbort(
|
|
|
133
134
|
|
|
134
135
|
export function buildFailedTailPayload(err: unknown, maskCredential?: (text: string) => string): string {
|
|
135
136
|
const translatorOverflow = isTranslatorBudgetExceededError(err);
|
|
137
|
+
// The operator's explicit stall budget expired: report the stall terminal the adapter paths use.
|
|
138
|
+
// A guard on a default budget (reset selection with the field unset) keeps its earlier reset tail.
|
|
139
|
+
const stalled = err instanceof ExplicitBodyStallError;
|
|
136
140
|
const raw = translatorOverflow
|
|
137
141
|
? "upstream translation buffer exceeded the safe limit"
|
|
142
|
+
: stalled ? err.message
|
|
138
143
|
: `Upstream stream terminated unexpectedly: ${err instanceof Error ? err.message : String(err)}`;
|
|
139
144
|
// Exact mask before pattern redaction, which could split a credential and hide it from the mask.
|
|
140
145
|
const message = redactSecretString(maskCredential?.(raw) ?? raw).slice(0, MAX_TAIL_ERROR_MESSAGE_CHARS);
|
|
141
146
|
const failure = {
|
|
142
147
|
type: "upstream_error",
|
|
143
|
-
code: translatorOverflow ? "translation_buffer_limit" : "upstream_reset",
|
|
148
|
+
code: translatorOverflow ? "translation_buffer_limit" : stalled ? "upstream_stall_timeout" : "upstream_reset",
|
|
144
149
|
message,
|
|
145
150
|
};
|
|
146
151
|
return JSON.stringify({
|
|
@@ -181,7 +181,11 @@ function firstSanitizedConversationId(
|
|
|
181
181
|
/**
|
|
182
182
|
* Conversation namespace for reasoning replay. Unlike the persisted log id, this stays the raw
|
|
183
183
|
* sanitized identity so mixed headers that carry the same conversation still hit one serving
|
|
184
|
-
* record.
|
|
184
|
+
* record. The request's own thread-id precedes the parent routing identity: a child agent sends
|
|
185
|
+
* both, and letting it resolve to the parent's record lets a successful child route overwrite
|
|
186
|
+
* the parent's serving provenance, which strips the parent's replayed thinking signatures on its
|
|
187
|
+
* next turn (#8632). The parent header stays the fallback for callers that only carry it.
|
|
188
|
+
* Do not hash, and do not prefer session_id over a true per-conversation thread/Cursor
|
|
185
189
|
* identity: session_id can be synthesized from a shared prompt_cache_key.
|
|
186
190
|
*/
|
|
187
191
|
export function reasoningReplayConversationIdFromResponsesRequest(input: {
|
|
@@ -191,8 +195,8 @@ export function reasoningReplayConversationIdFromResponsesRequest(input: {
|
|
|
191
195
|
sessionIdHeader?: string | null;
|
|
192
196
|
}): string | undefined {
|
|
193
197
|
return firstSanitizedConversationId(
|
|
194
|
-
input.clientThreadId,
|
|
195
198
|
input.threadIdHeader,
|
|
199
|
+
input.clientThreadId,
|
|
196
200
|
input.cursorConversationId,
|
|
197
201
|
input.sessionIdHeader,
|
|
198
202
|
);
|
|
@@ -286,8 +290,8 @@ export function conversationIdFromClaudeMetadata(
|
|
|
286
290
|
metadata: { user_id?: unknown } | null | undefined,
|
|
287
291
|
): string | undefined {
|
|
288
292
|
if (!metadata || typeof metadata.user_id !== "string") return undefined;
|
|
289
|
-
//
|
|
290
|
-
|
|
293
|
+
// No length guard before stripping tk: an oversized tk still leaves a valid session id,
|
|
294
|
+
// which also gates Claude routing identity (claude-messages.ts claudeNativeSessionId).
|
|
291
295
|
return normalizeLogConversationId(claudeSessionUserId(metadata.user_id));
|
|
292
296
|
}
|
|
293
297
|
|