@bitkyc08/opencodex 2.95.0 → 2.97.0
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/bin/ocx.mjs +214 -19
- package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
- package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
- package/gui/dist/assets/index-CynE_Rue.js +94 -0
- package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/kiro/stream.ts +63 -4
- package/src/adapters/kiro-constants.ts +15 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/ollama-native.ts +21 -7
- package/src/adapters/openai-responses/canonical-forward.ts +50 -13
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/passthrough.ts +8 -8
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/openai-responses/transport.ts +17 -26
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/qoder/adapter.ts +1 -1
- package/src/adapters/qoder/image-input.ts +5 -2
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/outbound.ts +49 -2
- package/src/cli/agent.ts +44 -15
- package/src/cli/capabilities-agents-routing.ts +9 -0
- package/src/cli/capabilities-base.ts +25 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +5 -4
- package/src/cli/dispatch.ts +11 -176
- package/src/cli/ensure-desired-integrations.ts +4 -3
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +9 -2
- package/src/cli/link.ts +1 -1
- package/src/cli/message-command.ts +2 -1
- package/src/cli/message-mcp-command.ts +29 -0
- package/src/cli/registry.ts +12 -4
- package/src/cli/root.ts +8 -0
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +150 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/client/connect.ts +31 -14
- package/src/client/link-home.ts +3 -2
- package/src/client/machine-listener.ts +3 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/account-store.ts +1 -0
- package/src/codex/auth-context-provider.ts +15 -0
- package/src/codex/auth-context.ts +59 -122
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +6 -8
- package/src/codex/forward-transport-headers.ts +65 -36
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/installation-id.ts +72 -0
- package/src/codex/lineage.ts +13 -7
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/process-state.ts +5 -0
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/generated/compatibility-version.json +496 -192
- package/src/grok/sync.ts +10 -1
- package/src/images/loop.ts +2 -1
- package/src/lib/client-error-body.ts +184 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership.ts +4 -0
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/desktop-cli-handoff.d.mts +1 -1
- package/src/lib/desktop-cli-handoff.mjs +11 -1
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +14 -11
- package/src/lib/windows-owner-acl.ts +13 -6
- package/src/lib/windows-secret-acl.ts +2 -2
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/messaging/mcp-queue-rpc.ts +102 -0
- package/src/messaging/mcp-queue-server.ts +42 -0
- package/src/messaging/mcp-queue-tools.ts +39 -0
- package/src/oauth/anthropic-identity.ts +2 -6
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +41 -74
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +1 -1
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +4 -0
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/trace.ts +18 -0
- package/src/providers/anthropic-subscription.ts +25 -0
- package/src/providers/claude-cli-usage.ts +15 -67
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/quota/anthropic-decision-windows.ts +5 -19
- package/src/providers/quota/anthropic-usage-windows.ts +65 -0
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/request-pacing.ts +3 -2
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/parser-tools.ts +1 -0
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/responses/schema.ts +5 -2
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +56 -0
- package/src/server/audio-dictation.ts +3 -0
- package/src/server/audio-live.ts +8 -2
- package/src/server/audio-upstream.ts +2 -0
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +57 -27
- package/src/server/context-history.ts +14 -7
- package/src/server/images.ts +14 -5
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/live-sideband.ts +16 -2
- package/src/server/index/ollama-routes.ts +89 -0
- package/src/server/index/serve-options.ts +22 -4
- package/src/server/index/websocket-handler.ts +5 -3
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +4 -2
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/live.ts +30 -5
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/route-registry.ts +1 -1
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +1 -1
- package/src/server/messages-native.ts +12 -7
- package/src/server/messages-shared.ts +6 -2
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +79 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +9 -4
- package/src/server/responses/adapter-delivery.ts +5 -4
- package/src/server/responses/adapter-dispatch.ts +36 -30
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +22 -17
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/combo-required-tool-contract.ts +24 -12
- package/src/server/responses/compact.ts +89 -41
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +34 -12
- package/src/server/responses/core-combo-failure.ts +5 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +51 -33
- package/src/server/responses/core-errors.ts +22 -20
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +8 -1
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-build-error.ts +36 -0
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +26 -39
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +67 -48
- package/src/server/responses/request-sidecar-auth.ts +3 -1
- package/src/server/responses/request-transport.ts +35 -31
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/search.ts +13 -4
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/server/ws-bridge.ts +5 -2
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/types/config.ts +2 -0
- package/src/update/index.ts +133 -25
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +60 -27
- package/src/vision/describe.ts +4 -7
- package/src/web-search/executor.ts +4 -7
- package/src/web-search/loop.ts +31 -5
- package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
package/src/oauth/index.ts
CHANGED
|
@@ -97,6 +97,7 @@ import { codexAccountNamespaceProviderCollisionError } from "../codex/account-na
|
|
|
97
97
|
|
|
98
98
|
import { REFRESH_SKEW_MS } from "./refresh-policy";
|
|
99
99
|
import { newerClaudeCredentialForInstance, captureAnthropicCredentialOwnerForInstance } from "./anthropic-continuity";
|
|
100
|
+
import { anthropicSubscriptionLabel } from "../providers/anthropic-subscription";
|
|
100
101
|
import { normalizeOAuthPlan, mergeOAuthPlan } from "./plan";
|
|
101
102
|
import { mergeAnthropicIdentity, type AnthropicIdentityResolver } from "./anthropic-identity";
|
|
102
103
|
import { AnthropicCrossInstanceDuplicateError, AnthropicLocalCliImportError, assertAnthropicCredentialSource } from "./store-anthropic-instance";
|
|
@@ -143,7 +144,7 @@ export type OAuthActiveTokenObservation =
|
|
|
143
144
|
|
|
144
145
|
const MAX_OAUTH_TOKEN_REFRESH_FLIGHTS = 32;
|
|
145
146
|
const OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS = 120_000;
|
|
146
|
-
interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean }
|
|
147
|
+
interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean; requireUsable?: boolean }
|
|
147
148
|
const tokenRefreshes = new Map<string, OAuthTokenRefreshFlight>();
|
|
148
149
|
export class OAuthTokenRefreshBusyError extends Error {
|
|
149
150
|
readonly code = "OAUTH_TOKEN_REFRESH_BUSY";
|
|
@@ -155,6 +156,8 @@ export class OAuthTokenRefreshStaleError extends Error {
|
|
|
155
156
|
readonly retryable = true;
|
|
156
157
|
constructor() { super("OAuth token refresh owner became stale"); this.name = "OAuthTokenRefreshStaleError"; }
|
|
157
158
|
}
|
|
159
|
+
/** Known pre-dispatch cancellation; independent waiters may acquire a new owner. */
|
|
160
|
+
class OAuthDiscoveryRefreshCancelledError extends OAuthTokenRefreshStaleError {}
|
|
158
161
|
|
|
159
162
|
/** Focused owner-identity tests only. Synthetic owners retain no account data. */
|
|
160
163
|
export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string; startedAt?: number; flightId?: string; dispatched?: boolean }>): {
|
|
@@ -186,9 +189,9 @@ export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string;
|
|
|
186
189
|
}
|
|
187
190
|
const XAI_PERMANENT_FAILURE_TTL_MS=30_000;
|
|
188
191
|
const permanentRefreshFailures=new Map<string,number>();
|
|
189
|
-
interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
|
|
192
|
+
interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; requireUsableAccount?: boolean }
|
|
190
193
|
interface AnthropicRefreshDeps { resolveIdentity?: AnthropicIdentityResolver; intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; flight?: OAuthRefreshFlightEvidence; replacedStaleFlight?: OAuthRefreshFlightEvidence }
|
|
191
|
-
interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
|
|
194
|
+
interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; authorityCurrent?: () => boolean; requireUsableAccount?: boolean }
|
|
192
195
|
function verdictKey(p:string,a:string,c:OAuthCredentials){return `${p}\0${a}\0${credentialGeneration(c)}`;}
|
|
193
196
|
function cached(p:string,a:string,c:OAuthCredentials,now:()=>number){const k=verdictKey(p,a,c),u=permanentRefreshFailures.get(k);if(u===undefined)return false;if(u<=now()){permanentRefreshFailures.delete(k);return false;}return true;}
|
|
194
197
|
export function sweepExpiredXaiPermanentFailureVerdicts(now=Date.now()):number{let removed=0;for(const[key,until]of permanentRefreshFailures){if(until>now)continue;permanentRefreshFailures.delete(key);removed+=1;}return removed;}
|
|
@@ -447,70 +450,8 @@ export function getOAuthCredentialApiBaseUrl(provider: string): string | undefin
|
|
|
447
450
|
export function listOAuthProviders(): string[] {
|
|
448
451
|
return Object.keys(OAUTH_PROVIDERS).filter(isPublicOAuthProvider);
|
|
449
452
|
}
|
|
450
|
-
|
|
451
|
-
export
|
|
452
|
-
constructor(provider: string) {
|
|
453
|
-
super(`Unsupported OAuth provider in config: ${provider}`);
|
|
454
|
-
this.name = "UnsupportedOAuthProviderError";
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
export class OAuthLoginRequiredError extends Error {
|
|
459
|
-
readonly provider: string;
|
|
460
|
-
|
|
461
|
-
constructor(provider: string) {
|
|
462
|
-
super(`Not logged in to ${provider}. Run: ocx login ${provider}`);
|
|
463
|
-
this.name = "OAuthLoginRequiredError";
|
|
464
|
-
this.provider = provider;
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
/** An operator-paused account is temporarily unavailable, not an invalid login. */
|
|
469
|
-
export class OAuthAccountPausedError extends Error {
|
|
470
|
-
constructor() {
|
|
471
|
-
super("OAuth account is paused. Resume it in account settings and retry.");
|
|
472
|
-
this.name = "OAuthAccountPausedError";
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
export class OAuthProviderPublicationError extends Error {
|
|
477
|
-
constructor(provider?: string, credentialWritten = true) {
|
|
478
|
-
super(provider !== "anthropic2" ? "OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login."
|
|
479
|
-
: credentialWritten ? "Anthropic Pool 2 credential was saved as an orphan auth row, but the provider entry was not written. Repair the persisted config or resolve the provider/account namespace collision, then retry login."
|
|
480
|
-
: "Anthropic Pool 2 login did not start because the config file is missing or could not be written; no credential was saved. Repair the persisted config, then retry login.");
|
|
481
|
-
this.name = "OAuthProviderPublicationError";
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
/** A local configuration conflict found before any credential is written; its text is fixed. */
|
|
486
|
-
export class OAuthProviderNamespaceCollisionError extends Error {
|
|
487
|
-
constructor(message: string) {
|
|
488
|
-
super(message);
|
|
489
|
-
this.name = "OAuthProviderNamespaceCollisionError";
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
export class OAuthReauthIdentityMismatchError extends Error {
|
|
494
|
-
constructor() {
|
|
495
|
-
super("Signed-in account does not match the selected account. Sign in with the same account.");
|
|
496
|
-
this.name = "OAuthReauthIdentityMismatchError";
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
export class OAuthReauthIdentityUnverifiedError extends Error {
|
|
501
|
-
constructor() {
|
|
502
|
-
super("Could not verify signed-in account identity for reauth.");
|
|
503
|
-
this.name = "OAuthReauthIdentityUnverifiedError";
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
class OAuthLoginSupersededError extends Error {
|
|
508
|
-
constructor() {
|
|
509
|
-
super("OAuth login was superseded before credential persistence");
|
|
510
|
-
this.name = "OAuthLoginSupersededError";
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
|
|
453
|
+
import { OAuthAccountUnusableError, OAuthLoginSupersededError, OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
|
|
454
|
+
export { OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
|
|
514
455
|
/** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
|
|
515
456
|
export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
|
|
516
457
|
if (error instanceof AntigravityProjectDiscoveryError) return error.publicMessage;
|
|
@@ -631,6 +572,8 @@ async function resolveAccessSnapshotForAccount(
|
|
|
631
572
|
rejectedGeneration?: string,
|
|
632
573
|
requireUsableAccount = false,
|
|
633
574
|
oauthProvider = provider,
|
|
575
|
+
authorityCurrent?: () => boolean,
|
|
576
|
+
retryCancelledDiscovery = true,
|
|
634
577
|
): Promise<OAuthAccessSnapshot> {
|
|
635
578
|
const def = OAUTH_PROVIDERS[oauthProvider];
|
|
636
579
|
if (!def) throw new UnsupportedOAuthProviderError(oauthProvider);
|
|
@@ -660,6 +603,7 @@ async function resolveAccessSnapshotForAccount(
|
|
|
660
603
|
// no replacement starts until the old consumers have actually released enough capacity.
|
|
661
604
|
const waiter = tokenRefreshWaiters.tryAcquire();
|
|
662
605
|
if (!waiter) throw new OAuthTokenRefreshBusyError();
|
|
606
|
+
let unrestrictedRetry = false;
|
|
663
607
|
try {
|
|
664
608
|
if (existing && replacedStaleFlight) {
|
|
665
609
|
// A replacement would wait for this owner's lock anyway. Keep its registry slot
|
|
@@ -674,7 +618,10 @@ async function resolveAccessSnapshotForAccount(
|
|
|
674
618
|
}
|
|
675
619
|
if (existing) {
|
|
676
620
|
logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
|
|
677
|
-
|
|
621
|
+
const joined = await existing.promise;
|
|
622
|
+
// The owner may not have required usability; a mark that landed meanwhile still rejects us.
|
|
623
|
+
if (requireUsableAccount && getAccountCredentialWithStatus(provider, accountId)?.needsReauth) throw new OAuthAccountUnusableError(provider);
|
|
624
|
+
return joined;
|
|
678
625
|
}
|
|
679
626
|
if (tokenRefreshes.size >= MAX_OAUTH_TOKEN_REFRESH_FLIGHTS) {
|
|
680
627
|
for (const [staleKey, stale] of tokenRefreshes) {
|
|
@@ -690,12 +637,14 @@ async function resolveAccessSnapshotForAccount(
|
|
|
690
637
|
abort,
|
|
691
638
|
flightId: randomUUID(),
|
|
692
639
|
dispatched: false,
|
|
640
|
+
requireUsable: requireUsableAccount,
|
|
693
641
|
};
|
|
694
642
|
const refresh = (async (): Promise<OAuthAccessSnapshot> => {
|
|
695
|
-
const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight);
|
|
643
|
+
const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight, authorityCurrent, requireUsableAccount);
|
|
696
644
|
const persistedRow = getAccountCredentialWithStatus(provider, accountId);
|
|
697
645
|
if (!persistedRow) throw new OAuthLoginRequiredError(provider);
|
|
698
646
|
if (persistedRow.paused === true) throw new OAuthAccountPausedError();
|
|
647
|
+
if (requireUsableAccount && persistedRow.needsReauth) throw new OAuthAccountUnusableError(provider);
|
|
699
648
|
const persisted = persistedRow.credential;
|
|
700
649
|
if (persisted.access !== accessToken) {
|
|
701
650
|
throw new Error(`OAuth refresh persisted an unexpected access token for ${provider}`);
|
|
@@ -714,7 +663,13 @@ async function resolveAccessSnapshotForAccount(
|
|
|
714
663
|
flight.promise = refresh;
|
|
715
664
|
tokenRefreshes.set(key, flight);
|
|
716
665
|
return await refresh;
|
|
666
|
+
} catch (error) {
|
|
667
|
+
// An unrestricted caller that joined a usable-only owner is not bound by that owner's rejection.
|
|
668
|
+
if (!requireUsableAccount && error instanceof OAuthAccountUnusableError) unrestrictedRetry = true;
|
|
669
|
+
else if (authorityCurrent || !retryCancelledDiscovery || !(error instanceof OAuthDiscoveryRefreshCancelledError)) throw error;
|
|
717
670
|
} finally { waiter.release(); }
|
|
671
|
+
if (unrestrictedRetry) return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, false, oauthProvider, authorityCurrent, retryCancelledDiscovery);
|
|
672
|
+
return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, requireUsableAccount, oauthProvider, undefined, false);
|
|
718
673
|
}
|
|
719
674
|
|
|
720
675
|
export async function getValidAccessTokenSnapshot(
|
|
@@ -772,9 +727,9 @@ export async function getValidAccessTokenForAccount(provider: string, accountId:
|
|
|
772
727
|
export async function getValidAccessSnapshotForAccount(
|
|
773
728
|
provider: string,
|
|
774
729
|
accountId: string,
|
|
775
|
-
opts: { requireUsableAccount?: boolean } = {},
|
|
730
|
+
opts: { requireUsableAccount?: boolean; authorityCurrent?: () => boolean } = {},
|
|
776
731
|
): Promise<OAuthAccessSnapshot> {
|
|
777
|
-
return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true);
|
|
732
|
+
return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true, provider, opts.authorityCurrent);
|
|
778
733
|
}
|
|
779
734
|
|
|
780
735
|
/** Terminal refresh failures (revoked/rotated-away grants) — retrying cannot succeed. */
|
|
@@ -838,7 +793,7 @@ function merged(fresh: OAuthCredentials, previous: OAuthCredentials): OAuthCrede
|
|
|
838
793
|
...(fresh.kiro === undefined && previous.kiro ? { kiro: previous.kiro } : {}),
|
|
839
794
|
};
|
|
840
795
|
}
|
|
841
|
-
export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
|
|
796
|
+
export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();if(deps.requireUsableAccount&&row.needsReauth)throw new OAuthAccountUnusableError(provider);const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead,keepReauthMarkedAfterDispatch:!row.needsReauth});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
|
|
842
797
|
|
|
843
798
|
|
|
844
799
|
/**
|
|
@@ -1029,6 +984,9 @@ export async function refreshGenericAccountWithLock(
|
|
|
1029
984
|
const row = getAccountCredentialWithStatus(provider, accountId);
|
|
1030
985
|
if (!row) throw new OAuthLoginRequiredError(provider);
|
|
1031
986
|
if (row.paused) throw new OAuthAccountPausedError();
|
|
987
|
+
// A usable-account caller rechecks needsReauth here: a mark committed while it waited must
|
|
988
|
+
// stop the refresh before the stored refresh token is sent.
|
|
989
|
+
if (deps.requireUsableAccount && row.needsReauth) throw new OAuthAccountUnusableError(provider);
|
|
1032
990
|
const stored = row.credential;
|
|
1033
991
|
if (
|
|
1034
992
|
credentialGeneration(stored) !== credentialGeneration(callerCredential)
|
|
@@ -1039,11 +997,14 @@ export async function refreshGenericAccountWithLock(
|
|
|
1039
997
|
}
|
|
1040
998
|
const generation = credentialGeneration(stored);
|
|
1041
999
|
try {
|
|
1000
|
+
if (deps.authorityCurrent && !deps.authorityCurrent()) throw new OAuthDiscoveryRefreshCancelledError();
|
|
1042
1001
|
const refreshed = await def.refresh(stored.refresh, deps.signal, stored, accountId);
|
|
1043
1002
|
const fresh = merged(refreshed, stored);
|
|
1044
1003
|
const outcome = await mergeAccountCredential(provider, accountId, fresh, {
|
|
1045
1004
|
expectedGeneration: generation,
|
|
1046
1005
|
afterPrePersistRead: deps.afterPrePersistRead,
|
|
1006
|
+
// A mark that landed after this flight read the row is newer than the refresh: keep it.
|
|
1007
|
+
keepReauthMarkedAfterDispatch: !row.needsReauth,
|
|
1047
1008
|
...(provider === "devin" ? { assertOwnership: (store: AuthStore) => {
|
|
1048
1009
|
if (store[provider]?.accounts.find(row => row.id === accountId)?.paused) throw new OAuthAccountPausedError();
|
|
1049
1010
|
assertDevinCliAdoptionOwnership(store, provider, accountId, refreshed);
|
|
@@ -1137,10 +1098,12 @@ async function refreshAndPersistAccessToken(
|
|
|
1137
1098
|
signal?: AbortSignal,
|
|
1138
1099
|
flight?: OAuthRefreshFlightEvidence,
|
|
1139
1100
|
replacedStaleFlight?: OAuthRefreshFlightEvidence,
|
|
1101
|
+
authorityCurrent?: () => boolean,
|
|
1102
|
+
requireUsableAccount = false,
|
|
1140
1103
|
): Promise<string> {
|
|
1141
|
-
if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal });
|
|
1104
|
+
if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal, requireUsableAccount });
|
|
1142
1105
|
if (isAnthropicOAuthInstance(provider)) return refreshAnthropicAccountWithLock(provider, accountId, def, cred, { signal, flight, replacedStaleFlight });
|
|
1143
|
-
return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal });
|
|
1106
|
+
return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal, authorityCurrent, requireUsableAccount });
|
|
1144
1107
|
}
|
|
1145
1108
|
|
|
1146
1109
|
/** Resolve discovery credentials only for the caller-owned configured OAuth row. */
|
|
@@ -1819,6 +1782,8 @@ export interface OAuthAccountSummary {
|
|
|
1819
1782
|
* Missing or invalid labels remain null; quota percentages never establish a subscription.
|
|
1820
1783
|
*/
|
|
1821
1784
|
plan: string | null;
|
|
1785
|
+
/** Anthropic display-only subscription name; absent when no tier was observed. */
|
|
1786
|
+
planLabel?: string;
|
|
1822
1787
|
}
|
|
1823
1788
|
|
|
1824
1789
|
/**
|
|
@@ -1846,6 +1811,8 @@ export function getLoginStatus(provider: string, maskEmails = true, flowId?: str
|
|
|
1846
1811
|
expiresAt: a.credential.expires,
|
|
1847
1812
|
// Explicitly null rather than omitted when upstream tier metadata is unknown.
|
|
1848
1813
|
plan: normalizeOAuthPlan(a.credential.plan) ?? null,
|
|
1814
|
+
...((provider === "anthropic" || provider === "anthropic2") && anthropicSubscriptionLabel(a.credential.plan)
|
|
1815
|
+
? { planLabel: anthropicSubscriptionLabel(a.credential.plan) } : {}),
|
|
1849
1816
|
}));
|
|
1850
1817
|
|
|
1851
1818
|
// A stored credential counts as "logged in" when it exists and is not marked for
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { errorDestinationText, providerErrorDestinationLabel } from "../lib/error-destination";
|
|
2
|
+
|
|
3
|
+
export class UnsupportedOAuthProviderError extends Error {
|
|
4
|
+
constructor(provider: string) {
|
|
5
|
+
super(`Unsupported OAuth provider in config: ${errorDestinationText(providerErrorDestinationLabel(provider))}`);
|
|
6
|
+
this.name = "UnsupportedOAuthProviderError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class OAuthLoginRequiredError extends Error {
|
|
11
|
+
readonly provider: string;
|
|
12
|
+
|
|
13
|
+
constructor(provider: string) {
|
|
14
|
+
super(`Not logged in to ${errorDestinationText(providerErrorDestinationLabel(provider))}. Run: ocx login ${errorDestinationText(providerErrorDestinationLabel(provider))}`);
|
|
15
|
+
this.name = "OAuthLoginRequiredError";
|
|
16
|
+
this.provider = provider;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A usable-account caller found needsReauth under the refresh lock; unrestricted joiners retry alone. */
|
|
21
|
+
export class OAuthAccountUnusableError extends OAuthLoginRequiredError {}
|
|
22
|
+
|
|
23
|
+
/** An operator-paused account is temporarily unavailable, not an invalid login. */
|
|
24
|
+
export class OAuthAccountPausedError extends Error {
|
|
25
|
+
constructor() {
|
|
26
|
+
super("OAuth account is paused. Resume it in account settings and retry.");
|
|
27
|
+
this.name = "OAuthAccountPausedError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class OAuthProviderPublicationError extends Error {
|
|
32
|
+
constructor(provider?: string, credentialWritten = true) {
|
|
33
|
+
super(provider !== "anthropic2" ? "OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login."
|
|
34
|
+
: credentialWritten ? "Anthropic Pool 2 credential was saved as an orphan auth row, but the provider entry was not written. Repair the persisted config or resolve the provider/account namespace collision, then retry login."
|
|
35
|
+
: "Anthropic Pool 2 login did not start because the config file is missing or could not be written; no credential was saved. Repair the persisted config, then retry login.");
|
|
36
|
+
this.name = "OAuthProviderPublicationError";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A local configuration conflict found before any credential is written; its text is fixed. */
|
|
41
|
+
export class OAuthProviderNamespaceCollisionError extends Error {
|
|
42
|
+
constructor(message: string) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "OAuthProviderNamespaceCollisionError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class OAuthReauthIdentityMismatchError extends Error {
|
|
49
|
+
constructor() {
|
|
50
|
+
super("Signed-in account does not match the selected account. Sign in with the same account.");
|
|
51
|
+
this.name = "OAuthReauthIdentityMismatchError";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class OAuthReauthIdentityUnverifiedError extends Error {
|
|
56
|
+
constructor() {
|
|
57
|
+
super("Could not verify signed-in account identity for reauth.");
|
|
58
|
+
this.name = "OAuthReauthIdentityUnverifiedError";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class OAuthLoginSupersededError extends Error {
|
|
63
|
+
constructor() {
|
|
64
|
+
super("OAuth login was superseded before credential persistence");
|
|
65
|
+
this.name = "OAuthLoginSupersededError";
|
|
66
|
+
}
|
|
67
|
+
}
|
package/src/oauth/store.ts
CHANGED
|
@@ -1610,7 +1610,7 @@ export async function markAccountNeedsReauth(
|
|
|
1610
1610
|
}, [provider, accountId]);
|
|
1611
1611
|
}
|
|
1612
1612
|
|
|
1613
|
-
export async function mergeAccountCredential(provider:string,accountId:string,credential:OAuthCredentials,opts:{expectedGeneration?:string;afterPrePersistRead?:()=>void|Promise<void>;assertOwnership?: (store: AuthStore) => void}={}):Promise<{superseded:false}|{superseded:true;stored:OAuthCredentials}>{const safe=normalizeCredential(credential);if(!safe)throw new Error("Refusing to persist invalid OAuth credential");if(isAnthropicInstanceId(provider))assertAnthropicCredentialSource(provider,safe);return await mutateStore(async store=>{await opts.afterPrePersistRead?.();const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account)throw new Error(`OAuth account disappeared before persist: ${provider}`);if(opts.expectedGeneration!==undefined&&credentialGeneration(account.credential)!==opts.expectedGeneration)return{superseded:true,stored:account.credential};opts.assertOwnership?.(store);account.credential=safe;delete account.refreshAttentionGeneration;if(account.needsReauthReason!=="verify_account"){delete account.needsReauth;delete account.needsReauthReason;}return{superseded:false};},[provider,accountId,safe,opts.expectedGeneration]);}
|
|
1613
|
+
export async function mergeAccountCredential(provider:string,accountId:string,credential:OAuthCredentials,opts:{expectedGeneration?:string;afterPrePersistRead?:()=>void|Promise<void>;assertOwnership?: (store: AuthStore) => void;keepReauthMarkedAfterDispatch?:boolean}={}):Promise<{superseded:false}|{superseded:true;stored:OAuthCredentials}>{const safe=normalizeCredential(credential);if(!safe)throw new Error("Refusing to persist invalid OAuth credential");if(isAnthropicInstanceId(provider))assertAnthropicCredentialSource(provider,safe);return await mutateStore(async store=>{await opts.afterPrePersistRead?.();const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account)throw new Error(`OAuth account disappeared before persist: ${provider}`);if(opts.expectedGeneration!==undefined&&credentialGeneration(account.credential)!==opts.expectedGeneration)return{superseded:true,stored:account.credential};opts.assertOwnership?.(store);account.credential=safe;delete account.refreshAttentionGeneration;if(account.needsReauthReason!=="verify_account"&&!(opts.keepReauthMarkedAfterDispatch&&account.needsReauth)){delete account.needsReauth;delete account.needsReauthReason;}return{superseded:false};},[provider,accountId,safe,opts.expectedGeneration]);}
|
|
1614
1614
|
// A late refresh failure must not change an operator-paused account's health. Check under
|
|
1615
1615
|
// the mutation lock, not before awaiting it, so a concurrent pause cannot be overwritten.
|
|
1616
1616
|
export async function markAccountNeedsReauthIfGeneration(provider:string,accountId:string,generation:string,writerGeneration=captureConfigGeneration(),reason?:"verify_account",isCurrent?:(store:AuthStore)=>boolean):Promise<boolean>{const key=oauthAccountKey(provider,accountId);if(writerGeneration<lastReconciledGeneration&&!liveOAuthAccountKeys.has(key))return false;return await mutateStore(store=>{const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account?.credential||account.paused||credentialGeneration(account.credential)!==generation)return false;if(writerGeneration<lastReconciledGeneration&&!liveOAuthAccountKeys.has(key))return false;if(isCurrent&&!isCurrent(store))return false;account.needsReauth=true;if(reason==="verify_account")account.needsReauthReason=reason;return true;},[provider,accountId,generation]);}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/** Pure Ollama native request and Chat response projections. */
|
|
2
|
+
type Obj = Record<string, unknown>;
|
|
3
|
+
export type OllamaKind = "chat" | "generate";
|
|
4
|
+
export class OllamaCodecError extends Error {
|
|
5
|
+
readonly status = 400;
|
|
6
|
+
readonly code = "invalid_ollama_request";
|
|
7
|
+
constructor(message: string) { super(message); this.name = "OllamaCodecError"; }
|
|
8
|
+
}
|
|
9
|
+
function fail(message: string): never { throw new OllamaCodecError(message); }
|
|
10
|
+
function object(value: unknown, label: string): Obj {
|
|
11
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) fail(`Invalid ${label}`);
|
|
12
|
+
return value as Obj;
|
|
13
|
+
}
|
|
14
|
+
function keys(value: Obj, allowed: readonly string[], label: string): void {
|
|
15
|
+
if (Object.keys(value).some(k => !allowed.includes(k))) fail(`Unsupported ${label} field`);
|
|
16
|
+
}
|
|
17
|
+
function string(value: unknown, label: string, nonempty = false): string {
|
|
18
|
+
if (typeof value !== "string" || (nonempty && !value.trim())) fail(`Invalid ${label}`);
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
function image(value: unknown): Obj {
|
|
22
|
+
const data = string(value, "image", true);
|
|
23
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) fail("Invalid image encoding");
|
|
24
|
+
let bytes: Uint8Array;
|
|
25
|
+
// The pattern above already validated the whole string; decode only the signature window.
|
|
26
|
+
try { bytes = Uint8Array.from(atob(data.slice(0, 16)), c => c.charCodeAt(0)); } catch { return fail("Invalid image encoding"); }
|
|
27
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
28
|
+
if ((data.endsWith("==") && (alphabet.indexOf(data[data.length - 3]!) & 15) !== 0) ||
|
|
29
|
+
(data.endsWith("=") && !data.endsWith("==") && (alphabet.indexOf(data[data.length - 2]!) & 3) !== 0)) fail("Invalid image encoding");
|
|
30
|
+
const starts = (...prefix: number[]) => prefix.every((b, i) => bytes[i] === b);
|
|
31
|
+
const mime = starts(137,80,78,71,13,10,26,10) ? "image/png" : starts(255,216,255) ? "image/jpeg" : starts(71,73,70,56,55,97) || starts(71,73,70,56,57,97) ? "image/gif" : starts(82,73,70,70) && bytes.length >= 12 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80 ? "image/webp" : undefined;
|
|
32
|
+
if (!mime) fail("Unsupported image media");
|
|
33
|
+
return { type: "image_url", image_url: { url: `data:${mime};base64,${data}` } };
|
|
34
|
+
}
|
|
35
|
+
function content(text: unknown, images: unknown): unknown {
|
|
36
|
+
const value = string(text, "content");
|
|
37
|
+
if (images === undefined) return value;
|
|
38
|
+
if (!Array.isArray(images)) fail("Invalid images");
|
|
39
|
+
if (!images.length) return value;
|
|
40
|
+
return [{ type: "text", text: value }, ...images.map(image)];
|
|
41
|
+
}
|
|
42
|
+
function requestTools(value: unknown): Obj[] {
|
|
43
|
+
if (!Array.isArray(value)) fail("Invalid tools");
|
|
44
|
+
return value.map(item => {
|
|
45
|
+
const tool = object(item, "tool"); keys(tool, ["type", "function"], "tool");
|
|
46
|
+
if (tool.type !== "function") fail("Unsupported tool type");
|
|
47
|
+
const fn = object(tool.function, "tool function"); keys(fn, ["name", "description", "parameters"], "tool function");
|
|
48
|
+
string(fn.name, "tool name", true);
|
|
49
|
+
if (fn.description !== undefined) string(fn.description, "tool description");
|
|
50
|
+
object(fn.parameters, "tool parameters");
|
|
51
|
+
return { type: "function", function: { ...fn } };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export function ollamaToChat(kind: OllamaKind, input: unknown): Obj {
|
|
55
|
+
const body = object(input, "request");
|
|
56
|
+
keys(body, kind === "chat" ? ["model", "messages", "stream", "options", "format", "tools"] : ["model", "prompt", "system", "images", "stream", "options", "format"], "request");
|
|
57
|
+
const model = string(body.model, "model", true);
|
|
58
|
+
if (body.stream !== undefined && typeof body.stream !== "boolean") fail("Invalid stream");
|
|
59
|
+
const result: Obj = { model, stream: body.stream ?? true, messages: [] };
|
|
60
|
+
const messages: Obj[] = [];
|
|
61
|
+
if (kind === "generate") {
|
|
62
|
+
if (body.system !== undefined) messages.push({ role: "system", content: string(body.system, "system") });
|
|
63
|
+
messages.push({ role: "user", content: content(body.prompt, body.images) });
|
|
64
|
+
} else {
|
|
65
|
+
if (!Array.isArray(body.messages)) fail("Invalid messages");
|
|
66
|
+
const pending: { id: string; name: string; message: number; matched: boolean }[] = [];
|
|
67
|
+
body.messages.forEach((raw, mi) => {
|
|
68
|
+
const msg = object(raw, "message");
|
|
69
|
+
const role = string(msg.role, "role");
|
|
70
|
+
if (!["system", "user", "assistant", "tool"].includes(role)) fail("Unsupported role");
|
|
71
|
+
keys(msg, role === "user" ? ["role", "content", "images"] : role === "assistant" ? ["role", "content", "tool_calls"] : role === "tool" ? ["role", "content", "tool_name", "tool_call_id"] : ["role", "content"], "message");
|
|
72
|
+
const projected: Obj = { role, content: content(msg.content, role === "user" ? msg.images : undefined) };
|
|
73
|
+
if (role === "assistant" && msg.tool_calls !== undefined) {
|
|
74
|
+
if (!Array.isArray(msg.tool_calls)) fail("Invalid tool calls");
|
|
75
|
+
projected.tool_calls = msg.tool_calls.map((rawCall, ci) => {
|
|
76
|
+
// A replayed response call keeps the id this proxy returned for it; older clients send none.
|
|
77
|
+
const call = object(rawCall, "tool call"); keys(call, ["id", "function"], "tool call");
|
|
78
|
+
const fn = object(call.function, "tool call function"); keys(fn, ["name", "arguments"], "tool call function");
|
|
79
|
+
const name = string(fn.name, "tool name", true); const args = object(fn.arguments, "tool arguments");
|
|
80
|
+
const id = call.id === undefined ? `call_ollama_${mi}_${ci}` : string(call.id, "tool call id", true);
|
|
81
|
+
if (pending.some(p => p.id === id)) fail("Duplicate tool call id");
|
|
82
|
+
pending.push({ id, name, message: mi, matched: false });
|
|
83
|
+
return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (role === "tool") {
|
|
87
|
+
const id = msg.tool_call_id === undefined ? undefined : string(msg.tool_call_id, "tool call id", true);
|
|
88
|
+
const name = msg.tool_name === undefined ? undefined : string(msg.tool_name, "tool name", true);
|
|
89
|
+
const candidates = pending.filter(p => !p.matched && (id ? p.id === id && (!name || p.name === name) : name && p.name === name));
|
|
90
|
+
if (!id && name && candidates.length) {
|
|
91
|
+
const latestMessage = candidates[candidates.length - 1]!.message;
|
|
92
|
+
const latest = candidates.filter(p => p.message === latestMessage);
|
|
93
|
+
if (latest.length !== 1) fail("Ambiguous tool result");
|
|
94
|
+
latest[0]!.matched = true; projected.tool_call_id = latest[0]!.id;
|
|
95
|
+
} else {
|
|
96
|
+
if (candidates.length !== 1) fail("Unmatched tool result");
|
|
97
|
+
candidates[0]!.matched = true; projected.tool_call_id = candidates[0]!.id;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
messages.push(projected);
|
|
101
|
+
});
|
|
102
|
+
if (body.tools !== undefined) result.tools = requestTools(body.tools);
|
|
103
|
+
}
|
|
104
|
+
result.messages = messages;
|
|
105
|
+
if (body.options !== undefined) {
|
|
106
|
+
const opts = object(body.options, "options"); keys(opts, ["temperature", "top_p", "num_predict", "stop"], "option");
|
|
107
|
+
for (const key of ["temperature", "top_p", "num_predict"] as const) if (opts[key] !== undefined) {
|
|
108
|
+
const v = opts[key]; if (typeof v !== "number" || !Number.isFinite(v) || (key === "num_predict" && (!Number.isSafeInteger(v) || v < 1))) fail("Invalid option");
|
|
109
|
+
result[key === "num_predict" ? "max_tokens" : key] = v;
|
|
110
|
+
}
|
|
111
|
+
if (opts.stop !== undefined) {
|
|
112
|
+
if (!Array.isArray(opts.stop) || !opts.stop.every(v => typeof v === "string")) fail("Invalid stop option");
|
|
113
|
+
result.stop = opts.stop;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (body.format !== undefined) { if (body.format !== "json") fail("Unsupported format"); result.response_format = { type: "json_object" }; }
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function usage(value: unknown): Obj {
|
|
121
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
122
|
+
const u = value as Obj; const out: Obj = {};
|
|
123
|
+
if (typeof u.prompt_tokens === "number" && Number.isSafeInteger(u.prompt_tokens) && u.prompt_tokens >= 0) out.prompt_eval_count = u.prompt_tokens;
|
|
124
|
+
if (typeof u.completion_tokens === "number" && Number.isSafeInteger(u.completion_tokens) && u.completion_tokens >= 0) out.eval_count = u.completion_tokens;
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
function finish(value: unknown): string | undefined { return value === "stop" || value === "tool_calls" || value === "length" ? value : undefined; }
|
|
128
|
+
function nativeError(): Obj { return { error: "Chat completion did not finish successfully" }; }
|
|
129
|
+
function nativeCalls(calls: unknown): Obj[] {
|
|
130
|
+
if (!Array.isArray(calls)) throw new Error("Invalid Chat tool calls");
|
|
131
|
+
return calls.map((raw, i) => {
|
|
132
|
+
const call = object(raw, "response tool call"); const fn = object(call.function, "response tool function");
|
|
133
|
+
const name = string(fn.name, "response tool name", true);
|
|
134
|
+
let args: unknown; try { args = typeof fn.arguments === "string" ? JSON.parse(fn.arguments) : fn.arguments; } catch { throw new Error("Invalid Chat tool arguments"); }
|
|
135
|
+
object(args, "response tool arguments");
|
|
136
|
+
return { id: typeof call.id === "string" && call.id ? call.id : `call_ollama_response_${i}`, function: { name, arguments: args } };
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function payload(kind: OllamaKind, text: string, calls?: Obj[]): Obj {
|
|
140
|
+
return kind === "chat" ? { message: { role: "assistant", content: text, ...(calls?.length ? { tool_calls: calls } : {}) } } : { response: text };
|
|
141
|
+
}
|
|
142
|
+
export function ollamaBufferedResponse(kind: OllamaKind, model: string, input: unknown, createdAt: string): Obj {
|
|
143
|
+
try {
|
|
144
|
+
const body = object(input, "Chat response"); if (!Array.isArray(body.choices) || body.choices.length !== 1) return nativeError();
|
|
145
|
+
const choice = object(body.choices[0], "Chat choice"); const reason = finish(choice.finish_reason); if (!reason) return nativeError();
|
|
146
|
+
const msg = object(choice.message, "Chat message");
|
|
147
|
+
if (msg.content != null && typeof msg.content !== "string") return nativeError();
|
|
148
|
+
const calls = msg.tool_calls === undefined ? undefined : nativeCalls(msg.tool_calls);
|
|
149
|
+
if (kind === "generate" && calls?.length) return nativeError();
|
|
150
|
+
return { model, created_at: createdAt, ...payload(kind, (msg.content as string | null | undefined) ?? "", calls), done: true, done_reason: reason, ...usage(body.usage) };
|
|
151
|
+
} catch { return nativeError(); }
|
|
152
|
+
}
|
|
153
|
+
type StreamTool = { id?: string; name: string; arguments: string };
|
|
154
|
+
export interface OllamaStreamState { kind: OllamaKind; model: string; createdAt: string; finishReason?: unknown; usage: Obj; tools: Map<number, StreamTool>; toolsEmitted: boolean; }
|
|
155
|
+
export function createOllamaStreamState(kind: OllamaKind, model: string, createdAt: string): OllamaStreamState {
|
|
156
|
+
return { kind, model, createdAt, usage: {}, tools: new Map(), toolsEmitted: false };
|
|
157
|
+
}
|
|
158
|
+
/** Consume one parsed Chat chunk. The caller owns settlement and may discard these records on failure. */
|
|
159
|
+
export function consumeOllamaChatChunk(state: OllamaStreamState, input: unknown): Obj[] {
|
|
160
|
+
const body = object(input, "Chat chunk");
|
|
161
|
+
if (body.error !== undefined) throw new Error("Chat stream error");
|
|
162
|
+
if (body.usage != null) state.usage = usage(body.usage);
|
|
163
|
+
if (!Array.isArray(body.choices) || body.choices.length > 1) throw new Error("Invalid Chat chunk choices");
|
|
164
|
+
if (!body.choices.length) return [];
|
|
165
|
+
const choice = object(body.choices[0], "Chat choice"); const delta = object(choice.delta, "Chat delta");
|
|
166
|
+
if (state.finishReason !== undefined) throw new Error("Chat chunk after finish");
|
|
167
|
+
const records: Obj[] = [];
|
|
168
|
+
if (delta.content != null) {
|
|
169
|
+
const text = string(delta.content, "Chat content");
|
|
170
|
+
if (text) records.push({ model: state.model, created_at: state.createdAt, ...payload(state.kind, text), done: false });
|
|
171
|
+
}
|
|
172
|
+
if (delta.tool_calls !== undefined) {
|
|
173
|
+
if (state.kind !== "chat" || !Array.isArray(delta.tool_calls) || state.toolsEmitted) throw new Error("Invalid Chat tool delta");
|
|
174
|
+
for (const raw of delta.tool_calls) {
|
|
175
|
+
const call = object(raw, "tool delta"); if (!Number.isSafeInteger(call.index) || (call.index as number) < 0) throw new Error("Invalid tool index");
|
|
176
|
+
const index = call.index as number; const current = state.tools.get(index) ?? { name: "", arguments: "" };
|
|
177
|
+
if (call.id !== undefined) { const id = string(call.id, "tool id", true); if (current.id && current.id !== id) throw new Error("Conflicting tool id"); current.id = id; }
|
|
178
|
+
if (call.function !== undefined) { const fn = object(call.function, "tool function"); if (fn.name !== undefined) current.name += string(fn.name, "tool name"); if (fn.arguments !== undefined) current.arguments += string(fn.arguments, "tool arguments"); }
|
|
179
|
+
state.tools.set(index, current);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (choice.finish_reason != null) {
|
|
183
|
+
if (state.finishReason !== undefined) throw new Error("Duplicate Chat finish");
|
|
184
|
+
state.finishReason = choice.finish_reason;
|
|
185
|
+
if (choice.finish_reason === "tool_calls" && state.tools.size) {
|
|
186
|
+
const calls = [...state.tools.entries()].sort((a, b) => a[0] - b[0]).map(([index, tool]) => ({ id: tool.id ?? `call_ollama_response_${index}`, function: { name: tool.name, arguments: tool.arguments } }));
|
|
187
|
+
records.push({ model: state.model, created_at: state.createdAt, ...payload(state.kind, "", nativeCalls(calls)), done: false }); state.toolsEmitted = true;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return records;
|
|
191
|
+
}
|
|
192
|
+
/** Call only after the outer handler confirms successful upstream settlement. */
|
|
193
|
+
export function ollamaStreamTerminal(state: OllamaStreamState): Obj {
|
|
194
|
+
const reason = finish(state.finishReason);
|
|
195
|
+
if (!reason || (state.tools.size > 0 && !state.toolsEmitted)) return nativeError();
|
|
196
|
+
return { model: state.model, created_at: state.createdAt, ...payload(state.kind, ""), done: true, done_reason: reason, ...state.usage };
|
|
197
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { markProxyError, isProxyError } from "../../lib/client-error-body";
|
|
1
2
|
/**
|
|
2
3
|
* AdapterEvent -> client wire, without the internal Responses SSE (PF-09).
|
|
3
4
|
*
|
|
@@ -525,6 +526,7 @@ export function encodeAdapterEventStream(
|
|
|
525
526
|
reportUsage: false,
|
|
526
527
|
durable: false,
|
|
527
528
|
};
|
|
529
|
+
markProxyError(terminal);
|
|
528
530
|
runBeforeTerminalSync(terminal);
|
|
529
531
|
try {
|
|
530
532
|
writer.terminal(terminal);
|
|
@@ -766,6 +768,7 @@ export function encodeAdapterEventStream(
|
|
|
766
768
|
reportUsage: true,
|
|
767
769
|
durable: true,
|
|
768
770
|
};
|
|
771
|
+
if (isProxyError(event)) markProxyError(terminal);
|
|
769
772
|
break;
|
|
770
773
|
}
|
|
771
774
|
case "error": {
|
|
@@ -845,6 +848,7 @@ export function encodeAdapterEventStream(
|
|
|
845
848
|
reportUsage: true,
|
|
846
849
|
durable: true,
|
|
847
850
|
};
|
|
851
|
+
markProxyError(terminal);
|
|
848
852
|
try {
|
|
849
853
|
if (!await deliverTerminalGuarded(terminal)) return;
|
|
850
854
|
} catch { /* see the catch path above */ }
|