Commit Graph

5015 Commits

Author SHA1 Message Date
Luis Pater
f48975b4dd fix(antigravity): skip model capability probes for unauthenticated credentials
- Gate Antigravity capability probing, refresh scheduling, queue admission, and post-slot execution on credential authentication eligibility instead of disabled status alone.
- Suppress repeated 401 probes for unknown-expiry access tokens under terminally rejected refresh grants using a route-independent credential and token key, and notify auth change watchers on terminal refresh failures.
- Add race-safe regression tests covering unauthenticated probe skipping, valid-token preservation during temporary quota errors, slot-wait expiry re-checks, terminal refresh probe cancellation, and credential recovery.

Closes: #7817
2026-11-22 02:08:56 +08:00
Luis Pater
cec8a7f390 fix(proxyutil): honor context cancellation on SOCKS5 HTTP transports
- Delegate SOCKS5/SOCKS5H Transport.DialContext calls in BuildHTTPTransport through proxy.ContextDialer so caller deadlines and cancellation abort stalled dials and handshakes without adding a fixed dialer timeout.
- Isolate Antigravity project-discovery HTTP/1.1 transports via newAntigravityProjectDiscoveryHTTPClient with deferred CloseIdleConnections so canceled credential acquisition cancels abandoned in-flight dials without affecting the shared pool.
- Add SOCKS5/SOCKS5H cancellation, deadline, tunnel, and HTTP client regression tests verifying prompt request exit and peer socket closure.

Closes: #7819
2026-11-22 02:08:54 +08:00
Luis Pater
533edd3814 fix(antigravity): persist capability hints freshness metadata and initialize cache expiry on seed
- Persist updated_at, expires_at, and a credential-free route_fingerprint (hashing proxy URL and client User-Agent) in Antigravity capability hints metadata with backward-compatible parsing.
- Initialize entry.expiresAt in seedAntigravityCapabilityCacheLocked when persisted hints match the current route fingerprint and remain within antigravityCapabilityCacheTTL, avoiding immediate probe bursts on restart or RegistrationEpoch advances while keeping stale fallback on route or version changes.
- Add regression tests covering fresh restart reuse, RegistrationEpoch reloads, expiry clamping, legacy metadata, proxy switches, and client version changes.

Closes: #7818
2026-11-22 02:08:52 +08:00
Luis Pater
acb56c6cba fix(antigravity): apply Host, custom auth headers, and TOS_VIOLATION handling in credits query
- Set httpReq.Host from the resolved loadCodeAssist base URL and apply static credential-scoped header:* attributes without reading pooled caller Gin contexts or session IDs.
- Invoke applyAntigravityTOSState on bounded 403 responses in updateAntigravityCreditsBalanceForTask while reusing task/epoch and context cancellation guards so superseded refreshes cannot arm pool-wide TOS pauses.
- Add race-tested regression tests covering Host resolution and overrides, detached background header safety, and active versus superseded/canceled 403 TOS_VIOLATION handling.

Closes: #7820
2026-11-22 02:08:50 +08:00
hkfires
1ef770d9a1 feat(copilot): support Home-dispatched Copilot execution
Resolve Copilot routes from Home-provided model info when Home is
enabled, allowing models absent from the local catalog to execute,
stream, and count tokens. Attach resolved info before after-auth
interception and skip the local catalog refresh in Home mode.

Expose Copilot device-login completion and model discovery through
the SDK. Fix Codex token counting for string inputs, string message
content, and role-only messages.
2026-11-21 21:46:59 +08:00
Luis Pater
093c7efaac fix(antigravity): update Hub fallback and changelist map to 2.34.0
- Bump antigravityFallbackVersion to 2.34.0 and add the verified 2.34.0 changelist mapping (1026637980) in internal/misc/antigravity_version.go.
- Update Antigravity Hub User-Agent and fallback regression tests to cover 2.34.0 and pin unmapped versions such as 2.30.0 and 2.35.0 to 2.34.0.

Closes: #7813
2026-11-21 21:38:43 +08:00
Luis Pater
cb5f62f7f4 fix(devin): preserve gpt reasoning across responses tool calls
- Carry typed OpenAI reasoning arrays through streamed and non-streamed Responses without changing their bytes.
- Replay signed thoughts only on the Devin route and cover fragmented and late signatures across tool turns.

Closes: #7805
2026-11-21 21:26:02 +08:00
Luis Pater
7a5dee5207 fix(claude): preserve native haiku helpers on custom base URLs
- Make the prompt caching scope beta optional for Haiku 5.5 helpers without relaxing other identity checks.
- Cover helper detection and verify that streamed title requests preserve the original client and session.

Closes: #7809
2026-11-21 21:06:13 +08:00
Luis Pater
a3e754213a fix(translator): correct antigravity gemini stream output
- Share output detection with the OpenAI translator to prevent false stops on empty streams.
- Restore usage metadata and original tool names in every Gemini JSON array response.

Closes: #7799
2026-11-21 20:43:40 +08:00
Luis Pater
221d5e0818 fix(auth): check active plugin scheduler in affinity lookup and normalize mixed legacy provider keys
- Use hasPluginScheduler() in LookupSessionAffinity so attached plugin hosts without an active scheduler plugin do not falsely return unsupported.
- Normalize executorKeyFromAuth with canonicalSchedulingProvider in pickNextMixedLegacy and warnLogAuthUnavailable to match providerSet keys across all scheduling paths.
- Add regression tests covering inactive plugin scheduler state in LookupSessionAffinity and host.affinity.lookup, plus provider alias handling in pickNextMixedLegacy and warnLogAuthUnavailable.

Closes: #7761
2026-11-21 20:26:16 +08:00
Luis Pater
91ccf28400 fix(antigravity): bound auth response reads, preserve error details, and make onboarding sleep ctx-aware
- Bound response body reads with io.LimitReader in FetchProjectID and OnboardUser (1 MiB for 2xx JSON payloads and 64 KiB for non-2xx error bodies) and cap HTTPStatusError messages at 8 KiB on valid UTF-8 boundaries instead of slicing OnboardUser errors at 200 raw bytes.
- Replace the uninterruptible 2-second time.Sleep in OnboardUser polling with a context-aware timer select, skip the trailing sleep after the final attempt, and normalize nil contexts safely.
- Add race-tested regression tests in internal/auth/antigravity/auth_test.go covering structured 403/429 error preservation, UTF-8 boundary truncation, immediate polling cancellation via synctest, and response body read limits.

Closes: #7759
2026-11-21 20:20:54 +08:00
Luis Pater
18a03e40c1 fix(antigravity): scan all user parts for session ID and match models case-insensitively
- Scan all parts of the first user turn in generateStableSessionIDFromContentsForAuth for the first non-empty text part so multimodal turns retain a stable sessionId across turns.
- Normalize model names to lowercase in buildRequestDoc, geminiToAntigravityDocForAuth, and Execute routing, including lowercase fallback lookup when capping maxOutputTokens.
- Add regression tests covering multimodal Turn 1 session ID stability and case-insensitive Claude, Gemini Pro, and image model handling.

Closes: #7760
2026-11-21 20:20:41 +08:00
Luis Pater
80fb55d8eb fix(antigravity): honor explicit lower and zero max-idle-conns-per-host pool limits
- Apply explicitly configured max-idle-conns-per-host even when lower than the base transport limit while preserving larger base limits when omitted, and include explicitness in antigravityTransportKey to avoid cache collisions across reloads.
- Treat max-idle-conns-per-host <= 0 as short-lived connection mode (MaxIdleConnsPerHost = -1) consistent with idle-conn-timeout <= 0 and ProxyConnectionPoolConfig, and align pool cap comments and docs with the 210s limit.

Closes: #7758
2026-11-21 20:14:23 +08:00
Luis Pater
e0a1e93d2b fix(antigravity): filter ineligible credentials and resolve aliases in credits fallback
- Exclude terminal unauthorized credentials, enforce request selection eligibility, and verify route model support for both selection and credits target models in findAllAntigravityCreditsCandidateAuths.
- Resolve per-auth OAuth model aliases and strip thinking suffixes via selectionModelKeyForAuth before checking Claude eligibility for Antigravity credits fallback.
- Add regression tests covering terminal 401 filtering, eligibility and route-model enforcement, alias/suffix resolution, empty-model ordering before PrepareRequestAuth, and non-streaming RequestAfterAuthInterceptor invocation.

Closes: #7757
2026-11-21 18:15:36 +08:00
Luis Pater
35afdf07f9 fix(auth): preserve disabled and terminal 401 states during model reconciliation
- Guard auth status, error, and unavailability updates in ReconcileRegistryModelStates and both passes of publishOAuthModelAliasAndReconcileStates so disabled, TOS_VIOLATION, and terminal 401 credentials are not reset to StatusActive.
- Exclude credentials marked with StatusDisabled consistently across all candidate selection, cooldown inspection, and unavailability warning loops in conductor_selection.go.
- Add race-safe regression tests covering dropped-model reconciliation, two-pass alias migration, terminal 401 preservation, and StatusDisabled candidate filtering.

Closes: #7756
2026-11-21 18:15:34 +08:00
Luis Pater
9176cb22e1 fix(antigravity): preserve thoughtSignature on text parts and empty-text carriers
- Capture and emit thoughtSignature on non-thought text parts and preserve standalone empty-text signature carriers in convertStreamChunksToNonStream.
- Flush pending text or thought segments at signed and same-chunk part boundaries while preserving whitespace text separated by signatures.
- Add unit and end-to-end regression tests covering non-thought signatures, empty-text carriers, same-chunk boundaries, and whitespace preservation.

Closes: #7755
2026-11-21 18:15:33 +08:00
Luis Pater
29de31a89d fix(auth): preserve disabled unavailability and skip inference verification on late success
- Guard updateAggregatedAvailability and clearAuthStateOnSuccess for Disabled/StatusDisabled credentials so active sibling models cannot clear auth.Unavailable.
- Skip InferenceVerified updates and model state resets in MarkResult for late in-flight successes on disabled credentials, and preserve Unavailable across disable-cooling and cooldown cleanup paths.
- Add race-verified regression tests covering multi-model TOS_VIOLATION suspension, late sibling and same-model successes, StatusDisabled-only auths, and cooldown state cleanup.

Closes: #7754
2026-11-21 18:15:30 +08:00
hkfires
d059cf2891 feat(copilot)!: add preset-based in-memory catalog
Add copilot presets to the registry models catalog and intersect
them with per-account /models capabilities, so usable credentials
get cold-start preset routes before discovery and account data
overrides limits, modalities, thinking and endpoint afterwards.

Replace the persisted metadata catalog with an immutable
in-memory Auth.CopilotCatalog with preset and unavailable
sentinels, preserving or revoking it across reloads, account
and origin changes, and re-resolving routes on each attempt.

Run discovery in a dedicated worker pool with per-account
transport, queued cancellation and skip-persist commits, gate
native-executor plugin models on catalog availability, and
remove login-time catalog fetch and embedded effort lists.

Add cmd/fetch_copilot_models to export the raw upstream /models
response atomically without modifying the stored credential.

BREAKING CHANGE: upstream-only Copilot models without a registry
preset are no longer routed, and the persisted copilot_catalog
metadata, ReadCatalog and string FetchCatalog APIs are removed
2026-11-21 17:11:35 +08:00
Luis Pater
cdbda2f2dc fix(antigravity): persist execution-time token refreshes and preserve refresh context values
- Route Antigravity execution-time OAuth refreshes through a Manager refresh coordinator that serializes per-credential refreshes, persists rotated tokens with detached cancellation, updates in-flight MarkResult auth state, and keeps Home-dispatched snapshots isolated from local credentials.
- Preserve non-cancellation context values such as httptransport.Decorator and custom round trippers via context.WithoutCancel while stripping execution-scoped RequestProxyURL across OAuth refresh, project discovery, and credits hint refreshes.
- Add race-tested regression tests covering single refresh persistence, client cancellation, project discovery failure, safety-window crossing, unsupported attachments, Home isolation, request preparation context preservation, and proxy isolation.

Closes: #7749
2026-11-21 16:10:40 +08:00
Luis Pater
204be8b9ae fix(antigravity): preserve project discovery error classification
- Classify genuinely missing Antigravity project_id as a credential-scoped 503 instead of HTTP 400 so broken credentials cool down and rotate.
- Preserve underlying cause chains, transient transport classification, and request-retry round eligibility for transport timeouts, internal discovery deadlines, and incomplete or transient onboardUser failures.
- Preserve full upstream response bodies, single-attempt discovery after token refresh, and structured TOS_VIOLATION and 429 metadata across loadCodeAssist and onboardUser responses.

Closes: #7751
2026-11-21 15:41:59 +08:00
Luis Pater
892fc4864c fix(antigravity): harden SSE JSON reassembly and mid-stream error bookkeeping
- Replace ad-hoc pendingJSON buffering in ExecuteStream and executeClaudeNonStream with a bounded SSEJSONAssembler that ignores non-data SSE control lines, resets on genuine empty-line event boundaries, and discards oversized event tails until the next empty line.
- Surface all 400-599 mid-stream JSON error frames in executeClaudeNonStream with replay invalidation, TOS state handling, and 429 bookkeeping instead of letting non-403 errors degrade to synthetic 502 or truncated responses.
- Share 429 bookkeeping across HTTP and mid-stream SSE paths in ExecuteStream and executeClaudeNonStream, and defer clearing prior credits failure state until request success is confirmed.

Closes: #7753
2026-11-21 15:21:19 +08:00
Luis Pater
81018ba473 fix(antigravity): mark TOS pause 503 error as request-scoped
- Add a requestScoped flag and IsRequestScoped method on statusErr so executor errors can explicitly opt into request-scoped handling without affecting ordinary status errors.
- Return a request-scoped 503 via newAntigravityTOSPauseStatusErr across Execute, executeClaudeNonStream, ExecuteStream, and CountTokens so the conductor stops immediately without rotating or cooling healthy credentials.
- Add executor and manager regression tests covering non-streaming, Claude non-streaming, streaming, and token-counting paths under an active TOS pause.

Closes: #7748
2026-11-21 15:11:50 +08:00
Luis Pater
8e5a98e886 fix(antigravity): publish unavailable credits hint when no GOOGLE_ONE_AI entry matches
- Publish a known-unavailable credits hint after inspecting paidTier.availableCredits when the array is missing, empty, or lacks a parseable GOOGLE_ONE_AI entry.
- Bound loadCodeAssist response reads with io.LimitReader and validate JSON before publishing to avoid unbounded reads or false negative hints.
- Add race-tested unit tests covering empty/unmatched availableCredits, stale positive hint replacement, oversized bodies, and invalid JSON responses.

Closes: #7750
2026-11-21 15:10:25 +08:00
Luis Pater
538f961107 fix(auth): cancel abandoned stream attempts before draining
- Derive a per-attempt cancellable context in executeStreamWithModelPool so failed, refreshed, or empty stream attempts are canceled before draining chunks.
- Preserve the caller context across retries and pass attempt cancellation ownership into wrapStreamResultWithCancel for clean shutdown on completion, error, or cancellation.
- Add regression tests covering model failover, credential failover, 401 refresh retries, empty streams, and post-handoff cancellation paths.

Closes: #7745
2026-11-21 14:35:46 +08:00
Luis Pater
486624c777 fix(auth): delete existing keys case-insensitively before applying updates in mergeRequestHeaders
- Share case-insensitive header deletion across clear and update loops in mergeRequestHeaders so non-canonical keys are removed before adding updated values.
- Add race-tested regression coverage for non-canonical header updates in mergeRequestHeaders and prepareRequestAfterAuth.

Closes: #7742
2026-11-21 14:12:49 +08:00
Luis Pater
df6c8ccb96 fix(auth): preserve stream headers and honor terminal request stops
- Preserve upstream stream bootstrap headers via streamHeaderError and forward them on direct error responses without allowing bootstrap replay.
- Short-circuit terminal request-stop and unoverridden RequestTerminatedError outcomes before Home retryRoundPending waits and avoid re-evaluating inner errors across continue/stop wrappers.
- Add regression tests covering stream bootstrap stop/terminated headers, Home retryRoundPending short-circuiting, and continue-overridden 400 credential failover.

Closes: #7740
2026-11-21 13:49:45 +08:00
Luis Pater
b4247e1918 fix(auth): use syncPreferredUpstreamError in stream failover paths
- Replace raw upstreamErr overwrites in stream, model-pool, non-stream, token-count, and Home execution paths with syncPreferredUpstreamError while preserving pre-refresh fallbacks and direct terminal stream errors across retry rounds.
- Allow synthetic empty_stream and headerless bootstrap wrappers to advance to later real bootstrap failures without overwriting earlier header-bearing bootstrap errors.
- Add regression tests covering credential rotation, model-pool failover, 401 refresh retries, cross-round retry preservation, and terminal 400 precedence.

Closes: #7734
2026-11-21 13:10:59 +08:00
Luis Pater
4aca8df3d3 fix(auth): close canceled streams during upstream stalls
- Observe request cancellation while waiting for remaining upstream chunks so stalled streams release wrapper state promptly.
- Preserve ready upstream errors and add deterministic cancellation coverage without changing normal stream forwarding.

Closes: #7741
2026-11-21 13:02:13 +08:00
Luis Pater
cdd6ae6d9b fix(auth): clear stream rewriter before emitting flushed tail in wrapStreamResult
- Clear the finalized StreamRewriter immediately after finishForceMappedStreamChunks so emit forwards the already-rewritten tail without re-running rewriteForceMappedStreamChunk.
- Preserve completion-flag inspection and context-cancellation handling on the flushed tail while preventing re-buffering or duplicate rewrites.
- Add race-checked regression tests in sdk/cliproxy/auth covering flushed tail preservation, unterminated final events, glued completion detection, and cancellation.

Closes: #7738
2026-11-21 12:57:00 +08:00
Luis Pater
2c8b32fd3e fix(auth): inspect response.candidates and additional Gemini failure finishReasons in completion flags
- Extract geminiCandidatesCompletionFlags to classify both top-level candidates and nested response.candidates envelopes consistently across streaming and non-streaming payloads.
- Extend Gemini incomplete finishReason matching with PROHIBITED_CONTENT, BLOCKLIST, SPII, IMAGE_SAFETY, LANGUAGE, and NO_IMAGE while preserving existing abnormal finish reasons.
- Add table-driven unit tests covering response.candidates envelopes, failure finishReasons, error precedence, and mixed-candidate payloads.

Closes: #7739
2026-11-21 12:48:45 +08:00
Luis Pater
8906442bd4 fix(auth): align VerifyInference with per-auth transport, auth prep, and cancellation
- Attach per-auth RoundTripper before prepareRequestAuth and retry once after 401 while fencing credential epoch and version.
- Select text-capable models without forcing gpt-5 on non-Codex/OpenAI providers and restrict max_output_tokens=16 to Codex.
- Honor caller cancellation across preparation, refresh, and stream drain without recording failure or cooldown, with unit and end-to-end tests.

Closes: #7737
2026-11-21 12:30:11 +08:00
Luis Pater
8f11580852 fix(auth): clone per-attempt opts.Metadata from immutable base metadata
- Snapshot immutable baseMetadata before the credential loops in executeMixedOnce, executeCountMixedOnce, executeStreamMixedOnce, and executeHomeOnce, cloning fresh per-attempt metadata on every iteration and syncing published selected-auth fields to pickOpts on Home prepare failures.
- Preserve the non-Home mid-round selected_auth_id scheduler plugin contract (#7434) as a trimmed one-shot signal after an attempted failure while preventing stale affinity/LCP, selection_id, index, or nested container mutations from leaking across attempts or mutating caller metadata.
- Add race-verified regression tests covering skipped attempts, failover isolation, Home execute/count/stream attempts, Home prepare failures, whitespace trimming, and cyclic/nested container cloning.

Closes: #7733
2026-11-21 12:30:08 +08:00
hkfires
20211183c5 fix(copilot): use execution mode for claude stream translation
Force the stream hint for the OpenAI-to-Claude response translator
whenever ExecuteStream is used, even if the original request set
stream:false or omitted it. Keep the original request unchanged
and add coverage for omitted, true, and false values.
2026-11-21 12:14:05 +08:00
hkfires
9792ac281e fix(copilot): translate copilot streaming responses
Forward typed SSE events through response translators instead of
emitting them raw, so non-native formats receive translated chunks.
2026-11-21 11:38:49 +08:00
Luis Pater
0147c80fe8 fix(auth): preserve interceptor session clearing and metadata isolation
- Run ensureCanonicalSessionMetadata before prepareRequestAfterAuth in executeStreamWithModelPool so streaming ClearHeaders session clearing is not undone by payload re-derivation.
- Clear stale ParentSessionIDMetadataKey when resp.Headers changes header-derived session identity to a standalone or self-referential session while preserving existing session metadata on unrelated header updates.
- Clone opts.Metadata with maps.Clone before passing it to RequestAfterAuthInterceptor and add race-safe regression tests covering all three behaviors.

Closes: #7735
2026-11-21 11:10:43 +08:00
hkfires
b824c05297 fix(copilot): return gemini format for count tokens
Use GeminiTokenCountJSON for Gemini-format requests instead of
falling back to OpenAI usage JSON, and reuse the shared Claude
input_tokens helper for Claude and OpenAI Response formats.
2026-11-21 10:58:18 +08:00
Luis Pater
ab971876bf fix(auth): treat zero-payload streams before EOF as empty_stream
- Skip buffering zero-payload chunks in readStreamBootstrap while preserving any leading Incomplete flag in O(1) memory, returning (nil, true, nil) when the stream closes before any payload arrives.
- Trigger the empty_stream failure and failover path in executeStreamWithModelPool whenever stream bootstrap finishes without a payload, and remove the unreachable closed-channel wrapper branch.
- Add -race regression tests covering readStreamBootstrap buffering bounds, multi-credential failover, post-refresh empty streams, and Incomplete flag preservation.

Closes: #7732
2026-11-21 10:39:57 +08:00
hkfires
5ab97c6d0b refactor(auth): rename applyRequestAfterAuthInterceptor
Rename applyRequestAfterAuthInterceptor to prepareRequestAfterAuth
to reflect that it plans the upstream route before invoking the
optional interceptor. Update all call sites and tests, fixing
issue7725 tests missing the auth argument.
2026-11-21 10:35:58 +08:00
Luis Pater
6d703fdf48 fix(codex): sync temp file before close and rename in WriteJSONFileAtomic
- Sync the temporary credential file after writing JSON data and before closing and renaming it onto the target path, closing and removing the temp file if sync fails.
- Remove the unused strconv import and dead strconv.IntSize placeholder in SaveTokenToFile.
- Add regression tests verifying sync ordering before close/rename and temp file cleanup with existing credential preservation on sync error.

Closes: #7718
2026-11-21 10:28:31 +08:00
Luis Pater
5dff8b6728 feat(copilot): support OAuth model aliases and exact route-aware selection
- Publish Copilot catalog and plugin models with native IDs, aliases, and auth prefixes while preserving suffixed routes.
- Route requests through exact registered Copilot models and send the resolved native model upstream.
- Reconcile Copilot model states and route metadata against published routes; document Copilot support in OAuth alias and error configuration.
2026-11-21 09:54:53 +08:00
hkfires
7ae771fcb4 feat(copilot): add GitHub Copilot provider support
Add device OAuth login via `--copilot-login`, trusted-endpoint token
exchange, and per-account model catalog discovery with independent
refresh so accounts expose only entitled Chat, Messages, or Responses
routes.

Implement the executor with official CLI parity defaults, cross-protocol
translation, account-scoped thinking, turn linking, and server-side
replay of private reasoning and signatures, keeping payload rules final.
2026-11-20 23:14:11 +08:00
Luis Pater
f5c5681a83 fix(auth): capture per-attempt access token on streaming failure results
- Capture the access token synchronously inside executeStreamWithModelPool and re-capture it after a 401 credential refresh so every failure Result carries the token that attempt actually used.
- Populate AccessToken on all failure Result literals in the stream-start, bootstrap, and empty-stream paths to match the wrapStreamResult and recordCanceledUpstreamCooldown helpers.

Closes: #7731
v8.0.80
2026-11-20 22:52:03 +08:00
Luis Pater
0399de3801 fix(auth): publish selected auth metadata only after executable model check
- Defer publishSelectedAuthMetadata until after the len(models)==0 gate in executeMixedOnce, executeCountMixedOnce, and the mixed-stream loop so credentials with no executable model are not reported as selected or counted in roundAttempted.
- Keep tried[auth.ID] ahead of the continue so unexecutable credentials cannot be re-picked in a loop.
- Add regression tests covering Execute, ExecuteCount, and ExecuteStream to assert the skipped credential never reaches SelectedAuthCallback or the executor metadata.

Closes: #7730
2026-11-20 22:32:09 +08:00
Luis Pater
d4f6edb162 fix(auth): scope stream bootstrap retry-after annotation to the same upstream attempt
- Assign a process-unique attempt id to upstream execution attempt markers and preserve it when withTrustedRetryAfter rebuilds the marker, so a credential attempt can be identified reliably.
- Record the attempt id on streamBootstrapError and require upstreamErrorMatchesBootstrap before syncPreferredUpstreamError annotates the preferred bootstrap in place, preventing a different credential attempt's trusted Retry-After hint from mutating an earlier bootstrap even when both surfaced equal or identical error values.
- Add regression tests covering foreign-attempt, equal-but-distinct, shared-sentinel, and same-attempt annotation cases.

Closes: #7728
2026-11-20 22:08:47 +08:00
Luis Pater
0a34244e32 fix(auth): serialize request auth preparation with refresh locks and abort unregistered credentials
- Unify RequestAuthPreparer serialization onto context-aware per-credential refreshLocks and abort preparation for all providers when the credential is unregistered before or during preparation, while keeping caller auth pointers non-nil on prepare errors.
- Replace Home snapshot prepare serialization with snapshot-keyed in-flight coalescing, reference-counted cancellation, panic recovery, and caller-isolated snapshot merging with deep metadata cloning.
- Add race-tested regression coverage for Antigravity/Claude refresh serialization, unregistered credential aborts, lock-wait cancellation, and Home snapshot coalescing.

Closes: #7727
2026-11-20 21:54:28 +08:00
Luis Pater
2f57a5a67e fix(auth): honor request-scoped-errors, Retry-After, and credential scope on PrepareRequestAuth failure
- Route errPrepare through the same error pipeline as execution errors in all four conductor paths (Execute/CountTokens/Stream/Home): record RetryAfter and CredentialScope, match request-scoped error rules, stop on stop-actions and invalid requests, and preserve the upstream attempt via markUpstreamExecutionAttemptFromContext plus annotateTrustedRetryAfterByHint/syncPreferredUpstreamError so stop responses keep their retry hint.
- Mark upstream attempts only at real HTTP boundaries (OAuth token refresh, project discovery) and propagate upstream Retry-After and credential scope from Antigravity prepare failures, while keeping local missing-credential errors and status-less transport faults from being misclassified or outranking a genuine upstream rejection.

Closes: #7726
2026-11-20 20:56:13 +08:00
sususu98
2e940ba1e5 test(meta): add regression coverage for incomplete synthesis and refusal fallbacks
- Cover response.incomplete synthesis and multi-part (output_text + refusal) message synthesis in ResponsesStreamOutputTracker and MetaExecutor.ExecuteStream.
- Add empty-delta fallback, response.created delta-state reset, and empty refusal->text fallback tests for Codex OpenAI Chat, Gemini, and Interactions translators.
2026-11-20 19:19:24 +08:00
sususu98
e442c32d4f fix(meta): tighten Responses output synthesis tracking and refusal fallbacks
- Mark unkeyed message response.output_item.done as seen to prevent duplicate terminal synthesis.
- Preserve fallback output_index tracking for ID-bearing events without colliding with shifted item IDs, require item.type == message in Observe, and skip duplicate response.content_part.added frames.
- Guard Claude HasTextDelta on non-empty deltas, skip empty strings in Interactions codexContentText fallback, reset HasMessageTextDelta on OpenAI Chat response.created, and build Gemini refusal parts via ojson.Doc.
2026-11-20 18:57:46 +08:00
sususu98
ca459712c0 fix(meta): synthesize unstreamed Responses messages and translate refusal parts
- Track streamed message items in ResponsesStreamOutputTracker and synthesize missing item/part/delta/done events before terminal response.completed or response.incomplete when upstream omits item-level SSE frames.
- Include response.refusal.delta in HasMeaningfulCodexOutputDelta.
- Support refusal content parts and response.refusal.delta across Codex response translators (OpenAI Chat, Claude, Gemini, and Interactions) with regression tests.
2026-11-20 18:20:36 +08:00
Luis Pater
2dbad4ddf0 fix(auth): clone metadata before interceptor session updates and publish refreshed auth on 401 retry
- Clone opts.Metadata once before writing or deleting session keys in applyRequestAfterAuthInterceptor when resp.Path is empty.
- Call publishSelectedAuthMetadata after 401 token refresh in both executeMixedOnce and executeCountMixedOnce for parity with executeStreamWithModelPool.
- Add race-safe regression tests covering caller metadata isolation and post-401 selected auth metadata publication.

Closes: #7725
2026-11-20 17:39:09 +08:00